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 { 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 argv = process.argv.slice(2);",
45 'const args = argv.join(" ");',
46 'const { realpathSync } = await import("node:fs");',
47 "",
48 "function fail(message, code) {",
49 ' process.stderr.write(message + "\\n");',
50 " process.exit(code);",
51 "}",
52 "",
53 'const toolsIndex = argv.indexOf("--tools");',
54 'if (toolsIndex === -1 || argv[toolsIndex + 1] !== "") {',
55 ' fail("text generation must receive an explicit empty tool set", 6);',
56 "}",
57 'if (argv.includes("--dangerously-skip-permissions")) {',
58 ' fail("text generation must not bypass permissions", 7);',
59 "}",
60 'if (!argv.includes("--disable-slash-commands")) {',
61 ' fail("text generation must disable skills", 8);',
62 "}",
63 'if (!argv.includes("--strict-mcp-config")) {',
64 ' fail("text generation must not load configured MCP servers", 9);',
65 "}",
66 'const settingsIndex = argv.indexOf("--settings");',
67 "if (settingsIndex === -1 || JSON.parse(argv[settingsIndex + 1]).disableAllHooks !== true) {",
68 ' fail("text generation must disable hooks", 10);',
69 "}",
70 "const cwdMustNotBe = process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE;",
71 "if (cwdMustNotBe && realpathSync(process.cwd()) === realpathSync(cwdMustNotBe)) {",
72 ' fail("text generation ran in the project directory", 11);',
73 "}",
74 "",
75 'let stdinContent = "";',
76 "if (!process.stdin.isTTY) {",
77 " const chunks = [];",
78 " for await (const chunk of process.stdin) {",
79 " chunks.push(chunk);",
80 " }",
81 ' stdinContent = Buffer.concat(chunks).toString("utf8");',
82 "}",
83 "",
84 "const argsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;",
85 "if (argsMustContain && !args.includes(argsMustContain)) {",
86 ' fail("args missing expected content", 2);',
87 "}",
88 "",
89 "const argsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;",
90 "if (argsMustNotContain && args.includes(argsMustNotContain)) {",
91 ' fail("args contained forbidden content", 3);',
92 "}",
93 "",
94 "const stdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;",
95 "if (stdinMustContain && !stdinContent.includes(stdinMustContain)) {",
96 ' fail("stdin missing expected content", 4);',
97 "}",
98 "",
99 "const configDirMustBe = process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;",
100 "if (configDirMustBe && process.env.CLAUDE_CONFIG_DIR !== configDirMustBe) {",
101 ' fail("CLAUDE_CONFIG_DIR was " + (process.env.CLAUDE_CONFIG_DIR ?? ""), 5);',
102 "}",
103 "",
104 "const stderrText = process.env.T3_FAKE_CLAUDE_STDERR;",
105 "if (stderrText) {",
106 ' process.stderr.write(stderrText + "\\n");',
107 "}",
108 "",
109 'process.stdout.write(process.env.T3_FAKE_CLAUDE_OUTPUT ?? "");',
110 "process.exitCode = Number(process.env.T3_FAKE_CLAUDE_EXIT_CODE ?? 0);",
111 "",
112 ].join("\n"),
113 });
114 return binDir;
115 });
116}
117
118function withFakeClaudeEnv<A, E, R>(
119 input: {
120 output: string;
121 exitCode?: number;
122 stderr?: string;
123 argsMustContain?: string;
124 argsMustNotContain?: string;
125 stdinMustContain?: string;
126 configDirMustBe?: string;
127 cwdMustNotBe?: string;
128 claudeConfig?: Partial<ClaudeSettings>;
129 },
130 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
131) {
132 return Effect.gen(function* () {
133 const fs = yield* FileSystem.FileSystem;
134 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
135 const binDir = yield* makeFakeClaudeBinary(tempDir);
136 const pathDelimiter = (yield* isHostWindows) ? ";" : ":";
137 const previousPath = process.env.PATH;
138 const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;
139 const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;
140 const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;
141 const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
142 const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
143 const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
144 const previousConfigDirMustBe = process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
145 const previousCwdMustNotBe = process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE;
146
147 yield* Effect.acquireRelease(
148 Effect.sync(() => {
149 process.env.PATH = `${binDir}${pathDelimiter}${previousPath ?? ""}`;
150 process.env.T3_FAKE_CLAUDE_OUTPUT = input.output;
151
152 if (input.exitCode !== undefined) {
153 process.env.T3_FAKE_CLAUDE_EXIT_CODE = String(input.exitCode);
154 } else {
155 delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
156 }
157
158 if (input.stderr !== undefined) {
159 process.env.T3_FAKE_CLAUDE_STDERR = input.stderr;
160 } else {
161 delete process.env.T3_FAKE_CLAUDE_STDERR;
162 }
163
164 if (input.argsMustContain !== undefined) {
165 process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = input.argsMustContain;
166 } else {
167 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
168 }
169
170 if (input.argsMustNotContain !== undefined) {
171 process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = input.argsMustNotContain;
172 } else {
173 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
174 }
175
176 if (input.stdinMustContain !== undefined) {
177 process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = input.stdinMustContain;
178 } else {
179 delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
180 }
181
182 if (input.cwdMustNotBe !== undefined) {
183 process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE = input.cwdMustNotBe;
184 } else {
185 delete process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE;
186 }
187
188 if (input.configDirMustBe !== undefined) {
189 process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = input.configDirMustBe;
190 } else {
191 delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
192 }
193 }),
194 () =>
195 Effect.sync(() => {
196 process.env.PATH = previousPath;
197
198 if (previousOutput === undefined) {
199 delete process.env.T3_FAKE_CLAUDE_OUTPUT;
200 } else {
201 process.env.T3_FAKE_CLAUDE_OUTPUT = previousOutput;
202 }
203
204 if (previousExitCode === undefined) {
205 delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
206 } else {
207 process.env.T3_FAKE_CLAUDE_EXIT_CODE = previousExitCode;
208 }
209
210 if (previousStderr === undefined) {
211 delete process.env.T3_FAKE_CLAUDE_STDERR;
212 } else {
213 process.env.T3_FAKE_CLAUDE_STDERR = previousStderr;
214 }
215
216 if (previousArgsMustContain === undefined) {
217 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
218 } else {
219 process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previousArgsMustContain;
220 }
221
222 if (previousArgsMustNotContain === undefined) {
223 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
224 } else {
225 process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previousArgsMustNotContain;
226 }
227
228 if (previousStdinMustContain === undefined) {
229 delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
230 } else {
231 process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previousStdinMustContain;
232 }
233
234 if (previousCwdMustNotBe === undefined) {
235 delete process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE;
236 } else {
237 process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE = previousCwdMustNotBe;
238 }
239
240 if (previousConfigDirMustBe === undefined) {
241 delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
242 } else {
243 process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = previousConfigDirMustBe;
244 }
245 }),
246 );
247
248 const config = decodeClaudeSettings(input.claudeConfig ?? {});
249 const textGeneration = yield* makeClaudeTextGeneration(
250 config,
251 undefined,
252 Effect.succeed(SYNTHETIC_CLAUDE_MODEL_CATALOG),
253 );
254 return yield* effectFn(textGeneration);
255 }).pipe(Effect.scoped);
256}
257
258it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {
259 it.effect("forwards Claude thinking settings without passing unsupported effort", () =>
260 withFakeClaudeEnv(
261 {
262 output: JSON.stringify({
263 structured_output: {
264 subject: "Add important change",
265 body: "",
266 },
267 }),
268 argsMustContain: '--settings {"disableAllHooks":true,"alwaysThinkingEnabled":false}',
269 argsMustNotContain: "--effort",
270 },
271 (textGeneration) =>
272 Effect.gen(function* () {
273 const generated = yield* textGeneration.generateCommitMessage({
274 cwd: process.cwd(),
275 branch: "feature/claude-effect",
276 stagedSummary: "M README.md",
277 stagedPatch: "diff --git a/README.md b/README.md",
278 modelSelection: {
279 ...createModelSelection(
280 ProviderInstanceId.make("claudeAgent"),
281 SYNTHETIC_CLAUDE_THINKING_MODEL,
282 [
283 { id: "thinking", value: false },
284 { id: "effort", value: "high" },
285 ],
286 ),
287 },
288 });
289
290 expect(generated.subject).toBe("Add important change");
291 }),
292 ),
293 );
294
295 it.effect("keeps a configured custom alias opaque to the Claude CLI", () =>
296 withFakeClaudeEnv(
297 {
298 output: JSON.stringify({
299 structured_output: {
300 title: "Keep custom model",
301 body: "",
302 },
303 }),
304 argsMustContain: `--model ${SYNTHETIC_CLAUDE_COLLIDING_ALIAS} --settings`,
305 claudeConfig: { customModels: [SYNTHETIC_CLAUDE_COLLIDING_ALIAS] },
306 },
307 (textGeneration) =>
308 Effect.gen(function* () {
309 const generated = yield* textGeneration.generatePrContent({
310 cwd: process.cwd(),
311 baseBranch: "main",
312 headBranch: "feature/custom-model",
313 commitSummary: "Keep custom model",
314 diffSummary: "1 file changed",
315 diffPatch: "diff --git a/README.md b/README.md",
316 modelSelection: createModelSelection(
317 ProviderInstanceId.make("claudeAgent"),
318 SYNTHETIC_CLAUDE_COLLIDING_ALIAS,
319 [
320 { id: "effort", value: "max" },
321 { id: "fastMode", value: true },
322 { id: "contextWindow", value: "expanded" },
323 ],
324 ),
325 });
326
327 expect(generated.title).toBe("Keep custom model");
328 }),
329 ),
330 );
331
332 it.effect(
333 "keeps canonical built-in capabilities when a custom model collides with its alias",
334 () =>
335 withFakeClaudeEnv(
336 {
337 output: JSON.stringify({
338 structured_output: {
339 title: "Improve orchestration flow",
340 body: "Body",
341 },
342 }),
343 argsMustContain: `--model ${SYNTHETIC_CLAUDE_CAPABLE_MODEL}[expanded] --effort max --settings {"disableAllHooks":true,"fastMode":true}`,
344 claudeConfig: { customModels: [SYNTHETIC_CLAUDE_COLLIDING_ALIAS] },
345 },
346 (textGeneration) =>
347 Effect.gen(function* () {
348 const generated = yield* textGeneration.generatePrContent({
349 cwd: process.cwd(),
350 baseBranch: "main",
351 headBranch: "feature/claude-effect",
352 commitSummary: "Improve orchestration",
353 diffSummary: "1 file changed",
354 diffPatch: "diff --git a/README.md b/README.md",
355 modelSelection: {
356 ...createModelSelection(
357 ProviderInstanceId.make("claudeAgent"),
358 SYNTHETIC_CLAUDE_CAPABLE_MODEL,
359 [
360 { id: "effort", value: "max" },
361 { id: "fastMode", value: true },
362 ],
363 ),
364 },
365 });
366
367 expect(generated.title).toBe("Improve orchestration flow");
368 }),
369 ),
370 );
371
372 it.effect(
373 "generates thread titles outside the project with tools, skills, and hooks disabled",
374 () =>
375 withFakeClaudeEnv(
376 {
377 output: JSON.stringify({
378 structured_output: {
379 title:
380 ' "Reconnect failures after restart because the session state does not recover" ',
381 },
382 }),
383 cwdMustNotBe: process.cwd(),
384 stdinMustContain: "/call-script",
385 },
386 (textGeneration) =>
387 Effect.gen(function* () {
388 const generated = yield* textGeneration.generateThreadTitle({
389 cwd: process.cwd(),
390 message: "/call-script",
391 modelSelection: {
392 instanceId: ProviderInstanceId.make("claudeAgent"),
393 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
394 },
395 });
396
397 expect(generated.title).toBe(
398 sanitizeThreadTitle(
399 '"Reconnect failures after restart because the session state does not recover"',
400 ),
401 );
402 }),
403 ),
404 );
405
406 it.effect("generates branch names from skill prompts without executable capabilities", () =>
407 withFakeClaudeEnv(
408 {
409 output: JSON.stringify({ structured_output: { branch: "call-script" } }),
410 stdinMustContain: "/call-script",
411 },
412 (textGeneration) =>
413 Effect.gen(function* () {
414 const generated = yield* textGeneration.generateBranchName({
415 cwd: process.cwd(),
416 message: "/call-script",
417 modelSelection: {
418 instanceId: ProviderInstanceId.make("claudeAgent"),
419 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
420 },
421 });
422
423 expect(generated.branch).toBe("call-script");
424 }),
425 ),
426 );
427
428 it.effect("runs Claude text generation with the configured CLAUDE_CONFIG_DIR", () =>
429 Effect.gen(function* () {
430 const path = yield* Path.Path;
431 const claudeConfigDir = path.join(process.cwd(), ".claude-work-test");
432 return yield* withFakeClaudeEnv(
433 {
434 // @effect-diagnostics-next-line preferSchemaOverJson:off
435 output: JSON.stringify({
436 structured_output: {
437 title: "Use Claude home",
438 },
439 }),
440 configDirMustBe: claudeConfigDir,
441 claudeConfig: { homePath: claudeConfigDir },
442 },
443 (textGeneration) =>
444 Effect.gen(function* () {
445 const generated = yield* textGeneration.generateThreadTitle({
446 cwd: process.cwd(),
447 message: "thread title",
448 modelSelection: {
449 instanceId: ProviderInstanceId.make("claudeAgent"),
450 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
451 },
452 });
453
454 expect(generated.title).toBe(sanitizeThreadTitle("Use Claude home"));
455 }),
456 );
457 }),
458 );
459
460 for (const verbose of [false, true]) {
461 it.effect(`unwraps a JSON title in ${verbose ? "verbose" : "normal"} Claude output`, () => {
462 const result = {
463 type: "result",
464 structured_output: { title: '{"title": "Refresh ev-stg APP ASG instances"}' },
465 };
466 return withFakeClaudeEnv(
467 { output: JSON.stringify(verbose ? [result] : result) },
468 (textGeneration) =>
469 Effect.gen(function* () {
470 const generated = yield* textGeneration.generateThreadTitle({
471 cwd: process.cwd(),
472 message: "Refresh ev-stg APP ASG instances",
473 modelSelection: {
474 instanceId: ProviderInstanceId.make("claudeAgent"),
475 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
476 },
477 });
478
479 expect(generated.title).toBe("Refresh ev-stg APP ASG instances");
480 }),
481 );
482 });
483 }
484
485 for (const previousTitle of [undefined, "Old thread title"]) {
486 it.effect(
487 `reads the result from verbose Claude output when ${previousTitle ? "regenerating" : "generating"} a title`,
488 () =>
489 withFakeClaudeEnv(
490 {
491 output: JSON.stringify([
492 { type: "system", subtype: "init" },
493 { type: "assistant", message: { content: [] } },
494 { type: "user", message: { content: [] } },
495 { type: "rate_limit_event" },
496 {
497 type: "result",
498 subtype: "success",
499 result: '{"title":"Refresh ev-stg APP ASG Instances"}',
500 structured_output: { title: "Refresh ev-stg APP ASG Instances" },
501 },
502 ]),
503 },
504 (textGeneration) =>
505 Effect.gen(function* () {
506 const generated = yield* textGeneration.generateThreadTitle({
507 cwd: process.cwd(),
508 message: "Refresh ev-stg APP ASG instances",
509 previousTitle,
510 modelSelection: {
511 instanceId: ProviderInstanceId.make("claudeAgent"),
512 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
513 },
514 });
515
516 expect(generated.title).toBe("Refresh ev-stg APP ASG Instances");
517 }),
518 ),
519 );
520 }
521
522 for (const [name, output] of [
523 ["empty message array", []],
524 ["missing result", [{ type: "assistant", structured_output: { title: "Not a result" } }]],
525 ["invalid title", [{ type: "result", structured_output: { title: 42 } }]],
526 [
527 "final result without structured output",
528 [
529 { type: "result", structured_output: { title: "Earlier result" } },
530 { type: "result", subtype: "error_max_structured_output_retries" },
531 ],
532 ],
533 ] as const) {
534 it.effect(`rejects verbose Claude output with ${name}`, () =>
535 withFakeClaudeEnv({ output: JSON.stringify(output) }, (textGeneration) =>
536 Effect.gen(function* () {
537 const error = yield* Effect.flip(
538 textGeneration.generateThreadTitle({
539 cwd: process.cwd(),
540 message: "Name this thread",
541 modelSelection: {
542 instanceId: ProviderInstanceId.make("claudeAgent"),
543 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
544 },
545 }),
546 );
547
548 expect(error._tag).toBe("TextGenerationError");
549 }),
550 ),
551 );
552 }
553
554 it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
555 withFakeClaudeEnv(
556 {
557 output: JSON.stringify({
558 structured_output: {
559 title: ' """ """ ',
560 },
561 }),
562 },
563 (textGeneration) =>
564 Effect.gen(function* () {
565 const generated = yield* textGeneration.generateThreadTitle({
566 cwd: process.cwd(),
567 message: "Name this thread.",
568 modelSelection: {
569 instanceId: ProviderInstanceId.make("claudeAgent"),
570 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
571 },
572 });
573
574 expect(generated.title).toBe("New thread");
575 }),
576 ),
577 );
578});