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