stream-update.spec.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { CallId } from '@deepseek-ai/dsh-llm'
  4. import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
  5. import type { SessionNotification } from '@agentclientprotocol/sdk'
  6. import type { ToolDefinition, ToolRegistry as ToolRegistryType } from '@deepseek-ai/dsh-tools'
  7. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  8. import ToolRegistry from '@deepseek-ai/dsh-tools'
  9. import FsLocal from '@deepseek-ai/dsh-fs-local'
  10. import * as ToolFs from '@deepseek-ai/dsh-tool-fs'
  11. import { streamSessionEventUpdate, agentOptions, todosToPlan, ToolPresenter } from '../src/index.ts'
  12. /** Collect the updates a single event produces (no presenter → generic fallback). */
  13. function updatesFor(event: SessionEvent): SessionNotification['update'][] {
  14. const out: SessionNotification['update'][] = []
  15. streamSessionEventUpdate(SessionId('s1'), event, n => out.push(n.update))
  16. return out
  17. }
  18. /** Collect the updates emitted by the live prompt stream (user echo suppressed). */
  19. function liveUpdatesFor(event: SessionEvent): SessionNotification['update'][] {
  20. const out: SessionNotification['update'][] = []
  21. streamSessionEventUpdate(SessionId('s1'), event, n => out.push(n.update), undefined, undefined, { includeUserMessages: false })
  22. return out
  23. }
  24. /** A tiny tool registry stub exposing just `get` for {@link ToolPresenter}. */
  25. function registryOf(...tools: ToolDefinition[]): Pick<ToolRegistryType, 'get'> {
  26. const map = new Map(tools.map(t => [t.name, t]))
  27. return { get: name => map.get(name) }
  28. }
  29. function updatesWith(presenter: ToolPresenter, ...events: SessionEvent[]): SessionNotification['update'][] {
  30. const out: SessionNotification['update'][] = []
  31. for (const event of events) streamSessionEventUpdate(SessionId('s1'), event, n => out.push(n.update), presenter)
  32. return out
  33. }
  34. async function fsCtx(): Promise<Context> {
  35. const ctx = new Context()
  36. await ctx.plugin(SystemPrompt)
  37. await ctx.plugin(ToolRegistry)
  38. await ctx.plugin(FsLocal)
  39. await ctx.plugin(ToolFs)
  40. return ctx
  41. }
  42. function evt<T extends SessionEvent['type']>(type: T, data: Extract<SessionEvent, { type: T }>['data']): SessionEvent {
  43. return { type, seq: 0, time: 0, data } as SessionEvent
  44. }
  45. describe('streamSessionEventUpdate', () => {
  46. it('maps assistant/chunk text-delta to agent_message_chunk', () => {
  47. expect(updatesFor(evt('assistant/chunk', { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'hi' } })))
  48. .toEqual([{ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'hi' } }])
  49. })
  50. it('maps assistant/chunk reasoning-delta to agent_thought_chunk', () => {
  51. expect(updatesFor(evt('assistant/chunk', { turn: 1, step: 1, chunk: { type: 'reasoning-delta', index: 0, text: 'mm' } })))
  52. .toEqual([{ sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: 'mm' } }])
  53. })
  54. it('produces no update for a non-text/reasoning chunk (e.g. block-start)', () => {
  55. expect(updatesFor(evt('assistant/chunk', { turn: 1, step: 1, chunk: { type: 'block-start', index: 0, blockType: 'text' } })))
  56. .toEqual([])
  57. })
  58. it('marks retry and terminal model failure boundaries but not ordinary turn errors', () => {
  59. expect(updatesFor(evt('llm/retry', {
  60. turn: 1,
  61. step: 1,
  62. retry: 1,
  63. maxRetries: 2,
  64. delayMs: 500,
  65. failure: { message: 'backend busy', code: 'SERVER' },
  66. }))).toEqual([{
  67. sessionUpdate: 'agent_message_chunk',
  68. content: {
  69. type: 'text',
  70. text: '\n\n[Previous model attempt discarded; retrying 1/2 in 500ms: backend busy]\n\n',
  71. },
  72. }])
  73. expect(updatesFor(evt('turn/end', {
  74. turn: 1,
  75. reason: { kind: 'error', step: 2, failure: { message: 'still busy', code: 'SERVER' } },
  76. }))).toEqual([{
  77. sessionUpdate: 'agent_message_chunk',
  78. content: {
  79. type: 'text',
  80. text: '\n\n[Model attempt failed; any partial output above is discarded: still busy]\n\n',
  81. },
  82. }])
  83. expect(updatesFor(evt('turn/end', {
  84. turn: 1,
  85. reason: { kind: 'error', step: 2, message: 'post-step failed' },
  86. }))).toEqual([])
  87. })
  88. it('maps tool/call to an in_progress tool_call with kind other and parsed rawInput (generic fallback, no presenter)', () => {
  89. const updates = updatesFor(evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'bash', arguments: '{"command":"ls"}' }))
  90. expect(updates).toEqual([{
  91. sessionUpdate: 'tool_call',
  92. toolCallId: 'c1',
  93. title: 'bash',
  94. // The fallback never sniffs a kind from the tool name — even a name a
  95. // first-party tool uses (`bash`) renders `other`; kinds are tool-owned
  96. // via presentCall.
  97. kind: 'other',
  98. status: 'in_progress',
  99. rawInput: { command: 'ls' },
  100. }])
  101. })
  102. it('falls back to the raw argument string when tool arguments are not JSON', () => {
  103. const update = updatesFor(evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'bash', arguments: 'not json' }))[0]
  104. expect((update as { rawInput: unknown }).rawInput).toBe('not json')
  105. })
  106. it('parses EMPTY tool arguments to an empty-object rawInput (a zero-arg call, not the raw-string fallback)', () => {
  107. // `JSON.parse('')` throws, so without the empty-string guard a zero-arg
  108. // call would render `rawInput: ''` via the non-JSON fallback; the guard
  109. // normalizes it to `{}`.
  110. const update = updatesFor(evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'noop', arguments: '' }))[0]
  111. expect((update as { rawInput: unknown }).rawInput).toEqual({})
  112. })
  113. it('maps tool/result to completed/failed tool_call_update with text content', () => {
  114. const ok = updatesFor(evt('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'out' }], isError: false }))
  115. expect(ok).toEqual([{
  116. sessionUpdate: 'tool_call_update',
  117. toolCallId: 'c1',
  118. status: 'completed',
  119. content: [{ type: 'content', content: { type: 'text', text: 'out' } }],
  120. }])
  121. const failed = updatesFor(evt('tool/result', { turn: 1, step: 1, callId: CallId('c2'), content: [], isError: true }))
  122. expect((failed[0] as { status: string }).status).toBe('failed')
  123. })
  124. it('emits no execution update for a tool-result surface replacement', () => {
  125. const replacement = {
  126. ...evt('tool/result', {
  127. turn: 1,
  128. step: 1,
  129. callId: CallId('c1'),
  130. content: [{ type: 'text', text: '[... tool result middle pruned ...]' }],
  131. isError: false,
  132. }),
  133. seq: 2,
  134. surfaceOp: { op: 'replace', start: 1, end: 1 },
  135. sourceEventSeqs: [1],
  136. } as SessionEvent
  137. expect(updatesFor(replacement)).toEqual([])
  138. })
  139. it('drops non-text tool-result content (text-only)', () => {
  140. const update = updatesFor(evt('tool/result', {
  141. turn: 1, step: 1, callId: CallId('c1'),
  142. content: [{ type: 'reasoning', text: 'private' }],
  143. isError: false,
  144. }))[0]
  145. expect((update as { content: unknown[] }).content).toEqual([])
  146. })
  147. it('maps user/message text blocks to user_message_chunk (load replays the user side)', () => {
  148. // A text block surfaces; a non-text block (here a tool-call) is skipped, so
  149. // only the text chunk is emitted.
  150. expect(updatesFor(evt('user/message', {
  151. content: [
  152. { type: 'text', text: 'hi' },
  153. { type: 'tool-call', id: CallId('c'), name: 'bash', arguments: '{}' },
  154. ],
  155. source: { kind: 'user' },
  156. }))).toEqual([{ sessionUpdate: 'user_message_chunk', content: { type: 'text', text: 'hi' } }])
  157. // A user/message with no text-bearing blocks produces no chunk.
  158. expect(updatesFor(evt('user/message', { content: [], source: { kind: 'user' } }))).toEqual([])
  159. })
  160. it('can suppress user/message chunks for live prompt turns', () => {
  161. expect(liveUpdatesFor(evt('user/message', {
  162. content: [{ type: 'text', text: 'hi' }],
  163. source: { kind: 'user' },
  164. }))).toEqual([])
  165. })
  166. it('produces no update for boundary/other event types', () => {
  167. expect(updatesFor(evt('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }))).toEqual([])
  168. expect(updatesFor(evt('turn/end', { turn: 1, reason: { kind: 'completed' } }))).toEqual([])
  169. expect(updatesFor(evt('step/start', { turn: 1, step: 1 }))).toEqual([])
  170. })
  171. it('maps todo/write to a plan sessionUpdate with priority synthesized as medium', () => {
  172. expect(updatesFor(evt('todo/write', {
  173. todos: [
  174. { content: 'plan the work', status: 'in_progress' },
  175. { content: 'write the code', status: 'pending' },
  176. { content: 'run the tests', status: 'completed' },
  177. ],
  178. }))).toEqual([{
  179. sessionUpdate: 'plan',
  180. entries: [
  181. { content: 'plan the work', priority: 'medium', status: 'in_progress' },
  182. { content: 'write the code', priority: 'medium', status: 'pending' },
  183. { content: 'run the tests', priority: 'medium', status: 'completed' },
  184. ],
  185. }])
  186. })
  187. it('maps an empty todo list to a plan with no entries', () => {
  188. expect(updatesFor(evt('todo/write', { todos: [] }))).toEqual([{ sessionUpdate: 'plan', entries: [] }])
  189. })
  190. })
  191. describe('todosToPlan', () => {
  192. it('maps status 1:1 and stamps every entry priority medium', () => {
  193. expect(todosToPlan([
  194. { content: 'a', status: 'pending' },
  195. { content: 'b', status: 'in_progress' },
  196. { content: 'c', status: 'completed' },
  197. ])).toEqual({
  198. entries: [
  199. { content: 'a', priority: 'medium', status: 'pending' },
  200. { content: 'b', priority: 'medium', status: 'in_progress' },
  201. { content: 'c', priority: 'medium', status: 'completed' },
  202. ],
  203. })
  204. })
  205. })
  206. describe('ToolPresenter (tool-owned presentation via the tool registry)', () => {
  207. /** A tool whose presentCall/presentResult return generic-card views. */
  208. const bashLike: ToolDefinition = {
  209. name: 'bash',
  210. description: 'run a command',
  211. parameters: {},
  212. execute: async () => [],
  213. presentCall: (args: unknown) => {
  214. const a = args as { command: string; description: string }
  215. return { card: 'generic', title: a.description, kind: 'execute', rawInput: a.command }
  216. },
  217. presentResult: (_args: unknown, result: { content: { type: string }[] }) => ({
  218. card: 'generic',
  219. content: [{ type: 'text', text: `wrapped:${result.content.length}` }],
  220. }),
  221. }
  222. it('tool/call uses the tool: description→title, command→rawInput, tool kind', () => {
  223. const presenter = new ToolPresenter(registryOf(bashLike))
  224. const [update] = updatesWith(presenter, evt('tool/call', {
  225. turn: 1, step: 1, callId: CallId('c1'), name: 'bash',
  226. arguments: JSON.stringify({ command: 'ls -la', description: 'List files' }),
  227. }))
  228. expect(update).toEqual({
  229. sessionUpdate: 'tool_call',
  230. toolCallId: 'c1',
  231. title: 'List files',
  232. kind: 'execute',
  233. status: 'in_progress',
  234. rawInput: 'ls -la',
  235. })
  236. })
  237. it('tool/result uses the tool to reformat content (resolved by the remembered tool/call)', () => {
  238. const presenter = new ToolPresenter(registryOf(bashLike))
  239. const updates = updatesWith(
  240. presenter,
  241. evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'bash', arguments: JSON.stringify({ command: 'x', description: 'd' }) }),
  242. evt('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'out' }], isError: false }),
  243. )
  244. expect(updates[1]).toEqual({
  245. sessionUpdate: 'tool_call_update',
  246. toolCallId: 'c1',
  247. status: 'completed',
  248. content: [{ type: 'content', content: { type: 'text', text: 'wrapped:1' } }],
  249. })
  250. })
  251. it('a result with NO preceding call (unknown callId) falls back to the raw content', () => {
  252. const presenter = new ToolPresenter(registryOf(bashLike))
  253. // No tool/call for c9 → presenter has nothing remembered → generic fallback.
  254. const [update] = updatesWith(presenter, evt('tool/result', {
  255. turn: 1, step: 1, callId: CallId('c9'), content: [{ type: 'text', text: 'raw' }], isError: false,
  256. }))
  257. expect(update).toEqual({
  258. sessionUpdate: 'tool_call_update',
  259. toolCallId: 'c9',
  260. status: 'completed',
  261. content: [{ type: 'content', content: { type: 'text', text: 'raw' } }],
  262. })
  263. })
  264. it('a tool with no presentCall/presentResult gets the generic fallback (title = name)', () => {
  265. const plain: ToolDefinition = { name: 'plain', description: 'p', parameters: {}, execute: async () => [] }
  266. const presenter = new ToolPresenter(registryOf(plain))
  267. const [update] = updatesWith(presenter, evt('tool/call', {
  268. turn: 1, step: 1, callId: CallId('c1'), name: 'plain', arguments: '{"a":1}',
  269. }))
  270. expect(update).toMatchObject({ title: 'plain', kind: 'other', rawInput: { a: 1 } })
  271. })
  272. it('a presentation that omits kind/content/rawInput uses the defaults (kind other, raw result content kept)', () => {
  273. // A minimal tool-owned presentation: presentCall returns only a title (no
  274. // kind → defaults to `other`, no rawInput → omitted); presentResult returns
  275. // only a title (no content → the raw result content is kept).
  276. const minimal: ToolDefinition = {
  277. name: 'mini',
  278. description: 'm',
  279. parameters: {},
  280. execute: async () => [],
  281. presentCall: () => ({ card: 'generic', title: 'Doing a thing' }),
  282. presentResult: () => ({ card: 'generic', title: 'Did the thing' }),
  283. }
  284. const presenter = new ToolPresenter(registryOf(minimal))
  285. const updates = updatesWith(
  286. presenter,
  287. evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'mini', arguments: '{}' }),
  288. evt('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'kept' }], isError: false }),
  289. )
  290. // No kind → 'other'; no rawInput key at all.
  291. expect(updates[0]).toEqual({ sessionUpdate: 'tool_call', toolCallId: 'c1', title: 'Doing a thing', kind: 'other', status: 'in_progress' })
  292. // Title replaced; content falls back to the raw result content.
  293. expect(updates[1]).toEqual({
  294. sessionUpdate: 'tool_call_update',
  295. toolCallId: 'c1',
  296. status: 'completed',
  297. content: [{ type: 'content', content: { type: 'text', text: 'kept' } }],
  298. title: 'Did the thing',
  299. })
  300. })
  301. it('holds ONLY in-flight calls: the callId entry is removed once its result is presented', () => {
  302. const presenter = new ToolPresenter(registryOf(bashLike))
  303. updatesWith(
  304. presenter,
  305. evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'bash', arguments: JSON.stringify({ command: 'x', description: 'd' }) }),
  306. evt('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'o' }], isError: false }),
  307. )
  308. // A SECOND result for the same callId now finds nothing remembered, so it
  309. // falls back to raw content (proving the first result consumed the entry —
  310. // the map does not retain finished calls).
  311. const [late] = updatesWith(presenter, evt('tool/result', {
  312. turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'late' }], isError: false,
  313. }))
  314. expect(late).toMatchObject({ content: [{ type: 'content', content: { type: 'text', text: 'late' } }] })
  315. })
  316. it('a THROWING presentCall/presentResult is contained: generic fallback + onError, never propagates', () => {
  317. // A buggy tool whose display callbacks throw must not fail a live turn or a session/load
  318. // replay (docs/defensive-patterns.md "contain callback exceptions at the boundary"). The
  319. // presenter reports the error and falls back to generic rendering.
  320. const boom: ToolDefinition = {
  321. name: 'boom',
  322. description: 'b',
  323. parameters: {},
  324. execute: async () => [],
  325. presentCall: () => { throw new Error('call boom') },
  326. presentResult: () => { throw new Error('result boom') },
  327. }
  328. const errors: string[] = []
  329. const presenter = new ToolPresenter(registryOf(boom), msg => errors.push(msg))
  330. const updates = updatesWith(
  331. presenter,
  332. evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'boom', arguments: '{"a":1}' }),
  333. evt('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'raw' }], isError: false }),
  334. )
  335. // tool/call fell back to title=name, raw args as rawInput.
  336. expect(updates[0]).toMatchObject({ sessionUpdate: 'tool_call', title: 'boom', kind: 'other', rawInput: { a: 1 } })
  337. // tool/result fell back to the raw content.
  338. expect(updates[1]).toMatchObject({ sessionUpdate: 'tool_call_update', content: [{ type: 'content', content: { type: 'text', text: 'raw' } }] })
  339. // Both throws were reported, not propagated.
  340. expect(errors).toHaveLength(2)
  341. expect(errors[0]).toContain('presentCall threw')
  342. expect(errors[1]).toContain('presentResult threw')
  343. })
  344. it('contains a throwing presenter even with the DEFAULT (no-op) onError sink', () => {
  345. // Constructed without an onError sink (the default `() => {}`): a throwing
  346. // presenter is still swallowed and falls back generically — the absence of a
  347. // logger must not turn a display bug into a propagated exception.
  348. const boom: ToolDefinition = {
  349. name: 'boom',
  350. description: 'b',
  351. parameters: {},
  352. execute: async () => [],
  353. presentCall: () => { throw new Error('call boom') },
  354. presentResult: () => { throw new Error('result boom') },
  355. }
  356. const presenter = new ToolPresenter(registryOf(boom))
  357. const updates = updatesWith(
  358. presenter,
  359. evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'boom', arguments: '{}' }),
  360. evt('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'raw' }], isError: false }),
  361. )
  362. expect(updates[0]).toMatchObject({ sessionUpdate: 'tool_call', title: 'boom' })
  363. expect(updates[1]).toMatchObject({ sessionUpdate: 'tool_call_update', content: [{ type: 'content', content: { type: 'text', text: 'raw' } }] })
  364. })
  365. it('an unknown render-intent card throws via the exhaustiveness guard (closed union)', () => {
  366. // The bridge switches on `view.card` and ends with assertNever: a rogue card
  367. // (only reachable by a cast — the union is closed) must throw, so adding a
  368. // real variant later fails to compile at the switch instead of silently
  369. // dropping the card.
  370. const rogue: ToolDefinition = {
  371. name: 'rogue',
  372. description: 'r',
  373. parameters: {},
  374. execute: async () => [],
  375. // A card value outside the union — forced with a cast (no valid input reaches this).
  376. presentCall: () => ({ card: 'chart', title: 'nope' }) as unknown as ReturnType<NonNullable<ToolDefinition['presentCall']>>,
  377. }
  378. const presenter = new ToolPresenter(registryOf(rogue))
  379. expect(() => updatesWith(presenter, evt('tool/call', {
  380. turn: 1, step: 1, callId: CallId('c1'), name: 'rogue', arguments: '{}',
  381. }))).toThrow('unreachable variant')
  382. })
  383. it('an unknown render-intent RESULT card throws via the exhaustiveness guard (closed union)', () => {
  384. // The result-side renderer is also an exhaustive switch + assertNever: a rogue
  385. // result card (only reachable by a cast) must throw, so adding a real result
  386. // variant later fails to compile at the switch.
  387. const rogue: ToolDefinition = {
  388. name: 'rogue',
  389. description: 'r',
  390. parameters: {},
  391. execute: async () => [],
  392. presentCall: () => ({ card: 'generic', title: 'r' }),
  393. presentResult: () => ({ card: 'chart' }) as unknown as ReturnType<NonNullable<ToolDefinition['presentResult']>>,
  394. }
  395. const presenter = new ToolPresenter(registryOf(rogue))
  396. expect(() => updatesWith(
  397. presenter,
  398. evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'rogue', arguments: '{}' }),
  399. evt('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'x' }], isError: false }),
  400. )).toThrow('unreachable variant')
  401. })
  402. it('forwards fs-tool render intents onto the wire (REAL read → generic locations, edit → diff content)', async () => {
  403. // Use the SHIPPING fs tools (not a stand-in), booted through their real
  404. // plugins, so the wire tool_call carries the actual presentCall output —
  405. // read's follow-along `locations` and edit's `diff` content block. (docs/testing.md
  406. // "prefer the real implementation over a mock".)
  407. const ctx = new Context()
  408. await ctx.plugin(SystemPrompt)
  409. await ctx.plugin(ToolRegistry)
  410. await ctx.plugin(FsLocal)
  411. await ctx.plugin(ToolFs)
  412. const presenter = new ToolPresenter(ctx.tools)
  413. const [readCall] = updatesWith(presenter, evt('tool/call', {
  414. turn: 1, step: 1, callId: CallId('r1'), name: 'read',
  415. arguments: JSON.stringify({ file_path: 'src/a.ts', offset: 12 }),
  416. }))
  417. // A generic card: the read window is in the title, the offset drives the
  418. // follow-along location line. No rawInput (the window lives in the title).
  419. expect(readCall).toMatchObject({
  420. sessionUpdate: 'tool_call', toolCallId: 'r1', title: 'Read src/a.ts (from line 12)', kind: 'read',
  421. locations: [{ path: 'src/a.ts', line: 12 }],
  422. })
  423. expect((readCall as { rawInput?: unknown }).rawInput).toBeUndefined()
  424. const [editCall] = updatesWith(presenter, evt('tool/call', {
  425. turn: 1, step: 1, callId: CallId('e1'), name: 'edit',
  426. arguments: JSON.stringify({ file_path: 'src/b.ts', old_string: 'x', new_string: 'y' }),
  427. }))
  428. // A diff card: `edit` kind, a `{ type: 'diff' }` content block carrying the
  429. // literal old→new replacement, plus the follow-along location.
  430. expect(editCall).toMatchObject({
  431. sessionUpdate: 'tool_call', toolCallId: 'e1', title: 'Edit src/b.ts', kind: 'edit',
  432. locations: [{ path: 'src/b.ts' }],
  433. content: [{ type: 'diff', path: 'src/b.ts', oldText: 'x', newText: 'y' }],
  434. })
  435. await ctx.fiber.dispose()
  436. })
  437. })
  438. describe('terminal-card mapping (capability-gated)', () => {
  439. // A tool that renders as a terminal — a stand-in for tool-bash's shape, letting
  440. // us drive the bridge's terminal mapping without the real executor. `callCard`
  441. // selects a terminal call view (optionally with a cwd) or a generic one (for the
  442. // orphan-guard test); `resultTerminal` is the terminal result view's output/exit.
  443. type CallCard = { card: 'terminal'; cwd?: string } | { card: 'generic' }
  444. type ResultTerm = { title?: string; output?: string; exitCode?: number; signal?: string }
  445. const termTool = (callCard: CallCard, resultTerminal: ResultTerm): ToolDefinition => ({
  446. name: 'bash',
  447. description: 'run a command',
  448. parameters: {},
  449. execute: async () => [],
  450. presentCall: (args: unknown) => {
  451. const command = (args as { command: string }).command
  452. const description = (args as { description: string }).description
  453. if (callCard.card === 'terminal') {
  454. return { card: 'terminal', title: command, description, ...callCard.cwd !== undefined ? { cwd: callCard.cwd } : {} }
  455. }
  456. return { card: 'generic', title: command, kind: 'execute', rawInput: command, content: [{ type: 'text', text: description }] }
  457. },
  458. presentResult: () => ({ card: 'terminal', ...resultTerminal }),
  459. })
  460. const callEvent = evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'bash', arguments: JSON.stringify({ command: 'echo hi', description: 'Greet' }) })
  461. const resultEvent = evt('tool/result', { turn: 1, step: 1, callId: CallId('c1'), content: [{ type: 'text', text: 'hi\n' }], isError: false })
  462. const prunedResultEvent = {
  463. ...resultEvent,
  464. seq: 2,
  465. data: {
  466. ...resultEvent.data,
  467. content: [{ type: 'text', text: '[... tool result middle pruned ...]' }],
  468. },
  469. surfaceOp: { op: 'replace', start: 1, end: 1 },
  470. sourceEventSeqs: [1],
  471. } as SessionEvent
  472. function termUpdates(tool: ToolDefinition, enabled: boolean, cwd: string | undefined, ...events: SessionEvent[]): SessionNotification['update'][] {
  473. const presenter = new ToolPresenter(registryOf(tool))
  474. const out: SessionNotification['update'][] = []
  475. for (const event of events) streamSessionEventUpdate(SessionId('s1'), event, n => out.push(n.update), presenter, { enabled, cwd })
  476. return out
  477. }
  478. it('capability ON: description content THEN terminal block; cwd from the session header when the tool gives none', () => {
  479. const [call, update] = termUpdates(termTool({ card: 'terminal' }, { output: 'hi\n', exitCode: 0 }), true, '/work/proj', callEvent, resultEvent)
  480. expect(call).toMatchObject({
  481. sessionUpdate: 'tool_call',
  482. content: [
  483. { type: 'content', content: { type: 'text', text: 'Greet' } },
  484. { type: 'terminal', terminalId: 'c1' },
  485. ],
  486. _meta: { terminal_info: { terminal_id: 'c1', cwd: '/work/proj' } },
  487. })
  488. // The update OMITS content (it would clobber the terminal block) and carries output + exit.
  489. expect(update).toEqual({
  490. sessionUpdate: 'tool_call_update',
  491. toolCallId: 'c1',
  492. status: 'completed',
  493. _meta: { terminal_output: { terminal_id: 'c1', data: 'hi\n' }, terminal_exit: { terminal_id: 'c1', exit_code: 0 } },
  494. })
  495. })
  496. it('live/replay translation preserves the original terminal completion across a pruning rewrite', () => {
  497. const updates = termUpdates(
  498. termTool({ card: 'terminal' }, { output: 'hi\n', exitCode: 0 }),
  499. true,
  500. '/work/proj',
  501. callEvent,
  502. resultEvent,
  503. prunedResultEvent,
  504. )
  505. expect(updates).toHaveLength(2)
  506. expect(updates[1]).toEqual({
  507. sessionUpdate: 'tool_call_update',
  508. toolCallId: 'c1',
  509. status: 'completed',
  510. _meta: {
  511. terminal_output: { terminal_id: 'c1', data: 'hi\n' },
  512. terminal_exit: { terminal_id: 'c1', exit_code: 0 },
  513. },
  514. })
  515. })
  516. it('capability ON: an ABSOLUTE tool cwd wins; a RELATIVE one resolves against the session cwd', () => {
  517. const [absCall] = termUpdates(termTool({ card: 'terminal', cwd: '/explicit/abs' }, { output: 'x' }), true, '/work/proj', callEvent)
  518. expect((absCall as unknown as { _meta: { terminal_info: { cwd: string } } })._meta.terminal_info.cwd).toBe('/explicit/abs')
  519. const [relCall] = termUpdates(termTool({ card: 'terminal', cwd: 'sub/dir' }, { output: 'x' }), true, '/work/proj', callEvent)
  520. // Relative workdir resolved against the session cwd — the card header matches
  521. // where execution actually ran (tool-bash resolves the same way).
  522. expect((relCall as unknown as { _meta: { terminal_info: { cwd: string } } })._meta.terminal_info.cwd).toBe('/work/proj/sub/dir')
  523. // No session cwd to resolve against → the relative tool cwd is passed through as-is.
  524. const [noSessionCwd] = termUpdates(termTool({ card: 'terminal', cwd: 'rel/only' }, { output: 'x' }), true, undefined, callEvent)
  525. expect((noSessionCwd as unknown as { _meta: { terminal_info: { cwd: string } } })._meta.terminal_info.cwd).toBe('rel/only')
  526. })
  527. it('capability ON: a signal kill maps to terminal_exit.signal', () => {
  528. const [, update] = termUpdates(termTool({ card: 'terminal' }, { output: 'gone', signal: 'SIGKILL' }), true, '/w', callEvent, resultEvent)
  529. expect((update as unknown as { _meta: { terminal_exit: unknown } })._meta.terminal_exit).toEqual({ terminal_id: 'c1', signal: 'SIGKILL' })
  530. })
  531. it('capability ON: a terminal result with output but NO exit/signal emits terminal_output and NO exit pill', () => {
  532. // A terminal-rendering tool that reports no structured exit (neither exitCode
  533. // nor signal) — the card shows output but no exit pill.
  534. const [, update] = termUpdates(termTool({ card: 'terminal' }, { output: 'partial' }), true, '/w', callEvent, resultEvent)
  535. const meta = (update as unknown as { _meta: { terminal_output?: unknown; terminal_exit?: unknown } })._meta
  536. expect(meta.terminal_output).toEqual({ terminal_id: 'c1', data: 'partial' })
  537. expect(meta.terminal_exit).toBeUndefined()
  538. })
  539. it('capability OFF: no terminal block or _meta; the description content and the bridge-derived fenced result render', () => {
  540. const [call, update] = termUpdates(termTool({ card: 'terminal' }, { output: 'hi\n' }), false, '/work/proj', callEvent, resultEvent)
  541. expect(call).toEqual({
  542. sessionUpdate: 'tool_call',
  543. toolCallId: 'c1',
  544. title: 'echo hi',
  545. kind: 'execute',
  546. status: 'in_progress',
  547. rawInput: 'echo hi',
  548. content: [{ type: 'content', content: { type: 'text', text: 'Greet' } }],
  549. })
  550. // The bridge derives the fenced ```console fallback from the terminal output.
  551. expect(update).toEqual({
  552. sessionUpdate: 'tool_call_update',
  553. toolCallId: 'c1',
  554. status: 'completed',
  555. content: [{ type: 'content', content: { type: 'text', text: '```console\nhi\n```' } }],
  556. })
  557. })
  558. it('orphan guard: a result-side terminal with a GENERIC call is dropped (no orphan terminal_output)', () => {
  559. // presentCall is a generic card, but presentResult returns a terminal view —
  560. // the bridge must not emit _meta.terminal_output for a terminal Zed never made.
  561. const [call, update] = termUpdates(termTool({ card: 'generic' }, { output: 'hi\n', exitCode: 0 }), true, '/w', callEvent, resultEvent)
  562. // The call was generic → ordinary tool_call (description content, no _meta).
  563. expect((call as { _meta?: unknown })._meta).toBeUndefined()
  564. expect((call as { content: unknown }).content).toEqual([{ type: 'content', content: { type: 'text', text: 'Greet' } }])
  565. // The result falls back to the RAW result content (the tool/result event's text); NO terminal _meta.
  566. expect((update as { _meta?: unknown })._meta).toBeUndefined()
  567. expect((update as { content: unknown }).content).toEqual([{ type: 'content', content: { type: 'text', text: 'hi\n' } }])
  568. })
  569. it('capability ON: a terminal result title replaces the completed-card title; missing output emits empty data', () => {
  570. // A terminal result MAY carry a replacement title and MAY omit output (a run
  571. // that produced nothing) — the _meta carries empty data, not a dropped key.
  572. const [, update] = termUpdates(termTool({ card: 'terminal' }, { title: 'Ran echo', exitCode: 0 }), true, '/w', callEvent, resultEvent)
  573. expect(update).toEqual({
  574. sessionUpdate: 'tool_call_update',
  575. toolCallId: 'c1',
  576. status: 'completed',
  577. title: 'Ran echo',
  578. _meta: { terminal_output: { terminal_id: 'c1', data: '' }, terminal_exit: { terminal_id: 'c1', exit_code: 0 } },
  579. })
  580. })
  581. it('capability OFF: a terminal result title rides on the fenced fallback update', () => {
  582. const [, update] = termUpdates(termTool({ card: 'terminal' }, { title: 'Ran echo', output: 'hi\n' }), false, '/w', callEvent, resultEvent)
  583. expect(update).toEqual({
  584. sessionUpdate: 'tool_call_update',
  585. toolCallId: 'c1',
  586. status: 'completed',
  587. content: [{ type: 'content', content: { type: 'text', text: '```console\nhi\n```' } }],
  588. title: 'Ran echo',
  589. })
  590. })
  591. it('a terminal call with NO description and NO capability is a bare execute card (no content key)', () => {
  592. // A terminal view whose presentCall omits `description`, with the capability
  593. // OFF: no description block and no terminal block → the card carries no content.
  594. const noDesc: ToolDefinition = {
  595. name: 'bash',
  596. description: 'run a command',
  597. parameters: {},
  598. execute: async () => [],
  599. presentCall: (args: unknown) => ({ card: 'terminal', title: (args as { command: string }).command }),
  600. }
  601. const [call] = termUpdates(noDesc, false, undefined, callEvent)
  602. expect(call).toEqual({
  603. sessionUpdate: 'tool_call',
  604. toolCallId: 'c1',
  605. title: 'echo hi',
  606. kind: 'execute',
  607. status: 'in_progress',
  608. rawInput: 'echo hi',
  609. })
  610. })
  611. })
  612. describe('diff-card mapping', () => {
  613. // A stand-in diff tool, letting us drive the bridge's diff arm across shapes
  614. // the shipping fs tools don't emit (no locations, empty diffs).
  615. const diffTool = (view: unknown): ToolDefinition => ({
  616. name: 'writer',
  617. description: 'writes a file',
  618. parameters: {},
  619. execute: async () => [],
  620. presentCall: () => view as ReturnType<NonNullable<ToolDefinition['presentCall']>>,
  621. })
  622. function callUpdate(tool: ToolDefinition, cwd: string | undefined): SessionNotification['update'] {
  623. const presenter = new ToolPresenter(registryOf(tool))
  624. const out: SessionNotification['update'][] = []
  625. streamSessionEventUpdate(
  626. SessionId('s1'),
  627. evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name: 'writer', arguments: '{}' }),
  628. n => out.push(n.update),
  629. presenter,
  630. { enabled: false, cwd },
  631. )
  632. return out[0]!
  633. }
  634. it('a diff with NO locations relativizes the title off the first diff path; omits the locations key', () => {
  635. const update = callUpdate(diffTool({ card: 'diff', title: 'Write /work/proj/a.txt', diffs: [{ path: '/work/proj/a.txt', oldText: null, newText: 'x' }] }), '/work/proj')
  636. expect(update).toEqual({
  637. sessionUpdate: 'tool_call',
  638. toolCallId: 'c1',
  639. title: 'Write a.txt',
  640. kind: 'edit',
  641. status: 'in_progress',
  642. content: [{ type: 'diff', path: '/work/proj/a.txt', oldText: null, newText: 'x' }],
  643. })
  644. })
  645. it('a diff with an EMPTY diffs array omits the content key (no diff blocks to send)', () => {
  646. const update = callUpdate(diffTool({ card: 'diff', title: 'Write nothing', diffs: [] }), undefined)
  647. expect(update).toEqual({
  648. sessionUpdate: 'tool_call',
  649. toolCallId: 'c1',
  650. title: 'Write nothing',
  651. kind: 'edit',
  652. status: 'in_progress',
  653. })
  654. })
  655. })
  656. describe('result-time diff card (REAL fs edit tool → tool_call_update diff blocks)', () => {
  657. // Drive the SHIPPING fs edit tool through the bridge: the pending tool/call installs the
  658. // call-time snippet, then the tool/result carries the tool's computed applied-hunk `meta`,
  659. // which presentResult narrows into a `diff` result card the bridge forwards as `{ type:
  660. // 'diff' }` content blocks. The real tool is required because its result metadata is the contract.
  661. it('live/replay translation keeps the applied diff when a pruning rewrite follows', async () => {
  662. const ctx = await fsCtx()
  663. const presenter = new ToolPresenter(ctx.tools)
  664. const args = JSON.stringify({ file_path: 'src/b.ts', old_string: 'OLD', new_string: 'NEW' })
  665. // The applied hunk the tool would compute and persist on the result meta.
  666. const meta = { diffs: [{ path: 'src/b.ts', oldText: 'a\nOLD\nb', newText: 'a\nNEW\nb' }] }
  667. const originalResult = evt('tool/result', {
  668. turn: 1,
  669. step: 1,
  670. callId: CallId('e1'),
  671. content: [{ type: 'text', text: 'ok' }],
  672. isError: false,
  673. meta,
  674. })
  675. const replacement = {
  676. ...originalResult,
  677. seq: 3,
  678. data: {
  679. ...originalResult.data,
  680. content: [{ type: 'text', text: '[... tool result middle pruned ...]' }],
  681. },
  682. surfaceOp: { op: 'replace', start: 2, end: 2 },
  683. sourceEventSeqs: [2],
  684. } as SessionEvent
  685. const updates = updatesWith(
  686. presenter,
  687. evt('tool/call', { turn: 1, step: 1, callId: CallId('e1'), name: 'edit', arguments: args }),
  688. originalResult,
  689. replacement,
  690. )
  691. expect(updates).toHaveLength(2)
  692. const resultUpdate = updates[1]
  693. expect(resultUpdate).toEqual({
  694. sessionUpdate: 'tool_call_update',
  695. toolCallId: 'e1',
  696. status: 'completed',
  697. title: 'Edit src/b.ts',
  698. content: [{ type: 'diff', path: 'src/b.ts', oldText: 'a\nOLD\nb', newText: 'a\nNEW\nb' }],
  699. })
  700. await ctx.fiber.dispose()
  701. })
  702. it('an error result carries NO diff card (falls back to raw content)', async () => {
  703. const ctx = await fsCtx()
  704. const presenter = new ToolPresenter(ctx.tools)
  705. const args = JSON.stringify({ file_path: 'src/b.ts', old_string: 'OLD', new_string: 'NEW' })
  706. const [, resultUpdate] = updatesWith(
  707. presenter,
  708. evt('tool/call', { turn: 1, step: 1, callId: CallId('e1'), name: 'edit', arguments: args }),
  709. evt('tool/result', { turn: 1, step: 1, callId: CallId('e1'), content: [{ type: 'text', text: 'Error: boom' }], isError: true }),
  710. )
  711. expect(resultUpdate).toMatchObject({ sessionUpdate: 'tool_call_update', status: 'failed' })
  712. expect(resultUpdate).not.toHaveProperty('content', expect.arrayContaining([expect.objectContaining({ type: 'diff' })]))
  713. await ctx.fiber.dispose()
  714. })
  715. it('the completed diff TITLE relativizes against the session cwd (the result title replaces the card header)', async () => {
  716. // A `tool_call_update.title` replaces the card header, so the result-side diff must
  717. // relativize its title exactly as the pending card did — otherwise a completed
  718. // absolute-path edit flips `Edit src/b.ts` back to the raw absolute path. Diff and location
  719. // paths remain absolute so the editor can open the real file.
  720. const ctx = await fsCtx()
  721. const presenter = new ToolPresenter(ctx.tools)
  722. const args = JSON.stringify({ file_path: '/work/proj/src/b.ts', old_string: 'OLD', new_string: 'NEW' })
  723. const meta = { diffs: [{ path: '/work/proj/src/b.ts', oldText: 'a\nOLD\nb', newText: 'a\nNEW\nb' }] }
  724. const out: SessionNotification['update'][] = []
  725. const rendering = { enabled: false, cwd: '/work/proj' }
  726. for (const event of [
  727. evt('tool/call', { turn: 1, step: 1, callId: CallId('e1'), name: 'edit', arguments: args }),
  728. evt('tool/result', { turn: 1, step: 1, callId: CallId('e1'), content: [{ type: 'text', text: 'ok' }], isError: false, meta }),
  729. ]) streamSessionEventUpdate(SessionId('s1'), event, n => out.push(n.update), presenter, rendering)
  730. expect(out[1]).toEqual({
  731. sessionUpdate: 'tool_call_update',
  732. toolCallId: 'e1',
  733. status: 'completed',
  734. title: 'Edit src/b.ts',
  735. content: [{ type: 'diff', path: '/work/proj/src/b.ts', oldText: 'a\nOLD\nb', newText: 'a\nNEW\nb' }],
  736. })
  737. await ctx.fiber.dispose()
  738. })
  739. it('a diff result with an EMPTY diffs array and no title omits both keys (nothing to send)', () => {
  740. // Shipping edit always has a hunk and write falls back to a whole-file diff, so a synthetic
  741. // tool is required to cover both absent-title and empty-content result branches.
  742. const emptyDiffTool: ToolDefinition = {
  743. name: 'writer',
  744. description: 'writes a file',
  745. parameters: {},
  746. execute: async () => [],
  747. presentCall: () => ({ card: 'diff', title: 'Write x', diffs: [{ path: 'x', oldText: null, newText: 'y' }] }),
  748. presentResult: () => ({ card: 'diff', diffs: [] }),
  749. }
  750. const presenter = new ToolPresenter(registryOf(emptyDiffTool))
  751. const [, resultUpdate] = updatesWith(
  752. presenter,
  753. evt('tool/call', { turn: 1, step: 1, callId: CallId('w1'), name: 'writer', arguments: '{}' }),
  754. evt('tool/result', { turn: 1, step: 1, callId: CallId('w1'), content: [{ type: 'text', text: 'ok' }], isError: false }),
  755. )
  756. expect(resultUpdate).toEqual({
  757. sessionUpdate: 'tool_call_update',
  758. toolCallId: 'w1',
  759. status: 'completed',
  760. })
  761. expect(resultUpdate).not.toHaveProperty('content')
  762. expect(resultUpdate).not.toHaveProperty('title')
  763. })
  764. })
  765. describe('relative-path display titles (bridge relativizes the title against the session cwd)', () => {
  766. // The bridge relativizes a file card's TITLE against the session workspace cwd (mirroring the
  767. // reference adapter's `toDisplayPath`), while leaving location/diff paths raw. Use real fs tools
  768. // and the absolute paths an editor supplies; presentation itself is args-only and lacks cwd.
  769. function callUpdate(ctx: Context, sessionCwd: string | undefined, name: string, args: unknown): SessionNotification['update'] {
  770. const presenter = new ToolPresenter(ctx.tools)
  771. const out: SessionNotification['update'][] = []
  772. streamSessionEventUpdate(
  773. SessionId('s1'),
  774. evt('tool/call', { turn: 1, step: 1, callId: CallId('c1'), name, arguments: JSON.stringify(args) }),
  775. n => out.push(n.update),
  776. presenter,
  777. { enabled: false, cwd: sessionCwd },
  778. )
  779. return out[0]!
  780. }
  781. it('read: an absolute path inside the workspace relativizes the TITLE; the location path stays absolute', async () => {
  782. const ctx = await fsCtx()
  783. const update = callUpdate(ctx, '/work/proj', 'read', { file_path: '/work/proj/src/a.ts', offset: 5 })
  784. expect(update).toMatchObject({
  785. title: 'Read src/a.ts (from line 5)',
  786. locations: [{ path: '/work/proj/src/a.ts', line: 5 }],
  787. })
  788. await ctx.fiber.dispose()
  789. })
  790. it('edit: the diff TITLE relativizes; the diff/location paths stay absolute (the editor opens the real path)', async () => {
  791. const ctx = await fsCtx()
  792. const update = callUpdate(ctx, '/work/proj', 'edit', { file_path: '/work/proj/src/b.ts', old_string: 'x', new_string: 'y' })
  793. expect(update).toMatchObject({
  794. title: 'Edit src/b.ts',
  795. locations: [{ path: '/work/proj/src/b.ts' }],
  796. content: [{ type: 'diff', path: '/work/proj/src/b.ts', oldText: 'x', newText: 'y' }],
  797. })
  798. await ctx.fiber.dispose()
  799. })
  800. it('a path OUTSIDE the workspace is left as-is (no `..` title)', async () => {
  801. const ctx = await fsCtx()
  802. const update = callUpdate(ctx, '/work/proj', 'read', { file_path: '/etc/passwd' })
  803. expect((update as { title: string }).title).toBe('Read /etc/passwd')
  804. await ctx.fiber.dispose()
  805. })
  806. it('an in-workspace file whose relative form starts with `..` chars (a sibling name) still relativizes', async () => {
  807. // `/work/proj/..cache/x` is inside the workspace — its relative form `..cache/x` begins
  808. // with the chars `..` but is not a parent segment. Segment-aware guarding must relativize it,
  809. // matching targets under `cwd + sep` in the reference adapter.
  810. const ctx = await fsCtx()
  811. const update = callUpdate(ctx, '/work/proj', 'read', { file_path: '/work/proj/..cache/x.ts' })
  812. expect((update as { title: string }).title).toBe('Read ..cache/x.ts')
  813. await ctx.fiber.dispose()
  814. })
  815. it('no session cwd → the absolute title is left unchanged', async () => {
  816. const ctx = await fsCtx()
  817. const update = callUpdate(ctx, undefined, 'read', { file_path: '/work/proj/src/a.ts' })
  818. expect((update as { title: string }).title).toBe('Read /work/proj/src/a.ts')
  819. await ctx.fiber.dispose()
  820. })
  821. it('a relative path is passed through unchanged (already display-friendly)', async () => {
  822. const ctx = await fsCtx()
  823. const update = callUpdate(ctx, '/work/proj', 'read', { file_path: 'src/a.ts' })
  824. expect((update as { title: string }).title).toBe('Read src/a.ts')
  825. await ctx.fiber.dispose()
  826. })
  827. })
  828. describe('agentOptions', () => {
  829. it('includes only the fields present in config', () => {
  830. expect(agentOptions({})).toEqual({})
  831. expect(agentOptions({ model: 'm' })).toEqual({ model: 'm' })
  832. expect(agentOptions({ provider: 'p', model: 'm' })).toEqual({ provider: 'p', model: 'm' })
  833. })
  834. })