Open History to see the last commit
1import { beforeEach, describe, expect, it, vi } from 'vitest'
2import { chat } from '@tanstack/ai'
3import { GeminiTextAdapter } from '../src/adapters/text'
4import type { StreamChunk } from '@tanstack/ai'
5
6const mocks = vi.hoisted(() => {
7 return {
8 generateContentStreamSpy: vi.fn(),
9 }
10})
11
12vi.mock('@google/genai', async () => {
13 const actual = await vi.importActual<any>('@google/genai')
14 class MockGoogleGenAI {
15 public models = {
16 generateContentStream: mocks.generateContentStreamSpy,
17 }
18
19 constructor(_options: { apiKey: string }) {}
20 }
21
22 return {
23 GoogleGenAI: MockGoogleGenAI,
24 Type: actual.Type,
25 FinishReason: actual.FinishReason,
26 }
27})
28
29const emptyStream = () =>
30 (async function* () {
31 yield {
32 candidates: [
33 { content: { parts: [{ text: 'ok' }] }, finishReason: 'STOP' },
34 ],
35 usageMetadata: {
36 promptTokenCount: 1,
37 candidatesTokenCount: 1,
38 totalTokenCount: 2,
39 },
40 }
41 })()
42
43async function collectChunks(
44 iterable: AsyncIterable<StreamChunk>,
45): Promise<Array<StreamChunk>> {
46 const chunks: Array<StreamChunk> = []
47 for await (const chunk of iterable) {
48 chunks.push(chunk)
49 }
50 return chunks
51}
52
53describe('gemini file content source', () => {
54 beforeEach(() => {
55 vi.clearAllMocks()
56 })
57
58 it('maps a gemini file handle to fileData.fileUri', async () => {
59 mocks.generateContentStreamSpy.mockResolvedValueOnce(emptyStream())
60 const adapter = new GeminiTextAdapter({ apiKey: 'k' }, 'gemini-2.5-pro')
61
62 await collectChunks(
63 chat({
64 adapter,
65 messages: [
66 {
67 role: 'user',
68 content: [
69 { type: 'text', content: 'describe' },
70 {
71 type: 'image',
72 source: {
73 type: 'file',
74 value:
75 'https://generativelanguage.googleapis.com/v1beta/files/abc-123',
76 provider: 'gemini',
77 mimeType: 'image/png',
78 },
79 },
80 ],
81 },
82 ],
83 }),
84 )
85
86 expect(mocks.generateContentStreamSpy).toHaveBeenCalledTimes(1)
87 const [payload] = mocks.generateContentStreamSpy.mock.calls[0]!
88 const parts = payload.contents.at(-1).parts
89 const filePart = parts.find((p: any) => p.fileData)
90 expect(filePart.fileData).toEqual({
91 fileUri: 'https://generativelanguage.googleapis.com/v1beta/files/abc-123',
92 mimeType: 'image/png',
93 })
94 })
95
96 it('rejects a foreign provider file handle before any request is sent', async () => {
97 mocks.generateContentStreamSpy.mockResolvedValueOnce(emptyStream())
98 const adapter = new GeminiTextAdapter({ apiKey: 'k' }, 'gemini-2.5-pro')
99
100 await expect(
101 collectChunks(
102 chat({
103 adapter,
104 messages: [
105 {
106 role: 'user',
107 content: [
108 {
109 type: 'image',
110 source: {
111 type: 'file',
112 value: 'file-openai-1',
113 provider: 'openai',
114 },
115 },
116 ],
117 },
118 ],
119 }),
120 ),
121 ).rejects.toThrow(/gemini/)
122 expect(mocks.generateContentStreamSpy).not.toHaveBeenCalled()
123 })
124})