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

GrokTextGeneration.test.ts

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