mirror of
https://github.com/Nezumi-2711/9router.git
synced 2026-09-22 13:38:31 +00:00
Merge branch 'master' into dev
# Conflicts: # src/app/(dashboard)/dashboard/cli-tools/[toolId]/ToolDetailClient.js # src/app/(dashboard)/dashboard/cli-tools/components/index.js # src/app/(dashboard)/dashboard/providers/[id]/AddApiKeyModal.js # src/app/api/cli-tools/all-statuses/route.js # src/app/api/settings/route.js # src/app/api/v1/models/route.js # src/shared/constants/cliTools.js
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
// #2591 — Alibaba Intl (alicode-intl) must use the OpenAI-compatible-mode
|
||||
// DashScope endpoint so standard DashScope API keys work. The previous
|
||||
// coding-intl host only accepted Alibaba Coding Plan keys and rejected
|
||||
// ordinary DashScope keys with "Invalid API key".
|
||||
import { describe, it, expect } from "vitest";
|
||||
import alicodeIntl from "../../open-sse/providers/registry/alicode-intl.js";
|
||||
|
||||
describe("alicode-intl endpoint (issue #2591)", () => {
|
||||
it("routes to the compatible-mode DashScope endpoint", () => {
|
||||
expect(alicodeIntl.id).toBe("alicode-intl");
|
||||
expect(alicodeIntl.transport.baseUrl).toBe(
|
||||
"https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions"
|
||||
);
|
||||
});
|
||||
|
||||
it("does not use the coding-intl host that rejects standard keys", () => {
|
||||
expect(alicodeIntl.transport.baseUrl).not.toContain("coding-intl.dashscope.aliyuncs.com");
|
||||
});
|
||||
|
||||
it("keeps the chat/completions path and preserveCacheControl quirk", () => {
|
||||
expect(alicodeIntl.transport.baseUrl).toContain("/v1/chat/completions");
|
||||
expect(alicodeIntl.transport.quirks.preserveCacheControl).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
// Guards the bulk-add API-key naming bug: auto-generated "Key N" names used to be
|
||||
// derived from the paste-line index, blind to existing connection names. The
|
||||
// backend upserts apikey connections by name (connectionsRepo), so a colliding
|
||||
// generated name OVERWROTE an existing key instead of adding a new one.
|
||||
// Fix: planBulkAdd gap-fills the smallest free "<base> <n>" against existing
|
||||
// names (and earlier entries in the same batch) so a name is never reused.
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { planBulkAdd } from "../../src/shared/utils/bulkAdd.js";
|
||||
|
||||
describe("planBulkAdd: auto-named gap-fill (the replace bug)", () => {
|
||||
it("uses Key 1..N by paste index when nothing exists", () => {
|
||||
const out = planBulkAdd(["sk-a", "sk-b", "sk-c"], []);
|
||||
expect(out.map(o => o.name)).toEqual(["Key 1", "Key 2", "Key 3"]);
|
||||
expect(out.every(o => o.skipped === false)).toBe(true);
|
||||
});
|
||||
|
||||
it("gap-fills around existing names — never reuses an existing name", () => {
|
||||
// Key 3 and Key 5 already exist; user adds 4 keys.
|
||||
// Free slots: 1, 2, 4, 6 -> assign those, never 3 or 5.
|
||||
const out = planBulkAdd(["sk-a", "sk-b", "sk-c", "sk-d"], ["Key 3", "Key 5"]);
|
||||
expect(out.map(o => o.name)).toEqual(["Key 1", "Key 2", "Key 4", "Key 6"]);
|
||||
});
|
||||
|
||||
it("continues past the highest existing index when low slots are taken", () => {
|
||||
const out = planBulkAdd(["sk-a", "sk-b"], ["Key 1", "Key 2"]);
|
||||
expect(out.map(o => o.name)).toEqual(["Key 3", "Key 4"]);
|
||||
});
|
||||
|
||||
it("skips blank/whitespace-only lines but keeps indexing contiguous", () => {
|
||||
const out = planBulkAdd(["sk-a", " ", "", "sk-b"], []);
|
||||
expect(out.map(o => o.name)).toEqual(["Key 1", "Key 2"]);
|
||||
expect(out.map(o => o.apiKey)).toEqual(["sk-a", "sk-b"]);
|
||||
});
|
||||
|
||||
it("within-batch names are unique even for the same free slot", () => {
|
||||
const out = planBulkAdd(["sk-a", "sk-b", "sk-c"], ["Key 1"]);
|
||||
// Key 1 taken; batch gets 2, 3, 4 — no internal dup.
|
||||
const names = out.map(o => o.name);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
expect(names).toEqual(["Key 2", "Key 3", "Key 4"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("planBulkAdd: custom name|apiKey", () => {
|
||||
it("uses the literal base name with a gap-filled index", () => {
|
||||
const out = planBulkAdd(["Prod|sk-1", "Prod|sk-2"], []);
|
||||
expect(out.map(o => o.name)).toEqual(["Prod 1", "Prod 2"]);
|
||||
expect(out.map(o => o.apiKey)).toEqual(["sk-1", "sk-2"]);
|
||||
});
|
||||
|
||||
it("custom name avoids an existing same-base name", () => {
|
||||
// "Prod 1" exists -> first new "Prod|.." line becomes "Prod 2".
|
||||
const out = planBulkAdd(["Prod|sk-new"], ["Prod 1"]);
|
||||
expect(out[0].name).toBe("Prod 2");
|
||||
});
|
||||
|
||||
it("apiKey containing pipes is preserved (parts after first rejoined)", () => {
|
||||
const out = planBulkAdd(["Prod|sk|with|pipes"], []);
|
||||
expect(out[0].apiKey).toBe("sk|with|pipes");
|
||||
expect(out[0].name).toBe("Prod 1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("planBulkAdd: cloudflare-ai (name|apiKey|accountId)", () => {
|
||||
it("parses 3-part lines into name + apiKey + accountId", () => {
|
||||
const out = planBulkAdd(
|
||||
["main|sk-key1|acc123", "main|sk-key2|def789"],
|
||||
[],
|
||||
{ isCloudflareAi: true }
|
||||
);
|
||||
expect(out.map(o => o.name)).toEqual(["main 1", "main 2"]);
|
||||
expect(out[0].apiKey).toBe("sk-key1");
|
||||
expect(out[0].providerSpecificData).toEqual({ accountId: "acc123" });
|
||||
expect(out[1].providerSpecificData).toEqual({ accountId: "def789" });
|
||||
});
|
||||
|
||||
it("2-part cloudflare line is name|apiKey (no accountId)", () => {
|
||||
const out = planBulkAdd(["main|sk-key1"], [], { isCloudflareAi: true });
|
||||
expect(out[0].name).toBe("main 1");
|
||||
expect(out[0].apiKey).toBe("sk-key1");
|
||||
expect(out[0].providerSpecificData).toBeUndefined();
|
||||
});
|
||||
|
||||
it("1-part cloudflare line is auto-named Key N", () => {
|
||||
const out = planBulkAdd(["sk-key1"], [], { isCloudflareAi: true });
|
||||
expect(out[0].name).toBe("Key 1");
|
||||
expect(out[0].apiKey).toBe("sk-key1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("planBulkAdd: robustness", () => {
|
||||
it("returns [] for no input", () => {
|
||||
expect(planBulkAdd([], [])).toEqual([]);
|
||||
expect(planBulkAdd(["", " "], [])).toEqual([]);
|
||||
});
|
||||
|
||||
it("trims names and apiKeys", () => {
|
||||
const out = planBulkAdd([" Prod | sk-1 "], []);
|
||||
expect(out[0].name).toBe("Prod 1");
|
||||
expect(out[0].apiKey).toBe("sk-1");
|
||||
});
|
||||
|
||||
it("falls back to base 'Key' when name part is empty", () => {
|
||||
const out = planBulkAdd(["|sk-1"], []);
|
||||
expect(out[0].name).toBe("Key 1");
|
||||
expect(out[0].apiKey).toBe("sk-1");
|
||||
});
|
||||
|
||||
it("coerces non-array existingNames gracefully", () => {
|
||||
const out = planBulkAdd(["sk-a"], null);
|
||||
expect(out[0].name).toBe("Key 1");
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,15 @@ describe("getCapabilitiesForModel", () => {
|
||||
search: true,
|
||||
};
|
||||
|
||||
const kiroGpt56Expected = {
|
||||
contextWindow: 272000,
|
||||
maxOutput: 128000,
|
||||
thinkingFormat: "openai",
|
||||
reasoning: true,
|
||||
vision: true,
|
||||
search: true,
|
||||
};
|
||||
|
||||
it("reports Kiro Claude Opus 4.8 as a 1M context model", () => {
|
||||
expect(getCapabilitiesForModel("kiro", "claude-opus-4.8").contextWindow).toBe(1000000);
|
||||
expect(getCapabilitiesForModel("kiro", "anthropic/claude-opus-4.8").contextWindow).toBe(1000000);
|
||||
@@ -26,4 +35,12 @@ describe("getCapabilitiesForModel", () => {
|
||||
expect(getCapabilitiesForModel("kiro", "claude-sonnet-5-agentic")).toMatchObject(claudeSonnet5Expected);
|
||||
expect(getCapabilitiesForModel("kiro", "claude-sonnet-5-thinking-agentic")).toMatchObject(claudeSonnet5Expected);
|
||||
});
|
||||
|
||||
it("reports Kiro GPT 5.6 models with the Kiro 272k context window", () => {
|
||||
expect(getCapabilitiesForModel("kiro", "gpt-5.6-sol")).toMatchObject(kiroGpt56Expected);
|
||||
expect(getCapabilitiesForModel("kiro", "openai/gpt-5.6-sol")).toMatchObject(kiroGpt56Expected);
|
||||
expect(getCapabilitiesForModel("kiro", "gpt-5.6-terra-thinking")).toMatchObject(kiroGpt56Expected);
|
||||
expect(getCapabilitiesForModel("kiro", "gpt-5.6-luna-agentic")).toMatchObject(kiroGpt56Expected);
|
||||
expect(getCapabilitiesForModel("kiro", "gpt-5.6-sol-thinking-agentic")).toMatchObject(kiroGpt56Expected);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
/**
|
||||
* Tests for the `9router xai video` CLI command (cli/src/cli/commands/xaiVideo.js)
|
||||
*
|
||||
* Uses a real local HTTP server standing in for the 9router gateway + video CDN.
|
||||
* No real credentials or upstream calls.
|
||||
*
|
||||
* Covers:
|
||||
* - arg parsing (defaults, flags, unknown flag rejection)
|
||||
* - full happy path: create → poll (pending → done) → MP4 download → atomic rename
|
||||
* - x-connection-id pinning from the create response header
|
||||
* - failed job → non-zero exit, no output file, no stray .part
|
||||
* - poll timeout → non-zero exit
|
||||
* - download failure cleans up the .part file
|
||||
* - no Authorization/token material in output
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
import http from "node:http";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { run, parseArgs, downloadToFile, sanitizeText, imageInputToUrl } = require("../../cli/src/cli/commands/xaiVideo.js");
|
||||
|
||||
const MP4_BYTES = Buffer.from("FAKE-MP4-DATA-0123456789");
|
||||
|
||||
function startServer(handler) {
|
||||
return new Promise((resolve) => {
|
||||
const server = http.createServer(handler);
|
||||
server.listen(0, "127.0.0.1", () => resolve({ server, port: server.address().port }));
|
||||
});
|
||||
}
|
||||
|
||||
const closeServer = (server) => new Promise((r) => server.close(r));
|
||||
|
||||
let tmpDir;
|
||||
let server;
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "xai-video-test-"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (server) {
|
||||
await closeServer(server);
|
||||
server = null;
|
||||
}
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("parseArgs", () => {
|
||||
it("applies defaults", () => {
|
||||
const opts = parseArgs(["--prompt", "hi"]);
|
||||
expect(opts.prompt).toBe("hi");
|
||||
expect(opts.model).toBe("xai/grok-imagine-video");
|
||||
expect(opts.output).toBe("video.mp4");
|
||||
expect(opts.port).toBe(20128);
|
||||
});
|
||||
|
||||
it("parses all documented flags", () => {
|
||||
const opts = parseArgs([
|
||||
"--prompt", "p", "--output", "o.mp4", "--model", "m",
|
||||
"--duration", "10", "--aspect-ratio", "16:9", "--resolution", "720p",
|
||||
"--image", "https://x/img.png", "--timeout", "30", "--port", "1234", "--api-key", "k",
|
||||
]);
|
||||
expect(opts).toMatchObject({
|
||||
prompt: "p", output: "o.mp4", model: "m", duration: 10,
|
||||
aspectRatio: "16:9", resolution: "720p", image: "https://x/img.png",
|
||||
timeoutSec: 30, port: 1234, apiKey: "k",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects unknown flags", () => {
|
||||
expect(() => parseArgs(["--bogus"])).toThrow(/Unknown option/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("imageInputToUrl", () => {
|
||||
it("passes URLs and data URLs through", () => {
|
||||
expect(imageInputToUrl("https://example.com/a.png")).toBe("https://example.com/a.png");
|
||||
expect(imageInputToUrl("data:image/png;base64,AAA")).toBe("data:image/png;base64,AAA");
|
||||
});
|
||||
|
||||
it("converts a local file to a base64 data URL", () => {
|
||||
const p = path.join(tmpDir, "in.png");
|
||||
fs.writeFileSync(p, Buffer.from([1, 2, 3]));
|
||||
expect(imageInputToUrl(p)).toBe(`data:image/png;base64,${Buffer.from([1, 2, 3]).toString("base64")}`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sanitizeText", () => {
|
||||
it("redacts bearer tokens from error output", () => {
|
||||
expect(sanitizeText("boom Bearer abcdefghijklmnop!")).toBe("boom Bearer [redacted]!");
|
||||
});
|
||||
});
|
||||
|
||||
describe("run (against a mock gateway)", () => {
|
||||
it("creates, polls to done, downloads the MP4, and exits 0", async () => {
|
||||
let pollCount = 0;
|
||||
const seen = { createAuth: null, pollConnectionIds: [] };
|
||||
|
||||
({ server } = await startServer((req, res) => {
|
||||
if (req.method === "POST" && req.url === "/v1/videos/generations") {
|
||||
seen.createAuth = req.headers.authorization || null;
|
||||
let body = "";
|
||||
req.on("data", (c) => (body += c));
|
||||
req.on("end", () => {
|
||||
seen.createBody = JSON.parse(body);
|
||||
res.writeHead(200, { "Content-Type": "application/json", "x-9router-connection-id": "conn-42" });
|
||||
res.end(JSON.stringify({ request_id: "job-1" }));
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (req.method === "GET" && req.url === "/v1/videos/job-1") {
|
||||
seen.pollConnectionIds.push(req.headers["x-connection-id"] || null);
|
||||
pollCount++;
|
||||
const port = server.address().port;
|
||||
const payload = pollCount < 3
|
||||
? { status: "pending", progress: pollCount * 30 }
|
||||
: { status: "done", video: { url: `http://127.0.0.1:${port}/files/out.mp4`, duration: 8 } };
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(payload));
|
||||
return;
|
||||
}
|
||||
if (req.method === "GET" && req.url === "/files/out.mp4") {
|
||||
res.writeHead(200, { "Content-Type": "video/mp4" });
|
||||
res.end(MP4_BYTES);
|
||||
return;
|
||||
}
|
||||
res.writeHead(404).end();
|
||||
}));
|
||||
|
||||
const output = path.join(tmpDir, "result.mp4");
|
||||
const logs = [];
|
||||
vi.spyOn(console, "log").mockImplementation((...a) => logs.push(a.join(" ")));
|
||||
vi.spyOn(console, "error").mockImplementation((...a) => logs.push(a.join(" ")));
|
||||
|
||||
const code = await run([
|
||||
"--prompt", "a neon city",
|
||||
"--output", output,
|
||||
"--port", String(server.address().port),
|
||||
"--api-key", "local-key-secret",
|
||||
"--timeout", "10",
|
||||
"--poll-interval-ms", "20",
|
||||
]);
|
||||
|
||||
expect(code).toBe(0);
|
||||
expect(fs.readFileSync(output)).toEqual(MP4_BYTES);
|
||||
expect(fs.existsSync(`${output}.part`)).toBe(false);
|
||||
|
||||
// Model prefix forwarded as-is to the gateway (gateway strips it)
|
||||
expect(seen.createBody.model).toBe("xai/grok-imagine-video");
|
||||
expect(seen.createBody.prompt).toBe("a neon city");
|
||||
// Polls pinned to the connection that created the job
|
||||
expect(seen.pollConnectionIds.every((id) => id === "conn-42")).toBe(true);
|
||||
// No token material in user-facing output
|
||||
expect(logs.join("\n")).not.toContain("local-key-secret");
|
||||
expect(logs.join("\n")).not.toContain("Authorization");
|
||||
});
|
||||
|
||||
it("exits non-zero when the job fails, without leaving files", async () => {
|
||||
({ server } = await startServer((req, res) => {
|
||||
if (req.method === "POST") {
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ request_id: "job-f" }));
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ status: "failed", error: { code: "invalid_argument", message: "bad prompt" } }));
|
||||
}));
|
||||
|
||||
const output = path.join(tmpDir, "nope.mp4");
|
||||
const errors = [];
|
||||
vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
vi.spyOn(console, "error").mockImplementation((...a) => errors.push(a.join(" ")));
|
||||
|
||||
const code = await run([
|
||||
"--prompt", "x", "--output", output,
|
||||
"--port", String(server.address().port),
|
||||
"--timeout", "10", "--poll-interval-ms", "10",
|
||||
]);
|
||||
|
||||
expect(code).toBe(1);
|
||||
expect(errors.join("\n")).toContain("bad prompt");
|
||||
expect(fs.existsSync(output)).toBe(false);
|
||||
expect(fs.existsSync(`${output}.part`)).toBe(false);
|
||||
});
|
||||
|
||||
it("exits non-zero when polling exceeds the timeout", async () => {
|
||||
({ server } = await startServer((req, res) => {
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(req.method === "POST" ? JSON.stringify({ request_id: "job-slow" }) : JSON.stringify({ status: "pending", progress: 1 }));
|
||||
}));
|
||||
|
||||
vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
const errors = [];
|
||||
vi.spyOn(console, "error").mockImplementation((...a) => errors.push(a.join(" ")));
|
||||
|
||||
const code = await run([
|
||||
"--prompt", "x", "--output", path.join(tmpDir, "slow.mp4"),
|
||||
"--port", String(server.address().port),
|
||||
"--timeout", "1", "--poll-interval-ms", "50",
|
||||
]);
|
||||
|
||||
expect(code).toBe(1);
|
||||
expect(errors.join("\n")).toMatch(/Timed out/i);
|
||||
}, 15000);
|
||||
|
||||
it("reports a helpful error when no xAI account is connected", async () => {
|
||||
({ server } = await startServer((req, res) => {
|
||||
res.writeHead(400, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: { message: "No credentials for provider: xai", type: "invalid_request_error" } }));
|
||||
}));
|
||||
|
||||
vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
const errors = [];
|
||||
vi.spyOn(console, "error").mockImplementation((...a) => errors.push(a.join(" ")));
|
||||
|
||||
const code = await run([
|
||||
"--prompt", "x", "--output", path.join(tmpDir, "n.mp4"),
|
||||
"--port", String(server.address().port),
|
||||
]);
|
||||
|
||||
expect(code).toBe(1);
|
||||
expect(errors.join("\n")).toContain("No credentials");
|
||||
expect(errors.join("\n")).toContain("Connect an xAI account");
|
||||
});
|
||||
});
|
||||
|
||||
describe("downloadToFile", () => {
|
||||
it("downloads via .part and renames atomically", async () => {
|
||||
({ server } = await startServer((req, res) => {
|
||||
res.writeHead(200, { "Content-Type": "video/mp4" });
|
||||
res.end(MP4_BYTES);
|
||||
}));
|
||||
|
||||
const out = path.join(tmpDir, "dl.mp4");
|
||||
await downloadToFile(`http://127.0.0.1:${server.address().port}/f.mp4`, out);
|
||||
expect(fs.readFileSync(out)).toEqual(MP4_BYTES);
|
||||
expect(fs.existsSync(`${out}.part`)).toBe(false);
|
||||
});
|
||||
|
||||
it("follows redirects", async () => {
|
||||
({ server } = await startServer((req, res) => {
|
||||
if (req.url === "/start") {
|
||||
res.writeHead(302, { Location: `/final` });
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
res.writeHead(200);
|
||||
res.end(MP4_BYTES);
|
||||
}));
|
||||
|
||||
const out = path.join(tmpDir, "redir.mp4");
|
||||
await downloadToFile(`http://127.0.0.1:${server.address().port}/start`, out);
|
||||
expect(fs.readFileSync(out)).toEqual(MP4_BYTES);
|
||||
});
|
||||
|
||||
it("removes the .part file when the download fails", async () => {
|
||||
({ server } = await startServer((req, res) => {
|
||||
res.writeHead(500);
|
||||
res.end("nope");
|
||||
}));
|
||||
|
||||
const out = path.join(tmpDir, "fail.mp4");
|
||||
await expect(downloadToFile(`http://127.0.0.1:${server.address().port}/f.mp4`, out)).rejects.toThrow(/HTTP 500/);
|
||||
expect(fs.existsSync(out)).toBe(false);
|
||||
expect(fs.existsSync(`${out}.part`)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -4,11 +4,14 @@ import {
|
||||
countGrokCliUserTurns,
|
||||
resolveGrokCliTurnIdx,
|
||||
_resetGrokCliTurnStore,
|
||||
_getGrokCliTurnStoreSize,
|
||||
normalizeGrokCliEffort,
|
||||
supportsGrokCliReasoningEffort,
|
||||
} 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 { getModelInfoCore, resolveProviderAlias } from "../../open-sse/services/model.js";
|
||||
import { OAUTH_PROVIDERS } from "../../src/shared/constants/providers.js";
|
||||
|
||||
describe("grok-cli registry", () => {
|
||||
@@ -27,7 +30,7 @@ describe("grok-cli registry", () => {
|
||||
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);
|
||||
expect(PROVIDER_MODELS.gcli?.some((m) => m.id === "grok-build")).toBe(true);
|
||||
});
|
||||
|
||||
it("is listed as oauth provider for dashboard", () => {
|
||||
@@ -42,6 +45,13 @@ describe("grok-cli registry", () => {
|
||||
expect(resolveProviderAlias("grok-cli")).toBe("grok-cli");
|
||||
});
|
||||
|
||||
it("routes bare grok-build to the subscription provider", async () => {
|
||||
await expect(getModelInfoCore("grok-build", {})).resolves.toEqual({
|
||||
provider: "grok-cli",
|
||||
model: "grok-build",
|
||||
});
|
||||
});
|
||||
|
||||
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");
|
||||
@@ -86,19 +96,19 @@ describe("GrokCliExecutor", () => {
|
||||
|
||||
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-xai-token-auth"]).toBeUndefined();
|
||||
expect(headers["x-grok-client-identifier"]).toBe("grok-shell");
|
||||
expect(headers["x-grok-client-version"]).toBe("0.2.99");
|
||||
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-compaction-at"]).toBeUndefined();
|
||||
expect(headers["x-email"]).toBe("u@example.com");
|
||||
expect(headers["x-userid"]).toBe("uid-1");
|
||||
expect(headers["x-authenticateresponse"]).toBe("authenticate-response");
|
||||
expect(headers["x-authenticateresponse"]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("buildHeaders falls back to top-level email/userId (OAuth mapTokens shape)", () => {
|
||||
@@ -190,6 +200,164 @@ describe("GrokCliExecutor", () => {
|
||||
expect(out.reasoning.effort).toBe("medium");
|
||||
});
|
||||
|
||||
it("normalizes Codex cross-provider tool and reasoning history", () => {
|
||||
const out = executor.transformRequest("grok-4.5", {
|
||||
model: "grok-4.5",
|
||||
input: [
|
||||
{ type: "message", role: "user", content: "continue" },
|
||||
{
|
||||
type: "reasoning",
|
||||
id: "rs_07fe505b3114f180016a5698411c448191bdcdcba678464461",
|
||||
encrypted_content: "openai-ciphertext",
|
||||
summary: [],
|
||||
internal_chat_message_metadata_passthrough: { turn_id: "turn-1" },
|
||||
},
|
||||
{
|
||||
type: "custom_tool_call",
|
||||
id: "ctc_openai",
|
||||
call_id: "call-custom",
|
||||
name: "exec",
|
||||
input: "run this",
|
||||
internal_chat_message_metadata_passthrough: { turn_id: "turn-1" },
|
||||
},
|
||||
{
|
||||
type: "custom_tool_call_output",
|
||||
call_id: "call-custom",
|
||||
output: [{ type: "input_text", text: "first" }, { type: "input_text", text: "second" }],
|
||||
},
|
||||
{
|
||||
type: "function_call_output",
|
||||
call_id: "call-function",
|
||||
output: [{ type: "input_text", text: "function result" }],
|
||||
},
|
||||
],
|
||||
tools: [{ type: "custom", name: "exec", description: "Run command" }],
|
||||
}, true, { connectionId: "cross-provider" });
|
||||
|
||||
expect(out.input.some((item) => item.type === "reasoning")).toBe(false);
|
||||
expect(out.input[1]).toEqual({
|
||||
type: "function_call",
|
||||
call_id: "call-custom",
|
||||
name: "exec",
|
||||
arguments: JSON.stringify({ input: "run this" }),
|
||||
});
|
||||
expect(out.input[2]).toEqual({
|
||||
type: "function_call_output",
|
||||
call_id: "call-custom",
|
||||
output: JSON.stringify([{ type: "input_text", text: "first" }, { type: "input_text", text: "second" }]),
|
||||
});
|
||||
expect(out.input.some((item) => item.call_id === "call-function")).toBe(false);
|
||||
expect(out.tools[0].parameters).toEqual({
|
||||
type: "object",
|
||||
properties: { input: { type: "string" } },
|
||||
required: ["input"],
|
||||
});
|
||||
});
|
||||
|
||||
it("stringifies structured outputs and removes orphaned output items", () => {
|
||||
const out = executor.transformRequest("grok-4.5", {
|
||||
model: "grok-4.5",
|
||||
input: [
|
||||
{ type: "function_call", call_id: "call-array", name: "array_tool", arguments: "{}" },
|
||||
{ type: "function_call_output", call_id: "call-array", output: [1, 2] },
|
||||
{ type: "function_call", call_id: "call-null", name: "null_tool", arguments: "{}" },
|
||||
{ type: "function_call_output", call_id: "call-null", output: null },
|
||||
{ type: "custom_tool_call", call_id: "call-invalid", input: "missing name" },
|
||||
{ type: "custom_tool_call_output", call_id: "call-invalid", output: "orphan" },
|
||||
],
|
||||
}, true, { connectionId: "structured-output" });
|
||||
|
||||
const outputs = out.input.filter((item) => item.type === "function_call_output");
|
||||
expect(outputs).toEqual([
|
||||
{ type: "function_call_output", call_id: "call-array", output: "[1,2]" },
|
||||
{ type: "function_call_output", call_id: "call-null", output: "null" },
|
||||
]);
|
||||
expect(out.input.some((item) => item.call_id === "call-invalid")).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves native Grok encrypted reasoning and item ids", () => {
|
||||
const reasoningId = "rs_3e3f6187-892a-96db-893b-904eff019e19";
|
||||
const messageId = "msg_3e3f6187-892a-96db-893b-904eff019e19";
|
||||
const functionId = "fc_3e3f6187-892a-96db-893b-904eff019e19";
|
||||
const out = executor.transformRequest("grok-4.5", {
|
||||
model: "grok-4.5",
|
||||
input: [
|
||||
{
|
||||
type: "reasoning",
|
||||
id: reasoningId,
|
||||
status: "completed",
|
||||
encrypted_content: "grok-ciphertext",
|
||||
summary: [],
|
||||
internal_chat_message_metadata_passthrough: { turn_id: "turn-2" },
|
||||
},
|
||||
{ type: "message", id: messageId, role: "assistant", content: "done" },
|
||||
{ type: "function_call", id: functionId, call_id: "native-call", name: "wait", arguments: "{}" },
|
||||
{ type: "function_call_output", call_id: "native-call", output: "done" },
|
||||
{ type: "message", role: "user", content: "next" },
|
||||
],
|
||||
}, true, { connectionId: "native-grok" });
|
||||
|
||||
expect(out.input[0]).toMatchObject({
|
||||
type: "reasoning",
|
||||
id: reasoningId,
|
||||
encrypted_content: "grok-ciphertext",
|
||||
});
|
||||
expect(out.input[0].internal_chat_message_metadata_passthrough).toBeUndefined();
|
||||
expect(out.input[1].id).toBe(messageId);
|
||||
expect(out.input[2].id).toBe(functionId);
|
||||
});
|
||||
|
||||
it("normalizes official effort aliases", () => {
|
||||
expect(normalizeGrokCliEffort("none")).toBe("high");
|
||||
expect(normalizeGrokCliEffort("minimal")).toBe("high");
|
||||
expect(normalizeGrokCliEffort("max")).toBe("xhigh");
|
||||
expect(normalizeGrokCliEffort("xhigh")).toBe("xhigh");
|
||||
expect(normalizeGrokCliEffort("ultra")).toBe("high");
|
||||
|
||||
const out = executor.transformRequest("grok-4.5", {
|
||||
model: "grok-4.5",
|
||||
input: "hi",
|
||||
reasoning: { effort: "max", summary: "detailed" },
|
||||
}, true, { connectionId: "effort-conn" });
|
||||
expect(out.reasoning).toEqual({ effort: "xhigh", summary: "detailed" });
|
||||
});
|
||||
|
||||
it("omits reasoning effort for models that reject it", () => {
|
||||
expect(supportsGrokCliReasoningEffort("grok-4.5")).toBe(true);
|
||||
expect(supportsGrokCliReasoningEffort("grok-build")).toBe(false);
|
||||
expect(supportsGrokCliReasoningEffort("grok-composer-2.5-fast")).toBe(false);
|
||||
|
||||
for (const model of ["grok-build", "grok-composer-2.5-fast"]) {
|
||||
const out = executor.transformRequest(model, {
|
||||
model,
|
||||
input: "hi",
|
||||
reasoning: { effort: "max" },
|
||||
}, true, { connectionId: `effort-${model}` });
|
||||
expect(out.reasoning).toEqual({ summary: "concise" });
|
||||
expect(out.include).toContain("reasoning.encrypted_content");
|
||||
}
|
||||
});
|
||||
|
||||
it("drops stale tool_choice and normalizes converted custom choices", () => {
|
||||
const noTools = executor.transformRequest("grok-build", {
|
||||
model: "grok-build",
|
||||
input: "hi",
|
||||
tool_choice: "auto",
|
||||
}, true, { connectionId: "tools-none" });
|
||||
expect(noTools.tool_choice).toBeUndefined();
|
||||
|
||||
const custom = executor.transformRequest("grok-build", {
|
||||
model: "grok-build",
|
||||
input: "hi",
|
||||
tools: [{ type: "custom", name: "apply_patch", description: "Patch files" }],
|
||||
tool_choice: { type: "custom", name: "apply_patch" },
|
||||
}, true, { connectionId: "tools-custom" });
|
||||
expect(custom.tools).toEqual([
|
||||
expect.objectContaining({ type: "function", name: "apply_patch" }),
|
||||
]);
|
||||
expect(custom.tool_choice).toEqual({ type: "function", name: "apply_patch" });
|
||||
});
|
||||
|
||||
it("increments x-grok-turn-idx from user-message count and stays monotonic", () => {
|
||||
const creds = {
|
||||
connectionId: "turn-conn",
|
||||
@@ -238,7 +406,7 @@ describe("GrokCliExecutor", () => {
|
||||
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
|
||||
// Same session, a new delta-style request advances without relying on full history.
|
||||
executor.transformRequest(
|
||||
"grok-4.5",
|
||||
{
|
||||
@@ -248,7 +416,7 @@ describe("GrokCliExecutor", () => {
|
||||
true,
|
||||
creds
|
||||
);
|
||||
expect(executor._currentTurnIdx).toBe(2);
|
||||
expect(executor._currentTurnIdx).toBe(3);
|
||||
});
|
||||
|
||||
it("countGrokCliUserTurns / resolveGrokCliTurnIdx helpers", () => {
|
||||
@@ -273,6 +441,45 @@ describe("GrokCliExecutor", () => {
|
||||
expect(resolveGrokCliTurnIdx("s1", [{ role: "user", type: "message", content: "a" }])).toBe(2);
|
||||
});
|
||||
|
||||
it("keeps fallback session stable when assistant history appears", () => {
|
||||
const creds = { connectionId: "fallback-conn", rawHeaders: {} };
|
||||
executor.transformRequest("grok-build", {
|
||||
model: "grok-build",
|
||||
input: [{ type: "message", role: "user", content: "first" }],
|
||||
}, true, creds);
|
||||
const firstSession = executor._currentSessionId;
|
||||
|
||||
executor.transformRequest("grok-build", {
|
||||
model: "grok-build",
|
||||
input: [
|
||||
{ type: "message", role: "user", content: "first" },
|
||||
{ type: "message", role: "assistant", content: "x".repeat(100) },
|
||||
{ type: "message", role: "user", content: "second" },
|
||||
],
|
||||
}, true, creds);
|
||||
expect(executor._currentSessionId).toBe(firstSession);
|
||||
expect(executor._currentTurnIdx).toBe(2);
|
||||
});
|
||||
|
||||
it("does not advance turn index when retrying the same request body", () => {
|
||||
const body = {
|
||||
model: "grok-build",
|
||||
input: [{ type: "message", role: "user", content: "retry me" }],
|
||||
};
|
||||
const creds = { connectionId: "retry-conn" };
|
||||
executor.transformRequest("grok-build", body, true, creds);
|
||||
const firstTurn = executor._currentTurnIdx;
|
||||
executor.transformRequest("grok-build", body, true, creds);
|
||||
expect(executor._currentTurnIdx).toBe(firstTurn);
|
||||
});
|
||||
|
||||
it("bounds per-session turn state", () => {
|
||||
for (let i = 0; i < 5100; i += 1) {
|
||||
resolveGrokCliTurnIdx(`session-${i}`, [{ role: "user", content: "hi" }]);
|
||||
}
|
||||
expect(_getGrokCliTurnStoreSize()).toBe(5000);
|
||||
});
|
||||
|
||||
it("parseError surfaces 402 spending-limit", () => {
|
||||
const err = executor.parseError(
|
||||
{ status: 402 },
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* Regression test for issue #2546: Grok CLI (xAI) token refresh not used,
|
||||
* session dies 40-45 min after login.
|
||||
*
|
||||
* Root cause: grok-cli mapTokens stored `expiresIn` but never `expiresAt`.
|
||||
* shouldRefreshCredentials() only reads expiresAt/tokenExpiresAt, so the
|
||||
* proactive refresh path never fired and only the reactive 401 path could
|
||||
* refresh — causing intermittent "token expired" failures.
|
||||
*
|
||||
* This test exercises the proactive-refresh decision path for grok-cli with
|
||||
* an absolute expiresAt. (The mapTokens unit portion cannot run in this
|
||||
* checkout because src/lib/oauth/providers.js self-imports the bare
|
||||
* "open-sse/index.js" specifier which vitest here does not resolve — a
|
||||
* pre-existing harness gap unrelated to this fix.)
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
describe("Grok CLI (xAI) token expiry propagation (#2546)", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.resetModules();
|
||||
global.fetch = originalFetch;
|
||||
});
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
});
|
||||
|
||||
it("proactive refresh fires for a near-expiry grok-cli token (expiresAt present)", async () => {
|
||||
const { shouldRefreshCredentials } = await import(
|
||||
"../../open-sse/services/oauthCredentialManager.js"
|
||||
);
|
||||
const soon = new Date(Date.now() + 60 * 1000).toISOString();
|
||||
const creds = {
|
||||
connectionId: "grok-1",
|
||||
refreshToken: "rt",
|
||||
expiresIn: 60,
|
||||
expiresAt: soon,
|
||||
};
|
||||
expect(shouldRefreshCredentials("grok-cli", creds)).toBe(true);
|
||||
});
|
||||
|
||||
it("proactive refresh does NOT fire for a far-future grok-cli token", async () => {
|
||||
const { shouldRefreshCredentials } = await import(
|
||||
"../../open-sse/services/oauthCredentialManager.js"
|
||||
);
|
||||
const farFuture = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString();
|
||||
const creds = {
|
||||
connectionId: "grok-2",
|
||||
refreshToken: "rt",
|
||||
expiresIn: 86400,
|
||||
expiresAt: farFuture,
|
||||
};
|
||||
expect(shouldRefreshCredentials("grok-cli", creds)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../../open-sse/services/oauthCredentialManager.js", () => ({
|
||||
refreshProviderCredentials: vi.fn(),
|
||||
}));
|
||||
|
||||
import { refreshProviderCredentials } from "../../open-sse/services/oauthCredentialManager.js";
|
||||
import {
|
||||
parseGrokCliModels,
|
||||
resolveGrokCliModels,
|
||||
} from "../../open-sse/services/grokCliModels.js";
|
||||
|
||||
function jsonResponse(body, status = 200) {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
describe("Grok CLI live models", () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it("normalizes official model metadata", () => {
|
||||
expect(parseGrokCliModels({
|
||||
models: [{
|
||||
model_id: "grok-build",
|
||||
display_name: "Grok Build",
|
||||
context_window: 500000,
|
||||
max_output_tokens: 64000,
|
||||
supported_in_api: false,
|
||||
}],
|
||||
})).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "grok-build",
|
||||
name: "Grok Build",
|
||||
contextLength: 500000,
|
||||
maxOutputTokens: 64000,
|
||||
supported_in_api: false,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("refreshes and retries through selected proxy", async () => {
|
||||
const fetchFn = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse({ error: "expired" }, 401))
|
||||
.mockResolvedValueOnce(jsonResponse({ data: [{ id: "grok-build" }] }));
|
||||
const onCredentialsRefreshed = vi.fn();
|
||||
const proxyOptions = {
|
||||
connectionProxyEnabled: true,
|
||||
connectionProxyUrl: "http://proxy.test:8080",
|
||||
strictProxy: true,
|
||||
};
|
||||
refreshProviderCredentials.mockResolvedValue({ accessToken: "new-token" });
|
||||
|
||||
const result = await resolveGrokCliModels({
|
||||
accessToken: "old-token",
|
||||
refreshToken: "refresh-token",
|
||||
providerSpecificData: { email: "user@example.com" },
|
||||
}, { fetchFn, proxyOptions, onCredentialsRefreshed });
|
||||
|
||||
expect(result.models).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "grok-build",
|
||||
contextLength: 500000,
|
||||
maxOutputTokens: 64000,
|
||||
}),
|
||||
]);
|
||||
expect(refreshProviderCredentials).toHaveBeenCalledWith(
|
||||
"grok-cli",
|
||||
expect.any(Object),
|
||||
expect.anything(),
|
||||
proxyOptions,
|
||||
);
|
||||
expect(onCredentialsRefreshed).toHaveBeenCalledWith({ accessToken: "new-token" });
|
||||
expect(fetchFn).toHaveBeenCalledTimes(2);
|
||||
expect(fetchFn.mock.calls[0][2]).toBe(proxyOptions);
|
||||
expect(fetchFn.mock.calls[1][1].headers.Authorization).toBe("Bearer new-token");
|
||||
expect(fetchFn.mock.calls[1][1].headers["x-grok-client-version"]).toBe("0.2.99");
|
||||
});
|
||||
});
|
||||
@@ -101,6 +101,35 @@ describe("parseGrokCliBilling", () => {
|
||||
});
|
||||
expect(parsed.plan).toBe("Super Grok");
|
||||
});
|
||||
|
||||
it("does not report paid subscription access as depleted on-demand credit", () => {
|
||||
const parsed = parseGrokCliBilling(EXHAUSTED_BILLING, {
|
||||
...USER_PROFILE,
|
||||
subscriptionTier: "XPremiumPlus",
|
||||
});
|
||||
expect(parsed.plan).toBe("XPremiumPlus");
|
||||
expect(parsed.subscriptionAccess).toBe(true);
|
||||
expect(parsed.quotas).toEqual({});
|
||||
expect(parsed.exhausted).toBe(false);
|
||||
});
|
||||
|
||||
it("maps current monthly fields and snake-case subscription tier", () => {
|
||||
const parsed = parseGrokCliBilling({
|
||||
monthlyLimit: { val: 1000 },
|
||||
includedUsed: { val: 275 },
|
||||
totalUsed: { val: 300 },
|
||||
resetAt: "2026-08-01T00:00:00Z",
|
||||
}, {
|
||||
subscription_tier: "premium_plus",
|
||||
});
|
||||
expect(parsed.plan).toBe("Premium Plus");
|
||||
expect(parsed.quotas["Monthly included"]).toMatchObject({
|
||||
used: 275,
|
||||
total: 1000,
|
||||
remainingPercentage: 72.5,
|
||||
resetAt: "2026-08-01T00:00:00.000Z",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("getUsageForProvider(grok-cli)", () => {
|
||||
@@ -140,6 +169,8 @@ describe("getUsageForProvider(grok-cli)", () => {
|
||||
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-grok-client-version"]).toBe("0.2.99");
|
||||
expect(billingCall[1].headers["x-grok-client-identifier"]).toBe("grok-shell");
|
||||
expect(billingCall[1].headers["x-userid"]).toBe(
|
||||
"d84768dd-224d-4052-ba49-0d336fa9160c",
|
||||
);
|
||||
@@ -174,6 +205,24 @@ describe("getUsageForProvider(grok-cli)", () => {
|
||||
expect(usage.quotas["On-demand"].remainingPercentage).toBe(0);
|
||||
expect(usage.quotas["On-demand"].total).toBe(1);
|
||||
});
|
||||
|
||||
it("reports active paid access when provider exposes no numeric quota", async () => {
|
||||
proxyAwareFetch
|
||||
.mockResolvedValueOnce(jsonResponse(EXHAUSTED_BILLING))
|
||||
.mockResolvedValueOnce(jsonResponse({
|
||||
...USER_PROFILE,
|
||||
subscriptionTier: "XPremiumPlus",
|
||||
}));
|
||||
|
||||
const usage = await getUsageForProvider({
|
||||
provider: "grok-cli",
|
||||
accessToken: "test-token",
|
||||
});
|
||||
|
||||
expect(usage.plan).toBe("XPremiumPlus");
|
||||
expect(usage.message).toMatch(/active.*numeric included quota/i);
|
||||
expect(usage.quotas).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseQuotaData(grok-cli)", () => {
|
||||
|
||||
@@ -250,4 +250,48 @@ describe("handleChatCore Headroom diagnostics", () => {
|
||||
expect.stringContaining("reported token delta, but outbound JSON shrank <5%; provider may bill near-original payload")
|
||||
);
|
||||
});
|
||||
|
||||
it("bypasses token savers when requested by the client", async () => {
|
||||
const log = { debug: vi.fn(), info: vi.fn(), warn: vi.fn() };
|
||||
const pxpipeTransform = vi.fn();
|
||||
const messages = [{ role: "user", content: "Write polished prose." }];
|
||||
|
||||
global.fetch = vi.fn(async (url) => {
|
||||
throw new Error(`unexpected fetch: ${url}`);
|
||||
});
|
||||
|
||||
await handleChatCore({
|
||||
body: { model: "gpt-4o", stream: false, messages },
|
||||
modelInfo: { provider: "openai", model: "gpt-4o" },
|
||||
credentials: { apiKey: "test-key", providerSpecificData: {} },
|
||||
log,
|
||||
connectionId: "test-conn",
|
||||
headroomEnabled: true,
|
||||
headroomUrl: "http://localhost:8787",
|
||||
headroomCompressUserMessages: true,
|
||||
rtkEnabled: true,
|
||||
cavemanEnabled: true,
|
||||
cavemanLevel: "full",
|
||||
ponytailEnabled: true,
|
||||
ponytailLevel: "full",
|
||||
pxpipeEnabled: true,
|
||||
pxpipeTransform,
|
||||
clientRawRequest: {
|
||||
endpoint: "/v1/chat/completions",
|
||||
body: {},
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
"x-9router-token-saver": "off",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
expect(pxpipeTransform).not.toHaveBeenCalled();
|
||||
expect(executeMock).toHaveBeenCalledWith(expect.objectContaining({
|
||||
body: expect.objectContaining({
|
||||
messages: [{ role: "user", content: "Write polished prose." }],
|
||||
}),
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,6 +25,13 @@ describe("Kiro MITM model slots", () => {
|
||||
expect(simpleTask).toBeTruthy();
|
||||
expect(simpleTask.alias).toBe("simple-task");
|
||||
});
|
||||
|
||||
it("offers mappable slots for GPT-5.6 family models", () => {
|
||||
const models = new Map(kiro.defaultModels.map((m) => [m.id, m]));
|
||||
expect(models.get("gpt-5.6-sol")).toMatchObject({ alias: "gpt-5.6-sol", contextLength: 272000, rateMultiplier: 2.4 });
|
||||
expect(models.get("gpt-5.6-terra")).toMatchObject({ alias: "gpt-5.6-terra", contextLength: 272000, rateMultiplier: 1.2 });
|
||||
expect(models.get("gpt-5.6-luna")).toMatchObject({ alias: "gpt-5.6-luna", contextLength: 272000, rateMultiplier: 0.6 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Kiro static provider models", () => {
|
||||
@@ -37,4 +44,47 @@ describe("Kiro static provider models", () => {
|
||||
"claude-sonnet-5-thinking-agentic",
|
||||
]));
|
||||
});
|
||||
|
||||
it("includes GPT-5.6 family and synthetic Kiro variants", () => {
|
||||
const models = new Map((PROVIDER_MODELS.kr || []).map((model) => [model.id, model]));
|
||||
const ids = [...models.keys()];
|
||||
expect(ids).toEqual(expect.arrayContaining([
|
||||
"gpt-5.6-sol",
|
||||
"gpt-5.6-sol-thinking",
|
||||
"gpt-5.6-sol-agentic",
|
||||
"gpt-5.6-sol-thinking-agentic",
|
||||
"gpt-5.6-terra",
|
||||
"gpt-5.6-terra-thinking",
|
||||
"gpt-5.6-terra-agentic",
|
||||
"gpt-5.6-terra-thinking-agentic",
|
||||
"gpt-5.6-luna",
|
||||
"gpt-5.6-luna-thinking",
|
||||
"gpt-5.6-luna-agentic",
|
||||
"gpt-5.6-luna-thinking-agentic",
|
||||
]));
|
||||
|
||||
for (const [id, rateMultiplier] of [
|
||||
["gpt-5.6-sol", 2.4],
|
||||
["gpt-5.6-sol-thinking", 2.4],
|
||||
["gpt-5.6-sol-agentic", 2.4],
|
||||
["gpt-5.6-sol-thinking-agentic", 2.4],
|
||||
["gpt-5.6-terra", 1.2],
|
||||
["gpt-5.6-terra-thinking", 1.2],
|
||||
["gpt-5.6-terra-agentic", 1.2],
|
||||
["gpt-5.6-terra-thinking-agentic", 1.2],
|
||||
["gpt-5.6-luna", 0.6],
|
||||
["gpt-5.6-luna-thinking", 0.6],
|
||||
["gpt-5.6-luna-agentic", 0.6],
|
||||
["gpt-5.6-luna-thinking-agentic", 0.6],
|
||||
]) {
|
||||
const model = models.get(id);
|
||||
const upstreamModelId = id.replace(/-(thinking-agentic|thinking|agentic)$/, "");
|
||||
expect(model).toMatchObject({
|
||||
contextLength: 272000,
|
||||
rateMultiplier,
|
||||
upstreamModelId,
|
||||
});
|
||||
expect(model.description).toContain("272k context window");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { KiroExecutor } from "../../open-sse/executors/kiro.js";
|
||||
import "../translator/registerAll.js";
|
||||
|
||||
function createMockFrame(eventType, payloadObj) {
|
||||
const payloadStr = JSON.stringify(payloadObj);
|
||||
@@ -47,6 +48,13 @@ async function readAllSSE(stream) {
|
||||
return result;
|
||||
}
|
||||
|
||||
async function readNextWithTimeout(reader) {
|
||||
return Promise.race([
|
||||
reader.read(),
|
||||
new Promise((_, reject) => setTimeout(() => reject(new Error("timed out waiting for SSE chunk")), 100)),
|
||||
]);
|
||||
}
|
||||
|
||||
describe("KiroExecutor thinking tag stripping", () => {
|
||||
it("strips <thinking> tags from assistantResponseEvent", async () => {
|
||||
const executor = new KiroExecutor();
|
||||
@@ -121,4 +129,53 @@ describe("KiroExecutor thinking tag stripping", () => {
|
||||
const contentChunks = objects.filter(obj => obj.choices[0].delta.content !== undefined);
|
||||
expect(contentChunks.length).toBe(0);
|
||||
});
|
||||
|
||||
it("emits a terminal chunk at messageStop before the upstream stream closes", async () => {
|
||||
const executor = new KiroExecutor();
|
||||
|
||||
const f1 = createMockFrame("assistantResponseEvent", { content: "OK" });
|
||||
const f2 = createMockFrame("messageStopEvent", {});
|
||||
|
||||
const readableStream = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(f1);
|
||||
controller.enqueue(f2);
|
||||
}
|
||||
});
|
||||
|
||||
const transformedResponse = executor.transformEventStreamToSSE({ body: readableStream }, "claude-test");
|
||||
const reader = transformedResponse.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let output = "";
|
||||
for (let i = 0; i < 4 && !output.includes("\"finish_reason\":\"stop\""); i++) {
|
||||
const { value } = await readNextWithTimeout(reader);
|
||||
output += decoder.decode(value, { stream: true });
|
||||
}
|
||||
await reader.cancel();
|
||||
|
||||
expect(output).toContain("\"finish_reason\":\"stop\"");
|
||||
});
|
||||
|
||||
it("uses tool_calls finish reason for tool streams without messageStop", async () => {
|
||||
const executor = new KiroExecutor();
|
||||
|
||||
const f1 = createMockFrame("toolUseEvent", { toolUseId: "tool-1", name: "read_file", input: { path: "a.txt" } });
|
||||
|
||||
const readableStream = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(f1);
|
||||
controller.close();
|
||||
}
|
||||
});
|
||||
|
||||
const transformedResponse = executor.transformEventStreamToSSE({ body: readableStream }, "claude-test");
|
||||
const output = await readAllSSE(transformedResponse.body);
|
||||
const objects = output
|
||||
.split("\n")
|
||||
.filter(line => line.startsWith("data: ") && !line.includes("[DONE]"))
|
||||
.map(line => JSON.parse(line.slice(6)));
|
||||
|
||||
const finalChunk = objects.at(-1);
|
||||
expect(finalChunk.choices[0].finish_reason).toBe("tool_calls");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -138,21 +138,21 @@ describe("openai ↔ responses multi-turn reasoning", () => {
|
||||
});
|
||||
|
||||
describe("GrokCliExecutor multi-turn input", () => {
|
||||
it("keeps reasoning items (incl. encrypted_content) and strips only server message ids", () => {
|
||||
it("keeps native Grok reasoning and item 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: "message", role: "user", content: "hi", id: "msg_3e3f6187-892a-96db-893b-904eff019e19" },
|
||||
{
|
||||
type: "reasoning",
|
||||
id: "rs_server_prev",
|
||||
id: "rs_3e3f6187-892a-96db-893b-904eff019e19",
|
||||
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: "assistant", content: "hello", id: "msg_4e3f6187-892a-96db-893b-904eff019e19" },
|
||||
{ type: "message", role: "user", content: "again" },
|
||||
],
|
||||
include: ["reasoning.encrypted_content"],
|
||||
@@ -166,14 +166,13 @@ describe("GrokCliExecutor multi-turn input", () => {
|
||||
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();
|
||||
expect(reasoning[0].id).toBe("rs_3e3f6187-892a-96db-893b-904eff019e19");
|
||||
|
||||
// system preserved (not developer)
|
||||
expect(out.input[0].role).toBe("system");
|
||||
// message server ids stripped
|
||||
// Native Grok IDs are required for encrypted continuity.
|
||||
for (const item of out.input) {
|
||||
if (item.type === "message") expect(item.id).toBeUndefined();
|
||||
if (item.type === "message" && item.id) expect(item.id).toMatch(/^msg_[0-9a-f-]{36}$/);
|
||||
}
|
||||
expect(out.include).toContain("reasoning.encrypted_content");
|
||||
expect(out.store).toBe(false);
|
||||
|
||||
@@ -11,6 +11,7 @@ import { openaiToKiroRequest } from "../../open-sse/translator/request/openai-to
|
||||
|
||||
const contentOf = (result) =>
|
||||
result.conversationState.currentMessage.userInputMessage.content;
|
||||
const systemPromptOf = (result) => result.systemPrompt || "";
|
||||
|
||||
describe("openaiToKiroRequest", () => {
|
||||
describe("basic message conversion", () => {
|
||||
@@ -293,7 +294,11 @@ describe("openaiToKiroRequest", () => {
|
||||
|
||||
const result = openaiToKiroRequest("claude-sonnet-4.6", body, true, {});
|
||||
|
||||
expect(contentOf(result)).toContain("<max_thinking_length>1024</max_thinking_length>");
|
||||
expect(systemPromptOf(result)).toContain("<max_thinking_length>1024</max_thinking_length>");
|
||||
expect(result.additionalModelRequestFields).toEqual({
|
||||
thinking: { type: "adaptive", display: "summarized" },
|
||||
output_config: { effort: "low" },
|
||||
});
|
||||
});
|
||||
|
||||
it("maps reasoning_effort high to max_thinking_length 24576", () => {
|
||||
@@ -304,7 +309,97 @@ describe("openaiToKiroRequest", () => {
|
||||
|
||||
const result = openaiToKiroRequest("claude-sonnet-4.6", body, true, {});
|
||||
|
||||
expect(contentOf(result)).toContain("<max_thinking_length>24576</max_thinking_length>");
|
||||
expect(systemPromptOf(result)).toContain("<max_thinking_length>24576</max_thinking_length>");
|
||||
expect(result.additionalModelRequestFields).toEqual({
|
||||
thinking: { type: "adaptive", display: "summarized" },
|
||||
output_config: { effort: "high" },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not send additionalModelRequestFields for legacy Kiro model ids", () => {
|
||||
const body = {
|
||||
reasoning_effort: "high",
|
||||
messages: [{ role: "user", content: "Legacy model id should not get adaptive fields" }]
|
||||
};
|
||||
|
||||
const result = openaiToKiroRequest("claude-sonnet-4.5", body, true, {});
|
||||
|
||||
expect(systemPromptOf(result)).toContain("<max_thinking_length>24576</max_thinking_length>");
|
||||
expect(result.additionalModelRequestFields).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not send additionalModelRequestFields for date-suffixed Claude 4 model ids", () => {
|
||||
const body = {
|
||||
reasoning_effort: "high",
|
||||
messages: [{ role: "user", content: "Date-suffixed Claude 4 should stay legacy" }]
|
||||
};
|
||||
|
||||
const result = openaiToKiroRequest("claude-sonnet-4-20250514", body, true, {});
|
||||
|
||||
expect(systemPromptOf(result)).toContain("<max_thinking_length>24576</max_thinking_length>");
|
||||
expect(result.additionalModelRequestFields).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not send additionalModelRequestFields for pre-4 legacy Kiro model ids", () => {
|
||||
const body = {
|
||||
reasoning_effort: "high",
|
||||
messages: [{ role: "user", content: "Older model id should not get adaptive fields" }]
|
||||
};
|
||||
|
||||
const result = openaiToKiroRequest("claude-sonnet-3.7", body, true, {});
|
||||
|
||||
expect(systemPromptOf(result)).toContain("<max_thinking_length>24576</max_thinking_length>");
|
||||
expect(result.additionalModelRequestFields).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not send additionalModelRequestFields for prefixed pre-4 legacy Kiro model ids", () => {
|
||||
const body = {
|
||||
reasoning_effort: "high",
|
||||
messages: [{ role: "user", content: "Prefixed older model id should not get adaptive fields" }]
|
||||
};
|
||||
|
||||
const result = openaiToKiroRequest("kiro/claude-3-7-sonnet-20250219", body, true, {});
|
||||
|
||||
expect(systemPromptOf(result)).toContain("<max_thinking_length>24576</max_thinking_length>");
|
||||
expect(result.additionalModelRequestFields).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not send Claude-specific additionalModelRequestFields for prefixed non-Claude aliases", () => {
|
||||
const body = {
|
||||
reasoning_effort: "high",
|
||||
messages: [{ role: "user", content: "Prefixed non-Claude alias should not get adaptive fields" }]
|
||||
};
|
||||
|
||||
const result = openaiToKiroRequest("kiro/gpt-4o", body, true, {});
|
||||
|
||||
expect(systemPromptOf(result)).toContain("<max_thinking_length>24576</max_thinking_length>");
|
||||
expect(result.additionalModelRequestFields).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not send Claude-specific additionalModelRequestFields for non-Claude aliases", () => {
|
||||
const body = {
|
||||
reasoning_effort: "high",
|
||||
messages: [{ role: "user", content: "Non-Claude aliases should not get Claude adaptive fields" }]
|
||||
};
|
||||
|
||||
const result = openaiToKiroRequest("gpt-4o", body, true, {});
|
||||
|
||||
expect(systemPromptOf(result)).toContain("<max_thinking_length>24576</max_thinking_length>");
|
||||
expect(result.additionalModelRequestFields).toBeUndefined();
|
||||
});
|
||||
|
||||
it("defaults future Kiro model ids to additionalModelRequestFields support", () => {
|
||||
const body = {
|
||||
reasoning_effort: "high",
|
||||
messages: [{ role: "user", content: "Future model id should get adaptive fields" }]
|
||||
};
|
||||
|
||||
const result = openaiToKiroRequest("claude-sonnet-4.60", body, true, {});
|
||||
|
||||
expect(result.additionalModelRequestFields).toEqual({
|
||||
thinking: { type: "adaptive", display: "summarized" },
|
||||
output_config: { effort: "high" },
|
||||
});
|
||||
});
|
||||
|
||||
it("clamps reasoning_effort max to Kiro max_thinking_length 32000", () => {
|
||||
@@ -315,7 +410,8 @@ describe("openaiToKiroRequest", () => {
|
||||
|
||||
const result = openaiToKiroRequest("claude-sonnet-4.6", body, true, {});
|
||||
|
||||
expect(contentOf(result)).toContain("<max_thinking_length>32000</max_thinking_length>");
|
||||
expect(systemPromptOf(result)).toContain("<max_thinking_length>32000</max_thinking_length>");
|
||||
expect(result.additionalModelRequestFields?.output_config?.effort).toBe("high");
|
||||
});
|
||||
|
||||
it("clamps OpenAI Responses reasoning.effort xhigh to max_thinking_length 32000", () => {
|
||||
@@ -326,7 +422,8 @@ describe("openaiToKiroRequest", () => {
|
||||
|
||||
const result = openaiToKiroRequest("claude-sonnet-4.6", body, true, {});
|
||||
|
||||
expect(contentOf(result)).toContain("<max_thinking_length>32000</max_thinking_length>");
|
||||
expect(systemPromptOf(result)).toContain("<max_thinking_length>32000</max_thinking_length>");
|
||||
expect(result.additionalModelRequestFields?.output_config?.effort).toBe("high");
|
||||
});
|
||||
|
||||
it("uses Claude thinking.budget_tokens as max_thinking_length", () => {
|
||||
@@ -337,7 +434,7 @@ describe("openaiToKiroRequest", () => {
|
||||
|
||||
const result = openaiToKiroRequest("claude-sonnet-4.6", body, true, {});
|
||||
|
||||
expect(contentOf(result)).toContain("<max_thinking_length>4096</max_thinking_length>");
|
||||
expect(systemPromptOf(result)).toContain("<max_thinking_length>4096</max_thinking_length>");
|
||||
});
|
||||
|
||||
it("uses the default budget for synthetic -thinking models with no explicit config", () => {
|
||||
@@ -347,7 +444,54 @@ describe("openaiToKiroRequest", () => {
|
||||
|
||||
const result = openaiToKiroRequest("claude-sonnet-4.6-thinking", body, true, {});
|
||||
|
||||
expect(contentOf(result)).toContain("<max_thinking_length>16000</max_thinking_length>");
|
||||
expect(systemPromptOf(result)).toContain("<max_thinking_length>16000</max_thinking_length>");
|
||||
});
|
||||
|
||||
it("keeps top-level systemPrompt stable across turns", () => {
|
||||
const first = openaiToKiroRequest(
|
||||
"claude-sonnet-4.6-thinking",
|
||||
{ messages: [{ role: "user", content: "first" }] },
|
||||
true,
|
||||
{}
|
||||
);
|
||||
const second = openaiToKiroRequest(
|
||||
"claude-sonnet-4.6-thinking",
|
||||
{ messages: [{ role: "user", content: "second" }] },
|
||||
true,
|
||||
{}
|
||||
);
|
||||
|
||||
expect(first.systemPrompt).toBe(second.systemPrompt);
|
||||
expect(first.systemPrompt).not.toContain("Current time");
|
||||
expect(first.conversationState.currentMessage.userInputMessage.content).toContain("Current time");
|
||||
});
|
||||
|
||||
it("replays frozen msg0 for explicit Kiro sessions while keeping current time fresh", () => {
|
||||
const credentials = {
|
||||
connectionId: "kiro-account-openai-replay",
|
||||
rawHeaders: { "x-session-id": "hermes-session-openai-replay" },
|
||||
};
|
||||
const first = openaiToKiroRequest(
|
||||
"claude-sonnet-4.6",
|
||||
{ messages: [{ role: "user", content: "first turn" }] },
|
||||
true,
|
||||
credentials
|
||||
);
|
||||
const second = openaiToKiroRequest(
|
||||
"claude-sonnet-4.6",
|
||||
{ messages: [{ role: "user", content: "second turn" }] },
|
||||
true,
|
||||
credentials
|
||||
);
|
||||
|
||||
expect(second.conversationState.conversationId).toBe("hermes-session-openai-replay");
|
||||
expect(second.conversationState.agentContinuationId).toBe(first.conversationState.agentContinuationId);
|
||||
expect(second.conversationState.history[0].userInputMessage.content).toBe(
|
||||
first.conversationState.currentMessage.userInputMessage.content
|
||||
);
|
||||
expect(second.conversationState.history[0].userInputMessage.modelId).toBe("claude-sonnet-4.6");
|
||||
expect(second.conversationState.currentMessage.userInputMessage.content).toContain("Current time");
|
||||
expect(second.conversationState.currentMessage.userInputMessage.content).toContain("second turn");
|
||||
});
|
||||
|
||||
it("does not inject thinking prefix for reasoning_effort none", () => {
|
||||
@@ -358,8 +502,9 @@ describe("openaiToKiroRequest", () => {
|
||||
|
||||
const result = openaiToKiroRequest("claude-sonnet-4.6", body, true, {});
|
||||
|
||||
expect(contentOf(result)).not.toContain("<thinking_mode>enabled</thinking_mode>");
|
||||
expect(contentOf(result)).not.toContain("<max_thinking_length>");
|
||||
expect(systemPromptOf(result)).not.toContain("<thinking_mode>enabled</thinking_mode>");
|
||||
expect(systemPromptOf(result)).not.toContain("<max_thinking_length>");
|
||||
expect(result.additionalModelRequestFields).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
filterQuotasByVisibility,
|
||||
getHiddenQuotaRows,
|
||||
parseQuotaData,
|
||||
} from "@/app/(dashboard)/dashboard/usage/components/ProviderLimits/utils.js";
|
||||
|
||||
describe("provider quota visibility", () => {
|
||||
const data = {
|
||||
quotas: {
|
||||
"gemini-pro-agent": {
|
||||
displayName: "Gemini 3.1 Pro (High)",
|
||||
used: 200,
|
||||
total: 1000,
|
||||
resetAt: "2026-07-04T00:00:00Z",
|
||||
},
|
||||
"claude-opus-4-6-thinking": {
|
||||
displayName: "Claude Opus 4.6 (Thinking)",
|
||||
used: 100,
|
||||
total: 1000,
|
||||
resetAt: "2026-07-04T00:00:00Z",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
it("keeps Antigravity modelKey so hidden settings use stable quota ids", () => {
|
||||
const quotas = parseQuotaData("antigravity", data);
|
||||
expect(quotas.map((q) => q.modelKey)).toEqual([
|
||||
"gemini-pro-agent",
|
||||
"claude-opus-4-6-thinking",
|
||||
]);
|
||||
});
|
||||
|
||||
it("shows all quotas by default and hides configured provider rows", () => {
|
||||
const quotas = parseQuotaData("antigravity", data);
|
||||
expect(filterQuotasByVisibility("antigravity", quotas, {})).toHaveLength(2);
|
||||
|
||||
const visibility = {
|
||||
antigravity: { hidden: ["claude-opus-4-6-thinking"] },
|
||||
};
|
||||
const visible = filterQuotasByVisibility("antigravity", quotas, visibility);
|
||||
const hidden = getHiddenQuotaRows("antigravity", quotas, visibility);
|
||||
|
||||
expect(visible.map((q) => q.modelKey)).toEqual(["gemini-pro-agent"]);
|
||||
expect(hidden.map((q) => q.modelKey)).toEqual(["claude-opus-4-6-thinking"]);
|
||||
});
|
||||
|
||||
it("does not apply one provider hidden list to another provider", () => {
|
||||
const quotas = parseQuotaData("antigravity", data);
|
||||
const visibility = {
|
||||
codex: { hidden: ["gemini-pro-agent"] },
|
||||
};
|
||||
expect(filterQuotasByVisibility("antigravity", quotas, visibility)).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
@@ -72,6 +72,7 @@ vi.mock("open-sse/executors/index.js", () => ({
|
||||
|
||||
describe("quota auto-ping", () => {
|
||||
let runQuotaAutoPingTick;
|
||||
let configureQuotaAutoPing;
|
||||
let deps;
|
||||
let state;
|
||||
let getCodexUsage;
|
||||
@@ -83,11 +84,12 @@ describe("quota auto-ping", () => {
|
||||
vi.resetModules();
|
||||
vi.clearAllMocks();
|
||||
vi.useRealTimers();
|
||||
delete global.__quotaAutoPing;
|
||||
|
||||
({ getCodexUsage } = await import("open-sse/services/usage/codex.js"));
|
||||
({ getClaudeUsage } = await import("open-sse/services/usage/claude.js"));
|
||||
({ getExecutor } = await import("open-sse/executors/index.js"));
|
||||
({ runQuotaAutoPingTick } = await import("../../src/shared/services/quotaAutoPing.js"));
|
||||
({ runQuotaAutoPingTick, configureQuotaAutoPing } = await import("../../src/shared/services/quotaAutoPing.js"));
|
||||
|
||||
deps = {
|
||||
getSettings: vi.fn(),
|
||||
@@ -117,6 +119,25 @@ describe("quota auto-ping", () => {
|
||||
expect(deps.proxyAwareFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("starts the scheduler only when an account opts in", () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
configureQuotaAutoPing({ codexAutoPing: { connections: {} } });
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
|
||||
configureQuotaAutoPing({ codexAutoPing: { connections: { "codex-1": true } } });
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
});
|
||||
|
||||
it("stops the scheduler when the last account opts out", () => {
|
||||
vi.useFakeTimers();
|
||||
configureQuotaAutoPing({ claudeAutoPing: { connections: { "claude-1": true } } });
|
||||
|
||||
configureQuotaAutoPing({ claudeAutoPing: { connections: { "claude-1": false } } });
|
||||
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("does not ping Codex on the first resetAt observation", async () => {
|
||||
deps.getSettings.mockResolvedValue({ codexAutoPing: { connections: { "codex-1": true } } });
|
||||
deps.getProviderConnections.mockImplementation(async ({ provider }) => (
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
// A2: locks resolveSessionId priority/stickiness (codex/kiro/antigravity centralization).
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { resolveSessionId, deriveSessionId, clearSessionStore } from "../../open-sse/utils/sessionManager.js";
|
||||
import { resolveContinuationId, resolveSessionId, resolveSessionIdentity, deriveSessionId, clearSessionStore } from "../../open-sse/utils/sessionManager.js";
|
||||
|
||||
// Assistant text must reach ASSISTANT_MIN_LEN (80) to use assistant anchor; else first user message.
|
||||
const longAssistant = "x".repeat(80);
|
||||
const bodyWithAssistant = { messages: [{ role: "assistant", content: longAssistant }] };
|
||||
const bodyWithUserOnly = { messages: [{ role: "user", content: "hello from first user message anchor" }] };
|
||||
|
||||
beforeEach(() => clearSessionStore());
|
||||
beforeEach(() => {
|
||||
clearSessionStore();
|
||||
});
|
||||
|
||||
describe("resolveSessionId", () => {
|
||||
it("stickiness: same body+connectionId+scope -> same id", () => {
|
||||
@@ -55,8 +57,170 @@ describe("resolveSessionId", () => {
|
||||
expect(got).toBe("client-sess-123");
|
||||
});
|
||||
|
||||
it("does not treat request-scoped x-client-request-id as a session override", () => {
|
||||
const first = resolveSessionId({
|
||||
headers: { "x-client-request-id": "req-1" },
|
||||
body: bodyWithUserOnly,
|
||||
connectionId: "conn1",
|
||||
scope: "kiro",
|
||||
});
|
||||
const second = resolveSessionId({
|
||||
headers: { "x-client-request-id": "req-2" },
|
||||
body: bodyWithUserOnly,
|
||||
connectionId: "conn1",
|
||||
scope: "kiro",
|
||||
});
|
||||
|
||||
expect(first).not.toBe("req-1");
|
||||
expect(second).not.toBe("req-2");
|
||||
expect(first).not.toBe(second);
|
||||
});
|
||||
|
||||
it("does not treat request-scoped previous_response_id as a Kiro session override", () => {
|
||||
const first = resolveSessionId({
|
||||
body: { ...bodyWithUserOnly, previous_response_id: "resp-1" },
|
||||
connectionId: "conn1",
|
||||
scope: "kiro",
|
||||
});
|
||||
const second = resolveSessionId({
|
||||
body: { ...bodyWithUserOnly, previous_response_id: "resp-2" },
|
||||
connectionId: "conn1",
|
||||
scope: "kiro",
|
||||
});
|
||||
|
||||
expect(first).not.toBe("resp-1");
|
||||
expect(second).not.toBe("resp-2");
|
||||
expect(first).not.toBe(second);
|
||||
});
|
||||
|
||||
it("does not treat raw metadata.user_id as a Kiro conversation session", () => {
|
||||
const first = resolveSessionId({
|
||||
body: {
|
||||
metadata: { user_id: "user-123" },
|
||||
messages: [{ role: "user", content: "new chat about invoices" }],
|
||||
},
|
||||
connectionId: "conn1",
|
||||
scope: "kiro",
|
||||
});
|
||||
const second = resolveSessionId({
|
||||
body: {
|
||||
metadata: { user_id: "user-123" },
|
||||
messages: [{ role: "user", content: "unrelated new chat about refunds" }],
|
||||
},
|
||||
connectionId: "conn1",
|
||||
scope: "kiro",
|
||||
});
|
||||
|
||||
expect(first).not.toBe("user-123");
|
||||
expect(second).not.toBe("user-123");
|
||||
expect(first).not.toBe(second);
|
||||
});
|
||||
|
||||
it("keeps Claude Code session_id metadata as a Kiro conversation session", () => {
|
||||
const body = {
|
||||
metadata: { user_id: JSON.stringify({ session_id: "claude-code-session-123" }) },
|
||||
messages: [{ role: "user", content: "same Claude Code session" }],
|
||||
};
|
||||
|
||||
expect(resolveSessionId({ body, connectionId: "conn1", scope: "kiro" })).toBe("claude:claude-code-session-123");
|
||||
});
|
||||
|
||||
it("keeps raw metadata.user_id as a non-Kiro session fallback", () => {
|
||||
const got = resolveSessionId({
|
||||
body: {
|
||||
metadata: { user_id: "user-123" },
|
||||
messages: [{ role: "user", content: "non-Kiro provider" }],
|
||||
},
|
||||
connectionId: "conn1",
|
||||
scope: "codex",
|
||||
});
|
||||
|
||||
expect(got).toBe("user-123");
|
||||
});
|
||||
|
||||
it("keeps x-client-request-id as a session override outside Kiro scope", () => {
|
||||
const got = resolveSessionId({
|
||||
headers: { "x-client-request-id": "req-1" },
|
||||
body: bodyWithAssistant,
|
||||
connectionId: "conn1",
|
||||
scope: "codex",
|
||||
});
|
||||
|
||||
expect(got).toBe("req-1");
|
||||
});
|
||||
|
||||
|
||||
it("workspaceId path: empty body + workspaceId set -> normalized workspaceId", () => {
|
||||
const got = resolveSessionId({ body: {}, connectionId: "conn1", workspaceId: "ws-abc" });
|
||||
expect(got).toBe("ws-abc");
|
||||
});
|
||||
|
||||
it("uses fresh Kiro sessions for unrelated headerless requests on the same connection", () => {
|
||||
const a = resolveSessionId({ body: bodyWithUserOnly, connectionId: "conn1", scope: "kiro" });
|
||||
const b = resolveSessionId({ body: bodyWithUserOnly, connectionId: "conn1", scope: "kiro" });
|
||||
expect(a).not.toBe(b);
|
||||
});
|
||||
|
||||
it("marks generated headerless Kiro sessions as ephemeral", () => {
|
||||
const generated = resolveSessionIdentity({ body: bodyWithUserOnly, connectionId: "conn1", scope: "kiro" });
|
||||
const explicit = resolveSessionIdentity({
|
||||
headers: { "x-session-id": "client-sess-123" },
|
||||
body: bodyWithUserOnly,
|
||||
connectionId: "conn1",
|
||||
scope: "kiro",
|
||||
});
|
||||
|
||||
expect(generated.ephemeral).toBe(true);
|
||||
expect(explicit).toEqual({ sessionId: "client-sess-123", ephemeral: false });
|
||||
});
|
||||
|
||||
it("does not switch Kiro headerless requests to assistant-text session ids mid-conversation", () => {
|
||||
const withAssistant = { messages: [{ role: "user", content: "same user" }, { role: "assistant", content: "y".repeat(80) }] };
|
||||
const a = resolveSessionId({ body: withAssistant, connectionId: "conn1", scope: "kiro" });
|
||||
const b = resolveSessionId({ body: withAssistant, connectionId: "conn1", scope: "kiro" });
|
||||
expect(a).not.toBe(b);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveContinuationId", () => {
|
||||
it("keeps continuation id stable for the same Kiro session", () => {
|
||||
const opts = { sessionId: "kiro-session-1", connectionId: "conn1", scope: "kiro" };
|
||||
expect(resolveContinuationId(opts)).toBe(resolveContinuationId(opts));
|
||||
});
|
||||
|
||||
it("uses a different continuation id for a different Kiro session", () => {
|
||||
const a = resolveContinuationId({ sessionId: "kiro-session-1", connectionId: "conn1", scope: "kiro" });
|
||||
const b = resolveContinuationId({ sessionId: "kiro-session-2", connectionId: "conn1", scope: "kiro" });
|
||||
expect(a).not.toBe(b);
|
||||
});
|
||||
|
||||
it("does not evict a recently used continuation id when the store exceeds its cap", () => {
|
||||
const first = resolveContinuationId({ sessionId: "kiro-session-0", connectionId: "conn1", scope: "kiro" });
|
||||
for (let i = 1; i < 5000; i++) {
|
||||
resolveContinuationId({ sessionId: `kiro-session-${i}`, connectionId: "conn1", scope: "kiro" });
|
||||
}
|
||||
expect(resolveContinuationId({ sessionId: "kiro-session-0", connectionId: "conn1", scope: "kiro" })).toBe(first);
|
||||
resolveContinuationId({ sessionId: "kiro-session-5000", connectionId: "conn1", scope: "kiro" });
|
||||
|
||||
expect(resolveContinuationId({ sessionId: "kiro-session-0", connectionId: "conn1", scope: "kiro" })).toBe(first);
|
||||
});
|
||||
|
||||
it("evicts old continuation ids when the store exceeds its cap", () => {
|
||||
const first = resolveContinuationId({ sessionId: "kiro-session-0", connectionId: "conn1", scope: "kiro" });
|
||||
for (let i = 1; i <= 5000; i++) {
|
||||
resolveContinuationId({ sessionId: `kiro-session-${i}`, connectionId: "conn1", scope: "kiro" });
|
||||
}
|
||||
|
||||
const afterEviction = resolveContinuationId({ sessionId: "kiro-session-0", connectionId: "conn1", scope: "kiro" });
|
||||
expect(afterEviction).not.toBe(first);
|
||||
});
|
||||
|
||||
it("does not let ephemeral Kiro continuations evict explicit session continuations", () => {
|
||||
const stable = resolveContinuationId({ sessionId: "explicit-session", connectionId: "conn1", scope: "kiro" });
|
||||
for (let i = 0; i <= 5000; i++) {
|
||||
resolveContinuationId({ sessionId: `ephemeral-session-${i}`, connectionId: "conn1", scope: "kiro", ephemeral: true });
|
||||
}
|
||||
|
||||
expect(resolveContinuationId({ sessionId: "explicit-session", connectionId: "conn1", scope: "kiro" })).toBe(stable);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* Unit tests for the xAI video proxy core (open-sse/handlers/videoCore.js)
|
||||
*
|
||||
* Covers:
|
||||
* - registry wiring (videoConfig, grok-imagine-video kind)
|
||||
* - byte-exact body forwarding (JSON + multipart)
|
||||
* - request_id / polling-status passthrough (pending, processing, done, failed)
|
||||
* - 401 → refresh once → retry once; refresh failure → no retry loop
|
||||
* - no auto-retry of creation POSTs on network error
|
||||
* - upstream error propagation with secret sanitization
|
||||
* - abort/cancellation
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
vi.mock("open-sse/services/tokenRefresh.js", () => ({
|
||||
refreshTokenByProvider: vi.fn(),
|
||||
}));
|
||||
|
||||
import { handleVideoProxyCore, getVideoConfig, sanitizeSecrets, VIDEO_ACTIONS } from "open-sse/handlers/videoCore.js";
|
||||
import { refreshTokenByProvider } from "open-sse/services/tokenRefresh.js";
|
||||
import { PROVIDER_MEDIA, PROVIDER_MODELS } from "open-sse/providers/index.js";
|
||||
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
const jsonResponse = (body, status = 200) =>
|
||||
new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
|
||||
|
||||
describe("registry wiring", () => {
|
||||
it("exposes videoConfig for xai", () => {
|
||||
expect(getVideoConfig("xai")).toEqual({ baseUrl: "https://api.x.ai/v1/videos" });
|
||||
expect(PROVIDER_MEDIA.xai.serviceKinds).toContain("video");
|
||||
});
|
||||
|
||||
it("registers grok-imagine-video with kind video (kept out of LLM lists)", () => {
|
||||
const model = PROVIDER_MODELS.xai.find((m) => m.id === "grok-imagine-video");
|
||||
expect(model).toBeTruthy();
|
||||
expect(model.kind || model.type).toBe("video");
|
||||
});
|
||||
|
||||
it("supports exactly the three creation actions", () => {
|
||||
expect([...VIDEO_ACTIONS].sort()).toEqual(["edits", "extensions", "generations"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleVideoProxyCore", () => {
|
||||
beforeEach(() => {
|
||||
global.fetch = vi.fn();
|
||||
refreshTokenByProvider.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
});
|
||||
|
||||
it("rejects providers without videoConfig", async () => {
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "openai",
|
||||
action: "generations",
|
||||
rawBody: "{}",
|
||||
credentials: { apiKey: "k" },
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toContain("does not support video generation");
|
||||
});
|
||||
|
||||
it("forwards a creation POST byte-for-byte and passes request_id through", async () => {
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ request_id: "req-123" }));
|
||||
|
||||
const raw = '{"model":"grok-imagine-video","prompt":"neon city","duration":8}';
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
action: "generations",
|
||||
rawBody: raw,
|
||||
contentType: "application/json",
|
||||
idempotencyKey: "idem-1",
|
||||
credentials: { accessToken: "tok-A", refreshToken: "ref-A" },
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
const [url, init] = global.fetch.mock.calls[0];
|
||||
expect(url).toBe("https://api.x.ai/v1/videos/generations");
|
||||
expect(init.method).toBe("POST");
|
||||
expect(init.body).toBe(raw); // byte-exact, no reshaping
|
||||
expect(init.headers.Authorization).toBe("Bearer tok-A");
|
||||
expect(init.headers["Content-Type"]).toBe("application/json");
|
||||
expect(init.headers["Idempotency-Key"]).toBe("idem-1");
|
||||
|
||||
expect(await result.response.json()).toEqual({ request_id: "req-123" });
|
||||
});
|
||||
|
||||
it("forwards multipart bodies untouched with the original boundary header", async () => {
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ request_id: "req-mp" }));
|
||||
|
||||
const boundary = "----vitestBoundary42";
|
||||
const multipartBody = Buffer.from(
|
||||
`--${boundary}\r\nContent-Disposition: form-data; name="prompt"\r\n\r\nextend it\r\n--${boundary}--\r\n`
|
||||
);
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
action: "extensions",
|
||||
rawBody: multipartBody,
|
||||
contentType: `multipart/form-data; boundary=${boundary}`,
|
||||
credentials: { apiKey: "xai-key" },
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
const [url, init] = global.fetch.mock.calls[0];
|
||||
expect(url).toBe("https://api.x.ai/v1/videos/extensions");
|
||||
expect(init.body).toBe(multipartBody); // same Buffer, no re-encode
|
||||
expect(init.headers["Content-Type"]).toBe(`multipart/form-data; boundary=${boundary}`);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["pending", { status: "pending", progress: 10 }],
|
||||
["processing", { status: "processing", progress: 55 }],
|
||||
["done", { status: "done", video: { url: "https://cdn.x.ai/v.mp4", duration: 8 } }],
|
||||
])("passes %s polling payload through verbatim", async (_label, payload) => {
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse(payload));
|
||||
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
requestId: "req-123",
|
||||
credentials: { accessToken: "tok" },
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
const [url, init] = global.fetch.mock.calls[0];
|
||||
expect(url).toBe("https://api.x.ai/v1/videos/req-123");
|
||||
expect(init.method).toBe("GET");
|
||||
expect(await result.response.json()).toEqual(payload);
|
||||
});
|
||||
|
||||
it("passes a failed job (HTTP 200, status failed) through without translating", async () => {
|
||||
const payload = { status: "failed", error: { code: "internal_error", message: "render crashed" } };
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse(payload));
|
||||
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
requestId: "req-bad",
|
||||
credentials: { accessToken: "tok" },
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(await result.response.json()).toEqual(payload);
|
||||
});
|
||||
|
||||
it("url-encodes the request id when polling", async () => {
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ status: "pending" }));
|
||||
await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
requestId: "id with/slash",
|
||||
credentials: { accessToken: "tok" },
|
||||
});
|
||||
expect(global.fetch.mock.calls[0][0]).toBe("https://api.x.ai/v1/videos/id%20with%2Fslash");
|
||||
});
|
||||
|
||||
it("401 → refreshes once and retries once with the new token", async () => {
|
||||
global.fetch
|
||||
.mockResolvedValueOnce(jsonResponse({ error: "expired" }, 401))
|
||||
.mockResolvedValueOnce(jsonResponse({ request_id: "req-after-refresh" }));
|
||||
refreshTokenByProvider.mockResolvedValueOnce({ accessToken: "tok-NEW", refreshToken: "ref-NEW" });
|
||||
|
||||
const credentials = { accessToken: "tok-OLD", refreshToken: "ref-OLD" };
|
||||
const onCredentialsRefreshed = vi.fn();
|
||||
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
action: "generations",
|
||||
rawBody: '{"prompt":"x"}',
|
||||
contentType: "application/json",
|
||||
credentials,
|
||||
onCredentialsRefreshed,
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(refreshTokenByProvider).toHaveBeenCalledTimes(1);
|
||||
expect(global.fetch).toHaveBeenCalledTimes(2);
|
||||
expect(global.fetch.mock.calls[1][1].headers.Authorization).toBe("Bearer tok-NEW");
|
||||
expect(onCredentialsRefreshed).toHaveBeenCalledWith(expect.objectContaining({ accessToken: "tok-NEW" }));
|
||||
expect(await result.response.json()).toEqual({ request_id: "req-after-refresh" });
|
||||
});
|
||||
|
||||
it("401 twice → still only one refresh and one retry (no loop)", async () => {
|
||||
global.fetch
|
||||
.mockResolvedValueOnce(jsonResponse({ error: "expired" }, 401))
|
||||
.mockResolvedValueOnce(jsonResponse({ error: "still expired" }, 401));
|
||||
refreshTokenByProvider.mockResolvedValueOnce({ accessToken: "tok-NEW" });
|
||||
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
action: "generations",
|
||||
rawBody: "{}",
|
||||
credentials: { accessToken: "tok-OLD", refreshToken: "ref" },
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.status).toBe(401);
|
||||
expect(refreshTokenByProvider).toHaveBeenCalledTimes(1);
|
||||
expect(global.fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("failed refresh → 401 propagates with a single upstream call (account flagged for re-auth upstream)", async () => {
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ error: "expired" }, 401));
|
||||
refreshTokenByProvider.mockResolvedValueOnce(null);
|
||||
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
action: "generations",
|
||||
rawBody: "{}",
|
||||
credentials: { accessToken: "tok-OLD", refreshToken: "ref" },
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.status).toBe(401);
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("API-key accounts (no refreshToken) never attempt refresh on 401", async () => {
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ error: "bad key" }, 401));
|
||||
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
action: "generations",
|
||||
rawBody: "{}",
|
||||
credentials: { apiKey: "xai-key" },
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(refreshTokenByProvider).not.toHaveBeenCalled();
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("never re-sends a creation POST after a network error", async () => {
|
||||
global.fetch.mockRejectedValueOnce(new Error("socket hang up"));
|
||||
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
action: "generations",
|
||||
rawBody: "{}",
|
||||
credentials: { accessToken: "tok", refreshToken: "ref" },
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.status).toBe(502);
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("sanitizes bearer tokens and credential values out of upstream errors", async () => {
|
||||
global.fetch.mockResolvedValueOnce(
|
||||
jsonResponse({ error: "denied for Bearer sk-secret-token-value-123456 (token tok-SECRETSECRET)" }, 403)
|
||||
);
|
||||
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
action: "generations",
|
||||
rawBody: "{}",
|
||||
credentials: { apiKey: "tok-SECRETSECRET" },
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).not.toContain("sk-secret-token-value-123456");
|
||||
expect(result.error).not.toContain("tok-SECRETSECRET");
|
||||
expect(result.error).toContain("[redacted]");
|
||||
});
|
||||
|
||||
it("maps client aborts to 408 without retrying", async () => {
|
||||
const abortError = new Error("This operation was aborted");
|
||||
abortError.name = "AbortError";
|
||||
global.fetch.mockRejectedValueOnce(abortError);
|
||||
|
||||
const result = await handleVideoProxyCore({
|
||||
provider: "xai",
|
||||
action: "generations",
|
||||
rawBody: "{}",
|
||||
credentials: { accessToken: "tok" },
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.status).toBe(408);
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sanitizeSecrets", () => {
|
||||
it("redacts bearer tokens", () => {
|
||||
expect(sanitizeSecrets("Authorization: Bearer abc.def-ghi_jkl")).not.toContain("abc.def-ghi_jkl");
|
||||
});
|
||||
|
||||
it("redacts explicit credential values", () => {
|
||||
const creds = { accessToken: "supersecretaccess", refreshToken: "supersecretrefresh" };
|
||||
const out = sanitizeSecrets("leak supersecretaccess and supersecretrefresh", creds);
|
||||
expect(out).toBe("leak [redacted] and [redacted]");
|
||||
});
|
||||
|
||||
it("leaves normal text untouched", () => {
|
||||
expect(sanitizeSecrets("video render failed: invalid_argument")).toBe("video render failed: invalid_argument");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,221 @@
|
||||
/**
|
||||
* Unit tests for the app-side video handler (src/sse/handlers/videoGeneration.js)
|
||||
*
|
||||
* Covers:
|
||||
* - `xai/` model prefix stripping before the body is forwarded upstream
|
||||
* - byte-exact forwarding when no prefix rewrite is needed
|
||||
* - multi-account selection (preferred connection id, rotation on 401)
|
||||
* - NO rotation on 5xx creation errors (a job may already exist upstream)
|
||||
* - connection id surfaced via x-9router-connection-id
|
||||
* - GET polling pinned to x-connection-id, no rotation
|
||||
* - refresh failure recorded via markAccountUnavailable (dashboard re-auth signal)
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
const authMocks = vi.hoisted(() => ({
|
||||
getProviderCredentials: vi.fn(),
|
||||
markAccountUnavailable: vi.fn(async () => ({ shouldFallback: true, cooldownMs: 0 })),
|
||||
clearAccountError: vi.fn(async () => {}),
|
||||
extractApiKey: vi.fn(() => null),
|
||||
isValidApiKey: vi.fn(async () => true),
|
||||
}));
|
||||
const tokenMocks = vi.hoisted(() => ({
|
||||
checkAndRefreshToken: vi.fn(async (_p, creds) => creds),
|
||||
updateProviderCredentials: vi.fn(async () => {}),
|
||||
}));
|
||||
|
||||
vi.mock("@/sse/services/auth.js", () => authMocks);
|
||||
vi.mock("@/sse/services/tokenRefresh.js", () => tokenMocks);
|
||||
vi.mock("@/lib/localDb", () => ({
|
||||
getSettings: vi.fn(async () => ({ requireApiKey: false })),
|
||||
getComboByName: vi.fn(async () => null),
|
||||
getModelAliases: vi.fn(async () => ({})),
|
||||
getProviderNodes: vi.fn(async () => []),
|
||||
}));
|
||||
vi.mock("@/sse/utils/logger.js", () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }));
|
||||
|
||||
import { handleVideoCreate, handleVideoGet } from "@/sse/handlers/videoGeneration.js";
|
||||
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
const jsonResponse = (body, status = 200) =>
|
||||
new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
|
||||
|
||||
const makeRequest = (body, { headers = {}, contentType = "application/json" } = {}) =>
|
||||
new Request("http://localhost/v1/videos/generations", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": contentType, ...headers },
|
||||
body: typeof body === "string" ? body : JSON.stringify(body),
|
||||
});
|
||||
|
||||
const account = (overrides = {}) => ({
|
||||
connectionId: "conn-1",
|
||||
accessToken: "tok-1",
|
||||
refreshToken: "ref-1",
|
||||
authType: "oauth",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
global.fetch = vi.fn();
|
||||
authMocks.getProviderCredentials.mockReset();
|
||||
authMocks.markAccountUnavailable.mockClear();
|
||||
authMocks.clearAccountError.mockClear();
|
||||
tokenMocks.checkAndRefreshToken.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
});
|
||||
|
||||
describe("handleVideoCreate", () => {
|
||||
it("strips the xai/ prefix from model before forwarding", async () => {
|
||||
authMocks.getProviderCredentials.mockResolvedValueOnce(account());
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ request_id: "r1" }));
|
||||
|
||||
const res = await handleVideoCreate(
|
||||
makeRequest({ model: "xai/grok-imagine-video", prompt: "a cat" }),
|
||||
"generations"
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const forwarded = JSON.parse(global.fetch.mock.calls[0][1].body);
|
||||
expect(forwarded.model).toBe("grok-imagine-video");
|
||||
expect(forwarded.prompt).toBe("a cat");
|
||||
});
|
||||
|
||||
it("forwards the original raw JSON bytes when no rewrite is needed", async () => {
|
||||
authMocks.getProviderCredentials.mockResolvedValueOnce(account());
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ request_id: "r1" }));
|
||||
|
||||
// Odd spacing survives only if we forward the raw string untouched
|
||||
const raw = '{ "model" : "grok-imagine-video", "prompt" : "spaced" }';
|
||||
await handleVideoCreate(makeRequest(raw), "generations");
|
||||
|
||||
expect(global.fetch.mock.calls[0][1].body).toBe(raw);
|
||||
});
|
||||
|
||||
it("rejects providers without video support", async () => {
|
||||
const res = await handleVideoCreate(
|
||||
makeRequest({ model: "openai/sora-alike", prompt: "x" }),
|
||||
"generations"
|
||||
);
|
||||
expect(res.status).toBe(400);
|
||||
expect(await res.text()).toContain("does not support video generation");
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns the serving connection id in x-9router-connection-id", async () => {
|
||||
authMocks.getProviderCredentials.mockResolvedValueOnce(account({ connectionId: "conn-77" }));
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ request_id: "r1" }));
|
||||
|
||||
const res = await handleVideoCreate(makeRequest({ prompt: "x" }), "generations");
|
||||
expect(res.headers.get("x-9router-connection-id")).toBe("conn-77");
|
||||
expect(await res.json()).toEqual({ request_id: "r1" });
|
||||
});
|
||||
|
||||
it("honors preferred x-connection-id when selecting the account", async () => {
|
||||
authMocks.getProviderCredentials.mockResolvedValueOnce(account());
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ request_id: "r1" }));
|
||||
|
||||
await handleVideoCreate(
|
||||
makeRequest({ prompt: "x" }, { headers: { "x-connection-id": "conn-9" } }),
|
||||
"generations"
|
||||
);
|
||||
|
||||
expect(authMocks.getProviderCredentials).toHaveBeenCalledWith(
|
||||
"xai", expect.anything(), null, expect.objectContaining({ preferredConnectionId: "conn-9" })
|
||||
);
|
||||
});
|
||||
|
||||
it("rotates to the next account on 401 (auth errors cannot have created a job)", async () => {
|
||||
authMocks.getProviderCredentials
|
||||
.mockResolvedValueOnce(account({ connectionId: "conn-1", refreshToken: null }))
|
||||
.mockResolvedValueOnce(account({ connectionId: "conn-2", accessToken: "tok-2", refreshToken: null }));
|
||||
global.fetch
|
||||
.mockResolvedValueOnce(jsonResponse({ error: "unauthorized" }, 401))
|
||||
.mockResolvedValueOnce(jsonResponse({ request_id: "r2" }));
|
||||
|
||||
const res = await handleVideoCreate(makeRequest({ prompt: "x" }), "generations");
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("x-9router-connection-id")).toBe("conn-2");
|
||||
expect(authMocks.markAccountUnavailable).toHaveBeenCalledWith(
|
||||
"conn-1", 401, expect.any(String), "xai", null
|
||||
);
|
||||
});
|
||||
|
||||
it("does NOT rotate accounts on a 500 creation error (job may exist upstream)", async () => {
|
||||
authMocks.getProviderCredentials.mockResolvedValueOnce(account({ refreshToken: null }));
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ error: "boom" }, 500));
|
||||
|
||||
const res = await handleVideoCreate(makeRequest({ prompt: "x" }), "generations");
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
expect(authMocks.getProviderCredentials).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("forwards multipart bodies byte-exact with default xai provider", async () => {
|
||||
authMocks.getProviderCredentials.mockResolvedValueOnce(account());
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ request_id: "r-mp" }));
|
||||
|
||||
const boundary = "----handlerBoundary";
|
||||
const raw = `--${boundary}\r\nContent-Disposition: form-data; name="prompt"\r\n\r\nedit\r\n--${boundary}--\r\n`;
|
||||
const req = new Request("http://localhost/v1/videos/edits", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": `multipart/form-data; boundary=${boundary}` },
|
||||
body: raw,
|
||||
});
|
||||
|
||||
const res = await handleVideoCreate(req, "edits");
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
const [url, init] = global.fetch.mock.calls[0];
|
||||
expect(url).toBe("https://api.x.ai/v1/videos/edits");
|
||||
expect(Buffer.from(init.body).toString()).toBe(raw);
|
||||
expect(init.headers["Content-Type"]).toContain(boundary);
|
||||
});
|
||||
|
||||
it("returns 400 when no credentials are connected", async () => {
|
||||
authMocks.getProviderCredentials.mockResolvedValueOnce(null);
|
||||
const res = await handleVideoCreate(makeRequest({ prompt: "x" }), "generations");
|
||||
expect(res.status).toBe(400);
|
||||
expect(await res.text()).toContain("No credentials for provider: xai");
|
||||
});
|
||||
|
||||
it("returns 400 on invalid JSON", async () => {
|
||||
const res = await handleVideoCreate(makeRequest("{not json"), "generations");
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleVideoGet", () => {
|
||||
it("polls upstream pinned to the x-connection-id account and passes status through", async () => {
|
||||
authMocks.getProviderCredentials.mockResolvedValueOnce(account({ connectionId: "conn-5" }));
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ status: "pending", progress: 42 }));
|
||||
|
||||
const req = new Request("http://localhost/v1/videos/req-1", {
|
||||
headers: { "x-connection-id": "conn-5" },
|
||||
});
|
||||
const res = await handleVideoGet(req, "req-1");
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ status: "pending", progress: 42 });
|
||||
expect(authMocks.getProviderCredentials).toHaveBeenCalledWith(
|
||||
"xai", null, null, expect.objectContaining({ preferredConnectionId: "conn-5" })
|
||||
);
|
||||
expect(global.fetch.mock.calls[0][0]).toBe("https://api.x.ai/v1/videos/req-1");
|
||||
});
|
||||
|
||||
it("records the failure when polling hits a terminal auth error", async () => {
|
||||
authMocks.getProviderCredentials.mockResolvedValueOnce(account({ refreshToken: null }));
|
||||
global.fetch.mockResolvedValueOnce(jsonResponse({ error: "unauthorized" }, 401));
|
||||
|
||||
const res = await handleVideoGet(new Request("http://localhost/v1/videos/req-1"), "req-1");
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(authMocks.markAccountUnavailable).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user