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(stream): fail zombie streams before accepting response (#1693)

Raxxoor9c9ba8f2bd9f
diff --git a/open-sse/config/constants.ts b/open-sse/config/constants.ts
index 421c62722e..7fb1d46392 100644
--- a/open-sse/config/constants.ts
+++ b/open-sse/config/constants.ts
@@ -11,9 +11,10 @@ const upstreamTimeouts = getUpstreamTimeoutConfig(process.env, (message) => {
// and Undici's bodyTimeout instead of this one-shot startup timer.
export const FETCH_TIMEOUT_MS = upstreamTimeouts.fetchTimeoutMs;
-// Idle timeout for SSE streams (ms). Closes stream if no data for this duration.
-// Default: 120s balances deep-reasoning pauses with fast zombie stream detection (#473).
-// Extended-thinking models rarely pause >90s between chunks. Override with STREAM_IDLE_TIMEOUT_MS env var.
+// Idle timeout for SSE streams (ms). Before a stream is accepted, the same
+// budget is used to wait for the first useful event so HTTP 200 zombie streams
+// can fail fast and trigger fallback. After startup, it closes streams that go
+// idle for this duration. Override with STREAM_IDLE_TIMEOUT_MS env var.
export const STREAM_IDLE_TIMEOUT_MS = upstreamTimeouts.streamIdleTimeoutMs;
// Timeout for reading the full response body after headers arrive (ms).
diff --git a/open-sse/handlers/chatCore.ts b/open-sse/handlers/chatCore.ts
index fb2198aeaa..cc1a778d25 100644
--- a/open-sse/handlers/chatCore.ts
+++ b/open-sse/handlers/chatCore.ts
@@ -8,6 +8,7 @@ import {
COLORS,
withBodyTimeout,
} from "../utils/stream.ts";
+import { ensureStreamReadiness } from "../utils/streamReadiness.ts";
import { createStreamController, pipeWithDisconnect } from "../utils/streamHandler.ts";
import { addBufferToUsage, filterUsageForFormat, estimateUsage } from "../utils/usageTracking.ts";
import { refreshWithRetry } from "../services/tokenRefresh.ts";
@@ -25,7 +26,12 @@ import {
parseUpstreamError,
formatProviderError,
} from "../utils/error.ts";
-import { COOLDOWN_MS, HTTP_STATUS, PROVIDER_MAX_TOKENS } from "../config/constants.ts";
+import {
+ COOLDOWN_MS,
+ HTTP_STATUS,
+ PROVIDER_MAX_TOKENS,
+ STREAM_IDLE_TIMEOUT_MS,
+} from "../config/constants.ts";
import {
classifyProviderError,
PROVIDER_ERROR_TYPES,
@@ -3208,6 +3214,48 @@ export async function handleChatCore({
}
// Streaming response
+ const streamReadiness = await ensureStreamReadiness(providerResponse, {
+ timeoutMs: STREAM_IDLE_TIMEOUT_MS,
+ provider,
+ model,
+ log,
+ });
+ if (streamReadiness.ok === false) {
+ const { response: failureResponse, reason } = streamReadiness;
+ const failure = {
+ status: failureResponse.status,
+ message: reason,
+ code: "stream_readiness_timeout",
+ type: "stream_timeout",
+ };
+ trackPendingRequest(model, provider, connectionId, false);
+ appendRequestLog({
+ model,
+ provider,
+ connectionId,
+ status: `FAILED ${failureResponse.status}`,
+ }).catch(() => {});
+ persistAttemptLogs({
+ status: failureResponse.status,
+ error: reason,
+ providerRequest: finalBody || translatedBody,
+ clientResponse: buildErrorBody(failureResponse.status, reason),
+ claudeCacheMeta: claudePromptCacheLogMeta,
+ cacheSource: "upstream",
+ });
+ persistFailureUsage(failureResponse.status, "stream_readiness_timeout");
+ // Do NOT call onStreamFailure — a stream stall is an upstream issue,
+ // not an account/quota failure. Marking the account unavailable here
+ // would lock out legitimate accounts when the upstream hangs.
+ return {
+ success: false,
+ status: failureResponse.status,
+ error: reason,
+ errorType: "stream_readiness_timeout",
+ response: failureResponse,
+ };
+ }
+ providerResponse = streamReadiness.response;
// Notify success - caller can clear error status if needed
if (onRequestSuccess) {
diff --git a/open-sse/services/combo.ts b/open-sse/services/combo.ts
index 988b7c432c..f7082d1f7d 100644
--- a/open-sse/services/combo.ts
+++ b/open-sse/services/combo.ts
@@ -285,6 +285,13 @@ function getTargetProvider(modelStr: string, providerId?: string | null): string
return providerId || parsed.provider || parsed.providerAlias || "unknown";
}
+function isStreamReadinessTimeoutErrorBody(errorBody: unknown): boolean {
+ if (!errorBody || typeof errorBody !== "object") return false;
+ const error = (errorBody as Record<string, unknown>).error;
+ if (!error || typeof error !== "object") return false;
+ return (error as Record<string, unknown>).code === "STREAM_READINESS_TIMEOUT";
+}
+
function toRecordedTarget(target: ResolvedComboTarget) {
return {
executionKey: target.executionKey,
@@ -1699,6 +1706,8 @@ export async function handleComboChat({
}
const providerBreakerOpen = isProviderBreakerOpenResponse(result, errorBody);
+ const isStreamReadinessTimeout =
+ result.status === 504 && isStreamReadinessTimeoutErrorBody(errorBody);
// Fix #1681: Status 499 means client disconnected — stop combo loop immediately.
// There is no point trying fallback models when nobody is listening.
@@ -1755,7 +1764,8 @@ export async function handleComboChat({
}
// Check if this is a transient error worth retrying on same model
- const isTransient = [408, 429, 500, 502, 503, 504].includes(result.status);
+ const isTransient =
+ !isStreamReadinessTimeout && [408, 429, 500, 502, 503, 504].includes(result.status);
if (retry < maxRetries && isTransient) {
continue; // Retry same model
}
@@ -2066,6 +2076,8 @@ async function handleRoundRobinCombo({
);
break;
}
+ const isStreamReadinessTimeout =
+ result.status === 504 && isStreamReadinessTimeoutErrorBody(errorBody);
const { shouldFallback, cooldownMs } = checkFallbackError(
result.status,
@@ -2116,7 +2128,8 @@ async function handleRoundRobinCombo({
}
// Transient error → retry same model
- const isTransient = [408, 429, 500, 502, 503, 504].includes(result.status);
+ const isTransient =
+ !isStreamReadinessTimeout && [408, 429, 500, 502, 503, 504].includes(result.status);
if (retry < maxRetries && isTransient) {
continue;
}
diff --git a/open-sse/utils/streamReadiness.ts b/open-sse/utils/streamReadiness.ts
new file mode 100644
index 0000000000..ed3a5729ba
--- /dev/null
+++ b/open-sse/utils/streamReadiness.ts
@@ -0,0 +1,238 @@
+import { HTTP_STATUS } from "../config/constants.ts";
+
+type StreamReadinessLogger = {
+ debug?: (tag: string, message: string) => void;
+ warn?: (tag: string, message: string) => void;
+};
+
+export type StreamReadinessResult =
+ | { ok: true; response: Response }
+ | { ok: false; response: Response; reason: string };
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === "object" && !Array.isArray(value);
+}
+
+function hasNonEmptyString(value: unknown): boolean {
+ return typeof value === "string" && value.length > 0;
+}
+
+function hasUsefulValue(value: unknown): boolean {
+ if (hasNonEmptyString(value)) return true;
+ if (Array.isArray(value)) return value.some(hasUsefulValue);
+ if (!isRecord(value)) return false;
+
+ for (const key of [
+ "content",
+ "text",
+ "delta",
+ "reasoning_content",
+ "reasoning",
+ "partial_json",
+ "arguments",
+ "name",
+ ]) {
+ const candidate = value[key];
+ if (hasNonEmptyString(candidate)) return true;
+ if ((Array.isArray(candidate) || isRecord(candidate)) && hasUsefulValue(candidate)) return true;
+ }
+
+ for (const key of [
+ "tool_calls",
+ "tool_use",
+ "function",
+ "functionCall",
+ "function_call",
+ "function_call_output",
+ "output",
+ "content_block",
+ "parts",
+ ]) {
+ if (hasUsefulValue(value[key])) return true;
+ }
+
+ return false;
+}
+
+function hasUsefulJsonPayload(payload: unknown): boolean {
+ if (!isRecord(payload)) return false;
+
+ const type = typeof payload.type === "string" ? payload.type : "";
+ if (
+ type.includes("delta") ||
+ type.includes("tool") ||
+ type.includes("function") ||
+ type.includes("content_block") ||
+ type.includes("output_item")
+ ) {
+ if (hasUsefulValue(payload)) return true;
+ }
+
+ return hasUsefulValue(payload.choices) || hasUsefulValue(payload.candidates) || hasUsefulValue(payload);
+}
+
+export function hasUsefulStreamContent(text: string): boolean {
+ const lines = text.split(/\r?\n/);
+
+ for (const line of lines) {
+ const trimmed = line.trim();
+ if (!trimmed || trimmed.startsWith(":")) continue;
+ if (/^event:\s*(?:ping|keepalive)$/i.test(trimmed)) continue;
+ if (!trimmed.startsWith("data:")) continue;
+
+ const data = trimmed.slice(5).trim();
+ if (!data || data === "[DONE]") continue;
+
+ try {
+ if (hasUsefulJsonPayload(JSON.parse(data))) return true;
+ } catch {
+ if (data.length > 0) return true;
+ }
+ }
+
+ return false;
+}
+
+function createErrorResponse(status: number, message: string): Response {
+ return new Response(
+ JSON.stringify({
+ error: {
+ message,
+ type: "stream_timeout",
+ code: "STREAM_READINESS_TIMEOUT",
+ },
+ }),
+ { status, headers: { "Content-Type": "application/json" } }
+ );
+}
+
+function prependBufferedChunks(
+ chunks: Uint8Array[],
+ reader: ReadableStreamDefaultReader<Uint8Array>
+): ReadableStream<Uint8Array> {
+ return new ReadableStream<Uint8Array>({
+ async start(controller) {
+ try {
+ for (const chunk of chunks) {
+ controller.enqueue(chunk);
+ }
+
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (value) controller.enqueue(value);
+ }
+
+ controller.close();
+ } catch (error) {
+ controller.error(error);
+ } finally {
+ reader.releaseLock();
+ }
+ },
+ async cancel(reason) {
+ await reader.cancel(reason).catch(() => {});
+ reader.releaseLock();
+ },
+ });
+}
+
+function readWithTimeout(
+ reader: ReadableStreamDefaultReader<Uint8Array>,
+ timeoutMs: number
+): Promise<ReadableStreamReadResult<Uint8Array>> {
+ return new Promise((resolve, reject) => {
+ const timeout = setTimeout(() => reject(new Error("STREAM_READINESS_TIMEOUT")), timeoutMs);
+ reader.read().then(
+ (value) => {
+ clearTimeout(timeout);
+ resolve(value);
+ },
+ (error) => {
+ clearTimeout(timeout);
+ reject(error);
+ }
+ );
+ });
+}
+
+export async function ensureStreamReadiness(
+ response: Response,
+ options: {
+ timeoutMs: number;
+ provider?: string | null;
+ model?: string | null;
+ log?: StreamReadinessLogger | null;
+ }
+): Promise<StreamReadinessResult> {
+ if (!response.body || options.timeoutMs <= 0) return { ok: true, response };
+
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ const decoder = new TextDecoder();
+ let bufferedText = "";
+ const startedAt = Date.now();
+ const deadline = startedAt + options.timeoutMs;
+ let handedOffReader = false;
+
+ try {
+ while (true) {
+ const remainingMs = deadline - Date.now();
+ if (remainingMs <= 0) {
+ const reason = `Stream produced no useful content within ${options.timeoutMs}ms`;
+ options.log?.warn?.(
+ "STREAM",
+ `${reason} (${options.provider || "provider"}/${options.model || "unknown"})`
+ );
+ await reader.cancel(reason).catch(() => {});
+ return { ok: false, reason, response: createErrorResponse(HTTP_STATUS.GATEWAY_TIMEOUT, reason) };
+ }
+
+ let readResult: ReadableStreamReadResult<Uint8Array>;
+ try {
+ readResult = await readWithTimeout(reader, remainingMs);
+ } catch {
+ const reason = `Stream produced no useful content within ${options.timeoutMs}ms`;
+ options.log?.warn?.(
+ "STREAM",
+ `${reason} (${options.provider || "provider"}/${options.model || "unknown"})`
+ );
+ await reader.cancel(reason).catch(() => {});
+ return { ok: false, reason, response: createErrorResponse(HTTP_STATUS.GATEWAY_TIMEOUT, reason) };
+ }
+
+ if (readResult.done) {
+ const reason = "Stream ended before producing useful content";
+ options.log?.warn?.(
+ "STREAM",
+ `${reason} (${options.provider || "provider"}/${options.model || "unknown"})`
+ );
+ return { ok: false, reason, response: createErrorResponse(HTTP_STATUS.BAD_GATEWAY, reason) };
+ }
+
+ if (!readResult.value) continue;
+ chunks.push(readResult.value);
+ bufferedText += decoder.decode(readResult.value, { stream: true });
+
+ if (hasUsefulStreamContent(bufferedText)) {
+ options.log?.debug?.(
+ "STREAM",
+ `Stream readiness confirmed in ${Date.now() - startedAt}ms (${options.provider || "provider"}/${options.model || "unknown"})`
+ );
+ handedOffReader = true;
+ return {
+ ok: true,
+ response: new Response(prependBufferedChunks(chunks, reader), {
+ status: response.status,
+ statusText: response.statusText,
+ headers: response.headers,
+ }),
+ };
+ }
+ }
+ } finally {
+ if (!handedOffReader) {
+ reader.releaseLock();
+ }
+ }
+}
diff --git a/src/sse/handlers/chat.ts b/src/sse/handlers/chat.ts
index 4c15e5e8d5..b8fcc35448 100644
--- a/src/sse/handlers/chat.ts
+++ b/src/sse/handlers/chat.ts
@@ -747,6 +747,12 @@ async function handleSingleModelChat(
return result.response;
}
+ if (result.errorType === "stream_readiness_timeout") {
+ // Stream readiness timeout is an upstream stall, not an account/quota failure.
+ // Do NOT mark the account as unavailable or trip the circuit breaker.
+ return result.response;
+ }
+
// Emergency fallback for budget exhaustion (402 / billing / quota keywords):
// reroute to a free model (default provider/model: nvidia + openai/gpt-oss-120b) exactly once.
if (!runtimeOptions.emergencyFallbackTried) {
diff --git a/tests/unit/chat-cooldown-aware-retry.test.ts b/tests/unit/chat-cooldown-aware-retry.test.ts
index 1ab266a799..4eda86f660 100644
--- a/tests/unit/chat-cooldown-aware-retry.test.ts
+++ b/tests/unit/chat-cooldown-aware-retry.test.ts
@@ -3,8 +3,11 @@ import assert from "node:assert/strict";
import { createChatPipelineHarness } from "../integration/_chatPipelineHarness.ts";
+process.env.STREAM_IDLE_TIMEOUT_MS = "50";
+
const harness = await createChatPipelineHarness("chat-cooldown-aware-retry");
const auth = await import("../../src/sse/services/auth.ts");
+const { getProviderConnectionById } = await import("../../src/lib/db/providers.ts");
const {
BaseExecutor,
buildOpenAIResponse,
@@ -14,6 +17,7 @@ const {
seedConnection,
settingsDb,
} = harness;
+const textEncoder = new TextEncoder();
const originalRetryConfig = {
maxAttempts: BaseExecutor.RETRY_CONFIG.maxAttempts,
delayMs: BaseExecutor.RETRY_CONFIG.delayMs,
@@ -30,6 +34,21 @@ function buildRequestWithSignal(body, signal) {
});
}
+function buildZombieSseResponse() {
+ return new Response(
+ new ReadableStream({
+ start(controller) {
+ controller.enqueue(textEncoder.encode(": keepalive\n\n"));
+ controller.enqueue(textEncoder.encode(`data: ${JSON.stringify({ type: "ping" })}\n\n`));
+ },
+ }),
+ {
+ status: 200,
+ headers: { "Content-Type": "text/event-stream" },
+ }
+ );
+}
+
test.beforeEach(async () => {
BaseExecutor.RETRY_CONFIG.maxAttempts = originalRetryConfig.maxAttempts;
BaseExecutor.RETRY_CONFIG.delayMs = 0;
@@ -222,6 +241,46 @@ test("handleChat returns model_cooldown when every credential for the requested
assert.ok(Number(response.headers.get("Retry-After")) >= 1);
});
+test("handleChat returns stream readiness timeout without entering cooldown-aware retry or account lockout", async () => {
+ const connection = await seedConnection("openai", {
+ apiKey: "sk-openai-stream-readiness-timeout",
+ });
+ await settingsDb.updateSettings({
+ requestRetry: 1,
+ maxRetryIntervalSec: 10,
+ });
+
+ let fetchCalls = 0;
+ globalThis.fetch = async () => {
+ fetchCalls += 1;
+ return buildZombieSseResponse();
+ };
+
+ const startedAt = Date.now();
+ const response = await handleChat(
+ buildRequest({
+ body: {
+ model: "openai/gpt-4o-mini",
+ stream: true,
+ messages: [{ role: "user", content: "trigger zombie stream" }],
+ },
+ })
+ );
+ const elapsedMs = Date.now() - startedAt;
+ const body = (await response.json()) as any;
+
+ assert.equal(response.status, 504);
+ assert.equal(fetchCalls, 1);
+ assert.ok(elapsedMs < 1000, `should not wait for cooldown retry, got ${elapsedMs}ms`);
+ assert.equal(body.error.code, "STREAM_READINESS_TIMEOUT");
+
+ const refreshedConnection = (await getProviderConnectionById((connection as any).id)) as any;
+ assert.equal(refreshedConnection.testStatus, "active");
+ assert.ok(refreshedConnection.rateLimitedUntil == null);
+ assert.ok(refreshedConnection.errorCode == null);
+ assert.equal(refreshedConnection.backoffLevel, 0);
+});
+
test("handleChat aborts the pending cooldown wait when the client disconnects", async () => {
await seedConnection("openai", {
apiKey: "sk-openai-cooldown-abort",
diff --git a/tests/unit/combo-stream-readiness-fallback.test.ts b/tests/unit/combo-stream-readiness-fallback.test.ts
new file mode 100644
index 0000000000..ed8cdc1e28
--- /dev/null
+++ b/tests/unit/combo-stream-readiness-fallback.test.ts
@@ -0,0 +1,235 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { handleComboChat } from "../../open-sse/services/combo.ts";
+import { ensureStreamReadiness } from "../../open-sse/utils/streamReadiness.ts";
+
+const textEncoder = new TextEncoder();
+
+function createLog() {
+ const entries: any[] = [];
+ return {
+ info: (tag: any, msg: any) => entries.push({ level: "info", tag, msg }),
+ warn: (tag: any, msg: any) => entries.push({ level: "warn", tag, msg }),
+ error: (tag: any, msg: any) => entries.push({ level: "error", tag, msg }),
+ debug: (tag: any, msg: any) => entries.push({ level: "debug", tag, msg }),
+ entries,
+ };
+}
+
+function okStreamResponse(content: string): Response {
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(
+ textEncoder.encode(
+ `data: ${JSON.stringify({
+ choices: [{ delta: { role: "assistant", content } }],
+ })}\n\n`
+ )
+ );
+ controller.enqueue(
+ textEncoder.encode(
+ `data: ${JSON.stringify({
+ choices: [{ delta: {}, finish_reason: "stop" }],
+ })}\n\n`
+ )
+ );
+ controller.enqueue(textEncoder.encode("data: [DONE]\n\n"));
+ controller.close();
+ },
+ });
+ return new Response(body, {
+ status: 200,
+ headers: { "Content-Type": "text/event-stream" },
+ });
+}
+
+function zombieStreamResponse(): Response {
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(textEncoder.encode(": keepalive\n\n"));
+ controller.enqueue(textEncoder.encode(`data: ${JSON.stringify({ type: "ping" })}\n\n`));
+ // Keep the stream open without useful content, matching HTTP 200 zombie streams.
+ },
+ cancel() {},
+ });
+
+ return new Response(body, {
+ status: 200,
+ headers: { "Content-Type": "text/event-stream" },
+ });
+}
+
+async function applyStreamReadiness(response: Response): Promise<Response> {
+ const result = await ensureStreamReadiness(response, {
+ timeoutMs: 10,
+ provider: "glm",
+ model: "zombie-model",
+ log: createLog(),
+ });
+ return result.response;
+}
+
+function errorResponse(status: number, message: string): Response {
+ return new Response(
+ JSON.stringify({ error: { message, type: "upstream_error" } }),
+ { status, headers: { "Content-Type": "application/json" } }
+ );
+}
+
+test("combo falls back when first model returns HTTP 200 zombie SSE stream", async () => {
+ const calls: string[] = [];
+ const log = createLog();
+
+ const result = await handleComboChat({
+ body: {
+ stream: true,
+ messages: [{ role: "user", content: "hello" }],
+ },
+ combo: {
+ name: "stream-readiness-504-fallback",
+ strategy: "priority",
+ models: [
+ { model: "glm/zombie-model", weight: 0 },
+ { model: "openai/gpt-5.4-mini", weight: 0 },
+ ],
+ config: { maxRetries: 0, retryDelayMs: 0 },
+ },
+ handleSingleModel: async (_body: any, modelStr: string) => {
+ calls.push(modelStr);
+ if (modelStr === "glm/zombie-model") {
+ return applyStreamReadiness(zombieStreamResponse());
+ }
+ return okStreamResponse("fallback success");
+ },
+ isModelAvailable: async () => true,
+ log,
+ settings: null,
+ allCombos: null,
+ relayOptions: null as any,
+ });
+
+ assert.equal(result.ok, true, "combo should succeed via fallback after 504");
+ assert.deepEqual(calls, ["glm/zombie-model", "openai/gpt-5.4-mini"]);
+ assert.ok(
+ log.entries.some(
+ (e) =>
+ e.level === "warn" &&
+ e.tag === "COMBO" &&
+ String(e.msg).includes("glm/zombie-model")
+ ),
+ "combo should log warning for the failed model"
+ );
+});
+
+test("combo fails when all models return 504", async () => {
+ const calls: string[] = [];
+ const log = createLog();
+
+ const result = await handleComboChat({
+ body: {
+ stream: true,
+ messages: [{ role: "user", content: "hello" }],
+ },
+ combo: {
+ name: "all-504-test",
+ strategy: "priority",
+ models: [
+ { model: "glm/zombie-a", weight: 0 },
+ { model: "glm/zombie-b", weight: 0 },
+ ],
+ config: { maxRetries: 0, retryDelayMs: 0 },
+ },
+ handleSingleModel: async (_body: any, modelStr: string) => {
+ calls.push(modelStr);
+ return applyStreamReadiness(zombieStreamResponse());
+ },
+ isModelAvailable: async () => true,
+ log,
+ settings: null,
+ allCombos: null,
+ relayOptions: null as any,
+ });
+
+ assert.ok(!result.ok, "combo should fail when all models return 504");
+ assert.equal(result.status, 504);
+ assert.equal(calls.length, 2, "combo should try both models");
+});
+
+test("combo retries 504 on same model before falling through (transient retry)", async () => {
+ const calls: string[] = [];
+ const log = createLog();
+
+ const result = await handleComboChat({
+ body: {
+ stream: true,
+ messages: [{ role: "user", content: "hello" }],
+ },
+ combo: {
+ name: "retry-504-test",
+ strategy: "priority",
+ models: [
+ { model: "glm/zombie", weight: 0 },
+ { model: "openai/gpt-5.4-mini", weight: 0 },
+ ],
+ config: { maxRetries: 1, retryDelayMs: 0 },
+ },
+ handleSingleModel: async (_body: any, modelStr: string) => {
+ calls.push(modelStr);
+ if (modelStr === "glm/zombie") {
+ return errorResponse(504, "Stream produced no useful content within 60000ms");
+ }
+ return okStreamResponse("fallback after retries");
+ },
+ isModelAvailable: async () => true,
+ log,
+ settings: null,
+ allCombos: null,
+ relayOptions: null as any,
+ });
+
+ assert.equal(result.ok, true, "combo should succeed via fallback after retries");
+ const zombieCalls = calls.filter((c) => c === "glm/zombie");
+ assert.equal(
+ zombieCalls.length,
+ 2,
+ "combo should retry zombie once before falling through"
+ );
+ assert.ok(calls.includes("openai/gpt-5.4-mini"), "combo should reach fallback model");
+});
+
+test("combo does not retry stream readiness timeouts on the same model", async () => {
+ const calls: string[] = [];
+ const log = createLog();
+
+ const result = await handleComboChat({
+ body: {
+ stream: true,
+ messages: [{ role: "user", content: "hello" }],
+ },
+ combo: {
+ name: "no-retry-readiness-timeout-test",
+ strategy: "priority",
+ models: [
+ { model: "glm/zombie", weight: 0 },
+ { model: "openai/gpt-5.4-mini", weight: 0 },
+ ],
+ config: { maxRetries: 1, retryDelayMs: 0 },
+ },
+ handleSingleModel: async (_body: any, modelStr: string) => {
+ calls.push(modelStr);
+ if (modelStr === "glm/zombie") {
+ return applyStreamReadiness(zombieStreamResponse());
+ }
+ return okStreamResponse("fallback without same-model retry");
+ },
+ isModelAvailable: async () => true,
+ log,
+ settings: null,
+ allCombos: null,
+ relayOptions: null as any,
+ });
+
+ assert.equal(result.ok, true, "combo should succeed via fallback");
+ assert.deepEqual(calls, ["glm/zombie", "openai/gpt-5.4-mini"]);
+});
diff --git a/tests/unit/stream-readiness.test.ts b/tests/unit/stream-readiness.test.ts
new file mode 100644
index 0000000000..1917dd3827
--- /dev/null
+++ b/tests/unit/stream-readiness.test.ts
@@ -0,0 +1,110 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ ensureStreamReadiness,
+ hasUsefulStreamContent,
+} from "../../open-sse/utils/streamReadiness.ts";
+
+const encoder = new TextEncoder();
+
+function streamFromChunks(chunks: string[], delayMs = 0): ReadableStream<Uint8Array> {
+ return new ReadableStream<Uint8Array>({
+ async start(controller) {
+ for (const chunk of chunks) {
+ if (delayMs > 0) await new Promise((resolve) => setTimeout(resolve, delayMs));
+ controller.enqueue(encoder.encode(chunk));
+ }
+ controller.close();
+ },
+ });
+}
+
+test("hasUsefulStreamContent ignores keepalives and lifecycle-only chunks", () => {
+ assert.equal(hasUsefulStreamContent(": keepalive\n\n"), false);
+ assert.equal(hasUsefulStreamContent("event: ping\ndata: {}\n\n"), false);
+ assert.equal(
+ hasUsefulStreamContent(`data: ${JSON.stringify({ type: "response.created" })}\n\n`),
+ false
+ );
+ assert.equal(
+ hasUsefulStreamContent(
+ `data: ${JSON.stringify({ choices: [{ delta: { role: "assistant" }, index: 0 }] })}\n\n`
+ ),
+ false
+ );
+});
+
+test("hasUsefulStreamContent detects text, reasoning, and tool deltas", () => {
+ assert.equal(
+ hasUsefulStreamContent(
+ `data: ${JSON.stringify({ choices: [{ delta: { content: "hello" }, index: 0 }] })}\n\n`
+ ),
+ true
+ );
+ assert.equal(
+ hasUsefulStreamContent(
+ `data: ${JSON.stringify({ choices: [{ delta: { content: " " }, index: 0 }] })}\n\n`
+ ),
+ true
+ );
+ assert.equal(
+ hasUsefulStreamContent(
+ `data: ${JSON.stringify({ choices: [{ delta: { reasoning_content: "thinking" }, index: 0 }] })}\n\n`
+ ),
+ true
+ );
+ assert.equal(
+ hasUsefulStreamContent(
+ `data: ${JSON.stringify({ choices: [{ delta: { tool_calls: [{ function: { name: "read" } }] }, index: 0 }] })}\n\n`
+ ),
+ true
+ );
+ assert.equal(
+ hasUsefulStreamContent(
+ `data: ${JSON.stringify({ type: "content_block_delta", delta: { text: "hello" } })}\n\n`
+ ),
+ true
+ );
+});
+
+test("ensureStreamReadiness preserves buffered chunks when stream starts", async () => {
+ const response = new Response(
+ streamFromChunks([
+ `data: ${JSON.stringify({ type: "response.created" })}\n\n`,
+ `data: ${JSON.stringify({ choices: [{ delta: { content: "hello" }, index: 0 }] })}\n\n`,
+ `data: ${JSON.stringify({ choices: [{ delta: { content: " world" }, index: 0 }] })}\n\n`,
+ ]),
+ { status: 200, headers: { "Content-Type": "text/event-stream" } }
+ );
+
+ const result = await ensureStreamReadiness(response, { timeoutMs: 100 });
+ assert.equal(result.ok, true);
+ const text = await result.response.text();
+ assert.match(text, /response\.created/);
+ assert.match(text, /hello/);
+ assert.match(text, / world/);
+});
+
+test("ensureStreamReadiness returns 504 when no useful content arrives before timeout", async () => {
+ const response = new Response(
+ streamFromChunks([": keepalive\n\n", `data: ${JSON.stringify({ type: "response.created" })}\n\n`], 20),
+ { status: 200, headers: { "Content-Type": "text/event-stream" } }
+ );
+
+ const result = await ensureStreamReadiness(response, { timeoutMs: 10 });
+ assert.equal(result.ok, false);
+ assert.equal(result.response.status, 504);
+ assert.match(await result.response.text(), /STREAM_READINESS_TIMEOUT/);
+});
+
+test("ensureStreamReadiness returns 502 when stream ends without useful content", async () => {
+ const response = new Response(streamFromChunks([": keepalive\n\n"]), {
+ status: 200,
+ headers: { "Content-Type": "text/event-stream" },
+ });
+
+ const result = await ensureStreamReadiness(response, { timeoutMs: 100 });
+ assert.equal(result.ok, false);
+ assert.equal(result.response.status, 502);
+});