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