|
| 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, vi } from "vitest"; |
| 6 | +import { chat } from "../src/v3/ai.js"; |
| 7 | +import { __setSessionOpenImplForTests, sessions } from "../src/v3/sessions.js"; |
| 8 | +import { apiClientManager, sessionStreams } from "@trigger.dev/core/v3"; |
| 9 | +import { runInMockTaskContext } from "@trigger.dev/core/v3/test"; |
| 10 | +import { simulateReadableStream, streamText } from "ai"; |
| 11 | +import { MockLanguageModelV3 } from "ai/test"; |
| 12 | +import type { LanguageModelV3StreamPart } from "@ai-sdk/provider"; |
| 13 | + |
| 14 | +// ── Helpers ──────────────────────────────────────────────────────────── |
| 15 | + |
| 16 | +function userMessage(text: string, id: string) { |
| 17 | + return { |
| 18 | + id, |
| 19 | + role: "user" as const, |
| 20 | + parts: [{ type: "text" as const, text }], |
| 21 | + }; |
| 22 | +} |
| 23 | + |
| 24 | +function textStreamChunks(text: string): LanguageModelV3StreamPart[] { |
| 25 | + return [ |
| 26 | + { type: "text-start", id: "t1" }, |
| 27 | + { type: "text-delta", id: "t1", delta: text }, |
| 28 | + { type: "text-end", id: "t1" }, |
| 29 | + { |
| 30 | + type: "finish", |
| 31 | + finishReason: { unified: "stop", raw: "stop" }, |
| 32 | + usage: { |
| 33 | + inputTokens: { total: 10, noCache: 10, cacheRead: undefined, cacheWrite: undefined }, |
| 34 | + outputTokens: { total: 10, text: 10, reasoning: undefined }, |
| 35 | + }, |
| 36 | + }, |
| 37 | + ]; |
| 38 | +} |
| 39 | + |
| 40 | +/** Model that answers `ANSWER(<last user text>)`, slowly enough that |
| 41 | + * records sent right after the turn starts arrive mid-stream. */ |
| 42 | +function echoModel() { |
| 43 | + return new MockLanguageModelV3({ |
| 44 | + doStream: async ({ prompt }) => { |
| 45 | + const users = prompt.filter((m) => m.role === "user"); |
| 46 | + const last = users[users.length - 1]; |
| 47 | + const text = Array.isArray(last?.content) |
| 48 | + ? last.content |
| 49 | + .filter((p): p is { type: "text"; text: string } => p.type === "text") |
| 50 | + .map((p) => p.text) |
| 51 | + .join("") |
| 52 | + : ""; |
| 53 | + return { |
| 54 | + stream: simulateReadableStream({ |
| 55 | + chunks: textStreamChunks(`ANSWER(${text})`), |
| 56 | + initialDelayInMs: 100, |
| 57 | + chunkDelayInMs: 10, |
| 58 | + }), |
| 59 | + }; |
| 60 | + }, |
| 61 | + }); |
| 62 | +} |
| 63 | + |
| 64 | +async function waitFor(check: () => boolean, timeoutMs = 10_000) { |
| 65 | + const start = Date.now(); |
| 66 | + while (Date.now() - start < timeoutMs) { |
| 67 | + if (check()) return; |
| 68 | + await new Promise((r) => setTimeout(r, 20)); |
| 69 | + } |
| 70 | + throw new Error("waitFor timed out"); |
| 71 | +} |
| 72 | + |
| 73 | +function streamedText(harness: { allChunks: unknown[] }): string { |
| 74 | + return (harness.allChunks as { type?: string; delta?: string }[]) |
| 75 | + .filter((c) => c.type === "text-delta") |
| 76 | + .map((c) => c.delta ?? "") |
| 77 | + .join(""); |
| 78 | +} |
| 79 | + |
| 80 | +function turnCompleteCount(harness: { allRawChunks: unknown[] }): number { |
| 81 | + return (harness.allRawChunks as { type?: string }[]).filter( |
| 82 | + (c) => c.type === "trigger:turn-complete" |
| 83 | + ).length; |
| 84 | +} |
| 85 | + |
| 86 | +// ── Tests ────────────────────────────────────────────────────────────── |
| 87 | + |
| 88 | +describe("chat.agent pending wire buffer", () => { |
| 89 | + it("dispatches every message buffered during a turn, not just the first", async () => { |
| 90 | + const agent = chat.agent({ |
| 91 | + id: "pending-drain.agent", |
| 92 | + run: async ({ messages, signal }) => { |
| 93 | + return streamText({ model: echoModel(), messages, abortSignal: signal }); |
| 94 | + }, |
| 95 | + }); |
| 96 | + |
| 97 | + const harness = mockChatAgent(agent, { chatId: "pending-drain-1" }); |
| 98 | + try { |
| 99 | + const first = harness.sendMessage(userMessage("m1", "u-1")); |
| 100 | + // Once m1's turn is streaming, land two more records back-to-back — |
| 101 | + // both are consumed into the turn's buffer before the turn ends. |
| 102 | + await waitFor(() => streamedText(harness).includes("ANSWER(m1)")); |
| 103 | + void harness.sendMessage(userMessage("m2", "u-2")); |
| 104 | + void harness.sendMessage(userMessage("m3", "u-3")); |
| 105 | + await first; |
| 106 | + |
| 107 | + await waitFor(() => turnCompleteCount(harness) >= 3); |
| 108 | + |
| 109 | + const text = streamedText(harness); |
| 110 | + const m2At = text.indexOf("ANSWER(m2)"); |
| 111 | + const m3At = text.indexOf("ANSWER(m3)"); |
| 112 | + expect(m2At).toBeGreaterThan(-1); |
| 113 | + expect(m3At).toBeGreaterThan(-1); |
| 114 | + expect(m3At).toBeGreaterThan(m2At); |
| 115 | + } finally { |
| 116 | + await harness.close(); |
| 117 | + } |
| 118 | + }); |
| 119 | +}); |
| 120 | + |
| 121 | +describe("chat.createSession pending wire buffer", () => { |
| 122 | + it("dispatches messages buffered during a turn as subsequent turns", async () => { |
| 123 | + const agent = chat.customAgent({ |
| 124 | + id: "pending-drain.session", |
| 125 | + run: async (payload) => { |
| 126 | + const session = chat.createSession(payload, { |
| 127 | + signal: new AbortController().signal, |
| 128 | + idleTimeoutInSeconds: 2, |
| 129 | + }); |
| 130 | + for await (const turn of session) { |
| 131 | + const result = streamText({ |
| 132 | + model: echoModel(), |
| 133 | + messages: turn.messages, |
| 134 | + abortSignal: turn.signal, |
| 135 | + }); |
| 136 | + await turn.complete(result); |
| 137 | + } |
| 138 | + }, |
| 139 | + }); |
| 140 | + |
| 141 | + const harness = mockChatAgent(agent, { chatId: "pending-drain-2" }); |
| 142 | + try { |
| 143 | + const first = harness.sendMessage(userMessage("m1", "u-1")); |
| 144 | + await waitFor(() => streamedText(harness).includes("ANSWER(m1)")); |
| 145 | + void harness.sendMessage(userMessage("m2", "u-2")); |
| 146 | + void harness.sendMessage(userMessage("m3", "u-3")); |
| 147 | + await first; |
| 148 | + |
| 149 | + await waitFor(() => turnCompleteCount(harness) >= 3); |
| 150 | + |
| 151 | + const text = streamedText(harness); |
| 152 | + expect(text).toContain("ANSWER(m2)"); |
| 153 | + expect(text).toContain("ANSWER(m3)"); |
| 154 | + } finally { |
| 155 | + await harness.close(); |
| 156 | + } |
| 157 | + }); |
| 158 | +}); |
| 159 | + |
| 160 | +describe("session.in.wait() consume cursor", () => { |
| 161 | + it("advances lastDispatchedSeqNum alongside lastSeqNum on waitpoint delivery", async () => { |
| 162 | + __setSessionOpenImplForTests(undefined); |
| 163 | + await runInMockTaskContext(async () => { |
| 164 | + vi.spyOn(apiClientManager, "clientOrThrow").mockReturnValue({ |
| 165 | + createSessionStreamWaitpoint: async () => ({ waitpointId: "wp_test_1" }), |
| 166 | + waitForWaitpointToken: async () => ({ success: true }), |
| 167 | + } as never); |
| 168 | + |
| 169 | + const sessionId = "cursor-sess"; |
| 170 | + // Simulate records 0..4 already received via SSE before the suspend. |
| 171 | + sessionStreams.setLastSeqNum(sessionId, "in", 4); |
| 172 | + |
| 173 | + const result = await sessions.open(sessionId).in.wait(); |
| 174 | + |
| 175 | + expect(result.ok).toBe(true); |
| 176 | + expect(sessionStreams.lastSeqNum(sessionId, "in")).toBe(5); |
| 177 | + // The waitpoint-delivered record was consumed by this caller, so the |
| 178 | + // committed-consume cursor (what turn-completes persist as |
| 179 | + // `session-in-event-id`) must advance with it. |
| 180 | + expect(sessionStreams.lastDispatchedSeqNum(sessionId, "in")).toBe(5); |
| 181 | + }); |
| 182 | + }); |
| 183 | +}); |
0 commit comments