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 { StreamChunk } 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<StreamChunk>> {
36 const chunks: Array<StreamChunk> = []
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): OpencodeStreamEvent {
59 return {
60 kind: 'event',
61 event: {
62 type: 'message.part.updated',
63 properties: {
64 part: { id, sessionID: 'sess-1', type: 'text', text },
65 ...(delta !== undefined && { delta }),
66 },
67 },
68 }
69}
70
71describe('translateOpencodeStream', () => {
72 it('translates a simple text turn', async () => {
73 const chunks = await collect([
74 session,
75 textPart('part-1', 'hi there', 'hi there'),
76 done(),
77 ])
78
79 expect(chunks.map((c) => c.type)).toEqual([
80 'RUN_STARTED',
81 'CUSTOM',
82 'TEXT_MESSAGE_START',
83 'TEXT_MESSAGE_CONTENT',
84 'TEXT_MESSAGE_END',
85 'RUN_FINISHED',
86 ])
87 expect(chunks[1]).toMatchObject({
88 name: SESSION_ID_EVENT,
89 value: { sessionId: 'sess-1' },
90 })
91 expect(chunks[3]).toMatchObject({ delta: 'hi there', content: 'hi there' })
92 expect(chunks.at(-1)).toMatchObject({ finishReason: 'stop' })
93 })
94
95 it('accumulates incremental text deltas', async () => {
96 const chunks = await collect([
97 session,
98 textPart('part-1', 'Hel', 'Hel'),
99 textPart('part-1', 'Hello', 'lo'),
100 done(),
101 ])
102 const contents = chunks.filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
103 expect(contents).toHaveLength(2)
104 expect(contents[0]).toMatchObject({ delta: 'Hel', content: 'Hel' })
105 expect(contents[1]).toMatchObject({ delta: 'lo', content: 'Hello' })
106 // A single START/END pair for the one part id.
107 expect(chunks.filter((c) => c.type === 'TEXT_MESSAGE_START')).toHaveLength(
108 1,
109 )
110 expect(chunks.filter((c) => c.type === 'TEXT_MESSAGE_END')).toHaveLength(1)
111 })
112
113 it('derives the delta from full-text snapshots when no delta is given', async () => {
114 const chunks = await collect([
115 session,
116 textPart('part-1', 'Hel'),
117 textPart('part-1', 'Hello'),
118 done(),
119 ])
120 const contents = chunks.filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
121 expect(contents[0]).toMatchObject({ delta: 'Hel' })
122 expect(contents[1]).toMatchObject({ delta: 'lo', content: 'Hello' })
123 })
124
125 it('reports usage with cache and reasoning details', async () => {
126 const chunks = await collect([
127 session,
128 done({
129 tokens: {
130 input: 100,
131 output: 20,
132 reasoning: 5,
133 cache: { read: 40, write: 0 },
134 },
135 }),
136 ])
137 const finished = chunks.at(-1) as unknown as {
138 usage: Record<string, unknown>
139 }
140 expect(finished.usage).toMatchObject({
141 promptTokens: 100,
142 completionTokens: 20,
143 totalTokens: 120,
144 promptTokensDetails: { cachedTokens: 40 },
145 completionTokensDetails: { reasoningTokens: 5 },
146 })
147 })
148
149 it('maps a length finish to finishReason length', async () => {
150 const chunks = await collect([session, done({ finish: 'length' })])
151 expect(chunks.at(-1)).toMatchObject({ finishReason: 'length' })
152 })
153
154 it('translates a reasoning part into a reasoning sequence', async () => {
155 const chunks = await collect([
156 session,
157 {
158 kind: 'event',
159 event: {
160 type: 'message.part.updated',
161 properties: {
162 part: {
163 id: 'r-1',
164 sessionID: 'sess-1',
165 type: 'reasoning',
166 text: 'thinking',
167 },
168 delta: 'thinking',
169 },
170 },
171 },
172 done(),
173 ])
174 expect(chunks.map((c) => c.type)).toEqual([
175 'RUN_STARTED',
176 'CUSTOM',
177 'REASONING_START',
178 'REASONING_MESSAGE_START',
179 'REASONING_MESSAGE_CONTENT',
180 'REASONING_MESSAGE_END',
181 'REASONING_END',
182 'RUN_FINISHED',
183 ])
184 })
185
186 function toolEvent(
187 callID: string,
188 tool: string,
189 state: Record<string, unknown>,
190 ): OpencodeStreamEvent {
191 return {
192 kind: 'event',
193 event: {
194 type: 'message.part.updated',
195 properties: {
196 part: {
197 id: `part-${callID}`,
198 sessionID: 'sess-1',
199 type: 'tool',
200 callID,
201 tool,
202 state: state as never,
203 },
204 },
205 },
206 }
207 }
208
209 it('pairs a tool call across running and completed states', async () => {
210 const chunks = await collect([
211 session,
212 toolEvent('call-1', 'bash', {
213 status: 'running',
214 input: { command: 'ls' },
215 }),
216 toolEvent('call-1', 'bash', {
217 status: 'completed',
218 input: { command: 'ls' },
219 output: 'file.txt',
220 title: 'ls',
221 }),
222 done(),
223 ])
224 expect(chunks.map((c) => c.type)).toEqual([
225 'RUN_STARTED',
226 'CUSTOM',
227 'TOOL_CALL_START',
228 'TOOL_CALL_ARGS',
229 'TOOL_CALL_END',
230 'TOOL_CALL_RESULT',
231 'RUN_FINISHED',
232 ])
233 expect(chunks[2]).toMatchObject({
234 toolCallId: 'call-1',
235 toolCallName: 'bash',
236 })
237 expect(chunks[3]).toMatchObject({ args: JSON.stringify({ command: 'ls' }) })
238 expect(chunks[5]).toMatchObject({ content: 'file.txt' })
239 expect((chunks[5] as { state?: string }).state).toBeUndefined()
240 })
241
242 it('marks tool errors as output-error', async () => {
243 const chunks = await collect([
244 session,
245 toolEvent('call-2', 'bash', {
246 status: 'error',
247 input: { command: 'false' },
248 error: 'exit 1',
249 }),
250 done(),
251 ])
252 expect(chunks.find((c) => c.type === 'TOOL_CALL_RESULT')).toMatchObject({
253 content: 'exit 1',
254 state: 'output-error',
255 })
256 })
257
258 it('does not duplicate START events across repeated tool updates', async () => {
259 const chunks = await collect([
260 session,
261 toolEvent('call-3', 'read', { status: 'pending', input: {} }),
262 toolEvent('call-3', 'read', { status: 'running', input: { path: 'a' } }),
263 toolEvent('call-3', 'read', {
264 status: 'completed',
265 input: { path: 'a' },
266 output: 'data',
267 title: 'read a',
268 }),
269 done(),
270 ])
271 expect(chunks.filter((c) => c.type === 'TOOL_CALL_START')).toHaveLength(1)
272 expect(chunks.filter((c) => c.type === 'TOOL_CALL_RESULT')).toHaveLength(1)
273 })
274
275 it('surfaces bridged MCP tool calls under the registered name', async () => {
276 const chunks = await collect(
277 [
278 session,
279 toolEvent('call-4', 'tanstack_lookup_user', {
280 status: 'completed',
281 input: { userId: '7' },
282 output: '{"name":"Ada"}',
283 title: 'lookup_user',
284 }),
285 done(),
286 ],
287 makeCtx({ bridgedToolNames: new Set(['lookup_user']) }),
288 )
289 expect(chunks.find((c) => c.type === 'TOOL_CALL_START')).toMatchObject({
290 toolCallName: 'lookup_user',
291 })
292 expect(chunks.find((c) => c.type === 'TOOL_CALL_RESULT')).toMatchObject({
293 content: '{"name":"Ada"}',
294 })
295 })
296
297 it('synthesizes interrupted results for unresolved tool calls on done', async () => {
298 const chunks = await collect([
299 session,
300 toolEvent('call-9', 'bash', {
301 status: 'running',
302 input: { command: 'sleep 100' },
303 }),
304 done(),
305 ])
306 const result = chunks.find((c) => c.type === 'TOOL_CALL_RESULT')
307 expect(result).toMatchObject({
308 toolCallId: 'call-9',
309 content: JSON.stringify({ status: 'interrupted' }),
310 })
311 expect(chunks.at(-1)).toMatchObject({ type: 'RUN_FINISHED' })
312 })
313
314 it('maps a message error to RUN_ERROR', async () => {
315 const chunks = await collect([
316 session,
317 done({
318 finish: undefined,
319 error: { name: 'ProviderAuthError', data: { message: 'no key' } },
320 }),
321 ])
322 expect(chunks.at(-1)).toMatchObject({
323 type: 'RUN_ERROR',
324 message: 'no key',
325 })
326 })
327
328 it('emits a todo CUSTOM event', async () => {
329 const chunks = await collect([
330 session,
331 {
332 kind: 'event',
333 event: {
334 type: 'todo.updated',
335 properties: {
336 sessionID: 'sess-1',
337 todos: [{ content: 'step 1', status: 'pending' }],
338 },
339 },
340 },
341 done(),
342 ])
343 expect(
344 chunks.find((c) => c.type === 'CUSTOM' && c.name === TODO_EVENT),
345 ).toBeDefined()
346 })
347
348 it('forwards raw stream events to onStreamEvent', async () => {
349 const kinds: Array<string> = []
350 await collect(
351 [session, textPart('p', 'hi', 'hi'), done()],
352 makeCtx({ onStreamEvent: (event) => kinds.push(event.kind) }),
353 )
354 expect(kinds).toEqual(['session', 'event', 'done'])
355 })
356
357 it('synthesizes results then rethrows when the source stream throws', async () => {
358 async function* failing(): AsyncIterable<OpencodeStreamEvent> {
359 yield session
360 yield {
361 kind: 'event',
362 event: {
363 type: 'message.part.updated',
364 properties: {
365 part: {
366 id: 'p-c',
367 sessionID: 'sess-1',
368 type: 'tool',
369 callID: 'call-7',
370 tool: 'bash',
371 state: { status: 'running', input: {} } as never,
372 },
373 },
374 },
375 }
376 throw new Error('aborted')
377 }
378
379 const chunks: Array<StreamChunk> = []
380 await expect(async () => {
381 for await (const chunk of translateOpencodeStream(failing(), makeCtx())) {
382 chunks.push(chunk)
383 }
384 }).rejects.toThrow('aborted')
385 expect(chunks.at(-1)).toMatchObject({
386 type: 'TOOL_CALL_RESULT',
387 toolCallId: 'call-7',
388 content: JSON.stringify({ status: 'interrupted' }),
389 })
390 })
391})
392
393describe('resolveToolName', () => {
394 it('returns the tool name verbatim without bridged names', () => {
395 expect(resolveToolName('bash', undefined)).toBe('bash')
396 expect(resolveToolName('edit', new Set())).toBe('edit')
397 })
398
399 it('strips the tanstack_ prefix for bridged tools', () => {
400 const bridged = new Set(['lookup_user'])
401 expect(resolveToolName('tanstack_lookup_user', bridged)).toBe('lookup_user')
402 expect(resolveToolName('lookup_user', bridged)).toBe('lookup_user')
403 })
404
405 it('leaves foreign tool names untouched', () => {
406 expect(
407 resolveToolName('github_create_issue', new Set(['lookup_user'])),
408 ).toBe('github_create_issue')
409 })
410})