Open History to see the last commit
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 }),
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 dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-version-" });
312 const grokPath = writeFakeCli({
313 directory: dir,
314 name: "grok",
315 source: [
316 // @effect-diagnostics-next-line preferSchemaOverJson:off
317 `process.stderr.write(${JSON.stringify(`${secretStderr}\n`)});`,
318 "process.exit(2);",
319 "",
320 ].join("\n"),
321 });
322
323 return yield* checkGrokProviderStatus(
324 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
325 );
326 }),
327 );
328
329 expect(snapshot.enabled).toBe(true);
330 expect(snapshot.installed).toBe(true);
331 expect(snapshot.status).toBe("error");
332 expect(snapshot.message).toBe("Grok CLI is installed but failed to run.");
333 expect(snapshot.message).not.toContain(secretStderr);
334 }),
335 );
336
337 // A 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 dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-probe-" });
343 const mockAgentPath = NodePath.resolve(__dirname, "../../../scripts/acp-mock-agent.ts");
344 return writeFakeCli({
345 directory: dir,
346 name: "grok",
347 source: [
348 'if (process.argv[2] === "--version") {',
349 ' process.stdout.write("grok 1.0.13\\n");',
350 " process.exit(0);",
351 "}",
352 'if (process.argv[2] === "models") {',
353 // @effect-diagnostics-next-line preferSchemaOverJson:off
354 ` process.stdout.write(${JSON.stringify(input.modelsOutput)});`,
355 " process.exit(0);",
356 "}",
357 'if (process.argv[2] !== "agent") process.exit(1);',
358 ...(input.acp ? [execScriptSource({ scriptPath: mockAgentPath })] : ["process.exit(3);"]),
359 "",
360 ].join("\n"),
361 });
362 });
363
364 it.effect("reports ready with ACP-discovered models when logged in", () =>
365 Effect.gen(function* () {
366 const snapshot = yield* Effect.scoped(
367 Effect.gen(function* () {
368 const grokPath = yield* writeFakeGrokCli({
369 modelsOutput: LOGGED_IN_MODELS_OUTPUT,
370 acp: true,
371 });
372 return yield* checkGrokProviderStatus(
373 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
374 { ...process.env, XAI_API_KEY: "" },
375 );
376 }),
377 );
378
379 expect(snapshot.status).toBe("ready");
380 expect(snapshot.version).toBe("1.0.13");
381 expect(snapshot.auth).toEqual({
382 status: "authenticated",
383 type: "cached_token",
384 label: "Grok account",
385 });
386 // The mock agent advertises grok-4.6 with reasoning options in initialize._meta.
387 expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-4.6", "grok-mock-alt"]);
388 expect(snapshot.models[0]?.isDefault).toBe(true);
389 expect(
390 snapshot.models[0]?.capabilities?.optionDescriptors?.map((option) => option.id) ?? [],
391 ).toEqual(["reasoningEffort"]);
392 }),
393 );
394
395 it.effect("reports unauthenticated from `grok models` without starting a session", () =>
396 Effect.gen(function* () {
397 const snapshot = yield* Effect.scoped(
398 Effect.gen(function* () {
399 const grokPath = yield* writeFakeGrokCli({
400 modelsOutput: LOGGED_OUT_MODELS_OUTPUT,
401 acp: true,
402 });
403 return yield* checkGrokProviderStatus(
404 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
405 { ...process.env, XAI_API_KEY: "" },
406 );
407 }),
408 );
409
410 expect(snapshot.status).toBe("error");
411 expect(snapshot.auth.status).toBe("unauthenticated");
412 expect(snapshot.message).toContain("grok login");
413 expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-4.6", "grok-mock-alt"]);
414 }),
415 );
416
417 it.effect("falls back to CLI-listed models with a warning when ACP initialize fails", () =>
418 Effect.gen(function* () {
419 const snapshot = yield* Effect.scoped(
420 Effect.gen(function* () {
421 const grokPath = yield* writeFakeGrokCli({
422 modelsOutput: LOGGED_IN_MODELS_OUTPUT,
423 acp: false,
424 });
425 return yield* checkGrokProviderStatus(
426 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
427 { ...process.env, XAI_API_KEY: "" },
428 );
429 }),
430 );
431
432 expect(snapshot.status).toBe("warning");
433 expect(snapshot.installed).toBe(true);
434 expect(snapshot.auth.status).toBe("authenticated");
435 expect(snapshot.models.map((model) => [model.slug, model.isDefault ?? false])).toEqual([
436 ["grok-4.6", true],
437 ["grok-4.5", false],
438 ]);
439 expect(snapshot.message).toContain("ACP initialize failed");
440 }),
441 );
442
443 it.effect("treats XAI_API_KEY as authenticated regardless of CLI login state", () =>
444 Effect.gen(function* () {
445 const snapshot = yield* Effect.scoped(
446 Effect.gen(function* () {
447 const grokPath = yield* writeFakeGrokCli({
448 modelsOutput: LOGGED_OUT_MODELS_OUTPUT,
449 acp: false,
450 });
451 return yield* checkGrokProviderStatus(
452 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
453 { ...process.env, XAI_API_KEY: "xai-test-key" },
454 );
455 }),
456 );
457
458 expect(snapshot.auth).toEqual({
459 status: "authenticated",
460 type: "api_key",
461 label: "xAI API key",
462 });
463 expect(snapshot.status).toBe("warning");
464 }),
465 );
466});