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 { 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 * as TextGeneration from "./TextGeneration.ts";
15import { sanitizeThreadTitle } from "./TextGenerationUtils.ts";
16import { makeClaudeTextGeneration } from "./ClaudeTextGeneration.ts";
17const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
18
19const ClaudeTextGenerationTestLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
20 prefix: "t3code-claude-text-generation-test-",
21}).pipe(Layer.provideMerge(NodeServices.layer));
22
23function makeFakeClaudeBinary(dir: string) {
24 return Effect.gen(function* () {
25 const fs = yield* FileSystem.FileSystem;
26 const path = yield* Path.Path;
27 const isWindows = yield* isHostWindows;
28 const binDir = path.join(dir, "bin");
29 const stubPath = path.join(binDir, "claude-stub.mjs");
30 yield* fs.makeDirectory(binDir, { recursive: true });
31
32 // The stub behaviour lives in Node rather than a `#!/bin/sh` script so the
33 // same implementation is usable on Windows, where a shebang file is not
34 // executable and would fall through to the real Claude CLI on PATH.
35 yield* fs.writeFileString(
36 stubPath,
37 [
38 'const args = process.argv.slice(2).join(" ");',
39 "",
40 "function fail(message, code) {",
41 ' process.stderr.write(message + "\\n");',
42 " process.exit(code);",
43 "}",
44 "",
45 'let stdinContent = "";',
46 "if (!process.stdin.isTTY) {",
47 " const chunks = [];",
48 " for await (const chunk of process.stdin) {",
49 " chunks.push(chunk);",
50 " }",
51 ' stdinContent = Buffer.concat(chunks).toString("utf8");',
52 "}",
53 "",
54 "const argsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;",
55 "if (argsMustContain && !args.includes(argsMustContain)) {",
56 ' fail("args missing expected content", 2);',
57 "}",
58 "",
59 "const argsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;",
60 "if (argsMustNotContain && args.includes(argsMustNotContain)) {",
61 ' fail("args contained forbidden content", 3);',
62 "}",
63 "",
64 "const stdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;",
65 "if (stdinMustContain && !stdinContent.includes(stdinMustContain)) {",
66 ' fail("stdin missing expected content", 4);',
67 "}",
68 "",
69 "const configDirMustBe = process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;",
70 "if (configDirMustBe && process.env.CLAUDE_CONFIG_DIR !== configDirMustBe) {",
71 ' fail("CLAUDE_CONFIG_DIR was " + (process.env.CLAUDE_CONFIG_DIR ?? ""), 5);',
72 "}",
73 "",
74 "const stderrText = process.env.T3_FAKE_CLAUDE_STDERR;",
75 "if (stderrText) {",
76 ' process.stderr.write(stderrText + "\\n");',
77 "}",
78 "",
79 'process.stdout.write(process.env.T3_FAKE_CLAUDE_OUTPUT ?? "");',
80 "process.exitCode = Number(process.env.T3_FAKE_CLAUDE_EXIT_CODE ?? 0);",
81 "",
82 ].join("\n"),
83 );
84
85 if (isWindows) {
86 // Windows resolves executables through PATHEXT, so the entry point has to
87 // carry a real extension. `resolveSpawnCommand` spawns `.cmd` via a shell.
88 yield* fs.writeFileString(
89 path.join(binDir, "claude.cmd"),
90 ["@echo off", 'node "%~dp0claude-stub.mjs" %*', "exit /b %ERRORLEVEL%", ""].join("\r\n"),
91 );
92 } else {
93 const claudePath = path.join(binDir, "claude");
94 yield* fs.writeFileString(
95 claudePath,
96 ["#!/bin/sh", 'exec node "$(dirname "$0")/claude-stub.mjs" "$@"', ""].join("\n"),
97 );
98 yield* fs.chmod(claudePath, 0o755);
99 }
100
101 return binDir;
102 });
103}
104
105function withFakeClaudeEnv<A, E, R>(
106 input: {
107 output: string;
108 exitCode?: number;
109 stderr?: string;
110 argsMustContain?: string;
111 argsMustNotContain?: string;
112 stdinMustContain?: string;
113 configDirMustBe?: string;
114 claudeConfig?: Partial<ClaudeSettings>;
115 },
116 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
117) {
118 return Effect.gen(function* () {
119 const fs = yield* FileSystem.FileSystem;
120 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
121 const binDir = yield* makeFakeClaudeBinary(tempDir);
122 const pathDelimiter = (yield* isHostWindows) ? ";" : ":";
123 const previousPath = process.env.PATH;
124 const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;
125 const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;
126 const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;
127 const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
128 const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
129 const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
130 const previousConfigDirMustBe = process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
131
132 yield* Effect.acquireRelease(
133 Effect.sync(() => {
134 process.env.PATH = `${binDir}${pathDelimiter}${previousPath ?? ""}`;
135 process.env.T3_FAKE_CLAUDE_OUTPUT = input.output;
136
137 if (input.exitCode !== undefined) {
138 process.env.T3_FAKE_CLAUDE_EXIT_CODE = String(input.exitCode);
139 } else {
140 delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
141 }
142
143 if (input.stderr !== undefined) {
144 process.env.T3_FAKE_CLAUDE_STDERR = input.stderr;
145 } else {
146 delete process.env.T3_FAKE_CLAUDE_STDERR;
147 }
148
149 if (input.argsMustContain !== undefined) {
150 process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = input.argsMustContain;
151 } else {
152 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
153 }
154
155 if (input.argsMustNotContain !== undefined) {
156 process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = input.argsMustNotContain;
157 } else {
158 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
159 }
160
161 if (input.stdinMustContain !== undefined) {
162 process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = input.stdinMustContain;
163 } else {
164 delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
165 }
166
167 if (input.configDirMustBe !== undefined) {
168 process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = input.configDirMustBe;
169 } else {
170 delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
171 }
172 }),
173 () =>
174 Effect.sync(() => {
175 process.env.PATH = previousPath;
176
177 if (previousOutput === undefined) {
178 delete process.env.T3_FAKE_CLAUDE_OUTPUT;
179 } else {
180 process.env.T3_FAKE_CLAUDE_OUTPUT = previousOutput;
181 }
182
183 if (previousExitCode === undefined) {
184 delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
185 } else {
186 process.env.T3_FAKE_CLAUDE_EXIT_CODE = previousExitCode;
187 }
188
189 if (previousStderr === undefined) {
190 delete process.env.T3_FAKE_CLAUDE_STDERR;
191 } else {
192 process.env.T3_FAKE_CLAUDE_STDERR = previousStderr;
193 }
194
195 if (previousArgsMustContain === undefined) {
196 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
197 } else {
198 process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previousArgsMustContain;
199 }
200
201 if (previousArgsMustNotContain === undefined) {
202 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
203 } else {
204 process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previousArgsMustNotContain;
205 }
206
207 if (previousStdinMustContain === undefined) {
208 delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
209 } else {
210 process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previousStdinMustContain;
211 }
212
213 if (previousConfigDirMustBe === undefined) {
214 delete process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE;
215 } else {
216 process.env.T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE = previousConfigDirMustBe;
217 }
218 }),
219 );
220
221 const config = decodeClaudeSettings(input.claudeConfig ?? {});
222 const textGeneration = yield* makeClaudeTextGeneration(config);
223 return yield* effectFn(textGeneration);
224 }).pipe(Effect.scoped);
225}
226
227it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {
228 it.effect("forwards Claude thinking settings for Haiku without passing effort", () =>
229 withFakeClaudeEnv(
230 {
231 output: JSON.stringify({
232 structured_output: {
233 subject: "Add important change",
234 body: "",
235 },
236 }),
237 argsMustContain: '--settings {"alwaysThinkingEnabled":false}',
238 argsMustNotContain: "--effort",
239 },
240 (textGeneration) =>
241 Effect.gen(function* () {
242 const generated = yield* textGeneration.generateCommitMessage({
243 cwd: process.cwd(),
244 branch: "feature/claude-effect",
245 stagedSummary: "M README.md",
246 stagedPatch: "diff --git a/README.md b/README.md",
247 modelSelection: {
248 ...createModelSelection(ProviderInstanceId.make("claudeAgent"), "claude-haiku-4-5", [
249 { id: "thinking", value: false },
250 { id: "effort", value: "high" },
251 ]),
252 },
253 });
254
255 expect(generated.subject).toBe("Add important change");
256 }),
257 ),
258 );
259
260 it.effect("forwards Claude fast mode and supported effort", () =>
261 withFakeClaudeEnv(
262 {
263 output: JSON.stringify({
264 structured_output: {
265 title: "Improve orchestration flow",
266 body: "Body",
267 },
268 }),
269 argsMustContain: '--effort max --settings {"fastMode":true}',
270 },
271 (textGeneration) =>
272 Effect.gen(function* () {
273 const generated = yield* textGeneration.generatePrContent({
274 cwd: process.cwd(),
275 baseBranch: "main",
276 headBranch: "feature/claude-effect",
277 commitSummary: "Improve orchestration",
278 diffSummary: "1 file changed",
279 diffPatch: "diff --git a/README.md b/README.md",
280 modelSelection: {
281 ...createModelSelection(ProviderInstanceId.make("claudeAgent"), "claude-opus-4-6", [
282 { id: "effort", value: "max" },
283 { id: "fastMode", value: true },
284 ]),
285 },
286 });
287
288 expect(generated.title).toBe("Improve orchestration flow");
289 }),
290 ),
291 );
292
293 it.effect("generates thread titles through the Claude provider", () =>
294 withFakeClaudeEnv(
295 {
296 output: JSON.stringify({
297 structured_output: {
298 title:
299 ' "Reconnect failures after restart because the session state does not recover" ',
300 },
301 }),
302 stdinMustContain: "Please investigate reconnect failures after restarting the session.",
303 },
304 (textGeneration) =>
305 Effect.gen(function* () {
306 const generated = yield* textGeneration.generateThreadTitle({
307 cwd: process.cwd(),
308 message: "Please investigate reconnect failures after restarting the session.",
309 modelSelection: {
310 instanceId: ProviderInstanceId.make("claudeAgent"),
311 model: "claude-sonnet-4-6",
312 },
313 });
314
315 expect(generated.title).toBe(
316 sanitizeThreadTitle(
317 '"Reconnect failures after restart because the session state does not recover"',
318 ),
319 );
320 }),
321 ),
322 );
323
324 it.effect("runs Claude text generation with the configured CLAUDE_CONFIG_DIR", () =>
325 Effect.gen(function* () {
326 const path = yield* Path.Path;
327 const claudeConfigDir = path.join(process.cwd(), ".claude-work-test");
328 return yield* withFakeClaudeEnv(
329 {
330 // @effect-diagnostics-next-line preferSchemaOverJson:off
331 output: JSON.stringify({
332 structured_output: {
333 title: "Use Claude home",
334 },
335 }),
336 configDirMustBe: claudeConfigDir,
337 claudeConfig: { homePath: claudeConfigDir },
338 },
339 (textGeneration) =>
340 Effect.gen(function* () {
341 const generated = yield* textGeneration.generateThreadTitle({
342 cwd: process.cwd(),
343 message: "thread title",
344 modelSelection: {
345 instanceId: ProviderInstanceId.make("claudeAgent"),
346 model: "claude-sonnet-4-6",
347 },
348 });
349
350 expect(generated.title).toBe(sanitizeThreadTitle("Use Claude home"));
351 }),
352 );
353 }),
354 );
355
356 it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
357 withFakeClaudeEnv(
358 {
359 output: JSON.stringify({
360 structured_output: {
361 title: ' """ """ ',
362 },
363 }),
364 },
365 (textGeneration) =>
366 Effect.gen(function* () {
367 const generated = yield* textGeneration.generateThreadTitle({
368 cwd: process.cwd(),
369 message: "Name this thread.",
370 modelSelection: {
371 instanceId: ProviderInstanceId.make("claudeAgent"),
372 model: "claude-sonnet-4-6",
373 },
374 });
375
376 expect(generated.title).toBe("New thread");
377 }),
378 ),
379 );
380});