load.spec.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. import { afterEach, beforeEach, describe, expect, it } from 'vitest'
  2. import { mkdtemp, rm } from 'node:fs/promises'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk'
  6. import { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session'
  7. import { makeBridgeHarness, textResponse, toolCallResponse, type BridgeHarness, type CapturedUpdate } from './harness.ts'
  8. /** Concatenate the text of all agent_message_chunk updates. */
  9. function messageText(updates: CapturedUpdate[]): string {
  10. return updates
  11. .filter(u => u.sessionUpdate === 'agent_message_chunk')
  12. .map(u => (u.content.type === 'text' ? u.content.text : ''))
  13. .join('')
  14. }
  15. describe('acp bridge — session/load replay', () => {
  16. let storageDir: string
  17. let live: BridgeHarness | undefined
  18. let loader: BridgeHarness | undefined
  19. beforeEach(async () => { storageDir = await mkdtemp(join(tmpdir(), 'acp-load-')) })
  20. afterEach(async () => {
  21. if (live) await live.dispose()
  22. if (loader) await loader.dispose()
  23. live = loader = undefined
  24. await rm(storageDir, { recursive: true, force: true })
  25. })
  26. it('replays a persisted turn from the event log as session/update on load', async () => {
  27. // 1. Create a session and run one turn — persistence writes the event log.
  28. live = await makeBridgeHarness({ storageDir, script: [textResponse('remembered answer')] })
  29. await live.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  30. const { sessionId } = await live.client.newSession({ cwd: process.cwd(), mcpServers: [] })
  31. await live.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'remember this' }] })
  32. // Dispose to flush + release; the on-disk log persists.
  33. await live.dispose()
  34. live = undefined
  35. // 2. A fresh bridge loads the same session id and must replay the turn.
  36. loader = await makeBridgeHarness({ storageDir, script: [] })
  37. await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  38. const res = await loader.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] })
  39. expect(res).toBeDefined()
  40. // The replayed updates reconstruct the assistant text from the event log
  41. // (assistant/chunk → agent_message_chunk), NOT from deriveMessages.
  42. expect(messageText(loader.updates)).toBe('remembered answer')
  43. // And the USER side of the turn replays too (user/message →
  44. // user_message_chunk), so the editor transcript shows both sides.
  45. const userText = loader.updates
  46. .filter(u => u.sessionUpdate === 'user_message_chunk')
  47. .map(u => (u.content.type === 'text' ? u.content.text : ''))
  48. .join('')
  49. expect(userText).toBe('remember this')
  50. })
  51. it('replays a persisted tool call with the TOOL-OWNED presentation (title/rawInput/console output)', async () => {
  52. // Persist a real bash call, then replay it through a fresh bridge. A throwaway presenter pairs
  53. // call and result in log order so replay uses the shipping tool's same cards as live streaming.
  54. live = await makeBridgeHarness({
  55. storageDir,
  56. withBash: true,
  57. script: [toolCallResponse('c1', 'bash', { command: 'echo hello', description: 'Print a greeting' }), textResponse('done')],
  58. })
  59. await live.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  60. const { sessionId } = await live.client.newSession({ cwd: process.cwd(), mcpServers: [] })
  61. await live.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'greet' }] })
  62. await live.dispose()
  63. live = undefined
  64. // A fresh bridge — also with the real bash tool, since the presentation is
  65. // resolved from the live registry at replay time — loads the session.
  66. loader = await makeBridgeHarness({ storageDir, withBash: true, script: [] })
  67. await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  68. await loader.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] })
  69. const call = loader.updates.find(u => u.sessionUpdate === 'tool_call')
  70. expect(call).toMatchObject({ toolCallId: 'c1', title: 'echo hello', kind: 'execute', rawInput: 'echo hello' })
  71. if (call?.sessionUpdate !== 'tool_call') throw new Error('expected a tool_call')
  72. // Capability OFF on this loader: the description renders as a content block, no terminal block.
  73. expect(call.content).toEqual([{ type: 'content', content: { type: 'text', text: 'Print a greeting' } }])
  74. const update = loader.updates.find(u => u.sessionUpdate === 'tool_call_update')
  75. expect(update?.sessionUpdate).toBe('tool_call_update')
  76. if (update?.sessionUpdate !== 'tool_call_update') throw new Error('expected a tool_call_update')
  77. expect(update).toMatchObject({ toolCallId: 'c1', status: 'completed' })
  78. const content = update.content as { content: { text: string } }[]
  79. expect(content[0]?.content.text).toBe('```console\nhello\n```')
  80. })
  81. it('replays a persisted todo/write as a plan sessionUpdate on load', async () => {
  82. // A persisted `todo/write` must replay as an ACP plan update so a reopened editor sees the
  83. // current plan, not just the tool transcript.
  84. live = await makeBridgeHarness({
  85. storageDir,
  86. withTodo: true,
  87. script: [
  88. toolCallResponse('c1', 'todo_write', {
  89. todos: [
  90. { content: 'first step', status: 'in_progress' },
  91. { content: 'second step', status: 'pending' },
  92. ],
  93. }),
  94. textResponse('planned'),
  95. ],
  96. })
  97. await live.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  98. const { sessionId } = await live.client.newSession({ cwd: process.cwd(), mcpServers: [] })
  99. await live.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'plan it' }] })
  100. await live.dispose()
  101. live = undefined
  102. loader = await makeBridgeHarness({ storageDir, withTodo: true, script: [] })
  103. await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  104. await loader.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] })
  105. const plan = loader.updates.find(u => u.sessionUpdate === 'plan')
  106. expect(plan).toEqual({
  107. sessionUpdate: 'plan',
  108. entries: [
  109. { content: 'first step', priority: 'medium', status: 'in_progress' },
  110. { content: 'second step', priority: 'medium', status: 'pending' },
  111. ],
  112. })
  113. })
  114. it('replays a persisted bash call as a TERMINAL card when the loader advertises the capability', async () => {
  115. // The presentation is resolved at replay time, so a loader that advertised
  116. // _meta.terminal_output must reconstruct the terminal card (content + _meta)
  117. // from the persisted log — identical to how it would have streamed live.
  118. live = await makeBridgeHarness({
  119. storageDir,
  120. withBash: true,
  121. script: [toolCallResponse('c1', 'bash', { command: 'echo hi', description: 'Greet' }), textResponse('done')],
  122. })
  123. await live.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  124. const { sessionId } = await live.client.newSession({ cwd: process.cwd(), mcpServers: [] })
  125. await live.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'greet' }] })
  126. await live.dispose()
  127. live = undefined
  128. loader = await makeBridgeHarness({ storageDir, withBash: true, script: [] })
  129. await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: { _meta: { terminal_output: true } } })
  130. await loader.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] })
  131. const call = loader.updates.find(u => u.sessionUpdate === 'tool_call')
  132. if (call?.sessionUpdate !== 'tool_call') throw new Error('expected a tool_call')
  133. // Replay reconstructs the terminal card: description block, then terminal block.
  134. expect(call.content).toEqual([
  135. { type: 'content', content: { type: 'text', text: 'Greet' } },
  136. { type: 'terminal', terminalId: 'c1' },
  137. ])
  138. expect((call._meta as { terminal_info?: unknown }).terminal_info).toEqual({ terminal_id: 'c1', cwd: process.cwd() })
  139. const update = loader.updates.find(u => u.sessionUpdate === 'tool_call_update')
  140. if (update?.sessionUpdate !== 'tool_call_update') throw new Error('expected a tool_call_update')
  141. // Terminal mode: content omitted, output + exit on _meta — matching live.
  142. expect(update.content).toBeUndefined()
  143. const meta = update._meta as { terminal_output?: { data: string }; terminal_exit?: { exit_code?: number } }
  144. expect(meta.terminal_output?.data).toBe('hi\n')
  145. expect(meta.terminal_exit?.exit_code).toBe(0)
  146. })
  147. it('keeps one terminal completion live and on replay when a pruning replacement is logged', async () => {
  148. live = await makeBridgeHarness({
  149. storageDir,
  150. withBash: true,
  151. script: [toolCallResponse('c1', 'bash', { command: 'echo full', description: 'Print full output' }), textResponse('done')],
  152. })
  153. await live.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: { _meta: { terminal_output: true } } })
  154. const { sessionId } = await live.client.newSession({ cwd: process.cwd(), mcpServers: [] })
  155. await live.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'run it' }] })
  156. const session = live.ctx.agents.get(SessionId(sessionId))!.session
  157. const original = session.events.find(event => event.type === 'tool/result')
  158. if (original?.type !== 'tool/result') throw new Error('expected original tool/result')
  159. const liveCompletions = () => live!.updates.filter(update =>
  160. update.sessionUpdate === 'tool_call_update' && update.toolCallId === 'c1')
  161. expect(liveCompletions()).toHaveLength(1)
  162. expect((liveCompletions()[0] as { _meta?: { terminal_output?: { data: string } } })._meta?.terminal_output?.data)
  163. .toBe('full\n')
  164. session.append('turn/start', { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } })
  165. session.append('tool/result', {
  166. ...original.data,
  167. content: [{ type: 'text', text: '[... tool result middle pruned ...]' }],
  168. }, {
  169. surfaceOp: { op: 'replace', start: original.seq, end: original.seq },
  170. sourceEventSeqs: [original.seq],
  171. })
  172. session.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
  173. // The replacement is durable but is not another live completion.
  174. expect(session.events.filter(event => event.type === 'tool/result')).toHaveLength(2)
  175. expect(JSON.stringify(session.deriveMessages())).toContain('tool result middle pruned')
  176. expect(liveCompletions()).toHaveLength(1)
  177. await live.dispose()
  178. live = undefined
  179. loader = await makeBridgeHarness({ storageDir, withBash: true, script: [] })
  180. await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: { _meta: { terminal_output: true } } })
  181. await loader.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] })
  182. const replayed = loader.updates.filter(update =>
  183. update.sessionUpdate === 'tool_call_update' && update.toolCallId === 'c1')
  184. expect(replayed).toHaveLength(1)
  185. expect((replayed[0] as { _meta?: { terminal_output?: { data: string } } })._meta?.terminal_output?.data)
  186. .toBe('full\n')
  187. })
  188. it('a load whose resume finishes after a client disconnect leaks no live session', async () => {
  189. // Stall persistence so transport closes while resume is pending. Whether the SDK rejects first
  190. // or the bridge's post-await guard fires, no agent may survive for the dead connection.
  191. live = await makeBridgeHarness({ storageDir, script: [textResponse('x')] })
  192. await live.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  193. const { sessionId } = await live.client.newSession({ cwd: process.cwd(), mcpServers: [] })
  194. await live.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'hi' }] })
  195. await live.dispose()
  196. live = undefined
  197. loader = await makeBridgeHarness({ storageDir, script: [] })
  198. await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  199. const realLoad = loader.ctx.sessionPersistence.load.bind(loader.ctx.sessionPersistence)
  200. let release!: () => void
  201. const gate = new Promise<void>((r) => { release = r })
  202. loader.ctx.sessionPersistence.load = async (id) => { await gate; return realLoad(id) }
  203. const loadResult = loader.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] })
  204. .then(() => 'resolved' as const, () => 'rejected' as const)
  205. await loader.closeClientTransport() // teardown sets `closed` while load is gated
  206. release() // resume() finishes AFTER teardown
  207. expect(await loadResult).toBe('rejected')
  208. // No live agent was installed for the closed connection.
  209. expect(loader.ctx.agents.get(SessionId(sessionId))).toBeUndefined()
  210. })
  211. it('rejects load when the requested cwd does not match the persisted session cwd', async () => {
  212. // Seed a session on disk whose header.cwd is a DIFFERENT absolute path than the server's
  213. // launch dir. Resume must retain the header cwd and route bash there rather than reject the
  214. // mismatch or substitute the server cwd.
  215. loader = await makeBridgeHarness({ storageDir, script: [] })
  216. const otherCwd = '/some/other/workspace'
  217. await loader.ctx.sessionPersistence.create({
  218. version: SESSION_FORMAT_VERSION, id: SessionId('elsewhere'), createdAt: 1, cwd: otherCwd,
  219. })
  220. await loader.ctx.sessionPersistence.append(SessionId('elsewhere'), [
  221. { type: 'turn/start', seq: 0, time: 0, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  222. { type: 'turn/end', seq: 1, time: 0, data: { turn: 1, reason: { kind: 'completed' } } },
  223. ])
  224. await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  225. await expect(loader.client.loadSession({ sessionId: 'elsewhere', cwd: process.cwd(), mcpServers: [] }))
  226. .rejects.toThrow(/cwd mismatch/)
  227. expect(loader.ctx.agents.get(SessionId('elsewhere'))).toBeUndefined()
  228. const res = await loader.client.loadSession({ sessionId: 'elsewhere', cwd: `${otherCwd}/.`, mcpServers: [] })
  229. expect(res).toBeDefined()
  230. expect(loader.ctx.agents.get(SessionId('elsewhere'))!.session.header.cwd).toBe(otherCwd)
  231. })
  232. it('rejects load for a non-absolute cwd (still required to be absolute)', async () => {
  233. loader = await makeBridgeHarness({ storageDir, script: [] })
  234. await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  235. await expect(loader.client.loadSession({ sessionId: 's', cwd: 'rel', mcpServers: [] }))
  236. .rejects.toThrow(/absolute/)
  237. })
  238. it('lets persistence reject a load for an unknown id after metadata lookup misses', async () => {
  239. loader = await makeBridgeHarness({ storageDir, script: [] })
  240. await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  241. await expect(loader.client.loadSession({ sessionId: 'missing', cwd: process.cwd(), mcpServers: [] }))
  242. .rejects.toThrow(/Internal error/)
  243. })
  244. it('rejects loading a persisted session that has NO cwd (would silently run in the launch dir)', async () => {
  245. // A legacy/external log without `header.cwd` must be rejected; the request cwd does not override
  246. // it, and accepting would let bash silently fall back to the server launch directory.
  247. loader = await makeBridgeHarness({ storageDir, script: [] })
  248. await loader.ctx.sessionPersistence.create({
  249. version: SESSION_FORMAT_VERSION, id: SessionId('legacy'), createdAt: 1, // no cwd
  250. })
  251. await loader.ctx.sessionPersistence.append(SessionId('legacy'), [
  252. { type: 'turn/start', seq: 0, time: 0, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  253. { type: 'turn/end', seq: 1, time: 0, data: { turn: 1, reason: { kind: 'completed' } } },
  254. ])
  255. await loader.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  256. await expect(loader.client.loadSession({ sessionId: 'legacy', cwd: process.cwd(), mcpServers: [] }))
  257. .rejects.toThrow(/no absolute persisted cwd/)
  258. // Rejected BEFORE resume (metadata-only check) — no agent was registered, so
  259. // the id is not wedged: a later attempt hits the same clean rejection, not a
  260. // duplicate-registration error.
  261. expect(loader.ctx.agents.get(SessionId('legacy'))).toBeUndefined()
  262. await expect(loader.client.loadSession({ sessionId: 'legacy', cwd: process.cwd(), mcpServers: [] }))
  263. .rejects.toThrow(/no absolute persisted cwd/)
  264. })
  265. it('allows loading alongside an existing session but rejects re-loading the SAME id', async () => {
  266. // Multi-session: a load can coexist with a live session, but loading an id
  267. // that is already live is rejected (it is already loaded).
  268. live = await makeBridgeHarness({ storageDir, script: [textResponse('one')] })
  269. await live.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  270. const { sessionId } = await live.client.newSession({ cwd: process.cwd(), mcpServers: [] })
  271. await live.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'hi' }] })
  272. // A different new session coexists.
  273. const other = await live.client.newSession({ cwd: process.cwd(), mcpServers: [] })
  274. expect(other.sessionId).not.toBe(sessionId)
  275. // Re-loading the already-live id is rejected.
  276. await expect(live.client.loadSession({ sessionId, cwd: process.cwd(), mcpServers: [] }))
  277. .rejects.toThrow(/already loaded/)
  278. })
  279. })