mirror of
https://github.com/Nezumi-2711/9router.git
synced 2026-09-22 13:38:31 +00:00
feat(grok-cli): add Grok CLI / Grok Build provider with OAuth device-code flow (#2502)
New OAuth provider routing through cli-chat-proxy.grok.com (OpenAI Responses
API), distinct from xai (api.x.ai) and grok-web (cookie SSO):
- Registry + GrokCliExecutor: Chat Completions -> Responses transform, CLI
fingerprint headers, virtual effort models grok-4.5-{low,medium,high}
- OAuth device-code flow (auth.x.ai) with no-PKCE, shared xAI token refresh
- store=false multi-turn continuity via reasoning encrypted_content
- Quota tracker: on-demand window + prepaid balance on dashboard
- Connection test: 402 spending-limit = soft success (auth OK, out of credits)
- Alias/oauth/provider baselines + unit tests
This commit is contained in:
committed by
decolua
parent
c73c419d09
commit
a11937cdd6
@@ -0,0 +1,288 @@
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import {
|
||||
GrokCliExecutor,
|
||||
countGrokCliUserTurns,
|
||||
resolveGrokCliTurnIdx,
|
||||
_resetGrokCliTurnStore,
|
||||
} from "../../open-sse/executors/grok-cli.js";
|
||||
import { getExecutor, hasSpecializedExecutor } from "../../open-sse/executors/index.js";
|
||||
import { PROVIDERS, PROVIDER_OAUTH, PROVIDER_MODELS } from "../../open-sse/providers/index.js";
|
||||
import { getModelUpstreamId } from "../../open-sse/config/providerModels.js";
|
||||
import { resolveProviderAlias } from "../../open-sse/services/model.js";
|
||||
import { OAUTH_PROVIDERS } from "../../src/shared/constants/providers.js";
|
||||
|
||||
describe("grok-cli registry", () => {
|
||||
it("registers transport + oauth + models", () => {
|
||||
const cfg = PROVIDERS["grok-cli"];
|
||||
expect(cfg).toBeTruthy();
|
||||
expect(cfg.baseUrl).toBe("https://cli-chat-proxy.grok.com/v1/responses");
|
||||
expect(cfg.format).toBe("openai-responses");
|
||||
expect(cfg.forceStream).toBe(true);
|
||||
expect(cfg.tokenAuth).toBe("xai-grok-cli");
|
||||
|
||||
const oauth = PROVIDER_OAUTH["grok-cli"];
|
||||
expect(oauth.clientId).toBe("b1a00492-073a-47ea-816f-4c329264a828");
|
||||
expect(oauth.deviceCodeUrl).toContain("auth.x.ai");
|
||||
expect(oauth.scope).toContain("grok-cli:access");
|
||||
expect(oauth.scope).toContain("conversations:write");
|
||||
expect(oauth.referrer).toBe("grok-build");
|
||||
|
||||
expect(PROVIDER_MODELS.gcli?.some((m) => m.id === "grok-4.5")).toBe(true);
|
||||
});
|
||||
|
||||
it("is listed as oauth provider for dashboard", () => {
|
||||
expect(OAUTH_PROVIDERS["grok-cli"]).toBeTruthy();
|
||||
expect(OAUTH_PROVIDERS["grok-cli"].name).toMatch(/Grok CLI/i);
|
||||
});
|
||||
|
||||
it("resolves aliases to provider id", () => {
|
||||
expect(resolveProviderAlias("gcli")).toBe("grok-cli");
|
||||
expect(resolveProviderAlias("gb")).toBe("grok-cli");
|
||||
expect(resolveProviderAlias("grok-build")).toBe("grok-cli");
|
||||
expect(resolveProviderAlias("grok-cli")).toBe("grok-cli");
|
||||
});
|
||||
|
||||
it("maps effort virtual models to upstream grok-4.5", () => {
|
||||
expect(getModelUpstreamId("gcli", "grok-4.5-high")).toBe("grok-4.5");
|
||||
expect(getModelUpstreamId("gcli", "grok-4.5-medium")).toBe("grok-4.5");
|
||||
expect(getModelUpstreamId("gcli", "grok-4.5-low")).toBe("grok-4.5");
|
||||
expect(getModelUpstreamId("gcli", "grok-4.5")).toBe("grok-4.5");
|
||||
});
|
||||
});
|
||||
|
||||
describe("GrokCliExecutor", () => {
|
||||
let executor;
|
||||
|
||||
beforeEach(() => {
|
||||
_resetGrokCliTurnStore();
|
||||
executor = new GrokCliExecutor();
|
||||
});
|
||||
|
||||
it("is registered on executor map (id + aliases)", () => {
|
||||
expect(hasSpecializedExecutor("grok-cli")).toBe(true);
|
||||
expect(getExecutor("grok-cli")).toBeInstanceOf(GrokCliExecutor);
|
||||
expect(getExecutor("gcli")).toBeInstanceOf(GrokCliExecutor);
|
||||
expect(getExecutor("gb")).toBeInstanceOf(GrokCliExecutor);
|
||||
});
|
||||
|
||||
it("buildUrl points at cli-chat-proxy responses", () => {
|
||||
expect(executor.buildUrl()).toBe("https://cli-chat-proxy.grok.com/v1/responses");
|
||||
});
|
||||
|
||||
it("buildHeaders sets CLI fingerprint + session headers", () => {
|
||||
executor._currentSessionId = "sess-abc";
|
||||
executor._currentReqId = "req-xyz";
|
||||
executor._agentId = "agent-1";
|
||||
executor._currentModel = "grok-4.5";
|
||||
executor._currentTurnIdx = 3;
|
||||
|
||||
const headers = executor.buildHeaders(
|
||||
{
|
||||
accessToken: "tok_test",
|
||||
providerSpecificData: { email: "u@example.com", userId: "uid-1" },
|
||||
},
|
||||
true
|
||||
);
|
||||
|
||||
expect(headers.Authorization).toBe("Bearer tok_test");
|
||||
expect(headers.Accept).toBe("text/event-stream");
|
||||
expect(headers["x-xai-token-auth"]).toBe("xai-grok-cli");
|
||||
expect(headers["x-grok-client-identifier"]).toBe("grok-pager");
|
||||
expect(headers["x-grok-client-version"]).toBe("0.2.93");
|
||||
expect(headers["x-grok-session-id"]).toBe("sess-abc");
|
||||
expect(headers["x-grok-conv-id"]).toBe("sess-abc");
|
||||
expect(headers["x-grok-req-id"]).toBe("req-xyz");
|
||||
expect(headers["x-grok-turn-idx"]).toBe("3");
|
||||
expect(headers["x-grok-agent-id"]).toBe("agent-1");
|
||||
expect(headers["x-grok-model-override"]).toBe("grok-4.5");
|
||||
expect(headers["x-compaction-at"]).toBe("400000");
|
||||
expect(headers["x-email"]).toBe("u@example.com");
|
||||
expect(headers["x-userid"]).toBe("uid-1");
|
||||
expect(headers["x-authenticateresponse"]).toBe("authenticate-response");
|
||||
});
|
||||
|
||||
it("buildHeaders falls back to top-level email/userId (OAuth mapTokens shape)", () => {
|
||||
executor._currentSessionId = "sess-top";
|
||||
executor._currentReqId = "req-top";
|
||||
|
||||
const headers = executor.buildHeaders(
|
||||
{
|
||||
accessToken: "tok_test",
|
||||
email: "top@example.com",
|
||||
// userId only top-level; psd has neither email nor userId
|
||||
providerSpecificData: { authMethod: "device_code" },
|
||||
},
|
||||
true
|
||||
);
|
||||
|
||||
expect(headers["x-email"]).toBe("top@example.com");
|
||||
expect(headers["x-userid"]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("transformRequest normalizes Responses body like official CLI", () => {
|
||||
const body = {
|
||||
model: "grok-4.5-high",
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
stream: false,
|
||||
tools: [
|
||||
{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "run_terminal_command",
|
||||
description: "Run bash",
|
||||
parameters: { type: "object", properties: { command: { type: "string" } } },
|
||||
},
|
||||
},
|
||||
{ type: "web_search" },
|
||||
{ type: "x_search" },
|
||||
],
|
||||
temperature: 0.7,
|
||||
max_tokens: 100,
|
||||
user: "cursor-user",
|
||||
};
|
||||
|
||||
// Simulate translator already converting messages→input; also test messages fallback
|
||||
const out = executor.transformRequest("grok-4.5-high", { ...body }, true, {
|
||||
connectionId: "conn-1",
|
||||
});
|
||||
|
||||
expect(out.model).toBe("grok-4.5");
|
||||
expect(out.stream).toBe(true);
|
||||
expect(out.store).toBe(false);
|
||||
expect(out.include).toContain("reasoning.encrypted_content");
|
||||
expect(out.reasoning).toEqual({ effort: "high", summary: "concise" });
|
||||
expect(out.messages).toBeUndefined();
|
||||
expect(out.max_tokens).toBeUndefined();
|
||||
expect(out.user).toBeUndefined();
|
||||
expect(Array.isArray(out.input)).toBe(true);
|
||||
expect(out.input.length).toBeGreaterThan(0);
|
||||
expect(executor._currentTurnIdx).toBe(1);
|
||||
|
||||
// tools flattened + hosted tools kept
|
||||
expect(out.tools).toHaveLength(3);
|
||||
expect(out.tools[0]).toMatchObject({
|
||||
type: "function",
|
||||
name: "run_terminal_command",
|
||||
});
|
||||
expect(out.tools[0].parameters).toBeTruthy();
|
||||
expect(out.tools[0].function).toBeUndefined();
|
||||
expect(out.tools[1]).toEqual({ type: "web_search" });
|
||||
expect(out.tools[2]).toEqual({ type: "x_search" });
|
||||
});
|
||||
|
||||
it("transformRequest keeps role:system (HAR parity) and strips server ids", () => {
|
||||
const body = {
|
||||
model: "grok-4.5",
|
||||
input: [
|
||||
{ type: "message", role: "system", content: "You are Grok" },
|
||||
{ type: "message", role: "user", content: "hi", id: "msg_server_id" },
|
||||
{ type: "item_reference", id: "rs_abc" },
|
||||
"rs_should_drop",
|
||||
],
|
||||
reasoning_effort: "medium",
|
||||
};
|
||||
|
||||
const out = executor.transformRequest("grok-4.5", body, true, { connectionId: "c1" });
|
||||
expect(out.input).toHaveLength(2);
|
||||
// Official CLI sends system, not developer (Codex converts; Grok does not)
|
||||
expect(out.input[0].role).toBe("system");
|
||||
expect(out.input[1].id).toBeUndefined();
|
||||
expect(out.reasoning.effort).toBe("medium");
|
||||
});
|
||||
|
||||
it("increments x-grok-turn-idx from user-message count and stays monotonic", () => {
|
||||
const creds = {
|
||||
connectionId: "turn-conn",
|
||||
rawHeaders: { "x-session-id": "stable-session-xyz" },
|
||||
};
|
||||
|
||||
// Turn 1: one user message
|
||||
executor.transformRequest(
|
||||
"grok-4.5",
|
||||
{
|
||||
model: "grok-4.5",
|
||||
input: [
|
||||
{ type: "message", role: "system", content: "sys" },
|
||||
{ type: "message", role: "user", content: "hi" },
|
||||
],
|
||||
},
|
||||
true,
|
||||
creds
|
||||
);
|
||||
expect(executor._currentSessionId).toBeTruthy();
|
||||
expect(executor._currentTurnIdx).toBe(1);
|
||||
let headers = executor.buildHeaders({ accessToken: "t" }, true);
|
||||
expect(headers["x-grok-turn-idx"]).toBe("1");
|
||||
expect(headers["x-grok-session-id"]).toBe(executor._currentSessionId);
|
||||
expect(headers["x-grok-conv-id"]).toBe(executor._currentSessionId);
|
||||
|
||||
const sessionId = executor._currentSessionId;
|
||||
|
||||
// Turn 2: full history with two user messages
|
||||
executor.transformRequest(
|
||||
"grok-4.5",
|
||||
{
|
||||
model: "grok-4.5",
|
||||
input: [
|
||||
{ type: "message", role: "system", content: "sys" },
|
||||
{ type: "message", role: "user", content: "hi" },
|
||||
{ type: "message", role: "assistant", content: "hello" },
|
||||
{ type: "message", role: "user", content: "next" },
|
||||
],
|
||||
},
|
||||
true,
|
||||
creds
|
||||
);
|
||||
expect(executor._currentSessionId).toBe(sessionId);
|
||||
expect(executor._currentTurnIdx).toBe(2);
|
||||
headers = executor.buildHeaders({ accessToken: "t" }, true);
|
||||
expect(headers["x-grok-turn-idx"]).toBe("2");
|
||||
|
||||
// Same session, payload that only has 1 user msg (delta-style client) must not go backwards
|
||||
executor.transformRequest(
|
||||
"grok-4.5",
|
||||
{
|
||||
model: "grok-4.5",
|
||||
input: [{ type: "message", role: "user", content: "only latest" }],
|
||||
},
|
||||
true,
|
||||
creds
|
||||
);
|
||||
expect(executor._currentTurnIdx).toBe(2);
|
||||
});
|
||||
|
||||
it("countGrokCliUserTurns / resolveGrokCliTurnIdx helpers", () => {
|
||||
expect(countGrokCliUserTurns(null)).toBe(1);
|
||||
expect(
|
||||
countGrokCliUserTurns([
|
||||
{ type: "message", role: "system", content: "s" },
|
||||
{ type: "message", role: "user", content: "a" },
|
||||
{ type: "message", role: "assistant", content: "b" },
|
||||
{ type: "message", role: "user", content: "c" },
|
||||
])
|
||||
).toBe(2);
|
||||
|
||||
expect(resolveGrokCliTurnIdx("s1", [{ role: "user", type: "message", content: "a" }])).toBe(1);
|
||||
expect(
|
||||
resolveGrokCliTurnIdx("s1", [
|
||||
{ role: "user", type: "message", content: "a" },
|
||||
{ role: "user", type: "message", content: "b" },
|
||||
])
|
||||
).toBe(2);
|
||||
// monotonic
|
||||
expect(resolveGrokCliTurnIdx("s1", [{ role: "user", type: "message", content: "a" }])).toBe(2);
|
||||
});
|
||||
|
||||
it("parseError surfaces 402 spending-limit", () => {
|
||||
const err = executor.parseError(
|
||||
{ status: 402 },
|
||||
JSON.stringify({
|
||||
code: "personal-team-blocked:spending-limit",
|
||||
error: "You have run out of credits",
|
||||
})
|
||||
);
|
||||
expect(err.status).toBe(402);
|
||||
expect(err.code).toBe("personal-team-blocked:spending-limit");
|
||||
expect(err.message).toMatch(/credits/i);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Grok CLI connection-test semantics: 402 spending-limit is soft success (auth OK).
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { classifyOAuthProbeResult } from "../../src/app/api/providers/[id]/test/testUtils.js";
|
||||
import { PROVIDERS } from "../../open-sse/providers/index.js";
|
||||
|
||||
const GROK_CLI_PROBE = {
|
||||
url: PROVIDERS["grok-cli"]?.userUrl || "https://cli-chat-proxy.grok.com/v1/user",
|
||||
method: "GET",
|
||||
acceptStatuses: [402],
|
||||
softFailMessage: {
|
||||
402: "Connected, but Grok Build credits are exhausted (spending limit). Add credits or upgrade SuperGrok.",
|
||||
},
|
||||
};
|
||||
|
||||
describe("classifyOAuthProbeResult (grok-cli)", () => {
|
||||
it("treats 200 as hard success", () => {
|
||||
const r = classifyOAuthProbeResult({ ok: true, status: 200 }, GROK_CLI_PROBE, "");
|
||||
expect(r).toEqual({ valid: true, error: null, soft: false });
|
||||
});
|
||||
|
||||
it("treats 402 spending-limit as soft success (connected, out of credits)", () => {
|
||||
const body = JSON.stringify({
|
||||
code: "personal-team-blocked:spending-limit",
|
||||
error: "You have run out of credits",
|
||||
});
|
||||
const r = classifyOAuthProbeResult({ ok: false, status: 402 }, GROK_CLI_PROBE, body);
|
||||
expect(r.valid).toBe(true);
|
||||
expect(r.soft).toBe(true);
|
||||
expect(r.error).toMatch(/credits|SuperGrok|spending/i);
|
||||
});
|
||||
|
||||
it("treats 401 as hard auth failure", () => {
|
||||
const r = classifyOAuthProbeResult({ ok: false, status: 401 }, GROK_CLI_PROBE, "unauthorized");
|
||||
expect(r).toEqual({ valid: false, error: "Token invalid or revoked", soft: false });
|
||||
});
|
||||
|
||||
it("treats 403 as access denied", () => {
|
||||
const r = classifyOAuthProbeResult({ ok: false, status: 403 }, GROK_CLI_PROBE, "");
|
||||
expect(r.valid).toBe(false);
|
||||
expect(r.error).toMatch(/Access denied/i);
|
||||
});
|
||||
|
||||
it("Codex-style acceptStatuses 400 stays silent success (no soft warning)", () => {
|
||||
const codex = { acceptStatuses: [400] };
|
||||
const r = classifyOAuthProbeResult({ ok: false, status: 400 }, codex, "bad request");
|
||||
expect(r).toEqual({ valid: true, error: null, soft: false });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("../../open-sse/utils/proxyFetch.js", () => ({
|
||||
proxyAwareFetch: vi.fn(),
|
||||
}));
|
||||
|
||||
import { proxyAwareFetch } from "../../open-sse/utils/proxyFetch.js";
|
||||
import { getUsageForProvider } from "../../open-sse/services/usage.js";
|
||||
import { parseGrokCliBilling } from "../../open-sse/services/usage/grok-cli.js";
|
||||
import { USAGE_SUPPORTED_PROVIDERS } from "../../src/shared/constants/providers.js";
|
||||
import { PROVIDERS } from "../../open-sse/providers/index.js";
|
||||
import { parseQuotaData } from "../../src/app/(dashboard)/dashboard/usage/components/ProviderLimits/utils.js";
|
||||
|
||||
function jsonResponse(body, status = 200) {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
const EXHAUSTED_BILLING = {
|
||||
config: {
|
||||
currentPeriod: {
|
||||
type: "USAGE_PERIOD_TYPE_WEEKLY",
|
||||
start: "2026-07-08T00:00:00+00:00",
|
||||
end: "2026-07-15T00:00:00+00:00",
|
||||
},
|
||||
onDemandCap: { val: 0 },
|
||||
onDemandUsed: { val: 0 },
|
||||
isUnifiedBillingUser: true,
|
||||
prepaidBalance: { val: 0 },
|
||||
topUpMethod: "TOP_UP_METHOD_SAVED_PAYMENT_METHOD",
|
||||
billingPeriodStart: "2026-07-08T00:00:00+00:00",
|
||||
billingPeriodEnd: "2026-07-15T00:00:00+00:00",
|
||||
},
|
||||
};
|
||||
|
||||
const ACTIVE_BILLING = {
|
||||
config: {
|
||||
currentPeriod: {
|
||||
type: "USAGE_PERIOD_TYPE_WEEKLY",
|
||||
start: "2026-07-08T00:00:00+00:00",
|
||||
end: "2026-07-15T00:00:00+00:00",
|
||||
},
|
||||
onDemandCap: { val: 100 },
|
||||
onDemandUsed: { val: 35 },
|
||||
isUnifiedBillingUser: true,
|
||||
prepaidBalance: { val: 12.5 },
|
||||
billingPeriodStart: "2026-07-08T00:00:00+00:00",
|
||||
billingPeriodEnd: "2026-07-15T00:00:00+00:00",
|
||||
},
|
||||
};
|
||||
|
||||
const USER_PROFILE = {
|
||||
userId: "d84768dd-224d-4052-ba49-0d336fa9160c",
|
||||
email: "user@example.com",
|
||||
hasGrokCodeAccess: true,
|
||||
subscriptionTier: null,
|
||||
};
|
||||
|
||||
describe("grok-cli registry usage flag", () => {
|
||||
it("exposes transport.usage urls", () => {
|
||||
const cfg = PROVIDERS["grok-cli"];
|
||||
expect(cfg.usage?.url).toContain("/v1/billing");
|
||||
expect(cfg.usage?.userUrl).toContain("/v1/user");
|
||||
});
|
||||
|
||||
it("is listed in USAGE_SUPPORTED_PROVIDERS", () => {
|
||||
expect(USAGE_SUPPORTED_PROVIDERS).toContain("grok-cli");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseGrokCliBilling", () => {
|
||||
it("maps on-demand cap/used + prepaid balance", () => {
|
||||
const parsed = parseGrokCliBilling(ACTIVE_BILLING, USER_PROFILE);
|
||||
expect(parsed.plan).toBe("Grok Code");
|
||||
expect(parsed.quotas["On-demand"]).toMatchObject({
|
||||
used: 35,
|
||||
total: 100,
|
||||
remainingPercentage: 65,
|
||||
});
|
||||
// Prepaid is remaining-balance style: 0 used of current pot
|
||||
expect(parsed.quotas.Prepaid).toMatchObject({
|
||||
used: 0,
|
||||
total: 12.5,
|
||||
remainingPercentage: 100,
|
||||
});
|
||||
expect(parsed.exhausted).toBe(false);
|
||||
});
|
||||
|
||||
it("marks depleted free/promo account as exhausted", () => {
|
||||
const parsed = parseGrokCliBilling(EXHAUSTED_BILLING, USER_PROFILE);
|
||||
expect(parsed.quotas["On-demand"].remainingPercentage).toBe(0);
|
||||
expect(parsed.exhausted).toBe(true);
|
||||
});
|
||||
|
||||
it("uses subscriptionTier for plan when present", () => {
|
||||
const parsed = parseGrokCliBilling(ACTIVE_BILLING, {
|
||||
...USER_PROFILE,
|
||||
subscriptionTier: "super_grok",
|
||||
});
|
||||
expect(parsed.plan).toBe("Super Grok");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getUsageForProvider(grok-cli)", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("returns normalized quotas from billing + user endpoints", async () => {
|
||||
proxyAwareFetch
|
||||
.mockResolvedValueOnce(jsonResponse(ACTIVE_BILLING))
|
||||
.mockResolvedValueOnce(jsonResponse(USER_PROFILE));
|
||||
|
||||
const usage = await getUsageForProvider({
|
||||
provider: "grok-cli",
|
||||
accessToken: "test-token",
|
||||
providerSpecificData: {
|
||||
email: "user@example.com",
|
||||
userId: "d84768dd-224d-4052-ba49-0d336fa9160c",
|
||||
},
|
||||
});
|
||||
|
||||
expect(usage.message).toBeUndefined();
|
||||
expect(usage.plan).toBe("Grok Code");
|
||||
expect(usage.quotas["On-demand"]).toMatchObject({
|
||||
used: 35,
|
||||
total: 100,
|
||||
remainingPercentage: 65,
|
||||
});
|
||||
expect(usage.quotas.Prepaid).toMatchObject({
|
||||
used: 0,
|
||||
total: 12.5,
|
||||
remainingPercentage: 100,
|
||||
});
|
||||
|
||||
// Official CLI fingerprint headers
|
||||
const billingCall = proxyAwareFetch.mock.calls[0];
|
||||
expect(billingCall[0]).toContain("/v1/billing");
|
||||
expect(billingCall[1].headers.Authorization).toBe("Bearer test-token");
|
||||
expect(billingCall[1].headers["x-xai-token-auth"]).toBe("xai-grok-cli");
|
||||
expect(billingCall[1].headers["x-userid"]).toBe(
|
||||
"d84768dd-224d-4052-ba49-0d336fa9160c",
|
||||
);
|
||||
});
|
||||
|
||||
it("surfaces auth-expired message on 401", async () => {
|
||||
proxyAwareFetch
|
||||
.mockResolvedValueOnce(jsonResponse({ error: "unauthorized" }, 401))
|
||||
.mockResolvedValueOnce(jsonResponse(USER_PROFILE));
|
||||
|
||||
const usage = await getUsageForProvider({
|
||||
provider: "grok-cli",
|
||||
accessToken: "expired",
|
||||
});
|
||||
|
||||
expect(usage.message).toMatch(/expired|re-authorize/i);
|
||||
});
|
||||
|
||||
it("returns depleted on-demand bar without blocking message when cap is zero", async () => {
|
||||
proxyAwareFetch
|
||||
.mockResolvedValueOnce(jsonResponse(EXHAUSTED_BILLING))
|
||||
.mockResolvedValueOnce(jsonResponse(USER_PROFILE));
|
||||
|
||||
const usage = await getUsageForProvider({
|
||||
provider: "grok-cli",
|
||||
accessToken: "test-token",
|
||||
});
|
||||
|
||||
// Dashboard hides QuotaTable when `message` is set — keep message empty
|
||||
// so the 0% bar still renders for exhausted free/promo accounts.
|
||||
expect(usage.message).toBeUndefined();
|
||||
expect(usage.quotas["On-demand"].remainingPercentage).toBe(0);
|
||||
expect(usage.quotas["On-demand"].total).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseQuotaData(grok-cli)", () => {
|
||||
it("forwards remainingPercentage for dashboard bars", () => {
|
||||
const rows = parseQuotaData("grok-cli", {
|
||||
plan: "Grok Code",
|
||||
quotas: {
|
||||
"On-demand": {
|
||||
used: 35,
|
||||
total: 100,
|
||||
remaining: 65,
|
||||
remainingPercentage: 65,
|
||||
resetAt: "2026-07-15T00:00:00.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toMatchObject({
|
||||
name: "On-demand",
|
||||
used: 35,
|
||||
total: 100,
|
||||
remainingPercentage: 65,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* Multi-turn continuity for store=false Responses backends (Grok CLI / Codex).
|
||||
* Prior-turn reasoning (+ encrypted_content) must survive Chat Completions ↔ Responses.
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
openaiToOpenAIResponsesRequest,
|
||||
openaiResponsesToOpenAIRequest,
|
||||
} from "../../open-sse/translator/request/openai-responses.js";
|
||||
import { GrokCliExecutor, _resetGrokCliTurnStore } from "../../open-sse/executors/grok-cli.js";
|
||||
import { translateRequest } from "../../open-sse/translator/index.js";
|
||||
|
||||
describe("openai ↔ responses multi-turn reasoning", () => {
|
||||
it("openai→responses re-emits reasoning item with summary + encrypted_content", () => {
|
||||
const body = {
|
||||
model: "grok-4.5",
|
||||
messages: [
|
||||
{ role: "user", content: "hi" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: "hello",
|
||||
reasoning_content: "thinking hard about greeting",
|
||||
encrypted_content: "enc_blob_turn1",
|
||||
},
|
||||
{ role: "user", content: "next" },
|
||||
],
|
||||
};
|
||||
|
||||
const out = openaiToOpenAIResponsesRequest("grok-4.5", body, true, null);
|
||||
expect(out.store).toBe(false);
|
||||
|
||||
const reasoning = out.input.filter((i) => i.type === "reasoning");
|
||||
expect(reasoning).toHaveLength(1);
|
||||
expect(reasoning[0].encrypted_content).toBe("enc_blob_turn1");
|
||||
expect(reasoning[0].summary?.[0]?.text).toMatch(/thinking hard/);
|
||||
|
||||
// Order: user → reasoning → assistant → user
|
||||
const types = out.input.map((i) => i.type || i.role);
|
||||
expect(types).toEqual(["message", "reasoning", "message", "message"]);
|
||||
expect(out.input[0].role).toBe("user");
|
||||
expect(out.input[2].role).toBe("assistant");
|
||||
expect(out.input[3].role).toBe("user");
|
||||
});
|
||||
|
||||
it("accepts reasoning_encrypted_content alias on assistant messages", () => {
|
||||
const out = openaiToOpenAIResponsesRequest(
|
||||
"m",
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: "assistant",
|
||||
content: "ok",
|
||||
reasoning_encrypted_content: "alt_enc",
|
||||
},
|
||||
],
|
||||
},
|
||||
true,
|
||||
null
|
||||
);
|
||||
expect(out.input.find((i) => i.type === "reasoning")?.encrypted_content).toBe("alt_enc");
|
||||
});
|
||||
|
||||
it("responses→openai attaches reasoning_content + encrypted_content to assistant", () => {
|
||||
const body = {
|
||||
model: "grok-4.5",
|
||||
input: [
|
||||
{ type: "message", role: "user", content: [{ type: "input_text", text: "hi" }] },
|
||||
{
|
||||
type: "reasoning",
|
||||
summary: [{ type: "summary_text", text: "plan A" }],
|
||||
encrypted_content: "enc_xyz",
|
||||
},
|
||||
{
|
||||
type: "message",
|
||||
role: "assistant",
|
||||
content: [{ type: "output_text", text: "hello" }],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const out = openaiResponsesToOpenAIRequest("grok-4.5", body, true, null);
|
||||
const assistant = out.messages.find((m) => m.role === "assistant");
|
||||
expect(assistant).toBeTruthy();
|
||||
expect(assistant.reasoning_content).toBe("plan A");
|
||||
expect(assistant.encrypted_content).toBe("enc_xyz");
|
||||
});
|
||||
|
||||
it("round-trips encrypted_content through openai → responses → openai", () => {
|
||||
const original = {
|
||||
model: "grok-4.5",
|
||||
messages: [
|
||||
{ role: "user", content: "q1" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: "a1",
|
||||
reasoning_content: "r1",
|
||||
encrypted_content: "ENC_KEEP_ME",
|
||||
},
|
||||
{ role: "user", content: "q2" },
|
||||
],
|
||||
};
|
||||
|
||||
const responses = openaiToOpenAIResponsesRequest("grok-4.5", structuredClone(original), true, null);
|
||||
const back = openaiResponsesToOpenAIRequest("grok-4.5", responses, true, null);
|
||||
const again = openaiToOpenAIResponsesRequest("grok-4.5", back, true, null);
|
||||
|
||||
const enc = again.input.find((i) => i.type === "reasoning")?.encrypted_content;
|
||||
expect(enc).toBe("ENC_KEEP_ME");
|
||||
});
|
||||
|
||||
it("translateRequest openai→openai-responses preserves encrypted blob", () => {
|
||||
const body = {
|
||||
model: "grok-4.5",
|
||||
messages: [
|
||||
{ role: "user", content: "hi" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: "yo",
|
||||
reasoning_content: "why",
|
||||
encrypted_content: "blob_via_registry",
|
||||
},
|
||||
{ role: "user", content: "go" },
|
||||
],
|
||||
};
|
||||
const out = translateRequest(
|
||||
"openai",
|
||||
"openai-responses",
|
||||
"grok-4.5",
|
||||
structuredClone(body),
|
||||
true,
|
||||
{},
|
||||
"grok-cli"
|
||||
);
|
||||
expect(out.input.some((i) => i.type === "reasoning" && i.encrypted_content === "blob_via_registry")).toBe(
|
||||
true
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GrokCliExecutor multi-turn input", () => {
|
||||
it("keeps reasoning items (incl. encrypted_content) and strips only server message ids", () => {
|
||||
_resetGrokCliTurnStore();
|
||||
const executor = new GrokCliExecutor();
|
||||
const body = {
|
||||
model: "grok-4.5",
|
||||
input: [
|
||||
{ type: "message", role: "system", content: "You are Grok" },
|
||||
{ type: "message", role: "user", content: "hi", id: "msg_server_prev" },
|
||||
{
|
||||
type: "reasoning",
|
||||
id: "rs_server_prev",
|
||||
summary: [{ type: "summary_text", text: "prior plan" }],
|
||||
encrypted_content: "enc_from_cli",
|
||||
},
|
||||
{ type: "message", role: "assistant", content: "hello", id: "msg_server_asst" },
|
||||
{ type: "message", role: "user", content: "again" },
|
||||
],
|
||||
include: ["reasoning.encrypted_content"],
|
||||
};
|
||||
|
||||
const out = executor.transformRequest("grok-4.5", structuredClone(body), true, {
|
||||
connectionId: "mt-1",
|
||||
});
|
||||
|
||||
const reasoning = out.input.filter((i) => i.type === "reasoning");
|
||||
expect(reasoning).toHaveLength(1);
|
||||
expect(reasoning[0].encrypted_content).toBe("enc_from_cli");
|
||||
expect(reasoning[0].summary?.[0]?.text).toBe("prior plan");
|
||||
// server id stripped from reasoning item, content kept
|
||||
expect(reasoning[0].id).toBeUndefined();
|
||||
|
||||
// system preserved (not developer)
|
||||
expect(out.input[0].role).toBe("system");
|
||||
// message server ids stripped
|
||||
for (const item of out.input) {
|
||||
if (item.type === "message") expect(item.id).toBeUndefined();
|
||||
}
|
||||
expect(out.include).toContain("reasoning.encrypted_content");
|
||||
expect(out.store).toBe(false);
|
||||
expect(executor._currentTurnIdx).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -15,7 +15,7 @@ const load = () => import("../../open-sse/services/usage.js");
|
||||
const SUPPORTED = [
|
||||
"github", "gemini-cli", "antigravity", "claude", "codex", "kiro",
|
||||
"qoder", "qwen", "iflow", "ollama", "glm", "glm-cn",
|
||||
"minimax", "minimax-cn", "vercel-ai-gateway",
|
||||
"minimax", "minimax-cn", "vercel-ai-gateway", "grok-cli",
|
||||
];
|
||||
|
||||
describe("usage dispatch", () => {
|
||||
|
||||
Reference in New Issue
Block a user