File size: 12,863 Bytes
8452e13
 
c22a968
 
 
 
 
 
 
 
 
 
8452e13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8907369
 
 
 
 
 
 
 
 
 
 
 
 
 
8452e13
 
 
 
 
 
 
 
 
8907369
 
 
 
8452e13
 
 
 
 
 
 
 
 
 
 
 
 
0ce6ec3
 
 
 
 
 
 
967cab3
0ce6ec3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
967cab3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ce6ec3
 
 
 
 
 
 
 
 
 
 
 
 
 
8452e13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ce6ec3
 
 
c22a968
0ce6ec3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c22a968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ce6ec3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f16ab09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ce6ec3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'

import {
  ensureAuthSession,
  getDomainPreferenceForm,
  getTaskStatus,
  guestLogin,
  recommend,
  register,
  updatePreferences,
  watchTaskStatus,
} from '../utils/api'


describe('frontend unit: api utils', () => {
  beforeEach(() => {
    vi.stubGlobal('fetch', vi.fn())
  })

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

  it('recommend should send expected payload and return parsed response', async () => {
    const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>
    mockFetch.mockResolvedValue({
      ok: true,
      json: async () => ({
        restaurants: [],
        items: [
          {
            id: 'movie-1',
            domain: 'movie',
            title: 'Quiet Signal',
            rating: 8.2,
            source: 'TMDB',
          },
        ],
        llm_reply: 'hello',
        intent: 'chat',
      }),
    })

    const response = await recommend(
      'need spicy food',
      'u-1',
      [{ role: 'user', content: 'history' }],
      'conv-1',
      true
    )

    expect(response.intent).toBe('chat')
    expect(response.items?.[0]?.title).toBe('Quiet Signal')
    expect(mockFetch).toHaveBeenCalledTimes(1)

    const [url, init] = mockFetch.mock.calls[0]
    expect(String(url)).toContain('/api/process')
    const body = JSON.parse((init as RequestInit).body as string)
    expect(body).toEqual({
      query: 'need spicy food',
      user_id: 'u-1',
      conversation_history: [{ role: 'user', content: 'history' }],
      conversation_id: 'conv-1',
      use_online_agent: true,
    })
  })

  it('recommend should throw friendly network error when fetch fails', async () => {
    const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>
    mockFetch.mockRejectedValue(new TypeError('Failed to fetch'))

    await expect(recommend('hi')).rejects.toThrow('Network error: Cannot connect to backend')
  })

  it('recommend should include optional time travel payload', async () => {
    const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>
    mockFetch.mockResolvedValue({
      ok: true,
      json: async () => ({
        restaurants: [],
        llm_reply: 'regenerated',
        intent: 'chat',
        domain: 'restaurant',
      }),
    })

    await recommend(
      'edited request',
      'u-1',
      [{ role: 'user', content: 'edited request' }],
      'conv-1',
      false,
      {
        sourceMessageId: 'm-new',
        replayFromMessageId: 'm-old',
        branchId: 'b-new',
        timeTravelMode: 'linear_regenerate',
      }
    )

    const [, init] = mockFetch.mock.calls[0]
    const body = JSON.parse((init as RequestInit).body as string)
    expect(body).toMatchObject({
      source_message_id: 'm-new',
      replay_from_message_id: 'm-old',
      branch_id: 'b-new',
      time_travel_mode: 'linear_regenerate',
    })
  })

  it('recommend should include a non-time-travel branch scope when provided', async () => {
    const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>
    mockFetch.mockResolvedValue({
      ok: true,
      json: async () => ({
        restaurants: [],
        llm_reply: 'scoped',
        intent: 'chat',
      }),
    })

    await recommend(
      'same branch request',
      'u-1',
      [{ role: 'user', content: 'same branch request' }],
      'conv-1',
      false,
      { scopeBranchId: 'branch-main' },
    )

    const [, init] = mockFetch.mock.calls[0]
    const body = JSON.parse((init as RequestInit).body as string)
    expect(body).toMatchObject({
      branch_id: 'branch-main',
    })
    expect(body).not.toHaveProperty('time_travel_mode')
  })

  it('recommend should throw contract error when response shape is invalid', async () => {
    const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>
    mockFetch.mockResolvedValue({
      ok: true,
      json: async () => ({
        restaurants: 'not-an-array',
      }),
    })

    await expect(recommend('invalid shape')).rejects.toThrow(
      'API contract validation failed for /api/process'
    )
  })

  it('getTaskStatus should include user and conversation query parameters', async () => {
    const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>
    mockFetch.mockResolvedValue({
      ok: true,
      json: async () => ({
        task_id: 't-1',
        status: 'processing',
        progress: 30,
        message: 'running',
      }),
    })

    const status = await getTaskStatus('t-1', 'u-2', 'c-2')
    expect(status.status).toBe('processing')

    const [url] = mockFetch.mock.calls[0]
    const calledUrl = String(url)
    expect(calledUrl).toContain('/api/status/t-1')
    expect(calledUrl).toContain('user_id=u-2')
    expect(calledUrl).toContain('conversation_id=c-2')
  })

  it('updatePreferences should normalize profile preference payload for the API', async () => {
    const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>
    mockFetch.mockResolvedValue({
      ok: true,
      json: async () => ({
        message: 'Preferences updated successfully',
        preferences: {
          restaurant_types: ['casual'],
          flavor_profiles: ['spicy'],
          dining_purpose: 'friends',
          budget_range: { min: 25, max: 70, currency: 'SGD', per: 'person' },
          location: 'Chinatown',
        },
      }),
    })

    await updatePreferences({
      restaurant_types: ['casual'],
      flavor_profiles: ['spicy'],
      dining_purpose: 'friends',
      budget_range: { min: 25, max: 70, currency: 'SGD', per: 'person' },
      location: 'Chinatown',
    }, 'u-3')

    const [url, init] = mockFetch.mock.calls[0]
    expect(String(url)).toContain('/api/update-preferences')
    expect(JSON.parse((init as RequestInit).body as string)).toEqual({
      user_id: 'u-3',
      restaurantTypes: ['casual'],
      flavorProfiles: ['spicy'],
      diningPurpose: 'friends',
      budgetRange: { min: 25, max: 70, currency: 'SGD', per: 'person' },
      location: 'Chinatown',
    })
  })

  it('getDomainPreferenceForm should encode the domain path segment', async () => {
    const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>
    mockFetch.mockResolvedValue({
      ok: true,
      json: async () => ({
        domain: 'movie/tv picks',
        fields: [],
        missing_required: [],
        complete: true,
      }),
    })

    await getDomainPreferenceForm('movie/tv picks')

    const [url, init] = mockFetch.mock.calls[0]
    expect(String(url)).toContain('/api/domains/movie%2Ftv%20picks/preference-form')
    expect((init as RequestInit).credentials).toBe('include')
  })

  it('guestLogin should send device id with credentials included', async () => {
    const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>
    mockFetch.mockResolvedValue({
      ok: true,
      json: async () => ({
        user: {
          id: 'u-session',
          kind: 'guest',
          role: 'user',
          status: 'active',
        },
        session: {
          id: 's-session',
          user_id: 'u-session',
          anonymous_device_id: 'd-session',
          status: 'active',
          expires_at: '2026-06-30T00:00:00Z',
        },
      }),
    })

    const auth = await guestLogin('browser-device')
    expect(auth.user.id).toBe('u-session')

    const [url, init] = mockFetch.mock.calls[0]
    expect(String(url)).toContain('/api/auth/guest')
    expect((init as RequestInit).credentials).toBe('include')
    expect(JSON.parse((init as RequestInit).body as string)).toEqual({ device_id: 'browser-device' })
  })

  it('ensureAuthSession should fall back to guest login when no cookie session exists', async () => {
    const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>
    mockFetch
      .mockResolvedValueOnce({
        ok: false,
        status: 401,
        statusText: 'Unauthorized',
        text: async () => 'missing session',
      })
      .mockResolvedValueOnce({
        ok: true,
        json: async () => ({
          user: {
            id: 'u-new-guest',
            kind: 'guest',
            role: 'user',
            status: 'active',
          },
          session: {
            id: 's-new-guest',
            user_id: 'u-new-guest',
            status: 'active',
            expires_at: '2026-06-30T00:00:00Z',
          },
        }),
      })

    const auth = await ensureAuthSession('browser-device')

    expect(auth.user.id).toBe('u-new-guest')
    expect(mockFetch).toHaveBeenCalledTimes(2)
    expect(String(mockFetch.mock.calls[0][0])).toContain('/api/auth/session')
    expect((mockFetch.mock.calls[0][1] as RequestInit).credentials).toBe('include')
    expect(String(mockFetch.mock.calls[1][0])).toContain('/api/auth/guest')
  })

  it('watchTaskStatus streams status frames over SSE and settles on completion', () => {
    const instances: FakeEventSource[] = []
    class FakeEventSource {
      static readonly CONNECTING = 0
      static readonly OPEN = 1
      static readonly CLOSED = 2
      url: string
      withCredentials: boolean
      readyState = FakeEventSource.OPEN
      onmessage: ((event: { data: string }) => void) | null = null
      onerror: (() => void) | null = null
      constructor(url: string, init?: { withCredentials?: boolean }) {
        this.url = url
        this.withCredentials = Boolean(init?.withCredentials)
        instances.push(this)
      }
      emit(payload: unknown) {
        this.onmessage?.({ data: JSON.stringify(payload) })
      }
      close() {
        this.readyState = FakeEventSource.CLOSED
      }
    }
    vi.stubGlobal('EventSource', FakeEventSource)

    const onStatus = vi.fn()
    const onSettled = vi.fn()
    const stop = watchTaskStatus('t-7', 'u-1', 'c-1', { onStatus, onSettled })

    const es = instances[0]
    expect(es.url).toContain('/api/status/t-7/stream')
    expect(es.url).toContain('user_id=u-1')
    expect(es.url).toContain('conversation_id=c-1')
    expect(es.withCredentials).toBe(true)

    es.emit({ task_id: 't-7', status: 'processing', progress: 40, message: 'searching' })
    expect(onStatus).toHaveBeenCalledWith(expect.objectContaining({ status: 'processing', progress: 40 }))
    expect(onSettled).not.toHaveBeenCalled()

    es.emit({
      task_id: 't-7',
      status: 'completed',
      progress: 100,
      message: 'ready',
      result: { restaurants: [], thinking_steps: [] },
    })
    expect(onStatus).toHaveBeenCalledWith(expect.objectContaining({ status: 'completed' }))
    expect(onSettled).toHaveBeenCalledTimes(1)
    // The stream is torn down once the task settles.
    expect(es.readyState).toBe(FakeEventSource.CLOSED)

    stop()
  })

  it('watchTaskStatus falls back to polling when EventSource is unavailable', async () => {
    // jsdom provides no EventSource, so the watcher must keep working via getTaskStatus.
    expect(typeof EventSource).toBe('undefined')
    const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>
    mockFetch.mockResolvedValue({
      ok: true,
      json: async () => ({
        task_id: 't-8',
        status: 'completed',
        progress: 100,
        message: 'ready',
        result: { restaurants: [], thinking_steps: [] },
      }),
    })

    const onStatus = vi.fn()
    const onSettled = vi.fn()
    const stop = watchTaskStatus('t-8', 'u-1', 'c-1', { onStatus, onSettled })

    // Allow the immediate poll's promise chain to resolve.
    await new Promise(resolve => setTimeout(resolve, 0))
    await new Promise(resolve => setTimeout(resolve, 0))

    expect(onStatus).toHaveBeenCalledWith(expect.objectContaining({ status: 'completed' }))
    expect(onSettled).toHaveBeenCalledTimes(1)
    const [url] = mockFetch.mock.calls[0]
    expect(String(url)).toContain('/api/status/t-8')
    stop()
  })

  it('register should expose only the backend detail message on auth errors', async () => {
    const mockFetch = globalThis.fetch as unknown as ReturnType<typeof vi.fn>
    mockFetch.mockResolvedValue({
      ok: false,
      status: 400,
      statusText: 'Bad Request',
      text: async () => JSON.stringify({ detail: 'password must be at least 8 characters' }),
    })

    let error: Error | null = null
    try {
      await register('test@example.com', 'short')
    } catch (caught) {
      error = caught as Error
    }

    expect(error?.message).toBe('password must be at least 8 characters')
  })
})