refactor(sse): serialize backend writes and add directory-aware frontend batching

SSE writes from the backend could arrive out of order under concurrent load.
The frontend parts batcher also lacked directory awareness, making it
unreliable when multiple directories are monitored.

Changes:
- Add QueuedSSEWriter that serializes SSE frames via promise chaining with
  backpressure handling and error isolation
- Refactor SSE route to use QueuedSSEWriter instead of raw encoder
- Make frontend parts batcher directory-aware: operations grouped by
  (sessionID, directory) composite key; flush() accepts optional target filter
- Decouple batcher lifecycle from directory dependency in useSSE hook
- Add comprehensive tests for all new behavior
This commit is contained in:
Chris Scott committed 2026-06-06 01:07:31 +00:00
1 parent 5b7e56ccda
commit 94941eb7a0
10 files changed
+677 -91

No files matched your search

+44
View File
@@ -0,0 +1,44 @@
export interface QueuedSSEWriterInput {
write: (chunk: Uint8Array) => Promise<unknown> | void
onError: (error: unknown) => void
}
export interface QueuedSSEWriter {
writeSSE: (event: string, data: string) => void
close: () => void
}
export function createQueuedSSEWriter(input: QueuedSSEWriterInput): QueuedSSEWriter {
const encoder = new TextEncoder()
let chain = Promise.resolve()
let closed = false
const writeSSE = (event: string, data: string) => {
if (closed) return
const lines: string[] = []
if (event) lines.push(`event: ${event}`)
lines.push(`data: ${data}`)
lines.push('')
lines.push('')
const encoded = encoder.encode(lines.join('\n'))
chain = chain
.then(async () => {
if (closed) return
await input.write(encoded)
})
.catch((error) => {
if (!closed) {
closed = true
input.onError(error)
}
})
}
const close = () => {
closed = true
}
return { writeSSE, close }
}
+19 -24
View File
@@ -4,6 +4,7 @@ import { sseAggregator } from '../services/sse-aggregator'
import { SSESubscribeSchema, SSEVisibilitySchema } from '@opencode-manager/shared/schemas'
import { logger } from '../utils/logger'
import { DEFAULTS } from '@opencode-manager/shared/config'
import { createQueuedSSEWriter } from './sse-writer'
const { HEARTBEAT_INTERVAL_MS } = DEFAULTS.SSE
@@ -21,42 +22,36 @@ export function createSSERoutes() {
c.header('X-Accel-Buffering', 'no')
return stream(c, async (writer) => {
const encoder = new TextEncoder()
const writeSSE = (event: string, data: string) => {
const lines = []
if (event) lines.push(`event: ${event}`)
lines.push(`data: ${data}`)
lines.push('')
lines.push('')
writer.write(encoder.encode(lines.join('\n')))
}
let cleanup: () => void = () => {}
const cleanup = sseAggregator.addClient(
const queuedWriter = createQueuedSSEWriter({
write: (chunk) => writer.write(chunk),
onError: (error) => {
logger.error(`SSE write failed for ${clientId}:`, error)
clearInterval(heartbeatInterval)
cleanup()
},
})
const heartbeatInterval = setInterval(() => {
queuedWriter.writeSSE('heartbeat', JSON.stringify({ timestamp: Date.now() }))
}, HEARTBEAT_INTERVAL_MS)
cleanup = sseAggregator.addClient(
clientId,
(event, data) => {
writeSSE(event, data)
queuedWriter.writeSSE(event, data)
},
directories
)
const heartbeatInterval = setInterval(() => {
try {
writeSSE('heartbeat', JSON.stringify({ timestamp: Date.now() }))
} catch {
clearInterval(heartbeatInterval)
}
}, HEARTBEAT_INTERVAL_MS)
writer.onAbort(() => {
queuedWriter.close()
clearInterval(heartbeatInterval)
cleanup()
})
try {
writeSSE('connected', JSON.stringify({ clientId, directories, ...sseAggregator.getConnectionStatus() }))
} catch (err) {
logger.error(`Failed to send SSE connected event for ${clientId}:`, err)
}
queuedWriter.writeSSE('connected', JSON.stringify({ clientId, directories, ...sseAggregator.getConnectionStatus() }))
await new Promise(() => {})
})
+60
View File
@@ -0,0 +1,60 @@
import { describe, it, expect, vi } from 'vitest'
import { createQueuedSSEWriter } from '../../src/routes/sse-writer'
describe('createQueuedSSEWriter', () => {
describe('serializes frames in enqueue order', () => {
it('should not execute second write until first resolves', async () => {
let firstWriteResolve!: () => void
const writes: Uint8Array[] = []
const write = vi.fn((chunk: Uint8Array) => {
writes.push(chunk)
if (writes.length === 1) {
return new Promise<void>((resolve) => {
firstWriteResolve = resolve
})
}
})
const onError = vi.fn()
const writer = createQueuedSSEWriter({ write, onError })
writer.writeSSE('message', '{"n":1}')
writer.writeSSE('message', '{"n":2}')
await new Promise((resolve) => setTimeout(resolve, 0))
expect(write).toHaveBeenCalledTimes(1)
expect(onError).not.toHaveBeenCalled()
firstWriteResolve()
await new Promise((resolve) => setTimeout(resolve, 0))
expect(write).toHaveBeenCalledTimes(2)
const decoder = new TextDecoder()
expect(decoder.decode(writes[0])).toBe('event: message\ndata: {"n":1}\n\n')
expect(decoder.decode(writes[1])).toBe('event: message\ndata: {"n":2}\n\n')
})
})
describe('stops writing after a write failure', () => {
it('should call onError and skip subsequent writes', async () => {
const write = vi.fn().mockRejectedValueOnce(new Error('write failed'))
const onError = vi.fn()
const writer = createQueuedSSEWriter({ write, onError })
writer.writeSSE('message', '{"n":1}')
await vi.waitFor(() => {
expect(onError).toHaveBeenCalledTimes(1)
})
expect(onError).toHaveBeenCalledWith(new Error('write failed'))
expect(write).toHaveBeenCalledTimes(1)
writer.writeSSE('message', '{"n":2}')
await vi.waitFor(() => {
expect(write).toHaveBeenCalledTimes(1)
})
})
})
})
+178
View File
@@ -4,6 +4,7 @@ import type { ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useSSE } from './useSSE'
import { useSessionStatus } from '../stores/sessionStatusStore'
import type { Part, MessageWithParts } from '@/api/types'
const mocks = vi.hoisted(() => ({
getSessionStatuses: vi.fn(),
@@ -274,4 +275,181 @@ describe('useSSE', () => {
unmount()
})
it('routes streamed part deltas to the event directory in multi-directory subscriptions', async () => {
const origRAF = window.requestAnimationFrame
window.requestAnimationFrame = ((cb: FrameRequestCallback) => {
cb(0)
return 0
}) as typeof window.requestAnimationFrame
try {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
// Seed both directory caches before rendering the hook
queryClient.setQueryData(
['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo-a'],
[{
...assistantMessage('session-1', 'message-1'),
parts: [textPart('session-1', 'message-1', 'part-1', 'A')],
}],
)
queryClient.setQueryData(
['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo-b'],
[{
...assistantMessage('session-1', 'message-1'),
parts: [textPart('session-1', 'message-1', 'part-1', 'B')],
}],
)
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
// Use stable reference to avoid re-render loop with inline array
const directories = ['/repo-a', '/repo-b']
const { result, unmount } = renderHook(
() => useSSE('http://localhost:5551', directories, 'session-1'),
{ wrapper },
)
await waitFor(() => {
expect(MockEventSource.instances.length).toBeGreaterThanOrEqual(1)
})
const eventSource = MockEventSource.instances[MockEventSource.instances.length - 1]
act(() => {
eventSource.emit('connected', { clientId: 'client-1' })
})
await waitFor(() => expect(result.current.isConnected).toBe(true))
act(() => {
eventSource.emit('message', {
type: 'message.part.delta',
directory: '/repo-b',
properties: {
sessionID: 'session-1',
messageID: 'message-1',
partID: 'part-1',
field: 'text',
delta: ' + streamed',
},
})
})
const repoBData = queryClient.getQueryData<MessageWithParts[]>([
'opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo-b',
])
expect(repoBData![0].parts[0]).toHaveProperty('text', 'B + streamed')
const repoAData = queryClient.getQueryData<MessageWithParts[]>([
'opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo-a',
])
expect(repoAData![0].parts[0]).toHaveProperty('text', 'A')
unmount()
} finally {
window.requestAnimationFrame = origRAF
}
})
it('processes part deltas when directory transitions from undefined to a real value', async () => {
const origRAF = window.requestAnimationFrame
window.requestAnimationFrame = ((cb: FrameRequestCallback) => {
cb(0)
return 0
}) as typeof window.requestAnimationFrame
try {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
// Seed cache with an empty part
queryClient.setQueryData(
['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo'],
[{
...assistantMessage('session-1', 'message-1'),
parts: [textPart('session-1', 'message-1', 'part-1', '')],
}],
)
// Initial render with directory=undefined — batcher should be created eagerly
const { rerender, unmount } = renderHook(
({ directory }) => useSSE('http://localhost:5551', directory, 'session-1'),
{ wrapper, initialProps: { directory: undefined as string | undefined } },
)
// No SSE subscription yet because directoriesList is empty
expect(MockEventSource.instances).toHaveLength(0)
// Re-render with a real directory to start the SSE subscription
rerender({ directory: '/repo' })
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1))
const eventSource = MockEventSource.instances[0]
act(() => {
eventSource.emit('connected', { clientId: 'client-1' })
})
// Emit a part delta — the batcher was created on the initial mount,
// so it should process the event even though directory was undefined at mount time
act(() => {
eventSource.emit('message', {
type: 'message.part.delta',
directory: '/repo',
properties: {
sessionID: 'session-1',
messageID: 'message-1',
partID: 'part-1',
field: 'text',
delta: 'streamed content',
},
})
})
await waitFor(() => {
const data = queryClient.getQueryData<MessageWithParts[]>([
'opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo',
])
expect(data![0].parts[0]).toHaveProperty('text', 'streamed content')
})
unmount()
} finally {
window.requestAnimationFrame = origRAF
}
})
})
function assistantMessage(sessionID: string, messageID: string): MessageWithParts {
return {
info: {
id: messageID,
sessionID,
role: 'assistant',
time: { created: Date.now() },
parentID: '',
modelID: 'test-model',
providerID: 'test-provider',
mode: 'test',
agent: 'test-agent',
path: { cwd: '/test', root: '/test' },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
},
parts: [],
}
}
function textPart(sessionID: string, messageID: string, partID: string, text: string): Part {
return { id: partID, sessionID, messageID, type: 'text', text } as Part
}
+22 -15
View File
@@ -73,19 +73,21 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string
const batcherRef = useRef<ReturnType<typeof createPartsBatcher> | null>(null)
useEffect(() => {
if (!opcodeUrl || !primaryDirectory) {
if (!opcodeUrl) {
batcherRef.current?.destroy()
batcherRef.current = null
return
}
batcherRef.current = createPartsBatcher(queryClient, opcodeUrl, primaryDirectory)
if (!batcherRef.current) {
batcherRef.current = createPartsBatcher(queryClient, opcodeUrl)
}
return () => {
batcherRef.current?.destroy()
batcherRef.current = null
}
}, [queryClient, opcodeUrl, primaryDirectory])
}, [queryClient, opcodeUrl])
const resolveCacheDirectory = useCallback(
(eventDirectory: string | undefined): string | undefined => {
@@ -134,14 +136,14 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string
case 'messagev2.part.updated': {
if (!('part' in event.properties)) break
const { part } = event.properties
batcherRef.current?.queuePartUpdate(part.sessionID, part)
batcherRef.current?.queuePartUpdate(part.sessionID, part, cacheDirectory)
break
}
case 'message.part.delta': {
if (!('sessionID' in event.properties && 'messageID' in event.properties && 'partID' in event.properties && 'field' in event.properties && 'delta' in event.properties)) break
const { sessionID, messageID, partID, field, delta } = event.properties
batcherRef.current?.queuePartDelta(sessionID, messageID, partID, field, delta)
batcherRef.current?.queuePartDelta(sessionID, messageID, partID, field, delta, cacheDirectory)
break
}
@@ -166,15 +168,15 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string
? currentData.filter(msgWithParts => !msgWithParts.info.id.startsWith('optimistic_'))
: currentData
queryClient.setQueryData(messagesQueryKey, [...filteredData, { info, parts: [] }])
return
} else {
const updated = currentData.map(msgWithParts => {
if (msgWithParts.info.id !== info.id) return msgWithParts
return { ...msgWithParts, info: { ...info } }
})
queryClient.setQueryData(messagesQueryKey, updated)
}
const updated = currentData.map(msgWithParts => {
if (msgWithParts.info.id !== info.id) return msgWithParts
return { ...msgWithParts, info: { ...info } }
})
queryClient.setQueryData(messagesQueryKey, updated)
batcherRef.current?.flush({ sessionID, directory: cacheDirectory })
break
}
@@ -200,7 +202,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string
const { sessionID, messageID, partID } = event.properties
batcherRef.current?.queuePartRemoval(sessionID, messageID, partID)
batcherRef.current?.queuePartRemoval(sessionID, messageID, partID, cacheDirectory)
break
}
@@ -224,11 +226,14 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string
setSessionStatus(sessionID, { type: 'idle' })
batcherRef.current?.flush()
batcherRef.current?.flush({ sessionID, directory: cacheDirectory })
const messagesQueryKey = ['opencode', 'messages', opcodeUrl, sessionID, cacheDirectory]
const currentData = queryClient.getQueryData<MessageWithParts[]>(messagesQueryKey)
if (!currentData) break
if (!currentData) {
queryClient.invalidateQueries({ queryKey: messagesQueryKey })
break
}
const now = Date.now()
const updated = currentData.map(msgWithParts => {
@@ -267,6 +272,8 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string
})
queryClient.setQueryData(messagesQueryKey, updated)
queryClient.invalidateQueries({ queryKey: messagesQueryKey })
break
}
@@ -79,6 +79,56 @@ describe('OpenCodeEventStream', () => {
})
})
it('opens the initial EventSource URL with first subscriber directories', () => {
const transport = new TestEventStreamTransport()
const stream = new OpenCodeEventStream({ transport })
stream.subscribeGlobalMonitor({ directories: ['/repo'], onEvent: vi.fn() })
expect(transport.openedUrls).toHaveLength(1)
const url = transport.openedUrls[0]
expect(url).toContain('/api/sse/stream')
expect(url).toContain(encodeURIComponent('/repo'))
})
it('opens the initial EventSource URL with all first subscriber directories', () => {
const transport = new TestEventStreamTransport()
const stream = new OpenCodeEventStream({ transport })
stream.subscribeGlobalMonitor({ directories: ['/repo-a', '/repo-b'], onEvent: vi.fn() })
expect(transport.openedUrls).toHaveLength(1)
const url = transport.openedUrls[0]
expect(url).toContain('/api/sse/stream')
expect(url).toContain(encodeURIComponent('/repo-a'))
expect(url).toContain(encodeURIComponent('/repo-b'))
})
it('marks health unhealthy when backend connected event reports no upstream connection', () => {
const transport = new TestEventStreamTransport()
const stream = new OpenCodeEventStream({ transport })
const healthStates: EventStreamHealthState[] = []
stream.subscribeGlobalMonitor({
directories: [],
onEvent: vi.fn(),
onHealthChange: (health) => healthStates.push(health),
})
transport.openConnection()
transport.connectedPayload({ clientId: 'client-1', connected: 0, total: 1 })
const unhealthyState = healthStates.at(-1)
expect(unhealthyState?.isConnected).toBe(true)
expect(unhealthyState?.isHealthy).toBe(false)
transport.connectedPayload({ clientId: 'client-1', connected: 1, total: 1 })
const healthyState = healthStates.at(-1)
expect(healthyState?.isConnected).toBe(true)
expect(healthyState?.isHealthy).toBe(true)
})
it('reports visibility through the transport adapter', async () => {
const transport = new TestEventStreamTransport()
const stream = new OpenCodeEventStream({ transport })
@@ -35,6 +35,8 @@ export class OpenCodeEventStream {
private clientId: string | null = null
private lastEventAt: number | null = null
private watchdogTimer: ReturnType<typeof setInterval> | null = null
private upstreamConnectedCount: number | null = null
private upstreamTotalCount: number | null = null
constructor(options: OpenCodeEventStreamOptions = {}) {
this.transport = options.transport ?? createBrowserEventStreamTransport()
@@ -46,8 +48,7 @@ export class OpenCodeEventStream {
onStatusChange?: EventStreamStatusHandler
onHealthChange?: (state: EventStreamHealthState) => void
}): GlobalMonitorSubscription {
const id = this.addSubscriber(input.onEvent, input.onStatusChange, input.onHealthChange)
this.updateSubscriberDirectories(id, input.directories)
const id = this.addSubscriber(input.onEvent, input.onStatusChange, input.onHealthChange, input.directories)
return {
updateDirectories: (directories) => this.updateSubscriberDirectories(id, directories),
@@ -65,14 +66,31 @@ export class OpenCodeEventStream {
onEvent: OpenCodeEventHandler,
onStatusChange?: EventStreamStatusHandler,
onHealthChange?: (state: EventStreamHealthState) => void,
directories: string[] = [],
): string {
const id = `sub_${++this.subscriberIdCounter}`
const initialDirectories = new Set(directories.filter(Boolean))
const newDirectories: string[] = []
for (const directory of initialDirectories) {
const currentCount = this.directoryRefCounts.get(directory) ?? 0
this.directoryRefCounts.set(directory, currentCount + 1)
if (currentCount === 0) {
if (this.clientId && this.connected) {
newDirectories.push(directory)
} else {
this.pendingDirectories.add(directory)
}
}
}
this.subscribers.set(id, {
id,
onEvent,
onStatusChange,
onHealthChange,
directories: new Set(),
directories: initialDirectories,
})
onStatusChange?.(this.connected)
@@ -80,6 +98,8 @@ export class OpenCodeEventStream {
if (this.subscribers.size === 1) {
this.connect()
} else if (newDirectories.length > 0) {
void this.subscribeToRemoteDirectories(newDirectories)
}
return id
@@ -186,6 +206,8 @@ export class OpenCodeEventStream {
private handleError(): void {
this.connected = false
this.clientId = null
this.upstreamConnectedCount = null
this.upstreamTotalCount = null
this.stopWatchdog()
this.lastEventAt = null
@@ -213,10 +235,16 @@ export class OpenCodeEventStream {
private handleConnected(data: string): void {
try {
const parsed = JSON.parse(data) as { clientId?: unknown }
const parsed = JSON.parse(data) as { clientId?: unknown; connected?: unknown; total?: unknown }
if (typeof parsed.clientId === 'string') {
this.clientId = parsed.clientId
}
if (typeof parsed.connected === 'number') {
this.upstreamConnectedCount = parsed.connected
}
if (typeof parsed.total === 'number') {
this.upstreamTotalCount = parsed.total
}
} catch {
this.clientId = null
}
@@ -239,6 +267,8 @@ export class OpenCodeEventStream {
this.connection = null
this.connected = false
this.clientId = null
this.upstreamConnectedCount = null
this.upstreamTotalCount = null
this.lastEventAt = null
this.pendingDirectories.clear()
this.notifyHealth()
@@ -263,6 +293,8 @@ export class OpenCodeEventStream {
this.connection = null
this.connected = false
this.clientId = null
this.upstreamConnectedCount = null
this.upstreamTotalCount = null
this.lastEventAt = null
this.pendingDirectories = new Set(this.directoryRefCounts.keys())
this.notifyStatusChange(false)
@@ -308,9 +340,10 @@ export class OpenCodeEventStream {
private buildHealth(): EventStreamHealthState {
const isStalled = this.connected && this.lastEventAt != null && Date.now() - this.lastEventAt > STALL_THRESHOLD_MS
const upstreamDisconnected = this.upstreamTotalCount != null && this.upstreamTotalCount > 0 && this.upstreamConnectedCount === 0
return {
isConnected: this.connected,
isHealthy: this.connected && this.lastEventAt != null && !isStalled,
isHealthy: this.connected && this.lastEventAt != null && !isStalled && !upstreamDisconnected,
lastEventAt: this.lastEventAt,
isStalled,
}
@@ -2,11 +2,13 @@ import type { EventStreamConnection, EventStreamTransport, EventStreamTransportH
export class TestEventStreamTransport implements EventStreamTransport {
readonly posts: Array<{ path: string; body: unknown }> = []
readonly openedUrls: string[] = []
closeCount = 0
private handlers: EventStreamTransportHandlers | null = null
private connection: EventStreamConnection | null = null
open(_url: string, handlers: EventStreamTransportHandlers): EventStreamConnection {
open(url: string, handlers: EventStreamTransportHandlers): EventStreamConnection {
this.openedUrls.push(url)
this.handlers = handlers
this.connection = {
close: () => {
@@ -29,7 +31,11 @@ export class TestEventStreamTransport implements EventStreamTransport {
}
connected(clientId = 'test-client'): void {
this.handlers?.onConnected(JSON.stringify({ clientId }))
this.connectedPayload({ clientId })
}
connectedPayload(payload: unknown): void {
this.handlers?.onConnected(JSON.stringify(payload))
}
message(data: unknown): void {
+137
View File
@@ -0,0 +1,137 @@
import { QueryClient } from '@tanstack/react-query'
import { describe, it, expect, vi } from 'vitest'
import { createPartsBatcher } from './partsBatcher'
import type { Part, MessageWithParts } from '@/api/types'
function assistantMessage(sessionID: string, messageID: string): MessageWithParts {
return {
info: {
id: messageID,
sessionID,
role: 'assistant',
time: { created: Date.now() },
parentID: '',
modelID: 'test-model',
providerID: 'test-provider',
mode: 'test',
agent: 'test-agent',
path: { cwd: '/test', root: '/test' },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
},
parts: [],
}
}
function textPart(sessionID: string, messageID: string, partID: string, text: string): Part {
return { id: partID, sessionID, messageID, type: 'text', text } as Part
}
describe('createPartsBatcher', () => {
it('keeps part deltas queued until message cache exists', () => {
const queryClient = new QueryClient()
const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries')
const batcher = createPartsBatcher(queryClient, 'http://localhost:5551')
batcher.queuePartDelta('session-1', 'message-1', 'part-1', 'text', 'Hello', '/repo')
batcher.flush()
expect(
queryClient.getQueryData(['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo']),
).toBeUndefined()
expect(invalidateSpy).toHaveBeenCalledWith({
queryKey: ['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo'],
})
queryClient.setQueryData(
['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo'],
[assistantMessage('session-1', 'message-1')],
)
batcher.queuePartUpdate('session-1', textPart('session-1', 'message-1', 'part-1', 'Hello world'), '/repo')
batcher.flush()
const data = queryClient.getQueryData<MessageWithParts[]>([
'opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo',
])
expect(data).toHaveLength(1)
expect(data![0].parts).toHaveLength(1)
expect(data![0].parts[0]).toHaveProperty('text', 'Hello world')
})
it('does not replay stale deltas after authoritative upsert resolves the part', () => {
const queryClient = new QueryClient()
const batcher = createPartsBatcher(queryClient, 'http://localhost:5551')
batcher.queuePartDelta('session-1', 'message-1', 'part-1', 'text', 'stale delta ', '/repo')
batcher.flush()
queryClient.setQueryData(
['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo'],
[assistantMessage('session-1', 'message-1')],
)
batcher.queuePartUpdate('session-1', textPart('session-1', 'message-1', 'part-1', 'authoritative text'), '/repo')
batcher.flush()
const data = queryClient.getQueryData<MessageWithParts[]>([
'opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo',
])
expect(data![0].parts).toHaveLength(1)
expect(data![0].parts[0]).toHaveProperty('text', 'authoritative text')
batcher.flush()
const data2 = queryClient.getQueryData<MessageWithParts[]>([
'opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo',
])
expect(data2![0].parts[0]).toHaveProperty('text', 'authoritative text')
})
it('applies deltas queued after an authoritative upsert in the same batch', () => {
const queryClient = new QueryClient()
const batcher = createPartsBatcher(queryClient, 'http://localhost:5551')
queryClient.setQueryData(
['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo'],
[assistantMessage('session-1', 'message-1')],
)
batcher.queuePartUpdate('session-1', textPart('session-1', 'message-1', 'part-1', 'snapshot'), '/repo')
batcher.queuePartDelta('session-1', 'message-1', 'part-1', 'text', ' later', '/repo')
batcher.flush()
const data = queryClient.getQueryData<MessageWithParts[]>([
'opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo',
])
expect(data![0].parts).toHaveLength(1)
expect(data![0].parts[0]).toHaveProperty('text', 'snapshot later')
})
it('applies deltas to the directory they were queued for', () => {
const queryClient = new QueryClient()
const batcher = createPartsBatcher(queryClient, 'http://localhost:5551')
queryClient.setQueryData(
['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo-a'],
[assistantMessage('session-1', 'message-1')],
)
queryClient.setQueryData(
['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo-b'],
[{ ...assistantMessage('session-1', 'message-1'), parts: [textPart('session-1', 'message-1', 'part-1', 'B')] }],
)
batcher.queuePartDelta('session-1', 'message-1', 'part-1', 'text', ' + chunk', '/repo-b')
batcher.flush()
const repoBData = queryClient.getQueryData<MessageWithParts[]>([
'opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo-b',
])
expect(repoBData![0].parts[0]).toHaveProperty('text', 'B + chunk')
const repoAData = queryClient.getQueryData<MessageWithParts[]>([
'opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo-a',
])
expect(repoAData![0].parts).toHaveLength(0)
})
})
+121 -45
View File
@@ -2,10 +2,10 @@ import type { QueryClient } from '@tanstack/react-query'
import type { Part, MessageWithParts } from '@/api/types'
interface PartsBatcher {
queuePartUpdate: (sessionID: string, part: Part) => void
queuePartDelta: (sessionID: string, messageID: string, partID: string, field: string, delta: string) => void
queuePartRemoval: (sessionID: string, messageID: string, partID: string) => void
flush: () => void
queuePartUpdate: (sessionID: string, part: Part, directory?: string) => void
queuePartDelta: (sessionID: string, messageID: string, partID: string, field: string, delta: string, directory?: string) => void
queuePartRemoval: (sessionID: string, messageID: string, partID: string, directory?: string) => void
flush: (target?: { sessionID?: string; directory?: string }) => void
destroy: () => void
}
@@ -14,12 +14,21 @@ type PartOperation =
| { type: 'delta'; messageID: string; partID: string; field: string; delta: string }
| { type: 'remove'; messageID: string; partID: string }
type OperationGroup = {
sessionID: string
directory?: string
operations: PartOperation[]
}
function groupKey(sessionID: string, directory?: string): string {
return `${directory ?? ''}\0${sessionID}`
}
export function createPartsBatcher(
queryClient: QueryClient,
opcodeUrl: string,
directory?: string
): PartsBatcher {
const pendingOperations = new Map<string, PartOperation[]>()
const pendingOperations = new Map<string, OperationGroup>()
let pendingFrameId: number | null = null
const scheduleFlush = () => {
@@ -30,47 +39,92 @@ export function createPartsBatcher(
})
}
const flush = () => {
const flush = (target?: { sessionID?: string; directory?: string }) => {
if (pendingOperations.size === 0) return
for (const [sessionID, operations] of pendingOperations.entries()) {
const groupsToDelete: string[] = []
for (const [key, group] of pendingOperations.entries()) {
if (target) {
if (target.sessionID !== undefined && group.sessionID !== target.sessionID) continue
if (target.directory !== undefined && group.directory !== target.directory) continue
}
const { sessionID, directory } = group
const queryKey = ['opencode', 'messages', opcodeUrl, sessionID, directory]
const currentData = queryClient.getQueryData<MessageWithParts[]>(queryKey)
if (!currentData) continue
if (!currentData) {
queryClient.invalidateQueries({ queryKey })
continue
}
let updatedData = [...currentData]
let anyApplied = false
const unapplied: PartOperation[] = []
const supersededPartIDs = new Set<string>()
for (const operation of operations) {
updatedData = updatedData.map((msgWithParts) => {
if (operation.type === 'upsert') {
if (msgWithParts.info.id !== operation.part.messageID) return msgWithParts
const existingIdx = msgWithParts.parts.findIndex((part) => part.id === operation.part.id)
const parts = [...msgWithParts.parts]
if (existingIdx >= 0) {
parts[existingIdx] = operation.part
} else {
parts.push(operation.part)
}
return { ...msgWithParts, parts }
for (const operation of group.operations) {
if (operation.type === 'upsert') {
const targetMsg = updatedData.find((m) => m.info.id === operation.part.messageID)
if (!targetMsg) {
unapplied.push(operation)
continue
}
if (msgWithParts.info.id !== operation.messageID) return msgWithParts
if (operation.type === 'remove') {
return {
...msgWithParts,
parts: msgWithParts.parts.filter((part) => part.id !== operation.partID),
}
anyApplied = true
const existingIdx = targetMsg.parts.findIndex((part) => part.id === operation.part.id)
const parts = [...targetMsg.parts]
if (existingIdx >= 0) {
parts[existingIdx] = operation.part
} else {
parts.push(operation.part)
}
updatedData = updatedData.map((m) =>
m.info.id === operation.part.messageID ? { ...m, parts } : m,
)
supersededPartIDs.add(operation.part.id)
continue
}
if (operation.type === 'remove') {
const targetMsg = updatedData.find((m) => m.info.id === operation.messageID)
if (!targetMsg) {
unapplied.push(operation)
continue
}
anyApplied = true
updatedData = updatedData.map((m) =>
m.info.id === operation.messageID
? { ...m, parts: m.parts.filter((part) => part.id !== operation.partID) }
: m,
)
supersededPartIDs.add(operation.partID)
continue
}
const targetMsg = updatedData.find((m) => m.info.id === operation.messageID)
if (!targetMsg) {
unapplied.push(operation)
continue
}
const targetPart = targetMsg.parts.find((p) => p.id === operation.partID)
if (!targetPart) {
unapplied.push(operation)
continue
}
anyApplied = true
updatedData = updatedData.map((m) => {
if (m.info.id !== operation.messageID) return m
return {
...msgWithParts,
parts: msgWithParts.parts.map((part) => {
...m,
parts: m.parts.map((part) => {
if (part.id !== operation.partID) return part
const currentValue = (part as Record<string, unknown>)[operation.field]
const nextValue = `${typeof currentValue === 'string' ? currentValue : ''}${operation.delta}`
return { ...part, [operation.field]: nextValue } as Part
@@ -79,29 +133,51 @@ export function createPartsBatcher(
})
}
queryClient.setQueryData(queryKey, updatedData)
if (anyApplied) {
queryClient.setQueryData(queryKey, updatedData)
}
const filteredUnapplied = unapplied.filter((op) => {
if (op.type === 'delta' || op.type === 'remove') {
return !supersededPartIDs.has(op.partID)
}
return true
})
if (filteredUnapplied.length > 0) {
group.operations = filteredUnapplied
queryClient.invalidateQueries({ queryKey })
} else {
groupsToDelete.push(key)
}
}
pendingOperations.clear()
for (const key of groupsToDelete) {
pendingOperations.delete(key)
}
}
const queueOperation = (sessionID: string, operation: PartOperation) => {
const operations = pendingOperations.get(sessionID) ?? []
operations.push(operation)
pendingOperations.set(sessionID, operations)
const queueOperation = (sessionID: string, operation: PartOperation, directory?: string) => {
const key = groupKey(sessionID, directory)
let group = pendingOperations.get(key)
if (!group) {
group = { sessionID, directory, operations: [] }
pendingOperations.set(key, group)
}
group.operations.push(operation)
scheduleFlush()
}
const queuePartUpdate = (sessionID: string, part: Part) => {
queueOperation(sessionID, { type: 'upsert', part })
const queuePartUpdate = (sessionID: string, part: Part, directory?: string) => {
queueOperation(sessionID, { type: 'upsert', part }, directory)
}
const queuePartDelta = (sessionID: string, messageID: string, partID: string, field: string, delta: string) => {
queueOperation(sessionID, { type: 'delta', messageID, partID, field, delta })
const queuePartDelta = (sessionID: string, messageID: string, partID: string, field: string, delta: string, directory?: string) => {
queueOperation(sessionID, { type: 'delta', messageID, partID, field, delta }, directory)
}
const queuePartRemoval = (sessionID: string, messageID: string, partID: string) => {
queueOperation(sessionID, { type: 'remove', messageID, partID })
const queuePartRemoval = (sessionID: string, messageID: string, partID: string, directory?: string) => {
queueOperation(sessionID, { type: 'remove', messageID, partID }, directory)
}
const destroy = () => {