ds-harness-remote-fast/packages/plugin/tests/acp-antigravity-process.tes...

438 lines
15 KiB
TypeScript

import { EventEmitter } from 'node:events'
import { PassThrough } from 'node:stream'
import type { ChildProcessWithoutNullStreams } from 'node:child_process'
import { describe, expect, it, vi } from 'vitest'
import { AntigravityAcpClient } from '../src/acp/adapters/antigravity-process.js'
import { createAntigravityAcpAdapter } from '../src/acp/adapters/antigravity.js'
import { cursorBinaryCandidates } from '../src/acp/gateway.js'
import type { SafeLogger } from '../src/logging.js'
describe('AntigravityAcpClient', () => {
it('handles stream-json init, prompt and step_updates', async () => {
const fake = fakeProcess()
const outbound: Array<Record<string, unknown>> = []
fake.child.stdin.on('data', chunk => {
for (const line of String(chunk).trim().split('\n')) {
if (!line.trim()) continue
const message = JSON.parse(line) as Record<string, unknown>
outbound.push(message)
if (message.event === 'user') {
// Emit step updates and result
fake.stdout.write(`${JSON.stringify({
event: 'step_update',
step_update: {
conversation_id: 'conv_123',
step_index: 0,
state: 'ACTIVE',
step_type: 'thought',
text_delta: 'thinking deep thoughts',
},
})}\n`)
fake.stdout.write(`${JSON.stringify({
event: 'step_update',
step_update: {
conversation_id: 'conv_123',
step_index: 1,
state: 'ACTIVE',
step_type: 'agent_response',
text_delta: 'hello from antigravity',
},
})}\n`)
fake.stdout.write(`${JSON.stringify({
event: 'step_update',
step_update: {
conversation_id: 'conv_123',
step_index: 2,
state: 'ACTIVE',
step_type: 'tool',
tool_name: 'test_tool',
tool_info: { name: 'test_tool', parameters: { a: 1 } },
},
})}\n`)
fake.stdout.write(`${JSON.stringify({
event: 'step_update',
step_update: {
conversation_id: 'conv_123',
step_index: 2,
state: 'DONE',
step_type: 'tool',
tool_name: 'test_tool',
tool_info: { name: 'test_tool', output: 'ok' },
},
})}\n`)
fake.stdout.write(`${JSON.stringify({
event: 'result',
result: {
conversation_id: 'conv_123',
status: 'SUCCESS',
response: 'hello from antigravity',
},
})}\n`)
}
}
})
const client = new AntigravityAcpClient('agy-custom', logger(), (bin, args) => {
expect(bin).toBe('agy-custom')
expect(args).toEqual(['--input-format', 'stream-json', '--output-format', 'stream-json', '--add-dir', expect.any(String)])
// Emit init event from agy
setTimeout(() => {
fake.stdout.write(`${JSON.stringify({
event: 'init',
conversation_id: 'conv_123',
init: { cwd: '/test' },
})}\n`)
}, 10)
return fake.child
}, { cwd: '/test' })
const inbound = vi.fn()
client.onInbound(inbound)
await client.start()
expect(client.isReady()).toBe(true)
const initResult = await client.call('initialize', {})
expect(initResult).toHaveProperty('agentInfo.name', 'antigravity')
const newSession = await client.call('session/new', { cwd: '/test' })
expect(newSession).toEqual({ sessionId: 'conv_123' })
const promptPromise = client.call('session/prompt', {
sessionId: 'conv_123',
prompt: [{ type: 'text', text: 'hi' }],
})
const result = await promptPromise
expect(result).toHaveProperty('stopReason', 'end_turn')
expect(outbound[0]).toEqual({
event: 'user',
message: { content: 'hi' },
})
// Verify notifications were delivered to inbound
expect(inbound).toHaveBeenCalledWith({
kind: 'notification',
method: 'session/update',
params: {
sessionId: 'conv_123',
update: {
sessionUpdate: 'agent_thought_chunk',
text: 'thinking deep thoughts',
},
},
})
expect(inbound).toHaveBeenCalledWith({
kind: 'notification',
method: 'session/update',
params: {
sessionId: 'conv_123',
update: {
sessionUpdate: 'agent_message_chunk',
text: 'hello from antigravity',
},
},
})
expect(inbound).toHaveBeenCalledWith({
kind: 'notification',
method: 'session/update',
params: {
sessionId: 'conv_123',
update: {
sessionUpdate: 'tool_call',
callId: '2',
name: 'test_tool',
parameters: { a: 1 },
},
},
})
expect(inbound).toHaveBeenCalledWith({
kind: 'notification',
method: 'session/update',
params: {
sessionId: 'conv_123',
update: {
sessionUpdate: 'tool_call_update',
callId: '2',
status: 'completed',
output: 'ok',
},
},
})
await client.close()
expect(client.isReady()).toBe(false)
})
it('uses warmed distinct conversations and routes prompts back to their own process', async () => {
const processes: ReturnType<typeof fakeProcess>[] = []
const messages: Array<{ process: number; content: string }> = []
const client = new AntigravityAcpClient('agy', logger(), (_bin, args, cwd) => {
const fake = fakeProcess()
const index = processes.push(fake) - 1
const id = `conversation-${index}`
expect(cwd).toBe('/test')
expect(args).not.toContain('--conversation')
fake.stdin.on('data', chunk => {
const payload = JSON.parse(String(chunk))
messages.push({ process: index, content: payload.message.content })
fake.stdout.write(JSON.stringify({ event: 'result', result: { conversation_id: id, status: 'SUCCESS' } }) + '\n')
})
queueMicrotask(() => fake.stdout.write(JSON.stringify({ event: 'init', conversation_id: id }) + '\n'))
return fake.child
}, { cwd: '/test' })
await client.start()
const first = await client.call('session/new', { cwd: '/test' }) as { sessionId: string }
await Promise.resolve()
const beforeCreate = processes.length
const second = await client.call('session/new', { cwd: '/test' }) as { sessionId: string }
expect(first.sessionId).toBe('conversation-0')
expect(second.sessionId).toBe('conversation-1')
expect(processes[0]!.child.kill).not.toHaveBeenCalled()
// The create claims process 1; only the next spare is spawned afterwards.
expect(processes.length).toBe(beforeCreate + 1)
await client.call('session/prompt', { sessionId: second.sessionId, prompt: [{ type: 'text', text: 'new' }] })
await client.call('session/prompt', { sessionId: first.sessionId, prompt: [{ type: 'text', text: 'old' }] })
expect(messages).toEqual([{ process: 1, content: 'new' }, { process: 0, content: 'old' }])
await client.close()
expect(processes[0]!.child.kill).toHaveBeenCalled()
expect(processes[1]!.child.kill).toHaveBeenCalled()
})
it('prewarms the selected directory once and preserves claimed sessions', async () => {
const processes: ReturnType<typeof fakeProcess>[] = []
const directories: string[] = []
const writes = vi.fn()
const client = new AntigravityAcpClient('agy', logger(), (_bin, _args, cwd) => {
const fake = fakeProcess()
const index = processes.push(fake) - 1
directories.push(cwd!)
fake.stdin.on('data', writes)
queueMicrotask(() => fake.stdout.write(JSON.stringify({ event: 'init', conversation_id: `warm-${index}` }) + '\n'))
return fake.child
}, { cwd: '/host' })
await client.start()
const first = await client.call('session/new', { cwd: '/host' })
expect(first).toEqual({ sessionId: 'warm-0' })
await vi.waitFor(() => expect(directories).toEqual(['/host', '/host']))
client.prewarmSession('/selected')
client.prewarmSession('/selected')
await vi.waitFor(() => expect(directories).toEqual(['/host', '/host', '/selected']))
await vi.waitFor(() => expect(processes[1]!.child.kill).toHaveBeenCalled())
expect(processes[0]!.child.kill).not.toHaveBeenCalled()
expect(writes).not.toHaveBeenCalled()
expect(await client.call('session/new', { cwd: '/selected' })).toEqual({ sessionId: 'warm-2' })
expect(processes[2]!.child.kill).not.toHaveBeenCalled()
await client.close()
for (const process of processes) expect(process.child.kill).toHaveBeenCalled()
})
it('cancels pending prompt cleanly', async () => {
const fake = fakeProcess()
const client = new AntigravityAcpClient('agy', logger(), () => {
setTimeout(() => {
fake.stdout.write(`${JSON.stringify({
event: 'init',
conversation_id: 'conv_cancel',
init: {},
})}\n`)
}, 5)
return fake.child
})
await client.start()
await client.call('session/new', {})
const promptPromise = client.call('session/prompt', {
sessionId: 'conv_cancel',
prompt: [{ type: 'text', text: 'cancel me' }],
})
const cancelResult = await client.call('session/cancel', { sessionId: 'conv_cancel' })
expect(cancelResult).toEqual({ cancelled: true })
const promptResult = await promptPromise
expect(promptResult).toEqual({ stopReason: 'cancelled' })
await client.close()
})
it('rejects start when the agy process cannot be spawned', async () => {
const fake = fakeProcess()
const client = new AntigravityAcpClient('missing-agy', logger(), () => {
queueMicrotask(() => fake.child.emit('error', new Error('spawn ENOENT')))
return fake.child
})
await expect(client.start()).rejects.toMatchObject({
code: 'ANTIGRAVITY_BINARY_UNAVAILABLE',
})
expect(client.isReady()).toBe(false)
})
it('resolves binary candidates and creates adapter', () => {
const candidates = cursorBinaryCandidates('agent')
expect(candidates).not.toContain('agy')
expect(candidates).toContain('agent')
expect(cursorBinaryCandidates('agy')).toEqual([expect.stringContaining('agy'), 'agy'])
expect(cursorBinaryCandidates('opencode')).toEqual([
expect.stringContaining('.opencode'),
expect.stringContaining('.local'),
'opencode',
])
expect(cursorBinaryCandidates('custom-bin')).toEqual(['custom-bin'])
const adapter = createAntigravityAcpAdapter('agy-test', logger(), () => fakeProcess().child as any)
expect(adapter.id).toBe('antigravity')
})
it('passes skipPermissions and conversationId to agy args', async () => {
let passedArgs: string[] = []
const client = new AntigravityAcpClient('agy', logger(), (_bin, args) => {
passedArgs = args
const proc = fakeProcess()
setTimeout(() => {
proc.stdout.write(Buffer.from(JSON.stringify({ event: 'init', conversation_id: 'conv-opt-1' }) + '\n'))
}, 10)
return proc.child
}, { skipPermissions: true, conversationId: 'conv-opt-1', sessionWorker: true })
await client.start()
expect(passedArgs).toContain('--dangerously-skip-permissions')
expect(passedArgs).toContain('--conversation')
expect(passedArgs).toContain('conv-opt-1')
await client.close()
})
it('captures thinking from transcript.jsonl via watcher even if stream-json omits thought', async () => {
const os = await import('node:os')
const path = await import('node:path')
const fs = await import('node:fs/promises')
const testDir = await fs.mkdtemp(path.join(os.tmpdir(), 'agy-watcher-client-'))
const brainDir = path.join(testDir, 'conv_watcher_1', '.system_generated/logs')
await fs.mkdir(brainDir, { recursive: true })
const fake = fakeProcess()
const client = new AntigravityAcpClient('agy-custom', logger(), (_bin, _args) => {
setTimeout(() => {
fake.stdout.write(`${JSON.stringify({
event: 'init',
conversation_id: 'conv_watcher_1',
init: { cwd: '/test' },
})}\n`)
}, 10)
return fake.child
}, { cwd: '/test', brainDir: testDir, sessionWorker: true })
const inbound = vi.fn()
client.onInbound(inbound)
await client.start()
fake.child.stdin.on('data', async () => {
const plannerStep = {
step_index: 1,
type: 'PLANNER_RESPONSE',
status: 'DONE',
created_at: '2026-10-09T10:00:00Z',
thinking: 'I need to check the files first.',
tool_calls: [{ name: 'run_command', args: { CommandLine: 'ls' } }],
}
await fs.appendFile(path.join(brainDir, 'transcript.jsonl'), `${JSON.stringify(plannerStep)}\n`)
fake.stdout.write(`${JSON.stringify({
event: 'step_update',
step_update: {
conversation_id: 'conv_watcher_1',
step_index: 2,
state: 'ACTIVE',
step_type: 'tool',
tool_name: 'run_command',
tool_info: { name: 'run_command', parameters: { CommandLine: 'ls' } },
},
})}\n`)
fake.stdout.write(`${JSON.stringify({
event: 'result',
result: {
conversation_id: 'conv_watcher_1',
status: 'SUCCESS',
response: 'done',
},
})}\n`)
})
await client.call('session/prompt', {
sessionId: 'conv_watcher_1',
prompt: [{ type: 'text', text: 'check files' }],
})
expect(inbound).toHaveBeenCalledWith({
kind: 'notification',
method: 'session/update',
params: {
sessionId: 'conv_watcher_1',
update: {
sessionUpdate: 'agent_thought_chunk',
text: 'I need to check the files first.\n\n',
},
},
})
await client.close()
await fs.rm(testDir, { recursive: true, force: true }).catch(() => undefined)
})
})
function fakeProcess(): {
child: ChildProcessWithoutNullStreams
stdin: PassThrough
stdout: PassThrough
stderr: PassThrough
} {
const stdin = new PassThrough()
const stdout = new PassThrough()
const stderr = new PassThrough()
const emitter = new EventEmitter()
const kill = vi.fn((signal?: NodeJS.Signals | number) => {
Object.assign(child, { killed: true })
emitter.emit('exit', 0, signal ?? 'SIGTERM')
return true
})
const child = Object.assign(emitter, {
stdin,
stdout,
stderr,
stdio: [stdin, stdout, stderr] as [PassThrough, PassThrough, PassThrough],
killed: false,
pid: 1234,
exitCode: null,
signalCode: null,
spawnargs: [],
spawnfile: 'agy',
connected: false,
kill,
send: vi.fn(),
disconnect: vi.fn(),
unref: vi.fn(),
ref: vi.fn(),
}) as unknown as ChildProcessWithoutNullStreams
return { child, stdin, stdout, stderr }
}
function logger(): SafeLogger {
return {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
} as unknown as SafeLogger
}