Merge remote-tracking branch 'upstream/master'

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