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

ClaudeTextGeneration.test.ts

439 lines15.7 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { it } from "@effect/vitest";
3import { ClaudeSettings, ProviderInstanceId } from "@t3tools/contracts";
4import { isHostWindows } from "@t3tools/shared/hostProcess";
5import { createModelSelection } from "@t3tools/shared/model";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import { expect } from "vite-plus/test";
12​
13import * as ServerConfig from "../config.ts";
14import {
15 SYNTHETIC_CLAUDE_CAPABLE_MODEL,
16 SYNTHETIC_CLAUDE_COLLIDING_ALIAS,
17 SYNTHETIC_CLAUDE_MODEL_CATALOG,
18 SYNTHETIC_CLAUDE_STANDARD_MODEL,
19 SYNTHETIC_CLAUDE_THINKING_MODEL,
20} from "../provider/ClaudeModelCatalog.testFixtures.ts";
21import * as TextGeneration from "./TextGeneration.ts";
22import { sanitizeThreadTitle } from "./TextGenerationUtils.ts";
23import { makeClaudeTextGeneration } from "./ClaudeTextGeneration.ts";
24const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
25​
26const ClaudeTextGenerationTestLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
27 prefix: "t3code-claude-text-generation-test-",
28}).pipe(Layer.provideMerge(NodeServices.layer));
29​
30function makeFakeClaudeBinary(dir: string) {
31 return Effect.gen(function* () {
32 const fs = yield* FileSystem.FileSystem;
33 const path = yield* Path.Path;
34 const isWindows = yield* isHostWindows;
35 const binDir = path.join(dir, "bin");
36 const stubPath = path.join(binDir, "claude-stub.mjs");
37 yield* fs.makeDirectory(binDir, { recursive: true });
38​
39 // The stub behaviour lives in Node rather than a `#!/bin/sh` script so the
40 // same implementation is usable on Windows, where a shebang file is not
41 // executable and would fall through to the real Claude CLI on PATH.
42 yield* fs.writeFileString(
43 stubPath,
44 [
45 'const args = process.argv.slice(2).join(" ");',
46 "",
47 "function fail(message, code) {",
48 ' process.stderr.write(message + "\\n");',
49 " process.exit(code);",
50 "}",
51 "",
52 'let stdinContent = "";',
53 "if (!process.stdin.isTTY) {",
54 " const chunks = [];",
55 " for await (const chunk of process.stdin) {",
56 " chunks.push(chunk);",
57 " }",
58 ' stdinContent = Buffer.concat(chunks).toString("utf8");',
59 "}",
60 "",
61 "const argsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;",
62 "if (argsMustContain && !args.includes(argsMustContain)) {",
63 ' fail("args missing expected content", 2);',
64 "}",
65 "",
66 "const argsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;",
67 "if (argsMustNotContain && args.includes(argsMustNotContain)) {",
68 ' fail("args contained forbidden content", 3);',
69 "}",
70 "",
71 "const stdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;",
72 "if (stdinMustContain && !stdinContent.includes(stdinMustContain)) {",
73 ' fail("stdin missing expected content", 4);',
74 "}",
75 "",
76 "const configDirMustBe = process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;",
77 "if (configDirMustBe && process.env.CLAUDE_CONFIG_DIR !== configDirMustBe) {",
78 ' fail("CLAUDE_CONFIG_DIR was " + (process.env.CLAUDE_CONFIG_DIR ?? ""), 5);',
79 "}",
80 "",
81 "const stderrText = process.env.T3_FAKE_CLAUDE_STDERR;",
82 "if (stderrText) {",
83 ' process.stderr.write(stderrText + "\\n");',
84 "}",
85 "",
86 'process.stdout.write(process.env.T3_FAKE_CLAUDE_OUTPUT ?? "");',
87 "process.exitCode = Number(process.env.T3_FAKE_CLAUDE_EXIT_CODE ?? 0);",
88 "",
89 ].join("\n"),
90 );
91​
92 if (isWindows) {
93 // Windows resolves executables through PATHEXT, so the entry point has to
94 // carry a real extension. `resolveSpawnCommand` spawns `.cmd` via a shell.
95 yield* fs.writeFileString(
96 path.join(binDir, "claude.cmd"),
97 ["@echo off", 'node "%~dp0claude-stub.mjs" %*', "exit /b %ERRORLEVEL%", ""].join("\r\n"),
98 );
99 } else {
100 const claudePath = path.join(binDir, "claude");
101 yield* fs.writeFileString(
102 claudePath,
103 ["#!/bin/sh", 'exec node "$(dirname "$0")/claude-stub.mjs" "$@"', ""].join("\n"),
104 );
105 yield* fs.chmod(claudePath, 0o755);
106 }
107​
108 return binDir;
109 });
111​
112function withFakeClaudeEnv<A, E, R>(
113 input: {
114 output: string;
115 exitCode?: number;
116 stderr?: string;
117 argsMustContain?: string;
118 argsMustNotContain?: string;
119 stdinMustContain?: string;
120 configDirMustBe?: string;
121 claudeConfig?: Partial<ClaudeSettings>;
122 },
123 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
124) {
125 return Effect.gen(function* () {
126 const fs = yield* FileSystem.FileSystem;
127 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
128 const binDir = yield* makeFakeClaudeBinary(tempDir);
129 const pathDelimiter = (yield* isHostWindows) ? ";" : ":";
130 const previousPath = process.env.PATH;
131 const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;
132 const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;
133 const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;
134 const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
135 const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
136 const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
137 const previousConfigDirMustBe = process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
138​
139 yield* Effect.acquireRelease(
140 Effect.sync(() => {
141 process.env.PATH = `${binDir}${pathDelimiter}${previousPath ?? ""}`;
142 process.env.T3_FAKE_CLAUDE_OUTPUT = input.output;
143​
144 if (input.exitCode !== undefined) {
145 process.env.T3_FAKE_CLAUDE_EXIT_CODE = String(input.exitCode);
146 } else {
147 delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
148 }
149​
150 if (input.stderr !== undefined) {
151 process.env.T3_FAKE_CLAUDE_STDERR = input.stderr;
152 } else {
153 delete process.env.T3_FAKE_CLAUDE_STDERR;
154 }
155​
156 if (input.argsMustContain !== undefined) {
157 process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = input.argsMustContain;
158 } else {
159 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
160 }
161​
162 if (input.argsMustNotContain !== undefined) {
163 process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = input.argsMustNotContain;
164 } else {
165 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
166 }
167​
168 if (input.stdinMustContain !== undefined) {
169 process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = input.stdinMustContain;
170 } else {
171 delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
172 }
173​
174 if (input.configDirMustBe !== undefined) {
175 process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = input.configDirMustBe;
176 } else {
177 delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
178 }
179 }),
180 () =>
181 Effect.sync(() => {
182 process.env.PATH = previousPath;
183​
184 if (previousOutput === undefined) {
185 delete process.env.T3_FAKE_CLAUDE_OUTPUT;
186 } else {
187 process.env.T3_FAKE_CLAUDE_OUTPUT = previousOutput;
188 }
189​
190 if (previousExitCode === undefined) {
191 delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
192 } else {
193 process.env.T3_FAKE_CLAUDE_EXIT_CODE = previousExitCode;
194 }
195​
196 if (previousStderr === undefined) {
197 delete process.env.T3_FAKE_CLAUDE_STDERR;
198 } else {
199 process.env.T3_FAKE_CLAUDE_STDERR = previousStderr;
200 }
201​
202 if (previousArgsMustContain === undefined) {
203 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
204 } else {
205 process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previousArgsMustContain;
206 }
207​
208 if (previousArgsMustNotContain === undefined) {
209 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
210 } else {
211 process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previousArgsMustNotContain;
212 }
213​
214 if (previousStdinMustContain === undefined) {
215 delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
216 } else {
217 process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previousStdinMustContain;
218 }
219​
220 if (previousConfigDirMustBe === undefined) {
221 delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
222 } else {
223 process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = previousConfigDirMustBe;
224 }
225 }),
226 );
227​
228 const config = decodeClaudeSettings(input.claudeConfig ?? {});
229 const textGeneration = yield* makeClaudeTextGeneration(
230 config,
231 undefined,
232 Effect.succeed(SYNTHETIC_CLAUDE_MODEL_CATALOG),
233 );
234 return yield* effectFn(textGeneration);
235 }).pipe(Effect.scoped);
237​
238it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {
239 it.effect("forwards Claude thinking settings without passing unsupported effort", () =>
240 withFakeClaudeEnv(
241 {
242 output: JSON.stringify({
243 structured_output: {
244 subject: "Add important change",
245 body: "",
246 },
247 }),
248 argsMustContain: '--settings {"alwaysThinkingEnabled":false}',
249 argsMustNotContain: "--effort",
250 },
251 (textGeneration) =>
252 Effect.gen(function* () {
253 const generated = yield* textGeneration.generateCommitMessage({
254 cwd: process.cwd(),
255 branch: "feature/claude-effect",
256 stagedSummary: "M README.md",
257 stagedPatch: "diff --git a/README.md b/README.md",
258 modelSelection: {
259 ...createModelSelection(
260 ProviderInstanceId.make("claudeAgent"),
261 SYNTHETIC_CLAUDE_THINKING_MODEL,
262 [
263 { id: "thinking", value: false },
264 { id: "effort", value: "high" },
265 ],
266 ),
267 },
268 });
269​
270 expect(generated.subject).toBe("Add important change");
271 }),
272 ),
273 );
274​
275 it.effect("keeps a configured custom alias opaque to the Claude CLI", () =>
276 withFakeClaudeEnv(
277 {
278 output: JSON.stringify({
279 structured_output: {
280 title: "Keep custom model",
281 body: "",
282 },
283 }),
284 argsMustContain: `--model ${SYNTHETIC_CLAUDE_COLLIDING_ALIAS} --dangerously-skip-permissions`,
285 claudeConfig: { customModels: [SYNTHETIC_CLAUDE_COLLIDING_ALIAS] },
286 },
287 (textGeneration) =>
288 Effect.gen(function* () {
289 const generated = yield* textGeneration.generatePrContent({
290 cwd: process.cwd(),
291 baseBranch: "main",
292 headBranch: "feature/custom-model",
293 commitSummary: "Keep custom model",
294 diffSummary: "1 file changed",
295 diffPatch: "diff --git a/README.md b/README.md",
296 modelSelection: createModelSelection(
297 ProviderInstanceId.make("claudeAgent"),
298 SYNTHETIC_CLAUDE_COLLIDING_ALIAS,
299 [
300 { id: "effort", value: "max" },
301 { id: "fastMode", value: true },
302 { id: "contextWindow", value: "expanded" },
303 ],
304 ),
305 });
306​
307 expect(generated.title).toBe("Keep custom model");
308 }),
309 ),
310 );
311​
312 it.effect(
313 "keeps canonical built-in capabilities when a custom model collides with its alias",
314 () =>
315 withFakeClaudeEnv(
316 {
317 output: JSON.stringify({
318 structured_output: {
319 title: "Improve orchestration flow",
320 body: "Body",
321 },
322 }),
323 argsMustContain: `--model ${SYNTHETIC_CLAUDE_CAPABLE_MODEL}[expanded] --effort max --settings {"fastMode":true} --dangerously-skip-permissions`,
324 claudeConfig: { customModels: [SYNTHETIC_CLAUDE_COLLIDING_ALIAS] },
325 },
326 (textGeneration) =>
327 Effect.gen(function* () {
328 const generated = yield* textGeneration.generatePrContent({
329 cwd: process.cwd(),
330 baseBranch: "main",
331 headBranch: "feature/claude-effect",
332 commitSummary: "Improve orchestration",
333 diffSummary: "1 file changed",
334 diffPatch: "diff --git a/README.md b/README.md",
335 modelSelection: {
336 ...createModelSelection(
337 ProviderInstanceId.make("claudeAgent"),
338 SYNTHETIC_CLAUDE_CAPABLE_MODEL,
339 [
340 { id: "effort", value: "max" },
341 { id: "fastMode", value: true },
342 ],
343 ),
344 },
345 });
346​
347 expect(generated.title).toBe("Improve orchestration flow");
348 }),
349 ),
350 );
351​
352 it.effect("generates thread titles through the Claude provider", () =>
353 withFakeClaudeEnv(
354 {
355 output: JSON.stringify({
356 structured_output: {
357 title:
358 ' "Reconnect failures after restart because the session state does not recover" ',
359 },
360 }),
361 stdinMustContain: "Please investigate reconnect failures after restarting the session.",
362 },
363 (textGeneration) =>
364 Effect.gen(function* () {
365 const generated = yield* textGeneration.generateThreadTitle({
366 cwd: process.cwd(),
367 message: "Please investigate reconnect failures after restarting the session.",
368 modelSelection: {
369 instanceId: ProviderInstanceId.make("claudeAgent"),
370 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
371 },
372 });
373​
374 expect(generated.title).toBe(
375 sanitizeThreadTitle(
376 '"Reconnect failures after restart because the session state does not recover"',
377 ),
378 );
379 }),
380 ),
381 );
382​
383 it.effect("runs Claude text generation with the configured CLAUDE_CONFIG_DIR", () =>
384 Effect.gen(function* () {
385 const path = yield* Path.Path;
386 const claudeConfigDir = path.join(process.cwd(), ".claude-work-test");
387 return yield* withFakeClaudeEnv(
388 {
389 // @effect-diagnostics-next-line preferSchemaOverJson:off
390 output: JSON.stringify({
391 structured_output: {
392 title: "Use Claude home",
393 },
394 }),
395 configDirMustBe: claudeConfigDir,
396 claudeConfig: { homePath: claudeConfigDir },
397 },
398 (textGeneration) =>
399 Effect.gen(function* () {
400 const generated = yield* textGeneration.generateThreadTitle({
401 cwd: process.cwd(),
402 message: "thread title",
403 modelSelection: {
404 instanceId: ProviderInstanceId.make("claudeAgent"),
405 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
406 },
407 });
408​
409 expect(generated.title).toBe(sanitizeThreadTitle("Use Claude home"));
410 }),
411 );
412 }),
413 );
414​
415 it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
416 withFakeClaudeEnv(
417 {
418 output: JSON.stringify({
419 structured_output: {
420 title: ' """ """ ',
421 },
422 }),
423 },
424 (textGeneration) =>
425 Effect.gen(function* () {
426 const generated = yield* textGeneration.generateThreadTitle({
427 cwd: process.cwd(),
428 message: "Name this thread.",
429 modelSelection: {
430 instanceId: ProviderInstanceId.make("claudeAgent"),
431 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
432 },
433 });
434​
435 expect(generated.title).toBe("New thread");
436 }),
437 ),
438 );
439});