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