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

GrokProvider.test.ts

469 lines15.6 KB

1// @effect-diagnostics nodeBuiltinImport:off - resolves the mock ACP agent script path relative to this test file.
2import * as NodePath from "node:path";
3import * as NodeURL from "node:url";
4​
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import { describe, expect, it } from "@effect/vitest";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import { GrokSettings } from "@t3tools/contracts";
12​
13import {
14 buildGrokModelCapabilities,
15 buildGrokModelsFromSessionModelState,
16 buildInitialGrokProviderSnapshot,
17 checkGrokProviderStatus,
18 parseGrokModelsCliOutput,
19} from "./GrokProvider.ts";
20​
21const decodeGrokSettings = Schema.decodeSync(GrokSettings);
22const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
23​
24const LOGGED_IN_MODELS_OUTPUT = [
25 "You are logged in with grok.com.",
26 "",
27 "Default model: grok-4.6",
28 "",
29 "Available models:",
30 " * grok-4.6 (default)",
31 " - grok-4.5",
32 "",
33].join("\n");
34​
35const LOGGED_OUT_MODELS_OUTPUT = LOGGED_IN_MODELS_OUTPUT.replace(
36 "You are logged in with grok.com.",
37 "You are not authenticated.",
38);
39​
40describe("parseGrokModelsCliOutput", () => {
41 it("reads login state and model slugs, marking the default", () => {
42 const parsed = parseGrokModelsCliOutput(LOGGED_IN_MODELS_OUTPUT);
43 expect(parsed.authenticated).toBe(true);
44 expect(parsed.models.map((model) => [model.slug, model.isDefault ?? false])).toEqual([
45 ["grok-4.6", true],
46 ["grok-4.5", false],
47 ]);
48 });
49​
50 it("detects a logged-out CLI even though it exits 0", () => {
51 expect(parseGrokModelsCliOutput(LOGGED_OUT_MODELS_OUTPUT).authenticated).toBe(false);
52 });
53​
54 it("returns unknown auth for unrecognized output", () => {
55 expect(parseGrokModelsCliOutput("grok 9.9.9\n").authenticated).toBeNull();
56 });
57});
58​
59describe("buildGrokModelsFromSessionModelState", () => {
60 it("marks the agent's current model as default and keeps reasoning options", () => {
61 const models = buildGrokModelsFromSessionModelState({
62 currentModelId: "grok-4.6",
63 availableModels: [
64 {
65 modelId: "grok-4.6",
66 name: "Grok 4.6",
67 _meta: {
68 supportsReasoningEffort: true,
69 reasoningEffort: "high",
70 reasoningEfforts: [{ value: "high", label: "High", default: true }],
71 },
72 },
73 { modelId: "grok-4.5", name: "Grok 4.5" },
74 ],
75 });
76 expect(models.map((model) => [model.slug, model.isDefault ?? false])).toEqual([
77 ["grok-4.6", true],
78 ["grok-4.5", false],
79 ]);
80 expect(models[0]?.capabilities?.optionDescriptors).toHaveLength(1);
81 });
82});
83​
84describe("buildGrokModelCapabilities", () => {
85 it("preserves ACP-provided reasoning labels and the active default", () => {
86 const capabilities = buildGrokModelCapabilities({
87 modelId: "grok-4.6",
88 name: "Grok 4.6",
89 _meta: {
90 supportsReasoningEffort: true,
91 reasoningEffort: "xhigh",
92 reasoningEfforts: [
93 { value: "xhigh", label: "Extra High Effort", default: true },
94 { value: "high", label: "High Effort", default: true },
95 { value: "medium", label: "Medium Effort" },
96 { value: "low", label: "Low Effort" },
97 ],
98 },
99 });
100​
101 expect(capabilities.optionDescriptors).toEqual([
102 {
103 id: "reasoningEffort",
104 label: "Reasoning",
105 type: "select",
106 currentValue: "xhigh",
107 options: [
108 { id: "xhigh", label: "Extra High Effort", isDefault: true },
109 { id: "high", label: "High Effort" },
110 { id: "medium", label: "Medium Effort" },
111 { id: "low", label: "Low Effort" },
112 ],
113 },
114 ]);
115 });
116​
117 it("uses raw ACP values when option labels are omitted", () => {
118 const capabilities = buildGrokModelCapabilities({
119 modelId: "grok-4.6",
120 name: "Grok 4.6",
121 _meta: {
122 supportsReasoningEffort: true,
123 reasoningEffort: "xhigh",
124 reasoningEfforts: [{ value: "xhigh" }, { value: "medium" }],
125 },
126 });
127​
128 expect(capabilities.optionDescriptors).toEqual([
129 {
130 id: "reasoningEffort",
131 label: "Reasoning",
132 type: "select",
133 currentValue: "xhigh",
134 options: [
135 { id: "xhigh", label: "xhigh" },
136 { id: "medium", label: "medium" },
137 ],
138 },
139 ]);
140 });
141​
142 it("keeps ACP current effort separate from its collapsed advertised default", () => {
143 const capabilities = buildGrokModelCapabilities({
144 modelId: "grok-4.6",
145 name: "Grok 4.6",
146 _meta: {
147 supportsReasoningEffort: true,
148 reasoningEffort: "medium",
149 reasoningEfforts: [
150 { value: "xhigh", label: "Extra High Effort", default: true },
151 { value: "high", label: "High Effort", default: true },
152 { value: "medium", label: "Medium Effort" },
153 ],
154 },
155 });
156​
157 expect(capabilities.optionDescriptors).toEqual([
158 {
159 id: "reasoningEffort",
160 label: "Reasoning",
161 type: "select",
162 currentValue: "medium",
163 options: [
164 { id: "xhigh", label: "Extra High Effort", isDefault: true },
165 { id: "high", label: "High Effort" },
166 { id: "medium", label: "Medium Effort" },
167 ],
168 },
169 ]);
170 });
171​
172 it("preserves ACP descriptions and falls back from invalid values to valid ids", () => {
173 const capabilities = buildGrokModelCapabilities({
174 modelId: "grok-4.6",
175 name: "Grok 4.6",
176 _meta: {
177 supportsReasoningEffort: true,
178 reasoningEffort: "high",
179 reasoningEfforts: [
180 {
181 id: "high",
182 value: "not a token",
183 label: "High Effort",
184 description: "Higher implementation quality",
185 default: true,
186 },
187 { id: "bad id", value: "also invalid", label: "Invalid" },
188 ],
189 },
190 });
191​
192 expect(capabilities.optionDescriptors).toEqual([
193 {
194 id: "reasoningEffort",
195 label: "Reasoning",
196 type: "select",
197 currentValue: "high",
198 options: [
199 {
200 id: "high",
201 label: "High Effort",
202 description: "Higher implementation quality",
203 isDefault: true,
204 },
205 ],
206 },
207 ]);
208 });
209​
210 it("accepts an advertised ACP menu when the support flag is omitted", () => {
211 const capabilities = buildGrokModelCapabilities({
212 modelId: "grok-4.6",
213 name: "Grok 4.6",
214 _meta: {
215 reasoningEffort: "high",
216 reasoningEfforts: [{ value: "high", label: "High Effort", default: true }],
217 },
218 });
219​
220 expect(capabilities.optionDescriptors).toHaveLength(1);
221 });
222​
223 it("honors an explicit ACP opt-out even when a menu is present", () => {
224 const capabilities = buildGrokModelCapabilities({
225 modelId: "grok-4.6",
226 name: "Grok 4.6",
227 _meta: {
228 supportsReasoningEffort: false,
229 reasoningEfforts: [{ value: "high", label: "High Effort", default: true }],
230 },
231 });
232​
233 expect(capabilities.optionDescriptors).toEqual([]);
234 });
235​
236 it("does not synthesize a reasoning menu when ACP omits it", () => {
237 expect(
238 buildGrokModelCapabilities({
239 modelId: "grok-4.6",
240 name: "Grok 4.6",
241 _meta: { supportsReasoningEffort: true, reasoningEffort: "xhigh" },
242 }).optionDescriptors,
243 ).toEqual([]);
244 });
245​
246 it("keeps non-reasoning Grok models free of reasoning controls", () => {
247 expect(
248 buildGrokModelCapabilities({ modelId: "grok-build", name: "Grok Build" }).optionDescriptors,
249 ).toEqual([]);
250 });
251});
252​
253describe("buildInitialGrokProviderSnapshot", () => {
254 it.effect("returns a disabled snapshot when settings.enabled is false", () =>
255 Effect.gen(function* () {
256 const snapshot = yield* buildInitialGrokProviderSnapshot(
257 decodeGrokSettings({ enabled: false }),
258 );
259 expect(snapshot.enabled).toBe(false);
260 expect(snapshot.status).toBe("disabled");
261 expect(snapshot.installed).toBe(false);
262 expect(snapshot.message).toContain("disabled");
263 }),
264 );
265​
266 it.effect("returns a disabled snapshot by default — Grok is opt-in", () =>
267 Effect.gen(function* () {
268 const snapshot = yield* buildInitialGrokProviderSnapshot(decodeGrokSettings({}));
269 expect(snapshot.enabled).toBe(false);
270 expect(snapshot.status).toBe("disabled");
271 }),
272 );
273​
274 it.effect("returns a pending snapshot when enabled", () =>
275 Effect.gen(function* () {
276 const snapshot = yield* buildInitialGrokProviderSnapshot(
277 decodeGrokSettings({ enabled: true }),
278 );
279 expect(snapshot.enabled).toBe(true);
280 expect(snapshot.installed).toBe(true);
281 expect(snapshot.status).toBe("warning");
282 expect(snapshot.version).toBeNull();
283 expect(snapshot.message).toContain("Checking Grok");
284 expect(snapshot.requiresNewThreadForModelChange).toBeUndefined();
285 }),
286 );
287});
288​
289it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => {
290 it.effect("reports the binary as missing when the binary path does not resolve", () =>
291 Effect.gen(function* () {
292 const snapshot = yield* checkGrokProviderStatus(
293 decodeGrokSettings({
294 enabled: true,
295 binaryPath: "/definitely/not/installed/grok-binary",
296 }),
297 );
298 expect(snapshot.enabled).toBe(true);
299 expect(snapshot.installed).toBe(false);
300 expect(snapshot.status).toBe("error");
301 expect(snapshot.message).toMatch(/not installed|not on PATH|Failed to execute/);
302 }),
303 );
304​
305 it.effect("reports an installed CLI as unhealthy when --version exits non-zero", () =>
306 Effect.gen(function* () {
307 const secretStderr = "broken grok install: secret-token-value";
308 const snapshot = yield* Effect.scoped(
309 Effect.gen(function* () {
310 const fs = yield* FileSystem.FileSystem;
311 const path = yield* Path.Path;
312 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-version-" });
313 const grokPath = path.join(dir, "grok");
314 yield* fs.writeFileString(
315 grokPath,
316 ["#!/bin/sh", `printf "%s\\n" "${secretStderr}" >&2`, "exit 2", ""].join("\n"),
317 );
318 yield* fs.chmod(grokPath, 0o755);
319​
320 return yield* checkGrokProviderStatus(
321 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
322 );
323 }),
324 );
325​
326 expect(snapshot.enabled).toBe(true);
327 expect(snapshot.installed).toBe(true);
328 expect(snapshot.status).toBe("error");
329 expect(snapshot.message).toBe("Grok CLI is installed but failed to run.");
330 expect(snapshot.message).not.toContain(secretStderr);
331 }),
332 );
333​
334 // Single-quotes a path for /bin/sh. Temp dirs and execPath never contain quotes.
335 const shellQuote = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`;
336​
337 // A shell stand-in for the Grok CLI: `--version` and `models` print canned text,
338 // and `agent stdio` execs the mock ACP agent so `initialize` returns model metadata.
339 const writeFakeGrokCli = (input: { readonly modelsOutput: string; readonly acp: boolean }) =>
340 Effect.gen(function* () {
341 const fs = yield* FileSystem.FileSystem;
342 const path = yield* Path.Path;
343 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-probe-" });
344 const modelsPath = path.join(dir, "models.txt");
345 yield* fs.writeFileString(modelsPath, input.modelsOutput);
346 const grokPath = path.join(dir, "grok");
347 const mockAgentPath = path.resolve(__dirname, "../../../scripts/acp-mock-agent.ts");
348 yield* fs.writeFileString(
349 grokPath,
350 [
351 "#!/bin/sh",
352 'case "$1" in',
353 ' --version) printf "grok 1.0.13\\n"; exit 0;;',
354 ` models) cat ${shellQuote(modelsPath)}; exit 0;;`,
355 input.acp
356 ? ` agent) exec ${shellQuote(process.execPath)} ${shellQuote(mockAgentPath)};;`
357 : " agent) exit 3;;",
358 "esac",
359 "exit 1",
360 "",
361 ].join("\n"),
362 );
363 yield* fs.chmod(grokPath, 0o755);
364 return grokPath;
365 });
366​
367 it.effect("reports ready with ACP-discovered models when logged in", () =>
368 Effect.gen(function* () {
369 const snapshot = yield* Effect.scoped(
370 Effect.gen(function* () {
371 const grokPath = yield* writeFakeGrokCli({
372 modelsOutput: LOGGED_IN_MODELS_OUTPUT,
373 acp: true,
374 });
375 return yield* checkGrokProviderStatus(
376 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
377 { ...process.env, XAI_API_KEY: "" },
378 );
379 }),
380 );
381​
382 expect(snapshot.status).toBe("ready");
383 expect(snapshot.version).toBe("1.0.13");
384 expect(snapshot.auth).toEqual({
385 status: "authenticated",
386 type: "cached_token",
387 label: "Grok account",
388 });
389 // The mock agent advertises grok-4.6 with reasoning options in initialize._meta.
390 expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-4.6", "grok-mock-alt"]);
391 expect(snapshot.models[0]?.isDefault).toBe(true);
392 expect(
393 snapshot.models[0]?.capabilities?.optionDescriptors?.map((option) => option.id) ?? [],
394 ).toEqual(["reasoningEffort"]);
395 }),
396 );
397​
398 it.effect("reports unauthenticated from `grok models` without starting a session", () =>
399 Effect.gen(function* () {
400 const snapshot = yield* Effect.scoped(
401 Effect.gen(function* () {
402 const grokPath = yield* writeFakeGrokCli({
403 modelsOutput: LOGGED_OUT_MODELS_OUTPUT,
404 acp: true,
405 });
406 return yield* checkGrokProviderStatus(
407 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
408 { ...process.env, XAI_API_KEY: "" },
409 );
410 }),
411 );
412​
413 expect(snapshot.status).toBe("error");
414 expect(snapshot.auth.status).toBe("unauthenticated");
415 expect(snapshot.message).toContain("grok login");
416 expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-4.6", "grok-mock-alt"]);
417 }),
418 );
419​
420 it.effect("falls back to CLI-listed models with a warning when ACP initialize fails", () =>
421 Effect.gen(function* () {
422 const snapshot = yield* Effect.scoped(
423 Effect.gen(function* () {
424 const grokPath = yield* writeFakeGrokCli({
425 modelsOutput: LOGGED_IN_MODELS_OUTPUT,
426 acp: false,
427 });
428 return yield* checkGrokProviderStatus(
429 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
430 { ...process.env, XAI_API_KEY: "" },
431 );
432 }),
433 );
434​
435 expect(snapshot.status).toBe("warning");
436 expect(snapshot.installed).toBe(true);
437 expect(snapshot.auth.status).toBe("authenticated");
438 expect(snapshot.models.map((model) => [model.slug, model.isDefault ?? false])).toEqual([
439 ["grok-4.6", true],
440 ["grok-4.5", false],
441 ]);
442 expect(snapshot.message).toContain("ACP initialize failed");
443 }),
444 );
445​
446 it.effect("treats XAI_API_KEY as authenticated regardless of CLI login state", () =>
447 Effect.gen(function* () {
448 const snapshot = yield* Effect.scoped(
449 Effect.gen(function* () {
450 const grokPath = yield* writeFakeGrokCli({
451 modelsOutput: LOGGED_OUT_MODELS_OUTPUT,
452 acp: false,
453 });
454 return yield* checkGrokProviderStatus(
455 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
456 { ...process.env, XAI_API_KEY: "xai-test-key" },
457 );
458 }),
459 );
460​
461 expect(snapshot.auth).toEqual({
462 status: "authenticated",
463 type: "api_key",
464 label: "xAI API key",
465 });
466 expect(snapshot.status).toBe("warning");
467 }),
468 );
469});