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 Fiber from "effect/Fiber";
9import * as FileSystem from "effect/FileSystem";
10import * as PlatformError from "effect/PlatformError";
11import * as Schema from "effect/Schema";
12import * as Sink from "effect/Sink";
13import * as Stream from "effect/Stream";
14import { HttpClient, HttpClientResponse } from "effect/http";
15import * as ChildProcess from "effect/process/ChildProcess";
16import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
17import * as TestClock from "effect/testing/TestClock";
18import { GrokSettings } from "@t3tools/provider-grok/settings";
19
20import {
21 buildGrokModelCapabilities,
22 checkGrokProviderStatus,
23 grokSlashCommandsFromInitialize,
24 parseGrokModelsCliOutput,
25} from "@t3tools/provider-grok/testing";
26import { execScriptSource, writeFakeCli } from "@t3tools/provider-testing/fakeCli";
27import { grokUsageResponseToLimits, readGrokAccount } from "@t3tools/provider-grok/testing";
28
29const decodeGrokSettings = Schema.decodeSync(GrokSettings);
30const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
31
32const LOGGED_IN_MODELS_OUTPUT = [
33 "You are logged in with grok.com.",
34 "",
35 "Default model: grok-4.6",
36 "",
37 "Available models:",
38 " * grok-4.6 (default)",
39 " - grok-4.5",
40 "",
41].join("\n");
42
43const LOGGED_OUT_MODELS_OUTPUT = LOGGED_IN_MODELS_OUTPUT.replace(
44 "You are logged in with grok.com.",
45 "You are not authenticated.",
46);
47
48describe("parseGrokModelsCliOutput", () => {
49 it("reads login state and model slugs, marking the default", () => {
50 const parsed = parseGrokModelsCliOutput(LOGGED_IN_MODELS_OUTPUT);
51 expect(parsed.authenticated).toBe(true);
52 expect(parsed.models.map((model) => [model.slug, model.isDefault ?? false])).toEqual([
53 ["grok-4.6", true],
54 ["grok-4.5", false],
55 ]);
56 });
57
58 it("detects a logged-out CLI even though it exits 0", () => {
59 expect(parseGrokModelsCliOutput(LOGGED_OUT_MODELS_OUTPUT).authenticated).toBe(false);
60 });
61});
62
63describe("grokSlashCommandsFromInitialize", () => {
64 it("publishes native ACP commands and input hints without permission overrides", () => {
65 const commands = grokSlashCommandsFromInitialize({
66 protocolVersion: 1,
67 _meta: {
68 availableCommands: [
69 { name: "compact", description: "Compress history", input: { hint: "what to preserve" } },
70 {
71 name: "always-approve",
72 description: "Skip permission prompts",
73 input: { hint: "on|off" },
74 },
75 { name: "context", description: "Show context usage", input: null },
76 { name: "session-info", description: "Show session details" },
77 { name: "deep-research", description: "Research a topic", input: { hint: "<query>" } },
78 { name: "workflow", description: "Manage workflows", input: { hint: "runs" } },
79 { name: "goal", description: "Manage an autonomous goal", input: { hint: "status" } },
80 ],
81 },
82 });
83 expect(commands.map((command) => command.name)).toEqual([
84 "compact",
85 "session-info",
86 "deep-research",
87 "workflow",
88 "goal",
89 ]);
90 expect(commands[0]?.input).toEqual({ hint: "what to preserve" });
91 expect(commands[2]).toEqual({
92 name: "deep-research",
93 description: "Research a topic",
94 input: { hint: "<query>" },
95 });
96 });
97
98 it("keeps valid commands when other metadata entries are malformed", () => {
99 const commands = grokSlashCommandsFromInitialize({
100 protocolVersion: 1,
101 _meta: {
102 availableCommands: [
103 null,
104 { name: "broken", description: 42 },
105 { name: " ", description: "Empty name" },
106 { name: " session-info ", description: " Session details " },
107 { name: "session-info", description: "Updated session details" },
108 ],
109 },
110 });
111 expect(commands.map((command) => command.name)).toEqual(["compact", "session-info"]);
112 expect(commands[1]?.description).toBe("Updated session details");
113 });
114});
115
116describe("buildGrokModelCapabilities", () => {
117 it("keeps ACP current effort separate from its collapsed advertised default", () => {
118 const capabilities = buildGrokModelCapabilities({
119 modelId: "grok-4.6",
120 name: "Grok 4.6",
121 _meta: {
122 supportsReasoningEffort: true,
123 reasoningEffort: "medium",
124 reasoningEfforts: [
125 { value: "xhigh", label: "Extra High Effort", default: true },
126 { value: "high", label: "High Effort", default: true },
127 { value: "medium", label: "Medium Effort" },
128 ],
129 },
130 });
131
132 expect(capabilities.optionDescriptors).toEqual([
133 {
134 id: "reasoningEffort",
135 label: "Reasoning",
136 type: "select",
137 currentValue: "medium",
138 options: [
139 { id: "medium", label: "Medium Effort" },
140 { id: "high", label: "High Effort" },
141 { id: "xhigh", label: "Extra High Effort", isDefault: true },
142 ],
143 },
144 ]);
145 });
146
147 it("preserves ACP descriptions and falls back from invalid values to valid ids", () => {
148 const capabilities = buildGrokModelCapabilities({
149 modelId: "grok-4.6",
150 name: "Grok 4.6",
151 _meta: {
152 supportsReasoningEffort: true,
153 reasoningEffort: "high",
154 reasoningEfforts: [
155 {
156 id: "high",
157 value: "not a token",
158 label: "High Effort",
159 description: "Higher implementation quality",
160 default: true,
161 },
162 { id: "bad id", value: "also invalid", label: "Invalid" },
163 ],
164 },
165 });
166
167 expect(capabilities.optionDescriptors).toEqual([
168 {
169 id: "reasoningEffort",
170 label: "Reasoning",
171 type: "select",
172 currentValue: "high",
173 options: [
174 {
175 id: "high",
176 label: "High Effort",
177 description: "Higher implementation quality",
178 isDefault: true,
179 },
180 ],
181 },
182 ]);
183 });
184
185 it("honors an explicit ACP opt-out even when a menu is present", () => {
186 const capabilities = buildGrokModelCapabilities({
187 modelId: "grok-4.6",
188 name: "Grok 4.6",
189 _meta: {
190 supportsReasoningEffort: false,
191 reasoningEfforts: [{ value: "high", label: "High Effort", default: true }],
192 },
193 });
194
195 expect(capabilities.optionDescriptors).toEqual([]);
196 });
197});
198
199it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => {
200 it.effect("reports an installed CLI as unhealthy when --version exits non-zero", () =>
201 Effect.gen(function* () {
202 const secretStderr = "broken grok install: secret-token-value";
203 const snapshot = yield* Effect.scoped(
204 Effect.gen(function* () {
205 const fs = yield* FileSystem.FileSystem;
206 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-version-" });
207 const grokPath = writeFakeCli({
208 directory: dir,
209 name: "grok",
210 source: [
211 `process.stderr.write(${JSON.stringify(`${secretStderr}\n`)});`,
212 "process.exit(2);",
213 "",
214 ].join("\n"),
215 });
216
217 return yield* checkGrokProviderStatus(
218 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
219 );
220 }),
221 );
222
223 expect(snapshot.enabled).toBe(true);
224 expect(snapshot.installed).toBe(true);
225 expect(snapshot.status).toBe("error");
226 expect(snapshot.message).toBe("Grok CLI is installed but failed to run.");
227 expect(snapshot.message).not.toContain(secretStderr);
228 }),
229 );
230
231 it.effect.each([
232 {
233 label: "answers after 6 s",
234 versionDelay: "6 seconds",
235 version: "1.0.52",
236 message: "Grok CLI is installed but ACP initialize failed. Model options may be incomplete.",
237 probesAfterVersion: true,
238 },
239 {
240 label: "never answers",
241 versionDelay: "Infinity",
242 version: null,
243 message: "Grok CLI is installed but timed out while running `grok --version`.",
244 probesAfterVersion: false,
245 },
246 ] as const)("gives `grok --version` 10 s when it $label", (row) =>
247 Effect.gen(function* () {
248 // A fake CLI runs on wall time, so a stub answers `--version` on the test clock.
249 const spawned: Array<string> = [];
250 const spawner = ChildProcessSpawner.make((command) => {
251 const args = ChildProcess.isStandardCommand(command) ? command.args : [];
252 spawned.push(args.join(" "));
253 if (!args.includes("--version")) {
254 return Effect.fail(
255 PlatformError.systemError({
256 _tag: "PermissionDenied",
257 module: "ChildProcess",
258 method: "spawn",
259 description: "Only `grok --version` is stubbed.",
260 }),
261 );
262 }
263 const handle = ChildProcessSpawner.makeHandle({
264 pid: ChildProcessSpawner.ProcessId(900_000_201),
265 exitCode: Effect.delay(Effect.succeed(ChildProcessSpawner.ExitCode(0)), row.versionDelay),
266 isRunning: Effect.succeed(true),
267 kill: () => Effect.void,
268 unref: Effect.succeed(Effect.void),
269 stdin: Sink.drain,
270 stdout: Stream.encodeText(
271 Stream.fromEffect(Effect.delay(Effect.succeed("grok 1.0.52\n"), row.versionDelay)),
272 ),
273 stderr: Stream.empty,
274 all: Stream.empty,
275 getInputFd: () => Sink.drain,
276 getOutputFd: () => Stream.empty,
277 });
278 return Effect.succeed(handle);
279 });
280 const fiber = yield* checkGrokProviderStatus(decodeGrokSettings({ enabled: true }), {}).pipe(
281 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
282 Effect.forkChild,
283 );
284 yield* TestClock.adjust("10 seconds");
285 const snapshot = yield* Fiber.join(fiber);
286 expect(snapshot.installed).toBe(true);
287 expect(snapshot.version).toBe(row.version);
288 expect(snapshot.message).toBe(row.message);
289 expect(spawned.length > 1).toBe(row.probesAfterVersion);
290 }),
291 );
292
293 // A stand-in for the Grok CLI: `--version` and `models` print canned text,
294 // and `agent stdio` execs the mock ACP agent so `initialize` returns model metadata.
295 // A list of `models` outputs is served in call order, repeating the last one.
296 const writeFakeGrokCli = (input: {
297 readonly modelsOutput: string | ReadonlyArray<string>;
298 readonly acp: boolean;
299 readonly updateLogPath?: string;
300 }) =>
301 Effect.gen(function* () {
302 const fs = yield* FileSystem.FileSystem;
303 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-probe-" });
304 const mockAgentPath = NodePath.resolve(__dirname, "../../scripts/acp-mock-agent.ts");
305 return writeFakeCli({
306 directory: dir,
307 name: "grok",
308 source: [
309 ...(input.updateLogPath
310 ? [
311 'import { appendFileSync as appendUpdateAttempt } from "node:fs";',
312 'if (process.env.GROK_DISABLE_AUTOUPDATER !== "1") {',
313 ` appendUpdateAttempt(${JSON.stringify(input.updateLogPath)}, "update\\n");`,
314 "}",
315 ]
316 : []),
317 'if (process.argv[2] === "--version") {',
318 ' process.stdout.write("grok 1.0.13\\n");',
319 " process.exit(0);",
320 "}",
321 'if (process.argv[2] === "models") {',
322 ' const fs = await import("node:fs");',
323 ` const callsPath = ${JSON.stringify(NodePath.join(dir, "models-calls"))};`,
324 ' const calls = fs.existsSync(callsPath) ? fs.readFileSync(callsPath, "utf8").length : 0;',
325 ' fs.appendFileSync(callsPath, ".");',
326 ` const outputs = ${JSON.stringify([input.modelsOutput].flat())};`,
327 " process.stdout.write(outputs[Math.min(calls, outputs.length - 1)]);",
328 " process.exit(0);",
329 "}",
330 'if (process.argv[2] !== "agent") process.exit(1);',
331 ...(input.acp ? [execScriptSource({ scriptPath: mockAgentPath })] : ["process.exit(3);"]),
332 "",
333 ].join("\n"),
334 });
335 });
336
337 it.effect("reports ready with ACP-discovered models without running startup updates", () =>
338 Effect.gen(function* () {
339 const environment = { ...process.env, XAI_API_KEY: "", GROK_DISABLE_AUTOUPDATER: "0" };
340 const { snapshot, updateRan } = yield* Effect.scoped(
341 Effect.gen(function* () {
342 const fs = yield* FileSystem.FileSystem;
343 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-updater-" });
344 const updateLogPath = NodePath.join(dir, "updates.log");
345 const grokPath = yield* writeFakeGrokCli({
346 modelsOutput: LOGGED_IN_MODELS_OUTPUT,
347 acp: true,
348 updateLogPath,
349 });
350 const snapshot = yield* checkGrokProviderStatus(
351 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
352 environment,
353 );
354 return { snapshot, updateRan: yield* fs.exists(updateLogPath) };
355 }),
356 );
357
358 expect(updateRan).toBe(false);
359 expect(environment.GROK_DISABLE_AUTOUPDATER).toBe("0");
360 expect(snapshot.status).toBe("ready");
361 expect(snapshot.version).toBe("1.0.13");
362 expect(snapshot.auth).toEqual({
363 status: "authenticated",
364 type: "cached_token",
365 label: "Grok account",
366 });
367 expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-4.6", "grok-mock-alt"]);
368 expect(snapshot.models[0]?.isDefault).toBe(true);
369 expect(
370 snapshot.models[0]?.capabilities?.optionDescriptors?.map((option) => option.id) ?? [],
371 ).toEqual(["reasoningEffort"]);
372 }),
373 );
374
375 // An expired access token prints the logged-out banner, then the CLI refreshes it in the
376 // same run, so the next `grok models` reports the login.
377 it.effect("reports authenticated when `grok models` logs in after refreshing a token", () =>
378 Effect.gen(function* () {
379 const snapshot = yield* Effect.scoped(
380 Effect.gen(function* () {
381 const grokPath = yield* writeFakeGrokCli({
382 modelsOutput: [LOGGED_OUT_MODELS_OUTPUT, LOGGED_IN_MODELS_OUTPUT],
383 acp: true,
384 });
385 return yield* checkGrokProviderStatus(
386 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
387 { ...process.env, XAI_API_KEY: "" },
388 );
389 }),
390 );
391
392 expect(snapshot.status).toBe("ready");
393 expect(snapshot.auth.status).toBe("authenticated");
394 }),
395 );
396
397 it.effect("falls back to CLI-listed models with a warning when ACP initialize fails", () =>
398 Effect.gen(function* () {
399 const snapshot = yield* Effect.scoped(
400 Effect.gen(function* () {
401 const grokPath = yield* writeFakeGrokCli({
402 modelsOutput: LOGGED_IN_MODELS_OUTPUT,
403 acp: false,
404 });
405 return yield* checkGrokProviderStatus(
406 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
407 { ...process.env, XAI_API_KEY: "" },
408 );
409 }),
410 );
411
412 expect(snapshot.status).toBe("warning");
413 expect(snapshot.installed).toBe(true);
414 expect(snapshot.auth.status).toBe("authenticated");
415 expect(snapshot.models.map((model) => [model.slug, model.isDefault ?? false])).toEqual([
416 ["grok-4.6", true],
417 ["grok-4.5", false],
418 ]);
419 expect(snapshot.message).toContain("ACP initialize failed");
420 expect(snapshot.slashCommands.map((command) => command.name)).toEqual(["compact"]);
421 }),
422 );
423
424 it.effect("warns instead of reporting ready when no models are discovered", () =>
425 Effect.gen(function* () {
426 const snapshot = yield* Effect.scoped(
427 Effect.gen(function* () {
428 const grokPath = yield* writeFakeGrokCli({
429 modelsOutput: "You are logged in with grok.com.\n",
430 acp: true,
431 });
432 return yield* checkGrokProviderStatus(
433 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
434 { ...process.env, XAI_API_KEY: "", T3_ACP_OMIT_INITIALIZE_MODEL_STATE: "1" },
435 );
436 }),
437 );
438
439 expect(snapshot.status).toBe("warning");
440 expect(snapshot.message).toContain("did not list any models");
441 expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-build"]);
442 }),
443 );
444
445 it.effect("treats XAI_API_KEY as authenticated regardless of CLI login state", () =>
446 Effect.gen(function* () {
447 const snapshot = yield* Effect.scoped(
448 Effect.gen(function* () {
449 const grokPath = yield* writeFakeGrokCli({
450 modelsOutput: LOGGED_OUT_MODELS_OUTPUT,
451 acp: false,
452 });
453 return yield* checkGrokProviderStatus(
454 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
455 { ...process.env, XAI_API_KEY: "xai-test-key" },
456 );
457 }),
458 );
459
460 expect(snapshot.auth).toEqual({
461 status: "authenticated",
462 type: "api_key",
463 label: "xAI API key",
464 });
465 expect(snapshot.status).toBe("warning");
466 }),
467 );
468});
469
470describe("Grok usage limits", () => {
471 const checkedAt = "2026-09-16T00:00:00.000Z";
472 const weeklyPeriod = {
473 type: "USAGE_PERIOD_TYPE_WEEKLY",
474 start: "2026-09-11T03:10:30.159171+00:00",
475 end: "2026-09-18T03:10:30.159171+00:00",
476 };
477
478 it("shows zero usage for complete weekly and monthly periods with no percentage", () => {
479 for (const [currentPeriod, kind, label, resetsAt] of [
480 [weeklyPeriod, "weekly", "Weekly", "2026-09-18T03:10:30.159Z"],
481 [
482 {
483 type: "USAGE_PERIOD_TYPE_MONTHLY",
484 start: "2026-09-01T00:00:00.000Z",
485 end: "2026-10-01T00:00:00.000Z",
486 },
487 "monthly",
488 "Monthly",
489 "2026-10-01T00:00:00.000Z",
490 ],
491 ] as const) {
492 const response = { config: { currentPeriod } };
493 expect
494 .soft(grokUsageResponseToLimits(response, checkedAt).windows)
495 .toEqual([{ id: "subscription", kind, label, usedPercent: 0, resetsAt }]);
496 }
497 });
498
499 it("keeps incomplete, invalid, unordered, and unknown periods unreported", () => {
500 for (const currentPeriod of [
501 undefined,
502 { ...weeklyPeriod, type: undefined },
503 { ...weeklyPeriod, type: "USAGE_PERIOD_TYPE_DAILY" },
504 { ...weeklyPeriod, start: undefined },
505 { ...weeklyPeriod, end: undefined },
506 { ...weeklyPeriod, start: "invalid" },
507 { ...weeklyPeriod, end: "invalid" },
508 { ...weeklyPeriod, start: weeklyPeriod.end },
509 { ...weeklyPeriod, start: weeklyPeriod.end, end: weeklyPeriod.start },
510 ]) {
511 const response = { config: { currentPeriod } };
512 expect
513 .soft(grokUsageResponseToLimits(response, checkedAt).windows, JSON.stringify(response))
514 .toEqual([]);
515 }
516 });
517
518 // regression: #17061 show zero-use Grok billing periods
519 it("rejects impossible calendar dates at either period boundary", () => {
520 for (const [start, end] of [
521 ["2026-02-30T00:00:00.000Z", "2026-03-09T00:00:00.000Z"],
522 ["2026-02-23T00:00:00.000Z", "2026-02-30T00:00:00.000Z"],
523 ]) {
524 const response = { config: { currentPeriod: { ...weeklyPeriod, start, end } } };
525 expect
526 .soft(grokUsageResponseToLimits(response, checkedAt).windows, JSON.stringify(response))
527 .toEqual([]);
528 }
529 });
530
531 it("does not invent allowance or reset dates when billing omits them", () => {
532 for (const response of [{}, { config: {} }, { config: { creditUsagePercent: NaN } }]) {
533 const limits = grokUsageResponseToLimits(response, checkedAt);
534 expect(limits.windows).toEqual([]);
535 expect(limits.unavailable).toBeUndefined();
536 }
537 expect(
538 grokUsageResponseToLimits({ config: { creditUsagePercent: 0 } }, checkedAt).windows,
539 ).toEqual([{ id: "subscription", kind: "other", label: "Subscription", usedPercent: 0 }]);
540 expect(
541 grokUsageResponseToLimits(
542 {
543 config: {
544 creditUsagePercent: 120,
545 currentPeriod: { type: "USAGE_PERIOD_TYPE_MONTHLY", end: "invalid" },
546 },
547 },
548 checkedAt,
549 ).windows,
550 ).toEqual([{ id: "subscription", kind: "monthly", label: "Monthly", usedPercent: 100 }]);
551 });
552});
553
554it.layer(NodeServices.layer)("readGrokAccount", (it) => {
555 it.effect("reads the configured Grok home and prefers the current login scope to legacy", () =>
556 Effect.gen(function* () {
557 const fs = yield* FileSystem.FileSystem;
558 const directory = yield* fs.makeTempDirectoryScoped();
559 yield* fs.writeFileString(
560 NodePath.join(directory, "auth.json"),
561 '{"https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828":{"key":"session-token","auth_mode":"oauth"},"https://accounts.x.ai/sign-in":{"key":"legacy-token"}}',
562 );
563 const { usageLimits: limits } = yield* readGrokAccount({
564 GROK_HOME: directory,
565 HOME: "/unrelated-home",
566 }).pipe(
567 Effect.provideService(
568 HttpClient.HttpClient,
569 HttpClient.make((request) => {
570 expect(request.method).toBe("GET");
571 expect(request.url).toBe("https://cli-chat-proxy.grok.com/v1/billing?format=credits");
572 expect(request.headers.authorization).toBe("Bearer session-token");
573 return Effect.succeed(
574 HttpClientResponse.fromWeb(
575 request,
576 Response.json({ config: { creditUsagePercent: 37 } }),
577 ),
578 );
579 }),
580 ),
581 );
582 expect(limits.windows[0]?.usedPercent).toBe(37);
583 }).pipe(Effect.scoped),
584 );
585
586 it.effect(
587 "uses GROK_AUTH without reading stored credentials and accepts the legacy login scope",
588 () =>
589 readGrokAccount({
590 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"legacy-token"}}',
591 }).pipe(
592 Effect.provideService(
593 FileSystem.FileSystem,
594 FileSystem.makeNoop({
595 readFileString: (path) =>
596 path.endsWith("auth.json")
597 ? Effect.die("must not read stored credentials")
598 : Effect.succeed(""),
599 }),
600 ),
601 Effect.provideService(
602 HttpClient.HttpClient,
603 HttpClient.make((request) => {
604 expect(request.headers.authorization).toBe("Bearer legacy-token");
605 return Effect.succeed(
606 HttpClientResponse.fromWeb(
607 request,
608 Response.json({ config: { creditUsagePercent: 12 } }),
609 ),
610 );
611 }),
612 ),
613 Effect.tap(({ usageLimits }) =>
614 Effect.sync(() => expect(usageLimits.windows[0]?.usedPercent).toBe(12)),
615 ),
616 ),
617 );
618
619 it.effect("does not use unrelated scopes, API keys, or custom auth deployments", () =>
620 Effect.gen(function* () {
621 for (const environment of [
622 {
623 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"stored-account"}}',
624 XAI_API_KEY: "different-api-account",
625 },
626 { GROK_AUTH: '{"https://other.example":{"key":"unrelated-token"}}' },
627 { GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"api-key","auth_mode":"api_key"}}' },
628 { GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":" "}}' },
629 {
630 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"session-token"}}',
631 GROK_OIDC_ISSUER: "https://custom.example",
632 },
633 {
634 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"stored-account"}}',
635 GROK_MODELS_BASE_URL: "https://custom.example/v1",
636 },
637 {
638 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"stored-account"}}',
639 GROK_OAUTH2_PRINCIPAL_TYPE: "Team",
640 },
641 {
642 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"stored-account"}}',
643 GROK_OAUTH2_PRINCIPAL_ID: "team-id",
644 },
645 {
646 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"session-token"}}',
647 GROK_CONFIG: '{"auth_provider_command":"custom-auth"}',
648 },
649 {
650 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"session-token"}}',
651 GROK_CONFIG_PATH: "/custom-config.toml",
652 },
653 ]) {
654 const { usageLimits: limits } = yield* readGrokAccount({
655 HOME: "/definitely/not/a/grok-home",
656 ...environment,
657 }).pipe(
658 Effect.provideService(
659 HttpClient.HttpClient,
660 HttpClient.make(() => Effect.die("must not request another account's quota")),
661 ),
662 );
663 expect(limits.windows).toEqual([]);
664 expect(limits.unavailable?.reason).toBe("unsupported");
665 }
666 }),
667 );
668
669 it.effect(
670 "reports a missing login as unsupported and malformed credentials as a sanitized failure",
671 () =>
672 Effect.gen(function* () {
673 const fs = yield* FileSystem.FileSystem;
674 const directory = yield* fs.makeTempDirectoryScoped();
675 const client = HttpClient.make(() => Effect.die("must not request without credentials"));
676 const { usageLimits: missing } = yield* readGrokAccount({ HOME: directory }).pipe(
677 Effect.provideService(HttpClient.HttpClient, client),
678 );
679 expect(missing.unavailable?.reason).toBe("unsupported");
680 for (const contents of [
681 "private-token-invalid-json",
682 '{"https://accounts.x.ai/sign-in":{"key":42}}',
683 ]) {
684 const { usageLimits: malformed } = yield* readGrokAccount({
685 GROK_HOME: directory,
686 GROK_AUTH: contents,
687 }).pipe(Effect.provideService(HttpClient.HttpClient, client));
688 expect(malformed.unavailable).toEqual({
689 reason: "probeFailed",
690 message: "Grok could not read usage limits.",
691 });
692 }
693 }).pipe(Effect.scoped),
694 );
695
696 it.effect("sanitizes HTTP failures and malformed billing responses, keeping the account", () =>
697 Effect.gen(function* () {
698 for (const response of [
699 new Response("private response", { status: 401 }),
700 Response.json({ config: { creditUsagePercent: "private-value" } }),
701 ]) {
702 const { email, usageLimits: limits } = yield* readGrokAccount({
703 HOME: "/definitely/not/a/grok-home",
704 GROK_AUTH:
705 '{"https://accounts.x.ai/sign-in":{"key":"private-token","email":"someone@example.com"}}',
706 }).pipe(
707 Effect.provideService(
708 HttpClient.HttpClient,
709 HttpClient.make((request) =>
710 Effect.succeed(HttpClientResponse.fromWeb(request, response)),
711 ),
712 ),
713 );
714 expect(email).toBe("someone@example.com");
715 expect(limits.windows).toEqual([]);
716 expect(limits.unavailable).toEqual({
717 reason: "probeFailed",
718 message: "Grok could not read usage limits.",
719 });
720 }
721 }),
722 );
723});
724
725it.layer(NodeServices.layer)("readGrokAccount email", (it) => {
726 it.effect("names the account whose limits were read, and nothing for other auth", () =>
727 Effect.gen(function* () {
728 const current = '"https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828"';
729 const cases = [
730 [
731 { GROK_AUTH: `{${current}:{"key":"t","email":" Someone@Example.com "}}` },
732 "Someone@Example.com",
733 ],
734 [
735 {
736 GROK_AUTH: `{${current}:{"key":"t","email":"current@example.com"},"https://accounts.x.ai/sign-in":{"key":"t","email":"legacy@example.com"}}`,
737 },
738 "current@example.com",
739 ],
740 [{ GROK_AUTH: `{${current}:{"key":"t"}}` }, undefined],
741 [
742 {
743 GROK_AUTH: `{${current}:{"key":"t","email":"someone@example.com"}}`,
744 XAI_API_KEY: "api-key",
745 },
746 undefined,
747 ],
748 [
749 {
750 GROK_AUTH: `{${current}:{"key":"t","email":"someone@example.com","auth_mode":"api_key"}}`,
751 },
752 undefined,
753 ],
754 [{ GROK_AUTH: "not-json" }, undefined],
755 ] as const;
756 for (const [environment, expected] of cases) {
757 const { email, usageLimits } = yield* readGrokAccount({
758 HOME: "/definitely/not/a/grok-home",
759 ...environment,
760 }).pipe(
761 Effect.provideService(
762 HttpClient.HttpClient,
763 HttpClient.make((request) =>
764 Effect.succeed(
765 HttpClientResponse.fromWeb(
766 request,
767 Response.json({ config: { creditUsagePercent: 25 } }),
768 ),
769 ),
770 ),
771 ),
772 );
773 expect(email).toBe(expected);
774 if (expected) expect(usageLimits.windows[0]?.usedPercent).toBe(25);
775 }
776 }),
777 );
778});