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

ClaudeTextGeneration.test.ts

345 lines12.1 KB

1import { ClaudeSettings, ProviderInstanceId } from "@t3tools/contracts";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { it } from "@effect/vitest";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Path from "effect/Path";
8import * as Schema from "effect/Schema";
9import { createModelSelection } from "@t3tools/shared/model";
10import { expect } from "vite-plus/test";
11​
12import * as ServerConfig from "../config.ts";
13import * as TextGeneration from "./TextGeneration.ts";
14import { sanitizeThreadTitle } from "./TextGenerationUtils.ts";
15import { makeClaudeTextGeneration } from "./ClaudeTextGeneration.ts";
16const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
17​
18const ClaudeTextGenerationTestLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
19 prefix: "t3code-claude-text-generation-test-",
20}).pipe(Layer.provideMerge(NodeServices.layer));
21​
22function makeFakeClaudeBinary(dir: string) {
23 return Effect.gen(function* () {
24 const fs = yield* FileSystem.FileSystem;
25 const path = yield* Path.Path;
26 const binDir = path.join(dir, "bin");
27 const claudePath = path.join(binDir, "claude");
28 yield* fs.makeDirectory(binDir, { recursive: true });
29​
30 yield* fs.writeFileString(
31 claudePath,
32 [
33 "#!/bin/sh",
34 'args="$*"',
35 'stdin_content="$(cat)"',
36 'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" ]; then',
37 ' printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" >/dev/null || {',
38 ' printf "%s\\n" "args missing expected content" >&2',
39 " exit 2",
40 " }",
41 "fi",
42 'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" ]; then',
43 ' if printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" >/dev/null; then',
44 ' printf "%s\\n" "args contained forbidden content" >&2',
45 " exit 3",
46 " fi",
47 "fi",
48 'if [ -n "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" ]; then',
49 ' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" >/dev/null || {',
50 ' printf "%s\\n" "stdin missing expected content" >&2',
51 " exit 4",
52 " }",
53 "fi",
54 'if [ -n "$T3_FAKE_CLAUDE_HOME_MUST_BE" ] && [ "$HOME" != "$T3_FAKE_CLAUDE_HOME_MUST_BE" ]; then',
55 ' printf "%s\\n" "HOME was $HOME" >&2',
56 " exit 5",
57 "fi",
58 'if [ -n "$T3_FAKE_CLAUDE_STDERR" ]; then',
59 ' printf "%s\\n" "$T3_FAKE_CLAUDE_STDERR" >&2',
60 "fi",
61 'printf "%s" "$T3_FAKE_CLAUDE_OUTPUT"',
62 'exit "${T3_FAKE_CLAUDE_EXIT_CODE:-0}"',
63 "",
64 ].join("\n"),
65 );
66 yield* fs.chmod(claudePath, 0o755);
67 return binDir;
68 });
70​
71function withFakeClaudeEnv<A, E, R>(
72 input: {
73 output: string;
74 exitCode?: number;
75 stderr?: string;
76 argsMustContain?: string;
77 argsMustNotContain?: string;
78 stdinMustContain?: string;
79 homeMustBe?: string;
80 claudeConfig?: Partial<ClaudeSettings>;
81 },
82 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
83) {
84 return Effect.gen(function* () {
85 const fs = yield* FileSystem.FileSystem;
86 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
87 const binDir = yield* makeFakeClaudeBinary(tempDir);
88 const previousPath = process.env.PATH;
89 const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;
90 const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;
91 const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;
92 const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
93 const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
94 const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
95 const previousHomeMustBe = process.env.T3_FAKE_CLAUDE_HOME_MUST_BE;
96​
97 yield* Effect.acquireRelease(
98 Effect.sync(() => {
99 process.env.PATH = `${binDir}:${previousPath ?? ""}`;
100 process.env.T3_FAKE_CLAUDE_OUTPUT = input.output;
101​
102 if (input.exitCode !== undefined) {
103 process.env.T3_FAKE_CLAUDE_EXIT_CODE = String(input.exitCode);
104 } else {
105 delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
106 }
107​
108 if (input.stderr !== undefined) {
109 process.env.T3_FAKE_CLAUDE_STDERR = input.stderr;
110 } else {
111 delete process.env.T3_FAKE_CLAUDE_STDERR;
112 }
113​
114 if (input.argsMustContain !== undefined) {
115 process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = input.argsMustContain;
116 } else {
117 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
118 }
119​
120 if (input.argsMustNotContain !== undefined) {
121 process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = input.argsMustNotContain;
122 } else {
123 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
124 }
125​
126 if (input.stdinMustContain !== undefined) {
127 process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = input.stdinMustContain;
128 } else {
129 delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
130 }
131​
132 if (input.homeMustBe !== undefined) {
133 process.env.T3_FAKE_CLAUDE_HOME_MUST_BE = input.homeMustBe;
134 } else {
135 delete process.env.T3_FAKE_CLAUDE_HOME_MUST_BE;
136 }
137 }),
138 () =>
139 Effect.sync(() => {
140 process.env.PATH = previousPath;
141​
142 if (previousOutput === undefined) {
143 delete process.env.T3_FAKE_CLAUDE_OUTPUT;
144 } else {
145 process.env.T3_FAKE_CLAUDE_OUTPUT = previousOutput;
146 }
147​
148 if (previousExitCode === undefined) {
149 delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
150 } else {
151 process.env.T3_FAKE_CLAUDE_EXIT_CODE = previousExitCode;
152 }
153​
154 if (previousStderr === undefined) {
155 delete process.env.T3_FAKE_CLAUDE_STDERR;
156 } else {
157 process.env.T3_FAKE_CLAUDE_STDERR = previousStderr;
158 }
159​
160 if (previousArgsMustContain === undefined) {
161 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
162 } else {
163 process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previousArgsMustContain;
164 }
165​
166 if (previousArgsMustNotContain === undefined) {
167 delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
168 } else {
169 process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previousArgsMustNotContain;
170 }
171​
172 if (previousStdinMustContain === undefined) {
173 delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
174 } else {
175 process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previousStdinMustContain;
176 }
177​
178 if (previousHomeMustBe === undefined) {
179 delete process.env.T3_FAKE_CLAUDE_HOME_MUST_BE;
180 } else {
181 process.env.T3_FAKE_CLAUDE_HOME_MUST_BE = previousHomeMustBe;
182 }
183 }),
184 );
185​
186 const config = decodeClaudeSettings(input.claudeConfig ?? {});
187 const textGeneration = yield* makeClaudeTextGeneration(config);
188 return yield* effectFn(textGeneration);
189 }).pipe(Effect.scoped);
191​
192it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {
193 it.effect("forwards Claude thinking settings for Haiku without passing effort", () =>
194 withFakeClaudeEnv(
195 {
196 output: JSON.stringify({
197 structured_output: {
198 subject: "Add important change",
199 body: "",
200 },
201 }),
202 argsMustContain: '--settings {"alwaysThinkingEnabled":false}',
203 argsMustNotContain: "--effort",
204 },
205 (textGeneration) =>
206 Effect.gen(function* () {
207 const generated = yield* textGeneration.generateCommitMessage({
208 cwd: process.cwd(),
209 branch: "feature/claude-effect",
210 stagedSummary: "M README.md",
211 stagedPatch: "diff --git a/README.md b/README.md",
212 modelSelection: {
213 ...createModelSelection(ProviderInstanceId.make("claudeAgent"), "claude-haiku-4-5", [
214 { id: "thinking", value: false },
215 { id: "effort", value: "high" },
216 ]),
217 },
218 });
219​
220 expect(generated.subject).toBe("Add important change");
221 }),
222 ),
223 );
224​
225 it.effect("forwards Claude fast mode and supported effort", () =>
226 withFakeClaudeEnv(
227 {
228 output: JSON.stringify({
229 structured_output: {
230 title: "Improve orchestration flow",
231 body: "Body",
232 },
233 }),
234 argsMustContain: '--effort max --settings {"fastMode":true}',
235 },
236 (textGeneration) =>
237 Effect.gen(function* () {
238 const generated = yield* textGeneration.generatePrContent({
239 cwd: process.cwd(),
240 baseBranch: "main",
241 headBranch: "feature/claude-effect",
242 commitSummary: "Improve orchestration",
243 diffSummary: "1 file changed",
244 diffPatch: "diff --git a/README.md b/README.md",
245 modelSelection: {
246 ...createModelSelection(ProviderInstanceId.make("claudeAgent"), "claude-opus-4-6", [
247 { id: "effort", value: "max" },
248 { id: "fastMode", value: true },
249 ]),
250 },
251 });
252​
253 expect(generated.title).toBe("Improve orchestration flow");
254 }),
255 ),
256 );
257​
258 it.effect("generates thread titles through the Claude provider", () =>
259 withFakeClaudeEnv(
260 {
261 output: JSON.stringify({
262 structured_output: {
263 title:
264 ' "Reconnect failures after restart because the session state does not recover" ',
265 },
266 }),
267 stdinMustContain: "You write concise thread titles for coding conversations.",
268 },
269 (textGeneration) =>
270 Effect.gen(function* () {
271 const generated = yield* textGeneration.generateThreadTitle({
272 cwd: process.cwd(),
273 message: "Please investigate reconnect failures after restarting the session.",
274 modelSelection: {
275 instanceId: ProviderInstanceId.make("claudeAgent"),
276 model: "claude-sonnet-4-6",
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("runs Claude text generation with the configured Claude HOME", () =>
290 Effect.gen(function* () {
291 const path = yield* Path.Path;
292 const claudeHome = path.join(process.cwd(), ".claude-work-test");
293 return yield* withFakeClaudeEnv(
294 {
295 // @effect-diagnostics-next-line preferSchemaOverJson:off
296 output: JSON.stringify({
297 structured_output: {
298 title: "Use Claude home",
299 },
300 }),
301 homeMustBe: claudeHome,
302 claudeConfig: { homePath: claudeHome },
303 },
304 (textGeneration) =>
305 Effect.gen(function* () {
306 const generated = yield* textGeneration.generateThreadTitle({
307 cwd: process.cwd(),
308 message: "thread title",
309 modelSelection: {
310 instanceId: ProviderInstanceId.make("claudeAgent"),
311 model: "claude-sonnet-4-6",
312 },
313 });
314​
315 expect(generated.title).toBe(sanitizeThreadTitle("Use Claude home"));
316 }),
317 );
318 }),
319 );
320​
321 it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
322 withFakeClaudeEnv(
323 {
324 output: JSON.stringify({
325 structured_output: {
326 title: ' """ """ ',
327 },
328 }),
329 },
330 (textGeneration) =>
331 Effect.gen(function* () {
332 const generated = yield* textGeneration.generateThreadTitle({
333 cwd: process.cwd(),
334 message: "Name this thread.",
335 modelSelection: {
336 instanceId: ProviderInstanceId.make("claudeAgent"),
337 model: "claude-sonnet-4-6",
338 },
339 });
340​
341 expect(generated.title).toBe("New thread");
342 }),
343 ),
344 );
345});