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 argsMustNotContain?: string;
66 stdinMustContain?: string;
67 configDirMustBe?: string;
68 cwdMustNotBe?: string;
69 claudeConfig?: Partial<ClaudeSettings>;
70 },
71 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
72) {
73 return Effect.gen(function* () {
74 const fs = yield* FileSystem.FileSystem;
75 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
76 const binDir = yield* makeFakeClaudeBinary(tempDir, input.lifecyclePort);
77 const pathDelimiter = (yield* HostProcess.isWindows) ? ";" : ":";
78 const previousPath = process.env.PATH;
79 const previousRejectsNoSessionPersistence =
80 process.env.T3_FAKE_CLAUDE_REJECTS_NO_SESSION_PERSISTENCE;
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.rejectsNoSessionPersistence) {
96 process.env.T3_FAKE_CLAUDE_REJECTS_NO_SESSION_PERSISTENCE = "1";
97 } else {
98 delete process.env.T3_FAKE_CLAUDE_REJECTS_NO_SESSION_PERSISTENCE;
99 }
100
101 if (input.exitCode !== undefined) {
102 process.env.T3_FAKE_CLAUDE_EXIT_CODE = String(input.exitCode);
103 } else {
104 delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
105 }
106
107 if (input.stderr !== undefined) {
108 process.env.T3_FAKE_CLAUDE_STDERR = input.stderr;
109 } else {
110 delete process.env.T3_FAKE_CLAUDE_STDERR;
111 }
112
113 if (input.argsMustContain !== undefined) {
114 process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = input.argsMustContain;
115 } else {
116 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
117 }
118
119 if (input.argsMustNotContain !== undefined) {
120 process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = input.argsMustNotContain;
121 } else {
122 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
123 }
124
125 if (input.stdinMustContain !== undefined) {
126 process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = input.stdinMustContain;
127 } else {
128 delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
129 }
130
131 if (input.cwdMustNotBe !== undefined) {
132 process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE = input.cwdMustNotBe;
133 } else {
134 delete process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE;
135 }
136
137 if (input.configDirMustBe !== undefined) {
138 process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = input.configDirMustBe;
139 } else {
140 delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
141 }
142 }),
143 () =>
144 Effect.sync(() => {
145 process.env.PATH = previousPath;
146
147 if (previousRejectsNoSessionPersistence === undefined) {
148 delete process.env.T3_FAKE_CLAUDE_REJECTS_NO_SESSION_PERSISTENCE;
149 } else {
150 process.env.T3_FAKE_CLAUDE_REJECTS_NO_SESSION_PERSISTENCE =
151 previousRejectsNoSessionPersistence;
152 }
153
154 if (previousOutput === undefined) {
155 delete process.env.T3_FAKE_CLAUDE_OUTPUT;
156 } else {
157 process.env.T3_FAKE_CLAUDE_OUTPUT = previousOutput;
158 }
159
160 if (previousExitCode === undefined) {
161 delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
162 } else {
163 process.env.T3_FAKE_CLAUDE_EXIT_CODE = previousExitCode;
164 }
165
166 if (previousStderr === undefined) {
167 delete process.env.T3_FAKE_CLAUDE_STDERR;
168 } else {
169 process.env.T3_FAKE_CLAUDE_STDERR = previousStderr;
170 }
171
172 if (previousArgsMustContain === undefined) {
173 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
174 } else {
175 process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previousArgsMustContain;
176 }
177
178 if (previousArgsMustNotContain === undefined) {
179 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
180 } else {
181 process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previousArgsMustNotContain;
182 }
183
184 if (previousStdinMustContain === undefined) {
185 delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
186 } else {
187 process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previousStdinMustContain;
188 }
189
190 if (previousCwdMustNotBe === undefined) {
191 delete process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE;
192 } else {
193 process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE = previousCwdMustNotBe;
194 }
195
196 if (previousConfigDirMustBe === undefined) {
197 delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
198 } else {
199 process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = previousConfigDirMustBe;
200 }
201 }),
202 );
203
204 const config = decodeClaudeSettings(input.claudeConfig ?? {});
205 const textGeneration = yield* makeClaudeTextGeneration(
206 config,
207 undefined,
208 Effect.succeed(SYNTHETIC_CLAUDE_MODEL_CATALOG),
209 );
210 return yield* effectFn(textGeneration);
211 }).pipe(Effect.scoped);
212}
213
214it.layer(layerClaudeTextGenerationTest)("ClaudeTextGeneration", (it) => {
215 it.effect(
216 "keeps canonical built-in capabilities when a custom model collides with its alias",
217 () =>
218 withFakeClaudeEnv(
219 {
220 output: JSON.stringify({
221 structured_output: {
222 title: "Improve orchestration flow",
223 body: "Body",
224 },
225 }),
226 argsMustContain: `--model ${SYNTHETIC_CLAUDE_CAPABLE_MODEL}[expanded] --effort max --settings {"disableAllHooks":true,"fastMode":true}`,
227 claudeConfig: { customModels: [SYNTHETIC_CLAUDE_COLLIDING_ALIAS] },
228 },
229 (textGeneration) =>
230 Effect.gen(function* () {
231 const generated = yield* textGeneration.generatePrContent({
232 cwd: process.cwd(),
233 baseBranch: "main",
234 headBranch: "feature/claude-effect",
235 commitSummary: "Improve orchestration",
236 diffSummary: "1 file changed",
237 diffPatch: "diff --git a/README.md b/README.md",
238 modelSelection: {
239 ...createModelSelection(
240 ProviderInstanceId.make("claudeAgent"),
241 SYNTHETIC_CLAUDE_CAPABLE_MODEL,
242 [
243 { id: "effort", value: "max" },
244 { id: "fastMode", value: true },
245 ],
246 ),
247 },
248 });
249
250 expect(generated.title).toBe("Improve orchestration flow");
251 }),
252 ),
253 );
254
255 it.effect(
256 "generates thread titles outside the project with tools, skills, and hooks disabled",
257 () =>
258 withFakeClaudeEnv(
259 {
260 output: JSON.stringify({
261 structured_output: {
262 title:
263 ' "Reconnect failures after restart because the session state does not recover" ',
264 },
265 }),
266 cwdMustNotBe: process.cwd(),
267 stdinMustContain: "/call-script",
268 },
269 (textGeneration) =>
270 Effect.gen(function* () {
271 const generated = yield* textGeneration.generateThreadTitle({
272 cwd: process.cwd(),
273 message: "/call-script",
274 modelSelection: {
275 instanceId: ProviderInstanceId.make("claudeAgent"),
276 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
277 },
278 });
279
280 expect(generated.title).toBe(
281 sanitizeThreadTitle(
282 '"Reconnect failures after restart because the session state does not recover"',
283 ),
284 );
285 }),
286 ),
287 );
288
289 it.effect("sends thread title instructions to the provider prompt", () =>
290 withFakeClaudeEnv(
291 {
292 output: JSON.stringify({ structured_output: { title: "Reconnect failures" } }),
293 stdinMustContain: "Additional instructions:\nUse two to four words.",
294 },
295 (textGeneration) =>
296 textGeneration.generateThreadTitle({
297 cwd: process.cwd(),
298 message: "Investigate reconnect failures",
299 instructions: "Use two to four words.",
300 modelSelection: {
301 instanceId: ProviderInstanceId.make("claudeAgent"),
302 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
303 },
304 }),
305 ),
306 );
307
308 it.effect("runs Claude text generation with the configured CLAUDE_CONFIG_DIR", () =>
309 Effect.gen(function* () {
310 const path = yield* Path.Path;
311 const claudeConfigDir = path.join(process.cwd(), ".claude-work-test");
312 return yield* withFakeClaudeEnv(
313 {
314 output: JSON.stringify({
315 structured_output: {
316 title: "Use Claude home",
317 },
318 }),
319 configDirMustBe: claudeConfigDir,
320 claudeConfig: { homePath: claudeConfigDir },
321 },
322 (textGeneration) =>
323 Effect.gen(function* () {
324 const generated = yield* textGeneration.generateThreadTitle({
325 cwd: process.cwd(),
326 message: "thread title",
327 modelSelection: {
328 instanceId: ProviderInstanceId.make("claudeAgent"),
329 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
330 },
331 });
332
333 expect(generated.title).toBe(sanitizeThreadTitle("Use Claude home"));
334 }),
335 );
336 }),
337 );
338
339 it.effect("retries without --no-session-persistence when the Claude CLI rejects it", () =>
340 withFakeClaudeEnv(
341 {
342 output: JSON.stringify({ structured_output: { title: "Reconnect failures" } }),
343 rejectsNoSessionPersistence: true,
344 },
345 (textGeneration) =>
346 Effect.gen(function* () {
347 const generated = yield* textGeneration.generateThreadTitle({
348 cwd: process.cwd(),
349 message: "Investigate reconnect failures",
350 modelSelection: {
351 instanceId: ProviderInstanceId.make("claudeAgent"),
352 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
353 },
354 });
355
356 expect(generated.title).toBe("Reconnect failures");
357 }),
358 ),
359 );
360
361 it.effect.each([
362 { verbose: false, label: "normal" },
363 { verbose: true, label: "verbose" },
364 ])("unwraps a JSON title in $label Claude output", ({ verbose }) => {
365 const result = {
366 type: "result",
367 structured_output: { title: '{"title": "Refresh ev-stg APP ASG instances"}' },
368 };
369 return withFakeClaudeEnv(
370 { output: JSON.stringify(verbose ? [result] : result) },
371 (textGeneration) =>
372 Effect.gen(function* () {
373 const generated = yield* textGeneration.generateThreadTitle({
374 cwd: process.cwd(),
375 message: "Refresh ev-stg APP ASG instances",
376 modelSelection: {
377 instanceId: ProviderInstanceId.make("claudeAgent"),
378 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
379 },
380 });
381
382 expect(generated.title).toBe("Refresh ev-stg APP ASG instances");
383 }),
384 );
385 });
386
387 it.effect.each([
388 { previousTitle: undefined, label: "generating" },
389 { previousTitle: "Old thread title", label: "regenerating" },
390 ])("reads the result from verbose Claude output when $label a title", ({ previousTitle }) =>
391 withFakeClaudeEnv(
392 {
393 output: JSON.stringify([
394 { type: "system", subtype: "init" },
395 { type: "assistant", message: { content: [] } },
396 { type: "user", message: { content: [] } },
397 { type: "rate_limit_event" },
398 {
399 type: "result",
400 subtype: "success",
401 result: '{"title":"Refresh ev-stg APP ASG Instances"}',
402 structured_output: { title: "Refresh ev-stg APP ASG Instances" },
403 },
404 ]),
405 },
406 (textGeneration) =>
407 Effect.gen(function* () {
408 const generated = yield* textGeneration.generateThreadTitle({
409 cwd: process.cwd(),
410 message: "Refresh ev-stg APP ASG instances",
411 previousTitle,
412 modelSelection: {
413 instanceId: ProviderInstanceId.make("claudeAgent"),
414 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
415 },
416 });
417
418 expect(generated.title).toBe("Refresh ev-stg APP ASG Instances");
419 }),
420 ),
421 );
422
423 it.effect.each([
424 ["empty message array", []],
425 ["missing result", [{ type: "assistant", structured_output: { title: "Not a result" } }]],
426 ["invalid title", [{ type: "result", structured_output: { title: 42 } }]],
427 [
428 "final result without structured output",
429 [
430 { type: "result", structured_output: { title: "Earlier result" } },
431 { type: "result", subtype: "error_max_structured_output_retries" },
432 ],
433 ],
434 ] as const)("rejects verbose Claude output with %s", ([, output]) =>
435 withFakeClaudeEnv({ output: JSON.stringify(output) }, (textGeneration) =>
436 Effect.gen(function* () {
437 const error = yield* Effect.flip(
438 textGeneration.generateThreadTitle({
439 cwd: process.cwd(),
440 message: "Name this thread",
441 modelSelection: {
442 instanceId: ProviderInstanceId.make("claudeAgent"),
443 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
444 },
445 }),
446 );
447
448 expect(error._tag).toBe("TextGenerationError");
449 }),
450 ),
451 );
452
453 const apiError = "API Error: 400 Model blocked by guardrail: 4 endpoints excluded";
454 const wrapperNotice = "Using the OpenRouter credential from the global credential file.";
455 it.effect.each([
456 [
457 "the stdout error over a stderr notice",
458 JSON.stringify({ is_error: true, api_error_status: 400, result: apiError }),
459 apiError,
460 ],
461 [
462 "the verbose stdout error over a stderr notice",
463 JSON.stringify([
464 { type: "system", subtype: "init" },
465 { type: "result", is_error: true, result: apiError },
466 { type: "result", is_error: true, result: " " },
467 ]),
468 apiError,
469 ],
470 ["stderr when stdout has no error", "not json", wrapperNotice],
471 [
472 "a stdout error naming --no-session-persistence without retrying",
473 JSON.stringify({
474 is_error: true,
475 result: "error: unknown option '--no-session-persistence'",
476 }),
477 "error: unknown option '--no-session-persistence'",
478 ],
479 ] as const)("reports %s when the Claude CLI fails", ([, output, expected]) =>
480 withFakeClaudeEnv({ output, stderr: wrapperNotice, exitCode: 1 }, (textGeneration) =>
481 Effect.gen(function* () {
482 const error = yield* Effect.flip(
483 textGeneration.generateThreadTitle({
484 cwd: process.cwd(),
485 message: "Name this thread",
486 modelSelection: {
487 instanceId: ProviderInstanceId.make("claudeAgent"),
488 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
489 },
490 }),
491 );
492
493 expect(error.detail).toBe(`Claude CLI command failed: ${expected}`);
494 }),
495 ),
496 );
497});