Merge origin/master (v0.5.81) into gitea/new_feature
Resolve conflicts: - streamingHandler.js: merge buildStreamErrorBytes onAbortTerminal + local shouldPersistRequestDetail & streamStatusForContent - capabilities.js: preserve server-injected user-asserted caps and models.dev catalog lookup; wire CommandCode /alpha/generate caps inside resolve() - commandcode.js (services/usage): adopt upstream whoami + billing credits/subscriptions with 5h/weekly rate windows and plan caps - openai-to-commandcode.js: merge toNativeImageBlock (data-URI & http(s) support) and assistant reasoning_content preservation - commandcode-to-openai.js: adopt upstream mid-stream error throw for clean retry and abortion - tests: sync commandcode test suite and exclude .next from vitest config
This commit is contained in:
@@ -44,6 +44,7 @@
|
||||
},
|
||||
"usage": {
|
||||
"quotaApiUrl": "https://daily-cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels",
|
||||
"quotaSummaryApiUrl": "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary",
|
||||
"loadProjectApiUrl": "https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist",
|
||||
"tokenUrl": "https://oauth2.googleapis.com/token"
|
||||
},
|
||||
@@ -131,6 +132,9 @@
|
||||
"HTTP-Referer": "https://cline.bot",
|
||||
"X-Title": "Cline"
|
||||
},
|
||||
"quirks": {
|
||||
"clineEnvelope": true
|
||||
},
|
||||
"tokenUrl": "https://api.cline.bot/api/v1/auth/token",
|
||||
"refreshUrl": "https://api.cline.bot/api/v1/auth/refresh",
|
||||
"auth": {
|
||||
@@ -149,6 +153,9 @@
|
||||
"HTTP-Referer": "https://cline.bot",
|
||||
"X-Title": "Cline"
|
||||
},
|
||||
"quirks": {
|
||||
"clineEnvelope": true
|
||||
},
|
||||
"auth": {
|
||||
"combined": true,
|
||||
"header": "Authorization",
|
||||
@@ -241,6 +248,12 @@
|
||||
"reasoningInject": {
|
||||
"scope": "all"
|
||||
},
|
||||
"quirks": {
|
||||
"claudeSupportedToolTypes": [
|
||||
"web_search_20250305",
|
||||
"web_search_20260209"
|
||||
]
|
||||
},
|
||||
"format": "openai",
|
||||
"transports": [
|
||||
{
|
||||
@@ -438,6 +451,9 @@
|
||||
"groq": {
|
||||
"baseUrl": "https://api.groq.com/openai/v1/chat/completions",
|
||||
"validateUrl": "https://api.groq.com/openai/v1/models",
|
||||
"usage": {
|
||||
"url": "https://api.groq.com/openai/v1/models"
|
||||
},
|
||||
"format": "openai"
|
||||
},
|
||||
"hyperbolic": {
|
||||
@@ -571,7 +587,8 @@
|
||||
"Anthropic-Beta": "claude-code-20250219,interleaved-thinking-2025-05-14"
|
||||
},
|
||||
"quirks": {
|
||||
"dropOutputConfig": true
|
||||
"dropOutputConfig": true,
|
||||
"requireClaudeToolType": true
|
||||
},
|
||||
"reasoningInject": {
|
||||
"scope": "all"
|
||||
@@ -622,7 +639,8 @@
|
||||
"Anthropic-Beta": "claude-code-20250219,interleaved-thinking-2025-05-14"
|
||||
},
|
||||
"quirks": {
|
||||
"dropOutputConfig": true
|
||||
"dropOutputConfig": true,
|
||||
"requireClaudeToolType": true
|
||||
},
|
||||
"reasoningInject": {
|
||||
"scope": "all"
|
||||
@@ -709,6 +727,9 @@
|
||||
"opencode-go": {
|
||||
"baseUrl": "https://opencode.ai/zen/go/v1/chat/completions",
|
||||
"headers": {},
|
||||
"usage": {
|
||||
"url": "https://opencode.ai/zen/go/v1/usage"
|
||||
},
|
||||
"format": "openai",
|
||||
"transports": [
|
||||
{
|
||||
@@ -746,7 +767,13 @@
|
||||
"headers": {
|
||||
"x-opencode-client": "desktop"
|
||||
},
|
||||
"forceStream": true,
|
||||
"noAuth": true,
|
||||
"quirks": {
|
||||
"forceAutoToolChoiceModels": [
|
||||
"muse-spark-1.3-contributor-free"
|
||||
]
|
||||
},
|
||||
"format": "openai"
|
||||
},
|
||||
"openrouter": {
|
||||
@@ -949,6 +976,7 @@
|
||||
"HTTP-Referer": "https://endpoint-proxy.local",
|
||||
"X-Title": "Endpoint Proxy"
|
||||
},
|
||||
"forceStream": true,
|
||||
"format": "openai"
|
||||
},
|
||||
"baidu": {
|
||||
@@ -1010,4 +1038,4 @@
|
||||
},
|
||||
"format": "openai"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -239,7 +239,7 @@ exports[`GOLDEN request: OpenAI → Kiro > full body (image base64 + tool_result
|
||||
"userInputMessage": {
|
||||
"content": "[Context: Current time is <TS>
|
||||
|
||||
continue",
|
||||
Tool results provided.",
|
||||
"modelId": "claude-sonnet-4.5",
|
||||
"origin": "AI_EDITOR",
|
||||
"userInputMessageContext": {
|
||||
@@ -281,7 +281,11 @@ continue",
|
||||
"history": [
|
||||
{
|
||||
"userInputMessage": {
|
||||
"content": "You are helpful.
|
||||
"content": "[Context: Current time is <TS>
|
||||
|
||||
<instructions>
|
||||
You are helpful.
|
||||
</instructions>
|
||||
|
||||
What's in this image?",
|
||||
"images": [
|
||||
|
||||
188
tests/translator/agent-client-fixes.test.js
Normal file
188
tests/translator/agent-client-fixes.test.js
Normal file
@@ -0,0 +1,188 @@
|
||||
// Fixes for agent clients (Claude Code) driving non-Anthropic upstreams:
|
||||
// - tool-result images survive the Claude → OpenAI / Kiro request translation
|
||||
// - Kiro tool calls stream back under the client's own (unsanitized) names
|
||||
// - the client's thinking `display` is kept on Claude-format upstreams
|
||||
import { describe, it, expect } from "vitest";
|
||||
import "./registerAll.js";
|
||||
import { translateRequest, translateResponse, initState } from "../../open-sse/translator/index.js";
|
||||
import { FORMATS } from "../../open-sse/translator/formats.js";
|
||||
import { applyThinking } from "../../open-sse/translator/concerns/thinkingUnified.js";
|
||||
import { kiroToClaudeResponse } from "../../open-sse/translator/response/kiro-to-claude.js";
|
||||
import { kiroToOpenAIResponse } from "../../open-sse/translator/response/kiro-to-openai.js";
|
||||
import { selectAnthropicBeta } from "../../open-sse/providers/shared.js";
|
||||
import { hoistToolResultImages } from "../../open-sse/translator/formats/claude.js";
|
||||
import { openaiToCommandCodeRequest } from "../../open-sse/translator/request/openai-to-commandcode.js";
|
||||
|
||||
const PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";
|
||||
|
||||
const screenshotTurn = (extraTools = []) => ({
|
||||
tools: [
|
||||
{ name: "mcp__browser__computer", description: "browser", input_schema: { type: "object", properties: {} } },
|
||||
...extraTools,
|
||||
],
|
||||
messages: [
|
||||
{ role: "user", content: "take a screenshot" },
|
||||
{ role: "assistant", content: [{ type: "tool_use", id: "toolu_1", name: "mcp__browser__computer", input: { action: "screenshot" } }] },
|
||||
{
|
||||
role: "user",
|
||||
content: [{
|
||||
type: "tool_result",
|
||||
tool_use_id: "toolu_1",
|
||||
content: [
|
||||
{ type: "text", text: "Successfully captured screenshot (1x1, png)" },
|
||||
{ type: "image", source: { type: "base64", media_type: "image/png", data: PNG } },
|
||||
],
|
||||
}],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
describe("tool-result images reach OpenAI-format upstreams", () => {
|
||||
it("emits the tool message text and a follow-up user message carrying the image", () => {
|
||||
const out = translateRequest(FORMATS.CLAUDE, FORMATS.OPENAI, "gpt-x", screenshotTurn(), true, null, "openai");
|
||||
const toolMsg = out.messages.find((m) => m.role === "tool");
|
||||
expect(toolMsg.tool_call_id).toBe("toolu_1");
|
||||
expect(toolMsg.content).toBe("Successfully captured screenshot (1x1, png)");
|
||||
expect(toolMsg.content).not.toContain(PNG);
|
||||
const follow = out.messages[out.messages.indexOf(toolMsg) + 1];
|
||||
expect(follow.role).toBe("user");
|
||||
const image = follow.content.find((p) => p.type === "image_url");
|
||||
expect(image.image_url.url).toBe(`data:image/png;base64,${PNG}`);
|
||||
expect(follow.content.find((p) => p.type === "text").text).toContain("toolu_1");
|
||||
});
|
||||
|
||||
it("does not dump base64 into a tool message that had no text", () => {
|
||||
const body = screenshotTurn();
|
||||
body.messages[2].content[0].content = [{ type: "image", source: { type: "base64", media_type: "image/png", data: PNG } }];
|
||||
const out = translateRequest(FORMATS.CLAUDE, FORMATS.OPENAI, "gpt-x", body, true, null, "openai");
|
||||
const toolMsg = out.messages.find((m) => m.role === "tool");
|
||||
expect(toolMsg.content).toBe("");
|
||||
expect(out.messages.some((m) => Array.isArray(m.content) && m.content.some((p) => p.type === "image_url"))).toBe(true);
|
||||
});
|
||||
|
||||
it("leaves text-only tool results exactly as before", () => {
|
||||
const body = screenshotTurn();
|
||||
body.messages[2].content[0].content = "plain result";
|
||||
const out = translateRequest(FORMATS.CLAUDE, FORMATS.OPENAI, "gpt-x", body, true, null, "openai");
|
||||
const toolMsg = out.messages.find((m) => m.role === "tool");
|
||||
expect(toolMsg.content).toBe("plain result");
|
||||
expect(out.messages[out.messages.length - 1]).toBe(toolMsg);
|
||||
});
|
||||
|
||||
it("forwards tool-result images to Kiro as user images", () => {
|
||||
const out = translateRequest(FORMATS.CLAUDE, FORMATS.KIRO, "claude-sonnet-4.5", screenshotTurn(), true, null, "kiro");
|
||||
const json = JSON.stringify(out.conversationState);
|
||||
expect(json).toContain(PNG);
|
||||
expect(json).toContain("Successfully captured screenshot");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Kiro tool names round-trip", () => {
|
||||
it("returns the sanitized→original map on the translated body", () => {
|
||||
const body = screenshotTurn();
|
||||
body.tools = [{ name: "mcp.browser.computer", description: "browser", input_schema: { type: "object", properties: {} } }];
|
||||
const out = translateRequest(FORMATS.CLAUDE, FORMATS.KIRO, "claude-sonnet-4.5", body, true, null, "kiro");
|
||||
expect(out._toolNameMap).toBeInstanceOf(Map);
|
||||
expect(out._toolNameMap.get("mcp_browser_computer")).toBe("mcp.browser.computer");
|
||||
const wire = JSON.parse(JSON.stringify(out.conversationState));
|
||||
expect(JSON.stringify(wire)).toContain("mcp_browser_computer");
|
||||
expect(JSON.stringify(wire)).not.toContain("mcp.browser.computer");
|
||||
});
|
||||
|
||||
it("omits the map when no name changed", () => {
|
||||
const body = screenshotTurn();
|
||||
body.tools = [{ name: "plain_tool", description: "x", input_schema: { type: "object", properties: {} } }];
|
||||
body.messages[1].content[0].name = "plain_tool";
|
||||
const out = translateRequest(FORMATS.CLAUDE, FORMATS.KIRO, "claude-sonnet-4.5", body, true, null, "kiro");
|
||||
expect(out._toolNameMap).toBeUndefined();
|
||||
});
|
||||
|
||||
it("restores the client name on streamed Claude tool_use blocks", () => {
|
||||
const state = { ...initState(FORMATS.CLAUDE), toolNameMap: new Map([["mcp_browser_computer", "mcp__browser__computer"]]) };
|
||||
const chunk = {
|
||||
id: "c1", object: "chat.completion.chunk", created: 1, model: "claude-sonnet-4.5",
|
||||
choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: "call_1", type: "function", function: { name: "mcp_browser_computer", arguments: "" } }] }, finish_reason: null }],
|
||||
};
|
||||
const events = kiroToClaudeResponse(chunk, state);
|
||||
const start = events.find((e) => e.type === "content_block_start" && e.content_block?.type === "tool_use");
|
||||
expect(start.content_block.name).toBe("mcp__browser__computer");
|
||||
});
|
||||
|
||||
it("passes unknown names through untouched", () => {
|
||||
const state = { ...initState(FORMATS.CLAUDE), toolNameMap: new Map([["mcp_browser_computer", "mcp__browser__computer"]]) };
|
||||
const chunk = {
|
||||
id: "c1", object: "chat.completion.chunk", created: 1, model: "claude-sonnet-4.5",
|
||||
choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: "call_2", type: "function", function: { name: "other_tool", arguments: "" } }] }, finish_reason: null }],
|
||||
};
|
||||
const events = kiroToClaudeResponse(chunk, state);
|
||||
const start = events.find((e) => e.type === "content_block_start" && e.content_block?.type === "tool_use");
|
||||
expect(start.content_block.name).toBe("other_tool");
|
||||
});
|
||||
|
||||
it("restores the client name on OpenAI chunks passed through kiro-to-openai", () => {
|
||||
const state = { ...initState(FORMATS.OPENAI), toolNameMap: new Map([["mcp_browser_computer", "mcp__browser__computer"]]) };
|
||||
const chunk = {
|
||||
id: "c1", object: "chat.completion.chunk", created: 1, model: "claude-sonnet-4.5",
|
||||
choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: "call_1", type: "function", function: { name: "mcp_browser_computer", arguments: "{}" } }] }, finish_reason: null }],
|
||||
};
|
||||
const out = kiroToOpenAIResponse(chunk, state);
|
||||
expect(out.choices[0].delta.tool_calls[0].function.name).toBe("mcp__browser__computer");
|
||||
expect(kiroToOpenAIResponse(chunk, initState(FORMATS.OPENAI))).toBe(chunk);
|
||||
});
|
||||
});
|
||||
|
||||
describe("thinking display is preserved for Claude-format upstreams", () => {
|
||||
it("keeps display on adaptive thinking", () => {
|
||||
const body = { model: "claude-sonnet-5", thinking: { type: "adaptive", display: "summarized" }, output_config: { effort: "high" }, messages: [] };
|
||||
applyThinking(FORMATS.CLAUDE, "claude-sonnet-5", body, "claude");
|
||||
expect(body.thinking).toEqual({ type: "adaptive", display: "summarized" });
|
||||
expect(body.output_config).toEqual({ effort: "high" });
|
||||
});
|
||||
|
||||
it("keeps display on budget thinking and omits it when the client sent none", () => {
|
||||
const withDisplay = { model: "claude-haiku-4-5-20251001", thinking: { type: "adaptive", display: "omitted" }, output_config: { effort: "low" }, messages: [] };
|
||||
applyThinking(FORMATS.CLAUDE, "claude-haiku-4-5-20251001", withDisplay, "claude");
|
||||
expect(withDisplay.thinking.type).toBe("enabled");
|
||||
expect(withDisplay.thinking.display).toBe("omitted");
|
||||
|
||||
const without = { model: "claude-sonnet-5", thinking: { type: "adaptive" }, output_config: { effort: "high" }, messages: [] };
|
||||
applyThinking(FORMATS.CLAUDE, "claude-sonnet-5", without, "claude");
|
||||
expect(without.thinking).toEqual({ type: "adaptive" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("redact-thinking beta follows the client's display request", () => {
|
||||
it("keeps redact-thinking by default and drops it for summarized display", () => {
|
||||
expect(selectAnthropicBeta("claude-sonnet-5")).toContain("redact-thinking-2026-02-12");
|
||||
expect(selectAnthropicBeta("claude-sonnet-5", { thinking: { type: "adaptive", display: "omitted" } })).toContain("redact-thinking-2026-02-12");
|
||||
const summarized = selectAnthropicBeta("claude-sonnet-5", { thinking: { type: "adaptive", display: "summarized" } });
|
||||
expect(summarized).not.toContain("redact-thinking-2026-02-12");
|
||||
expect(summarized).toContain("interleaved-thinking-2025-05-14");
|
||||
expect(summarized).toContain("effort-2025-11-24");
|
||||
});
|
||||
});
|
||||
|
||||
describe("tool-result images reach Anthropic-compatible and Command Code upstreams", () => {
|
||||
it("hoists a tool_result image into the same user turn after the results", () => {
|
||||
const body = screenshotTurn();
|
||||
const out = hoistToolResultImages(body);
|
||||
const user = out.messages[2];
|
||||
expect(user.content[0].type).toBe("tool_result");
|
||||
expect(user.content[0].content.every((c) => c.type !== "image")).toBe(true);
|
||||
expect(user.content.some((c) => c.type === "image" && c.source?.data === PNG)).toBe(true);
|
||||
expect(user.content.find((c) => c.type === "text" && /toolu_1/.test(c.text))).toBeTruthy();
|
||||
// No image: untouched object identity.
|
||||
const plain = { messages: [{ role: "user", content: [{ type: "tool_result", tool_use_id: "x", content: "ok" }] }] };
|
||||
expect(hoistToolResultImages(plain)).toBe(plain);
|
||||
});
|
||||
|
||||
it("sends an image block to Command Code instead of a placeholder", () => {
|
||||
const openaiBody = translateRequest(FORMATS.CLAUDE, FORMATS.OPENAI, "muse-spark", screenshotTurn(), true, null, "commandcode");
|
||||
const out = openaiToCommandCodeRequest("muse-spark", openaiBody, true);
|
||||
const json = JSON.stringify(out);
|
||||
expect(json).not.toContain("[image omitted]");
|
||||
expect(json).toContain(`"type":"image"`);
|
||||
expect(json).toContain(`data:image/png;base64,${PNG}`);
|
||||
expect(json).toContain(`"mediaType":"image/png"`);
|
||||
});
|
||||
});
|
||||
@@ -114,9 +114,7 @@ describe("OpenAI → CommandCode", () => {
|
||||
).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
// openai-to-commandcode.js — image blocks now map to {type:"image", image:"data:..."}
|
||||
// FIXED: was "[image omitted]", now preserved as data URI
|
||||
it("image content is preserved", () => {
|
||||
it("image content is preserved as native CommandCode image blocks", () => {
|
||||
const out = O2CC({
|
||||
messages: [
|
||||
{
|
||||
@@ -131,6 +129,15 @@ describe("OpenAI → CommandCode", () => {
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(JSON.stringify(out), "image omitted").toContain("BBBB");
|
||||
expect(JSON.stringify(out)).toContain("BBBB");
|
||||
expect(JSON.stringify(out)).not.toContain("[image omitted]");
|
||||
expect(out.params.messages[0].content).toMatchObject([
|
||||
{ type: "text", text: "look" },
|
||||
{
|
||||
type: "image",
|
||||
image: "data:image/png;base64,BBBB",
|
||||
mimeType: "image/png",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
110
tests/translator/kiro-tool-name-roundtrip.test.js
Normal file
110
tests/translator/kiro-tool-name-roundtrip.test.js
Normal file
@@ -0,0 +1,110 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { normalizeKiroToolSpecs } from "../../open-sse/translator/concerns/kiroConversation.js";
|
||||
import { openaiToKiroRequest } from "../../open-sse/translator/request/openai-to-kiro.js";
|
||||
import { claudeToKiroRequest } from "../../open-sse/translator/request/claude-to-kiro.js";
|
||||
import { kiroToOpenAIResponse } from "../../open-sse/translator/response/kiro-to-openai.js";
|
||||
import { kiroToClaudeResponse, kiroToClaudeNonStreaming } from "../../open-sse/translator/response/kiro-to-claude.js";
|
||||
|
||||
describe("Kiro tool name normalization and roundtrip", () => {
|
||||
it("preserves consecutive underscores like mcp__gitea__search_repos without collapsing", () => {
|
||||
const { specs, nameMap } = normalizeKiroToolSpecs([
|
||||
{ name: "mcp__gitea__search_repos", description: "Search Gitea" },
|
||||
]);
|
||||
expect(specs).toHaveLength(1);
|
||||
expect(specs[0].toolSpecification.name).toBe("mcp__gitea__search_repos");
|
||||
expect(nameMap.get("mcp__gitea__search_repos")).toBe("mcp__gitea__search_repos");
|
||||
});
|
||||
|
||||
it("builds _toolNameMap for illegal characters and deduplicates colliding names", () => {
|
||||
const tools = [
|
||||
{ name: "my.tool/search", description: "tool 1" },
|
||||
{ name: "my_tool_search", description: "tool 2" },
|
||||
];
|
||||
const openaiPayload = openaiToKiroRequest("claude-sonnet-4.6", {
|
||||
tools: tools.map((t) => ({ type: "function", function: t })),
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
}, true, {});
|
||||
|
||||
expect(openaiPayload._toolNameMap).toBeInstanceOf(Map);
|
||||
// my.tool/search cleaned to my_tool_search. Since my_tool_search comes next, it becomes my_tool_search_2
|
||||
expect(openaiPayload._toolNameMap.get("my_tool_search")).toBe("my.tool/search");
|
||||
|
||||
const claudePayload = claudeToKiroRequest("claude-sonnet-4.6", {
|
||||
tools,
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
}, true, {});
|
||||
|
||||
expect(claudePayload._toolNameMap).toBeInstanceOf(Map);
|
||||
expect(claudePayload._toolNameMap.get("my_tool_search")).toBe("my.tool/search");
|
||||
});
|
||||
|
||||
it("does not attach _toolNameMap when all tool names are legal and unchanged", () => {
|
||||
const tools = [
|
||||
{ name: "mcp__gitea__search_repos", description: "Search Gitea" },
|
||||
{ name: "bash_exec", description: "Run bash" },
|
||||
];
|
||||
const payload = openaiToKiroRequest("claude-sonnet-4.6", {
|
||||
tools: tools.map((t) => ({ type: "function", function: t })),
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
}, true, {});
|
||||
|
||||
expect(payload._toolNameMap).toBeUndefined();
|
||||
});
|
||||
|
||||
it("restores original tool name in kiroToOpenAIResponse when state.toolNameMap is present", () => {
|
||||
const state = {
|
||||
toolNameMap: new Map([["my_tool_search", "my.tool/search"]]),
|
||||
};
|
||||
const event = {
|
||||
toolUseEvent: {
|
||||
toolUseId: "call_123",
|
||||
name: "my_tool_search",
|
||||
input: { q: "test" },
|
||||
},
|
||||
};
|
||||
const chunk = kiroToOpenAIResponse(event, state);
|
||||
expect(chunk).not.toBeNull();
|
||||
expect(chunk.choices[0].delta.tool_calls[0].function.name).toBe("my.tool/search");
|
||||
});
|
||||
|
||||
it("restores original tool name in kiroToClaudeResponse streaming when state.toolNameMap is present", () => {
|
||||
const state = {
|
||||
toolNameMap: new Map([["my_tool_search", "my.tool/search"]]),
|
||||
toolCalls: new Map(),
|
||||
nextBlockIndex: 0,
|
||||
};
|
||||
const chunk = {
|
||||
id: "chatcmpl-1",
|
||||
choices: [{
|
||||
delta: {
|
||||
tool_calls: [{
|
||||
index: 0,
|
||||
id: "call_123",
|
||||
type: "function",
|
||||
function: { name: "my_tool_search", arguments: "" },
|
||||
}],
|
||||
},
|
||||
}],
|
||||
};
|
||||
const events = kiroToClaudeResponse(chunk, state);
|
||||
const startEvent = events.find((e) => e.type === "content_block_start");
|
||||
expect(startEvent).toBeDefined();
|
||||
expect(startEvent.content_block.name).toBe("my.tool/search");
|
||||
});
|
||||
|
||||
it("restores original tool name in kiroToClaudeNonStreaming when toolNameMap is present", () => {
|
||||
const data = {
|
||||
choices: [{
|
||||
message: {
|
||||
tool_calls: [{
|
||||
id: "call_123",
|
||||
function: { name: "my_tool_search", arguments: "{}" },
|
||||
}],
|
||||
},
|
||||
}],
|
||||
toolNameMap: new Map([["my_tool_search", "my.tool/search"]]),
|
||||
};
|
||||
const result = kiroToClaudeNonStreaming(data);
|
||||
expect(result.content[0].name).toBe("my.tool/search");
|
||||
});
|
||||
});
|
||||
@@ -250,6 +250,29 @@ describe("applyThinking per provider format", () => {
|
||||
const out = apply("gemini-cli", "gemini-3.5-flash-lite", { reasoning_effort: "medium" }, "gemini-cli");
|
||||
expect(out.generationConfig.thinkingConfig.thinkingLevel).toBe("medium");
|
||||
});
|
||||
it("commandcode envelope writes params.reasoning_effort, not wrapper fields", () => {
|
||||
const out = apply("commandcode", "deepseek/deepseek-v4.1-flash", {
|
||||
params: { model: "deepseek/deepseek-v4.1-flash", messages: [] },
|
||||
reasoning_effort: "high",
|
||||
}, "commandcode");
|
||||
expect(out.params.reasoning_effort).toBe("high");
|
||||
expect(out.reasoning_effort).toBeUndefined();
|
||||
expect(out.thinking).toBeUndefined();
|
||||
});
|
||||
it("commandcode preserves low effort instead of remapping to high", () => {
|
||||
const out = apply("commandcode", "deepseek/deepseek-v4.1-flash", {
|
||||
params: { messages: [] },
|
||||
reasoning_effort: "low",
|
||||
}, "commandcode");
|
||||
expect(out.params.reasoning_effort).toBe("low");
|
||||
});
|
||||
it("commandcode preserves max effort", () => {
|
||||
const out = apply("commandcode", "deepseek/deepseek-v4.1-flash", {
|
||||
params: { messages: [] },
|
||||
reasoning_effort: "max",
|
||||
}, "commandcode");
|
||||
expect(out.params.reasoning_effort).toBe("max");
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractReasoningText (response shapes)", () => {
|
||||
|
||||
38
tests/unit/account-fallback-4xx.test.js
Normal file
38
tests/unit/account-fallback-4xx.test.js
Normal file
@@ -0,0 +1,38 @@
|
||||
// Regression: an unmatched 4xx (a request-scoped failure) used to hit the
|
||||
// transient-cooldown default, which locked the account for 30s and — with a
|
||||
// single connection — answered every other request in that window with a copy of
|
||||
// the first error. A 400 "maximum context length" from one session therefore
|
||||
// looked like the same failure in unrelated sessions.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { checkFallbackError } from "../../open-sse/services/accountFallback.js";
|
||||
|
||||
describe("checkFallbackError — request-scoped vs account-scoped failures", () => {
|
||||
it("does not cool the account down for a 400 caused by the request", () => {
|
||||
const result = checkFallbackError(400, JSON.stringify({
|
||||
error: {
|
||||
message: "This model's maximum context length is 1048576 tokens. However, you requested 1186139 tokens",
|
||||
type: "invalid_request_error",
|
||||
},
|
||||
}));
|
||||
|
||||
expect(result).toEqual({ shouldFallback: false, cooldownMs: 0 });
|
||||
});
|
||||
|
||||
it("still falls back for account-scoped statuses", () => {
|
||||
for (const status of [401, 402, 403, 404, 429]) {
|
||||
expect(checkFallbackError(status, "nope").shouldFallback).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("still honours rate-limit / quota wording on any 4xx", () => {
|
||||
expect(checkFallbackError(400, "rate limit reached").shouldFallback).toBe(true);
|
||||
expect(checkFallbackError(422, "quota exceeded").shouldFallback).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the transient cooldown for unmatched server errors", () => {
|
||||
const result = checkFallbackError(503, "upstream exploded");
|
||||
|
||||
expect(result.shouldFallback).toBe(true);
|
||||
expect(result.cooldownMs).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
38
tests/unit/antigravity-billing-header-rewrite.test.js
Normal file
38
tests/unit/antigravity-billing-header-rewrite.test.js
Normal file
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { AntigravityExecutor } from "../../open-sse/executors/antigravity.js";
|
||||
import { openaiToAntigravityRequest } from "../../open-sse/translator/request/openai-to-gemini.js";
|
||||
|
||||
const HEADER = "x-anthropic-billing-header: cc_version=2.1.275.f15; cc_entrypoint=cli;";
|
||||
|
||||
function systemTextSentToAntigravity(systemContent) {
|
||||
// OpenAI-format client (e.g. a proxy converting Claude Code to /v1/chat/completions).
|
||||
const body = openaiToAntigravityRequest("gemini-3.8-flash-tiered", {
|
||||
messages: [
|
||||
{ role: "system", content: systemContent },
|
||||
{ role: "user", content: "hi" },
|
||||
],
|
||||
}, true);
|
||||
const finalBody = new AntigravityExecutor().transformRequest("gemini-3.8-flash-tiered", body, true, {});
|
||||
return finalBody.request.systemInstruction.parts.map((p) => p.text).join("\n");
|
||||
}
|
||||
|
||||
describe("Antigravity strips the Claude Code billing header from system prompts", () => {
|
||||
it("removes the header line prepended by Claude Code", () => {
|
||||
const text = systemTextSentToAntigravity(`${HEADER}\n\nYou are Claude Code, Anthropic's official CLI for Claude.`);
|
||||
expect(text).not.toContain("x-anthropic-billing-header");
|
||||
expect(text).toContain("You are Claude Code, Anthropic's official CLI for Claude.");
|
||||
});
|
||||
|
||||
it("removes the header when it is not the first line", () => {
|
||||
const text = systemTextSentToAntigravity(`Some preamble\n${HEADER}\nRest of prompt`);
|
||||
expect(text).not.toContain("x-anthropic-billing-header");
|
||||
expect(text).toContain("Some preamble");
|
||||
expect(text).toContain("Rest of prompt");
|
||||
});
|
||||
|
||||
it("leaves prompts without the header untouched", () => {
|
||||
const text = systemTextSentToAntigravity("You are a helpful assistant.");
|
||||
expect(text).toContain("You are a helpful assistant.");
|
||||
});
|
||||
});
|
||||
104
tests/unit/antigravity-thought-signature-family.test.js
Normal file
104
tests/unit/antigravity-thought-signature-family.test.js
Normal file
@@ -0,0 +1,104 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// Keep the signature store in RAM only; the SQLite kv layer is not under test here.
|
||||
vi.mock("@/lib/db/helpers/kvStore.js", () => ({
|
||||
makeKv: () => ({
|
||||
get: async () => null,
|
||||
set: async () => {},
|
||||
remove: async () => {},
|
||||
getAll: async () => ({}),
|
||||
}),
|
||||
}));
|
||||
|
||||
const {
|
||||
storeGeminiThoughtSignature,
|
||||
getGeminiThoughtSignatureSync,
|
||||
signatureFamily,
|
||||
} = await import("../../open-sse/services/thoughtSignatureStore.js");
|
||||
const { openaiToAntigravityRequest } = await import("../../open-sse/translator/request/openai-to-gemini.js");
|
||||
const { geminiToOpenAIResponse } = await import("../../open-sse/translator/response/gemini-to-openai.js");
|
||||
const { DEFAULT_THINKING_GEMINI_CLI_SIGNATURE } = await import("../../open-sse/config/defaultThinkingSignature.js");
|
||||
|
||||
let n = 0;
|
||||
const uid = (p) => `${p}_${Date.now()}_${n++}`;
|
||||
|
||||
function toolHistory(callId) {
|
||||
return {
|
||||
messages: [
|
||||
{ role: "user", content: "list files" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: callId, type: "function", function: { name: "ls", arguments: "{}" } }] },
|
||||
{ role: "tool", tool_call_id: callId, content: "a.txt" },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function functionCallSignatures(req) {
|
||||
return req.request.contents.flatMap((c) => c.parts || []).filter((p) => p.functionCall).map((p) => p.thoughtSignature);
|
||||
}
|
||||
|
||||
describe("antigravity thought signatures are scoped to the model family", () => {
|
||||
beforeEach(() => { n++; });
|
||||
|
||||
it("classifies model families", () => {
|
||||
expect(signatureFamily("claude-opus-4-6-thinking")).toBe("claude");
|
||||
expect(signatureFamily("gemini-3.8-flash-tiered")).toBe("gemini");
|
||||
expect(signatureFamily("gpt-oss-120b-medium")).toBe("gpt-oss-120b-medium");
|
||||
expect(signatureFamily(null)).toBe(null);
|
||||
});
|
||||
|
||||
it("does not return a Claude signature for a Gemini target (and vice versa)", () => {
|
||||
const claudeCall = uid("toolu");
|
||||
const geminiCall = uid("call");
|
||||
storeGeminiThoughtSignature(claudeCall, "CLAUDE_SIG", "sess", "claude-opus-4-6-thinking");
|
||||
storeGeminiThoughtSignature(geminiCall, "GEMINI_SIG", "sess", "gemini-3.8-flash-tiered");
|
||||
|
||||
expect(getGeminiThoughtSignatureSync(claudeCall, "sess", "gemini-3.8-flash")).toBe(null);
|
||||
expect(getGeminiThoughtSignatureSync(claudeCall, "sess", "claude-opus-4-6-thinking")).toBe("CLAUDE_SIG");
|
||||
expect(getGeminiThoughtSignatureSync(geminiCall, "sess", "gemini-3.7-flash")).toBe("GEMINI_SIG");
|
||||
expect(getGeminiThoughtSignatureSync(geminiCall, null, "claude-sonnet-4-6")).toBe(null);
|
||||
});
|
||||
|
||||
it("keeps old behaviour for untagged entries and untargeted lookups", () => {
|
||||
const call = uid("call");
|
||||
storeGeminiThoughtSignature(call, "LEGACY_SIG", "sess");
|
||||
expect(getGeminiThoughtSignatureSync(call, "sess", "gemini-3.8-flash")).toBe("LEGACY_SIG");
|
||||
|
||||
const tagged = uid("toolu");
|
||||
storeGeminiThoughtSignature(tagged, "CLAUDE_SIG", "sess", "claude-opus-4-6-thinking");
|
||||
expect(getGeminiThoughtSignatureSync(tagged, "sess")).toBe("CLAUDE_SIG");
|
||||
});
|
||||
|
||||
it("records the producing model from the Gemini response stream", () => {
|
||||
const call = uid("toolu_vrtx");
|
||||
const state = { model: "claude-opus-4-6-thinking", sessionId: null, toolNameMap: null };
|
||||
geminiToOpenAIResponse({
|
||||
response: {
|
||||
responseId: "r1",
|
||||
candidates: [{ content: { role: "model", parts: [{ functionCall: { id: call, name: "ls", args: {} }, thoughtSignature: "CLAUDE_SIG" }] } }],
|
||||
},
|
||||
}, state);
|
||||
expect(getGeminiThoughtSignatureSync(call, null, "gemini-3.8-flash-tiered")).toBe(null);
|
||||
expect(getGeminiThoughtSignatureSync(call, null, "claude-opus-4-6-thinking")).toBe("CLAUDE_SIG");
|
||||
});
|
||||
|
||||
it("switching Claude -> Gemini mid-conversation sends the default signature, not Claude's", () => {
|
||||
const call = uid("toolu_vrtx");
|
||||
storeGeminiThoughtSignature(call, "CLAUDE_SIG", null, "claude-opus-4-6-thinking");
|
||||
const req = openaiToAntigravityRequest("gemini-3.8-flash-tiered", toolHistory(call), true);
|
||||
expect(functionCallSignatures(req)).toEqual([DEFAULT_THINKING_GEMINI_CLI_SIGNATURE]);
|
||||
});
|
||||
|
||||
it("switching Gemini -> Claude mid-conversation does not replay Gemini's signature", () => {
|
||||
const call = uid("call");
|
||||
storeGeminiThoughtSignature(call, "GEMINI_SIG", null, "gemini-3.8-flash-tiered");
|
||||
const req = openaiToAntigravityRequest("claude-opus-4-6-thinking", toolHistory(call), true);
|
||||
expect(functionCallSignatures(req)).not.toContain("GEMINI_SIG");
|
||||
});
|
||||
|
||||
it("same model family still reuses the cached signature", () => {
|
||||
const call = uid("call");
|
||||
storeGeminiThoughtSignature(call, "GEMINI_SIG", null, "gemini-3.8-flash-tiered");
|
||||
const req = openaiToAntigravityRequest("gemini-3.8-flash-tiered", toolHistory(call), true);
|
||||
expect(functionCallSignatures(req)).toEqual(["GEMINI_SIG"]);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,24 @@ import { describe, expect, it } from "vitest";
|
||||
import { getCapabilitiesForModel } from "../../open-sse/providers/capabilities.js";
|
||||
|
||||
describe("getCapabilitiesForModel", () => {
|
||||
|
||||
it("reports DeepSeek V4.1-Flash ids as vision-capable without dropping their thinking/context", () => {
|
||||
const v41 = { vision: true, reasoning: true, thinkingFormat: "deepseek", contextWindow: 1000000, maxOutput: 384000 };
|
||||
expect(getCapabilitiesForModel(undefined, "deepseek-v4.1-flash")).toMatchObject(v41);
|
||||
expect(getCapabilitiesForModel("opencode-go", "deepseek-v4.1-flash")).toMatchObject(v41);
|
||||
expect(getCapabilitiesForModel("openrouter", "deepseek/deepseek-v4.1-flash")).toMatchObject(v41);
|
||||
// "deepseek-flash" is the GA id for V4.1-Flash on the DeepSeek API; the pattern it
|
||||
// used to fall through to gives it 128K/64K, which the exact entry keeps.
|
||||
expect(getCapabilitiesForModel("opencode-go", "deepseek-flash")).toMatchObject({
|
||||
vision: true,
|
||||
reasoning: true,
|
||||
thinkingFormat: "deepseek",
|
||||
contextWindow: 128000,
|
||||
maxOutput: 64000,
|
||||
});
|
||||
// the superseded text-only Flash id stays text-only
|
||||
expect(getCapabilitiesForModel("opencode-go", "deepseek-v4-flash").vision).toBe(false);
|
||||
});
|
||||
const claudeSonnet5Expected = {
|
||||
contextWindow: 1000000,
|
||||
maxOutput: 128000,
|
||||
@@ -73,4 +91,26 @@ describe("getCapabilitiesForModel", () => {
|
||||
maxOutput: 128000,
|
||||
});
|
||||
});
|
||||
|
||||
it("CommandCode v4.1-flash is vision + effort capable", () => {
|
||||
expect(getCapabilitiesForModel("commandcode", "deepseek/deepseek-v4.1-flash")).toMatchObject({
|
||||
vision: true,
|
||||
reasoning: true,
|
||||
thinkingFormat: "commandcode",
|
||||
thinkingEffortSupported: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("CommandCode MiniMax-M3 is vision capable", () => {
|
||||
expect(getCapabilitiesForModel("commandcode", "MiniMaxAI/MiniMax-M3").vision).toBe(true);
|
||||
});
|
||||
|
||||
it("CommandCode text-only DeepSeek V4 Flash stays non-vision", () => {
|
||||
expect(getCapabilitiesForModel("commandcode", "deepseek/deepseek-v4-flash").vision).toBe(false);
|
||||
expect(getCapabilitiesForModel("commandcode", "deepseek/deepseek-v4-flash")).toMatchObject({
|
||||
reasoning: true,
|
||||
thinkingFormat: "commandcode",
|
||||
thinkingEffortSupported: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
44
tests/unit/codex-auto-review-routing.test.js
Normal file
44
tests/unit/codex-auto-review-routing.test.js
Normal file
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
getDefaultModel,
|
||||
getModelQuotaFamily,
|
||||
getModelUpstreamId,
|
||||
getProviderModels,
|
||||
} from "../../open-sse/config/providerModels.js";
|
||||
import { getModelInfoCore } from "../../open-sse/services/model.js";
|
||||
|
||||
// Codex CLI's auto-review sends the bare model id "codex-auto-review". Before #1398 it fell
|
||||
// through prefix inference to the "openai" default and failed with
|
||||
// "No active credentials for provider: openai".
|
||||
describe("codex auto-review routing (#1398)", () => {
|
||||
it("routes the bare Codex auto-review model to the OAuth Codex provider", async () => {
|
||||
await expect(getModelInfoCore("codex-auto-review", {})).resolves.toEqual({
|
||||
provider: "codex",
|
||||
model: "codex-auto-review",
|
||||
});
|
||||
});
|
||||
|
||||
it("exposes Codex auto-review as a review-quota Codex model", () => {
|
||||
const autoReview = getProviderModels("cx").find(
|
||||
(model) => model.id === "codex-auto-review",
|
||||
);
|
||||
|
||||
expect(autoReview).toBeTruthy();
|
||||
expect(autoReview.name).toBe("Codex Auto Review");
|
||||
expect(getModelQuotaFamily("cx", "codex-auto-review")).toBe("review");
|
||||
});
|
||||
|
||||
// getModelUpstreamId strips CODEX_REVIEW_SUFFIX from unregistered "cx" ids, which would send
|
||||
// "codex-auto" upstream. This model is not a derived review variant, so it must go out verbatim.
|
||||
it("forwards the id upstream without stripping the -review suffix", () => {
|
||||
expect(getModelUpstreamId("cx", "codex-auto-review")).toBe(
|
||||
"codex-auto-review",
|
||||
);
|
||||
});
|
||||
|
||||
// Registering it must not push it to the front of the cx list — getDefaultModel takes models[0].
|
||||
it("does not become the default Codex model", () => {
|
||||
expect(getDefaultModel("cx")).not.toBe("codex-auto-review");
|
||||
});
|
||||
});
|
||||
@@ -132,6 +132,46 @@ describe("inspectAndWrapCommandCodeResponse", () => {
|
||||
expect(text).toContain("Hello from Laguna");
|
||||
expect(text).toContain("data: [DONE]");
|
||||
});
|
||||
|
||||
it("retries when initial stream yields an error and succeeds on second attempt", async () => {
|
||||
let callCount = 0;
|
||||
const executor = new CommandCodeExecutor();
|
||||
|
||||
// Override execute on instance to test retry behavior
|
||||
executor.execute = async (opts) => {
|
||||
const maxRetries = 2;
|
||||
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
||||
callCount++;
|
||||
let rawResponse;
|
||||
if (callCount === 1) {
|
||||
rawResponse = new Response(createNdjsonStream([
|
||||
JSON.stringify({
|
||||
type: "error",
|
||||
error: { type: "server_error", message: "Network connection lost." }
|
||||
}) + "\n"
|
||||
]), { status: 200, headers: { "Content-Type": "text/event-stream" } });
|
||||
} else {
|
||||
rawResponse = new Response(createNdjsonStream([
|
||||
JSON.stringify({ type: "start" }) + "\n",
|
||||
JSON.stringify({ type: "text-delta", text: "Recovered from lost connection" }) + "\n",
|
||||
JSON.stringify({ type: "finish" }) + "\n"
|
||||
]), { status: 200, headers: { "Content-Type": "text/event-stream" } });
|
||||
}
|
||||
|
||||
const wrappedResponse = await inspectAndWrapCommandCodeResponse(rawResponse, opts.model);
|
||||
if (!wrappedResponse.ok && attempt < maxRetries) {
|
||||
continue;
|
||||
}
|
||||
return { response: wrappedResponse };
|
||||
}
|
||||
};
|
||||
|
||||
const res = await executor.execute({ model: "deepseek/deepseek-v4.1-flash" });
|
||||
expect(res.response.ok).toBe(true);
|
||||
expect(callCount).toBe(2);
|
||||
const text = await res.response.text();
|
||||
expect(text).toContain("Recovered from lost connection");
|
||||
});
|
||||
});
|
||||
|
||||
describe("CommandCode in Combo Fallback", () => {
|
||||
|
||||
@@ -139,25 +139,23 @@ describe("commandcode-to-openai — finish", () => {
|
||||
});
|
||||
|
||||
describe("commandcode-to-openai — error event", () => {
|
||||
it("emits an OpenAI-shaped error chunk instead of fake success content", () => {
|
||||
const { chunks } = feed([
|
||||
{ type: "error", error: { type: "server_error", message: "Boom" } },
|
||||
]);
|
||||
expect(chunks[0].error).toEqual({ message: "Boom", type: "server_error" });
|
||||
expect(chunks[0].choices[0].delta.content).toBeUndefined();
|
||||
expect(chunks[1].choices[0].finish_reason).toBe("stop");
|
||||
expect(JSON.stringify(chunks)).not.toContain("[CommandCode error:");
|
||||
it("throws rather than emitting fake success content with stop chunks", () => {
|
||||
expect(() =>
|
||||
feed([
|
||||
{ type: "error", error: { type: "server_error", message: "Boom" } },
|
||||
]),
|
||||
).toThrow(/\[CommandCode error:.*Boom/);
|
||||
});
|
||||
|
||||
it("keeps the stream terminal so clients do not hang waiting for more", () => {
|
||||
const { chunks } = feed([
|
||||
{ type: "start" },
|
||||
{
|
||||
type: "error",
|
||||
error: { type: "server_error", message: "Network connection lost." },
|
||||
},
|
||||
]);
|
||||
expect(chunks[0].error.message).toBe("Network connection lost.");
|
||||
expect(chunks[1].choices[0].finish_reason).toBe("stop");
|
||||
it("throws on mid-stream error so stream handler can retry or abort cleanly", () => {
|
||||
expect(() =>
|
||||
feed([
|
||||
{ type: "start" },
|
||||
{
|
||||
type: "error",
|
||||
error: { type: "server_error", message: "Network connection lost." },
|
||||
},
|
||||
]),
|
||||
).toThrow(/\[CommandCode error:.*Network connection lost/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,217 +1,135 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("../../open-sse/utils/proxyFetch.js", () => ({
|
||||
proxyAwareFetch: vi.fn(),
|
||||
proxyAwareFetch: vi.fn(),
|
||||
}));
|
||||
|
||||
import { proxyAwareFetch } from "../../open-sse/utils/proxyFetch.js";
|
||||
import { getUsageForProvider } from "../../open-sse/services/usage.js";
|
||||
import {
|
||||
USAGE_SUPPORTED_PROVIDERS,
|
||||
USAGE_APIKEY_PROVIDERS,
|
||||
USAGE_SUPPORTED_PROVIDERS,
|
||||
USAGE_APIKEY_PROVIDERS,
|
||||
} from "../../src/shared/constants/providers.js";
|
||||
import { parseQuotaData } from "../../src/app/(dashboard)/dashboard/usage/components/ProviderLimits/utils.js";
|
||||
|
||||
const BASE = "https://api.commandcode.ai";
|
||||
const WHOAMI_URL = `${BASE}/alpha/whoami`;
|
||||
const CREDITS_URL = `${BASE}/alpha/billing/credits`;
|
||||
const SUBS_URL = `${BASE}/alpha/billing/subscriptions`;
|
||||
const SUMMARY_URL = `${BASE}/alpha/usage/summary`;
|
||||
|
||||
function jsonResponse(body, status = 200) {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
const WHOAMI = { success: true, user: { id: "u1" }, org: null };
|
||||
const WHOAMI = {
|
||||
user: { name: "Hieu", email: "hieu@example.com" },
|
||||
org: { id: "org_1", name: "personal" },
|
||||
};
|
||||
const CREDITS = {
|
||||
credits: {
|
||||
belowThreshold: false,
|
||||
creditThreshold: 0,
|
||||
monthlyCredits: 9.9,
|
||||
purchasedCredits: 0,
|
||||
freeCredits: 0,
|
||||
},
|
||||
windowLimits: {
|
||||
limited: true,
|
||||
exceeded: null,
|
||||
fiveHour: { used: 0.05, cap: 3, exceeded: false, resetAt: 1785812386064 },
|
||||
weekly: { used: 0.1, cap: 6, exceeded: false, resetAt: 1786379982640 },
|
||||
},
|
||||
credits: { monthlyCredits: 12.5, purchasedCredits: 1, freeCredits: 0.5 },
|
||||
windowLimits: {
|
||||
fiveHour: { used: 2, cap: 10, resetAt: Date.now() + 3_600_000, exceeded: false },
|
||||
weekly: { used: 20, cap: 70, resetAt: Date.now() + 86_400_000, exceeded: false },
|
||||
},
|
||||
};
|
||||
const SUBS = {
|
||||
success: true,
|
||||
data: {
|
||||
id: "sub_1",
|
||||
status: "active",
|
||||
orgId: null,
|
||||
planId: "individual-go",
|
||||
currentPeriodStart: "2026-08-03T16:38:16.000Z",
|
||||
currentPeriodEnd: "2026-09-03T16:38:16.000Z",
|
||||
},
|
||||
};
|
||||
const SUMMARY = {
|
||||
totalCount: 61,
|
||||
totalCost: 0.1,
|
||||
totalCredits: 0.1,
|
||||
totalMonthlyCredits: 0.1,
|
||||
periodBasis: "billing-period",
|
||||
data: {
|
||||
planId: "individual-goat",
|
||||
currentPeriodStart: "2026-09-01T00:00:00.000Z",
|
||||
currentPeriodEnd: "2026-10-01T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
|
||||
function mockHappyPath() {
|
||||
proxyAwareFetch.mockImplementation(async (url) => {
|
||||
const u = String(url);
|
||||
if (u.includes("/alpha/whoami")) return jsonResponse(WHOAMI);
|
||||
if (u.includes("/alpha/billing/credits")) return jsonResponse(CREDITS);
|
||||
if (u.includes("/alpha/billing/subscriptions")) return jsonResponse(SUBS);
|
||||
return jsonResponse({ error: "unexpected " + u }, 404);
|
||||
});
|
||||
}
|
||||
|
||||
describe("commandcode registry usage flags", () => {
|
||||
it("is listed for apikey quota dashboard", () => {
|
||||
expect(USAGE_SUPPORTED_PROVIDERS).toContain("commandcode");
|
||||
expect(USAGE_APIKEY_PROVIDERS).toContain("commandcode");
|
||||
});
|
||||
it("is listed for apikey quota dashboard", () => {
|
||||
expect(USAGE_SUPPORTED_PROVIDERS).toContain("commandcode");
|
||||
expect(USAGE_APIKEY_PROVIDERS).toContain("commandcode");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getUsageForProvider(commandcode)", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("fetches whoami → credits+subs → summary and maps windows + credits", async () => {
|
||||
proxyAwareFetch
|
||||
.mockResolvedValueOnce(jsonResponse(WHOAMI))
|
||||
.mockResolvedValueOnce(jsonResponse(CREDITS))
|
||||
.mockResolvedValueOnce(jsonResponse(SUBS))
|
||||
.mockResolvedValueOnce(jsonResponse(SUMMARY));
|
||||
it("returns a message when apiKey is missing", async () => {
|
||||
const usage = await getUsageForProvider({ provider: "commandcode" });
|
||||
expect(usage.message).toMatch(/api key/i);
|
||||
expect(proxyAwareFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const usage = await getUsageForProvider({
|
||||
provider: "commandcode",
|
||||
apiKey: "user_cc_test",
|
||||
});
|
||||
it("GETs whoami, credits, and subscriptions with Bearer apiKey", async () => {
|
||||
mockHappyPath();
|
||||
const usage = await getUsageForProvider({
|
||||
provider: "commandcode",
|
||||
apiKey: "user_test",
|
||||
});
|
||||
|
||||
expect(usage.message).toBeUndefined();
|
||||
expect(usage.plan).toBe("individual-go");
|
||||
expect(usage.periodBasis).toBe("billing-period");
|
||||
expect(usage.message).toBeUndefined();
|
||||
expect(usage.plan).toBe("GOAT");
|
||||
const urls = proxyAwareFetch.mock.calls.map(([url]) => String(url));
|
||||
expect(urls.some((u) => u.startsWith(`${BASE}/alpha/whoami`))).toBe(true);
|
||||
expect(urls.some((u) => u.includes("/alpha/billing/credits") && u.includes("orgId=org_1"))).toBe(true);
|
||||
expect(urls.some((u) => u.includes("/alpha/billing/subscriptions") && u.includes("orgId=org_1"))).toBe(true);
|
||||
expect(proxyAwareFetch.mock.calls[0][1].headers.Authorization).toBe("Bearer user_test");
|
||||
});
|
||||
|
||||
expect(proxyAwareFetch).toHaveBeenCalledTimes(4);
|
||||
const [whoamiUrl, whoamiOpts] = proxyAwareFetch.mock.calls[0];
|
||||
expect(whoamiUrl).toBe(WHOAMI_URL);
|
||||
expect(whoamiOpts.headers.Authorization).toBe("Bearer user_cc_test");
|
||||
it("maps remaining credits vs plan cap and rate windows", async () => {
|
||||
mockHappyPath();
|
||||
const usage = await getUsageForProvider({
|
||||
provider: "commandcode",
|
||||
apiKey: "user_test",
|
||||
});
|
||||
|
||||
// No org → credits/subscriptions called without orgId query
|
||||
const creditsCall = proxyAwareFetch.mock.calls[1][0];
|
||||
expect(creditsCall).toBe(CREDITS_URL);
|
||||
// remaining = 12.5 + 1 + 0.5 = 14; cap GOAT = 70; used = 56
|
||||
expect(usage.quotas.Credits).toMatchObject({
|
||||
used: 56,
|
||||
total: 70,
|
||||
unlimited: false,
|
||||
});
|
||||
expect(usage.quotas["Session (5h)"]).toMatchObject({
|
||||
used: 2,
|
||||
total: 10,
|
||||
unlimited: false,
|
||||
});
|
||||
expect(usage.quotas.Weekly).toMatchObject({
|
||||
used: 20,
|
||||
total: 70,
|
||||
});
|
||||
expect(new Date(usage.quotas.Credits.resetAt).toISOString()).toBe("2026-10-01T00:00:00.000Z");
|
||||
});
|
||||
|
||||
// Summary uses currentPeriodStart as `since`
|
||||
const summaryCall = proxyAwareFetch.mock.calls[3][0];
|
||||
expect(summaryCall).toBe(
|
||||
`${SUMMARY_URL}?since=${encodeURIComponent("2026-08-03T16:38:16.000Z")}`,
|
||||
);
|
||||
|
||||
expect(usage.quotas["5-hour window"]).toMatchObject({
|
||||
used: 0.05,
|
||||
total: 3,
|
||||
resetAt: new Date(1785812386064).toISOString(),
|
||||
});
|
||||
expect(usage.quotas["Weekly window"]).toMatchObject({
|
||||
used: 0.1,
|
||||
total: 6,
|
||||
resetAt: new Date(1786379982640).toISOString(),
|
||||
});
|
||||
// monthlyCredits/purchasedCredits/freeCredits are remaining balances;
|
||||
// total = consumed (summary.totalCredits) + remaining, matching the CLI.
|
||||
expect(usage.quotas["Monthly credits"]).toMatchObject({
|
||||
used: 0.1,
|
||||
total: 10,
|
||||
});
|
||||
});
|
||||
|
||||
it("adds orgId query when whoami returns an org", async () => {
|
||||
proxyAwareFetch
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({ success: true, org: { id: "org_1" } }),
|
||||
)
|
||||
.mockResolvedValueOnce(jsonResponse(CREDITS))
|
||||
.mockResolvedValueOnce(jsonResponse(SUBS))
|
||||
.mockResolvedValueOnce(jsonResponse(SUMMARY));
|
||||
|
||||
await getUsageForProvider({
|
||||
provider: "commandcode",
|
||||
apiKey: "user_cc_test",
|
||||
});
|
||||
|
||||
expect(proxyAwareFetch.mock.calls[1][0]).toBe(`${CREDITS_URL}?orgId=org_1`);
|
||||
expect(proxyAwareFetch.mock.calls[2][0]).toBe(`${SUBS_URL}?orgId=org_1`);
|
||||
});
|
||||
|
||||
it("falls back to first-of-month since when subscription has no period start", async () => {
|
||||
proxyAwareFetch
|
||||
.mockResolvedValueOnce(jsonResponse(WHOAMI))
|
||||
.mockResolvedValueOnce(jsonResponse(CREDITS))
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({ success: true, data: { planId: "individual-go" } }),
|
||||
)
|
||||
.mockResolvedValueOnce(jsonResponse(SUMMARY));
|
||||
|
||||
await getUsageForProvider({
|
||||
provider: "commandcode",
|
||||
apiKey: "user_cc_test",
|
||||
});
|
||||
|
||||
const since = new URL(proxyAwareFetch.mock.calls[3][0]).searchParams.get(
|
||||
"since",
|
||||
);
|
||||
// firstOfMonth() is local-time based; assert the local date is the 1st.
|
||||
const localDate = new Date(since);
|
||||
expect(localDate.getDate()).toBe(1);
|
||||
});
|
||||
|
||||
it("returns message on missing key / 401 / non-ok whoami", async () => {
|
||||
const missing = await getUsageForProvider({ provider: "commandcode" });
|
||||
expect(missing.message).toMatch(/credential/i);
|
||||
expect(proxyAwareFetch).not.toHaveBeenCalled();
|
||||
|
||||
proxyAwareFetch.mockResolvedValueOnce(jsonResponse({ error: "no" }, 401));
|
||||
const auth = await getUsageForProvider({
|
||||
provider: "commandcode",
|
||||
apiKey: "bad",
|
||||
});
|
||||
expect(auth.message).toMatch(/invalid|expired/i);
|
||||
|
||||
proxyAwareFetch.mockResolvedValueOnce(jsonResponse({ error: "x" }, 500));
|
||||
const err = await getUsageForProvider({
|
||||
provider: "commandcode",
|
||||
apiKey: "bad",
|
||||
});
|
||||
expect(err.message).toMatch(/whoami/i);
|
||||
});
|
||||
it("returns an auth message on 401", async () => {
|
||||
proxyAwareFetch.mockResolvedValueOnce(jsonResponse({ error: "unauthorized" }, 401));
|
||||
const usage = await getUsageForProvider({
|
||||
provider: "commandcode",
|
||||
apiKey: "bad",
|
||||
});
|
||||
expect(usage.message).toMatch(/auth|key|login/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseQuotaData(commandcode)", () => {
|
||||
it("forwards remainingPercentage + unit for window/credit rows", () => {
|
||||
const rows = parseQuotaData("commandcode", {
|
||||
plan: "individual-go",
|
||||
quotas: {
|
||||
"5-hour window": {
|
||||
used: 0.05,
|
||||
total: 3,
|
||||
remainingPercentage: 98.33,
|
||||
resetAt: "2026-08-03T22:59:46.064Z",
|
||||
unit: "$",
|
||||
},
|
||||
"Monthly credits": {
|
||||
used: 0.1,
|
||||
total: 10,
|
||||
remainingPercentage: 99,
|
||||
resetAt: null,
|
||||
unit: "$",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(rows[0]).toMatchObject({
|
||||
name: "5-hour window",
|
||||
used: 0.05,
|
||||
total: 3,
|
||||
});
|
||||
expect(rows[1]).toMatchObject({
|
||||
name: "Monthly credits",
|
||||
used: 0.1,
|
||||
total: 10,
|
||||
});
|
||||
});
|
||||
it("forwards used/total/resetAt for the dashboard table", () => {
|
||||
const rows = parseQuotaData("commandcode", {
|
||||
plan: "GOAT",
|
||||
quotas: {
|
||||
Credits: { used: 56, total: 70, resetAt: "2026-10-01T00:00:00.000Z" },
|
||||
"Session (5h)": { used: 2, total: 10, resetAt: "2026-09-16T10:00:00.000Z" },
|
||||
},
|
||||
});
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows[0]).toMatchObject({ name: "Credits", used: 56, total: 70 });
|
||||
expect(rows[1]).toMatchObject({ name: "Session (5h)", used: 2, total: 10 });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -80,6 +80,8 @@ describe("getUsageForProvider(deepseek)", () => {
|
||||
used: 0,
|
||||
total: 12.5,
|
||||
remainingPercentage: 100,
|
||||
isCreditBalance: true,
|
||||
currency: "USD",
|
||||
});
|
||||
expect(usage.quotas["Balance (USD)"].remaining).toBeUndefined();
|
||||
// Zero CNY still listed so user sees currency row
|
||||
|
||||
@@ -71,6 +71,7 @@ vi.mock("../../open-sse/rtk/index.js", () => ({
|
||||
vi.mock("../../open-sse/rtk/headroom.js", () => ({
|
||||
compressWithHeadroom: vi.fn(async () => null),
|
||||
formatHeadroomLog: vi.fn(() => ""),
|
||||
formatHeadroomSizeLog: vi.fn(() => ""),
|
||||
}));
|
||||
|
||||
vi.mock("../../open-sse/providers/capabilities.js", () => ({
|
||||
@@ -88,6 +89,7 @@ vi.mock("../../open-sse/translator/concerns/prefetch.js", () => ({
|
||||
vi.mock("../../open-sse/handlers/chatCore/requestDetail.js", () => ({
|
||||
buildRequestDetail: vi.fn((detail) => detail),
|
||||
extractRequestConfig: vi.fn((body, stream) => ({ body, stream })),
|
||||
shouldPersistRequestDetail: vi.fn(() => false),
|
||||
}));
|
||||
|
||||
vi.mock("../../open-sse/utils/error.js", () => ({
|
||||
|
||||
115
tests/unit/kiro-tool-result-placeholder.test.js
Normal file
115
tests/unit/kiro-tool-result-placeholder.test.js
Normal file
@@ -0,0 +1,115 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { openaiToKiroRequest } from "../../open-sse/translator/request/openai-to-kiro.js";
|
||||
import { claudeToKiroRequest } from "../../open-sse/translator/request/claude-to-kiro.js";
|
||||
import {
|
||||
canonicalizeKiroConversation,
|
||||
KIRO_TOOL_RESULTS_PLACEHOLDER,
|
||||
KIRO_EMPTY_USER_PLACEHOLDER,
|
||||
} from "../../open-sse/translator/concerns/kiroConversation.js";
|
||||
|
||||
const TOOLS_OPENAI = [{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "get_weather",
|
||||
description: "Get weather",
|
||||
parameters: { type: "object", properties: { city: { type: "string" } }, required: ["city"] },
|
||||
},
|
||||
}];
|
||||
|
||||
const TOOLS_CLAUDE = [{
|
||||
name: "get_weather",
|
||||
description: "Get weather",
|
||||
input_schema: { type: "object", properties: { city: { type: "string" } }, required: ["city"] },
|
||||
}];
|
||||
|
||||
function allUserContents(payload) {
|
||||
const state = payload.conversationState;
|
||||
return [
|
||||
...state.history.filter((t) => t.userInputMessage).map((t) => t.userInputMessage.content),
|
||||
state.currentMessage.userInputMessage.content,
|
||||
];
|
||||
}
|
||||
|
||||
describe("Kiro tool-result-only turns", () => {
|
||||
it("OpenAI → Kiro: tool message gets a neutral placeholder, not \"continue\"", () => {
|
||||
const payload = openaiToKiroRequest("claude-sonnet-4.6", {
|
||||
tools: TOOLS_OPENAI,
|
||||
messages: [
|
||||
{ role: "user", content: "The secret word is PINEAPPLE. Weather in Jakarta?" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "call_1", type: "function", function: { name: "get_weather", arguments: "{\"city\":\"Jakarta\"}" } }] },
|
||||
{ role: "tool", tool_call_id: "call_1", content: "32C, humid" },
|
||||
],
|
||||
}, true, {});
|
||||
|
||||
const current = payload.conversationState.currentMessage.userInputMessage;
|
||||
expect(current.content).toContain(KIRO_TOOL_RESULTS_PLACEHOLDER);
|
||||
expect(current.content).not.toMatch(/\bcontinue\b/);
|
||||
expect(current.userInputMessageContext.toolResults).toHaveLength(1);
|
||||
expect(allUserContents(payload).join("\n")).toContain("PINEAPPLE");
|
||||
});
|
||||
|
||||
it("Claude → Kiro: tool_result-only user message gets a neutral placeholder", () => {
|
||||
const payload = claudeToKiroRequest("claude-sonnet-4.6", {
|
||||
tools: TOOLS_CLAUDE,
|
||||
messages: [
|
||||
{ role: "user", content: "The secret word is PINEAPPLE. Weather in Jakarta?" },
|
||||
{ role: "assistant", content: [{ type: "tool_use", id: "toolu_1", name: "get_weather", input: { city: "Jakarta" } }] },
|
||||
{ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_1", content: "32C, humid" }] },
|
||||
],
|
||||
}, true, {});
|
||||
|
||||
const current = payload.conversationState.currentMessage.userInputMessage;
|
||||
expect(current.content).toContain(KIRO_TOOL_RESULTS_PLACEHOLDER);
|
||||
expect(current.content).not.toMatch(/\bcontinue\b/);
|
||||
expect(current.userInputMessageContext.toolResults).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("keeps real user text when a turn has both text and tool results", () => {
|
||||
const payload = claudeToKiroRequest("claude-sonnet-4.6", {
|
||||
tools: TOOLS_CLAUDE,
|
||||
messages: [
|
||||
{ role: "user", content: "Weather in Jakarta?" },
|
||||
{ role: "assistant", content: [{ type: "tool_use", id: "toolu_1", name: "get_weather", input: { city: "Jakarta" } }] },
|
||||
{ role: "user", content: [
|
||||
{ type: "tool_result", tool_use_id: "toolu_1", content: "32C" },
|
||||
{ type: "text", text: "Now answer in one word." },
|
||||
] },
|
||||
],
|
||||
}, true, {});
|
||||
|
||||
const current = payload.conversationState.currentMessage.userInputMessage;
|
||||
expect(current.content).toContain("Now answer in one word.");
|
||||
expect(current.content).not.toContain(KIRO_TOOL_RESULTS_PLACEHOLDER);
|
||||
});
|
||||
|
||||
it("canonicalize: history turn with tool results and no text uses the placeholder", () => {
|
||||
const result = canonicalizeKiroConversation({
|
||||
history: [
|
||||
{ userInputMessage: { content: "Weather in Jakarta?", modelId: "m" } },
|
||||
{ assistantResponseMessage: { content: "", toolUses: [{ toolUseId: "t1", name: "get_weather", input: { city: "Jakarta" } }] } },
|
||||
{ userInputMessage: { content: "", modelId: "m", userInputMessageContext: { toolResults: [{ toolUseId: "t1", status: "success", content: [{ text: "32C" }] }] } } },
|
||||
{ assistantResponseMessage: { content: "It is 32C." } },
|
||||
],
|
||||
currentMessage: { userInputMessage: { content: "Hot or cold?", modelId: "m" } },
|
||||
modelId: "m",
|
||||
toolSpecs: [{ toolSpecification: { name: "get_weather", description: "Get weather", inputSchema: { json: { type: "object", properties: {} } } } }],
|
||||
nameMap: new Map([["get_weather", "get_weather"]]),
|
||||
});
|
||||
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.history[2].userInputMessage.content).toBe(KIRO_TOOL_RESULTS_PLACEHOLDER);
|
||||
});
|
||||
|
||||
it("canonicalize: an empty turn without tool results still falls back to \"continue\"", () => {
|
||||
const result = canonicalizeKiroConversation({
|
||||
history: [{ assistantResponseMessage: { content: "Hello" } }],
|
||||
currentMessage: { userInputMessage: { content: "", modelId: "m" } },
|
||||
modelId: "m",
|
||||
toolSpecs: [],
|
||||
nameMap: new Map(),
|
||||
});
|
||||
|
||||
expect(result.history[0].userInputMessage.content).toBe(KIRO_EMPTY_USER_PLACEHOLDER);
|
||||
expect(result.currentMessage.userInputMessage.content).toBe(KIRO_EMPTY_USER_PLACEHOLDER);
|
||||
});
|
||||
});
|
||||
174
tests/unit/model-catalog-scope.test.js
Normal file
174
tests/unit/model-catalog-scope.test.js
Normal file
@@ -0,0 +1,174 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
// Both modules read their file path from DATA_DIR at import time, so the temp
|
||||
// data dir has to be in place before the first import.
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "9r-catalog-"));
|
||||
process.env.DATA_DIR = dataDir;
|
||||
const catalogFile = path.join(dataDir, "model-catalog.json");
|
||||
|
||||
// One upstream record per gateway: the same short id means different things to
|
||||
// different vendors, which is what used to leak capabilities across providers.
|
||||
const upstream = {
|
||||
zai: { models: { "glm-4.6v": { modalities: { input: ["text", "image"] } } } },
|
||||
// two local ids alias this one upstream provider
|
||||
zhipuai: { models: { "glm-5-canary": { modalities: { input: ["text", "image", "pdf"] } } } },
|
||||
moonshotai: { models: { "kimi-k3": { modalities: { input: ["text"] } } } },
|
||||
kilo: { models: { "kilo-auto/efficient": { modalities: { input: ["text", "image"] } } } },
|
||||
};
|
||||
// The registry snapshot the sync feeds build(): local ids, with the capabilities
|
||||
// the tables resolve on their own.
|
||||
const entries = [
|
||||
{ provider: "glm", model: "glm-4.6v", current: { contextWindow: 200000, maxOutput: 128000 } },
|
||||
{ provider: "glm-cn", model: "glm-5-canary", current: { contextWindow: 200000, maxOutput: 128000 } },
|
||||
{ provider: "zhipu", model: "glm-5-canary", current: { contextWindow: 200000, maxOutput: 128000 } },
|
||||
{ provider: "kimi", model: "kimi-k3", current: { contextWindow: 128000, maxOutput: 32000 } },
|
||||
];
|
||||
|
||||
let build, getCatalogModalities, invalidateCatalog, syncModelCatalog, startModelCatalogSync, capabilities;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ build, syncModelCatalog, startModelCatalogSync } = await import("../../src/lib/modelCatalog/sync.js"));
|
||||
// the builder is exercised directly; a missing export must fail loudly here
|
||||
// rather than skip every case below
|
||||
expect(typeof build).toBe("function");
|
||||
const { models, providers } = build(upstream, entries);
|
||||
fs.writeFileSync(catalogFile, JSON.stringify({ v: 2, models, providers }));
|
||||
({ getCatalogModalities, invalidateCatalog } = await import("../../open-sse/providers/catalogOverride.js"));
|
||||
capabilities = await import("../../open-sse/providers/capabilities.js");
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
fs.rmSync(dataDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("model catalog", () => {
|
||||
it("keys modalities by gateway and writes no model-only key", () => {
|
||||
const { models } = build(upstream, entries);
|
||||
// upstream "zai" is filed under the local id requests arrive with...
|
||||
expect(models["glm:glm-4.6v"]).toEqual({ vision: true });
|
||||
// ...and under its upstream name, because a custom provider node can carry
|
||||
// that name without being in the registry snapshot
|
||||
expect(models["zai:glm-4.6v"]).toEqual({ vision: true });
|
||||
expect(models["kilo:efficient"]).toEqual({ vision: true });
|
||||
// the vendor-stripped key is what used to be shared with every other gateway
|
||||
expect(models["glm-4.6v"]).toBeUndefined();
|
||||
expect(models["efficient"]).toBeUndefined();
|
||||
// a gateway that only declares text has nothing to contribute
|
||||
expect(models["kimi:kimi-k3"]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("files an upstream provider under every local id that aliases it", () => {
|
||||
const { models } = build(upstream, entries);
|
||||
// glm-cn and zhipu are both zhipuai upstream; neither may be dropped
|
||||
expect(models["glm-cn:glm-5-canary"]).toEqual({ vision: true, pdf: true });
|
||||
expect(models["zhipu:glm-5-canary"]).toEqual({ vision: true, pdf: true });
|
||||
expect(models["zhipuai:glm-5-canary"]).toEqual({ vision: true, pdf: true });
|
||||
expect(getCatalogModalities("glm-cn", "glm-5-canary")).toEqual({ vision: true, pdf: true });
|
||||
expect(getCatalogModalities("zhipu", "glm-5-canary")).toEqual({ vision: true, pdf: true });
|
||||
});
|
||||
|
||||
it("does not hand a router mode another vendor's modalities", () => {
|
||||
// kilo's "efficient" is a real model; another gateway's "efficient" is a mode
|
||||
expect(getCatalogModalities("kilo", "kilo-auto/efficient")).toEqual({ vision: true });
|
||||
expect(getCatalogModalities("kilo-gateway", "kilo-auto/efficient")).toBeNull();
|
||||
expect(getCatalogModalities("qoder", "efficient")).toBeNull();
|
||||
});
|
||||
|
||||
it("resolves a gateway the file was written for, and nobody else", () => {
|
||||
expect(getCatalogModalities("glm", "glm-4.6v")).toEqual({ vision: true });
|
||||
expect(getCatalogModalities("zai", "glm-4.6v")).toEqual({ vision: true });
|
||||
expect(getCatalogModalities("unrelated", "glm-4.6v")).toBeNull();
|
||||
expect(getCatalogModalities(undefined, "glm-4.6v")).toBeNull();
|
||||
});
|
||||
|
||||
it("passes the gateway to the catalog reader when refining", () => {
|
||||
const seen = [];
|
||||
capabilities.setCatalogSource({
|
||||
getModalities: (provider) => {
|
||||
seen.push(provider);
|
||||
return provider === "gateway-a" ? { vision: true } : null;
|
||||
},
|
||||
getLimits: () => null,
|
||||
});
|
||||
try {
|
||||
// "*laguna*" resolves from the pattern table, so refine() runs
|
||||
expect(capabilities.getCapabilitiesForModel("gateway-a", "laguna-9-preview").vision).toBe(true);
|
||||
expect(capabilities.getCapabilitiesForModel("gateway-b", "laguna-9-preview").vision).toBe(false);
|
||||
expect(seen).toContain("gateway-a");
|
||||
} finally {
|
||||
capabilities.setCatalogSource(null);
|
||||
}
|
||||
});
|
||||
|
||||
it("shares the installed source with every copy of the module", async () => {
|
||||
const source = {
|
||||
getModalities: (provider) => (provider === "gateway-a" ? { vision: true } : null),
|
||||
getLimits: () => null,
|
||||
};
|
||||
capabilities.setCatalogSource(source);
|
||||
try {
|
||||
// The server bundles this module into more than one chunk and the startup
|
||||
// hook only runs in one of them, so the slot has to be process-wide.
|
||||
expect(globalThis.__9rCatalogSource).toBe(source);
|
||||
const other = await import("../../open-sse/providers/capabilities.js?copy=2");
|
||||
expect(other.getCapabilitiesForModel).not.toBe(capabilities.getCapabilitiesForModel);
|
||||
// ...and that second copy resolves through the source it never installed
|
||||
expect(other.getCapabilitiesForModel("gateway-a", "laguna-9-preview").vision).toBe(true);
|
||||
} finally {
|
||||
capabilities.setCatalogSource(null);
|
||||
}
|
||||
expect(globalThis.__9rCatalogSource).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("catalog schema", () => {
|
||||
it("ignores a file written before the keys were scoped", () => {
|
||||
const scoped = fs.readFileSync(catalogFile);
|
||||
// v1: flat model keys, which is exactly the shape that collided
|
||||
fs.writeFileSync(catalogFile, JSON.stringify({ v: 1, models: { "kimi-k3": { vision: true } }, providers: {} }));
|
||||
invalidateCatalog();
|
||||
expect(getCatalogModalities("kimi", "kimi-k3")).toBeNull();
|
||||
fs.writeFileSync(catalogFile, scoped);
|
||||
invalidateCatalog();
|
||||
});
|
||||
|
||||
it("rebuilds an older-schema file instead of trusting its etag", async () => {
|
||||
fs.writeFileSync(catalogFile, JSON.stringify({ v: 1, etag: 'W/"old"', models: {}, providers: {} }));
|
||||
invalidateCatalog();
|
||||
startModelCatalogSync(); // picks the file's etag + schema version back up
|
||||
|
||||
const sent = [];
|
||||
const realFetch = globalThis.fetch;
|
||||
globalThis.fetch = async (_url, options) => {
|
||||
sent.push(options?.headers || {});
|
||||
return { ok: true, status: 200, headers: new Map([["etag", 'W/"new"']]), json: async () => upstream };
|
||||
};
|
||||
try {
|
||||
expect((await syncModelCatalog()).status).toBe("updated");
|
||||
} finally {
|
||||
globalThis.fetch = realFetch;
|
||||
}
|
||||
expect(sent[0]["if-none-match"]).toBeUndefined();
|
||||
const written = JSON.parse(fs.readFileSync(catalogFile, "utf8"));
|
||||
expect(written.v).toBe(2);
|
||||
expect(written.models["glm:glm-4.6v"]).toEqual({ vision: true });
|
||||
});
|
||||
|
||||
it("asks upstream for a 304 once the file is current", async () => {
|
||||
const sent = [];
|
||||
const realFetch = globalThis.fetch;
|
||||
globalThis.fetch = async (_url, options) => {
|
||||
sent.push(options?.headers || {});
|
||||
return { ok: false, status: 304, headers: new Map(), json: async () => ({}) };
|
||||
};
|
||||
try {
|
||||
expect((await syncModelCatalog()).status).toBe("unchanged");
|
||||
} finally {
|
||||
globalThis.fetch = realFetch;
|
||||
}
|
||||
expect(sent[0]["if-none-match"]).toBe('W/"new"');
|
||||
});
|
||||
});
|
||||
@@ -14,341 +14,222 @@ import { openaiToCommandCodeRequest } from "../../open-sse/translator/request/op
|
||||
const MODEL = "moonshotai/Kimi-K2.6";
|
||||
|
||||
describe("openaiToCommandCodeRequest — basic envelope", () => {
|
||||
it("returns the expected top-level envelope shape", () => {
|
||||
const out = openaiToCommandCodeRequest(
|
||||
MODEL,
|
||||
{
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
},
|
||||
true,
|
||||
);
|
||||
it("returns the expected top-level envelope shape", () => {
|
||||
const out = openaiToCommandCodeRequest(MODEL, {
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
}, true);
|
||||
|
||||
expect(out).toHaveProperty("threadId");
|
||||
expect(out).toHaveProperty("memory");
|
||||
expect(out).toHaveProperty("config");
|
||||
expect(out).toHaveProperty("params");
|
||||
expect(out.params.model).toBe(MODEL);
|
||||
expect(out.params.stream).toBe(true);
|
||||
});
|
||||
expect(out).toHaveProperty("threadId");
|
||||
expect(out).toHaveProperty("memory");
|
||||
expect(out).toHaveProperty("config");
|
||||
expect(out).toHaveProperty("params");
|
||||
expect(out.params.model).toBe(MODEL);
|
||||
expect(out.params.stream).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("openaiToCommandCodeRequest — system handling", () => {
|
||||
it("hoists system messages to params.system (string), not messages[]", () => {
|
||||
const out = openaiToCommandCodeRequest(
|
||||
MODEL,
|
||||
{
|
||||
messages: [
|
||||
{ role: "system", content: "You are concise." },
|
||||
{ role: "user", content: "hi" },
|
||||
],
|
||||
},
|
||||
true,
|
||||
);
|
||||
it("hoists system messages to params.system (string), not messages[]", () => {
|
||||
const out = openaiToCommandCodeRequest(MODEL, {
|
||||
messages: [
|
||||
{ role: "system", content: "You are concise." },
|
||||
{ role: "user", content: "hi" },
|
||||
],
|
||||
}, true);
|
||||
|
||||
expect(typeof out.params.system).toBe("string");
|
||||
expect(out.params.system).toBe("You are concise.");
|
||||
const roles = out.params.messages.map((m) => m.role);
|
||||
expect(roles).not.toContain("system");
|
||||
});
|
||||
expect(typeof out.params.system).toBe("string");
|
||||
expect(out.params.system).toBe("You are concise.");
|
||||
const roles = out.params.messages.map((m) => m.role);
|
||||
expect(roles).not.toContain("system");
|
||||
});
|
||||
|
||||
it("joins multiple system messages with blank line", () => {
|
||||
const out = openaiToCommandCodeRequest(
|
||||
MODEL,
|
||||
{
|
||||
messages: [
|
||||
{ role: "system", content: "A" },
|
||||
{ role: "system", content: "B" },
|
||||
{ role: "user", content: "hi" },
|
||||
],
|
||||
},
|
||||
true,
|
||||
);
|
||||
it("joins multiple system messages with blank line", () => {
|
||||
const out = openaiToCommandCodeRequest(MODEL, {
|
||||
messages: [
|
||||
{ role: "system", content: "A" },
|
||||
{ role: "system", content: "B" },
|
||||
{ role: "user", content: "hi" },
|
||||
],
|
||||
}, true);
|
||||
|
||||
expect(out.params.system).toBe("A\n\nB");
|
||||
});
|
||||
expect(out.params.system).toBe("A\n\nB");
|
||||
});
|
||||
|
||||
it("omits params.system when no system messages", () => {
|
||||
const out = openaiToCommandCodeRequest(
|
||||
MODEL,
|
||||
{
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
},
|
||||
true,
|
||||
);
|
||||
expect(out.params.system).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("openaiToCommandCodeRequest — vision / image blocks", () => {
|
||||
const PNG =
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==";
|
||||
|
||||
it('maps OpenAI image_url (data URI) → {type:"image", image:"data:..."}', () => {
|
||||
const out = openaiToCommandCodeRequest(
|
||||
MODEL,
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: "What color?" },
|
||||
{
|
||||
type: "image_url",
|
||||
image_url: { url: `data:image/png;base64,${PNG}` },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
const blocks = out.params.messages[0].content;
|
||||
expect(blocks[0]).toEqual({ type: "text", text: "What color?" });
|
||||
expect(blocks[1]).toEqual({
|
||||
type: "image",
|
||||
image: `data:image/png;base64,${PNG}`,
|
||||
});
|
||||
});
|
||||
|
||||
it("maps Claude-style image block (source.base64) → data URI with media_type", () => {
|
||||
const out = openaiToCommandCodeRequest(
|
||||
MODEL,
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "image",
|
||||
source: {
|
||||
type: "base64",
|
||||
media_type: "image/jpeg",
|
||||
data: "AAAA",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
expect(out.params.messages[0].content[0]).toEqual({
|
||||
type: "image",
|
||||
image: "data:image/jpeg;base64,AAAA",
|
||||
});
|
||||
});
|
||||
|
||||
it("passes raw URL through when image_url is a remote http(s) URL", () => {
|
||||
const out = openaiToCommandCodeRequest(
|
||||
MODEL,
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "image_url",
|
||||
image_url: { url: "https://example.com/a.png" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
expect(out.params.messages[0].content[0]).toEqual({
|
||||
type: "image",
|
||||
image: "https://example.com/a.png",
|
||||
});
|
||||
});
|
||||
|
||||
it("skips image block when no usable image source", () => {
|
||||
const out = openaiToCommandCodeRequest(
|
||||
MODEL,
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [{ type: "image_url", image_url: { url: "" } }],
|
||||
},
|
||||
],
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
const blocks = out.params.messages[0].content;
|
||||
expect(blocks.every((b) => b.type !== "image")).toBe(true);
|
||||
});
|
||||
it("omits params.system when no system messages", () => {
|
||||
const out = openaiToCommandCodeRequest(MODEL, {
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
}, true);
|
||||
expect(out.params.system).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("openaiToCommandCodeRequest — content shape", () => {
|
||||
it("MUST always emit content as Array (never string) for user", () => {
|
||||
const out = openaiToCommandCodeRequest(
|
||||
MODEL,
|
||||
{
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
},
|
||||
true,
|
||||
);
|
||||
it("MUST always emit content as Array (never string) for user", () => {
|
||||
const out = openaiToCommandCodeRequest(MODEL, {
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
}, true);
|
||||
|
||||
const u = out.params.messages[0];
|
||||
expect(Array.isArray(u.content)).toBe(true);
|
||||
expect(u.content[0]).toEqual({ type: "text", text: "hello" });
|
||||
});
|
||||
const u = out.params.messages[0];
|
||||
expect(Array.isArray(u.content)).toBe(true);
|
||||
expect(u.content[0]).toEqual({ type: "text", text: "hello" });
|
||||
});
|
||||
|
||||
it("MUST always emit content as Array for assistant", () => {
|
||||
const out = openaiToCommandCodeRequest(
|
||||
MODEL,
|
||||
{
|
||||
messages: [
|
||||
{ role: "user", content: "a" },
|
||||
{ role: "assistant", content: "b" },
|
||||
],
|
||||
},
|
||||
true,
|
||||
);
|
||||
const a = out.params.messages[1];
|
||||
expect(Array.isArray(a.content)).toBe(true);
|
||||
expect(a.content[0]).toEqual({ type: "text", text: "b" });
|
||||
});
|
||||
it("MUST always emit content as Array for assistant", () => {
|
||||
const out = openaiToCommandCodeRequest(MODEL, {
|
||||
messages: [
|
||||
{ role: "user", content: "a" },
|
||||
{ role: "assistant", content: "b" },
|
||||
],
|
||||
}, true);
|
||||
const a = out.params.messages[1];
|
||||
expect(Array.isArray(a.content)).toBe(true);
|
||||
expect(a.content[0]).toEqual({ type: "text", text: "b" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("openaiToCommandCodeRequest — tool role / tool-result (AI SDK)", () => {
|
||||
it('converts role:"tool" to role:"tool" with tool-result block; output is {type:"text",value}', () => {
|
||||
const out = openaiToCommandCodeRequest(
|
||||
MODEL,
|
||||
{
|
||||
messages: [
|
||||
{ role: "user", content: "run X" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: null,
|
||||
tool_calls: [
|
||||
{
|
||||
id: "call_1",
|
||||
type: "function",
|
||||
function: { name: "do_x", arguments: '{"a":1}' },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "tool",
|
||||
tool_call_id: "call_1",
|
||||
name: "do_x",
|
||||
content: "RESULT_OK",
|
||||
},
|
||||
],
|
||||
},
|
||||
true,
|
||||
);
|
||||
it("converts role:\"tool\" to role:\"tool\" with tool-result block; output is {type:\"text\",value}", () => {
|
||||
const out = openaiToCommandCodeRequest(MODEL, {
|
||||
messages: [
|
||||
{ role: "user", content: "run X" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: null,
|
||||
tool_calls: [
|
||||
{ id: "call_1", type: "function", function: { name: "do_x", arguments: "{\"a\":1}" } },
|
||||
],
|
||||
},
|
||||
{ role: "tool", tool_call_id: "call_1", name: "do_x", content: "RESULT_OK" },
|
||||
],
|
||||
}, true);
|
||||
|
||||
const toolMsg = out.params.messages[out.params.messages.length - 1];
|
||||
expect(toolMsg.role).toBe("tool");
|
||||
const block = toolMsg.content[0];
|
||||
expect(block.type).toBe("tool-result");
|
||||
expect(block.toolCallId).toBe("call_1");
|
||||
expect(block.toolName).toBe("do_x");
|
||||
expect(block.output).toEqual({ type: "text", value: "RESULT_OK" });
|
||||
});
|
||||
const toolMsg = out.params.messages[out.params.messages.length - 1];
|
||||
expect(toolMsg.role).toBe("tool");
|
||||
const block = toolMsg.content[0];
|
||||
expect(block.type).toBe("tool-result");
|
||||
expect(block.toolCallId).toBe("call_1");
|
||||
expect(block.toolName).toBe("do_x");
|
||||
expect(block.output).toEqual({ type: "text", value: "RESULT_OK" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("openaiToCommandCodeRequest — assistant tool_calls / tool-call", () => {
|
||||
it("converts assistant.tool_calls[] into content blocks of type tool-call", () => {
|
||||
const out = openaiToCommandCodeRequest(
|
||||
MODEL,
|
||||
{
|
||||
messages: [
|
||||
{ role: "user", content: "go" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: null,
|
||||
tool_calls: [
|
||||
{
|
||||
id: "call_42",
|
||||
type: "function",
|
||||
function: { name: "search", arguments: '{"q":"hi"}' },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
true,
|
||||
);
|
||||
it("converts assistant.tool_calls[] into content blocks of type tool-call", () => {
|
||||
const out = openaiToCommandCodeRequest(MODEL, {
|
||||
messages: [
|
||||
{ role: "user", content: "go" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: null,
|
||||
tool_calls: [
|
||||
{ id: "call_42", type: "function", function: { name: "search", arguments: "{\"q\":\"hi\"}" } },
|
||||
],
|
||||
},
|
||||
],
|
||||
}, true);
|
||||
|
||||
const asst = out.params.messages[1];
|
||||
expect(asst.role).toBe("assistant");
|
||||
const tc = asst.content.find((b) => b.type === "tool-call");
|
||||
expect(tc).toBeDefined();
|
||||
expect(tc.toolCallId).toBe("call_42");
|
||||
expect(tc.toolName).toBe("search");
|
||||
expect(tc.input).toEqual({ q: "hi" });
|
||||
});
|
||||
const asst = out.params.messages[1];
|
||||
expect(asst.role).toBe("assistant");
|
||||
const tc = asst.content.find((b) => b.type === "tool-call");
|
||||
expect(tc).toBeDefined();
|
||||
expect(tc.toolCallId).toBe("call_42");
|
||||
expect(tc.toolName).toBe("search");
|
||||
expect(tc.input).toEqual({ q: "hi" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("openaiToCommandCodeRequest — tools schema conversion", () => {
|
||||
it('converts OpenAI {type:"function", function:{...}} to Anthropic plain {name, input_schema}', () => {
|
||||
const out = openaiToCommandCodeRequest(
|
||||
MODEL,
|
||||
{
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
tools: [
|
||||
{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "weather",
|
||||
description: "Get weather",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: { city: { type: "string" } },
|
||||
required: ["city"],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
true,
|
||||
);
|
||||
it("converts OpenAI {type:\"function\", function:{...}} to Anthropic plain {name, input_schema}", () => {
|
||||
const out = openaiToCommandCodeRequest(MODEL, {
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
tools: [
|
||||
{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "weather",
|
||||
description: "Get weather",
|
||||
parameters: { type: "object", properties: { city: { type: "string" } }, required: ["city"] },
|
||||
},
|
||||
},
|
||||
],
|
||||
}, true);
|
||||
|
||||
const t = out.params.tools[0];
|
||||
expect(t.name).toBe("weather");
|
||||
expect(t.input_schema).toBeDefined();
|
||||
expect(t.input_schema.type).toBe("object");
|
||||
expect(t.function).toBeUndefined();
|
||||
expect(t.parameters).toBeUndefined();
|
||||
});
|
||||
const t = out.params.tools[0];
|
||||
expect(t.name).toBe("weather");
|
||||
expect(t.input_schema).toBeDefined();
|
||||
expect(t.input_schema.type).toBe("object");
|
||||
expect(t.function).toBeUndefined();
|
||||
expect(t.parameters).toBeUndefined();
|
||||
});
|
||||
|
||||
it("preserves description on converted tool", () => {
|
||||
const out = openaiToCommandCodeRequest(
|
||||
MODEL,
|
||||
{
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
tools: [
|
||||
{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "ping",
|
||||
description: "Ping the server",
|
||||
parameters: { type: "object" },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
true,
|
||||
);
|
||||
expect(out.params.tools[0].description).toBe("Ping the server");
|
||||
});
|
||||
it("preserves description on converted tool", () => {
|
||||
const out = openaiToCommandCodeRequest(MODEL, {
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
tools: [
|
||||
{ type: "function", function: { name: "ping", description: "Ping the server", parameters: { type: "object" } } },
|
||||
],
|
||||
}, true);
|
||||
expect(out.params.tools[0].description).toBe("Ping the server");
|
||||
});
|
||||
|
||||
it("does not include tools field when input has none", () => {
|
||||
const out = openaiToCommandCodeRequest(
|
||||
MODEL,
|
||||
{
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
},
|
||||
true,
|
||||
);
|
||||
expect(out.params.tools).toBeUndefined();
|
||||
});
|
||||
it("does not include tools field when input has none", () => {
|
||||
const out = openaiToCommandCodeRequest(MODEL, {
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
}, true);
|
||||
expect(out.params.tools).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("openaiToCommandCodeRequest — native image blocks", () => {
|
||||
const PNG_B64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==";
|
||||
const DATA_URI = `data:image/png;base64,${PNG_B64}`;
|
||||
|
||||
it("maps OpenAI image_url data URI to CommandCode {type:image,image,mimeType}", () => {
|
||||
const out = openaiToCommandCodeRequest(MODEL, {
|
||||
messages: [{
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: "what color?" },
|
||||
{ type: "image_url", image_url: { url: DATA_URI } },
|
||||
],
|
||||
}],
|
||||
}, true);
|
||||
|
||||
expect(out.params.messages[0].content).toEqual([
|
||||
{ type: "text", text: "what color?" },
|
||||
{ type: "image", image: DATA_URI, mimeType: "image/png" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("maps Claude/OpenAI base64 image source to a data-URI image block", () => {
|
||||
const out = openaiToCommandCodeRequest(MODEL, {
|
||||
messages: [{
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "image", source: { type: "base64", media_type: "image/png", data: PNG_B64 } },
|
||||
],
|
||||
}],
|
||||
}, true);
|
||||
|
||||
expect(out.params.messages[0].content).toEqual([
|
||||
{ type: "image", image: DATA_URI, mimeType: "image/png" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not stub dropped images as [image omitted]", () => {
|
||||
const out = openaiToCommandCodeRequest(MODEL, {
|
||||
messages: [{
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: "see this" },
|
||||
{ type: "image_url", image_url: { url: DATA_URI } },
|
||||
],
|
||||
}],
|
||||
}, true);
|
||||
|
||||
const texts = out.params.messages[0].content
|
||||
.filter((b) => b.type === "text")
|
||||
.map((b) => b.text);
|
||||
expect(texts).not.toContain("[image omitted]");
|
||||
});
|
||||
});
|
||||
|
||||
90
tests/unit/opencode-free-tool-choice.test.js
Normal file
90
tests/unit/opencode-free-tool-choice.test.js
Normal file
@@ -0,0 +1,90 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { PROVIDERS } from "../../open-sse/config/providers.js";
|
||||
import { OpenCodeExecutor } from "../../open-sse/executors/opencode.js";
|
||||
import { proxyAwareFetch } from "../../open-sse/utils/proxyFetch.js";
|
||||
|
||||
vi.mock("../../open-sse/utils/proxyFetch.js", () => ({
|
||||
proxyAwareFetch: vi.fn(async () => ({ ok: true, status: 200, headers: { get: () => "" } })),
|
||||
}));
|
||||
|
||||
// Break caught: opencode/muse-spark-1.3-contributor-free 400 vì upstream
|
||||
// chỉ nhận tool_choice "auto"; named/required/none phải demote sang "auto".
|
||||
const FREE_13 = "muse-spark-1.3-contributor-free";
|
||||
const CREDS = { connectionId: "opencode-free-tool-choice-test" };
|
||||
const INPUT = [{ type: "message", role: "user", content: [{ type: "input_text", text: "hi" }] }];
|
||||
const TOOLS = [{ type: "function", name: "get_weather", description: "w", parameters: { type: "object", properties: {} } }];
|
||||
|
||||
function responsesBody(model, tool_choice) {
|
||||
const body = { model, input: structuredClone(INPUT), tools: structuredClone(TOOLS) };
|
||||
if (tool_choice !== undefined) body.tool_choice = tool_choice;
|
||||
return body;
|
||||
}
|
||||
|
||||
describe("opencode Free 1.3 tool_choice auto-only", () => {
|
||||
it("khai quirk đúng model 1.3-Free trong registry", () => {
|
||||
expect(PROVIDERS.opencode.quirks?.forceAutoToolChoiceModels).toEqual([FREE_13]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Responses named", { type: "function", name: "get_weather" }],
|
||||
["Chat function named", { type: "function", function: { name: "get_weather" } }],
|
||||
["Claude tool named", { type: "tool", name: "get_weather" }],
|
||||
["required", "required"],
|
||||
["none", "none"],
|
||||
])("demote %s sang auto (plain và max)", (_label, choice) => {
|
||||
for (const model of [FREE_13, `${FREE_13}(max)`]) {
|
||||
const body = responsesBody(model, structuredClone(choice));
|
||||
const out = new OpenCodeExecutor().transformRequest(model, body, true, CREDS);
|
||||
expect(out.tool_choice).toBe("auto");
|
||||
expect(out.tools).toEqual(TOOLS);
|
||||
expect(out.input).toEqual(INPUT);
|
||||
}
|
||||
});
|
||||
|
||||
it("giữ auto và absent; tools/input nguyên vẹn", () => {
|
||||
const autoOut = new OpenCodeExecutor().transformRequest(
|
||||
FREE_13, responsesBody(FREE_13, "auto"), true, CREDS,
|
||||
);
|
||||
expect(autoOut.tool_choice).toBe("auto");
|
||||
expect(autoOut.tools).toEqual(TOOLS);
|
||||
expect(autoOut.input).toEqual(INPUT);
|
||||
|
||||
const absentOut = new OpenCodeExecutor().transformRequest(
|
||||
FREE_13, responsesBody(FREE_13, undefined), true, CREDS,
|
||||
);
|
||||
expect("tool_choice" in absentOut).toBe(false);
|
||||
expect(absentOut.tools).toEqual(TOOLS);
|
||||
expect(absentOut.input).toEqual(INPUT);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["1.2-Free", "muse-spark-1.2-contributor-free"],
|
||||
["future 1.4-Free", "muse-spark-1.4-contributor-free"],
|
||||
["Go id", "muse-spark-1.3-contributor"],
|
||||
["non-Muse", "big-pickle"],
|
||||
])("không đổi tool_choice của %s", (_label, model) => {
|
||||
const choice = { type: "function", name: "get_weather" };
|
||||
const body = responsesBody(model, structuredClone(choice));
|
||||
const out = new OpenCodeExecutor().transformRequest(model, body, true, CREDS);
|
||||
expect(out.tool_choice).toEqual(choice);
|
||||
});
|
||||
|
||||
it("wire: execute gửi choice auto tới /zen/v1/responses", async () => {
|
||||
proxyAwareFetch.mockClear();
|
||||
const ex = new OpenCodeExecutor();
|
||||
const body = responsesBody(FREE_13, { type: "function", name: "get_weather" });
|
||||
const { url, transformedBody } = await ex.execute({
|
||||
model: FREE_13, body, stream: true, credentials: CREDS,
|
||||
});
|
||||
expect(url).toBe("https://opencode.ai/zen/v1/responses");
|
||||
expect(transformedBody.tool_choice).toBe("auto");
|
||||
expect(proxyAwareFetch).toHaveBeenCalledTimes(1);
|
||||
const [actualUrl, actualInit] = proxyAwareFetch.mock.calls[0];
|
||||
expect(actualUrl).toBe("https://opencode.ai/zen/v1/responses");
|
||||
const sent = JSON.parse(actualInit.body);
|
||||
expect(sent.tool_choice).toBe("auto");
|
||||
expect(sent.model).toBe(FREE_13);
|
||||
expect(sent.tools).toEqual(TOOLS);
|
||||
expect(sent.input).toEqual(INPUT);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { PROVIDER_MODELS, getModelSupportedFormats } from "../../open-sse/config/providerModels.js";
|
||||
import { PROVIDER_MODELS, getModelSupportedFormats, getModelTargetFormat } from "../../open-sse/config/providerModels.js";
|
||||
import { PROVIDERS } from "../../open-sse/config/providers.js";
|
||||
import { resolveTransport } from "../../open-sse/services/provider.js";
|
||||
|
||||
@@ -37,6 +37,18 @@ describe("OpenCode Go model catalog", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("OpenCode Go thinking-suffix model lookup", () => {
|
||||
it("preserves Responses routing for gpt-5.6-luna thinking variants", () => {
|
||||
expect(getModelSupportedFormats("opencode-go", "gpt-5.6-luna(high)")).toEqual(["openai-responses"]);
|
||||
expect(getModelTargetFormat("opencode-go", "gpt-5.6-luna(high)")).toBe("openai-responses");
|
||||
});
|
||||
|
||||
it("preserves Responses routing for grok-4.6 thinking variants", () => {
|
||||
expect(getModelSupportedFormats("opencode-go", "grok-4.6(high)")).toEqual(["openai-responses"]);
|
||||
expect(getModelTargetFormat("opencode-go", "grok-4.6(high)")).toBe("openai-responses");
|
||||
});
|
||||
});
|
||||
|
||||
describe("OpenCode Go per-model supportedFormats", () => {
|
||||
it("declares [openai, claude] for MiniMax + Qwen models", () => {
|
||||
for (const m of CLAUDE_CAPABLE) {
|
||||
|
||||
@@ -48,6 +48,22 @@ describe("ocg/muse-spark-1.3-contributor catalog", () => {
|
||||
});
|
||||
|
||||
describe("OpenCodeGoExecutor routing + sanitization", () => {
|
||||
it("routes gpt-5.6-luna to /responses", () => {
|
||||
const ex = new OpenCodeGoExecutor();
|
||||
expect(ex.buildUrl("gpt-5.6-luna")).toBe("https://opencode.ai/zen/go/v1/responses");
|
||||
expect(ex.buildUrl("gpt-5.6-luna(high)", true, 0, {
|
||||
runtimeTransport: { baseUrl: "https://opencode.ai/zen/go/v1/chat/completions" },
|
||||
})).toBe("https://opencode.ai/zen/go/v1/responses");
|
||||
});
|
||||
|
||||
it("routes every responses-only registry model (grok-4.6) to /responses", () => {
|
||||
const ex = new OpenCodeGoExecutor();
|
||||
expect(ex.buildUrl("grok-4.6")).toBe("https://opencode.ai/zen/go/v1/responses");
|
||||
expect(ex.buildUrl("grok-4.6(high)", true, 0, {
|
||||
runtimeTransport: { baseUrl: "https://opencode.ai/zen/go/v1/chat/completions" },
|
||||
})).toBe("https://opencode.ai/zen/go/v1/responses");
|
||||
});
|
||||
|
||||
it("is wired for opencode-go and routes muse-spark to /responses", () => {
|
||||
expect(getExecutor("opencode-go")).toBeInstanceOf(OpenCodeGoExecutor);
|
||||
const ex = new OpenCodeGoExecutor();
|
||||
@@ -120,6 +136,28 @@ describe("OpenCodeGoExecutor routing + sanitization", () => {
|
||||
expect(out.tools.find((t) => t.name === "bare").parameters).toEqual({ type: "object", properties: {} });
|
||||
expect(out.tools.find((t) => t.name === "full").parameters).toEqual({ type: "object", properties: { a: { type: "string" } } });
|
||||
});
|
||||
|
||||
it("strips prior-turn reasoning items carrying encrypted_content from input", () => {
|
||||
const ex = new OpenCodeGoExecutor();
|
||||
const body = {
|
||||
model: MODEL,
|
||||
input: [
|
||||
{ type: "message", role: "user", content: [{ type: "input_text", text: "hi" }] },
|
||||
{
|
||||
type: "reasoning",
|
||||
id: "rs_123",
|
||||
encrypted_content: "ENC_BLOB_TURN_1",
|
||||
summary: [{ type: "summary_text", text: "thinking text" }],
|
||||
},
|
||||
{ type: "function_call", call_id: "c1", name: "read", arguments: "{}" },
|
||||
{ type: "function_call_output", call_id: "c1", output: "ok" },
|
||||
],
|
||||
};
|
||||
const out = ex.transformRequest(MODEL, body, true, {});
|
||||
expect(out.input.some((i) => i.type === "reasoning")).toBe(false);
|
||||
expect(JSON.stringify(out.input)).not.toContain("ENC_BLOB_TURN_1");
|
||||
expect(out.input.map((i) => i.type)).toEqual(["message", "function_call", "function_call_output"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("chat/claude clients translate to Responses without breaking tools", () => {
|
||||
|
||||
@@ -63,6 +63,39 @@ describe("OpenCode Free Muse Spark thinking", () => {
|
||||
expect(out.max_tokens).toBeUndefined();
|
||||
});
|
||||
|
||||
it("routes Union Alpha through Anthropic Messages", () => {
|
||||
const caps = getCapabilitiesForModel(PROVIDER, "union-alpha");
|
||||
expect(caps.vision).toBe(true);
|
||||
expect(caps.contextWindow).toBe(262144);
|
||||
expect(caps.maxOutput).toBe(131072);
|
||||
|
||||
const executor = new OpenCodeExecutor();
|
||||
|
||||
expect(getModelTargetFormat("oc", "union-alpha")).toBe(FORMATS.CLAUDE);
|
||||
const url = executor.buildUrl("union-alpha");
|
||||
expect(url).toBe("https://opencode.ai/zen/v1/messages");
|
||||
expect(executor.buildHeaders({}, true, url)).toMatchObject({
|
||||
"anthropic-version": "2023-06-01",
|
||||
});
|
||||
expect(executor.buildHeaders({}, true, executor.buildUrl("big-pickle")))
|
||||
.not.toHaveProperty("anthropic-version");
|
||||
|
||||
const translated = translateRequest(
|
||||
FORMATS.OPENAI,
|
||||
FORMATS.CLAUDE,
|
||||
"union-alpha",
|
||||
{ messages: [{ role: "user", content: "ping" }], max_tokens: 1 },
|
||||
false,
|
||||
{},
|
||||
PROVIDER,
|
||||
);
|
||||
expect(translated).toMatchObject({
|
||||
model: "union-alpha",
|
||||
messages: [{ role: "user", content: [{ type: "text", text: "ping" }] }],
|
||||
max_tokens: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves the other free models on Chat Completions", () => {
|
||||
const executor = new OpenCodeExecutor();
|
||||
const body = { messages: [{ role: "user", content: "hi" }], max_tokens: 1024 };
|
||||
@@ -132,4 +165,63 @@ describe("OpenCode Free Muse Spark thinking", () => {
|
||||
expect(out.max_tokens).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it("strips prior-turn reasoning items carrying encrypted_content from input", () => {
|
||||
const executor = new OpenCodeExecutor();
|
||||
const model = "muse-spark-1.3-contributor-free";
|
||||
const body = {
|
||||
model,
|
||||
input: [
|
||||
{ type: "message", role: "user", content: [{ type: "input_text", text: "say hi" }] },
|
||||
{
|
||||
type: "reasoning",
|
||||
id: "rs_123",
|
||||
encrypted_content: "ENC_BLOB_TURN_1",
|
||||
summary: [{ type: "summary_text", text: "thinking text" }],
|
||||
},
|
||||
{
|
||||
type: "function_call",
|
||||
id: "fc_1",
|
||||
call_id: "call_1",
|
||||
name: "shell",
|
||||
arguments: JSON.stringify({ command: "echo hi" }),
|
||||
},
|
||||
{
|
||||
type: "function_call_output",
|
||||
call_id: "call_1",
|
||||
output: "hi",
|
||||
},
|
||||
{ type: "message", role: "user", content: [{ type: "input_text", text: "now say bye" }] },
|
||||
],
|
||||
tools: [
|
||||
{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "shell",
|
||||
description: "Run shell command",
|
||||
parameters: { type: "object" },
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const out = executor.transformRequest(model, body, true, {});
|
||||
expect(out.stream).toBe(true);
|
||||
expect(out.store).toBe(false);
|
||||
// Prior reasoning items stripped to prevent 400 "reasoning encrypted_content was not issued to this caller"
|
||||
expect(out.input.some((item) => item.type === "reasoning")).toBe(false);
|
||||
expect(JSON.stringify(out.input)).not.toContain("ENC_BLOB_TURN_1");
|
||||
// User message, function_call, function_call_output, and next user message survive
|
||||
const types = out.input.map((item) => item.type);
|
||||
expect(types).toEqual(["message", "function_call", "function_call_output", "message"]);
|
||||
// Tools flattened and empty properties added
|
||||
expect(out.tools).toEqual([
|
||||
{
|
||||
type: "function",
|
||||
name: "shell",
|
||||
description: "Run shell command",
|
||||
parameters: { type: "object", properties: {} },
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
319
tests/unit/opencode-session.test.js
Normal file
319
tests/unit/opencode-session.test.js
Normal file
@@ -0,0 +1,319 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { fetchMock } = vi.hoisted(() => ({
|
||||
fetchMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../open-sse/utils/proxyFetch.js", () => ({
|
||||
proxyAwareFetch: fetchMock,
|
||||
}));
|
||||
|
||||
import { getExecutor } from "../../open-sse/executors/index.js";
|
||||
import {
|
||||
OPENCODE_SESSION_RE,
|
||||
OPENCODE_REQUEST_RE,
|
||||
generateSessionId,
|
||||
generateRequestId,
|
||||
translateSessionId,
|
||||
stableSessionId,
|
||||
deriveRequestId,
|
||||
} from "../../open-sse/executors/opencode.js";
|
||||
|
||||
function makeCredentials(overrides = {}) {
|
||||
return {
|
||||
connectionId: "conn_test",
|
||||
rawHeaders: {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function prepare(executor, overrides = {}) {
|
||||
const credentials = overrides.credentials || makeCredentials();
|
||||
const prepared = executor.prepareRequestCredentials({
|
||||
body: overrides.body || { input: [{ type: "message", role: "user", content: [{ type: "input_text", text: "hello" }] }] },
|
||||
credentials,
|
||||
providerSessionId: overrides.providerSessionId ?? "conversation-a",
|
||||
clientTool: overrides.clientTool ?? "claude",
|
||||
});
|
||||
return { credentials, prepared };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
fetchMock.mockReset();
|
||||
fetchMock.mockResolvedValue(new Response("{}", {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
}));
|
||||
});
|
||||
|
||||
describe("OpenCode Free Session ID Format", () => {
|
||||
it("generates session IDs matching OpenCode canonical format (ses_ + 12 hex + 14 base62)", () => {
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const id = generateSessionId();
|
||||
expect(id).toMatch(OPENCODE_SESSION_RE);
|
||||
expect(id).toHaveLength(30);
|
||||
}
|
||||
});
|
||||
|
||||
it("generates request IDs matching OpenCode canonical format (msg_ + 12 hex + 14 base62)", () => {
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const id = generateRequestId();
|
||||
expect(id).toMatch(/^msg_[0-9a-f]{12}[0-9A-Za-z]{14}$/);
|
||||
expect(id).toHaveLength(30);
|
||||
}
|
||||
});
|
||||
|
||||
it("translates arbitrary sessions into valid OpenCode session format", () => {
|
||||
const inputs = [
|
||||
"claude:550e8400-e29b-41d4-a716-446655440000",
|
||||
"antigravity:conv-abc-123",
|
||||
"session-from-codex",
|
||||
"12345",
|
||||
"",
|
||||
];
|
||||
for (const raw of inputs) {
|
||||
const translated = translateSessionId(raw, "claude");
|
||||
expect(translated).toMatch(OPENCODE_SESSION_RE);
|
||||
expect(translated).toHaveLength(30);
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves already-valid OpenCode sessions without re-hashing", () => {
|
||||
const valid = "ses_f534dfae8ffeCy4Ee4tLWNygDc";
|
||||
expect(translateSessionId(valid)).toBe(valid);
|
||||
expect(translateSessionId(` ${valid} `)).toBe(valid);
|
||||
});
|
||||
});
|
||||
|
||||
describe("OpenCode Free Executor Session Resolution", () => {
|
||||
it("uses request-local session credentials without mutating source credentials", () => {
|
||||
const executor = getExecutor("opencode");
|
||||
const { credentials, prepared } = prepare(executor);
|
||||
|
||||
expect(executor.constructor.name).toBe("OpenCodeExecutor");
|
||||
expect(prepared).not.toBe(credentials);
|
||||
expect(prepared._opencodeSession).toMatch(OPENCODE_SESSION_RE);
|
||||
expect(credentials).not.toHaveProperty("_opencodeSession");
|
||||
expect(executor).not.toHaveProperty("_currentSessionId");
|
||||
});
|
||||
|
||||
it("preserves valid native x-opencode-session header case-insensitively", () => {
|
||||
const executor = getExecutor("opencode");
|
||||
const valid = "ses_f534dfae8ffeCy4Ee4tLWNygDc";
|
||||
const { prepared } = prepare(executor, {
|
||||
credentials: makeCredentials({ rawHeaders: { "X-OpenCode-Session": ` ${valid} ` } }),
|
||||
});
|
||||
|
||||
expect(prepared._opencodeSession).toBe(valid);
|
||||
});
|
||||
|
||||
it("translates invalid native x-opencode-session header into a valid session", () => {
|
||||
const executor = getExecutor("opencode");
|
||||
const { prepared } = prepare(executor, {
|
||||
credentials: makeCredentials({ rawHeaders: { "x-opencode-session": "invalid-session-uuid" } }),
|
||||
});
|
||||
|
||||
expect(prepared._opencodeSession).toMatch(OPENCODE_SESSION_RE);
|
||||
expect(prepared._opencodeSession).not.toBe("invalid-session-uuid");
|
||||
});
|
||||
|
||||
it("translates conversation session deterministically", () => {
|
||||
const executor = getExecutor("opencode");
|
||||
const first = prepare(executor, { providerSessionId: "conversation-a", clientTool: "claude" }).prepared._opencodeSession;
|
||||
const second = prepare(executor, { providerSessionId: "conversation-a", clientTool: "claude" }).prepared._opencodeSession;
|
||||
|
||||
expect(first).toBe(second);
|
||||
expect(first).toMatch(OPENCODE_SESSION_RE);
|
||||
});
|
||||
|
||||
it("isolates different conversations and tools", () => {
|
||||
const executor = getExecutor("opencode");
|
||||
const convA = prepare(executor, { providerSessionId: "conversation-a" }).prepared._opencodeSession;
|
||||
const convB = prepare(executor, { providerSessionId: "conversation-b" }).prepared._opencodeSession;
|
||||
const toolClaude = prepare(executor, { providerSessionId: "same", clientTool: "claude" }).prepared._opencodeSession;
|
||||
const toolCodex = prepare(executor, { providerSessionId: "same", clientTool: "codex" }).prepared._opencodeSession;
|
||||
|
||||
expect(convA).not.toBe(convB);
|
||||
expect(toolClaude).not.toBe(toolCodex);
|
||||
});
|
||||
|
||||
it("adds the valid session header to fetch requests", async () => {
|
||||
const executor = getExecutor("opencode");
|
||||
const credentials = makeCredentials();
|
||||
const result = await executor.execute({
|
||||
model: "muse-spark-1.3-contributor-free",
|
||||
body: { input: [{ type: "message", role: "user", content: [{ type: "input_text", text: "hello" }] }] },
|
||||
stream: false,
|
||||
credentials,
|
||||
providerSessionId: "conversation-fetch-test",
|
||||
clientTool: "claude",
|
||||
});
|
||||
|
||||
expect(result.headers["x-opencode-session"]).toMatch(OPENCODE_SESSION_RE);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
expect(fetchMock.mock.calls[0][1].headers["x-opencode-session"]).toBe(result.headers["x-opencode-session"]);
|
||||
expect(fetchMock.mock.calls[0][1].headers["Authorization"]).toBe("Bearer public");
|
||||
expect(credentials).not.toHaveProperty("_opencodeSession");
|
||||
});
|
||||
|
||||
it("falls back to a valid generated session in buildHeaders when called standalone", () => {
|
||||
const executor = getExecutor("opencode");
|
||||
const headers = executor.buildHeaders({});
|
||||
|
||||
expect(headers["x-opencode-session"]).toMatch(OPENCODE_SESSION_RE);
|
||||
expect(headers["Authorization"]).toBe("Bearer public");
|
||||
});
|
||||
it("handles null or undefined body gracefully in transformRequest", () => {
|
||||
const executor = getExecutor("opencode");
|
||||
expect(() => executor.transformRequest("muse-spark-1.3-contributor-free", null, false, {})).not.toThrow();
|
||||
expect(() => executor.transformRequest("big-pickle", undefined, false, {})).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("OpenCode Free User-Agent Validation", () => {
|
||||
it("defaults User-Agent to opencode/1.18.31 for non-opencode downstream clients", () => {
|
||||
const executor = getExecutor("opencode");
|
||||
const headersNoUa = executor.buildHeaders({});
|
||||
expect(headersNoUa["User-Agent"]).toBe("opencode/1.18.31");
|
||||
|
||||
const headersClaude = executor.buildHeaders({ rawHeaders: { "user-agent": "Claude-Code/1.0" } });
|
||||
expect(headersClaude["User-Agent"]).toBe("opencode/1.18.31");
|
||||
});
|
||||
|
||||
it("replaces bare opencode with versioned opencode/1.18.31 to prevent 403 FreeTierError", () => {
|
||||
const executor = getExecutor("opencode");
|
||||
const headers = executor.buildHeaders({ rawHeaders: { "user-agent": "opencode" } });
|
||||
expect(headers["User-Agent"]).toBe("opencode/1.18.31");
|
||||
});
|
||||
|
||||
it("upgrades outdated opencode versions (< 1.17) to prevent 426 Upgrade Required", () => {
|
||||
const executor = getExecutor("opencode");
|
||||
const headers = executor.buildHeaders({ rawHeaders: { "user-agent": "opencode/1.15.0" } });
|
||||
expect(headers["User-Agent"]).toBe("opencode/1.18.31");
|
||||
});
|
||||
|
||||
it("preserves valid opencode versions (>= 1.17)", () => {
|
||||
const executor = getExecutor("opencode");
|
||||
const headers118 = executor.buildHeaders({
|
||||
rawHeaders: { "user-agent": "opencode/1.18.31 ai-sdk/provider-utils/4.0.40 runtime/bun/1.3.14" },
|
||||
});
|
||||
expect(headers118["User-Agent"]).toBe("opencode/1.18.31 ai-sdk/provider-utils/4.0.40 runtime/bun/1.3.14");
|
||||
|
||||
const headersFuture = executor.buildHeaders({ rawHeaders: { "user-agent": "opencode/1.19.0" } });
|
||||
expect(headersFuture["User-Agent"]).toBe("opencode/1.19.0");
|
||||
});
|
||||
});
|
||||
|
||||
describe("OpenCode Stable Session Reuse (429 follow-up)", () => {
|
||||
function anonymousCredentials(auth) {
|
||||
return makeCredentials({ connectionId: undefined, rawHeaders: { authorization: `Bearer ${auth}` } });
|
||||
}
|
||||
|
||||
it("reuses one stable upstream session instead of minting a new one per request", () => {
|
||||
const executor = getExecutor("opencode");
|
||||
const body = { messages: [{ role: "user", content: "hello" }] };
|
||||
const first = executor.prepareRequestCredentials({
|
||||
body,
|
||||
credentials: anonymousCredentials("stable-key-1"),
|
||||
providerSessionId: null,
|
||||
clientTool: "claude",
|
||||
});
|
||||
const second = executor.prepareRequestCredentials({
|
||||
body,
|
||||
credentials: anonymousCredentials("stable-key-1"),
|
||||
providerSessionId: null,
|
||||
clientTool: "claude",
|
||||
});
|
||||
|
||||
expect(first._opencodeSession).toMatch(OPENCODE_SESSION_RE);
|
||||
expect(second._opencodeSession).toBe(first._opencodeSession);
|
||||
});
|
||||
|
||||
it("isolates stable sessions by downstream identity", () => {
|
||||
const executor = getExecutor("opencode");
|
||||
const body = { messages: [{ role: "user", content: "hello" }] };
|
||||
const forKey = (auth) => executor.prepareRequestCredentials({
|
||||
body,
|
||||
credentials: anonymousCredentials(auth),
|
||||
providerSessionId: null,
|
||||
clientTool: "claude",
|
||||
})._opencodeSession;
|
||||
|
||||
expect(forKey("user-A")).not.toBe(forKey("user-B"));
|
||||
expect(forKey("user-A")).toMatch(OPENCODE_SESSION_RE);
|
||||
});
|
||||
|
||||
it("exposes the stable session helper directly", () => {
|
||||
const first = stableSessionId({ connectionId: "direct-conn" });
|
||||
expect(stableSessionId({ connectionId: "direct-conn" })).toBe(first);
|
||||
expect(first).toMatch(OPENCODE_SESSION_RE);
|
||||
});
|
||||
|
||||
it("derives deterministic, canonical request ids per message", () => {
|
||||
const session = stableSessionId({ connectionId: "req-conn" });
|
||||
const body = { messages: [{ role: "user", content: "ping" }] };
|
||||
const first = deriveRequestId(session, body);
|
||||
expect(first).toMatch(OPENCODE_REQUEST_RE);
|
||||
expect(deriveRequestId(session, body)).toBe(first);
|
||||
expect(
|
||||
deriveRequestId(session, { messages: [{ role: "user", content: "a different question" }] }),
|
||||
).not.toBe(first);
|
||||
});
|
||||
|
||||
it("preserves a valid downstream x-opencode-request header", () => {
|
||||
const executor = getExecutor("opencode");
|
||||
const validReq = "msg_0ae8d9cd3001swxaFbM248jcIF";
|
||||
const { prepared } = prepare(executor, {
|
||||
credentials: makeCredentials({ rawHeaders: { "x-opencode-request": validReq } }),
|
||||
});
|
||||
expect(prepared._opencodeRequest).toBe(validReq);
|
||||
});
|
||||
|
||||
it("keeps the standalone buildHeaders session stable across calls", () => {
|
||||
const executor = getExecutor("opencode");
|
||||
const first = executor.buildHeaders({})["x-opencode-session"];
|
||||
const second = executor.buildHeaders({})["x-opencode-session"];
|
||||
expect(first).toMatch(OPENCODE_SESSION_RE);
|
||||
expect(second).toBe(first);
|
||||
});
|
||||
|
||||
it("cloaks free-tier requests with bash and read decoy tools", () => {
|
||||
const executor = getExecutor("opencode");
|
||||
|
||||
// Case 1: no tools sent by client -> injects bash + read with tool_choice none
|
||||
const chatNoTools = executor.transformRequest("nemotron-3-ultra-free", {
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
});
|
||||
expect(chatNoTools.stream).toBe(true);
|
||||
expect(chatNoTools.tool_choice).toBe("none");
|
||||
expect(chatNoTools.tools.map((t) => t.function?.name)).toEqual(["bash", "read"]);
|
||||
|
||||
// Case 2: external CLI tools (e.g. Claude Code Bash) -> preserves Bash, appends read
|
||||
const chatWithTools = executor.transformRequest("nemotron-3-ultra-free", {
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
tools: [{ type: "function", function: { name: "Bash", description: "Claude Code tool" } }],
|
||||
tool_choice: "auto",
|
||||
});
|
||||
expect(chatWithTools.tool_choice).toBe("auto");
|
||||
const names = chatWithTools.tools.map((t) => t.function?.name);
|
||||
expect(names).toContain("Bash");
|
||||
expect(names).toContain("bash");
|
||||
expect(names).toContain("read");
|
||||
|
||||
// Case 3: already has both bash and read -> do not insert anything
|
||||
const chatFull = executor.transformRequest("nemotron-3-ultra-free", {
|
||||
messages: [{ role: "user", content: "hi" }],
|
||||
tools: [
|
||||
{ type: "function", function: { name: "bash", description: "existing" } },
|
||||
{ type: "function", function: { name: "read", description: "existing" } },
|
||||
],
|
||||
});
|
||||
expect(chatFull.tools.length).toBe(2);
|
||||
expect(chatFull.tools[0].function.description).toBe("existing");
|
||||
});
|
||||
|
||||
it("declares forceStream on the opencode transport so chatCore serves SSE upstream", async () => {
|
||||
const { PROVIDERS } = await import("../../open-sse/config/providers.js");
|
||||
expect(PROVIDERS.opencode?.forceStream).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -55,4 +55,21 @@ describe("prefetchRemoteImages", () => {
|
||||
expect(n).toBe(1);
|
||||
expect(body.messages[0].content[0].source.type).toBe("base64");
|
||||
});
|
||||
|
||||
it("openai source -> commandcode target: converts remote URL to base64", async () => {
|
||||
const body = { messages: [{ role: "user", content: [{ type: "image_url", image_url: { url: "https://x/a.png" } }] }] };
|
||||
const n = await prefetchRemoteImages(body, FORMATS.OPENAI, FORMATS.COMMANDCODE);
|
||||
expect(n).toBe(1);
|
||||
expect(body.messages[0].content[0].image_url.url.startsWith("data:image/png;base64,")).toBe(true);
|
||||
expect(fetchImageAsBase64).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("claude source -> commandcode target: source.url -> base64", async () => {
|
||||
const body = { messages: [{ role: "user", content: [
|
||||
{ type: "image", source: { type: "url", url: "https://x/a.png" } },
|
||||
] }] };
|
||||
const n = await prefetchRemoteImages(body, FORMATS.CLAUDE, FORMATS.COMMANDCODE);
|
||||
expect(n).toBe(1);
|
||||
expect(body.messages[0].content[0].source.type).toBe("base64");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createDisconnectAwareStream } from "../../open-sse/utils/streamHandler.js";
|
||||
import { createDisconnectAwareStream, pipeWithDisconnect, createStreamController } from "../../open-sse/utils/streamHandler.js";
|
||||
import { buildAbortedResponsesTerminalBytes } from "../../open-sse/utils/responsesStreamHelpers.js";
|
||||
import { buildStreamErrorBytes } from "../../open-sse/utils/streamHelpers.js";
|
||||
import { FORMATS } from "../../open-sse/translator/formats.js";
|
||||
|
||||
// Minimal stream controller stub
|
||||
function makeController() {
|
||||
@@ -70,3 +72,71 @@ describe("Responses abort terminal synthesis", () => {
|
||||
expect(text).not.toContain("[DONE]");
|
||||
});
|
||||
});
|
||||
|
||||
// A stream that aborts after HTTP 200 cannot change status, so the failure must
|
||||
// travel in-band: structured error frame first, then [DONE]. openai-python raises
|
||||
// APIError on any `data:` payload carrying an `error` key (checked before [DONE]);
|
||||
// Anthropic clients need `event: error`. Never a fabricated finish_reason.
|
||||
describe("buildStreamErrorBytes", () => {
|
||||
const jsonOf = (sse) => JSON.parse(sse.match(/\{.*\}/s)[0]);
|
||||
const textOf = (bytes) => new TextDecoder().decode(bytes);
|
||||
|
||||
// onAbortTerminal callbacks are enqueued verbatim, so a string here is a
|
||||
// silent no-op at runtime (createDisconnectAwareStream swallows the throw).
|
||||
it("returns bytes, not a string", () => {
|
||||
expect(buildStreamErrorBytes(504, "x", FORMATS.OPENAI)).toBeInstanceOf(Uint8Array);
|
||||
});
|
||||
|
||||
it("emits error frame then [DONE] for OpenAI clients", () => {
|
||||
const out = textOf(buildStreamErrorBytes(504, "stream stall timeout", FORMATS.OPENAI));
|
||||
|
||||
expect(out).toContain('data: {"error"');
|
||||
expect(out.indexOf("data: [DONE]")).toBeGreaterThan(out.indexOf('data: {"error"'));
|
||||
|
||||
expect(jsonOf(out).error).toEqual({
|
||||
message: "stream stall timeout",
|
||||
type: "server_error",
|
||||
code: "gateway_timeout",
|
||||
});
|
||||
});
|
||||
|
||||
it("emits event: error (no [DONE]) for Claude clients", () => {
|
||||
const out = textOf(buildStreamErrorBytes(504, "stream stall timeout", FORMATS.CLAUDE));
|
||||
|
||||
expect(out).toContain("event: error\n");
|
||||
expect(out).not.toContain("[DONE]");
|
||||
expect(jsonOf(out)).toMatchObject({ type: "error", error: { message: "stream stall timeout" } });
|
||||
});
|
||||
});
|
||||
|
||||
// The wiring, not just the frame builder: the watchdog must hand its reason to
|
||||
// onAbortTerminal and the bytes must reach a real consumer.
|
||||
describe("stall abort through pipeWithDisconnect", () => {
|
||||
it("delivers the error frame and closes the stream", async () => {
|
||||
// Real controller: the stub above never fires its signal, and the abort
|
||||
// must reach the upstream body for the pipe to end.
|
||||
const ctrl = createStreamController({ provider: "ollama", model: "test" });
|
||||
|
||||
// Emits one chunk then goes silent; errors on abort like a real fetch body.
|
||||
const upstream = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode("data: hi\n\n"));
|
||||
ctrl.signal.addEventListener("abort", () => controller.error(new Error("aborted")), { once: true });
|
||||
},
|
||||
});
|
||||
|
||||
let seen = null;
|
||||
const out = pipeWithDisconnect(
|
||||
{ body: upstream },
|
||||
new TransformStream(),
|
||||
ctrl,
|
||||
(message) => { seen = message; return buildStreamErrorBytes(504, message, FORMATS.OPENAI); },
|
||||
50
|
||||
);
|
||||
|
||||
const text = await readAll(out);
|
||||
expect(seen).toBe("stream stall timeout");
|
||||
expect(text).toContain('"stream stall timeout"');
|
||||
expect(text).toContain("data: [DONE]");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -16,7 +16,7 @@ const SUPPORTED = [
|
||||
"github", "gemini-cli", "antigravity", "claude", "codex", "kiro",
|
||||
"qoder", "iflow", "ollama", "glm", "glm-cn",
|
||||
"minimax", "minimax-cn", "vercel-ai-gateway", "grok-cli", "kimi",
|
||||
"deepseek", "opencode-go", "zed",
|
||||
"deepseek", "opencode-go", "zed", "commandcode",
|
||||
];
|
||||
|
||||
describe("usage dispatch", () => {
|
||||
|
||||
121
tests/unit/zed-completions-wire.test.js
Normal file
121
tests/unit/zed-completions-wire.test.js
Normal file
@@ -0,0 +1,121 @@
|
||||
// Zed completions wire acceptance: the `provider` field of POST /completions
|
||||
// must use cloud.zed.dev's exact wire values (anthropic/open_ai/google/x_ai),
|
||||
// and the Zed Gemini path must not carry the shared translator's
|
||||
// safetySettings (Zed's hosted Gemini backend speaks the Vertex safety
|
||||
// vocabulary, not the public-Gemini enums).
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
|
||||
vi.mock("open-sse/shared/zedAuth.js", async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
resolveZedModels: vi.fn(),
|
||||
zedLlmFetch: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
import {
|
||||
resolveZedModels,
|
||||
zedLlmFetch,
|
||||
} from "open-sse/shared/zedAuth.js";
|
||||
import ZedExecutor from "open-sse/executors/zed.js";
|
||||
|
||||
function catalogFor(entries) {
|
||||
const rawById = new Map(entries);
|
||||
return { rawById, models: [] };
|
||||
}
|
||||
|
||||
function mockCatalogFetch(captured) {
|
||||
zedLlmFetch.mockImplementation(async (credentials, path, options) => {
|
||||
captured.body = JSON.parse(options.fetchOptions.body);
|
||||
return new Response("upstream-error-stub", { status: 500 });
|
||||
});
|
||||
}
|
||||
|
||||
function makeExecutor() {
|
||||
const executor = new ZedExecutor();
|
||||
executor.config = {};
|
||||
return executor;
|
||||
}
|
||||
|
||||
const CHAT_BODY = { messages: [{ role: "user", content: "hi" }] };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("wire provider enum", () => {
|
||||
it.each([
|
||||
["Anthropic", "anthropic"],
|
||||
["anthropic", "anthropic"],
|
||||
["OpenAi", "open_ai"],
|
||||
["open_ai", "open_ai"],
|
||||
["Google", "google"],
|
||||
["gemini", "google"],
|
||||
["XAi", "x_ai"],
|
||||
["x_ai", "x_ai"],
|
||||
])("catalog provider %j normalizes to wire %j", async (catalogValue, wire) => {
|
||||
resolveZedModels.mockResolvedValue(catalogFor([["m", { provider: catalogValue }]]));
|
||||
const executor = makeExecutor();
|
||||
const { provider } = await executor.resolveModel("m", {}, null, null);
|
||||
expect(provider).toBe(wire);
|
||||
});
|
||||
|
||||
it("infers wire provider from the model id when the catalog is unavailable", async () => {
|
||||
resolveZedModels.mockRejectedValue(new Error("catalog down"));
|
||||
const executor = makeExecutor();
|
||||
const log = { warn: vi.fn() };
|
||||
expect((await executor.resolveModel("claude-opus-x", {}, null, log)).provider).toBe("anthropic");
|
||||
expect((await executor.resolveModel("gemini-3-x", {}, null, log)).provider).toBe("google");
|
||||
expect((await executor.resolveModel("grok-4-x", {}, null, log)).provider).toBe("x_ai");
|
||||
expect((await executor.resolveModel("gpt-5-x", {}, null, log)).provider).toBe("open_ai");
|
||||
});
|
||||
});
|
||||
|
||||
describe("completion payload shaping", () => {
|
||||
it("sends wire provider values per model family", async () => {
|
||||
resolveZedModels.mockImplementation(async () => catalogFor([
|
||||
["claude-x", { provider: "anthropic" }],
|
||||
["gpt-x", { provider: "open_ai" }],
|
||||
["gemini-x", { provider: "google" }],
|
||||
["grok-x", { provider: "x_ai" }],
|
||||
]));
|
||||
const captured = {};
|
||||
mockCatalogFetch(captured);
|
||||
const executor = makeExecutor();
|
||||
|
||||
for (const [model, wire] of [
|
||||
["claude-x", "anthropic"],
|
||||
["gpt-x", "open_ai"],
|
||||
["gemini-x", "google"],
|
||||
["grok-x", "x_ai"],
|
||||
]) {
|
||||
await executor.execute({ model, body: { ...CHAT_BODY }, stream: false, credentials: {} });
|
||||
expect(captured.body.provider).toBe(wire);
|
||||
expect(captured.body.model).toBe(model);
|
||||
}
|
||||
});
|
||||
|
||||
it("strips safetySettings on the Zed Gemini path only", async () => {
|
||||
resolveZedModels.mockImplementation(async () => catalogFor([
|
||||
["gemini-x", { provider: "google" }],
|
||||
["claude-x", { provider: "anthropic" }],
|
||||
]));
|
||||
const captured = {};
|
||||
mockCatalogFetch(captured);
|
||||
const executor = makeExecutor();
|
||||
|
||||
await executor.execute({ model: "gemini-x", body: { ...CHAT_BODY }, stream: false, credentials: {} });
|
||||
expect(captured.body.provider).toBe("google");
|
||||
expect(captured.body.provider_request).not.toHaveProperty("safetySettings");
|
||||
|
||||
// Sanity: the shared translator still emits safetySettings — the removal
|
||||
// happens in the Zed executor, not in shared/native Gemini behavior.
|
||||
const { openaiToGeminiRequest } = await import(
|
||||
"open-sse/translator/request/openai-to-gemini.js"
|
||||
);
|
||||
expect(openaiToGeminiRequest("gemini-x", { ...CHAT_BODY }, true)).toHaveProperty(
|
||||
"safetySettings",
|
||||
);
|
||||
});
|
||||
});
|
||||
165
tests/unit/zed-live-models.test.js
Normal file
165
tests/unit/zed-live-models.test.js
Normal file
@@ -0,0 +1,165 @@
|
||||
// Route-level acceptance for the Zed live-model wiring:
|
||||
// GET /api/providers/[connectionId]/models → resolveZedModels → UI rows
|
||||
// RUN WITH AN ISOLATED DB: DATA_DIR=$(mktemp -d) npx vitest run ...
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
import { GET } from "@/app/api/providers/[id]/models/route.js";
|
||||
import { createProviderConnection } from "@/models/index.js";
|
||||
|
||||
// Transport stub BELOW resolveZedModels: proxyAwareFetch captures the native
|
||||
// fetch at import time, so stubbing globalThis.fetch cannot intercept it.
|
||||
// Mock the module instead; untouched hosts pass through to native fetch.
|
||||
const stub = vi.hoisted(() => {
|
||||
const nativeFetch = globalThis.fetch.bind(globalThis);
|
||||
return { mode: "ok", calls: [], nativeFetch };
|
||||
});
|
||||
vi.mock("open-sse/utils/proxyFetch.js", () => ({
|
||||
proxyAwareFetch: async (url, options) => {
|
||||
const u = String(url);
|
||||
stub.calls.push(u);
|
||||
if (u.includes("cloud.zed.dev/client/users/me")) {
|
||||
return Response.json({ default_organization_id: "org-1" });
|
||||
}
|
||||
if (u.includes("cloud.zed.dev/client/llm_tokens")) {
|
||||
return Response.json({ token: "llm-token" });
|
||||
}
|
||||
if (u.includes("cloud.zed.dev/models")) {
|
||||
if (stub.mode === "error") return new Response("boom", { status: 500 });
|
||||
if (stub.mode === "empty") return Response.json({ models: [] });
|
||||
return Response.json(stub.catalog);
|
||||
}
|
||||
return stub.nativeFetch(url, options);
|
||||
},
|
||||
default: async (url, options) => stub.nativeFetch(url, options),
|
||||
}));
|
||||
|
||||
stub.catalog = {
|
||||
models: [
|
||||
{
|
||||
id: "claude-opus-4-live",
|
||||
display_name: "Claude Opus Live",
|
||||
provider: "anthropic",
|
||||
max_token_count: 200000,
|
||||
max_output_tokens: 32000,
|
||||
supports_tools: true,
|
||||
supports_images: true,
|
||||
supports_thinking: true,
|
||||
is_disabled: false,
|
||||
},
|
||||
{
|
||||
id: "gpt-live",
|
||||
display_name: "GPT Live",
|
||||
provider: "openai",
|
||||
max_token_count: 128000,
|
||||
max_output_tokens: 16384,
|
||||
supports_tools: true,
|
||||
is_disabled: false,
|
||||
},
|
||||
{
|
||||
id: "retired-model",
|
||||
display_name: "Retired",
|
||||
provider: "openai",
|
||||
is_disabled: true,
|
||||
},
|
||||
],
|
||||
default_model: "claude-opus-4-live",
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
stub.mode = "ok";
|
||||
stub.calls.length = 0;
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
async function seedZed(n) {
|
||||
return createProviderConnection({
|
||||
provider: "zed",
|
||||
authType: "oauth",
|
||||
accessToken: `tok-live-${n}-${Date.now()}`,
|
||||
email: `zed-live-${n}-${Date.now()}@example.com`,
|
||||
providerSpecificData: { userId: `u-${n}`, systemId: `sys-${n}` },
|
||||
testStatus: "active",
|
||||
});
|
||||
}
|
||||
|
||||
async function getModels(connectionId) {
|
||||
const req = new Request(`http://localhost/api/providers/${connectionId}/models`);
|
||||
return GET(req, { params: Promise.resolve({ id: connectionId }) });
|
||||
}
|
||||
|
||||
describe("criterion 1+2 — active connection + live catalog → models with metadata", () => {
|
||||
it("returns enabled models with preserved metadata, no secrets", async () => {
|
||||
const conn = await seedZed("m1");
|
||||
const res = await getModels(conn.id);
|
||||
expect(res.status).toBe(200);
|
||||
const data = await res.json();
|
||||
expect(data.models.map((m) => m.id).sort()).toEqual(["claude-opus-4-live", "gpt-live"]);
|
||||
const opus = data.models.find((m) => m.id === "claude-opus-4-live");
|
||||
expect(opus.name).toBe("Claude Opus Live");
|
||||
expect(opus.contextLength).toBe(200000);
|
||||
expect(opus.maxOutputTokens).toBe(32000);
|
||||
expect(opus.supportsTools).toBe(true);
|
||||
expect(opus.supportsImages).toBe(true);
|
||||
expect(opus.supportsThinking).toBe(true);
|
||||
// Credentials must never leak into the client response.
|
||||
expect(JSON.stringify(data)).not.toContain(conn.accessToken);
|
||||
expect(JSON.stringify(data)).not.toContain("tok-live");
|
||||
});
|
||||
});
|
||||
|
||||
describe("criterion 4 — disabled models excluded", () => {
|
||||
it("is_disabled entries never reach the UI", async () => {
|
||||
const conn = await seedZed("m2");
|
||||
const data = await (await getModels(conn.id)).json();
|
||||
expect(data.models.some((m) => m.id === "retired-model")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("criterion 4b — empty catalog → explicit warning", () => {
|
||||
it("returns warning instead of silent zero", async () => {
|
||||
stub.mode = "empty";
|
||||
const conn = await seedZed("m3");
|
||||
const res = await getModels(conn.id);
|
||||
expect(res.status).toBe(200);
|
||||
const data = await res.json();
|
||||
expect(data.models).toEqual([]);
|
||||
expect(data.warning).toMatch(/no live models/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe("criterion 5 — resolver failure → useful warning, no crash", () => {
|
||||
it("returns 200 with warning text", async () => {
|
||||
stub.mode = "error";
|
||||
const conn = await seedZed("m4");
|
||||
const res = await getModels(conn.id);
|
||||
expect(res.status).toBe(200);
|
||||
const data = await res.json();
|
||||
expect(data.models).toEqual([]);
|
||||
expect(data.warning).toMatch(/failed to fetch zed models/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe("criterion 6 (route) — unknown connection → 404", () => {
|
||||
it("rejects missing connections", async () => {
|
||||
const res = await getModels("00000000-0000-0000-0000-000000000000");
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("criterion 5 (guard) — unsupported provider unchanged", () => {
|
||||
it("still 400s for providers without a models config", async () => {
|
||||
const conn = await createProviderConnection({
|
||||
provider: "kimchi-nope",
|
||||
authType: "oauth",
|
||||
accessToken: "x",
|
||||
email: `guard-${Date.now()}@example.com`,
|
||||
testStatus: "active",
|
||||
}).catch(() => null);
|
||||
// createProviderConnection may reject unknown providers; either way the
|
||||
// route must not have gained a zed-shaped branch for others.
|
||||
if (!conn) return;
|
||||
const res = await getModels(conn.id);
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
266
tests/unit/zed-native-auth.test.js
Normal file
266
tests/unit/zed-native-auth.test.js
Normal file
@@ -0,0 +1,266 @@
|
||||
// Acceptance suite for the Zed native-app auth fix.
|
||||
// RUN WITH AN ISOLATED DB: DATA_DIR=$(mktemp -d) npx vitest run unit/zed-native-auth.test.js
|
||||
//
|
||||
// Covers criteria:
|
||||
// 1. Zed proxy starts
|
||||
// 2. Stray callback (no params) MUST NOT kill session / stop proxy
|
||||
// 3. Real callback (user_id + access_token) MUST complete session + save connection
|
||||
// 4. RSA decrypt works (round-trip)
|
||||
// 5. systemId identical authorize → exchange → stored connection
|
||||
// 6. register-session failure is distinguishable (backend contract)
|
||||
// 8. (backend) reopen/re-register creates a fresh session
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
import crypto from "node:crypto";
|
||||
import {
|
||||
createZedNativeAuthData,
|
||||
parseZedCallbackPayload,
|
||||
decryptZedAccessToken,
|
||||
} from "open-sse/shared/zedAuth.js";
|
||||
import {
|
||||
startZedProxy,
|
||||
stopZedProxy,
|
||||
registerZedSession,
|
||||
getZedSessionStatus,
|
||||
clearZedSession,
|
||||
} from "@/lib/oauth/utils/server.js";
|
||||
import {
|
||||
generateAuthData,
|
||||
exchangeTokens,
|
||||
} from "@/lib/oauth/providers/index.js";
|
||||
|
||||
const realFetch = globalThis.fetch;
|
||||
|
||||
// Never hit the real network in tests: cloud.zed.dev calls are best-effort
|
||||
// (postExchange try/catch) — fail them fast and loud instead.
|
||||
beforeEach(() => {
|
||||
globalThis.fetch = async (url, init) => {
|
||||
if (String(url).includes("cloud.zed.dev")) {
|
||||
return new Response("test-stubbed", { status: 500 });
|
||||
}
|
||||
return realFetch(url, init);
|
||||
};
|
||||
});
|
||||
afterEach(async () => {
|
||||
globalThis.fetch = realFetch;
|
||||
stopZedProxy();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
async function startTestProxy() {
|
||||
const started = await startZedProxy(0); // random loopback port — parallel-safe
|
||||
expect(started.success).toBe(true);
|
||||
return started;
|
||||
}
|
||||
|
||||
/** Simulate zed.dev: RSA-encrypt a plaintext token with the flow's public key. */
|
||||
function encryptForCallback(publicKeyB64Url, plaintext) {
|
||||
const der = Buffer.from(String(publicKeyB64Url), "base64url");
|
||||
const key = crypto.createPublicKey({ key: der, format: "der", type: "pkcs1" });
|
||||
return crypto
|
||||
.publicEncrypt(
|
||||
{ key, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" },
|
||||
Buffer.from(plaintext, "utf8"),
|
||||
)
|
||||
.toString("base64url");
|
||||
}
|
||||
|
||||
describe("criterion 1 — Zed proxy starts", () => {
|
||||
it("binds 127.0.0.1 and reports a usable callback URL", async () => {
|
||||
const started = await startTestProxy();
|
||||
expect(started.port).toBeGreaterThan(0);
|
||||
expect(started.callbackUrl).toBe(`http://127.0.0.1:${started.port}/`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("criterion 4 — RSA decrypt works", () => {
|
||||
it("round-trips OAEP-SHA256 through the verifier slot", async () => {
|
||||
const auth = createZedNativeAuthData({}, { nativeAppPort: 1 });
|
||||
const encrypted = encryptForCallback(auth.publicKey, "plaintext-token-abc");
|
||||
expect(decryptZedAccessToken(encrypted, auth.privateKeyVerifier)).toBe(
|
||||
"plaintext-token-abc",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects a missing verifier instead of silently failing", () => {
|
||||
const auth = createZedNativeAuthData({}, { nativeAppPort: 1 });
|
||||
const encrypted = encryptForCallback(auth.publicKey, "x");
|
||||
expect(() => decryptZedAccessToken(encrypted, null)).toThrow(
|
||||
/private key verifier/i,
|
||||
);
|
||||
});
|
||||
|
||||
it("parser keeps strict validation (no weakened acceptance)", () => {
|
||||
expect(() => parseZedCallbackPayload("")).toThrow();
|
||||
expect(() => parseZedCallbackPayload("http://127.0.0.1:1/")).toThrow(
|
||||
/user_id and access_token/,
|
||||
);
|
||||
expect(() =>
|
||||
parseZedCallbackPayload("http://127.0.0.1:1/?user_id=only-user"),
|
||||
).toThrow(/user_id and access_token/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("criterion 2 — stray callback MUST NOT kill session", () => {
|
||||
it("bare GET / leaves session pending and proxy listening", async () => {
|
||||
const started = await startTestProxy();
|
||||
const auth = createZedNativeAuthData({}, { nativeAppPort: started.port });
|
||||
expect(
|
||||
registerZedSession({ state: "stray-state-1", codeVerifier: auth.privateKeyVerifier }),
|
||||
).toBe(true);
|
||||
|
||||
const res = await realFetch(`http://127.0.0.1:${started.port}/`);
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
// Session must still be pending (not poisoned to error)…
|
||||
const session = getZedSessionStatus("stray-state-1");
|
||||
expect(session).not.toBeNull();
|
||||
expect(session.status).toBe("pending");
|
||||
|
||||
// …and the SAME server must still own the port (no silent restart).
|
||||
const again = await startZedProxy(0);
|
||||
expect(again.port).toBe(started.port);
|
||||
|
||||
clearZedSession("stray-state-1");
|
||||
});
|
||||
|
||||
it("GET /callback with unrelated params leaves session pending", async () => {
|
||||
const started = await startTestProxy();
|
||||
const auth = createZedNativeAuthData({}, { nativeAppPort: started.port });
|
||||
registerZedSession({ state: "stray-state-2", codeVerifier: auth.privateKeyVerifier });
|
||||
|
||||
const res = await realFetch(`http://127.0.0.1:${started.port}/callback?foo=bar`);
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
const session = getZedSessionStatus("stray-state-2");
|
||||
expect(session).not.toBeNull();
|
||||
expect(session.status).toBe("pending");
|
||||
clearZedSession("stray-state-2");
|
||||
});
|
||||
});
|
||||
|
||||
describe("criterion 3 — real callback completes session + saves connection", () => {
|
||||
it("user_id + access_token → done, decrypted token persisted", async () => {
|
||||
const started = await startTestProxy();
|
||||
const auth = createZedNativeAuthData({}, { nativeAppPort: started.port });
|
||||
const state = `real-state-${Date.now()}`;
|
||||
registerZedSession({ state, codeVerifier: auth.privateKeyVerifier, systemId: auth.systemId });
|
||||
|
||||
const encrypted = encryptForCallback(auth.publicKey, "decrypted-token-xyz");
|
||||
const cb = new URL(`http://127.0.0.1:${started.port}/`);
|
||||
cb.searchParams.set("user_id", "user-123");
|
||||
cb.searchParams.set("access_token", encrypted);
|
||||
const res = await realFetch(cb.toString());
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
const session = getZedSessionStatus(state);
|
||||
expect(session).not.toBeNull();
|
||||
expect(session.status).toBe("done");
|
||||
expect(session.connectionId).toBeTruthy();
|
||||
|
||||
const { getProviderConnectionById } = await import("@/models/index.js");
|
||||
const conn = await getProviderConnectionById(session.connectionId);
|
||||
expect(conn).toBeTruthy();
|
||||
expect(conn.provider).toBe("zed");
|
||||
expect(conn.accessToken).toBe("decrypted-token-xyz");
|
||||
expect(conn.providerSpecificData?.userId).toBe("user-123");
|
||||
expect(conn.providerSpecificData?.systemId).toBe(auth.systemId);
|
||||
|
||||
// Proxy stopped itself after the terminal outcome (no orphan listener).
|
||||
const again = await startZedProxy(0);
|
||||
expect(again.port).not.toBe(started.port);
|
||||
stopZedProxy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("criterion 5 — systemId stable authorize → exchange → stored", () => {
|
||||
it("generateAuthData exposes the systemId sent to zed.dev", async () => {
|
||||
const auth = await generateAuthData("zed", "http://127.0.0.1:59999/", {
|
||||
nativeAppPort: 59999,
|
||||
});
|
||||
const url = new URL(auth.authUrl);
|
||||
expect(url.searchParams.get("native_app_port")).toBe("59999");
|
||||
// The system_id embedded in the sign-in URL must be observable downstream.
|
||||
expect(auth.systemId).toBe(url.searchParams.get("system_id"));
|
||||
expect(auth.systemId).toBeTruthy();
|
||||
});
|
||||
|
||||
it("exchange preserves the registered systemId (no regeneration)", async () => {
|
||||
const auth = await generateAuthData("zed", "http://127.0.0.1:59998/", {
|
||||
nativeAppPort: 59998,
|
||||
});
|
||||
// Public key always rides in the authorize URL (mirrors the real flow).
|
||||
const pubFromUrl = new URL(auth.authUrl).searchParams.get("native_app_public_key");
|
||||
expect(pubFromUrl).toBeTruthy();
|
||||
const enc2 = encryptForCallback(pubFromUrl, "tok2");
|
||||
const tokens = await exchangeTokens(
|
||||
"zed",
|
||||
`/?user_id=u1&access_token=${encodeURIComponent(enc2)}`,
|
||||
null,
|
||||
auth.codeVerifier,
|
||||
auth.state,
|
||||
{ systemId: auth.systemId },
|
||||
);
|
||||
expect(tokens.providerSpecificData.systemId).toBe(auth.systemId);
|
||||
});
|
||||
});
|
||||
|
||||
describe("criterion 6 — register-session failure is distinguishable", () => {
|
||||
it("route reports { success: false } when the verifier is missing", async () => {
|
||||
const { POST } = await import("@/app/api/oauth/[provider]/[action]/route.js");
|
||||
const req = new Request("http://localhost/api/oauth/zed/register-session", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ state: "no-verifier-state" }),
|
||||
});
|
||||
const res = await POST(req, {
|
||||
params: Promise.resolve({ provider: "zed", action: "register-session" }),
|
||||
});
|
||||
const data = await res.json();
|
||||
// Backend contract: failure must be explicit (modal is required to check it).
|
||||
expect(data.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("criterion 8 (backend) — re-register creates a fresh session", () => {
|
||||
it("a new register supersedes the old state cleanly", async () => {
|
||||
const a = createZedNativeAuthData({}, { nativeAppPort: 1 });
|
||||
const b = createZedNativeAuthData({}, { nativeAppPort: 1 });
|
||||
registerZedSession({ state: "old-state", codeVerifier: a.privateKeyVerifier });
|
||||
registerZedSession({ state: "new-state", codeVerifier: b.privateKeyVerifier });
|
||||
|
||||
expect(getZedSessionStatus("old-state")).toBeNull();
|
||||
const fresh = getZedSessionStatus("new-state");
|
||||
expect(fresh).not.toBeNull();
|
||||
expect(fresh.status).toBe("pending");
|
||||
expect(fresh.codeVerifier).toBe(b.privateKeyVerifier);
|
||||
clearZedSession("new-state");
|
||||
});
|
||||
});
|
||||
|
||||
describe("criterion L — decrypt failure errors the session but keeps the server", () => {
|
||||
it("wrong-key token → session error, listener survives for the live attempt", async () => {
|
||||
const started = await startTestProxy();
|
||||
const live = createZedNativeAuthData({}, { nativeAppPort: started.port });
|
||||
const other = createZedNativeAuthData({}, { nativeAppPort: started.port });
|
||||
const state = `wrongkey-state-${Date.now()}`;
|
||||
registerZedSession({ state, codeVerifier: live.privateKeyVerifier });
|
||||
|
||||
// Token encrypted for a DIFFERENT keypair (e.g. superseded popup).
|
||||
const bad = encryptForCallback(other.publicKey, "not-for-this-key");
|
||||
const cb = new URL(`http://127.0.0.1:${started.port}/`);
|
||||
cb.searchParams.set("user_id", "user-123");
|
||||
cb.searchParams.set("access_token", bad);
|
||||
const res = await realFetch(cb.toString());
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
const session = getZedSessionStatus(state);
|
||||
expect(session).not.toBeNull();
|
||||
expect(session.status).toBe("error");
|
||||
expect(session.error).toMatch(/decrypt/i);
|
||||
|
||||
// Server must still be alive (same port) for the live attempt.
|
||||
const again = await startZedProxy(0);
|
||||
expect(again.port).toBe(started.port);
|
||||
clearZedSession(state);
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,7 @@ export default defineConfig({
|
||||
// Don't scan into git worktrees nested under .claude/ — they carry their
|
||||
// own copies of the test files but lack an installed node_modules (open-sse,
|
||||
// etc.), which makes provider imports fail during collection.
|
||||
exclude: ["**/node_modules/**", "**/.claude/**", "**/dist/**"],
|
||||
exclude: ["**/node_modules/**", "**/.claude/**", "**/dist/**", "**/.next/**"],
|
||||
// Allow many it.concurrent cases (real provider smoke runs ~50 providers in parallel)
|
||||
maxConcurrency: 60,
|
||||
// Suppress noisy console output from handlers under test
|
||||
|
||||
Reference in New Issue
Block a user