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

GrokProvider.test.ts

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