Open History to see the last commit
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 }
37}
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
49}
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
59}
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 ]
79}
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 adapter: adapterWithMockClient(create),
87 messages: fileSourceMessage('grok', 'image'),
88 }),
89 )
90
91 const [payload] = create.mock.calls[0]!
92 const userItem = payload.input.find(
93 (item: any) => item.type === 'message' && item.role === 'user',
94 )
95 const imageContent = userItem.content.find(
96 (c: any) => c.type === 'input_image',
97 )
98 expect(imageContent.image_url).toBe(PUBLIC_URL)
99 // xAI's image path has no file_id form.
100 expect(imageContent.file_id).toBeUndefined()
101 })
102
103 it('maps a grok handle to input_file.file_url for documents', async () => {
104 const create = vi.fn().mockResolvedValueOnce(mockResponsesStream())
105 await collectChunks(
106 chat({
107 adapter: adapterWithMockClient(create),
108 messages: fileSourceMessage('grok', 'document'),
109 }),
110 )
111
112 const [payload] = create.mock.calls[0]!
113 const userItem = payload.input.find(
114 (item: any) => item.type === 'message' && item.role === 'user',
115 )
116 const fileContent = userItem.content.find(
117 (c: any) => c.type === 'input_file',
118 )
119 expect(fileContent.file_url).toBe(PUBLIC_URL)
120 // A public URL works on every chat model; file_id would not.
121 expect(fileContent.file_id).toBeUndefined()
122 })
123
124 it('rejects a handle another provider issued', async () => {
125 const create = vi.fn()
126 // The adapter declares support, so the lookup fails while the request is
127 // being built and surfaces as a RUN_ERROR chunk rather than a preflight
128 // throw. Either way no request reaches xAI.
129 const chunks = await collectChunks(
130 chat({
131 adapter: adapterWithMockClient(create),
132 messages: fileSourceMessage('openai', 'image'),
133 }),
134 )
135
136 const runError = chunks.find((chunk) => chunk.type === 'RUN_ERROR')
137 expect(runError).toBeDefined()
138 expect((runError as { message?: string }).message).toMatch(
139 /grok.*issued by openai/s,
140 )
141 expect(create).not.toHaveBeenCalled()
142 })
143})