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 threadId: 'thread-1',
65 adapter,
66 messages: [
67 {
68 role: 'user',
69 content: [
70 { type: 'text', content: 'describe' },
71 {
72 type: 'image',
73 source: {
74 type: 'file',
75 value:
76 'https://generativelanguage.googleapis.com/v1beta/files/abc-123',
77 provider: 'gemini',
78 mimeType: 'image/png',
79 },
80 },
81 ],
82 },
83 ],
84 }),
85 )
86
87 expect(mocks.generateContentStreamSpy).toHaveBeenCalledTimes(1)
88 const [payload] = mocks.generateContentStreamSpy.mock.calls[0]!
89 const parts = payload.contents.at(-1).parts
90 const filePart = parts.find((p: any) => p.fileData)
91 expect(filePart.fileData).toEqual({
92 fileUri: 'https://generativelanguage.googleapis.com/v1beta/files/abc-123',
93 mimeType: 'image/png',
94 })
95 })
96
97 it('rejects a foreign provider file handle before any request is sent', async () => {
98 mocks.generateContentStreamSpy.mockResolvedValueOnce(emptyStream())
99 const adapter = new GeminiTextAdapter({ apiKey: 'k' }, 'gemini-2.5-pro')
100
101 await expect(
102 collectChunks(
103 chat({
104 threadId: 'thread-1',
105 adapter,
106 messages: [
107 {
108 role: 'user',
109 content: [
110 {
111 type: 'image',
112 source: {
113 type: 'file',
114 value: 'file-openai-1',
115 provider: 'openai',
116 },
117 },
118 ],
119 },
120 ],
121 }),
122 ),
123 ).rejects.toThrow(/gemini/)
124 expect(mocks.generateContentStreamSpy).not.toHaveBeenCalled()
125 })
126})