@cloudflare/ai-chat 0.0.8 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/README.md +225 -459
  3. package/dist/ai-chat-v5-migration.d.ts +9 -9
  4. package/dist/ai-chat-v5-migration.js +25 -4
  5. package/dist/ai-chat-v5-migration.js.map +1 -1
  6. package/dist/experimental/forever.d.ts +29 -0
  7. package/dist/experimental/forever.js +55 -0
  8. package/dist/experimental/forever.js.map +1 -0
  9. package/dist/index.d.ts +114 -76
  10. package/dist/index.js +745 -629
  11. package/dist/index.js.map +1 -1
  12. package/dist/message-builder-Bwc_Umye.js +231 -0
  13. package/dist/message-builder-Bwc_Umye.js.map +1 -0
  14. package/dist/react.d.ts +27 -9
  15. package/dist/react.js +244 -258
  16. package/dist/react.js.map +1 -1
  17. package/dist/resumable-stream-DqXxQVjf.d.ts +103 -0
  18. package/dist/types.d.ts +16 -4
  19. package/dist/types.js +2 -0
  20. package/dist/types.js.map +1 -1
  21. package/e2e/chat.spec.ts +1703 -0
  22. package/e2e/client-tools.spec.ts +504 -0
  23. package/e2e/llm.spec.ts +637 -0
  24. package/e2e/playwright.config.ts +24 -0
  25. package/e2e/worker.ts +176 -0
  26. package/e2e/wrangler.jsonc +23 -0
  27. package/package.json +13 -5
  28. package/scripts/build.ts +2 -1
  29. package/src/ai-chat-v5-migration.ts +32 -5
  30. package/src/experimental/forever.ts +66 -0
  31. package/src/index.ts +831 -1137
  32. package/src/message-builder.ts +384 -0
  33. package/src/react-tests/use-agent-chat.test.tsx +738 -2
  34. package/src/react.tsx +385 -461
  35. package/src/resumable-stream.ts +441 -0
  36. package/src/tests/chat-context.test.ts +1 -1
  37. package/src/tests/chat-persistence.test.ts +5 -5
  38. package/src/tests/clear-history.test.ts +132 -0
  39. package/src/tests/client-tool-duplicate-message.test.ts +457 -14
  40. package/src/tests/client-tools-broadcast.test.ts +2 -2
  41. package/src/tests/client-tools-continuation.test.ts +3 -3
  42. package/src/tests/client-tools-reconnect.test.ts +143 -0
  43. package/src/tests/custom-body-continuation.test.ts +309 -0
  44. package/src/tests/custom-body.test.ts +3 -3
  45. package/src/tests/destroy.test.ts +57 -0
  46. package/src/tests/get-messages-endpoint.test.ts +79 -0
  47. package/src/tests/max-persisted-messages.test.ts +201 -0
  48. package/src/tests/merge-server-state.test.ts +106 -0
  49. package/src/tests/message-builder.test.ts +808 -0
  50. package/src/tests/migration.test.ts +282 -0
  51. package/src/tests/non-sse-response.test.ts +2 -2
  52. package/src/tests/onfinish-cleanup.test.ts +362 -0
  53. package/src/tests/plaintext-response.test.ts +87 -0
  54. package/src/tests/resumable-streaming.test.ts +220 -14
  55. package/src/tests/row-size-guard.test.ts +374 -0
  56. package/src/tests/sanitize-messages.test.ts +215 -0
  57. package/src/tests/validate-messages.test.ts +269 -0
  58. package/src/tests/worker.ts +59 -24
  59. package/src/types.ts +17 -1
  60. package/src/ws-chat-transport.ts +203 -0
@@ -0,0 +1,637 @@
1
+ import { test, expect } from "@playwright/test";
2
+
3
+ /**
4
+ * E2E tests that make real LLM calls via Workers AI (@cf/zai-org/glm-4.7-flash).
5
+ * These verify the full streaming pipeline: streamText → SSE → WebSocket → client.
6
+ *
7
+ * Uses the AI binding configured in wrangler.jsonc -- no API key needed.
8
+ * The only OpenAI usage is BadKeyAgent, which tests error handling with an invalid key.
9
+ */
10
+
11
+ const MessageType = {
12
+ CF_AGENT_USE_CHAT_REQUEST: "cf_agent_use_chat_request",
13
+ CF_AGENT_USE_CHAT_RESPONSE: "cf_agent_use_chat_response",
14
+ CF_AGENT_CHAT_CLEAR: "cf_agent_chat_clear"
15
+ } as const;
16
+
17
+ type WSMessage = {
18
+ type: string;
19
+ [key: string]: unknown;
20
+ };
21
+
22
+ function agentPath(baseURL: string, room: string) {
23
+ return `${baseURL.replace("http", "ws")}/agents/llm-chat-agent/${room}`;
24
+ }
25
+
26
+ /**
27
+ * Opens a WebSocket, sends a chat request, collects all messages until done.
28
+ */
29
+ async function sendChatAndCollect(
30
+ page: import("@playwright/test").Page,
31
+ wsUrl: string,
32
+ userMessage: string,
33
+ requestId: string,
34
+ timeoutMs = 15000
35
+ ): Promise<WSMessage[]> {
36
+ return page.evaluate(
37
+ ({ url, userMessage, requestId, timeoutMs, MT }) => {
38
+ return new Promise<WSMessage[]>((resolve, reject) => {
39
+ const ws = new WebSocket(url);
40
+ const received: WSMessage[] = [];
41
+
42
+ ws.onmessage = (e) => {
43
+ try {
44
+ received.push(JSON.parse(e.data as string));
45
+ } catch {
46
+ // ignore non-JSON
47
+ }
48
+ };
49
+
50
+ ws.onerror = () => reject(new Error("WebSocket error"));
51
+
52
+ ws.onopen = () => {
53
+ ws.send(
54
+ JSON.stringify({
55
+ type: MT.CF_AGENT_USE_CHAT_REQUEST,
56
+ id: requestId,
57
+ init: {
58
+ method: "POST",
59
+ body: JSON.stringify({
60
+ messages: [
61
+ {
62
+ id: `msg-${requestId}`,
63
+ role: "user",
64
+ parts: [{ type: "text", text: userMessage }]
65
+ }
66
+ ]
67
+ })
68
+ }
69
+ })
70
+ );
71
+
72
+ const check = setInterval(() => {
73
+ const doneMsg = received.find(
74
+ (m) => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done === true
75
+ );
76
+ if (doneMsg) {
77
+ clearInterval(check);
78
+ ws.close();
79
+ resolve(received);
80
+ }
81
+ }, 100);
82
+
83
+ setTimeout(() => {
84
+ clearInterval(check);
85
+ ws.close();
86
+ resolve(received);
87
+ }, timeoutMs);
88
+ };
89
+ });
90
+ },
91
+ { url: wsUrl, userMessage, requestId, timeoutMs, MT: MessageType }
92
+ );
93
+ }
94
+
95
+ /** Extract parsed chunk bodies from stream responses */
96
+ function extractChunkBodies(
97
+ messages: WSMessage[]
98
+ ): Array<{ type: string; [k: string]: unknown }> {
99
+ return messages
100
+ .filter(
101
+ (m) =>
102
+ m.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE &&
103
+ !m.done &&
104
+ typeof m.body === "string" &&
105
+ (m.body as string).trim()
106
+ )
107
+ .map((m) => JSON.parse(m.body as string));
108
+ }
109
+
110
+ test.describe("LLM e2e (Workers AI)", () => {
111
+ // Longer timeout for real LLM calls
112
+ test.setTimeout(30_000);
113
+
114
+ test.beforeEach(async ({ page }) => {
115
+ await page.goto("about:blank");
116
+ });
117
+
118
+ test("SSE streaming: receives text-start, text-delta(s), text-end from real model", async ({
119
+ page,
120
+ baseURL
121
+ }) => {
122
+ const room = crypto.randomUUID();
123
+ const messages = await sendChatAndCollect(
124
+ page,
125
+ agentPath(baseURL!, room),
126
+ "Say hello in exactly 3 words.",
127
+ "req-sse-1"
128
+ );
129
+
130
+ const chunks = extractChunkBodies(messages);
131
+ const types = chunks.map((c) => c.type);
132
+
133
+ // Should have SSE format (not plain text format)
134
+ expect(types).toContain("text-start");
135
+ expect(types).toContain("text-delta");
136
+ expect(types).toContain("text-end");
137
+
138
+ // Accumulate the text deltas
139
+ const fullText = chunks
140
+ .filter((c) => c.type === "text-delta")
141
+ .map((c) => c.delta as string)
142
+ .join("");
143
+
144
+ // Model should have responded with something
145
+ expect(fullText.length).toBeGreaterThan(0);
146
+ console.log("LLM response:", fullText);
147
+
148
+ // Should have start/finish lifecycle events
149
+ expect(types).toContain("start");
150
+ expect(types).toContain("finish");
151
+ });
152
+
153
+ test("server-side tool call: model calls getWeather and returns result", async ({
154
+ page,
155
+ baseURL
156
+ }) => {
157
+ const room = crypto.randomUUID();
158
+ const messages = await sendChatAndCollect(
159
+ page,
160
+ agentPath(baseURL!, room),
161
+ "What is the weather in London?",
162
+ "req-tool-1"
163
+ );
164
+
165
+ const chunks = extractChunkBodies(messages);
166
+ const types = chunks.map((c) => c.type);
167
+
168
+ // Should have tool lifecycle events
169
+ // The model should call getWeather, which executes server-side,
170
+ // and then continue with text output
171
+ expect(types).toContain("tool-input-start");
172
+ expect(types).toContain("tool-input-available");
173
+ expect(types).toContain("tool-output-available");
174
+
175
+ // Find the tool-input-available chunk
176
+ const toolInput = chunks.find((c) => c.type === "tool-input-available");
177
+ expect(toolInput).toBeTruthy();
178
+ expect(toolInput!.toolName).toBe("getWeather");
179
+
180
+ // Find the tool-output-available chunk — the execute function returns mocked data
181
+ const toolOutput = chunks.find((c) => c.type === "tool-output-available");
182
+ expect(toolOutput).toBeTruthy();
183
+ const output = toolOutput!.output as { city: string; temperature: number };
184
+ expect(output.city).toBe("London");
185
+ expect(output.temperature).toBe(22);
186
+
187
+ // After the tool result, the model should continue with text
188
+ // (maxSteps=3 allows continuation). The model usually responds with text,
189
+ // but may occasionally stop after the tool result.
190
+ const textDeltas = chunks.filter((c) => c.type === "text-delta");
191
+ if (textDeltas.length > 0) {
192
+ const fullText = textDeltas.map((c) => c.delta as string).join("");
193
+ console.log("Tool call response:", fullText);
194
+ expect(fullText.length).toBeGreaterThan(0);
195
+ } else {
196
+ // Model stopped after tool result — this is valid behavior
197
+ console.log("Model did not produce text after tool result (valid)");
198
+ }
199
+ });
200
+
201
+ test("message persistence with real LLM: messages survive reconnection", async ({
202
+ page,
203
+ baseURL
204
+ }) => {
205
+ const room = crypto.randomUUID();
206
+
207
+ // Send a message
208
+ await sendChatAndCollect(
209
+ page,
210
+ agentPath(baseURL!, room),
211
+ "Remember the number 42.",
212
+ "req-persist-llm"
213
+ );
214
+
215
+ // Check persistence via HTTP
216
+ const res = await page.request.get(
217
+ `${baseURL}/agents/llm-chat-agent/${room}/get-messages`
218
+ );
219
+ expect(res.ok()).toBe(true);
220
+
221
+ const persisted = await res.json();
222
+ expect(persisted.length).toBeGreaterThanOrEqual(2); // user + assistant
223
+
224
+ // User message
225
+ const userMsg = persisted.find(
226
+ (m: { id: string }) => m.id === "msg-req-persist-llm"
227
+ );
228
+ expect(userMsg).toBeTruthy();
229
+ expect(userMsg.role).toBe("user");
230
+
231
+ // Assistant message should have text parts from the real LLM response
232
+ const assistantMsgs = persisted.filter(
233
+ (m: { role: string }) => m.role === "assistant"
234
+ );
235
+ expect(assistantMsgs.length).toBeGreaterThanOrEqual(1);
236
+
237
+ const assistantParts = assistantMsgs[0].parts;
238
+ const textParts = assistantParts.filter(
239
+ (p: { type: string }) => p.type === "text"
240
+ );
241
+ expect(textParts.length).toBeGreaterThanOrEqual(1);
242
+ expect(textParts[0].text.length).toBeGreaterThan(0);
243
+ });
244
+
245
+ test("multi-step tool use: model uses addNumbers tool", async ({
246
+ page,
247
+ baseURL
248
+ }) => {
249
+ const room = crypto.randomUUID();
250
+ const messages = await sendChatAndCollect(
251
+ page,
252
+ agentPath(baseURL!, room),
253
+ "What is 17 + 25? Use the addNumbers tool to calculate.",
254
+ "req-math-1"
255
+ );
256
+
257
+ const chunks = extractChunkBodies(messages);
258
+
259
+ // Should have called addNumbers tool
260
+ const toolInput = chunks.find(
261
+ (c) => c.type === "tool-input-available" && c.toolName === "addNumbers"
262
+ );
263
+ expect(toolInput).toBeTruthy();
264
+
265
+ // Tool output should have the correct result
266
+ const toolOutput = chunks.find((c) => c.type === "tool-output-available");
267
+ expect(toolOutput).toBeTruthy();
268
+ const output = toolOutput!.output as { result: number };
269
+ expect(output.result).toBe(42);
270
+
271
+ // Model should have continued with text mentioning the result
272
+ const textDeltas = chunks.filter((c) => c.type === "text-delta");
273
+ if (textDeltas.length > 0) {
274
+ const fullText = textDeltas.map((c) => c.delta as string).join("");
275
+ console.log("Math response:", fullText);
276
+ // The model should mention 42 somewhere in its response
277
+ expect(fullText).toContain("42");
278
+ } else {
279
+ console.log("Model did not produce text after tool result (valid)");
280
+ }
281
+ });
282
+
283
+ test("step boundaries: multi-step response has start-step and finish-step", async ({
284
+ page,
285
+ baseURL
286
+ }) => {
287
+ const room = crypto.randomUUID();
288
+ const messages = await sendChatAndCollect(
289
+ page,
290
+ agentPath(baseURL!, room),
291
+ "What is the weather in Paris? Use the getWeather tool.",
292
+ "req-steps-1"
293
+ );
294
+
295
+ const chunks = extractChunkBodies(messages);
296
+ const types = chunks.map((c) => c.type);
297
+
298
+ // Multi-step responses should have step boundaries
299
+ expect(types).toContain("start-step");
300
+ expect(types).toContain("finish-step");
301
+
302
+ // Should have at least 1 step (the tool call step).
303
+ // With maxSteps=3, the model may also produce a continuation step.
304
+ const startSteps = types.filter((t) => t === "start-step").length;
305
+ expect(startSteps).toBeGreaterThanOrEqual(1);
306
+
307
+ // Tool lifecycle should be present in the steps
308
+ expect(types).toContain("tool-input-available");
309
+ expect(types).toContain("tool-output-available");
310
+ });
311
+
312
+ test("clear history works after LLM conversation", async ({
313
+ page,
314
+ baseURL
315
+ }) => {
316
+ const room = crypto.randomUUID();
317
+ const wsUrl = agentPath(baseURL!, room);
318
+
319
+ // Have a conversation
320
+ await sendChatAndCollect(page, wsUrl, "Hello!", "req-clear-llm");
321
+
322
+ // Verify messages exist
323
+ const before = await page.request.get(
324
+ `${baseURL}/agents/llm-chat-agent/${room}/get-messages`
325
+ );
326
+ const beforeData = await before.json();
327
+ expect(beforeData.length).toBeGreaterThanOrEqual(2);
328
+
329
+ // Clear
330
+ await page.evaluate(
331
+ ({ url, MT }) => {
332
+ return new Promise<void>((resolve) => {
333
+ const ws = new WebSocket(url);
334
+ ws.onopen = () => {
335
+ ws.send(JSON.stringify({ type: MT.CF_AGENT_CHAT_CLEAR }));
336
+ setTimeout(() => {
337
+ ws.close();
338
+ resolve();
339
+ }, 500);
340
+ };
341
+ });
342
+ },
343
+ { url: wsUrl, MT: MessageType }
344
+ );
345
+
346
+ // Verify cleared
347
+ const after = await page.request.get(
348
+ `${baseURL}/agents/llm-chat-agent/${room}/get-messages`
349
+ );
350
+ const afterData = await after.json();
351
+ expect(afterData.length).toBe(0);
352
+ });
353
+
354
+ test("multi-turn context: LLM remembers previous messages", async ({
355
+ page,
356
+ baseURL
357
+ }) => {
358
+ const room = crypto.randomUUID();
359
+ const wsUrl = agentPath(baseURL!, room);
360
+
361
+ // First turn: tell the model a fact
362
+ await sendChatAndCollect(
363
+ page,
364
+ wsUrl,
365
+ "My name is Alice. Remember that.",
366
+ "req-ctx-1"
367
+ );
368
+
369
+ // Second turn: ask about the fact, including the first message
370
+ // (as the client would — the full conversation history is sent)
371
+ const messages = await page.evaluate(
372
+ ({ url, MT }) => {
373
+ return new Promise<Array<{ type: string; [k: string]: unknown }>>(
374
+ (resolve) => {
375
+ const ws = new WebSocket(url);
376
+ const received: Array<{ type: string; [k: string]: unknown }> = [];
377
+
378
+ ws.onmessage = (e) => {
379
+ try {
380
+ received.push(JSON.parse(e.data));
381
+ } catch {
382
+ // ignore
383
+ }
384
+ };
385
+
386
+ ws.onopen = () => {
387
+ ws.send(
388
+ JSON.stringify({
389
+ type: MT.CF_AGENT_USE_CHAT_REQUEST,
390
+ id: "req-ctx-2",
391
+ init: {
392
+ method: "POST",
393
+ body: JSON.stringify({
394
+ messages: [
395
+ {
396
+ id: "msg-req-ctx-1",
397
+ role: "user",
398
+ parts: [
399
+ {
400
+ type: "text",
401
+ text: "My name is Alice. Remember that."
402
+ }
403
+ ]
404
+ },
405
+ {
406
+ id: "msg-req-ctx-2",
407
+ role: "user",
408
+ parts: [{ type: "text", text: "What is my name?" }]
409
+ }
410
+ ]
411
+ })
412
+ }
413
+ })
414
+ );
415
+
416
+ const check = setInterval(() => {
417
+ const done = received.find(
418
+ (m) =>
419
+ m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done === true
420
+ );
421
+ if (done) {
422
+ clearInterval(check);
423
+ ws.close();
424
+ resolve(received);
425
+ }
426
+ }, 100);
427
+
428
+ setTimeout(() => {
429
+ clearInterval(check);
430
+ ws.close();
431
+ resolve(received);
432
+ }, 15000);
433
+ };
434
+ }
435
+ );
436
+ },
437
+ { url: wsUrl, MT: MessageType }
438
+ );
439
+
440
+ // Extract text from the response
441
+ const chunks = extractChunkBodies(messages);
442
+ const fullText = chunks
443
+ .filter((c) => c.type === "text-delta")
444
+ .map((c) => c.delta as string)
445
+ .join("");
446
+
447
+ console.log("Context response:", fullText);
448
+ // Model should mention "Alice" since it has the context
449
+ expect(fullText.toLowerCase()).toContain("alice");
450
+ });
451
+
452
+ test("OpenAI metadata sanitization: no itemId in persisted messages", async ({
453
+ page,
454
+ baseURL
455
+ }) => {
456
+ const room = crypto.randomUUID();
457
+
458
+ // Have a conversation to generate messages with OpenAI metadata
459
+ await sendChatAndCollect(
460
+ page,
461
+ agentPath(baseURL!, room),
462
+ "Tell me a short fun fact.",
463
+ "req-sanitize"
464
+ );
465
+
466
+ // Fetch persisted messages
467
+ const res = await page.request.get(
468
+ `${baseURL}/agents/llm-chat-agent/${room}/get-messages`
469
+ );
470
+ expect(res.ok()).toBe(true);
471
+ const persisted = await res.json();
472
+
473
+ // Check that no part has providerMetadata.openai.itemId
474
+ for (const msg of persisted) {
475
+ for (const part of msg.parts || []) {
476
+ if (part.providerMetadata?.openai) {
477
+ expect(part.providerMetadata.openai.itemId).toBeUndefined();
478
+ expect(
479
+ part.providerMetadata.openai.reasoningEncryptedContent
480
+ ).toBeUndefined();
481
+ }
482
+ if (part.callProviderMetadata?.openai) {
483
+ expect(part.callProviderMetadata.openai.itemId).toBeUndefined();
484
+ }
485
+ }
486
+ }
487
+
488
+ // Also verify messages actually exist and have content
489
+ expect(persisted.length).toBeGreaterThanOrEqual(2);
490
+ const assistant = persisted.find(
491
+ (m: { role: string }) => m.role === "assistant"
492
+ );
493
+ expect(assistant).toBeTruthy();
494
+ expect(assistant.parts.length).toBeGreaterThan(0);
495
+ });
496
+
497
+ test("multi-tab tool streaming: second connection sees tool-input-start and tool-output-available", async ({
498
+ page,
499
+ baseURL
500
+ }) => {
501
+ const room = crypto.randomUUID();
502
+ const wsUrl = agentPath(baseURL!, room);
503
+
504
+ // Open two connections to the same room.
505
+ // ws1 sends the request, ws2 observes the broadcast.
506
+ const result = await page.evaluate(
507
+ ({ url, MT }) => {
508
+ return new Promise<{
509
+ ws2ChunkTypes: string[];
510
+ ws2HasToolInputStart: boolean;
511
+ ws2HasToolOutputAvailable: boolean;
512
+ }>((resolve) => {
513
+ const ws1 = new WebSocket(url);
514
+ const ws2 = new WebSocket(url);
515
+ const ws2ChunkTypes: string[] = [];
516
+ let ws1Open = false;
517
+ let ws2Open = false;
518
+
519
+ function maybeSend() {
520
+ if (!ws1Open || !ws2Open) return;
521
+ setTimeout(() => {
522
+ ws1.send(
523
+ JSON.stringify({
524
+ type: MT.CF_AGENT_USE_CHAT_REQUEST,
525
+ id: "req-multi-tab-tool",
526
+ init: {
527
+ method: "POST",
528
+ body: JSON.stringify({
529
+ messages: [
530
+ {
531
+ id: "mtt-1",
532
+ role: "user",
533
+ parts: [
534
+ {
535
+ type: "text",
536
+ text: "What is the weather in Tokyo? Use the getWeather tool."
537
+ }
538
+ ]
539
+ }
540
+ ]
541
+ })
542
+ }
543
+ })
544
+ );
545
+ }, 100);
546
+ }
547
+
548
+ ws1.onopen = () => {
549
+ ws1Open = true;
550
+ maybeSend();
551
+ };
552
+ ws2.onopen = () => {
553
+ ws2Open = true;
554
+ maybeSend();
555
+ };
556
+
557
+ // Collect chunk types from ws2 (the observer)
558
+ ws2.onmessage = (e) => {
559
+ try {
560
+ const data = JSON.parse(e.data);
561
+ if (
562
+ data.type === MT.CF_AGENT_USE_CHAT_RESPONSE &&
563
+ typeof data.body === "string" &&
564
+ data.body.trim()
565
+ ) {
566
+ try {
567
+ const chunk = JSON.parse(data.body);
568
+ ws2ChunkTypes.push(chunk.type);
569
+ } catch {
570
+ // not JSON body
571
+ }
572
+ }
573
+ } catch {
574
+ // ignore
575
+ }
576
+ };
577
+
578
+ // Wait for ws1 to get done signal
579
+ const ws1Messages: Array<{
580
+ type: string;
581
+ [k: string]: unknown;
582
+ }> = [];
583
+ ws1.onmessage = (e) => {
584
+ try {
585
+ const data = JSON.parse(e.data);
586
+ ws1Messages.push(data);
587
+ } catch {
588
+ // ignore
589
+ }
590
+ };
591
+
592
+ const check = setInterval(() => {
593
+ const done = ws1Messages.find(
594
+ (m) => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done === true
595
+ );
596
+ if (done) {
597
+ clearInterval(check);
598
+ setTimeout(() => {
599
+ ws1.close();
600
+ ws2.close();
601
+ resolve({
602
+ ws2ChunkTypes,
603
+ ws2HasToolInputStart:
604
+ ws2ChunkTypes.includes("tool-input-start"),
605
+ ws2HasToolOutputAvailable: ws2ChunkTypes.includes(
606
+ "tool-output-available"
607
+ )
608
+ });
609
+ }, 300);
610
+ }
611
+ }, 100);
612
+
613
+ setTimeout(() => {
614
+ clearInterval(check);
615
+ ws1.close();
616
+ ws2.close();
617
+ resolve({
618
+ ws2ChunkTypes,
619
+ ws2HasToolInputStart: ws2ChunkTypes.includes("tool-input-start"),
620
+ ws2HasToolOutputAvailable: ws2ChunkTypes.includes(
621
+ "tool-output-available"
622
+ )
623
+ });
624
+ }, 20000);
625
+ });
626
+ },
627
+ { url: wsUrl, MT: MessageType }
628
+ );
629
+
630
+ // ws2 should see the full tool lifecycle streamed to it
631
+ expect(result.ws2ChunkTypes.length).toBeGreaterThan(0);
632
+ // Should see tool-input-start (the tool being called)
633
+ expect(result.ws2HasToolInputStart).toBe(true);
634
+ // Should see tool-output-available (the tool result)
635
+ expect(result.ws2HasToolOutputAvailable).toBe(true);
636
+ });
637
+ });
@@ -0,0 +1,24 @@
1
+ import { defineConfig } from "@playwright/test";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ const PORT = 8799;
6
+ const e2eDir = dirname(fileURLToPath(import.meta.url));
7
+ const configPath = join(e2eDir, "wrangler.jsonc");
8
+
9
+ export default defineConfig({
10
+ testDir: e2eDir,
11
+ testMatch: "*.spec.ts",
12
+ timeout: 30_000,
13
+ retries: 0,
14
+ workers: 1, // Sequential — single wrangler dev instance
15
+ use: {
16
+ baseURL: `http://localhost:${PORT}`
17
+ },
18
+ webServer: {
19
+ command: `npx wrangler dev --config ${configPath} --port ${PORT}`,
20
+ port: PORT,
21
+ reuseExistingServer: !process.env.CI,
22
+ timeout: 20_000
23
+ }
24
+ });