|
| 1 | +// Import the test harness FIRST — this installs the resource catalog so |
| 2 | +// `chat.agent()` calls below register their task functions correctly. |
| 3 | +import { mockChatAgent } from "../src/v3/test/index.js"; |
| 4 | + |
| 5 | +import { describe, expect, it } from "vitest"; |
| 6 | +import type { UIMessage } from "ai"; |
| 7 | +import { chat } from "../src/v3/ai.js"; |
| 8 | +import type { TurnCompleteEvent } from "../src/v3/ai.js"; |
| 9 | + |
| 10 | +// ── Helpers ──────────────────────────────────────────────────────────── |
| 11 | + |
| 12 | +function userMessage(text: string, id: string): UIMessage { |
| 13 | + return { id, role: "user", parts: [{ type: "text", text }] }; |
| 14 | +} |
| 15 | + |
| 16 | +function extractText(message: UIMessage | undefined): string { |
| 17 | + if (!message) return ""; |
| 18 | + return (message.parts as Array<{ type: string; text?: string }>) |
| 19 | + .filter((p) => p.type === "text") |
| 20 | + .map((p) => p.text ?? "") |
| 21 | + .join(""); |
| 22 | +} |
| 23 | + |
| 24 | +async function waitFor(check: () => boolean, timeoutMs = 5_000) { |
| 25 | + const start = Date.now(); |
| 26 | + while (Date.now() - start < timeoutMs) { |
| 27 | + if (check()) return; |
| 28 | + await new Promise((r) => setTimeout(r, 20)); |
| 29 | + } |
| 30 | + throw new Error("waitFor timed out"); |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * A `run()` return value that looks like a `StreamTextResult` (has |
| 35 | + * `toUIMessageStream()`) but whose UI stream emits a partial assistant |
| 36 | + * message and then errors — reproducing a source-stream transport failure |
| 37 | + * (e.g. `UND_ERR_BODY_TIMEOUT`) mid-turn. `onFinish` is never invoked, which |
| 38 | + * is exactly what happens on a hard transport error. Chunks are delivered |
| 39 | + * one-per-pull before the error so they aren't discarded (calling |
| 40 | + * `controller.error()` in the same tick as `enqueue()` resets the queue). |
| 41 | + */ |
| 42 | +function erroringSource(errorMessage: string) { |
| 43 | + const partialChunks = [ |
| 44 | + { type: "start", messageId: "a-err" }, |
| 45 | + { type: "text-start", id: "t1" }, |
| 46 | + { type: "text-delta", id: "t1", delta: "partial answer" }, |
| 47 | + ]; |
| 48 | + return { |
| 49 | + toUIMessageStream() { |
| 50 | + let i = 0; |
| 51 | + return new ReadableStream({ |
| 52 | + pull(controller) { |
| 53 | + if (i < partialChunks.length) { |
| 54 | + controller.enqueue(partialChunks[i++]); |
| 55 | + } else { |
| 56 | + controller.error(new Error(errorMessage)); |
| 57 | + } |
| 58 | + }, |
| 59 | + }); |
| 60 | + }, |
| 61 | + }; |
| 62 | +} |
| 63 | + |
| 64 | +// ── Tests ────────────────────────────────────────────────────────────── |
| 65 | + |
| 66 | +describe("chat.agent managed loop — source-stream failure", () => { |
| 67 | + it("preserves the partial assistant message on onTurnComplete when the source stream fails", async () => { |
| 68 | + const turnCompletes: TurnCompleteEvent<unknown, UIMessage>[] = []; |
| 69 | + |
| 70 | + const agent = chat.agent({ |
| 71 | + id: "chatAgent.source-stream-error", |
| 72 | + run: async () => erroringSource("UND_ERR_BODY_TIMEOUT") as never, |
| 73 | + onTurnComplete: async (event) => { |
| 74 | + turnCompletes.push(event); |
| 75 | + }, |
| 76 | + }); |
| 77 | + |
| 78 | + const harness = mockChatAgent(agent, { chatId: "cae-source-error" }); |
| 79 | + try { |
| 80 | + await harness.sendMessage(userMessage("hi", "u-1")); |
| 81 | + await waitFor(() => turnCompletes.length >= 1); |
| 82 | + |
| 83 | + const evt = turnCompletes[0]!; |
| 84 | + |
| 85 | + // The turn is reported as errored, carrying the thrown transport error. |
| 86 | + expect(evt.finishReason).toBe("error"); |
| 87 | + expect(evt.error).toBeInstanceOf(Error); |
| 88 | + expect((evt.error as Error).message).toBe("UND_ERR_BODY_TIMEOUT"); |
| 89 | + |
| 90 | + // The partial assistant output that streamed before the failure must be |
| 91 | + // preserved so persistence / recovery can keep it, instead of being |
| 92 | + // dropped (responseMessage: undefined). |
| 93 | + expect(evt.responseMessage).toBeDefined(); |
| 94 | + expect(extractText(evt.responseMessage)).toBe("partial answer"); |
| 95 | + } finally { |
| 96 | + await harness.close(); |
| 97 | + } |
| 98 | + }); |
| 99 | +}); |
| 100 | + |
| 101 | +describe("chat.createSession turn.complete() — source-stream failure", () => { |
| 102 | + it("accumulates the partial before rethrowing so the caller can persist it", async () => { |
| 103 | + let caughtError: unknown; |
| 104 | + let uiMessagesAfterError: UIMessage[] = []; |
| 105 | + |
| 106 | + const agent = chat.customAgent({ |
| 107 | + id: "createSession.source-stream-error", |
| 108 | + run: async (payload) => { |
| 109 | + const session = chat.createSession(payload, { |
| 110 | + signal: new AbortController().signal, |
| 111 | + idleTimeoutInSeconds: 2, |
| 112 | + }); |
| 113 | + for await (const turn of session) { |
| 114 | + try { |
| 115 | + await turn.complete(erroringSource("UND_ERR_BODY_TIMEOUT") as never); |
| 116 | + } catch (err) { |
| 117 | + caughtError = err; |
| 118 | + // The partial must be accumulated so persistence from the session |
| 119 | + // state keeps it, rather than being lost on the rethrow. |
| 120 | + uiMessagesAfterError = [...turn.uiMessages]; |
| 121 | + await turn.done(); |
| 122 | + } |
| 123 | + } |
| 124 | + }, |
| 125 | + }); |
| 126 | + |
| 127 | + const harness = mockChatAgent(agent, { chatId: "cs-source-error" }); |
| 128 | + try { |
| 129 | + await harness.sendMessage(userMessage("hi", "u-1")); |
| 130 | + await waitFor(() => caughtError !== undefined); |
| 131 | + |
| 132 | + expect(caughtError).toBeInstanceOf(Error); |
| 133 | + expect((caughtError as Error).message).toBe("UND_ERR_BODY_TIMEOUT"); |
| 134 | + |
| 135 | + const partial = uiMessagesAfterError.find((m) => m.role === "assistant"); |
| 136 | + expect(partial).toBeDefined(); |
| 137 | + expect(extractText(partial)).toBe("partial answer"); |
| 138 | + } finally { |
| 139 | + await harness.close(); |
| 140 | + } |
| 141 | + }); |
| 142 | +}); |
0 commit comments