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

stateful-interactions.spec.ts

101 lines4.5 KB

1import { test, expect } from './fixtures'
2import {
3 sendMessage,
4 waitForResponse,
5 getLastAssistantMessage,
6 featureUrl,
7} from './helpers'
8import { providersFor } from './test-matrix'
9​
10// E2E coverage for Gemini's stateful Interactions API (geminiTextInteractions).
11//
12// Two-turn flow:
13// 1. Issue a first chat call. The aimock fixture returns a server-assigned
14// interactionId in interaction.created. The adapter surfaces it via the
15// `gemini.interactionId` CUSTOM event, which the route stores in state
16// and renders into a hidden `gemini-interaction-id` element so this
17// spec can read it.
18// 2. The route threads that id back through the request body as
19// `previousInteractionId`, which api/chat translates into
20// `modelOptions.previous_interaction_id`. The adapter then sends only the
21// new user turn (not prior history), and aimock matches the second
22// fixture by userMessage.
23//
24// Test boundary: aimock matches fixtures purely by `userMessage` text and
25// discards `previous_interaction_id` when normalising to the OpenAI canonical
26// shape, so we can't observe the chained id at the aimock layer. The
27// load-bearing assertion is on the page → /api/chat POST body: turn 2 must
28// forward the id captured from turn 1's CUSTOM event. That covers:
29// - client: useChat → fetchServerSentEvents marshals `body` into the wire
30// under `forwardedProps`.
31// - the React example wires the CUSTOM event into state and back into body.
32// The route's translation of `forwardedProps.previousInteractionId` into
33// `modelOptions.previous_interaction_id`, and the adapter's wire-format
34// translation of that into the Interactions API payload, are covered by unit
35// tests in `packages/ai-gemini/tests/text-interactions-adapter.test.ts`.
36for (const provider of providersFor('stateful-interactions')) {
37 test.describe(`${provider} — stateful-interactions`, () => {
38 test('two-turn conversation chained via previous_interaction_id', async ({
39 page,
40 testId,
41 aimockPort,
42 }) => {
43 const chatRequestBodies: Array<Record<string, unknown>> = []
44 page.on('request', (req) => {
45 if (req.method() !== 'POST') return
46 if (!req.url().endsWith('/api/chat')) return
47 const raw = req.postData()
48 if (!raw) return
49 try {
50 chatRequestBodies.push(JSON.parse(raw) as Record<string, unknown>)
51 } catch {
52 // Non-JSON bodies are unrelated to the chat round-trip.
53 }
54 })
55​
56 await page.goto(
57 featureUrl(provider, 'stateful-interactions', testId, aimockPort),
58 )
59​
60 await sendMessage(page, '[stateful-1] what guitars do you have')
61 await waitForResponse(page)
62 const firstResponse = await getLastAssistantMessage(page)
63 expect(firstResponse).toContain('Fender Stratocaster')
64​
65 const interactionIdEl = page.getByTestId('gemini-interaction-id')
66 await interactionIdEl.waitFor({ state: 'attached' })
67 const interactionId = (await interactionIdEl.textContent())?.trim()
68 expect(interactionId).toBeTruthy()
69 // Tighten beyond "truthy" so an accidental "undefined"/"null" string
70 // can't sneak past — the id is a non-trivial server-assigned token.
71 expect(interactionId!.length).toBeGreaterThan(3)
72​
73 await sendMessage(page, '[stateful-2] tell me about the cheapest one')
74 await waitForResponse(page)
75 const secondResponse = await getLastAssistantMessage(page)
76 expect(secondResponse).toContain('$1,299')
77​
78 // Turn 1 must not carry a previousInteractionId (it's a fresh
79 // interaction); turn 2 must carry the id surfaced by the
80 // gemini.interactionId CUSTOM event from turn 1. useChat marshals
81 // the `body:` keys onto the wire under `forwardedProps`.
82 expect(chatRequestBodies).toHaveLength(2)
83 const fp0 = chatRequestBodies[0]?.forwardedProps as
84 | Record<string, unknown>
85 | undefined
86 const fp1 = chatRequestBodies[1]?.forwardedProps as
87 | Record<string, unknown>
88 | undefined
89 expect(fp0).toBeDefined()
90 expect(fp1).toBeDefined()
91 expect(fp0!.previousInteractionId).toBeUndefined()
92 expect(fp1!.previousInteractionId).toBe(interactionId)
93 // Sanity: the other forwardedProps keys must match across turns so a
94 // regression that *replaced* turn 2's body with a different shape
95 // (rather than adding the id) doesn't accidentally satisfy the
96 // assertion above.
97 expect(fp1!.provider).toBe(fp0!.provider)
98 expect(fp1!.feature).toBe(fp0!.feature)
99 })
100 })