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