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 textPart('part-1', 'Hel', 'Hel'),
150 textPart('part-1', 'Hello', 'lo'),
151 done(),
152 ])
153 const contents = chunks.filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
154 expect(contents).toHaveLength(2)
155 expect(contents[0]).toMatchObject({ delta: 'Hel', content: 'Hel' })
156 expect(contents[1]).toMatchObject({ delta: 'lo', content: 'Hello' })
157 // A single START/END pair for the one part id.
158 expect(chunks.filter((c) => c.type === 'TEXT_MESSAGE_START')).toHaveLength(
159 1,
160 )
161 expect(chunks.filter((c) => c.type === 'TEXT_MESSAGE_END')).toHaveLength(1)
162 })
163
164 it('derives the delta from full-text snapshots when no delta is given', async () => {
165 const chunks = await collect([
166 session,
167 textPart('part-1', 'Hel'),
168 textPart('part-1', 'Hello'),
169 done(),
170 ])
171 const contents = chunks.filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
172 expect(contents[0]).toMatchObject({ delta: 'Hel' })
173 expect(contents[1]).toMatchObject({ delta: 'lo', content: 'Hello' })
174 })
175
176 it('reports usage with cache and reasoning details', async () => {
177 const chunks = await collect([
178 session,
179 done({
180 tokens: {
181 input: 100,
182 output: 20,
183 reasoning: 5,
184 cache: { read: 40, write: 0 },
185 },
186 }),
187 ])
188 const finished = chunks.at(-1) as unknown as {
189 usage: Record<string, unknown>
190 }
191 expect(finished.usage).toMatchObject({
192 promptTokens: 100,
193 completionTokens: 20,
194 totalTokens: 120,
195 promptTokensDetails: { cachedTokens: 40 },
196 completionTokensDetails: { reasoningTokens: 5 },
197 })
198 })
199
200 it('maps a length finish to finishReason length', async () => {
201 const chunks = await collect([session, done({ finish: 'length' })])
202 expect(chunks.at(-1)).toMatchObject({ finishReason: 'length' })
203 })
204
205 it('translates a reasoning part into a reasoning sequence', async () => {
206 const chunks = await collect([
207 session,
208 {
209 kind: 'event',
210 event: {
211 type: 'message.part.updated',
212 properties: {
213 part: {
214 id: 'r-1',
215 sessionID: 'sess-1',
216 messageID: 'msg-1',
217 type: 'reasoning',
218 text: 'thinking',
219 },
220 delta: 'thinking',
221 },
222 },
223 },
224 done(),
225 ])
226 expect(chunks.map((c) => c.type)).toEqual([
227 'RUN_STARTED',
228 'CUSTOM',
229 'REASONING_START',
230 'REASONING_MESSAGE_START',
231 'REASONING_MESSAGE_CONTENT',
232 'REASONING_MESSAGE_END',
233 'REASONING_END',
234 'RUN_FINISHED',
235 ])
236 })
237
238 function toolEvent(
239 callID: string,
240 tool: string,
241 state: Record<string, unknown>,
242 ): OpencodeStreamEvent {
243 return {
244 kind: 'event',
245 event: {
246 type: 'message.part.updated',
247 properties: {
248 part: {
249 id: `part-${callID}`,
250 sessionID: 'sess-1',
251 messageID: 'msg-1',
252 type: 'tool',
253 callID,
254 tool,
255 state: state as never,
256 },
257 },
258 },
259 }
260 }
261
262 it('pairs a tool call across running and completed states', async () => {
263 const chunks = await collect([
264 session,
265 toolEvent('call-1', 'bash', {
266 status: 'running',
267 input: { command: 'ls' },
268 }),
269 toolEvent('call-1', 'bash', {
270 status: 'completed',
271 input: { command: 'ls' },
272 output: 'file.txt',
273 title: 'ls',
274 }),
275 done(),
276 ])
277 expect(chunks.map((c) => c.type)).toEqual([
278 'RUN_STARTED',
279 'CUSTOM',
280 'TOOL_CALL_START',
281 'TOOL_CALL_ARGS',
282 'TOOL_CALL_END',
283 'TOOL_CALL_RESULT',
284 'RUN_FINISHED',
285 ])
286 expect(chunks[2]).toMatchObject({
287 toolCallId: 'call-1',
288 toolCallName: 'bash',
289 })
290 expect(chunks[3]).toMatchObject({ args: JSON.stringify({ command: 'ls' }) })
291 expect(chunks[5]).toMatchObject({ content: 'file.txt' })
292 expect((chunks[5] as { state?: string }).state).toBeUndefined()
293 })
294
295 it('waits for tool input before opening a pending tool call', async () => {
296 const chunks = await collect([
297 session,
298 toolEvent('call-pending', 'bash', { status: 'pending', input: {} }),
299 toolEvent('call-pending', 'bash', {
300 status: 'running',
301 input: { command: 'ls' },
302 }),
303 toolEvent('call-pending', 'bash', {
304 status: 'completed',
305 input: { command: 'ls' },
306 output: 'file.txt',
307 }),
308 done(),
309 ])
310
311 expect(
312 chunks.filter((chunk) => chunk.type === 'TOOL_CALL_ARGS'),
313 ).toMatchObject([{ args: JSON.stringify({ command: 'ls' }) }])
314 })
315
316 it('marks tool errors as output-error', async () => {
317 const chunks = await collect([
318 session,
319 toolEvent('call-2', 'bash', {
320 status: 'error',
321 input: { command: 'false' },
322 error: 'exit 1',
323 }),
324 done(),
325 ])
326 expect(chunks.find((c) => c.type === 'TOOL_CALL_RESULT')).toMatchObject({
327 content: 'exit 1',
328 state: 'output-error',
329 })
330 })
331
332 it('does not duplicate START events across repeated tool updates', async () => {
333 const chunks = await collect([
334 session,
335 toolEvent('call-3', 'read', { status: 'pending', input: {} }),
336 toolEvent('call-3', 'read', { status: 'running', input: { path: 'a' } }),
337 toolEvent('call-3', 'read', {
338 status: 'completed',
339 input: { path: 'a' },
340 output: 'data',
341 title: 'read a',
342 }),
343 done(),
344 ])
345 expect(chunks.filter((c) => c.type === 'TOOL_CALL_START')).toHaveLength(1)
346 expect(chunks.filter((c) => c.type === 'TOOL_CALL_RESULT')).toHaveLength(1)
347 })
348
349 it('surfaces bridged MCP tool calls under the registered name', async () => {
350 const chunks = await collect(
351 [
352 session,
353 toolEvent('call-4', 'tanstack_lookup_user', {
354 status: 'completed',
355 input: { userId: '7' },
356 output: '{"name":"Ada"}',
357 title: 'lookup_user',
358 }),
359 done(),
360 ],
361 makeCtx({ bridgedToolNames: new Set(['lookup_user']) }),
362 )
363 expect(chunks.find((c) => c.type === 'TOOL_CALL_START')).toMatchObject({
364 toolCallName: 'lookup_user',
365 })
366 expect(chunks.find((c) => c.type === 'TOOL_CALL_RESULT')).toMatchObject({
367 content: '{"name":"Ada"}',
368 })
369 })
370
371 it('synthesizes interrupted results for unresolved tool calls on done', async () => {
372 const chunks = await collect([
373 session,
374 toolEvent('call-9', 'bash', {
375 status: 'running',
376 input: { command: 'sleep 100' },
377 }),
378 done(),
379 ])
380 const result = chunks.find((c) => c.type === 'TOOL_CALL_RESULT')
381 expect(result).toMatchObject({
382 toolCallId: 'call-9',
383 content: JSON.stringify({ status: 'interrupted' }),
384 })
385 expect(chunks.at(-1)).toMatchObject({ type: 'RUN_FINISHED' })
386 })
387
388 it('maps a message error to RUN_ERROR', async () => {
389 const chunks = await collect([
390 session,
391 done({
392 finish: undefined,
393 error: { name: 'ProviderAuthError', data: { message: 'no key' } },
394 }),
395 ])
396 expect(chunks.at(-1)).toMatchObject({
397 type: 'RUN_ERROR',
398 message: 'no key',
399 })
400 })
401
402 it('emits a todo CUSTOM event', async () => {
403 const chunks = await collect([
404 session,
405 {
406 kind: 'event',
407 event: {
408 type: 'todo.updated',
409 properties: {
410 sessionID: 'sess-1',
411 todos: [{ content: 'step 1', status: 'pending' }],
412 },
413 },
414 },
415 done(),
416 ])
417 expect(
418 chunks.find((c) => c.type === 'CUSTOM' && c.name === TODO_EVENT),
419 ).toBeDefined()
420 })
421
422 it('forwards raw stream events to onStreamEvent', async () => {
423 const kinds: Array<string> = []
424 await collect(
425 [session, textPart('p', 'hi', 'hi'), done()],
426 makeCtx({ onStreamEvent: (event) => kinds.push(event.kind) }),
427 )
428 expect(kinds).toEqual(['session', 'event', 'done'])
429 })
430
431 it('synthesizes results then rethrows when the source stream throws', async () => {
432 async function* failing(): AsyncIterable<OpencodeStreamEvent> {
433 yield session
434 yield messageUpdated('msg-1', 'assistant')
435 yield {
436 kind: 'event',
437 event: {
438 type: 'message.part.updated',
439 properties: {
440 part: {
441 id: 'p-c',
442 sessionID: 'sess-1',
443 messageID: 'msg-1',
444 type: 'tool',
445 callID: 'call-7',
446 tool: 'bash',
447 state: { status: 'running', input: {} } as never,
448 },
449 },
450 },
451 }
452 throw new Error('aborted')
453 }
454
455 const chunks: Array<AdapterYieldChunk> = []
456 await expect(async () => {
457 for await (const chunk of translateOpencodeStream(failing(), makeCtx())) {
458 chunks.push(chunk)
459 }
460 }).rejects.toThrow('aborted')
461 expect(chunks.at(-1)).toMatchObject({
462 type: 'TOOL_CALL_RESULT',
463 toolCallId: 'call-7',
464 content: JSON.stringify({ status: 'interrupted' }),
465 })
466 })
467})
468
469describe('resolveToolName', () => {
470 it('returns the tool name verbatim without bridged names', () => {
471 expect(resolveToolName('bash', undefined)).toBe('bash')
472 expect(resolveToolName('edit', new Set())).toBe('edit')
473 })
474
475 it('strips the tanstack_ prefix for bridged tools', () => {
476 const bridged = new Set(['lookup_user'])
477 expect(resolveToolName('tanstack_lookup_user', bridged)).toBe('lookup_user')
478 expect(resolveToolName('lookup_user', bridged)).toBe('lookup_user')
479 })
480
481 it('leaves foreign tool names untouched', () => {
482 expect(
483 resolveToolName('github_create_issue', new Set(['lookup_user'])),
484 ).toBe('github_create_issue')
485 })
486})