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 { HttpClient, HttpClientResponse } from "effect/http";
11import { GrokSettings } from "@t3tools/provider-grok/settings";
12
13import {
14 buildGrokModelCapabilities,
15 buildGrokModelsFromSessionModelState,
16 buildInitialGrokProviderSnapshot,
17 checkGrokProviderStatus,
18 grokSlashCommandsFromInitialize,
19 parseGrokModelsCliOutput,
20} from "@t3tools/provider-grok/testing";
21import { execScriptSource, writeFakeCli } from "@t3tools/provider-testing/fakeCli";
22import { grokUsageResponseToLimits, readGrokAccount } from "@t3tools/provider-grok/testing";
23
24const decodeGrokSettings = Schema.decodeSync(GrokSettings);
25const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
26
27const LOGGED_IN_MODELS_OUTPUT = [
28 "You are logged in with grok.com.",
29 "",
30 "Default model: grok-4.6",
31 "",
32 "Available models:",
33 " * grok-4.6 (default)",
34 " - grok-4.5",
35 "",
36].join("\n");
37
38const LOGGED_OUT_MODELS_OUTPUT = LOGGED_IN_MODELS_OUTPUT.replace(
39 "You are logged in with grok.com.",
40 "You are not authenticated.",
41);
42
43describe("parseGrokModelsCliOutput", () => {
44 it("reads login state and model slugs, marking the default", () => {
45 const parsed = parseGrokModelsCliOutput(LOGGED_IN_MODELS_OUTPUT);
46 expect(parsed.authenticated).toBe(true);
47 expect(parsed.models.map((model) => [model.slug, model.isDefault ?? false])).toEqual([
48 ["grok-4.6", true],
49 ["grok-4.5", false],
50 ]);
51 });
52
53 it("detects a logged-out CLI even though it exits 0", () => {
54 expect(parseGrokModelsCliOutput(LOGGED_OUT_MODELS_OUTPUT).authenticated).toBe(false);
55 });
56
57 it("returns unknown auth for unrecognized output", () => {
58 expect(parseGrokModelsCliOutput("grok 9.9.9\n").authenticated).toBeNull();
59 });
60});
61
62describe("grokSlashCommandsFromInitialize", () => {
63 it("publishes native ACP commands and input hints without permission overrides", () => {
64 const commands = grokSlashCommandsFromInitialize({
65 protocolVersion: 1,
66 _meta: {
67 availableCommands: [
68 { name: "compact", description: "Compress history", input: { hint: "what to preserve" } },
69 {
70 name: "always-approve",
71 description: "Skip permission prompts",
72 input: { hint: "on|off" },
73 },
74 { name: "context", description: "Show context usage", input: null },
75 { name: "session-info", description: "Show session details" },
76 { name: "deep-research", description: "Research a topic", input: { hint: "<query>" } },
77 { name: "workflow", description: "Manage workflows", input: { hint: "runs" } },
78 { name: "goal", description: "Manage an autonomous goal", input: { hint: "status" } },
79 ],
80 },
81 });
82 expect(commands.map((command) => command.name)).toEqual([
83 "compact",
84 "session-info",
85 "deep-research",
86 "workflow",
87 "goal",
88 ]);
89 expect(commands[0]?.input).toEqual({ hint: "what to preserve" });
90 expect(commands[2]).toEqual({
91 name: "deep-research",
92 description: "Research a topic",
93 input: { hint: "<query>" },
94 });
95 });
96
97 it("keeps valid commands when other metadata entries are malformed", () => {
98 const commands = grokSlashCommandsFromInitialize({
99 protocolVersion: 1,
100 _meta: {
101 availableCommands: [
102 null,
103 { name: "broken", description: 42 },
104 { name: " ", description: "Empty name" },
105 { name: " session-info ", description: " Session details " },
106 { name: "session-info", description: "Updated session details" },
107 ],
108 },
109 });
110 expect(commands.map((command) => command.name)).toEqual(["compact", "session-info"]);
111 expect(commands[1]?.description).toBe("Updated session details");
112 });
113
114 it("keeps compact available for older agents without command metadata", () => {
115 for (const _meta of [undefined, {}, { availableCommands: "invalid" }]) {
116 expect(
117 grokSlashCommandsFromInitialize({ protocolVersion: 1, ...(_meta ? { _meta } : {}) }).map(
118 (command) => command.name,
119 ),
120 ).toEqual(["compact"]);
121 }
122 });
123});
124
125describe("buildGrokModelsFromSessionModelState", () => {
126 it("marks the agent's current model as default and keeps reasoning options", () => {
127 const models = buildGrokModelsFromSessionModelState({
128 currentModelId: "grok-4.6",
129 availableModels: [
130 {
131 modelId: "grok-4.6",
132 name: "Grok 4.6",
133 _meta: {
134 supportsReasoningEffort: true,
135 reasoningEffort: "high",
136 reasoningEfforts: [{ value: "high", label: "High", default: true }],
137 },
138 },
139 { modelId: "grok-4.5", name: "Grok 4.5" },
140 ],
141 });
142 expect(models.map((model) => [model.slug, model.isDefault ?? false])).toEqual([
143 ["grok-4.6", true],
144 ["grok-4.5", false],
145 ]);
146 expect(models[0]?.capabilities?.optionDescriptors).toHaveLength(1);
147 });
148});
149
150describe("buildGrokModelCapabilities", () => {
151 it("preserves ACP-provided reasoning labels and the active default", () => {
152 const capabilities = buildGrokModelCapabilities({
153 modelId: "grok-4.6",
154 name: "Grok 4.6",
155 _meta: {
156 supportsReasoningEffort: true,
157 reasoningEffort: "xhigh",
158 reasoningEfforts: [
159 { value: "xhigh", label: "Extra High Effort", default: true },
160 { value: "high", label: "High Effort", default: true },
161 { value: "medium", label: "Medium Effort" },
162 { value: "low", label: "Low Effort" },
163 ],
164 },
165 });
166
167 expect(capabilities.optionDescriptors).toEqual([
168 {
169 id: "reasoningEffort",
170 label: "Reasoning",
171 type: "select",
172 currentValue: "xhigh",
173 options: [
174 { id: "xhigh", label: "Extra High Effort", isDefault: true },
175 { id: "high", label: "High Effort" },
176 { id: "medium", label: "Medium Effort" },
177 { id: "low", label: "Low Effort" },
178 ],
179 },
180 ]);
181 });
182
183 it("uses raw ACP values when option labels are omitted", () => {
184 const capabilities = buildGrokModelCapabilities({
185 modelId: "grok-4.6",
186 name: "Grok 4.6",
187 _meta: {
188 supportsReasoningEffort: true,
189 reasoningEffort: "xhigh",
190 reasoningEfforts: [{ value: "xhigh" }, { value: "medium" }],
191 },
192 });
193
194 expect(capabilities.optionDescriptors).toEqual([
195 {
196 id: "reasoningEffort",
197 label: "Reasoning",
198 type: "select",
199 currentValue: "xhigh",
200 options: [
201 { id: "xhigh", label: "xhigh" },
202 { id: "medium", label: "medium" },
203 ],
204 },
205 ]);
206 });
207
208 it("keeps ACP current effort separate from its collapsed advertised default", () => {
209 const capabilities = buildGrokModelCapabilities({
210 modelId: "grok-4.6",
211 name: "Grok 4.6",
212 _meta: {
213 supportsReasoningEffort: true,
214 reasoningEffort: "medium",
215 reasoningEfforts: [
216 { value: "xhigh", label: "Extra High Effort", default: true },
217 { value: "high", label: "High Effort", default: true },
218 { value: "medium", label: "Medium Effort" },
219 ],
220 },
221 });
222
223 expect(capabilities.optionDescriptors).toEqual([
224 {
225 id: "reasoningEffort",
226 label: "Reasoning",
227 type: "select",
228 currentValue: "medium",
229 options: [
230 { id: "xhigh", label: "Extra High Effort", isDefault: true },
231 { id: "high", label: "High Effort" },
232 { id: "medium", label: "Medium Effort" },
233 ],
234 },
235 ]);
236 });
237
238 it("preserves ACP descriptions and falls back from invalid values to valid ids", () => {
239 const capabilities = buildGrokModelCapabilities({
240 modelId: "grok-4.6",
241 name: "Grok 4.6",
242 _meta: {
243 supportsReasoningEffort: true,
244 reasoningEffort: "high",
245 reasoningEfforts: [
246 {
247 id: "high",
248 value: "not a token",
249 label: "High Effort",
250 description: "Higher implementation quality",
251 default: true,
252 },
253 { id: "bad id", value: "also invalid", label: "Invalid" },
254 ],
255 },
256 });
257
258 expect(capabilities.optionDescriptors).toEqual([
259 {
260 id: "reasoningEffort",
261 label: "Reasoning",
262 type: "select",
263 currentValue: "high",
264 options: [
265 {
266 id: "high",
267 label: "High Effort",
268 description: "Higher implementation quality",
269 isDefault: true,
270 },
271 ],
272 },
273 ]);
274 });
275
276 it("accepts an advertised ACP menu when the support flag is omitted", () => {
277 const capabilities = buildGrokModelCapabilities({
278 modelId: "grok-4.6",
279 name: "Grok 4.6",
280 _meta: {
281 reasoningEffort: "high",
282 reasoningEfforts: [{ value: "high", label: "High Effort", default: true }],
283 },
284 });
285
286 expect(capabilities.optionDescriptors).toHaveLength(1);
287 });
288
289 it("honors an explicit ACP opt-out even when a menu is present", () => {
290 const capabilities = buildGrokModelCapabilities({
291 modelId: "grok-4.6",
292 name: "Grok 4.6",
293 _meta: {
294 supportsReasoningEffort: false,
295 reasoningEfforts: [{ value: "high", label: "High Effort", default: true }],
296 },
297 });
298
299 expect(capabilities.optionDescriptors).toEqual([]);
300 });
301
302 it("does not synthesize a reasoning menu when ACP omits it", () => {
303 expect(
304 buildGrokModelCapabilities({
305 modelId: "grok-4.6",
306 name: "Grok 4.6",
307 _meta: { supportsReasoningEffort: true, reasoningEffort: "xhigh" },
308 }).optionDescriptors,
309 ).toEqual([]);
310 });
311
312 it("keeps non-reasoning Grok models free of reasoning controls", () => {
313 expect(
314 buildGrokModelCapabilities({ modelId: "grok-build", name: "Grok Build" }).optionDescriptors,
315 ).toEqual([]);
316 });
317});
318
319describe("buildInitialGrokProviderSnapshot", () => {
320 it.effect("returns a disabled snapshot when settings.enabled is false", () =>
321 Effect.gen(function* () {
322 const snapshot = yield* buildInitialGrokProviderSnapshot(
323 decodeGrokSettings({ enabled: false }),
324 );
325 expect(snapshot.enabled).toBe(false);
326 expect(snapshot.status).toBe("disabled");
327 expect(snapshot.installed).toBe(false);
328 expect(snapshot.message).toContain("disabled");
329 }),
330 );
331
332 it.effect("returns a disabled snapshot by default — Grok is opt-in", () =>
333 Effect.gen(function* () {
334 const snapshot = yield* buildInitialGrokProviderSnapshot(decodeGrokSettings({}));
335 expect(snapshot.enabled).toBe(false);
336 expect(snapshot.status).toBe("disabled");
337 }),
338 );
339
340 it.effect("returns a pending snapshot when enabled", () =>
341 Effect.gen(function* () {
342 const snapshot = yield* buildInitialGrokProviderSnapshot(
343 decodeGrokSettings({ enabled: true }),
344 );
345 expect(snapshot.enabled).toBe(true);
346 expect(snapshot.installed).toBe(true);
347 expect(snapshot.status).toBe("warning");
348 expect(snapshot.version).toBeNull();
349 expect(snapshot.message).toContain("Checking Grok");
350 expect(snapshot.requiresNewThreadForModelChange).toBeUndefined();
351 expect(snapshot.supportsConversationRollback).toBe(false);
352 }),
353 );
354});
355
356it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => {
357 it.effect("reports the binary as missing when the binary path does not resolve", () =>
358 Effect.gen(function* () {
359 const snapshot = yield* checkGrokProviderStatus(
360 decodeGrokSettings({
361 enabled: true,
362 binaryPath: "/definitely/not/installed/grok-binary",
363 }),
364 );
365 expect(snapshot.enabled).toBe(true);
366 expect(snapshot.installed).toBe(false);
367 expect(snapshot.status).toBe("error");
368 expect(snapshot.message).toMatch(/not installed|not on PATH|Failed to execute/);
369 }),
370 );
371
372 it.effect("reports an installed CLI as unhealthy when --version exits non-zero", () =>
373 Effect.gen(function* () {
374 const secretStderr = "broken grok install: secret-token-value";
375 const snapshot = yield* Effect.scoped(
376 Effect.gen(function* () {
377 const fs = yield* FileSystem.FileSystem;
378 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-version-" });
379 const grokPath = writeFakeCli({
380 directory: dir,
381 name: "grok",
382 source: [
383 `process.stderr.write(${JSON.stringify(`${secretStderr}\n`)});`,
384 "process.exit(2);",
385 "",
386 ].join("\n"),
387 });
388
389 return yield* checkGrokProviderStatus(
390 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
391 );
392 }),
393 );
394
395 expect(snapshot.enabled).toBe(true);
396 expect(snapshot.installed).toBe(true);
397 expect(snapshot.status).toBe("error");
398 expect(snapshot.message).toBe("Grok CLI is installed but failed to run.");
399 expect(snapshot.message).not.toContain(secretStderr);
400 }),
401 );
402
403 // A stand-in for the Grok CLI: `--version` and `models` print canned text,
404 // and `agent stdio` execs the mock ACP agent so `initialize` returns model metadata.
405 // A list of `models` outputs is served in call order, repeating the last one.
406 const writeFakeGrokCli = (input: {
407 readonly modelsOutput: string | ReadonlyArray<string>;
408 readonly acp: boolean;
409 readonly updateLogPath?: string;
410 }) =>
411 Effect.gen(function* () {
412 const fs = yield* FileSystem.FileSystem;
413 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-probe-" });
414 const mockAgentPath = NodePath.resolve(__dirname, "../../scripts/acp-mock-agent.ts");
415 return writeFakeCli({
416 directory: dir,
417 name: "grok",
418 source: [
419 ...(input.updateLogPath
420 ? [
421 'import { appendFileSync as appendUpdateAttempt } from "node:fs";',
422 'if (process.env.GROK_DISABLE_AUTOUPDATER !== "1") {',
423 ` appendUpdateAttempt(${JSON.stringify(input.updateLogPath)}, "update\\n");`,
424 "}",
425 ]
426 : []),
427 'if (process.argv[2] === "--version") {',
428 ' process.stdout.write("grok 1.0.13\\n");',
429 " process.exit(0);",
430 "}",
431 'if (process.argv[2] === "models") {',
432 ' const fs = await import("node:fs");',
433 ` const callsPath = ${JSON.stringify(NodePath.join(dir, "models-calls"))};`,
434 ' const calls = fs.existsSync(callsPath) ? fs.readFileSync(callsPath, "utf8").length : 0;',
435 ' fs.appendFileSync(callsPath, ".");',
436 ` const outputs = ${JSON.stringify([input.modelsOutput].flat())};`,
437 " process.stdout.write(outputs[Math.min(calls, outputs.length - 1)]);",
438 " process.exit(0);",
439 "}",
440 'if (process.argv[2] !== "agent") process.exit(1);',
441 ...(input.acp ? [execScriptSource({ scriptPath: mockAgentPath })] : ["process.exit(3);"]),
442 "",
443 ].join("\n"),
444 });
445 });
446
447 it.effect("reports ready with ACP-discovered models without running startup updates", () =>
448 Effect.gen(function* () {
449 const environment = { ...process.env, XAI_API_KEY: "", GROK_DISABLE_AUTOUPDATER: "0" };
450 const { snapshot, updateRan } = yield* Effect.scoped(
451 Effect.gen(function* () {
452 const fs = yield* FileSystem.FileSystem;
453 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-updater-" });
454 const updateLogPath = NodePath.join(dir, "updates.log");
455 const grokPath = yield* writeFakeGrokCli({
456 modelsOutput: LOGGED_IN_MODELS_OUTPUT,
457 acp: true,
458 updateLogPath,
459 });
460 const snapshot = yield* checkGrokProviderStatus(
461 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
462 environment,
463 );
464 return { snapshot, updateRan: yield* fs.exists(updateLogPath) };
465 }),
466 );
467
468 expect(updateRan).toBe(false);
469 expect(environment.GROK_DISABLE_AUTOUPDATER).toBe("0");
470 expect(snapshot.status).toBe("ready");
471 expect(snapshot.version).toBe("1.0.13");
472 expect(snapshot.auth).toEqual({
473 status: "authenticated",
474 type: "cached_token",
475 label: "Grok account",
476 });
477 expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-4.6", "grok-mock-alt"]);
478 expect(snapshot.models[0]?.isDefault).toBe(true);
479 expect(
480 snapshot.models[0]?.capabilities?.optionDescriptors?.map((option) => option.id) ?? [],
481 ).toEqual(["reasoningEffort"]);
482 }),
483 );
484
485 it.effect("reports unauthenticated from `grok models` without starting a session", () =>
486 Effect.gen(function* () {
487 const snapshot = yield* Effect.scoped(
488 Effect.gen(function* () {
489 const grokPath = yield* writeFakeGrokCli({
490 modelsOutput: LOGGED_OUT_MODELS_OUTPUT,
491 acp: true,
492 });
493 return yield* checkGrokProviderStatus(
494 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
495 { ...process.env, XAI_API_KEY: "" },
496 );
497 }),
498 );
499
500 expect(snapshot.status).toBe("error");
501 expect(snapshot.auth.status).toBe("unauthenticated");
502 expect(snapshot.message).toContain("grok login");
503 expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-4.6", "grok-mock-alt"]);
504 }),
505 );
506
507 // An expired access token prints the logged-out banner, then the CLI refreshes it in the
508 // same run, so the next `grok models` reports the login (#14285).
509 it.effect("reports authenticated when `grok models` logs in after refreshing a token", () =>
510 Effect.gen(function* () {
511 const snapshot = yield* Effect.scoped(
512 Effect.gen(function* () {
513 const grokPath = yield* writeFakeGrokCli({
514 modelsOutput: [LOGGED_OUT_MODELS_OUTPUT, LOGGED_IN_MODELS_OUTPUT],
515 acp: true,
516 });
517 return yield* checkGrokProviderStatus(
518 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
519 { ...process.env, XAI_API_KEY: "" },
520 );
521 }),
522 );
523
524 expect(snapshot.status).toBe("ready");
525 expect(snapshot.auth.status).toBe("authenticated");
526 }),
527 );
528
529 it.effect("falls back to CLI-listed models with a warning when ACP initialize fails", () =>
530 Effect.gen(function* () {
531 const snapshot = yield* Effect.scoped(
532 Effect.gen(function* () {
533 const grokPath = yield* writeFakeGrokCli({
534 modelsOutput: LOGGED_IN_MODELS_OUTPUT,
535 acp: false,
536 });
537 return yield* checkGrokProviderStatus(
538 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
539 { ...process.env, XAI_API_KEY: "" },
540 );
541 }),
542 );
543
544 expect(snapshot.status).toBe("warning");
545 expect(snapshot.installed).toBe(true);
546 expect(snapshot.auth.status).toBe("authenticated");
547 expect(snapshot.models.map((model) => [model.slug, model.isDefault ?? false])).toEqual([
548 ["grok-4.6", true],
549 ["grok-4.5", false],
550 ]);
551 expect(snapshot.message).toContain("ACP initialize failed");
552 expect(snapshot.slashCommands.map((command) => command.name)).toEqual(["compact"]);
553 }),
554 );
555
556 it.effect("treats XAI_API_KEY as authenticated regardless of CLI login state", () =>
557 Effect.gen(function* () {
558 const snapshot = yield* Effect.scoped(
559 Effect.gen(function* () {
560 const grokPath = yield* writeFakeGrokCli({
561 modelsOutput: LOGGED_OUT_MODELS_OUTPUT,
562 acp: false,
563 });
564 return yield* checkGrokProviderStatus(
565 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
566 { ...process.env, XAI_API_KEY: "xai-test-key" },
567 );
568 }),
569 );
570
571 expect(snapshot.auth).toEqual({
572 status: "authenticated",
573 type: "api_key",
574 label: "xAI API key",
575 });
576 expect(snapshot.status).toBe("warning");
577 }),
578 );
579});
580
581describe("Grok usage limits", () => {
582 const checkedAt = "2026-09-16T00:00:00.000Z";
583 const weeklyPeriod = {
584 type: "USAGE_PERIOD_TYPE_WEEKLY",
585 start: "2026-09-11T03:10:30.159171+00:00",
586 end: "2026-09-18T03:10:30.159171+00:00",
587 };
588
589 it("shows zero usage for complete weekly and monthly periods with no percentage", () => {
590 for (const [currentPeriod, kind, label, resetsAt] of [
591 [weeklyPeriod, "weekly", "Weekly", "2026-09-18T03:10:30.159Z"],
592 [
593 {
594 type: "USAGE_PERIOD_TYPE_MONTHLY",
595 start: "2026-09-01T00:00:00.000Z",
596 end: "2026-10-01T00:00:00.000Z",
597 },
598 "monthly",
599 "Monthly",
600 "2026-10-01T00:00:00.000Z",
601 ],
602 ] as const) {
603 const response = { config: { currentPeriod } };
604 expect
605 .soft(grokUsageResponseToLimits(response, checkedAt).windows)
606 .toEqual([{ id: "subscription", kind, label, usedPercent: 0, resetsAt }]);
607 }
608 });
609
610 it("keeps incomplete, invalid, unordered, and unknown periods unreported", () => {
611 for (const currentPeriod of [
612 undefined,
613 { ...weeklyPeriod, type: undefined },
614 { ...weeklyPeriod, type: "USAGE_PERIOD_TYPE_DAILY" },
615 { ...weeklyPeriod, start: undefined },
616 { ...weeklyPeriod, end: undefined },
617 { ...weeklyPeriod, start: "invalid" },
618 { ...weeklyPeriod, end: "invalid" },
619 { ...weeklyPeriod, start: weeklyPeriod.end },
620 { ...weeklyPeriod, start: weeklyPeriod.end, end: weeklyPeriod.start },
621 ]) {
622 const response = { config: { currentPeriod } };
623 expect
624 .soft(grokUsageResponseToLimits(response, checkedAt).windows, JSON.stringify(response))
625 .toEqual([]);
626 }
627 });
628
629 it("rejects impossible calendar dates at either period boundary", () => {
630 for (const [start, end] of [
631 ["2026-02-30T00:00:00.000Z", "2026-03-09T00:00:00.000Z"],
632 ["2026-02-23T00:00:00.000Z", "2026-02-30T00:00:00.000Z"],
633 ]) {
634 const response = { config: { currentPeriod: { ...weeklyPeriod, start, end } } };
635 expect
636 .soft(grokUsageResponseToLimits(response, checkedAt).windows, JSON.stringify(response))
637 .toEqual([]);
638 }
639 });
640
641 it("uses the reported subscription percentage and weekly reset", () => {
642 const limits = grokUsageResponseToLimits(
643 {
644 config: {
645 creditUsagePercent: 100,
646 currentPeriod: {
647 type: "USAGE_PERIOD_TYPE_WEEKLY",
648 end: "2026-09-18T03:10:30.159171+00:00",
649 },
650 },
651 },
652 checkedAt,
653 );
654 expect(limits.windows).toEqual([
655 {
656 id: "subscription",
657 kind: "weekly",
658 label: "Weekly",
659 usedPercent: 100,
660 resetsAt: "2026-09-18T03:10:30.159Z",
661 },
662 ]);
663 });
664
665 it("does not invent allowance or reset dates when billing omits them", () => {
666 for (const response of [{}, { config: {} }, { config: { creditUsagePercent: NaN } }]) {
667 const limits = grokUsageResponseToLimits(response, checkedAt);
668 expect(limits.windows).toEqual([]);
669 expect(limits.unavailable).toBeUndefined();
670 }
671 expect(
672 grokUsageResponseToLimits({ config: { creditUsagePercent: 0 } }, checkedAt).windows,
673 ).toEqual([{ id: "subscription", kind: "other", label: "Subscription", usedPercent: 0 }]);
674 expect(
675 grokUsageResponseToLimits(
676 {
677 config: {
678 creditUsagePercent: 120,
679 currentPeriod: { type: "USAGE_PERIOD_TYPE_MONTHLY", end: "invalid" },
680 },
681 },
682 checkedAt,
683 ).windows,
684 ).toEqual([{ id: "subscription", kind: "monthly", label: "Monthly", usedPercent: 100 }]);
685 });
686});
687
688it.layer(NodeServices.layer)("readGrokAccount", (it) => {
689 it.effect("reads the configured Grok home and prefers the current login scope to legacy", () =>
690 Effect.gen(function* () {
691 const fs = yield* FileSystem.FileSystem;
692 const directory = yield* fs.makeTempDirectoryScoped();
693 yield* fs.writeFileString(
694 NodePath.join(directory, "auth.json"),
695 '{"https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828":{"key":"session-token","auth_mode":"oauth"},"https://accounts.x.ai/sign-in":{"key":"legacy-token"}}',
696 );
697 const { usageLimits: limits } = yield* readGrokAccount({
698 GROK_HOME: directory,
699 HOME: "/unrelated-home",
700 }).pipe(
701 Effect.provideService(
702 HttpClient.HttpClient,
703 HttpClient.make((request) => {
704 expect(request.method).toBe("GET");
705 expect(request.url).toBe("https://cli-chat-proxy.grok.com/v1/billing?format=credits");
706 expect(request.headers.authorization).toBe("Bearer session-token");
707 return Effect.succeed(
708 HttpClientResponse.fromWeb(
709 request,
710 Response.json({ config: { creditUsagePercent: 37 } }),
711 ),
712 );
713 }),
714 ),
715 );
716 expect(limits.windows[0]?.usedPercent).toBe(37);
717 }).pipe(Effect.scoped),
718 );
719
720 it.effect(
721 "uses GROK_AUTH without reading stored credentials and accepts the legacy login scope",
722 () =>
723 readGrokAccount({
724 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"legacy-token"}}',
725 }).pipe(
726 Effect.provideService(
727 FileSystem.FileSystem,
728 FileSystem.makeNoop({
729 readFileString: (path) =>
730 path.endsWith("auth.json")
731 ? Effect.die("must not read stored credentials")
732 : Effect.succeed(""),
733 }),
734 ),
735 Effect.provideService(
736 HttpClient.HttpClient,
737 HttpClient.make((request) => {
738 expect(request.headers.authorization).toBe("Bearer legacy-token");
739 return Effect.succeed(
740 HttpClientResponse.fromWeb(
741 request,
742 Response.json({ config: { creditUsagePercent: 12 } }),
743 ),
744 );
745 }),
746 ),
747 Effect.tap(({ usageLimits }) =>
748 Effect.sync(() => expect(usageLimits.windows[0]?.usedPercent).toBe(12)),
749 ),
750 ),
751 );
752
753 it.effect("ignores malformed period starts without inventing usage", () =>
754 Effect.gen(function* () {
755 for (const start of [null, 42]) {
756 for (const creditUsagePercent of [37.5, undefined]) {
757 const response = {
758 config: {
759 creditUsagePercent,
760 currentPeriod: {
761 type: "USAGE_PERIOD_TYPE_WEEKLY",
762 start,
763 end: "2026-09-18T03:10:30.159171+00:00",
764 },
765 },
766 };
767 const { usageLimits } = yield* readGrokAccount({
768 HOME: "/definitely/not/a/grok-home",
769 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"session-token"}}',
770 }).pipe(
771 Effect.provideService(
772 HttpClient.HttpClient,
773 HttpClient.make((request) =>
774 Effect.succeed(HttpClientResponse.fromWeb(request, Response.json(response))),
775 ),
776 ),
777 );
778 expect.soft(usageLimits.unavailable, JSON.stringify(response)).toBeUndefined();
779 expect.soft(usageLimits.windows, JSON.stringify(response)).toEqual(
780 creditUsagePercent === undefined
781 ? []
782 : [
783 {
784 id: "subscription",
785 kind: "weekly",
786 label: "Weekly",
787 usedPercent: creditUsagePercent,
788 resetsAt: "2026-09-18T03:10:30.159Z",
789 },
790 ],
791 );
792 }
793 }
794 }),
795 );
796
797 it.effect("does not use unrelated scopes, API keys, or custom auth deployments", () =>
798 Effect.gen(function* () {
799 for (const environment of [
800 {
801 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"stored-account"}}',
802 XAI_API_KEY: "different-api-account",
803 },
804 { GROK_AUTH: '{"https://other.example":{"key":"unrelated-token"}}' },
805 { GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"api-key","auth_mode":"api_key"}}' },
806 { GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":" "}}' },
807 {
808 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"session-token"}}',
809 GROK_OIDC_ISSUER: "https://custom.example",
810 },
811 {
812 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"stored-account"}}',
813 GROK_MODELS_BASE_URL: "https://custom.example/v1",
814 },
815 {
816 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"stored-account"}}',
817 GROK_OAUTH2_PRINCIPAL_TYPE: "Team",
818 },
819 {
820 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"stored-account"}}',
821 GROK_OAUTH2_PRINCIPAL_ID: "team-id",
822 },
823 {
824 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"session-token"}}',
825 GROK_CONFIG: '{"auth_provider_command":"custom-auth"}',
826 },
827 {
828 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"session-token"}}',
829 GROK_CONFIG_PATH: "/custom-config.toml",
830 },
831 ]) {
832 const { usageLimits: limits } = yield* readGrokAccount({
833 HOME: "/definitely/not/a/grok-home",
834 ...environment,
835 }).pipe(
836 Effect.provideService(
837 HttpClient.HttpClient,
838 HttpClient.make(() => Effect.die("must not request another account's quota")),
839 ),
840 );
841 expect(limits.windows).toEqual([]);
842 expect(limits.unavailable?.reason).toBe("unsupported");
843 }
844 }),
845 );
846
847 it.effect(
848 "reports a missing login as unsupported and malformed credentials as a sanitized failure",
849 () =>
850 Effect.gen(function* () {
851 const fs = yield* FileSystem.FileSystem;
852 const directory = yield* fs.makeTempDirectoryScoped();
853 const client = HttpClient.make(() => Effect.die("must not request without credentials"));
854 const { usageLimits: missing } = yield* readGrokAccount({ HOME: directory }).pipe(
855 Effect.provideService(HttpClient.HttpClient, client),
856 );
857 expect(missing.unavailable?.reason).toBe("unsupported");
858 for (const contents of [
859 "private-token-invalid-json",
860 '{"https://accounts.x.ai/sign-in":{"key":42}}',
861 ]) {
862 const { usageLimits: malformed } = yield* readGrokAccount({
863 GROK_HOME: directory,
864 GROK_AUTH: contents,
865 }).pipe(Effect.provideService(HttpClient.HttpClient, client));
866 expect(malformed.unavailable).toEqual({
867 reason: "probeFailed",
868 message: "Grok could not read usage limits.",
869 });
870 }
871 }).pipe(Effect.scoped),
872 );
873
874 it.effect(
875 "does not request subscription limits for custom account or endpoint configuration",
876 () =>
877 Effect.gen(function* () {
878 for (const config of [
879 '[auth]\nprovider_command = "custom-auth"',
880 '[grok_com_config]\nissuer = "https://custom.example"',
881 'endpoints.proxy = "https://custom.example"',
882 ]) {
883 const { usageLimits: limits } = yield* readGrokAccount({
884 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"stored-token"}}',
885 }).pipe(
886 Effect.provideService(
887 FileSystem.FileSystem,
888 FileSystem.makeNoop({
889 readFileString: (path) => {
890 expect(path.endsWith("config.toml")).toBe(true);
891 return Effect.succeed(config);
892 },
893 }),
894 ),
895 Effect.provideService(
896 HttpClient.HttpClient,
897 HttpClient.make(() => Effect.die("must not request another account's quota")),
898 ),
899 );
900 expect(limits.windows).toEqual([]);
901 expect(limits.unavailable?.reason).toBe("unsupported");
902 }
903 }),
904 );
905
906 it.effect("sanitizes HTTP failures and malformed billing responses, keeping the account", () =>
907 Effect.gen(function* () {
908 for (const response of [
909 new Response("private response", { status: 401 }),
910 Response.json({ config: { creditUsagePercent: "private-value" } }),
911 ]) {
912 const { email, usageLimits: limits } = yield* readGrokAccount({
913 HOME: "/definitely/not/a/grok-home",
914 GROK_AUTH:
915 '{"https://accounts.x.ai/sign-in":{"key":"private-token","email":"someone@example.com"}}',
916 }).pipe(
917 Effect.provideService(
918 HttpClient.HttpClient,
919 HttpClient.make((request) =>
920 Effect.succeed(HttpClientResponse.fromWeb(request, response)),
921 ),
922 ),
923 );
924 expect(email).toBe("someone@example.com");
925 expect(limits.windows).toEqual([]);
926 expect(limits.unavailable).toEqual({
927 reason: "probeFailed",
928 message: "Grok could not read usage limits.",
929 });
930 }
931 }),
932 );
933});
934
935it.layer(NodeServices.layer)("readGrokAccount email", (it) => {
936 it.effect("names the account whose limits were read, and nothing for other auth", () =>
937 Effect.gen(function* () {
938 const current = '"https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828"';
939 const cases = [
940 [
941 { GROK_AUTH: `{${current}:{"key":"t","email":" Someone@Example.com "}}` },
942 "Someone@Example.com",
943 ],
944 [
945 {
946 GROK_AUTH: `{${current}:{"key":"t","email":"current@example.com"},"https://accounts.x.ai/sign-in":{"key":"t","email":"legacy@example.com"}}`,
947 },
948 "current@example.com",
949 ],
950 [{ GROK_AUTH: `{${current}:{"key":"t"}}` }, undefined],
951 [
952 {
953 GROK_AUTH: `{${current}:{"key":"t","email":"someone@example.com"}}`,
954 XAI_API_KEY: "api-key",
955 },
956 undefined,
957 ],
958 [
959 {
960 GROK_AUTH: `{${current}:{"key":"t","email":"someone@example.com","auth_mode":"api_key"}}`,
961 },
962 undefined,
963 ],
964 [{ GROK_AUTH: "not-json" }, undefined],
965 ] as const;
966 for (const [environment, expected] of cases) {
967 const { email, usageLimits } = yield* readGrokAccount({
968 HOME: "/definitely/not/a/grok-home",
969 ...environment,
970 }).pipe(
971 Effect.provideService(
972 HttpClient.HttpClient,
973 HttpClient.make((request) =>
974 Effect.succeed(
975 HttpClientResponse.fromWeb(
976 request,
977 Response.json({ config: { creditUsagePercent: 25 } }),
978 ),
979 ),
980 ),
981 ),
982 );
983 expect(email).toBe(expected);
984 if (expected) expect(usageLimits.windows[0]?.usedPercent).toBe(25);
985 }
986 }),
987 );
988});