merge origin/master into gitea/new_feature

Bring local branch up to v0.5.35 while keeping xAI image/edit, SuperGrok
quota tracking, per-provider timeouts, and pinned model-test actions.
This commit is contained in:
2026-07-17 15:31:47 +07:00
224 changed files with 21037 additions and 1643 deletions

View File

@@ -66,6 +66,10 @@
"vertex-partner": "vertex-partner",
"gw": "grok-web",
"grok-web": "grok-web",
"gcli": "grok-cli",
"gb": "grok-cli",
"grok-build": "grok-cli",
"grok-cli": "grok-cli",
"pw": "perplexity-web",
"perplexity-web": "perplexity-web",
"mimo": "xiaomi-mimo",
@@ -104,6 +108,7 @@
"chutes": "chutes",
"claude": "cc",
"cline": "cl",
"clinepass": "clinepass",
"cloudflare-ai": "cloudflare-ai",
"codebuddy-cn": "cbcn",
"codex": "cx",
@@ -119,11 +124,13 @@
"gitlab": "gitlab",
"glm": "glm",
"glm-cn": "glm-cn",
"grok-cli": "gcli",
"grok-web": "grok-web",
"groq": "groq",
"hyperbolic": "hyperbolic",
"iflow": "if",
"kilocode": "kc",
"kimchi": "kimchi",
"kimi": "kimi",
"kimi-coding": "kmc",
"kiro": "kr",
@@ -147,6 +154,7 @@
"qwen": "qw",
"siliconflow": "siliconflow",
"together": "together",
"venice": "venice",
"vercel-ai-gateway": "vercel-ai-gateway",
"vertex": "vertex",
"vertex-partner": "vertex-partner",
@@ -168,6 +176,7 @@
"cc",
"cerebras",
"cl",
"clinepass",
"cloudflare-ai",
"cohere",
"comfyui",
@@ -181,6 +190,7 @@
"fal-ai",
"fireworks",
"gc",
"gcli",
"gemini",
"gemini-tts-models",
"gemini-tts-voices",
@@ -194,6 +204,7 @@
"hyperbolic",
"if",
"kc",
"kimchi",
"kimi",
"kmc",
"kr",
@@ -224,6 +235,7 @@
"siliconflow",
"stability-ai",
"together",
"venice",
"vertex",
"vertex-partner",
"volcengine-ark",

View File

@@ -13,8 +13,8 @@
"auth": "https://api.anthropic.com/v1/oauth/authorize"
},
"qwen": {
"token": "https://qwen.ai/api/v1/oauth2/token",
"auth": "https://qwen.ai/api/v1/oauth2/device/code"
"token": "https://chat.qwen.ai/api/v1/oauth2/token",
"auth": "https://chat.qwen.ai/api/v1/oauth2/device/code"
},
"iflow": {
"token": "https://iflow.cn/oauth/token",
@@ -33,24 +33,25 @@
"iflow": "https://iflow.cn/oauth/token",
"kiro": "https://prod.us-east-1.auth.desktop.kiro.dev/refreshToken",
"xai": "https://auth.x.ai/oauth2/token",
"grok-cli": "https://auth.x.ai/oauth2/token",
"cline": "https://api.cline.bot/api/v1/auth/token",
"kimi-coding": "https://auth.kimi.com/api/oauth/token"
},
"authUrls": {
"qwen": "https://chat.qwen.ai/api/v1/oauth2/device/code",
"iflow": "https://iflow.cn/oauth",
"kiro": "https://prod.us-east-1.auth.desktop.kiro.dev"
},
"refreshUrls": {
"cline": "https://api.cline.bot/api/v1/auth/refresh",
"kimi-coding": "https://auth.kimi.com/api/oauth/token",
"xai": "https://auth.x.ai/oauth2/token"
"xai": "https://auth.x.ai/oauth2/token",
"grok-cli": "https://auth.x.ai/oauth2/token"
},
"clientIds": {
"claude": "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
"codex": "app_EMoamEEZ73f0CkXaXp7hrann",
"qwen": "f0304373b74a44d2b584a3fb70ca9e56",
"iflow": "10009311001",
"kimi-coding": "17e5f671-d194-4dfb-9706-5516cb48c098"
"kimi-coding": "17e5f671-d194-4dfb-9706-5516cb48c098",
"grok-cli": "b1a00492-073a-47ea-816f-4c329264a828"
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -16,7 +16,8 @@ const ALIAS_TOKENS = [
"mistral","pplx","perplexity","together","fireworks","cerebras","cohere","nvidia","nebius",
"siliconflow","hyp","hyperbolic","dg","deepgram","aai","assemblyai","nb","nanobanana","ch",
"chutes","ark","volcengine-ark","byteplus","bpm","cursor","vx","vertex","vxp","vertex-partner",
"gw","grok-web","pw","perplexity-web","mimo","xiaomi-mimo","xmtp","xiaomi-tokenplan","cf",
"gw","grok-web","gcli","gb","grok-build","grok-cli","pw","perplexity-web","mimo","xiaomi-mimo",
"xmtp","xiaomi-tokenplan","cf",
"cloudflare-ai","fal","fal-ai","stability","stability-ai","bfl","black-forest-labs","recraft",
"topaz","runway","runwayml","jina","jina-ai","polly","aws-polly","bb","blackbox",
];

View File

@@ -19,6 +19,8 @@ const resolved = {
iflow: PROVIDERS.iflow?.tokenUrl,
kiro: PROVIDERS.kiro?.tokenUrl,
xai: PROVIDERS.xai?.tokenUrl,
// Grok CLI injects oauth.tokenUrl onto PROVIDERS via OAUTH_INJECT_FIELDS
"grok-cli": PROVIDERS["grok-cli"]?.tokenUrl,
cline: PROVIDERS.cline?.tokenUrl,
"kimi-coding": PROVIDERS["kimi-coding"]?.tokenUrl,
},
@@ -31,6 +33,7 @@ const resolved = {
cline: PROVIDERS.cline?.refreshUrl,
"kimi-coding": PROVIDERS["kimi-coding"]?.refreshUrl,
xai: PROVIDERS.xai?.refreshUrl,
"grok-cli": PROVIDERS["grok-cli"]?.tokenUrl,
},
clientIds: {
claude: PROVIDERS.claude?.clientId,
@@ -38,6 +41,7 @@ const resolved = {
qwen: PROVIDERS.qwen?.clientId,
iflow: PROVIDERS.iflow?.clientId,
"kimi-coding": PROVIDERS["kimi-coding"]?.clientId,
"grok-cli": PROVIDERS["grok-cli"]?.clientId,
},
};
const current = JSON.parse(JSON.stringify(resolved));

View File

@@ -118,6 +118,9 @@ exports[`GOLDEN request: OpenAI → Claude > reasoning_effort → adaptive outpu
"type": "text",
},
],
"thinking": {
"type": "adaptive",
},
}
`;

View File

@@ -4,6 +4,8 @@ import "./registerAll.js";
import { translateRequest, translateResponse, initState } from "../../open-sse/translator/index.js";
import { FORMATS } from "../../open-sse/translator/formats.js";
import { AntigravityExecutor } from "../../open-sse/executors/antigravity.js";
import { openaiToAntigravityRequest } from "../../open-sse/translator/request/openai-to-gemini.js";
import { ANTIGRAVITY_DEFAULT_SYSTEM } from "../../open-sse/config/appConstants.js";
const AG2O = (req) =>
translateRequest(FORMATS.ANTIGRAVITY, FORMATS.OPENAI, "m", { request: req }, true, null, null);
@@ -106,4 +108,32 @@ describe("Antigravity executor", () => {
const query = out.request.tools[0].functionDeclarations[0].parameters.properties.query;
expect(query).toEqual({ type: "string", description: "Search query" });
});
it("does not inject the legacy Antigravity default system prompt for Gemini-backed models", () => {
const out = openaiToAntigravityRequest("gemini-3.5-flash-low", {
messages: [
{ role: "system", content: "USER_SYSTEM_PROMPT" },
{ role: "user", content: "hello" },
],
}, true, { projectId: "project-1", connectionId: "conn-1" });
const system = JSON.stringify(out.request.systemInstruction);
expect(system).toContain("USER_SYSTEM_PROMPT");
expect(system).not.toContain(ANTIGRAVITY_DEFAULT_SYSTEM);
expect(system).not.toContain("Please ignore the following [ignore]");
});
it("does not inject the legacy Antigravity default system prompt for Claude-backed models", () => {
const out = openaiToAntigravityRequest("claude-opus-4-6-thinking", {
messages: [
{ role: "system", content: "USER_SYSTEM_PROMPT" },
{ role: "user", content: "hello" },
],
}, true, { projectId: "project-1", connectionId: "conn-1" });
const system = JSON.stringify(out.request.systemInstruction);
expect(system).toContain("USER_SYSTEM_PROMPT");
expect(system).not.toContain(ANTIGRAVITY_DEFAULT_SYSTEM);
expect(system).not.toContain("Please ignore the following [ignore]");
});
});

View File

@@ -46,6 +46,20 @@ describe("Codex CLI Responses → OpenAI", () => {
});
describe("OpenAI → Codex Responses (reverse)", () => {
it("maps developer messages to Responses API instructions", () => {
const out = O2R({
messages: [
{ role: "developer", content: "Follow the project rules." },
{ role: "user", content: "Hello" },
],
});
expect(out.instructions).toBe("Follow the project rules.");
expect(out.input).toEqual([
{ type: "message", role: "user", content: [{ type: "input_text", text: "Hello" }] },
]);
});
// openai-responses.js:13 — clampCallId NOT applied on Responses→Chat; but here Chat→Responses must clamp
it("call_id longer than 64 chars is clamped", () => {
const longId = "call_" + "x".repeat(80);

View File

@@ -67,6 +67,101 @@ describe("OpenAI → Claude context mapping", () => {
expect(JSON.stringify(out), "remote image dropped").toContain("pic.png");
});
// prepareClaudeRequest reconciles max_tokens vs thinking.budget_tokens.
// applyThinking runs after adjustMaxTokens caps max_tokens, so a claude-budget
// model at "max" effort (budget 128000) can exceed the clamped max_tokens and
// trip Anthropic's "max_tokens > budget_tokens" rule (400). See claude.js.
describe("max_tokens vs thinking.budget_tokens reconciliation", () => {
// 64k-ceiling model (maxOutput 64000) + max-effort budget 128000: budget alone
// exceeds the ceiling → cap max_tokens at 64000 and shrink budget below it.
it("max effort budget on a 64k model → budget < max_tokens ≤ 64000", () => {
const out = prepareClaudeRequest({
model: "claude-opus-4-20250514",
max_tokens: 64000,
thinking: { type: "enabled", budget_tokens: 128000 },
messages: [{ role: "user", content: "q" }],
}, "anthropic");
expect(out.max_tokens).toBe(64000);
expect(out.thinking.budget_tokens).toBeLessThan(out.max_tokens);
expect(out.thinking.budget_tokens).toBeGreaterThan(0);
});
// Budget fits under the ceiling but exceeds a small client max_tokens →
// raise max_tokens to fit, preserving the requested thinking depth.
it("xhigh budget with a low client max_tokens → raise max_tokens, preserve budget", () => {
const out = prepareClaudeRequest({
model: "claude-opus-4-20250514",
max_tokens: 16000,
thinking: { type: "enabled", budget_tokens: 32768 },
messages: [{ role: "user", content: "q" }],
}, "anthropic");
expect(out.thinking.budget_tokens).toBe(32768);
expect(out.max_tokens).toBe(33792); // 32768 + 1024, under the 64000 ceiling
});
// Budget already below max_tokens → nothing to reconcile.
it("high budget under max_tokens → both unchanged", () => {
const out = prepareClaudeRequest({
model: "claude-opus-4-20250514",
max_tokens: 64000,
thinking: { type: "enabled", budget_tokens: 24576 },
messages: [{ role: "user", content: "q" }],
}, "anthropic");
expect(out.max_tokens).toBe(64000);
expect(out.thinking.budget_tokens).toBe(24576);
});
// Non-budget thinking shapes (adaptive / disabled) carry no budget_tokens →
// the reconciliation must never touch them.
it("adaptive thinking (no budget_tokens) is left untouched", () => {
const out = prepareClaudeRequest({
model: "claude-opus-4-20250514",
max_tokens: 64000,
thinking: { type: "adaptive" },
messages: [{ role: "user", content: "q" }],
}, "anthropic");
expect(out.max_tokens).toBe(64000);
expect(out.thinking).toEqual({ type: "adaptive" });
});
// Lifted ceiling: a claude-budget model whose caps declare maxOutput 128000
// (e.g. fable) may use the full budget at max effort instead of being pinned
// to the conservative 64000 default.
it("max effort budget on a 128k model → max_tokens up to 128000, budget preserved just under", () => {
const out = prepareClaudeRequest({
model: "claude-fable-5",
max_tokens: 64000,
thinking: { type: "enabled", budget_tokens: 128000 },
messages: [{ role: "user", content: "q" }],
}, "anthropic");
expect(out.max_tokens).toBe(128000);
expect(out.thinking.budget_tokens).toBe(126976); // 128000 - 1024
expect(out.thinking.budget_tokens).toBeLessThan(out.max_tokens);
});
// Regression: a default 64k-ceiling model still clamps an over-large client
// max_tokens down to 64000 (the lift is per-model, not global).
it("over-large client max_tokens on a 64k model is still clamped to 64000", () => {
const out = prepareClaudeRequest({
model: "claude-opus-4-20250514",
max_tokens: 120000,
messages: [{ role: "user", content: "q" }],
}, "anthropic");
expect(out.max_tokens).toBe(64000);
});
// Lifted ceiling for a 128k model: a large client max_tokens is now allowed
// through instead of being clamped to 64000.
it("large client max_tokens on a 128k model is allowed up to maxOutput", () => {
const out = prepareClaudeRequest({
model: "claude-fable-5",
max_tokens: 100000,
messages: [{ role: "user", content: "q" }],
}, "anthropic");
expect(out.max_tokens).toBe(100000);
});
});
it("DeepSeek Claude transport adds a thinking placeholder before tool_use in thinking mode", () => {
const out = prepareClaudeRequest({
model: "deepseek-v4-pro",

View File

@@ -6,8 +6,8 @@ import "./registerAll.js";
import { translateRequest, translateResponse } from "../../open-sse/translator/index.js";
import { FORMATS } from "../../open-sse/translator/formats.js";
const C2K = (body) =>
translateRequest(FORMATS.CLAUDE, FORMATS.KIRO, "claude-sonnet-4.5", body, true, null, "kiro");
const C2K = (body, credentials = null, model = "claude-sonnet-4.5") =>
translateRequest(FORMATS.CLAUDE, FORMATS.KIRO, model, body, true, credentials, "kiro");
describe("Claude → Kiro (direct route)", () => {
it("produces a Kiro conversationState payload", () => {
@@ -16,6 +16,27 @@ describe("Claude → Kiro (direct route)", () => {
expect(out.conversationState.currentMessage.userInputMessage.content).toContain("hello");
});
it("keeps conversationId stable from client session headers and replays frozen msg0", () => {
const credentials = {
rawHeaders: { "x-session-id": "hermes-session-123-claude-replay" },
connectionId: "kiro-account-1",
};
const first = C2K({ messages: [{ role: "user", content: "first" }] }, credentials);
const second = C2K({ messages: [{ role: "user", content: "second" }] }, credentials);
expect(first.conversationState.conversationId).toBe("hermes-session-123-claude-replay");
expect(second.conversationState.conversationId).toBe("hermes-session-123-claude-replay");
expect(first.conversationState.agentContinuationId).toBeTruthy();
expect(second.conversationState.agentContinuationId).toBe(first.conversationState.agentContinuationId);
expect(first.conversationState.agentTaskType).toBe("vibe");
expect(second.conversationState.history[0].userInputMessage.content).toBe(
first.conversationState.currentMessage.userInputMessage.content
);
expect(second.conversationState.history[0].userInputMessage.modelId).toBe("claude-sonnet-4.5");
expect(second.conversationState.currentMessage.userInputMessage.content).toContain("Current time");
expect(second.conversationState.currentMessage.userInputMessage.content).toContain("second");
});
it("guard 1: with no tools, a dangling tool_result is flattened to text (no structured ref)", () => {
// Client omitted `tools` but kept a tool_result after compaction.
const out = C2K({
@@ -60,20 +81,60 @@ describe("Claude → Kiro (direct route)", () => {
null,
"kiro"
);
expect(out.conversationState.currentMessage.userInputMessage.content).toContain(
expect(out.systemPrompt).toContain(
"<thinking_mode>enabled</thinking_mode>"
);
expect(out.agentMode).toBe("vibe");
});
it("maps output_config.effort high to Kiro max_thinking_length 24576", () => {
it("does not send additionalModelRequestFields for Kiro models without effort support", () => {
const out = C2K({
output_config: { effort: "high" },
messages: [{ role: "user", content: "think with adaptive effort" }],
});
expect(out.conversationState.currentMessage.userInputMessage.content).toContain(
"<max_thinking_length>24576</max_thinking_length>"
);
expect(out.additionalModelRequestFields).toBeUndefined();
expect(out.thinking).toBeUndefined();
expect(out.systemPrompt).toContain("<max_thinking_length>24576</max_thinking_length>");
});
it("maps output_config.effort high to Kiro CLI-style additionalModelRequestFields for effort models", () => {
const out = C2K({
output_config: { effort: "high" },
messages: [{ role: "user", content: "think with adaptive effort" }],
}, null, "claude-sonnet-5");
expect(out.additionalModelRequestFields).toEqual({
thinking: { type: "adaptive", display: "summarized" },
output_config: { effort: "high" },
});
expect(out.thinking).toBeUndefined();
expect(out.systemPrompt).toContain("<max_thinking_length>24576</max_thinking_length>");
});
it("sends Claude system as top-level systemPrompt and keeps a user-content fallback", () => {
const out = C2K({
system: "system-only instruction",
messages: [{ role: "user", content: "hello" }],
});
expect(out.systemPrompt).toContain("system-only instruction");
expect(out.conversationState.currentMessage.userInputMessage.content).toContain("system-only instruction");
});
it("keeps top-level systemPrompt stable across turns", () => {
const first = C2K({
system: "stable instruction",
messages: [{ role: "user", content: "first" }],
});
const second = C2K({
system: "stable instruction",
messages: [{ role: "user", content: "second" }],
});
expect(first.systemPrompt).toBe(second.systemPrompt);
expect(first.systemPrompt).not.toContain("Current time");
expect(first.conversationState.currentMessage.userInputMessage.content).toContain("Current time");
});
});

View File

@@ -54,6 +54,45 @@ describe("GOLDEN request: OpenAI → Gemini", () => {
const out = translateRequest(FORMATS.OPENAI, FORMATS.GEMINI, "gemini-3-pro", baseBody(), true, { apiKey: "k" }, "gemini");
expect(clean(out)).toMatchSnapshot();
});
it("Gemini CLI tool requests include validated toolConfig and enough output for high thinking", () => {
const body = {
messages: [{ role: "user", content: "Call add with 7 and 35." }],
tools: [
{
type: "function",
function: {
name: "add",
description: "Add two numbers",
parameters: {
type: "object",
properties: {
a: { type: "number" },
b: { type: "number" },
},
required: ["a", "b"],
},
},
},
],
reasoning_effort: "high",
max_tokens: 128,
};
const out = translateRequest(
FORMATS.OPENAI,
FORMATS.GEMINI_CLI,
"gemini-3.1-pro-preview",
body,
true,
{ accessToken: "t", projectId: "p" },
"gemini-cli"
);
expect(out.request.toolConfig).toEqual({ functionCallingConfig: { mode: "VALIDATED" } });
expect(out.request.safetySettings).toBeDefined();
expect(out.request.generationConfig.thinkingConfig).toEqual({ thinkingLevel: "high", includeThoughts: true });
expect(out.request.generationConfig.maxOutputTokens).toBe(65535);
});
});
describe("GOLDEN request: OpenAI → Kiro", () => {

View File

@@ -55,10 +55,14 @@ describe("extractThinking", () => {
});
describe("applyThinking per provider format", () => {
it("claude 4.6+ → adaptive output_config (no budget_tokens)", () => {
it("claude 4.6+ → adaptive thinking + output_config (no budget_tokens)", () => {
const out = apply("claude", "claude-opus-4.7", { reasoning_effort: "high" }, "claude");
expect(out.output_config).toEqual({ effort: "high" });
expect(out.thinking).toBeUndefined();
// Anthropic: on Opus 4.6/4.7/4.8 and Sonnet 4.6 thinking stays OFF unless
// thinking:{type:"adaptive"} is sent explicitly; output_config alone is not
// enough (and Anthropic-compatible shims like Copilot default off even on
// Sonnet 5). Both fields together are the documented adaptive shape.
expect(out.thinking).toEqual({ type: "adaptive" });
});
it("claude haiku → enabled+budget", () => {
const out = apply("claude", "claude-haiku-4.5", { reasoning_effort: "high" }, "claude");
@@ -78,11 +82,27 @@ describe("applyThinking per provider format", () => {
const out = apply("gemini", "gemini-3-pro", { reasoning_effort: "auto" }, "gemini");
expect(out.generationConfig.thinkingConfig.thinkingLevel).toBe("high");
});
it("gemini-3 high thinking raises too-small maxOutputTokens", () => {
const out = apply("gemini-cli", "gemini-3.1-pro-preview", {
request: { generationConfig: { maxOutputTokens: 128 } },
reasoning_effort: "high",
}, "gemini-cli");
expect(out.request.generationConfig.thinkingConfig).toEqual({ thinkingLevel: "high", includeThoughts: true });
expect(out.request.generationConfig.maxOutputTokens).toBe(65535);
});
it("gemini-2.5 → thinkingBudget", () => {
const out = apply("gemini", "gemini-2.5-flash", { reasoning_effort: "high" }, "gemini");
expect(out.generationConfig.thinkingConfig.thinkingBudget).toBe(24576);
expect(out.generationConfig.thinkingConfig.thinkingLevel).toBeUndefined();
});
it("gemini-2.5 budget thinking keeps enough room for answer tokens", () => {
const out = apply("gemini-cli", "gemini-2.5-pro", {
request: { generationConfig: { maxOutputTokens: 1024 } },
reasoning_effort: "high",
}, "gemini-cli");
expect(out.request.generationConfig.thinkingConfig).toEqual({ thinkingBudget: 24576, includeThoughts: true });
expect(out.request.generationConfig.maxOutputTokens).toBe(32768);
});
it("GLM off → enable_thinking:false (not thinking.disabled)", () => {
const out = apply("openai", "glm-4.6", { reasoning_effort: "none" }, "glm");
expect(out.enable_thinking).toBe(false);
@@ -106,6 +126,16 @@ describe("applyThinking per provider format", () => {
const out = apply("openai", "kimi-k2.6", { reasoning_effort: "high" }, "kimi");
expect(out.reasoning_effort).toBe("high");
});
it("Kimi auto → supported reasoning_effort", () => {
const out = apply("openai", "kimi-k2.7", { reasoning_effort: "auto" }, "kimchi");
expect(out.reasoning_effort).toBe("high");
});
it("Kimi unsupported OpenAI levels → supported reasoning_effort", () => {
const minimal = apply("openai", "kimi-k2.7", { reasoning_effort: "minimal" }, "kimchi");
const xhigh = apply("openai", "kimi-k2.7", { reasoning_effort: "xhigh" }, "kimchi");
expect(minimal.reasoning_effort).toBe("low");
expect(xhigh.reasoning_effort).toBe("max");
});
it("MiniMax M3 → adaptive", () => {
const out = apply("claude", "MiniMax-M3", { reasoning_effort: "high" }, "minimax");
expect(out.thinking).toEqual({ type: "adaptive" });

View File

@@ -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);
});
});

View File

@@ -1,6 +1,7 @@
// Guards D3: antigravity 429/503 retry merged into base via computeRetryDelay hook.
import { describe, it, expect } from "vitest";
import { AntigravityExecutor } from "../../open-sse/executors/antigravity.js";
import antigravity from "../../open-sse/providers/registry/antigravity.js";
const MAX = 10000;
function res(status, headers = {}, body = null) {
@@ -66,9 +67,35 @@ describe("antigravity computeRetryDelay hook (D3)", () => {
expect(out.request.tools[0].functionDeclarations.map(fn => fn.name)).toEqual(["read_file"]);
});
it("buildHeaders includes cached session id after transformRequest", () => {
it("registry uses the official IDE cloudcode host and user agent", () => {
expect(antigravity.transport.baseUrls).toEqual(["https://cloudcode-pa.googleapis.com"]);
expect(antigravity.transport.headers["User-Agent"]).toBe("antigravity/ide/2.1.1 darwin/arm64");
});
it("buildHeaders matches official IDE stream headers", () => {
ag._lastSessionId = "sess-123";
const h = ag.buildHeaders({ accessToken: "tok" }, true);
expect(h["X-Machine-Session-Id"]).toBe("sess-123");
expect(h["User-Agent"]).toBe("antigravity/ide/2.1.1 darwin/arm64");
expect(h["Content-Type"]).toBe("application/json");
expect(h["Authorization"]).toBe("Bearer tok");
expect(h).not.toHaveProperty("X-Machine-Session-Id");
expect(h).not.toHaveProperty("x-request-source");
expect(h).not.toHaveProperty("Accept");
});
it("transforms chat requests with official IDE requestId shape and 64000 token cap", () => {
const out = ag.transformRequest("claude-opus-4-6-thinking", {
request: {
contents: [
{ role: "user", parts: [{ text: "hi" }] },
{ role: "model", parts: [{ text: "hello" }] },
],
generationConfig: { maxOutputTokens: 90000 },
sessionId: "-3750763034362895579",
},
}, true, { projectId: "project-1", connectionId: "conn-1" });
expect(out.requestId).toMatch(/^agent\/[0-9a-f-]{36}\/\d{13}\/[0-9a-f-]{36}\/\d+$/);
expect(out.request.generationConfig.maxOutputTokens).toBe(64000);
});
});

View File

@@ -0,0 +1,30 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const proxyAwareFetch = vi.fn(async (url) => ({
ok: true,
status: 200,
json: async () => url.includes(":loadCodeAssist")
? { cloudaicompanionProject: "project-1", currentTier: { name: "Pro" } }
: { models: {} },
text: async () => "{}",
}));
vi.mock("../../open-sse/utils/proxyFetch.js", () => ({
proxyAwareFetch,
}));
describe("Antigravity usage headers", () => {
beforeEach(() => proxyAwareFetch.mockClear());
it("uses the official IDE user agent and omits router-only source headers", async () => {
const { getAntigravityUsage } = await import("../../open-sse/services/usage/google.js");
await getAntigravityUsage("access-token", {});
expect(proxyAwareFetch).toHaveBeenCalledTimes(2);
for (const [, options] of proxyAwareFetch.mock.calls) {
expect(options.headers["User-Agent"]).toBe("antigravity/ide/2.1.1 darwin/arm64");
expect(options.headers).not.toHaveProperty("x-request-source");
}
});
});

View File

@@ -4,6 +4,7 @@ import { describe, it, expect } from "vitest";
import { autoDetectFilter } from "../../open-sse/rtk/autodetect.js";
import { buildOutput } from "../../open-sse/rtk/filters/buildOutput.js";
import { gitDiff } from "../../open-sse/rtk/filters/gitDiff.js";
import { gitLog } from "../../open-sse/rtk/filters/gitLog.js";
import { gitStatus } from "../../open-sse/rtk/filters/gitStatus.js";
import { safeApply } from "../../open-sse/rtk/applyFilter.js";
import { compressMessages } from "../../open-sse/rtk/index.js";
@@ -279,6 +280,41 @@ describe("PR #1175 - integration with compressMessages", () => {
});
});
// ============================================================
// 6.5. GIT-LOG PRIORITY
// ============================================================
describe("git-log priority", () => {
it("git-log chosen over build-output when commit header present in first window", () => {
const input = [
"commit abc1234def5678abc1234def5678abc1234def5",
"Author: Dev One <dev1@example.com>",
"Date: Sun Jul 6 10:00:00 2026 +0700",
"",
" Add auth middleware",
"",
"diff --git a/src/auth.js b/src/auth.js",
"index abc..def 100644",
"--- a/src/auth.js",
"+++ b/src/auth.js",
"@@ -1 +1 @@",
"+new line"
].join("\n");
expect(autoDetectFilter(input)).toBe(gitLog);
});
it("pure git diff still stays git-diff", () => {
const input = [
"diff --git a/src/auth.js b/src/auth.js",
"index abc..def 100644",
"--- a/src/auth.js",
"+++ b/src/auth.js",
"@@ -1 +1 @@",
"+new line"
].join("\n");
expect(autoDetectFilter(input)).toBe(gitDiff);
});
});
// ============================================================
// 7. PORCELAIN REGRESSION DEEPER TESTS
// ============================================================

View File

@@ -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");
});
});

View File

@@ -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);
});
});

View File

@@ -0,0 +1,79 @@
import { describe, it, expect } from "vitest";
import { CAVEMAN_LEVELS, CAVEMAN_PROMPTS } from "../../open-sse/rtk/cavemanPrompts.js";
const LEVEL_KEYS = [
CAVEMAN_LEVELS.LITE,
CAVEMAN_LEVELS.FULL,
CAVEMAN_LEVELS.ULTRA,
CAVEMAN_LEVELS.WENYAN_LITE,
CAVEMAN_LEVELS.WENYAN,
CAVEMAN_LEVELS.WENYAN_ULTRA,
];
describe("Caveman prompt coverage", () => {
it("every level key has matching prompt and vice versa", () => {
const levelValues = Object.values(CAVEMAN_LEVELS);
for (const key of LEVEL_KEYS) {
expect(levelValues).toContain(key);
}
for (const value of levelValues) {
expect(LEVEL_KEYS).toContain(value);
}
});
it("has a prompt string for every level", () => {
for (const level of LEVEL_KEYS) {
expect(typeof CAVEMAN_PROMPTS[level]).toBe("string");
expect(CAVEMAN_PROMPTS[level].length).toBeGreaterThan(0);
}
});
it("adds no-invented-abbreviations guidance to every level", () => {
for (const level of LEVEL_KEYS) {
expect(CAVEMAN_PROMPTS[level]).toContain("No invented abbreviations");
}
});
it("adds preserve-user-language guidance to every level", () => {
for (const level of LEVEL_KEYS) {
expect(CAVEMAN_PROMPTS[level]).toContain("Preserve the user's dominant language");
}
});
it("adds no-self-reference guidance to every level", () => {
for (const level of LEVEL_KEYS) {
expect(CAVEMAN_PROMPTS[level]).toContain("No self-reference");
}
});
it("adds no-decorative-emoji guidance to every level", () => {
for (const level of LEVEL_KEYS) {
expect(CAVEMAN_PROMPTS[level]).toContain("No decorative emoji");
}
});
});
describe("Caveman internal consistency", () => {
it("no level uses Unicode arrow (SHARED_NO_DECORATION bans arrow shorthand)", () => {
// SHARED_NO_DECORATION uses ASCII -> to quote the banned pattern.
// Unicode → is the character old ULTRA used in "Pattern: [thing] → [result]".
// Verify no level now uses it.
for (const level of LEVEL_KEYS) {
expect(CAVEMAN_PROMPTS[level]).not.toContain("→");
}
});
});
describe("Caveman ULTRA targeted sync", () => {
it("does not encourage invented abbreviations", () => {
const ultra = CAVEMAN_PROMPTS[CAVEMAN_LEVELS.ULTRA];
expect(ultra).not.toContain("req/res/fn/impl");
expect(ultra).not.toContain("Abbreviate (DB/auth/config/req/res/fn/impl)");
});
it("does not encourage arrow shorthand", () => {
const ultra = CAVEMAN_PROMPTS[CAVEMAN_LEVELS.ULTRA];
expect(ultra).not.toContain("use arrows for causality");
expect(ultra).not.toContain("X → Y");
});
});

View File

@@ -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);
});
});

View File

@@ -0,0 +1,71 @@
import { describe, expect, it } from "vitest";
import { CodexExecutor } from "../../open-sse/executors/codex.js";
function streamFromText(text) {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
controller.enqueue(encoder.encode(text));
controller.close();
},
});
}
describe("Codex fast tier and capacity handling", () => {
it("maps Codex fast tier to priority and max reasoning to xhigh", () => {
const executor = new CodexExecutor();
const body = executor.transformRequest("gpt-5.5", {
model: "gpt-5.5",
input: "hi",
reasoning_effort: "max",
service_tier: "fast",
}, true, {});
expect(body.service_tier).toBe("priority");
expect(body.reasoning.effort).toBe("xhigh");
});
it("uses ChatGPT workspace header fallback", () => {
const executor = new CodexExecutor();
const headers = executor.buildHeaders({
accessToken: "token",
connectionId: "conn_1",
providerSpecificData: { chatgptAccountId: "acct_1" },
});
expect(headers["ChatGPT-Account-ID"]).toBe("acct_1");
});
it("classifies 200-SSE model capacity as account fallback", async () => {
const executor = new CodexExecutor();
const response = new Response(streamFromText([
"event: error",
'data: {"error":{"message":"Selected model is at capacity. Please try a different model."}}',
"",
].join("\n")), {
status: 200,
headers: { "Content-Type": "text/event-stream" },
});
const peek = await executor._peekSseTransientError(response);
expect(peek.accountFallback).toBe(true);
expect(peek.message).toBe("Selected model is at capacity. Please try a different model.");
});
it("reassembles normal SSE after peeking", async () => {
const executor = new CodexExecutor();
const text = [
"event: response.output_text.delta",
'data: {"type":"response.output_text.delta","delta":"OK"}',
"",
].join("\n");
const response = new Response(streamFromText(text), {
status: 200,
headers: { "Content-Type": "text/event-stream" },
});
const peek = await executor._peekSseTransientError(response);
expect(peek.matched).toBeNull();
await expect(new Response(peek.replacementBody).text()).resolves.toBe(text);
});
});

View File

@@ -0,0 +1,84 @@
import { describe, expect, it } from "vitest";
import { POST } from "../../src/app/api/v1/messages/count_tokens/route.js";
async function countTokens(body) {
const response = await POST(new Request("https://9router.local/v1/messages/count_tokens", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
}));
expect(response.status).toBe(200);
return response.json();
}
describe("Anthropic count_tokens estimator", () => {
it("preserves the existing plain text estimate", async () => {
const result = await countTokens({
messages: [
{
role: "user",
content: "hello world",
},
],
});
expect(result.input_tokens).toBe(3);
});
it("counts tool and thinking content blocks that carry context", async () => {
const result = await countTokens({
messages: [
{
role: "assistant",
content: [
{
type: "tool_use",
id: "toolu_01",
name: "Read",
input: { file_path: "/tmp/example.txt" },
},
{
type: "thinking",
thinking: "Need to inspect the file before answering.",
},
],
},
{
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "toolu_01",
content: "line1 line2 line3 some file content here",
},
],
},
],
});
expect(result.input_tokens).toBeGreaterThan(0);
});
it("counts system prompts and tool definitions", async () => {
const result = await countTokens({
system: "You are a coding assistant.",
tools: [
{
name: "Read",
description: "Read a file",
input_schema: {
type: "object",
properties: {
file_path: { type: "string" },
},
},
},
],
messages: [],
});
expect(result.input_tokens).toBeGreaterThan(0);
});
});

View File

@@ -101,6 +101,19 @@ describe("DB SQLite layer — public API parity", () => {
expect(back.providerSpecificData).toEqual({ foo: "bar" });
});
it("providerConnections: GitHub OAuth uses account identity as fallback name", async () => {
const c = await sqliteDb.createProviderConnection({
provider: "github",
authType: "oauth",
accessToken: "tok",
providerSpecificData: { githubLogin: "octocat" },
});
expect(c.name).toBe("octocat");
const back = await sqliteDb.getProviderConnectionById(c.id);
expect(back.name).toBe("octocat");
});
it("providerNodes: CRUD", async () => {
const n = await sqliteDb.createProviderNode({ type: "openai", name: "Test", baseUrl: "https://api.test", apiType: "openai" });
expect(n.id).toBeDefined();

View File

@@ -0,0 +1,495 @@
import { describe, it, expect, beforeEach } from "vitest";
import {
GrokCliExecutor,
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 { getModelInfoCore, resolveProviderAlias } from "../../open-sse/services/model.js";
import { OAUTH_PROVIDERS } from "../../src/shared/constants/providers.js";
describe("grok-cli registry", () => {
it("registers transport + oauth + models", () => {
const cfg = PROVIDERS["grok-cli"];
expect(cfg).toBeTruthy();
expect(cfg.baseUrl).toBe("https://cli-chat-proxy.grok.com/v1/responses");
expect(cfg.format).toBe("openai-responses");
expect(cfg.forceStream).toBe(true);
expect(cfg.tokenAuth).toBe("xai-grok-cli");
const oauth = PROVIDER_OAUTH["grok-cli"];
expect(oauth.clientId).toBe("b1a00492-073a-47ea-816f-4c329264a828");
expect(oauth.deviceCodeUrl).toContain("auth.x.ai");
expect(oauth.scope).toContain("grok-cli:access");
expect(oauth.scope).toContain("conversations:write");
expect(oauth.referrer).toBe("grok-build");
expect(PROVIDER_MODELS.gcli?.some((m) => m.id === "grok-build")).toBe(true);
});
it("is listed as oauth provider for dashboard", () => {
expect(OAUTH_PROVIDERS["grok-cli"]).toBeTruthy();
expect(OAUTH_PROVIDERS["grok-cli"].name).toMatch(/Grok CLI/i);
});
it("resolves aliases to provider id", () => {
expect(resolveProviderAlias("gcli")).toBe("grok-cli");
expect(resolveProviderAlias("gb")).toBe("grok-cli");
expect(resolveProviderAlias("grok-build")).toBe("grok-cli");
expect(resolveProviderAlias("grok-cli")).toBe("grok-cli");
});
it("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");
expect(getModelUpstreamId("gcli", "grok-4.5-low")).toBe("grok-4.5");
expect(getModelUpstreamId("gcli", "grok-4.5")).toBe("grok-4.5");
});
});
describe("GrokCliExecutor", () => {
let executor;
beforeEach(() => {
_resetGrokCliTurnStore();
executor = new GrokCliExecutor();
});
it("is registered on executor map (id + aliases)", () => {
expect(hasSpecializedExecutor("grok-cli")).toBe(true);
expect(getExecutor("grok-cli")).toBeInstanceOf(GrokCliExecutor);
expect(getExecutor("gcli")).toBeInstanceOf(GrokCliExecutor);
expect(getExecutor("gb")).toBeInstanceOf(GrokCliExecutor);
});
it("buildUrl points at cli-chat-proxy responses", () => {
expect(executor.buildUrl()).toBe("https://cli-chat-proxy.grok.com/v1/responses");
});
it("buildHeaders sets CLI fingerprint + session headers", () => {
executor._currentSessionId = "sess-abc";
executor._currentReqId = "req-xyz";
executor._agentId = "agent-1";
executor._currentModel = "grok-4.5";
executor._currentTurnIdx = 3;
const headers = executor.buildHeaders(
{
accessToken: "tok_test",
providerSpecificData: { email: "u@example.com", userId: "uid-1" },
},
true
);
expect(headers.Authorization).toBe("Bearer tok_test");
expect(headers.Accept).toBe("text/event-stream");
expect(headers["x-xai-token-auth"]).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"]).toBeUndefined();
expect(headers["x-email"]).toBe("u@example.com");
expect(headers["x-userid"]).toBe("uid-1");
expect(headers["x-authenticateresponse"]).toBeUndefined();
});
it("buildHeaders falls back to top-level email/userId (OAuth mapTokens shape)", () => {
executor._currentSessionId = "sess-top";
executor._currentReqId = "req-top";
const headers = executor.buildHeaders(
{
accessToken: "tok_test",
email: "top@example.com",
// userId only top-level; psd has neither email nor userId
providerSpecificData: { authMethod: "device_code" },
},
true
);
expect(headers["x-email"]).toBe("top@example.com");
expect(headers["x-userid"]).toBeUndefined();
});
it("transformRequest normalizes Responses body like official CLI", () => {
const body = {
model: "grok-4.5-high",
messages: [{ role: "user", content: "hi" }],
stream: false,
tools: [
{
type: "function",
function: {
name: "run_terminal_command",
description: "Run bash",
parameters: { type: "object", properties: { command: { type: "string" } } },
},
},
{ type: "web_search" },
{ type: "x_search" },
],
temperature: 0.7,
max_tokens: 100,
user: "cursor-user",
};
// Simulate translator already converting messages→input; also test messages fallback
const out = executor.transformRequest("grok-4.5-high", { ...body }, true, {
connectionId: "conn-1",
});
expect(out.model).toBe("grok-4.5");
expect(out.stream).toBe(true);
expect(out.store).toBe(false);
expect(out.include).toContain("reasoning.encrypted_content");
expect(out.reasoning).toEqual({ effort: "high", summary: "concise" });
expect(out.messages).toBeUndefined();
expect(out.max_tokens).toBeUndefined();
expect(out.user).toBeUndefined();
expect(Array.isArray(out.input)).toBe(true);
expect(out.input.length).toBeGreaterThan(0);
expect(executor._currentTurnIdx).toBe(1);
// tools flattened + hosted tools kept
expect(out.tools).toHaveLength(3);
expect(out.tools[0]).toMatchObject({
type: "function",
name: "run_terminal_command",
});
expect(out.tools[0].parameters).toBeTruthy();
expect(out.tools[0].function).toBeUndefined();
expect(out.tools[1]).toEqual({ type: "web_search" });
expect(out.tools[2]).toEqual({ type: "x_search" });
});
it("transformRequest keeps role:system (HAR parity) and strips server ids", () => {
const body = {
model: "grok-4.5",
input: [
{ type: "message", role: "system", content: "You are Grok" },
{ type: "message", role: "user", content: "hi", id: "msg_server_id" },
{ type: "item_reference", id: "rs_abc" },
"rs_should_drop",
],
reasoning_effort: "medium",
};
const out = executor.transformRequest("grok-4.5", body, true, { connectionId: "c1" });
expect(out.input).toHaveLength(2);
// Official CLI sends system, not developer (Codex converts; Grok does not)
expect(out.input[0].role).toBe("system");
expect(out.input[1].id).toBeUndefined();
expect(out.reasoning.effort).toBe("medium");
});
it("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",
rawHeaders: { "x-session-id": "stable-session-xyz" },
};
// Turn 1: one user message
executor.transformRequest(
"grok-4.5",
{
model: "grok-4.5",
input: [
{ type: "message", role: "system", content: "sys" },
{ type: "message", role: "user", content: "hi" },
],
},
true,
creds
);
expect(executor._currentSessionId).toBeTruthy();
expect(executor._currentTurnIdx).toBe(1);
let headers = executor.buildHeaders({ accessToken: "t" }, true);
expect(headers["x-grok-turn-idx"]).toBe("1");
expect(headers["x-grok-session-id"]).toBe(executor._currentSessionId);
expect(headers["x-grok-conv-id"]).toBe(executor._currentSessionId);
const sessionId = executor._currentSessionId;
// Turn 2: full history with two user messages
executor.transformRequest(
"grok-4.5",
{
model: "grok-4.5",
input: [
{ type: "message", role: "system", content: "sys" },
{ type: "message", role: "user", content: "hi" },
{ type: "message", role: "assistant", content: "hello" },
{ type: "message", role: "user", content: "next" },
],
},
true,
creds
);
expect(executor._currentSessionId).toBe(sessionId);
expect(executor._currentTurnIdx).toBe(2);
headers = executor.buildHeaders({ accessToken: "t" }, true);
expect(headers["x-grok-turn-idx"]).toBe("2");
// Same session, a new delta-style request advances without relying on full history.
executor.transformRequest(
"grok-4.5",
{
model: "grok-4.5",
input: [{ type: "message", role: "user", content: "only latest" }],
},
true,
creds
);
expect(executor._currentTurnIdx).toBe(3);
});
it("countGrokCliUserTurns / resolveGrokCliTurnIdx helpers", () => {
expect(countGrokCliUserTurns(null)).toBe(1);
expect(
countGrokCliUserTurns([
{ type: "message", role: "system", content: "s" },
{ type: "message", role: "user", content: "a" },
{ type: "message", role: "assistant", content: "b" },
{ type: "message", role: "user", content: "c" },
])
).toBe(2);
expect(resolveGrokCliTurnIdx("s1", [{ role: "user", type: "message", content: "a" }])).toBe(1);
expect(
resolveGrokCliTurnIdx("s1", [
{ role: "user", type: "message", content: "a" },
{ role: "user", type: "message", content: "b" },
])
).toBe(2);
// monotonic
expect(resolveGrokCliTurnIdx("s1", [{ role: "user", type: "message", content: "a" }])).toBe(2);
});
it("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 },
JSON.stringify({
code: "personal-team-blocked:spending-limit",
error: "You have run out of credits",
})
);
expect(err.status).toBe(402);
expect(err.code).toBe("personal-team-blocked:spending-limit");
expect(err.message).toMatch(/credits/i);
});
});

View File

@@ -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);
});
});

View File

@@ -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");
});
});

View File

@@ -0,0 +1,50 @@
/**
* Grok CLI connection-test semantics: 402 spending-limit is soft success (auth OK).
*/
import { describe, it, expect } from "vitest";
import { classifyOAuthProbeResult } from "../../src/app/api/providers/[id]/test/testUtils.js";
import { PROVIDERS } from "../../open-sse/providers/index.js";
const GROK_CLI_PROBE = {
url: PROVIDERS["grok-cli"]?.userUrl || "https://cli-chat-proxy.grok.com/v1/user",
method: "GET",
acceptStatuses: [402],
softFailMessage: {
402: "Connected, but Grok Build credits are exhausted (spending limit). Add credits or upgrade SuperGrok.",
},
};
describe("classifyOAuthProbeResult (grok-cli)", () => {
it("treats 200 as hard success", () => {
const r = classifyOAuthProbeResult({ ok: true, status: 200 }, GROK_CLI_PROBE, "");
expect(r).toEqual({ valid: true, error: null, soft: false });
});
it("treats 402 spending-limit as soft success (connected, out of credits)", () => {
const body = JSON.stringify({
code: "personal-team-blocked:spending-limit",
error: "You have run out of credits",
});
const r = classifyOAuthProbeResult({ ok: false, status: 402 }, GROK_CLI_PROBE, body);
expect(r.valid).toBe(true);
expect(r.soft).toBe(true);
expect(r.error).toMatch(/credits|SuperGrok|spending/i);
});
it("treats 401 as hard auth failure", () => {
const r = classifyOAuthProbeResult({ ok: false, status: 401 }, GROK_CLI_PROBE, "unauthorized");
expect(r).toEqual({ valid: false, error: "Token invalid or revoked", soft: false });
});
it("treats 403 as access denied", () => {
const r = classifyOAuthProbeResult({ ok: false, status: 403 }, GROK_CLI_PROBE, "");
expect(r.valid).toBe(false);
expect(r.error).toMatch(/Access denied/i);
});
it("Codex-style acceptStatuses 400 stays silent success (no soft warning)", () => {
const codex = { acceptStatuses: [400] };
const r = classifyOAuthProbeResult({ ok: false, status: 400 }, codex, "bad request");
expect(r).toEqual({ valid: true, error: null, soft: false });
});
});

View File

@@ -0,0 +1,251 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("../../open-sse/utils/proxyFetch.js", () => ({
proxyAwareFetch: vi.fn(),
}));
import { proxyAwareFetch } from "../../open-sse/utils/proxyFetch.js";
import { getUsageForProvider } from "../../open-sse/services/usage.js";
import { parseGrokCliBilling } from "../../open-sse/services/usage/grok-cli.js";
import { USAGE_SUPPORTED_PROVIDERS } from "../../src/shared/constants/providers.js";
import { PROVIDERS } from "../../open-sse/providers/index.js";
import { parseQuotaData } from "../../src/app/(dashboard)/dashboard/usage/components/ProviderLimits/utils.js";
function jsonResponse(body, status = 200) {
return new Response(JSON.stringify(body), {
status,
headers: { "Content-Type": "application/json" },
});
}
const EXHAUSTED_BILLING = {
config: {
currentPeriod: {
type: "USAGE_PERIOD_TYPE_WEEKLY",
start: "2026-07-08T00:00:00+00:00",
end: "2026-07-15T00:00:00+00:00",
},
onDemandCap: { val: 0 },
onDemandUsed: { val: 0 },
isUnifiedBillingUser: true,
prepaidBalance: { val: 0 },
topUpMethod: "TOP_UP_METHOD_SAVED_PAYMENT_METHOD",
billingPeriodStart: "2026-07-08T00:00:00+00:00",
billingPeriodEnd: "2026-07-15T00:00:00+00:00",
},
};
const ACTIVE_BILLING = {
config: {
currentPeriod: {
type: "USAGE_PERIOD_TYPE_WEEKLY",
start: "2026-07-08T00:00:00+00:00",
end: "2026-07-15T00:00:00+00:00",
},
onDemandCap: { val: 100 },
onDemandUsed: { val: 35 },
isUnifiedBillingUser: true,
prepaidBalance: { val: 12.5 },
billingPeriodStart: "2026-07-08T00:00:00+00:00",
billingPeriodEnd: "2026-07-15T00:00:00+00:00",
},
};
const USER_PROFILE = {
userId: "d84768dd-224d-4052-ba49-0d336fa9160c",
email: "user@example.com",
hasGrokCodeAccess: true,
subscriptionTier: null,
};
describe("grok-cli registry usage flag", () => {
it("exposes transport.usage urls", () => {
const cfg = PROVIDERS["grok-cli"];
expect(cfg.usage?.url).toContain("/v1/billing");
expect(cfg.usage?.userUrl).toContain("/v1/user");
});
it("is listed in USAGE_SUPPORTED_PROVIDERS", () => {
expect(USAGE_SUPPORTED_PROVIDERS).toContain("grok-cli");
});
});
describe("parseGrokCliBilling", () => {
it("maps on-demand cap/used + prepaid balance", () => {
const parsed = parseGrokCliBilling(ACTIVE_BILLING, USER_PROFILE);
expect(parsed.plan).toBe("Grok Code");
expect(parsed.quotas["On-demand"]).toMatchObject({
used: 35,
total: 100,
remainingPercentage: 65,
});
// Prepaid is remaining-balance style: 0 used of current pot
expect(parsed.quotas.Prepaid).toMatchObject({
used: 0,
total: 12.5,
remainingPercentage: 100,
});
expect(parsed.exhausted).toBe(false);
});
it("marks depleted free/promo account as exhausted", () => {
const parsed = parseGrokCliBilling(EXHAUSTED_BILLING, USER_PROFILE);
expect(parsed.quotas["On-demand"].remainingPercentage).toBe(0);
expect(parsed.exhausted).toBe(true);
});
it("uses subscriptionTier for plan when present", () => {
const parsed = parseGrokCliBilling(ACTIVE_BILLING, {
...USER_PROFILE,
subscriptionTier: "super_grok",
});
expect(parsed.plan).toBe("Super Grok");
});
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)", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("returns normalized quotas from billing + user endpoints", async () => {
proxyAwareFetch
.mockResolvedValueOnce(jsonResponse(ACTIVE_BILLING))
.mockResolvedValueOnce(jsonResponse(USER_PROFILE));
const usage = await getUsageForProvider({
provider: "grok-cli",
accessToken: "test-token",
providerSpecificData: {
email: "user@example.com",
userId: "d84768dd-224d-4052-ba49-0d336fa9160c",
},
});
expect(usage.message).toBeUndefined();
expect(usage.plan).toBe("Grok Code");
expect(usage.quotas["On-demand"]).toMatchObject({
used: 35,
total: 100,
remainingPercentage: 65,
});
expect(usage.quotas.Prepaid).toMatchObject({
used: 0,
total: 12.5,
remainingPercentage: 100,
});
// Official CLI fingerprint headers
const billingCall = proxyAwareFetch.mock.calls[0];
expect(billingCall[0]).toContain("/v1/billing");
expect(billingCall[1].headers.Authorization).toBe("Bearer test-token");
expect(billingCall[1].headers["x-xai-token-auth"]).toBe("xai-grok-cli");
expect(billingCall[1].headers["x-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",
);
});
it("surfaces auth-expired message on 401", async () => {
proxyAwareFetch
.mockResolvedValueOnce(jsonResponse({ error: "unauthorized" }, 401))
.mockResolvedValueOnce(jsonResponse(USER_PROFILE));
const usage = await getUsageForProvider({
provider: "grok-cli",
accessToken: "expired",
});
expect(usage.message).toMatch(/expired|re-authorize/i);
});
it("returns depleted on-demand bar without blocking message when cap is zero", async () => {
proxyAwareFetch
.mockResolvedValueOnce(jsonResponse(EXHAUSTED_BILLING))
.mockResolvedValueOnce(jsonResponse(USER_PROFILE));
const usage = await getUsageForProvider({
provider: "grok-cli",
accessToken: "test-token",
});
// Dashboard hides QuotaTable when `message` is set — keep message empty
// so the 0% bar still renders for exhausted free/promo accounts.
expect(usage.message).toBeUndefined();
expect(usage.quotas["On-demand"].remainingPercentage).toBe(0);
expect(usage.quotas["On-demand"].total).toBe(1);
});
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)", () => {
it("forwards remainingPercentage for dashboard bars", () => {
const rows = parseQuotaData("grok-cli", {
plan: "Grok Code",
quotas: {
"On-demand": {
used: 35,
total: 100,
remaining: 65,
remainingPercentage: 65,
resetAt: "2026-07-15T00:00:00.000Z",
},
},
});
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({
name: "On-demand",
used: 35,
total: 100,
remainingPercentage: 65,
});
});
});

View File

@@ -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." }],
}),
}));
});
});

View File

@@ -2,21 +2,92 @@ import { describe, it, expect, vi, afterEach } from "vitest";
const mocks = vi.hoisted(() => ({
execSync: vi.fn(() => { throw new Error("not found"); }),
execFile: vi.fn(() => ({ toString: () => "[object Object]" })),
execFileSync: vi.fn(() => Buffer.from(JSON.stringify([
{ name: "headroom-ai", version: "0.26.0" },
{ name: "tree-sitter", version: "0.25.0" },
]))),
}));
vi.mock("child_process", () => ({
execSync: mocks.execSync,
execFile: mocks.execFile,
execFileSync: mocks.execFileSync,
}));
import { getHeadroomStatus, isLoopbackHeadroomUrl } from "../../src/lib/headroom/detect.js";
import { findPython310, getHeadroomStatus, getInstalledHeadroomExtras, isLoopbackHeadroomUrl } from "../../src/lib/headroom/detect.js";
afterEach(() => {
vi.clearAllMocks();
});
describe("headroom detect", () => {
it("detects installed headroom version and extras from pip list", () => {
const result = getInstalledHeadroomExtras("python3");
expect(mocks.execFileSync).toHaveBeenCalledWith(
"python3",
["-m", "pip", "list", "--format=json", "--disable-pip-version-check"],
expect.objectContaining({ windowsHide: true, timeout: 8000 }),
);
expect(result).toEqual({
installed: true,
version: "0.26.0",
extras: { code: true, ml: false },
});
});
it("prefers the interpreter that actually has headroom-ai installed", () => {
// headroom binary lives in a bin dir; the python next to it has headroom-ai.
const binPython = "/opt/hr/bin/python3";
mocks.execSync.mockImplementation((cmd) => {
if (String(cmd).includes("where") || String(cmd).includes("which")) return Buffer.from("/opt/hr/bin/headroom\n");
if (String(cmd).includes("--version")) return Buffer.from("Python 3.13.0\n");
throw new Error("unexpected execSync");
});
mocks.execFileSync.mockImplementation((py, args) => {
if (args.join(" ") === "-m pip show headroom-ai") {
if (py === binPython) return Buffer.from("Name: headroom-ai\nVersion: 0.26.0\n");
throw new Error(`not installed in ${py}`);
}
throw new Error(`unexpected execFileSync: ${py} ${args.join(" ")}`);
});
expect(findPython310()).toBe(binPython);
});
it("keeps top-level installed flag true when extras are readable", async () => {
global.fetch = vi.fn(async () => new Response("ok", { status: 200 }));
mocks.execSync.mockImplementation((cmd) => {
if (String(cmd).includes("where") || String(cmd).includes("which")) return Buffer.from("C:/Python/Scripts/headroom.exe\n");
if (String(cmd).includes("python3 --version")) return Buffer.from("Python 3.13.0\n");
if (String(cmd).includes("python --version")) return Buffer.from("Python 3.13.0\n");
throw new Error("unexpected execSync");
});
mocks.execFileSync.mockImplementation((py, args) => {
if (py === "python3" && args.join(" ") === "-m pip show headroom-ai") throw new Error("not installed in python3");
if (py === "python" && args.join(" ") === "-m pip show headroom-ai") return Buffer.from("Name: headroom-ai\nVersion: 0.26.0\n");
if (py === "python" && args.join(" ").startsWith("-m pip list ")) return Buffer.from(JSON.stringify([
{ name: "headroom-ai", version: "0.26.0" },
{ name: "tree-sitter", version: "0.25.0" },
]));
throw new Error(`unexpected execFileSync: ${py} ${args.join(" ")}`);
});
const status = await getHeadroomStatus("http://localhost:8787");
expect(status.installed).toBe(true);
expect(status.version).toBe("0.26.0");
expect(status.extras).toEqual({ code: true, ml: false });
});
it("treats a reachable external proxy as running without local CLI", async () => {
global.fetch = vi.fn(async () => new Response("ok", { status: 200 }));
mocks.execSync.mockImplementation((cmd) => {
if (String(cmd).includes("where") || String(cmd).includes("which")) throw new Error("not found");
throw new Error("unexpected execSync");
});
mocks.execFileSync.mockImplementation(() => { throw new Error("pip unavailable"); });
const status = await getHeadroomStatus("http://headroom:8787");

View File

@@ -31,6 +31,10 @@ describe("compressWithHeadroom", () => {
expect(body.messages[0].content).toBe("short");
expect(stats.tokens_saved).toBe(80);
expect(global.fetch).toHaveBeenCalledWith("http://headroom:8787/v1/compress", expect.objectContaining({ method: "POST" }));
expect(JSON.parse(global.fetch.mock.calls[0][1].body)).toMatchObject({
model: "gpt-4o",
messages: [{ role: "user", content: "long" }],
});
});
it("compresses responses input in-place", async () => {
@@ -44,6 +48,141 @@ describe("compressWithHeadroom", () => {
expect(body.input[0].content).toBe("short");
});
it("compresses Kiro conversationState history/currentMessage in-place", async () => {
let requestPayload;
global.fetch = vi.fn(async (_url, init) => {
requestPayload = JSON.parse(init.body);
return new Response(JSON.stringify({
messages: [
{ role: "user", content: "compressed earlier user" },
{ role: "assistant", content: "compressed assistant", tool_calls: [{ id: "tool_1", type: "function", function: { name: "read_file", arguments: "{\"path\":\"a.js\"}" } }] },
{ role: "system", content: "compressed system instruction" },
{ role: "user", content: "compressed current user" },
{ role: "tool", content: [{ type: "text", text: "compressed tool output" }], tool_call_id: "tool_1" },
],
tokens_before: 100,
tokens_after: 40,
tokens_saved: 60,
}), { status: 200 });
});
const body = {
profileArn: "arn:test",
conversationState: {
chatTriggerType: "MANUAL",
conversationId: "conv-1",
history: [
{
userInputMessage: {
content: "earlier user",
modelId: "claude-sonnet-4.5",
},
},
{
assistantResponseMessage: {
content: "assistant response",
toolUses: [
{
toolUseId: "tool_1",
name: "read_file",
input: { path: "a.js" },
},
],
},
},
],
currentMessage: {
userInputMessage: {
content: "current user",
modelId: "claude-sonnet-4.5",
systemInstruction: "native system instruction",
userInputMessageContext: {
tools: [{ toolSpecification: { name: "read_file" } }],
toolResults: [
{
toolUseId: "tool_1",
status: "success",
content: [{ text: "long tool output" }],
},
],
},
},
},
},
};
const stats = await compressWithHeadroom(body, {
enabled: true,
url: "http://localhost:8787",
model: "claude-sonnet-4.5",
format: "kiro",
compressUserMessages: true,
});
expect(stats.tokens_saved).toBe(60);
expect(requestPayload).toEqual({
model: "claude-sonnet-4.5",
config: { compress_user_messages: true },
messages: [
{ role: "user", content: "earlier user" },
{
role: "assistant",
content: "assistant response",
tool_calls: [
{
id: "tool_1",
type: "function",
function: { name: "read_file", arguments: "{\"path\":\"a.js\"}" },
},
],
},
{ role: "system", content: "native system instruction" },
{ role: "user", content: "current user" },
{ role: "tool", content: "long tool output", tool_call_id: "tool_1" },
],
});
expect(body.conversationState.history[0].userInputMessage.content).toBe("compressed earlier user");
expect(body.conversationState.history[1].assistantResponseMessage.content).toBe("compressed assistant");
expect(body.conversationState.currentMessage.userInputMessage.systemInstruction).toBe("compressed system instruction");
expect(body.conversationState.currentMessage.userInputMessage.content).toBe("compressed current user");
expect(body.conversationState.currentMessage.userInputMessage.userInputMessageContext.toolResults[0].content[0].text)
.toBe("compressed tool output");
expect(body.profileArn).toBe("arn:test");
expect(body.conversationState.currentMessage.userInputMessage.userInputMessageContext.tools)
.toEqual([{ toolSpecification: { name: "read_file" } }]);
});
it("fails open when Kiro Headroom output does not preserve message order", async () => {
global.fetch = vi.fn(async () => new Response(JSON.stringify({
messages: [{ role: "assistant", content: "wrong role" }],
tokens_saved: 10,
}), { status: 200 }));
const body = {
conversationState: {
currentMessage: {
userInputMessage: {
content: "original",
modelId: "claude-sonnet-4.5",
},
},
history: [],
},
};
const original = structuredClone(body);
const diagnostics = {};
const stats = await compressWithHeadroom(body, {
enabled: true,
url: "http://localhost:8787",
model: "claude-sonnet-4.5",
format: "kiro",
diagnostics,
});
expect(stats).toBeNull();
expect(body).toEqual(original);
expect(diagnostics.reason).toBe("proxy response did not preserve Kiro message order");
});
it("fails open on bad response", async () => {
global.fetch = vi.fn(async () => new Response(JSON.stringify({ error: "bad" }), { status: 500 }));
const body = { messages: [{ role: "user", content: "long" }] };

View File

@@ -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");
}
});
});

View File

@@ -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");
});
});

View File

@@ -1,7 +1,7 @@
// Guards C2: regex name fallback (no catalog). Terse entries derive name; existing names untouched.
import { describe, it, expect } from "vitest";
import { deriveModelName } from "../../open-sse/providers/models/namePatterns.js";
import { normalizeModel } from "../../open-sse/providers/models/schema.js";
import { normalizeModel, normalizeModelId } from "../../open-sse/providers/models/schema.js";
describe("model name regex fallback (C2)", () => {
it("derives display name from id per family", () => {
@@ -25,4 +25,26 @@ describe("model name regex fallback (C2)", () => {
expect(m.id).toBe("glm-5");
expect(m.name).toBe("GLM 5");
});
it("normalizeModelId: dash between digits becomes a dot (version separator)", () => {
expect(normalizeModelId("claude-sonnet-4-5")).toBe("claude-sonnet-4.5");
expect(normalizeModelId("minimax-m2-5")).toBe("minimax-m2.5");
expect(normalizeModelId("deepseek-3-2")).toBe("deepseek-3.2");
});
it("normalizeModelId: preserves word-suffix hyphens (-thinking, -agentic)", () => {
expect(normalizeModelId("claude-sonnet-4-5-thinking")).toBe("claude-sonnet-4.5-thinking");
expect(normalizeModelId("claude-sonnet-4-5-thinking-agentic")).toBe("claude-sonnet-4.5-thinking-agentic");
});
it("normalizeModelId: leaves ids with no digit-digit hyphen untouched", () => {
expect(normalizeModelId("qwen3-coder-next")).toBe("qwen3-coder-next");
expect(normalizeModelId("claude-sonnet-5")).toBe("claude-sonnet-5");
expect(normalizeModelId("glm-5")).toBe("glm-5");
});
it("normalizeModelId: non-string input passes through", () => {
expect(normalizeModelId(undefined)).toBeUndefined();
expect(normalizeModelId(null)).toBeNull();
});
});

View File

@@ -0,0 +1,181 @@
/**
* Multi-turn continuity for store=false Responses backends (Grok CLI / Codex).
* Prior-turn reasoning (+ encrypted_content) must survive Chat Completions ↔ Responses.
*/
import { describe, it, expect } from "vitest";
import {
openaiToOpenAIResponsesRequest,
openaiResponsesToOpenAIRequest,
} from "../../open-sse/translator/request/openai-responses.js";
import { GrokCliExecutor, _resetGrokCliTurnStore } from "../../open-sse/executors/grok-cli.js";
import { translateRequest } from "../../open-sse/translator/index.js";
describe("openai ↔ responses multi-turn reasoning", () => {
it("openai→responses re-emits reasoning item with summary + encrypted_content", () => {
const body = {
model: "grok-4.5",
messages: [
{ role: "user", content: "hi" },
{
role: "assistant",
content: "hello",
reasoning_content: "thinking hard about greeting",
encrypted_content: "enc_blob_turn1",
},
{ role: "user", content: "next" },
],
};
const out = openaiToOpenAIResponsesRequest("grok-4.5", body, true, null);
expect(out.store).toBe(false);
const reasoning = out.input.filter((i) => i.type === "reasoning");
expect(reasoning).toHaveLength(1);
expect(reasoning[0].encrypted_content).toBe("enc_blob_turn1");
expect(reasoning[0].summary?.[0]?.text).toMatch(/thinking hard/);
// Order: user → reasoning → assistant → user
const types = out.input.map((i) => i.type || i.role);
expect(types).toEqual(["message", "reasoning", "message", "message"]);
expect(out.input[0].role).toBe("user");
expect(out.input[2].role).toBe("assistant");
expect(out.input[3].role).toBe("user");
});
it("accepts reasoning_encrypted_content alias on assistant messages", () => {
const out = openaiToOpenAIResponsesRequest(
"m",
{
messages: [
{
role: "assistant",
content: "ok",
reasoning_encrypted_content: "alt_enc",
},
],
},
true,
null
);
expect(out.input.find((i) => i.type === "reasoning")?.encrypted_content).toBe("alt_enc");
});
it("responses→openai attaches reasoning_content + encrypted_content to assistant", () => {
const body = {
model: "grok-4.5",
input: [
{ type: "message", role: "user", content: [{ type: "input_text", text: "hi" }] },
{
type: "reasoning",
summary: [{ type: "summary_text", text: "plan A" }],
encrypted_content: "enc_xyz",
},
{
type: "message",
role: "assistant",
content: [{ type: "output_text", text: "hello" }],
},
],
};
const out = openaiResponsesToOpenAIRequest("grok-4.5", body, true, null);
const assistant = out.messages.find((m) => m.role === "assistant");
expect(assistant).toBeTruthy();
expect(assistant.reasoning_content).toBe("plan A");
expect(assistant.encrypted_content).toBe("enc_xyz");
});
it("round-trips encrypted_content through openai → responses → openai", () => {
const original = {
model: "grok-4.5",
messages: [
{ role: "user", content: "q1" },
{
role: "assistant",
content: "a1",
reasoning_content: "r1",
encrypted_content: "ENC_KEEP_ME",
},
{ role: "user", content: "q2" },
],
};
const responses = openaiToOpenAIResponsesRequest("grok-4.5", structuredClone(original), true, null);
const back = openaiResponsesToOpenAIRequest("grok-4.5", responses, true, null);
const again = openaiToOpenAIResponsesRequest("grok-4.5", back, true, null);
const enc = again.input.find((i) => i.type === "reasoning")?.encrypted_content;
expect(enc).toBe("ENC_KEEP_ME");
});
it("translateRequest openai→openai-responses preserves encrypted blob", () => {
const body = {
model: "grok-4.5",
messages: [
{ role: "user", content: "hi" },
{
role: "assistant",
content: "yo",
reasoning_content: "why",
encrypted_content: "blob_via_registry",
},
{ role: "user", content: "go" },
],
};
const out = translateRequest(
"openai",
"openai-responses",
"grok-4.5",
structuredClone(body),
true,
{},
"grok-cli"
);
expect(out.input.some((i) => i.type === "reasoning" && i.encrypted_content === "blob_via_registry")).toBe(
true
);
});
});
describe("GrokCliExecutor multi-turn input", () => {
it("keeps 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_3e3f6187-892a-96db-893b-904eff019e19" },
{
type: "reasoning",
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_4e3f6187-892a-96db-893b-904eff019e19" },
{ type: "message", role: "user", content: "again" },
],
include: ["reasoning.encrypted_content"],
};
const out = executor.transformRequest("grok-4.5", structuredClone(body), true, {
connectionId: "mt-1",
});
const reasoning = out.input.filter((i) => i.type === "reasoning");
expect(reasoning).toHaveLength(1);
expect(reasoning[0].encrypted_content).toBe("enc_from_cli");
expect(reasoning[0].summary?.[0]?.text).toBe("prior plan");
expect(reasoning[0].id).toBe("rs_3e3f6187-892a-96db-893b-904eff019e19");
// system preserved (not developer)
expect(out.input[0].role).toBe("system");
// Native Grok IDs are required for encrypted continuity.
for (const item of out.input) {
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);
expect(executor._currentTurnIdx).toBe(2);
});
});

View File

@@ -0,0 +1,91 @@
/**
* Regression: tools WITHOUT an explicit `type:"function"` wrapper were
* forwarded to the upstream Claude-compatible gateway with `name:"undefined"`,
* because openai-to-claude only unwrapped `tool.function` when BOTH
* `tool.type === "function"` AND `tool.function` were truthy.
*
* Repro path (v0.5.20):
* tools: [{ function: { name: "echo", parameters: {...} } }] // no parent type
* → originalName = undefined
* → upstream body: { name: "undefined", description: "", input_schema: {...} }
*
* Pragmatic OpenAI clients and some library generators emit the bare
* `function` wrapper shape; when this lands on a strict Anthropic-compatible
* gateway (e.g. MiniMax's `api.minimaxi.com/anthropic/v1/messages`), the
* payload is rejected with an "invalid tool type" / "(2013)" error, which
* is the same family of failure that PR #2463 was diagnosing from the
* runtimeTransport side. PR #2463 fixes the combo-path transport
* selection; this regression closes the translator-side shape gap so
* single-connection OpenAI clients aren't bit by it once #2463 lands.
*
* See: #2435, follow-up to PR #2463.
*/
import { describe, it, expect } from "vitest";
import { openaiToClaudeRequest } from "../../open-sse/translator/request/openai-to-claude.js";
const baseBody = (extra = {}) => ({
messages: [{ role: "user", content: "hi" }],
...extra,
});
describe("openai→claude: tools shape fidelity", () => {
it("tool WITH explicit type:'function' is rewritten to Anthropic shape", () => {
const out = openaiToClaudeRequest("claude-sonnet-4.5", baseBody({
tools: [
{ type: "function", function: { name: "echo", parameters: { type: "object" } } },
],
}), false);
expect(out.tools).toHaveLength(1);
expect(out.tools[0].name).toBe("echo");
expect(out.tools[0].input_schema).toEqual({ type: "object" });
// Anthropic-shape has no top-level `type` and no nested `function`.
expect(out.tools[0]).not.toHaveProperty("type");
expect(out.tools[0]).not.toHaveProperty("function");
});
it("tool WITHOUT explicit type but WITH function wrapper preserves the original name (was 'undefined' in v0.5.20)", () => {
const out = openaiToClaudeRequest("claude-sonnet-4.5", baseBody({
tools: [
{ function: { name: "echo", parameters: { type: "object" } } },
],
}), false);
expect(out.tools).toHaveLength(1);
expect(out.tools[0].name).toBe("echo");
expect(out.tools[0].input_schema).toEqual({ type: "object" });
// The Anthropic-shape envelope strips the OpenAI `function` wrapper entirely.
expect(out.tools[0]).not.toHaveProperty("function");
expect(out.tools[0]).not.toHaveProperty("type");
});
it("flat Anthropic-shape tool (no function wrapper) is passed through with name preserved", () => {
const out = openaiToClaudeRequest("claude-sonnet-4.5", baseBody({
tools: [
{ name: "echo", description: "echo input", input_schema: { type: "object" } },
],
}), false);
expect(out.tools).toHaveLength(1);
expect(out.tools[0].name).toBe("echo");
expect(out.tools[0].description).toBe("echo input");
expect(out.tools[0].input_schema).toEqual({ type: "object" });
});
it("non-function built-in tool types are passed through (cache_control tag is OK)", () => {
// 9router adds a `cache_control` tag to the last tool for prompt caching;
// the test asserts the original shape is preserved alongside it rather
// than checking strict equality. This is the existing buildHeaders /
// cache_control behavior unchanged by this fix.
const out = openaiToClaudeRequest("claude-sonnet-4.5", baseBody({
tools: [
{ type: "web_search_20250305", name: "web_search" },
],
}), false);
expect(out.tools).toHaveLength(1);
expect(out.tools[0].type).toBe("web_search_20250305");
expect(out.tools[0].name).toBe("web_search");
});
});

View File

@@ -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();
});
});
});

View File

@@ -28,4 +28,28 @@ describe("stripUnsupportedParams", () => {
expect(body).toEqual({ top_p: 1 });
});
it("clamps VolcEngine Ark GLM max token fields to the model output ceiling", () => {
const body = {
max_tokens: 131072,
max_completion_tokens: 131072,
max_output_tokens: 131072,
};
stripUnsupportedParams("volcengine-ark", "GLM-5.2", body);
expect(body).toEqual({
max_tokens: 128000,
max_completion_tokens: 128000,
max_output_tokens: 128000,
});
});
it("keeps VolcEngine Ark GLM max tokens when already under the ceiling", () => {
const body = { max_tokens: 64000 };
stripUnsupportedParams("volcengine-ark", "GLM-5.2", body);
expect(body.max_tokens).toBe(64000);
});
});

View File

@@ -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);
});
});

95
tests/unit/pxpipe.test.js Normal file
View File

@@ -0,0 +1,95 @@
import { describe, expect, it, vi } from "vitest";
import { compressWithPxpipe, formatPxpipeLog } from "../../open-sse/rtk/pxpipe.js";
const bigText = "x".repeat(30000);
const claudeBody = () => ({
model: "claude-fable-5",
max_tokens: 100,
messages: [{ role: "user", content: bigText }],
});
// A transform double mimicking pxpipe-proxy/transform's contract.
const appliedTransform = (outBody) => async () => ({
applied: true,
reason: "applied",
body: new TextEncoder().encode(JSON.stringify(outBody)),
info: { compressedChars: 25000, imageCount: 2, imageBytes: 5000, imagePixels: 1500000 },
cache: { ownsCacheControl: true, markerCount: 1 },
});
describe("compressWithPxpipe gates", () => {
it("skips when disabled", async () => {
const { body, summary } = await compressWithPxpipe(claudeBody(), { enabled: false });
expect(body).toBeNull();
expect(summary.reason).toBe("disabled");
});
it("skips when transform is unavailable (not installed)", async () => {
const { body, summary } = await compressWithPxpipe(claudeBody(), { enabled: true, format: "claude", transform: null });
expect(body).toBeNull();
expect(summary.reason).toBe("not_installed");
});
it("skips non-Claude formats", async () => {
const transform = vi.fn();
const { body, summary } = await compressWithPxpipe(claudeBody(), { enabled: true, format: "openai", transform });
expect(body).toBeNull();
expect(summary.reason).toBe("unsupported_format");
expect(transform).not.toHaveBeenCalled();
});
it("bypasses small prompts below minChars", async () => {
const transform = vi.fn();
const small = { model: "claude-fable-5", messages: [{ role: "user", content: "hi" }] };
const { body, summary } = await compressWithPxpipe(small, { enabled: true, format: "claude", minChars: 25000, transform });
expect(body).toBeNull();
expect(summary.reason).toBe("below_threshold");
expect(transform).not.toHaveBeenCalled();
});
it("applies the transform and reports savings", async () => {
const compressed = { model: "claude-fable-5", messages: [{ role: "user", content: "imaged" }] };
const { body, summary } = await compressWithPxpipe(claudeBody(), {
enabled: true, format: "claude", minChars: 1000, transform: appliedTransform(compressed),
});
expect(body).toEqual(compressed);
expect(summary.applied).toBe(true);
expect(summary.imageCount).toBe(2);
expect(summary.tokensBeforeEst).toBeGreaterThan(summary.tokensAfterEst);
expect(summary.savedPct).toBeGreaterThan(0);
expect(formatPxpipeLog(summary)).toContain("2 image(s)");
});
it("passes through when the transform declines (not_profitable)", async () => {
const transform = async () => ({ applied: false, reason: "not_profitable", body: new Uint8Array(), info: {} });
const { body, summary } = await compressWithPxpipe(claudeBody(), {
enabled: true, format: "claude", minChars: 1000, transform,
});
expect(body).toBeNull();
expect(summary.reason).toBe("not_profitable");
});
it("fails open when the transform throws", async () => {
const transform = async () => { throw new Error("boom"); };
const { body, summary } = await compressWithPxpipe(claudeBody(), {
enabled: true, format: "claude", minChars: 1000, transform,
});
expect(body).toBeNull();
expect(summary.reason).toBe("transform_error");
expect(summary.detail).toBe("boom");
});
it("fails open on timeout", async () => {
const transform = () => new Promise(() => {}); // never resolves
const { body, summary } = await compressWithPxpipe(claudeBody(), {
enabled: true, format: "claude", minChars: 1000, timeoutMs: 50, transform,
});
expect(body).toBeNull();
expect(summary.reason).toBe("timeout");
});
it("does not log skipped requests as savings", () => {
expect(formatPxpipeLog({ applied: false, reason: "below_threshold" })).toBeNull();
expect(formatPxpipeLog(null)).toBeNull();
});
});

View File

@@ -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 }) => (

View File

@@ -0,0 +1,252 @@
// Backend logic behind /dashboard/usage?tab=details.
// Covers crash-risk edge cases in getRequestDetails() used by
// /api/usage/request-details and /api/usage/providers.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, it, expect, beforeAll, afterAll, vi } from "vitest";
const originalDataDir = process.env.DATA_DIR;
let tempDir;
let db;
let adapter;
async function saveDetail(detail) {
await db.saveRequestDetail(detail);
await new Promise((r) => setTimeout(r, 120));
}
beforeAll(async () => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "9router-details-tab-"));
process.env.DATA_DIR = tempDir;
vi.resetModules();
db = await import("@/lib/db/index.js");
await db.initDb();
await db.updateSettings({ enableObservability2: true, observabilityBatchSize: 1 });
const { getAdapter } = await import("@/lib/db/driver.js");
adapter = await getAdapter();
});
afterAll(() => {
if (tempDir) fs.rmSync(tempDir, { recursive: true, force: true });
if (originalDataDir === undefined) delete process.env.DATA_DIR;
else process.env.DATA_DIR = originalDataDir;
});
describe("request details — tab crash-risk cases", () => {
it("corrupt data column → parseJson fallback {}, no throw", async () => {
// Inject a row with invalid JSON directly, bypassing save path
adapter.run(
`INSERT INTO requestDetails(id, timestamp, provider, model, connectionId, status, data) VALUES(?, ?, ?, ?, ?, ?, ?)`,
["corrupt-1", new Date().toISOString(), "openai", "gpt-4", null, "ok", "{not-valid-json"]
);
const res = await db.getRequestDetails({ provider: "openai" });
expect(Array.isArray(res.details)).toBe(true);
const corrupt = res.details.find((d) => Object.keys(d).length === 0);
expect(corrupt).toEqual({});
});
it("pagination beyond last page → empty details, valid meta", async () => {
const res = await db.getRequestDetails({ page: 9999, pageSize: 20 });
expect(res.details).toEqual([]);
expect(res.pagination.page).toBe(9999);
expect(res.pagination.hasNext).toBe(false);
expect(res.pagination.totalItems).toBeGreaterThanOrEqual(0);
});
it("invalid startDate → Invalid Date ISO throws inside getRequestDetails is caught upstream", async () => {
// new Date("bad").toISOString() throws RangeError; verify it surfaces
// so the API route's try/catch returns 500 rather than silent corruption.
await expect(db.getRequestDetails({ startDate: "not-a-date" })).rejects.toThrow();
});
it("valid date filter range → no throw", async () => {
const res = await db.getRequestDetails({
startDate: "2020-01-01T00:00:00",
endDate: "2999-01-01T00:00:00",
});
expect(Array.isArray(res.details)).toBe(true);
});
it("large pageSize (providers route uses 9999) → returns all, no crash", async () => {
await saveDetail({
id: "big-1", provider: "anthropic", model: "claude-3",
status: "ok", tokens: { input_tokens: 5 },
request: { method: "POST" }, response: { content: "hi" },
});
const res = await db.getRequestDetails({ pageSize: 9999 });
expect(res.details.length).toBeGreaterThanOrEqual(1);
expect(res.pagination.pageSize).toBe(9999);
});
it("oversized field → stored truncated + reparseable (no circular)", async () => {
const huge = "x".repeat(20 * 1024);
await saveDetail({
id: "trunc-1", provider: "openai", model: "gpt-4",
status: "ok", tokens: {},
request: { blob: huge }, response: { content: "ok" },
});
const got = await db.getRequestDetailById("trunc-1");
expect(got).toBeDefined();
// Truncated field is a plain object safe for JSON.stringify in the drawer
expect(() => JSON.stringify(got)).not.toThrow();
expect(got.request._truncated).toBe(true);
});
it("missing tokens/timestamp on row → getInputTokens-style access safe", async () => {
adapter.run(
`INSERT INTO requestDetails(id, timestamp, provider, model, connectionId, status, data) VALUES(?, ?, ?, ?, ?, ?, ?)`,
["sparse-1", new Date().toISOString(), "openai", null, null, null, JSON.stringify({ id: "sparse-1" })]
);
const got = await db.getRequestDetailById("sparse-1");
expect(got.tokens).toBeUndefined();
// Drawer reads tokens?.prompt_tokens — optional chaining tolerates undefined
expect(got.tokens?.prompt_tokens || 0).toBe(0);
});
});
// Mirror of RequestDetailsTab token helpers (component is "use client",
// helpers are not exported). Keep in sync with the component.
function getCachedTokens(tokens) {
return tokens?.cached_tokens || tokens?.cache_read_input_tokens || 0;
}
function getCacheCreationTokens(tokens) {
return tokens?.cache_creation_input_tokens || 0;
}
function getInputTokens(tokens) {
const prompt = tokens?.prompt_tokens || tokens?.input_tokens || 0;
const cache = getCachedTokens(tokens);
return prompt < cache ? cache : prompt;
}
describe("backupDbLite — excludes requestDetails, keeps critical data", () => {
it("backup file omits requestDetails rows but keeps other tables", async () => {
const { backupDbLite } = await import("@/lib/db/backup.js");
await saveDetail({ id: "bk-1", provider: "openai", model: "m", status: "ok", tokens: {}, request: {}, response: {} });
const backupDir = fs.mkdtempSync(path.join(os.tmpdir(), "9router-bklite-"));
const dest = backupDbLite(adapter, backupDir);
expect(fs.existsSync(dest)).toBe(true);
// Open backup and assert requestDetails is empty, settings present
const Database = (await import("better-sqlite3")).default;
const bak = new Database(dest);
try {
// requestDetails is fully excluded — table must not exist in the backup
const rdTable = bak.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='requestDetails'").get();
expect(rdTable).toBeUndefined();
// Critical data preserved
const st = bak.prepare("SELECT COUNT(*) c FROM settings").get();
expect(st.c).toBeGreaterThanOrEqual(1);
} finally {
bak.close();
fs.rmSync(backupDir, { recursive: true, force: true });
}
});
});
describe("getDistinctProviders — providers route (no full-row parse)", () => {
it("returns unique provider list without parsing data blobs", async () => {
await saveDetail({ id: "dp-1", provider: "openai", model: "m", status: "ok", tokens: {}, request: {}, response: {} });
await saveDetail({ id: "dp-2", provider: "anthropic", model: "m", status: "ok", tokens: {}, request: {}, response: {} });
await saveDetail({ id: "dp-3", provider: "openai", model: "m", status: "ok", tokens: {}, request: {}, response: {} });
const list = await db.getDistinctProviders();
expect(Array.isArray(list)).toBe(true);
expect(list).toContain("openai");
expect(list).toContain("anthropic");
// No duplicates
expect(new Set(list).size).toBe(list.length);
});
it("skips null providers, returns sorted", async () => {
const list = await db.getDistinctProviders();
expect(list.every((p) => p !== null)).toBe(true);
const sorted = [...list].sort();
expect(list).toEqual(sorted);
});
});
describe("token helpers — render-time crash safety", () => {
it("undefined/null tokens → 0, no throw", () => {
expect(getInputTokens(undefined)).toBe(0);
expect(getInputTokens(null)).toBe(0);
expect(getCachedTokens(undefined)).toBe(0);
expect(getCacheCreationTokens(null)).toBe(0);
});
it("empty object → 0 across all helpers", () => {
expect(getInputTokens({})).toBe(0);
expect(getCachedTokens({})).toBe(0);
expect(getCacheCreationTokens({})).toBe(0);
});
it("prompt_tokens preferred, falls back to input_tokens", () => {
expect(getInputTokens({ prompt_tokens: 100 })).toBe(100);
expect(getInputTokens({ input_tokens: 50 })).toBe(50);
});
it("legacy Claude row (prompt < cache) → returns cache", () => {
expect(getInputTokens({ prompt_tokens: 10, cached_tokens: 200 })).toBe(200);
});
it("cached via cache_read_input_tokens alias", () => {
expect(getCachedTokens({ cache_read_input_tokens: 42 })).toBe(42);
});
it("toLocaleString on helper result never throws", () => {
expect(() => getInputTokens(undefined).toLocaleString()).not.toThrow();
});
});
describe("API route contract — validation boundary", () => {
let GET;
beforeAll(async () => {
({ GET } = await import("@/app/api/usage/request-details/route.js"));
});
function makeReq(query) {
return new Request(`http://localhost/api/usage/request-details?${query}`);
}
it("page=0 → 400 (guard now reachable after NaN-check fix)", async () => {
const res = await GET(makeReq("page=0"));
expect(res.status).toBe(400);
});
it("page=-5 → 400", async () => {
const res = await GET(makeReq("page=-5"));
expect(res.status).toBe(400);
});
it("pageSize=101 → 400", async () => {
const res = await GET(makeReq("pageSize=101"));
expect(res.status).toBe(400);
});
it("pageSize=abc (NaN) → defaults to 20, returns 200", async () => {
const res = await GET(makeReq("pageSize=abc"));
expect(res.status).toBe(200);
const body = await res.json();
expect(body.pagination.pageSize).toBe(20);
});
it("invalid startDate → route catches, returns 500 (not thrown)", async () => {
const res = await GET(makeReq("startDate=not-a-date"));
expect(res.status).toBe(500);
const body = await res.json();
expect(body.error).toBeDefined();
});
it("valid request → 200 with details + pagination shape", async () => {
const res = await GET(makeReq("page=1&pageSize=20"));
expect(res.status).toBe(200);
const body = await res.json();
expect(Array.isArray(body.details)).toBe(true);
expect(body.pagination).toMatchObject({ page: 1, pageSize: 20 });
});
});

View File

@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach } from "vitest";
import { compressMessages, setRtkEnabled, isRtkEnabled, formatRtkLog } from "../../open-sse/rtk/index.js";
import { compressMessages, formatRtkLog } from "../../open-sse/rtk/index.js";
import { gitDiff } from "../../open-sse/rtk/filters/gitDiff.js";
import { gitStatus } from "../../open-sse/rtk/filters/gitStatus.js";
import { grep } from "../../open-sse/rtk/filters/grep.js";
@@ -10,6 +10,7 @@ import { tree } from "../../open-sse/rtk/filters/tree.js";
import { smartTruncate } from "../../open-sse/rtk/filters/smartTruncate.js";
import { readNumbered } from "../../open-sse/rtk/filters/readNumbered.js";
import { searchList } from "../../open-sse/rtk/filters/searchList.js";
import { gitLog } from "../../open-sse/rtk/filters/gitLog.js";
import { autoDetectFilter } from "../../open-sse/rtk/autodetect.js";
import { safeApply } from "../../open-sse/rtk/applyFilter.js";
@@ -53,13 +54,172 @@ function makeFindOutput() {
return lines.join("\n");
}
describe("RTK flag", () => {
it("default off, toggle works", () => {
setRtkEnabled(false);
expect(isRtkEnabled()).toBe(false);
setRtkEnabled(true);
expect(isRtkEnabled()).toBe(true);
setRtkEnabled(false);
function makeGitLogOneline() {
return [
"abc1234 Add auth middleware",
"def5678 Fix token refresh race",
"fedcba9 Update docs"
].join("\n");
}
function makeGitLogDefault() {
return [
"commit abc1234def5678abc1234def5678abc1234def5",
"Author: Dev One <dev1@example.com>",
"Date: Sun Jul 6 10:00:00 2026 +0700",
"",
" Add auth middleware",
"",
" More body detail should be dropped.",
" This is padding that consumes tokens."
].join("\n");
}
function makeGitLogGraph() {
return [
"* abc1234 Add auth middleware",
"| * def5678 Fix token refresh race",
"|/",
"* fedcba9 Update docs"
].join("\n");
}
function makeGitLogGraphDefault() {
return [
"* commit abc1234def5678abc1234def5678abc1234def5",
"|\\",
"| * commit def5678abc1234def5678abc1234def5678abc1",
"|/",
"|",
"* commit fedcba9abc1234fedcba9abc1234fedcba9abc1234",
"Author: Dev One <dev1@example.com>",
"Date: Sun Jul 6 10:00:00 2026 +0700",
"",
" Add auth middleware",
""
].join("\n");
}
function makeGitLogWithMerge() {
return [
"commit abc1234def5678abc1234def5678abc1234def5",
"Merge: abc1234 def5678",
"Author: Dev One <dev1@example.com>",
"Date: Sun Jul 6 10:00:00 2026 +0700",
"",
" Merge branch 'feature'"
].join("\n");
}
function makeGitLogWithStats() {
return [
"commit abc1234def5678abc1234def5678abc1234def5",
"Author: Dev One <dev1@example.com>",
"Date: Sun Jul 6 10:00:00 2026 +0700",
"",
" Fix typo",
"",
" 2 files changed, 15 insertions(+), 3 deletions(-)"
].join("\n");
}
function makeGitLogWithEmbeddedDiff() {
return [
"commit abc1234def5678abc1234def5678abc1234def5",
"Author: Dev One <dev1@example.com>",
"Date: Sun Jul 6 10:00:00 2026 +0700",
"",
" Fix typo",
"",
"diff --git a/src/main.js b/src/main.js"
].join("\n");
}
describe("gitLog filter", () => {
it("compresses git log --oneline without losing commit subjects", () => {
const input = makeGitLogOneline();
const out = gitLog(input);
expect(out).toContain("abc1234");
expect(out).toContain("Add auth middleware");
expect(out.length).toBeLessThanOrEqual(input.length);
});
it("keeps commit header + subject in default git log, drops body detail", () => {
const input = makeGitLogDefault();
const out = gitLog(input);
expect(out).toContain("commit abc1234def5678abc1234def5678abc1234def5");
expect(out).toContain("Add auth middleware");
expect(out).not.toContain("More body detail should be dropped.");
});
it("strips graph-only decoration but keeps commit subjects", () => {
const input = makeGitLogGraph();
const out = gitLog(input);
expect(out).toContain("abc1234 Add auth middleware");
expect(out).toContain("def5678 Fix token refresh race");
expect(out).not.toContain("|/");
});
it("returns empty string for empty input", () => {
expect(gitLog("")).toBe("");
});
it("returns empty string for null/undefined input", () => {
expect(gitLog(null)).toBe("");
expect(gitLog(undefined)).toBe("");
});
it("handles git log --graph without --oneline (graph-prefixed commit headers)", () => {
const input = makeGitLogGraphDefault();
const out = gitLog(input);
expect(out).toContain("commit abc1234def5678abc1234def5678abc1234def5");
expect(out).toContain("Add auth middleware");
// graph decoration dropped, pure-graph branch connectors dropped
expect(out).not.toContain("|\\");
expect(out).not.toContain("|/");
});
it("drops merge commit line ('Merge: abc1234 def5678')", () => {
const input = makeGitLogWithMerge();
const out = gitLog(input);
expect(out).toContain("commit abc1234def5678abc1234def5678abc1234def5");
expect(out).toContain("Merge branch 'feature'");
// "Merge:" line should be dropped (not in output)
expect(out).not.toContain("Merge:");
});
it("keeps stat-summary lines verbatim", () => {
const input = makeGitLogWithStats();
const out = gitLog(input);
expect(out).toContain("2 files changed, 15 insertions(+), 3 deletions(-)");
});
it("replaces embedded diff markers with '... diff body omitted'", () => {
const input = makeGitLogWithEmbeddedDiff();
const out = gitLog(input);
expect(out).toContain("diff body omitted");
// Original diff line replaced
expect(out).not.toContain("diff --git a/src/main.js b/src/main.js");
});
it("truncates beyond maxLines and reports skipped count", () => {
// Generate 50 commit lines but cap at 20
const lines = [];
for (let i = 0; i < 50; i++) {
lines.push(`commit ${String(i).padStart(40, "0")}`);
}
const input = lines.join("\n");
const out = gitLog(input, 20);
const outLines = out.split("\n").filter(l => l.length > 0);
expect(outLines.length).toBeLessThanOrEqual(21); // 20 commits + optional skipped note
expect(out).toContain("more lines");
});
it("preserves input when compressed output inflates", () => {
// Input shorter than output would be — e.g. tiny log
const input = "abc\ndef";
const out = gitLog(input, 10);
expect(out).toBe(input);
});
});
@@ -123,6 +283,16 @@ describe("autoDetectFilter", () => {
it("detects find", () => {
expect(autoDetectFilter("./a/b.js\n./a/c.js\n./a/d.js").filterName).toBe("find");
});
it("detects git log via commit header", () => {
const input = [
"commit abc1234def5678abc1234def5678abc1234def5",
"Author: Dev One <dev1@example.com>",
"Date: Sun Jul 6 10:00:00 2026 +0700",
"",
" Add auth middleware"
].join("\n");
expect(autoDetectFilter(input).filterName).toBe("git-log");
});
it("falls back to dedupLog for generic text", () => {
const txt = "line1\nline2\nline3\nline4\nline5\nline6\n";
expect(autoDetectFilter(txt).filterName).toBe("dedup-log");
@@ -245,20 +415,17 @@ describe("safeApply", () => {
});
describe("compressMessages (disabled)", () => {
beforeEach(() => setRtkEnabled(false));
it("returns null when disabled", () => {
const body = { messages: [{ role: "tool", tool_call_id: "x", content: makeLongDiff() }] };
expect(compressMessages(body)).toBeNull();
expect(compressMessages(body, false)).toBeNull();
});
});
describe("compressMessages (enabled)", () => {
beforeEach(() => setRtkEnabled(true));
it("compresses OpenAI tool message (string content)", () => {
const big = makeLongDiff();
const body = { messages: [{ role: "tool", tool_call_id: "call_1", content: big }] };
const stats = compressMessages(body);
const stats = compressMessages(body, true);
expect(stats.hits.length).toBeGreaterThan(0);
expect(body.messages[0].content.length).toBeLessThan(big.length);
expect(stats.bytesBefore).toBeGreaterThan(stats.bytesAfter);
@@ -272,7 +439,7 @@ describe("compressMessages (enabled)", () => {
content: [{ type: "tool_result", tool_use_id: "toolu_1", content: big }]
}]
};
const stats = compressMessages(body);
const stats = compressMessages(body, true);
expect(stats.hits.length).toBeGreaterThan(0);
expect(body.messages[0].content[0].content.length).toBeLessThan(big.length);
});
@@ -289,7 +456,7 @@ describe("compressMessages (enabled)", () => {
}]
}]
};
const stats = compressMessages(body);
const stats = compressMessages(body, true);
expect(stats.hits.length).toBeGreaterThan(0);
expect(body.messages[0].content[0].content[0].text.length).toBeLessThan(big.length);
// short part unchanged
@@ -304,7 +471,7 @@ describe("compressMessages (enabled)", () => {
content: [{ type: "tool_result", tool_use_id: "toolu_1", content: big, is_error: true }]
}]
};
const stats = compressMessages(body);
const stats = compressMessages(body, true);
expect(stats.hits.length).toBe(0);
expect(body.messages[0].content[0].content).toBe(big);
});
@@ -312,7 +479,7 @@ describe("compressMessages (enabled)", () => {
it("skips below MIN_COMPRESS_SIZE (<500 bytes)", () => {
const small = "diff --git a/x b/x\n@@ -1 +1 @@\n+a";
const body = { messages: [{ role: "tool", tool_call_id: "x", content: small }] };
const stats = compressMessages(body);
const stats = compressMessages(body, true);
expect(stats.hits.length).toBe(0);
expect(body.messages[0].content).toBe(small);
});
@@ -320,7 +487,7 @@ describe("compressMessages (enabled)", () => {
it("never produces empty content (R14 guard)", () => {
const input = "a".repeat(1000);
const body = { messages: [{ role: "tool", tool_call_id: "x", content: input }] };
compressMessages(body);
compressMessages(body, true);
expect(body.messages[0].content.length).toBeGreaterThan(0);
});
@@ -339,7 +506,7 @@ describe("compressMessages (enabled)", () => {
{ role: "user", content: [{ type: "text", text: "next" }] }
]
};
const stats = compressMessages(body);
const stats = compressMessages(body, true);
expect(stats).not.toBeNull();
expect(stats.hits.length).toBeGreaterThan(0);
});

View File

@@ -0,0 +1,62 @@
// Tests for Windows path support in the `find` filter + autodetect
// Windows absolute paths ("C:\Users\me\src\a.js") carry a drive-letter
// separator that the Unix-only colon check used to reject, so no compaction
// happened for Windows `find`-style dumps. See fix(rtk/find).
import { describe, it, expect } from "vitest";
import { autoDetectFilter } from "../../open-sse/rtk/autodetect.js";
import { find } from "../../open-sse/rtk/filters/find.js";
import { grep } from "../../open-sse/rtk/filters/grep.js";
const WIN_PATHS = [
"C:\\Users\\me\\project\\src\\a.js",
"C:\\Users\\me\\project\\src\\b.js",
"C:\\Users\\me\\project\\src\\c.js"
].join("\n");
const UNIX_PATHS = [
"./src/a.js",
"./src/b.js",
"./src/c.js"
].join("\n");
describe("Windows find-path detection", () => {
it("detects Windows drive-letter paths as `find`", () => {
expect(autoDetectFilter(WIN_PATHS)).toBe(find);
});
it("still detects Unix paths as `find` (no regression)", () => {
expect(autoDetectFilter(UNIX_PATHS)).toBe(find);
});
it("still routes a Windows file:line dump to a compacting filter", () => {
const input = [
"C:\\Users\\me\\project\\src\\a.js:10:const x = 1",
"C:\\Users\\me\\project\\src\\b.js:20:const y = 2",
"C:\\Users\\me\\project\\src\\c.js:30:const z = 3"
].join("\n");
// Each line is grep-shaped (file:line:content), so it routes to `grep`
// — but a drive-letter-only dump would route to `find`. Both are
// compaction-positive, so either is acceptable here.
const f = autoDetectFilter(input);
expect(f).not.toBeNull();
expect([find, grep]).toContain(f);
});
});
describe("Windows find-path grouping", () => {
it("groups Windows backslash paths and normalizes to forward slashes", () => {
const out = find(WIN_PATHS);
expect(out).toContain("3 files in 1 dirs");
expect(out).toContain("C:/Users/me/project/src/");
expect(out).toContain("a.js");
expect(out).toContain("b.js");
expect(out).toContain("c.js");
// backslashes must not leak into output
expect(out).not.toContain("\\");
});
it("compresses the dump (output shorter than input)", () => {
const out = find(WIN_PATHS);
expect(out.length).toBeLessThan(WIN_PATHS.length);
});
});

View File

@@ -0,0 +1,30 @@
import { afterEach, describe, expect, it, vi } from "vitest";
const originalSearxngUrl = process.env.SEARXNG_URL;
async function loadProvider(url) {
if (url === undefined) delete process.env.SEARXNG_URL;
else process.env.SEARXNG_URL = url;
vi.resetModules();
return (await import("../../open-sse/providers/registry/searxng.js")).default;
}
afterEach(() => {
if (originalSearxngUrl === undefined) delete process.env.SEARXNG_URL;
else process.env.SEARXNG_URL = originalSearxngUrl;
vi.resetModules();
});
describe("SearXNG provider configuration", () => {
it("uses SEARXNG_URL when the deployment config supplies one", async () => {
const provider = await loadProvider("http://searxng:8080/search");
expect(provider.searchConfig.baseUrl).toBe("http://searxng:8080/search");
});
it("preserves the loopback default when SEARXNG_URL is unset", async () => {
const provider = await loadProvider(undefined);
expect(provider.searchConfig.baseUrl).toBe("http://localhost:8888/search");
});
});

View File

@@ -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);
});
});

View File

@@ -0,0 +1,40 @@
import { describe, expect, it } from "vitest";
import { applyThinking } from "../../open-sse/translator/concerns/thinkingUnified.js";
import { FORMATS } from "../../open-sse/translator/formats.js";
// Regression: Claude Code sends thinking effort "max" (its top level). When
// 9router routes to an OpenAI-format provider, applyThinking() case "openai"
// must clamp "max"→"xhigh" because OpenAI's reasoning_effort enum has no "max"
// (L.openai caps at "xhigh"). Without the clamp, upstream returns HTTP 400
// "max effort not support". See open-sse/providers/thinkingLevels.js:10.
describe("applyThinking (openai): clamp max effort to xhigh", () => {
it("client output_config.effort:\"max\" → reasoning_effort:\"xhigh\" (not \"max\")", () => {
const body = { output_config: { effort: "max" } };
const out = applyThinking(FORMATS.OPENAI, "gpt-5", body, "openai");
expect(out.reasoning_effort).toBe("xhigh");
});
it("direct reasoning_effort:\"max\" clamped to \"xhigh\"", () => {
const body = { reasoning_effort: "max" };
const out = applyThinking(FORMATS.OPENAI, "gpt-5", body, "openai");
expect(out.reasoning_effort).toBe("xhigh");
});
it("\"xhigh\" passes through unchanged (highest valid OpenAI level)", () => {
const body = { reasoning_effort: "xhigh" };
const out = applyThinking(FORMATS.OPENAI, "gpt-5", body, "openai");
expect(out.reasoning_effort).toBe("xhigh");
});
it("\"high\" passes through unchanged", () => {
const body = { reasoning_effort: "high" };
const out = applyThinking(FORMATS.OPENAI, "gpt-5", body, "openai");
expect(out.reasoning_effort).toBe("high");
});
it("max budget (thinking.budget_tokens:128000) → reasoning_effort:\"xhigh\" (budgetToLevel caps at xhigh)", () => {
const body = { thinking: { type: "enabled", budget_tokens: 128000 } };
const out = applyThinking(FORMATS.OPENAI, "gpt-5", body, "openai");
expect(out.reasoning_effort).toBe("xhigh");
});
});

View File

@@ -0,0 +1,21 @@
import { describe, it, expect } from "vitest";
import { getThinkingLevels } from "../../open-sse/providers/thinkingLevels.js";
describe("getThinkingLevels", () => {
it("adds max for gpt-5.6-sol on codex", () => {
const levels = getThinkingLevels("codex", "gpt-5.6-sol");
expect(levels).toContain("max");
expect(levels).toContain("xhigh");
expect(levels).not.toContain("ultra");
});
it("does not add max for other codex models", () => {
const levels = getThinkingLevels("codex", "gpt-5.3-codex");
expect(levels).toEqual(["low", "medium", "high", "xhigh"]);
});
it("does not add max for other gpt-5.6 models", () => {
const levels = getThinkingLevels("codex", "gpt-5.5");
expect(levels || []).not.toContain("max");
});
});

View File

@@ -15,7 +15,7 @@ const load = () => import("../../open-sse/services/usage.js");
const SUPPORTED = [
"github", "gemini-cli", "antigravity", "claude", "codex", "kiro",
"qoder", "qwen", "iflow", "ollama", "glm", "glm-cn",
"minimax", "minimax-cn", "vercel-ai-gateway", "xai",
"minimax", "minimax-cn", "vercel-ai-gateway", "xai", "grok-cli",
];
describe("usage dispatch", () => {

View File

@@ -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");
});
});

View File

@@ -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();
});
});