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