Recover terminal subscribe overflow from snapshots

This commit is contained in:
Neil
2026-06-09 17:06:57 -07:00
parent 53c99c0314
commit 4d15d9c9d6
2 changed files with 133 additions and 17 deletions
+79 -6
View File
@@ -291,6 +291,38 @@ function trimPendingOutputToBudget(
return { bytes: pendingOutputBytes, overflowed: omittedChunkCount > 0 }
}
function trimPendingOutputCoveredBySnapshot(
pendingOutput: TerminalOutputChunk[],
snapshotSeq: number | undefined
): { chunks: TerminalOutputChunk[]; bytes: number } {
if (typeof snapshotSeq !== 'number') {
return {
chunks: pendingOutput,
bytes: pendingOutput.reduce((sum, chunk) => sum + terminalStreamByteLength(chunk.data), 0)
}
}
const chunks: TerminalOutputChunk[] = []
let bytes = 0
for (const chunk of pendingOutput) {
const chunkSeq = chunk.meta?.seq
const rawLength = chunk.meta?.rawLength ?? chunk.data.length
if (typeof chunkSeq !== 'number' || rawLength !== chunk.data.length) {
chunks.push(chunk)
bytes += terminalStreamByteLength(chunk.data)
continue
}
const startSeq = chunkSeq - rawLength
if (snapshotSeq >= chunkSeq) {
continue
}
const data =
snapshotSeq > startSeq ? chunk.data.slice(Math.max(0, snapshotSeq - startSeq)) : chunk.data
chunks.push({ data, meta: data === chunk.data ? chunk.meta : undefined })
bytes += terminalStreamByteLength(data)
}
return { chunks, bytes }
}
function terminalStreamByteLength(data: string): number {
return terminalStreamTextEncoder.encode(data).byteLength
}
@@ -1566,8 +1598,9 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
let cursor = 0
let closed = false
let buffering = true
const pendingOutput: string[] = []
let pendingOutput: TerminalOutputChunk[] = []
let pendingOutputBytes = 0
let pendingOutputOverflowed = false
let unsubscribeData = (): void => {}
let unsubscribeResize = (): void => {}
let unsubscribeFit = (): void => {}
@@ -1669,17 +1702,19 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
return
}
unsubscribeData = runtime.subscribeToTerminalData(ptyId, (data) => {
unsubscribeData = runtime.subscribeToTerminalData(ptyId, (data, meta) => {
if (closed) {
return
}
if (buffering) {
pendingOutput.push(data)
pendingOutput.push({ data, meta })
pendingOutputBytes += terminalStreamByteLength(data)
pendingOutputBytes = trimPendingOutputToBudget(pendingOutput, pendingOutputBytes).bytes
const trimmed = trimPendingOutputToBudget(pendingOutput, pendingOutputBytes)
pendingOutputBytes = trimmed.bytes
pendingOutputOverflowed ||= trimmed.overflowed
return
}
outputBatcher?.push(data)
outputBatcher?.push(data, meta)
})
const read = await runtime.readTerminal(params.terminal)
@@ -1723,9 +1758,47 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
scrollbackRows: serialized?.scrollbackRows,
truncatedByByteBudget: serialized?.truncatedByByteBudget === true
})
let recoveryAttempts = 0
// Why: if the bounded pre-subscribe tail overflowed, only a fresh
// model snapshot can cover the dropped middle without replay gaps.
while (pendingOutputOverflowed && recoveryAttempts < 2) {
pendingOutputOverflowed = false
recoveryAttempts += 1
const recovery = await serializeBudgetedMobileSnapshot(runtime, ptyId, isMobile)
if (closed) {
return
}
if (!recovery) {
break
}
const recoveryStats = sendSnapshotFrames(sendFrame, {
kind: 'scrollback',
cols: recovery.cols,
rows: recovery.rows,
displayMode,
reason: 'pending-output-overflow',
seq: recovery.seq,
source: recovery.source,
truncated: false,
truncatedByByteBudget: recovery.truncatedByByteBudget,
data: recovery.data
})
console.log('[mobile-terminal-stream] recovery snapshot', {
terminal: params.terminal,
streamId,
reason: 'pending-output-overflow',
bytes: recoveryStats.bytes,
chunks: recoveryStats.chunks,
scrollbackRows: recovery.scrollbackRows,
truncatedByByteBudget: recovery.truncatedByByteBudget === true
})
const trimmed = trimPendingOutputCoveredBySnapshot(pendingOutput, recovery.seq)
pendingOutput = trimmed.chunks
pendingOutputBytes = trimmed.bytes
}
buffering = false
for (const item of pendingOutput.splice(0)) {
outputBatcher.push(item)
outputBatcher.push(item.data, item.meta)
}
pendingOutputBytes = 0
outputBatcher.flush()
@@ -331,21 +331,35 @@ describe('terminal subscribe buffering', () => {
await dispatchPromise
})
it('bounds legacy binary output queued while the initial snapshot is serializing', async () => {
it('recovers binary output overflow queued while the initial snapshot is serializing', async () => {
vi.useFakeTimers()
try {
const messages: string[] = []
const binaryFrames: Uint8Array<ArrayBufferLike>[] = []
const cleanups = new Map<string, () => void>()
const dataListenerRef: { current?: (data: string) => void } = {}
let resolveSnapshot: (value: { data: string; cols: number; rows: number }) => void = () => {}
const dataListenerRef: {
current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void
} = {}
const snapshotResolvers: ((value: {
data: string
cols: number
rows: number
seq?: number
source?: 'headless' | 'renderer'
}) => void)[] = []
const runtime = stubRuntime({
resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }),
readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }),
serializeTerminalBuffer: vi.fn(
() =>
new Promise<{ data: string; cols: number; rows: number }>((resolve) => {
resolveSnapshot = resolve
new Promise<{
data: string
cols: number
rows: number
seq?: number
source?: 'headless' | 'renderer'
}>((resolve) => {
snapshotResolvers.push(resolve)
})
),
getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }),
@@ -386,26 +400,55 @@ describe('terminal subscribe buffering', () => {
await vi.waitFor(() => expect(dataListenerRef.current).toBeDefined())
const shiftSpy = vi.spyOn(Array.prototype, 'shift')
let seq = 0
for (let index = 0; index < 400; index += 1) {
dataListenerRef.current?.(`${String(index).padStart(3, '0')}${'x'.repeat(1021)}`)
const data = `${String(index).padStart(3, '0')}${'x'.repeat(1021)}`
seq += data.length
dataListenerRef.current?.(data, { seq, rawLength: data.length })
}
const shiftCallCount = shiftSpy.mock.calls.length
shiftSpy.mockRestore()
await vi.waitFor(() => expect(runtime.serializeTerminalBuffer).toHaveBeenCalled())
resolveSnapshot({ data: '', cols: 120, rows: 40 })
snapshotResolvers[0]?.({ data: '', cols: 120, rows: 40, seq: 0, source: 'headless' })
await vi.waitFor(() => expect(runtime.serializeTerminalBuffer).toHaveBeenCalledTimes(2))
snapshotResolvers[1]?.({
data: 'recovered after overflow\r\n',
cols: 120,
rows: 40,
seq,
source: 'headless'
})
await vi.waitFor(() =>
expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true)
)
await vi.runOnlyPendingTimersAsync()
const output = binaryFrames
const decodedFrames = binaryFrames
.map((frame) => decodeTerminalStreamFrame(frame))
.filter((frame) => frame?.opcode === TerminalStreamOpcode.Output)
.map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : ''))
.filter((frame): frame is NonNullable<typeof frame> => frame !== null)
const snapshotStarts = decodedFrames.filter(
(frame) => frame.opcode === TerminalStreamOpcode.SnapshotStart
)
expect(snapshotStarts.map((frame) => decodeTerminalStreamJson(frame.payload))).toEqual([
expect.objectContaining({ kind: 'scrollback', seq: 1 }),
expect.objectContaining({
reason: 'pending-output-overflow',
seq,
source: 'headless'
})
])
const snapshotText = decodedFrames
.filter((frame) => frame.opcode === TerminalStreamOpcode.SnapshotChunk)
.map((frame) => decodeTerminalStreamText(frame.payload))
.join('')
const output = decodedFrames
.filter((frame) => frame.opcode === TerminalStreamOpcode.Output)
.map((frame) => decodeTerminalStreamText(frame.payload))
.join('')
expect(output.length).toBeLessThanOrEqual(256 * 1024)
expect(output).not.toContain('000')
expect(output).toContain('399')
expect(output).not.toContain('399')
expect(snapshotText).toContain('recovered after overflow')
expect(shiftCallCount).toBe(0)
runtime.cleanupSubscription('terminal-1:desktop-1')