File size: 8,719 Bytes
f0634fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Scenario: the managed `/tools` chat_title request contract, including
 * response validation, API failures, timeouts, and transport errors.
 * Wiring: the real request builder with only the external fetch boundary
 * stubbed. Run with:
 * `pnpm exec vitest run packages/oauth/test/managed-tools.test.ts`.
 */

import { afterEach, describe, expect, it, vi } from 'vitest';

import { fetchChatTitle, kimiCodeToolsUrl } from '../src/managed-tools';

afterEach(() => {
  vi.unstubAllGlobals();
  vi.unstubAllEnvs();
});

describe('kimiCodeToolsUrl', () => {
  it('appends /tools to the default base URL', () => {
    expect(kimiCodeToolsUrl()).toBe('https://api.kimi.com/coding/v1/tools');
  });

  it('honours KIMI_CODE_BASE_URL and trims trailing slashes', () => {
    vi.stubEnv('KIMI_CODE_BASE_URL', 'https://example.test/v9///');
    expect(kimiCodeToolsUrl()).toBe('https://example.test/v9/tools');
  });
});

describe('fetchChatTitle', () => {
  it('POSTs the chat_title method with bearer auth and returns the title on 200', async () => {
    const fetchMock = vi.fn(
      async () =>
        new Response(JSON.stringify({ title: 'Go nil pointer 错误排查' }), {
          status: 200,
          headers: { 'Content-Type': 'application/json' },
        }),
    );
    vi.stubGlobal('fetch', fetchMock);

    const result = await fetchChatTitle(
      'https://api.example/tools',
      'access-token',
      'user: nil pointer 报错',
    );

    expect(result).toEqual({ kind: 'ok', title: 'Go nil pointer 错误排查' });

    const calls = fetchMock.mock.calls as unknown as [string, RequestInit?][];
    const [calledUrl, init] = calls[0]!;
    expect(calledUrl).toBe('https://api.example/tools');
    expect(init?.method).toBe('POST');

    const headers = new Headers((init?.headers ?? {}) as Record<string, string>);
    expect(headers.get('authorization')).toBe('Bearer access-token');
    expect(headers.get('content-type')).toBe('application/json');

    expect(JSON.parse(init?.body as string)).toEqual({
      method: 'chat_title',
      params: { chat_content: 'user: nil pointer 报错' },
    });
  });

  it('keeps protocol headers authoritative when custom header casing differs', async () => {
    const fetchMock = vi.fn(
      async () =>
        new Response(JSON.stringify({ title: '标题' }), {
          status: 200,
          headers: { 'Content-Type': 'application/json' },
        }),
    );
    vi.stubGlobal('fetch', fetchMock);

    await fetchChatTitle('https://api.example/tools', 'access-token', 'user: hi', {
      headers: {
        authorization: 'Bearer wrong-token',
        aCcEpT: 'text/plain',
        'content-TYPE': 'text/plain',
        'X-Proxy-Header': 'present',
      },
    });

    const [, init] = (fetchMock.mock.calls as unknown as [string, RequestInit?][])[0]!;
    const headers = new Headers(init?.headers as Record<string, string>);
    expect(headers.get('authorization')).toBe('Bearer access-token');
    expect(headers.get('accept')).toBe('application/json');
    expect(headers.get('content-type')).toBe('application/json');
    expect(headers.get('x-proxy-header')).toBe('present');
  });

  it('trims surrounding whitespace from the title', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn(
        async () =>
          new Response(JSON.stringify({ title: '  标题  \n' }), {
            status: 200,
            headers: { 'Content-Type': 'application/json' },
          }),
      ),
    );

    const result = await fetchChatTitle('https://api.example/tools', 'tok', 'user: hi');

    expect(result).toEqual({ kind: 'ok', title: '标题' });
  });

  it('returns an error when the server omits the title', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn(
        async () =>
          new Response(JSON.stringify({ ok: true }), {
            status: 200,
            headers: { 'Content-Type': 'application/json' },
          }),
      ),
    );

    const result = await fetchChatTitle('https://api.example/tools', 'tok', 'user: hi');

    expect(result).toEqual({
      kind: 'error',
      message: 'Failed to generate session title: missing title.',
    });
  });

  it('returns an error with status when the server responds 401', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn(async () => new Response('', { status: 401 })),
    );

    const result = await fetchChatTitle('https://api.example/tools', 'tok', 'user: hi');

    expect(result.kind).toBe('error');
    if (result.kind !== 'error') return;
    expect(result.status).toBe(401);
    expect(result.message).toMatch(/401/);
  });

  it('surfaces API error messages from failed generations', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn(
        async () =>
          new Response(JSON.stringify({ error: { message: 'title rejected' } }), {
            status: 400,
            headers: { 'Content-Type': 'application/json' },
          }),
      ),
    );

    const result = await fetchChatTitle('https://api.example/tools', 'tok', 'user: hi');

    expect(result).toEqual({ kind: 'error', status: 400, message: 'title rejected' });
  });

  it('returns a timeout error when the request aborts', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn(
        (_url: string, init?: RequestInit) =>
          new Promise<Response>((_, reject) => {
            init?.signal?.addEventListener('abort', () => {
              const err = new Error('aborted');
              err.name = 'AbortError';
              reject(err);
            });
          }),
      ),
    );

    const result = await fetchChatTitle('https://api.example/tools', 'tok', 'user: hi', {
      timeoutMs: 5,
    });

    expect(result.kind).toBe('error');
    if (result.kind !== 'error') return;
    expect(result.status).toBeUndefined();
    expect(result.message).toMatch(/timed out/);
  });

  it('returns a generic error message on network failure', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn(async () => {
        throw new TypeError('network down');
      }),
    );

    const result = await fetchChatTitle('https://api.example/tools', 'tok', 'user: hi');

    expect(result.kind).toBe('error');
    if (result.kind !== 'error') return;
    expect(result.message).toMatch(/network down/);
  });

  it('reports an external abort as an abort, not a timeout', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn(
        (_url: string, init?: RequestInit) =>
          new Promise<Response>((_, reject) => {
            const rejectAbort = () => {
              const err = new Error('aborted');
              err.name = 'AbortError';
              reject(err);
            };
            if (init?.signal?.aborted === true) {
              rejectAbort();
              return;
            }
            init?.signal?.addEventListener('abort', rejectAbort);
          }),
      ),
    );
    const external = new AbortController();

    const resultPromise = fetchChatTitle('https://api.example/tools', 'tok', 'user: hi', {
      signal: external.signal,
      timeoutMs: 60_000,
    });
    external.abort();
    const result = await resultPromise;

    expect(result.kind).toBe('error');
    if (result.kind !== 'error') return;
    expect(result.message).toMatch(/aborted/);
    expect(result.message).not.toMatch(/timed out/);
  });

  it('fails fast on an already-aborted external signal', async () => {
    const fetchMock = vi.fn(async () => {
      throw new Error('fetch should not start when the signal is pre-aborted');
    });
    vi.stubGlobal('fetch', fetchMock);
    const external = new AbortController();
    external.abort();

    const result = await fetchChatTitle('https://api.example/tools', 'tok', 'user: hi', {
      signal: external.signal,
    });

    expect(result.kind).toBe('error');
    if (result.kind !== 'error') return;
    expect(result.message).toMatch(/aborted/);
  });

  it('removes the external abort listener once the request settles', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn(
        async () =>
          new Response(JSON.stringify({ title: '标题' }), {
            status: 200,
            headers: { 'Content-Type': 'application/json' },
          }),
      ),
    );
    const external = new AbortController();
    const addSpy = vi.spyOn(external.signal, 'addEventListener');
    const removeSpy = vi.spyOn(external.signal, 'removeEventListener');

    await fetchChatTitle('https://api.example/tools', 'tok', 'user: hi', {
      signal: external.signal,
    });

    expect(addSpy).toHaveBeenCalledTimes(1);
    expect(removeSpy).toHaveBeenCalledTimes(1);
    expect(removeSpy.mock.calls[0]?.[1]).toBe(addSpy.mock.calls[0]?.[1]);
  });
});