diff --git a/src/main/agent-hooks/server.test.ts b/src/main/agent-hooks/server.test.ts index c8baaa6e6..f9c0b4627 100644 --- a/src/main/agent-hooks/server.test.ts +++ b/src/main/agent-hooks/server.test.ts @@ -31,6 +31,7 @@ import { type HookListenerState } from '../../shared/agent-hook-listener' import { makePaneKey } from '../../shared/stable-pane-id' +import { createShedSubagentsField } from '../../shared/agent-hook-relay' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), @@ -187,6 +188,51 @@ describe('AgentHookServer listener replay', () => { expect(server.getStatusSnapshot()[0]?.subagents).toEqual([child('new-child')]) }) + it('restores a subagent roster the relay shed to fit the frame', () => { + const server = new AgentHookServer() + const roster = [ + { id: 'reviewer-1', agentType: 'reviewer', state: 'working' as const, startedAt: 1 } + ] + server.ingestRemote( + { + paneKey: PANE, + payload: { state: 'working', prompt: 'review', agentType: 'claude', subagents: roster } + }, + 'conn-1' + ) + // The relay dropped the roster to fit an oversized frame and said so on the wire. + server.ingestRemote( + { + paneKey: PANE, + shedFields: ['lastAssistantMessage', createShedSubagentsField(roster)], + payload: { state: 'done', prompt: 'review', agentType: 'claude' } + }, + 'conn-1' + ) + expect(server.getStatusSnapshot()[0]).toMatchObject({ state: 'done', subagents: roster }) + }) + + it('lets an unmarked absent roster clear, so a finished team still retires', () => { + const server = new AgentHookServer() + server.ingestRemote( + { + paneKey: PANE, + payload: { + state: 'working', + prompt: 'review', + agentType: 'claude', + subagents: [{ id: 'reviewer-1', agentType: 'reviewer', state: 'working', startedAt: 1 }] + } + }, + 'conn-1' + ) + server.ingestRemote( + { paneKey: PANE, payload: { state: 'done', prompt: 'review', agentType: 'claude' } }, + 'conn-1' + ) + expect(server.getStatusSnapshot()[0]?.subagents).toBeUndefined() + }) + it('retains root Codex identity when relay child events omit it', () => { const server = new AgentHookServer() const providerSession = { key: 'session_id' as const, id: 'root-session' } diff --git a/src/main/agent-hooks/server.ts b/src/main/agent-hooks/server.ts index 8d5e57943..c8b0cb2f3 100644 --- a/src/main/agent-hooks/server.ts +++ b/src/main/agent-hooks/server.ts @@ -41,7 +41,7 @@ import { claudeRosterHasWorkingSubagent, claudeRosterToSnapshots } from '../../shared/claude-subagent-roster' -import type { AgentHookSource } from '../../shared/agent-hook-relay' +import { restoreShedStatusFields, type AgentHookSource } from '../../shared/agent-hook-relay' import { CLAUDE_STATUSLINE_PATHNAME, parseClaudeStatusLineBody, @@ -1718,6 +1718,8 @@ export class AgentHookServer { providerSession?: unknown providerSessionOnly?: unknown isReplay?: boolean + /** Payload fields the relay dropped to fit an oversized frame; validated below. */ + shedFields?: unknown payload: unknown }, connectionId: string @@ -1796,10 +1798,16 @@ export class AgentHookServer { : undefined const providerSession = normalizeAgentProviderSession(envelope.providerSession) ?? undefined // Why: relay crosses a trust boundary — re-run the canonical normalizer to enforce caps/invariants (returns null on malformed). - const normalizedPayload = normalizeAgentStatusPayload(envelope.payload) - if (!normalizedPayload) { + const validatedPayload = normalizeAgentStatusPayload(envelope.payload) + if (!validatedPayload) { return } + // Why: restore a shed roster only when its digest and turn identity still match the cache. + const normalizedPayload = restoreShedStatusFields( + validatedPayload, + envelope.shedFields, + this.state.lastStatusByPaneKey.get(paneKey)?.payload + ) if ( envelope.providerSessionOnly === true && !isValidPiProviderSessionOnly(providerSession, normalizedPayload.agentType) diff --git a/src/main/ipc/ssh.test.ts b/src/main/ipc/ssh.test.ts index 58b7b4463..09b741076 100644 --- a/src/main/ipc/ssh.test.ts +++ b/src/main/ipc/ssh.test.ts @@ -246,6 +246,7 @@ import { RelayVersionMismatchError } from '../ssh/ssh-relay-version-mismatch-err import { SSH_RELAY_CONFIGURE_GRACE_TIME_METHOD, type SshConnectionState, + type SshConnectionStatus, type SshTarget } from '../../shared/ssh-types' import { PTY_CONSUMER_SESSION_PROTOCOL_VERSION } from '../../shared/pty-consumer-session' @@ -1062,6 +1063,152 @@ describe('SSH IPC handlers', () => { } }) + describe('relay loss while the SSH transport is down', () => { + const relayLostTarget: SshTarget = { + id: 'ssh-1', + label: 'Server', + host: 'example.com', + port: 22, + username: 'deploy' + } + const transportState = (status: SshConnectionStatus): SshConnectionState => ({ + targetId: 'ssh-1', + status, + error: null, + reconnectAttempt: 0 + }) + const setTransportStatus = (status: SshConnectionStatus): void => { + mockConnectionManager.getState.mockReturnValue(transportState(status)) + } + const maxRelayDelayMs = relayReconnectDelaysMs.at(-1)! + const connectWithLiveTransport = async (): Promise => { + mockSshStore.getTarget.mockReturnValue(relayLostTarget) + mockConnectionManager.connect.mockResolvedValue({}) + mockConnectionManager.getConnection.mockReturnValue({}) + setTransportStatus('connected') + await handlers.get('ssh:connect')!(null, { targetId: 'ssh-1' }) + mockDeployAndLaunchRelay.mockClear() + } + + it('does not consume attempts or publish the manual-reconnect banner', async () => { + vi.useFakeTimers() + vi.setSystemTime(0) + try { + await connectWithLiveTransport() + setTransportStatus('reconnecting') + getLatestRelayDisposeCallback()('connection_lost') + + // Well past the whole 6-step ladder: a redeploy cannot ride a dead transport, so nothing is spent. + const fullLadderMs = relayReconnectDelaysMs.reduce((sum, delay) => sum + delay, 0) + await vi.advanceTimersByTimeAsync(fullLadderMs + relayLostStabilizedMs) + + expect(mockDeployAndLaunchRelay).not.toHaveBeenCalled() + expect(handlers.get('ssh:getState')!(null, { targetId: 'ssh-1' })).toEqual({ + targetId: 'ssh-1', + status: 'reconnecting', + error: 'Relay channel lost. Reconnecting...', + reconnectAttempt: 0, + providerEpoch: expect.any(String), + connectionGeneration: 2 + }) + + setTransportStatus('connected') + await vi.advanceTimersByTimeAsync(maxRelayDelayMs) + expect(mockDeployAndLaunchRelay).toHaveBeenCalledTimes(1) + expect( + (handlers.get('ssh:getState')!(null, { targetId: 'ssh-1' }) as SshConnectionState).status + ).toBe('connected') + } finally { + vi.useRealTimers() + } + }) + + it('stops retrying once the transport reaches a terminal state', async () => { + vi.useFakeTimers() + vi.setSystemTime(0) + try { + await connectWithLiveTransport() + setTransportStatus('reconnecting') + getLatestRelayDisposeCallback()('connection_lost') + await vi.advanceTimersByTimeAsync(maxRelayDelayMs) + + setTransportStatus('reconnection-failed') + await vi.advanceTimersByTimeAsync(maxRelayDelayMs) + + // The wait loop is gone: only onStateChange's redeploy may revive the relay after this. + setTransportStatus('connected') + await vi.advanceTimersByTimeAsync(maxRelayDelayMs * 4) + expect(mockDeployAndLaunchRelay).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + + it('resets the relay budget when the connection disappears before retry', async () => { + vi.useFakeTimers() + vi.setSystemTime(0) + try { + await connectWithLiveTransport() + getLatestRelayDisposeCallback()('connection_lost') + + mockConnectionManager.getConnection.mockReturnValue(undefined) + await vi.advanceTimersByTimeAsync(relayReconnectDelaysMs[0]) + + mockConnectionManager.getConnection.mockReturnValue({}) + getLatestRelayDisposeCallback()('connection_lost') + expect(handlers.get('ssh:getState')!(null, { targetId: 'ssh-1' })).toEqual( + expect.objectContaining({ reconnectAttempt: 1 }) + ) + } finally { + vi.useRealTimers() + } + }) + + it('still reaches the manual-reconnect banner when the transport is healthy', async () => { + vi.useFakeTimers() + vi.setSystemTime(0) + try { + await connectWithLiveTransport() + mockDeployAndLaunchRelay.mockRejectedValue(new Error('relay refused')) + getLatestRelayDisposeCallback()('connection_lost') + for (const delayMs of relayReconnectDelaysMs) { + await vi.advanceTimersByTimeAsync(delayMs) + } + + expect( + (handlers.get('ssh:getState')!(null, { targetId: 'ssh-1' }) as SshConnectionState).error + ).toBe('Relay channel kept dropping. Click Reconnect on the SSH target before retrying.') + } finally { + vi.useRealTimers() + } + }) + + it('restores the full relay budget once the transport reconnects', async () => { + vi.useFakeTimers() + vi.setSystemTime(0) + try { + await connectWithLiveTransport() + mockDeployAndLaunchRelay.mockRejectedValue(new Error('relay refused')) + getLatestRelayDisposeCallback()('connection_lost') + await vi.advanceTimersByTimeAsync(relayReconnectDelaysMs[0]) + + const callbacks = mockConnectionManager.callbacksRef.current as { + onStateChange: (targetId: string, state: SshConnectionState) => void + } + callbacks.onStateChange('ssh-1', transportState('reconnecting')) + callbacks.onStateChange('ssh-1', transportState('connected')) + await vi.advanceTimersByTimeAsync(0) + + // Budget reset: the next loss waits the base delay again instead of the third ladder step. + mockDeployAndLaunchRelay.mockClear() + await vi.advanceTimersByTimeAsync(relayReconnectDelaysMs[0]) + expect(mockDeployAndLaunchRelay).toHaveBeenCalledTimes(1) + } finally { + vi.useRealTimers() + } + }) + }) + it('reuses a fast relay reconnect after the post-ready stabilization window', async () => { vi.useFakeTimers() vi.setSystemTime(0) diff --git a/src/main/ipc/ssh.ts b/src/main/ipc/ssh.ts index 7e1a54026..0227b84f3 100644 --- a/src/main/ipc/ssh.ts +++ b/src/main/ipc/ssh.ts @@ -295,6 +295,13 @@ const RELAY_LOST_BASE_DELAY_MS = 500 const RELAY_LOST_MAX_DELAY_MS = 15_000 // Why: a reconnect whose mux dies within this window was a flap, not a recovery — don't reset the attempt counter. 5s covers provider re-registration + PTY reattach. const RELAY_LOST_STABILIZED_MS = 5_000 +// Why: transport states the SSH ladder never leaves on its own — waiting for a relay redeploy past one of these is an unbounded loop. +const TRANSPORT_TERMINAL_STATUSES = new Set([ + 'disconnected', + 'auth-failed', + 'reconnection-failed', + 'error' +]) function clearRelayLostBackoff(targetId: string): void { const state = relayLostBackoff.get(targetId) @@ -615,6 +622,8 @@ function createSshConnectionCallbacks(): SshConnectionCallbacks { relayStateOverrides.has(targetId) if (shouldReconnectRelay) { + // Why: this branch redeploys the relay itself over a fresh transport, so any pending relay-lost retry is stale — dropping it also gives the new transport generation a full attempt budget. + clearRelayLostBackoff(targetId) // Why: SSH connects before the relay providers rebuild; keep renderer actions gated until SshRelaySession reaches ready again. publishRelayOverride( getCurrentMainWindow, @@ -714,7 +723,13 @@ function configureRelaySessionCallbacks(session: SshRelaySession): void { return } rotateSshProviderAuthority(tid) - if (state.attempts >= RELAY_LOST_MAX_ATTEMPTS) { + + // Why: re-deploying the relay rides the SSH transport, so while the transport is itself down no attempt + // can succeed. Waiting at the max delay without consuming the budget keeps a flapping host off the + // manual-reconnect banner, which would tell the user to act on a link that is still auto-recovering. + const transportStatus = connectionManager?.getState(tid)?.status + const transportConnected = transportStatus === 'connected' + if (transportConnected && state.attempts >= RELAY_LOST_MAX_ATTEMPTS) { console.warn( `[ssh] Relay channel for ${tid} kept dying across ${state.attempts} attempts; giving up. User must reconnect manually.` ) @@ -729,6 +744,53 @@ function configureRelaySessionCallbacks(session: SshRelaySession): void { ) return } + + const scheduleRelayRedeploy = (delay: number, attemptCharged: boolean): void => { + state.reconnectTimer = setTimeout(() => { + state.reconnectTimer = null + relayLostBackoff.set(tid, state) + const liveConn = connectionManager?.getConnection(tid) + if (!liveConn || !activeSessions.has(tid)) { + clearRelayLostBackoff(tid) + return + } + const status = connectionManager?.getState(tid)?.status + if (status === 'connected') { + if (!attemptCharged) { + // Why: waiting is free, but the deploy it defers is real — charge it here so a transport that + // flaps back to 'connected' can't redeploy forever on an uncharged budget. + state.attempts += 1 + } + void s.reconnect(liveConn, relayGracePeriodForTarget(t)) + return + } + if (status === undefined || TRANSPORT_TERMINAL_STATUSES.has(status)) { + // Why: the transport gave up for good; its own state is what the user acts on, so stop waiting for a redeploy that can never run. + clearRelayLostBackoff(tid) + return + } + // Why: still mid-transition — re-arm at the max delay without consuming an attempt. It ends once + // the transport settles: 'connected' redeploys, a terminal status or a dropped session clears above. + scheduleRelayRedeploy(RELAY_LOST_MAX_DELAY_MS, false) + }, delay) + relayLostBackoff.set(tid, state) + } + + if (!transportConnected) { + publishRelayOverride( + getCurrentMainWindow, + tid, + 'reconnecting', + 'Relay channel lost. Reconnecting...', + state.attempts + ) + scheduleRelayRedeploy(RELAY_LOST_MAX_DELAY_MS, false) + console.warn( + `[ssh] Relay channel for ${tid} lost while the SSH transport is ${transportStatus ?? 'unknown'}; waiting ${RELAY_LOST_MAX_DELAY_MS}ms without consuming an attempt` + ) + return + } + const delay = Math.min(RELAY_LOST_BASE_DELAY_MS * 2 ** state.attempts, RELAY_LOST_MAX_DELAY_MS) state.attempts += 1 publishRelayOverride( @@ -738,16 +800,7 @@ function configureRelaySessionCallbacks(session: SshRelaySession): void { 'Relay channel lost. Reconnecting...', state.attempts ) - state.reconnectTimer = setTimeout(() => { - state.reconnectTimer = null - relayLostBackoff.set(tid, state) - const liveConn = connectionManager?.getConnection(tid) - if (!liveConn || !activeSessions.has(tid)) { - return - } - void s.reconnect(liveConn, relayGracePeriodForTarget(t)) - }, delay) - relayLostBackoff.set(tid, state) + scheduleRelayRedeploy(delay, true) console.warn( `[ssh] Relay channel for ${tid} lost; reconnect attempt ${state.attempts}/${RELAY_LOST_MAX_ATTEMPTS} in ${delay}ms` ) diff --git a/src/main/ssh/ssh-connection.test.ts b/src/main/ssh/ssh-connection.test.ts index a3bcadf66..db5287d2a 100644 --- a/src/main/ssh/ssh-connection.test.ts +++ b/src/main/ssh/ssh-connection.test.ts @@ -12,6 +12,7 @@ let connectErrorMessage = '' let connectErrorCode = '' let destroyErrorMessage = '' let connectSequence: ('ready' | Error)[] = [] +let connectAttempts = 0 let execBehavior: 'callback' | 'pending' = 'callback' let pendingExecCallback: ((err: Error | undefined, channel: unknown) => void) | null = null let sftpBehavior: 'callback' | 'pending' = 'callback' @@ -34,6 +35,27 @@ function emitSshEvent(event: string, ...args: unknown[]): void { } } +function nextSshClientCreation(): Promise { + return new Promise((resolve) => { + notifyClientCreated = resolve + }) +} + +async function connectWithFakeTimers(conn: SshConnection): Promise { + const clientCreated = nextSshClientCreation() + const connected = conn.connect() + await clientCreated + await vi.advanceTimersByTimeAsync(1) + await connected +} + +async function advanceToNextSshClient(delayMs: number): Promise { + const clientCreated = nextSshClientCreation() + await vi.advanceTimersByTimeAsync(delayMs) + await clientCreated + await vi.advanceTimersByTimeAsync(1) +} + vi.mock('ssh2', () => { class MockBaseAgent {} class MockSshClient { @@ -62,6 +84,7 @@ vi.mock('ssh2', () => { } } connect(config?: unknown) { + connectAttempts += 1 this.lastConnectConfig = config const hostVerifier = (config as { hostVerifier?: (key: Buffer) => boolean } | undefined) ?.hostVerifier @@ -170,7 +193,8 @@ import { writeFileViaSystemSsh } from './ssh-system-fallback' import { getRemoteHostPlatform } from './ssh-remote-platform' -import type { SshTarget } from '../../shared/ssh-types' +import { CONNECT_TIMEOUT_MS, RECONNECT_BACKOFF_MS } from './ssh-connection-utils' +import { MIN_SSH_RELAY_GRACE_PERIOD_SECONDS, type SshTarget } from '../../shared/ssh-types' import { createOpenSshPrivateKeyFixture, createOpenSshPublicKeyFixture @@ -281,6 +305,7 @@ describe('SshConnection', () => { connectErrorCode = '' destroyErrorMessage = '' connectSequence = [] + connectAttempts = 0 execBehavior = 'callback' pendingExecCallback = null sftpBehavior = 'callback' @@ -420,6 +445,205 @@ describe('SshConnection', () => { expect(conn.getState().status).toBe('connected') }) + it('escalates the backoff across repeated post-handshake drops', async () => { + vi.useFakeTimers() + try { + const conn = new SshConnection(createTarget(), createCallbacks()) + await connectWithFakeTimers(conn) + expect(clientInstances).toHaveLength(1) + + emitSshEvent('close') + await vi.advanceTimersByTimeAsync(999) + expect(clientInstances).toHaveLength(1) + await advanceToNextSshClient(1) + expect(clientInstances).toHaveLength(2) + + // Why: a single published counter pinned every post-handshake drop at the 1000ms head step. + emitSshEvent('close') + await vi.advanceTimersByTimeAsync(1999) + expect(clientInstances).toHaveLength(2) + await advanceToNextSshClient(1) + expect(clientInstances).toHaveLength(3) + } finally { + vi.useRealTimers() + } + }) + + it('publishes reconnectAttempt=0 on the reconnected state and the escalating step while reconnecting', async () => { + vi.useFakeTimers() + try { + const published: { status: string; reconnectAttempt: number }[] = [] + const conn = new SshConnection( + createTarget(), + createCallbacks({ + onStateChange: vi.fn((_id, state) => + published.push({ status: state.status, reconnectAttempt: state.reconnectAttempt }) + ) + }) + ) + await connectWithFakeTimers(conn) + + for (let drop = 0; drop < 3; drop++) { + emitSshEvent('close') + await advanceToNextSshClient(30_000) + } + + expect( + published.filter((e) => e.status === 'reconnecting').map((e) => e.reconnectAttempt) + ).toEqual([0, 1, 2]) + // src/main/ipc/ssh.ts gates the relay redeploy on reconnectAttempt === 0 at 'connected'. + expect( + published.filter((e) => e.status === 'connected').map((e) => e.reconnectAttempt) + ).toEqual([0, 0, 0, 0]) + } finally { + vi.useRealTimers() + } + }) + + it('restarts the ladder at the head when an explicit reconnect fails', async () => { + // Accepted delta: reset() puts the ladder at the head and the explicit attempt consumes no + // step, so the first failure publishes 0/1000ms where the single-counter version published 1/2000ms. + vi.useFakeTimers() + try { + const published: { status: string; reconnectAttempt: number }[] = [] + const conn = new SshConnection( + createTarget(), + createCallbacks({ + onStateChange: vi.fn((_id, state) => + published.push({ status: state.status, reconnectAttempt: state.reconnectAttempt }) + ) + }) + ) + await connectWithFakeTimers(conn) + + connectBehavior = 'error' + connectErrorMessage = 'connect ETIMEDOUT 10.0.0.5:22' + connectErrorCode = 'ETIMEDOUT' + published.length = 0 + const clientCreated = nextSshClientCreation() + const reconnected = conn.reconnect() + await clientCreated + await vi.advanceTimersByTimeAsync(1) + await reconnected + + // Shipped published [0, 1] here; the ladder's reset() keeps the retry at the head instead. + expect( + published.filter((e) => e.status === 'reconnecting').map((e) => e.reconnectAttempt) + ).toEqual([0, 0]) + } finally { + vi.useRealTimers() + } + }) + + it('reaches reconnection-failed after 9 consecutive handshake failures', async () => { + vi.useFakeTimers() + try { + const statuses: string[] = [] + const conn = new SshConnection( + createTarget(), + createCallbacks({ + onStateChange: vi.fn((_id, state) => statuses.push(state.status)) + }) + ) + await connectWithFakeTimers(conn) + + connectBehavior = 'error' + connectErrorMessage = 'connect ETIMEDOUT 10.0.0.5:22' + connectErrorCode = 'ETIMEDOUT' + emitSshEvent('close') + for (const delayMs of RECONNECT_BACKOFF_MS) { + await advanceToNextSshClient(delayMs) + } + + expect(statuses).toContain('reconnection-failed') + // Pin the budget itself: the initial success plus exactly RECONNECT_BACKOFF_MS.length retries. + // Counting a failure twice, or giving up early, would strand a user on a flaky link. + expect(connectAttempts).toBe(1 + RECONNECT_BACKOFF_MS.length) + } finally { + vi.useRealTimers() + } + }) + + it('retries a saturated flap streak while the remote relay is still in grace', async () => { + vi.useFakeTimers() + try { + const conn = new SshConnection(createTarget(), createCallbacks()) + await connectWithFakeTimers(conn) + + // Saturate the delay ladder on flaps alone; 45s reconnects each drop while staying under + // STABLE_CONNECTION_MS, so the ladder never resets to the head. + for (let drop = 0; drop < 12; drop++) { + emitSshEvent('close') + await advanceToNextSshClient(45_000) + } + expect(conn.getState().status).toBe('connected') + + const before = clientInstances.length + emitSshEvent('close') + // The retry plus a worst-case handshake must land inside the shortest configurable relay grace, + // or the remote daemon shuts down and takes every PTY on that host with it. + await advanceToNextSshClient( + MIN_SSH_RELAY_GRACE_PERIOD_SECONDS * 1000 - CONNECT_TIMEOUT_MS - 1 + ) + expect(clientInstances.length).toBeGreaterThan(before) + } finally { + vi.useRealTimers() + } + }) + + it('logs the delay ladder position separately from the failure streak', async () => { + vi.useFakeTimers() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + const conn = new SshConnection(createTarget(), createCallbacks()) + await connectWithFakeTimers(conn) + + for (let drop = 0; drop < 12; drop++) { + emitSshEvent('close') + await advanceToNextSshClient(45_000) + } + + const lastReconnectLog = warn.mock.calls + .map((call) => String(call[0])) + .findLast((line) => line.includes('Reconnecting to')) + // A saturated flap ladder must not read like the connection is one step from giving up. + expect(lastReconnectLog).toContain('delay step 9/9') + expect(lastReconnectLog).toContain('failed handshakes 0/9') + } finally { + warn.mockRestore() + vi.useRealTimers() + } + }) + + it('keeps retrying when a flap streak is followed by one handshake failure', async () => { + vi.useFakeTimers() + try { + const statuses: string[] = [] + const conn = new SshConnection( + createTarget(), + createCallbacks({ + onStateChange: vi.fn((_id, state) => statuses.push(state.status)) + }) + ) + await connectWithFakeTimers(conn) + + // 12 flaps saturate the delay ladder without ever touching the failure streak. + for (let drop = 0; drop < 12; drop++) { + emitSshEvent('close') + await advanceToNextSshClient(30_000) + } + connectSequence = [new Error('connect ETIMEDOUT 10.0.0.5:22')] + emitSshEvent('close') + await advanceToNextSshClient(30_000) + await advanceToNextSshClient(30_000) + + expect(statuses).not.toContain('reconnection-failed') + expect(conn.getState().status).toBe('connected') + } finally { + vi.useRealTimers() + } + }) + it('transitions through connecting → connected states', async () => { const states: string[] = [] const callbacks = createCallbacks({ diff --git a/src/main/ssh/ssh-connection.ts b/src/main/ssh/ssh-connection.ts index 37d661587..f183a7049 100644 --- a/src/main/ssh/ssh-connection.ts +++ b/src/main/ssh/ssh-connection.ts @@ -40,6 +40,7 @@ import { type SshExecOptions, type SshConnectionCallbacks } from './ssh-connection-utils' +import { SshReconnectLadder } from './ssh-reconnect-ladder' import { getPassphrasePrivateKeyPath } from './ssh-private-key-authentication' import { requiresSystemSshForSecurityKey, @@ -126,6 +127,7 @@ export class SshConnection { private callbacks: SshConnectionCallbacks private target: SshTarget private reconnectTimer: ReturnType | null = null + private readonly reconnectLadder = new SshReconnectLadder() private disposed = false private cachedPassphrase: string | null = null private cachedPassword: string | null = null @@ -601,6 +603,8 @@ export class SshConnection { for (let attempt = 0; attempt < INITIAL_RETRY_ATTEMPTS; attempt++) { try { await this.attemptConnect() + this.reconnectLadder.reset() + this.reconnectLadder.markConnected(Date.now()) return } catch (err) { lastError = err instanceof Error ? err : new Error(String(err)) @@ -852,8 +856,9 @@ export class SshConnection { // Why: OS sleep/wake can leave ssh2 thinking a dead TCP socket is still connected; tear down and reconnect so the relay can reattach remote PTYs. this.closeTransportsForReconnect() this.state.reconnectAttempt = 0 + this.reconnectLadder.reset() this.setState('reconnecting') - await this.runReconnectAttempt(0) + await this.runReconnectAttempt() } private async doSystemSshProbe(connectGeneration: number): Promise { @@ -1239,26 +1244,32 @@ export class SshConnection { if (this.disposed || this.reconnectTimer) { return } - const attempt = this.state.reconnectAttempt - if (attempt >= RECONNECT_BACKOFF_MS.length) { + const decision = this.reconnectLadder.next(Date.now()) + if (decision.kind === 'give-up') { this.setState('reconnection-failed', 'Max reconnection attempts reached') return } + this.state.reconnectAttempt = decision.attemptIndex this.setState('reconnecting') + console.warn( + `[ssh] Reconnecting to ${this.target.label} in ${decision.delayMs}ms (delay step ${decision.attemptIndex + 1}/${RECONNECT_BACKOFF_MS.length}, failed handshakes ${this.reconnectLadder.failedAttemptStreak}/${RECONNECT_BACKOFF_MS.length})` + ) this.reconnectTimer = setTimeout(async () => { this.reconnectTimer = null if (this.disposed) { return } - await this.runReconnectAttempt(attempt) - }, RECONNECT_BACKOFF_MS[attempt]) + await this.runReconnectAttempt() + }, decision.delayMs) } - private async runReconnectAttempt(attempt: number): Promise { + private async runReconnectAttempt(): Promise { try { // Why: reset before connecting so the 'connected' broadcast carries reconnectAttempt=0, which ssh.ts uses to trigger relay re-establishment. this.state.reconnectAttempt = 0 await this.attemptConnect() + // Why: attemptConnect resolves only after a real handshake on either transport; the system-ssh probe's 'connected' must not clear the failure streak. + this.reconnectLadder.markConnected(Date.now()) } catch (err) { if (this.disposed) { return @@ -1272,7 +1283,7 @@ export class SshConnection { this.setState('error', error.message) return } - this.state.reconnectAttempt = attempt + 1 + this.reconnectLadder.markAttemptFailed() this.scheduleReconnect() } } @@ -1383,6 +1394,7 @@ export class SshConnection { this.systemSshControlMasterDisabledForSession = false this.systemSshGssapiOnlyForSession = false this.useSystemSshTransport = false + this.reconnectLadder.reset() this.setState('disconnected') } diff --git a/src/main/ssh/ssh-reconnect-ladder.test.ts b/src/main/ssh/ssh-reconnect-ladder.test.ts new file mode 100644 index 000000000..c43d4e9e6 --- /dev/null +++ b/src/main/ssh/ssh-reconnect-ladder.test.ts @@ -0,0 +1,191 @@ +import { describe, expect, it } from 'vitest' +import { MIN_SSH_RELAY_GRACE_PERIOD_SECONDS } from '../../shared/ssh-types' +import { CONNECT_TIMEOUT_MS, RECONNECT_BACKOFF_MS } from './ssh-connection-utils' +import { + FLAP_DELAY_CAP_MS, + RELAY_REESTABLISH_BUDGET_MS, + SshReconnectLadder, + STABLE_CONNECTION_MS +} from './ssh-reconnect-ladder' + +describe('SshReconnectLadder', () => { + it('climbs the table across consecutive post-handshake drops', () => { + const ladder = new SshReconnectLadder() + + ladder.markConnected(0) + expect(ladder.next(50)).toEqual({ kind: 'retry', delayMs: 1000, attemptIndex: 0 }) + ladder.markConnected(60) + expect(ladder.next(110)).toEqual({ kind: 'retry', delayMs: 2000, attemptIndex: 1 }) + + // Table steps past FLAP_DELAY_CAP_MS are clamped so the retry still fits inside the relay grace floor. + const rest = [5000, 5000, 10000, 10000, 10000, 30000, 30000] + let now = 200 + rest.forEach((delayMs, index) => { + ladder.markConnected(now) + now += 50 + expect(ladder.next(now)).toEqual({ + kind: 'retry', + delayMs: Math.min(delayMs, FLAP_DELAY_CAP_MS), + attemptIndex: index + 2 + }) + }) + + // Saturates at the last step instead of going terminal. + for (let i = 0; i < 3; i++) { + ladder.markConnected(now) + now += 50 + expect(ladder.next(now)).toEqual({ + kind: 'retry', + delayMs: Math.min(30000, FLAP_DELAY_CAP_MS), + attemptIndex: 8 + }) + } + }) + + it('caps every flap delay so handshake and relay re-establishment beat grace', () => { + const ladder = new SshReconnectLadder() + let now = 0 + + for (let i = 0; i < RECONNECT_BACKOFF_MS.length + 4; i++) { + ladder.markConnected(now) + now += 50 + const decision = ladder.next(now) + expect(decision.kind).toBe('retry') + if (decision.kind === 'retry') { + expect(decision.delayMs + CONNECT_TIMEOUT_MS + RELAY_REESTABLISH_BUDGET_MS).toBeLessThan( + MIN_SSH_RELAY_GRACE_PERIOD_SECONDS * 1000 + ) + now += decision.delayMs + } + } + expect(FLAP_DELAY_CAP_MS).toBe(5_000) + }) + + it('keeps the uncapped table for a host whose handshakes fail', () => { + const ladder = new SshReconnectLadder() + const delays: number[] = [] + + for (let i = 0; i < RECONNECT_BACKOFF_MS.length - 1; i++) { + ladder.markAttemptFailed() + const decision = ladder.next(i * 1000) + if (decision.kind === 'retry') { + delays.push(decision.delayMs) + } + expect(ladder.failedAttemptStreak).toBe(i + 1) + } + + expect(delays).toEqual(RECONNECT_BACKOFF_MS.slice(0, -1)) + expect(delays.some((delayMs) => delayMs > FLAP_DELAY_CAP_MS)).toBe(true) + }) + + it('escalates a post-handshake drop identically to a handshake failure', () => { + const dropLadder = new SshReconnectLadder() + const failureLadder = new SshReconnectLadder() + const dropDelays: number[] = [] + const dropIndexes: number[] = [] + const failureIndexes: number[] = [] + + let now = 0 + for (let i = 0; i < RECONNECT_BACKOFF_MS.length; i++) { + dropLadder.markConnected(now) + now += 50 + const dropDecision = dropLadder.next(now) + const failureDecision = failureLadder.next(now) + expect(dropDecision.kind).toBe('retry') + expect(failureDecision.kind).toBe('retry') + if (dropDecision.kind === 'retry') { + dropDelays.push(dropDecision.delayMs) + dropIndexes.push(dropDecision.attemptIndex) + } + if (failureDecision.kind === 'retry') { + failureIndexes.push(failureDecision.attemptIndex) + } + failureLadder.markAttemptFailed() + now += 50 + } + + // Same ladder position; the flap path only clamps the wall-clock delay to the grace budget. + expect(dropIndexes).toEqual(failureIndexes) + expect(dropDelays).toEqual(RECONNECT_BACKOFF_MS.map((d) => Math.min(d, FLAP_DELAY_CAP_MS))) + }) + + it('never reaches give-up on a flap streak, even with a later handshake failure', () => { + const ladder = new SshReconnectLadder() + let now = 0 + for (let i = 0; i < 12; i++) { + ladder.markConnected(now) + now += 50 + const decision = ladder.next(now) + expect(decision.kind).toBe('retry') + if (decision.kind === 'retry') { + now += decision.delayMs + } + } + + ladder.markAttemptFailed() + + expect(ladder.next(now)).toEqual({ kind: 'retry', delayMs: 30000, attemptIndex: 8 }) + }) + + it('gives up only after RECONNECT_BACKOFF_MS.length consecutive failed attempts', () => { + const ladder = new SshReconnectLadder() + const decisions: string[] = [] + + for (let i = 0; i < RECONNECT_BACKOFF_MS.length; i++) { + ladder.markAttemptFailed() + decisions.push(ladder.next(i * 1000).kind) + } + + expect(decisions.slice(0, RECONNECT_BACKOFF_MS.length - 1)).toEqual( + Array(RECONNECT_BACKOFF_MS.length - 1).fill('retry') + ) + expect(decisions.at(-1)).toBe('give-up') + }) + + it('resets the delay ladder exactly once for a stable connection', () => { + const ladder = new SshReconnectLadder() + for (let i = 0; i < 5; i++) { + ladder.next(i) + } + + ladder.markConnected(0) + expect(ladder.next(STABLE_CONNECTION_MS)).toEqual({ + kind: 'retry', + delayMs: 1000, + attemptIndex: 0 + }) + // The consumed timestamp must not reset the ladder again later in the same outage. + expect(ladder.next(STABLE_CONNECTION_MS * 4)).toEqual({ + kind: 'retry', + delayMs: 2000, + attemptIndex: 1 + }) + }) + + it('does not let a dead host self-reset past the give-up bound', () => { + const ladder = new SshReconnectLadder() + ladder.markConnected(0) + + let now = 0 + let last = ladder.next(now) + for (let i = 0; i < RECONNECT_BACKOFF_MS.length; i++) { + ladder.markAttemptFailed() + now += STABLE_CONNECTION_MS * 2 + last = ladder.next(now) + } + + expect(last).toEqual({ kind: 'give-up' }) + }) + + it('returns to the head of the ladder after reset()', () => { + const ladder = new SshReconnectLadder() + for (let i = 0; i < RECONNECT_BACKOFF_MS.length; i++) { + ladder.markAttemptFailed() + ladder.next(i) + } + + ladder.reset() + + expect(ladder.next(0)).toEqual({ kind: 'retry', delayMs: 1000, attemptIndex: 0 }) + }) +}) diff --git a/src/main/ssh/ssh-reconnect-ladder.ts b/src/main/ssh/ssh-reconnect-ladder.ts new file mode 100644 index 000000000..bf03154be --- /dev/null +++ b/src/main/ssh/ssh-reconnect-ladder.ts @@ -0,0 +1,78 @@ +import { MIN_SSH_RELAY_GRACE_PERIOD_SECONDS } from '../../shared/ssh-types' +import { CONNECT_TIMEOUT_MS, RECONNECT_BACKOFF_MS } from './ssh-connection-utils' + +// A connection that held this long is treated as healthy, so the next drop restarts the delay ladder. +export const STABLE_CONNECTION_MS = 60_000 +// Existing-relay attach and one bounded PTY reattach attempt each allow 10s. +export const RELAY_REESTABLISH_BUDGET_MS = 20_000 + +/** + * Why: a flap leaves the remote relay in grace, and the shortest grace a target can configure is + * MIN_SSH_RELAY_GRACE_PERIOD_SECONDS. Retrying later than this cap would let even a full-length + * handshake plus relay/mux re-establishment finish after grace expires, so the relay would shut + * down and take every remote PTY with it. Raising the backoff past this bound changes nothing. + */ +export const FLAP_DELAY_CAP_MS = (() => { + const budgetMs = + MIN_SSH_RELAY_GRACE_PERIOD_SECONDS * 1000 - CONNECT_TIMEOUT_MS - RELAY_REESTABLISH_BUDGET_MS + const fitting = RECONNECT_BACKOFF_MS.filter((delayMs) => delayMs < budgetMs) + return fitting.length > 0 ? Math.max(...fitting) : RECONNECT_BACKOFF_MS[0] +})() + +export type SshReconnectDecision = + | { kind: 'retry'; delayMs: number; attemptIndex: number } + | { kind: 'give-up' } + +/** + * Why two counters: `delayIndex` advances on every scheduled retry (flap or handshake failure) so a + * host that keeps dropping after a successful handshake still backs off, while + * `consecutiveFailedAttempts` advances only on a failed connect attempt so 'reconnection-failed' + * stays reachable exactly after RECONNECT_BACKOFF_MS.length failed handshakes — never after flaps. + */ +export class SshReconnectLadder { + private delayIndex = 0 + private consecutiveFailedAttempts = 0 + private connectedAtMs: number | null = null + + next(nowMs: number): SshReconnectDecision { + const connectedAt = this.connectedAtMs + // Why: consume it — one reset per connection, never a rolling reset mid-outage (the table sums past the window). + this.connectedAtMs = null + if (connectedAt !== null && nowMs - connectedAt >= STABLE_CONNECTION_MS) { + this.delayIndex = 0 + } + if (this.consecutiveFailedAttempts >= RECONNECT_BACKOFF_MS.length) { + return { kind: 'give-up' } + } + const attemptIndex = Math.min(this.delayIndex, RECONNECT_BACKOFF_MS.length - 1) + this.delayIndex = attemptIndex + 1 + const tableDelayMs = RECONNECT_BACKOFF_MS[attemptIndex] + // Why: only a flap (no failed handshake) means the remote relay is alive and burning grace; a dead + // host keeps the full table because nothing over there is waiting for us. + const delayMs = + this.consecutiveFailedAttempts === 0 + ? Math.min(tableDelayMs, FLAP_DELAY_CAP_MS) + : tableDelayMs + return { kind: 'retry', delayMs, attemptIndex } + } + + get failedAttemptStreak(): number { + return this.consecutiveFailedAttempts + } + + markConnected(nowMs: number): void { + this.consecutiveFailedAttempts = 0 + this.connectedAtMs = nowMs + } + + markAttemptFailed(): void { + this.consecutiveFailedAttempts += 1 + this.connectedAtMs = null + } + + reset(): void { + this.delayIndex = 0 + this.consecutiveFailedAttempts = 0 + this.connectedAtMs = null + } +} diff --git a/src/main/ssh/ssh-relay-session.ts b/src/main/ssh/ssh-relay-session.ts index 5edce4306..a3be2082c 100644 --- a/src/main/ssh/ssh-relay-session.ts +++ b/src/main/ssh/ssh-relay-session.ts @@ -1138,6 +1138,7 @@ export class SshRelaySession { isReplay?: unknown providerSession?: unknown providerSessionOnly?: unknown + shedFields?: unknown payload?: unknown } if (typeof envelope.paneKey !== 'string') { @@ -1166,6 +1167,8 @@ export class SshRelaySession { isReplay: envelope.isReplay === true ? true : undefined, providerSession: envelope.providerSession, providerSessionOnly: envelope.providerSessionOnly === true ? true : undefined, + // Why: names the fields the relay dropped to fit the frame; ingestRemote restores them. + shedFields: envelope.shedFields, payload: envelope.payload }, this.targetId diff --git a/src/relay/agent-hook-envelope-publication.test.ts b/src/relay/agent-hook-envelope-publication.test.ts new file mode 100644 index 000000000..164c36f9c --- /dev/null +++ b/src/relay/agent-hook-envelope-publication.test.ts @@ -0,0 +1,642 @@ +import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' +import { RelayDispatcher, type RelayClientSinkOptions } from './dispatcher' +import { publishAgentHookEnvelope } from './agent-hook-envelope-publication' +import { + AGENT_HOOK_NOTIFICATION_METHOD, + createShedSubagentsField +} from '../shared/agent-hook-relay' +import type { AgentHookRelayEnvelope } from '../shared/agent-hook-relay' +import type { AgentSubagentSnapshot } from '../shared/agent-status-types' + +type BoundedClient = { + frames: Buffer[] + closes: number + options: RelayClientSinkOptions + write: (data: Buffer) => boolean + /** Mimics a socket whose kernel buffer is full: writes are accepted but never settle. */ + blocked: boolean + drain: () => void +} + +function makeBoundedClient(highWaterMark: number): BoundedClient { + const drainListeners = new Set<() => void>() + const client: BoundedClient = { + frames: [], + closes: 0, + blocked: false, + write: (data: Buffer) => { + client.frames.push(Buffer.from(data)) + return !client.blocked + }, + drain: () => { + for (const listener of Array.from(drainListeners)) { + drainListeners.delete(listener) + listener() + } + }, + options: { + writableHighWaterMark: () => highWaterMark, + writableLength: () => 0, + waitWriteDrain: (callback: () => void) => { + drainListeners.add(callback) + return () => drainListeners.delete(callback) + }, + close: () => { + client.closes++ + } + } + } + return client +} + +/** Fills the producer queue so the next publish is rejected for backpressure, not for frame size. */ +function saturateProducerQueue(dispatcher: RelayDispatcher, client: BoundedClient): void { + client.blocked = true + // Shrinking chunks close the headroom a rejected 8 KB frame leaves behind, so even a small + // hook envelope is refused. + for (const size of [8_000, 512, 16]) { + const data = 'x'.repeat(size) + let filled = false + for (let attempt = 0; attempt < 5_000 && !filled; attempt++) { + filled = !dispatcher.tryNotifyPtyData({ id: 'pty-1', data }) + } + if (!filled) { + throw new Error('producer queue never filled') + } + } +} + +function decodePayload(frame: Buffer): Record { + const length = frame.readUInt32BE(9) + return JSON.parse(frame.subarray(13, 13 + length).toString('utf-8')) +} + +/** `shedFields` is relay-emitted wire metadata; the typed envelope does not declare it yet. */ +type PublishedEnvelope = AgentHookRelayEnvelope & { shedFields?: string[] } + +function decodeEnvelopes(client: BoundedClient): PublishedEnvelope[] { + // Keepalive frames carry no payload; only regular frames decode as JSON-RPC. + return client.frames + .filter((frame) => frame.readUInt32BE(9) > 0) + .map((frame) => decodePayload(frame)) + .filter((msg) => msg.method === AGENT_HOOK_NOTIFICATION_METHOD) + .map((msg) => msg.params as unknown as PublishedEnvelope) +} + +function makeSubagents(count: number): AgentSubagentSnapshot[] { + return Array.from({ length: count }, (_, index) => ({ + id: `subagent-${index}-${'s'.repeat(40)}`, + agentType: 'general-purpose', + model: 'claude-opus', + description: 'd'.repeat(200), + state: 'working' as const, + startedAt: 1_700_000_000_000 + index + })) +} + +function makeEnvelope(sizes: { + lastAssistantMessage?: number + interactivePrompt?: number + subagents?: number +}): AgentHookRelayEnvelope { + return { + source: 'claude', + paneKey: 'tab-1:4f1b0f4e-0000-4000-8000-000000000001', + connectionId: null, + worktreeId: 'worktree-1', + payload: { + state: 'working', + prompt: 'p'.repeat(64), + agentType: 'claude', + model: 'claude-opus', + toolName: 'Bash', + toolInput: 'echo hi', + ...(sizes.lastAssistantMessage !== undefined + ? { lastAssistantMessage: 'a'.repeat(sizes.lastAssistantMessage) } + : {}), + ...(sizes.interactivePrompt !== undefined + ? { interactivePrompt: 'q'.repeat(sizes.interactivePrompt) } + : {}), + ...(sizes.subagents !== undefined ? { subagents: makeSubagents(sizes.subagents) } : {}) + } + } +} + +describe('publishAgentHookEnvelope', () => { + beforeEach(() => { + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('publishes an in-capacity envelope untouched', () => { + const primary = makeBoundedClient(65536) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + try { + const envelope = makeEnvelope({ lastAssistantMessage: 128, interactivePrompt: 64 }) + publishAgentHookEnvelope(dispatcher, envelope) + + const published = decodeEnvelopes(primary) + expect(published).toHaveLength(1) + expect(published[0]).toEqual(envelope) + expect(primary.closes).toBe(0) + } finally { + dispatcher.dispose() + } + }) + + it('sheds lastAssistantMessage first and stops as soon as the frame fits', () => { + const primary = makeBoundedClient(16384) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + try { + // Only lastAssistantMessage pushes this past the 12288-byte producer cap. + publishAgentHookEnvelope( + dispatcher, + makeEnvelope({ lastAssistantMessage: 20_000, interactivePrompt: 128, subagents: 2 }) + ) + + const published = decodeEnvelopes(primary) + expect(published).toHaveLength(1) + expect(published[0].payload.lastAssistantMessage).toBeUndefined() + expect(published[0].payload.interactivePrompt).toBe('q'.repeat(128)) + expect(published[0].payload.subagents).toHaveLength(2) + expect(published[0].payload.state).toBe('working') + expect(published[0].paneKey).toBe('tab-1:4f1b0f4e-0000-4000-8000-000000000001') + expect(published[0].connectionId).toBeNull() + expect(primary.closes).toBe(0) + } finally { + dispatcher.dispose() + } + }) + + it('logs only when the final single-sink envelope is actually dropped', () => { + const primary = makeBoundedClient(16384) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + try { + publishAgentHookEnvelope(dispatcher, makeEnvelope({ lastAssistantMessage: 20_000 })) + expect(decodeEnvelopes(primary)).toHaveLength(1) + expect(stderr).not.toHaveBeenCalled() + + const unsendable = makeEnvelope({}) + unsendable.payload.prompt = 'p'.repeat(40_000) + publishAgentHookEnvelope(dispatcher, unsendable) + expect(stderr).toHaveBeenCalledTimes(1) + expect(String(stderr.mock.calls[0][0])).toContain('Dropped agent.hook') + } finally { + stderr.mockRestore() + dispatcher.dispose() + } + }) + + it('sheds subagents next when dropping the assistant message is not enough', () => { + const primary = makeBoundedClient(16384) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + try { + publishAgentHookEnvelope( + dispatcher, + makeEnvelope({ lastAssistantMessage: 8_000, interactivePrompt: 6_000, subagents: 40 }) + ) + + const published = decodeEnvelopes(primary) + expect(published).toHaveLength(1) + expect(published[0].payload.lastAssistantMessage).toBeUndefined() + expect(published[0].payload.subagents).toBeUndefined() + expect(published[0].payload.interactivePrompt).toBe('q'.repeat(6_000)) + expect(primary.closes).toBe(0) + } finally { + dispatcher.dispose() + } + }) + + it('keeps the blocking question card when a waiting envelope has to shed', () => { + const primary = makeBoundedClient(16384) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + try { + // A blocked pane is only answerable from web/mobile if interactivePrompt survives the ladder. + const envelope = makeEnvelope({ + lastAssistantMessage: 8_000, + interactivePrompt: 4_000, + subagents: 40 + }) + envelope.payload.state = 'waiting' + publishAgentHookEnvelope(dispatcher, envelope) + + const published = decodeEnvelopes(primary) + expect(published).toHaveLength(1) + expect(published[0].payload.state).toBe('waiting') + expect(published[0].payload.interactivePrompt).toBe('q'.repeat(4_000)) + expect(published[0].payload.subagents).toBeUndefined() + expect(published[0].payload.lastAssistantMessage).toBeUndefined() + expect(primary.closes).toBe(0) + } finally { + dispatcher.dispose() + } + }) + + it('sheds interactivePrompt last and still delivers the status', () => { + const primary = makeBoundedClient(16384) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + try { + publishAgentHookEnvelope( + dispatcher, + makeEnvelope({ lastAssistantMessage: 6_000, interactivePrompt: 13_000, subagents: 2 }) + ) + + const published = decodeEnvelopes(primary) + expect(published).toHaveLength(1) + expect(published[0].payload.lastAssistantMessage).toBeUndefined() + expect(published[0].payload.subagents).toBeUndefined() + expect(published[0].payload.interactivePrompt).toBeUndefined() + expect(published[0].payload.state).toBe('working') + expect(primary.closes).toBe(0) + } finally { + dispatcher.dispose() + } + }) + + it('shrinks an oversized waiting card instead of publishing waiting without it', () => { + const primary = makeBoundedClient(16384) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + try { + const envelope = makeEnvelope({ + lastAssistantMessage: 6_000, + subagents: 2 + }) + envelope.payload.state = 'waiting' + envelope.payload.interactivePrompt = JSON.stringify({ + questions: [ + { + question: 'q'.repeat(13_000), + options: [{ label: 'Keep' }, { label: 'Discard' }] + } + ] + }) + publishAgentHookEnvelope(dispatcher, envelope) + + const published = decodeEnvelopes(primary) + expect(published).toHaveLength(1) + expect(published[0].payload.state).toBe('waiting') + const card = JSON.parse(published[0].payload.interactivePrompt!) as { + questions: { question: string; options: { label: string }[] }[] + } + expect(card.questions[0].question.length).toBeLessThan(13_000) + expect(card.questions[0].options).toEqual([{ label: 'Keep' }, { label: 'Discard' }]) + expect(stderr).not.toHaveBeenCalled() + expect(primary.closes).toBe(0) + } finally { + stderr.mockRestore() + dispatcher.dispose() + } + }) + + it('drops an oversized waiting card when preserving its answer labels cannot fit', () => { + const primary = makeBoundedClient(16384) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + try { + const envelope = makeEnvelope({}) + envelope.payload.state = 'waiting' + envelope.payload.interactivePrompt = JSON.stringify({ + questions: [{ options: [{ label: 'answer'.repeat(3_000) }] }] + }) + publishAgentHookEnvelope(dispatcher, envelope) + + expect(decodeEnvelopes(primary)).toHaveLength(0) + expect(stderr).toHaveBeenCalledTimes(1) + expect(String(stderr.mock.calls[0][0])).toContain('Dropped agent.hook') + expect(primary.closes).toBe(0) + } finally { + stderr.mockRestore() + dispatcher.dispose() + } + }) + + it('never probes the budget for a single sink that accepts the frame', () => { + const primary = makeBoundedClient(16384) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + const probe = vi.spyOn(dispatcher, 'producerEnvelopeBudget') + try { + // One sink writes nothing when it rejects, so the publish attempt is itself the measurement. + publishAgentHookEnvelope(dispatcher, makeEnvelope({ lastAssistantMessage: 128 })) + expect(probe).not.toHaveBeenCalled() + + // Two of the three ladder steps are absent here; skipping them must not cost an extra encode. + publishAgentHookEnvelope(dispatcher, makeEnvelope({ interactivePrompt: 20_000 })) + expect(probe).toHaveBeenCalledTimes(1) + expect(decodeEnvelopes(primary)).toHaveLength(2) + } finally { + probe.mockRestore() + dispatcher.dispose() + } + }) + + it('measures a fan-out up front so both sinks get the same payload', () => { + const primary = makeBoundedClient(65536) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + const secondary = makeBoundedClient(16384) + const probe = vi.spyOn(dispatcher, 'producerEnvelopeBudget') + try { + dispatcher.attachClient(secondary.write, secondary.options) + publishAgentHookEnvelope(dispatcher, makeEnvelope({ lastAssistantMessage: 20_000 })) + // Probing first is what keeps the larger sink from being written a frame we then have to shed. + expect(probe).toHaveBeenCalledTimes(2) + for (const client of [primary, secondary]) { + expect(decodeEnvelopes(client)).toHaveLength(1) + } + } finally { + probe.mockRestore() + dispatcher.dispose() + } + }) + + it('skips absent fields instead of consuming a shed step on them', () => { + const primary = makeBoundedClient(16384) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + try { + // No lastAssistantMessage at all: the ladder must move on to interactivePrompt. + publishAgentHookEnvelope(dispatcher, makeEnvelope({ interactivePrompt: 20_000 })) + + const published = decodeEnvelopes(primary) + expect(published).toHaveLength(1) + expect(published[0].payload.interactivePrompt).toBeUndefined() + expect(primary.closes).toBe(0) + } finally { + dispatcher.dispose() + } + }) + + it('publishes without closing the client when even the fully shed envelope is oversized', () => { + const primary = makeBoundedClient(16384) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + try { + const envelope = makeEnvelope({}) + envelope.payload.prompt = 'p'.repeat(40_000) + publishAgentHookEnvelope(dispatcher, envelope) + + expect(decodeEnvelopes(primary)).toHaveLength(0) + expect(primary.closes).toBe(0) + + // The sink still accepts the next in-capacity frame. + publishAgentHookEnvelope(dispatcher, makeEnvelope({})) + expect(decodeEnvelopes(primary)).toHaveLength(1) + } finally { + dispatcher.dispose() + } + }) + + it('does not mutate the caller envelope, so the hook-server replay cache stays intact', () => { + const primary = makeBoundedClient(16384) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + try { + const envelope = makeEnvelope({ + lastAssistantMessage: 6_000, + interactivePrompt: 6_000, + subagents: 40 + }) + const before = structuredClone(envelope) + + publishAgentHookEnvelope(dispatcher, envelope) + + expect(envelope).toEqual(before) + expect(envelope.payload.lastAssistantMessage).toBe('a'.repeat(6_000)) + expect(envelope.payload.subagents).toHaveLength(40) + } finally { + dispatcher.dispose() + } + }) + + it('sheds to the smallest attached sink so a replay reaches every client', () => { + const primary = makeBoundedClient(65536) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + const secondary = makeBoundedClient(16384) + try { + dispatcher.attachClient(secondary.write, secondary.options) + publishAgentHookEnvelope(dispatcher, makeEnvelope({ lastAssistantMessage: 20_000 })) + + for (const client of [primary, secondary]) { + const published = decodeEnvelopes(client) + expect(published).toHaveLength(1) + expect(published[0].payload.lastAssistantMessage).toBeUndefined() + expect(client.closes).toBe(0) + } + } finally { + dispatcher.dispose() + } + }) + + it('logs one multi-sink drop when the fully shed envelope remains unsendable', () => { + const primary = makeBoundedClient(65536) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + const secondary = makeBoundedClient(16384) + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + try { + dispatcher.attachClient(secondary.write, secondary.options) + const envelope = makeEnvelope({}) + envelope.payload.prompt = 'p'.repeat(40_000) + publishAgentHookEnvelope(dispatcher, envelope) + publishAgentHookEnvelope(dispatcher, envelope) + + expect(decodeEnvelopes(primary)).toHaveLength(0) + expect(decodeEnvelopes(secondary)).toHaveLength(0) + expect(stderr).toHaveBeenCalledTimes(1) + expect(String(stderr.mock.calls[0][0])).toContain('Dropped agent.hook') + } finally { + stderr.mockRestore() + dispatcher.dispose() + } + }) +}) + +describe('publishAgentHookEnvelope shed marker', () => { + it('names every shed field so a consumer can tell a shed roster from an absent one', () => { + const primary = makeBoundedClient(16384) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + try { + publishAgentHookEnvelope( + dispatcher, + makeEnvelope({ lastAssistantMessage: 8_000, interactivePrompt: 6_000, subagents: 40 }) + ) + + const published = decodeEnvelopes(primary) + expect(published).toHaveLength(1) + // Without this marker the renderer overwrites a populated roster with undefined, blanking live + // subagent rows and unblocking hibernation for a pane that is still working. + expect(published[0].shedFields).toEqual([ + 'lastAssistantMessage', + createShedSubagentsField(makeSubagents(40)) + ]) + expect(published[0].payload.subagents).toBeUndefined() + expect(published[0].payload.interactivePrompt).toBe('q'.repeat(6_000)) + } finally { + dispatcher.dispose() + } + }) + + it('omits the marker when nothing was shed and never stamps the caller envelope', () => { + const primary = makeBoundedClient(65536) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + try { + const envelope = makeEnvelope({ lastAssistantMessage: 128, subagents: 2 }) + publishAgentHookEnvelope(dispatcher, envelope) + expect(decodeEnvelopes(primary)[0].shedFields).toBeUndefined() + + const shedding = makeEnvelope({ lastAssistantMessage: 20_000, subagents: 2 }) + publishAgentHookEnvelope(dispatcher, shedding) + // The hook server replays this exact object, so the marker must live on the wire copy only. + expect((shedding as PublishedEnvelope).shedFields).toBeUndefined() + expect(shedding.payload.lastAssistantMessage).toBe('a'.repeat(20_000)) + } finally { + dispatcher.dispose() + } + }) +}) + +describe('publishAgentHookEnvelope redelivery', () => { + beforeEach(() => { + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('redelivers a backpressure-rejected envelope once the producer queue drains', () => { + const primary = makeBoundedClient(16384) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + try { + saturateProducerQueue(dispatcher, primary) + const envelope = makeEnvelope({}) + envelope.payload.state = 'done' + publishAgentHookEnvelope(dispatcher, envelope) + expect(decodeEnvelopes(primary)).toHaveLength(0) + + primary.blocked = false + primary.drain() + // Nothing in the pipeline republishes a hook envelope: it is fire-and-forget, and the only + // other delivery path is the reattach replay. + expect(decodeEnvelopes(primary)).toHaveLength(0) + + vi.advanceTimersByTime(250) + const published = decodeEnvelopes(primary) + expect(published).toHaveLength(1) + expect(published[0].payload.state).toBe('done') + expect(published[0].paneKey).toBe('tab-1:4f1b0f4e-0000-4000-8000-000000000001') + expect(primary.closes).toBe(0) + } finally { + dispatcher.dispose() + } + }) + + it('keeps only the newest snapshot per pane instead of queueing every drop', () => { + const primary = makeBoundedClient(16384) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + try { + saturateProducerQueue(dispatcher, primary) + for (const state of ['working', 'waiting', 'done'] as const) { + const envelope = makeEnvelope({}) + envelope.payload.state = state + publishAgentHookEnvelope(dispatcher, envelope) + } + + primary.blocked = false + primary.drain() + vi.advanceTimersByTime(1_000) + + const published = decodeEnvelopes(primary) + expect(published).toHaveLength(1) + expect(published[0].payload.state).toBe('done') + } finally { + dispatcher.dispose() + } + }) + + it('makes one final retry when capacity returns after the timer budget is exhausted', () => { + const primary = makeBoundedClient(16384) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + try { + const idleTimers = vi.getTimerCount() + saturateProducerQueue(dispatcher, primary) + publishAgentHookEnvelope(dispatcher, makeEnvelope({})) + expect(vi.getTimerCount()).toBeGreaterThan(idleTimers) + + vi.advanceTimersByTime(250 * 41) + expect(vi.getTimerCount()).toBe(idleTimers) + + primary.blocked = false + primary.drain() + expect(decodeEnvelopes(primary)).toHaveLength(1) + + primary.drain() + vi.advanceTimersByTime(10_000) + expect(decodeEnvelopes(primary)).toHaveLength(1) + } finally { + dispatcher.dispose() + } + }) + + it('evicts the longest-idle pane once the pending map is full, keeping the newest', () => { + const primary = makeBoundedClient(16384) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + try { + saturateProducerQueue(dispatcher, primary) + // 65 panes against a 64-pane cap: the first must be evicted, the last must survive. + for (let pane = 0; pane < 65; pane++) { + const envelope = makeEnvelope({}) + envelope.paneKey = `tab-1:4f1b0f4e-0000-4000-8000-${String(pane).padStart(12, '0')}` + publishAgentHookEnvelope(dispatcher, envelope) + } + + primary.blocked = false + primary.drain() + vi.advanceTimersByTime(1_000) + + const redelivered = decodeEnvelopes(primary).map((envelope) => envelope.paneKey) + expect(redelivered).toHaveLength(64) + expect(redelivered).toContain('tab-1:4f1b0f4e-0000-4000-8000-000000000064') + expect(redelivered).not.toContain('tab-1:4f1b0f4e-0000-4000-8000-000000000000') + } finally { + dispatcher.dispose() + } + }) + + it('drops pending redeliveries when the dispatcher is disposed', () => { + const primary = makeBoundedClient(16384) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + const idleTimers = vi.getTimerCount() + saturateProducerQueue(dispatcher, primary) + publishAgentHookEnvelope(dispatcher, makeEnvelope({})) + + dispatcher.dispose() + primary.blocked = false + vi.advanceTimersByTime(10_000) + + expect(vi.getTimerCount()).toBeLessThanOrEqual(idleTimers) + expect(decodeEnvelopes(primary)).toHaveLength(0) + }) + + it('cancels the retry when a later snapshot for the same pane gets through', () => { + const primary = makeBoundedClient(16384) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + try { + const idleTimers = vi.getTimerCount() + saturateProducerQueue(dispatcher, primary) + publishAgentHookEnvelope(dispatcher, makeEnvelope({})) + + primary.blocked = false + primary.drain() + const accepted = makeEnvelope({}) + accepted.payload.state = 'done' + publishAgentHookEnvelope(dispatcher, accepted) + expect(vi.getTimerCount()).toBe(idleTimers) + + vi.advanceTimersByTime(10_000) + expect(decodeEnvelopes(primary)).toHaveLength(1) + } finally { + dispatcher.dispose() + } + }) +}) diff --git a/src/relay/agent-hook-envelope-publication.ts b/src/relay/agent-hook-envelope-publication.ts new file mode 100644 index 000000000..96a413a02 --- /dev/null +++ b/src/relay/agent-hook-envelope-publication.ts @@ -0,0 +1,332 @@ +import { + AGENT_HOOK_NOTIFICATION_METHOD, + AGENT_HOOK_SHED_FIELDS_KEY, + createShedSubagentsField, + type AgentHookRelayEnvelope +} from '../shared/agent-hook-relay' +import type { RelayDispatcher } from './dispatcher' + +// Why: shed the biggest, most reconstructible fields first — state/paneKey must survive or the pane +// stays stuck on its last spinner, and an over-capacity frame is now dropped rather than sent. +// Why: interactivePrompt is last on purpose — a blocking question is load-bearing (without its card +// the pane sits on `waiting` with no way to answer from web or mobile). The roster is shed earlier +// only because it is cheaper to rebuild, NOT because it is cosmetic: a missing roster blanks live +// subagent rows and unblocks pane hibernation, which is why shed fields are named on the wire — +// `restoreShedStatusFields` re-attaches the restorable ones from Orca's cached payload. +const SHED_ORDER = ['lastAssistantMessage', 'subagents', 'interactivePrompt'] as const + +// Why: these envelopes are fire-and-forget state snapshots — no ack, no producer-side retry — and +// the only other delivery path is the reattach replay. A queue-full drop would otherwise leave the +// pane on a stale spinner until the SSH link cycles, so a rejected snapshot is retried briefly. +const REDELIVERY_INTERVAL_MS = 250 +const MAX_REDELIVERY_ATTEMPTS = 40 +// Why: a wedged link must not pin snapshots for panes that are already gone; recency-evict the rest. +const MAX_PENDING_PANES = 64 + +type PendingEnvelope = { + params: Record + clientIds: readonly number[] + /** Zero means the timer budget is exhausted and one capacity-driven attempt remains. */ + attemptsLeft: number +} + +type RedeliveryState = { + pending: Map + timer: ReturnType | null +} + +const redeliveryByDispatcher = new WeakMap() +// Why: some agents submit option labels verbatim, so only presentation-only fields may shrink. +const COMPACTABLE_INTERACTIVE_PROMPT_FIELDS = new Set([ + 'description', + 'detail', + 'header', + 'question', + 'summary' +]) + +function fitsProducerFrame(dispatcher: RelayDispatcher, params: Record): boolean { + return dispatcher.producerEnvelopeBudget(AGENT_HOOK_NOTIFICATION_METHOD, params) >= 0 +} + +function toNotificationParams( + envelope: AgentHookRelayEnvelope, + shedFields: readonly string[] +): Record { + const params = envelope as unknown as Record + return shedFields.length === 0 + ? params + : { ...params, [AGENT_HOOK_SHED_FIELDS_KEY]: [...shedFields] } +} + +function compactInteractivePromptValue(value: unknown, maxStringLength: number): unknown { + if (Array.isArray(value)) { + return value.map((item) => compactInteractivePromptValue(item, maxStringLength)) + } + if (!value || typeof value !== 'object') { + return value + } + return Object.fromEntries( + Object.entries(value).map(([key, item]) => [ + key, + typeof item === 'string' && COMPACTABLE_INTERACTIVE_PROMPT_FIELDS.has(key) + ? item.slice(0, maxStringLength) + : compactInteractivePromptValue(item, maxStringLength) + ]) + ) +} + +function fitWaitingInteractivePrompt( + dispatcher: RelayDispatcher, + envelope: AgentHookRelayEnvelope, + shedFields: readonly string[] +): AgentHookRelayEnvelope | null { + const prompt = envelope.payload.interactivePrompt + if (!prompt) { + return null + } + let parsed: unknown + try { + parsed = JSON.parse(prompt) + } catch { + parsed = undefined + } + const promptAtLimit = (limit: number): string => + parsed === undefined + ? prompt.slice(0, limit) + : JSON.stringify(compactInteractivePromptValue(parsed, limit)) + let low = 1 + let high = prompt.length + let fitted: AgentHookRelayEnvelope | null = null + while (low <= high) { + const mid = Math.floor((low + high) / 2) + const candidate = { + ...envelope, + payload: { ...envelope.payload, interactivePrompt: promptAtLimit(mid) } + } + if (fitsProducerFrame(dispatcher, toNotificationParams(candidate, shedFields))) { + fitted = candidate + low = mid + 1 + } else { + high = mid - 1 + } + } + return fitted +} + +/** Returns the ids of the clients that rejected the frame; a rejected client is never written to. */ +function publishToClients( + dispatcher: RelayDispatcher, + params: Record, + clientIds: readonly number[], + logDrop?: boolean +): number[] { + const rejected: number[] = [] + for (const clientId of clientIds) { + if ( + !dispatcher.publishProducerNotification( + clientId, + AGENT_HOOK_NOTIFICATION_METHOD, + params, + logDrop === undefined ? undefined : { logDrop } + ) + ) { + rejected.push(clientId) + } + } + return rejected +} + +function logUnsendableEnvelope( + dispatcher: RelayDispatcher, + params: Record, + clientIds: readonly number[] +): void { + const rejectedClientId = clientIds.find( + (clientId) => + dispatcher.producerEnvelopeBudget(AGENT_HOOK_NOTIFICATION_METHOD, params, clientId) < 0 + ) + if (rejectedClientId !== undefined) { + publishToClients(dispatcher, params, [rejectedClientId], true) + } +} + +/** Publishes an agent-hook envelope, dropping optional detail fields until the frame fits the + * smallest attached sink. A frame the sink queue merely has no room for is retried in the + * background; one that no shedding can fit is dropped. */ +export function publishAgentHookEnvelope( + dispatcher: RelayDispatcher, + envelope: AgentHookRelayEnvelope +): void { + const clientIds = dispatcher.activeClientIds() + if (clientIds.length === 0) { + return + } + // Why: a fan-out must choose one payload before it writes anything, or the first client keeps a + // frame a smaller later client forces us to shed. A single sink writes nothing when it rejects, + // so there the attempt itself is the measurement — one encode instead of a probe plus a publish. + const measureBeforePublish = clientIds.length > 1 + let candidate = envelope + const shedFields: string[] = [] + let step = 0 + for (;;) { + const params = toNotificationParams(candidate, shedFields) + while (step < SHED_ORDER.length && candidate.payload[SHED_ORDER[step]] === undefined) { + step += 1 + } + if (!measureBeforePublish || fitsProducerFrame(dispatcher, params)) { + // A rejected intermediate probe is not a drop if a smaller envelope is delivered next. + const rejected = publishToClients( + dispatcher, + params, + clientIds, + measureBeforePublish ? undefined : step >= SHED_ORDER.length + ) + if (rejected.length === 0) { + clearPendingEnvelope(dispatcher, envelope.paneKey) + return + } + // Rejection is ambiguous: an over-capacity frame must shed, a full producer queue must wait. + if (measureBeforePublish || fitsProducerFrame(dispatcher, params)) { + setPendingEnvelope(dispatcher, envelope.paneKey, params, rejected) + return + } + } + if (step >= SHED_ORDER.length) { + // Nothing left to shed and it still does not fit: waiting cannot make it sendable, and this + // snapshot supersedes any pending one, which is now stale. + if (measureBeforePublish) { + logUnsendableEnvelope(dispatcher, params, clientIds) + } + clearPendingEnvelope(dispatcher, envelope.paneKey) + return + } + const field = SHED_ORDER[step] + step += 1 + if (field === 'interactivePrompt' && candidate.payload.state === 'waiting') { + const fitted = fitWaitingInteractivePrompt(dispatcher, candidate, shedFields) + if (fitted) { + candidate = fitted + continue + } + // A waiting snapshot without an answerable card must not reach web/mobile. + logUnsendableEnvelope(dispatcher, params, clientIds) + clearPendingEnvelope(dispatcher, envelope.paneKey) + return + } + // Why: the hook server caches envelopes and replays them after --connect, so shedding in place + // would permanently strip the cached copy too. + candidate = { ...candidate, payload: { ...candidate.payload } } + const shedField = + field === 'subagents' ? createShedSubagentsField(candidate.payload.subagents ?? []) : field + delete candidate.payload[field] + shedFields.push(shedField) + } +} + +function setPendingEnvelope( + dispatcher: RelayDispatcher, + paneKey: string, + params: Record, + clientIds: readonly number[] +): void { + let state = redeliveryByDispatcher.get(dispatcher) + if (!state) { + state = { pending: new Map(), timer: null } + redeliveryByDispatcher.set(dispatcher, state) + // A disposed dispatcher can never accept the retry, and pending params pin the cached payload. + dispatcher.onDisposed(() => stopRedelivery(dispatcher)) + dispatcher.onLegacyPtyCapacity(() => runFinalCapacityPass(dispatcher)) + } + // Latest-wins: one snapshot per pane, never a growing queue. Delete-then-set keeps Map insertion + // order = recency so the cap below evicts the longest-idle pane. + state.pending.delete(paneKey) + state.pending.set(paneKey, { params, clientIds, attemptsLeft: MAX_REDELIVERY_ATTEMPTS }) + while (state.pending.size > MAX_PENDING_PANES) { + state.pending.delete(state.pending.keys().next().value as string) + } + if (!state.timer) { + const timer = setInterval(() => runRedeliveryPass(dispatcher), REDELIVERY_INTERVAL_MS) + if (typeof timer.unref === 'function') { + timer.unref() + } + state.timer = timer + } +} + +function clearPendingEnvelope(dispatcher: RelayDispatcher, paneKey: string): void { + const state = redeliveryByDispatcher.get(dispatcher) + if (!state?.pending.delete(paneKey) || state.pending.size > 0) { + return + } + stopRedelivery(dispatcher) +} + +function stopRedelivery(dispatcher: RelayDispatcher): void { + const state = redeliveryByDispatcher.get(dispatcher) + if (!state) { + return + } + state.pending.clear() + if (state.timer) { + clearInterval(state.timer) + state.timer = null + } +} + +function stopRedeliveryTimer(state: RedeliveryState): void { + if (state.timer) { + clearInterval(state.timer) + state.timer = null + } +} + +function runRedeliveryPass(dispatcher: RelayDispatcher): void { + const state = redeliveryByDispatcher.get(dispatcher) + if (!state) { + return + } + const active = new Set(dispatcher.activeClientIds()) + for (const [paneKey, pending] of Array.from(state.pending)) { + if (pending.attemptsLeft <= 0) { + continue + } + // A client that detached gets caught up by the reattach replay, so stop tracking it. + const targets = pending.clientIds.filter((clientId) => active.has(clientId)) + const rejected = + targets.length === 0 ? [] : publishToClients(dispatcher, pending.params, targets) + pending.attemptsLeft -= 1 + if (rejected.length === 0) { + state.pending.delete(paneKey) + continue + } + pending.clientIds = rejected + } + if (state.pending.size === 0) { + stopRedelivery(dispatcher) + } else if (Array.from(state.pending.values()).every((pending) => pending.attemptsLeft <= 0)) { + stopRedeliveryTimer(state) + } +} + +function runFinalCapacityPass(dispatcher: RelayDispatcher): void { + const state = redeliveryByDispatcher.get(dispatcher) + if (!state) { + return + } + const active = new Set(dispatcher.activeClientIds()) + for (const [paneKey, pending] of Array.from(state.pending)) { + if (pending.attemptsLeft > 0) { + continue + } + // Delete before publishing because a synchronous sink settlement emits capacity reentrantly. + state.pending.delete(paneKey) + const targets = pending.clientIds.filter((clientId) => active.has(clientId)) + if (targets.length > 0) { + publishToClients(dispatcher, pending.params, targets) + } + } + if (state.pending.size === 0) { + stopRedelivery(dispatcher) + } +} diff --git a/src/relay/agent-hook-integration.test.ts b/src/relay/agent-hook-integration.test.ts index 9e3df40a9..3b941e6ba 100644 --- a/src/relay/agent-hook-integration.test.ts +++ b/src/relay/agent-hook-integration.test.ts @@ -26,7 +26,9 @@ import { AGENT_HOOK_NOTIFICATION_METHOD, AGENT_HOOK_REQUEST_REPLAY_METHOD } from '../shared/agent-hook-relay' +import { AGENT_STATUS_ASSISTANT_MESSAGE_MAX_LENGTH } from '../shared/agent-status-types' import { AgentHookServer } from '../main/agent-hooks/server' +import { publishAgentHookEnvelope } from './agent-hook-envelope-publication' const LEAF_7 = '77777777-7777-4777-8777-777777777777' const LEAF_9 = '99999999-9999-4999-8999-999999999999' @@ -57,22 +59,25 @@ describe('Integration: relay hook server → mux → AgentHookServer.ingestRemot onClose: () => {} } - dispatcher = new RelayDispatcher((data: Buffer) => { - setImmediate(() => { - for (const cb of clientDataCallbacks) { - cb(data) - } - }) - }) + dispatcher = new RelayDispatcher( + (data: Buffer) => { + setImmediate(() => { + for (const cb of clientDataCallbacks) { + cb(data) + } + }) + }, + { + writableHighWaterMark: () => 4096, + writableLength: () => 0 + } + ) relayFeedFn = (data: Buffer) => dispatcher.feed(data) hookServer = new RelayAgentHookServer({ endpointDir: tmpDir, forward: (envelope) => { - dispatcher.notify( - AGENT_HOOK_NOTIFICATION_METHOD, - envelope as unknown as Record - ) + publishAgentHookEnvelope(dispatcher, envelope) } }) await hookServer.start() @@ -157,6 +162,42 @@ describe('Integration: relay hook server → mux → AgentHookServer.ingestRemot expect(payload.agentType).toBe('claude') }) + it('sheds an oversized assistant message through the production publication path', async () => { + const events: { payload: { state: string; lastAssistantMessage?: string } }[] = [] + orcaServer.setListener((event) => { + events.push({ payload: event.payload }) + }) + const { port, token } = hookServer.getCoordinates() + const post = (payload: Record): Promise => + fetch(`http://127.0.0.1:${port}/hook/claude`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Orca-Agent-Hook-Token': token + }, + body: JSON.stringify({ paneKey: `tab-7:${LEAF_7}`, payload }) + }) + + await expect( + post({ hook_event_name: 'UserPromptSubmit', prompt: 'bounded publication' }) + ).resolves.toMatchObject({ status: 204 }) + await expect( + post({ + hook_event_name: 'Stop', + last_assistant_message: 'a'.repeat(AGENT_STATUS_ASSISTANT_MESSAGE_MAX_LENGTH) + }) + ).resolves.toMatchObject({ status: 204 }) + + const start = Date.now() + while (events.length < 2 && Date.now() - start < 1500) { + await new Promise((resolve) => setImmediate(resolve)) + } + expect(events).toHaveLength(2) + expect(events[1].payload.state).toBe('done') + expect(events[1].payload.lastAssistantMessage).toBeUndefined() + expect(dispatcher.activeClientIds()).toHaveLength(1) + }) + it('clears remote Claude permission when the approved tool starts with matching identity', async () => { const { port, token } = hookServer.getCoordinates() const postClaude = async (payload: Record): Promise => diff --git a/src/relay/dispatcher-capacity-degradation.test.ts b/src/relay/dispatcher-capacity-degradation.test.ts new file mode 100644 index 000000000..a546989d5 --- /dev/null +++ b/src/relay/dispatcher-capacity-degradation.test.ts @@ -0,0 +1,469 @@ +import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' +import { + RelayDispatcher, + type RelayClientSinkOptions, + type SinkWriteSettlement +} from './dispatcher' +import { DISPATCHER_CONTROL_QUEUE_MAX_FRAMES } from './dispatcher-writer-admission' +import { LEGACY_CLIENT_RETAINED_BYTES_LOW } from './legacy-relay-publication-ledger' +import type * as ProtocolModule from './protocol' +import { encodeJsonRpcFrame, RelayErrorCode } from './protocol' + +// Counts every frame encode (including the estimate-only ones) so a redundant re-encode is observable. +const encodeCalls = vi.hoisted(() => ({ count: 0 })) + +vi.mock('./protocol', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + encodeJsonRpcFrame: (...args: Parameters) => { + encodeCalls.count++ + return actual.encodeJsonRpcFrame(...args) + } + } +}) + +type BoundedClient = { + frames: Buffer[] + closes: number + options: RelayClientSinkOptions + write: (data: Buffer) => boolean +} + +// Why: a sink that never accepts a write and never drains retains producer bytes, so the queue saturates +// while every individual frame stays comfortably inside the per-frame capacity. +function makeSaturatingClient(highWaterMark: number): BoundedClient { + const client = makeBoundedClient(highWaterMark) + client.write = (data: Buffer) => { + client.frames.push(Buffer.from(data)) + return false + } + return client +} + +function makeBoundedClient(highWaterMark: number): BoundedClient { + const client: BoundedClient = { + frames: [], + closes: 0, + write: (data: Buffer) => { + client.frames.push(Buffer.from(data)) + return true + }, + options: { + writableHighWaterMark: () => highWaterMark, + writableLength: () => 0, + close: () => { + client.closes++ + } + } + } + return client +} + +function decodePayload(frame: Buffer): Record { + const length = frame.readUInt32BE(9) + return JSON.parse(frame.subarray(13, 13 + length).toString('utf-8')) +} + +describe('RelayDispatcher bounded-capacity degradation', () => { + beforeEach(() => { + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('producerEnvelopeBudget returns a negative budget for an over-cap envelope', () => { + const primary = makeBoundedClient(16384) + const bounded = new RelayDispatcher(primary.write, primary.options) + try { + expect( + bounded.producerEnvelopeBudget('fs.changed', { events: ['x'.repeat(64)] }) + ).toBeGreaterThan(0) + expect( + bounded.producerEnvelopeBudget('fs.changed', { events: ['x'.repeat(20_000)] }) + ).toBeLessThan(0) + } finally { + bounded.dispose() + } + }) + + it('producerEnvelopeBudget takes the smallest client capacity unless a client is named', () => { + const primary = makeBoundedClient(65536) + const secondary = makeBoundedClient(16384) + const bounded = new RelayDispatcher(primary.write, primary.options) + try { + const secondaryId = bounded.attachClient(secondary.write, secondary.options) + const params = { events: ['x'.repeat(64)] } + const envelopeBytes = encodeJsonRpcFrame( + { jsonrpc: '2.0', method: 'fs.changed', params }, + 0, + 0 + ).length + + expect(bounded.activeClientIds()).toHaveLength(2) + expect(bounded.producerEnvelopeBudget('fs.changed', params)).toBe(12288 - envelopeBytes) + expect( + bounded.producerEnvelopeBudget('fs.changed', params, bounded.activeClientIds()[0]) + ).toBe(49152 - envelopeBytes) + expect(bounded.producerEnvelopeBudget('fs.changed', params, secondaryId)).toBe( + 12288 - envelopeBytes + ) + expect(bounded.producerEnvelopeBudget('fs.changed', params, 999)).toBe( + Number.MIN_SAFE_INTEGER + ) + } finally { + bounded.dispose() + } + }) + + it('producerEnvelopeBudget reports no capacity for a named client that is gone', () => { + const primary = makeBoundedClient(65536) + const secondary = makeBoundedClient(65536) + const bounded = new RelayDispatcher(primary.write, primary.options) + try { + const secondaryId = bounded.attachClient(secondary.write, secondary.options) + const params = { events: ['x'.repeat(64)] } + expect(bounded.producerEnvelopeBudget('fs.changed', params, secondaryId)).toBeGreaterThan(0) + + // A client that detached between activeClientIds() and publication must never look like it fits. + bounded.detachClient(secondaryId) + expect(bounded.producerEnvelopeBudget('fs.changed', params, secondaryId)).toBeLessThan(0) + expect(bounded.producerEnvelopeBudget('fs.changed', params, 999)).toBeLessThan(0) + // The no-target broadcast case still reports unbounded room. + expect(bounded.producerEnvelopeBudget('fs.changed', params)).toBeGreaterThan(0) + } finally { + bounded.dispose() + } + }) + + it('producerDataBudget keeps its pre-delegation value for a pty.data envelope', () => { + const primary = makeBoundedClient(65536) + const bounded = new RelayDispatcher(primary.write, primary.options) + try { + // Snapshot of the shipped formula: 49152-byte producer capacity minus the 96-byte empty-data frame. + expect(bounded.producerDataBudget('pty.data', { ptyId: 'pty-7', seq: 42 })).toBe(49056) + // A vanished client leaves no room for data at all. + expect(bounded.producerDataBudget('pty.data', { ptyId: 'pty-7', seq: 42 }, 999)).toBe(0) + } finally { + bounded.dispose() + } + }) + + it('producerDataBudget floors at zero when the envelope alone exceeds capacity', () => { + const primary = makeBoundedClient(1030) + const bounded = new RelayDispatcher(primary.write, primary.options) + try { + expect(bounded.producerDataBudget('pty.data', { ptyId: 'x'.repeat(4096) })).toBe(0) + } finally { + bounded.dispose() + } + }) + + it('notify drops an over-capacity frame and keeps the client open', () => { + const primary = makeBoundedClient(16384) + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + const bounded = new RelayDispatcher(primary.write, primary.options) + try { + bounded.notify('fs.changed', { events: ['x'.repeat(20_000)] }) + + expect(primary.closes).toBe(0) + expect(primary.frames).toHaveLength(0) + expect(stderr).toHaveBeenCalledTimes(1) + expect(stderr.mock.calls[0][0]).toMatch( + /^\[relay\] Dropped fs\.changed \(\d+B > producer frame capacity 12288B\)\n$/ + ) + + bounded.notify('pty.exit', { id: 'pty-1' }) + expect(primary.frames).toHaveLength(1) + expect(decodePayload(primary.frames[0]).method).toBe('pty.exit') + } finally { + stderr.mockRestore() + bounded.dispose() + } + }) + + it('logs at most one drop per client generation', () => { + const primary = makeBoundedClient(16384) + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + const bounded = new RelayDispatcher(primary.write, primary.options) + try { + const flood = { events: ['x'.repeat(20_000)] } + bounded.notify('fs.changed', flood) + bounded.notify('fs.changed', flood) + expect(stderr).toHaveBeenCalledTimes(1) + + const reattached = makeBoundedClient(16384) + bounded.setWrite(reattached.write, reattached.options) + bounded.notify('fs.changed', flood) + expect(stderr).toHaveBeenCalledTimes(2) + } finally { + stderr.mockRestore() + bounded.dispose() + } + }) + + it('distinguishes an over-capacity drop from a producer-queue-full drop on one client', () => { + const primary = makeSaturatingClient(4 * 1024 * 1024) + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + const bounded = new RelayDispatcher(primary.write, primary.options) + try { + // The first 1.5MB frame is retained by the stalled sink; the second exceeds the 2MB producer queue. + bounded.notify('fs.changed', { events: ['x'.repeat(1_500_000)] }) + expect(primary.frames).toHaveLength(1) + bounded.notify('fs.changed', { events: ['x'.repeat(1_500_000)] }) + bounded.notify('fs.changed', { events: ['x'.repeat(5_000_000)] }) + + expect(primary.closes).toBe(0) + expect(stderr).toHaveBeenCalledTimes(2) + expect(stderr.mock.calls[0][0]).toMatch( + /^\[relay\] Dropped fs\.changed \(\d+B, producer queue full; frame capacity 4128768B\)\n$/ + ) + expect(stderr.mock.calls[1][0]).toMatch( + /^\[relay\] Dropped fs\.changed \(\d+B > producer frame capacity 4128768B\)\n$/ + ) + + // Both classifications stay one-per-generation once logged. + bounded.notify('fs.changed', { events: ['x'.repeat(1_500_000)] }) + bounded.notify('fs.changed', { events: ['x'.repeat(5_000_000)] }) + expect(stderr).toHaveBeenCalledTimes(2) + } finally { + stderr.mockRestore() + bounded.dispose() + } + }) + + it('logs each dropped method once instead of letting the first method silence the rest', () => { + const primary = makeBoundedClient(16384) + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + const bounded = new RelayDispatcher(primary.write, primary.options) + try { + const flood = { events: ['x'.repeat(20_000)] } + bounded.notify('fs.changed', flood) + bounded.notify('pty.data', flood) + bounded.notify('fs.changed', flood) + bounded.notify('pty.data', flood) + + expect(stderr).toHaveBeenCalledTimes(2) + expect(stderr.mock.calls[0][0]).toContain('Dropped fs.changed') + expect(stderr.mock.calls[1][0]).toContain('Dropped pty.data') + } finally { + stderr.mockRestore() + bounded.dispose() + } + }) + + it('publishProducerNotification publishes on the producer lane and never closes', () => { + const primary = makeBoundedClient(65536) + const secondary = makeBoundedClient(16384) + const bounded = new RelayDispatcher(primary.write, primary.options) + try { + const secondaryId = bounded.attachClient(secondary.write, secondary.options) + + expect(bounded.publishProducerNotification(secondaryId, 'fs.changed', { events: [] })).toBe( + true + ) + expect(secondary.frames).toHaveLength(1) + expect(primary.frames).toHaveLength(0) + + expect( + bounded.publishProducerNotification(secondaryId, 'fs.changed', { + events: ['x'.repeat(20_000)] + }) + ).toBe(false) + expect(secondary.closes).toBe(0) + expect(secondary.frames).toHaveLength(1) + + expect(bounded.publishProducerNotification(999, 'fs.changed')).toBe(false) + } finally { + bounded.dispose() + } + }) + + it('still closes on protocol-critical control queue overflow', () => { + const primary = makeSaturatingClient(65536) + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + const bounded = new RelayDispatcher(primary.write, primary.options) + try { + const clientId = bounded.activeClientIds()[0] + for (let index = 0; index < DISPATCHER_CONTROL_QUEUE_MAX_FRAMES; index += 1) { + bounded.notifyClient(clientId, `control.${index}`) + } + expect(primary.closes).toBe(0) + + bounded.notifyClient(clientId, 'control.overflow') + expect(primary.closes).toBe(1) + } finally { + stderr.mockRestore() + bounded.dispose() + } + }) + + it('closes the client when pty.replay overflows the control queue', () => { + const primary = makeSaturatingClient(65536) + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + const bounded = new RelayDispatcher(primary.write, primary.options) + try { + const clientId = bounded.activeClientIds()[0] + for (let index = 0; index < DISPATCHER_CONTROL_QUEUE_MAX_FRAMES; index += 1) { + bounded.notifyClient(clientId, `control.${index}`) + } + expect(primary.closes).toBe(0) + + // Replay is never retried, so an unnoticed drop would strand the pane on a short buffer. + bounded.notify('pty.replay', { paneKey: 'tab-1:pane-1', data: 'x' }) + expect(primary.closes).toBe(1) + } finally { + stderr.mockRestore() + bounded.dispose() + } + }) + + it('publishProducerNotification reports its drops like notify', () => { + const primary = makeBoundedClient(65536) + const secondary = makeBoundedClient(16384) + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + const bounded = new RelayDispatcher(primary.write, primary.options) + try { + const secondaryId = bounded.attachClient(secondary.write, secondary.options) + const flood = { events: ['x'.repeat(20_000)] } + + expect(bounded.publishProducerNotification(secondaryId, 'fs.changed', flood)).toBe(false) + expect(stderr).toHaveBeenCalledTimes(1) + expect(stderr.mock.calls[0][0]).toMatch( + /^\[relay\] Dropped fs\.changed \(\d+B > producer frame capacity 12288B\)\n$/ + ) + + // Same one-line-per-generation budget as notify(). + expect(bounded.publishProducerNotification(secondaryId, 'fs.changed', flood)).toBe(false) + expect(stderr).toHaveBeenCalledTimes(1) + } finally { + stderr.mockRestore() + bounded.dispose() + } + }) + + it('does not re-encode a dropped frame when its log line is suppressed', () => { + const primary = makeBoundedClient(16384) + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + const bounded = new RelayDispatcher(primary.write, primary.options) + try { + const flood = { events: ['x'.repeat(20_000)] } + bounded.notify('fs.changed', flood) + expect(stderr).toHaveBeenCalledTimes(1) + + // The suppressed drop must size the frame once, not once to publish and again to log. + encodeCalls.count = 0 + bounded.notify('fs.changed', flood) + expect(stderr).toHaveBeenCalledTimes(1) + expect(encodeCalls.count).toBe(1) + } finally { + stderr.mockRestore() + bounded.dispose() + } + }) + + it('sendResponse substitutes a JSON-RPC error instead of closing when the legacy lane rejects', async () => { + const primary = makeBoundedClient(65536) + const bounded = new RelayDispatcher(primary.write, primary.options) + try { + bounded.onRequest('fs.listFiles', async () => ({ paths: 'x'.repeat(3 * 1024 * 1024) })) + bounded.feed(encodeJsonRpcFrame({ jsonrpc: '2.0', id: 77, method: 'fs.listFiles' }, 1, 0)) + await vi.advanceTimersByTimeAsync(0) + + expect(primary.closes).toBe(0) + expect(primary.frames).toHaveLength(1) + const response = decodePayload(primary.frames[0]) as unknown as { + id: number + error: { code: number; message: string } + } + expect(response.id).toBe(77) + expect(response.error.code).toBe(RelayErrorCode.ResponseOverCapacity) + expect(response.error.message).toBe('Relay response exceeded the bounded transport capacity') + } finally { + bounded.dispose() + } + }) + + it('settles the response fence as failed when the substitute error replaces the result', async () => { + const primary = makeBoundedClient(65536) + const bounded = new RelayDispatcher(primary.write, primary.options) + try { + const settlements: SinkWriteSettlement[] = [] + bounded.onRequest('fs.listFiles', async (_params, context) => { + context.onResponseSettled?.((result) => settlements.push(result)) + return { paths: 'x'.repeat(3 * 1024 * 1024) } + }) + bounded.feed(encodeJsonRpcFrame({ jsonrpc: '2.0', id: 79, method: 'fs.listFiles' }, 1, 0)) + await vi.advanceTimersByTimeAsync(0) + + expect(primary.closes).toBe(0) + expect(settlements).toHaveLength(1) + // The peer got a capacity error, not the result — the fence must not claim delivery. + expect(settlements[0]).toEqual({ + ok: false, + error: new Error('Relay response exceeded the bounded transport capacity') + }) + } finally { + bounded.dispose() + } + }) + + it('producerRetentionBelowLowWater reports the reserve of one client, not the dispatcher', () => { + const stalled = makeSaturatingClient(65536) + const healthy = makeBoundedClient(65536) + const bounded = new RelayDispatcher(stalled.write, stalled.options) + try { + const stalledId = bounded.activeClientIds()[0] + const healthyId = bounded.attachClient(healthy.write, healthy.options) + let parked = 0 + while ( + parked <= LEGACY_CLIENT_RETAINED_BYTES_LOW && + bounded.publishProducerNotification(stalledId, 'pty.data', { + paneId: 'pane', + data: 'x'.repeat(40_000) + }) + ) { + parked += 40_000 + } + expect(parked).toBeGreaterThan(LEGACY_CLIENT_RETAINED_BYTES_LOW) + + expect(bounded.producerRetentionBelowLowWater(stalledId)).toBe(false) + expect(bounded.producerRetentionBelowLowWater(healthyId)).toBe(true) + // The dispatcher-wide signal is the one that lets a stalled peer speak for a healthy client. + expect(bounded.legacyRetentionBelowLowWater).toBe(false) + + // A client that cannot be written to has no headroom at all. + expect(bounded.producerRetentionBelowLowWater(999)).toBe(false) + bounded.detachClient(healthyId) + expect(bounded.producerRetentionBelowLowWater(healthyId)).toBe(false) + } finally { + bounded.dispose() + } + }) + + it('sendResponse settles an already-failed oversized response without closing', async () => { + const primary = makeBoundedClient(65536) + const bounded = new RelayDispatcher(primary.write, primary.options) + try { + bounded.onRequest('fs.listFiles', async () => { + throw new Error('x'.repeat(3 * 1024 * 1024)) + }) + bounded.feed(encodeJsonRpcFrame({ jsonrpc: '2.0', id: 78, method: 'fs.listFiles' }, 1, 0)) + await vi.advanceTimersByTimeAsync(0) + + expect(primary.closes).toBe(0) + expect(primary.frames).toHaveLength(1) + const response = decodePayload(primary.frames[0]) as unknown as { + id: number + error: { code: number; message: string } + } + expect(response.id).toBe(78) + expect(response.error.code).toBe(RelayErrorCode.ResponseOverCapacity) + expect(response.error.message).toBe('Relay response exceeded the bounded transport capacity') + } finally { + bounded.dispose() + } + }) +}) diff --git a/src/relay/dispatcher-client-writer.ts b/src/relay/dispatcher-client-writer.ts index 1966ce31d..58be59173 100644 --- a/src/relay/dispatcher-client-writer.ts +++ b/src/relay/dispatcher-client-writer.ts @@ -83,7 +83,8 @@ export class DispatcherClientWriter { lane: DispatcherWriterLane, encode: () => Buffer, estimatedBytes: number, - onSettled: (result: SinkWriteSettlement) => void = () => {} + onSettled: (result: SinkWriteSettlement) => void = () => {}, + overflowIsNonFatal = false ): boolean { if (this.closed) { onSettled({ ok: false, error: new Error('Relay writer is closed') }) @@ -94,7 +95,8 @@ export class DispatcherClientWriter { encode, estimatedBytes, onSettled: onceDispatcherWriterSettlement(onSettled), - settled: false + settled: false, + overflowIsNonFatal } const admission = this.admission.admit(entry, this.sink.frameCapacity(lane, this.saturated)) if (!admission.accepted) { @@ -176,29 +178,18 @@ export class DispatcherClientWriter { } return this.laneScheduler.select( this.admission, - (entry) => this.canWriteControl(entry), - (entry) => this.canWriteProducer(entry) + (entry) => this.canWrite(entry, this.sink.highWaterMark), + (entry) => this.canWrite(entry, this.sink.producerFrameCapacity) ) } - private canWriteControl(entry: DispatcherWriterEntry): boolean { - const highWaterMark = this.sink.highWaterMark - if (!Number.isFinite(highWaterMark)) { + // Why: a zero-length writable always takes one frame, else a single oversized frame could never drain. + private canWrite(entry: DispatcherWriterEntry, capacity: number): boolean { + if (!Number.isFinite(this.sink.highWaterMark)) { return true } const writableLength = this.sink.writableLength - return writableLength + entry.estimatedBytes <= highWaterMark || writableLength === 0 - } - - private canWriteProducer(entry: DispatcherWriterEntry): boolean { - const highWaterMark = this.sink.highWaterMark - if (!Number.isFinite(highWaterMark)) { - return true - } - return ( - this.sink.writableLength + entry.estimatedBytes <= this.sink.producerFrameCapacity || - this.sink.writableLength === 0 - ) + return writableLength + entry.estimatedBytes <= capacity || writableLength === 0 } private writeEntry(entry: DispatcherWriterEntry): void { diff --git a/src/relay/dispatcher-writer-admission.ts b/src/relay/dispatcher-writer-admission.ts index a49627d4d..07db61c12 100644 --- a/src/relay/dispatcher-writer-admission.ts +++ b/src/relay/dispatcher-writer-admission.ts @@ -15,13 +15,15 @@ export type DispatcherWriterEntry = { estimatedBytes: number onSettled: (result: DispatcherWriterSettlement) => void settled: boolean + // Why: control overflow closes the client by default; best-effort frames opt out of that instead. + overflowIsNonFatal?: boolean } type AdmissionResult = | { accepted: true; replaced?: DispatcherWriterEntry } | { accepted: false; error?: Error } -const CONTROL_QUEUE_MAX_FRAMES = 256 +export const DISPATCHER_CONTROL_QUEUE_MAX_FRAMES = 256 export const DISPATCHER_CONTROL_QUEUE_MAX_BYTES = 1024 * 1024 const LIVENESS_QUEUE_MAX_FRAMES = 2 @@ -143,10 +145,15 @@ export class DispatcherWriterAdmission { } private admitControl(entry: DispatcherWriterEntry): AdmissionResult { + // Why: best-effort controls may fail soft without weakening protocol-critical admission. + const overflowIsNonFatal = entry.overflowIsNonFatal === true if ( - this.controlFrames >= CONTROL_QUEUE_MAX_FRAMES || + this.controlFrames >= DISPATCHER_CONTROL_QUEUE_MAX_FRAMES || this.controlBytes + entry.estimatedBytes > DISPATCHER_CONTROL_QUEUE_MAX_BYTES ) { + if (overflowIsNonFatal) { + return { accepted: false } + } return { accepted: false, error: new Error('Relay control queue exceeded its bounded capacity') diff --git a/src/relay/dispatcher.ts b/src/relay/dispatcher.ts index 7149144c9..e8766dc34 100644 --- a/src/relay/dispatcher.ts +++ b/src/relay/dispatcher.ts @@ -6,6 +6,7 @@ import { encodeKeepAliveFrame, parseJsonRpcMessage, KEEPALIVE_SEND_MS, + RelayErrorCode, type DecodedFrame, type JsonRpcRequest, type JsonRpcNotification, @@ -69,9 +70,21 @@ type RelayClient = { highestReceivedSeq: number generation: number closed: boolean + droppedNotificationLog: DroppedProducerNotificationLog | null sessionIdentity: RelayClientSessionIdentity } +// Why: the log key set is rebuilt per generation, but a producer minting synthetic method names would still +// grow it inside one generation — cap it well above the fixed relay method vocabulary. +const DROPPED_NOTIFICATION_LOG_KEY_LIMIT = 64 + +const RESPONSE_OVER_CAPACITY_MESSAGE = 'Relay response exceeded the bounded transport capacity' + +type DroppedProducerNotificationLog = { + generation: number + loggedKeys: Set +} + type PendingRelayRequest = { resolve: (result: unknown) => void reject: (error: Error) => void @@ -180,6 +193,19 @@ export class RelayDispatcher { return this.publicationLedger.belowLowWater(this.activeClientKeys()) } + /** + * Same reserve as legacyRetentionBelowLowWater, but scoped to one client: a paced bulk producer + * gated on the dispatcher-wide signal stops for a peer's stall and degrades a healthy link. + * The relay-wide aggregate still counts — that ceiling is shared by every client. + */ + producerRetentionBelowLowWater(clientId: number): boolean { + const client = this.clients.get(clientId) + if (!client || client.closed) { + return false + } + return this.publicationLedger.belowLowWater([this.clientKey(client)]) + } + writePrimaryBytes(data: Buffer, lane: 'control' | 'ordinary' = 'control'): boolean { if (this.disposed || this.primaryClient.closed) { return false @@ -365,26 +391,44 @@ export class RelayDispatcher { ) } + activeClientIds(): number[] { + return this.activeClients().map((client) => client.id) + } + + // Why: signed on purpose — `budget >= 0` is an exact fits-check that a floored budget cannot express. + producerEnvelopeBudget( + method: string, + params: Record, + clientId?: number + ): number { + if (clientId !== undefined) { + const client = this.clients.get(clientId) + // Why: a detached or closed target has no room at all — reporting infinite capacity passes a + // fits-check and the frame is then dropped by the publish seam instead. + if (!client || client.closed) { + return Number.MIN_SAFE_INTEGER + } + return ( + client.writer.producerFrameCapacity - + this.estimateFrameBytes({ jsonrpc: '2.0', method, params }) + ) + } + const targets = this.activeClients() + if (targets.length === 0) { + return Number.MAX_SAFE_INTEGER + } + const frameBytes = this.estimateFrameBytes({ jsonrpc: '2.0', method, params }) + return Math.min(...targets.map((client) => client.writer.producerFrameCapacity - frameBytes)) + } + producerDataBudget( method: string, paramsWithoutData: Record, clientId?: number ): number { - const targets = - clientId === undefined - ? this.activeClients() - : [this.clients.get(clientId)].filter((client): client is RelayClient => !!client) - if (targets.length === 0) { - return Number.MAX_SAFE_INTEGER - } - const emptyFrameBytes = this.estimateFrameBytes({ - jsonrpc: '2.0', - method, - params: { ...paramsWithoutData, data: '' } - }) return Math.max( 0, - Math.min(...targets.map((client) => client.writer.producerFrameCapacity - emptyFrameBytes)) + this.producerEnvelopeBudget(method, { ...paramsWithoutData, data: '' }, clientId) ) } @@ -434,26 +478,82 @@ export class RelayDispatcher { method, ...(params !== undefined ? { params } : {}) } + const frameBytes = this.estimateFrameBytes(msg) this.runPublicationTransaction(() => { for (const client of this.clients.values()) { if (client.closed) { continue } if (method === 'pty.replay') { - this.enqueueFrame(client, msg, 'control') + // Why: replay is never re-sent, so it takes the control lane where overflow is fatal — the + // writer closes the client and reconnect reloads history rather than stranding a short buffer. + this.enqueueFrame(client, msg, 'control', undefined, frameBytes) continue } - if (!this.publishToClient(client, msg, 'ordinary')) { - this.closeClient( - client, - new Error('Relay ordinary publication capacity exceeded'), - client !== this.primaryClient - ) + // Why: closing can never make an oversized frame sendable — the producer regenerates it after + // reattach and re-kills the link, turning a recoverable drop into an endless reconnect loop. + if (!this.publishToClient(client, msg, 'ordinary', undefined, frameBytes)) { + this.logDroppedProducerNotification(client, method, frameBytes) } } }) } + // Why: producer-lane publication for a single client; notifyClient/tryNotifyClient use the control lane, + // which floods must never occupy. Rejection drops the frame and never closes the client. + publishProducerNotification( + clientId: number, + method: string, + params?: Record, + // Why: a caller that recovers from rejection itself (the watcher emitter re-sends the batch in + // chunks) would otherwise log "Dropped" for a frame it goes on to deliver in full. + options?: { logDrop?: boolean } + ): boolean { + if (this.disposed) { + return false + } + const client = this.clients.get(clientId) + if (!client || client.closed) { + return false + } + const msg: JsonRpcNotification = { + jsonrpc: '2.0', + method, + ...(params !== undefined ? { params } : {}) + } + const frameBytes = this.estimateFrameBytes(msg) + if (this.publishToClient(client, msg, 'ordinary', undefined, frameBytes)) { + return true + } + // Why: same diagnostics as notify() — a producer that drops here must not do so silently. + if (options?.logDrop !== false) { + this.logDroppedProducerNotification(client, method, frameBytes) + } + return false + } + + // Why: one line per generation, method and drop reason — a flooding producer retries every batch and would + // spam stderr, but a transient queue-full drop must not consume the slot a real over-capacity drop needs. + private logDroppedProducerNotification(client: RelayClient, method: string, bytes: number): void { + const capacity = client.writer.producerFrameCapacity + const overCapacity = bytes > capacity + const key = `${method}:${overCapacity ? 'over-capacity' : 'queue-full'}` + let log = client.droppedNotificationLog + if (!log || log.generation !== client.generation) { + log = { generation: client.generation, loggedKeys: new Set() } + client.droppedNotificationLog = log + } + if (log.loggedKeys.has(key) || log.loggedKeys.size >= DROPPED_NOTIFICATION_LOG_KEY_LIMIT) { + return + } + log.loggedKeys.add(key) + process.stderr.write( + overCapacity + ? `[relay] Dropped ${method} (${bytes}B > producer frame capacity ${capacity}B)\n` + : `[relay] Dropped ${method} (${bytes}B, producer queue full; frame capacity ${capacity}B)\n` + ) + } + notifyClient(clientId: number, method: string, params?: Record): void { this.tryNotifyClient(clientId, method, params) } @@ -462,7 +562,8 @@ export class RelayDispatcher { clientId: number, method: string, params?: Record, - onSettled: (result: SinkWriteSettlement) => void = () => {} + onSettled: (result: SinkWriteSettlement) => void = () => {}, + options: { controlOverflow?: 'close-client' | 'reject' } = {} ): boolean { if (this.disposed) { onSettled({ ok: false, error: new Error('Relay dispatcher is disposed') }) @@ -481,7 +582,9 @@ export class RelayDispatcher { ...(params !== undefined ? { params } : {}) }, 'control', - onSettled + onSettled, + undefined, + options.controlOverflow ) } @@ -646,6 +749,7 @@ export class RelayDispatcher { highestReceivedSeq: 0, generation: 0, closed: false, + droppedNotificationLog: null, sessionIdentity: sessionIdentity ?? { principal: `unproved:${id}`, authenticated: false, @@ -840,16 +944,31 @@ export class RelayDispatcher { const estimatedBytes = this.estimateFrameBytes(msg) const lane = estimatedBytes > DISPATCHER_CONTROL_QUEUE_MAX_BYTES ? 'legacy-response' : 'control' const accepted = this.enqueueFrame(client, msg, lane, onSettled) - if (!accepted) { - this.closeClient( - client, - new Error( - `Relay response exceeds the bounded ${DEFAULT_PRODUCER_QUEUE_MAX_BYTES}-byte legacy lane` - ), - client !== this.primaryClient - ) + if (accepted) { + return true } - return accepted + // Why: an oversized response must fail its own request; closing would kill every pane on the host. + // A rejected first enqueue either left onSettled untouched or closed the client, so exactly one settlement happens. + return this.enqueueFrame( + client, + { + jsonrpc: '2.0', + id, + error: { + code: RelayErrorCode.ResponseOverCapacity, + message: RESPONSE_OVER_CAPACITY_MESSAGE + } + }, + 'control', + // Why: writing the substitute is not delivering the result — a settlement fence must never read + // the capacity error's successful write as "the peer received your result". + (settlement) => + onSettled( + settlement.ok + ? { ok: false, error: new Error(RESPONSE_OVER_CAPACITY_MESSAGE) } + : settlement + ) + ) } private enqueueFrame( @@ -858,20 +977,23 @@ export class RelayDispatcher { lane: DispatcherWriterLane, onSettled: (result: SinkWriteSettlement) => void = () => {}, // Why: publish paths already sized the frame; avoid a redundant encode. - estimatedBytes?: number + estimatedBytes?: number, + controlOverflow: 'close-client' | 'reject' = 'close-client' ): boolean { if (this.disposed || client.closed) { return false } const frameBytes = estimatedBytes ?? this.estimateFrameBytes(msg) + const encode = (): Buffer => { + const seq = client.nextOutgoingSeq++ + return encodeJsonRpcFrame(msg, seq, client.highestReceivedSeq) + } return client.writer.enqueue( lane, - () => { - const seq = client.nextOutgoingSeq++ - return encodeJsonRpcFrame(msg, seq, client.highestReceivedSeq) - }, + encode, frameBytes, - onSettled + onSettled, + lane === 'control' && controlOverflow === 'reject' ) } @@ -972,9 +1094,11 @@ export class RelayDispatcher { client: RelayClient, msg: JsonRpcNotification, lane: 'interactive' | 'ordinary' | 'fixed-bulk' | 'bulk', - onSettled: (result: SinkWriteSettlement) => void = () => {} + onSettled: (result: SinkWriteSettlement) => void = () => {}, + // Why: broadcast callers size the frame once for every client; avoid a redundant encode. + estimatedBytes?: number ): boolean { - const bytes = this.estimateFrameBytes(msg) + const bytes = estimatedBytes ?? this.estimateFrameBytes(msg) const fixedBlocked = lane === 'fixed-bulk' && (client.writer.retainedProducerBytes > 0 || bytes > client.writer.fixedFrameCapacity) diff --git a/src/relay/fs-handler-file-read.ts b/src/relay/fs-handler-file-read.ts index 003172c08..14672457c 100644 --- a/src/relay/fs-handler-file-read.ts +++ b/src/relay/fs-handler-file-read.ts @@ -1,8 +1,14 @@ import { open, readFile, stat } from 'node:fs/promises' +import type { FileHandle } from 'node:fs/promises' import { extname } from 'node:path' import type { RelayDispatcher, RequestContext } from './dispatcher' -import { STREAM_ACK_WINDOW_CHUNKS, STREAM_CHUNK_SIZE, RelayErrorCode } from './protocol' -import type { RelayStreamRegistry, TooManyStreamsError } from './fs-stream-registry' +import { + MAX_CONCURRENT_STREAMS, + STREAM_ACK_WINDOW_CHUNKS, + STREAM_CHUNK_SIZE, + RelayErrorCode +} from './protocol' +import { TooManyStreamsError, type RelayStreamRegistry } from './fs-stream-registry' import { BINARY_PROBE_BYTES, IMAGE_MIME_TYPES, @@ -102,12 +108,17 @@ export async function readRelayFileStreamMetadata( return { totalSize: 0, isBinary: true, empty: true } } - const handle = await open(filePath, 'r') + // Why: reserved before the fd opens so a refusal costs nothing, and released only + // once the terminal frame settles — see reserveTerminalFrameSlot. + const releaseTerminalFrameSlot = reserveTerminalFrameSlot(registry, context.clientId) + let handle: FileHandle | undefined let streamId: number try { + handle = await open(filePath, 'r') streamId = registry.register(handle) } catch (err) { - await handle.close() + await handle?.close() + releaseTerminalFrameSlot() throw err } @@ -118,7 +129,15 @@ export async function readRelayFileStreamMetadata( // sees the response before the first chunk frame. const resolvedPumpOptions = pumpOptions ?? { paceWithAcks: false } setImmediate(() => { - void pumpChunks(streamId, stats.size, dispatcher, registry, context, resolvedPumpOptions) + void pumpChunks( + streamId, + stats.size, + dispatcher, + registry, + context, + resolvedPumpOptions, + releaseTerminalFrameSlot + ) }) return { @@ -132,16 +151,60 @@ export async function readRelayFileStreamMetadata( } } +/** + * Terminal frames (fs.streamEnd/fs.streamError) ride the control lane, which does not + * drop on overflow — it destroys the link at 256 queued frames / 1 MB. A stream's + * registry slot is gone the moment its last chunk is read, so on a socket that is not + * draining, back-to-back reads could stack one undelivered terminal frame each until + * that budget blew. Holding the slot until the frame settles keeps the number of queued + * terminal frames at MAX_CONCURRENT_STREAMS, far below the killing threshold; the + * overflow now costs one refused read (TooManyStreams, which clients already handle) + * instead of the whole connection. + * + * Counted per client, because the control queue this protects is per client: one peer whose + * socket stopped draining must not refuse reads for every other peer on the same relay. + */ +const pendingTerminalFramesByClient = new WeakMap>() + +function reserveTerminalFrameSlot(registry: RelayStreamRegistry, clientId: number): () => void { + let byClient = pendingTerminalFramesByClient.get(registry) + if (!byClient) { + byClient = new Map() + pendingTerminalFramesByClient.set(registry, byClient) + } + const pending = byClient.get(clientId) ?? 0 + if (pending >= MAX_CONCURRENT_STREAMS) { + throw new TooManyStreamsError() + } + byClient.set(clientId, pending + 1) + let released = false + return () => { + if (released) { + return + } + released = true + const remaining = (byClient.get(clientId) ?? 1) - 1 + // Drop the entry at zero so a long-lived registry cannot accumulate one per detached client. + if (remaining <= 0) { + byClient.delete(clientId) + return + } + byClient.set(clientId, remaining) + } +} + async function pumpChunks( streamId: number, totalSize: number, dispatcher: RelayDispatcher, registry: RelayStreamRegistry, context: RequestContext, - pumpOptions: StreamPumpOptions + pumpOptions: StreamPumpOptions, + releaseTerminalFrameSlot: () => void ): Promise { const entry = registry.get(streamId) if (!entry) { + releaseTerminalFrameSlot() return } const buffer = Buffer.allocUnsafe(STREAM_CHUNK_SIZE) @@ -150,6 +213,7 @@ async function pumpChunks( let endReason: 'end' | 'aborted' | 'stale' | 'error' = 'end' let errorCode: string | null = null let errorMessage: string | null = null + let slotReleaseDeferred = false try { try { @@ -226,11 +290,28 @@ async function pumpChunks( } try { + // Why: a dropped terminal frame hangs the reader forever, so it takes the control lane, which + // never drops — but that lane KILLS the link when it overflows, hence the reserved slot held + // until this frame settles. The per-chunk await already settled every chunk, so the control + // frame cannot overtake stream data. + const publishTerminal = (method: string, params: Record): void => { + if (pumpOptions.clientId === undefined) { + // Legacy broadcast path (direct calls/tests): no per-frame settlement to hold the slot on. + dispatcher.notifyControl(method, params) + return + } + slotReleaseDeferred = dispatcher.tryNotifyClient( + pumpOptions.clientId, + method, + params, + releaseTerminalFrameSlot + ) + } if (endReason === 'end') { - dispatcher.notify('fs.streamEnd', { streamId }) + publishTerminal('fs.streamEnd', { streamId }) process.stderr.write(`[relay] stream end id=${streamId}\n`) } else if (endReason === 'error') { - dispatcher.notify('fs.streamError', { + publishTerminal('fs.streamError', { streamId, code: errorCode ?? 'ESTREAMERROR', message: errorMessage ?? 'stream error' @@ -247,7 +328,12 @@ async function pumpChunks( ) } } finally { + // Why: the fd goes back first — a terminal frame that can never be delivered must not + // strand it. Cancelled/stale streams publish nothing, so nothing else frees their slot. await registry.release(streamId) + if (!slotReleaseDeferred) { + releaseTerminalFrameSlot() + } } } diff --git a/src/relay/fs-handler-stream.test.ts b/src/relay/fs-handler-stream.test.ts index c7624afce..ba6cfbf18 100644 --- a/src/relay/fs-handler-stream.test.ts +++ b/src/relay/fs-handler-stream.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import { FsHandler } from './fs-handler' import { RelayContext } from './context' import type { RelayDispatcher } from './dispatcher' -import { STREAM_CHUNK_SIZE } from './protocol' +import { MAX_CONCURRENT_STREAMS, STREAM_CHUNK_SIZE } from './protocol' import * as fs from 'node:fs/promises' import * as path from 'node:path' import { mkdtempSync, writeFileSync } from 'node:fs' @@ -10,15 +10,27 @@ import { tmpdir } from 'node:os' vi.mock('@parcel/watcher', () => ({ subscribe: vi.fn() })) -type Notification = { method: string; params?: Record } +type NotificationLane = 'producer' | 'bulk' | 'control' +type Notification = { + method: string + params?: Record + lane: NotificationLane + clientId?: number +} +type MockRequestContext = { clientId?: number; isStale: () => boolean } function createMockDispatcher() { const requestHandlers = new Map< string, - (params: Record, context?: { isStale: () => boolean }) => Promise + (params: Record, context?: MockRequestContext) => Promise >() const notificationHandlers = new Map) => void>() const notifications: Notification[] = [] + const droppedProducerFrames: Notification[] = [] + // Mirrors the real lane split: a saturated producer queue drops frames, control frames still land. + let producerSaturated = false + let holdControlSettlement = false + const heldControlSettlements: (() => void)[] = [] return { onRequest: vi.fn( ( @@ -32,16 +44,65 @@ function createMockDispatcher() { notificationHandlers.set(method, handler) }), notify: vi.fn((method: string, params?: Record) => { - notifications.push({ method, params }) + const frame: Notification = { method, params, lane: 'producer' } + if (producerSaturated) { + droppedProducerFrames.push(frame) + return + } + notifications.push(frame) }), - notifyBulk: vi.fn(async (method: string, params?: Record): Promise => { - notifications.push({ method, params }) + notifyBulk: vi.fn( + async ( + method: string, + params?: Record, + opts?: { clientId?: number } + ): Promise => { + notifications.push({ method, params, lane: 'bulk', clientId: opts?.clientId }) + } + ), + notifyClient: vi.fn((clientId: number, method: string, params?: Record) => { + notifications.push({ method, params, lane: 'control', clientId }) + }), + // Mirrors the real control lane: the frame is queued on enqueue, but settles only once the + // sink actually wrote it — holding settlement models a socket that is not draining. + tryNotifyClient: vi.fn( + ( + clientId: number, + method: string, + params?: Record, + onSettled?: (result: { ok: boolean }) => void + ): boolean => { + notifications.push({ method, params, lane: 'control', clientId }) + const settle = () => onSettled?.({ ok: true }) + if (holdControlSettlement) { + heldControlSettlements.push(settle) + } else { + settle() + } + return true + } + ), + notifyControl: vi.fn((method: string, params?: Record) => { + notifications.push({ method, params, lane: 'control' }) }), _notifications: notifications, + _droppedProducerFrames: droppedProducerFrames, + saturateProducerLane() { + producerSaturated = true + }, + holdControlSettlements() { + holdControlSettlement = true + }, + settleHeldControlFrames() { + holdControlSettlement = false + for (const settle of heldControlSettlements.splice(0)) { + settle() + } + }, callRequest( method: string, params: Record = {}, - context?: { isStale: () => boolean } + context?: MockRequestContext ) { const handler = requestHandlers.get(method) if (!handler) { @@ -138,6 +199,60 @@ describe('FsHandler readFileStream', () => { expect(reassembled.equals(content)).toBe(true) }) + it('publishes fs.streamEnd after the final fs.streamChunk and targets the same client', async () => { + const filePath = path.join(tmpDir, 'targeted.png') + writeFileSync(filePath, Buffer.alloc(300 * 1024, 0x42)) + + const meta = (await dispatcher.callRequest( + 'fs.readFileStream', + { filePath }, + { clientId: 7, isStale: () => false } + )) as { streamId: number } + + await waitFor(() => collectStream(dispatcher).end !== null) + const frames = dispatcher._notifications + const endIndex = frames.findIndex((n) => n.method === 'fs.streamEnd') + const lastChunkIndex = frames.map((n) => n.method).lastIndexOf('fs.streamChunk') + expect(lastChunkIndex).toBeGreaterThanOrEqual(0) + expect(endIndex).toBe(lastChunkIndex + 1) + expect(frames[endIndex]).toEqual({ + method: 'fs.streamEnd', + params: { streamId: meta.streamId }, + lane: 'control', + clientId: 7 + }) + expect(frames[lastChunkIndex].clientId).toBe(7) + }) + + // Real saturation is not constructible: the fixed-bulk lane admits a chunk only while producerBytes is 0, + // so a real backlog parks the chunk pump long before the terminal frame — hence the lane-tagging mock. + it('orders fs.streamEnd after the final chunk on the control lane and releases the stream', async () => { + const filePath = path.join(tmpDir, 'stream-end-release.png') + writeFileSync(filePath, Buffer.alloc(300 * 1024, 0x42)) + // Producer-lane frames now divert to the drop log, so an empty log proves no stream frame took that lane. + dispatcher.saturateProducerLane() + + const meta = (await dispatcher.callRequest( + 'fs.readFileStream', + { filePath }, + { clientId: 3, isStale: () => false } + )) as { streamId: number } + + await waitFor(() => collectStream(dispatcher).end !== null) + expect(dispatcher._droppedProducerFrames).toHaveLength(0) + expect(collectStream(dispatcher).end).toEqual({ streamId: meta.streamId }) + + const frames = dispatcher._notifications + const endIndex = frames.findIndex((n) => n.method === 'fs.streamEnd') + const lastChunkIndex = frames.map((n) => n.method).lastIndexOf('fs.streamChunk') + expect(lastChunkIndex).toBeGreaterThanOrEqual(0) + expect(endIndex).toBe(lastChunkIndex + 1) + expect(frames[endIndex].lane).toBe('control') + + const registry = (handler as unknown as { streamRegistry: { size(): number } }).streamRegistry + await waitFor(() => registry.size() === 0) + }) + it('fills protocol chunks when fs.read returns short before EOF', async () => { const filePath = path.join(tmpDir, 'short-read.png') const content = Buffer.alloc(STREAM_CHUNK_SIZE + 17, 0x42) @@ -336,6 +451,47 @@ describe('FsHandler readFileStream', () => { expect(err).toBeNull() }) + it('caps undelivered terminal frames so they cannot overflow the link-killing control lane', async () => { + const filePath = path.join(tmpDir, 'terminal-budget.png') + writeFileSync(filePath, Buffer.alloc(STREAM_CHUNK_SIZE, 0x42)) // one chunk per stream + // A socket that accepts nothing: control frames queue, and the real writer destroys the + // client once 256 of them pile up. + dispatcher.holdControlSettlements() + + const registry = (handler as unknown as { streamRegistry: { size(): number } }).streamRegistry + const context = { clientId: 5, isStale: () => false } + const terminalFrames = () => + dispatcher._notifications.filter( + (n) => n.method === 'fs.streamEnd' || n.method === 'fs.streamError' + ) + + for (let i = 0; i < MAX_CONCURRENT_STREAMS; i++) { + await dispatcher.callRequest('fs.readFileStream', { filePath }, context) + await waitFor(() => terminalFrames().length === i + 1) + } + // The fd must go back even though its terminal frame is still undelivered. + await waitFor(() => registry.size() === 0) + + await expect( + dispatcher.callRequest('fs.readFileStream', { filePath }, context) + ).rejects.toThrow(/Too many concurrent streams/) + await flush(10) + expect(terminalFrames()).toHaveLength(MAX_CONCURRENT_STREAMS) + + // The budget is per client, so a second peer on the same relay still reads. + await dispatcher.callRequest( + 'fs.readFileStream', + { filePath }, + { clientId: 9, isStale: () => false } + ) + await waitFor(() => terminalFrames().length === MAX_CONCURRENT_STREAMS + 1) + + // Draining the sink settles the queued frames and hands the budget back. + dispatcher.settleHeldControlFrames() + await dispatcher.callRequest('fs.readFileStream', { filePath }, context) + await waitFor(() => terminalFrames().length === MAX_CONCURRENT_STREAMS + 2) + }) + it('rejects the 17th concurrent stream with TooManyStreams', async () => { const paths: string[] = [] for (let i = 0; i < 17; i++) { diff --git a/src/relay/protocol.ts b/src/relay/protocol.ts index 0fbd85cc8..8cb4ab57a 100644 --- a/src/relay/protocol.ts +++ b/src/relay/protocol.ts @@ -102,7 +102,10 @@ export type GitResponseStreamMarker = { export const RelayErrorCode = { TooManyStreams: -33006, - StreamProtocolError: -33007 + StreamProtocolError: -33007, + /** Substituted for a response too large for the sink's frame capacity; the request fails + * instead of the whole link, so a caller can retry with a narrower scope. */ + ResponseOverCapacity: -33008 } as const export type JsonRpcRequest = { diff --git a/src/relay/relay-filesystem-watch-registry.test.ts b/src/relay/relay-filesystem-watch-registry.test.ts index 8c4c0134a..0c6109a55 100644 --- a/src/relay/relay-filesystem-watch-registry.test.ts +++ b/src/relay/relay-filesystem-watch-registry.test.ts @@ -61,11 +61,38 @@ class FakeWatcherPool { function createDispatcher() { const detached = new Set<(clientId: number) => void>() + // Batches ride the producer lane and markers the control lane, so record both in one ordered log. + const fsChanged: Record[] = [] + const record = (_clientId: number, method: string, params?: Record): void => { + if (method === 'fs.changed' && params) { + fsChanged.push(params) + } + } return { + fsChanged, notify: vi.fn(), - notifyClient: vi.fn(), - broadcastProducerFrameCapacity: vi.fn(() => Number.MAX_SAFE_INTEGER), - notificationFrameBytes: vi.fn(() => 64), + notifyClient: vi.fn(record), + tryNotifyClient: vi.fn( + ( + clientId: number, + method: string, + params?: Record, + onSettled?: (result: { ok: true } | { ok: false; error: Error }) => void + ) => { + record(clientId, method, params) + // A healthy sink settles as the frame is written, which releases the emitter's outstanding-marker slot. + onSettled?.({ ok: true }) + return true + } + ), + activeClientIds: vi.fn(() => [1]), + producerEnvelopeBudget: vi.fn(() => Number.MAX_SAFE_INTEGER), + publishProducerNotification: vi.fn( + (clientId: number, method: string, params?: Record) => { + record(clientId, method, params) + return true + } + ), onClientDetached: vi.fn((listener: (clientId: number) => void) => { detached.add(listener) return () => detached.delete(listener) @@ -73,6 +100,10 @@ function createDispatcher() { } } +function watchFailedCalls(dispatcher: ReturnType): unknown[][] { + return dispatcher.notifyClient.mock.calls.filter(([, method]) => method === 'fs.watchFailed') +} + function context(clientId: number): RequestContext { return { clientId, isStale: () => false } } @@ -96,10 +127,10 @@ describe('RelayFilesystemWatchRegistry', () => { first.hooks.onInterruption?.() first.callback(null, [{ type: 'update', path: '/repo/after-resubscribe.txt' }]) - expect(dispatcher.notify.mock.calls).toEqual([ - ['fs.changed', { events: [{ kind: 'create', absolutePath: '/repo/before.txt' }] }], - ['fs.changed', { events: [{ kind: 'overflow', absolutePath: '/repo' }] }], - ['fs.changed', { events: [{ kind: 'update', absolutePath: '/repo/after-resubscribe.txt' }] }] + expect(dispatcher.fsChanged).toEqual([ + { events: [{ kind: 'create', absolutePath: '/repo/before.txt' }] }, + { events: [{ kind: 'overflow', absolutePath: '/repo' }] }, + { events: [{ kind: 'update', absolutePath: '/repo/after-resubscribe.txt' }] } ]) }) @@ -118,12 +149,10 @@ describe('RelayFilesystemWatchRegistry', () => { expect(pool.installed).toHaveLength(2) pool.installed[1].callback(null, [{ type: 'create', path: '/repo/recovered.txt' }]) - expect(dispatcher.notify).toHaveBeenNthCalledWith(1, 'fs.changed', { - events: [{ kind: 'overflow', absolutePath: '/repo' }] - }) - expect(dispatcher.notify).toHaveBeenNthCalledWith(2, 'fs.changed', { - events: [{ kind: 'create', absolutePath: '/repo/recovered.txt' }] - }) + expect(dispatcher.fsChanged).toEqual([ + { events: [{ kind: 'overflow', absolutePath: '/repo' }] }, + { events: [{ kind: 'create', absolutePath: '/repo/recovered.txt' }] } + ]) registry.unwatch('/repo', context(1)) expect(pool.installed[1].unsubscribe).not.toHaveBeenCalled() @@ -145,17 +174,19 @@ describe('RelayFilesystemWatchRegistry', () => { ) ) - await vi.waitFor(() => expect(dispatcher.notifyClient).toHaveBeenCalledTimes(2)) - expect(dispatcher.notifyClient).toHaveBeenNthCalledWith(1, 1, 'fs.watchFailed', { - rootPath: '/repo', - watchId: 101, - message: 'quarantine recovery failed' - }) - expect(dispatcher.notifyClient).toHaveBeenNthCalledWith(2, 2, 'fs.watchFailed', { - rootPath: '/repo', - watchId: 202, - message: 'quarantine recovery failed' - }) + await vi.waitFor(() => expect(watchFailedCalls(dispatcher)).toHaveLength(2)) + expect(watchFailedCalls(dispatcher)).toEqual([ + [ + 1, + 'fs.watchFailed', + { rootPath: '/repo', watchId: 101, message: 'quarantine recovery failed' } + ], + [ + 2, + 'fs.watchFailed', + { rootPath: '/repo', watchId: 202, message: 'quarantine recovery failed' } + ] + ]) }) it('aborts a pending crawl only after the last same-root client leaves', async () => { @@ -400,21 +431,18 @@ describe('createRelayWatcherProcessPool', () => { expect(recoveredWatches.map((watches) => watches.map(({ dir }) => dir))).toEqual( roots.map((root) => [root]) ) - expect(dispatcher.notify.mock.calls.slice(0, roots.length)).toEqual( - roots.map((root) => ['fs.changed', { events: [{ kind: 'overflow', absolutePath: root }] }]) + expect(dispatcher.fsChanged.slice(0, roots.length)).toEqual( + roots.map((root) => ({ events: [{ kind: 'overflow', absolutePath: root }] })) ) for (const watches of recoveredWatches) { const [{ callback, dir }] = watches callback(null, [{ type: 'update', path: join(dir, 'recovered.txt') }]) } - expect(dispatcher.notify.mock.calls.slice(roots.length)).toEqual( - roots.map((root) => [ - 'fs.changed', - { - events: [{ kind: 'update', absolutePath: join(root, 'recovered.txt') }] - } - ]) + expect(dispatcher.fsChanged.slice(roots.length)).toEqual( + roots.map((root) => ({ + events: [{ kind: 'update', absolutePath: join(root, 'recovered.txt') }] + })) ) } finally { registry.dispose() diff --git a/src/relay/relay-filesystem-watch-registry.ts b/src/relay/relay-filesystem-watch-registry.ts index 4acb786fa..de583b2f5 100644 --- a/src/relay/relay-filesystem-watch-registry.ts +++ b/src/relay/relay-filesystem-watch-registry.ts @@ -223,7 +223,7 @@ export class RelayFilesystemWatchRegistry { emitOverflow() return } - emitRelayWatcherEvents(this.dispatcher, state.closed, events) + emitRelayWatcherEvents(this.dispatcher, state.rootPath, state.closed, events) }, RELAY_WATCH_OPTIONS, { diff --git a/src/relay/relay-oversized-notification-survival.test.ts b/src/relay/relay-oversized-notification-survival.test.ts new file mode 100644 index 000000000..41d3dd833 --- /dev/null +++ b/src/relay/relay-oversized-notification-survival.test.ts @@ -0,0 +1,270 @@ +import { describe, expect, it } from 'vitest' +import { RelayDispatcher } from './dispatcher' +import { relayWriterControlReserve } from './dispatcher-writer-admission' +import { encodeJsonRpcFrame, HEADER_LENGTH, parseJsonRpcMessage } from './protocol' +import { + AGENT_HOOK_NOTIFICATION_METHOD, + type AgentHookRelayEnvelope +} from '../shared/agent-hook-relay' +import { MAX_BATCHED_WATCHER_EVENTS } from '../main/ipc/filesystem-watcher-event-batch' +import { emitRelayWatcherEvents } from './relay-watcher-event-emitter' +import { publishAgentHookEnvelope } from './agent-hook-envelope-publication' +import type { WatcherProcessEvent } from '../main/ipc/parcel-watcher-process' +import { + AGENT_STATUS_ASSISTANT_MESSAGE_MAX_LENGTH, + AGENT_STATUS_INTERACTIVE_PROMPT_MAX_LENGTH, + AGENT_STATUS_MAX_SUBAGENTS, + normalizeAgentStatusPayload +} from '../shared/agent-status-types' + +// The relay runs on the REMOTE host, so the stream default is that host's Node major. +const NODE22_HWM = 64 * 1024 // Node >= 22 default +const NODE21_HWM = 16 * 1024 // Node <= 21 default + +const WATCHER_ROOT = '/home/dev/project' + +function capacityFor(hwm: number): number { + return hwm - relayWriterControlReserve(hwm) +} + +/** Largest envelope the normalizer accepts: every field at its own documented cap. */ +function buildMaximalHookEnvelope(): Record { + const payload = normalizeAgentStatusPayload({ + state: 'waiting', + prompt: 'x'.repeat(200), + interactivePrompt: 'q'.repeat(AGENT_STATUS_INTERACTIVE_PROMPT_MAX_LENGTH), + lastAssistantMessage: 'a'.repeat(AGENT_STATUS_ASSISTANT_MESSAGE_MAX_LENGTH), + toolName: 'Bash', + toolInput: 'i'.repeat(160), + model: 'claude-opus-5', + agentType: 'general-purpose', + subagents: Array.from({ length: AGENT_STATUS_MAX_SUBAGENTS }, (_, i) => ({ + id: `subagent-${i}`.padEnd(64, '0'), + state: 'working', + agentType: 'general-purpose', + model: 'claude-opus-5', + toolName: 'Grep', + toolInput: 'i'.repeat(160) + })) + }) + expect(payload, 'normalizer must accept this payload').not.toBeNull() + return { + paneKey: 'worktree-abc:0f2c1d84-3b9a-4c77-9d21-5e6f7a8b9c0d', + connectionId: 'ssh-target-1', + tabId: 'tab-1', + worktreeId: 'wt-1', + hookEventName: 'Notification', + payload + } as unknown as Record +} + +function watcherProcessEvents(count: number): WatcherProcessEvent[] { + return Array.from({ length: count }, (_, i) => ({ + type: 'update', + path: `${WATCHER_ROOT}/node_modules/.vite/deps/chunk-${String(i).padStart(6, '0')}.js` + })) as unknown as WatcherProcessEvent[] +} + +/** The exact `fs.changed` params emitRelayWatcherEvents publishes, so the pinned sizes measure reality. */ +function buildWatcherBatch(count: number): Record { + return { + events: watcherProcessEvents(count).map((event) => ({ + kind: event.type, + absolutePath: event.path + })) + } +} + +function frameBytes(method: string, params: Record): number { + return encodeJsonRpcFrame({ jsonrpc: '2.0', method, params }, 1, 0).length +} + +function frameParams(frame: Buffer): Record { + const payloadLength = frame.readUInt32BE(9) + const message = parseJsonRpcMessage(frame.subarray(HEADER_LENGTH, HEADER_LENGTH + payloadLength)) + return 'method' in message ? ((message.params ?? {}) as Record) : {} +} + +function createDispatcher(hwm: number, onClose: () => void, sink: Buffer[]): RelayDispatcher { + return new RelayDispatcher( + (data: Buffer) => { + sink.push(data) + return true + }, + { + writableHighWaterMark: () => hwm, + writableLength: () => 0, + supportsWriteCallback: false, + close: onClose + } + ) +} + +describe('relay oversized notification survival', () => { + // Without this the byte measurements below could describe a payload the emitter never sends. + it('measures the params emitRelayWatcherEvents actually publishes', () => { + const sink: Buffer[] = [] + const dispatcher = createDispatcher(NODE22_HWM, () => {}, sink) + + try { + emitRelayWatcherEvents(dispatcher, WATCHER_ROOT, false, watcherProcessEvents(1)) + expect(sink).toHaveLength(1) + expect(frameParams(sink[0])).toEqual(buildWatcherBatch(1)) + } finally { + dispatcher.dispose() + } + }) + + it('measures both producers against both Node tiers', () => { + const hookBytes = frameBytes(AGENT_HOOK_NOTIFICATION_METHOD, buildMaximalHookEnvelope()) + const fullBatchBytes = frameBytes('fs.changed', buildWatcherBatch(MAX_BATCHED_WATCHER_EVENTS)) + + // Binary-search the largest watcher batch that still fits each tier. + const trip = (cap: number): number => { + let lo = 1 + let hi = MAX_BATCHED_WATCHER_EVENTS + while (lo < hi) { + const mid = Math.ceil((lo + hi) / 2) + if (frameBytes('fs.changed', buildWatcherBatch(mid)) <= cap) { + lo = mid + } else { + hi = mid - 1 + } + } + return lo + } + + // Capacity is a fixed fraction of the sink's high-water mark, so these are exact. + expect(capacityFor(NODE22_HWM)).toBe(49152) + expect(capacityFor(NODE21_HWM)).toBe(12288) + + // agent.hook: fits a modern remote, over-cap on an older one — which is why the remote's + // Node major, not Orca's, decides whether a maximal envelope has to shed. + expect(hookBytes).toBeLessThan(capacityFor(NODE22_HWM)) + expect(hookBytes).toBeGreaterThan(capacityFor(NODE21_HWM)) + + // fs.changed: the batch cap is orders of magnitude above what one frame can carry, on BOTH tiers. + expect(fullBatchBytes).toBeGreaterThan(capacityFor(NODE22_HWM)) + expect(trip(capacityFor(NODE22_HWM)) * 5).toBeLessThan(MAX_BATCHED_WATCHER_EVENTS) + expect(trip(capacityFor(NODE21_HWM))).toBeLessThan(trip(capacityFor(NODE22_HWM))) + }) + + it('a 5000-event fs.changed no longer closes the client on a Node>=22-sized sink', () => { + const sink: Buffer[] = [] + let closes = 0 + const dispatcher = createDispatcher(NODE22_HWM, () => (closes += 1), sink) + + try { + dispatcher.notify('pty.exit', { id: 'pty-1', exitCode: 0 }) + const before = sink.length + expect(before).toBeGreaterThan(0) + + // The batch the registry is configured to allow (maxEventsPerBatch = MAX_BATCHED_WATCHER_EVENTS). + emitRelayWatcherEvents( + dispatcher, + WATCHER_ROOT, + false, + watcherProcessEvents(MAX_BATCHED_WATCHER_EVENTS) + ) + expect(closes).toBe(0) + expect(sink.length).toBeGreaterThan(before) + expect(sink.every((frame) => frame.length <= capacityFor(NODE22_HWM))).toBe(true) + + // The link is still live: the next frame reaches the sink. + const afterBatch = sink.length + dispatcher.notify('pty.exit', { id: 'pty-2', exitCode: 0 }) + expect(sink.length).toBe(afterBatch + 1) + } finally { + dispatcher.dispose() + } + }) + + it('a maximal agent.hook envelope survives a Node<=21-sized sink through publishAgentHookEnvelope', () => { + const sink: Buffer[] = [] + let closes = 0 + const dispatcher = createDispatcher(NODE21_HWM, () => (closes += 1), sink) + + try { + publishAgentHookEnvelope( + dispatcher, + buildMaximalHookEnvelope() as unknown as AgentHookRelayEnvelope + ) + + expect(closes).toBe(0) + expect(sink).toHaveLength(1) + expect(sink[0].length).toBeLessThanOrEqual(capacityFor(NODE21_HWM)) + + const params = frameParams(sink[0]) + expect(params.paneKey).toBe('worktree-abc:0f2c1d84-3b9a-4c77-9d21-5e6f7a8b9c0d') + expect(params.connectionId).toBe('ssh-target-1') + const payload = params.payload as Record + expect(payload.state).toBe('waiting') + expect(payload.lastAssistantMessage).toBeUndefined() + } finally { + dispatcher.dispose() + } + }) + + it("publishAgentHookEnvelope does not mutate the caller's envelope", () => { + const sink: Buffer[] = [] + const dispatcher = createDispatcher(NODE21_HWM, () => {}, sink) + const envelope = buildMaximalHookEnvelope() + const before = structuredClone(envelope) + + try { + publishAgentHookEnvelope(dispatcher, envelope as unknown as AgentHookRelayEnvelope) + // The hook server replays this exact object after --connect, so shedding must never touch it. + expect(envelope).toEqual(before) + } finally { + dispatcher.dispose() + } + }) + + it('reattach + replay does not re-kill', () => { + const sink: Buffer[] = [] + let killCloses = 0 + let retiredSinkCloses = 0 + let replacingSink = false + // setWrite deliberately closes the sink it retires; only a close on the LIVE sink is a kill. + const onClose = (): void => { + if (replacingSink) { + retiredSinkCloses += 1 + } else { + killCloses += 1 + } + } + const dispatcher = createDispatcher(NODE21_HWM, onClose, sink) + const envelope = buildMaximalHookEnvelope() as unknown as AgentHookRelayEnvelope + + try { + publishAgentHookEnvelope(dispatcher, envelope) + expect(sink).toHaveLength(1) + + for (let reconnect = 0; reconnect < 4; reconnect += 1) { + // Real reattach: relay.ts swaps the sink onto the new SSH channel, then the + // hook server replays its per-paneKey cache (agent-hook-server.ts). + replacingSink = true + dispatcher.setWrite( + (data: Buffer) => { + sink.push(data) + return true + }, + { + writableHighWaterMark: () => NODE21_HWM, + writableLength: () => 0, + supportsWriteCallback: false, + close: onClose + } + ) + replacingSink = false + publishAgentHookEnvelope(dispatcher, envelope) + } + + expect(killCloses).toBe(0) + expect(retiredSinkCloses).toBe(4) + expect(sink).toHaveLength(5) + } finally { + dispatcher.dispose() + } + }) +}) diff --git a/src/relay/relay-watcher-event-emitter.test.ts b/src/relay/relay-watcher-event-emitter.test.ts index ae5781c57..35b448e85 100644 --- a/src/relay/relay-watcher-event-emitter.test.ts +++ b/src/relay/relay-watcher-event-emitter.test.ts @@ -1,51 +1,618 @@ -import { describe, expect, it } from 'vitest' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { describe, expect, it, vi } from 'vitest' +import type { WatcherProcessEvent } from '../main/ipc/parcel-watcher-process-protocol' import { RelayDispatcher } from './dispatcher' +import { + DEFAULT_PRODUCER_QUEUE_MAX_BYTES, + DISPATCHER_CONTROL_QUEUE_MAX_FRAMES +} from './dispatcher-writer-admission' +import type { RelayClientSinkOptions, RelayClientWrite } from './dispatcher-writer-sink' +import { LEGACY_CLIENT_RETAINED_BYTES_LOW } from './legacy-relay-publication-ledger' import { HEADER_LENGTH, parseJsonRpcMessage } from './protocol' import { emitRelayWatcherEvents, emitRelayWatcherOverflow } from './relay-watcher-event-emitter' -function frameMethod(frame: Buffer): string { +type WatcherFrameEvent = { kind: string; absolutePath: string; isDirectory?: boolean } + +function frameMessage(frame: Buffer): { method: string; params?: Record } { const payloadLength = frame.readUInt32BE(9) const message = parseJsonRpcMessage(frame.subarray(HEADER_LENGTH, HEADER_LENGTH + payloadLength)) - return 'method' in message ? message.method : '' + return 'method' in message + ? { method: message.method, params: message.params as Record | undefined } + : { method: '' } +} + +function frameMethod(frame: Buffer): string { + return frameMessage(frame).method +} + +function frameEvents(frame: Buffer): WatcherFrameEvent[] { + const params = frameMessage(frame).params + return (params?.events ?? []) as WatcherFrameEvent[] +} + +function createRecordingSink(highWaterMark?: number): { + frames: Buffer[] + closes: () => number + drainWaiters: (() => void)[] + blockNextWrite: () => void + write: RelayClientWrite + options: RelayClientSinkOptions +} { + const frames: Buffer[] = [] + const drainWaiters: (() => void)[] = [] + let closes = 0 + let blocked = false + const write: RelayClientWrite = (frame) => { + frames.push(Buffer.from(frame)) + if (blocked) { + blocked = false + return false + } + return true + } + const options: RelayClientSinkOptions = { + ...(highWaterMark === undefined ? {} : { writableHighWaterMark: () => highWaterMark }), + close: () => { + closes += 1 + }, + waitWriteDrain: (callback) => { + drainWaiters.push(callback) + return () => { + const index = drainWaiters.indexOf(callback) + if (index >= 0) { + drainWaiters.splice(index, 1) + } + } + } + } + return { + frames, + closes: () => closes, + drainWaiters, + blockNextWrite: () => { + blocked = true + }, + write, + options + } +} + +function watcherBatch(count: number): { type: 'create'; path: string; isDirectory: false }[] { + return Array.from({ length: count }, (_unused, index) => ({ + type: 'create' as const, + path: `/workspace/project/src/module-${index}/component-${index}.tsx`, + isDirectory: false as const + })) +} + +function parentDir(absolutePath: string): string { + return absolutePath.slice(0, absolutePath.lastIndexOf('/')) +} + +// Fills the 2 MB producer queue so every subsequent watcher batch is rejected on the producer lane. +function saturateProducerQueue(dispatcher: RelayDispatcher): void { + let admitted = 0 + for (const chunk of [40_000, 1_000, 1]) { + while ( + admitted < 5_000 && + dispatcher.tryNotifyPtyData({ paneId: 'pane', data: 'x'.repeat(chunk) }) + ) { + admitted += 1 + } + } + expect(admitted).toBeGreaterThan(0) + expect(admitted).toBeLessThan(5_000) +} + +// Parks PTY frames in the producer queue of a stalled sink without filling it. +function parkProducerBytes(dispatcher: RelayDispatcher, bytes: number): number { + const chunk = 'x'.repeat(40_000) + let parked = 0 + while (parked < bytes && dispatcher.tryNotifyPtyData({ paneId: 'pane', data: chunk })) { + parked += chunk.length + } + expect(parked).toBeGreaterThanOrEqual(bytes) + return parked +} + +// Parks PTY frames in ONE client's producer queue, leaving every peer's retention untouched. +function parkProducerBytesForClient( + dispatcher: RelayDispatcher, + clientId: number, + bytes: number +): number { + const chunk = 'x'.repeat(40_000) + let parked = 0 + while ( + parked < bytes && + dispatcher.publishProducerNotification(clientId, 'pty.data', { paneId: 'pane', data: chunk }) + ) { + parked += chunk.length + } + expect(parked).toBeGreaterThanOrEqual(bytes) + return parked +} + +function isOverflowFrame(frame: Buffer): boolean { + return frameEvents(frame).some((event) => event.kind === 'overflow') +} + +function watcherFrames(frames: readonly Buffer[]): Buffer[] { + return frames.filter((frame) => frameMethod(frame) === 'fs.changed') +} + +function deliveredEvents(events: readonly WatcherProcessEvent[]): WatcherFrameEvent[] { + return events.map((event) => ({ + kind: event.type, + absolutePath: event.path, + ...(event.isDirectory === undefined ? {} : { isDirectory: event.isDirectory }) + })) } describe('relay watcher writer admission', () => { - it('keeps watcher batches on the bounded ordinary lane under saturation', () => { - const frames: Buffer[] = [] - const drainWaiters: (() => void)[] = [] - let saturate = true - const dispatcher = new RelayDispatcher( - (frame) => { - frames.push(Buffer.from(frame)) - if (saturate) { - saturate = false - return false - } - return true - }, - { - waitWriteDrain: (callback) => { - drainWaiters.push(callback) - return () => { - const index = drainWaiters.indexOf(callback) - if (index >= 0) { - drainWaiters.splice(index, 1) - } - } - } - } - ) + it('keeps watcher batches on the producer lane while overflow markers ride the control lane', () => { + const sink = createRecordingSink() + sink.blockNextWrite() + const dispatcher = new RelayDispatcher(sink.write, sink.options) try { - emitRelayWatcherEvents(dispatcher, false, [ + emitRelayWatcherEvents(dispatcher, '/workspace', false, [ { type: 'create', path: '/workspace/first', isDirectory: false } ]) emitRelayWatcherOverflow(dispatcher, '/workspace', false) dispatcher.notifyClient(1, 'control.event') - expect(frames.map(frameMethod)).toEqual(['fs.changed']) - drainWaiters.shift()?.() - expect(frames.map(frameMethod)).toEqual(['fs.changed', 'control.event', 'fs.changed']) + expect(sink.frames.map(frameMethod)).toEqual(['fs.changed']) + sink.drainWaiters.shift()?.() + // The marker now shares the control lane with control.event and drains ahead of the producer lanes. + expect(sink.frames.map(frameMethod)).toEqual(['fs.changed', 'fs.changed', 'control.event']) + expect(frameEvents(sink.frames[1])).toEqual([ + { kind: 'overflow', absolutePath: '/workspace' } + ]) + } finally { + dispatcher.dispose() + } + }) +}) + +describe('relay watcher overflow suppression key', () => { + it('keeps the source free of NUL bytes so git and grep still see text', () => { + const source = readFileSync( + fileURLToPath(new URL('./relay-watcher-event-emitter.ts', import.meta.url)) + ) + expect(source.includes(0)).toBe(false) + }) + + it('scopes the outstanding marker per client as well as per root', () => { + const primary = createRecordingSink(65536) + const secondary = createRecordingSink(65536) + primary.blockNextWrite() + secondary.blockNextWrite() + const dispatcher = new RelayDispatcher(primary.write, primary.options) + + try { + dispatcher.attachClient(secondary.write, secondary.options) + // Two clients, same root: a key that collapses them would silently desync the second tree. + emitRelayWatcherOverflow(dispatcher, '/workspace', false) + primary.drainWaiters.shift()?.() + secondary.drainWaiters.shift()?.() + + for (const sink of [primary, secondary]) { + expect(sink.frames.filter((frame) => frameMethod(frame) === 'fs.changed')).toHaveLength(1) + expect(sink.closes()).toBe(0) + } + } finally { + dispatcher.dispose() + } + }) + + it('releases the outstanding key when notification admission rejects without settlement', () => { + const sink = createRecordingSink(65536) + const dispatcher = new RelayDispatcher(sink.write, sink.options) + const notify = vi.spyOn(dispatcher, 'tryNotifyClient').mockReturnValue(false) + + try { + emitRelayWatcherOverflow(dispatcher, '/workspace', false) + emitRelayWatcherOverflow(dispatcher, '/workspace', false) + expect(notify).toHaveBeenCalledTimes(2) + } finally { + notify.mockRestore() + dispatcher.dispose() + } + }) + + it('fails soft and releases the outstanding key when the control queue is full', () => { + const sink = createRecordingSink(65536) + sink.blockNextWrite() + const dispatcher = new RelayDispatcher(sink.write, sink.options) + + try { + const clientId = dispatcher.activeClientIds()[0] + for (let index = 0; index < DISPATCHER_CONTROL_QUEUE_MAX_FRAMES; index += 1) { + dispatcher.notifyClient(clientId, `control.${index}`) + } + + emitRelayWatcherOverflow(dispatcher, '/workspace', false) + expect(watcherFrames(sink.frames)).toHaveLength(0) + expect(sink.closes()).toBe(0) + + sink.drainWaiters.shift()?.() + emitRelayWatcherOverflow(dispatcher, '/workspace', false) + expect(watcherFrames(sink.frames).flatMap(frameEvents)).toEqual([ + { kind: 'overflow', absolutePath: '/workspace' } + ]) + expect(sink.closes()).toBe(0) + } finally { + dispatcher.dispose() + } + }) +}) + +describe('relay watcher batch chunking', () => { + it.each([ + [65536, 49152], + [16384, 12288] + ])('splits a 5000-event batch into frames that fit a %i-byte sink', (highWaterMark, capacity) => { + const sink = createRecordingSink(highWaterMark) + const dispatcher = new RelayDispatcher(sink.write, sink.options) + const events = watcherBatch(5000) + + try { + emitRelayWatcherEvents(dispatcher, '/workspace', false, events) + + expect(sink.frames.length).toBeGreaterThan(1) + expect(sink.frames.every((frame) => frameMethod(frame) === 'fs.changed')).toBe(true) + expect(sink.frames.every((frame) => frame.length <= capacity)).toBe(true) + expect(sink.frames.flatMap(frameEvents)).toEqual( + events.map((event) => ({ + kind: event.type, + absolutePath: event.path, + isDirectory: event.isDirectory + })) + ) + expect(sink.closes()).toBe(0) + } finally { + dispatcher.dispose() + } + }) + + it('encodes the empty envelope once instead of re-encoding candidate chunks', () => { + const sink = createRecordingSink(16384) + const dispatcher = new RelayDispatcher(sink.write, sink.options) + const budget = vi.spyOn(dispatcher, 'producerEnvelopeBudget') + + try { + emitRelayWatcherEvents(dispatcher, '/workspace', false, watcherBatch(5000)) + expect(budget).toHaveBeenCalledTimes(1) + expect(sink.frames.flatMap(frameEvents)).toHaveLength(5000) + } finally { + budget.mockRestore() + dispatcher.dispose() + } + }) + + it('sizes each event once across clients that need different chunk cuts', () => { + const primary = createRecordingSink(16384) + const secondary = createRecordingSink(65536) + const dispatcher = new RelayDispatcher(primary.write, primary.options) + const stringify = vi.spyOn(JSON, 'stringify') + const events = watcherBatch(5000) + + try { + dispatcher.attachClient(secondary.write, secondary.options) + emitRelayWatcherEvents(dispatcher, '/workspace', false, events) + + const sizedEvents = stringify.mock.calls.filter(([value]) => { + if (typeof value !== 'object' || value === null) { + return false + } + return 'kind' in value && 'absolutePath' in value + }) + expect(sizedEvents).toHaveLength(events.length) + expect(primary.frames.flatMap(frameEvents)).toHaveLength(events.length) + expect(secondary.frames.flatMap(frameEvents)).toHaveLength(events.length) + } finally { + stringify.mockRestore() + dispatcher.dispose() + } + }) + + it('falls back to one overflow marker when a single event exceeds the frame budget', () => { + const sink = createRecordingSink(65536) + const dispatcher = new RelayDispatcher(sink.write, sink.options) + + try { + emitRelayWatcherEvents(dispatcher, '/workspace', false, [ + { type: 'update', path: `/workspace/${'p'.repeat(60_000)}`, isDirectory: false } + ]) + + expect(sink.frames.map(frameMethod)).toEqual(['fs.changed']) + expect(frameEvents(sink.frames[0])).toEqual([ + { kind: 'overflow', absolutePath: '/workspace' } + ]) + expect(sink.closes()).toBe(0) + } finally { + dispatcher.dispose() + } + }) + + it('emits the overflow marker on the control lane when a chunk is rejected by a full producer queue', () => { + const sink = createRecordingSink(65536) + sink.blockNextWrite() + const dispatcher = new RelayDispatcher(sink.write, sink.options) + + try { + // Fill the 2 MB producer queue down to a residue smaller than a one-event fs.changed frame. + saturateProducerQueue(dispatcher) + + emitRelayWatcherEvents(dispatcher, '/workspace', false, [ + { type: 'create', path: '/workspace/first', isDirectory: false } + ]) + sink.drainWaiters.shift()?.() + + const markers = sink.frames.filter((frame) => frameMethod(frame) === 'fs.changed') + expect(markers).toHaveLength(1) + expect(frameEvents(markers[0])).toEqual([{ kind: 'overflow', absolutePath: '/workspace' }]) + // Control lane preempts: the marker lands before the producer frames still queued behind it. + expect(sink.frames.indexOf(markers[0])).toBeLessThan(sink.frames.length - 1) + expect(sink.closes()).toBe(0) + } finally { + dispatcher.dispose() + } + }) + + it('keeps at most one outstanding overflow marker per root without closing the client', () => { + const sink = createRecordingSink(65536) + sink.blockNextWrite() + const dispatcher = new RelayDispatcher(sink.write, sink.options) + + try { + saturateProducerQueue(dispatcher) + + // More rejected batches than the 256-frame control queue can hold: one marker each would close the link. + for (let index = 0; index < 300; index += 1) { + emitRelayWatcherEvents(dispatcher, '/workspace', false, [ + { type: 'create', path: `/workspace/file-${index}`, isDirectory: false } + ]) + } + // A second root must still get its own marker, or that tree silently desyncs. + emitRelayWatcherEvents(dispatcher, '/other', false, [ + { type: 'create', path: '/other/file', isDirectory: false } + ]) + expect(sink.closes()).toBe(0) + + sink.drainWaiters.shift()?.() + const markers = sink.frames + .filter((frame) => frameMethod(frame) === 'fs.changed') + .flatMap(frameEvents) + expect(markers).toEqual([ + { kind: 'overflow', absolutePath: '/workspace' }, + { kind: 'overflow', absolutePath: '/other' } + ]) + expect(sink.closes()).toBe(0) + + // The slot clears once the marker drains, so a later batch can still resync the same root. + emitRelayWatcherEvents(dispatcher, '/workspace', false, [ + { type: 'create', path: '/workspace/later', isDirectory: false } + ]) + expect( + sink.frames.filter((frame) => frameMethod(frame) === 'fs.changed').flatMap(frameEvents) + ).toHaveLength(3) + } finally { + dispatcher.dispose() + } + }) + + it('keeps one directory in one chunk when the batch interleaves directories', () => { + const sink = createRecordingSink(16384) + const dispatcher = new RelayDispatcher(sink.write, sink.options) + const directoryCount = 8 + const replacedPath = '/workspace/project/src/module-7/component-0.tsx' + const events: WatcherProcessEvent[] = [ + ...Array.from({ length: 200 }, (_unused, index) => ({ + type: 'create' as const, + path: `/workspace/project/src/module-${index % directoryCount}/component-${Math.floor(index / directoryCount)}.tsx`, + isDirectory: false + })), + { type: 'delete' as const, path: replacedPath } + ] + + try { + emitRelayWatcherEvents(dispatcher, '/workspace', false, events) + + expect(sink.frames.length).toBeGreaterThan(1) + const frameDirs = sink.frames.map( + (frame) => new Set(frameEvents(frame).map((event) => parentDir(event.absolutePath))) + ) + const dirs = Array.from(new Set(events.map((event) => parentDir(event.path)))) + expect(dirs).toHaveLength(directoryCount) + // Each directory in one frame; the renderer dedupes refreshes per payload, so extra frames = extra readDir RPCs. + const refreshes = frameDirs.reduce((total, frameDir) => total + frameDir.size, 0) + expect(refreshes).toBeLessThanOrEqual(directoryCount + sink.frames.length - 1) + + const delivered = sink.frames.flatMap(frameEvents) + for (const dir of dirs) { + const positions = delivered + .map((event, index) => ({ event, index })) + .filter((entry) => parentDir(entry.event.absolutePath) === dir) + .map((entry) => entry.index) + expect(positions.at(-1)! - positions[0]).toBe(positions.length - 1) + } + // Stable grouping keeps per-path order: the create still precedes the delete of the same path. + expect( + delivered.filter((event) => event.absolutePath === replacedPath).map((event) => event.kind) + ).toEqual(['create', 'delete']) + expect(delivered).toHaveLength(events.length) + } finally { + dispatcher.dispose() + } + }) + + it('does not report a drop for a batch it goes on to deliver in full', () => { + const sink = createRecordingSink(16384) + const dispatcher = new RelayDispatcher(sink.write, sink.options) + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + + try { + const events = watcherBatch(5000) + emitRelayWatcherEvents(dispatcher, '/workspace', false, events) + + expect(sink.frames.length).toBeGreaterThan(1) + expect(sink.frames.flatMap(frameEvents)).toHaveLength(events.length) + // A "Dropped fs.changed" line here would both lie and burn the one-per-generation + // suppression slot a genuine over-capacity drop needs. + const lines = stderr.mock.calls.map(([line]) => String(line)) + expect(lines.filter((line) => line.includes('fs.changed'))).toEqual([]) + } finally { + stderr.mockRestore() + dispatcher.dispose() + } + }) + + it('sizes chunks near the byte minimum instead of overshooting it', () => { + const sink = createRecordingSink(16384) + const capacity = 12288 + const dispatcher = new RelayDispatcher(sink.write, sink.options) + + try { + emitRelayWatcherEvents(dispatcher, '/workspace', false, watcherBatch(5000)) + + const totalBytes = sink.frames.reduce((total, frame) => total + frame.length, 0) + expect(sink.frames.length).toBeLessThanOrEqual(Math.ceil(totalBytes / capacity) + 1) + for (const frame of sink.frames.slice(0, -1)) { + expect(frame.length).toBeGreaterThanOrEqual(capacity * 0.9) + } + } finally { + dispatcher.dispose() + } + }) + + it('stops the chunk walk while the producer queue sits past its retention reserve', () => { + const sink = createRecordingSink(65536) + sink.blockNextWrite() + const dispatcher = new RelayDispatcher(sink.write, sink.options) + + try { + // Past the retention reserve but far from the 2 MB queue limit: every chunk would still be admitted. + const parked = parkProducerBytes(dispatcher, LEGACY_CLIENT_RETAINED_BYTES_LOW) + expect(parked).toBeLessThan(DEFAULT_PRODUCER_QUEUE_MAX_BYTES / 2 + 256 * 1024) + + emitRelayWatcherEvents(dispatcher, '/workspace', false, watcherBatch(5000)) + sink.drainWaiters.shift()?.() + + const watcherFrames = sink.frames.filter((frame) => frameMethod(frame) === 'fs.changed') + expect(watcherFrames.map(isOverflowFrame)).toEqual([true]) + // The flood injected nothing: the interactive lane keeps the whole reserve instead of ~425 KB less. + const injected = watcherFrames + .filter((frame) => !isOverflowFrame(frame)) + .reduce((total, frame) => total + frame.length, 0) + expect(injected).toBe(0) + expect(injected).toBeLessThan( + DEFAULT_PRODUCER_QUEUE_MAX_BYTES - LEGACY_CLIENT_RETAINED_BYTES_LOW + ) + expect(sink.closes()).toBe(0) + } finally { + dispatcher.dispose() + } + }) + + it('delivers a whole flood to a healthy client while a second client sits past its reserve', () => { + const stalled = createRecordingSink(65536) + const healthy = createRecordingSink(65536) + stalled.blockNextWrite() + const dispatcher = new RelayDispatcher(stalled.write, stalled.options) + const events = watcherBatch(5000) + + try { + dispatcher.attachClient(healthy.write, healthy.options) + const stalledId = dispatcher.activeClientIds()[0] + parkProducerBytesForClient(dispatcher, stalledId, LEGACY_CLIENT_RETAINED_BYTES_LOW) + + emitRelayWatcherEvents(dispatcher, '/workspace', false, events) + stalled.drainWaiters.shift()?.() + + // A resync forces a readDir per directory, so an unrelated peer's stall must never trigger one here. + expect(watcherFrames(healthy.frames).some(isOverflowFrame)).toBe(false) + expect(watcherFrames(healthy.frames).flatMap(frameEvents)).toEqual(deliveredEvents(events)) + expect(watcherFrames(stalled.frames).map(isOverflowFrame)).toEqual([true]) + expect(healthy.closes()).toBe(0) + expect(stalled.closes()).toBe(0) + } finally { + dispatcher.dispose() + } + }) + + it('stops the walk for the congested client while a healthy peer takes the whole flood', () => { + const healthy = createRecordingSink(65536) + const stalled = createRecordingSink(65536) + stalled.blockNextWrite() + const dispatcher = new RelayDispatcher(healthy.write, healthy.options) + const events = watcherBatch(5000) + + try { + // Reversed attach order from the peer-stall case: the gate must read the client being written to. + const stalledId = dispatcher.attachClient(stalled.write, stalled.options) + parkProducerBytesForClient(dispatcher, stalledId, LEGACY_CLIENT_RETAINED_BYTES_LOW) + + emitRelayWatcherEvents(dispatcher, '/workspace', false, events) + stalled.drainWaiters.shift()?.() + + const stalledWatcher = watcherFrames(stalled.frames) + expect(stalledWatcher.map(isOverflowFrame)).toEqual([true]) + const injected = stalledWatcher + .filter((frame) => !isOverflowFrame(frame)) + .reduce((total, frame) => total + frame.length, 0) + // Nothing injected: the congested client keeps its whole reserve for interactive PTY frames. + expect(injected).toBe(0) + expect(watcherFrames(healthy.frames).some(isOverflowFrame)).toBe(false) + expect(watcherFrames(healthy.frames).flatMap(frameEvents)).toEqual(deliveredEvents(events)) + expect(healthy.closes()).toBe(0) + expect(stalled.closes()).toBe(0) + } finally { + dispatcher.dispose() + } + }) + + it('still delivers a flood larger than the reserve while the sink keeps draining', () => { + const sink = createRecordingSink(16384) + const dispatcher = new RelayDispatcher(sink.write, sink.options) + const events = watcherBatch(20_000) + + try { + emitRelayWatcherEvents(dispatcher, '/workspace', false, events) + + const totalBytes = sink.frames.reduce((total, frame) => total + frame.length, 0) + expect(totalBytes).toBeGreaterThan(LEGACY_CLIENT_RETAINED_BYTES_LOW) + expect(sink.frames.some(isOverflowFrame)).toBe(false) + expect(sink.frames.flatMap(frameEvents)).toHaveLength(events.length) + } finally { + dispatcher.dispose() + } + }) + + it('chunks per client so a small sink never degrades a healthy one', () => { + const healthy = createRecordingSink(65536) + const small = createRecordingSink(16384) + const dispatcher = new RelayDispatcher(healthy.write, healthy.options) + + try { + dispatcher.attachClient(small.write, small.options) + const events = watcherBatch(200) + emitRelayWatcherEvents(dispatcher, '/workspace', false, events) + + const expected = events.map((event) => ({ + kind: event.type, + absolutePath: event.path, + isDirectory: event.isDirectory + })) + expect(healthy.frames).toHaveLength(1) + expect(frameEvents(healthy.frames[0])).toEqual(expected) + expect(small.frames.length).toBeGreaterThan(1) + expect(small.frames.every((frame) => frame.length <= 12288)).toBe(true) + expect(small.frames.flatMap(frameEvents)).toEqual(expected) + expect(healthy.closes()).toBe(0) + expect(small.closes()).toBe(0) } finally { dispatcher.dispose() } diff --git a/src/relay/relay-watcher-event-emitter.ts b/src/relay/relay-watcher-event-emitter.ts index 05cdd68c2..54aa6af8c 100644 --- a/src/relay/relay-watcher-event-emitter.ts +++ b/src/relay/relay-watcher-event-emitter.ts @@ -1,52 +1,197 @@ import type { WatcherProcessEvent } from '../main/ipc/parcel-watcher-process' +import { resolveRuntimePath } from '../shared/cross-platform-path' import type { RelayDispatcher } from './dispatcher' -const FS_CHANGED = 'fs.changed' - -type RelayWatcherEventPayload = { +type MappedWatcherEvent = { kind: string absolutePath: string isDirectory?: boolean } +type WatcherBatchSizing = { + eventBytes: Map + batchBytes: number +} + +// Why: one outstanding marker per (client, root) keeps sustained backpressure bounded. +const outstandingOverflowMarkers = new WeakMap>() + export function emitRelayWatcherEvents( dispatcher: RelayDispatcher, + rootPath: string, closed: boolean, events: readonly WatcherProcessEvent[] ): void { if (closed || events.length === 0) { return } - const frameCapacity = dispatcher.broadcastProducerFrameCapacity() - if (frameCapacity === undefined) { + const mapped: MappedWatcherEvent[] = events.map((event) => ({ + kind: event.type, + absolutePath: event.path, + ...(event.isDirectory === undefined ? {} : { isDirectory: event.isDirectory }) + })) + // Grouping walks every path, so only the chunking path pays for it — and only once across all clients. + let grouped: MappedWatcherEvent[] | null = null + const groupedByDirectory = (): MappedWatcherEvent[] => + (grouped ??= groupWatcherEventsByDirectory(mapped)) + let sizing: WatcherBatchSizing | null = null + const batchSizing = (): WatcherBatchSizing => (sizing ??= measureWatcherBatch(mapped)) + for (const clientId of dispatcher.activeClientIds()) { + publishWatcherBatchToClient( + dispatcher, + clientId, + rootPath, + mapped, + groupedByDirectory, + batchSizing + ) + } +} + +/** + * Why: the renderer dedupes directory refreshes within a SINGLE fs.changed payload, so a directory + * scattered across chunks costs one forced readDir RPC per chunk. Grouping is stable, so events for a + * given path keep their relative order and a create-then-delete can never invert. + */ +function groupWatcherEventsByDirectory( + mapped: readonly MappedWatcherEvent[] +): MappedWatcherEvent[] { + const groups = new Map() + for (const event of mapped) { + // Runs on the remote host: derive the parent with the runtime-flavored resolver, not a '/' split. + const parentPath = resolveRuntimePath(event.absolutePath, '..') + const group = groups.get(parentPath) + if (group) { + group.push(event) + } else { + groups.set(parentPath, [event]) + } + } + return Array.from(groups.values()).flat() +} + +function encodedWatcherEventBytes(event: MappedWatcherEvent): number { + return Buffer.byteLength(JSON.stringify(event)) +} + +function measureWatcherBatch(mapped: readonly MappedWatcherEvent[]): WatcherBatchSizing { + const eventBytes = new Map() + let batchBytes = Math.max(0, mapped.length - 1) + for (const event of mapped) { + const bytes = encodedWatcherEventBytes(event) + eventBytes.set(event, bytes) + batchBytes += bytes + } + return { eventBytes, batchBytes } +} + +// Batches are sized to each sink's frame capacity; a batch that cannot be sized degrades to an overflow resync. +function publishWatcherBatchToClient( + dispatcher: RelayDispatcher, + clientId: number, + rootPath: string, + mapped: readonly MappedWatcherEvent[], + groupedByDirectory: () => readonly MappedWatcherEvent[], + batchSizing: () => WatcherBatchSizing +): void { + const publish = (events: readonly MappedWatcherEvent[]): boolean => + dispatcher.publishProducerNotification(clientId, 'fs.changed', { events }) + + // Fast path: publish the whole batch first — two encodes, the same cost as an unchunked emit. + // logDrop:false because rejection here is a measurement, not an outcome: the batch is re-sent in + // chunks below, so logging it would report a drop for events that all arrive. + if ( + dispatcher.publishProducerNotification( + clientId, + 'fs.changed', + { events: mapped }, + { + logDrop: false + } + ) + ) { return } - // Whole watcher batches exceed the ordinary-lane cap; byte-pack ordered chunks instead. - const envelopeBytes = dispatcher.notificationFrameBytes(FS_CHANGED, { events: [] }) - let chunk: RelayWatcherEventPayload[] = [] - let chunkBytes = envelopeBytes - const flush = (): void => { - if (chunk.length === 0) { + + // Rejection is ambiguous: an over-capacity frame is chunkable, a full producer queue is real data loss. + // The empty envelope is encoded once; event JSON sizes are exact deltas apart from array commas. + const eventsCapacity = dispatcher.producerEnvelopeBudget('fs.changed', { events: [] }, clientId) + if (eventsCapacity < 0) { + emitWatcherOverflowToClient(dispatcher, clientId, rootPath) + return + } + const { eventBytes, batchBytes } = batchSizing() + if (batchBytes <= eventsCapacity) { + emitWatcherOverflowToClient(dispatcher, clientId, rootPath) + return + } + + const grouped = groupedByDirectory() + const groupedEventBytes = grouped.map((event) => eventBytes.get(event)!) + let index = 0 + while (index < grouped.length) { + // Why: the retention ledger covers every producer publication despite its legacy name, and admission + // is lane-agnostic: chunks queued past its low-water reserve (half the 2 MB queue) starve interactive + // PTY frames until pty-handler pauses every remote pane. A resync costs the user far less. + // Per client, never dispatcher-wide: one stalled peer must not cost a healthy client a resync, + // which forces a readDir per directory in its file tree. + if (!dispatcher.producerRetentionBelowLowWater(clientId)) { + emitWatcherOverflowToClient(dispatcher, clientId, rootPath) return } - dispatcher.notify(FS_CHANGED, { events: chunk }) - chunk = [] - chunkBytes = envelopeBytes - } - for (const event of events) { - const payload: RelayWatcherEventPayload = { - kind: event.type, - absolutePath: event.path, - ...(event.isDirectory === undefined ? {} : { isDirectory: event.isDirectory }) + let end = index + let chunkBytes = 0 + while (end < grouped.length) { + const nextBytes = groupedEventBytes[end] + (end === index ? 0 : 1) + if (chunkBytes + nextBytes > eventsCapacity) { + break + } + chunkBytes += nextBytes + end += 1 } - const payloadBytes = Buffer.byteLength(JSON.stringify(payload)) - if (chunk.length > 0 && chunkBytes + 1 + payloadBytes > frameCapacity) { - flush() + if (end === index || !publish(grouped.slice(index, end))) { + emitWatcherOverflowToClient(dispatcher, clientId, rootPath) + return } - chunkBytes += payloadBytes + (chunk.length === 0 ? 0 : 1) - chunk.push(payload) + index = end + } +} + +// Why: the control lane — on the producer lane the marker would hit the same full queue that just +// rejected the batch and be dropped, silently desyncing the remote file tree. +function emitWatcherOverflowToClient( + dispatcher: RelayDispatcher, + clientId: number, + rootPath: string +): void { + // Per root, never per client alone: an outstanding marker for one tree must not suppress another's resync. + const key = `${clientId} ${rootPath}` + const outstanding = outstandingOverflowMarkers.get(dispatcher) ?? new Set() + if (outstanding.has(key)) { + return + } + outstanding.add(key) + outstandingOverflowMarkers.set(dispatcher, outstanding) + const release = (): void => { + outstanding.delete(key) + if (outstanding.size === 0) { + outstandingOverflowMarkers.delete(dispatcher) + } + } + const accepted = dispatcher.tryNotifyClient( + clientId, + 'fs.changed', + { events: [{ kind: 'overflow', absolutePath: rootPath }] }, + () => { + // Settles on write, drop, or client close, so the slot can never leak. + release() + }, + { controlOverflow: 'reject' } + ) + // Admission rejection has no settlement callback, so release the slot directly. + if (!accepted) { + release() } - flush() } export function emitRelayWatcherOverflow( @@ -54,9 +199,10 @@ export function emitRelayWatcherOverflow( rootPath: string, closed: boolean ): void { - if (!closed) { - dispatcher.notify(FS_CHANGED, { - events: [{ kind: 'overflow', absolutePath: rootPath }] - }) + if (closed) { + return + } + for (const clientId of dispatcher.activeClientIds()) { + emitWatcherOverflowToClient(dispatcher, clientId, rootPath) } } diff --git a/src/relay/relay-watcher-frame-chunking.test.ts b/src/relay/relay-watcher-frame-chunking.test.ts index 5d505fb8a..8b9782972 100644 --- a/src/relay/relay-watcher-frame-chunking.test.ts +++ b/src/relay/relay-watcher-frame-chunking.test.ts @@ -134,7 +134,7 @@ describe('relay watcher fs.changed frame chunking', () => { const events = watcherBatch(5000) try { - emitRelayWatcherEvents(dispatcher, false, events) + emitRelayWatcherEvents(dispatcher, '/workspace', false, events) expect(detached).toEqual([]) for (const frame of capture.frames) { @@ -152,7 +152,7 @@ describe('relay watcher fs.changed frame chunking', () => { const events = watcherBatch(5000) try { - emitRelayWatcherEvents(dispatcher, false, events) + emitRelayWatcherEvents(dispatcher, '/workspace', false, events) expect(detached).toEqual([]) for (const frame of capture.frames) { @@ -170,7 +170,7 @@ describe('relay watcher fs.changed frame chunking', () => { const events = multiByteWatcherBatch(5000) try { - emitRelayWatcherEvents(dispatcher, false, events) + emitRelayWatcherEvents(dispatcher, '/workspace', false, events) expect(detached).toEqual([]) for (const frame of capture.frames) { @@ -190,7 +190,7 @@ describe('relay watcher fs.changed frame chunking', () => { const { dispatcher, capture, detached } = createDispatcher(NODE_21_HIGH_WATER_MARK) try { - emitRelayWatcherEvents(dispatcher, false, events) + emitRelayWatcherEvents(dispatcher, '/workspace', false, events) expect(detached).toEqual([]) expect(capture.frames).toHaveLength(2) @@ -208,7 +208,7 @@ describe('relay watcher fs.changed frame chunking', () => { const { dispatcher, capture, detached } = createDispatcher(NODE_21_HIGH_WATER_MARK) try { - emitRelayWatcherEvents(dispatcher, false, overshoot) + emitRelayWatcherEvents(dispatcher, '/workspace', false, overshoot) expect(detached).toEqual([]) expect(capture.frames).toHaveLength(2) @@ -221,7 +221,7 @@ describe('relay watcher fs.changed frame chunking', () => { } }) - it('sizes chunks against the smallest capacity across attached clients', () => { + it('sizes chunks independently for clients with different capacities', () => { const { capture: attachedCapture, write: attachedWrite } = captureFrames() const { dispatcher, capture, detached } = createDispatcher(NODE_22_HIGH_WATER_MARK) const events = watcherBatch(2000) @@ -232,10 +232,13 @@ describe('relay watcher fs.changed frame chunking', () => { writableLength: () => 0 }) - emitRelayWatcherEvents(dispatcher, false, events) + emitRelayWatcherEvents(dispatcher, '/workspace', false, events) expect(detached).toEqual([]) - for (const frame of [...capture.frames, ...attachedCapture.frames]) { + for (const frame of capture.frames) { + expect(frame.length).toBeLessThanOrEqual(NODE_22_PRODUCER_CAPACITY) + } + for (const frame of attachedCapture.frames) { expect(frame.length).toBeLessThanOrEqual(NODE_21_PRODUCER_CAPACITY) } expect(capture.fsChangedEvents()).toEqual(expectedPayloads(events)) @@ -245,7 +248,7 @@ describe('relay watcher fs.changed frame chunking', () => { } }) - it('still closes the client when a single event cannot fit any frame', () => { + it('resyncs without closing when a single event cannot fit any frame', () => { vi.spyOn(process.stderr, 'write').mockReturnValue(true) const { dispatcher, capture, detached } = createDispatcher(NODE_21_HIGH_WATER_MARK) const oversized: WatcherProcessEvent[] = [ @@ -253,16 +256,16 @@ describe('relay watcher fs.changed frame chunking', () => { ] try { - emitRelayWatcherEvents(dispatcher, false, oversized) + emitRelayWatcherEvents(dispatcher, '/workspace', false, oversized) - expect(detached).toEqual([1]) - expect(capture.frames).toEqual([]) + expect(detached).toEqual([]) + expect(capture.fsChangedEvents()).toEqual([{ kind: 'overflow', absolutePath: '/workspace' }]) } finally { dispatcher.dispose() } }) - it('delivers the prefix then closes when an oversized event appears mid-batch', () => { + it('delivers the prefix then resyncs when an oversized event appears mid-batch', () => { vi.spyOn(process.stderr, 'write').mockReturnValue(true) const { dispatcher, capture, detached } = createDispatcher(NODE_21_HIGH_WATER_MARK) const oversized = { @@ -273,13 +276,15 @@ describe('relay watcher fs.changed frame chunking', () => { const events = [...watcherBatch(300), oversized, ...watcherBatch(50)] try { - emitRelayWatcherEvents(dispatcher, false, events) + emitRelayWatcherEvents(dispatcher, '/workspace', false, events) - expect(detached).toEqual([1]) + expect(detached).toEqual([]) const delivered = capture.fsChangedEvents() expect(delivered.length).toBeGreaterThan(0) - expect(delivered).toEqual(expectedPayloads(events).slice(0, delivered.length)) - expect(delivered.some((event) => event.absolutePath === oversized.path)).toBe(false) + expect(delivered.at(-1)).toEqual({ kind: 'overflow', absolutePath: '/workspace' }) + const prefix = delivered.slice(0, -1) + expect(prefix).toEqual(expectedPayloads(events.filter((event) => event !== oversized))) + expect(prefix.some((event) => event.absolutePath === oversized.path)).toBe(false) for (const frame of capture.frames) { expect(frame.length).toBeLessThanOrEqual(NODE_21_PRODUCER_CAPACITY) } @@ -288,7 +293,7 @@ describe('relay watcher fs.changed frame chunking', () => { } }) - it('keeps the fail-closed kill when retained chunks exhaust the producer queue budget', () => { + it('keeps the client alive when retained chunks exhaust the producer queue budget', () => { vi.spyOn(process.stderr, 'write').mockReturnValue(true) // An unsettled sink models retained relay stdout writes. const { dispatcher, capture, detached } = createDispatcher(NODE_21_HIGH_WATER_MARK, { @@ -300,15 +305,18 @@ describe('relay watcher fs.changed frame chunking', () => { for (let round = 0; round < 10 && detached.length === 0; round++) { const events = watcherBatch(5000) emitted.push(...events) - emitRelayWatcherEvents(dispatcher, false, events) + emitRelayWatcherEvents(dispatcher, '/workspace', false, events) } - expect(detached).toEqual([1]) + expect(detached).toEqual([]) const delivered = capture.fsChangedEvents() expect(delivered.length).toBeGreaterThan(0) expect(delivered.length).toBeLessThan(emitted.length) - // The kill truncates delivery at a chunk boundary; nothing is reordered or duplicated. - expect(delivered).toEqual(expectedPayloads(emitted).slice(0, delivered.length)) + const producerEvents = delivered.filter((event) => event.kind !== 'overflow') + expect(delivered.filter((event) => event.kind === 'overflow')).toEqual([ + { kind: 'overflow', absolutePath: '/workspace' } + ]) + expect(producerEvents).toEqual(expectedPayloads(emitted).slice(0, producerEvents.length)) for (const frame of capture.frames) { expect(frame.length).toBeLessThanOrEqual(NODE_21_PRODUCER_CAPACITY) } @@ -326,7 +334,7 @@ describe('relay watcher fs.changed frame chunking', () => { const notify = vi.spyOn(dispatcher, 'notify') try { dispatcher.invalidateClient() - emitRelayWatcherEvents(dispatcher, false, watcherBatch(10)) + emitRelayWatcherEvents(dispatcher, '/workspace', false, watcherBatch(10)) expect(notify).not.toHaveBeenCalled() expect(capture.frames).toEqual([]) diff --git a/src/relay/relay.ts b/src/relay/relay.ts index f807fc6ac..516bbadc6 100644 --- a/src/relay/relay.ts +++ b/src/relay/relay.ts @@ -36,9 +36,9 @@ import { endpointDirForRelaySocket, RelayAgentHookServer } from './agent-hook-se import { PluginOverlayManager } from './plugin-overlay' import { AGENT_HOOK_INSTALL_PLUGINS_METHOD, - AGENT_HOOK_NOTIFICATION_METHOD, AGENT_HOOK_REQUEST_REPLAY_METHOD } from '../shared/agent-hook-relay' +import { publishAgentHookEnvelope } from './agent-hook-envelope-publication' import { DEFAULT_SSH_RELAY_GRACE_PERIOD_SECONDS, SSH_RELAY_CONFIGURE_GRACE_TIME_METHOD @@ -714,13 +714,8 @@ async function main(): Promise { const hookServer = new RelayAgentHookServer({ // Why: scope endpoint.env/cmd by socket path so multiple relay daemons on one account can't overwrite each other's hook tokens. endpointDir: endpointDir ?? endpointDirForRelaySocket(sockPath), - forward: (envelope) => { - // Why: notify is fire-and-forget and drops during reconnect; the per-paneKey cache lets us replay last status after --connect. - dispatcher.notify( - AGENT_HOOK_NOTIFICATION_METHOD, - envelope as unknown as Record - ) - } + // Why: publication is fire-and-forget and drops during reconnect; the per-paneKey cache lets us replay last status after --connect. + forward: (envelope) => publishAgentHookEnvelope(dispatcher, envelope) }) // Why: await the bind before announcing readiness so the first PTY spawn already sees ORCA_AGENT_HOOK_* env; bind failure is soft (log and continue). try { diff --git a/src/relay/wsl-agent-hook-relay.ts b/src/relay/wsl-agent-hook-relay.ts index 384fbc2c3..7f3ee8e40 100644 --- a/src/relay/wsl-agent-hook-relay.ts +++ b/src/relay/wsl-agent-hook-relay.ts @@ -21,9 +21,9 @@ import { createInstallPluginsHandler } from './wsl-install-plugins-handler' import { PreflightHandler } from './preflight-handler' import { AGENT_HOOK_INSTALL_PLUGINS_METHOD, - AGENT_HOOK_NOTIFICATION_METHOD, AGENT_HOOK_REQUEST_REPLAY_METHOD } from '../shared/agent-hook-relay' +import { publishAgentHookEnvelope } from './agent-hook-envelope-publication' import { sanitizeWslHookInstanceKey, WSL_HOOK_RELAY_INSTANCE_ENV, @@ -68,11 +68,7 @@ async function main(): Promise { endpointDir: wslHookRelayEndpointDir(homedir(), instanceKey), token, preferredPort: windowsPort, - forward: (envelope) => - dispatcher.notify( - AGENT_HOOK_NOTIFICATION_METHOD, - envelope as unknown as Record - ) + forward: (envelope) => publishAgentHookEnvelope(dispatcher, envelope) }) new PreflightHandler(dispatcher) diff --git a/src/shared/agent-hook-relay.test.ts b/src/shared/agent-hook-relay.test.ts index 27aec4052..338581c28 100644 --- a/src/shared/agent-hook-relay.test.ts +++ b/src/shared/agent-hook-relay.test.ts @@ -3,10 +3,14 @@ import { AGENT_HOOK_INSTALL_PLUGINS_METHOD, AGENT_HOOK_NOTIFICATION_METHOD, AGENT_HOOK_REQUEST_REPLAY_METHOD, + AGENT_HOOK_SHED_FIELDS_KEY, ORCA_FEATURE_REMOTE_AGENT_HOOKS_ENV, + createShedSubagentsField, isRemoteAgentHooksEnabled, + restoreShedStatusFields, type AgentHookRelayEnvelope } from './agent-hook-relay' +import type { ParsedAgentStatusPayload } from './agent-status-types' describe('agent-hook-relay wire shape', () => { it('encodes/decodes through JSON without losing fields', () => { @@ -55,3 +59,77 @@ describe('isRemoteAgentHooksEnabled', () => { expect(isRemoteAgentHooksEnabled({ [ORCA_FEATURE_REMOTE_AGENT_HOOKS_ENV]: 'true' })).toBe(true) }) }) + +describe('restoreShedStatusFields', () => { + const roster = [{ id: 'child-1', agentType: 'reviewer', state: 'working' as const, startedAt: 1 }] + const cached: ParsedAgentStatusPayload = { + state: 'working', + prompt: 'p', + agentType: 'claude', + subagents: roster, + lastAssistantMessage: 'cached message', + interactivePrompt: '{"questions":["old"]}' + } + const shed: ParsedAgentStatusPayload = { state: 'done', prompt: 'p', agentType: 'claude' } + + it('restores a matching shed roster, so a done pane is not falsely hibernation-eligible', () => { + const restored = restoreShedStatusFields(shed, [createShedSubagentsField(roster)], cached) + expect(restored.subagents).toEqual(roster) + expect(restored.state).toBe('done') + // Only the named field comes back. + expect(restored.lastAssistantMessage).toBeUndefined() + }) + + it('does not restore a shed roster across a prompt identity change', () => { + expect(AGENT_HOOK_SHED_FIELDS_KEY).toBe('shedFields') + const nextTurn = { ...shed, prompt: 'next prompt' } + const restored = restoreShedStatusFields( + nextTurn, + ['lastAssistantMessage', createShedSubagentsField(roster)], + cached + ) + expect(restored.lastAssistantMessage).toBeUndefined() + expect(restored.subagents).toBeUndefined() + expect(restored).toBe(nextTurn) + }) + + it('does not restore the cached roster when the shed roster digest changed', () => { + const changedRoster = [ + { id: 'child-2', agentType: 'reviewer', state: 'working' as const, startedAt: 2 } + ] + const restored = restoreShedStatusFields( + shed, + [createShedSubagentsField(changedRoster)], + cached + ) + expect(restored.subagents).toBeUndefined() + expect(restored).toBe(shed) + }) + + it('never restores interactivePrompt — a stale answerable card is worse than none', () => { + const restored = restoreShedStatusFields(shed, ['interactivePrompt'], cached) + expect(restored.interactivePrompt).toBeUndefined() + expect(restored).toBe(shed) + }) + + it('leaves an intentional lastAssistantMessage clear intact when the relay shed nothing', () => { + expect(restoreShedStatusFields(shed, undefined, cached)).toBe(shed) + expect(restoreShedStatusFields(shed, [], cached)).toBe(shed) + expect(restoreShedStatusFields(shed, [], cached).lastAssistantMessage).toBeUndefined() + // A hostile/garbled marker must not throw or restore. + expect(restoreShedStatusFields(shed, 'subagents', cached)).toBe(shed) + expect(restoreShedStatusFields(shed, ['subagents'], cached)).toBe(shed) + expect(restoreShedStatusFields(shed, [{ toString: () => 'subagents' }], cached)).toBe(shed) + }) + + it('does not overwrite a value the envelope still carries', () => { + const fresh: ParsedAgentStatusPayload = { ...shed, lastAssistantMessage: 'fresh' } + expect( + restoreShedStatusFields(fresh, ['lastAssistantMessage'], cached).lastAssistantMessage + ).toBe('fresh') + }) + + it('is a no-op with no cached payload for the pane', () => { + expect(restoreShedStatusFields(shed, ['subagents'], undefined)).toBe(shed) + }) +}) diff --git a/src/shared/agent-hook-relay.ts b/src/shared/agent-hook-relay.ts index 71e795317..ebb3648a2 100644 --- a/src/shared/agent-hook-relay.ts +++ b/src/shared/agent-hook-relay.ts @@ -22,7 +22,9 @@ // POST body so Orca's warn-once protocol diagnostics still fire. The relay // default env is `remote`, a location marker ignored by dev-vs-prod checks. -import type { ParsedAgentStatusPayload } from './agent-status-types' +import { createHash } from 'node:crypto' + +import type { AgentSubagentSnapshot, ParsedAgentStatusPayload } from './agent-status-types' import type { AgentProviderSessionMetadata } from './agent-session-resume' import type { AgentHookTarget } from './agent-hook-types' @@ -99,6 +101,82 @@ export type AgentHookRelayEnvelope = { /** JSON-RPC notification method name carried over the relay control channel. */ export const AGENT_HOOK_NOTIFICATION_METHOD = 'agent.hook' as const +/** Identifies optional payload fields the relay dropped to fit an oversized frame + * (see `src/relay/agent-hook-envelope-publication.ts`), so `ingestRemote` can tell + * "shed in transit" from "the agent cleared it"; rosters include their digest. */ +export const AGENT_HOOK_SHED_FIELDS_KEY = 'shedFields' as const +const AGENT_HOOK_SHED_SUBAGENTS_DIGEST_PREFIX = 'subagents:sha256:' + +function subagentRosterDigest(subagents: readonly AgentSubagentSnapshot[]): string { + const stableRoster = subagents.map(({ id, state, startedAt, agentType, model, description }) => [ + id, + state, + startedAt, + agentType ?? null, + model ?? null, + description ?? null + ]) + return createHash('sha256').update(JSON.stringify(stableRoster)).digest('base64url') +} + +/** Carries the dropped roster identity without carrying its full rows. */ +export function createShedSubagentsField(subagents: readonly AgentSubagentSnapshot[]): string { + return `${AGENT_HOOK_SHED_SUBAGENTS_DIGEST_PREFIX}${subagentRosterDigest(subagents)}` +} + +function hasMatchingShedSubagentsField( + shedFields: readonly unknown[], + previous: ParsedAgentStatusPayload +): boolean { + if (!previous.subagents) { + return false + } + const expected = createShedSubagentsField(previous.subagents) + return shedFields.some((field) => field === expected) +} + +function hasMatchingTurnIdentity( + payload: ParsedAgentStatusPayload, + previous: ParsedAgentStatusPayload +): boolean { + return ( + payload.prompt === previous.prompt && + payload.agentType === previous.agentType && + payload.model === previous.model + ) +} + +/** + * Re-attaches shed fields from Orca's cached payload for this pane, so a transport-level + * truncation cannot read as a cleared field — an absent `subagents` blanks live child rows and + * unblocks hibernation for a pane whose teammates are still running. + * + * `interactivePrompt` and `lastAssistantMessage` are deliberately not restored: cached prose can + * belong to an earlier turn. A roster returns only when its wire digest and turn identity match. + */ +export function restoreShedStatusFields( + payload: ParsedAgentStatusPayload, + shedFields: unknown, + previous: ParsedAgentStatusPayload | undefined +): ParsedAgentStatusPayload { + if (!previous || !Array.isArray(shedFields) || shedFields.length === 0) { + return payload + } + const subagents = + payload.subagents === undefined && + hasMatchingTurnIdentity(payload, previous) && + hasMatchingShedSubagentsField(shedFields, previous) + ? previous.subagents + : undefined + if (subagents === undefined) { + return payload + } + return { + ...payload, + subagents + } +} + /** JSON-RPC request method Orca issues after `--connect` reattach to ask the * relay to replay its per-paneKey last-payload cache. See §5 Path 3 of the * design doc for the race that ruled out push-on-`setWrite`. */ diff --git a/tests/tools/benchmarks/terminal-perf-bench.mjs b/tests/tools/benchmarks/terminal-perf-bench.mjs index 23559a63f..a73ffae6b 100644 --- a/tests/tools/benchmarks/terminal-perf-bench.mjs +++ b/tests/tools/benchmarks/terminal-perf-bench.mjs @@ -591,7 +591,8 @@ async function main() { args.reportPath ?? path.join( rootDir, - 'tests', 'tools', + 'tests', + 'tools', 'benchmarks', 'results', `terminal-perf-${args.label}-${stamp}.json`