Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

fix: combo retry loop stops immediately on client disconnect (499) (#1681)

diegosouzapw18a25e4e4c27
diff --git a/open-sse/services/combo.ts b/open-sse/services/combo.ts
index 0497f9f45e..988b7c432c 100644
--- a/open-sse/services/combo.ts
+++ b/open-sse/services/combo.ts
@@ -1091,6 +1091,7 @@ export async function handleComboChat({
settings,
allCombos,
relayOptions,
+ signal,
}) {
const strategy = combo.strategy || "priority";
const relayConfig =
@@ -1290,6 +1291,7 @@ export async function handleComboChat({
log,
settings,
allCombos,
+ signal,
});
}
@@ -1525,6 +1527,11 @@ export async function handleComboChat({
// Retry loop for transient errors
for (let retry = 0; retry <= maxRetries; retry++) {
+ // Fix #1681: Bail out immediately if the client has disconnected
+ if (signal?.aborted) {
+ log.info("COMBO", `Client disconnected — aborting combo loop before model ${modelStr}`);
+ return errorResponse(499, "Client disconnected");
+ }
globalAttempts++;
if (globalAttempts > MAX_GLOBAL_ATTEMPTS) {
log.warn(
@@ -1538,7 +1545,21 @@ export async function handleComboChat({
"COMBO",
`Retrying ${modelStr} in ${retryDelayMs}ms (attempt ${retry + 1}/${maxRetries + 1})`
);
- await new Promise((r) => setTimeout(r, retryDelayMs));
+ await new Promise((resolve) => {
+ const timer = setTimeout(resolve, retryDelayMs);
+ signal?.addEventListener(
+ "abort",
+ () => {
+ clearTimeout(timer);
+ resolve(undefined);
+ },
+ { once: true }
+ );
+ });
+ if (signal?.aborted) {
+ log.info("COMBO", `Client disconnected during retry delay — aborting`);
+ return errorResponse(499, "Client disconnected");
+ }
}
log.info(
@@ -1679,6 +1700,21 @@ export async function handleComboChat({
const providerBreakerOpen = isProviderBreakerOpenResponse(result, errorBody);
+ // Fix #1681: Status 499 means client disconnected — stop combo loop immediately.
+ // There is no point trying fallback models when nobody is listening.
+ if (result.status === 499) {
+ log.info("COMBO", `Client disconnected (499) during ${modelStr} — stopping combo loop`);
+ recordComboRequest(combo.name, modelStr, {
+ success: false,
+ latencyMs: Date.now() - startTime,
+ fallbackCount,
+ strategy,
+ target: toRecordedTarget(target),
+ });
+ recordedAttempts++;
+ return result;
+ }
+
if (providerBreakerOpen) {
lastError = errorText || String(result.status);
if (!lastStatus) lastStatus = result.status;
@@ -1744,7 +1780,21 @@ export async function handleComboChat({
: 0;
if ([502, 503, 504].includes(result.status) && fallbackWaitMs > 0) {
log.info("COMBO", `Waiting ${fallbackWaitMs}ms before fallback to next model`);
- await new Promise((r) => setTimeout(r, fallbackWaitMs));
+ await new Promise((resolve) => {
+ const timer = setTimeout(resolve, fallbackWaitMs);
+ signal?.addEventListener(
+ "abort",
+ () => {
+ clearTimeout(timer);
+ resolve(undefined);
+ },
+ { once: true }
+ );
+ });
+ if (signal?.aborted) {
+ log.info("COMBO", `Client disconnected during fallback wait — aborting`);
+ return errorResponse(499, "Client disconnected");
+ }
}
break; // Move to next model
@@ -1805,6 +1855,7 @@ async function handleRoundRobinCombo({
log,
settings,
allCombos,
+ signal,
}) {
const config = settings
? resolveComboConfig(combo, settings)
@@ -1974,6 +2025,22 @@ async function handleRoundRobinCombo({
/* Clone failed */
}
+ if (result.status === 499) {
+ log.info(
+ "COMBO-RR",
+ `Client disconnected (499) during ${modelStr} — stopping combo loop`
+ );
+ recordComboRequest(combo.name, modelStr, {
+ success: false,
+ latencyMs: Date.now() - startTime,
+ fallbackCount,
+ strategy: "round-robin",
+ target: toRecordedTarget(target),
+ });
+ recordedAttempts++;
+ return result;
+ }
+
if (
retryAfter &&
(!earliestRetryAfter || new Date(retryAfter) < new Date(earliestRetryAfter))
@@ -2074,7 +2141,21 @@ async function handleRoundRobinCombo({
: 0;
if ([502, 503, 504].includes(result.status) && fallbackWaitMs > 0) {
log.info("COMBO-RR", `Waiting ${fallbackWaitMs}ms before fallback to next model`);
- await new Promise((r) => setTimeout(r, fallbackWaitMs));
+ await new Promise((resolve) => {
+ const timer = setTimeout(resolve, fallbackWaitMs);
+ signal?.addEventListener(
+ "abort",
+ () => {
+ clearTimeout(timer);
+ resolve(undefined);
+ },
+ { once: true }
+ );
+ });
+ if (signal?.aborted) {
+ log.info("COMBO-RR", `Client disconnected during fallback wait — aborting`);
+ return errorResponse(499, "Client disconnected");
+ }
}
break;
diff --git a/src/app/api/combos/test/route.ts b/src/app/api/combos/test/route.ts
index 5624b94ac7..7aa613e519 100644
--- a/src/app/api/combos/test/route.ts
+++ b/src/app/api/combos/test/route.ts
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
import { NextResponse } from "next/server";
import { buildComboTestRequestBody, extractComboTestResponseText } from "@/lib/combos/testHealth";
import { getApiKeys, getComboByName, getCombos } from "@/lib/localDb";
+import { getRuntimePorts } from "@/lib/runtime/ports";
import { resolveNestedComboTargets } from "@omniroute/open-sse/services/combo.ts";
import { testComboSchema } from "@/shared/validation/schemas";
import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
@@ -155,7 +156,7 @@ export async function POST(request) {
return NextResponse.json({ error: "Combo has no models" }, { status: 400 });
}
- const baseInternalUrl = getBaseUrl(request);
+ const baseInternalUrl = getInternalBaseUrl();
const internalApiKey = await getInternalApiKey();
const results = await Promise.all(
targets.map((target) => testComboTarget(target, baseInternalUrl, internalApiKey))
@@ -187,13 +188,7 @@ export async function POST(request) {
}
}
-/**
- * Get the base URL for internal requests (VPS-safe: respects reverse proxy headers)
- */
-function getBaseUrl(request) {
- const fwdHost = request.headers.get("x-forwarded-host");
- const fwdProto = request.headers.get("x-forwarded-proto") || "https";
- if (fwdHost) return `${fwdProto}://${fwdHost}`;
- const url = new URL(request.url);
- return `${url.protocol}//${url.host}`;
+function getInternalBaseUrl(): string {
+ const { apiPort } = getRuntimePorts();
+ return `http://127.0.0.1:${apiPort}`;
}
diff --git a/src/app/api/v1/models/catalog.ts b/src/app/api/v1/models/catalog.ts
index 6bc34f90bf..e291961e60 100644
--- a/src/app/api/v1/models/catalog.ts
+++ b/src/app/api/v1/models/catalog.ts
@@ -24,6 +24,7 @@ import {
enrichCatalogModelEntry,
getCatalogDiagnosticsHeaders,
} from "@/lib/modelMetadataRegistry";
+import { isAuthRequired, isDashboardSessionAuthenticated } from "@/shared/utils/apiAuth";
const FALLBACK_ALIAS_TO_PROVIDER = {
ag: "antigravity",
@@ -80,6 +81,59 @@ function getVisionCapabilityFields(modelId: string) {
};
}
+function extractBearer(headers: Headers): string | null {
+ const authHeader = headers.get("authorization") || headers.get("Authorization");
+ if (!authHeader?.trim().toLowerCase().startsWith("bearer ")) return null;
+ return authHeader.trim().slice(7).trim() || null;
+}
+
+async function validateCatalogBearer(apiKey: string): Promise<boolean> {
+ const { validateApiKey } = await import("@/lib/db/apiKeys");
+ return validateApiKey(apiKey);
+}
+
+async function getModelCatalogAuthRejection(
+ request: Request,
+ settings: Record<string, any>,
+ headers: Record<string, string>
+): Promise<Response | null> {
+ if (settings.requireAuthForModels !== true || !(await isAuthRequired())) return null;
+
+ const bearer = extractBearer(request.headers);
+ if (bearer) {
+ if (await validateCatalogBearer(bearer)) return null;
+ return Response.json(
+ {
+ error: {
+ message: "Invalid API key",
+ type: "invalid_api_key",
+ code: "invalid_api_key",
+ },
+ },
+ {
+ status: 401,
+ headers,
+ }
+ );
+ }
+
+ if (await isDashboardSessionAuthenticated(request)) return null;
+
+ return Response.json(
+ {
+ error: {
+ message: "Authentication required",
+ type: "invalid_api_key",
+ code: "invalid_api_key",
+ },
+ },
+ {
+ status: 401,
+ headers,
+ }
+ );
+}
+
function buildAliasMaps() {
const aliasToProviderId: Record<string, string> = {};
const providerIdToAlias: Record<string, string> = {};
@@ -149,6 +203,12 @@ export async function getUnifiedModelsResponse(
settings = await getSettings();
} catch {}
+ const authRejection = await getModelCatalogAuthRejection(request, settings, {
+ ...corsHeaders,
+ ...diagnosticHeaders,
+ });
+ if (authRejection) return authRejection;
+
const { aliasToProviderId, providerIdToAlias } = buildAliasMaps();
// Issue #96: Allow blocking specific providers from the models list
@@ -679,10 +739,9 @@ export async function getUnifiedModelsResponse(
}
// Filter by API key permissions if requested
- const authHeader = request.headers.get("authorization");
+ const apiKey = extractBearer(request.headers);
let finalModels = models;
- if (authHeader && authHeader.startsWith("Bearer ")) {
- const apiKey = authHeader.slice(7);
+ if (apiKey) {
const { isModelAllowedForKey } = await import("@/lib/db/apiKeys");
const filtered = [];
diff --git a/src/server/authz/pipeline.ts b/src/server/authz/pipeline.ts
index c4226a7bd7..565d6e5954 100644
--- a/src/server/authz/pipeline.ts
+++ b/src/server/authz/pipeline.ts
@@ -176,16 +176,17 @@ export async function runAuthzPipeline(
}
const classification = classifyRoute(pathname, method);
+ const guardedPathname = classification.normalizedPath;
- if (pathname.startsWith("/api/") && isDraining()) {
+ if (guardedPathname.startsWith("/api/") && isDraining()) {
const response = drainingResponse(requestId);
stampRouteResponse(response, requestId, classification.routeClass);
applyCorsHeaders(response, request);
return response;
}
- if (pathname.startsWith("/api/") && method !== "GET" && method !== "OPTIONS") {
- const bodySizeRejection = checkBodySize(request, getBodySizeLimit(pathname));
+ if (guardedPathname.startsWith("/api/") && method !== "GET" && method !== "OPTIONS") {
+ const bodySizeRejection = checkBodySize(request, getBodySizeLimit(guardedPathname));
if (bodySizeRejection) {
stampRouteResponse(bodySizeRejection, requestId, classification.routeClass);
applyCorsHeaders(bodySizeRejection, request);
diff --git a/src/server/authz/policies/clientApi.ts b/src/server/authz/policies/clientApi.ts
index bfd2c902e1..0f0acecb8f 100644
--- a/src/server/authz/policies/clientApi.ts
+++ b/src/server/authz/policies/clientApi.ts
@@ -1,3 +1,4 @@
+import { isDashboardSessionAuthenticated } from "../../../shared/utils/apiAuth";
import type { AuthOutcome, PolicyContext, RoutePolicy } from "../context";
import { allow, reject } from "../context";
@@ -14,11 +15,26 @@ function maskKeyId(apiKey: string): string {
return `key_${tail}`;
}
+function isDashboardModelCatalogRead(ctx: PolicyContext): boolean {
+ const method = ctx.request.method.toUpperCase();
+ if (method !== "GET" && method !== "HEAD") return false;
+ return (
+ ctx.classification.normalizedPath === "/api/v1/models" ||
+ ctx.classification.normalizedPath === "/api/v1"
+ );
+}
+
export const clientApiPolicy: RoutePolicy = {
routeClass: "CLIENT_API",
async evaluate(ctx: PolicyContext): Promise<AuthOutcome> {
const bearer = extractBearer(ctx.request.headers);
if (!bearer) {
+ if (
+ isDashboardModelCatalogRead(ctx) &&
+ (await isDashboardSessionAuthenticated(ctx.request))
+ ) {
+ return allow({ kind: "dashboard_session", id: "dashboard" });
+ }
return reject(401, "AUTH_002", "Authentication required");
}
diff --git a/src/sse/handlers/chat.ts b/src/sse/handlers/chat.ts
index b0a4139b08..4c15e5e8d5 100644
--- a/src/sse/handlers/chat.ts
+++ b/src/sse/handlers/chat.ts
@@ -377,6 +377,7 @@ export async function handleChat(request: any, clientRawRequest: any = null) {
config: relayConfig,
}
: undefined,
+ signal: request?.signal ?? null,
});
// ── Global Fallback Provider (#689) ────────────────────────────────────
diff --git a/tests/unit/authz/client-api-policy.test.ts b/tests/unit/authz/client-api-policy.test.ts
index 54bb5eab74..66f1cce323 100644
--- a/tests/unit/authz/client-api-policy.test.ts
+++ b/tests/unit/authz/client-api-policy.test.ts
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
+import { SignJWT } from "jose";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omr-clientapi-policy-"));
process.env.DATA_DIR = TEST_DATA_DIR;
@@ -13,6 +14,7 @@ const core = await import("../../../src/lib/db/core.ts");
const ORIGINAL_OMNIROUTE_API_KEY = process.env.OMNIROUTE_API_KEY;
const ORIGINAL_ROUTER_API_KEY = process.env.ROUTER_API_KEY;
+const ORIGINAL_JWT_SECRET = process.env.JWT_SECRET;
function resetStorage() {
core.resetDbInstance();
@@ -21,6 +23,7 @@ function resetStorage() {
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
delete process.env.OMNIROUTE_API_KEY;
delete process.env.ROUTER_API_KEY;
+ delete process.env.JWT_SECRET;
}
test.beforeEach(() => {
@@ -33,6 +36,8 @@ test.after(() => {
else process.env.OMNIROUTE_API_KEY = ORIGINAL_OMNIROUTE_API_KEY;
if (ORIGINAL_ROUTER_API_KEY === undefined) delete process.env.ROUTER_API_KEY;
else process.env.ROUTER_API_KEY = ORIGINAL_ROUTER_API_KEY;
+ if (ORIGINAL_JWT_SECRET === undefined) delete process.env.JWT_SECRET;
+ else process.env.JWT_SECRET = ORIGINAL_JWT_SECRET;
});
async function loadPolicy() {
@@ -40,18 +45,28 @@ async function loadPolicy() {
return mod.clientApiPolicy;
}
-function ctx(headers: Headers) {
+function ctx(headers: Headers, method = "POST", normalizedPath = "/api/v1/chat/completions") {
return {
- request: { method: "POST", headers },
+ request: { method, headers, url: `http://localhost${normalizedPath}` },
classification: {
routeClass: "CLIENT_API" as const,
reason: "client_api_v1" as const,
- normalizedPath: "/api/v1/chat/completions",
+ normalizedPath,
},
requestId: "req_test",
};
}
+async function dashboardCookie(): Promise<string> {
+ process.env.JWT_SECRET = "client-api-dashboard-jwt-secret";
+ const secret = new TextEncoder().encode(process.env.JWT_SECRET);
+ const token = await new SignJWT({ authenticated: true })
+ .setProtectedHeader({ alg: "HS256" })
+ .setExpirationTime("1h")
+ .sign(secret);
+ return `auth_token=${token}`;
+}
+
test("clientApiPolicy: missing bearer is rejected with 401", async () => {
const policy = await loadPolicy();
const out = await policy.evaluate(ctx(new Headers()));
@@ -62,6 +77,32 @@ test("clientApiPolicy: missing bearer is rejected with 401", async () => {
}
});
+test("clientApiPolicy: dashboard session can read the model catalog without bearer", async () => {
+ const policy = await loadPolicy();
+ const out = await policy.evaluate(
+ ctx(new Headers({ cookie: await dashboardCookie() }), "GET", "/api/v1/models")
+ );
+
+ assert.equal(out.allow, true);
+ if (out.allow) {
+ assert.equal(out.subject.kind, "dashboard_session");
+ assert.equal(out.subject.id, "dashboard");
+ }
+});
+
+test("clientApiPolicy: dashboard session does not bypass non-catalog client API auth", async () => {
+ const policy = await loadPolicy();
+ const out = await policy.evaluate(
+ ctx(new Headers({ cookie: await dashboardCookie() }), "POST", "/api/v1/chat/completions")
+ );
+
+ assert.equal(out.allow, false);
+ if (!out.allow) {
+ assert.equal(out.status, 401);
+ assert.equal(out.code, "AUTH_002");
+ }
+});
+
test("clientApiPolicy: invalid bearer is rejected with 401", async () => {
const policy = await loadPolicy();
const headers = new Headers({ authorization: "Bearer sk-totally-bogus" });
diff --git a/tests/unit/authz/pipeline.test.ts b/tests/unit/authz/pipeline.test.ts
index 5b42f2f91a..2b6e81c8c3 100644
--- a/tests/unit/authz/pipeline.test.ts
+++ b/tests/unit/authz/pipeline.test.ts
@@ -34,6 +34,15 @@ async function forceAuthRequired() {
await settingsDb.updateSettings({ requireLogin: true });
}
+async function dashboardCookie(expiresIn = "1h"): Promise<string> {
+ const secret = new TextEncoder().encode(process.env.JWT_SECRET);
+ const token = await new SignJWT({ authenticated: true })
+ .setProtectedHeader({ alg: "HS256" })
+ .setExpirationTime(expiresIn)
+ .sign(secret);
+ return `auth_token=${token}`;
+}
+
function request(url: string, init?: RequestInit): NextRequest {
return new NextRequest(url, init);
}
@@ -109,6 +118,23 @@ test("runAuthzPipeline rejects oversized API bodies before auth", async () => {
);
});
+test("runAuthzPipeline rejects oversized rewritten alias API bodies before auth", async () => {
+ const response = await pipeline.runAuthzPipeline(
+ request("http://localhost/v1/chat/completions", {
+ method: "POST",
+ headers: {
+ "content-length": String(99 * 1024 * 1024),
+ origin: "https://app.example.com",
+ },
+ }),
+ { enforce: true }
+ );
+
+ assert.equal(response.status, 413);
+ assert.equal(response.headers.get("x-omniroute-route-class"), "CLIENT_API");
+ assert.ok(response.headers.get("x-request-id"));
+});
+
test("runAuthzPipeline rejects new API requests during shutdown drain", async () => {
globalThis.__omnirouteShutdown = { init: true, shuttingDown: true, activeRequests: 0 };
@@ -121,6 +147,33 @@ test("runAuthzPipeline rejects new API requests during shutdown drain", async ()
assert.equal(body.error.code, "SERVICE_UNAVAILABLE");
});
+test("runAuthzPipeline rejects rewritten API aliases during shutdown drain", async () => {
+ globalThis.__omnirouteShutdown = { init: true, shuttingDown: true, activeRequests: 0 };
+
+ const response = await pipeline.runAuthzPipeline(request("http://localhost/responses"), {
+ enforce: true,
+ });
+ const body = await response.json();
+
+ assert.equal(response.status, 503);
+ assert.equal(response.headers.get("x-omniroute-route-class"), "CLIENT_API");
+ assert.equal(body.error.code, "SERVICE_UNAVAILABLE");
+});
+
+test("runAuthzPipeline allows dashboard sessions to read model catalog aliases", async () => {
+ await forceAuthRequired();
+
+ const response = await pipeline.runAuthzPipeline(
+ request("http://localhost/v1/models", {
+ headers: { cookie: await dashboardCookie() },
+ }),
+ { enforce: true }
+ );
+
+ assert.equal(response.status, 200);
+ assert.equal(response.headers.get("x-omniroute-route-class"), "CLIENT_API");
+});
+
test("runAuthzPipeline refreshes dashboard JWTs near expiry", async () => {
await forceAuthRequired();
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
diff --git a/tests/unit/combo-499-abort.test.ts b/tests/unit/combo-499-abort.test.ts
new file mode 100644
index 0000000000..0333fa72ac
--- /dev/null
+++ b/tests/unit/combo-499-abort.test.ts
@@ -0,0 +1,147 @@
+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-combo-499-"));
+process.env.DATA_DIR = TEST_DATA_DIR;
+process.env.API_KEY_SECRET = process.env.API_KEY_SECRET || "combo-499-test-secret";
+
+const { handleComboChat } = await import("../../open-sse/services/combo.ts");
+
+const noop = () => {};
+const log = { info: noop, warn: noop, debug: noop, error: noop };
+
+function makeCombo(strategy = "priority", models = ["a/model-1", "b/model-2", "c/model-3"]) {
+ return {
+ name: "test-combo-499",
+ strategy,
+ models: models.map((m) => ({ model: m })),
+ };
+}
+
+test("combo loop stops immediately when handleSingleModel returns 499 (client disconnect)", async () => {
+ let callCount = 0;
+ const handleSingleModel = async () => {
+ callCount++;
+ return new Response("Client disconnected", { status: 499 });
+ };
+
+ const result = await handleComboChat({
+ body: { model: "test", messages: [{ role: "user", content: "hi" }] },
+ combo: makeCombo("priority"),
+ handleSingleModel,
+ log,
+ settings: {},
+ allCombos: [],
+ });
+
+ // Should stop after the FIRST model — no fallback to model-2 or model-3
+ assert.equal(callCount, 1, "should only call handleSingleModel once on 499");
+ assert.equal(result.status, 499, "should return 499 status");
+});
+
+test("combo loop stops on signal.aborted before trying any model", async () => {
+ let callCount = 0;
+ const handleSingleModel = async () => {
+ callCount++;
+ return new Response("ok", { status: 200 });
+ };
+
+ const ac = new AbortController();
+ ac.abort(); // Pre-abort
+
+ const result = await handleComboChat({
+ body: { model: "test", messages: [{ role: "user", content: "hi" }] },
+ combo: makeCombo("priority"),
+ handleSingleModel,
+ log,
+ settings: {},
+ allCombos: [],
+ signal: ac.signal,
+ });
+
+ assert.equal(callCount, 0, "should NOT call handleSingleModel when signal is already aborted");
+ assert.equal(result.status, 499);
+});
+
+test("combo loop with 3 models: 499 on model-1 prevents trying model-2 and model-3", async () => {
+ const modelsCalled = [];
+ const handleSingleModel = async (_body, modelStr) => {
+ modelsCalled.push(modelStr);
+ return new Response("Client disconnected", { status: 499 });
+ };
+
+ const result = await handleComboChat({
+ body: { model: "test", messages: [{ role: "user", content: "hi" }] },
+ combo: makeCombo("priority", ["provider-a/fast", "provider-b/medium", "provider-c/large"]),
+ handleSingleModel,
+ log,
+ settings: {},
+ allCombos: [],
+ });
+
+ assert.equal(modelsCalled.length, 1);
+ assert.ok(
+ modelsCalled[0].includes("fast"),
+ `Expected first model to contain 'fast', got '${modelsCalled[0]}'`
+ );
+ assert.equal(result.status, 499);
+});
+
+test("combo loop does NOT stop on 502 (transient) — tries more than one model", async () => {
+ let callCount = 0;
+ const handleSingleModel = async () => {
+ callCount++;
+ return new Response("Bad Gateway", { status: 502 });
+ };
+
+ const result = await handleComboChat({
+ body: { model: "test", messages: [{ role: "user", content: "hi" }] },
+ combo: makeCombo("priority", ["a/m1", "b/m2", "c/m3"]),
+ handleSingleModel,
+ log,
+ settings: {},
+ allCombos: [],
+ });
+
+ // Key assertion: unlike 499, a 502 should try more than 1 model
+ assert.ok(callCount >= 2, `502 should attempt multiple models, but only tried ${callCount}`);
+ assert.equal(result.status, 502, "should still return 502 if all models fail");
+});
+
+test("signal abort during fallback wait interrupts immediately", async () => {
+ const ac = new AbortController();
+ let callCount = 0;
+
+ const handleSingleModel = async () => {
+ callCount++;
+ if (callCount === 1) {
+ // First call returns 502 (which triggers fallback wait)
+ return new Response("Bad Gateway", { status: 502 });
+ }
+ return new Response("ok", { status: 200 });
+ };
+
+ // Abort 50ms after start — should interrupt any wait
+ const timer = setTimeout(() => ac.abort(), 50);
+
+ const startMs = Date.now();
+ const result = await handleComboChat({
+ body: { model: "test", messages: [{ role: "user", content: "hi" }] },
+ combo: makeCombo("priority", ["a/m1", "b/m2"]),
+ handleSingleModel,
+ log,
+ settings: { retryDelayMs: 5000 }, // 5s delay would normally be slow
+ allCombos: [],
+ signal: ac.signal,
+ });
+
+ clearTimeout(timer);
+ const elapsed = Date.now() - startMs;
+
+ // Should complete in well under 5s — the abort interrupted the fallback wait
+ assert.ok(elapsed < 2000, `Expected fast abort, but took ${elapsed}ms`);
+ assert.equal(result.status, 499, "should return 499 after abort during wait");
+});
diff --git a/tests/unit/combo-test-route.test.ts b/tests/unit/combo-test-route.test.ts
index ecb1cc6875..a809e7eca7 100644
--- a/tests/unit/combo-test-route.test.ts
+++ b/tests/unit/combo-test-route.test.ts
@@ -6,15 +6,19 @@ import path from "node:path";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-combo-test-route-"));
process.env.DATA_DIR = TEST_DATA_DIR;
+process.env.API_KEY_SECRET = process.env.API_KEY_SECRET || "combo-test-route-secret";
const core = await import("../../src/lib/db/core.ts");
+const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");
const combosDb = await import("../../src/lib/db/combos.ts");
+const runtimePorts = await import("../../src/lib/runtime/ports.ts");
const route = await import("../../src/app/api/combos/test/route.ts");
const originalFetch = globalThis.fetch;
async function resetStorage() {
core.resetDbInstance();
+ apiKeysDb.resetApiKeyState();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}
@@ -35,6 +39,10 @@ function makeRequest(comboName = "strict-live-test") {
});
}
+function expectedInternalUrl(pathname: string): string {
+ return `http://127.0.0.1:${runtimePorts.getRuntimePorts().apiPort}${pathname}`;
+}
+
test.beforeEach(async () => {
globalThis.fetch = originalFetch;
await resetStorage();
@@ -125,7 +133,7 @@ test("combo test route marks a model healthy only when it returns assistant text
assert.equal(response.status, 200);
assert.equal(fetchCalls.length, 1);
- assert.equal(fetchCalls[0].url, "http://localhost/v1/chat/completions");
+ assert.equal(fetchCalls[0].url, expectedInternalUrl("/v1/chat/completions"));
assert.equal(fetchCalls[0].init.headers["X-Internal-Test"], "combo-health-check");
assert.equal(fetchCalls[0].init.headers["X-OmniRoute-No-Cache"], "true");
assert.match(fetchCalls[0].init.headers["X-Request-Id"], /^combo-test-/);
@@ -362,7 +370,7 @@ test("combo test route preserves structured step metadata for repeated model/acc
assert.equal(body.resolvedByTarget.connectionId, "conn-openai-a");
});
-test("combo test route rejects empty combos and respects forwarded base URLs", async () => {
+test("combo test route rejects empty combos and ignores forwarded origins for internal probes", async () => {
await createTestCombo([]);
const emptyResponse = await route.POST(makeRequest());
@@ -372,6 +380,7 @@ test("combo test route rejects empty combos and respects forwarded base URLs", a
await resetStorage();
await createTestCombo(["provider/forwarded"]);
+ const internalKey = await apiKeysDb.createApiKey("combo-internal", "machine-combo-internal");
const fetchCalls = [];
globalThis.fetch = async (url, init = {}) => {
@@ -392,7 +401,7 @@ test("combo test route rejects empty combos and respects forwarded base URLs", a
method: "POST",
headers: {
"content-type": "application/json",
- "x-forwarded-host": "router.example.com",
+ "x-forwarded-host": "attacker.example.com",
"x-forwarded-proto": "https",
},
body: JSON.stringify({ comboName: "strict-live-test" }),
@@ -401,7 +410,9 @@ test("combo test route rejects empty combos and respects forwarded base URLs", a
assert.equal(forwardedResponse.status, 200);
assert.equal(fetchCalls.length, 1);
- assert.equal(fetchCalls[0].url, "https://router.example.com/v1/chat/completions");
+ assert.equal(fetchCalls[0].url, expectedInternalUrl("/v1/chat/completions"));
+ assert.equal(fetchCalls[0].init.headers.Authorization, `Bearer ${internalKey.key}`);
+ assert.equal(String(fetchCalls[0].url).includes("attacker.example.com"), false);
});
test("combo test route handles upstream timeouts and non-JSON error bodies", async () => {