Open History to see the last commit
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 isRunning: Effect.succeed(true),
67 kill: () => Effect.void,
68 unref: Effect.succeed(Effect.void),
69 stdin: Sink.forEach(onStdin),
70 stdout: versionProbe
71 ? Stream.make(new TextEncoder().encode(version))
72 : Stream.fromQueue(stdout),
73 stderr: Stream.empty,
74 all: Stream.empty,
75 getInputFd: () => Sink.drain,
76 getOutputFd: () => Stream.empty,
77 }),
78 );
79 });
80 return { spawner, received };
81 });
82
83it.effect("runs Pi offline, since the process is stopped as soon as it answers", () =>
84 Effect.gen(function* () {
85 const pi = yield* makeFakePi(JSON.stringify({ subject: "Update README", body: "" }));
86 const launches: Array<ReadonlyArray<string>> = [];
87 const spawner = ChildProcessSpawner.make((command) => {
88 if (ChildProcess.isStandardCommand(command)) launches.push(command.args.map(String));
89 return pi.spawner.spawn(command);
90 });
91 const textGeneration = yield* makePiTextGeneration(
92 { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] },
93 {},
94 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
95
96 const result = yield* textGeneration.generateCommitMessage({
97 cwd: process.cwd(),
98 branch: "main",
99 stagedSummary: "M README.md",
100 stagedPatch: "diff --git a/README.md b/README.md",
101 modelSelection: createModelSelection(ProviderInstanceId.make("pi"), "default"),
102 });
103
104 assert.equal(result.subject, "Update README");
105 assert.deepEqual(
106 launches.map((args) => args.filter((arg) => arg === "--offline")),
107 [["--offline"]],
108 );
109 }),
110);
111
112it.effect("names the model and the disabled extensions when Pi cannot load it", () =>
113 Effect.gen(function* () {
114 const pi = yield* makeFakePi("", "Model not found: demo/demo-model");
115 const textGeneration = yield* makePiTextGeneration(
116 { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] },
117 {},
118 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, pi.spawner));
119
120 const error = yield* textGeneration
121 .generateCommitMessage({
122 cwd: process.cwd(),
123 branch: "main",
124 stagedSummary: "M README.md",
125 stagedPatch: "diff --git a/README.md b/README.md",
126 modelSelection: createModelSelection(ProviderInstanceId.make("pi"), "demo/demo-model"),
127 })
128 .pipe(Effect.flip);
129
130 assert.equal(error._tag, "TextGenerationError");
131 assert.include(error.detail, "Pi rejected model 'demo/demo-model'");
132 assert.include(error.detail, "Model not found: demo/demo-model");
133 assert.include(error.detail, "--no-extensions");
134 assert.isUndefined(pi.received.find((record) => record["type"] === "prompt"));
135 }),
136);
137
138it.effect("selects the provider and id Pi reported when the provider contains a slash", () =>
139 Effect.gen(function* () {
140 const provider = "llama-server=http://127.0.0.1:8080";
141 const pi = yield* makeFakePi(
142 JSON.stringify({ subject: "Update README", body: "" }),
143 undefined,
144 [],
145 [{ provider, id: "qwen3" }],
146 );
147 const textGeneration = yield* makePiTextGeneration(
148 { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] },
149 {},
150 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, pi.spawner));
151
152 yield* textGeneration.generateCommitMessage({
153 cwd: process.cwd(),
154 branch: "main",
155 stagedSummary: "M README.md",
156 stagedPatch: "diff --git a/README.md b/README.md",
157 modelSelection: createModelSelection(ProviderInstanceId.make("pi"), `${provider}/qwen3`),
158 });
159
160 const setModel = pi.received.find((record) => record["type"] === "set_model");
161 assert.deepEqual(
162 { provider: setModel?.["provider"], modelId: setModel?.["modelId"] },
163 { provider, modelId: "qwen3" },
164 );
165 }),
166);
167
168const failedTurnWith = (errorMessage: string) => ({
169 type: "message_end",
170 message: { role: "assistant", stopReason: "error", errorMessage },
171});
172
173const failedTurn = failedTurnWith(
174 '401: {"error":{"message":"Incorrect API key provided: sk-test-SECRET123"}}',
175);
176
177const generateCommitMessage = (turnEvents: ReadonlyArray<Record<string, unknown>>, reply = "") =>
178 Effect.gen(function* () {
179 const pi = yield* makeFakePi(reply, undefined, turnEvents);
180 const textGeneration = yield* makePiTextGeneration(
181 { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] },
182 {},
183 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, pi.spawner));
184 return yield* textGeneration.generateCommitMessage({
185 cwd: process.cwd(),
186 branch: "main",
187 stagedSummary: "M README.md",
188 stagedPatch: "diff --git a/README.md b/README.md",
189 modelSelection: createModelSelection(ProviderInstanceId.make("pi"), "default"),
190 });
191 });
192
193it.effect("reports Pi's turn error when the reply is empty", () =>
194 Effect.gen(function* () {
195 const error = yield* generateCommitMessage([failedTurn]).pipe(Effect.flip);
196
197 assert.equal(error._tag, "TextGenerationError");
198 assert.equal(error.detail, "Pi could not generate text: the model provider returned HTTP 401.");
199 }),
200);
201
202it.effect("reports a provider failure when Pi has already streamed valid commit text", () =>
203 Effect.gen(function* () {
204 const reply = JSON.stringify({ subject: "Update README", body: "" });
205 const result = yield* generateCommitMessage(
206 [
207 {
208 type: "message_end",
209 message: {
210 role: "assistant",
211 content: [{ type: "text", text: reply }],
212 stopReason: "error",
213 errorMessage: "Stream ended without finish_reason",
214 },
215 },
216 ],
217 reply,
218 ).pipe(Effect.result);
219
220 assert.equal(result._tag, "Failure");
221 if (result._tag === "Failure") {
222 assert.equal(
223 result.failure.detail,
224 "Pi could not generate text: the model provider reported an error.",
225 );
226 }
227 }),
228);
229
230it.effect("keeps Pi's raw error text out of the error", () =>
231 Effect.gen(function* () {
232 const error = yield* generateCommitMessage([
233 failedTurnWith("Invalid API key sk-test-SECRET123"),
234 ]).pipe(Effect.flip);
235
236 assert.equal(error.detail, "Pi could not generate text: the model provider reported an error.");
237 assert.notInclude(error.message, "SECRET123");
238 }),
239);
240
241it.effect("keeps the reply when Pi answers after a failed attempt", () =>
242 Effect.gen(function* () {
243 const result = yield* generateCommitMessage(
244 [failedTurn, { type: "message_end", message: { role: "assistant", stopReason: "stop" } }],
245 JSON.stringify({ subject: "Update README", body: "" }),
246 );
247
248 assert.equal(result.subject, "Update README");
249 }),
250);
251
252it.effect("drops an earlier error once a later attempt succeeds", () =>
253 Effect.gen(function* () {
254 const error = yield* generateCommitMessage([
255 failedTurn,
256 { type: "message_end", message: { role: "assistant", stopReason: "stop" } },
257 ]).pipe(Effect.flip);
258
259 assert.equal(error.detail, "Pi returned empty output.");
260 }),
261);
262
263it.effect.each([
264 { model: "demo/demo-model", thinking: "off", expected: "off", version: "0.84.3" },
265 { model: "demo/demo-model", thinking: "max", expected: "max", version: "1.4.0" },
266 { model: "demo/demo-model", thinking: "invalid", expected: undefined, version: "0.84.3" },
267 { model: "demo/demo-model", thinking: undefined, expected: undefined, version: "0.84.3" },
268 { model: "default", thinking: "off", expected: "off", version: "0.84.3" },
269 { model: "demo/demo-model", thinking: "low", expected: undefined, version: "0.84.2" },
270])(
271 "handles thinking=$thinking for $model on Pi $version",
272 ({ model, thinking, expected, version }) =>
273 Effect.gen(function* () {
274 const pi = yield* makeFakePi(
275 JSON.stringify({ subject: "Update README", body: "" }),
276 undefined,
277 [],
278 undefined,
279 version,
280 );
281 const textGeneration = yield* makePiTextGeneration(
282 { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] },
283 {},
284 (_driver, detected) =>
285 Effect.succeed(
286 detected === "0.84.2"
287 ? {
288 status: "broken" as const,
289 message: null,
290 recommendedVersion: null,
291 recommendedRange: ">=1.0.0",
292 }
293 : undefined,
294 ),
295 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, pi.spawner));
296
297 const generation = textGeneration.generateCommitMessage({
298 cwd: process.cwd(),
299 branch: "main",
300 stagedSummary: "M README.md",
301 stagedPatch: "diff --git a/README.md b/README.md",
302 modelSelection: createModelSelection(
303 ProviderInstanceId.make("pi"),
304 model,
305 thinking === undefined ? [] : [{ id: "thinking", value: thinking }],
306 ),
307 });
308 if (version === "0.84.2") {
309 const error = yield* generation.pipe(Effect.flip);
310 assert.include(error.detail, "Pi 0.84.2 does not work");
311 assert.deepEqual(pi.received, []);
312 return;
313 }
314 const result = yield* generation;
315
316 assert.equal(result.subject, "Update README");
317 assert.deepEqual(
318 pi.received.map((record) => record["type"]),
319 [
320 ...(model === "default" ? [] : ["get_available_models", "set_model"]),
321 ...(expected === undefined ? [] : ["set_thinking_level"]),
322 "prompt",
323 "get_last_assistant_text",
324 ],
325 );
326 assert.equal(
327 pi.received.find((record) => record["type"] === "set_thinking_level")?.["level"],
328 expected,
329 );
330 }),
331);
332
333it.effect("generates at Pi's default level when Pi rejects the saved thinking level", () =>
334 Effect.gen(function* () {
335 const pi = yield* makeFakePi(
336 JSON.stringify({ subject: "Update README", body: "" }),
337 undefined,
338 [],
339 undefined,
340 "1.4.0",
341 'Thinking level "max" is not supported by demo/demo-model',
342 );
343 const textGeneration = yield* makePiTextGeneration(
344 { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] },
345 {},
346 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, pi.spawner));
347
348 const result = yield* textGeneration.generateCommitMessage({
349 cwd: process.cwd(),
350 branch: "main",
351 stagedSummary: "M README.md",
352 stagedPatch: "diff --git a/README.md b/README.md",
353 modelSelection: createModelSelection(ProviderInstanceId.make("pi"), "demo/demo-model", [
354 { id: "thinking", value: "max" },
355 ]),
356 });
357
358 assert.equal(result.subject, "Update README");
359 assert.deepEqual(
360 pi.received.map((record) => record["type"]),
361 [
362 "get_available_models",
363 "set_model",
364 "set_thinking_level",
365 "prompt",
366 "get_last_assistant_text",
367 ],
368 );
369 }),
370);