From b8628cc0f1e34b9d7bc6e9c822b906b40f00322a Mon Sep 17 00:00:00 2001 From: tyuXX Date: Thu, 19 Nov 2026 18:23:28 +0000 Subject: [PATCH] fix timeouts --- .env.example | 3 + src/config.ts | 1 + src/revolverEngine.ts | 553 +++++++++++++++++++++----------------- test-timeout-keepalive.ts | 87 +++++- 4 files changed, 403 insertions(+), 241 deletions(-) diff --git a/.env.example b/.env.example index 6ceec9c..e906c7f 100644 --- a/.env.example +++ b/.env.example @@ -30,6 +30,9 @@ RATE_LIMIT_DURATION_MS=60000 # Streaming Time-To-First-Token (TTFT) timeout before failover (in ms, default 15s) # STREAM_FIRST_TOKEN_TIMEOUT_MS=15000 +# Streaming per-chunk idle timeout during active generation before aborting a stalled stream (in ms, default 120s) +# STREAM_IDLE_TIMEOUT_MS=120000 + # Model circuit breaker cooldown duration on 503 / high demand (in ms, default 60s) # MODEL_COOLDOWN_MS=60000 diff --git a/src/config.ts b/src/config.ts index e876b77..a8ab395 100644 --- a/src/config.ts +++ b/src/config.ts @@ -18,6 +18,7 @@ export const config = { candidateTimeoutMs: parseInt(process.env.CANDIDATE_TIMEOUT_MS || '20000', 10), // Model Overload & Fast-Failover Circuit Breaker settings streamFirstTokenTimeoutMs: parseInt(process.env.STREAM_FIRST_TOKEN_TIMEOUT_MS || '15000', 10), + streamIdleTimeoutMs: parseInt(process.env.STREAM_IDLE_TIMEOUT_MS || '120000', 10), modelCooldownDurationMs: parseInt(process.env.MODEL_COOLDOWN_MS || '60000', 10), maxTargetTimeoutRetries: parseInt(process.env.MAX_TARGET_TIMEOUT_RETRIES || '0', 10), maxTargetOverloadRetries: parseInt(process.env.MAX_TARGET_OVERLOAD_RETRIES || '1', 10), diff --git a/src/revolverEngine.ts b/src/revolverEngine.ts index abdfec4..b43711c 100644 --- a/src/revolverEngine.ts +++ b/src/revolverEngine.ts @@ -310,6 +310,39 @@ export class RevolverEngine { ); } + /** Creates a TimeoutError compatible with isTimeoutError() and Node fetch abort reasons. */ + private createTimeoutError(message: string): Error { + const timeoutErr = new Error(message); + timeoutErr.name = 'TimeoutError'; + return timeoutErr; + } + + /** Races an async operation against a timeout timer, cleaning up the timer on settlement. */ + private async raceWithTimeout( + operation: () => Promise, + timeoutMs: number, + timeoutMessage: string, + onTimeout?: (err: Error) => void + ): Promise { + let timer: NodeJS.Timeout | null = null; + const timeoutPromise = new Promise((_, reject) => { + timer = setTimeout(() => { + const err = this.createTimeoutError(timeoutMessage); + if (onTimeout) onTimeout(err); + reject(err); + }, timeoutMs); + }); + + try { + return await Promise.race([operation(), timeoutPromise]); + } finally { + if (timer) { + clearTimeout(timer); + timer = null; + } + } + } + public async executeChatCompletion(params: { requestBody: OpenAIChatRequest; requestId: string; @@ -674,21 +707,23 @@ export class RevolverEngine { const hasReachedOverloadLimit = isModelOverload && overloadAttempts >= maxOverloadAttempts; let tripResult = { tripped: false, cooldownSeconds: 0, reason: '' }; - if (allPairsOnCooldown) { - // When all pairs were on cooldown, emergency probe failed: put target and key back on cooldown immediately - modelCircuitBreaker.tripCooldown(candidate.provider.id, candidate.target.model, detailedErrorMessage); - this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { - rateLimitedUntil: Date.now() + config.rateLimitDurationMs, - incrementError: true - }); - } else if (isModelOverload || isTimeout) { - tripResult = modelCircuitBreaker.recordFailure( - candidate.provider.id, - candidate.target.model, - err, - isTimeout, - candidate.provider.keys.length - ); + if (!streamStarted) { + if (allPairsOnCooldown) { + // When all pairs were on cooldown, emergency probe failed: put target and key back on cooldown immediately + modelCircuitBreaker.tripCooldown(candidate.provider.id, candidate.target.model, detailedErrorMessage); + this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { + rateLimitedUntil: Date.now() + config.rateLimitDurationMs, + incrementError: true + }); + } else if (isModelOverload || isTimeout) { + tripResult = modelCircuitBreaker.recordFailure( + candidate.provider.id, + candidate.target.model, + err, + isTimeout, + candidate.provider.keys.length + ); + } } // On 503 high-demand/overload, only try 1 more key (up to maxOverloadAttempts = 2 keys total) before skipping remaining keys for this target. @@ -1193,7 +1228,7 @@ export class RevolverEngine { model: candidate.target.model, systemInstruction: systemInstruction || undefined, safetySettings: shouldDisableModeration ? GEMINI_SAFETY_SETTINGS_BLOCK_NONE : undefined - }, { timeout: config.candidateTimeoutMs }); + }); const lastMessage = geminiMessages[geminiMessages.length - 1]; if (!lastMessage || lastMessage.role !== 'user') { @@ -1209,9 +1244,15 @@ export class RevolverEngine { } }); - // Start streaming from Gemini - const result = await chat.sendMessageStream(lastMessage.parts[0].text); + const abortController = new AbortController(); + const onClientClose = () => { + if (!res.writableEnded) { + abortController.abort(); + } + }; + res.on('close', onClientClose); + let result: Awaited>; let fullContent = ''; let promptTokens = 0; let completionTokens = 0; @@ -1220,109 +1261,111 @@ export class RevolverEngine { : { mode: 'none' as const, filters: [] }; const collectedChunkTraces: FilterExecutionStepTrace[] = []; - const streamIterator = result.stream[Symbol.asyncIterator](); - - // TTFT Timeout: Wait for first chunk within streamFirstTokenTimeoutMs - let firstResult: IteratorResult; - let ttftTimer: NodeJS.Timeout | null = null; - const ttftPromise = new Promise((_, reject) => { - ttftTimer = setTimeout(() => { - const timeoutErr = new Error(`Streaming TTFT timeout: no tokens received within ${config.streamFirstTokenTimeoutMs}ms`); - (timeoutErr as any).name = 'TimeoutError'; - reject(timeoutErr); - }, config.streamFirstTokenTimeoutMs); - }); - try { - firstResult = await Promise.race([ - streamIterator.next(), - ttftPromise - ]); - } finally { - if (ttftTimer) { - clearTimeout(ttftTimer); - ttftTimer = null; - } - } + // Start streaming from Gemini with connection/headers timeout + result = await this.raceWithTimeout( + () => chat.sendMessageStream(lastMessage.parts[0].text, { signal: abortController.signal }), + config.candidateTimeoutMs, + 'The operation was aborted due to timeout', + (err) => abortController.abort(err) + ); - // If headers haven't been committed, commit them now - if (!res.headersSent) { - res.setHeader('Content-Type', 'text/event-stream; charset=utf-8'); - res.setHeader('Cache-Control', 'no-cache, no-transform'); - res.setHeader('Connection', 'keep-alive'); - res.setHeader('X-Accel-Buffering', 'no'); - if (typeof res.flushHeaders === 'function') { - res.flushHeaders(); - } - } + const streamIterator = result.stream[Symbol.asyncIterator](); - const handleGeminiChunk = (rawChunkText: string) => { - if (streamStrategy.mode === 'buffer_full') { - fullContent += rawChunkText; - return; + // TTFT Timeout: Wait for first chunk within streamFirstTokenTimeoutMs + const firstResult = await this.raceWithTimeout( + () => streamIterator.next(), + config.streamFirstTokenTimeoutMs, + `Streaming TTFT timeout: no tokens received within ${config.streamFirstTokenTimeoutMs}ms`, + (err) => abortController.abort(err) + ); + + // If headers haven't been committed, commit them now + if (!res.headersSent) { + res.setHeader('Content-Type', 'text/event-stream; charset=utf-8'); + res.setHeader('Cache-Control', 'no-cache, no-transform'); + res.setHeader('Connection', 'keep-alive'); + res.setHeader('X-Accel-Buffering', 'no'); + if (typeof res.flushHeaders === 'function') { + res.flushHeaders(); + } } - let emittedText = rawChunkText; - if (streamStrategy.mode === 'chunk_by_chunk' && customModel) { - const chunkRes = this.filterEngine.applyOutputFilters({ - text: rawChunkText, - customModel, - messages: requestBody.messages, - onlyChunkByChunk: true - }); - emittedText = chunkRes.text; - collectedChunkTraces.push(...chunkRes.traces); - } + const handleGeminiChunk = (rawChunkText: string) => { + if (streamStrategy.mode === 'buffer_full') { + fullContent += rawChunkText; + return; + } - fullContent += emittedText; - liveWatcher.appendStreamChunk(requestId, emittedText); - onStreamStart(); + let emittedText = rawChunkText; + if (streamStrategy.mode === 'chunk_by_chunk' && customModel) { + const chunkRes = this.filterEngine.applyOutputFilters({ + text: rawChunkText, + customModel, + messages: requestBody.messages, + onlyChunkByChunk: true + }); + emittedText = chunkRes.text; + collectedChunkTraces.push(...chunkRes.traces); + } - const chunkResponse = { - id: `chatcmpl-${requestId}`, - object: 'chat.completion.chunk', - created: Math.floor(Date.now() / 1000), - model: requestedModelName, - choices: [ - { - index: 0, - delta: { content: emittedText }, - finish_reason: null - } - ] + fullContent += emittedText; + liveWatcher.appendStreamChunk(requestId, emittedText); + onStreamStart(); + + const chunkResponse = { + id: `chatcmpl-${requestId}`, + object: 'chat.completion.chunk', + created: Math.floor(Date.now() / 1000), + model: requestedModelName, + choices: [ + { + index: 0, + delta: { content: emittedText }, + finish_reason: null + } + ] + }; + + res.write(`data: ${JSON.stringify(chunkResponse)}\n\n`); }; - res.write(`data: ${JSON.stringify(chunkResponse)}\n\n`); - }; - - if (!firstResult.done && firstResult.value) { - let text = ''; - try { - text = firstResult.value.text(); - } catch (err: any) { - if (err?.message?.includes('SAFETY') || err?.message?.includes('blocked')) { - throw new Error(`Gemini stream blocked by upstream safety policy: ${err.message}`); + if (!firstResult.done && firstResult.value) { + let text = ''; + try { + text = firstResult.value.text(); + } catch (err: any) { + if (err?.message?.includes('SAFETY') || err?.message?.includes('blocked')) { + throw new Error(`Gemini stream blocked by upstream safety policy: ${err.message}`); + } + throw err; } - throw err; + handleGeminiChunk(text); } - handleGeminiChunk(text); - } - while (true) { - if (res.destroyed) break; - const { done, value } = await streamIterator.next(); - if (done) break; + while (true) { + if (res.destroyed) break; + const { done, value } = await this.raceWithTimeout( + () => streamIterator.next(), + config.streamIdleTimeoutMs, + `Streaming idle timeout: no chunks received within ${config.streamIdleTimeoutMs}ms`, + (err) => abortController.abort(err) + ); + if (done) break; - let text = ''; - try { - text = value.text(); - } catch (err: any) { - if (err?.message?.includes('SAFETY') || err?.message?.includes('blocked')) { - throw new Error(`Gemini stream blocked by upstream safety policy: ${err.message}`); + let text = ''; + try { + text = value.text(); + } catch (err: any) { + if (err?.message?.includes('SAFETY') || err?.message?.includes('blocked')) { + throw new Error(`Gemini stream blocked by upstream safety policy: ${err.message}`); + } + throw err; } - throw err; + handleGeminiChunk(text); } - handleGeminiChunk(text); + } finally { + res.off('close', onClientClose); } if (streamStrategy.mode === 'buffer_full' && customModel) { @@ -1438,51 +1481,14 @@ export class RevolverEngine { stream: true }; - const response = await fetch(url, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${candidate.keyConfig.key}`, - 'Accept-Encoding': 'identity' - }, - body: JSON.stringify(forwardedBody), - signal: AbortSignal.timeout(config.candidateTimeoutMs) - }); - - if (!response.ok) { - let errBody = ''; - try { - errBody = await response.text(); - } catch (readErr: any) { - errBody = readErr.message || 'Failed to read error response'; + const abortController = new AbortController(); + const onClientClose = () => { + if (!res.writableEnded) { + abortController.abort(); } - let errorDetails = errBody; - try { - const parsed = JSON.parse(errBody); - errorDetails = parsed.error?.message || errBody; - } catch {} - const err = new Error(`Provider API error (${response.status}): ${errorDetails}`); - (err as any).status = response.status; - throw err; - } + }; + res.on('close', onClientClose); - if (!response.body) { - throw new Error('Response body is null from provider stream.'); - } - - // If headers haven't been committed, commit them now - if (!res.headersSent) { - res.setHeader('Content-Type', 'text/event-stream; charset=utf-8'); - res.setHeader('Cache-Control', 'no-cache, no-transform'); - res.setHeader('Connection', 'keep-alive'); - res.setHeader('X-Accel-Buffering', 'no'); - if (typeof res.flushHeaders === 'function') { - res.flushHeaders(); - } - } - - const reader = response.body.getReader(); - const decoder = new TextDecoder(); let buffer = ''; let totalOutputChars = 0; let fullContent = ''; @@ -1493,117 +1499,184 @@ export class RevolverEngine { : { mode: 'none' as const, filters: [] }; const collectedChunkTraces: FilterExecutionStepTrace[] = []; - const processText = (textChunk: string) => { - buffer += textChunk; - const lines = buffer.split('\n'); - buffer = lines.pop() || ''; + try { + let connectionTimer: NodeJS.Timeout | null = setTimeout(() => { + abortController.abort(this.createTimeoutError('The operation was aborted due to timeout')); + }, config.candidateTimeoutMs); - for (const line of lines) { - const trimmed = line.trim(); - if (!trimmed) { - if (streamStrategy.mode !== 'buffer_full') { - res.write('\n'); + let response: globalThis.Response; + try { + response = await fetch(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${candidate.keyConfig.key}`, + 'Accept-Encoding': 'identity' + }, + body: JSON.stringify(forwardedBody), + signal: abortController.signal + }); + + if (!response.ok) { + let errBody = ''; + try { + errBody = await response.text(); + } catch (readErr: any) { + errBody = readErr.message || 'Failed to read error response'; } - continue; + let errorDetails = errBody; + try { + const parsed = JSON.parse(errBody); + errorDetails = parsed.error?.message || errBody; + } catch {} + const err = new Error(`Provider API error (${response.status}): ${errorDetails}`); + (err as any).status = response.status; + throw err; } + } finally { + if (connectionTimer) { + clearTimeout(connectionTimer); + connectionTimer = null; + } + } - if (trimmed.startsWith('data: ')) { - const dataStr = trimmed.slice(6); - if (dataStr === '[DONE]') { + if (!response.body) { + throw new Error('Response body is null from provider stream.'); + } + + // If headers haven't been committed, commit them now + if (!res.headersSent) { + res.setHeader('Content-Type', 'text/event-stream; charset=utf-8'); + res.setHeader('Cache-Control', 'no-cache, no-transform'); + res.setHeader('Connection', 'keep-alive'); + res.setHeader('X-Accel-Buffering', 'no'); + if (typeof res.flushHeaders === 'function') { + res.flushHeaders(); + } + } + + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + + const processText = (textChunk: string) => { + buffer += textChunk; + const lines = buffer.split('\n'); + buffer = lines.pop() || ''; + + for (const line of lines) { + const trimmed = line.trim(); + if (!trimmed) { if (streamStrategy.mode !== 'buffer_full') { - res.write('data: [DONE]\n\n'); + res.write('\n'); } continue; } - try { - const parsed = JSON.parse(dataStr); - parsed.model = requestedModelName; - if (parsed.choices?.[0]?.finish_reason) { - finishReason = parsed.choices[0].finish_reason; - } - if (parsed.choices?.[0]?.delta?.content) { - const rawDelta = parsed.choices[0].delta.content; - if (streamStrategy.mode === 'buffer_full') { - fullContent += rawDelta; - totalOutputChars += rawDelta.length; - continue; + if (trimmed.startsWith('data: ')) { + const dataStr = trimmed.slice(6); + if (dataStr === '[DONE]') { + if (streamStrategy.mode !== 'buffer_full') { + res.write('data: [DONE]\n\n'); } + continue; + } - let emittedDelta = rawDelta; - if (streamStrategy.mode === 'chunk_by_chunk' && customModel) { - const chunkRes = this.filterEngine.applyOutputFilters({ - text: rawDelta, - customModel, - messages: requestBody.messages, - onlyChunkByChunk: true - }); - emittedDelta = chunkRes.text; - parsed.choices[0].delta.content = emittedDelta; - collectedChunkTraces.push(...chunkRes.traces); + try { + const parsed = JSON.parse(dataStr); + parsed.model = requestedModelName; + if (parsed.choices?.[0]?.finish_reason) { + finishReason = parsed.choices[0].finish_reason; } + const rawReasoning = parsed.choices?.[0]?.delta?.reasoning_content ?? parsed.choices?.[0]?.delta?.reasoning; + if (typeof rawReasoning === 'string' && rawReasoning.length > 0) { + totalOutputChars += rawReasoning.length; + if (streamStrategy.mode !== 'buffer_full') { + onStreamStart(); + streamHasStarted = true; + if (!parsed.choices?.[0]?.delta?.content) { + liveWatcher.appendStreamChunk(requestId, rawReasoning); + } + } + } + if (parsed.choices?.[0]?.delta?.content) { + const rawDelta = parsed.choices[0].delta.content; + if (streamStrategy.mode === 'buffer_full') { + fullContent += rawDelta; + totalOutputChars += rawDelta.length; + continue; + } - onStreamStart(); - streamHasStarted = true; - totalOutputChars += emittedDelta.length; - fullContent += emittedDelta; - liveWatcher.appendStreamChunk(requestId, emittedDelta); - } - if (streamStrategy.mode !== 'buffer_full') { - res.write(`data: ${JSON.stringify(parsed)}\n\n`); - } - } catch { - if (streamStrategy.mode !== 'buffer_full') { - res.write(`${line}\n`); + let emittedDelta = rawDelta; + if (streamStrategy.mode === 'chunk_by_chunk' && customModel) { + const chunkRes = this.filterEngine.applyOutputFilters({ + text: rawDelta, + customModel, + messages: requestBody.messages, + onlyChunkByChunk: true + }); + emittedDelta = chunkRes.text; + parsed.choices[0].delta.content = emittedDelta; + collectedChunkTraces.push(...chunkRes.traces); + } + + onStreamStart(); + streamHasStarted = true; + totalOutputChars += emittedDelta.length; + fullContent += emittedDelta; + liveWatcher.appendStreamChunk(requestId, emittedDelta); + } + if (streamStrategy.mode !== 'buffer_full') { + res.write(`data: ${JSON.stringify(parsed)}\n\n`); + } + } catch { + if (streamStrategy.mode !== 'buffer_full') { + res.write(`${line}\n`); + } } + } else if (streamStrategy.mode !== 'buffer_full') { + res.write(`${line}\n`); } - } else if (streamStrategy.mode !== 'buffer_full') { - res.write(`${line}\n`); } + }; + + const abortStreamRead = (err: Error) => { + reader.cancel(err).catch(() => {}); + abortController.abort(err); + }; + + // TTFT Timeout: Wait for first chunk within streamFirstTokenTimeoutMs + const firstReadResult = await this.raceWithTimeout( + () => reader.read(), + config.streamFirstTokenTimeoutMs, + `Streaming TTFT timeout: no tokens received within ${config.streamFirstTokenTimeoutMs}ms`, + abortStreamRead + ); + + if (!firstReadResult.done && firstReadResult.value) { + const text = decoder.decode(firstReadResult.value, { stream: true }); + processText(text); } - }; - // TTFT Timeout: Wait for first chunk within streamFirstTokenTimeoutMs - let ttftTimer: NodeJS.Timeout | null = null; - const ttftPromise = new Promise((_, reject) => { - ttftTimer = setTimeout(() => { - try { reader.cancel(); } catch {} - const timeoutErr = new Error(`Streaming TTFT timeout: no tokens received within ${config.streamFirstTokenTimeoutMs}ms`); - (timeoutErr as any).name = 'TimeoutError'; - reject(timeoutErr); - }, config.streamFirstTokenTimeoutMs); - }); + while (true) { + if (res.destroyed) break; + const { done, value } = await this.raceWithTimeout( + () => reader.read(), + config.streamIdleTimeoutMs, + `Streaming idle timeout: no chunks received within ${config.streamIdleTimeoutMs}ms`, + abortStreamRead + ); + if (done) break; - let firstReadResult: { done?: boolean; value?: Uint8Array }; - try { - firstReadResult = await Promise.race([ - reader.read(), - ttftPromise - ]); + const text = decoder.decode(value, { stream: true }); + processText(text); + } + + // Flush any remaining partial line in buffer + if (buffer.trim()) { + processText('\n'); + } } finally { - if (ttftTimer) { - clearTimeout(ttftTimer); - ttftTimer = null; - } - } - - if (!firstReadResult.done && firstReadResult.value) { - const text = decoder.decode(firstReadResult.value, { stream: true }); - processText(text); - } - - while (true) { - if (res.destroyed) break; - const { done, value } = await reader.read(); - if (done) break; - - const text = decoder.decode(value, { stream: true }); - processText(text); - } - - // Flush any remaining partial line in buffer - if (buffer.trim()) { - processText('\n'); + res.off('close', onClientClose); } if (streamStrategy.mode === 'buffer_full' && customModel) { diff --git a/test-timeout-keepalive.ts b/test-timeout-keepalive.ts index dd9ab3f..ece3680 100644 --- a/test-timeout-keepalive.ts +++ b/test-timeout-keepalive.ts @@ -14,13 +14,33 @@ async function runKeepAliveTests() { // 1. Create a mock upstream OpenAI-compatible server let mockStreamDelay = 250; let mockNonStreamDelay = 250; + let mockLongStreamMode = false; const mockUpstream = http.createServer((req, res) => { let body = ''; req.on('data', chunk => (body += chunk)); req.on('end', () => { const parsed = JSON.parse(body || '{}'); - if (parsed.stream) { + if (parsed.stream && mockLongStreamMode) { + setTimeout(() => { + res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache' + }); + res.write('data: {"choices":[{"delta":{"reasoning_content":"Thinking..."}}]}\n\n'); + + let count = 0; + const interval = setInterval(() => { + count++; + res.write(`data: {"choices":[{"delta":{"content":"Part ${count}"}}]}\n\n`); + if (count >= 5) { + clearInterval(interval); + res.write('data: [DONE]\n\n'); + res.end(); + } + }, 80); + }, 50); + } else if (parsed.stream) { setTimeout(() => { res.writeHead(200, { 'Content-Type': 'text/event-stream', @@ -186,6 +206,71 @@ async function runKeepAliveTests() { assert.strictEqual(fastData.choices[0].message.content, 'Mock non-streaming answer'); console.log(' ✓ Fast requests preserve standard non-chunked JSON responses.'); + // TEST 4: Long streaming generation exceeding candidateTimeoutMs succeeds + console.log('\n4. Testing Long Streaming Generation exceeding candidateTimeoutMs...'); + const origCandidateTimeoutMs = config.candidateTimeoutMs; + const origStreamFirstTokenTimeoutMs = config.streamFirstTokenTimeoutMs; + config.candidateTimeoutMs = 200; + config.streamFirstTokenTimeoutMs = 150; + mockLongStreamMode = true; + + try { + const longStart = Date.now(); + const longResp = await fetch(`${baseUrl}/v1/chat/completions`, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${validKey}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + model: 'test-keepalive-model', + stream: true, + messages: [{ role: 'user', content: 'Long high-token stream' }] + }) + }); + + assert.strictEqual(longResp.status, 200); + const longReader = longResp.body!.getReader(); + const longDecoder = new TextDecoder(); + let receivedReasoning = ''; + let receivedLongContent = ''; + let sawDone = false; + + while (true) { + const { done, value } = await longReader.read(); + if (done) break; + const text = longDecoder.decode(value, { stream: true }); + for (const line of text.split('\n')) { + const trimmed = line.trim(); + if (!trimmed.startsWith('data: ')) continue; + const payload = trimmed.slice(6); + if (payload === '[DONE]') { + sawDone = true; + continue; + } + const parsed = JSON.parse(payload); + assert.ok(!parsed.error, `Stream should not emit error: ${JSON.stringify(parsed.error)}`); + if (parsed.choices?.[0]?.delta?.reasoning_content) { + receivedReasoning += parsed.choices[0].delta.reasoning_content; + } + if (parsed.choices?.[0]?.delta?.content) { + receivedLongContent += parsed.choices[0].delta.content; + } + } + } + + const longDuration = Date.now() - longStart; + assert.ok(longDuration > config.candidateTimeoutMs, `Expected stream duration (${longDuration}ms) > candidateTimeoutMs (${config.candidateTimeoutMs}ms)`); + assert.strictEqual(receivedReasoning, 'Thinking...'); + assert.strictEqual(receivedLongContent, 'Part 1Part 2Part 3Part 4Part 5'); + assert.strictEqual(sawDone, true, 'Long stream should complete cleanly with [DONE]'); + console.log(` ✓ Long streaming generation (${longDuration}ms > ${config.candidateTimeoutMs}ms) completed with reasoning and all content chunks.`); + } finally { + mockLongStreamMode = false; + config.candidateTimeoutMs = origCandidateTimeoutMs; + config.streamFirstTokenTimeoutMs = origStreamFirstTokenTimeoutMs; + } + } finally { // Cleanup configStore.deleteCustomModel(testModel.id);