Open History to see the last commit
1import * as NodeAssert from "node:assert/strict";
2
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { PiSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
5import { createModelSelection } from "@t3tools/shared/model";
6import { it } from "@effect/vitest";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as Queue from "effect/Queue";
10import * as Schema from "effect/Schema";
11import * as Stream from "effect/Stream";
12import * as TestClock from "effect/testing/TestClock";
13
14import {
15 PiRpcCommandError,
16 type PiRpcClient,
17 type PiRpcSpawnOptions,
18} from "../provider/pi/PiRpcClient.ts";
19import type { PiRpcEvent, PiThinkingLevel } from "../provider/pi/PiRpcSchema.ts";
20import { makePiTextGeneration } from "./PiTextGeneration.ts";
21
22const assert: typeof NodeAssert = NodeAssert;
23
24class FakeClient implements PiRpcClient {
25 // oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- The synchronous fake exposes its queue through the PiRpcClient stream interface.
26 readonly queue = Effect.runSync(Queue.unbounded<PiRpcEvent>());
27 readonly events = Stream.fromQueue(this.queue);
28 readonly models: Array<[string, string]> = [];
29 readonly thinking: PiThinkingLevel[] = [];
30 closeCalls = 0;
31 failPrompt = false;
32 settle = true;
33 shutdownAfterPrompt = false;
34 promptEvents: PiRpcEvent[] | undefined;
35 output = '{"subject":"Ship Pi generation","body":"Use RPC output."}';
36 getState = () => Effect.succeed({});
37 getAvailableModels = () => Effect.succeed({ models: [] });
38 getCommands = () => Effect.succeed({ commands: [] });
39 setModel = (provider: string, modelId: string) =>
40 Effect.sync(() => {
41 this.models.push([provider, modelId]);
42 return { provider, id: modelId };
43 });
44 setThinkingLevel = (level: PiThinkingLevel) =>
45 Effect.sync(() => {
46 this.thinking.push(level);
47 });
48 prompt = () => {
49 const self = this;
50 return self.failPrompt
51 ? Effect.fail(
52 new PiRpcCommandError({ command: "prompt", requestId: "test", detail: "prompt failed" }),
53 )
54 : Effect.gen(function* () {
55 yield* Queue.offerAll(
56 self.queue,
57 self.promptEvents ?? [
58 {
59 type: "message_update",
60 assistantMessageEvent: { type: "text_delta", delta: `preface ${self.output}` },
61 },
62 {
63 type: "message_end",
64 message: { role: "assistant", content: [{ type: "text", text: self.output }] },
65 },
66 ...(self.settle ? [{ type: "agent_settled" }] : []),
67 ],
68 );
69 if (self.shutdownAfterPrompt) yield* Queue.shutdown(self.queue);
70 });
71 };
72 abort = () => Effect.void;
73 respondToExtensionUi = () => Effect.void;
74 close = () =>
75 Effect.sync(() => {
76 this.closeCalls += 1;
77 });
78}
79
80const settings = Schema.decodeSync(PiSettings)({ binaryPath: "fake-pi" });
81const selection = createModelSelection(ProviderInstanceId.make("pi-test"), "openai%20api/gpt%2F5", [
82 { id: "thinkingLevel", value: "high" },
83]);
84const input = {
85 cwd: "/tmp/pi-generation",
86 branch: "feature/pi",
87 stagedSummary: "M pi.ts",
88 stagedPatch: "diff --git a/pi.ts b/pi.ts",
89 modelSelection: selection,
90};
91
92const makeHarness = (client: FakeClient, spawns: PiRpcSpawnOptions[], timeoutMs?: number) =>
93 Effect.scoped(
94 Effect.gen(function* () {
95 const textGeneration = yield* makePiTextGeneration(
96 settings,
97 { PI_TOKEN: "test" },
98 (options) =>
99 Effect.acquireRelease(
100 Effect.sync(() => {
101 spawns.push(options);
102 return client;
103 }),
104 (opened) => opened.close(),
105 ),
106 timeoutMs === undefined ? {} : { timeoutMs },
107 );
108 return yield* textGeneration.generateCommitMessage(input);
109 }),
110 ).pipe(Effect.provide(NodeServices.layer));
111
112it.effect("selects the decoded model and thinking level, then parses assistant text", () => {
113 const client = new FakeClient();
114 const spawns: PiRpcSpawnOptions[] = [];
115 return Effect.gen(function* () {
116 const result = yield* makeHarness(client, spawns);
117
118 assert.deepEqual(result, { subject: "Ship Pi generation", body: "Use RPC output." });
119 assert.deepEqual(client.models, [["openai api", "gpt/5"]]);
120 assert.deepEqual(client.thinking, ["high"]);
121 assert.equal(spawns[0]?.cwd, input.cwd);
122 assert.equal(spawns[0]?.env?.PI_TOKEN, "test");
123 assert.equal(spawns[0]?.args?.includes("--no-session"), true);
124 for (const arg of [
125 "--no-context-files",
126 "--no-extensions",
127 "--no-skills",
128 "--no-prompt-templates",
129 ])
130 assert.equal(spawns[0]?.args?.includes(arg), false);
131 assert.equal(client.closeCalls, 1);
132 });
133});
134
135it.effect("closes the RPC client when generation fails", () => {
136 const client = new FakeClient();
137 client.failPrompt = true;
138 return Effect.gen(function* () {
139 const result = yield* makeHarness(client, []).pipe(Effect.result);
140
141 assert.equal(result._tag, "Failure");
142 if (result._tag === "Failure")
143 assert.equal(Schema.is(TextGenerationError)(result.failure), true);
144 assert.equal(client.closeCalls, 1);
145 });
146});
147
148it.effect("uses only the last completed assistant message across attempts", () => {
149 const client = new FakeClient();
150 client.promptEvents = [
151 {
152 type: "message_end",
153 message: {
154 role: "assistant",
155 content: [{ type: "text", text: '{"subject":"Stale","body":"old"}' }],
156 },
157 },
158 {
159 type: "message_end",
160 message: {
161 role: "assistant",
162 content: [{ type: "text", text: '{"subject":"Final","body":"correct"}' }],
163 },
164 },
165 { type: "agent_settled" },
166 ];
167 return Effect.gen(function* () {
168 const result = yield* makeHarness(client, []);
169 assert.deepEqual(result, { subject: "Final", body: "correct" });
170 });
171});
172
173it.effect("fails and closes when the event stream ends before agent settlement", () => {
174 const client = new FakeClient();
175 client.settle = false;
176 client.shutdownAfterPrompt = true;
177 return Effect.gen(function* () {
178 const result = yield* makeHarness(client, []).pipe(Effect.result);
179 assert.equal(result._tag, "Failure");
180 if (result._tag === "Failure") {
181 assert.equal(Schema.is(TextGenerationError)(result.failure), true);
182 assert.match(result.failure.detail, /stream ended/);
183 }
184 assert.equal(client.closeCalls, 1);
185 });
186});
187
188it.effect("fails and closes once after the overall timeout", () => {
189 const client = new FakeClient();
190 client.settle = false;
191 client.promptEvents = [];
192 return Effect.gen(function* () {
193 const fiber = yield* makeHarness(client, [], 1_000).pipe(Effect.result, Effect.forkChild);
194 yield* Effect.yieldNow;
195 yield* TestClock.adjust("1 second");
196 const result = yield* Fiber.join(fiber);
197 assert.equal(result._tag, "Failure");
198 if (result._tag === "Failure") assert.match(result.failure.detail, /timed out/);
199 assert.equal(client.closeCalls, 1);
200 });
201});
202
203it.effect("rejects an aborted final assistant message", () => {
204 const client = new FakeClient();
205 client.promptEvents = [
206 {
207 type: "message_end",
208 message: { role: "assistant", content: [], stopReason: "aborted" },
209 },
210 ];
211 return Effect.gen(function* () {
212 const result = yield* makeHarness(client, []).pipe(Effect.result);
213 assert.equal(result._tag, "Failure");
214 if (result._tag === "Failure") assert.match(result.failure.detail, /aborted/);
215 assert.equal(client.closeCalls, 1);
216 });
217});