File size: 14,357 Bytes
ed57015
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';
import type { Express } from 'express';
import { createApp } from '../../app.js';
import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';
import { mintDashboardToken, isGatedApiPath } from '../helpers/auth.js';

let dashToken = '';

async function request(app: Express, method: string, path: string, body?: any, headers: Record<string, string> = {}) {
  const server = app.listen(0);
  const addr = server.address() as any;
  const url = `http://127.0.0.1:${addr.port}${path}`;

  const res = await fetch(url, {
    method,
    headers: { ...(body ? { 'Content-Type': 'application/json' } : {}), ...(isGatedApiPath(path) && !('Authorization' in headers) ? { Authorization: `Bearer ${dashToken}` } : {}), ...headers },
    body: body ? JSON.stringify(body) : undefined,
  });

  const data = await res.text();
  server.close();

  let json: any = null;
  try { json = JSON.parse(data); } catch {}

  return { status: res.status, body: json };
}

function authHeaders() {
  return { Authorization: `Bearer ${getUnifiedApiKey()}` };
}

describe('OpenAI multimodal array content', () => {
  let app: Express;

  beforeAll(() => {
    process.env.ENCRYPTION_KEY = '0'.repeat(64);
    initDb(':memory:');
    app = createApp();
    dashToken = mintDashboardToken();
  });

  beforeEach(async () => {
    const db = getDb();
    db.prepare('DELETE FROM api_keys').run();
    db.prepare('DELETE FROM requests').run();

    const addKey = await request(app, 'POST', '/api/keys', {
      platform: 'groq',
      key: 'gsk_array_content_test',
      label: 'array-content',
    });
    expect(addKey.status).toBe(201);
  });

  afterEach(() => {
    vi.restoreAllMocks();
  });

  it('accepts content as a string (the legacy shape)', async () => {
    // Provider call will fail (no real key), but schema validation must pass —
    // we assert it isn't rejected with a 400 zod error.
    const { status, body } = await request(app, 'POST', '/v1/chat/completions', {
      messages: [{ role: 'user', content: 'hello' }],
    }, authHeaders());
    expect(status).not.toBe(400);
    if (status === 400) {
      // Diagnostic if regression: show the validation error.
      throw new Error(`unexpected 400: ${JSON.stringify(body)}`);
    }
  });

  it('accepts content as a text-only multimodal array', async () => {
    const { status, body } = await request(app, 'POST', '/v1/chat/completions', {
      messages: [{
        role: 'user',
        content: [{ type: 'text', text: 'hello from opencode-style client' }],
      }],
    }, authHeaders());
    expect(status).not.toBe(400);
    if (status === 400) {
      throw new Error(`unexpected 400: ${JSON.stringify(body)}`);
    }
  });

  it('accepts mixed text + image_url blocks (image blocks are silently dropped)', async () => {
    const { status } = await request(app, 'POST', '/v1/chat/completions', {
      messages: [{
        role: 'user',
        content: [
          { type: 'text', text: 'describe' },
          { type: 'image_url', image_url: { url: 'https://example.com/x.png' } },
        ],
      }],
    }, authHeaders());
    expect(status).not.toBe(400);
  });

  it('successfully routes an array-content request and gets a 200 (mocked groq)', async () => {
    const origFetch = global.fetch;
    vi.spyOn(global, 'fetch').mockImplementation(async (url, init) => {
      const urlStr = typeof url === 'string' ? url : url.toString();
      if (urlStr.includes('api.groq.com/openai/v1/chat/completions')) {
        // Sanity check that the array shape made it through to the upstream call.
        const body = JSON.parse(String((init as RequestInit).body));
        expect(Array.isArray(body.messages[0].content)).toBe(true);
        return {
          ok: true,
          json: () => Promise.resolve({
            id: 'chatcmpl-array', object: 'chat.completion', created: 1, model: 'openai/gpt-oss-120b',
            choices: [{
              index: 0,
              message: { role: 'assistant', content: 'got it' },
              finish_reason: 'stop',
            }],
            usage: { prompt_tokens: 4, completion_tokens: 2, total_tokens: 6 },
          }),
        } as any;
      }
      return origFetch(url, init);
    });

    const { status, body } = await request(app, 'POST', '/v1/chat/completions', {
      model: 'auto',
      messages: [{
        role: 'user',
        content: [{ type: 'text', text: 'hi' }],
      }],
    }, authHeaders());

    expect(status).toBe(200);
    expect(body.choices[0].message.content).toBe('got it');
  });

  it('rejects an empty array as missing content', async () => {
    const { status } = await request(app, 'POST', '/v1/chat/completions', {
      messages: [], // top-level empty messages
    }, authHeaders());
    expect(status).toBe(400);
  });

  it('accepts an assistant message with empty content and no tool_calls (#165)', async () => {
    // OpenAI accepts empty/null assistant turns in history; we coerce to "" and
    // forward rather than 400-ing a payload OpenAI would take. The request then
    // routes (and fails downstream on the fake key) — the point is it is NOT a
    // 400 schema rejection.
    const { status, body } = await request(app, 'POST', '/v1/chat/completions', {
      messages: [
        { role: 'user', content: 'hi' },
        { role: 'assistant', content: [] },
        { role: 'user', content: 'continue' },
      ],
    }, authHeaders());
    expect(status).not.toBe(400);
    if (status === 400) throw new Error(`unexpected 400: ${JSON.stringify(body)}`);
  });

  // #200: code agents (AionUI, OpenCode, Qwen Code) fail on the SECOND request
  // of a session because their follow-up history carries shapes the strict
  // schema rejected. Each case below is a real second-turn payload pattern.
  describe('agent second-turn shapes (#200)', () => {
    it('accepts Gemini-part-style content blocks without a type field', async () => {
      const { status, body } = await request(app, 'POST', '/v1/chat/completions', {
        messages: [
          { role: 'user', content: [{ text: 'hi' }] },
          { role: 'assistant', content: [{ text: 'hello!' }] },
          { role: 'user', content: [{ text: 'ok' }] },
        ],
      }, authHeaders());
      expect(status).not.toBe(400);
      if (status === 400) throw new Error(`unexpected 400: ${JSON.stringify(body)}`);
    });

    it('accepts echoed tool_calls without type and with object arguments', async () => {
      const { status, body } = await request(app, 'POST', '/v1/chat/completions', {
        messages: [
          { role: 'user', content: 'list files' },
          {
            role: 'assistant',
            content: null,
            // type dropped + arguments already parsed to an object — the way
            // Gemini-lineage agents replay our tool_calls back at us.
            tool_calls: [{ id: 'call_1', function: { name: 'ls', arguments: { path: '.' } } }],
          },
          { role: 'tool', tool_call_id: 'call_1', content: 'file1.ts' },
          { role: 'user', content: 'thanks' },
        ],
      }, authHeaders());
      expect(status).not.toBe(400);
      if (status === 400) throw new Error(`unexpected 400: ${JSON.stringify(body)}`);
    });

    it('accepts the developer role (newer OpenAI SDK system prompt)', async () => {
      const { status, body } = await request(app, 'POST', '/v1/chat/completions', {
        messages: [
          { role: 'developer', content: 'You are a coding agent.' },
          { role: 'user', content: 'hi' },
        ],
      }, authHeaders());
      expect(status).not.toBe(400);
      if (status === 400) throw new Error(`unexpected 400: ${JSON.stringify(body)}`);
    });

    it('reports the failing path in 400 validation errors', async () => {
      const { status, body } = await request(app, 'POST', '/v1/chat/completions', {
        messages: [{ role: 'user', content: 42 }],
      }, authHeaders());
      expect(status).toBe(400);
      // Path-qualified detail ("messages.0...") instead of a bare "Invalid input"
      expect(body.error.message).toMatch(/messages\.0/);
    });

    it('accepts tool_calls with missing or empty ids and pairs tool results by order', async () => {
      const { status, body } = await request(app, 'POST', '/v1/chat/completions', {
        messages: [
          { role: 'user', content: 'list files' },
          {
            role: 'assistant',
            content: null,
            // Gemini-lineage: no id at all on the first, empty id on the second.
            tool_calls: [
              { function: { name: 'ls', arguments: '{}' } },
              { id: '', function: { name: 'pwd', arguments: '{}' } },
            ],
          },
          { role: 'tool', content: 'file1.ts' },
          { role: 'tool', tool_call_id: '', content: '/home' },
          { role: 'user', content: 'thanks' },
        ],
      }, authHeaders());
      expect(status).not.toBe(400);
      if (status === 400) throw new Error(`unexpected 400: ${JSON.stringify(body)}`);
    });

    it('accepts a tool message with null content (tool returned nothing)', async () => {
      const { status, body } = await request(app, 'POST', '/v1/chat/completions', {
        messages: [
          { role: 'user', content: 'do it' },
          { role: 'assistant', content: null, tool_calls: [{ id: 'c1', function: { name: 'noop', arguments: '{}' } }] },
          { role: 'tool', tool_call_id: 'c1', content: null },
          { role: 'user', content: 'ok' },
        ],
      }, authHeaders());
      expect(status).not.toBe(400);
      if (status === 400) throw new Error(`unexpected 400: ${JSON.stringify(body)}`);
    });

    it('accepts the legacy function role in history', async () => {
      const { status, body } = await request(app, 'POST', '/v1/chat/completions', {
        messages: [
          { role: 'user', content: 'weather?' },
          { role: 'function', name: 'get_weather', content: '{"temp": 20}' },
          { role: 'user', content: 'thanks' },
        ],
      }, authHeaders());
      expect(status).not.toBe(400);
      if (status === 400) throw new Error(`unexpected 400: ${JSON.stringify(body)}`);
    });

    it('accepts max_tokens <= 0 (treated as no limit)', async () => {
      for (const value of [-1, 0]) {
        const { status, body } = await request(app, 'POST', '/v1/chat/completions', {
          max_tokens: value,
          messages: [{ role: 'user', content: 'hi' }],
        }, authHeaders());
        expect(status).not.toBe(400);
        if (status === 400) throw new Error(`unexpected 400 for max_tokens ${value}: ${JSON.stringify(body)}`);
      }
    });

    it('accepts tool_choice "any" and tools without a type field', async () => {
      const { status, body } = await request(app, 'POST', '/v1/chat/completions', {
        tool_choice: 'any',
        tools: [{ function: { name: 'ls', parameters: { type: 'object', properties: {} } } }],
        messages: [{ role: 'user', content: 'hi' }],
      }, authHeaders());
      expect(status).not.toBe(400);
      if (status === 400) throw new Error(`unexpected 400: ${JSON.stringify(body)}`);
    });

    it('accepts an assistant echo with tool_calls: null (aionrs/AionUI session replay)', async () => {
      // The exact second-turn shape captured from aionrs v0.1.28 (AionUI's
      // engine): resumed sessions replay the assistant turn with an explicit
      // tool_calls: null plus a reasoning_content side field.
      const { status, body } = await request(app, 'POST', '/v1/chat/completions', {
        max_tokens: 8192,
        messages: [
          { role: 'system', content: 'You are an AI assistant.' },
          { role: 'user', content: 'ciao' },
          {
            role: 'assistant',
            content: 'Ciao! Come posso aiutarti oggi?',
            reasoning_content: 'The user is greeting me in Italian.',
            tool_calls: null,
          },
          { role: 'user', content: 'Che modello sei' },
        ],
      }, authHeaders());
      expect(status).not.toBe(400);
      if (status === 400) throw new Error(`unexpected 400: ${JSON.stringify(body)}`);
    });

    it('accepts null top-level tool knobs (tools, tool_choice, parallel_tool_calls)', async () => {
      const { status, body } = await request(app, 'POST', '/v1/chat/completions', {
        tools: null,
        tool_choice: null,
        parallel_tool_calls: null,
        messages: [{ role: 'user', content: 'hi' }],
      }, authHeaders());
      expect(status).not.toBe(400);
      if (status === 400) throw new Error(`unexpected 400: ${JSON.stringify(body)}`);
    });

    it('drops null/empty tool_calls instead of forwarding them upstream', async () => {
      const origFetch = global.fetch;
      vi.spyOn(global, 'fetch').mockImplementation(async (url, init) => {
        const urlStr = typeof url === 'string' ? url : url.toString();
        if (urlStr.includes('api.groq.com/openai/v1/chat/completions')) {
          const body = JSON.parse(String((init as RequestInit).body));
          // Strict upstreams reject tool_calls: null AND tool_calls: [] —
          // neither may survive normalization.
          expect(body.messages[1]).not.toHaveProperty('tool_calls');
          expect(body.messages[2]).not.toHaveProperty('tool_calls');
          return {
            ok: true,
            json: () => Promise.resolve({
              id: 'chatcmpl-nulltc', object: 'chat.completion', created: 1, model: 'openai/gpt-oss-120b',
              choices: [{ index: 0, message: { role: 'assistant', content: 'ok' }, finish_reason: 'stop' }],
              usage: { prompt_tokens: 4, completion_tokens: 2, total_tokens: 6 },
            }),
          } as any;
        }
        return origFetch(url, init);
      });

      const { status, body } = await request(app, 'POST', '/v1/chat/completions', {
        model: 'auto',
        messages: [
          { role: 'user', content: 'ciao' },
          { role: 'assistant', content: 'Ciao!', tool_calls: null },
          { role: 'assistant', content: 'ancora', tool_calls: [] },
          { role: 'user', content: 'Che modello sei' },
        ],
      }, authHeaders());
      expect(status).toBe(200);
      expect(body.choices[0].message.content).toBe('ok');
    });
  });
});