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 Fiber from "effect/Fiber";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Path from "effect/Path";
11import * as Schema from "effect/Schema";
12import * as TestClock from "effect/testing/TestClock";
13import { expect } from "vite-plus/test";
14
15import * as ServerConfig from "../config.ts";
16import { makeProcessProbe, processProbeSource } from "../testUtils/processProbe.ts";
17import {
18 SYNTHETIC_CLAUDE_CAPABLE_MODEL,
19 SYNTHETIC_CLAUDE_COLLIDING_ALIAS,
20 SYNTHETIC_CLAUDE_MODEL_CATALOG,
21 SYNTHETIC_CLAUDE_STANDARD_MODEL,
22 SYNTHETIC_CLAUDE_THINKING_MODEL,
23} from "../provider/ClaudeModelCatalog.testFixtures.ts";
24import * as TextGeneration from "./TextGeneration.ts";
25import { sanitizeThreadTitle } from "@t3tools/provider-core/server/textGenerationUtils";
26import { makeClaudeTextGeneration } from "./ClaudeTextGeneration.ts";
27import { writeFakeCli } from "@t3tools/provider-testing/fakeCli";
28const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
29
30const layerClaudeTextGenerationTest = ServerConfig.ServerConfig.layerTest(process.cwd(), {
31 prefix: "t3code-claude-text-generation-test-",
32}).pipe(Layer.provideMerge(NodeServices.layer));
33
34// The stub behaviour lives in Node so the same implementation runs on Windows,
35// where a shebang file is not executable and would fall through to the real
36// Claude CLI on PATH; `writeFakeCli` picks the launcher shape per host.
37function makeFakeClaudeBinary(dir: string, lifecyclePort?: number) {
38 return Effect.gen(function* () {
39 const path = yield* Path.Path;
40 const fs = yield* FileSystem.FileSystem;
41 const platform = yield* HostProcess.Platform;
42 const binDir = path.join(dir, "bin");
43 const fixturePath = yield* path.fromFileUrl(
44 new URL("./testing/ClaudeTextGeneration.fixture.mjs", import.meta.url),
45 );
46 const source = yield* fs.readFileString(fixturePath);
47 writeFakeCli({
48 directory: binDir,
49 name: "claude",
50 platform,
51 source:
52 lifecyclePort === undefined
53 ? source
54 : `process.on("SIGTERM", () => {}); ${processProbeSource(lifecyclePort)}`,
55 });
56 return binDir;
57 });
58}
59
60function withFakeClaudeEnv<A, E, R>(
61 input: {
62 output: string;
63 lifecyclePort?: number;
64 exitCode?: number;
65 stderr?: string;
66 argsMustContain?: string;
67 argsMustNotContain?: string;
68 stdinMustContain?: string;
69 configDirMustBe?: string;
70 cwdMustNotBe?: string;
71 claudeConfig?: Partial<ClaudeSettings>;
72 },
73 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
74) {
75 return Effect.gen(function* () {
76 const fs = yield* FileSystem.FileSystem;
77 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
78 const binDir = yield* makeFakeClaudeBinary(tempDir, input.lifecyclePort);
79 const pathDelimiter = (yield* HostProcess.isWindows) ? ";" : ":";
80 const previousPath = process.env.PATH;
81 const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;
82 const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;
83 const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;
84 const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
85 const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
86 const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
87 const previousConfigDirMustBe = process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
88 const previousCwdMustNotBe = process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE;
89
90 yield* Effect.acquireRelease(
91 Effect.sync(() => {
92 process.env.PATH = `${binDir}${pathDelimiter}${previousPath ?? ""}`;
93 process.env.T3_FAKE_CLAUDE_OUTPUT = input.output;
94
95 if (input.exitCode !== undefined) {
96 process.env.T3_FAKE_CLAUDE_EXIT_CODE = String(input.exitCode);
97 } else {
98 delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
99 }
100
101 if (input.stderr !== undefined) {
102 process.env.T3_FAKE_CLAUDE_STDERR = input.stderr;
103 } else {
104 delete process.env.T3_FAKE_CLAUDE_STDERR;
105 }
106
107 if (input.argsMustContain !== undefined) {
108 process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = input.argsMustContain;
109 } else {
110 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
111 }
112
113 if (input.argsMustNotContain !== undefined) {
114 process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = input.argsMustNotContain;
115 } else {
116 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
117 }
118
119 if (input.stdinMustContain !== undefined) {
120 process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = input.stdinMustContain;
121 } else {
122 delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
123 }
124
125 if (input.cwdMustNotBe !== undefined) {
126 process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE = input.cwdMustNotBe;
127 } else {
128 delete process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE;
129 }
130
131 if (input.configDirMustBe !== undefined) {
132 process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = input.configDirMustBe;
133 } else {
134 delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
135 }
136 }),
137 () =>
138 Effect.sync(() => {
139 process.env.PATH = previousPath;
140
141 if (previousOutput === undefined) {
142 delete process.env.T3_FAKE_CLAUDE_OUTPUT;
143 } else {
144 process.env.T3_FAKE_CLAUDE_OUTPUT = previousOutput;
145 }
146
147 if (previousExitCode === undefined) {
148 delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
149 } else {
150 process.env.T3_FAKE_CLAUDE_EXIT_CODE = previousExitCode;
151 }
152
153 if (previousStderr === undefined) {
154 delete process.env.T3_FAKE_CLAUDE_STDERR;
155 } else {
156 process.env.T3_FAKE_CLAUDE_STDERR = previousStderr;
157 }
158
159 if (previousArgsMustContain === undefined) {
160 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
161 } else {
162 process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previousArgsMustContain;
163 }
164
165 if (previousArgsMustNotContain === undefined) {
166 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
167 } else {
168 process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previousArgsMustNotContain;
169 }
170
171 if (previousStdinMustContain === undefined) {
172 delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
173 } else {
174 process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previousStdinMustContain;
175 }
176
177 if (previousCwdMustNotBe === undefined) {
178 delete process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE;
179 } else {
180 process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE = previousCwdMustNotBe;
181 }
182
183 if (previousConfigDirMustBe === undefined) {
184 delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
185 } else {
186 process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = previousConfigDirMustBe;
187 }
188 }),
189 );
190
191 const config = decodeClaudeSettings(input.claudeConfig ?? {});
192 const textGeneration = yield* makeClaudeTextGeneration(
193 config,
194 undefined,
195 Effect.succeed(SYNTHETIC_CLAUDE_MODEL_CATALOG),
196 );
197 return yield* effectFn(textGeneration);
198 }).pipe(Effect.scoped);
199}
200
201it.layer(layerClaudeTextGenerationTest)("ClaudeTextGeneration", (it) => {
202 it.effect("kills a stalled CLI when the request times out", () =>
203 Effect.gen(function* () {
204 const probe = yield* makeProcessProbe;
205 yield* withFakeClaudeEnv({ output: "", lifecyclePort: probe.port }, (textGeneration) =>
206 Effect.gen(function* () {
207 const fiber = yield* textGeneration
208 .generateThreadTitle({
209 cwd: process.cwd(),
210 message: "Name this thread",
211 modelSelection: {
212 instanceId: ProviderInstanceId.make("claudeAgent"),
213 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
214 },
215 })
216 .pipe(Effect.flip, Effect.forkScoped);
217 yield* probe.started;
218
219 yield* TestClock.adjust("180 seconds");
220 yield* probe.exited;
221 expect((yield* Fiber.join(fiber)).detail).toBe("Claude CLI request timed out.");
222 }),
223 );
224 }),
225 );
226
227 it.effect.each([
228 { thinking: true, settings: '{"disableAllHooks":true,"alwaysThinkingEnabled":true}' },
229 { thinking: false, settings: '{"disableAllHooks":true,"alwaysThinkingEnabled":false}' },
230 { thinking: undefined, settings: '{"disableAllHooks":true}' },
231 ])("forwards only the explicit thinking choice ($thinking)", ({ thinking, settings }) =>
232 withFakeClaudeEnv(
233 {
234 output: JSON.stringify({
235 structured_output: {
236 subject: "Add important change",
237 body: "",
238 },
239 }),
240 argsMustContain: `--settings ${settings}`,
241 argsMustNotContain: "--effort",
242 },
243 (textGeneration) =>
244 Effect.gen(function* () {
245 const generated = yield* textGeneration.generateCommitMessage({
246 cwd: process.cwd(),
247 branch: "feature/claude-effect",
248 stagedSummary: "M README.md",
249 stagedPatch: "diff --git a/README.md b/README.md",
250 modelSelection: createModelSelection(
251 ProviderInstanceId.make("claudeAgent"),
252 SYNTHETIC_CLAUDE_THINKING_MODEL,
253 [
254 ...(thinking === undefined ? [] : [{ id: "thinking", value: thinking }]),
255 { id: "effort", value: "high" },
256 ],
257 ),
258 });
259
260 expect(generated.subject).toBe("Add important change");
261 }),
262 ),
263 );
264
265 it.effect("keeps a configured custom alias opaque to the Claude CLI", () =>
266 withFakeClaudeEnv(
267 {
268 output: JSON.stringify({
269 structured_output: {
270 title: "Keep custom model",
271 body: "",
272 },
273 }),
274 argsMustContain: `--model ${SYNTHETIC_CLAUDE_COLLIDING_ALIAS} --effort max --settings`,
275 claudeConfig: { customModels: [SYNTHETIC_CLAUDE_COLLIDING_ALIAS] },
276 },
277 (textGeneration) =>
278 Effect.gen(function* () {
279 const generated = yield* textGeneration.generatePrContent({
280 cwd: process.cwd(),
281 baseBranch: "main",
282 headBranch: "feature/custom-model",
283 commitSummary: "Keep custom model",
284 diffSummary: "1 file changed",
285 diffPatch: "diff --git a/README.md b/README.md",
286 modelSelection: createModelSelection(
287 ProviderInstanceId.make("claudeAgent"),
288 SYNTHETIC_CLAUDE_COLLIDING_ALIAS,
289 [
290 { id: "effort", value: "max" },
291 { id: "fastMode", value: true },
292 { id: "contextWindow", value: "expanded" },
293 ],
294 ),
295 });
296
297 expect(generated.title).toBe("Keep custom model");
298 }),
299 ),
300 );
301
302 it.effect(
303 "keeps canonical built-in capabilities when a custom model collides with its alias",
304 () =>
305 withFakeClaudeEnv(
306 {
307 output: JSON.stringify({
308 structured_output: {
309 title: "Improve orchestration flow",
310 body: "Body",
311 },
312 }),
313 argsMustContain: `--model ${SYNTHETIC_CLAUDE_CAPABLE_MODEL}[expanded] --effort max --settings {"disableAllHooks":true,"fastMode":true}`,
314 claudeConfig: { customModels: [SYNTHETIC_CLAUDE_COLLIDING_ALIAS] },
315 },
316 (textGeneration) =>
317 Effect.gen(function* () {
318 const generated = yield* textGeneration.generatePrContent({
319 cwd: process.cwd(),
320 baseBranch: "main",
321 headBranch: "feature/claude-effect",
322 commitSummary: "Improve orchestration",
323 diffSummary: "1 file changed",
324 diffPatch: "diff --git a/README.md b/README.md",
325 modelSelection: {
326 ...createModelSelection(
327 ProviderInstanceId.make("claudeAgent"),
328 SYNTHETIC_CLAUDE_CAPABLE_MODEL,
329 [
330 { id: "effort", value: "max" },
331 { id: "fastMode", value: true },
332 ],
333 ),
334 },
335 });
336
337 expect(generated.title).toBe("Improve orchestration flow");
338 }),
339 ),
340 );
341
342 it.effect(
343 "generates thread titles outside the project with tools, skills, and hooks disabled",
344 () =>
345 withFakeClaudeEnv(
346 {
347 output: JSON.stringify({
348 structured_output: {
349 title:
350 ' "Reconnect failures after restart because the session state does not recover" ',
351 },
352 }),
353 cwdMustNotBe: process.cwd(),
354 stdinMustContain: "/call-script",
355 },
356 (textGeneration) =>
357 Effect.gen(function* () {
358 const generated = yield* textGeneration.generateThreadTitle({
359 cwd: process.cwd(),
360 message: "/call-script",
361 modelSelection: {
362 instanceId: ProviderInstanceId.make("claudeAgent"),
363 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
364 },
365 });
366
367 expect(generated.title).toBe(
368 sanitizeThreadTitle(
369 '"Reconnect failures after restart because the session state does not recover"',
370 ),
371 );
372 }),
373 ),
374 );
375
376 it.effect("generates branch names from skill prompts without executable capabilities", () =>
377 withFakeClaudeEnv(
378 {
379 output: JSON.stringify({ structured_output: { branch: "call-script" } }),
380 stdinMustContain: "/call-script",
381 },
382 (textGeneration) =>
383 Effect.gen(function* () {
384 const generated = yield* textGeneration.generateBranchName({
385 cwd: process.cwd(),
386 message: "/call-script",
387 modelSelection: {
388 instanceId: ProviderInstanceId.make("claudeAgent"),
389 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
390 },
391 });
392
393 expect(generated.branch).toBe("call-script");
394 }),
395 ),
396 );
397
398 it.effect("runs Claude text generation with the configured CLAUDE_CONFIG_DIR", () =>
399 Effect.gen(function* () {
400 const path = yield* Path.Path;
401 const claudeConfigDir = path.join(process.cwd(), ".claude-work-test");
402 return yield* withFakeClaudeEnv(
403 {
404 output: JSON.stringify({
405 structured_output: {
406 title: "Use Claude home",
407 },
408 }),
409 configDirMustBe: claudeConfigDir,
410 claudeConfig: { homePath: claudeConfigDir },
411 },
412 (textGeneration) =>
413 Effect.gen(function* () {
414 const generated = yield* textGeneration.generateThreadTitle({
415 cwd: process.cwd(),
416 message: "thread title",
417 modelSelection: {
418 instanceId: ProviderInstanceId.make("claudeAgent"),
419 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
420 },
421 });
422
423 expect(generated.title).toBe(sanitizeThreadTitle("Use Claude home"));
424 }),
425 );
426 }),
427 );
428
429 it.effect.each([
430 { verbose: false, label: "normal" },
431 { verbose: true, label: "verbose" },
432 ])("unwraps a JSON title in $label Claude output", ({ verbose }) => {
433 const result = {
434 type: "result",
435 structured_output: { title: '{"title": "Refresh ev-stg APP ASG instances"}' },
436 };
437 return withFakeClaudeEnv(
438 { output: JSON.stringify(verbose ? [result] : result) },
439 (textGeneration) =>
440 Effect.gen(function* () {
441 const generated = yield* textGeneration.generateThreadTitle({
442 cwd: process.cwd(),
443 message: "Refresh ev-stg APP ASG instances",
444 modelSelection: {
445 instanceId: ProviderInstanceId.make("claudeAgent"),
446 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
447 },
448 });
449
450 expect(generated.title).toBe("Refresh ev-stg APP ASG instances");
451 }),
452 );
453 });
454
455 it.effect.each([
456 { previousTitle: undefined, label: "generating" },
457 { previousTitle: "Old thread title", label: "regenerating" },
458 ])("reads the result from verbose Claude output when $label a title", ({ previousTitle }) =>
459 withFakeClaudeEnv(
460 {
461 output: JSON.stringify([
462 { type: "system", subtype: "init" },
463 { type: "assistant", message: { content: [] } },
464 { type: "user", message: { content: [] } },
465 { type: "rate_limit_event" },
466 {
467 type: "result",
468 subtype: "success",
469 result: '{"title":"Refresh ev-stg APP ASG Instances"}',
470 structured_output: { title: "Refresh ev-stg APP ASG Instances" },
471 },
472 ]),
473 },
474 (textGeneration) =>
475 Effect.gen(function* () {
476 const generated = yield* textGeneration.generateThreadTitle({
477 cwd: process.cwd(),
478 message: "Refresh ev-stg APP ASG instances",
479 previousTitle,
480 modelSelection: {
481 instanceId: ProviderInstanceId.make("claudeAgent"),
482 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
483 },
484 });
485
486 expect(generated.title).toBe("Refresh ev-stg APP ASG Instances");
487 }),
488 ),
489 );
490
491 it.effect.each([
492 ["empty message array", []],
493 ["missing result", [{ type: "assistant", structured_output: { title: "Not a result" } }]],
494 ["invalid title", [{ type: "result", structured_output: { title: 42 } }]],
495 [
496 "final result without structured output",
497 [
498 { type: "result", structured_output: { title: "Earlier result" } },
499 { type: "result", subtype: "error_max_structured_output_retries" },
500 ],
501 ],
502 ] as const)("rejects verbose Claude output with %s", ([, output]) =>
503 withFakeClaudeEnv({ output: JSON.stringify(output) }, (textGeneration) =>
504 Effect.gen(function* () {
505 const error = yield* Effect.flip(
506 textGeneration.generateThreadTitle({
507 cwd: process.cwd(),
508 message: "Name this thread",
509 modelSelection: {
510 instanceId: ProviderInstanceId.make("claudeAgent"),
511 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
512 },
513 }),
514 );
515
516 expect(error._tag).toBe("TextGenerationError");
517 }),
518 ),
519 );
520
521 const apiError = "API Error: 400 Model blocked by guardrail: 4 endpoints excluded";
522 const wrapperNotice = "Using the OpenRouter credential from the global credential file.";
523 it.effect.each([
524 [
525 "the stdout error over a stderr notice",
526 JSON.stringify({ is_error: true, api_error_status: 400, result: apiError }),
527 apiError,
528 ],
529 [
530 "the verbose stdout error over a stderr notice",
531 JSON.stringify([
532 { type: "system", subtype: "init" },
533 { type: "result", is_error: true, result: apiError },
534 { type: "result", is_error: true, result: " " },
535 ]),
536 apiError,
537 ],
538 ["stderr when stdout has no error", "not json", wrapperNotice],
539 ] as const)("reports %s when the Claude CLI fails", ([, output, expected]) =>
540 withFakeClaudeEnv({ output, stderr: wrapperNotice, exitCode: 1 }, (textGeneration) =>
541 Effect.gen(function* () {
542 const error = yield* Effect.flip(
543 textGeneration.generateThreadTitle({
544 cwd: process.cwd(),
545 message: "Name this thread",
546 modelSelection: {
547 instanceId: ProviderInstanceId.make("claudeAgent"),
548 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
549 },
550 }),
551 );
552
553 expect(error.detail).toBe(`Claude CLI command failed: ${expected}`);
554 }),
555 ),
556 );
557
558 it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
559 withFakeClaudeEnv(
560 {
561 output: JSON.stringify({
562 structured_output: {
563 title: ' """ """ ',
564 },
565 }),
566 },
567 (textGeneration) =>
568 Effect.gen(function* () {
569 const generated = yield* textGeneration.generateThreadTitle({
570 cwd: process.cwd(),
571 message: "Name this thread.",
572 modelSelection: {
573 instanceId: ProviderInstanceId.make("claudeAgent"),
574 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
575 },
576 });
577
578 expect(generated.title).toBe("New thread");
579 }),
580 ),
581 );
582});