acp.e2e.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'
  2. import { Readable, Writable } from 'node:stream'
  3. import { mkdtemp, rm, readFile } from 'node:fs/promises'
  4. import { tmpdir } from 'node:os'
  5. import { join } from 'node:path'
  6. import { fileURLToPath } from 'node:url'
  7. import { afterEach, describe, expect, it } from 'vitest'
  8. import {
  9. ClientSideConnection,
  10. ndJsonStream,
  11. PROTOCOL_VERSION,
  12. type Agent as AcpAgent,
  13. type Client,
  14. type RequestPermissionRequest,
  15. type RequestPermissionResponse,
  16. type SessionNotification,
  17. } from '@agentclientprotocol/sdk'
  18. /**
  19. * End-to-end: boot examples/acp-agent as a real subprocess speaking ACP over
  20. * its stdio, drive it with a real ClientSideConnection, send a real prompt, and
  21. * verify the WORLD (a file the agent wrote), not the agent's self-report. Owns
  22. * and disposes the subprocess in afterEach. Key-gated.
  23. *
  24. * Also asserts stdout purity (only framed JSON-RPC on stdout) — that one runs
  25. * WITHOUT a key, since it only needs the server to boot and answer initialize.
  26. */
  27. // The dsh-acp-agent bin (the demo:acp entry) and this example's cordis.yml. The
  28. // bin resolves its config-path arg from CWD; the subprocess runs from a temp
  29. // workdir, so pass the example config's ABSOLUTE path.
  30. const binScript = fileURLToPath(new URL('../../../packages/ui/acp-agent/src/bin.ts', import.meta.url))
  31. const configPath = fileURLToPath(new URL('../cordis.yml', import.meta.url))
  32. // Resolve tsx's loader to an ABSOLUTE path: the subprocess runs with cwd set to
  33. // a temp workdir (this test launches there and uses it as the session cwd; the
  34. // bridge no longer requires cwd === the launch dir, but a temp dir keeps the
  35. // test hermetic), where a bare `--import tsx` would not resolve from
  36. // node_modules. import.meta.resolve gives the worktree's tsx regardless of cwd.
  37. const tsxLoader = fileURLToPath(import.meta.resolve('tsx'))
  38. // Absolute path to the repo-root tsconfig. Dev/test/demo run UNBUILT: the
  39. // `@deepseek-ai/dsh-*` workspace imports resolve through the `paths` map in the
  40. // root tsconfig (tsx reads it), NOT through built `lib/` output. But tsx finds
  41. // that tsconfig by searching UP from the child's cwd — and the child's cwd is a
  42. // temp workdir OUTSIDE the repo, so the search misses and the dsh-* imports fail
  43. // (the child dies before writing a byte). Point tsx at the repo tsconfig
  44. // explicitly via TSX_TSCONFIG_PATH so resolution is cwd-independent. (Without
  45. // this the suite only passed by accident when a stale built `lib/` happened to
  46. // exist — exactly the contamination that masked the inject bug this suite now
  47. // guards.) The repo root is four levels up from this file (examples/acp-agent/tests).
  48. const repoTsconfig = fileURLToPath(new URL('../../../tsconfig.json', import.meta.url))
  49. interface Spawned {
  50. child: ChildProcessWithoutNullStreams
  51. client: ClientSideConnection
  52. updates: SessionNotification['update'][]
  53. stderr: string[]
  54. }
  55. function spawnAcpAgent(cwd: string, env: NodeJS.ProcessEnv = process.env): Spawned {
  56. const child = spawn(
  57. process.execPath,
  58. ['--import', tsxLoader, binScript, configPath],
  59. { cwd, env: { ...env, TSX_TSCONFIG_PATH: repoTsconfig }, stdio: ['pipe', 'pipe', 'pipe'] },
  60. )
  61. const stderr: string[] = []
  62. child.stderr.setEncoding('utf8')
  63. child.stderr.on('data', (chunk: string) => stderr.push(chunk))
  64. const updates: SessionNotification['update'][] = []
  65. const stream = ndJsonStream(
  66. Writable.toWeb(child.stdin) as WritableStream<Uint8Array>,
  67. Readable.toWeb(child.stdout) as ReadableStream<Uint8Array>,
  68. )
  69. const makeClient = (_agent: AcpAgent): Client => ({
  70. sessionUpdate(params: SessionNotification): Promise<void> {
  71. updates.push(params.update)
  72. return Promise.resolve()
  73. },
  74. requestPermission(_params: RequestPermissionRequest): Promise<RequestPermissionResponse> {
  75. // Permission gate is deferred (TODO(rfc010-permission-gate)); the bridge
  76. // never requests permission yet, so just allow if it ever does.
  77. return Promise.resolve({ outcome: { outcome: 'cancelled' } })
  78. },
  79. })
  80. const client = new ClientSideConnection(makeClient, stream)
  81. return { child, client, updates, stderr }
  82. }
  83. let spawned: Spawned | undefined
  84. let workdir: string | undefined
  85. afterEach(async () => {
  86. if (spawned) {
  87. spawned.child.kill('SIGKILL')
  88. spawned = undefined
  89. }
  90. if (workdir !== undefined) await rm(workdir, { recursive: true, force: true })
  91. workdir = undefined
  92. })
  93. describe('acp-agent over real stdio (no key required)', () => {
  94. it('emits only framed JSON-RPC on stdout', async () => {
  95. workdir = await mkdtemp(join(tmpdir(), 'acp-e2e-'))
  96. // Collect raw stdout bytes directly (bypass the SDK framing) to inspect.
  97. // A dummy key lets the deepseek adapter APPLY (it only checks the key is
  98. // present at boot, not valid — the key is used only on a real model call,
  99. // which this purity test never triggers). So this runs WITHOUT real creds.
  100. const child = spawn(process.execPath, ['--import', tsxLoader, binScript, configPath], {
  101. cwd: workdir,
  102. env: { ...process.env, DEEPSEEK_API_KEY: process.env.DEEPSEEK_API_KEY ?? 'sk-dummy-for-boot', TSX_TSCONFIG_PATH: repoTsconfig },
  103. stdio: ['pipe', 'pipe', 'pipe'],
  104. })
  105. const out: string[] = []
  106. child.stdout.setEncoding('utf8')
  107. child.stdout.on('data', (c: string) => out.push(c))
  108. // Send a single initialize request as a newline-delimited JSON-RPC frame.
  109. const req = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} } })
  110. child.stdin.write(req + '\n')
  111. // Give it a moment to boot + reply, then inspect stdout.
  112. await new Promise(r => setTimeout(r, 4000))
  113. child.kill('SIGKILL')
  114. const lines = out.join('').split('\n').filter(l => l.trim().length > 0)
  115. expect(lines.length).toBeGreaterThan(0)
  116. for (const line of lines) {
  117. // Every stdout line MUST parse as JSON (a JSON-RPC frame). A non-JSON
  118. // line means a logger/print leaked onto the protocol channel.
  119. expect(() => JSON.parse(line) as unknown).not.toThrow()
  120. }
  121. }, 30_000)
  122. it('session/new succeeds over real stdio (no model call)', async () => {
  123. // REGRESSION GUARD (this exact RPC crashed a real Zed session with
  124. // "cannot get property \"agents\" without inject"): `session/new` drives the
  125. // full bridge → `ctx.agents.create({sessionId, meta:{cwd}})` → AgentLoop →
  126. // registry/persistence path, ALL of which run from the JSON-RPC read loop
  127. // OUTSIDE the bridge plugin's injection scope. A lazy `ctx.<service>` read
  128. // on that path throws and the RPC fails with an Internal error — yet the
  129. // call never touches the model, so this reproduces WITHOUT a key. The
  130. // key-gated prompt test below never caught it (it needs real creds); the
  131. // initialize-only purity test never caught it (initialize does not reach
  132. // the factory). This closes that gap: boot the real subprocess and create a
  133. // session, asserting the RPC RESOLVES (not rejects with an inject error).
  134. workdir = await mkdtemp(join(tmpdir(), 'acp-e2e-'))
  135. // A dummy key lets the deepseek adapter boot (it only checks presence, not
  136. // validity, at apply time); no model call is made, so the key is never used.
  137. spawned = spawnAcpAgent(workdir, { ...process.env, DEEPSEEK_API_KEY: process.env.DEEPSEEK_API_KEY ?? 'sk-dummy-for-boot' })
  138. const { client } = spawned
  139. await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  140. const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] })
  141. expect(typeof sessionId).toBe('string')
  142. expect(sessionId.length).toBeGreaterThan(0)
  143. }, 60_000)
  144. })
  145. describe.skipIf(!process.env.DEEPSEEK_API_KEY)('acp-agent e2e: real prompt over ACP', () => {
  146. it('runs a real turn and the agent writes the requested file (verified on disk)', async () => {
  147. workdir = await mkdtemp(join(tmpdir(), 'acp-e2e-'))
  148. spawned = spawnAcpAgent(workdir)
  149. const { client, updates } = spawned
  150. await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  151. // Any absolute cwd is honored now; use the temp `workdir` as this session's
  152. // workspace (the bash tool will run there) — it need not equal the launch dir.
  153. const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] })
  154. const res = await client.prompt({
  155. sessionId,
  156. prompt: [{ type: 'text', text: 'Use the bash tool to write the exact text ACP_OK into a file named proof.txt in the current directory. Then stop.' }],
  157. })
  158. expect(['end_turn', 'max_tokens']).toContain(res.stopReason)
  159. // Verify the WORLD, not the agent's self-report: read the file from disk.
  160. const proof = await readFile(join(workdir, 'proof.txt'), 'utf8')
  161. expect(proof).toContain('ACP_OK')
  162. // And the client saw tool-call activity stream through.
  163. const toolCalls = updates.filter(u => u.sessionUpdate === 'tool_call')
  164. expect(toolCalls.length).toBeGreaterThan(0)
  165. // Tool-call UI quality (the tool owns its presentation): the bash tool's
  166. // `presentCall` sets the title to the exact command (an execute card hides
  167. // rawInput, so the command IS the title) — NOT the bare tool name "bash".
  168. // A `bash` call must therefore carry an execute kind, a non-"bash" title,
  169. // and a string rawInput (the command). `toolCalls` is already narrowed to
  170. // the `tool_call` shape by the filter above, so these fields are reachable.
  171. const bashCall = toolCalls.find(u => u.kind === 'execute')
  172. expect(bashCall).toBeDefined()
  173. if (bashCall === undefined) throw new Error('expected an execute tool_call')
  174. expect(typeof bashCall.title).toBe('string')
  175. expect(bashCall.title.length).toBeGreaterThan(0)
  176. expect(bashCall.title).not.toBe('bash') // the old, unhelpful title
  177. expect(typeof bashCall.rawInput).toBe('string') // the exact command
  178. // Capability OFF: no terminal _meta — the ```console text path renders.
  179. expect((bashCall as { _meta?: unknown })._meta).toBeUndefined()
  180. }, 180_000)
  181. it('with the terminal_output capability, a real bash call renders as a terminal card (content + _meta + exit)', async () => {
  182. workdir = await mkdtemp(join(tmpdir(), 'acp-e2e-'))
  183. spawned = spawnAcpAgent(workdir)
  184. const { client, updates } = spawned
  185. // Advertise the Zed `_meta.terminal_output` capability so the bridge emits
  186. // the terminal card for the real bash tool.
  187. await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: { _meta: { terminal_output: true } } })
  188. const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] })
  189. const res = await client.prompt({
  190. sessionId,
  191. prompt: [{ type: 'text', text: 'Use the bash tool to run: echo ACP_TERMINAL_OK. Then stop.' }],
  192. })
  193. expect(['end_turn', 'max_tokens']).toContain(res.stopReason)
  194. // A bash tool_call now carries a terminal content block + _meta.terminal_info
  195. // with the session cwd as the header; the matching update streams the output
  196. // on _meta.terminal_output.
  197. const bashCall = updates.find(u => u.sessionUpdate === 'tool_call' && u.kind === 'execute')
  198. if (bashCall?.sessionUpdate !== 'tool_call') throw new Error('expected an execute tool_call')
  199. // The content carries the description text block AND a terminal block (the
  200. // description renders above the card) — find the terminal block by type, not
  201. // by position.
  202. const blocks = (bashCall.content ?? []) as { type: string; terminalId?: string }[]
  203. const terminalBlock = blocks.find(b => b.type === 'terminal')
  204. expect(terminalBlock).toBeDefined()
  205. expect(typeof terminalBlock?.terminalId).toBe('string')
  206. const info = (bashCall._meta as { terminal_info?: { terminal_id: string; cwd?: string } }).terminal_info
  207. expect(info?.cwd).toBe(workdir)
  208. const updatesForTerminal = updates.filter(u => u.sessionUpdate === 'tool_call_update' && (u._meta as { terminal_output?: unknown } | undefined)?.terminal_output !== undefined)
  209. expect(updatesForTerminal.length).toBeGreaterThan(0)
  210. // The completed update also carries the parsed exit on _meta.terminal_exit.
  211. const exitUpdate = updates.find(u => u.sessionUpdate === 'tool_call_update' && (u._meta as { terminal_exit?: unknown } | undefined)?.terminal_exit !== undefined)
  212. expect(exitUpdate).toBeDefined()
  213. }, 180_000)
  214. })