Improve daemon echo latency after interactive input (#2535)

This commit is contained in:
Jinjing
2026-05-21 11:48:53 -07:00
committed by GitHub
parent a140313d4a
commit cb15124cbb
4 changed files with 192 additions and 9 deletions
+80 -6
View File
@@ -1,19 +1,22 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { connect } from 'net'
import { connect, type Socket } from 'net'
import { tmpdir } from 'os'
import { join } from 'path'
import { mkdtempSync, rmSync, readFileSync } from 'fs'
import { DaemonServer } from './daemon-server'
import { DaemonClient } from './client'
import { encodeNdjson } from './ndjson'
import { PROTOCOL_VERSION } from './types'
import { PROTOCOL_VERSION, type DaemonRequest } from './types'
import type { SubprocessHandle } from './session'
function createTestDir(): string {
return mkdtempSync(join(tmpdir(), 'daemon-server-test-'))
}
function createMockSubprocess(): SubprocessHandle {
function createMockSubprocess(): SubprocessHandle & {
_simulateData: (data: string) => void
} {
let onDataCb: ((data: string) => void) | null = null
let onExitCb: ((code: number) => void) | null = null
return {
pid: 55555,
@@ -22,16 +25,31 @@ function createMockSubprocess(): SubprocessHandle {
kill: vi.fn(() => setTimeout(() => onExitCb?.(0), 5)),
forceKill: vi.fn(),
signal: vi.fn(),
onData(_cb) {
/* stored for future tests */
onData(cb) {
onDataCb = cb
},
onExit(cb) {
onExitCb = cb
},
dispose: vi.fn()
dispose: vi.fn(),
_simulateData(data: string) {
onDataCb?.(data)
}
}
}
type DaemonServerPrivate = {
clients: Map<
string,
{
clientId: string
controlSocket: Socket
streamSocket: Socket | null
}
>
routeRequest(clientId: string, request: DaemonRequest): Promise<unknown>
}
describe('DaemonServer', () => {
let dir: string
let socketPath: string
@@ -206,6 +224,62 @@ describe('DaemonServer', () => {
payload: { code: -1 }
})
})
it('bypasses daemon stream batching for output after input', async () => {
vi.useFakeTimers()
try {
let subprocess: ReturnType<typeof createMockSubprocess>
server = new DaemonServer({
socketPath,
tokenPath,
spawnSubprocess: () => {
subprocess = createMockSubprocess()
return subprocess
}
})
const daemon = server as unknown as DaemonServerPrivate
const controlSocket = { destroy: vi.fn() } as unknown as Socket
const streamSocket = {
destroyed: false,
destroy: vi.fn(),
write: vi.fn()
} as unknown as Socket & { write: ReturnType<typeof vi.fn> }
daemon.clients.set('client-1', {
clientId: 'client-1',
controlSocket,
streamSocket
})
await daemon.routeRequest('client-1', {
id: 'req-1',
type: 'createOrAttach',
payload: { sessionId: 'test-session', cols: 80, rows: 24 }
})
subprocess!._simulateData('background')
expect(streamSocket.write).not.toHaveBeenCalled()
vi.advanceTimersByTime(8)
expect(streamSocket.write).toHaveBeenCalledTimes(1)
expect(String(streamSocket.write.mock.calls[0]?.[0])).toContain('"data":"background"')
streamSocket.write.mockClear()
await daemon.routeRequest('client-1', {
id: 'req-2',
type: 'write',
payload: { sessionId: 'test-session', data: 'x' }
})
expect(subprocess!.write).toHaveBeenCalledWith('x')
subprocess!._simulateData('echo')
expect(streamSocket.write).toHaveBeenCalledTimes(1)
expect(String(streamSocket.write.mock.calls[0]?.[0])).toContain('"data":"echo"')
vi.advanceTimersByTime(8)
expect(streamSocket.write).toHaveBeenCalledTimes(1)
} finally {
vi.useRealTimers()
}
})
})
describe('authentication', () => {
+22 -1
View File
@@ -1,5 +1,6 @@
import { createServer, type Server, type Socket } from 'net'
import { randomUUID } from 'crypto'
import { performance } from 'perf_hooks'
import { writeFileSync, chmodSync, unlinkSync } from 'fs'
import { encodeNdjson, createNdjsonParser } from './ndjson'
import { TerminalHost } from './terminal-host'
@@ -42,6 +43,14 @@ export class DaemonServer {
private clients = new Map<string, ConnectedClient>()
private streamDataBatcher = new DaemonStreamDataBatcher((clientId) => this.clients.get(clientId))
private lastInputAtBySessionId = new Map<string, number>()
// Why: main-process PTY IPC has the same recent-input bypass, but daemon
// output reaches main only after this stream layer. Keeping the window here
// removes the daemon's fixed batch delay from keystroke echo/redraws while
// preserving batching for background and large output.
private static readonly INTERACTIVE_OUTPUT_WINDOW_MS = 100
private static readonly INTERACTIVE_OUTPUT_MAX_CHARS = 1024
constructor(opts: DaemonServerOptions) {
this.socketPath = opts.socketPath
@@ -209,12 +218,21 @@ export class DaemonServer {
shellReadySupported: p.shellReadySupported,
streamClient: {
onData: (data) => {
this.streamDataBatcher.enqueue(clientId, p.sessionId, data)
const lastInputAt = this.lastInputAtBySessionId.get(p.sessionId)
const isInteractiveOutput =
data.length <= DaemonServer.INTERACTIVE_OUTPUT_MAX_CHARS &&
lastInputAt !== undefined &&
performance.now() - lastInputAt <= DaemonServer.INTERACTIVE_OUTPUT_WINDOW_MS
this.streamDataBatcher.enqueue(clientId, p.sessionId, data, {
flushImmediately: isInteractiveOutput,
flushMaxChars: DaemonServer.INTERACTIVE_OUTPUT_MAX_CHARS
})
},
onExit: (code) => {
// Why: exit tears down renderer handlers; flush final output first
// so the last few milliseconds of PTY data are not stranded.
this.streamDataBatcher.flush(clientId)
this.lastInputAtBySessionId.delete(p.sessionId)
if (client?.streamSocket) {
client.streamSocket.write(
encodeNdjson({
@@ -238,8 +256,10 @@ export class DaemonServer {
case 'write':
try {
this.lastInputAtBySessionId.set(request.payload.sessionId, performance.now())
this.host.write(request.payload.sessionId, request.payload.data)
} catch (err) {
this.lastInputAtBySessionId.delete(request.payload.sessionId)
if (err instanceof SessionNotFoundError) {
this.sendExitEvent(client, request.payload.sessionId, -1)
}
@@ -259,6 +279,7 @@ export class DaemonServer {
return {}
case 'kill':
this.lastInputAtBySessionId.delete(request.payload.sessionId)
this.host.kill(request.payload.sessionId)
return {}
@@ -0,0 +1,74 @@
import { describe, expect, it, vi } from 'vitest'
import type { Socket } from 'net'
import { DaemonStreamDataBatcher } from './daemon-stream-data-batcher'
function createBatcher() {
const streamSocket = {
destroyed: false,
write: vi.fn()
} as unknown as Socket & { write: ReturnType<typeof vi.fn> }
const batcher = new DaemonStreamDataBatcher(() => ({ streamSocket }))
return { batcher, streamSocket }
}
describe('DaemonStreamDataBatcher', () => {
it('coalesces background output before writing daemon stream events', () => {
vi.useFakeTimers()
try {
const { batcher, streamSocket } = createBatcher()
batcher.enqueue('client-1', 'session-1', 'a')
batcher.enqueue('client-1', 'session-1', 'b')
expect(streamSocket.write).not.toHaveBeenCalled()
vi.advanceTimersByTime(7)
expect(streamSocket.write).not.toHaveBeenCalled()
vi.advanceTimersByTime(1)
expect(streamSocket.write).toHaveBeenCalledTimes(1)
expect(String(streamSocket.write.mock.calls[0]?.[0])).toContain('"data":"ab"')
} finally {
vi.useRealTimers()
}
})
it('flushes small interactive output immediately', () => {
vi.useFakeTimers()
try {
const { batcher, streamSocket } = createBatcher()
batcher.enqueue('client-1', 'session-1', '\x1b[20;2Hredraw', {
flushImmediately: true,
flushMaxChars: 1024
})
expect(streamSocket.write).toHaveBeenCalledTimes(1)
expect(String(streamSocket.write.mock.calls[0]?.[0])).toContain('\\u001b[20;2Hredraw')
vi.advanceTimersByTime(8)
expect(streamSocket.write).toHaveBeenCalledTimes(1)
} finally {
vi.useRealTimers()
}
})
it('keeps large pending output batched even when an interactive redraw follows', () => {
vi.useFakeTimers()
try {
const { batcher, streamSocket } = createBatcher()
const pending = 'x'.repeat(1020)
batcher.enqueue('client-1', 'session-1', pending)
batcher.enqueue('client-1', 'session-1', 'redraw', {
flushImmediately: true,
flushMaxChars: 1024
})
expect(streamSocket.write).not.toHaveBeenCalled()
vi.advanceTimersByTime(8)
expect(streamSocket.write).toHaveBeenCalledTimes(1)
expect(String(streamSocket.write.mock.calls[0]?.[0])).toContain(`${pending}redraw`)
} finally {
vi.useRealTimers()
}
})
})
+16 -2
View File
@@ -8,12 +8,18 @@ type StreamDataClient = {
type PendingStreamDataBatch = {
timer: ReturnType<typeof setTimeout> | null
queue: { sessionId: string; data: string }[]
queuedChars: number
}
// Why: match main-process PTY IPC batching to avoid adding latency while
// removing daemon socket writes and JSON framing during bursty output.
const STREAM_DATA_BATCH_INTERVAL_MS = 8
type EnqueueOptions = {
flushImmediately?: boolean
flushMaxChars?: number
}
export class DaemonStreamDataBatcher {
private pendingByClient = new Map<string, PendingStreamDataBatch>()
private getClient: (clientId: string) => StreamDataClient | undefined
@@ -22,7 +28,7 @@ export class DaemonStreamDataBatcher {
this.getClient = getClient
}
enqueue(clientId: string, sessionId: string, data: string): void {
enqueue(clientId: string, sessionId: string, data: string, options: EnqueueOptions = {}): void {
const client = this.getClient(clientId)
if (!client?.streamSocket || client.streamSocket.destroyed) {
return
@@ -30,7 +36,7 @@ export class DaemonStreamDataBatcher {
let batch = this.pendingByClient.get(clientId)
if (!batch) {
batch = { timer: null, queue: [] }
batch = { timer: null, queue: [], queuedChars: 0 }
this.pendingByClient.set(clientId, batch)
}
@@ -40,7 +46,15 @@ export class DaemonStreamDataBatcher {
} else {
batch.queue.push({ sessionId, data })
}
batch.queuedChars += data.length
if (
options.flushImmediately === true &&
batch.queuedChars <= (options.flushMaxChars ?? Number.POSITIVE_INFINITY)
) {
this.flush(clientId)
return
}
if (!batch.timer) {
batch.timer = setTimeout(() => this.flush(clientId), STREAM_DATA_BATCH_INTERVAL_MS)
}