fix: bound agent communication memory growth (#369)

* fix: bound agent communication memory growth

UDS messaging now uses private local capabilities instead of exposing auth tokens through SDK metadata, environment variables, session registry, peer listing, or tool output. The receive path bounds NDJSON frames, response buffers, active clients, and pending inbox bytes, and strips auth metadata before messages enter the prompt queue.

Teammate mailboxes now validate file and message sizes, fail closed on corrupt mutation inputs, compact by count and retained bytes, and use stable message identity for in-process acknowledgements. Agent summaries now fork only a bounded recent context using lazy size estimation and content fingerprints instead of retaining or serializing unbounded histories.

Constraint: PR #361 was already merged; this branch is based on upstream/main@c2ac9a74.
Rejected: Default-disabling COORDINATOR_MODE/TEAMMEM only | explicit feature enablement still hit unbounded paths.
Rejected: Persisting UDS auth in SDK/env/session registry | bridge/remote metadata can leak local capability secrets.
Rejected: Inline uds #token addresses | observable/tool/classifier paths can reflect raw addresses outside the UDS request frame.
Rejected: Positional mailbox marking after compaction | compaction can shift indices across the lock boundary.
Confidence: high
Scope-risk: moderate
Directive: Do not expose UDS capability tokens through SDK messages, environment variables, session registry, peer-list output, or SendMessage result/classifier surfaces.
Directive: Do not reintroduce positional mailbox acknowledgements unless compaction is removed or read+mark is atomic under one lock.
Tested: bun test src/utils/__tests__/ndjsonFramer.test.ts src/utils/__tests__/udsMessaging.test.ts packages/builtin-tools/src/tools/SendMessageTool/__tests__/udsRecipientSanitization.test.ts
Tested: bunx tsc --noEmit --pretty false
Tested: bun run lint
Tested: bunx biome lint modified src/package files
Tested: bun run test:all (3704 pass, 0 fail, 6734 expects)
Tested: bun audit (No vulnerabilities found)
Tested: bun run build
Tested: bun run build:vite
Tested: git diff --check
Not-tested: End-to-end external UDS client driving a full production headless model turn.

* fix: harden bounded agent communication review fixes

CodeRabbit and Codecov surfaced real gaps in UDS framing, peer discovery, mailbox retention, and summary context coverage. This tightens those paths without suppressing review or coverage signals.

Constraint: PR #369 must address CodeRabbit and Codecov findings without warning suppression or fake fallbacks

Rejected: Suppress Codecov or CodeRabbit warnings | leaves real receive-path and test-isolation gaps

Rejected: Add unreachable feature-gated tests | bun:bundle keeps those branches compile-time gated in local tests

Confidence: high

Scope-risk: moderate

Directive: Keep UDS auth-token rejection outside feature flags; do not reintroduce inline token fallbacks

Tested: bun test --coverage --coverage-reporter lcov --coverage-dir coverage; bun run test:all; bun run lint; bun run build; bun run build:vite; bun audit; git diff --cached --check

Not-tested: Remote Codecov/CodeRabbit refreshed reports until pushed

* fix: prevent agent communication bounds from hiding CI regressions

Tighten the UDS auth, framing, and response-reader boundaries while keeping the AgentSummary lifecycle covered so Codecov and CI fail on real regressions instead of missing coverage. The poorMode settings mock mirrors unrelated real settings defaults to avoid Bun mock retention changing later permission tests.

Constraint: PR #369 must fix Codecov/CI precisely without warning suppression, fallback masking, or mock pollution

Rejected: Delete AgentSummary lifecycle coverage | would hide Codecov loss and stale-summary behavior

Rejected: Store inline UDS rejection in a hidden input sentinel | cloned observable inputs can drop it and bypass rejection

Rejected: Ignore malformed UDS frames until timeout | leaves client slots and SendMessage calls open to exhaustion

Confidence: high

Scope-risk: moderate

Directive: Keep empty #token= markers rejected; do not require a non-empty token value in hasInlineUdsToken

Tested: bun test packages/builtin-tools/src/tools/SendMessageTool/__tests__/udsRecipientSanitization.test.ts src/utils/__tests__/udsMessaging.test.ts src/utils/__tests__/udsResponseReader.test.ts src/utils/__tests__/ndjsonFramer.test.ts

Tested: bunx tsc --noEmit --pretty false

Tested: bun run lint

Tested: bun test --coverage --coverage-reporter lcov --coverage-dir coverage

Tested: bun run test:all

Tested: bun audit

Tested: bun run build

Tested: bun run build:vite

Not-tested: GitHub-hosted Codecov upload until pushed PR checks rerun

---------

Co-authored-by: unraid <local@unraid.local>
This commit is contained in:
Dosion
2026-04-27 14:47:18 +08:00
committed by GitHub
parent 3cb4828de6
commit 52b61c2c06
26 changed files with 3925 additions and 242 deletions

View File

@@ -0,0 +1,153 @@
import { EventEmitter } from 'node:events'
import type { Socket } from 'node:net'
import { describe, expect, test } from 'bun:test'
import { attachNdjsonFramer } from '../ndjsonFramer.js'
type TestSocket = Socket & {
destroyed: boolean
emitData: (chunk: Buffer) => void
}
function createTestSocket(): TestSocket {
const emitter = new EventEmitter() as TestSocket
emitter.destroyed = false
emitter.destroy = ((_error?: Error) => {
emitter.destroyed = true
emitter.emit('close')
return emitter
}) as TestSocket['destroy']
emitter.emitData = (chunk: Buffer) => {
emitter.emit('data', chunk)
}
return emitter
}
describe('attachNdjsonFramer', () => {
test('accepts a complete frame at the configured byte limit', () => {
const socket = createTestSocket()
const messages: unknown[] = []
const errors: Error[] = []
attachNdjsonFramer(
socket,
msg => messages.push(msg),
text => JSON.parse(text) as unknown,
{
maxFrameBytes: Buffer.byteLength('{"a":1}', 'utf8'),
onFrameError: error => errors.push(error),
},
)
socket.emitData(Buffer.from('{"a":1}\n'))
expect(messages).toEqual([{ a: 1 }])
expect(errors).toEqual([])
expect(socket.destroyed).toBe(false)
})
test('destroys a complete frame over the configured byte limit', () => {
const socket = createTestSocket()
const messages: unknown[] = []
const errors: Error[] = []
attachNdjsonFramer(
socket,
msg => messages.push(msg),
text => JSON.parse(text) as unknown,
{
maxFrameBytes: 8,
onFrameError: error => errors.push(error),
},
)
socket.emitData(Buffer.from('{"long":true}\n'))
expect(messages).toEqual([])
expect(errors[0]?.message).toContain('NDJSON frame exceeded')
expect(socket.destroyed).toBe(true)
})
test('destroys oversized no-newline input before a frame can form', () => {
const socket = createTestSocket()
const messages: unknown[] = []
const errors: Error[] = []
attachNdjsonFramer(
socket,
msg => messages.push(msg),
text => JSON.parse(text) as unknown,
{
maxFrameBytes: 8,
onFrameError: error => errors.push(error),
},
)
socket.emitData(Buffer.from('x'.repeat(9)))
expect(messages).toEqual([])
expect(errors[0]?.message).toContain('NDJSON frame exceeded')
expect(socket.destroyed).toBe(true)
})
test('lets callers own oversized-frame shutdown when configured', () => {
const socket = createTestSocket()
const errors: Error[] = []
attachNdjsonFramer(
socket,
() => undefined,
text => JSON.parse(text) as unknown,
{
maxFrameBytes: 8,
onFrameError: error => errors.push(error),
destroyOnFrameError: false,
},
)
socket.emitData(Buffer.from('{"long":true}\n'))
expect(errors[0]?.message).toContain('NDJSON frame exceeded')
expect(socket.destroyed).toBe(false)
})
test('reports malformed non-empty frames without changing default compatibility', () => {
const socket = createTestSocket()
const messages: unknown[] = []
const errors: Error[] = []
attachNdjsonFramer(
socket,
msg => messages.push(msg),
text => JSON.parse(text) as unknown,
{
onInvalidFrame: error => errors.push(error),
},
)
socket.emitData(Buffer.from('{not-json\n'))
expect(messages).toEqual([])
expect(errors).toHaveLength(1)
expect(socket.destroyed).toBe(false)
})
test('destroys malformed frames when configured by the caller', () => {
const socket = createTestSocket()
const errors: Error[] = []
attachNdjsonFramer(
socket,
() => undefined,
text => JSON.parse(text) as unknown,
{
destroyOnInvalidFrame: true,
onInvalidFrame: error => errors.push(error),
},
)
socket.emitData(Buffer.from('{not-json\n'))
expect(errors).toHaveLength(1)
expect(socket.destroyed).toBe(true)
})
})

View File

@@ -0,0 +1,462 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import { mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import type { Message } from 'src/types/message.js'
import {
compactMailboxMessages,
getLastPeerDmSummary,
getInboxPath,
markMessageAsReadByIndex,
markMessageAsReadByIdentity,
markMessagesAsRead,
markMessagesAsReadByPredicate,
MAX_MAILBOX_MESSAGE_TEXT_BYTES,
MAX_MAILBOX_FILE_BYTES,
MAX_MAILBOX_MESSAGES,
MAX_READ_MAILBOX_MESSAGES,
MAX_UNREAD_PROTOCOL_MAILBOX_MESSAGES,
readMailbox,
type TeammateMessage,
writeToMailbox,
} from 'src/utils/teammateMailbox.js'
let tempHome = ''
let previousConfigDir: string | undefined
function message(
text: string,
read: boolean,
timestamp = new Date(0).toISOString(),
): TeammateMessage {
return {
from: 'team-lead',
text,
timestamp,
read,
}
}
async function seedMailbox(
agentName: string,
teamName: string,
messages: TeammateMessage[],
): Promise<void> {
const inboxPath = getInboxPath(agentName, teamName)
await mkdir(dirname(inboxPath), { recursive: true })
await writeFile(inboxPath, JSON.stringify(messages, null, 2), 'utf-8')
}
async function readRawMailbox(
agentName: string,
teamName: string,
): Promise<TeammateMessage[]> {
const content = await readFile(getInboxPath(agentName, teamName), 'utf-8')
return JSON.parse(content) as TeammateMessage[]
}
describe('compactMailboxMessages', () => {
test('prioritizes unread messages and keeps only recent read history', () => {
const compacted = compactMailboxMessages(
[
message('read-1', true),
message('read-2', true),
message('unread-1', false),
message('read-3', true),
message('unread-2', false),
message('read-4', true),
message('read-5', true),
message('unread-3', false),
],
{ maxMessages: 5, maxReadMessages: 2 },
)
expect(compacted.map(m => m.text)).toEqual([
'unread-1',
'unread-2',
'read-4',
'read-5',
'unread-3',
])
})
test('retains unread protocol messages separately from regular cap', () => {
const protocol = message(
JSON.stringify({ type: 'permission_response', request_id: 'req-1' }),
false,
)
const compacted = compactMailboxMessages(
[
protocol,
...Array.from({ length: 5 }, (_value, index) =>
message(`regular-${index}`, false),
),
],
{
maxMessages: 2,
maxReadMessages: 0,
maxUnreadProtocolMessages: 1,
},
)
expect(compacted.map(m => m.text)).toEqual([
protocol.text,
'regular-3',
'regular-4',
])
})
test('does not prioritize malformed JSON-like unread messages as protocol', () => {
const compacted = compactMailboxMessages(
[
message('{not-json', false),
message('regular-1', false),
message('regular-2', false),
],
{
maxMessages: 1,
maxReadMessages: 0,
maxUnreadProtocolMessages: 10,
},
)
expect(compacted.map(m => m.text)).toEqual(['regular-2'])
})
test('caps unread protocol messages with an independent bound', () => {
const compacted = compactMailboxMessages(
Array.from(
{ length: MAX_UNREAD_PROTOCOL_MAILBOX_MESSAGES + 1 },
(_value, index) =>
message(
JSON.stringify({
type: 'permission_response',
request_id: `req-${index}`,
}),
false,
),
),
)
expect(compacted).toHaveLength(MAX_UNREAD_PROTOCOL_MAILBOX_MESSAGES)
expect(compacted[0]?.text).toContain('req-1')
})
test('keeps retained mailbox bytes under an explicit budget', () => {
const compacted = compactMailboxMessages(
Array.from({ length: 20 }, (_value, index) =>
message(`msg-${index}-${'x'.repeat(200)}`, false),
),
{
maxMessages: 20,
maxReadMessages: 0,
maxRetainedBytes: 1_000,
},
)
expect(
Buffer.byteLength(JSON.stringify(compacted), 'utf8'),
).toBeLessThanOrEqual(1_000)
expect(compacted.length).toBeLessThan(20)
expect(compacted.at(-1)?.text).toContain('msg-19')
})
test('returns an empty mailbox when even one message exceeds retained budget', () => {
const compacted = compactMailboxMessages([message('too-large', false)], {
maxMessages: 10,
maxReadMessages: 0,
maxRetainedBytes: 1,
})
expect(compacted).toEqual([])
})
})
describe('teammate mailbox retention', () => {
beforeEach(() => {
previousConfigDir = process.env.CLAUDE_CONFIG_DIR
tempHome = mkdtempSync(join(tmpdir(), 'teammate-mailbox-'))
process.env.CLAUDE_CONFIG_DIR = tempHome
})
afterEach(async () => {
if (previousConfigDir === undefined) {
delete process.env.CLAUDE_CONFIG_DIR
} else {
process.env.CLAUDE_CONFIG_DIR = previousConfigDir
}
await rm(tempHome, { recursive: true, force: true })
tempHome = ''
})
test('writeToMailbox compacts oversized unread inbox files', async () => {
const existing = Array.from(
{ length: MAX_MAILBOX_MESSAGES + 20 },
(_value, index) => message(`old-${index}`, false),
)
await seedMailbox('worker', 'alpha', existing)
await writeToMailbox(
'worker',
{
from: 'team-lead',
text: 'newest',
timestamp: new Date(1).toISOString(),
},
'alpha',
)
const after = await readMailbox('worker', 'alpha')
expect(after).toHaveLength(MAX_MAILBOX_MESSAGES)
expect(after[0]?.text).toBe('old-21')
expect(after.at(-1)?.text).toBe('newest')
})
test('markMessagesAsRead compacts read history after consumption', async () => {
const existing = Array.from(
{ length: MAX_MAILBOX_MESSAGES + 20 },
(_value, index) => message(`msg-${index}`, false),
)
await seedMailbox('worker', 'alpha', existing)
await markMessagesAsRead('worker', 'alpha')
const after = await readRawMailbox('worker', 'alpha')
expect(after).toHaveLength(MAX_READ_MAILBOX_MESSAGES)
expect(after.every(m => m.read)).toBe(true)
expect(after[0]?.text).toBe(
`msg-${MAX_MAILBOX_MESSAGES + 20 - MAX_READ_MAILBOX_MESSAGES}`,
)
})
test('markMessagesAsReadByPredicate leaves structured messages unread', async () => {
await seedMailbox('worker', 'alpha', [
message('plain', false),
message(JSON.stringify({ type: 'permission_request' }), false),
])
await markMessagesAsReadByPredicate(
'worker',
m => !m.text.includes('permission_request'),
'alpha',
)
const after = await readRawMailbox('worker', 'alpha')
expect(after.map(m => m.read)).toEqual([true, false])
})
test('markMessageAsReadByIdentity survives compaction shifting indexes', async () => {
const permissionResponse = message(
JSON.stringify({ type: 'permission_response', request_id: 'req-1' }),
false,
)
await seedMailbox('worker', 'alpha', [
permissionResponse,
...Array.from({ length: MAX_MAILBOX_MESSAGES + 20 }, (_value, index) =>
message(`regular-${index}`, false),
),
])
await writeToMailbox(
'worker',
{
from: 'team-lead',
text: 'newest',
timestamp: new Date(2).toISOString(),
},
'alpha',
)
const marked = await markMessageAsReadByIdentity(
'worker',
'alpha',
permissionResponse,
)
const after = await readRawMailbox('worker', 'alpha')
expect(marked).toBe(true)
expect(after.some(m => m.text === permissionResponse.text && !m.read)).toBe(
false,
)
})
test('markMessageAsReadByIndex also compacts through the compatibility path', async () => {
const existing = Array.from(
{ length: MAX_MAILBOX_MESSAGES + 10 },
(_value, index) => message(`msg-${index}`, false),
)
await seedMailbox('worker', 'alpha', existing)
await markMessageAsReadByIndex('worker', 'alpha', existing.length - 1)
const after = await readRawMailbox('worker', 'alpha')
expect(after).toHaveLength(MAX_MAILBOX_MESSAGES)
expect(after.some(m => m.text === `msg-${existing.length - 1}`)).toBe(false)
expect(after.at(-1)?.text).toBe(`msg-${existing.length - 2}`)
})
test('writeToMailbox rejects oversized message text instead of storing it', async () => {
await expect(
writeToMailbox(
'worker',
{
from: 'team-lead',
text: 'x'.repeat(MAX_MAILBOX_MESSAGE_TEXT_BYTES + 1),
timestamp: new Date(3).toISOString(),
},
'alpha',
),
).rejects.toThrow('Mailbox message text exceeds')
expect(await readRawMailbox('worker', 'alpha')).toEqual([])
})
test('writeToMailbox fails closed when an existing mailbox is corrupt', async () => {
const inboxPath = getInboxPath('worker', 'alpha')
await mkdir(dirname(inboxPath), { recursive: true })
await writeFile(inboxPath, '{not-json', 'utf-8')
await expect(
writeToMailbox(
'worker',
{
from: 'team-lead',
text: 'new',
timestamp: new Date(4).toISOString(),
},
'alpha',
),
).rejects.toThrow()
expect(await readFile(inboxPath, 'utf-8')).toBe('{not-json')
})
test('readMailbox fails closed on corrupt mailbox content', async () => {
const inboxPath = getInboxPath('worker', 'alpha')
await mkdir(dirname(inboxPath), { recursive: true })
await writeFile(inboxPath, '{not-json', 'utf-8')
await expect(readMailbox('worker', 'alpha')).rejects.toThrow()
})
test('readMailbox rejects non-array mailbox files', async () => {
const inboxPath = getInboxPath('worker', 'alpha')
await mkdir(dirname(inboxPath), { recursive: true })
await writeFile(inboxPath, JSON.stringify({ text: 'not an array' }), 'utf-8')
await expect(readMailbox('worker', 'alpha')).rejects.toThrow(
'expected message array',
)
})
test('readMailbox rejects malformed stored message shapes', async () => {
const inboxPath = getInboxPath('worker', 'alpha')
await mkdir(dirname(inboxPath), { recursive: true })
await writeFile(
inboxPath,
JSON.stringify([{ from: 'lead', text: 'missing timestamp' }]),
'utf-8',
)
await expect(readMailbox('worker', 'alpha')).rejects.toThrow(
'Invalid mailbox message shape',
)
})
test('readMailbox rejects non-object stored messages', async () => {
const inboxPath = getInboxPath('worker', 'alpha')
await mkdir(dirname(inboxPath), { recursive: true })
await writeFile(inboxPath, JSON.stringify(['not an object']), 'utf-8')
await expect(readMailbox('worker', 'alpha')).rejects.toThrow(
'expected object',
)
})
test('readMailbox rejects oversized mailbox files before parsing', async () => {
const inboxPath = getInboxPath('worker', 'alpha')
await mkdir(dirname(inboxPath), { recursive: true })
await writeFile(inboxPath, `[${' '.repeat(MAX_MAILBOX_FILE_BYTES)}]`, 'utf-8')
await expect(readMailbox('worker', 'alpha')).rejects.toThrow(
'Mailbox file exceeds',
)
})
test('markMessageAsReadByIdentity returns false for missing mailbox files', async () => {
await expect(
markMessageAsReadByIdentity('worker', 'alpha', message('absent', false)),
).resolves.toBe(false)
})
test('markMessageAsReadByIdentity returns false when the expected message moved out', async () => {
await seedMailbox('worker', 'alpha', [message('other', false)])
await expect(
markMessageAsReadByIdentity('worker', 'alpha', message('missing', false)),
).resolves.toBe(false)
expect((await readRawMailbox('worker', 'alpha'))[0]?.read).toBe(false)
})
test('markMessageAsReadByIdentity returns false on corrupt mailbox content', async () => {
const inboxPath = getInboxPath('worker', 'alpha')
await mkdir(dirname(inboxPath), { recursive: true })
await writeFile(inboxPath, '{not-json', 'utf-8')
await expect(
markMessageAsReadByIdentity('worker', 'alpha', message('missing', false)),
).resolves.toBe(false)
})
})
describe('getLastPeerDmSummary', () => {
test('extracts the final peer direct-message summary from assistant tool use', () => {
const messages = [
{ type: 'user', message: { content: 'wake up' } },
{
type: 'assistant',
message: {
content: [
{
type: 'tool_use',
name: 'SendMessage',
input: {
to: 'worker-1',
message: 'please check the UDS bounds',
summary: 'Checking UDS bounds',
},
},
],
},
},
] as unknown as Message[]
expect(getLastPeerDmSummary(messages)).toBe(
'[to worker-1] Checking UDS bounds',
)
})
test('stops peer direct-message summary search at the wake-up boundary', () => {
const messages = [
{
type: 'assistant',
message: {
content: [
{
type: 'tool_use',
name: 'SendMessage',
input: {
to: 'worker-1',
message: 'old message',
},
},
],
},
},
{ type: 'user', message: { content: 'new prompt' } },
] as unknown as Message[]
expect(getLastPeerDmSummary(messages)).toBeUndefined()
})
})

View File

@@ -0,0 +1,614 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
import {
chmod,
mkdir,
mkdtemp,
readdir,
rm,
stat,
symlink,
unlink,
writeFile,
} from 'node:fs/promises'
import { createHash } from 'node:crypto'
import { createConnection, createServer } from 'node:net'
import { dirname, join } from 'node:path'
import { tmpdir } from 'node:os'
import {
drainInbox,
getDefaultUdsSocketPath,
MAX_UDS_INBOX_ENTRIES,
MAX_UDS_INBOX_BYTES,
MAX_UDS_FRAME_BYTES,
MAX_UDS_CLIENTS,
formatUdsAddress,
parseUdsTarget,
sendUdsMessage,
setOnEnqueue,
startUdsMessaging,
stopUdsMessaging,
UDS_AUTH_TIMEOUT_MS,
} from '../udsMessaging.js'
let previousConfigDir: string | undefined
let tempConfigDir = ''
function socketPath(label: string): string {
const suffix = `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}-${label}`
if (process.platform === 'win32') {
return `\\\\.\\pipe\\claude-code-test-${suffix}`
}
return join(tmpdir(), 'claude-code-test', `${suffix}.sock`)
}
function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms))
}
async function waitForEnqueues(
expected: number,
sendMessages: () => Promise<void>,
): Promise<void> {
let count = 0
let resolveDone: (() => void) | undefined
const done = new Promise<void>(resolve => {
resolveDone = resolve
})
setOnEnqueue(() => {
count++
if (count >= expected) resolveDone?.()
})
await sendMessages()
await Promise.race([
done,
sleep(5_000).then(() => {
throw new Error(`Timed out waiting for ${expected} UDS enqueues`)
}),
])
setOnEnqueue(null)
}
beforeEach(async () => {
previousConfigDir = process.env.CLAUDE_CONFIG_DIR
tempConfigDir = await mkdtemp(join(tmpdir(), 'uds-messaging-home-'))
process.env.CLAUDE_CONFIG_DIR = tempConfigDir
})
afterEach(async () => {
setOnEnqueue(null)
drainInbox()
await stopUdsMessaging()
if (previousConfigDir === undefined) {
delete process.env.CLAUDE_CONFIG_DIR
} else {
process.env.CLAUDE_CONFIG_DIR = previousConfigDir
}
if (tempConfigDir) {
await rm(tempConfigDir, { recursive: true, force: true })
tempConfigDir = ''
}
})
async function closeServer(server: ReturnType<typeof createServer>): Promise<void> {
await new Promise<void>(resolve => {
server.close(() => resolve())
})
}
describe('UDS inbox retention', () => {
test('drainInbox returns each pending socket message once', async () => {
const path = socketPath('drain')
await startUdsMessaging(path, { isExplicit: true })
expect(process.env.CLAUDE_CODE_MESSAGING_TOKEN).toBeUndefined()
await waitForEnqueues(2, async () => {
await sendUdsMessage(path, { type: 'text', data: 'one' })
await sendUdsMessage(path, { type: 'text', data: 'two' })
})
const drained = drainInbox()
expect(drained.map(entry => entry.message.data)).toEqual(['one', 'two'])
expect(drained.every(entry => entry.status === 'processed')).toBe(true)
expect(drainInbox()).toEqual([])
})
test('inbox is capped when messages arrive faster than they are drained', async () => {
const path = socketPath('cap')
await startUdsMessaging(path, { isExplicit: true })
await waitForEnqueues(MAX_UDS_INBOX_ENTRIES, async () => {
for (let i = 0; i < MAX_UDS_INBOX_ENTRIES; i++) {
await sendUdsMessage(path, { type: 'text', data: String(i) })
}
})
await expect(
sendUdsMessage(path, { type: 'text', data: 'overflow' }),
).rejects.toThrow('inbox full')
const drained = drainInbox()
expect(drained).toHaveLength(MAX_UDS_INBOX_ENTRIES)
expect(drained[0]?.message.data).toBe('0')
expect(drained.at(-1)?.message.data).toBe(String(MAX_UDS_INBOX_ENTRIES - 1))
})
test('inbox is capped by retained bytes before entry count', async () => {
const path = socketPath('byte-cap')
await startUdsMessaging(path, { isExplicit: true })
const payload = 'x'.repeat(32 * 1024)
let accepted = 0
for (;;) {
try {
await sendUdsMessage(path, { type: 'text', data: payload })
accepted++
if (accepted > MAX_UDS_INBOX_BYTES / payload.length + 20) {
throw new Error('byte cap was not enforced')
}
} catch (error) {
expect(error).toBeInstanceOf(Error)
expect((error as Error).message).toContain('inbox full')
break
}
}
const drained = drainInbox()
expect(drained.length).toBe(accepted)
expect(drained.length).toBeLessThan(MAX_UDS_INBOX_ENTRIES)
})
test('ping replies with pong without enqueueing inbox work', async () => {
const path = socketPath('ping')
await startUdsMessaging(path, { isExplicit: true })
await sendUdsMessage(path, { type: 'ping' })
expect(drainInbox()).toEqual([])
})
test('udsClient helpers authenticate through the capability file', async () => {
const path = socketPath('uds-client')
await startUdsMessaging(path, { isExplicit: true })
const { isPeerAlive, sendToUdsSocket } = await import('../udsClient.js')
expect(await isPeerAlive(path)).toBe(true)
await waitForEnqueues(1, async () => {
await sendToUdsSocket(path, 'hello from client')
})
const drained = drainInbox()
expect(drained).toHaveLength(1)
expect(drained[0]?.message.data).toBe('hello from client')
expect(drained[0]?.message.meta).toBeUndefined()
})
test('udsClient peer probe fails closed on oversized pong frames', async () => {
const path = socketPath('uds-client-oversized-pong')
if (process.platform !== 'win32') {
await mkdir(dirname(path), { recursive: true })
}
const receiver = createServer(socket => {
socket.on('data', () => {
socket.write('x'.repeat(MAX_UDS_FRAME_BYTES + 1))
})
})
await new Promise<void>((resolve, reject) => {
receiver.on('error', reject)
receiver.listen(path, () => resolve())
})
try {
const { isPeerAlive } = await import('../udsClient.js')
expect(await isPeerAlive(path, 3_000, 'test-token')).toBe(false)
} finally {
await closeServer(receiver)
if (process.platform !== 'win32') {
await unlink(path).catch(() => undefined)
}
}
})
test('udsClient send fails closed when no capability token exists', async () => {
const path = socketPath('uds-client-no-token')
const { sendToUdsSocket } = await import('../udsClient.js')
await expect(sendToUdsSocket(path, 'hello')).rejects.toThrow(
'No auth token found',
)
})
test('sendUdsMessage fails closed before connecting without an auth token', async () => {
await expect(
sendUdsMessage(socketPath('no-auth-token'), { type: 'text', data: 'x' }),
).rejects.toThrow('without auth token')
})
test('drained entries never expose the UDS auth token', async () => {
const path = socketPath('strip-token')
await startUdsMessaging(path, { isExplicit: true })
await waitForEnqueues(1, async () => {
await sendUdsMessage(path, {
type: 'notification',
meta: { keep: 'visible' },
})
})
const drained = drainInbox()
expect(drained).toHaveLength(1)
expect(drained[0]?.message.meta).toEqual({ keep: 'visible' })
expect(drained[0]?.message.meta).not.toHaveProperty('authToken')
})
test('rejects unauthenticated socket messages', async () => {
const path = socketPath('auth')
await startUdsMessaging(path, { isExplicit: true })
const response = await new Promise<string>((resolve, reject) => {
let responseText = ''
const conn = createConnection(path, () => {
conn.write(`${JSON.stringify({ type: 'text', data: 'bad' })}\n`)
})
conn.setTimeout(5_000, () => {
conn.destroy()
reject(new Error('Timed out waiting for auth rejection'))
})
conn.on('data', chunk => {
const text = chunk.toString('utf-8')
if (text.includes('\n')) {
responseText = text
}
})
conn.on('close', () => resolve(responseText))
conn.on('error', reject)
})
expect(JSON.parse(response).type).toBe('error')
expect(drainInbox()).toEqual([])
})
test('disconnects malformed JSON clients without enqueueing inbox work', async () => {
const path = socketPath('malformed-client')
await startUdsMessaging(path, { isExplicit: true })
const response = await new Promise<string>((resolve, reject) => {
let responseText = ''
const conn = createConnection(path, () => {
conn.write('{not-json\n')
})
conn.setTimeout(5_000, () => {
conn.destroy()
reject(new Error('Timed out waiting for malformed frame close'))
})
conn.on('data', chunk => {
responseText += chunk.toString('utf-8')
})
conn.on('close', () => resolve(responseText))
conn.on('error', reject)
})
const parsed = JSON.parse(response)
expect(parsed.type).toBe('error')
expect(parsed.data).toBe('invalid frame')
expect(drainInbox()).toEqual([])
})
test('disconnects idle unauthenticated clients', async () => {
const path = socketPath('idle-client')
await startUdsMessaging(path, { isExplicit: true })
const response = await new Promise<string>((resolve, reject) => {
let responseText = ''
const conn = createConnection(path)
conn.setTimeout(UDS_AUTH_TIMEOUT_MS + 2_000, () => {
conn.destroy()
reject(new Error('Timed out waiting for auth timeout close'))
})
conn.on('data', chunk => {
responseText += chunk.toString('utf-8')
})
conn.on('close', () => resolve(responseText))
conn.on('error', reject)
})
const parsed = JSON.parse(response)
expect(parsed.type).toBe('error')
expect(parsed.data).toBe('authentication timeout')
expect(drainInbox()).toEqual([])
})
test('destroys oversized frames before enqueueing inbox work', async () => {
const path = socketPath('oversized')
await startUdsMessaging(path, { isExplicit: true })
await new Promise<void>((resolve, reject) => {
const conn = createConnection(path, () => {
conn.write('x'.repeat(MAX_UDS_FRAME_BYTES + 1))
})
conn.setTimeout(5_000, () => {
conn.destroy()
reject(new Error('Timed out waiting for oversized frame close'))
})
conn.on('close', () => resolve())
conn.on('error', () => resolve())
})
expect(drainInbox()).toEqual([])
})
test('default socket path is regenerated after stop', async () => {
const firstPath = getDefaultUdsSocketPath()
await startUdsMessaging(firstPath)
await stopUdsMessaging()
expect(getDefaultUdsSocketPath()).not.toBe(firstPath)
})
test('rejects oversized receiver responses before retaining them', async () => {
const path = socketPath('oversized-response')
if (process.platform !== 'win32') {
await mkdir(dirname(path), { recursive: true })
}
const receiver = createServer(socket => {
socket.on('data', () => {
socket.write('x'.repeat(MAX_UDS_FRAME_BYTES + 1))
})
})
await new Promise<void>((resolve, reject) => {
receiver.on('error', reject)
receiver.listen(path, () => resolve())
})
try {
await expect(
sendUdsMessage(
path,
{ type: 'text', data: 'hello' },
{ authToken: 'test-token' },
),
).rejects.toThrow('UDS response frame exceeded size limit')
} finally {
await closeServer(receiver)
if (process.platform !== 'win32') {
await unlink(path).catch(() => undefined)
}
}
})
test('rejects closed receiver responses without waiting for timeout', async () => {
const path = socketPath('closed-response')
if (process.platform !== 'win32') {
await mkdir(dirname(path), { recursive: true })
}
const receiver = createServer(socket => {
socket.end()
})
await new Promise<void>((resolve, reject) => {
receiver.on('error', reject)
receiver.listen(path, () => resolve())
})
try {
await expect(
sendUdsMessage(
path,
{ type: 'text', data: 'hello' },
{ authToken: 'test-token' },
),
).rejects.toThrow('before response')
} finally {
await closeServer(receiver)
if (process.platform !== 'win32') {
await unlink(path).catch(() => undefined)
}
}
})
test('rejects malformed receiver responses without waiting for timeout', async () => {
const path = socketPath('malformed-response')
if (process.platform !== 'win32') {
await mkdir(dirname(path), { recursive: true })
}
const receiver = createServer(socket => {
socket.on('data', () => {
socket.write('{not-json\n')
})
})
await new Promise<void>((resolve, reject) => {
receiver.on('error', reject)
receiver.listen(path, () => resolve())
})
try {
await expect(
sendUdsMessage(
path,
{ type: 'text', data: 'hello' },
{ authToken: 'test-token' },
),
).rejects.toThrow('Invalid UDS response frame')
} finally {
await closeServer(receiver)
if (process.platform !== 'win32') {
await unlink(path).catch(() => undefined)
}
}
})
test('rejects inline auth token UDS targets instead of parsing them', async () => {
const path = socketPath('inline-token')
expect(formatUdsAddress(path)).toBe(`uds:${path}`)
const targetWithToken = `${path}#token=secret`
expect(() => parseUdsTarget(targetWithToken)).toThrow('inline auth token')
try {
parseUdsTarget(targetWithToken)
} catch (error) {
expect((error as Error).message).not.toContain('secret')
}
const { sendToUdsSocket } = await import('../udsClient.js')
await expect(sendToUdsSocket(targetWithToken, 'hello')).rejects.toThrow(
'inline auth token',
)
})
test('fails closed and cleans temp files when capability target is occupied', async () => {
const path = socketPath('capability-target-dir')
const capabilityDir = join(tempConfigDir, 'messaging-capabilities')
const capabilityName = `${createHash('sha256').update(path).digest('hex')}.json`
await mkdir(join(capabilityDir, capabilityName), {
recursive: true,
mode: 0o700,
})
await expect(
startUdsMessaging(path, { isExplicit: true }),
).rejects.toThrow()
expect(process.env.CLAUDE_CODE_MESSAGING_SOCKET).toBeUndefined()
expect(await readdir(capabilityDir)).toEqual([capabilityName])
})
if (process.platform !== 'win32') {
test('creates the listening socket with owner-only permissions', async () => {
const path = socketPath('socket-mode')
await startUdsMessaging(path, { isExplicit: true })
const mode = (await stat(path)).mode & 0o777
expect(mode).toBe(0o600)
})
test('fails closed when the capability directory is not private', async () => {
const previousConfigDir = process.env.CLAUDE_CONFIG_DIR
const tempHome = join(
tmpdir(),
`uds-capability-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`,
)
process.env.CLAUDE_CONFIG_DIR = tempHome
const capabilityDir = join(tempHome, 'messaging-capabilities')
await mkdir(capabilityDir, { recursive: true, mode: 0o755 })
await chmod(capabilityDir, 0o755)
try {
const path = socketPath('broad-capdir')
await expect(
startUdsMessaging(path, { isExplicit: true }),
).rejects.toThrow('permissions are too broad')
await expect(stat(path)).rejects.toThrow()
} finally {
if (previousConfigDir === undefined) {
delete process.env.CLAUDE_CONFIG_DIR
} else {
process.env.CLAUDE_CONFIG_DIR = previousConfigDir
}
await rm(tempHome, { recursive: true, force: true })
}
})
test('fails closed when the capability directory is a symlink', async () => {
const previousConfigDir = process.env.CLAUDE_CONFIG_DIR
const tempHome = join(
tmpdir(),
`uds-capability-link-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`,
)
const target = join(tempHome, 'target')
process.env.CLAUDE_CONFIG_DIR = tempHome
await mkdir(target, { recursive: true, mode: 0o700 })
await symlink(target, join(tempHome, 'messaging-capabilities'), 'dir')
try {
await expect(
startUdsMessaging(socketPath('symlink-capdir'), { isExplicit: true }),
).rejects.toThrow('not a private directory')
} finally {
if (previousConfigDir === undefined) {
delete process.env.CLAUDE_CONFIG_DIR
} else {
process.env.CLAUDE_CONFIG_DIR = previousConfigDir
}
await rm(tempHome, { recursive: true, force: true })
}
})
test('fails closed when an explicit socket parent is not private', async () => {
const parent = join(
tmpdir(),
`uds-socket-parent-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`,
)
await mkdir(parent, { recursive: true, mode: 0o755 })
await chmod(parent, 0o755)
try {
await expect(
startUdsMessaging(join(parent, 'messaging.sock'), {
isExplicit: true,
}),
).rejects.toThrow('socket parent permissions are too broad')
} finally {
await rm(parent, { recursive: true, force: true })
}
})
test('fails closed when an explicit socket parent is a file', async () => {
const parentFile = join(
tmpdir(),
`uds-socket-parent-file-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`,
)
await writeFile(parentFile, 'not a directory', 'utf-8')
try {
await expect(
startUdsMessaging(join(parentFile, 'messaging.sock'), {
isExplicit: true,
}),
).rejects.toThrow('socket parent is not a directory')
} finally {
await rm(parentFile, { force: true })
}
})
test('stop tolerates an already removed socket path', async () => {
const path = socketPath('already-removed')
await startUdsMessaging(path, { isExplicit: true })
await unlink(path)
await stopUdsMessaging()
expect(process.env.CLAUDE_CODE_MESSAGING_SOCKET).toBeUndefined()
})
test('rejects clients over the configured connection cap', async () => {
const path = socketPath('client-cap')
await startUdsMessaging(path, { isExplicit: true })
const sockets: ReturnType<typeof createConnection>[] = []
try {
for (let i = 0; i < MAX_UDS_CLIENTS; i++) {
const socket = await new Promise<ReturnType<typeof createConnection>>(
(resolve, reject) => {
const conn = createConnection(path, () => resolve(conn))
conn.on('error', reject)
},
)
sockets.push(socket)
}
await new Promise<void>((resolve, reject) => {
const extra = createConnection(path)
extra.on('close', () => resolve())
extra.on('error', reject)
extra.setTimeout(5_000, () => {
extra.destroy()
reject(new Error('Timed out waiting for client cap close'))
})
})
} finally {
for (const socket of sockets) {
socket.destroy()
}
}
})
}
})

View File

@@ -0,0 +1,171 @@
import { describe, expect, test } from 'bun:test'
import { EventEmitter } from 'node:events'
import type { Socket } from 'node:net'
import { attachUdsResponseReader } from '../udsResponseReader.js'
class FakeSocket extends EventEmitter {
destroyed = false
ended = false
destroy(): this {
this.destroyed = true
this.emit('close', true)
return this
}
end(): this {
this.ended = true
this.emit('close', false)
return this
}
emitData(chunk: Buffer): void {
this.emit('data', chunk)
}
}
function asSocket(socket: FakeSocket): Socket {
return socket as unknown as Socket
}
describe('attachUdsResponseReader', () => {
test('tracks byte limits across split multibyte response chunks', () => {
const socket = new FakeSocket()
let settled = false
let settledError: Error | undefined
attachUdsResponseReader(asSocket(socket), {
maxFrameBytes: 128,
onSettled: error => {
settled = true
settledError = error
},
})
const multibyte = String.fromCodePoint(0x20ac)
const frame = Buffer.from(
JSON.stringify({ type: 'response', data: `ok ${multibyte}` }) + '\n',
'utf8',
)
const multibyteStart = frame.indexOf(Buffer.from(multibyte, 'utf8')[0])
socket.emitData(frame.subarray(0, multibyteStart + 1))
expect(settled).toBe(false)
socket.emitData(frame.subarray(multibyteStart + 1))
expect(settled).toBe(true)
expect(settledError).toBeUndefined()
expect(socket.ended).toBe(true)
})
test('rejects malformed response frames immediately', () => {
const socket = new FakeSocket()
let settledError: Error | undefined
attachUdsResponseReader(asSocket(socket), {
maxFrameBytes: 128,
onSettled: error => {
settledError = error
},
})
socket.emitData(Buffer.from('{bad-json}\n'))
expect(settledError?.message).toBe('Invalid UDS response frame')
expect(socket.destroyed).toBe(true)
})
test('skips blank frames before a valid response', () => {
const socket = new FakeSocket()
let settled = false
let settledError: Error | undefined
attachUdsResponseReader(asSocket(socket), {
maxFrameBytes: 128,
onSettled: error => {
settled = true
settledError = error
},
})
socket.emitData(Buffer.from('\n \n'))
expect(settled).toBe(false)
socket.emitData(Buffer.from(`${JSON.stringify({ type: 'response' })}\n`))
expect(settled).toBe(true)
expect(settledError).toBeUndefined()
expect(socket.ended).toBe(true)
})
test('rejects receiver error frames', () => {
const socket = new FakeSocket()
let settledError: Error | undefined
attachUdsResponseReader(asSocket(socket), {
maxFrameBytes: 128,
onSettled: error => {
settledError = error
},
})
socket.emitData(
Buffer.from(`${JSON.stringify({ type: 'error', data: 'denied' })}\n`),
)
expect(settledError?.message).toBe('denied')
expect(socket.destroyed).toBe(true)
})
test('uses custom socket error formatting', () => {
const socket = new FakeSocket()
let settledError: Error | undefined
attachUdsResponseReader(asSocket(socket), {
maxFrameBytes: 128,
onSettled: error => {
settledError = error
},
formatSocketError: error =>
new Error(`wrapped:${(error as Error).message}`),
})
socket.emit('error', new Error('connect failed'))
expect(settledError?.message).toBe('wrapped:connect failed')
expect(socket.destroyed).toBe(true)
})
test('rejects socket end before response', () => {
const socket = new FakeSocket()
let settledError: Error | undefined
attachUdsResponseReader(asSocket(socket), {
maxFrameBytes: 128,
onSettled: error => {
settledError = error
},
})
socket.emit('end')
expect(settledError?.message).toBe('UDS socket ended before response')
expect(socket.destroyed).toBe(true)
})
test('rejects clean socket close before response', () => {
const socket = new FakeSocket()
let settledError: Error | undefined
attachUdsResponseReader(asSocket(socket), {
maxFrameBytes: 128,
onSettled: error => {
settledError = error
},
})
socket.emit('close', false)
expect(settledError?.message).toBe('UDS socket closed before response')
expect(socket.destroyed).toBe(true)
})
})