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) =>
23 Effect.gen(function* () {
24 const stdout = yield* Queue.unbounded<Uint8Array, Cause.Done>();
25 const received: Array<Record<string, unknown>> = [];
26 const emit = (record: Record<string, unknown>) =>
27 Queue.offer(stdout, new TextEncoder().encode(`${encodeJsonLine(record)}\n`));
28 let buffered = "";
29 const onStdin = (chunk: Uint8Array) =>
30 Effect.gen(function* () {
31 buffered += new TextDecoder().decode(chunk);
32 const lines = buffered.split("\n");
33 buffered = lines.pop() ?? "";
34 for (const line of lines.filter((candidate) => candidate.length > 0)) {
35 const record = decodeJsonLine(line) as Record<string, unknown>;
36 received.push(record);
37 const response = { type: "response", id: record["id"], command: record["type"] };
38 if (record["type"] === "prompt") {
39 yield* emit({ ...response, success: true });
40 for (const event of turnEvents) yield* emit(event);
41 yield* emit({ type: "agent_settled" });
42 } else if (record["type"] === "get_last_assistant_text") {
43 yield* emit({ ...response, success: true, data: { text: reply } });
44 } else if (record["type"] === "set_model" && setModelError !== undefined) {
45 yield* emit({ ...response, success: false, error: setModelError });
46 } else {
47 yield* emit({ ...response, success: true });
48 }
49 }
50 });
51 const spawner = ChildProcessSpawner.make(() =>
52 Effect.succeed(
53 ChildProcessSpawner.makeHandle({
54 // Outside the valid pid range, so PiRpc's process-group kill never lands.
55 pid: ChildProcessSpawner.ProcessId(999_999_999),
56 exitCode: Effect.never,
57 isRunning: Effect.succeed(true),
58 kill: () => Effect.void,
59 unref: Effect.succeed(Effect.void),
60 stdin: Sink.forEach(onStdin),
61 stdout: Stream.fromQueue(stdout),
62 stderr: Stream.empty,
63 all: Stream.empty,
64 getInputFd: () => Sink.drain,
65 getOutputFd: () => Stream.empty,
66 }),
67 ),
68 );
69 return { spawner, received };
70 });
71
72it.effect("runs Pi offline, since the process is stopped as soon as it answers", () =>
73 Effect.gen(function* () {
74 const pi = yield* makeFakePi(JSON.stringify({ subject: "Update README", body: "" }));
75 const launches: Array<ReadonlyArray<string>> = [];
76 const spawner = ChildProcessSpawner.make((command) => {
77 if (ChildProcess.isStandardCommand(command)) launches.push(command.args.map(String));
78 return pi.spawner.spawn(command);
79 });
80 const textGeneration = yield* makePiTextGeneration(
81 { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] },
82 {},
83 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
84
85 const result = yield* textGeneration.generateCommitMessage({
86 cwd: process.cwd(),
87 branch: "main",
88 stagedSummary: "M README.md",
89 stagedPatch: "diff --git a/README.md b/README.md",
90 modelSelection: createModelSelection(ProviderInstanceId.make("pi"), "default"),
91 });
92
93 assert.equal(result.subject, "Update README");
94 assert.deepEqual(
95 launches.map((args) => args.filter((arg) => arg === "--offline")),
96 [["--offline"]],
97 );
98 }),
99);
100
101it.effect("names the model and the disabled extensions when Pi cannot load it", () =>
102 Effect.gen(function* () {
103 const pi = yield* makeFakePi("", "Model not found: demo/demo-model");
104 const textGeneration = yield* makePiTextGeneration(
105 { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] },
106 {},
107 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, pi.spawner));
108
109 const error = yield* textGeneration
110 .generateCommitMessage({
111 cwd: process.cwd(),
112 branch: "main",
113 stagedSummary: "M README.md",
114 stagedPatch: "diff --git a/README.md b/README.md",
115 modelSelection: createModelSelection(ProviderInstanceId.make("pi"), "demo/demo-model"),
116 })
117 .pipe(Effect.flip);
118
119 assert.equal(error._tag, "TextGenerationError");
120 assert.include(error.detail, "Pi rejected model 'demo/demo-model'");
121 assert.include(error.detail, "Model not found: demo/demo-model");
122 assert.include(error.detail, "--no-extensions");
123 assert.isUndefined(pi.received.find((record) => record["type"] === "prompt"));
124 }),
125);
126
127const failedTurnWith = (errorMessage: string) => ({
128 type: "message_end",
129 message: { role: "assistant", stopReason: "error", errorMessage },
130});
131
132const failedTurn = failedTurnWith(
133 '401: {"error":{"message":"Incorrect API key provided: sk-test-SECRET123"}}',
134);
135
136const generateCommitMessage = (turnEvents: ReadonlyArray<Record<string, unknown>>, reply = "") =>
137 Effect.gen(function* () {
138 const pi = yield* makeFakePi(reply, undefined, turnEvents);
139 const textGeneration = yield* makePiTextGeneration(
140 { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] },
141 {},
142 ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, pi.spawner));
143 return yield* textGeneration.generateCommitMessage({
144 cwd: process.cwd(),
145 branch: "main",
146 stagedSummary: "M README.md",
147 stagedPatch: "diff --git a/README.md b/README.md",
148 modelSelection: createModelSelection(ProviderInstanceId.make("pi"), "default"),
149 });
150 });
151
152it.effect("reports Pi's turn error when the reply is empty", () =>
153 Effect.gen(function* () {
154 const error = yield* generateCommitMessage([failedTurn]).pipe(Effect.flip);
155
156 assert.equal(error._tag, "TextGenerationError");
157 assert.equal(error.detail, "Pi could not generate text: the model provider returned HTTP 401.");
158 }),
159);
160
161it.effect("keeps Pi's raw error text out of the error", () =>
162 Effect.gen(function* () {
163 const error = yield* generateCommitMessage([
164 failedTurnWith("Invalid API key sk-test-SECRET123"),
165 ]).pipe(Effect.flip);
166
167 assert.equal(error.detail, "Pi could not generate text: the model provider reported an error.");
168 assert.notInclude(error.message, "SECRET123");
169 }),
170);
171
172it.effect("keeps the reply when Pi answers after a failed attempt", () =>
173 Effect.gen(function* () {
174 const result = yield* generateCommitMessage(
175 [failedTurn, { type: "message_end", message: { role: "assistant", stopReason: "stop" } }],
176 JSON.stringify({ subject: "Update README", body: "" }),
177 );
178
179 assert.equal(result.subject, "Update README");
180 }),
181);
182
183it.effect("drops an earlier error once a later attempt succeeds", () =>
184 Effect.gen(function* () {
185 const error = yield* generateCommitMessage([
186 failedTurn,
187 { type: "message_end", message: { role: "assistant", stopReason: "stop" } },
188 ]).pipe(Effect.flip);
189
190 assert.equal(error.detail, "Pi returned empty output.");
191 }),
192);