mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
perf(terminal): cut remote keystroke latency and per-frame copies (#39663)
* perf(terminal): send idle remote keystrokes without the 8ms debounce Remote terminal input batching was a pure trailing debounce, so every isolated keystroke waited 8ms before leaving the renderer. Send input at once when the batcher is idle and coalesce only what arrives inside the following window. Recovery-hold replay keeps the trailing path so a synchronous flush cannot re-enter the still-buffering hold. * perf(ssh): disable Nagle on loopback sockets carrying orcad RPC The SSH forward listener, the stdio bridge listener, and the remote bridge's connect to orcad relay WebSocket RPC (keystrokes and echo). ws sets TCP_NODELAY on its own sockets, but these relay sockets did not, so small writes could wait behind an unacknowledged segment. * perf(terminal): decode terminal frame payloads as views, not copies Every message buffer is fresh and consumers decode the payload synchronously or retain it read-only; the only in-place rewrite touches header bytes. * fix(terminal): send idle remote keys at once only to input-acking hosts On hosts without input acks, an immediately sent key travels as a stream frame while a following accepted write (Ctrl+C, paste) goes as a separate terminal.send RPC on another socket, so the host could apply them out of order. Keep the trailing batch there so both still leave as one RPC.
This commit is contained in:
@@ -70,7 +70,8 @@ export async function listenOrcadStdioBridge(
|
||||
pipeSocketThroughBridge(socket, channel, mode)
|
||||
}
|
||||
|
||||
const server = createServer((socket) => {
|
||||
// Why noDelay: bridged orcad RPC carries keystroke echo; Nagle would hold small writes behind an unacked segment.
|
||||
const server = createServer({ noDelay: true }, (socket) => {
|
||||
sockets.add(socket)
|
||||
socket.on('error', () => socket.destroy())
|
||||
const entry = {
|
||||
|
||||
@@ -19,7 +19,7 @@ export const ORCAD_STDIO_BRIDGE_FUNCTION = `function orcadStdioBridge(port, mode
|
||||
const exit = () => out.write('', () => process.exit(0))
|
||||
out.on('error', () => process.exit(0))
|
||||
let connected = false
|
||||
const socket = net.connect({ host: '127.0.0.1', port })
|
||||
const socket = net.connect({ host: '127.0.0.1', port, noDelay: true })
|
||||
socket.on('error', (error) => {
|
||||
if (!connected) out.write(${text(`${ORCAD_STDIO_BRIDGE_REFUSED} `)} + String(error.code || 'ERROR') + '\\n', () => process.exit(0))
|
||||
})
|
||||
|
||||
@@ -103,7 +103,7 @@ function getLastMockServer() {
|
||||
|
||||
vi.mock('net', () => {
|
||||
return {
|
||||
createServer: vi.fn().mockImplementation((connectionHandler) => {
|
||||
createServer: vi.fn().mockImplementation((_options, connectionHandler) => {
|
||||
const listeners = new Map<string, (...args: unknown[]) => void>()
|
||||
let boundPort = 0
|
||||
const server = {
|
||||
|
||||
@@ -21,7 +21,8 @@ export class Ssh2PortForwardProvider implements SshPortForwardProvider {
|
||||
const activeSockets = new Set<Socket>()
|
||||
let closed = false
|
||||
|
||||
const server = createServer((socket) => {
|
||||
// Why noDelay: forwarded orcad RPC carries keystroke echo; Nagle would hold small writes behind an unacked segment.
|
||||
const server = createServer({ noDelay: true }, (socket) => {
|
||||
activeSockets.add(socket)
|
||||
socket.on('close', () => activeSockets.delete(socket))
|
||||
socket.on('error', () => socket.destroy())
|
||||
|
||||
+51
-26
@@ -7,7 +7,7 @@ import {
|
||||
} from './remote-runtime-pty-batching'
|
||||
|
||||
describe('createRemoteRuntimePtyTextBatcher', () => {
|
||||
it('coalesces small input until the debounce flush', async () => {
|
||||
it('sends idle input at once and coalesces input inside the window', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const flushes: string[] = []
|
||||
@@ -15,38 +15,67 @@ describe('createRemoteRuntimePtyTextBatcher', () => {
|
||||
maxPendingBytes: 8
|
||||
})
|
||||
|
||||
expect(batcher.hasPendingInput()).toBe(false)
|
||||
expect(batcher.push('a')).toBe(true)
|
||||
expect(flushes).toEqual(['a'])
|
||||
expect(batcher.push('b')).toBe(true)
|
||||
expect(flushes).toEqual([])
|
||||
// Why: a remount during the debounce discards these, and the pane must know to say so.
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(batcher.push('c')).toBe(true)
|
||||
expect(flushes).toEqual(['a'])
|
||||
// Why: a remount during the window discards these, and the pane must know to say so.
|
||||
expect(batcher.hasPendingInput()).toBe(true)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(10)
|
||||
|
||||
expect(flushes).toEqual(['ab'])
|
||||
expect(flushes).toEqual(['a', 'bc'])
|
||||
expect(batcher.hasPendingInput()).toBe(false)
|
||||
|
||||
// The window stays open after a trailing flush; once it lapses idle, the next key goes at once.
|
||||
expect(batcher.push('d')).toBe(true)
|
||||
expect(flushes).toEqual(['a', 'bc'])
|
||||
await vi.advanceTimersByTimeAsync(10)
|
||||
expect(flushes).toEqual(['a', 'bc', 'd'])
|
||||
await vi.advanceTimersByTimeAsync(10)
|
||||
expect(batcher.push('e')).toBe(true)
|
||||
expect(flushes).toEqual(['a', 'bc', 'd', 'e'])
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps idle input trailing while the leading edge is disabled', () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const flushes: string[] = []
|
||||
const batcher = createRemoteRuntimePtyTextBatcher(10, (text) => flushes.push(text), {
|
||||
sendLeadingEdge: () => false
|
||||
})
|
||||
|
||||
expect(batcher.push('a')).toBe(true)
|
||||
expect(batcher.push('b')).toBe(true)
|
||||
expect(flushes).toEqual([])
|
||||
vi.advanceTimersByTime(10)
|
||||
expect(flushes).toEqual(['ab'])
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('flushes before pending input exceeds the byte ceiling', () => {
|
||||
const flushes: string[] = []
|
||||
const batcher = createRemoteRuntimePtyTextBatcher(10, (text) => flushes.push(text), {
|
||||
maxPendingBytes: 4
|
||||
})
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const flushes: string[] = []
|
||||
const batcher = createRemoteRuntimePtyTextBatcher(10, (text) => flushes.push(text), {
|
||||
maxPendingBytes: 4
|
||||
})
|
||||
|
||||
expect(batcher.push('ab')).toBe(true)
|
||||
expect(batcher.push('cd')).toBe(true)
|
||||
expect(flushes).toEqual([])
|
||||
expect(batcher.push('x')).toBe(true)
|
||||
expect(batcher.push('ab')).toBe(true)
|
||||
expect(batcher.push('cd')).toBe(true)
|
||||
expect(flushes).toEqual(['x'])
|
||||
|
||||
expect(batcher.push('e')).toBe(true)
|
||||
|
||||
expect(flushes).toEqual(['abcd'])
|
||||
batcher.flush()
|
||||
expect(flushes).toEqual(['abcd', 'e'])
|
||||
expect(batcher.push('e')).toBe(true)
|
||||
expect(flushes).toEqual(['x', 'abcd', 'e'])
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('splits one large UTF-8 input without splitting a code point', () => {
|
||||
@@ -75,7 +104,7 @@ describe('createRemoteRuntimePtyTextBatcher', () => {
|
||||
expect(flushes).toEqual([])
|
||||
})
|
||||
|
||||
it('yields while validating large accepted input before debounce flushing', async () => {
|
||||
it('yields while validating large accepted input before sending it', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const flushes: string[] = []
|
||||
@@ -91,10 +120,6 @@ describe('createRemoteRuntimePtyTextBatcher', () => {
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
await drained
|
||||
|
||||
expect(flushes).toEqual([])
|
||||
|
||||
await vi.advanceTimersByTimeAsync(10)
|
||||
|
||||
expect(flushes).toEqual([text])
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
@@ -117,8 +142,8 @@ describe('createRemoteRuntimePtyTextBatcher', () => {
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
await drained
|
||||
|
||||
expect(batcher.takePending()).toBe(`${text}tail`)
|
||||
expect(flushes).toEqual([])
|
||||
expect(flushes).toEqual([text])
|
||||
expect(batcher.takePending()).toBe('tail')
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
|
||||
+17
-3
@@ -27,6 +27,8 @@ export type RemoteRuntimeViewportBatcher = {
|
||||
export type RemoteRuntimePtyTextBatcherOptions = {
|
||||
maxPendingBytes?: number
|
||||
maxBytes?: number
|
||||
/** False keeps input trailing even when idle; defaults to sending idle input at once. */
|
||||
sendLeadingEdge?: () => boolean
|
||||
}
|
||||
|
||||
export function createRemoteRuntimePtyTextBatcher(
|
||||
@@ -75,12 +77,24 @@ export function createRemoteRuntimePtyTextBatcher(
|
||||
return text
|
||||
}
|
||||
|
||||
// Why: the window only coalesces input that follows a send, so an isolated keystroke never waits.
|
||||
const closeWindow = (): void => {
|
||||
timer = null
|
||||
if (pending) {
|
||||
flush()
|
||||
timer ??= setTimeout(closeWindow, delayMs)
|
||||
}
|
||||
}
|
||||
|
||||
const queuePending = (chunk: string, chunkBytes: number): void => {
|
||||
if (!timer && !pending && (options.sendLeadingEdge?.() ?? true)) {
|
||||
timer = setTimeout(closeWindow, delayMs)
|
||||
onFlush(chunk)
|
||||
return
|
||||
}
|
||||
pending += chunk
|
||||
pendingBytes += chunkBytes
|
||||
if (!timer) {
|
||||
timer = setTimeout(flush, delayMs)
|
||||
}
|
||||
timer ??= setTimeout(closeWindow, delayMs)
|
||||
}
|
||||
|
||||
const pushValidatedInput = (data: string): void => {
|
||||
|
||||
+15
@@ -214,6 +214,21 @@ describe('remote pane input across a silent outage', () => {
|
||||
transport.destroy?.()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['acknowledging', { inputAck: 1 }, ['a']],
|
||||
['legacy', { outputPause: 1 }, []]
|
||||
] as const)(
|
||||
'sends an idle key at once only to a host that acknowledges input (%s)',
|
||||
async (_host, capabilities, immediate) => {
|
||||
const { transport } = await connectPane(capabilities)
|
||||
subscriptionSendBinary.mockClear()
|
||||
transport.sendInput('a', 'driving')
|
||||
expect(sentInputs().map((input) => input.text)).toEqual(immediate)
|
||||
transport.sendInput('b', 'driving')
|
||||
await vi.waitFor(() => expect(sentText()).toBe('ab'))
|
||||
}
|
||||
)
|
||||
|
||||
it('preserves the acknowledged input session across reconnects', async () => {
|
||||
const { transport, streamId } = await connectPane({ inputAck: 1 })
|
||||
const payload = latestSubscribePayload()
|
||||
|
||||
+16
-5
@@ -2276,11 +2276,22 @@ export function createRemoteRuntimePtyTransport(
|
||||
return true
|
||||
}
|
||||
|
||||
const inputBatcher = createRemoteRuntimePtyTextBatcher(REMOTE_TERMINAL_INPUT_FLUSH_MS, (text) => {
|
||||
if (!sendUnacknowledgedInput(text)) {
|
||||
holdUnsentInput(text)
|
||||
const inputBatcher = createRemoteRuntimePtyTextBatcher(
|
||||
REMOTE_TERMINAL_INPUT_FLUSH_MS,
|
||||
(text) => {
|
||||
if (!sendUnacknowledgedInput(text)) {
|
||||
holdUnsentInput(text)
|
||||
}
|
||||
},
|
||||
{
|
||||
// Why: without the ack journal an accepted write's separate RPC could overtake an immediate key.
|
||||
sendLeadingEdge: () =>
|
||||
// A hold replaying through sendInputNow must not re-enter its own queue.
|
||||
!recoveryInputHold.isHolding() &&
|
||||
handle !== null &&
|
||||
getCurrentMultiplexedStream(handle)?.acknowledgesInput() === true
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
function deferViewportForRecovery(claim: boolean): void {
|
||||
// Why: the replay sends the latest viewport; an older queued batch flushing after it would win.
|
||||
@@ -4107,7 +4118,7 @@ export function createRemoteRuntimePtyTransport(
|
||||
return sendInputNow(data)
|
||||
},
|
||||
|
||||
// Why: query replies (CPR/DSR/DA/OSC) are read in raw mode with a short timeout; the 8ms debounce would miss it and echo the reply onto the prompt (#7329).
|
||||
// Why: query replies (CPR/DSR/DA/OSC) are read in raw mode with a short timeout; the 8ms coalescing window would miss it and echo the reply onto the prompt (#7329).
|
||||
sendInputImmediate: (data: string): boolean => sendInputImmediateNow(data),
|
||||
|
||||
sendInputAccepted(data, inputKind, options) {
|
||||
|
||||
@@ -100,7 +100,8 @@ export function decodeTerminalStreamFrame(bytes: Uint8Array): TerminalStreamFram
|
||||
opcode,
|
||||
streamId: view.getUint32(4, true),
|
||||
seq: high * 0x100000000 + low,
|
||||
payload: bytes.slice(HEADER_BYTES)
|
||||
// Why a view: each message is a fresh buffer, and only the header is ever rewritten in place.
|
||||
payload: bytes.subarray(HEADER_BYTES)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user