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

GrokProvider.test.ts

709 lines25.7 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 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.
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("warns instead of reporting ready when no models are discovered", () =>
356 Effect.gen(function* () {
357 const snapshot = yield* Effect.scoped(
358 Effect.gen(function* () {
359 const grokPath = yield* writeFakeGrokCli({
360 modelsOutput: "You are logged in with grok.com.\n",
361 acp: true,
362 });
363 return yield* checkGrokProviderStatus(
364 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
365 { ...process.env, XAI_API_KEY: "", T3_ACP_OMIT_INITIALIZE_MODEL_STATE: "1" },
366 );
367 }),
368 );
369​
370 expect(snapshot.status).toBe("warning");
371 expect(snapshot.message).toContain("did not list any models");
372 expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-build"]);
373 }),
374 );
375​
376 it.effect("treats XAI_API_KEY as authenticated regardless of CLI login state", () =>
377 Effect.gen(function* () {
378 const snapshot = yield* Effect.scoped(
379 Effect.gen(function* () {
380 const grokPath = yield* writeFakeGrokCli({
381 modelsOutput: LOGGED_OUT_MODELS_OUTPUT,
382 acp: false,
383 });
384 return yield* checkGrokProviderStatus(
385 decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
386 { ...process.env, XAI_API_KEY: "xai-test-key" },
387 );
388 }),
389 );
390​
391 expect(snapshot.auth).toEqual({
392 status: "authenticated",
393 type: "api_key",
394 label: "xAI API key",
395 });
396 expect(snapshot.status).toBe("warning");
397 }),
398 );
399});
400​
401describe("Grok usage limits", () => {
402 const checkedAt = "2026-09-16T00:00:00.000Z";
403 const weeklyPeriod = {
404 type: "USAGE_PERIOD_TYPE_WEEKLY",
405 start: "2026-09-11T03:10:30.159171+00:00",
406 end: "2026-09-18T03:10:30.159171+00:00",
407 };
408​
409 it("shows zero usage for complete weekly and monthly periods with no percentage", () => {
410 for (const [currentPeriod, kind, label, resetsAt] of [
411 [weeklyPeriod, "weekly", "Weekly", "2026-09-18T03:10:30.159Z"],
412 [
413 {
414 type: "USAGE_PERIOD_TYPE_MONTHLY",
415 start: "2026-09-01T00:00:00.000Z",
416 end: "2026-10-01T00:00:00.000Z",
417 },
418 "monthly",
419 "Monthly",
420 "2026-10-01T00:00:00.000Z",
421 ],
422 ] as const) {
423 const response = { config: { currentPeriod } };
424 expect
425 .soft(grokUsageResponseToLimits(response, checkedAt).windows)
426 .toEqual([{ id: "subscription", kind, label, usedPercent: 0, resetsAt }]);
427 }
428 });
429​
430 it("keeps incomplete, invalid, unordered, and unknown periods unreported", () => {
431 for (const currentPeriod of [
432 undefined,
433 { ...weeklyPeriod, type: undefined },
434 { ...weeklyPeriod, type: "USAGE_PERIOD_TYPE_DAILY" },
435 { ...weeklyPeriod, start: undefined },
436 { ...weeklyPeriod, end: undefined },
437 { ...weeklyPeriod, start: "invalid" },
438 { ...weeklyPeriod, end: "invalid" },
439 { ...weeklyPeriod, start: weeklyPeriod.end },
440 { ...weeklyPeriod, start: weeklyPeriod.end, end: weeklyPeriod.start },
441 ]) {
442 const response = { config: { currentPeriod } };
443 expect
444 .soft(grokUsageResponseToLimits(response, checkedAt).windows, JSON.stringify(response))
445 .toEqual([]);
446 }
447 });
448​
449 // regression: #17061 show zero-use Grok billing periods
450 it("rejects impossible calendar dates at either period boundary", () => {
451 for (const [start, end] of [
452 ["2026-02-30T00:00:00.000Z", "2026-03-09T00:00:00.000Z"],
453 ["2026-02-23T00:00:00.000Z", "2026-02-30T00:00:00.000Z"],
454 ]) {
455 const response = { config: { currentPeriod: { ...weeklyPeriod, start, end } } };
456 expect
457 .soft(grokUsageResponseToLimits(response, checkedAt).windows, JSON.stringify(response))
458 .toEqual([]);
459 }
460 });
461​
462 it("does not invent allowance or reset dates when billing omits them", () => {
463 for (const response of [{}, { config: {} }, { config: { creditUsagePercent: NaN } }]) {
464 const limits = grokUsageResponseToLimits(response, checkedAt);
465 expect(limits.windows).toEqual([]);
466 expect(limits.unavailable).toBeUndefined();
467 }
468 expect(
469 grokUsageResponseToLimits({ config: { creditUsagePercent: 0 } }, checkedAt).windows,
470 ).toEqual([{ id: "subscription", kind: "other", label: "Subscription", usedPercent: 0 }]);
471 expect(
472 grokUsageResponseToLimits(
473 {
474 config: {
475 creditUsagePercent: 120,
476 currentPeriod: { type: "USAGE_PERIOD_TYPE_MONTHLY", end: "invalid" },
477 },
478 },
479 checkedAt,
480 ).windows,
481 ).toEqual([{ id: "subscription", kind: "monthly", label: "Monthly", usedPercent: 100 }]);
482 });
483});
484​
485it.layer(NodeServices.layer)("readGrokAccount", (it) => {
486 it.effect("reads the configured Grok home and prefers the current login scope to legacy", () =>
487 Effect.gen(function* () {
488 const fs = yield* FileSystem.FileSystem;
489 const directory = yield* fs.makeTempDirectoryScoped();
490 yield* fs.writeFileString(
491 NodePath.join(directory, "auth.json"),
492 '{"https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828":{"key":"session-token","auth_mode":"oauth"},"https://accounts.x.ai/sign-in":{"key":"legacy-token"}}',
493 );
494 const { usageLimits: limits } = yield* readGrokAccount({
495 GROK_HOME: directory,
496 HOME: "/unrelated-home",
497 }).pipe(
498 Effect.provideService(
499 HttpClient.HttpClient,
500 HttpClient.make((request) => {
501 expect(request.method).toBe("GET");
502 expect(request.url).toBe("https://cli-chat-proxy.grok.com/v1/billing?format=credits");
503 expect(request.headers.authorization).toBe("Bearer session-token");
504 return Effect.succeed(
505 HttpClientResponse.fromWeb(
506 request,
507 Response.json({ config: { creditUsagePercent: 37 } }),
508 ),
509 );
510 }),
511 ),
512 );
513 expect(limits.windows[0]?.usedPercent).toBe(37);
514 }).pipe(Effect.scoped),
515 );
516​
517 it.effect(
518 "uses GROK_AUTH without reading stored credentials and accepts the legacy login scope",
519 () =>
520 readGrokAccount({
521 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"legacy-token"}}',
522 }).pipe(
523 Effect.provideService(
524 FileSystem.FileSystem,
525 FileSystem.makeNoop({
526 readFileString: (path) =>
527 path.endsWith("auth.json")
528 ? Effect.die("must not read stored credentials")
529 : Effect.succeed(""),
530 }),
531 ),
532 Effect.provideService(
533 HttpClient.HttpClient,
534 HttpClient.make((request) => {
535 expect(request.headers.authorization).toBe("Bearer legacy-token");
536 return Effect.succeed(
537 HttpClientResponse.fromWeb(
538 request,
539 Response.json({ config: { creditUsagePercent: 12 } }),
540 ),
541 );
542 }),
543 ),
544 Effect.tap(({ usageLimits }) =>
545 Effect.sync(() => expect(usageLimits.windows[0]?.usedPercent).toBe(12)),
546 ),
547 ),
548 );
549​
550 it.effect("does not use unrelated scopes, API keys, or custom auth deployments", () =>
551 Effect.gen(function* () {
552 for (const environment of [
553 {
554 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"stored-account"}}',
555 XAI_API_KEY: "different-api-account",
556 },
557 { GROK_AUTH: '{"https://other.example":{"key":"unrelated-token"}}' },
558 { GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"api-key","auth_mode":"api_key"}}' },
559 { GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":" "}}' },
560 {
561 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"session-token"}}',
562 GROK_OIDC_ISSUER: "https://custom.example",
563 },
564 {
565 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"stored-account"}}',
566 GROK_MODELS_BASE_URL: "https://custom.example/v1",
567 },
568 {
569 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"stored-account"}}',
570 GROK_OAUTH2_PRINCIPAL_TYPE: "Team",
571 },
572 {
573 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"stored-account"}}',
574 GROK_OAUTH2_PRINCIPAL_ID: "team-id",
575 },
576 {
577 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"session-token"}}',
578 GROK_CONFIG: '{"auth_provider_command":"custom-auth"}',
579 },
580 {
581 GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"session-token"}}',
582 GROK_CONFIG_PATH: "/custom-config.toml",
583 },
584 ]) {
585 const { usageLimits: limits } = yield* readGrokAccount({
586 HOME: "/definitely/not/a/grok-home",
587 ...environment,
588 }).pipe(
589 Effect.provideService(
590 HttpClient.HttpClient,
591 HttpClient.make(() => Effect.die("must not request another account's quota")),
592 ),
593 );
594 expect(limits.windows).toEqual([]);
595 expect(limits.unavailable?.reason).toBe("unsupported");
596 }
597 }),
598 );
599​
600 it.effect(
601 "reports a missing login as unsupported and malformed credentials as a sanitized failure",
602 () =>
603 Effect.gen(function* () {
604 const fs = yield* FileSystem.FileSystem;
605 const directory = yield* fs.makeTempDirectoryScoped();
606 const client = HttpClient.make(() => Effect.die("must not request without credentials"));
607 const { usageLimits: missing } = yield* readGrokAccount({ HOME: directory }).pipe(
608 Effect.provideService(HttpClient.HttpClient, client),
609 );
610 expect(missing.unavailable?.reason).toBe("unsupported");
611 for (const contents of [
612 "private-token-invalid-json",
613 '{"https://accounts.x.ai/sign-in":{"key":42}}',
614 ]) {
615 const { usageLimits: malformed } = yield* readGrokAccount({
616 GROK_HOME: directory,
617 GROK_AUTH: contents,
618 }).pipe(Effect.provideService(HttpClient.HttpClient, client));
619 expect(malformed.unavailable).toEqual({
620 reason: "probeFailed",
621 message: "Grok could not read usage limits.",
622 });
623 }
624 }).pipe(Effect.scoped),
625 );
626​
627 it.effect("sanitizes HTTP failures and malformed billing responses, keeping the account", () =>
628 Effect.gen(function* () {
629 for (const response of [
630 new Response("private response", { status: 401 }),
631 Response.json({ config: { creditUsagePercent: "private-value" } }),
632 ]) {
633 const { email, usageLimits: limits } = yield* readGrokAccount({
634 HOME: "/definitely/not/a/grok-home",
635 GROK_AUTH:
636 '{"https://accounts.x.ai/sign-in":{"key":"private-token","email":"someone@example.com"}}',
637 }).pipe(
638 Effect.provideService(
639 HttpClient.HttpClient,
640 HttpClient.make((request) =>
641 Effect.succeed(HttpClientResponse.fromWeb(request, response)),
642 ),
643 ),
644 );
645 expect(email).toBe("someone@example.com");
646 expect(limits.windows).toEqual([]);
647 expect(limits.unavailable).toEqual({
648 reason: "probeFailed",
649 message: "Grok could not read usage limits.",
650 });
651 }
652 }),
653 );
654});
655​
656it.layer(NodeServices.layer)("readGrokAccount email", (it) => {
657 it.effect("names the account whose limits were read, and nothing for other auth", () =>
658 Effect.gen(function* () {
659 const current = '"https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828"';
660 const cases = [
661 [
662 { GROK_AUTH: `{${current}:{"key":"t","email":" Someone@Example.com "}}` },
663 "Someone@Example.com",
664 ],
665 [
666 {
667 GROK_AUTH: `{${current}:{"key":"t","email":"current@example.com"},"https://accounts.x.ai/sign-in":{"key":"t","email":"legacy@example.com"}}`,
668 },
669 "current@example.com",
670 ],
671 [{ GROK_AUTH: `{${current}:{"key":"t"}}` }, undefined],
672 [
673 {
674 GROK_AUTH: `{${current}:{"key":"t","email":"someone@example.com"}}`,
675 XAI_API_KEY: "api-key",
676 },
677 undefined,
678 ],
679 [
680 {
681 GROK_AUTH: `{${current}:{"key":"t","email":"someone@example.com","auth_mode":"api_key"}}`,
682 },
683 undefined,
684 ],
685 [{ GROK_AUTH: "not-json" }, undefined],
686 ] as const;
687 for (const [environment, expected] of cases) {
688 const { email, usageLimits } = yield* readGrokAccount({
689 HOME: "/definitely/not/a/grok-home",
690 ...environment,
691 }).pipe(
692 Effect.provideService(
693 HttpClient.HttpClient,
694 HttpClient.make((request) =>
695 Effect.succeed(
696 HttpClientResponse.fromWeb(
697 request,
698 Response.json({ config: { creditUsagePercent: 25 } }),
699 ),
700 ),
701 ),
702 ),
703 );
704 expect(email).toBe(expected);
705 if (expected) expect(usageLimits.windows[0]?.usedPercent).toBe(25);
706 }
707 }),
708 );
709});