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

ClaudeTextGeneration.test.ts

536 lines19.0 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { it } from "@effect/vitest";
3import { ClaudeSettings, ProviderInstanceId } from "@t3tools/contracts";
4import * as HostProcess 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 { processProbeSource } from "../testUtils/processProbe.ts";
15import {
16 SYNTHETIC_CLAUDE_CAPABLE_MODEL,
17 SYNTHETIC_CLAUDE_COLLIDING_ALIAS,
18 SYNTHETIC_CLAUDE_MODEL_CATALOG,
19 SYNTHETIC_CLAUDE_STANDARD_MODEL,
20} from "../provider/ClaudeModelCatalog.testFixtures.ts";
21import * as TextGeneration from "./TextGeneration.ts";
22import { sanitizeThreadTitle } from "@t3tools/provider-core/server/textGenerationUtils";
23import { makeClaudeTextGeneration } from "./ClaudeTextGeneration.ts";
24import { writeFakeCli } from "@t3tools/provider-testing/fakeCli";
25const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
26​
27const layerClaudeTextGenerationTest = 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, lifecyclePort?: number) {
35 return Effect.gen(function* () {
36 const path = yield* Path.Path;
37 const fs = yield* FileSystem.FileSystem;
38 const platform = yield* HostProcess.Platform;
39 const binDir = path.join(dir, "bin");
40 const fixturePath = yield* path.fromFileUrl(
41 new URL("./testing/ClaudeTextGeneration.fixture.mjs", import.meta.url),
42 );
43 const source = yield* fs.readFileString(fixturePath);
44 writeFakeCli({
45 directory: binDir,
46 name: "claude",
47 platform,
48 source:
49 lifecyclePort === undefined
50 ? source
51 : `process.on("SIGTERM", () => {}); ${processProbeSource(lifecyclePort)}`,
52 });
53 return binDir;
54 });
56​
57function withFakeClaudeEnv<A, E, R>(
58 input: {
59 output: string;
60 rejectsNoSessionPersistence?: boolean;
61 lifecyclePort?: number;
62 exitCode?: number;
63 stderr?: string;
64 argsMustContain?: string;
65 expectedTools?: string;
66 argsMustNotContain?: string;
67 stdinMustContain?: string;
68 configDirMustBe?: string;
69 cwdMustNotBe?: string;
70 claudeConfig?: Partial<ClaudeSettings>;
71 },
72 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
73) {
74 return Effect.gen(function* () {
75 const fs = yield* FileSystem.FileSystem;
76 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
77 const binDir = yield* makeFakeClaudeBinary(tempDir, input.lifecyclePort);
78 const pathDelimiter = (yield* HostProcess.isWindows) ? ";" : ":";
79 const hostEnv = yield* HostProcess.Environment;
80 const fakeClaudeEnv: Record<string, string | undefined> = {
81 T3_FAKE_CLAUDE_OUTPUT: input.output,
82 T3_FAKE_CLAUDE_REJECTS_NO_SESSION_PERSISTENCE: input.rejectsNoSessionPersistence
83 ? "1"
84 : undefined,
85 T3_FAKE_CLAUDE_EXIT_CODE: input.exitCode === undefined ? undefined : String(input.exitCode),
86 T3_FAKE_CLAUDE_STDERR: input.stderr,
87 T3_FAKE_CLAUDE_EXPECTED_TOOLS: input.expectedTools,
88 T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN: input.argsMustContain,
89 T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN: input.argsMustNotContain,
90 T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN: input.stdinMustContain,
91 T3_FAKE_CLAUDE_CWD_MUST_NOT_BE: input.cwdMustNotBe,
92 T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE: input.configDirMustBe,
93 };
94 const environment: NodeJS.ProcessEnv = {
95 ...Object.fromEntries(
96 Object.entries(hostEnv).filter(([name]) => !name.startsWith("T3_FAKE_CLAUDE_")),
97 ),
98 ...Object.fromEntries(
99 Object.entries(fakeClaudeEnv).filter(([, value]) => value !== undefined),
100 ),
101 PATH: `${binDir}${pathDelimiter}${hostEnv.PATH ?? ""}`,
102 };
103​
104 const config = decodeClaudeSettings(input.claudeConfig ?? {});
105 const textGeneration = yield* makeClaudeTextGeneration(
106 config,
107 environment,
108 Effect.succeed(SYNTHETIC_CLAUDE_MODEL_CATALOG),
109 );
110 return yield* effectFn(textGeneration);
111 }).pipe(Effect.scoped);
113​
114it.layer(layerClaudeTextGenerationTest)("ClaudeTextGeneration", (it) => {
115 it.effect("loads only user settings when generating review guides", () =>
116 withFakeClaudeEnv(
117 {
118 output: JSON.stringify({ structured_output: { stops: [] } }),
119 argsMustContain: "--setting-sources user",
120 expectedTools: "Read,Grep,Glob,Bash",
121 },
122 (textGeneration) =>
123 textGeneration.generateReviewGuide({
124 cwd: process.cwd(),
125 number: 12,
126 title: "Review a change",
127 description: "",
128 baseBranch: "main",
129 baseCommit: "base",
130 settledReview: "",
131 modelSelection: createModelSelection(
132 ProviderInstanceId.make("claudeAgent"),
133 SYNTHETIC_CLAUDE_CAPABLE_MODEL,
134 ),
135 }),
136 ),
137 );
138​
139 it.effect(
140 "keeps canonical built-in capabilities when a custom model collides with its alias",
141 () =>
142 withFakeClaudeEnv(
143 {
144 output: JSON.stringify({
145 structured_output: {
146 title: "Improve orchestration flow",
147 body: "Body",
148 },
149 }),
150 argsMustContain: `--model ${SYNTHETIC_CLAUDE_CAPABLE_MODEL}[expanded] --effort max --settings {"disableAllHooks":true,"fastMode":true}`,
151 claudeConfig: { customModels: [SYNTHETIC_CLAUDE_COLLIDING_ALIAS] },
152 },
153 (textGeneration) =>
154 Effect.gen(function* () {
155 const generated = yield* textGeneration.generatePrContent({
156 cwd: process.cwd(),
157 baseBranch: "main",
158 headBranch: "feature/claude-effect",
159 commitSummary: "Improve orchestration",
160 diffSummary: "1 file changed",
161 diffPatch: "diff --git a/README.md b/README.md",
162 modelSelection: {
163 ...createModelSelection(
164 ProviderInstanceId.make("claudeAgent"),
165 SYNTHETIC_CLAUDE_CAPABLE_MODEL,
166 [
167 { id: "effort", value: "max" },
168 { id: "fastMode", value: true },
169 ],
170 ),
171 },
172 });
173​
174 expect(generated.title).toBe("Improve orchestration flow");
175 }),
176 ),
177 );
178​
179 it.effect(
180 "generates thread titles outside the project with tools, skills, and hooks disabled",
181 () =>
182 withFakeClaudeEnv(
183 {
184 output: JSON.stringify({
185 structured_output: {
186 title:
187 ' "Reconnect failures after restart because the session state does not recover" ',
188 },
189 }),
190 cwdMustNotBe: process.cwd(),
191 stdinMustContain: "/call-script",
192 },
193 (textGeneration) =>
194 Effect.gen(function* () {
195 const generated = yield* textGeneration.generateThreadTitle({
196 cwd: process.cwd(),
197 message: "/call-script",
198 modelSelection: {
199 instanceId: ProviderInstanceId.make("claudeAgent"),
200 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
201 },
202 });
203​
204 expect(generated.title).toBe(
205 sanitizeThreadTitle(
206 '"Reconnect failures after restart because the session state does not recover"',
207 ),
208 );
209 }),
210 ),
211 );
212​
213 it.effect("sends thread title instructions to the provider prompt", () =>
214 withFakeClaudeEnv(
215 {
216 output: JSON.stringify({ structured_output: { title: "Reconnect failures" } }),
217 stdinMustContain: "Title instructions from the user:\nUse two to four words.",
218 },
219 (textGeneration) =>
220 textGeneration.generateThreadTitle({
221 cwd: process.cwd(),
222 message: "Investigate reconnect failures",
223 instructions: "Use two to four words.",
224 modelSelection: {
225 instanceId: ProviderInstanceId.make("claudeAgent"),
226 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
227 },
228 }),
229 ),
230 );
231​
232 it.effect("sends image attachments to Claude, not only their metadata", () =>
233 withFakeClaudeEnv(
234 {
235 output: JSON.stringify({ structured_output: { branch: "fix/login-button" } }),
236 stdinMustContain: Buffer.from("hello").toString("base64"),
237 },
238 (textGeneration) =>
239 Effect.gen(function* () {
240 const fs = yield* FileSystem.FileSystem;
241 const path = yield* Path.Path;
242 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
243 const attachmentId = "thread-1-claude-attachment";
244 const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
245 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
246 yield* fs.writeFile(imagePath, Buffer.from("hello"));
247​
248 yield* textGeneration
249 .generateBranchName({
250 cwd: process.cwd(),
251 message: "fix this",
252 attachments: [
253 {
254 type: "image",
255 id: attachmentId,
256 name: "screen.png",
257 mimeType: "image/png",
258 sizeBytes: 5,
259 },
260 ],
261 modelSelection: {
262 instanceId: ProviderInstanceId.make("claudeAgent"),
263 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
264 },
265 })
266 .pipe(Effect.ensuring(fs.remove(imagePath).pipe(Effect.ignore)));
267 }),
268 ),
269 );
270​
271 it.effect("runs Claude text generation with the configured CLAUDE_CONFIG_DIR", () =>
272 Effect.gen(function* () {
273 const path = yield* Path.Path;
274 const claudeConfigDir = path.join(process.cwd(), ".claude-work-test");
275 return yield* withFakeClaudeEnv(
276 {
277 output: JSON.stringify({
278 structured_output: {
279 title: "Use Claude home",
280 },
281 }),
282 configDirMustBe: claudeConfigDir,
283 claudeConfig: { homePath: claudeConfigDir },
284 },
285 (textGeneration) =>
286 Effect.gen(function* () {
287 const generated = yield* textGeneration.generateThreadTitle({
288 cwd: process.cwd(),
289 message: "thread title",
290 modelSelection: {
291 instanceId: ProviderInstanceId.make("claudeAgent"),
292 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
293 },
294 });
295​
296 expect(generated.title).toBe(sanitizeThreadTitle("Use Claude home"));
297 }),
298 );
299 }),
300 );
301​
302 it.effect("passes --settings from the instance launch args to Claude text generation", () =>
303 withFakeClaudeEnv(
304 {
305 output: JSON.stringify({
306 structured_output: {
307 title: "Use instance settings",
308 },
309 }),
310 argsMustContain: `"env":{"ANTHROPIC_VERTEX_PROJECT_ID":"vertex-project-a"}`,
311 claudeConfig: {
312 launchArgs: `--settings '{"env":{"ANTHROPIC_VERTEX_PROJECT_ID":"vertex-project-a"}}'`,
313 },
314 },
315 (textGeneration) =>
316 Effect.gen(function* () {
317 const generated = yield* textGeneration.generateThreadTitle({
318 cwd: process.cwd(),
319 message: "thread title",
320 modelSelection: {
321 instanceId: ProviderInstanceId.make("claudeAgent"),
322 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
323 },
324 });
325​
326 expect(generated.title).toBe(sanitizeThreadTitle("Use instance settings"));
327 }),
328 ),
329 );
330​
331 it.effect("retries without --no-session-persistence when the Claude CLI rejects it", () =>
332 withFakeClaudeEnv(
333 {
334 output: JSON.stringify({ structured_output: { title: "Reconnect failures" } }),
335 rejectsNoSessionPersistence: true,
336 },
337 (textGeneration) =>
338 Effect.gen(function* () {
339 const generated = yield* textGeneration.generateThreadTitle({
340 cwd: process.cwd(),
341 message: "Investigate reconnect failures",
342 modelSelection: {
343 instanceId: ProviderInstanceId.make("claudeAgent"),
344 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
345 },
346 });
347​
348 expect(generated.title).toBe("Reconnect failures");
349 }),
350 ),
351 );
352​
353 it.effect.each([
354 { verbose: false, label: "normal" },
355 { verbose: true, label: "verbose" },
356 ])("unwraps a JSON title in $label Claude output", ({ verbose }) => {
357 const result = {
358 type: "result",
359 structured_output: { title: '{"title": "Refresh ev-stg APP ASG instances"}' },
360 };
361 return withFakeClaudeEnv(
362 { output: JSON.stringify(verbose ? [result] : result) },
363 (textGeneration) =>
364 Effect.gen(function* () {
365 const generated = yield* textGeneration.generateThreadTitle({
366 cwd: process.cwd(),
367 message: "Refresh ev-stg APP ASG instances",
368 modelSelection: {
369 instanceId: ProviderInstanceId.make("claudeAgent"),
370 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
371 },
372 });
373​
374 expect(generated.title).toBe("Refresh ev-stg APP ASG instances");
375 }),
376 );
377 });
378​
379 it.effect.each([
380 { previousTitle: undefined, label: "generating" },
381 { previousTitle: "Old thread title", label: "regenerating" },
382 ])("reads the result from verbose Claude output when $label a title", ({ previousTitle }) =>
383 withFakeClaudeEnv(
384 {
385 output: JSON.stringify([
386 { type: "system", subtype: "init" },
387 { type: "assistant", message: { content: [] } },
388 { type: "user", message: { content: [] } },
389 { type: "rate_limit_event" },
390 {
391 type: "result",
392 subtype: "success",
393 result: '{"title":"Refresh ev-stg APP ASG Instances"}',
394 structured_output: { title: "Refresh ev-stg APP ASG Instances" },
395 },
396 ]),
397 },
398 (textGeneration) =>
399 Effect.gen(function* () {
400 const generated = yield* textGeneration.generateThreadTitle({
401 cwd: process.cwd(),
402 message: "Refresh ev-stg APP ASG instances",
403 previousTitle,
404 modelSelection: {
405 instanceId: ProviderInstanceId.make("claudeAgent"),
406 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
407 },
408 });
409​
410 expect(generated.title).toBe("Refresh ev-stg APP ASG Instances");
411 }),
412 ),
413 );
414​
415 it.effect.each([
416 ["empty message array", []],
417 ["missing result", [{ type: "assistant", structured_output: { title: "Not a result" } }]],
418 ["invalid title", [{ type: "result", structured_output: { title: 42 } }]],
419 [
420 "final result without structured output",
421 [
422 { type: "result", structured_output: { title: "Earlier result" } },
423 { type: "result", subtype: "error_max_structured_output_retries" },
424 ],
425 ],
426 ] as const)("rejects verbose Claude output with %s", ([, output]) =>
427 withFakeClaudeEnv({ output: JSON.stringify(output) }, (textGeneration) =>
428 Effect.gen(function* () {
429 const error = yield* Effect.flip(
430 textGeneration.generateThreadTitle({
431 cwd: process.cwd(),
432 message: "Name this thread",
433 modelSelection: {
434 instanceId: ProviderInstanceId.make("claudeAgent"),
435 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
436 },
437 }),
438 );
439​
440 expect(error._tag).toBe("TextGenerationError");
441 }),
442 ),
443 );
444​
445 const apiError = "API Error: 400 Model blocked by guardrail: 4 endpoints excluded";
446 const wrapperNotice = "Using the OpenRouter credential from the global credential file.";
447 const structuredOutputError = "Failed to provide valid structured output after 5 attempts";
448 const structuredOutputFailure = {
449 type: "result",
450 subtype: "error_max_structured_output_retries",
451 is_error: true,
452 errors: [structuredOutputError],
453 };
454 it.effect.each([
455 [
456 "the errors list of a result with no result text",
457 JSON.stringify(structuredOutputFailure),
458 structuredOutputError,
459 ],
460 [
461 "the errors list from verbose output",
462 JSON.stringify([{ type: "system", subtype: "init" }, structuredOutputFailure]),
463 structuredOutputError,
464 ],
465 [
466 "the errors list without CLI telemetry",
467 JSON.stringify({
468 ...structuredOutputFailure,
469 subtype: "error_during_execution",
470 errors: ["[ede_diagnostic] result_type=user last_content_type=n/a", apiError],
471 }),
472 apiError,
473 ],
474 [
475 "the stdout error over a stderr notice",
476 JSON.stringify({ is_error: true, api_error_status: 400, result: apiError }),
477 apiError,
478 ],
479 [
480 "the verbose stdout error over a stderr notice",
481 JSON.stringify([
482 { type: "system", subtype: "init" },
483 { type: "result", is_error: true, result: apiError },
484 { type: "result", is_error: true, result: " " },
485 ]),
486 apiError,
487 ],
488 ["stderr when stdout has no error", "not json", wrapperNotice],
489 [
490 "a stdout error naming --no-session-persistence without retrying",
491 JSON.stringify({
492 is_error: true,
493 result: "error: unknown option '--no-session-persistence'",
494 }),
495 "error: unknown option '--no-session-persistence'",
496 ],
497 ] as const)("reports %s when the Claude CLI fails", ([, output, expected]) =>
498 withFakeClaudeEnv({ output, stderr: wrapperNotice, exitCode: 1 }, (textGeneration) =>
499 Effect.gen(function* () {
500 const error = yield* Effect.flip(
501 textGeneration.generateThreadTitle({
502 cwd: process.cwd(),
503 message: "Name this thread",
504 modelSelection: {
505 instanceId: ProviderInstanceId.make("claudeAgent"),
506 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
507 },
508 }),
509 );
510​
511 expect(error.detail).toBe(`Claude CLI command failed: ${expected}`);
512 }),
513 ),
514 );
515​
516 it.effect("does not report the raw result JSON when a failed run writes nothing to stderr", () =>
517 withFakeClaudeEnv(
518 { output: JSON.stringify(structuredOutputFailure), exitCode: 1 },
519 (textGeneration) =>
520 Effect.gen(function* () {
521 const error = yield* Effect.flip(
522 textGeneration.generateThreadTitle({
523 cwd: process.cwd(),
524 message: "Name this thread",
525 modelSelection: {
526 instanceId: ProviderInstanceId.make("claudeAgent"),
527 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
528 },
529 }),
530 );
531​
532 expect(error.detail).toBe(`Claude CLI command failed: ${structuredOutputError}`);
533 }),
534 ),
535 );
536});