Files
OmniRoute/tests/unit/responses-handler.test.ts
Diego Rodrigues de Sa e Souza 929caeb910 Release v3.8.15 (#3373)
* chore(release): open v3.8.15 development cycle

Version bump 3.8.14 -> 3.8.15 (root + electron + open-sse + openapi + lockfiles)
and seed the v3.8.15 changelog placeholder (root + 41 i18n mirrors).

* fix(catalog): add getTokenLimit fallback for combo targets with unknown context (#3369)

Integrated into release/v3.8.15. Fixes applied on the contributor's branch: removed duplicate JSDoc opening in accountFallback.ts and dropped a test asserting unreachable catalog behavior (models with no registry/spec/synced source are filtered before the getTokenLimit fallback at catalog.ts:499).

* fix(combo): add 429 to PROVIDER_FAILURE_ERROR_CODES to prevent infinite retry loop (#3366)

Integrated into release/v3.8.15. Comment block reconciled on the contributor's branch to remove the contradictory 'intentionally excluded' text that remained from the original code.

* fix(auto-combo): include no-auth providers declaratively (#3365)

Integrated into release/v3.8.15. Cleanup applied on contributor's branch: removed duplicate migration 095 (already exists from PR #3338), reverted CHANGELOG.md and i18n changelogs to release versions (release process owns these), dropped package version-bump noise from stale fork base. Core feature — declarative no-auth via serviceKinds metadata, declarative VEO as 'video' provider, anonymousFallback flag for opencode-zen/opencode-go — integrated cleanly.

* fix(migrations): restore 095_provider_node_custom_headers migration

The squash merge of PR #3365 accidentally deleted this migration because
the cleanup commit on the contributor's branch included 'git rm' for the
file (which was a duplicate on their branch). The migration was merged
in v3.8.14 via PR #3338 and must be present in the release branch.

Restoring from git history.

* fix: update Command Code base URL from /alpha/ to /provider/v1/ (#3372)

Integrated into release/v3.8.15.

* feat(error-rules): provider-specific error classification with scope (#3370)

Integrated into release/v3.8.15. PR has genuine value beyond #3369: (1) getProviderErrorRuleMatch now accepts native Headers objects from fetch(); (2) checkFallbackError also uses the provider rule registry — the real end-to-end wiring in the combo fallback path; (3) S4 end-to-end test proving the wiring fires. Merge commit on contributor branch resolved the add/add conflict by taking the #3370 version throughout.

* fix(auto-combo): validate web-session credentials (#3371)

Integrated into release/v3.8.15. Core feature: provider-aware web-session credential validation — hasUsableWebSessionCredential() replaces the broad Object.keys check in virtualFactory.ts, ensuring only sessions with the required storageKeys are included in auto-combo. Cleanup: removed duplicate 095 migration, reverted CHANGELOG/i18n, dropped package bump noise.

* fix(migrations): restore 095_provider_node_custom_headers (deleted again by #3371 squash)

Same issue as after #3365: git rm in the contributor cleanup commit
was included in the squash, deleting this migration from release.
Permanent fix needed: use 'git checkout origin/release -- <file>'
instead of 'git rm' when cleaning up duplicate files in contributor branches.

* fix(kiro): probe Windows %APPDATA%\kiro\storage.db in auto-import (#3363) (#3375)

Integrated into release/v3.8.15. Test fix applied: kiro-windows-auto-import-3363.test.ts now sets DATA_DIR to a fresh temp dir before importing app modules, ensuring isAuthRequired() sees an empty settings DB (no password → auth not required). This fixed test 4 (synthetic SQLite) which was getting 401 due to settings DB state leakage.

* chore(release): finalize v3.8.15 changelog — 2026-06-07

---------

Co-authored-by: Hernan Javier Ardila Sanchez <hjasgr@gmail.com>
Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com>
Co-authored-by: Muhammad Nabil Muyassar Rahman <65392758+TapZe@users.noreply.github.com>
Co-authored-by: kiro-agent[bot] <245459735+kiro-agent[bot]@users.noreply.github.com>
2026-06-07 12:16:33 -03:00

362 lines
11 KiB
TypeScript

import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-responses-handler-"));
process.env.DATA_DIR = TEST_DATA_DIR;
const core = await import("../../src/lib/db/core.ts");
const { handleResponsesCore } = await import("../../open-sse/handlers/responsesHandler.ts");
const originalFetch = globalThis.fetch;
function noopLog() {
return {
debug() {},
info() {},
warn() {},
error() {},
};
}
function toPlainHeaders(headers: any) {
if (!headers) return {};
if (headers instanceof Headers) return Object.fromEntries(headers.entries());
return Object.fromEntries(
Object.entries(headers).map(([key, value]) => [key, value == null ? "" : String(value)])
);
}
function buildOpenAISseResponse(text = "hello") {
return new Response(
[
`data: ${JSON.stringify({
id: "chatcmpl-responses",
object: "chat.completion.chunk",
choices: [{ index: 0, delta: { role: "assistant", content: text } }],
})}`,
"",
`data: ${JSON.stringify({
id: "chatcmpl-responses",
object: "chat.completion.chunk",
choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
usage: { prompt_tokens: 4, completion_tokens: 2, total_tokens: 6 },
})}`,
"",
"data: [DONE]",
"",
].join("\n"),
{
status: 200,
headers: { "Content-Type": "text/event-stream" },
}
);
}
function buildJsonResponse(status: number, payload: any) {
return new Response(JSON.stringify(payload), {
status,
headers: { "Content-Type": "application/json" },
});
}
async function resetStorage() {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}
async function invokeResponsesCore({
body,
provider = "openai",
model = "gpt-4o-mini",
credentials,
responseFactory,
signal,
}: {
body?: any;
provider?: string;
model?: string;
credentials?: any;
responseFactory?: any;
signal?: AbortSignal;
} = {}) {
const calls: any[] = [];
globalThis.fetch = async (url, init = {}) => {
const call = {
url: String(url),
method: init.method || "GET",
headers: toPlainHeaders(init.headers),
body: init.body ? JSON.parse(String(init.body)) : null,
};
calls.push(call);
return responseFactory ? responseFactory(call, calls) : buildOpenAISseResponse();
};
try {
const result = await handleResponsesCore({
body: structuredClone(body),
modelInfo: { provider, model, extendedContext: false },
credentials: credentials || {
apiKey: "sk-test",
providerSpecificData: {},
},
log: noopLog(),
onCredentialsRefreshed: null,
onRequestSuccess: null,
onDisconnect: null,
connectionId: null,
signal,
});
return { result, calls, call: calls.at(-1) };
} finally {
globalThis.fetch = originalFetch;
}
}
test.afterEach(async () => {
globalThis.fetch = originalFetch;
await resetStorage();
});
test.after(async () => {
globalThis.fetch = originalFetch;
await resetStorage();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
});
test("handleResponsesCore converts Responses API input, instructions, tools, metadata, and forces streaming", async () => {
const { call, result } = await invokeResponsesCore({
body: {
model: "gpt-4o-mini",
instructions: "You are terse",
input: [
{
type: "message",
role: "user",
content: [{ type: "input_text", text: "hello" }],
},
],
tools: [
{
type: "function",
name: "lookup_weather",
description: "Find weather",
parameters: { type: "object" },
},
],
metadata: { source: "responses-test" },
store: true,
},
});
assert.equal(result.success, true);
assert.equal(call.body.stream, true);
assert.equal(call.body.messages[0].role, "system");
assert.equal(call.body.messages[0].content, "You are terse");
assert.equal(call.body.messages[1].role, "user");
assert.equal(call.body.messages[1].content[0].text, "hello");
assert.equal(call.body.tools[0].function.name, "lookup_weather");
assert.equal(call.body.metadata, undefined);
assert.equal("store" in call.body, false);
});
test("handleResponsesCore strips previous_response_id by default and handles empty input arrays", async () => {
const { call, result } = await invokeResponsesCore({
body: {
model: "gpt-4o-mini",
input: [],
previous_response_id: "resp_prev_123",
metadata: { session: "abc" },
},
});
assert.equal(result.success, true);
assert.equal(call.body.previous_response_id, undefined);
assert.equal(call.body.metadata, undefined);
assert.deepEqual(call.body.messages, []);
assert.equal(call.body.stream, true);
});
test("handleResponsesCore preserves store for Codex responses when connection opt-in is enabled", async () => {
const { call, result } = await invokeResponsesCore({
body: {
model: "gpt-5.3-codex",
input: [],
previous_response_id: "resp_prev_store",
store: true,
},
provider: "codex",
model: "gpt-5.3-codex",
credentials: {
accessToken: "codex-token",
providerSpecificData: {
openaiStoreEnabled: true,
},
},
});
assert.equal(result.success, true);
// When openaiStoreEnabled=true, the request keeps previous_response_id and
// store=true so the upstream Codex Responses session continues from prior turn.
assert.equal(call.body.previous_response_id, "resp_prev_store");
assert.equal(call.body.store, true);
assert.equal(call.body.stream, true);
});
test("handleResponsesCore transforms upstream OpenAI SSE into Responses API SSE", async () => {
const { result } = await invokeResponsesCore({
body: {
model: "gpt-4o-mini",
input: "hello",
},
});
assert.equal(result.success, true);
assert.equal(result.response.headers.get("Content-Type"), "text/event-stream");
const sse = await result.response.text();
assert.match(sse, /event: response\.created/);
assert.match(sse, /event: response\.output_text\.delta/);
assert.match(sse, /event: response\.completed/);
assert.match(sse, /data: \[DONE\]/);
});
test("handleResponsesCore transforms Command Code executor SSE through Responses shim", async () => {
const { call, result } = await invokeResponsesCore({
provider: "command-code",
model: "gpt-5.4-mini",
credentials: { apiKey: "cc_test_key", providerSpecificData: {} },
body: {
model: "gpt-5.4-mini",
input: "hello command code",
},
responseFactory() {
return new Response(
[
`data: ${JSON.stringify({ type: "text-delta", text: "command" })}`,
"",
`data: ${JSON.stringify({ type: "reasoning-delta", text: "thinking" })}`,
"",
`data: ${JSON.stringify({ type: "finish", finishReason: "stop" })}`,
"",
].join("\n"),
{ status: 200, headers: { "Content-Type": "application/x-ndjson" } }
);
},
});
assert.equal(result.success, true);
assert.equal(call.url, "https://api.commandcode.ai/provider/v1/chat/completions");
assert.equal(call.headers.Authorization, "Bearer cc_test_key");
assert.equal(call.headers["x-command-code-version"], "0.24.1");
assert.equal(call.body.params.model, "gpt-5.4-mini");
assert.equal(call.body.params.stream, true);
const sse = await result.response.text();
assert.match(sse, /event: response\.created/);
assert.match(sse, /event: response\.output_text\.delta/);
assert.match(sse, /command/);
assert.match(sse, /event: response\.completed/);
assert.match(sse, /data: \[DONE\]/);
});
test("handleResponsesCore propagates upstream failures from chatCore unchanged", async () => {
const { result } = await invokeResponsesCore({
body: {
model: "gpt-4o-mini",
input: "hello",
},
responseFactory() {
return buildJsonResponse(401, {
error: { message: "unauthorized" },
});
},
});
assert.equal(result.success, false);
assert.equal(result.status, 401);
const payload = (await result.response.json()) as any;
assert.equal(payload.error.message, "[401]: unauthorized");
});
test("handleResponsesCore rejects invalid Responses API input that cannot be translated", async () => {
// After #2695 the web_search family is allowed; use file_search to keep this
// assertion exercising the "untranslatable tool type" path.
await assert.rejects(
() =>
handleResponsesCore({
body: {
model: "gpt-4o-mini",
input: "hello",
tools: [{ type: "file_search" }],
},
modelInfo: { provider: "openai", model: "gpt-4o-mini", extendedContext: false },
credentials: { apiKey: "sk-test", providerSpecificData: {} },
log: noopLog(),
onCredentialsRefreshed: null,
onRequestSuccess: null,
onDisconnect: null,
connectionId: null,
}),
(error) =>
error instanceof Error && error.message.includes("file_search tool type is not supported")
);
});
test("handleResponsesCore injects SSE keepalive frames for Responses streams", async (t) => {
// PR #2233 changed the Responses-API heartbeat shape from a SSE comment
// (`: keepalive ...`) to a `data: {"type":"response.in_progress"}` frame,
// because strict proxies only count `data:` lines as activity.
t.mock.timers.enable({ apis: ["setInterval"] });
try {
const { result } = await invokeResponsesCore({
body: {
model: "gpt-4o-mini",
input: "hello",
},
});
assert.equal(result.success, true);
t.mock.timers.tick(15000); // Advance time by 15s to trigger heartbeat
const sse = await result.response.text();
assert.match(sse, /data: \{"type":"response\.in_progress"\}/);
assert.match(sse, /event: response\.created/);
assert.match(sse, /data: \[DONE\]/);
} finally {
t.mock.timers.reset();
}
});
test("handleResponsesCore clears heartbeat timers immediately when the request signal aborts", async (t) => {
t.mock.timers.enable({ apis: ["setInterval"] });
try {
const controller = new AbortController();
const { result } = await invokeResponsesCore({
body: {
model: "gpt-4o-mini",
input: "hello",
},
signal: controller.signal,
});
assert.equal(result.success, true);
// We can't directly check clearInterval count because the stream flush
// also clears it. We'll just verify no crash and it resolves properly.
controller.abort();
await new Promise((r) => process.nextTick(r)); // yield to event loop
await result.response.body?.cancel();
} finally {
t.mock.timers.reset();
}
});