Files
OmniRoute/tests/unit/chat-combo-live-test.test.ts
Ravi Tharuma 137e49e393 feat(search): first-class X Search via SuperGrok x_search (#10988)
5 — Provider x-search de primeira classe (SuperGrok/xAI x_search) em POST /v1/search e MCP omniroute_x_search. Fallback de credenciais xai-oauth→xao→xai; distinto de web search e do X Developer MCP.

Reconciliado com o release tip (que já incluía #10981 "skip catalog-default SearXNG" deste mesmo lote): merge trouxe 5 conflitos reais de contagem gerada (llm.txt/README.md/AGENTS.md/PROVIDER_REFERENCE.md/SVGs/46 mirrors i18n, todos verificados como bump puro 347→348, sem perda de conteúdo do HEAD) + 1 conflito real de mergeable=CONFLICTING.

Durante a validação, os 3 testes novos de SearXNG expuseram um bug real de interação com #10981: `isUnconfiguredLoopbackSearchProvider()` checava o baseUrl ESTÁTICO do catálogo em vez do baseUrl efetivo (após override de `provider_options.baseUrl` ou `providerSpecificData.baseUrl` da conexão), então QUALQUER request a searxng-search — mesmo com override customizado — era rejeitado como se fosse o default não-configurado. Corrigido em `open-sse/handlers/search.ts` (resolve o baseUrl efetivo via `resolveSearchBaseUrl()` antes do skip-check, tanto para o provider primário quanto o alternate). Um teste do próprio #10988 que assumia o comportamento pré-#10981 (default localhost:8888 sempre atendido) foi atualizado para refletir o comportamento já mesclado e intencional (503 quando não configurado).

Validação completa: typecheck limpo, 70/70 testes unit (search-route/search-registry/x-search-provider/searxng-loopback-default), 24/24 vitest MCP, 14/14 integration (search-providers-catalog), lint limpo nos arquivos tocados, docs-counts-sync OK (2 drifts soft pré-existentes, não relacionados), gates estáticos (file-size/complexity/cognitive/dead-code/changelog) todos OK.
2026-08-21 14:16:42 -03:00

352 lines
10 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-chat-combo-live-"));
process.env.DATA_DIR = TEST_DATA_DIR;
const core = await import("../../src/lib/db/core.ts");
const providersDb = await import("../../src/lib/db/providers.ts");
const settingsDb = await import("../../src/lib/db/settings.ts");
const chatRoute = await import("../../src/app/api/v1/chat/completions/route.ts");
const { generateSignature, invalidateBySignature, setCachedResponse } =
await import("../../src/lib/semanticCache.ts");
const { getCircuitBreaker, resetAllCircuitBreakers, STATE } =
await import("../../src/shared/utils/circuitBreaker.ts");
const originalFetch = globalThis.fetch;
async function flushBackgroundWork() {
await new Promise((resolve) => setTimeout(resolve, 50));
await new Promise((resolve) => setImmediate(resolve));
}
async function resetStorage() {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
resetAllCircuitBreakers();
}
async function seedSuppressedConnection() {
return providersDb.createProviderConnection({
provider: "openai",
authType: "apikey",
name: "openai-live-test",
apiKey: "sk-live-test",
isActive: true,
testStatus: "credits_exhausted",
rateLimitedUntil: new Date(Date.now() + 60_000).toISOString(),
});
}
async function seedHealthyConnection() {
return providersDb.createProviderConnection({
provider: "openai",
authType: "apikey",
name: "openai-cache-test",
apiKey: "sk-cache-test",
isActive: true,
testStatus: "active",
});
}
function makeRequest(extraHeaders = {}) {
return new Request("http://localhost/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
...extraHeaders,
},
body: JSON.stringify({
model: "openai/gpt-4.1",
messages: [{ role: "user", content: "Reply with OK only." }],
max_tokens: 16,
stream: false,
temperature: 0,
}),
});
}
function makeStreamingRequest(extraHeaders = {}) {
return new Request("http://localhost/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "text/event-stream",
...extraHeaders,
},
body: JSON.stringify({
model: "openai/gpt-4.1",
messages: [{ role: "user", content: "Stream OK only." }],
max_tokens: 16,
stream: true,
temperature: 0,
}),
});
}
function makeRequestWithoutStreamFlag(extraHeaders = {}) {
return new Request("http://localhost/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
...extraHeaders,
},
body: JSON.stringify({
model: "openai/gpt-4.1",
messages: [{ role: "user", content: "Reply with OMITTED STREAM OK only." }],
max_tokens: 16,
temperature: 0,
}),
});
}
async function readAll(response: Response): Promise<string> {
const reader = response.body!.getReader();
const decoder = new TextDecoder();
let out = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (value) out += decoder.decode(value, { stream: true });
}
return out;
}
test.beforeEach(async () => {
globalThis.fetch = originalFetch;
await resetStorage();
});
test.afterEach(async () => {
await flushBackgroundWork();
globalThis.fetch = originalFetch;
resetAllCircuitBreakers();
});
test.after(async () => {
await flushBackgroundWork();
globalThis.fetch = originalFetch;
resetAllCircuitBreakers();
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
});
test("combo live test bypasses connection cooldown and breaker state to perform a real upstream request", async () => {
const created = await seedSuppressedConnection();
const fetchCalls = [];
globalThis.fetch = async (url, init = {}) => {
fetchCalls.push({ url: String(url), init });
return Response.json({
id: "chatcmpl-live-test",
choices: [
{
message: {
role: "assistant",
content: "OK",
},
},
],
});
};
const blockedByCooldown = await chatRoute.POST(makeRequest());
assert.equal(blockedByCooldown.status, 503);
assert.equal(fetchCalls.length, 0);
const breaker = getCircuitBreaker("openai");
breaker.state = STATE.OPEN;
breaker.lastFailureTime = Date.now();
breaker.resetTimeout = 60_000;
const blockedByBreaker = await chatRoute.POST(makeRequest());
assert.equal(blockedByBreaker.status, 503);
assert.equal(fetchCalls.length, 0);
const liveResponse = await chatRoute.POST(
makeRequest({ "X-Internal-Test": "combo-health-check" })
);
const liveBody = (await liveResponse.json()) as any;
assert.equal(liveResponse.status, 200);
assert.equal(fetchCalls.length, 1);
assert.match(fetchCalls[0].url, /\/chat\/completions$/);
assert.equal(fetchCalls[0].init.headers.Authorization, "Bearer sk-live-test");
assert.equal(liveBody.choices[0].message.content, "OK");
const updated = await providersDb.getProviderConnectionById((created as any).id);
assert.equal(updated.testStatus, "active");
});
test("combo live test bypasses semantic cache and forces a fresh upstream request", async () => {
await seedHealthyConnection();
const signature = generateSignature(
"gpt-4.1",
[{ role: "user", content: "Reply with OK only." }],
0,
1
);
setCachedResponse(signature, "gpt-4.1", {
id: "chatcmpl-cached",
choices: [
{
message: {
role: "assistant",
content: "CACHED",
},
},
],
});
const fetchCalls = [];
globalThis.fetch = async (url, init = {}) => {
fetchCalls.push({ url: String(url), init });
return Response.json({
id: "chatcmpl-live",
choices: [
{
message: {
role: "assistant",
content: "LIVE",
},
},
],
});
};
try {
const cachedResponse = await chatRoute.POST(makeRequest());
const cachedBody = (await cachedResponse.json()) as any;
assert.equal(cachedResponse.status, 200);
assert.equal(fetchCalls.length, 0);
assert.equal(cachedBody.choices[0].message.content, "CACHED");
const liveResponse = await chatRoute.POST(
makeRequest({
"X-Internal-Test": "combo-health-check",
"X-OmniRoute-No-Cache": "true",
"X-Request-Id": "combo-test-cache-bypass",
})
);
const liveBody = (await liveResponse.json()) as any;
assert.equal(liveResponse.status, 200);
assert.equal(fetchCalls.length, 1);
assert.match(fetchCalls[0].url, /\/chat\/completions$/);
assert.equal(liveBody.choices[0].message.content, "LIVE");
} finally {
invalidateBySignature(signature);
}
});
test("chat completions route emits early keepalive while waiting for stream readiness", async () => {
await seedHealthyConnection();
globalThis.fetch = async () => {
// Must exceed resolveKeepaliveThreshold()'s DEFAULT_THRESHOLD_MS (2000ms) for
// openai/* — otherwise withEarlyStreamKeepalive takes the FAST path, forwards
// the handler response as-is and no keepalive frame is ever emitted. The old
// 100ms only worked while unrelated handler latency happened to push the
// total past the threshold, which made this assertion incidental rather than
// deterministic; it stopped holding once the handler got faster.
await new Promise((resolve) => setTimeout(resolve, 2_400));
return new Response(
[
`data: ${JSON.stringify({
id: "chatcmpl-slow-stream",
object: "chat.completion.chunk",
choices: [{ index: 0, delta: { role: "assistant", content: "OK" } }],
})}`,
"",
"data: [DONE]",
"",
].join("\n"),
{
status: 200,
headers: { "Content-Type": "text/event-stream" },
}
);
};
const response = await chatRoute.POST(makeStreamingRequest());
assert.equal(response.status, 200);
assert.match(response.headers.get("content-type") || "", /text\/event-stream/);
const body = await readAll(response);
assert.match(body, /data: \{"id":"chatcmpl-keepalive","object":"chat\.completion\.chunk"/);
assert.match(body, /OK/);
assert.match(body, /\[DONE\]/);
});
test("chat completions route returns JSON without early SSE framing when stream is omitted and Accept is application/json", async () => {
await seedHealthyConnection();
globalThis.fetch = async () => {
await new Promise((resolve) => setTimeout(resolve, 100));
return Response.json({
id: "chatcmpl-slow-json",
choices: [
{
message: {
role: "assistant",
content: "OK",
},
},
],
});
};
const response = await chatRoute.POST(
makeRequestWithoutStreamFlag({
Accept: "application/json",
"X-OmniRoute-No-Cache": "true",
"X-Request-Id": "chat-route-omitted-stream-json",
})
);
assert.equal(response.status, 200);
assert.doesNotMatch(response.headers.get("content-type") || "", /text\/event-stream/);
const body = (await response.json()) as any;
assert.equal(body.choices[0].message.content, "OK");
});
test("combo live test does not use cooldown-aware request retry on upstream failures", async () => {
await seedHealthyConnection();
await settingsDb.updateSettings({
requestRetry: 3,
maxRetryIntervalSec: 5,
});
let fetchCalls = 0;
globalThis.fetch = async () => {
fetchCalls += 1;
return Response.json(
{
error: {
message: "upstream unavailable",
},
},
{ status: 503 }
);
};
const liveResponse = await chatRoute.POST(
makeRequest({ "X-Internal-Test": "combo-health-check" })
);
const liveBody = (await liveResponse.json()) as any;
assert.equal(liveResponse.status, 503);
assert.ok(
fetchCalls >= 1 && fetchCalls <= 3,
`live combo test should not storm retries, got ${fetchCalls} fetches`
);
assert.match(liveBody.error.message, /upstream unavailable/i);
});