Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

fix(emulation): stop a failed Gemini/Ollama request from exiting the process (#1285)

tashdroid48153ead5f7a
diff --git a/server/src/__tests__/routes/emulation-handler-rejection.test.ts b/server/src/__tests__/routes/emulation-handler-rejection.test.ts
new file mode 100644
index 00000000..18b40d9e
--- /dev/null
+++ b/server/src/__tests__/routes/emulation-handler-rejection.test.ts
@@ -0,0 +1,111 @@
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { Express } from 'express';
+
+// Fails the first thing `runInboundChat` awaits, so the handler promise
+// rejects AFTER the synchronous part of the Express handler has returned —
+// exactly the shape Express can only see when the handler hands it the
+// promise. The flag keeps every other test on the real implementation.
+let failNormalize = false;
+vi.mock('../../lib/image-normalize.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../lib/image-normalize.js')>();
+ return {
+ ...actual,
+ normalizeMessageImages: async (...args: Parameters<typeof actual.normalizeMessageImages>) => {
+ if (failNormalize) throw new Error('boom from image normalization');
+ return actual.normalizeMessageImages(...args);
+ },
+ };
+});
+
+const { createApp } = await import('../../app.js');
+const { getDb, getUnifiedApiKey, initDb, setSetting } = await import('../../db/index.js');
+const { encrypt } = await import('../../lib/crypto.js');
+
+async function request(
+ app: Express,
+ path: string,
+ body: unknown,
+ headers: Record<string, string> = {},
+) {
+ const server = app.listen(0, '127.0.0.1');
+ if (!server.listening) await new Promise<void>(resolve => server.once('listening', () => resolve()));
+ const address = server.address() as { port: number };
+ try {
+ const response = await fetch(`http://127.0.0.1:${address.port}${path}`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...headers },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(5_000),
+ });
+ const text = await response.text();
+ let json: any;
+ try { json = JSON.parse(text); } catch { json = null; }
+ return { status: response.status, body: json };
+ } finally {
+ server.close();
+ }
+}
+
+// A handler that voids its promise never answers and never reaches
+// errorHandler: the request hangs until the client gives up, and the
+// rejection escapes to `unhandledRejection`, which lib/process-safety-net.ts
+// treats as fatal for non-transport errors. Both surfaces must answer 500.
+describe('emulation surfaces forward handler rejections to the error handler', () => {
+ let app: Express;
+
+ beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ app = createApp();
+ });
+
+ beforeEach(() => {
+ getDb().prepare('DELETE FROM api_keys').run();
+ const key = encrypt('gsk_handler_rejection_test');
+ getDb().prepare(`
+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)
+ VALUES ('groq', 'rejection-test', ?, ?, ?, 'healthy', 1)
+ `).run(key.encrypted, key.iv, key.authTag);
+ failNormalize = true;
+ });
+
+ afterEach(() => {
+ failNormalize = false;
+ setSetting('ollama_emulation', 'off');
+ vi.restoreAllMocks();
+ });
+
+ it('answers 500 on the Gemini generateContent surface', async () => {
+ const response = await request(
+ app,
+ `/v1beta/models/gemini-2.5-flash:generateContent?key=${getUnifiedApiKey()}`,
+ { contents: [{ role: 'user', parts: [{ text: 'hello' }] }] },
+ );
+ expect(response.status).toBe(500);
+ expect(response.body?.error).toBeTruthy();
+ });
+
+ it('answers 500 on the Ollama chat surface', async () => {
+ setSetting('ollama_emulation', 'key-required');
+ const response = await request(
+ app,
+ '/api/chat',
+ { model: 'auto', messages: [{ role: 'user', content: 'hello' }], stream: false },
+ { Authorization: `Bearer ${getUnifiedApiKey()}` },
+ );
+ expect(response.status).toBe(500);
+ expect(response.body?.error).toBeTruthy();
+ });
+
+ it('answers 500 on the Ollama generate surface', async () => {
+ setSetting('ollama_emulation', 'key-required');
+ const response = await request(
+ app,
+ '/api/generate',
+ { model: 'auto', prompt: 'hello', stream: false },
+ { Authorization: `Bearer ${getUnifiedApiKey()}` },
+ );
+ expect(response.status).toBe(500);
+ expect(response.body?.error).toBeTruthy();
+ });
+});
diff --git a/server/src/routes/gemini.ts b/server/src/routes/gemini.ts
index 2c26a269..4b9414ce 100644
--- a/server/src/routes/gemini.ts
+++ b/server/src/routes/gemini.ts
@@ -217,13 +217,16 @@ async function handleGenerate(req: Request, res: Response, stream: boolean): Pro
}, streamWire(String(req.query.alt ?? '').toLowerCase() === 'sse'));
}
-geminiRouter.post(/^\/models\/(.+):generateContent$/, (req, res) => {
- void handleGenerate(req, res, false);
-});
+// The handler promise is RETURNED, not voided, so Express 5 forwards a
+// rejection to errorHandler like it already does for the OpenAI (/v1) and
+// Anthropic (/v1/messages) surfaces, whose handlers are `async` and so hand
+// Express their promise. A voided promise escapes the router entirely and
+// resurfaces as an `unhandledRejection`, which the process safety net
+// classifies as fatal for anything that is not a transport error — so one
+// failing request exited the whole gateway instead of answering 500.
+geminiRouter.post(/^\/models\/(.+):generateContent$/, (req, res) => handleGenerate(req, res, false));
-geminiRouter.post(/^\/models\/(.+):streamGenerateContent$/, (req, res) => {
- void handleGenerate(req, res, true);
-});
+geminiRouter.post(/^\/models\/(.+):streamGenerateContent$/, (req, res) => handleGenerate(req, res, true));
geminiRouter.post(/^\/models\/(.+):countTokens$/, (req, res) => {
if (!authenticate(req, res)) return;
diff --git a/server/src/routes/ollama.ts b/server/src/routes/ollama.ts
index 71c0722e..32791637 100644
--- a/server/src/routes/ollama.ts
+++ b/server/src/routes/ollama.ts
@@ -378,6 +378,12 @@ function ollamaWire(model: string): InboundChatWire {
};
}
+// Every handler below RETURNS its promise rather than voiding it, so Express
+// 5 forwards a rejection to errorHandler — the same treatment the OpenAI and
+// Anthropic surfaces get from their `async` handlers. A voided promise leaves
+// the router and resurfaces as an `unhandledRejection`, which the process
+// safety net classifies as fatal for anything that is not a transport error,
+// so one failing request exited the whole gateway instead of answering 500.
ollamaRouter.post('/api/chat', (req, res) => {
if (!authorize(req, res)) return;
const parsed = chatSchema.safeParse(req.body);
@@ -403,7 +409,7 @@ ollamaRouter.post('/api/chat', (req, res) => {
const options = body.options as Record<string, unknown> | undefined;
const rawSession = req.headers['x-ollama-session-id'] ?? req.headers['x-session-id'];
const sessionId = Array.isArray(rawSession) ? rawSession[0] : rawSession;
- void runInboundChat(req, res, {
+ return runInboundChat(req, res, {
model,
messages: ollamaMessages(body.messages),
stream: body.stream !== false,
@@ -523,7 +529,7 @@ ollamaRouter.post('/api/generate', (req, res) => {
? `${body.prompt}\n\nComplete the text before this suffix:\n${body.suffix}`
: body.prompt,
});
- void runInboundChat(req, res, {
+ return runInboundChat(req, res, {
model,
messages,
stream: body.stream !== false,
@@ -587,7 +593,7 @@ async function handleEmbed(req: Request, res: Response, legacy: boolean): Promis
}
ollamaRouter.post('/api/embed', (req, res) => {
- void handleEmbed(req, res, false);
+ return handleEmbed(req, res, false);
});
// The dashboard already owns POST /api/embeddings. A valid dashboard session
@@ -607,5 +613,5 @@ ollamaRouter.post('/api/embeddings', (req: Request, res: Response, next: NextFun
res.status(401).json({ error: { message: 'Authentication required', type: 'authentication_error' } });
return;
}
- void handleEmbed(req, res, true);
+ return handleEmbed(req, res, true);
});