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

files-source.test.ts

146 lines4.3 KB

1import { describe, expect, it, vi } from 'vitest'
2import { chat } from '@tanstack/ai'
3import { createGrokText } from '../src/adapters/text'
4import { GROK_CHAT_MODELS } from '../src/model-meta'
5import type { StreamChunk } from '@tanstack/ai'
6​
7vi.mock('openai', () => {
8 return {
9 default: class {
10 responses = {
11 create: vi.fn(),
12 }
13 },
14 }
15})
16​
17function mockResponsesStream(): AsyncIterable<Record<string, unknown>> {
18 return {
19 // eslint-disable-next-line @typescript-eslint/require-await
20 async *[Symbol.asyncIterator]() {
21 yield {
22 type: 'response.created',
23 response: { id: 'r1', model: 'grok', status: 'in_progress' },
24 }
25 yield {
26 type: 'response.completed',
27 response: {
28 id: 'r1',
29 model: 'grok',
30 status: 'completed',
31 output: [],
32 usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 },
33 },
34 }
35 },
36 }
38​
39// xAI accepts `file_id` only on `input_file`, and only on agentic-capable
40// models, while its image path takes `image_url`. `grokFiles()` therefore
41// hands out an xAI public URL as the wire reference, and the adapter routes
42// it to the URL-shaped fields. These tests pin that mapping.
43function adapterWithMockClient(create: ReturnType<typeof vi.fn>) {
44 const adapter = createGrokText(GROK_CHAT_MODELS[0], 'test-key')
45 ;(adapter as unknown as { client: unknown }).client = {
46 responses: { create },
47 }
48 return adapter
50​
51async function collectChunks(
52 iterable: AsyncIterable<StreamChunk>,
53): Promise<Array<StreamChunk>> {
54 const chunks: Array<StreamChunk> = []
55 for await (const chunk of iterable) {
56 chunks.push(chunk)
57 }
58 return chunks
60​
61const PUBLIC_URL = 'https://files-cdn.x.ai/tok/file_abc123.png'
62​
63function fileSourceMessage(provider: string, type: 'image' | 'document') {
64 return [
65 {
66 role: 'user' as const,
67 content: [
68 {
69 type,
70 source: {
71 type: 'file' as const,
72 value: PUBLIC_URL,
73 provider: provider,
74 },
75 },
76 ],
77 },
78 ]
80​
81describe('grok file content source', () => {
82 it('maps a grok handle to input_image.image_url, not file_id', async () => {
83 const create = vi.fn().mockResolvedValueOnce(mockResponsesStream())
84 await collectChunks(
85 chat({
86 threadId: 'thread-1',
87 adapter: adapterWithMockClient(create),
88 messages: fileSourceMessage('grok', 'image'),
89 }),
90 )
91​
92 const [payload] = create.mock.calls[0]!
93 const userItem = payload.input.find(
94 (item: any) => item.type === 'message' && item.role === 'user',
95 )
96 const imageContent = userItem.content.find(
97 (c: any) => c.type === 'input_image',
98 )
99 expect(imageContent.image_url).toBe(PUBLIC_URL)
100 // xAI's image path has no file_id form.
101 expect(imageContent.file_id).toBeUndefined()
102 })
103​
104 it('maps a grok handle to input_file.file_url for documents', async () => {
105 const create = vi.fn().mockResolvedValueOnce(mockResponsesStream())
106 await collectChunks(
107 chat({
108 threadId: 'thread-1',
109 adapter: adapterWithMockClient(create),
110 messages: fileSourceMessage('grok', 'document'),
111 }),
112 )
113​
114 const [payload] = create.mock.calls[0]!
115 const userItem = payload.input.find(
116 (item: any) => item.type === 'message' && item.role === 'user',
117 )
118 const fileContent = userItem.content.find(
119 (c: any) => c.type === 'input_file',
120 )
121 expect(fileContent.file_url).toBe(PUBLIC_URL)
122 // A public URL works on every chat model; file_id would not.
123 expect(fileContent.file_id).toBeUndefined()
124 })
125​
126 it('rejects a handle another provider issued', async () => {
127 const create = vi.fn()
128 // The adapter declares support, so the lookup fails while the request is
129 // being built and surfaces as a RUN_ERROR chunk rather than a preflight
130 // throw. Either way no request reaches xAI.
131 const chunks = await collectChunks(
132 chat({
133 threadId: 'thread-1',
134 adapter: adapterWithMockClient(create),
135 messages: fileSourceMessage('openai', 'image'),
136 }),
137 )
138​
139 const runError = chunks.find((chunk) => chunk.type === 'RUN_ERROR')
140 expect(runError).toBeDefined()
141 expect((runError as { message?: string }).message).toMatch(
142 /grok.*issued by openai/s,
143 )
144 expect(create).not.toHaveBeenCalled()
145 })
146})