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("forwards Claude thinking settings without passing unsupported effort", () =>
228 withFakeClaudeEnv(
229 {
230 output: JSON.stringify({
231 structured_output: {
232 subject: "Add important change",
233 body: "",
234 },
235 }),
236 argsMustContain: '--settings {"disableAllHooks":true,"alwaysThinkingEnabled":false}',
237 argsMustNotContain: "--effort",
238 },
239 (textGeneration) =>
240 Effect.gen(function* () {
241 const generated = yield* textGeneration.generateCommitMessage({
242 cwd: process.cwd(),
243 branch: "feature/claude-effect",
244 stagedSummary: "M README.md",
245 stagedPatch: "diff --git a/README.md b/README.md",
246 modelSelection: {
247 ...createModelSelection(
248 ProviderInstanceId.make("claudeAgent"),
249 SYNTHETIC_CLAUDE_THINKING_MODEL,
250 [
251 { id: "thinking", value: false },
252 { id: "effort", value: "high" },
253 ],
254 ),
255 },
256 });
257
258 expect(generated.subject).toBe("Add important change");
259 }),
260 ),
261 );
262
263 it.effect("keeps a configured custom alias opaque to the Claude CLI", () =>
264 withFakeClaudeEnv(
265 {
266 output: JSON.stringify({
267 structured_output: {
268 title: "Keep custom model",
269 body: "",
270 },
271 }),
272 argsMustContain: `--model ${SYNTHETIC_CLAUDE_COLLIDING_ALIAS} --effort max --settings`,
273 claudeConfig: { customModels: [SYNTHETIC_CLAUDE_COLLIDING_ALIAS] },
274 },
275 (textGeneration) =>
276 Effect.gen(function* () {
277 const generated = yield* textGeneration.generatePrContent({
278 cwd: process.cwd(),
279 baseBranch: "main",
280 headBranch: "feature/custom-model",
281 commitSummary: "Keep custom model",
282 diffSummary: "1 file changed",
283 diffPatch: "diff --git a/README.md b/README.md",
284 modelSelection: createModelSelection(
285 ProviderInstanceId.make("claudeAgent"),
286 SYNTHETIC_CLAUDE_COLLIDING_ALIAS,
287 [
288 { id: "effort", value: "max" },
289 { id: "fastMode", value: true },
290 { id: "contextWindow", value: "expanded" },
291 ],
292 ),
293 });
294
295 expect(generated.title).toBe("Keep custom model");
296 }),
297 ),
298 );
299
300 it.effect(
301 "keeps canonical built-in capabilities when a custom model collides with its alias",
302 () =>
303 withFakeClaudeEnv(
304 {
305 output: JSON.stringify({
306 structured_output: {
307 title: "Improve orchestration flow",
308 body: "Body",
309 },
310 }),
311 argsMustContain: `--model ${SYNTHETIC_CLAUDE_CAPABLE_MODEL}[expanded] --effort max --settings {"disableAllHooks":true,"fastMode":true}`,
312 claudeConfig: { customModels: [SYNTHETIC_CLAUDE_COLLIDING_ALIAS] },
313 },
314 (textGeneration) =>
315 Effect.gen(function* () {
316 const generated = yield* textGeneration.generatePrContent({
317 cwd: process.cwd(),
318 baseBranch: "main",
319 headBranch: "feature/claude-effect",
320 commitSummary: "Improve orchestration",
321 diffSummary: "1 file changed",
322 diffPatch: "diff --git a/README.md b/README.md",
323 modelSelection: {
324 ...createModelSelection(
325 ProviderInstanceId.make("claudeAgent"),
326 SYNTHETIC_CLAUDE_CAPABLE_MODEL,
327 [
328 { id: "effort", value: "max" },
329 { id: "fastMode", value: true },
330 ],
331 ),
332 },
333 });
334
335 expect(generated.title).toBe("Improve orchestration flow");
336 }),
337 ),
338 );
339
340 it.effect(
341 "generates thread titles outside the project with tools, skills, and hooks disabled",
342 () =>
343 withFakeClaudeEnv(
344 {
345 output: JSON.stringify({
346 structured_output: {
347 title:
348 ' "Reconnect failures after restart because the session state does not recover" ',
349 },
350 }),
351 cwdMustNotBe: process.cwd(),
352 stdinMustContain: "/call-script",
353 },
354 (textGeneration) =>
355 Effect.gen(function* () {
356 const generated = yield* textGeneration.generateThreadTitle({
357 cwd: process.cwd(),
358 message: "/call-script",
359 modelSelection: {
360 instanceId: ProviderInstanceId.make("claudeAgent"),
361 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
362 },
363 });
364
365 expect(generated.title).toBe(
366 sanitizeThreadTitle(
367 '"Reconnect failures after restart because the session state does not recover"',
368 ),
369 );
370 }),
371 ),
372 );
373
374 it.effect("generates branch names from skill prompts without executable capabilities", () =>
375 withFakeClaudeEnv(
376 {
377 output: JSON.stringify({ structured_output: { branch: "call-script" } }),
378 stdinMustContain: "/call-script",
379 },
380 (textGeneration) =>
381 Effect.gen(function* () {
382 const generated = yield* textGeneration.generateBranchName({
383 cwd: process.cwd(),
384 message: "/call-script",
385 modelSelection: {
386 instanceId: ProviderInstanceId.make("claudeAgent"),
387 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
388 },
389 });
390
391 expect(generated.branch).toBe("call-script");
392 }),
393 ),
394 );
395
396 it.effect("runs Claude text generation with the configured CLAUDE_CONFIG_DIR", () =>
397 Effect.gen(function* () {
398 const path = yield* Path.Path;
399 const claudeConfigDir = path.join(process.cwd(), ".claude-work-test");
400 return yield* withFakeClaudeEnv(
401 {
402 output: JSON.stringify({
403 structured_output: {
404 title: "Use Claude home",
405 },
406 }),
407 configDirMustBe: claudeConfigDir,
408 claudeConfig: { homePath: claudeConfigDir },
409 },
410 (textGeneration) =>
411 Effect.gen(function* () {
412 const generated = yield* textGeneration.generateThreadTitle({
413 cwd: process.cwd(),
414 message: "thread title",
415 modelSelection: {
416 instanceId: ProviderInstanceId.make("claudeAgent"),
417 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
418 },
419 });
420
421 expect(generated.title).toBe(sanitizeThreadTitle("Use Claude home"));
422 }),
423 );
424 }),
425 );
426
427 it.effect.each([
428 { verbose: false, label: "normal" },
429 { verbose: true, label: "verbose" },
430 ])("unwraps a JSON title in $label Claude output", ({ verbose }) => {
431 const result = {
432 type: "result",
433 structured_output: { title: '{"title": "Refresh ev-stg APP ASG instances"}' },
434 };
435 return withFakeClaudeEnv(
436 { output: JSON.stringify(verbose ? [result] : result) },
437 (textGeneration) =>
438 Effect.gen(function* () {
439 const generated = yield* textGeneration.generateThreadTitle({
440 cwd: process.cwd(),
441 message: "Refresh ev-stg APP ASG instances",
442 modelSelection: {
443 instanceId: ProviderInstanceId.make("claudeAgent"),
444 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
445 },
446 });
447
448 expect(generated.title).toBe("Refresh ev-stg APP ASG instances");
449 }),
450 );
451 });
452
453 it.effect.each([
454 { previousTitle: undefined, label: "generating" },
455 { previousTitle: "Old thread title", label: "regenerating" },
456 ])("reads the result from verbose Claude output when $label a title", ({ previousTitle }) =>
457 withFakeClaudeEnv(
458 {
459 output: JSON.stringify([
460 { type: "system", subtype: "init" },
461 { type: "assistant", message: { content: [] } },
462 { type: "user", message: { content: [] } },
463 { type: "rate_limit_event" },
464 {
465 type: "result",
466 subtype: "success",
467 result: '{"title":"Refresh ev-stg APP ASG Instances"}',
468 structured_output: { title: "Refresh ev-stg APP ASG Instances" },
469 },
470 ]),
471 },
472 (textGeneration) =>
473 Effect.gen(function* () {
474 const generated = yield* textGeneration.generateThreadTitle({
475 cwd: process.cwd(),
476 message: "Refresh ev-stg APP ASG instances",
477 previousTitle,
478 modelSelection: {
479 instanceId: ProviderInstanceId.make("claudeAgent"),
480 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
481 },
482 });
483
484 expect(generated.title).toBe("Refresh ev-stg APP ASG Instances");
485 }),
486 ),
487 );
488
489 it.effect.each([
490 ["empty message array", []],
491 ["missing result", [{ type: "assistant", structured_output: { title: "Not a result" } }]],
492 ["invalid title", [{ type: "result", structured_output: { title: 42 } }]],
493 [
494 "final result without structured output",
495 [
496 { type: "result", structured_output: { title: "Earlier result" } },
497 { type: "result", subtype: "error_max_structured_output_retries" },
498 ],
499 ],
500 ] as const)("rejects verbose Claude output with %s", ([, output]) =>
501 withFakeClaudeEnv({ output: JSON.stringify(output) }, (textGeneration) =>
502 Effect.gen(function* () {
503 const error = yield* Effect.flip(
504 textGeneration.generateThreadTitle({
505 cwd: process.cwd(),
506 message: "Name this thread",
507 modelSelection: {
508 instanceId: ProviderInstanceId.make("claudeAgent"),
509 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
510 },
511 }),
512 );
513
514 expect(error._tag).toBe("TextGenerationError");
515 }),
516 ),
517 );
518
519 const apiError = "API Error: 400 Model blocked by guardrail: 4 endpoints excluded";
520 const wrapperNotice = "Using the OpenRouter credential from the global credential file.";
521 it.effect.each([
522 [
523 "the stdout error over a stderr notice",
524 JSON.stringify({ is_error: true, api_error_status: 400, result: apiError }),
525 apiError,
526 ],
527 [
528 "the verbose stdout error over a stderr notice",
529 JSON.stringify([
530 { type: "system", subtype: "init" },
531 { type: "result", is_error: true, result: apiError },
532 { type: "result", is_error: true, result: " " },
533 ]),
534 apiError,
535 ],
536 ["stderr when stdout has no error", "not json", wrapperNotice],
537 ] as const)("reports %s when the Claude CLI fails", ([, output, expected]) =>
538 withFakeClaudeEnv({ output, stderr: wrapperNotice, exitCode: 1 }, (textGeneration) =>
539 Effect.gen(function* () {
540 const error = yield* Effect.flip(
541 textGeneration.generateThreadTitle({
542 cwd: process.cwd(),
543 message: "Name this thread",
544 modelSelection: {
545 instanceId: ProviderInstanceId.make("claudeAgent"),
546 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
547 },
548 }),
549 );
550
551 expect(error.detail).toBe(`Claude CLI command failed: ${expected}`);
552 }),
553 ),
554 );
555
556 it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
557 withFakeClaudeEnv(
558 {
559 output: JSON.stringify({
560 structured_output: {
561 title: ' """ """ ',
562 },
563 }),
564 },
565 (textGeneration) =>
566 Effect.gen(function* () {
567 const generated = yield* textGeneration.generateThreadTitle({
568 cwd: process.cwd(),
569 message: "Name this thread.",
570 modelSelection: {
571 instanceId: ProviderInstanceId.make("claudeAgent"),
572 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
573 },
574 });
575
576 expect(generated.title).toBe("New thread");
577 }),
578 ),
579 );
580});