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

PiTextGeneration.test.ts

257 lines9.6 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFSP from "node:fs/promises";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5​
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import { it } from "@effect/vitest";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Result from "effect/Result";
13import * as Schema from "effect/Schema";
14import { createModelSelection } from "@t3tools/shared/model";
15import { expect } from "vite-plus/test";
16​
17import { PiSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
18​
19import * as ServerConfig from "../config.ts";
20import { makePiTextGeneration } from "./PiTextGeneration.ts";
21import { type TextGenerationShape } from "./TextGeneration.ts";
22​
23const decodePiSettings = Schema.decodeSync(PiSettings);
24const MOCK_PATH = NodePath.join(__dirname, "../../scripts/pi-mock-rpc.ts");
25​
26const DEFAULT_TEST_MODEL_SELECTION = createModelSelection(
27 ProviderInstanceId.make("pi"),
28 "anthropic/claude-sonnet-4-6",
29);
30​
31const PiTextGenerationTestLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
32 prefix: "t3code-pi-text-generation-test-",
33}).pipe(Layer.provideMerge(NodeServices.layer));
34​
35// shell wrapper that execs the JSONL mock via node; `PI_MOCK_*` env drives behavior
36async function makePiWrapper(): Promise<string> {
37 const dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "pi-textgen-mock-"));
38 const wrapperPath = NodePath.join(dir, "fake-pi.sh");
39 const script = `#!/bin/sh\nexec ${JSON.stringify(process.execPath)} ${JSON.stringify(MOCK_PATH)} "$@"\n`;
40 await NodeFSP.writeFile(wrapperPath, script, "utf8");
41 await NodeFSP.chmod(wrapperPath, 0o755);
42 return wrapperPath;
44​
45const withFakePi = <A, E, R>(
46 mockEnv: Record<string, string>,
47 use: (textGeneration: TextGenerationShape) => Effect.Effect<A, E, R>,
48) =>
49 Effect.gen(function* () {
50 const wrapperPath = yield* Effect.promise(() => makePiWrapper());
51 const settings = decodePiSettings({ binaryPath: wrapperPath });
52 const environment: NodeJS.ProcessEnv = { ...process.env, ...mockEnv };
53 const textGeneration = yield* makePiTextGeneration(settings, environment);
54 return yield* use(textGeneration);
55 });
56​
57it.effect("generateThreadTitle parses the JSON returned via get_last_assistant_text", () =>
58 withFakePi(
59 { PI_MOCK_ASSISTANT_TEXT: '{"title":"Investigate reconnect regressions"}' },
60 (textGeneration) =>
61 Effect.gen(function* () {
62 const result = yield* textGeneration.generateThreadTitle({
63 cwd: process.cwd(),
64 message: "look into reconnect bugs",
65 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
66 });
67 expect(result.title).toBe("Investigate reconnect regressions");
68 }),
69 ).pipe(Effect.provide(PiTextGenerationTestLayer)),
70);
71​
72it.effect("waits for the terminal agent_end when Pi retries", () =>
73 withFakePi(
74 {
75 PI_MOCK_ASSISTANT_TEXT: '{"title":"Recovered after retry"}',
76 PI_MOCK_RETRY_ONCE: "1",
77 },
78 (textGeneration) =>
79 Effect.gen(function* () {
80 const result = yield* textGeneration.generateThreadTitle({
81 cwd: process.cwd(),
82 message: "retry this request",
83 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
84 });
85 expect(result.title).toBe("Recovered after retry");
86 }),
87 ).pipe(Effect.provide(PiTextGenerationTestLayer)),
88);
89​
90it.effect("sends persisted image bytes with Pi text-generation prompts", () => {
91 const imageBytes = Buffer.from("pi-image-bytes");
92 return withFakePi(
93 {
94 PI_MOCK_ASSISTANT_TEXT: '{"title":"Screenshot regression"}',
95 PI_MOCK_REQUIRE_IMAGE: "1",
96 PI_MOCK_EXPECT_IMAGE_DATA: imageBytes.toString("base64"),
97 },
98 (textGeneration) =>
99 Effect.gen(function* () {
100 const fileSystem = yield* FileSystem.FileSystem;
101 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
102 const attachmentId = "pi-thread-image-attachment";
103 const attachmentPath = NodePath.join(attachmentsDir, `${attachmentId}.png`);
104 yield* fileSystem.writeFile(attachmentPath, imageBytes);
105​
106 const result = yield* textGeneration
107 .generateThreadTitle({
108 cwd: process.cwd(),
109 message: "Name this screenshot regression",
110 attachments: [
111 {
112 type: "image",
113 id: attachmentId,
114 name: "regression.png",
115 mimeType: "image/png",
116 sizeBytes: imageBytes.byteLength,
117 },
118 ],
119 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
120 })
121 .pipe(
122 Effect.ensuring(
123 fileSystem.remove(attachmentPath).pipe(Effect.catch(() => Effect.void)),
124 ),
125 );
126​
127 expect(result.title).toBe("Screenshot regression");
128 }),
129 ).pipe(Effect.provide(PiTextGenerationTestLayer));
130});
131​
132it.effect("generateCommitMessage sanitizes subject and trims body", () =>
133 withFakePi(
134 { PI_MOCK_ASSISTANT_TEXT: '{"subject":"Add reconnect handling.","body":"- detail\\n"}' },
135 (textGeneration) =>
136 Effect.gen(function* () {
137 const result = yield* textGeneration.generateCommitMessage({
138 cwd: process.cwd(),
139 branch: "feature/pi",
140 stagedSummary: "M file.ts",
141 stagedPatch: "@@ -1 +1 @@\n-old\n+new\n",
142 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
143 });
144 expect(result.subject).toBe("Add reconnect handling");
145 expect(result.body).toBe("- detail");
146 expect(result).not.toHaveProperty("branch");
147 }),
148 ).pipe(Effect.provide(PiTextGenerationTestLayer)),
149);
150​
151it.effect("generateBranchName sanitizes the branch fragment", () =>
152 withFakePi({ PI_MOCK_ASSISTANT_TEXT: '{"branch":" Feat/Session "}' }, (textGeneration) =>
153 Effect.gen(function* () {
154 const result = yield* textGeneration.generateBranchName({
155 cwd: process.cwd(),
156 message: "please update session handling",
157 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
158 });
159 expect(result.branch).toBe("feat/session");
160 }),
161 ).pipe(Effect.provide(PiTextGenerationTestLayer)),
162);
163​
164it.effect("generatePrContent sanitizes title and body", () =>
165 withFakePi(
166 {
167 PI_MOCK_ASSISTANT_TEXT: '{"title":"Improve reconnect flow","body":"## Summary\\n- x\\n\\n"}',
168 },
169 (textGeneration) =>
170 Effect.gen(function* () {
171 const result = yield* textGeneration.generatePrContent({
172 cwd: process.cwd(),
173 baseBranch: "main",
174 headBranch: "feature/pi",
175 commitSummary: "one commit",
176 diffSummary: "file.ts | 2 +-",
177 diffPatch: "@@ -1 +1 @@\n-old\n+new\n",
178 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
179 });
180 expect(result.title).toBe("Improve reconnect flow");
181 expect(result.body).toBe("## Summary\n- x");
182 }),
183 ).pipe(Effect.provide(PiTextGenerationTestLayer)),
184);
185​
186it.effect("tolerates JSON wrapped in a markdown code fence", () =>
187 withFakePi({ PI_MOCK_ASSISTANT_TEXT: '```json {"title":"Fenced title"} ```' }, (textGeneration) =>
188 Effect.gen(function* () {
189 const result = yield* textGeneration.generateThreadTitle({
190 cwd: process.cwd(),
191 message: "anything",
192 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
193 });
194 expect(result.title).toBe("Fenced title");
195 }),
196 ).pipe(Effect.provide(PiTextGenerationTestLayer)),
197);
198​
199it.effect("fails with a TextGenerationError when Pi returns non-JSON prose", () =>
200 withFakePi({ PI_MOCK_EMIT_INVALID_JSON: "1" }, (textGeneration) =>
201 Effect.gen(function* () {
202 const result = yield* textGeneration
203 .generateThreadTitle({
204 cwd: process.cwd(),
205 message: "anything",
206 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
207 })
208 .pipe(Effect.result);
209 expect(Result.isFailure(result)).toBe(true);
210 if (Result.isFailure(result)) {
211 expect(result.failure).toBeInstanceOf(TextGenerationError);
212 expect(result.failure.message).toContain("invalid structured output");
213 }
214 }),
215 ).pipe(Effect.provide(PiTextGenerationTestLayer)),
216);
217​
218it.effect("fails with a TextGenerationError when the assistant text is unavailable", () =>
219 withFakePi({ PI_MOCK_LAST_TEXT_FAILS: "1" }, (textGeneration) =>
220 Effect.gen(function* () {
221 const result = yield* textGeneration
222 .generateThreadTitle({
223 cwd: process.cwd(),
224 message: "anything",
225 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
226 })
227 .pipe(Effect.result);
228 expect(Result.isFailure(result)).toBe(true);
229 if (Result.isFailure(result)) {
230 expect(result.failure).toBeInstanceOf(TextGenerationError);
231 }
232 }),
233 ).pipe(Effect.provide(PiTextGenerationTestLayer)),
234);
235​
236it.effect("fails quickly when Pi exits before agent_end", () =>
237 withFakePi({ PI_MOCK_EXIT_ON_PROMPT: "1" }, (textGeneration) =>
238 Effect.gen(function* () {
239 const completed = yield* textGeneration
240 .generateThreadTitle({
241 cwd: process.cwd(),
242 message: "anything",
243 modelSelection: DEFAULT_TEST_MODEL_SELECTION,
244 })
245 .pipe(Effect.result, Effect.timeoutOption(3_000));
246​
247 expect(Option.isSome(completed)).toBe(true);
248 if (Option.isSome(completed)) {
249 expect(Result.isFailure(completed.value)).toBe(true);
250 if (Result.isFailure(completed.value)) {
251 expect(completed.value.failure).toBeInstanceOf(TextGenerationError);
252 expect(completed.value.failure.message).toMatch(/process exited/i);
253 }
254 }
255 }),
256 ).pipe(Effect.provide(PiTextGenerationTestLayer)),
257);