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

ClaudeTextGeneration.test.ts

421 lines15.1 KB

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