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

GrokTextGeneration.test.ts

234 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 "@v12/shared/model";
13import { expect } from "vite-plus/test";
14import { GrokSettings, ProviderInstanceId } from "@v12/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: "v12-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(), "v12-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(NodePath.join(NodeOS.tmpdir(), "v12-grok-text-log-"));
85 const requestLogPath = NodePath.join(requestLogDir, "requests.ndjson");
86​
87 return withFakeAcpGrok(
88 {
89 V12_ACP_REQUEST_LOG_PATH: requestLogPath,
90 V12_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
91 subject: "Add Grok provider",
92 body: "Wire up the ACP runtime and headless text generation path.",
93 }),
94 },
95 (textGeneration) =>
96 Effect.gen(function* () {
97 const generated = yield* textGeneration.generateCommitMessage({
98 cwd: process.cwd(),
99 branch: "feature/grok",
100 stagedSummary: "M apps/server/src/provider/Drivers/GrokDriver.ts",
101 stagedPatch: "diff --git a/.../GrokDriver.ts b/.../GrokDriver.ts",
102 modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-mock-alt"),
103 });
104​
105 expect(generated.subject).toBe("Add Grok provider");
106 expect(generated.body).toBe("Wire up the ACP runtime and headless text generation path.");
107​
108 const requests = readJsonRpcRequests(requestLogPath);
109 expect(
110 requests.find((request) => request.method === "initialize")?.params?.clientCapabilities,
111 ).toMatchObject({
112 fs: { readTextFile: false, writeTextFile: false },
113 terminal: false,
114 });
115 expect(
116 requests.some(
117 (request) =>
118 request.method === "session/set_model" &&
119 request.params?.modelId === "grok-mock-alt",
120 ),
121 ).toBe(true);
122 }),
123 );
124 });
125​
126 it.effect("extracts the JSON object when Grok wraps it in conversational text", () =>
127 withFakeAcpGrok(
128 {
129 V12_ACP_PROMPT_RESPONSE_TEXT:
130 "Sure! Here's a thread title:\n\n" +
131 JSON.stringify({ title: "Investigate failing CI" }) +
132 "\n\nLet me know if you need anything else.",
133 },
134 (textGeneration) =>
135 Effect.gen(function* () {
136 const generated = yield* textGeneration.generateThreadTitle({
137 cwd: process.cwd(),
138 message: "the lint job is red",
139 modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-mock-alt"),
140 });
141 expect(generated.title).toBe("Investigate failing CI");
142 }),
143 ),
144 );
145​
146 it.effect("surfaces ACP request failures as text generation errors", () =>
147 withFakeAcpGrok(
148 {
149 V12_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({ branch: "unreachable" }),
150 },
151 (textGeneration) =>
152 Effect.gen(function* () {
153 const error = yield* Effect.flip(
154 textGeneration.generateBranchName({
155 cwd: process.cwd(),
156 message: "wire up grok",
157 modelSelection: createModelSelection(
158 ProviderInstanceId.make("grok"),
159 "missing-grok-model",
160 ),
161 }),
162 );
163 expect(error._tag).toBe("TextGenerationError");
164 expect(error.detail).toContain("Grok ACP base model");
165 }),
166 ),
167 );
168​
169 it.effect("fails with TextGenerationError when output is empty", () =>
170 withFakeAcpGrok(
171 {
172 V12_ACP_PROMPT_RESPONSE_TEXT: " \n ",
173 },
174 (textGeneration) =>
175 Effect.gen(function* () {
176 const error = yield* Effect.flip(
177 textGeneration.generateThreadTitle({
178 cwd: process.cwd(),
179 message: "anything",
180 modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-build"),
181 }),
182 );
183 expect(error._tag).toBe("TextGenerationError");
184 expect(error.detail).toMatch(/empty/i);
185 }),
186 ),
187 );
188​
189 it.effect("decodes a structured PR title + body", () =>
190 withFakeAcpGrok(
191 {
192 V12_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
193 title: "feat(grok): wire up session/set_model",
194 body: "## Summary\n- Replace `-m` spawn flag with the typed ACP `session/set_model`.\n- Translate `MODEL_SWITCH_INCOMPATIBLE_AGENT` into a validation error.",
195 }),
196 },
197 (textGeneration) =>
198 Effect.gen(function* () {
199 const generated = yield* textGeneration.generatePrContent({
200 cwd: process.cwd(),
201 baseBranch: "main",
202 headBranch: "feat/grok-provider",
203 commitSummary: "feat: add grok provider",
204 diffSummary: "M apps/server/src/provider/Drivers/GrokDriver.ts",
205 diffPatch: "diff --git a/.../GrokDriver.ts b/.../GrokDriver.ts",
206 modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-build"),
207 });
208​
209 expect(generated.title).toBe("feat(grok): wire up session/set_model");
210 expect(generated.body).toContain("Translate `MODEL_SWITCH_INCOMPATIBLE_AGENT`");
211 }),
212 ),
213 );
214​
215 it.effect("fails with TextGenerationError when output is unparseable JSON", () =>
216 withFakeAcpGrok(
217 {
218 V12_ACP_PROMPT_RESPONSE_TEXT: "totally not json output from a confused model",
219 },
220 (textGeneration) =>
221 Effect.gen(function* () {
222 const error = yield* Effect.flip(
223 textGeneration.generateThreadTitle({
224 cwd: process.cwd(),
225 message: "anything",
226 modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-build"),
227 }),
228 );
229 expect(error._tag).toBe("TextGenerationError");
230 expect(error.detail).toMatch(/invalid structured output/i);
231 }),
232 ),
233 );
234});