Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import {
3 SESSION_ID_EVENT,
4 TODO_EVENT,
5 resolveToolName,
6 translateOpencodeStream,
7} from '../src/stream/translate'
8import type { TranslateContext } from '../src/stream/translate'
9import type {
10 OpencodeAssistantMessage,
11 OpencodeStreamEvent,
12} from '../src/stream/sdk-types'
13import type { AdapterYieldChunk } from '@tanstack/ai'
14
15function makeCtx(overrides: Partial<TranslateContext> = {}): TranslateContext {
16 let id = 0
17 return {
18 model: 'anthropic/claude-sonnet-4-5',
19 runId: 'run-1',
20 threadId: 'thread-1',
21 genId: () => `gen-${++id}`,
22 ...overrides,
23 }
24}
25
26async function* fromArray(
27 events: Array<OpencodeStreamEvent>,
28): AsyncIterable<OpencodeStreamEvent> {
29 for (const event of events) yield event
30}
31
32async function collect(
33 events: Array<OpencodeStreamEvent>,
34 ctx: TranslateContext = makeCtx(),
35): Promise<Array<AdapterYieldChunk>> {
36 const chunks: Array<AdapterYieldChunk> = []
37 for await (const chunk of translateOpencodeStream(fromArray(events), ctx)) {
38 chunks.push(chunk)
39 }
40 return chunks
41}
42
43const session: OpencodeStreamEvent = { kind: 'session', sessionId: 'sess-1' }
44
45function done(
46 overrides: Partial<OpencodeAssistantMessage> = {},
47): OpencodeStreamEvent {
48 return {
49 kind: 'done',
50 message: { id: 'msg-1', role: 'assistant', finish: 'stop', ...overrides },
51 }
52}
53
54function textPart(
55 id: string,
56 text: string,
57 delta?: string,
58 messageID = 'msg-1',
59): OpencodeStreamEvent {
60 return {
61 kind: 'event',
62 event: {
63 type: 'message.part.updated',
64 properties: {
65 part: { id, sessionID: 'sess-1', messageID, type: 'text', text },
66 ...(delta !== undefined && { delta }),
67 },
68 },
69 }
70}
71
72function messageUpdated(
73 id: string,
74 role: 'user' | 'assistant',
75): OpencodeStreamEvent {
76 return {
77 kind: 'event',
78 event: {
79 type: 'message.updated',
80 properties: { info: { id, sessionID: 'sess-1', role } },
81 },
82 }
83}
84
85describe('translateOpencodeStream', () => {
86 it('translates a simple text turn', async () => {
87 const chunks = await collect([
88 session,
89 textPart('part-1', 'hi there', 'hi there'),
90 done(),
91 ])
92
93 expect(chunks.map((c) => c.type)).toEqual([
94 'RUN_STARTED',
95 'CUSTOM',
96 'TEXT_MESSAGE_START',
97 'TEXT_MESSAGE_CONTENT',
98 'TEXT_MESSAGE_END',
99 'RUN_FINISHED',
100 ])
101 expect(chunks[1]).toMatchObject({
102 name: SESSION_ID_EVENT,
103 value: { sessionId: 'sess-1' },
104 })
105 expect(chunks[3]).toMatchObject({ delta: 'hi there', content: 'hi there' })
106 expect(chunks.at(-1)).toMatchObject({ finishReason: 'stop' })
107 })
108
109 it('does not expose user message parts as assistant output', async () => {
110 const chunks = await collect([
111 session,
112 textPart('user-part', 'user prompt', 'user prompt', 'user-message'),
113 messageUpdated('user-message', 'user'),
114 textPart('late-user-part', 'more', 'more', 'user-message'),
115 textPart('a-part', 'assistant answer', 'assistant answer', 'a-message'),
116 messageUpdated('a-message', 'assistant'),
117 done({ id: 'a-message' }),
118 ])
119
120 expect(
121 chunks.filter((chunk) => chunk.type === 'TEXT_MESSAGE_CONTENT'),
122 ).toMatchObject([
123 { delta: 'assistant answer', content: 'assistant answer' },
124 ])
125 })
126
127 it('streams parts as they arrive once the assistant role is known', async () => {
128 const log: Array<string> = []
129 async function* source(): AsyncIterable<OpencodeStreamEvent> {
130 yield session
131 yield messageUpdated('msg-1', 'assistant')
132 yield textPart('part-1', 'hi', 'hi')
133 log.push('done-pulled')
134 yield done()
135 }
136
137 for await (const chunk of translateOpencodeStream(source(), makeCtx())) {
138 log.push(chunk.type)
139 }
140
141 expect(log.indexOf('TEXT_MESSAGE_CONTENT')).toBeLessThan(
142 log.indexOf('done-pulled'),
143 )
144 })
145
146 it('accumulates incremental text deltas', async () => {
147 const chunks = await collect([
148 session,
149 messageUpdated('msg-1', 'assistant'),
150 textPart('part-1', 'Hel', 'Hel'),
151 textPart('part-1', 'Hello', 'lo'),
152 done(),
153 ])
154 const contents = chunks.filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
155 expect(contents).toHaveLength(2)
156 expect(contents[0]).toMatchObject({ delta: 'Hel', content: 'Hel' })
157 expect(contents[1]).toMatchObject({ delta: 'lo', content: 'Hello' })
158 // A single START/END pair for the one part id.
159 expect(chunks.filter((c) => c.type === 'TEXT_MESSAGE_START')).toHaveLength(
160 1,
161 )
162 expect(chunks.filter((c) => c.type === 'TEXT_MESSAGE_END')).toHaveLength(1)
163 })
164
165 it('derives the delta from full-text snapshots when no delta is given', async () => {
166 const chunks = await collect([
167 session,
168 messageUpdated('msg-1', 'assistant'),
169 textPart('part-1', 'Hel'),
170 textPart('part-1', 'Hello'),
171 done(),
172 ])
173 const contents = chunks.filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
174 expect(contents[0]).toMatchObject({ delta: 'Hel' })
175 expect(contents[1]).toMatchObject({ delta: 'lo', content: 'Hello' })
176 })
177
178 it('keeps only the latest update of a part while its role is unknown', async () => {
179 const chunks = await collect([
180 session,
181 textPart('part-1', 'The', 'The'),
182 textPart('part-1', 'The answer', ' answer'),
183 textPart('part-1', 'The answer is 42', ' is 42'),
184 done(),
185 ])
186 const contents = chunks.filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
187
188 expect(contents).toHaveLength(1)
189 expect(contents[0]).toMatchObject({
190 delta: 'The answer is 42',
191 content: 'The answer is 42',
192 })
193 })
194
195 it('reports usage with cache and reasoning details', async () => {
196 const chunks = await collect([
197 session,
198 done({
199 tokens: {
200 input: 100,
201 output: 20,
202 reasoning: 5,
203 cache: { read: 40, write: 0 },
204 },
205 }),
206 ])
207 const finished = chunks.at(-1) as unknown as {
208 usage: Record<string, unknown>
209 }
210 expect(finished.usage).toMatchObject({
211 promptTokens: 100,
212 completionTokens: 20,
213 totalTokens: 120,
214 promptTokensDetails: { cachedTokens: 40 },
215 completionTokensDetails: { reasoningTokens: 5 },
216 })
217 })
218
219 it('maps a length finish to finishReason length', async () => {
220 const chunks = await collect([session, done({ finish: 'length' })])
221 expect(chunks.at(-1)).toMatchObject({ finishReason: 'length' })
222 })
223
224 it('translates a reasoning part into a reasoning sequence', async () => {
225 const chunks = await collect([
226 session,
227 {
228 kind: 'event',
229 event: {
230 type: 'message.part.updated',
231 properties: {
232 part: {
233 id: 'r-1',
234 sessionID: 'sess-1',
235 messageID: 'msg-1',
236 type: 'reasoning',
237 text: 'thinking',
238 },
239 delta: 'thinking',
240 },
241 },
242 },
243 done(),
244 ])
245 expect(chunks.map((c) => c.type)).toEqual([
246 'RUN_STARTED',
247 'CUSTOM',
248 'REASONING_START',
249 'REASONING_MESSAGE_START',
250 'REASONING_MESSAGE_CONTENT',
251 'REASONING_MESSAGE_END',
252 'REASONING_END',
253 'RUN_FINISHED',
254 ])
255 })
256
257 function toolEvent(
258 callID: string,
259 tool: string,
260 state: Record<string, unknown>,
261 ): OpencodeStreamEvent {
262 return {
263 kind: 'event',
264 event: {
265 type: 'message.part.updated',
266 properties: {
267 part: {
268 id: `part-${callID}`,
269 sessionID: 'sess-1',
270 messageID: 'msg-1',
271 type: 'tool',
272 callID,
273 tool,
274 state: state as never,
275 },
276 },
277 },
278 }
279 }
280
281 it('pairs a tool call across running and completed states', async () => {
282 const chunks = await collect([
283 session,
284 toolEvent('call-1', 'bash', {
285 status: 'running',
286 input: { command: 'ls' },
287 }),
288 toolEvent('call-1', 'bash', {
289 status: 'completed',
290 input: { command: 'ls' },
291 output: 'file.txt',
292 title: 'ls',
293 }),
294 done(),
295 ])
296 expect(chunks.map((c) => c.type)).toEqual([
297 'RUN_STARTED',
298 'CUSTOM',
299 'TOOL_CALL_START',
300 'TOOL_CALL_ARGS',
301 'TOOL_CALL_END',
302 'TOOL_CALL_RESULT',
303 'RUN_FINISHED',
304 ])
305 expect(chunks[2]).toMatchObject({
306 toolCallId: 'call-1',
307 toolCallName: 'bash',
308 })
309 expect(chunks[3]).toMatchObject({ args: JSON.stringify({ command: 'ls' }) })
310 expect(chunks[5]).toMatchObject({ content: 'file.txt' })
311 expect((chunks[5] as { state?: string }).state).toBeUndefined()
312 })
313
314 it('waits for tool input before opening a pending tool call', async () => {
315 const chunks = await collect([
316 session,
317 toolEvent('call-pending', 'bash', { status: 'pending', input: {} }),
318 toolEvent('call-pending', 'bash', {
319 status: 'running',
320 input: { command: 'ls' },
321 }),
322 toolEvent('call-pending', 'bash', {
323 status: 'completed',
324 input: { command: 'ls' },
325 output: 'file.txt',
326 }),
327 done(),
328 ])
329
330 expect(
331 chunks.filter((chunk) => chunk.type === 'TOOL_CALL_ARGS'),
332 ).toMatchObject([{ args: JSON.stringify({ command: 'ls' }) }])
333 })
334
335 it('marks tool errors as output-error', async () => {
336 const chunks = await collect([
337 session,
338 toolEvent('call-2', 'bash', {
339 status: 'error',
340 input: { command: 'false' },
341 error: 'exit 1',
342 }),
343 done(),
344 ])
345 expect(chunks.find((c) => c.type === 'TOOL_CALL_RESULT')).toMatchObject({
346 content: 'exit 1',
347 state: 'output-error',
348 })
349 })
350
351 it('does not duplicate START events across repeated tool updates', async () => {
352 const chunks = await collect([
353 session,
354 toolEvent('call-3', 'read', { status: 'pending', input: {} }),
355 toolEvent('call-3', 'read', { status: 'running', input: { path: 'a' } }),
356 toolEvent('call-3', 'read', {
357 status: 'completed',
358 input: { path: 'a' },
359 output: 'data',
360 title: 'read a',
361 }),
362 done(),
363 ])
364 expect(chunks.filter((c) => c.type === 'TOOL_CALL_START')).toHaveLength(1)
365 expect(chunks.filter((c) => c.type === 'TOOL_CALL_RESULT')).toHaveLength(1)
366 })
367
368 it('surfaces bridged MCP tool calls under the registered name', async () => {
369 const chunks = await collect(
370 [
371 session,
372 toolEvent('call-4', 'tanstack_lookup_user', {
373 status: 'completed',
374 input: { userId: '7' },
375 output: '{"name":"Ada"}',
376 title: 'lookup_user',
377 }),
378 done(),
379 ],
380 makeCtx({ bridgedToolNames: new Set(['lookup_user']) }),
381 )
382 expect(chunks.find((c) => c.type === 'TOOL_CALL_START')).toMatchObject({
383 toolCallName: 'lookup_user',
384 })
385 expect(chunks.find((c) => c.type === 'TOOL_CALL_RESULT')).toMatchObject({
386 content: '{"name":"Ada"}',
387 })
388 })
389
390 it('synthesizes interrupted results for unresolved tool calls on done', async () => {
391 const chunks = await collect([
392 session,
393 toolEvent('call-9', 'bash', {
394 status: 'running',
395 input: { command: 'sleep 100' },
396 }),
397 done(),
398 ])
399 const result = chunks.find((c) => c.type === 'TOOL_CALL_RESULT')
400 expect(result).toMatchObject({
401 toolCallId: 'call-9',
402 content: JSON.stringify({ status: 'interrupted' }),
403 })
404 expect(chunks.at(-1)).toMatchObject({ type: 'RUN_FINISHED' })
405 })
406
407 it('maps a message error to RUN_ERROR', async () => {
408 const chunks = await collect([
409 session,
410 done({
411 finish: undefined,
412 error: { name: 'ProviderAuthError', data: { message: 'no key' } },
413 }),
414 ])
415 expect(chunks.at(-1)).toMatchObject({
416 type: 'RUN_ERROR',
417 message: 'no key',
418 })
419 })
420
421 it('emits a todo CUSTOM event', async () => {
422 const chunks = await collect([
423 session,
424 {
425 kind: 'event',
426 event: {
427 type: 'todo.updated',
428 properties: {
429 sessionID: 'sess-1',
430 todos: [{ content: 'step 1', status: 'pending' }],
431 },
432 },
433 },
434 done(),
435 ])
436 expect(
437 chunks.find((c) => c.type === 'CUSTOM' && c.name === TODO_EVENT),
438 ).toBeDefined()
439 })
440
441 it('forwards raw stream events to onStreamEvent', async () => {
442 const kinds: Array<string> = []
443 await collect(
444 [session, textPart('p', 'hi', 'hi'), done()],
445 makeCtx({ onStreamEvent: (event) => kinds.push(event.kind) }),
446 )
447 expect(kinds).toEqual(['session', 'event', 'done'])
448 })
449
450 it('synthesizes results then rethrows when the source stream throws', async () => {
451 async function* failing(): AsyncIterable<OpencodeStreamEvent> {
452 yield session
453 yield messageUpdated('msg-1', 'assistant')
454 yield {
455 kind: 'event',
456 event: {
457 type: 'message.part.updated',
458 properties: {
459 part: {
460 id: 'p-c',
461 sessionID: 'sess-1',
462 messageID: 'msg-1',
463 type: 'tool',
464 callID: 'call-7',
465 tool: 'bash',
466 state: { status: 'running', input: {} } as never,
467 },
468 },
469 },
470 }
471 throw new Error('aborted')
472 }
473
474 const chunks: Array<AdapterYieldChunk> = []
475 await expect(async () => {
476 for await (const chunk of translateOpencodeStream(failing(), makeCtx())) {
477 chunks.push(chunk)
478 }
479 }).rejects.toThrow('aborted')
480 expect(chunks.at(-1)).toMatchObject({
481 type: 'TOOL_CALL_RESULT',
482 toolCallId: 'call-7',
483 content: JSON.stringify({ status: 'interrupted' }),
484 })
485 })
486})
487
488describe('resolveToolName', () => {
489 it('returns the tool name verbatim without bridged names', () => {
490 expect(resolveToolName('bash', undefined)).toBe('bash')
491 expect(resolveToolName('edit', new Set())).toBe('edit')
492 })
493
494 it('strips the tanstack_ prefix for bridged tools', () => {
495 const bridged = new Set(['lookup_user'])
496 expect(resolveToolName('tanstack_lookup_user', bridged)).toBe('lookup_user')
497 expect(resolveToolName('lookup_user', bridged)).toBe('lookup_user')
498 })
499
500 it('leaves foreign tool names untouched', () => {
501 expect(
502 resolveToolName('github_create_issue', new Set(['lookup_user'])),
503 ).toBe('github_create_issue')
504 })
505})