|
| 1 | +import { mockChatAgent } from "../src/v3/test/index.js"; |
| 2 | + |
| 3 | +import { sessionStreams } from "@trigger.dev/core/v3"; |
| 4 | +import type { LanguageModelV3StreamPart } from "@ai-sdk/provider"; |
| 5 | +import { simulateReadableStream, stepCountIs, streamText, tool } from "ai"; |
| 6 | +import { MockLanguageModelV3 } from "ai/test"; |
| 7 | +import { describe, expect, it } from "vitest"; |
| 8 | +import { z } from "zod"; |
| 9 | +import { chat } from "../src/v3/ai.js"; |
| 10 | + |
| 11 | +/** |
| 12 | + * `pendingMessages.prepare` decides how a steer is presented to the model. |
| 13 | + * The steered turn gets that form. Later turns have to get the same form, |
| 14 | + * or the model's memory of the instruction differs from what it acted on. |
| 15 | + */ |
| 16 | + |
| 17 | +const USAGE = { |
| 18 | + inputTokens: { total: 1, noCache: 1, cacheRead: undefined, cacheWrite: undefined }, |
| 19 | + outputTokens: { total: 1, text: 1, reasoning: undefined }, |
| 20 | +}; |
| 21 | +const userMessage = (text: string, id: string) => ({ |
| 22 | + id, |
| 23 | + role: "user" as const, |
| 24 | + parts: [{ type: "text" as const, text }], |
| 25 | +}); |
| 26 | +function deferred() { |
| 27 | + let resolve!: () => void; |
| 28 | + const promise = new Promise<void>((res) => { |
| 29 | + resolve = res; |
| 30 | + }); |
| 31 | + return { promise, resolve }; |
| 32 | +} |
| 33 | +async function waitFor(check: () => boolean, label = "condition", timeoutMs = 8_000) { |
| 34 | + const start = Date.now(); |
| 35 | + while (Date.now() - start < timeoutMs) { |
| 36 | + if (check()) return; |
| 37 | + await new Promise((r) => setTimeout(r, 10)); |
| 38 | + } |
| 39 | + throw new Error(`waitFor timed out: ${label}`); |
| 40 | +} |
| 41 | +const textChunks = (text: string): LanguageModelV3StreamPart[] => [ |
| 42 | + { type: "text-start", id: "t1" }, |
| 43 | + { type: "text-delta", id: "t1", delta: text }, |
| 44 | + { type: "text-end", id: "t1" }, |
| 45 | + { type: "finish", finishReason: { unified: "stop", raw: "stop" }, usage: USAGE }, |
| 46 | +]; |
| 47 | +const toolCallChunks = (callId: string): LanguageModelV3StreamPart[] => [ |
| 48 | + { type: "tool-call", toolCallId: callId, toolName: "gate", input: JSON.stringify({ q: "go" }) }, |
| 49 | + { type: "finish", finishReason: { unified: "tool-calls", raw: "tool-calls" }, usage: USAGE }, |
| 50 | +]; |
| 51 | +type SeqReader = { lastSeqNum: (chatId: string, dir: "in" | "out") => number | undefined }; |
| 52 | +async function sendAndLand( |
| 53 | + harness: { sendMessage: (m: ReturnType<typeof userMessage>) => Promise<unknown> }, |
| 54 | + chatId: string, |
| 55 | + text: string, |
| 56 | + id: string |
| 57 | +) { |
| 58 | + const seqs = sessionStreams as unknown as SeqReader; |
| 59 | + const before = seqs.lastSeqNum(chatId, "in") ?? -1; |
| 60 | + void harness.sendMessage(userMessage(text, id)); |
| 61 | + await waitFor(() => (seqs.lastSeqNum(chatId, "in") ?? -1) > before, `append ${id}`); |
| 62 | +} |
| 63 | + |
| 64 | +describe("a steer transformed by pendingMessages.prepare", () => { |
| 65 | + it("reaches later turns in the transformed form", { timeout: 30_000 }, async () => { |
| 66 | + const chatId = "steer-prepare-transform"; |
| 67 | + const toolGate = deferred(); |
| 68 | + let toolEntered = false; |
| 69 | + const prompts: string[] = []; |
| 70 | + |
| 71 | + const gateTool = tool({ |
| 72 | + description: "blocks until the test opens it", |
| 73 | + inputSchema: z.object({ q: z.string() }), |
| 74 | + execute: async () => { |
| 75 | + toolEntered = true; |
| 76 | + await toolGate.promise; |
| 77 | + return "ok"; |
| 78 | + }, |
| 79 | + }); |
| 80 | + |
| 81 | + let step = 0; |
| 82 | + const model = new MockLanguageModelV3({ |
| 83 | + doStream: async ({ prompt }) => { |
| 84 | + prompts.push(JSON.stringify(prompt)); |
| 85 | + const isToolStep = step++ % 2 === 0; |
| 86 | + return { |
| 87 | + stream: simulateReadableStream({ |
| 88 | + chunks: isToolStep ? toolCallChunks(`tc-${step}`) : textChunks("done"), |
| 89 | + initialDelayInMs: 10, |
| 90 | + chunkDelayInMs: 2, |
| 91 | + }), |
| 92 | + }; |
| 93 | + }, |
| 94 | + }); |
| 95 | + |
| 96 | + const agent = chat.agent({ |
| 97 | + id: "steer-prepare-transform", |
| 98 | + pendingMessages: { |
| 99 | + shouldInject: () => true, |
| 100 | + // Present the steer to the model as an operator note, not a user turn. |
| 101 | + prepare: async ({ messages }) => [ |
| 102 | + { |
| 103 | + role: "system", |
| 104 | + content: `[OPERATOR-NOTE] ${messages.map((m) => (m.parts as { text?: string }[]).map((p) => p.text ?? "").join("")).join(" ")}`, |
| 105 | + }, |
| 106 | + ], |
| 107 | + }, |
| 108 | + run: async ({ messages, signal }) => |
| 109 | + streamText({ |
| 110 | + model, |
| 111 | + messages, |
| 112 | + abortSignal: signal, |
| 113 | + ...chat.toStreamTextOptions(), |
| 114 | + tools: { gate: gateTool }, |
| 115 | + stopWhen: stepCountIs(5), |
| 116 | + }), |
| 117 | + }); |
| 118 | + |
| 119 | + const harness = mockChatAgent(agent, { chatId }); |
| 120 | + try { |
| 121 | + const first = harness.sendMessage(userMessage("m1", "u-1")); |
| 122 | + await waitFor(() => toolEntered, "tool entered"); |
| 123 | + await sendAndLand(harness, chatId, "steer-me", "u-2"); |
| 124 | + toolGate.resolve(); |
| 125 | + await first; |
| 126 | + await waitFor(() => prompts.length >= 2, "turn 1 second step"); |
| 127 | + |
| 128 | + // The steered turn saw the transformed form. |
| 129 | + expect(prompts[1]!).toContain("[OPERATOR-NOTE] steer-me"); |
| 130 | + const promptsAfterTurn1 = prompts.length; |
| 131 | + |
| 132 | + await harness.sendMessage(userMessage("m3", "u-3")); |
| 133 | + await waitFor(() => prompts.length > promptsAfterTurn1, "turn 2 prompt built"); |
| 134 | + |
| 135 | + // And so does the next one. Reconverting the UI message gives the raw |
| 136 | + // user turn instead, so the model remembers a different instruction |
| 137 | + // from the one it acted on. |
| 138 | + expect(prompts[promptsAfterTurn1]!).toContain("[OPERATOR-NOTE] steer-me"); |
| 139 | + } finally { |
| 140 | + toolGate.resolve(); |
| 141 | + await harness.close(); |
| 142 | + } |
| 143 | + }); |
| 144 | +}); |
0 commit comments