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

GrokProvider.test.ts

467 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 Schema from "effect/Schema";
10import { GrokSettings } from "@t3tools/contracts";
11​
12import {
13 buildGrokModelCapabilities,
14 buildGrokModelsFromSessionModelState,
15 buildInitialGrokProviderSnapshot,
16 checkGrokProviderStatus,
17 parseGrokModelsCliOutput,
18} from "./GrokProvider.ts";
19import { execScriptSource, writeFakeCli } from "../../testUtils/fakeCli.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 expect(snapshot.supportsConversationRollback).toBe(false);
286 }),
287 );
288});
289​
290it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => {
291 it.effect("reports the binary as missing when the binary path does not resolve", () =>
292 Effect.gen(function* () {
293 const snapshot = yield* checkGrokProviderStatus(
294 decodeGrokSettings({
295 enabled: true,
296 binaryPath: "/definitely/not/installed/grok-binary",
297 }),
298 );
299 expect(snapshot.enabled).toBe(true);
300 expect(snapshot.installed).toBe(false);
301 expect(snapshot.status).toBe("error");
302 expect(snapshot.message).toMatch(/not installed|not on PATH|Failed to execute/);
303 }),
304 );
305​
306 it.effect("reports an installed CLI as unhealthy when --version exits non-zero", () =>
307 Effect.gen(function* () {
308 const secretStderr = "broken grok install: secret-token-value";
309 const snapshot = yield* Effect.scoped(
310 Effect.gen(function* () {
311 const fs = yield* FileSystem.FileSystem;
312 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-version-" });
313 const grokPath = writeFakeCli({
314 directory: dir,
315 name: "grok",
316 source: [
317 // @effect-diagnostics-next-line preferSchemaOverJson:off
318 `process.stderr.write(${JSON.stringify(`${secretStderr}\n`)});`,
319 "process.exit(2);",
320 "",
321 ].join("\n"),
322 });
323​
324 return yield* checkGrokProviderStatus(
325 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
326 );
327 }),
328 );
329​
330 expect(snapshot.enabled).toBe(true);
331 expect(snapshot.installed).toBe(true);
332 expect(snapshot.status).toBe("error");
333 expect(snapshot.message).toBe("Grok CLI is installed but failed to run.");
334 expect(snapshot.message).not.toContain(secretStderr);
335 }),
336 );
337​
338 // A stand-in for the Grok CLI: `--version` and `models` print canned text,
339 // and `agent stdio` execs the mock ACP agent so `initialize` returns model metadata.
340 const writeFakeGrokCli = (input: { readonly modelsOutput: string; readonly acp: boolean }) =>
341 Effect.gen(function* () {
342 const fs = yield* FileSystem.FileSystem;
343 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-probe-" });
344 const mockAgentPath = NodePath.resolve(__dirname, "../../../scripts/acp-mock-agent.ts");
345 return writeFakeCli({
346 directory: dir,
347 name: "grok",
348 source: [
349 'if (process.argv[2] === "--version") {',
350 ' process.stdout.write("grok 1.0.13\\n");',
351 " process.exit(0);",
352 "}",
353 'if (process.argv[2] === "models") {',
354 // @effect-diagnostics-next-line preferSchemaOverJson:off
355 ` process.stdout.write(${JSON.stringify(input.modelsOutput)});`,
356 " process.exit(0);",
357 "}",
358 'if (process.argv[2] !== "agent") process.exit(1);',
359 ...(input.acp ? [execScriptSource({ scriptPath: mockAgentPath })] : ["process.exit(3);"]),
360 "",
361 ].join("\n"),
362 });
363 });
364​
365 it.effect("reports ready with ACP-discovered models when logged in", () =>
366 Effect.gen(function* () {
367 const snapshot = yield* Effect.scoped(
368 Effect.gen(function* () {
369 const grokPath = yield* writeFakeGrokCli({
370 modelsOutput: LOGGED_IN_MODELS_OUTPUT,
371 acp: true,
372 });
373 return yield* checkGrokProviderStatus(
374 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
375 { ...process.env, XAI_API_KEY: "" },
376 );
377 }),
378 );
379​
380 expect(snapshot.status).toBe("ready");
381 expect(snapshot.version).toBe("1.0.13");
382 expect(snapshot.auth).toEqual({
383 status: "authenticated",
384 type: "cached_token",
385 label: "Grok account",
386 });
387 // The mock agent advertises grok-4.6 with reasoning options in initialize._meta.
388 expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-4.6", "grok-mock-alt"]);
389 expect(snapshot.models[0]?.isDefault).toBe(true);
390 expect(
391 snapshot.models[0]?.capabilities?.optionDescriptors?.map((option) => option.id) ?? [],
392 ).toEqual(["reasoningEffort"]);
393 }),
394 );
395​
396 it.effect("reports unauthenticated from `grok models` without starting a session", () =>
397 Effect.gen(function* () {
398 const snapshot = yield* Effect.scoped(
399 Effect.gen(function* () {
400 const grokPath = yield* writeFakeGrokCli({
401 modelsOutput: LOGGED_OUT_MODELS_OUTPUT,
402 acp: true,
403 });
404 return yield* checkGrokProviderStatus(
405 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
406 { ...process.env, XAI_API_KEY: "" },
407 );
408 }),
409 );
410​
411 expect(snapshot.status).toBe("error");
412 expect(snapshot.auth.status).toBe("unauthenticated");
413 expect(snapshot.message).toContain("grok login");
414 expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-4.6", "grok-mock-alt"]);
415 }),
416 );
417​
418 it.effect("falls back to CLI-listed models with a warning when ACP initialize fails", () =>
419 Effect.gen(function* () {
420 const snapshot = yield* Effect.scoped(
421 Effect.gen(function* () {
422 const grokPath = yield* writeFakeGrokCli({
423 modelsOutput: LOGGED_IN_MODELS_OUTPUT,
424 acp: false,
425 });
426 return yield* checkGrokProviderStatus(
427 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
428 { ...process.env, XAI_API_KEY: "" },
429 );
430 }),
431 );
432​
433 expect(snapshot.status).toBe("warning");
434 expect(snapshot.installed).toBe(true);
435 expect(snapshot.auth.status).toBe("authenticated");
436 expect(snapshot.models.map((model) => [model.slug, model.isDefault ?? false])).toEqual([
437 ["grok-4.6", true],
438 ["grok-4.5", false],
439 ]);
440 expect(snapshot.message).toContain("ACP initialize failed");
441 }),
442 );
443​
444 it.effect("treats XAI_API_KEY as authenticated regardless of CLI login state", () =>
445 Effect.gen(function* () {
446 const snapshot = yield* Effect.scoped(
447 Effect.gen(function* () {
448 const grokPath = yield* writeFakeGrokCli({
449 modelsOutput: LOGGED_OUT_MODELS_OUTPUT,
450 acp: false,
451 });
452 return yield* checkGrokProviderStatus(
453 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
454 { ...process.env, XAI_API_KEY: "xai-test-key" },
455 );
456 }),
457 );
458​
459 expect(snapshot.auth).toEqual({
460 status: "authenticated",
461 type: "api_key",
462 label: "xAI API key",
463 });
464 expect(snapshot.status).toBe("warning");
465 }),
466 );
467});