Open History to see the last commit
1import { expect, test } from './fixtures'
2import {
3 approveToolCall,
4 sendMessage,
5 waitForAssistantText,
6 waitForResponse,
7} from './helpers'
8import type { Page } from '@playwright/test'
9
10/**
11 * JSON transport (`toJsonResponse` + `fetchJson`).
12 *
13 * The server answers each request with one `{ chunks, offset?, done }` JSON
14 * body instead of a stream. `/api/json-transport` runs `chat()` against aimock
15 * (fixtures in `fixtures/json-transport/`) and drains the run into a
16 * `memoryStream` log. `?maxWaitMs=` makes it reply early with `done: false`,
17 * and the client polls `GET ?runId=&offset=` for the rest. The page runs
18 * `persistence: true`, so a reload hydrates `activeRun` and the client joins
19 * the run with `joinRun` (`GET ?runId=&offset=-1`).
20 */
21
22const LONG_PROMPT = '[json-transport-long] tell me about the lighthouse'
23const LONG_START = 'The lighthouse keeper climbed the stairs'
24const LONG_END = 'JSON_LONG_END'
25
26function pageUrl(
27 testId: string,
28 aimockPort: number,
29 maxWaitMs?: number,
30 structured = false,
31) {
32 const query = new URLSearchParams({
33 testId,
34 aimockPort: String(aimockPort),
35 })
36 if (maxWaitMs !== undefined) query.set('maxWaitMs', String(maxWaitMs))
37 if (structured) query.set('structured', '1')
38 return `/json-transport?${query.toString()}`
39}
40
41/** Collects the `offset` of every GET that reads the run log. */
42function trackLogReads(page: Page) {
43 const offsets: Array<string> = []
44 page.on('request', (request) => {
45 const url = new URL(request.url())
46 const offset = url.searchParams.get('offset')
47 if (
48 request.method() === 'GET' &&
49 url.pathname === '/api/json-transport' &&
50 offset !== null
51 ) {
52 offsets.push(offset)
53 }
54 })
55 return offsets
56}
57
58async function openPage(page: Page, url: string) {
59 await page.goto(url)
60 await expect(page.getByTestId('hydration-marker')).toBeAttached()
61}
62
63test.describe('json transport', () => {
64 test('a chat turn shows the full answer from one JSON reply', async ({
65 page,
66 testId,
67 aimockPort,
68 }) => {
69 const logReads = trackLogReads(page)
70 await openPage(page, pageUrl(testId, aimockPort))
71
72 await sendMessage(page, '[json-transport-text] say hello')
73 await waitForAssistantText(
74 page,
75 'JSON_TEXT_OK the whole answer came back in one JSON reply.',
76 )
77 await waitForResponse(page)
78
79 // No maxWaitMs: the POST waits for the run to end, so there is no poll.
80 expect(logReads).toEqual([])
81 })
82
83 test('an awaited structured output shows as a structured-output part', async ({
84 page,
85 testId,
86 aimockPort,
87 }) => {
88 await openPage(page, pageUrl(testId, aimockPort, undefined, true))
89
90 await sendMessage(page, '[json-transport-structured] recommend a guitar')
91 await waitForResponse(page)
92
93 const first = page.getByTestId('assistant-message').last()
94 await expect(first.getByTestId('structured-output-part')).toHaveCount(1)
95 await expect(first.getByTestId('text-part')).toHaveCount(0)
96 await expect(first).toContainText('"name":"Fender Stratocaster"')
97 await expect(first).toContainText('"price":1299')
98 // The strict-mode `null` for the optional field is dropped.
99 await expect(first).not.toContainText('condition')
100
101 // The second turn sends the first object back as the assistant turn.
102 await sendMessage(page, '[json-transport-structured] a cheaper one')
103 await waitForResponse(page)
104
105 await expect(page.getByTestId('assistant-message')).toHaveCount(2)
106 const second = page.getByTestId('assistant-message').last()
107 await expect(second.getByTestId('structured-output-part')).toHaveCount(1)
108 await expect(second).toContainText('"name":"Squier Classic Vibe"')
109 })
110
111 test('a server tool completes over JSON', async ({
112 page,
113 testId,
114 aimockPort,
115 }) => {
116 await openPage(page, pageUrl(testId, aimockPort))
117
118 await sendMessage(
119 page,
120 '[json-transport-server-tool] weather in san francisco',
121 )
122 await waitForAssistantText(
123 page,
124 'JSON_SERVER_TOOL_OK San Francisco is 72F and sunny.',
125 )
126 await expect(page.getByTestId('tool-call-get_weather')).toBeVisible()
127 })
128
129 test('a client tool completes over JSON', async ({
130 page,
131 testId,
132 aimockPort,
133 }) => {
134 await openPage(page, pageUrl(testId, aimockPort))
135
136 await sendMessage(page, '[json-transport-client-tool] show a notification')
137 // The second fixture answer needs a second POST that carries the client
138 // tool result.
139 await waitForAssistantText(
140 page,
141 'JSON_CLIENT_TOOL_OK the notification was shown.',
142 )
143 await expect(page.getByTestId('tool-call-show_notification')).toBeVisible()
144 })
145
146 test('an approved tool completes over JSON', async ({
147 page,
148 testId,
149 aimockPort,
150 }) => {
151 await openPage(page, pageUrl(testId, aimockPort))
152
153 await sendMessage(page, '[json-transport-approval] delete the temp file')
154 await expect(page.getByTestId('approval-prompt-delete_file')).toBeVisible({
155 timeout: 15_000,
156 })
157 await expect(page.getByTestId('message-list')).not.toContainText(
158 'JSON_APPROVAL_OK',
159 )
160
161 await approveToolCall(page, 'delete_file')
162 await waitForAssistantText(
163 page,
164 'JSON_APPROVAL_OK the file has been deleted.',
165 )
166 await expect(page.getByTestId('approval-prompt-delete_file')).toHaveCount(0)
167 })
168
169 test('a short maxWaitMs makes the client poll, and the answer is complete', async ({
170 page,
171 testId,
172 aimockPort,
173 }) => {
174 const logReads = trackLogReads(page)
175 await openPage(page, pageUrl(testId, aimockPort, 1))
176
177 await sendMessage(page, LONG_PROMPT)
178 await waitForAssistantText(page, LONG_END, 30_000)
179 await waitForResponse(page)
180
181 // The POST replied with done: false, so the rest came from polls that
182 // carry a real offset (not the -1 of a join).
183 expect(logReads.length).toBeGreaterThan(0)
184 expect(logReads).not.toContain('-1')
185 const answer = page.getByTestId('assistant-message').filter({
186 hasText: LONG_END,
187 })
188 await expect(answer).toHaveCount(1)
189 await expect(answer).toContainText(LONG_START)
190 })
191
192 test('a reload during a run joins it and the answer completes', async ({
193 page,
194 testId,
195 aimockPort,
196 }) => {
197 const logReads = trackLogReads(page)
198 // A short maxWaitMs shows the first words before the run ends, so the
199 // reload happens while the run is still going.
200 await openPage(page, pageUrl(testId, aimockPort, 200))
201
202 await sendMessage(page, LONG_PROMPT)
203 await waitForAssistantText(page, LONG_START, 15_000)
204 await expect(page.getByTestId('message-list')).not.toContainText(LONG_END)
205
206 await page.reload()
207 await expect(page.getByTestId('hydration-marker')).toBeAttached()
208
209 await waitForAssistantText(page, LONG_END, 30_000)
210 await waitForResponse(page)
211
212 // `joinRun` reads the log from the start with offset -1.
213 expect(logReads).toContain('-1')
214 await expect(page.getByTestId('user-message')).toHaveCount(1)
215 const answer = page.getByTestId('assistant-message').filter({
216 hasText: LONG_END,
217 })
218 await expect(answer).toHaveCount(1)
219 await expect(answer).toContainText(LONG_START)
220 })
221})