fix(cua): satisfy typed lint and expose fixture failures

This commit is contained in:
creatixchu committed 2026-10-11 17:58:53 +08:00
1 parent b9de05d1c4
commit 5ea72ef0d2
7 files changed
+26 -21

No files matched your search

+2 -2
View File
@@ -142,7 +142,7 @@ interface CuaExecution extends ToolExecution {
}
/**
* Mount logged native operations with a separate helper per agent.
* Mount logged native operations with separate Agent connections to the shared helper.
* @param ctx - Host context with computer-use, subprocess and tool services.
* @param config - Validated native preparation and operation bounds.
* @returns Completion after native preparation and tool registration.
@@ -299,7 +299,7 @@ function mount(ctx: Context, config: Config, helperPath: string): void {
throw new NativeError('APP_ACCESS_REQUIRED', 'Select the application with getApp before reading or controlling it')
}
if (!client || (client.disposed && !('appHandle' in request.params))) {
client = new NativeClient(ctx, native, message => ctx.logger.debug(message))
client = new NativeClient(ctx, native, (message) => { ctx.logger.debug(message) })
clients.set(agent, client)
}
const nativeClient = client
@@ -14,7 +14,7 @@ const Reply = z.union([
const screenshotPrefix = '[cua-screenshot] '
const ScreenshotDiagnostic = z.object({
requestId: z.string(), stage: z.string(), elapsedMs: z.number().finite().nonnegative(), errorCode: z.string().optional(),
requestId: z.string(), stage: z.string(), elapsedMs: z.number().nonnegative(), errorCode: z.string().optional(),
})
const WireReply = z.union([Reply, ScreenshotDiagnostic.extend({ type: z.literal('diagnostic') })])
@@ -225,7 +225,6 @@ export class NativeClient {
}
private receive(chunk: Buffer): void {
if (this.failure) return
let offset = 0
while (offset < chunk.length && !this.failure) {
const newline = chunk.indexOf(10, offset)
+10 -9
View File
@@ -201,8 +201,7 @@ class SharedNativeChannel implements NativeChannel {
let peerEnded = false
let socketError: Error | undefined
let bytes = Buffer.alloc(0)
let accepted = false
let refused = false
const admission: { status: 'pending' | 'accepted' | 'refused' } = { status: 'pending' }
const abort = (): void => { socket.destroy(asError(this.startup.signal.reason)) }
this.startup.signal.addEventListener('abort', abort, { once: true })
socket.on('error', (error: Error) => { socketError = error; handshake.reject(error) })
@@ -223,7 +222,7 @@ class SharedNativeChannel implements NativeChannel {
const newline = chunk.indexOf(10)
const length = newline < 0 ? chunk.length : newline + 1
if (bytes.length + length > handshakeByteLimit) {
refused = true
admission.status = 'refused'
socket.destroy(transportError('NATIVE_PROTOCOL', 'Native handshake exceeded its byte limit'))
return
}
@@ -233,20 +232,20 @@ class SharedNativeChannel implements NativeChannel {
const value: unknown = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, -1)))
const refusal = Refusal.safeParse(value)
if (refusal.success) {
refused = true
admission.status = 'refused'
socket.destroy(transportError(refusal.data.code, refusal.data.message))
return
}
const ready = Ready.parse(value)
if (ready.runtimeKey !== runtimeKey) throw transportError('NATIVE_PROTOCOL', 'Native handshake returned a different runtime identity')
accepted = true
admission.status = 'accepted'
socket.removeListener('data', receive)
this.startup.signal.removeEventListener('abort', abort)
if (chunk.length > length) this.stdout.write(chunk.subarray(length))
socket.pipe(this.stdout, { end: false })
handshake.resolve()
} catch (error) {
refused = true
admission.status = 'refused'
socket.destroy(transportError('NATIVE_PROTOCOL', 'Native helper refused or returned an invalid handshake', error))
}
}
@@ -258,11 +257,11 @@ class SharedNativeChannel implements NativeChannel {
} catch (error) {
socket.destroy()
await ended.promise.catch(() => {})
if (!refused && !accepted && error instanceof Error && 'code' in error
if (admission.status === 'pending' && error instanceof Error && 'code' in error
&& ['ENOENT', 'ECONNREFUSED', 'ECONNRESET', 'NATIVE_EOF'].includes(String(error.code))) return undefined
throw error
} finally {
if (!accepted) socket.removeListener('data', receive)
if (admission.status !== 'accepted') socket.removeListener('data', receive)
}
}
@@ -273,7 +272,9 @@ class SharedNativeChannel implements NativeChannel {
controller.abort(transportError('NATIVE_CLEANUP', `Native startup cleanup exceeded ${this.config.graceMs}ms`))
}, this.config.graceMs)
try {
const [, launcher] = await untilAbort(Promise.allSettled([this.socketClosed, this.launcherExit] as const), controller.signal)
const [, launcher] = await untilAbort(Promise.allSettled([
Promise.resolve(this.socketClosed), Promise.resolve(this.launcherExit),
] as const), controller.signal)
if (launcher.status === 'fulfilled' && launcher.value) {
const range = launcher.value[1]
if (range.status === 'rejected') throw range.reason
@@ -144,7 +144,7 @@ it.skipIf(process.platform === 'win32')('delivers a valid PNG larger than 4 MiB
const messages = handle.agent.session.deriveMessages()
const result = messages.find(message => message.role === 'tool' && message.toolCallId === 'large-image-ptc')
if (result?.role !== 'tool') throw new Error('The PTC result was not recorded')
expect(result.isError).toBe(false)
expect(result.isError, JSON.stringify(result.content)).toBe(false)
expect(result.content.filter(block => block.type === 'text').map(block => block.text).join('\n')).toContain(String(encodedLength))
const nextImages = model.requests[1]?.messages.flatMap(message => message.content).filter(block => block.type === 'image')
expect(nextImages).toHaveLength(1)
@@ -102,7 +102,7 @@ it.skipIf(process.platform === 'win32')('shares one application between retained
expect(model.requests).toHaveLength(calls.length + 1)
const toolMessages = agent.session.deriveMessages().filter(message => message.role === 'tool')
expect(toolMessages).toHaveLength(calls.length)
expect(toolMessages.every(message => !message.isError)).toBe(true)
expect(toolMessages.filter(message => message.isError)).toEqual([])
expect(JSON.stringify(model.requests[0])).toContain('getCapabilities')
expect(JSON.stringify(model.requests[0])).toContain('appHandle')
expect(JSON.stringify(model.requests[0])).not.toContain('preloaded')
@@ -408,12 +408,13 @@ describe('native helper transport', () => {
it('retains the last screenshot phase after timeout and request cancellation', async () => {
vi.useFakeTimers()
try {
const reportDiagnostic = vi.fn()
const reportDiagnostic = vi.fn<(message: string) => void>()
const f = fixture({ timeoutMs: 25, reportDiagnostic })
const pending = f.client.request('screenshot', {}, new AbortController().signal, ToolCallId('capture-timeout'))
const rejected = expect(pending).rejects.toMatchObject({ code: 'NATIVE_TIMEOUT',
message: expect.stringContaining('"stage":"capture-image.begin"'),
})
const rejected = Promise.all([
expect(pending).rejects.toMatchObject({ code: 'NATIVE_TIMEOUT' }),
expect(pending).rejects.toThrow('"stage":"capture-image.begin"'),
])
f.reply({ type: 'diagnostic', requestId: 'capture-timeout', stage: 'capture-image.begin', elapsedMs: 2 })
await vi.advanceTimersByTimeAsync(25)
f.reply({ id: f.id(), error: { code: 'NATIVE_CANCELLED', message: 'Capture stopped' } })
@@ -450,7 +451,7 @@ describe('native helper transport', () => {
})
it('bounds retained screenshot diagnostics and keeps successful results out of model text', async () => {
const reportDiagnostic = vi.fn()
const reportDiagnostic = vi.fn<(message: string) => void>()
const f = fixture({ reportDiagnostic })
const pending = f.client.request('screenshot', {}, new AbortController().signal, ToolCallId('capture'))
for (let index = 0; index < 200; index++) {
@@ -57,7 +57,7 @@ async function fixture(options: {
for (const channel of channels) channel.close()
for (const socket of sockets) socket.destroy()
await Promise.all(channels.map(channel => channel.waitForClose().catch(() => {})))
await new Promise<void>((resolve) => { server.close(() => resolve()) })
await new Promise<void>((resolve) => { server.close(() => { resolve() }) })
runtime.source = ''
runtime.directory = ''
runtime.foreignOwner = false
@@ -184,6 +184,7 @@ describe.skipIf(process.platform === 'win32')('shared native Unix connection', (
await write(second, 'three\n')
expect(JSON.parse(String(await remaining))).toEqual({ sequence: 2, request: 'three' })
expect(f.spawn).toHaveBeenCalledTimes(2)
// oxlint-disable-next-line typescript/unbound-method -- Fixture termination methods are spies inspected without invocation.
for (const handle of f.handles) expect(handle.terminate).not.toHaveBeenCalled()
expect(f.hellos).toEqual([expect.objectContaining({ type: 'hello', protocol: 1, config: {
axTimeoutMs: 3000, timeoutMs: 30000, screenshotTimeoutMs: 5000, graceMs: 1000,
@@ -297,6 +298,7 @@ describe.skipIf(process.platform === 'win32')('shared native Unix connection', (
})
it('reports non-Error provider failures through the Error stream without losing their cause', async () => {
// oxlint-disable-next-line typescript/prefer-promise-reject-errors -- The provider's non-Error rejection is the test input.
const f = await fixture({ launch: () => ({ ...launcherFixture(), done: Promise.reject('provider unavailable') }) })
const channel = f.open()
await expect(channel.done).rejects.toMatchObject({ code: 'NATIVE_CONNECT', cause: 'provider unavailable' })
@@ -369,6 +371,7 @@ describe.skipIf(process.platform === 'win32')('shared native Unix connection', (
channel.close()
await expect(channel.waitForClose()).rejects.toMatchObject({ code: 'NATIVE_CLEANUP' })
await expect(channel.done).rejects.toMatchObject({ code: 'NATIVE_CLEANUP' })
// oxlint-disable-next-line typescript/unbound-method -- The fixture spy is inspected without invoking the method.
expect(f.handles[0]?.terminate).not.toHaveBeenCalled()
})
@@ -520,6 +523,7 @@ describe.skipIf(process.platform === 'win32')('shared native Unix connection', (
if (attempts === 1) socket.end()
else socket.write(ready)
} })
// oxlint-disable-next-line typescript/unbound-method -- Reflect.apply below supplies the original Socket receiver.
const originalEmit = Socket.prototype.emit
let injected = false
// Unix kernels differ in reporting close as EOF or ECONNRESET; inject only that error event.