Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ClaudeTextGeneration.test.ts

673 lines24.4 KB

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 });
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 expectedTools?: string;
66 argsMustNotContain?: string;
67 stdinMustContain?: string;
68 imageRejection?: string;
69 imageAttemptLog?: string;
70 configDirMustBe?: string;
71 cwdMustNotBe?: string;
72 settingsLog?: string;
73 claudeConfig?: Partial<ClaudeSettings>;
74 },
75 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
76) {
77 return Effect.gen(function* () {
78 const fs = yield* FileSystem.FileSystem;
79 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
80 const binDir = yield* makeFakeClaudeBinary(tempDir, input.lifecyclePort);
81 const pathDelimiter = (yield* HostProcess.isWindows) ? ";" : ":";
82 const hostEnv = yield* HostProcess.Environment;
83 const fakeClaudeEnv: Record<string, string | undefined> = {
84 T3_FAKE_CLAUDE_OUTPUT: input.output,
85 T3_FAKE_CLAUDE_REJECTS_NO_SESSION_PERSISTENCE: input.rejectsNoSessionPersistence
86 ? "1"
87 : undefined,
88 T3_FAKE_CLAUDE_EXIT_CODE: input.exitCode === undefined ? undefined : String(input.exitCode),
89 T3_FAKE_CLAUDE_STDERR: input.stderr,
90 T3_FAKE_CLAUDE_EXPECTED_TOOLS: input.expectedTools,
91 T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN: input.argsMustContain,
92 T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN: input.argsMustNotContain,
93 T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN: input.stdinMustContain,
94 T3_FAKE_CLAUDE_IMAGE_REJECTION: input.imageRejection,
95 T3_FAKE_CLAUDE_IMAGE_ATTEMPT_LOG: input.imageAttemptLog,
96 T3_FAKE_CLAUDE_CWD_MUST_NOT_BE: input.cwdMustNotBe,
97 T3_FAKE_CLAUDE_SETTINGS_LOG: input.settingsLog,
98 T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE: input.configDirMustBe,
99 };
100 const environment: NodeJS.ProcessEnv = {
101 ...Object.fromEntries(
102 Object.entries(hostEnv).filter(([name]) => !name.startsWith("T3_FAKE_CLAUDE_")),
103 ),
104 ...Object.fromEntries(
105 Object.entries(fakeClaudeEnv).filter(([, value]) => value !== undefined),
106 ),
107 PATH: `${binDir}${pathDelimiter}${hostEnv.PATH ?? ""}`,
108 };
109​
110 const config = decodeClaudeSettings(input.claudeConfig ?? {});
111 const textGeneration = yield* makeClaudeTextGeneration(
112 config,
113 environment,
114 Effect.succeed(SYNTHETIC_CLAUDE_MODEL_CATALOG),
115 );
116 return yield* effectFn(textGeneration);
117 }).pipe(Effect.scoped);
119​
120const reviewGuideInput = {
121 number: 12,
122 title: "Review a change",
123 description: "",
124 baseBranch: "main",
125 baseCommit: "base",
126 settledReview: "",
127 modelSelection: createModelSelection(
128 ProviderInstanceId.make("claudeAgent"),
129 SYNTHETIC_CLAUDE_CAPABLE_MODEL,
130 ),
131};
132​
133it.layer(layerClaudeTextGenerationTest)("ClaudeTextGeneration", (it) => {
134 it.effect("reads a relative settings path for a review guide from the project folder", () =>
135 Effect.gen(function* () {
136 const fs = yield* FileSystem.FileSystem;
137 const path = yield* Path.Path;
138 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-guide-" });
139 const project = path.join(root, "project");
140 const checkout = path.join(root, "checkout");
141 for (const [directory, origin] of [
142 [project, "project"],
143 [checkout, "checkout"],
144 ] as const) {
145 yield* fs.makeDirectory(directory);
146 yield* fs.writeFileString(
147 path.join(directory, "claude.json"),
148 JSON.stringify({ env: { ORIGIN: origin } }),
149 );
150 }
151 const settingsLog = path.join(root, "settings.json");
152 yield* withFakeClaudeEnv(
153 {
154 output: JSON.stringify({ structured_output: { stops: [] } }),
155 expectedTools: "Read,Grep,Glob,Bash",
156 settingsLog,
157 claudeConfig: { homePath: path.join(root, "home"), launchArgs: "--settings claude.json" },
158 },
159 (textGeneration) =>
160 textGeneration.generateReviewGuide({
161 ...reviewGuideInput,
162 cwd: checkout,
163 projectCwd: project,
164 }),
165 );
166 expect(JSON.parse(yield* fs.readFileString(settingsLog))).toEqual({
167 env: { ORIGIN: "project" },
168 disableAllHooks: true,
169 });
170 }),
171 );
172​
173 it.effect("gives a review guide the user's settings without their pre-approved tools", () =>
174 Effect.gen(function* () {
175 const fs = yield* FileSystem.FileSystem;
176 const path = yield* Path.Path;
177 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-guide-" });
178 const home = path.join(root, "home");
179 yield* fs.makeDirectory(home);
180 yield* fs.writeFileString(
181 path.join(home, "settings.json"),
182 JSON.stringify({
183 env: { ENDPOINT: "user", SHARED: "user" },
184 permissions: { allow: ["Bash(touch:*)"], deny: ["Read(./private/**)"] },
185 }),
186 );
187 const settingsLog = path.join(root, "settings.json");
188 const launchSettings = JSON.stringify({
189 env: { SHARED: "launch" },
190 permissions: { allow: ["Bash(npm test:*)"], deny: ["Read(./keys/**)"] },
191 });
192 yield* withFakeClaudeEnv(
193 {
194 output: JSON.stringify({ structured_output: { stops: [] } }),
195 // The CLI loads no settings file of its own.
196 argsMustContain: "--setting-sources --disable-slash-commands",
197 argsMustNotContain: "ENDPOINT",
198 expectedTools: "Read,Grep,Glob,Bash",
199 settingsLog,
200 claudeConfig: { homePath: home, launchArgs: `--settings '${launchSettings}'` },
201 },
202 (textGeneration) =>
203 textGeneration.generateReviewGuide({
204 ...reviewGuideInput,
205 cwd: process.cwd(),
206 projectCwd: process.cwd(),
207 }),
208 );
209 expect(JSON.parse(yield* fs.readFileString(settingsLog))).toEqual({
210 env: { ENDPOINT: "user", SHARED: "launch" },
211 permissions: { deny: ["Read(./private/**)", "Read(./keys/**)"] },
212 disableAllHooks: true,
213 });
214 }),
215 );
216​
217 it.effect(
218 "keeps canonical built-in capabilities when a custom model collides with its alias",
219 () =>
220 withFakeClaudeEnv(
221 {
222 output: JSON.stringify({
223 structured_output: {
224 title: "Improve orchestration flow",
225 body: "Body",
226 },
227 }),
228 argsMustContain: `--model ${SYNTHETIC_CLAUDE_CAPABLE_MODEL}[expanded] --effort max --settings {"disableAllHooks":true,"fastMode":true}`,
229 claudeConfig: { customModels: [SYNTHETIC_CLAUDE_COLLIDING_ALIAS] },
230 },
231 (textGeneration) =>
232 Effect.gen(function* () {
233 const generated = yield* textGeneration.generatePrContent({
234 cwd: process.cwd(),
235 baseBranch: "main",
236 headBranch: "feature/claude-effect",
237 commitSummary: "Improve orchestration",
238 diffSummary: "1 file changed",
239 diffPatch: "diff --git a/README.md b/README.md",
240 modelSelection: {
241 ...createModelSelection(
242 ProviderInstanceId.make("claudeAgent"),
243 SYNTHETIC_CLAUDE_CAPABLE_MODEL,
244 [
245 { id: "effort", value: "max" },
246 { id: "fastMode", value: true },
247 ],
248 ),
249 },
250 });
251​
252 expect(generated.title).toBe("Improve orchestration flow");
253 }),
254 ),
255 );
256​
257 it.effect(
258 "generates thread titles outside the project with tools, skills, and hooks disabled",
259 () =>
260 withFakeClaudeEnv(
261 {
262 output: JSON.stringify({
263 structured_output: {
264 title:
265 ' "Reconnect failures after restart because the session state does not recover" ',
266 },
267 }),
268 cwdMustNotBe: process.cwd(),
269 stdinMustContain: "/call-script",
270 },
271 (textGeneration) =>
272 Effect.gen(function* () {
273 const generated = yield* textGeneration.generateThreadTitle({
274 cwd: process.cwd(),
275 message: "/call-script",
276 modelSelection: {
277 instanceId: ProviderInstanceId.make("claudeAgent"),
278 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
279 },
280 });
281​
282 expect(generated.title).toBe(
283 sanitizeThreadTitle(
284 '"Reconnect failures after restart because the session state does not recover"',
285 ),
286 );
287 }),
288 ),
289 );
290​
291 it.effect("sends thread title instructions to the provider prompt", () =>
292 withFakeClaudeEnv(
293 {
294 output: JSON.stringify({ structured_output: { title: "Reconnect failures" } }),
295 stdinMustContain: "Title instructions from the user:\nUse two to four words.",
296 },
297 (textGeneration) =>
298 textGeneration.generateThreadTitle({
299 cwd: process.cwd(),
300 message: "Investigate reconnect failures",
301 instructions: "Use two to four words.",
302 modelSelection: {
303 instanceId: ProviderInstanceId.make("claudeAgent"),
304 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
305 },
306 }),
307 ),
308 );
309​
310 it.effect("sends image attachments to Claude, not only their metadata", () =>
311 withFakeClaudeEnv(
312 {
313 output: JSON.stringify({ structured_output: { branch: "fix/login-button" } }),
314 stdinMustContain: Buffer.from("hello").toString("base64"),
315 },
316 (textGeneration) =>
317 Effect.gen(function* () {
318 const fs = yield* FileSystem.FileSystem;
319 const path = yield* Path.Path;
320 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
321 const attachmentId = "thread-1-claude-attachment";
322 const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
323 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
324 yield* fs.writeFile(imagePath, Buffer.from("hello"));
325​
326 yield* textGeneration
327 .generateBranchName({
328 cwd: process.cwd(),
329 message: "fix this",
330 attachments: [
331 {
332 type: "image",
333 id: attachmentId,
334 name: "screen.png",
335 mimeType: "image/png",
336 sizeBytes: 5,
337 },
338 ],
339 modelSelection: {
340 instanceId: ProviderInstanceId.make("claudeAgent"),
341 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
342 },
343 })
344 .pipe(Effect.ensuring(fs.remove(imagePath).pipe(Effect.ignore)));
345 }),
346 ),
347 );
348​
349 it.effect.each([
350 // A model that cannot take images is remembered, so later calls go straight to text only.
351 { rejection: "Image inputs are not supported by this model", imageAttempts: 1 },
352 // A rejection of this request's images says nothing about the model.
353 {
354 rejection:
355 "At least one of the image dimensions exceed max allowed size for many-image requests: 2000 pixels",
356 imageAttempts: 2,
357 },
358 ])("still generates text when images are rejected: $rejection", ({ rejection, imageAttempts }) =>
359 Effect.gen(function* () {
360 const fs = yield* FileSystem.FileSystem;
361 const path = yield* Path.Path;
362 const logDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-image-log-" });
363 const imageAttemptLog = path.join(logDir, "image-attempts.log");
364 return yield* withFakeClaudeEnv(
365 {
366 output: JSON.stringify({ structured_output: { branch: "fix/login-button" } }),
367 imageRejection: rejection,
368 imageAttemptLog,
369 },
370 (textGeneration) =>
371 Effect.gen(function* () {
372 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
373 const attachmentId = "thread-1-claude-text-only-attachment";
374 const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
375 yield* fs.makeDirectory(attachmentsDir, { recursive: true });
376 yield* fs.writeFile(imagePath, Buffer.from("hello"));
377 const generate = textGeneration.generateBranchName({
378 cwd: process.cwd(),
379 message: "fix this",
380 attachments: [
381 {
382 type: "image",
383 id: attachmentId,
384 name: "screen.png",
385 mimeType: "image/png",
386 sizeBytes: 5,
387 },
388 ],
389 modelSelection: {
390 instanceId: ProviderInstanceId.make("claudeAgent"),
391 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
392 },
393 });
394​
395 const [first, second] = yield* Effect.all([generate, generate]).pipe(
396 Effect.ensuring(fs.remove(imagePath).pipe(Effect.ignore)),
397 );
398​
399 expect(first.branch).toBe("fix/login-button");
400 expect(second.branch).toBe("fix/login-button");
401 const attempts = yield* fs.readFileString(imageAttemptLog);
402 expect(attempts.trim().split("\n")).toHaveLength(imageAttempts);
403 }),
404 );
405 }).pipe(Effect.scoped),
406 );
407​
408 it.effect("runs Claude text generation with the configured CLAUDE_CONFIG_DIR", () =>
409 Effect.gen(function* () {
410 const path = yield* Path.Path;
411 const claudeConfigDir = path.join(process.cwd(), ".claude-work-test");
412 return yield* withFakeClaudeEnv(
413 {
414 output: JSON.stringify({
415 structured_output: {
416 title: "Use Claude home",
417 },
418 }),
419 configDirMustBe: claudeConfigDir,
420 claudeConfig: { homePath: claudeConfigDir },
421 },
422 (textGeneration) =>
423 Effect.gen(function* () {
424 const generated = yield* textGeneration.generateThreadTitle({
425 cwd: process.cwd(),
426 message: "thread title",
427 modelSelection: {
428 instanceId: ProviderInstanceId.make("claudeAgent"),
429 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
430 },
431 });
432​
433 expect(generated.title).toBe(sanitizeThreadTitle("Use Claude home"));
434 }),
435 );
436 }),
437 );
438​
439 it.effect("passes --settings from the instance launch args to Claude text generation", () =>
440 withFakeClaudeEnv(
441 {
442 output: JSON.stringify({
443 structured_output: {
444 title: "Use instance settings",
445 },
446 }),
447 argsMustContain: `"env":{"ANTHROPIC_VERTEX_PROJECT_ID":"vertex-project-a"}`,
448 claudeConfig: {
449 launchArgs: `--settings '{"env":{"ANTHROPIC_VERTEX_PROJECT_ID":"vertex-project-a"}}'`,
450 },
451 },
452 (textGeneration) =>
453 Effect.gen(function* () {
454 const generated = yield* textGeneration.generateThreadTitle({
455 cwd: process.cwd(),
456 message: "thread title",
457 modelSelection: {
458 instanceId: ProviderInstanceId.make("claudeAgent"),
459 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
460 },
461 });
462​
463 expect(generated.title).toBe(sanitizeThreadTitle("Use instance settings"));
464 }),
465 ),
466 );
467​
468 it.effect("retries without --no-session-persistence when the Claude CLI rejects it", () =>
469 withFakeClaudeEnv(
470 {
471 output: JSON.stringify({ structured_output: { title: "Reconnect failures" } }),
472 rejectsNoSessionPersistence: true,
473 },
474 (textGeneration) =>
475 Effect.gen(function* () {
476 const generated = yield* textGeneration.generateThreadTitle({
477 cwd: process.cwd(),
478 message: "Investigate reconnect failures",
479 modelSelection: {
480 instanceId: ProviderInstanceId.make("claudeAgent"),
481 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
482 },
483 });
484​
485 expect(generated.title).toBe("Reconnect failures");
486 }),
487 ),
488 );
489​
490 it.effect.each([
491 { verbose: false, label: "normal" },
492 { verbose: true, label: "verbose" },
493 ])("unwraps a JSON title in $label Claude output", ({ verbose }) => {
494 const result = {
495 type: "result",
496 structured_output: { title: '{"title": "Refresh ev-stg APP ASG instances"}' },
497 };
498 return withFakeClaudeEnv(
499 { output: JSON.stringify(verbose ? [result] : result) },
500 (textGeneration) =>
501 Effect.gen(function* () {
502 const generated = yield* textGeneration.generateThreadTitle({
503 cwd: process.cwd(),
504 message: "Refresh ev-stg APP ASG instances",
505 modelSelection: {
506 instanceId: ProviderInstanceId.make("claudeAgent"),
507 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
508 },
509 });
510​
511 expect(generated.title).toBe("Refresh ev-stg APP ASG instances");
512 }),
513 );
514 });
515​
516 it.effect.each([
517 { previousTitle: undefined, label: "generating" },
518 { previousTitle: "Old thread title", label: "regenerating" },
519 ])("reads the result from verbose Claude output when $label a title", ({ previousTitle }) =>
520 withFakeClaudeEnv(
521 {
522 output: JSON.stringify([
523 { type: "system", subtype: "init" },
524 { type: "assistant", message: { content: [] } },
525 { type: "user", message: { content: [] } },
526 { type: "rate_limit_event" },
527 {
528 type: "result",
529 subtype: "success",
530 result: '{"title":"Refresh ev-stg APP ASG Instances"}',
531 structured_output: { title: "Refresh ev-stg APP ASG Instances" },
532 },
533 ]),
534 },
535 (textGeneration) =>
536 Effect.gen(function* () {
537 const generated = yield* textGeneration.generateThreadTitle({
538 cwd: process.cwd(),
539 message: "Refresh ev-stg APP ASG instances",
540 previousTitle,
541 modelSelection: {
542 instanceId: ProviderInstanceId.make("claudeAgent"),
543 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
544 },
545 });
546​
547 expect(generated.title).toBe("Refresh ev-stg APP ASG Instances");
548 }),
549 ),
550 );
551​
552 it.effect.each([
553 ["empty message array", []],
554 ["missing result", [{ type: "assistant", structured_output: { title: "Not a result" } }]],
555 ["invalid title", [{ type: "result", structured_output: { title: 42 } }]],
556 [
557 "final result without structured output",
558 [
559 { type: "result", structured_output: { title: "Earlier result" } },
560 { type: "result", subtype: "error_max_structured_output_retries" },
561 ],
562 ],
563 ] as const)("rejects verbose Claude output with %s", ([, output]) =>
564 withFakeClaudeEnv({ output: JSON.stringify(output) }, (textGeneration) =>
565 Effect.gen(function* () {
566 const error = yield* Effect.flip(
567 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​
577 expect(error._tag).toBe("TextGenerationError");
578 }),
579 ),
580 );
581​
582 const apiError = "API Error: 400 Model blocked by guardrail: 4 endpoints excluded";
583 const wrapperNotice = "Using the OpenRouter credential from the global credential file.";
584 const structuredOutputError = "Failed to provide valid structured output after 5 attempts";
585 const structuredOutputFailure = {
586 type: "result",
587 subtype: "error_max_structured_output_retries",
588 is_error: true,
589 errors: [structuredOutputError],
590 };
591 it.effect.each([
592 [
593 "the errors list of a result with no result text",
594 JSON.stringify(structuredOutputFailure),
595 structuredOutputError,
596 ],
597 [
598 "the errors list from verbose output",
599 JSON.stringify([{ type: "system", subtype: "init" }, structuredOutputFailure]),
600 structuredOutputError,
601 ],
602 [
603 "the errors list without CLI telemetry",
604 JSON.stringify({
605 ...structuredOutputFailure,
606 subtype: "error_during_execution",
607 errors: ["[ede_diagnostic] result_type=user last_content_type=n/a", apiError],
608 }),
609 apiError,
610 ],
611 [
612 "the stdout error over a stderr notice",
613 JSON.stringify({ is_error: true, api_error_status: 400, result: apiError }),
614 apiError,
615 ],
616 [
617 "the verbose stdout error over a stderr notice",
618 JSON.stringify([
619 { type: "system", subtype: "init" },
620 { type: "result", is_error: true, result: apiError },
621 { type: "result", is_error: true, result: " " },
622 ]),
623 apiError,
624 ],
625 ["stderr when stdout has no error", "not json", wrapperNotice],
626 [
627 "a stdout error naming --no-session-persistence without retrying",
628 JSON.stringify({
629 is_error: true,
630 result: "error: unknown option '--no-session-persistence'",
631 }),
632 "error: unknown option '--no-session-persistence'",
633 ],
634 ] as const)("reports %s when the Claude CLI fails", ([, output, expected]) =>
635 withFakeClaudeEnv({ output, stderr: wrapperNotice, exitCode: 1 }, (textGeneration) =>
636 Effect.gen(function* () {
637 const error = yield* Effect.flip(
638 textGeneration.generateThreadTitle({
639 cwd: process.cwd(),
640 message: "Name this thread",
641 modelSelection: {
642 instanceId: ProviderInstanceId.make("claudeAgent"),
643 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
644 },
645 }),
646 );
647​
648 expect(error.detail).toBe(`Claude CLI command failed: ${expected}`);
649 }),
650 ),
651 );
652​
653 it.effect("does not report the raw result JSON when a failed run writes nothing to stderr", () =>
654 withFakeClaudeEnv(
655 { output: JSON.stringify(structuredOutputFailure), exitCode: 1 },
656 (textGeneration) =>
657 Effect.gen(function* () {
658 const error = yield* Effect.flip(
659 textGeneration.generateThreadTitle({
660 cwd: process.cwd(),
661 message: "Name this thread",
662 modelSelection: {
663 instanceId: ProviderInstanceId.make("claudeAgent"),
664 model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
665 },
666 }),
667 );
668​
669 expect(error.detail).toBe(`Claude CLI command failed: ${structuredOutputError}`);
670 }),
671 ),
672 );
673});