Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

realtime-parse.test.ts

86 lines2.8 KB

1import { describe, expect, it } from 'vitest'
2import { parseResponseMessages } from '../src/realtime/client'
3import type { LiveServerMessage } from '@google/genai'
4​
5describe('parseResponseMessages', () => {
6 it('maps setup completion exclusively', () => {
7 const responses = parseResponseMessages({
8 setupComplete: {},
9 // A real message never bundles these with setupComplete, but assert the
10 // "exclusive" short-circuit ignores anything else present.
11 serverContent: { turnComplete: true },
12 } as LiveServerMessage)
13​
14 expect(responses).toEqual([
15 { type: 'setup_complete', data: '', endOfTurn: false },
16 ])
17 })
18​
19 it('maps tool calls exclusively', () => {
20 const toolCall = { functionCalls: [{ id: '1', name: 'getTime', args: {} }] }
21 const responses = parseResponseMessages({
22 toolCall,
23 } as LiveServerMessage)
24​
25 expect(responses).toEqual([
26 { type: 'tool_call', data: toolCall, endOfTurn: false },
27 ])
28 })
29​
30 it('emits audio and input/output transcription from one bundled message', () => {
31 const responses = parseResponseMessages({
32 serverContent: {
33 modelTurn: { parts: [{ inlineData: { data: 'AAAA' } }] },
34 inputTranscription: { text: 'hello', finished: true },
35 outputTranscription: { text: 'hi', finished: false },
36 },
37 } as LiveServerMessage)
38​
39 expect(responses.map((r) => r.type)).toEqual([
40 'audio',
41 'input_transcription',
42 'output_transcription',
43 ])
44 const input = responses.find((r) => r.type === 'input_transcription')
45 expect(input).toMatchObject({ data: { text: 'hello', finished: true } })
46 })
47​
48 it('distinguishes thought parts from text parts', () => {
49 const responses = parseResponseMessages({
50 serverContent: {
51 modelTurn: {
52 parts: [{ text: 'thinking...', thought: true }, { text: 'answer' }],
53 },
54 },
55 } as LiveServerMessage)
56​
57 expect(responses).toEqual([
58 { type: 'thought', data: 'thinking...', endOfTurn: false },
59 { type: 'text', data: 'answer', endOfTurn: false },
60 ])
61 })
62​
63 it('maps go_away, usage and turn completion', () => {
64 const goAway = parseResponseMessages({
65 goAway: { timeLeft: '5s' },
66 } as LiveServerMessage)
67 expect(goAway[0]).toMatchObject({
68 type: 'go_away',
69 data: { timeLeft: '5s' },
70 })
71​
72 const usage = parseResponseMessages({
73 usageMetadata: { totalTokenCount: 10 },
74 } as LiveServerMessage)
75 expect(usage[0]?.type).toBe('usage_metadata')
76​
77 const turn = parseResponseMessages({
78 serverContent: { turnComplete: true },
79 } as LiveServerMessage)
80 expect(turn).toEqual([{ type: 'turn_complete', data: '', endOfTurn: true }])
81 })
82​
83 it('returns an empty array for an empty message', () => {
84 expect(parseResponseMessages({} as LiveServerMessage)).toEqual([])
85 })
86})