Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

textGeneration.test.ts

373 lines14.1 KB

1import { assert, it } from "@effect/vitest";
2import { ProviderInstanceId } from "@t3tools/contracts";
3import { createModelSelection } from "@t3tools/shared/model";
4import * as Cause from "effect/Cause";
5import * as Effect from "effect/Effect";
6import * as Queue from "effect/Queue";
7import * as Schema from "effect/Schema";
8import * as Sink from "effect/Sink";
9import * as Stream from "effect/Stream";
10import * as ChildProcess from "effect/process/ChildProcess";
11import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12​
13import { makePiTextGeneration } from "./textGeneration.ts";
14​
15const decodeJsonLine = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
16const encodeJsonLine = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
17​
18const makeFakePi = (
19 reply: string,
20 setModelError?: string,
21 turnEvents: ReadonlyArray<Record<string, unknown>> = [],
22 models?: ReadonlyArray<Record<string, unknown>>,
23 version = "0.84.3",
24 thinkingError?: string,
25) =>
26 Effect.gen(function* () {
27 const stdout = yield* Queue.unbounded<Uint8Array, Cause.Done>();
28 const received: Array<Record<string, unknown>> = [];
29 const emit = (record: Record<string, unknown>) =>
30 Queue.offer(stdout, new TextEncoder().encode(`${encodeJsonLine(record)}\n`));
31 let buffered = "";
32 const onStdin = (chunk: Uint8Array) =>
33 Effect.gen(function* () {
34 buffered += new TextDecoder().decode(chunk);
35 const lines = buffered.split("\n");
36 buffered = lines.pop() ?? "";
37 for (const line of lines.filter((candidate) => candidate.length > 0)) {
38 const record = decodeJsonLine(line) as Record<string, unknown>;
39 received.push(record);
40 const response = { type: "response", id: record["id"], command: record["type"] };
41 if (record["type"] === "prompt") {
42 yield* emit({ ...response, success: true });
43 for (const event of turnEvents) yield* emit(event);
44 yield* emit({ type: "agent_settled" });
45 } else if (record["type"] === "get_last_assistant_text") {
46 yield* emit({ ...response, success: true, data: { text: reply } });
47 } else if (record["type"] === "get_available_models" && models !== undefined) {
48 yield* emit({ ...response, success: true, data: { models } });
49 } else if (record["type"] === "set_model" && setModelError !== undefined) {
50 yield* emit({ ...response, success: false, error: setModelError });
51 } else if (record["type"] === "set_thinking_level" && thinkingError !== undefined) {
52 yield* emit({ ...response, success: false, error: thinkingError });
53 } else {
54 yield* emit({ ...response, success: true });
55 }
56 }
57 });
58 const spawner = ChildProcessSpawner.make((command) => {
59 const versionProbe =
60 ChildProcess.isStandardCommand(command) && command.args.includes("--version");
61 return Effect.succeed(
62 ChildProcessSpawner.makeHandle({
63 // Outside the valid pid range, so PiRpc's process-group kill never lands.
64 pid: ChildProcessSpawner.ProcessId(999_999_999),
65 exitCode: versionProbe ? Effect.succeed(ChildProcessSpawner.ExitCode(0)) : Effect.never,
66 exitStatus: versionProbe
67 ? Effect.succeed({ _tag: "Exited", code: ChildProcessSpawner.ExitCode(0) })
68 : Effect.never,
69 isRunning: Effect.succeed(true),
70 kill: () => Effect.void,
71 unref: Effect.succeed(Effect.void),
72 stdin: Sink.forEach(onStdin),
73 stdout: versionProbe
74 ? Stream.make(new TextEncoder().encode(version))
75 : Stream.fromQueue(stdout),
76 stderr: Stream.empty,
77 all: Stream.empty,
78 getInputFd: () => Sink.drain,
79 getOutputFd: () => Stream.empty,
80 }),
81 );
82 });
83 return { spawner, received };
84 });
85​
86it.effect("runs Pi offline, since the process is stopped as soon as it answers", () =>
87 Effect.gen(function* () {
88 const pi = yield* makeFakePi(JSON.stringify({ subject: "Update README", body: "" }));
89 const launches: Array<ReadonlyArray<string>> = [];
90 const spawner = ChildProcessSpawner.make((command) => {
91 if (ChildProcess.isStandardCommand(command)) launches.push(command.args.map(String));
92 return pi.spawner.spawn(command);
93 });
94 const textGeneration = yield* makePiTextGeneration(
95 { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] },
96 {},
97 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
98​
99 const result = yield* textGeneration.generateCommitMessage({
100 cwd: process.cwd(),
101 branch: "main",
102 stagedSummary: "M README.md",
103 stagedPatch: "diff --git a/README.md b/README.md",
104 modelSelection: createModelSelection(ProviderInstanceId.make("pi"), "default"),
105 });
106​
107 assert.equal(result.subject, "Update README");
108 assert.deepEqual(
109 launches.map((args) => args.filter((arg) => arg === "--offline")),
110 [["--offline"]],
111 );
112 }),
113);
114​
115it.effect("names the model and the disabled extensions when Pi cannot load it", () =>
116 Effect.gen(function* () {
117 const pi = yield* makeFakePi("", "Model not found: demo/demo-model");
118 const textGeneration = yield* makePiTextGeneration(
119 { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] },
120 {},
121 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, pi.spawner));
122​
123 const error = yield* textGeneration
124 .generateCommitMessage({
125 cwd: process.cwd(),
126 branch: "main",
127 stagedSummary: "M README.md",
128 stagedPatch: "diff --git a/README.md b/README.md",
129 modelSelection: createModelSelection(ProviderInstanceId.make("pi"), "demo/demo-model"),
130 })
131 .pipe(Effect.flip);
132​
133 assert.equal(error._tag, "TextGenerationError");
134 assert.include(error.detail, "Pi rejected model 'demo/demo-model'");
135 assert.include(error.detail, "Model not found: demo/demo-model");
136 assert.include(error.detail, "--no-extensions");
137 assert.isUndefined(pi.received.find((record) => record["type"] === "prompt"));
138 }),
139);
140​
141it.effect("selects the provider and id Pi reported when the provider contains a slash", () =>
142 Effect.gen(function* () {
143 const provider = "llama-server=http://127.0.0.1:8080";
144 const pi = yield* makeFakePi(
145 JSON.stringify({ subject: "Update README", body: "" }),
146 undefined,
147 [],
148 [{ provider, id: "qwen3" }],
149 );
150 const textGeneration = yield* makePiTextGeneration(
151 { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] },
152 {},
153 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, pi.spawner));
154​
155 yield* textGeneration.generateCommitMessage({
156 cwd: process.cwd(),
157 branch: "main",
158 stagedSummary: "M README.md",
159 stagedPatch: "diff --git a/README.md b/README.md",
160 modelSelection: createModelSelection(ProviderInstanceId.make("pi"), `${provider}/qwen3`),
161 });
162​
163 const setModel = pi.received.find((record) => record["type"] === "set_model");
164 assert.deepEqual(
165 { provider: setModel?.["provider"], modelId: setModel?.["modelId"] },
166 { provider, modelId: "qwen3" },
167 );
168 }),
169);
170​
171const failedTurnWith = (errorMessage: string) => ({
172 type: "message_end",
173 message: { role: "assistant", stopReason: "error", errorMessage },
174});
175​
176const failedTurn = failedTurnWith(
177 '401: {"error":{"message":"Incorrect API key provided: sk-test-SECRET123"}}',
178);
179​
180const generateCommitMessage = (turnEvents: ReadonlyArray<Record<string, unknown>>, reply = "") =>
181 Effect.gen(function* () {
182 const pi = yield* makeFakePi(reply, undefined, turnEvents);
183 const textGeneration = yield* makePiTextGeneration(
184 { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] },
185 {},
186 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, pi.spawner));
187 return yield* textGeneration.generateCommitMessage({
188 cwd: process.cwd(),
189 branch: "main",
190 stagedSummary: "M README.md",
191 stagedPatch: "diff --git a/README.md b/README.md",
192 modelSelection: createModelSelection(ProviderInstanceId.make("pi"), "default"),
193 });
194 });
195​
196it.effect("reports Pi's turn error when the reply is empty", () =>
197 Effect.gen(function* () {
198 const error = yield* generateCommitMessage([failedTurn]).pipe(Effect.flip);
199​
200 assert.equal(error._tag, "TextGenerationError");
201 assert.equal(error.detail, "Pi could not generate text: the model provider returned HTTP 401.");
202 }),
203);
204​
205it.effect("reports a provider failure when Pi has already streamed valid commit text", () =>
206 Effect.gen(function* () {
207 const reply = JSON.stringify({ subject: "Update README", body: "" });
208 const result = yield* generateCommitMessage(
209 [
210 {
211 type: "message_end",
212 message: {
213 role: "assistant",
214 content: [{ type: "text", text: reply }],
215 stopReason: "error",
216 errorMessage: "Stream ended without finish_reason",
217 },
218 },
219 ],
220 reply,
221 ).pipe(Effect.result);
222​
223 assert.equal(result._tag, "Failure");
224 if (result._tag === "Failure") {
225 assert.equal(
226 result.failure.detail,
227 "Pi could not generate text: the model provider reported an error.",
228 );
229 }
230 }),
231);
232​
233it.effect("keeps Pi's raw error text out of the error", () =>
234 Effect.gen(function* () {
235 const error = yield* generateCommitMessage([
236 failedTurnWith("Invalid API key sk-test-SECRET123"),
237 ]).pipe(Effect.flip);
238​
239 assert.equal(error.detail, "Pi could not generate text: the model provider reported an error.");
240 assert.notInclude(error.message, "SECRET123");
241 }),
242);
243​
244it.effect("keeps the reply when Pi answers after a failed attempt", () =>
245 Effect.gen(function* () {
246 const result = yield* generateCommitMessage(
247 [failedTurn, { type: "message_end", message: { role: "assistant", stopReason: "stop" } }],
248 JSON.stringify({ subject: "Update README", body: "" }),
249 );
250​
251 assert.equal(result.subject, "Update README");
252 }),
253);
254​
255it.effect("drops an earlier error once a later attempt succeeds", () =>
256 Effect.gen(function* () {
257 const error = yield* generateCommitMessage([
258 failedTurn,
259 { type: "message_end", message: { role: "assistant", stopReason: "stop" } },
260 ]).pipe(Effect.flip);
261​
262 assert.equal(error.detail, "Pi returned empty output.");
263 }),
264);
265​
266it.effect.each([
267 { model: "demo/demo-model", thinking: "off", expected: "off", version: "0.84.3" },
268 { model: "demo/demo-model", thinking: "max", expected: "max", version: "1.4.0" },
269 { model: "demo/demo-model", thinking: "invalid", expected: undefined, version: "0.84.3" },
270 { model: "demo/demo-model", thinking: undefined, expected: undefined, version: "0.84.3" },
271 { model: "default", thinking: "off", expected: "off", version: "0.84.3" },
272 { model: "demo/demo-model", thinking: "low", expected: undefined, version: "0.84.2" },
273])(
274 "handles thinking=$thinking for $model on Pi $version",
275 ({ model, thinking, expected, version }) =>
276 Effect.gen(function* () {
277 const pi = yield* makeFakePi(
278 JSON.stringify({ subject: "Update README", body: "" }),
279 undefined,
280 [],
281 undefined,
282 version,
283 );
284 const textGeneration = yield* makePiTextGeneration(
285 { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] },
286 {},
287 (_driver, detected) =>
288 Effect.succeed(
289 detected === "0.84.2"
290 ? {
291 status: "broken" as const,
292 message: null,
293 recommendedVersion: null,
294 recommendedRange: ">=1.0.0",
295 }
296 : undefined,
297 ),
298 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, pi.spawner));
299​
300 const generation = textGeneration.generateCommitMessage({
301 cwd: process.cwd(),
302 branch: "main",
303 stagedSummary: "M README.md",
304 stagedPatch: "diff --git a/README.md b/README.md",
305 modelSelection: createModelSelection(
306 ProviderInstanceId.make("pi"),
307 model,
308 thinking === undefined ? [] : [{ id: "thinking", value: thinking }],
309 ),
310 });
311 if (version === "0.84.2") {
312 const error = yield* generation.pipe(Effect.flip);
313 assert.include(error.detail, "Pi 0.84.2 does not work");
314 assert.deepEqual(pi.received, []);
315 return;
316 }
317 const result = yield* generation;
318​
319 assert.equal(result.subject, "Update README");
320 assert.deepEqual(
321 pi.received.map((record) => record["type"]),
322 [
323 ...(model === "default" ? [] : ["get_available_models", "set_model"]),
324 ...(expected === undefined ? [] : ["set_thinking_level"]),
325 "prompt",
326 "get_last_assistant_text",
327 ],
328 );
329 assert.equal(
330 pi.received.find((record) => record["type"] === "set_thinking_level")?.["level"],
331 expected,
332 );
333 }),
334);
335​
336it.effect("generates at Pi's default level when Pi rejects the saved thinking level", () =>
337 Effect.gen(function* () {
338 const pi = yield* makeFakePi(
339 JSON.stringify({ subject: "Update README", body: "" }),
340 undefined,
341 [],
342 undefined,
343 "1.4.0",
344 'Thinking level "max" is not supported by demo/demo-model',
345 );
346 const textGeneration = yield* makePiTextGeneration(
347 { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] },
348 {},
349 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, pi.spawner));
350​
351 const result = yield* textGeneration.generateCommitMessage({
352 cwd: process.cwd(),
353 branch: "main",
354 stagedSummary: "M README.md",
355 stagedPatch: "diff --git a/README.md b/README.md",
356 modelSelection: createModelSelection(ProviderInstanceId.make("pi"), "demo/demo-model", [
357 { id: "thinking", value: "max" },
358 ]),
359 });
360​
361 assert.equal(result.subject, "Update README");
362 assert.deepEqual(
363 pi.received.map((record) => record["type"]),
364 [
365 "get_available_models",
366 "set_model",
367 "set_thinking_level",
368 "prompt",
369 "get_last_assistant_text",
370 ],
371 );
372 }),
373);