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

GrokTextGeneration.test.ts

236 lines8.7 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodePath from "node:path";
3import * as NodeOS from "node:os";
4import * as NodeURL from "node:url";
5import * as NodeFS from "node:fs";
6​
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import { it } from "@effect/vitest";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Schema from "effect/Schema";
12import { createModelSelection } from "@t3tools/shared/model";
13import { expect } from "vite-plus/test";
14import { GrokSettings, ProviderInstanceId } from "@t3tools/contracts";
15​
16import * as ServerConfig from "../config.ts";
17import * as TextGeneration from "./TextGeneration.ts";
18import { makeGrokTextGeneration } from "./GrokTextGeneration.ts";
19const decodeGrokSettings = Schema.decodeSync(GrokSettings);
20​
21const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
22const mockAgentPath = NodePath.join(__dirname, "../../scripts/acp-mock-agent.ts");
23​
24function shellSingleQuote(value: string): string {
25 return `'${value.replaceAll("'", `'"'"'`)}'`;
27​
28const GrokTextGenerationTestLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
29 prefix: "t3code-grok-text-generation-test-",
30}).pipe(Layer.provideMerge(NodeServices.layer));
31​
32function makeAcpGrokWrapper(dir: string, env: Record<string, string>): string {
33 const binDir = NodePath.join(dir, "bin");
34 const grokPath = NodePath.join(binDir, "grok");
35 NodeFS.mkdirSync(binDir, { recursive: true });
36 NodeFS.writeFileSync(
37 grokPath,
38 [
39 "#!/bin/sh",
40 ...Object.entries(env).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}`),
41 'if [ "$1" != "agent" ] || [ "$2" != "stdio" ]; then',
42 ' printf "%s\\n" "unexpected args: $*" >&2',
43 " exit 11",
44 "fi",
45 `exec ${JSON.stringify(process.execPath)} ${JSON.stringify(mockAgentPath)}`,
46 "",
47 ].join("\n"),
48 "utf8",
49 );
50 NodeFS.chmodSync(grokPath, 0o755);
51 return grokPath;
53​
54function withFakeAcpGrok<A, E, R>(
55 env: Record<string, string>,
56 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
57) {
58 return Effect.gen(function* () {
59 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-grok-text-acp-"));
60 yield* Effect.addFinalizer(() =>
61 Effect.sync(() => {
62 NodeFS.rmSync(tempDir, { recursive: true, force: true });
63 }),
64 );
65 const binaryPath = makeAcpGrokWrapper(tempDir, env);
66 const config = decodeGrokSettings({ binaryPath });
67 const textGeneration = yield* makeGrokTextGeneration(config);
68 return yield* effectFn(textGeneration);
69 }).pipe(Effect.scoped);
71​
72function readJsonRpcRequests(
73 filePath: string,
74): ReadonlyArray<{ readonly method?: string; readonly params?: Record<string, unknown> }> {
75 return NodeFS.readFileSync(filePath, "utf8")
76 .trim()
77 .split("\n")
78 .filter((line) => line.length > 0)
79 .map((line) => JSON.parse(line) as { method?: string; params?: Record<string, unknown> });
81​
82it.layer(GrokTextGenerationTestLayer)("GrokTextGeneration", (it) => {
83 it.effect("uses ACP with disabled tool capabilities and forwards the requested model id", () => {
84 const requestLogDir = NodeFS.mkdtempSync(
85 NodePath.join(NodeOS.tmpdir(), "t3code-grok-text-log-"),
86 );
87 const requestLogPath = NodePath.join(requestLogDir, "requests.ndjson");
88​
89 return withFakeAcpGrok(
90 {
91 T3_ACP_REQUEST_LOG_PATH: requestLogPath,
92 T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
93 subject: "Add Grok provider",
94 body: "Wire up the ACP runtime and headless text generation path.",
95 }),
96 },
97 (textGeneration) =>
98 Effect.gen(function* () {
99 const generated = yield* textGeneration.generateCommitMessage({
100 cwd: process.cwd(),
101 branch: "feature/grok",
102 stagedSummary: "M apps/server/src/provider/Drivers/GrokDriver.ts",
103 stagedPatch: "diff --git a/.../GrokDriver.ts b/.../GrokDriver.ts",
104 modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-mock-alt"),
105 });
106​
107 expect(generated.subject).toBe("Add Grok provider");
108 expect(generated.body).toBe("Wire up the ACP runtime and headless text generation path.");
109​
110 const requests = readJsonRpcRequests(requestLogPath);
111 expect(
112 requests.find((request) => request.method === "initialize")?.params?.clientCapabilities,
113 ).toMatchObject({
114 fs: { readTextFile: false, writeTextFile: false },
115 terminal: false,
116 });
117 expect(
118 requests.some(
119 (request) =>
120 request.method === "session/set_model" &&
121 request.params?.modelId === "grok-mock-alt",
122 ),
123 ).toBe(true);
124 }),
125 );
126 });
127​
128 it.effect("extracts the JSON object when Grok wraps it in conversational text", () =>
129 withFakeAcpGrok(
130 {
131 T3_ACP_PROMPT_RESPONSE_TEXT:
132 "Sure! Here's a thread title:\n\n" +
133 JSON.stringify({ title: "Investigate failing CI" }) +
134 "\n\nLet me know if you need anything else.",
135 },
136 (textGeneration) =>
137 Effect.gen(function* () {
138 const generated = yield* textGeneration.generateThreadTitle({
139 cwd: process.cwd(),
140 message: "the lint job is red",
141 modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-mock-alt"),
142 });
143 expect(generated.title).toBe("Investigate failing CI");
144 }),
145 ),
146 );
147​
148 it.effect("surfaces ACP request failures as text generation errors", () =>
149 withFakeAcpGrok(
150 {
151 T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({ branch: "unreachable" }),
152 },
153 (textGeneration) =>
154 Effect.gen(function* () {
155 const error = yield* Effect.flip(
156 textGeneration.generateBranchName({
157 cwd: process.cwd(),
158 message: "wire up grok",
159 modelSelection: createModelSelection(
160 ProviderInstanceId.make("grok"),
161 "missing-grok-model",
162 ),
163 }),
164 );
165 expect(error._tag).toBe("TextGenerationError");
166 expect(error.detail).toContain("Grok ACP base model");
167 }),
168 ),
169 );
170​
171 it.effect("fails with TextGenerationError when output is empty", () =>
172 withFakeAcpGrok(
173 {
174 T3_ACP_PROMPT_RESPONSE_TEXT: " \n ",
175 },
176 (textGeneration) =>
177 Effect.gen(function* () {
178 const error = yield* Effect.flip(
179 textGeneration.generateThreadTitle({
180 cwd: process.cwd(),
181 message: "anything",
182 modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-build"),
183 }),
184 );
185 expect(error._tag).toBe("TextGenerationError");
186 expect(error.detail).toMatch(/empty/i);
187 }),
188 ),
189 );
190​
191 it.effect("decodes a structured PR title + body", () =>
192 withFakeAcpGrok(
193 {
194 T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
195 title: "feat(grok): wire up session/set_model",
196 body: "## Summary\n- Replace `-m` spawn flag with the typed ACP `session/set_model`.\n- Translate `MODEL_SWITCH_INCOMPATIBLE_AGENT` into a validation error.",
197 }),
198 },
199 (textGeneration) =>
200 Effect.gen(function* () {
201 const generated = yield* textGeneration.generatePrContent({
202 cwd: process.cwd(),
203 baseBranch: "main",
204 headBranch: "feat/grok-provider",
205 commitSummary: "feat: add grok provider",
206 diffSummary: "M apps/server/src/provider/Drivers/GrokDriver.ts",
207 diffPatch: "diff --git a/.../GrokDriver.ts b/.../GrokDriver.ts",
208 modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-build"),
209 });
210​
211 expect(generated.title).toBe("feat(grok): wire up session/set_model");
212 expect(generated.body).toContain("Translate `MODEL_SWITCH_INCOMPATIBLE_AGENT`");
213 }),
214 ),
215 );
216​
217 it.effect("fails with TextGenerationError when output is unparseable JSON", () =>
218 withFakeAcpGrok(
219 {
220 T3_ACP_PROMPT_RESPONSE_TEXT: "totally not json output from a confused model",
221 },
222 (textGeneration) =>
223 Effect.gen(function* () {
224 const error = yield* Effect.flip(
225 textGeneration.generateThreadTitle({
226 cwd: process.cwd(),
227 message: "anything",
228 modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-build"),
229 }),
230 );
231 expect(error._tag).toBe("TextGenerationError");
232 expect(error.detail).toMatch(/invalid structured output/i);
233 }),
234 ),
235 );
236});