diff --git a/src/routes.ts b/src/routes.ts index 6f426f9..c805872 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -64,8 +64,8 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { let requestedModel = ''; const startTime = Date.now(); - // Listen for client disconnect/cancellation - req.on('close', () => { + // Listen for client disconnect/cancellation on response + res.on('close', () => { if (!isFinished && !res.writableEnded) { isCancelled = true; requestTracker.recordCancelled({ @@ -164,7 +164,7 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { const firstChunkTime = Date.now(); for await (const chunk of result.stream) { - if (isCancelled || req.destroyed || res.destroyed) { + if (isCancelled || res.destroyed) { isCancelled = true; break; } @@ -215,6 +215,7 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { res.write(`data: ${JSON.stringify(finalChunk)}\n\n`); res.write('data: [DONE]\n\n'); + isFinished = true; res.end(); const totalTime = Date.now() - startTime; @@ -269,10 +270,10 @@ router.post('/v1/chat/completions', async (req: Request, res: Response) => { // Generate non-streaming response const geminiStart = Date.now(); const result = await chat.sendMessage(lastMessage.parts[0].text); - if (isCancelled || req.destroyed) return; + if (isCancelled || res.destroyed) return; const response = await result.response; - if (isCancelled || req.destroyed) return; + if (isCancelled || res.destroyed) return; console.log('[TIMING] Gemini API call took:', Date.now() - geminiStart, 'ms');