Bound live terminal output frames (#4789)
This commit is contained in:
@@ -85,6 +85,11 @@ type TerminalOutputChunk = {
|
||||
meta?: { seq?: number; rawLength?: number }
|
||||
}
|
||||
|
||||
type TerminalOutputFrameChunk = {
|
||||
bytes: Uint8Array<ArrayBufferLike>
|
||||
seq?: number
|
||||
}
|
||||
|
||||
function createTerminalOutputBatcher(
|
||||
onFlush: (data: string, meta?: { seq?: number; rawLength?: number }) => void
|
||||
): {
|
||||
@@ -150,6 +155,52 @@ function createTerminalOutputBatcher(
|
||||
}
|
||||
}
|
||||
|
||||
function splitTerminalOutputFrameChunks(
|
||||
data: string,
|
||||
meta?: { seq?: number; rawLength?: number }
|
||||
): TerminalOutputFrameChunk[] {
|
||||
const bytes = encodeTerminalStreamText(data)
|
||||
if (bytes.byteLength <= TERMINAL_STREAM_CHUNK_BYTES) {
|
||||
return [{ bytes, seq: meta?.seq }]
|
||||
}
|
||||
const chunks: TerminalOutputFrameChunk[] = []
|
||||
const rawLength = meta?.rawLength ?? data.length
|
||||
const canPreserveChunkSeq = typeof meta?.seq === 'number' && rawLength === data.length
|
||||
const startSeq = canPreserveChunkSeq ? meta.seq! - rawLength : undefined
|
||||
let chunk = ''
|
||||
let chunkBytes = 0
|
||||
let chunkStartOffset = 0
|
||||
let offset = 0
|
||||
|
||||
const flushChunk = (): void => {
|
||||
if (!chunk) {
|
||||
return
|
||||
}
|
||||
const chunkSeq = canPreserveChunkSeq ? startSeq! + chunkStartOffset + chunk.length : undefined
|
||||
chunks.push({ bytes: encodeTerminalStreamText(chunk), seq: chunkSeq })
|
||||
chunk = ''
|
||||
chunkBytes = 0
|
||||
chunkStartOffset = offset
|
||||
}
|
||||
|
||||
for (const part of data) {
|
||||
const partBytes = terminalStreamByteLength(part)
|
||||
if (chunkBytes > 0 && chunkBytes + partBytes > TERMINAL_STREAM_CHUNK_BYTES) {
|
||||
flushChunk()
|
||||
}
|
||||
chunk += part
|
||||
chunkBytes += partBytes
|
||||
offset += part.length
|
||||
}
|
||||
flushChunk()
|
||||
if (!canPreserveChunkSeq && typeof meta?.seq === 'number' && chunks.length > 0) {
|
||||
// Why: if a future caller reports rawLength that cannot be mapped back to
|
||||
// UTF-16 offsets, only the final frame can safely carry the high-water mark.
|
||||
chunks.at(-1)!.seq = meta.seq
|
||||
}
|
||||
return chunks
|
||||
}
|
||||
|
||||
function isTerminalInputLockedForClient(
|
||||
runtime: OrcaRuntimeService,
|
||||
ptyId: string,
|
||||
@@ -1038,12 +1089,9 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
pendingOutputBytes: 0,
|
||||
pendingOutputOverflowed: false,
|
||||
outputBatcher: createTerminalOutputBatcher((data, meta) => {
|
||||
sendFrame(
|
||||
request.streamId,
|
||||
TerminalStreamOpcode.Output,
|
||||
encodeTerminalStreamText(data),
|
||||
meta?.seq
|
||||
)
|
||||
for (const chunk of splitTerminalOutputFrameChunks(data, meta)) {
|
||||
sendFrame(request.streamId, TerminalStreamOpcode.Output, chunk.bytes, chunk.seq)
|
||||
}
|
||||
}),
|
||||
unsubscribeData: () => {},
|
||||
unsubscribeResize: () => {},
|
||||
@@ -1364,7 +1412,9 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
sendBinary(encodeTerminalStreamFrame({ opcode, streamId, seq: cursor++, payload }))
|
||||
}
|
||||
outputBatcher = createTerminalOutputBatcher((data) => {
|
||||
sendFrame(TerminalStreamOpcode.Output, encodeTerminalStreamText(data))
|
||||
for (const chunk of splitTerminalOutputFrameChunks(data)) {
|
||||
sendFrame(TerminalStreamOpcode.Output, chunk.bytes)
|
||||
}
|
||||
})
|
||||
unregisterBinaryHandler =
|
||||
registerBinaryStreamHandler?.(streamId, (frame) => {
|
||||
|
||||
@@ -37,7 +37,9 @@ describe('terminal multiplex RPC', () => {
|
||||
(frame: NonNullable<ReturnType<typeof decodeTerminalStreamFrame>>) => void
|
||||
>()
|
||||
const cleanups = new Map<string, () => void>()
|
||||
const dataListenerRef: { current?: (data: string) => void } = {}
|
||||
const dataListenerRef: {
|
||||
current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void
|
||||
} = {}
|
||||
const runtime = stubRuntime({
|
||||
resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }),
|
||||
readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }),
|
||||
@@ -49,10 +51,15 @@ describe('terminal multiplex RPC', () => {
|
||||
getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }),
|
||||
getMobileDisplayMode: vi.fn().mockReturnValue('auto'),
|
||||
getLayout: vi.fn().mockReturnValue({ seq: 1 }),
|
||||
subscribeToTerminalData: vi.fn((_: string, listener: (data: string) => void) => {
|
||||
dataListenerRef.current = listener
|
||||
return vi.fn()
|
||||
}),
|
||||
subscribeToTerminalData: vi.fn(
|
||||
(
|
||||
_: string,
|
||||
listener: (data: string, meta?: { seq?: number; rawLength?: number }) => void
|
||||
) => {
|
||||
dataListenerRef.current = listener
|
||||
return vi.fn()
|
||||
}
|
||||
),
|
||||
subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()),
|
||||
subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()),
|
||||
subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()),
|
||||
@@ -242,7 +249,9 @@ describe('terminal multiplex RPC', () => {
|
||||
(frame: NonNullable<ReturnType<typeof decodeTerminalStreamFrame>>) => void
|
||||
>()
|
||||
const cleanups = new Map<string, () => void>()
|
||||
const dataListenerRef: { current?: (data: string) => void } = {}
|
||||
const dataListenerRef: {
|
||||
current?: (data: string, meta?: { seq?: number; rawLength?: number }) => void
|
||||
} = {}
|
||||
const runtime = stubRuntime({
|
||||
resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }),
|
||||
readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }),
|
||||
@@ -254,10 +263,15 @@ describe('terminal multiplex RPC', () => {
|
||||
getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }),
|
||||
getMobileDisplayMode: vi.fn().mockReturnValue('auto'),
|
||||
getLayout: vi.fn().mockReturnValue({ seq: 1 }),
|
||||
subscribeToTerminalData: vi.fn((_: string, listener: (data: string) => void) => {
|
||||
dataListenerRef.current = listener
|
||||
return vi.fn()
|
||||
}),
|
||||
subscribeToTerminalData: vi.fn(
|
||||
(
|
||||
_: string,
|
||||
listener: (data: string, meta?: { seq?: number; rawLength?: number }) => void
|
||||
) => {
|
||||
dataListenerRef.current = listener
|
||||
return vi.fn()
|
||||
}
|
||||
),
|
||||
subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()),
|
||||
subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()),
|
||||
subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()),
|
||||
@@ -309,15 +323,22 @@ describe('terminal multiplex RPC', () => {
|
||||
binaryFrames.splice(0)
|
||||
|
||||
const multibyteOutput = '界'.repeat(22_000)
|
||||
dataListenerRef.current?.(multibyteOutput)
|
||||
dataListenerRef.current?.(multibyteOutput, {
|
||||
seq: multibyteOutput.length,
|
||||
rawLength: multibyteOutput.length
|
||||
})
|
||||
|
||||
const outputFrames = binaryFrames
|
||||
.map((frame) => decodeTerminalStreamFrame(frame))
|
||||
.filter((frame) => frame?.opcode === TerminalStreamOpcode.Output)
|
||||
expect(outputFrames).toHaveLength(1)
|
||||
expect(outputFrames[0] ? decodeTerminalStreamText(outputFrames[0].payload) : '').toBe(
|
||||
multibyteOutput
|
||||
expect(outputFrames.length).toBeGreaterThan(1)
|
||||
expect(outputFrames.every((frame) => (frame?.payload.byteLength ?? 0) <= 48 * 1024)).toBe(
|
||||
true
|
||||
)
|
||||
expect(outputFrames.map((frame) => frame?.seq)).toEqual([16_384, 22_000])
|
||||
expect(
|
||||
outputFrames.map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')).join('')
|
||||
).toBe(multibyteOutput)
|
||||
|
||||
cleanups.get('terminal-multiplex:conn-multibyte-output-batch')?.()
|
||||
await dispatchPromise
|
||||
@@ -798,6 +819,92 @@ describe('terminal multiplex RPC', () => {
|
||||
await dispatchPromise
|
||||
})
|
||||
|
||||
it('bounds oversized live output frames for subscribed binary streams', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const messages: string[] = []
|
||||
const binaryFrames: Uint8Array<ArrayBufferLike>[] = []
|
||||
const handlers = new Map<
|
||||
number,
|
||||
(frame: NonNullable<ReturnType<typeof decodeTerminalStreamFrame>>) => void
|
||||
>()
|
||||
const cleanups = new Map<string, () => void>()
|
||||
const dataListenerRef: { current?: (data: string) => void } = {}
|
||||
const runtime = stubRuntime({
|
||||
resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }),
|
||||
readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }),
|
||||
serializeTerminalBuffer: vi.fn().mockResolvedValue({
|
||||
data: 'snapshot',
|
||||
cols: 120,
|
||||
rows: 40
|
||||
}),
|
||||
getTerminalSize: vi.fn().mockReturnValue({ cols: 120, rows: 40 }),
|
||||
getMobileDisplayMode: vi.fn().mockReturnValue('auto'),
|
||||
getLayout: vi.fn().mockReturnValue({ seq: 1 }),
|
||||
subscribeToTerminalData: vi.fn((_: string, listener: (data: string) => void) => {
|
||||
dataListenerRef.current = listener
|
||||
return vi.fn()
|
||||
}),
|
||||
subscribeToTerminalResize: vi.fn().mockReturnValue(vi.fn()),
|
||||
subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()),
|
||||
getDriver: vi.fn().mockReturnValue({ kind: 'idle' }),
|
||||
registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => {
|
||||
cleanups.set(id, cleanup)
|
||||
}),
|
||||
cleanupSubscription: vi.fn((id: string) => {
|
||||
const cleanup = cleanups.get(id)
|
||||
cleanups.delete(id)
|
||||
cleanup?.()
|
||||
}),
|
||||
waitForTerminal: vi.fn(() => new Promise<RuntimeTerminalWait>(() => {})),
|
||||
sendTerminal: vi.fn().mockResolvedValue({ accepted: true }),
|
||||
updateDesktopViewport: vi.fn().mockResolvedValue(true)
|
||||
})
|
||||
const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS })
|
||||
|
||||
const dispatchPromise = dispatcher.dispatchStreaming(
|
||||
makeRequest('terminal.subscribe', {
|
||||
terminal: 'terminal-1',
|
||||
client: { id: 'desktop-1', type: 'desktop' },
|
||||
capabilities: { terminalBinaryStream: 1 }
|
||||
}),
|
||||
(msg) => messages.push(msg),
|
||||
{
|
||||
connectionId: 'conn-subscribe-output-chunking',
|
||||
sendBinary: (bytes) => binaryFrames.push(bytes),
|
||||
registerBinaryStreamHandler: (streamId, handler) => {
|
||||
handlers.set(streamId, handler)
|
||||
return () => handlers.delete(streamId)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.some((msg) => JSON.parse(msg).result?.type === 'subscribed')).toBe(true)
|
||||
)
|
||||
binaryFrames.splice(0)
|
||||
|
||||
const output = 'output-line\n'.repeat(8_000)
|
||||
dataListenerRef.current?.(output)
|
||||
|
||||
const outputFrames = binaryFrames
|
||||
.map((frame) => decodeTerminalStreamFrame(frame))
|
||||
.filter((frame) => frame?.opcode === TerminalStreamOpcode.Output)
|
||||
expect(outputFrames.length).toBeGreaterThan(1)
|
||||
expect(outputFrames.every((frame) => (frame?.payload.byteLength ?? 0) <= 48 * 1024)).toBe(
|
||||
true
|
||||
)
|
||||
expect(
|
||||
outputFrames.map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : '')).join('')
|
||||
).toBe(output)
|
||||
|
||||
runtime.cleanupSubscription('terminal-1:desktop-1')
|
||||
await dispatchPromise
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('settles mobile multiplex PTY waits when the stream signal aborts before PTY spawn', async () => {
|
||||
const messages: string[] = []
|
||||
const binaryFrames: Uint8Array<ArrayBufferLike>[] = []
|
||||
|
||||
Reference in New Issue
Block a user