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
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
test: add unit test coverage for proxy settings, embedding routes, and error handling branches
diegosouzapwa24854a3cc6f
diff --git a/tests/integration/api-keys.test.mjs b/tests/integration/api-keys.test.mjsindex b58ed4faab..960c310e83 100644--- a/tests/integration/api-keys.test.mjs+++ b/tests/integration/api-keys.test.mjs@@ -222,6 +222,28 @@ test("GET /api/keys falls back to default pagination for invalid query params",assert.equal(body.keys[0].name, "management");});+test("GET /api/keys treats non-numeric pagination params as defaults", async () => {+ await enableManagementAuth();+ const authKey = await createManagementKey();+ await apiKeysDb.createApiKey("Alpha", MACHINE_ID);+ await apiKeysDb.createApiKey("Beta", MACHINE_ID);++ const response = await listRoute.GET(+ makeRequest("http://localhost/api/keys?limit=abc&offset=xyz", {+ token: authKey.key,+ })+ );+ const body = await response.json();++ assert.equal(response.status, 200);+ assert.equal(body.total, 3);+ assert.equal(body.keys.length, 3);+ assert.deepEqual(+ body.keys.map((entry) => entry.name),+ ["management", "Alpha", "Beta"]+ );+});+test("GET /api/keys uses default pagination when query params are absent and reports reveal support", async () => {await enableManagementAuth();process.env.ALLOW_API_KEY_REVEAL = "true";@@ -280,6 +302,39 @@ test("POST /api/keys triggers cloud sync when cloud mode is enabled", async () =}});+test("GET /api/keys returns 500 when the key store throws unexpectedly", async () => {+ await apiKeysDb.createApiKey("Alpha", MACHINE_ID);++ const db = core.getDbInstance();+ const originalPrepare = db.prepare.bind(db);+ const originalLog = console.log;+ const logs = [];++ db.prepare = (sql) => {+ if (String(sql).includes("FROM api_keys")) {+ throw new Error("api keys offline");+ }+ return originalPrepare(sql);+ };+ apiKeysDb.resetApiKeyState();+ console.log = (...args) => {+ logs.push(args.map((arg) => String(arg)).join(" "));+ };++ try {+ const response = await listRoute.GET(new Request("http://localhost/api/keys"));+ const body = await response.json();++ assert.equal(response.status, 500);+ assert.equal(body.error, "Failed to fetch keys");+ assert.ok(logs.some((entry) => entry.includes("Error fetching keys:")));+ } finally {+ db.prepare = originalPrepare;+ apiKeysDb.resetApiKeyState();+ console.log = originalLog;+ }+});+test("POST /api/keys still succeeds when cloud sync fails after creation", async () => {await enableManagementAuth();await localDb.updateSettings({ cloudEnabled: true });diff --git a/tests/unit/api-key-reveal-route.test.mjs b/tests/unit/api-key-reveal-route.test.mjsindex d3a1aefb78..0095995dda 100644--- a/tests/unit/api-key-reveal-route.test.mjs+++ b/tests/unit/api-key-reveal-route.test.mjs@@ -17,6 +17,7 @@ const MACHINE_ID = "1234567890abcdef";async function resetStorage() {delete process.env.ALLOW_API_KEY_REVEAL;+ delete process.env.INITIAL_PASSWORD;core.resetDbInstance();apiKeysDb.resetApiKeyState();fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });@@ -51,6 +52,61 @@ test("GET /api/keys stays masked even when reveal is enabled", async () => {assert.equal(body.keys[0].key, maskKey(created.key));});+test("GET /api/keys falls back to default pagination for invalid query params", async () => {+ await apiKeysDb.createApiKey("Alpha", MACHINE_ID);+ await apiKeysDb.createApiKey("Beta", MACHINE_ID);++ const response = await listRoute.GET(+ new Request("http://localhost/api/keys?limit=abc&offset=xyz")+ );+ const body = await response.json();++ assert.equal(response.status, 200);+ assert.equal(body.allowKeyReveal, false);+ assert.equal(body.total, 2);+ assert.equal(body.keys.length, 2);+ assert.equal(+ body.keys.every((entry) => entry.key.includes("****")),+ true+ );+});++test("GET /api/keys returns 500 when key loading fails unexpectedly", async () => {+ await apiKeysDb.createApiKey("Primary Key", MACHINE_ID);++ const db = core.getDbInstance();+ const originalPrepare = db.prepare.bind(db);+ const originalConsoleLog = console.log;+ const capturedLogs = [];++ db.prepare = (sql, ...args) => {+ if (typeof sql === "string" && sql.includes("SELECT * FROM api_keys")) {+ throw new Error("db exploded");+ }+ return originalPrepare(sql, ...args);+ };+ console.log = (...args) => {+ capturedLogs.push(args.map((arg) => String(arg)).join(" "));+ };+ apiKeysDb.resetApiKeyState();++ try {+ const response = await listRoute.GET(new Request("http://localhost/api/keys"));+ const body = await response.json();++ assert.equal(response.status, 500);+ assert.equal(body.error, "Failed to fetch keys");+ assert.equal(+ capturedLogs.some((line) => line.includes("Error fetching keys:")),+ true+ );+ } finally {+ db.prepare = originalPrepare;+ console.log = originalConsoleLog;+ apiKeysDb.resetApiKeyState();+ }+});+test("GET /api/keys/[id]/reveal rejects requests when reveal is disabled", async () => {const created = await apiKeysDb.createApiKey("Primary Key", MACHINE_ID);const request = new Request(`http://localhost/api/keys/${created.id}/reveal`);@@ -77,3 +133,29 @@ test("GET /api/keys/[id]/reveal returns the full key when reveal is enabled", asassert.equal(response.status, 200);assert.equal(body.key, created.key);});++test("GET /api/keys/[id]/reveal returns 404 for unknown keys even when reveal is enabled", async () => {+ process.env.ALLOW_API_KEY_REVEAL = "true";+ const request = new Request("http://localhost/api/keys/missing/reveal");++ const response = await revealRoute.GET(request, {+ params: Promise.resolve({ id: "missing" }),+ });+ const body = await response.json();++ assert.equal(response.status, 404);+ assert.equal(body.error, "Key not found");+});++test("GET /api/keys/[id]/reveal returns 500 when params resolution fails", async () => {+ process.env.ALLOW_API_KEY_REVEAL = "true";+ const request = new Request("http://localhost/api/keys/broken/reveal");++ const response = await revealRoute.GET(request, {+ params: Promise.reject(new Error("params exploded")),+ });+ const body = await response.json();++ assert.equal(response.status, 500);+ assert.equal(body.error, "Failed to reveal key");+});diff --git a/tests/unit/call-log-cap.test.mjs b/tests/unit/call-log-cap.test.mjsindex d9b50b77c8..7cb8f2568a 100644--- a/tests/unit/call-log-cap.test.mjs+++ b/tests/unit/call-log-cap.test.mjs@@ -10,6 +10,7 @@ process.env.CALL_LOG_RETENTION_DAYS = "1";const core = await import("../../src/lib/db/core.ts");const callLogs = await import("../../src/lib/usage/callLogs.ts");+const detailedLogs = await import("../../src/lib/db/detailedLogs.ts");async function resetStorage() {core.resetDbInstance();@@ -91,3 +92,380 @@ test("call log artifact rotation removes directories older than CALL_LOG_RETENTIassert.equal(fs.existsSync(oldDir), false);assert.equal(fs.existsSync(freshDir), true);});++test("getCallLogs applies provider, account, apiKey, combo, and search filters together", async () => {+ const db = core.getDbInstance();+ const insert = db.prepare(`+ INSERT INTO call_logs (+ id, timestamp, method, path, status, model, requested_model, provider, account,+ connection_id, duration, tokens_in, tokens_out, source_format, target_format,+ api_key_id, api_key_name, combo_name, request_body, response_body, error,+ artifact_relpath, has_pipeline_details+ )+ VALUES (+ @id, @timestamp, @method, @path, @status, @model, @requested_model, @provider, @account,+ @connection_id, @duration, @tokens_in, @tokens_out, @source_format, @target_format,+ @api_key_id, @api_key_name, @combo_name, @request_body, @response_body, @error,+ @artifact_relpath, @has_pipeline_details+ )+ `);++ insert.run({+ id: "filter-hit",+ timestamp: "2026-03-30T12:34:56",+ method: "POST",+ path: "/v1/chat/completions",+ status: 200,+ model: "openai/gpt-4.1",+ requested_model: "openai/gpt-5",+ provider: "openai",+ account: "Primary Account",+ connection_id: "conn-1",+ duration: 42,+ tokens_in: 11,+ tokens_out: 7,+ source_format: "openai",+ target_format: "openai",+ api_key_id: "key-1",+ api_key_name: "Primary Key",+ combo_name: "combo-a",+ request_body: JSON.stringify({ ok: true }),+ response_body: JSON.stringify({ ok: true }),+ error: null,+ artifact_relpath: null,+ has_pipeline_details: 0,+ });+ insert.run({+ id: "filter-miss",+ timestamp: "2026-03-30T12:35:56.000Z",+ method: "POST",+ path: "/v1/embeddings",+ status: 500,+ model: "gemini/text-embedding",+ requested_model: null,+ provider: "gemini",+ account: "Backup Account",+ connection_id: "conn-2",+ duration: 9,+ tokens_in: 3,+ tokens_out: 1,+ source_format: "openai",+ target_format: "gemini",+ api_key_id: "key-2",+ api_key_name: "Backup Key",+ combo_name: null,+ request_body: null,+ response_body: null,+ error: "upstream failed",+ artifact_relpath: null,+ has_pipeline_details: 0,+ });++ const providerFiltered = await callLogs.getCallLogs({ provider: "openai" });+ assert.deepEqual(+ providerFiltered.map((row) => row.id),+ ["filter-hit"]+ );++ const accountFiltered = await callLogs.getCallLogs({ account: "primary" });+ assert.deepEqual(+ accountFiltered.map((row) => row.id),+ ["filter-hit"]+ );++ const apiKeyFiltered = await callLogs.getCallLogs({ apiKey: "Primary" });+ assert.deepEqual(+ apiKeyFiltered.map((row) => row.id),+ ["filter-hit"]+ );++ const comboFiltered = await callLogs.getCallLogs({ combo: true });+ assert.deepEqual(+ comboFiltered.map((row) => row.id),+ ["filter-hit"]+ );++ const searchFiltered = await callLogs.getCallLogs({ search: "gpt-5" });+ assert.deepEqual(+ searchFiltered.map((row) => row.id),+ ["filter-hit"]+ );+});++test("getCallLogs applies status filters for error, ok, and explicit status codes", async () => {+ const db = core.getDbInstance();+ const insert = db.prepare(`+ INSERT INTO call_logs (+ id, timestamp, method, path, status, model, requested_model, provider, account,+ connection_id, duration, tokens_in, tokens_out, source_format, target_format,+ api_key_id, api_key_name, combo_name, request_body, response_body, error,+ artifact_relpath, has_pipeline_details+ )+ VALUES (+ @id, @timestamp, @method, @path, @status, @model, @requested_model, @provider, @account,+ @connection_id, @duration, @tokens_in, @tokens_out, @source_format, @target_format,+ @api_key_id, @api_key_name, @combo_name, @request_body, @response_body, @error,+ @artifact_relpath, @has_pipeline_details+ )+ `);++ insert.run({+ id: "status-ok",+ timestamp: "2026-03-30T12:34:56",+ method: "POST",+ path: "/v1/chat/completions",+ status: 201,+ model: "openai/gpt-4.1",+ requested_model: null,+ provider: "openai",+ account: "Primary Account",+ connection_id: "conn-1",+ duration: 12,+ tokens_in: 1,+ tokens_out: 2,+ source_format: "openai",+ target_format: "openai",+ api_key_id: null,+ api_key_name: null,+ combo_name: null,+ request_body: null,+ response_body: null,+ error: null,+ artifact_relpath: null,+ has_pipeline_details: 0,+ });+ insert.run({+ id: "status-error",+ timestamp: "2026-03-30T12:35:56",+ method: "POST",+ path: "/v1/chat/completions",+ status: 500,+ model: "openai/gpt-4.1",+ requested_model: null,+ provider: "openai",+ account: "Primary Account",+ connection_id: "conn-2",+ duration: 13,+ tokens_in: 1,+ tokens_out: 2,+ source_format: "openai",+ target_format: "openai",+ api_key_id: null,+ api_key_name: null,+ combo_name: null,+ request_body: null,+ response_body: null,+ error: null,+ artifact_relpath: null,+ has_pipeline_details: 0,+ });+ insert.run({+ id: "status-error-by-message",+ timestamp: "2026-03-30T12:36:56",+ method: "POST",+ path: "/v1/chat/completions",+ status: 200,+ model: "openai/gpt-4.1",+ requested_model: null,+ provider: "openai",+ account: "Primary Account",+ connection_id: "conn-3",+ duration: 14,+ tokens_in: 1,+ tokens_out: 2,+ source_format: "openai",+ target_format: "openai",+ api_key_id: null,+ api_key_name: null,+ combo_name: null,+ request_body: null,+ response_body: null,+ error: "synthetic failure",+ artifact_relpath: null,+ has_pipeline_details: 0,+ });++ const errorFiltered = await callLogs.getCallLogs({ status: "error" });+ assert.deepEqual(+ errorFiltered.map((row) => row.id),+ ["status-error-by-message", "status-error"]+ );++ const okFiltered = await callLogs.getCallLogs({ status: "ok" });+ assert.deepEqual(+ okFiltered.map((row) => row.id),+ ["status-error-by-message", "status-ok"]+ );++ const numericFiltered = await callLogs.getCallLogs({ status: "500" });+ assert.deepEqual(+ numericFiltered.map((row) => row.id),+ ["status-error"]+ );++ const invalidNumericFiltered = await callLogs.getCallLogs({ status: "not-a-number" });+ assert.deepEqual(+ invalidNumericFiltered.map((row) => row.id),+ ["status-error-by-message", "status-error", "status-ok"]+ );+});++test("getCallLogById falls back to legacy disk payloads and request_detail_logs when artifacts are absent", async () => {+ const db = core.getDbInstance();+ db.prepare(+ `+ INSERT INTO call_logs (+ id, timestamp, method, path, status, model, requested_model, provider, account,+ connection_id, duration, tokens_in, tokens_out, source_format, target_format,+ api_key_id, api_key_name, combo_name, request_body, response_body, error,+ artifact_relpath, has_pipeline_details+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ `+ ).run(+ "legacy-read",+ "2026-03-30T12:34:56",+ "POST",+ "/v1/chat/completions",+ 200,+ "openai/gpt-4.1",+ null,+ "openai",+ "Primary Account",+ "conn-1",+ 42,+ 11,+ 7,+ "openai",+ "openai",+ null,+ null,+ null,+ JSON.stringify({ _truncated: true }),+ JSON.stringify({ _truncated: true }),+ "db-error",+ null,+ 0+ );++ const legacyDir = path.join(TEST_DATA_DIR, "call_logs", "2026-03-30");+ fs.mkdirSync(legacyDir, { recursive: true });+ fs.writeFileSync(+ path.join(legacyDir, "123456_alt_200.json"),+ JSON.stringify(+ {+ requestBody: { recovered: "request" },+ responseBody: { recovered: "response" },+ error: "legacy-error",+ },+ null,+ 2+ )+ );++ detailedLogs.saveRequestDetailLog({+ call_log_id: "legacy-read",+ client_request: { body: { from: "detail-client" } },+ translated_request: { body: { from: "detail-provider-request" } },+ provider_response: { body: { from: "detail-provider-response" } },+ client_response: { body: { from: "detail-client-response" } },+ });++ const detail = await callLogs.getCallLogById("legacy-read");++ assert.deepEqual(detail?.requestBody, { recovered: "request" });+ assert.deepEqual(detail?.responseBody, { recovered: "response" });+ assert.equal(detail?.error, "legacy-error");+ assert.equal(detail?.pipelinePayloads?.clientRequest?.body?.from, "detail-client");+ assert.equal(detail?.pipelinePayloads?.providerRequest?.body?.from, "detail-provider-request");+ assert.equal(detail?.pipelinePayloads?.providerResponse?.body?.from, "detail-provider-response");+ assert.equal(detail?.pipelinePayloads?.clientResponse?.body?.from, "detail-client-response");+ assert.equal(detail?.hasPipelineDetails, true);+});++test("getCallLogById returns legacy pipeline details even when no legacy disk artifact exists", async () => {+ const db = core.getDbInstance();+ db.prepare(+ `+ INSERT INTO call_logs (+ id, timestamp, method, path, status, model, requested_model, provider, account,+ connection_id, duration, tokens_in, tokens_out, source_format, target_format,+ api_key_id, api_key_name, combo_name, request_body, response_body, error,+ artifact_relpath, has_pipeline_details+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ `+ ).run(+ "legacy-pipeline-only",+ "2026-03-30T12:34:57",+ "POST",+ "/v1/chat/completions",+ 200,+ "openai/gpt-4.1",+ null,+ "openai",+ "Primary Account",+ "conn-1",+ 1,+ 1,+ 1,+ "openai",+ "openai",+ null,+ null,+ null,+ JSON.stringify({ stored: "request" }),+ JSON.stringify({ stored: "response" }),+ null,+ null,+ 0+ );++ detailedLogs.saveRequestDetailLog({+ call_log_id: "legacy-pipeline-only",+ client_request: { fallback: "pipeline-only" },+ });++ const detail = await callLogs.getCallLogById("legacy-pipeline-only");++ assert.deepEqual(detail?.requestBody, { stored: "request" });+ assert.deepEqual(detail?.responseBody, { stored: "response" });+ assert.deepEqual(detail?.pipelinePayloads?.clientRequest, { fallback: "pipeline-only" });+ assert.equal(detail?.hasPipelineDetails, true);+});++test("saveCallLog logs and returns when sqlite persistence throws unexpectedly", async () => {+ const db = core.getDbInstance();+ const originalPrepare = db.prepare;+ const originalConsoleError = console.error;+ const consoleCalls = [];++ db.prepare = () => {+ throw new Error("simulated sqlite prepare failure");+ };+ console.error = (...args) => {+ consoleCalls.push(args.join(" "));+ };++ try {+ await assert.doesNotReject(() =>+ callLogs.saveCallLog({+ id: "prepare-failure",+ timestamp: "2026-03-30T12:40:00Z",+ method: "POST",+ path: "/v1/chat/completions",+ status: 200,+ model: "openai/gpt-4.1",+ provider: "openai",+ duration: 1,+ })+ );+ } finally {+ db.prepare = originalPrepare;+ console.error = originalConsoleError;+ }++ assert.equal(consoleCalls.length, 1);+ assert.match(consoleCalls[0], /Failed to save call log/);+ assert.match(consoleCalls[0], /simulated sqlite prepare failure/);+});diff --git a/tests/unit/call-log-file-rotation.test.mjs b/tests/unit/call-log-file-rotation.test.mjsindex 22e457b043..56f20ee32b 100644--- a/tests/unit/call-log-file-rotation.test.mjs+++ b/tests/unit/call-log-file-rotation.test.mjs@@ -13,7 +13,8 @@ process.env.DATA_DIR = TEST_DATA_DIR;process.env.CALL_LOG_RETENTION_DAYS = "7";process.env.CALL_LOG_MAX_ENTRIES = "2";-const { rotateCallLogs } = await import("../../src/lib/usage/callLogs.ts");+const { rotateCallLogs, cleanupOverflowCallLogFiles } =+ await import("../../src/lib/usage/callLogs.ts");const { CALL_LOGS_DIR } = await import("../../src/lib/usage/migrations.ts");test.after(() => {@@ -72,3 +73,122 @@ test("call log file rotation honors both retention days and file count", () => {assert.equal(fs.existsSync(keepB), true);assert.equal(fs.existsSync(keepC), true);});++test("rotateCallLogs swallows filesystem errors during cleanup", () => {+ assert.ok(CALL_LOGS_DIR, "CALL_LOGS_DIR should resolve for test data dir");+ fs.mkdirSync(CALL_LOGS_DIR, { recursive: true });++ const originalReaddirSync = fs.readdirSync;+ const originalConsoleError = console.error;+ const consoleCalls = [];++ fs.readdirSync = () => {+ throw new Error("simulated readdir failure");+ };+ console.error = (...args) => {+ consoleCalls.push(args.join(" "));+ };++ try {+ assert.doesNotThrow(() => rotateCallLogs());+ } finally {+ fs.readdirSync = originalReaddirSync;+ console.error = originalConsoleError;+ }++ assert.equal(consoleCalls.length, 1);+ assert.match(consoleCalls[0], /Failed to rotate request artifacts/);+ assert.match(consoleCalls[0], /simulated readdir failure/);+});++test("cleanupOverflowCallLogFiles logs and returns when directory scanning fails", () => {+ assert.ok(CALL_LOGS_DIR, "CALL_LOGS_DIR should resolve for test data dir");+ fs.mkdirSync(CALL_LOGS_DIR, { recursive: true });++ const originalReaddirSync = fs.readdirSync;+ const originalConsoleError = console.error;+ const consoleCalls = [];++ fs.readdirSync = (targetPath, ...args) => {+ if (targetPath === CALL_LOGS_DIR) {+ throw new Error("simulated overflow scan failure");+ }+ return originalReaddirSync.call(fs, targetPath, ...args);+ };+ console.error = (...args) => {+ consoleCalls.push(args.join(" "));+ };++ try {+ assert.doesNotThrow(() => cleanupOverflowCallLogFiles(CALL_LOGS_DIR, 2));+ } finally {+ fs.readdirSync = originalReaddirSync;+ console.error = originalConsoleError;+ }++ assert.equal(consoleCalls.length, 1);+ assert.match(consoleCalls[0], /Failed to prune overflow request artifacts/);+ assert.match(consoleCalls[0], /simulated overflow scan failure/);+});++test("cleanupOverflowCallLogFiles ignores directory entries that fail nested inspection", () => {+ assert.ok(CALL_LOGS_DIR, "CALL_LOGS_DIR should resolve for test data dir");+ fs.rmSync(CALL_LOGS_DIR, { recursive: true, force: true });+ fs.mkdirSync(CALL_LOGS_DIR, { recursive: true });++ const nestedDir = path.join(CALL_LOGS_DIR, "2026-04-01");+ fs.mkdirSync(nestedDir, { recursive: true });+ fs.writeFileSync(path.join(nestedDir, "100000_keep.json"), "{}");++ const originalReaddirSync = fs.readdirSync;+ fs.readdirSync = (targetPath, ...args) => {+ if (targetPath === nestedDir) {+ throw new Error("simulated nested scan failure");+ }+ return originalReaddirSync.call(fs, targetPath, ...args);+ };++ try {+ assert.doesNotThrow(() => cleanupOverflowCallLogFiles(CALL_LOGS_DIR, 1));+ } finally {+ fs.readdirSync = originalReaddirSync;+ }++ assert.equal(fs.existsSync(nestedDir), true);+ assert.equal(fs.existsSync(path.join(nestedDir, "100000_keep.json")), true);+});++test("cleanupOverflowCallLogFiles ignores rmSync failures for old artifacts", () => {+ assert.ok(CALL_LOGS_DIR, "CALL_LOGS_DIR should resolve for test data dir");+ fs.rmSync(CALL_LOGS_DIR, { recursive: true, force: true });+ fs.mkdirSync(CALL_LOGS_DIR, { recursive: true });++ const dayDir = path.join(CALL_LOGS_DIR, "2026-04-02");+ fs.mkdirSync(dayDir, { recursive: true });++ const newerFile = path.join(dayDir, "110000_keep.json");+ const olderFile = path.join(dayDir, "100000_remove.json");+ fs.writeFileSync(newerFile, "{}");+ fs.writeFileSync(olderFile, "{}");++ const now = Date.now();+ fs.utimesSync(newerFile, new Date(now), new Date(now));+ fs.utimesSync(olderFile, new Date(now - 5_000), new Date(now - 5_000));++ const originalRmSync = fs.rmSync;+ fs.rmSync = (targetPath, options) => {+ if (targetPath === olderFile) {+ throw new Error("simulated rm failure");+ }+ return originalRmSync.call(fs, targetPath, options);+ };++ try {+ assert.doesNotThrow(() => cleanupOverflowCallLogFiles(CALL_LOGS_DIR, 1));+ } finally {+ fs.rmSync = originalRmSync;+ }++ assert.equal(fs.existsSync(newerFile), true);+ assert.equal(fs.existsSync(olderFile), true);+});diff --git a/tests/unit/call-log-startup.test.mjs b/tests/unit/call-log-startup.test.mjsnew file mode 100644index 0000000000..f47c636adb--- /dev/null+++ b/tests/unit/call-log-startup.test.mjs@@ -0,0 +1,47 @@+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-call-log-startup-"));+const ORIGINAL_DATA_DIR = process.env.DATA_DIR;++test.after(() => {+ if (ORIGINAL_DATA_DIR === undefined) {+ delete process.env.DATA_DIR;+ } else {+ process.env.DATA_DIR = ORIGINAL_DATA_DIR;+ }++ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+});++test("callLogs startup cleanup swallows unexpected rotateCallLogs bootstrap failures", async () => {+ process.env.DATA_DIR = TEST_DATA_DIR;+ const expectedCallLogsDir = path.resolve(TEST_DATA_DIR, "call_logs");++ const originalExistsSync = fs.existsSync;+ const originalConsoleError = console.error;+ const consoleCalls = [];++ fs.existsSync = (targetPath, ...args) => {+ if (path.resolve(String(targetPath)) === expectedCallLogsDir) {+ throw new Error("simulated startup exists failure");+ }+ return originalExistsSync.call(fs, targetPath, ...args);+ };+ console.error = (...args) => {+ consoleCalls.push(args.join(" "));+ };++ try {+ const moduleUrl = new URL("../../src/lib/usage/callLogs.ts?startup-catch", import.meta.url);+ await assert.doesNotReject(() => import(moduleUrl.href));+ } finally {+ fs.existsSync = originalExistsSync;+ console.error = originalConsoleError;+ }++ assert.ok(consoleCalls.every((line) => typeof line === "string"));+});diff --git a/tests/unit/cc-compatible-provider.test.mjs b/tests/unit/cc-compatible-provider.test.mjsindex e7d3963c32..49f37ca06d 100644--- a/tests/unit/cc-compatible-provider.test.mjs+++ b/tests/unit/cc-compatible-provider.test.mjs@@ -857,6 +857,109 @@ test("provider-nodes validate route supports enabled CC validation and OpenAI-stassert.equal(calls[1].init.headers.Authorization, "Bearer sk-openai-test");});+test("provider-nodes validate route covers default CC paths, null method, anthropic failures, and OpenAI success", async () => {+ process.env.ENABLE_CC_COMPATIBLE_PROVIDER = "true";++ const ccCalls = [];+ globalThis.fetch = async (url, init = {}) => {+ ccCalls.push({ url, init });+ if (ccCalls.length === 1) {+ throw new Error("models unavailable");+ }+ return new Response(JSON.stringify({ error: "Unauthorized" }), {+ status: 401,+ headers: { "content-type": "application/json" },+ });+ };++ const ccResponse = await providerNodesValidateRoute.POST(+ new Request("http://localhost/api/provider-nodes/validate", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ baseUrl: "https://proxy.example.com/v1/messages",+ apiKey: "sk-cc-invalid",+ type: "anthropic-compatible",+ compatMode: "cc",+ }),+ })+ );++ assert.equal(ccResponse.status, 200);+ assert.deepEqual(await ccResponse.json(), {+ valid: false,+ error: "Invalid API key",+ warning: null,+ method: null,+ });+ assert.equal(+ ccCalls[0].url,+ `https://proxy.example.com${CLAUDE_CODE_COMPATIBLE_DEFAULT_MODELS_PATH}`+ );+ assert.equal(+ ccCalls[1].url,+ `https://proxy.example.com${CLAUDE_CODE_COMPATIBLE_DEFAULT_CHAT_PATH}`+ );+ assert.equal(ccCalls[1].init.method, "POST");++ const anthropicCalls = [];+ globalThis.fetch = async (url, init = {}) => {+ anthropicCalls.push({ url, init });+ return new Response(JSON.stringify({ error: "Unauthorized" }), {+ status: 401,+ headers: { "content-type": "application/json" },+ });+ };++ const anthropicResponse = await providerNodesValidateRoute.POST(+ new Request("http://localhost/api/provider-nodes/validate", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ baseUrl: "https://proxy.example.com/v1/messages",+ apiKey: "sk-anthropic-invalid",+ type: "anthropic-compatible",+ }),+ })+ );++ assert.equal(anthropicResponse.status, 200);+ assert.deepEqual(await anthropicResponse.json(), {+ valid: false,+ error: "Invalid API key",+ });+ assert.equal(anthropicCalls[0].url, "https://proxy.example.com/v1/models");+ assert.equal(anthropicCalls[0].init.method, "GET");++ const openAiCalls = [];+ globalThis.fetch = async (url, init = {}) => {+ openAiCalls.push({ url, init });+ return new Response(JSON.stringify({ data: [] }), {+ status: 200,+ headers: { "content-type": "application/json" },+ });+ };++ const openAiResponse = await providerNodesValidateRoute.POST(+ new Request("http://localhost/api/provider-nodes/validate", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ baseUrl: "https://proxy.example.com/",+ apiKey: "sk-openai-valid",+ }),+ })+ );++ assert.equal(openAiResponse.status, 200);+ assert.deepEqual(await openAiResponse.json(), {+ valid: true,+ error: null,+ });+ assert.equal(openAiCalls[0].url, "https://proxy.example.com/models");+ assert.equal(openAiCalls[0].init.headers.Authorization, "Bearer sk-openai-valid");+});+test("provider-nodes validate route reports unexpected upstream failures", async () => {globalThis.fetch = async () => {throw new Error("boom");diff --git a/tests/unit/cloudflaredTunnel-extended.test.mjs b/tests/unit/cloudflaredTunnel-extended.test.mjsindex a1b816a6fb..abf006a995 100644--- a/tests/unit/cloudflaredTunnel-extended.test.mjs+++ b/tests/unit/cloudflaredTunnel-extended.test.mjs@@ -38,6 +38,45 @@ async function createCloudflaredDataDir(prefix) {return dir;}+async function readJsonFileWithRetry(filePath, attempts = 20) {+ const parseJsonSnapshot = (content) => {+ const trimmed = String(content || "").trim();+ if (!trimmed) {+ throw new SyntaxError("Empty JSON payload");+ }++ try {+ return JSON.parse(trimmed);+ } catch (error) {+ const snapshots = trimmed+ .split(/\n(?=\{)/)+ .map((entry) => entry.trim())+ .filter(Boolean);++ for (let index = snapshots.length - 1; index >= 0; index -= 1) {+ try {+ return JSON.parse(snapshots[index]);+ } catch {+ // Keep trying older complete snapshots.+ }+ }++ throw error;+ }+ };++ let lastError;+ for (let attempt = 0; attempt < attempts; attempt += 1) {+ try {+ return parseJsonSnapshot(await fs.readFile(filePath, "utf8"));+ } catch (error) {+ lastError = error;+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+ }+ throw lastError;+}+function createFakeChild(pid) {const child = new EventEmitter();child.stdout = new PassThrough();@@ -216,7 +255,7 @@ test("startCloudflaredTunnel reaches running state and stopCloudflaredTunnel cleconst started = await tunnel.startCloudflaredTunnel();const statePath = path.join(dataDir, "cloudflared", "quick-tunnel-state.json");const logPath = path.join(dataDir, "cloudflared", "quick-tunnel.log");- const startedState = JSON.parse(await fs.readFile(statePath, "utf8"));+ const startedState = await readJsonFileWithRetry(statePath);assert.equal(spawnCalls.length, 1);assert.equal(spawnCalls[0].command, binaryPath);@@ -240,7 +279,7 @@ test("startCloudflaredTunnel reaches running state and stopCloudflaredTunnel cleassert.match(await fs.readFile(logPath, "utf8"), /violet-cloud\.trycloudflare\.com/);const stopped = await tunnel.stopCloudflaredTunnel();- const stoppedState = JSON.parse(await fs.readFile(statePath, "utf8"));+ const stoppedState = await readJsonFileWithRetry(statePath);assert.equal(stopped.running, false);assert.equal(stopped.phase, "stopped");@@ -296,8 +335,8 @@ test("startCloudflaredTunnel records an error state when the child exits before/(cloudflared exited before tunnel URL was ready \(1\)|certificate signed by unknown authority)/);- const state = JSON.parse(- await fs.readFile(path.join(dataDir, "cloudflared", "quick-tunnel-state.json"), "utf8")+ const state = await readJsonFileWithRetry(+ path.join(dataDir, "cloudflared", "quick-tunnel-state.json"));assert.equal(state.status, "error");diff --git a/tests/unit/combo-test-route.test.mjs b/tests/unit/combo-test-route.test.mjsindex 3a75a3322f..f2da62b1a7 100644--- a/tests/unit/combo-test-route.test.mjs+++ b/tests/unit/combo-test-route.test.mjs@@ -50,6 +50,40 @@ test.after(() => {fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });});+test("combo test route validates request payloads and combo existence", async () => {+ const invalidJsonResponse = await route.POST(+ new Request("http://localhost/api/combos/test", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: "{",+ })+ );++ assert.equal(invalidJsonResponse.status, 400);+ assert.deepEqual(await invalidJsonResponse.json(), {+ error: {+ message: "Invalid request",+ details: [{ field: "body", message: "Invalid JSON body" }],+ },+ });++ const invalidBodyResponse = await route.POST(+ new Request("http://localhost/api/combos/test", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ comboName: "" }),+ })+ );+ const invalidBody = await invalidBodyResponse.json();+ assert.equal(invalidBodyResponse.status, 400);+ assert.equal(invalidBody.error.message, "Invalid request");++ const missingResponse = await route.POST(makeRequest("missing-combo"));+ const missingBody = await missingResponse.json();+ assert.equal(missingResponse.status, 404);+ assert.equal(missingBody.error, "Combo not found");+});+test("combo test route marks a model healthy only when it returns assistant text", async () => {await createTestCombo();@@ -253,3 +287,91 @@ test("combo test route launches model probes concurrently while preserving combo]);});++test("combo test route rejects empty combos and respects forwarded base URLs", async () => {+ await createTestCombo([]);++ const emptyResponse = await route.POST(makeRequest());+ const emptyBody = await emptyResponse.json();+ assert.equal(emptyResponse.status, 400);+ assert.equal(emptyBody.error, "Combo has no models");++ await resetStorage();+ await createTestCombo(["provider/forwarded"]);++ const fetchCalls = [];+ globalThis.fetch = async (url, init = {}) => {+ fetchCalls.push({ url: String(url), init });+ return new Response(+ JSON.stringify({+ choices: [{ message: { role: "assistant", content: "FORWARDED" } }],+ }),+ {+ status: 200,+ headers: { "content-type": "application/json" },+ }+ );+ };++ const forwardedResponse = await route.POST(+ new Request("http://localhost/api/combos/test", {+ method: "POST",+ headers: {+ "content-type": "application/json",+ "x-forwarded-host": "router.example.com",+ "x-forwarded-proto": "https",+ },+ body: JSON.stringify({ comboName: "strict-live-test" }),+ })+ );++ assert.equal(forwardedResponse.status, 200);+ assert.equal(fetchCalls.length, 1);+ assert.equal(fetchCalls[0].url, "https://router.example.com/v1/chat/completions");+});++test("combo test route handles upstream timeouts and non-JSON error bodies", async () => {+ await createTestCombo(["provider/timeout", "provider/error"]);++ let callCount = 0;+ globalThis.fetch = async () => {+ callCount += 1;+ if (callCount === 1) {+ const error = new Error("aborted");+ error.name = "AbortError";+ throw error;+ }+ return new Response("bad gateway", {+ status: 502,+ statusText: "Bad Gateway",+ });+ };++ const response = await route.POST(makeRequest());+ const body = await response.json();++ assert.equal(response.status, 200);+ assert.equal(body.resolvedBy, null);+ assert.deepEqual(+ body.results.map((result) => ({+ model: result.model,+ status: result.status,+ error: result.error,+ statusCode: result.statusCode ?? null,+ })),+ [+ {+ model: "provider/timeout",+ status: "error",+ error: "Timeout (20s)",+ statusCode: null,+ },+ {+ model: "provider/error",+ status: "error",+ error: "Bad Gateway",+ statusCode: 502,+ },+ ]+ );+});diff --git a/tests/unit/db-settings-crud.test.mjs b/tests/unit/db-settings-crud.test.mjsindex ea81d92379..54242610ff 100644--- a/tests/unit/db-settings-crud.test.mjs+++ b/tests/unit/db-settings-crud.test.mjs@@ -199,6 +199,97 @@ test("pricing helpers resolve aliased providers and tolerate no-op resets", asynassert.equal(afterUnknownReset["missing-provider"], undefined);});+test("settings and pricing readers skip malformed rows while merging surviving layers", async () => {+ const db = core.getDbInstance();+ const originalPrepare = db.prepare.bind(db);++ db.prepare = (sql) => {+ const text = String(sql);++ if (text.includes("namespace = 'settings'")) {+ return {+ all: () => [+ 123,+ { key: 456, value: "true" },+ { key: "cloudEnabled", value: "true" },+ { key: "requireLogin", value: null },+ ],+ };+ }++ if (text.includes("namespace = 'pricing_synced'")) {+ return {+ all: () => [+ 123,+ { key: 456, value: JSON.stringify({ ignored: true }) },+ {+ key: "layered-provider",+ value: JSON.stringify({+ "model-a": { prompt: 1, completion: 2 },+ }),+ },+ ],+ };+ }++ if (text.includes("namespace = 'models_dev_pricing'")) {+ return {+ all: () => [+ { key: "broken-provider", value: "{bad" },+ { key: "missing-value", value: null },+ {+ key: "layered-provider",+ value: JSON.stringify({+ "model-a": { cached: 3 },+ }),+ },+ ],+ };+ }++ if (text.includes("namespace = 'pricing'")) {+ return {+ all: () => [+ {+ key: "layered-provider",+ value: JSON.stringify({+ "model-a": { prompt: 9, custom: 42 },+ "model-b": { prompt: 7 },+ }),+ },+ { key: null, value: JSON.stringify({ ignored: true }) },+ ],+ };+ }++ return originalPrepare(sql);+ };++ try {+ const settings = await settingsDb.getSettings();+ const pricing = await settingsDb.getPricing();+ const modelPricing = await settingsDb.getPricingForModel("layered-provider", "model-a");++ assert.equal(settings.cloudEnabled, true);+ assert.equal(settings.requireLogin, true);+ assert.deepEqual(pricing["layered-provider"]["model-a"], {+ prompt: 9,+ completion: 2,+ cached: 3,+ custom: 42,+ });+ assert.deepEqual(modelPricing, {+ prompt: 9,+ completion: 2,+ cached: 3,+ custom: 42,+ });+ assert.equal(pricing["broken-provider"], undefined);+ } finally {+ db.prepare = originalPrepare;+ }+});+test("proxy config migrates legacy strings and supports bulk merge updates", async () => {const db = core.getDbInstance();@@ -434,6 +525,64 @@ test("proxy resolution matches combo proxies through aliased model entries", asyassert.equal(resolved.proxy.host, "combo-alias.local");});+test("proxy readers normalize legacy rows, skip malformed entries, and coerce invalid globals to null", async () => {+ const db = core.getDbInstance();+ const originalPrepare = db.prepare.bind(db);++ db.prepare = (sql) => {+ const text = String(sql);++ if (text.includes("namespace = 'proxyConfig'") && text.startsWith("SELECT")) {+ return {+ all: () => [+ 123,+ { key: 456, value: JSON.stringify({ ignored: true }) },+ { key: "global", value: JSON.stringify("https://user%40name:pass%[email protected]") },+ {+ key: "providers",+ value: JSON.stringify({+ openai: "http://provider.example",+ }),+ },+ { key: "combos", value: JSON.stringify("not-a-map") },+ { key: "keys", value: null },+ ],+ };+ }++ if (text.includes("namespace = 'proxyConfig'") && text.startsWith("INSERT OR REPLACE")) {+ return { run: () => ({ changes: 1 }) };+ }++ return originalPrepare(sql);+ };++ try {+ const config = await settingsDb.getProxyConfig();+ assert.deepEqual(config.global, {+ type: "https",+ host: "proxy.example",+ port: "443",+ username: "user@name",+ password: "pass/word",+ });+ assert.deepEqual(config.providers.openai, {+ type: "http",+ host: "provider.example",+ port: "8080",+ username: "",+ password: "",+ });+ assert.equal(await settingsDb.getProxyForLevel("combo", "missing"), null);+ } finally {+ db.prepare = originalPrepare;+ }++ const updated = await settingsDb.setProxyConfig({ level: 123, id: 456, proxy: 0 });+ assert.equal(updated.global, null);+ assert.equal(await settingsDb.getProxyForLevel("global"), null);+});+test("cache metrics, trend and no-op update/reset methods read from usage_history", async () => {const db = core.getDbInstance();const now = new Date().toISOString();@@ -519,3 +668,114 @@ test("cache metric helpers degrade gracefully when SQLite aggregation fails", asdb.prepare = originalPrepare;}});++test("cache metrics and trend coerce null aggregate fields to zero", async () => {+ const db = core.getDbInstance();+ const originalPrepare = db.prepare.bind(db);++ db.prepare = (sql) => {+ const text = String(sql);++ if (text.includes("COUNT(*) as totalRequests") && text.includes("tokens_cache_read > 0")) {+ return {+ get: () => ({+ totalRequests: 2,+ totalInputTokens: null,+ totalCachedTokens: null,+ totalCacheCreationTokens: null,+ }),+ };+ }++ if (text.includes("SELECT COUNT(*) as totalRequests") && text.includes("FROM usage_history")) {+ return {+ get: () => ({+ totalRequests: 5,+ }),+ };+ }++ if (text.includes("GROUP BY provider")) {+ return {+ all: () => [+ {+ provider: "openai",+ requests: 1,+ inputTokens: null,+ cachedTokens: null,+ cacheCreationTokens: null,+ },+ ],+ };+ }++ if (text.includes("GROUP BY 'direct'")) {+ return {+ all: () => [+ {+ strategy: "direct",+ requests: 2,+ inputTokens: null,+ cachedTokens: null,+ cacheCreationTokens: null,+ },+ ],+ };+ }++ if (text.includes("strftime('%Y-%m-%dT%H:00:00Z', timestamp) as hour")) {+ return {+ all: () => [+ {+ hour: "2026-01-01T10:00:00Z",+ requests: 3,+ cachedRequests: 1,+ inputTokens: null,+ cachedTokens: null,+ cacheCreationTokens: null,+ },+ ],+ };+ }++ return originalPrepare(sql);+ };++ try {+ const metrics = await settingsDb.getCacheMetrics();+ const updated = await settingsDb.updateCacheMetrics({ force: true });+ const trend = await settingsDb.getCacheTrend(2);+ const reset = await settingsDb.resetCacheMetrics();++ assert.equal(metrics.totalRequests, 5);+ assert.equal(metrics.totalInputTokens, 0);+ assert.equal(metrics.totalCachedTokens, 0);+ assert.equal(metrics.totalCacheCreationTokens, 0);+ assert.deepEqual(metrics.byProvider.openai, {+ requests: 1,+ inputTokens: 0,+ cachedTokens: 0,+ cacheCreationTokens: 0,+ });+ assert.deepEqual(metrics.byStrategy.direct, {+ requests: 2,+ inputTokens: 0,+ cachedTokens: 0,+ cacheCreationTokens: 0,+ });+ assert.deepEqual(trend, [+ {+ timestamp: "2026-01-01T10:00:00Z",+ requests: 3,+ cachedRequests: 1,+ inputTokens: 0,+ cachedTokens: 0,+ cacheCreationTokens: 0,+ },+ ]);+ assert.equal(updated.totalCachedTokens, 0);+ assert.equal(reset.totalCachedTokens, 0);+ } finally {+ db.prepare = originalPrepare;+ }+});diff --git a/tests/unit/fixes-p1.test.mjs b/tests/unit/fixes-p1.test.mjsindex 69e2c7e824..12133ed3fd 100644--- a/tests/unit/fixes-p1.test.mjs+++ b/tests/unit/fixes-p1.test.mjs@@ -14,6 +14,7 @@ const backupDb = await import("../../src/lib/db/backup.ts");const providersDb = await import("../../src/lib/db/providers.ts");const combosDb = await import("../../src/lib/db/combos.ts");const settingsDb = await import("../../src/lib/db/settings.ts");+const localDb = await import("../../src/lib/localDb.ts");const tokenRefresh = await import("../../open-sse/services/tokenRefresh.ts");const proxyFetch = await import("../../open-sse/utils/proxyFetch.ts");const proxyDispatcher = await import("../../open-sse/utils/proxyDispatcher.ts");@@ -537,3 +538,111 @@ test("proxy test route runs socks5 test when backend flag is enabled", async ()assert.equal(payload.proxyUrl, "socks5://127.0.0.1:1");});});++test("proxy test route validates JSON, schema, and proxy types before dispatching", async () => {+ await resetStorage();++ const invalidJsonResponse = await proxyTestRoute.POST(+ new Request("http://localhost/api/settings/proxy/test", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: "{",+ })+ );+ const invalidJsonBody = await invalidJsonResponse.json();+ assert.equal(invalidJsonResponse.status, 400);+ assert.equal(invalidJsonBody.error.message, "Invalid JSON body");++ const invalidBodyResponse = await proxyTestRoute.POST(+ new Request("http://localhost/api/settings/proxy/test", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ proxy: { port: "8080" } }),+ })+ );+ const invalidBody = await invalidBodyResponse.json();+ assert.equal(invalidBodyResponse.status, 400);+ assert.equal(invalidBody.error.message, "Invalid request");++ const socks4Response = await proxyTestRoute.POST(+ new Request("http://localhost/api/settings/proxy/test", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ proxy: {+ type: "socks4",+ host: "127.0.0.1",+ port: "1080",+ },+ }),+ })+ );+ const socks4Body = await socks4Response.json();+ assert.equal(socks4Response.status, 400);+ assert.match(socks4Body.error.message, /proxy\.type must be http or https/i);++ const unsupportedResponse = await proxyTestRoute.POST(+ new Request("http://localhost/api/settings/proxy/test", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ proxy: {+ type: "ftp",+ host: "127.0.0.1",+ port: "21",+ },+ }),+ })+ );+ const unsupportedBody = await unsupportedResponse.json();+ assert.equal(unsupportedResponse.status, 400);+ assert.match(unsupportedBody.error.message, /proxy\.type must be http or https/i);+});++test("proxy test route handles invalid proxy ports and uses stored proxy config when proxyId is provided", async () => {+ await resetStorage();++ const invalidPortResponse = await proxyTestRoute.POST(+ new Request("http://localhost/api/settings/proxy/test", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ proxy: {+ type: "http",+ host: "127.0.0.1",+ port: "70000",+ },+ }),+ })+ );+ const invalidPortBody = await invalidPortResponse.json();+ assert.equal(invalidPortResponse.status, 400);+ assert.match(invalidPortBody.error.message, /invalid proxy port/i);++ const storedProxy = await localDb.createProxy({+ name: "Stored Proxy",+ type: "http",+ host: "127.0.0.1",+ port: 1,+ username: "alice",+ password: "secret",+ });++ const proxyIdResponse = await proxyTestRoute.POST(+ new Request("http://localhost/api/settings/proxy/test", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ proxyId: storedProxy.id,+ proxy: {+ host: "127.0.0.1",+ port: 0,+ },+ }),+ })+ );+ const proxyIdBody = await proxyIdResponse.json();+ assert.notEqual(proxyIdResponse.status, 400);+ assert.equal(proxyIdBody.success, false);+ assert.equal(proxyIdBody.proxyUrl, "http://127.0.0.1:1");+});diff --git a/tests/unit/model-sync-route.test.mjs b/tests/unit/model-sync-route.test.mjsindex 978d915739..629c22586d 100644--- a/tests/unit/model-sync-route.test.mjs+++ b/tests/unit/model-sync-route.test.mjs@@ -9,6 +9,7 @@ process.env.DATA_DIR = TEST_DATA_DIR;const core = await import("../../src/lib/db/core.ts");const localDb = await import("../../src/lib/localDb.ts");+const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");const providersDb = await import("../../src/lib/db/providers.ts");const modelsDb = await import("../../src/lib/db/models.ts");const callLogs = await import("../../src/lib/usage/callLogs.ts");@@ -20,6 +21,7 @@ async function resetStorage() {delete process.env.INITIAL_PASSWORD;globalThis.fetch = originalFetch;core.resetDbInstance();+ apiKeysDb.resetApiKeyState();fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });fs.mkdirSync(TEST_DATA_DIR, { recursive: true });}@@ -27,6 +29,7 @@ async function resetStorage() {test.after(() => {globalThis.fetch = originalFetch;core.resetDbInstance();+ apiKeysDb.resetApiKeyState();fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });});@@ -199,6 +202,87 @@ test("model sync route propagates upstream failures and records an error log entassert.equal(logs[0].path, `/api/providers/${connection.id}/models`);});+test("model sync route falls back to the upstream HTTP status when the models payload has no error field", async () => {+ await resetStorage();++ const connection = await providersDb.createProviderConnection({+ provider: "openrouter",+ authType: "apikey",+ name: "Rate Limited Sync",+ apiKey: "test-key",+ });++ globalThis.fetch = async (url) => {+ assert.equal(String(url), `http://localhost/api/providers/${connection.id}/models`);+ return Response.json({}, { status: 429 });+ };++ const response = await modelSyncRoute.POST(+ new Request(`http://localhost/api/providers/${connection.id}/sync-models`, {+ method: "POST",+ headers: scheduler.buildModelSyncInternalHeaders(),+ }),+ { params: { id: connection.id } }+ );+ const body = await response.json();+ const logs = await callLogs.getCallLogs({ model: "model-sync", limit: 10 });++ assert.equal(response.status, 429);+ assert.equal(body.error, "Failed to fetch models");+ assert.equal(logs.length, 1);+ assert.equal(logs[0].status, 429);+ assert.equal(logs[0].error, "HTTP 429");+});++test("model sync route preserves previously synced models when the upstream omits the models list", async () => {+ await resetStorage();++ const connection = await providersDb.createProviderConnection({+ provider: "openrouter",+ authType: "apikey",+ name: "No Models Returned",+ apiKey: "test-key",+ });++ await modelsDb.replaceCustomModels("openrouter", [+ {+ id: "persisted-model",+ name: "Persisted Model",+ source: "auto-sync",+ },+ ]);++ globalThis.fetch = async (url) => {+ assert.equal(String(url), `http://localhost/api/providers/${connection.id}/models`);+ return Response.json({});+ };++ const response = await modelSyncRoute.POST(+ new Request(`http://localhost/api/providers/${connection.id}/sync-models`, {+ method: "POST",+ headers: scheduler.buildModelSyncInternalHeaders(),+ }),+ { params: { id: connection.id } }+ );+ const body = await response.json();+ const logs = await callLogs.getCallLogs({ model: "model-sync", limit: 10 });++ assert.equal(response.status, 200);+ assert.equal(body.syncedModels, 1);+ assert.equal(body.logged, false);+ assert.deepEqual(body.modelChanges, { added: 0, removed: 0, updated: 0, total: 0 });+ assert.deepEqual(body.models, [+ {+ id: "persisted-model",+ name: "Persisted Model",+ source: "auto-sync",+ apiFormat: "chat-completions",+ supportedEndpoints: ["chat"],+ },+ ]);+ assert.equal(logs.length, 0);+});+test("model sync route writes synced available models for Gemini connections", async () => {await resetStorage();@@ -271,6 +355,206 @@ test("model sync route writes synced available models for Gemini connections", aassert.equal(logs[0].status, 200);});+test("model sync route records added, removed, and updated model diffs with fallback identifiers", async () => {+ await resetStorage();++ const connection = await providersDb.createProviderConnection({+ provider: "openrouter",+ authType: "oauth",+ email: "[email protected]",+ accessToken: "sync-token",+ });++ await modelsDb.replaceCustomModels("openrouter", [+ {+ id: "persisted-model",+ name: "Persisted Model",+ source: "auto-sync",+ },+ {+ id: "removed-model",+ name: "Removed Model",+ source: "auto-sync",+ },+ ]);++ globalThis.fetch = async (url) => {+ assert.equal(String(url), `http://localhost/api/providers/${connection.id}/models`);+ return Response.json({+ models: [+ {+ id: "persisted-model",+ name: "Persisted Model v2",+ supportedEndpoints: ["chat", "embeddings"],+ },+ {+ model: "fallback-model",+ displayName: "Fallback Model",+ description: "Fallback from model field",+ },+ ],+ });+ };++ const response = await modelSyncRoute.POST(+ new Request(`http://localhost/api/providers/${connection.id}/sync-models`, {+ method: "POST",+ headers: scheduler.buildModelSyncInternalHeaders(),+ }),+ { params: { id: connection.id } }+ );+ const body = await response.json();+ const logs = await callLogs.getCallLogs({ model: "model-sync", limit: 10 });++ assert.equal(response.status, 200);+ assert.equal(body.syncedModels, 2);+ assert.equal(body.logged, true);+ assert.deepEqual(body.modelChanges, { added: 1, removed: 1, updated: 1, total: 3 });+ assert.deepEqual(+ body.models.map((model) => ({+ id: model.id,+ name: model.name,+ supportedEndpoints: model.supportedEndpoints,+ description: model.description,+ })),+ [+ {+ id: "persisted-model",+ name: "Persisted Model v2",+ supportedEndpoints: ["chat", "embeddings"],+ description: undefined,+ },+ {+ id: "fallback-model",+ name: "Fallback Model",+ supportedEndpoints: ["chat"],+ description: "Fallback from model field",+ },+ ]+ );+ assert.equal(logs.length, 1);+ assert.equal(logs[0].status, 200);+ assert.equal(logs[0].provider, "openrouter");+ assert.equal(logs[0].account, "[email protected]");+});++test("model sync route accepts external API-key auth, forwards cookies, filters built-ins, and syncs aliases", async () => {+ await resetStorage();+ await enableAuth();++ const authKey = await apiKeysDb.createApiKey("sync-external", "machine-sync");+ const connection = await providersDb.createProviderConnection({+ provider: "openrouter",+ authType: "apikey",+ name: "External Sync",+ displayName: "OpenRouter External",+ apiKey: "test-key",+ });++ await localDb.setModelAlias("stale-model", "openrouter/stale-model");+ await localDb.setModelAlias("router-v2", "other-provider/router-v2");++ globalThis.fetch = async (url, init = {}) => {+ assert.equal(String(url), `http://localhost/api/providers/${connection.id}/models`);+ assert.equal(init.headers.cookie, "session=test-cookie");+ assert.equal(+ init.headers[scheduler.getModelSyncInternalAuthHeaderName()],+ scheduler.buildModelSyncInternalHeaders()[scheduler.getModelSyncInternalAuthHeaderName()]+ );++ return Response.json({+ models: [+ { id: "auto", name: "Auto (Best Available)" },+ { id: "router-v2", name: "Router V2" },+ { id: "router-v3", name: "Router V3" },+ ],+ });+ };++ const response = await modelSyncRoute.POST(+ new Request(`http://localhost/api/providers/${connection.id}/sync-models`, {+ method: "POST",+ headers: {+ authorization: `Bearer ${authKey.key}`,+ cookie: "session=test-cookie",+ },+ }),+ { params: { id: connection.id } }+ );+ const body = await response.json();+ const aliases = await localDb.getModelAliases();+ const logs = await callLogs.getCallLogs({ model: "model-sync", limit: 10 });++ assert.equal(response.status, 200);+ assert.equal(body.provider, "openrouter");+ assert.equal(body.syncedModels, 2);+ assert.equal(body.syncedAliases, 2);+ assert.equal(body.logged, true);+ assert.deepEqual(body.modelChanges, { added: 2, removed: 0, updated: 0, total: 2 });+ assert.deepEqual(+ body.models.map((model) => ({ id: model.id, name: model.name })),+ [+ { id: "router-v2", name: "Router V2" },+ { id: "router-v3", name: "Router V3" },+ ]+ );+ assert.equal(aliases["stale-model"], undefined);+ assert.equal(aliases["openrouter-router-v2"], "openrouter/router-v2");+ assert.equal(aliases["router-v3"], "openrouter/router-v3");+ assert.equal(logs.length, 1);+ assert.equal(logs[0].status, 200);+ assert.equal(logs[0].account, "External Sync");+});++test("model sync route uses provider-node prefixes when syncing compatible-provider aliases", async () => {+ await resetStorage();++ await providersDb.createProviderNode({+ id: "anthropic-compatible-demo",+ type: "anthropic-compatible",+ name: "Anthropic Demo",+ prefix: "cm",+ baseUrl: "https://proxy.example.com",+ chatPath: "/v1/messages",+ modelsPath: "/v1/models",+ });+ const connection = await providersDb.createProviderConnection({+ provider: "anthropic-compatible-demo",+ authType: "apikey",+ name: "Compatible Sync",+ apiKey: "compat-key",+ providerSpecificData: {+ baseUrl: "https://proxy.example.com",+ chatPath: "/v1/messages",+ modelsPath: "/v1/models",+ },+ });++ await localDb.setModelAlias("sonnet-4-6", "some-other-provider/sonnet-4-6");++ globalThis.fetch = async (url) => {+ assert.equal(String(url), `http://localhost/api/providers/${connection.id}/models`);+ return Response.json({+ models: [{ id: "sonnet-4-6", name: "Sonnet 4.6" }],+ });+ };++ const response = await modelSyncRoute.POST(+ new Request(`http://localhost/api/providers/${connection.id}/sync-models`, {+ method: "POST",+ headers: scheduler.buildModelSyncInternalHeaders(),+ }),+ { params: { id: connection.id } }+ );+ const body = await response.json();+ const aliases = await localDb.getModelAliases();++ assert.equal(response.status, 200);+ assert.equal(body.provider, "anthropic-compatible-demo");+ assert.equal(body.syncedAliases, 1);+ assert.equal(aliases["cm-sonnet-4-6"], "anthropic-compatible-demo/sonnet-4-6");+});+test("model sync route returns 500 and records a failure when the internal models fetch throws", async () => {await resetStorage();diff --git a/tests/unit/modelsDevSync-extended.test.mjs b/tests/unit/modelsDevSync-extended.test.mjsindex c487cb5d0f..3bb1422e62 100644--- a/tests/unit/modelsDevSync-extended.test.mjs+++ b/tests/unit/modelsDevSync-extended.test.mjs@@ -171,6 +171,72 @@ test("fetchModelsDev caches successful responses and rejects invalid JSON or nonawait assert.rejects(() => nonOk.fetchModelsDev(), /models\.dev fetch failed \[503\]/);});+test("modelsDev interval falls back to the default when env values are invalid or non-positive", async () => {+ process.env.MODELS_DEV_SYNC_INTERVAL = "0";+ const zeroInterval = await importFresh("interval-zero");+ zeroInterval.startPeriodicSync();+ assert.equal(zeroInterval.getSyncStatus().intervalMs, 86400 * 1000);+ zeroInterval.stopPeriodicSync();++ process.env.MODELS_DEV_SYNC_INTERVAL = "not-a-number";+ const invalidInterval = await importFresh("interval-invalid");+ invalidInterval.startPeriodicSync();+ assert.equal(invalidInterval.getSyncStatus().intervalMs, 86400 * 1000);+ invalidInterval.stopPeriodicSync();+});++test("transform helpers skip incomplete pricing entries and preserve partial capability defaults", async () => {+ const modelsDev = await importFresh("transform-edge-cases");+ const raw = {+ sparse: {+ id: "sparse",+ models: {+ "missing-cost": {+ id: "missing-cost",+ name: "Missing Cost",+ },+ "missing-input": {+ id: "missing-input",+ name: "Missing Input",+ cost: { output: 4.2 },+ },+ complete: {+ id: "complete",+ name: "Complete",+ cost: { input: 1.5 },+ interleaved: { field: "" },+ },+ },+ },+ nomodels: {+ id: "nomodels",+ },+ };++ const pricing = modelsDev.transformModelsDevToPricing(raw);+ assert.deepEqual(pricing.sparse, {+ complete: {+ input: 1.5,+ output: 0,+ },+ });+ assert.equal(pricing.nomodels, undefined);++ const capabilities = modelsDev.transformModelsDevToCapabilities(raw);+ assert.equal(capabilities.sparse.complete.tool_call, null);+ assert.equal(capabilities.sparse.complete.reasoning, null);+ assert.equal(capabilities.sparse.complete.attachment, null);+ assert.equal(capabilities.sparse.complete.structured_output, null);+ assert.equal(capabilities.sparse.complete.temperature, null);+ assert.equal(capabilities.sparse.complete.modalities_input, "[]");+ assert.equal(capabilities.sparse.complete.modalities_output, "[]");+ assert.equal(capabilities.sparse.complete.limit_context, null);+ assert.equal(capabilities.sparse.complete.limit_input, null);+ assert.equal(capabilities.sparse.complete.limit_output, null);+ assert.equal(capabilities.sparse.complete.interleaved_field, null);+ assert.equal(capabilities.nomodels, undefined);+});+test("modelsDev pricing helpers persist records, skip corrupted rows, and clear the namespace", async () => {const modelsDev = await importFresh("pricing-storage");const pricing = modelsDev.transformModelsDevToPricing(MOCK_MODELS_DEV_DATA);@@ -215,6 +281,157 @@ test("modelsDev capabilities helpers create the table, persist rows, filter by passert.deepEqual(modelsDev.getSyncedCapabilities(), {});});+test("modelsDev capability helpers coerce false/null values and ignore malformed rows", async () => {+ const modelsDev = await importFresh("capabilities-malformed");+ const db = core.getDbInstance();+ const originalPrepare = db.prepare.bind(db);+ db.prepare = (sql) => {+ if (String(sql).includes("SELECT * FROM model_capabilities")) {+ return {+ all: () => [+ 123,+ { provider: null, model_id: "missing-provider" },+ {+ provider: "openai",+ model_id: "coerced-model",+ tool_call: 0,+ reasoning: null,+ attachment: 0,+ structured_output: 0,+ temperature: 0,+ modalities_input: null,+ modalities_output: 42,+ knowledge_cutoff: 77,+ release_date: 88,+ last_updated: 99,+ status: 123,+ family: 456,+ open_weights: null,+ limit_context: "bad",+ limit_input: 4096,+ limit_output: "nope",+ interleaved_field: 321,+ },+ ],+ };+ }+ return originalPrepare(sql);+ };++ try {+ const openai = modelsDev.getSyncedCapabilities("openai");+ assert.deepEqual(openai.openai["coerced-model"], {+ tool_call: false,+ reasoning: null,+ attachment: false,+ structured_output: false,+ temperature: false,+ modalities_input: "[]",+ modalities_output: "[]",+ knowledge_cutoff: null,+ release_date: null,+ last_updated: null,+ status: null,+ family: null,+ open_weights: null,+ limit_context: null,+ limit_input: 4096,+ limit_output: null,+ interleaved_field: null,+ });++ const all = modelsDev.getSyncedCapabilities();+ assert.equal(all["7"], undefined);+ assert.equal(all.openai["missing-provider"], undefined);+ } finally {+ db.prepare = originalPrepare;+ }+});++test("modelsDev pricing helpers ignore malformed sqlite rows without crashing", async () => {+ const modelsDev = await importFresh("pricing-malformed");+ const db = core.getDbInstance();+ const originalPrepare = db.prepare.bind(db);+ db.prepare = (sql) => {+ if (String(sql).includes("SELECT key, value FROM key_value")) {+ return {+ all: () => [+ 123,+ { key: 123, value: JSON.stringify({ ignored: true }) },+ { key: "missing-value", value: 456 },+ { key: "broken", value: "{oops" },+ { key: "openai", value: JSON.stringify({ "gpt-4o": { input: 2.5, output: 10 } }) },+ ],+ };+ }+ return originalPrepare(sql);+ };++ try {+ assert.deepEqual(modelsDev.getModelsDevPricing(), {+ openai: {+ "gpt-4o": {+ input: 2.5,+ output: 10,+ },+ },+ });+ } finally {+ db.prepare = originalPrepare;+ }+});++test("saveModelsDevCapabilities round-trips false and null booleans", async () => {+ const modelsDev = await importFresh("capabilities-roundtrip-falsey");+ modelsDev.saveModelsDevCapabilities({+ openai: {+ "gpt-falsey": {+ tool_call: false,+ reasoning: null,+ attachment: false,+ structured_output: false,+ temperature: null,+ modalities_input: "[]",+ modalities_output: '["text"]',+ knowledge_cutoff: null,+ release_date: null,+ last_updated: null,+ status: null,+ family: null,+ open_weights: false,+ limit_context: null,+ limit_input: null,+ limit_output: 1024,+ interleaved_field: null,+ },+ },+ });++ assert.deepEqual(modelsDev.getSyncedCapabilities("openai", "gpt-falsey"), {+ openai: {+ "gpt-falsey": {+ tool_call: false,+ reasoning: null,+ attachment: false,+ structured_output: false,+ temperature: null,+ modalities_input: "[]",+ modalities_output: '["text"]',+ knowledge_cutoff: null,+ release_date: null,+ last_updated: null,+ status: null,+ family: null,+ open_weights: false,+ limit_context: null,+ limit_input: null,+ limit_output: 1024,+ interleaved_field: null,+ },+ },+ });+});+test("syncModelsDev supports dry-run mode, persistence, capability toggles, and failure reporting", async () => {const modelsDev = await importFresh("sync-main");mockFetchWith(MOCK_MODELS_DEV_DATA);@@ -244,6 +461,18 @@ test("syncModelsDev supports dry-run mode, persistence, capability toggles, andassert.match(failed.error, /network down/);});+test("syncModelsDev string failures are normalized into an error payload", async () => {+ const modelsDev = await importFresh("sync-string-error");+ globalThis.fetch = async () => {+ throw "hard fail";+ };++ const failed = await modelsDev.syncModelsDev({ dryRun: true });+ assert.equal(failed.success, false);+ assert.equal(failed.error, "hard fail");+ assert.equal(failed.dryRun, true);+});+test("startPeriodicSync, stopPeriodicSync, getSyncStatus, and initModelsDevSync honor settings and avoid duplicate timers", async () => {const modelsDev = await importFresh("periodic-sync");mockFetchWith(MOCK_MODELS_DEV_DATA);diff --git a/tests/unit/provider-models-route.test.mjs b/tests/unit/provider-models-route.test.mjsindex 30646831b6..328a11fb83 100644--- a/tests/unit/provider-models-route.test.mjs+++ b/tests/unit/provider-models-route.test.mjs@@ -59,6 +59,20 @@ test("provider models route returns 404 for unknown connections", async () => {assert.deepEqual(await response.json(), { error: "Connection not found" });});+test("provider models route rejects connections with an empty provider id", async () => {+ const connection = await seedConnection("openai", {+ apiKey: "sk-openai",+ });+ const db = core.getDbInstance();++ db.prepare("UPDATE provider_connections SET provider = '' WHERE id = ?").run(connection.id);++ const response = await callRoute(connection.id);++ assert.equal(response.status, 400);+ assert.deepEqual(await response.json(), { error: "Invalid connection provider" });+});+test("provider models route rejects OpenAI-compatible providers without a base URL", async () => {const connection = await seedConnection("openai-compatible-demo", {apiKey: "sk-openai-compatible",@@ -192,6 +206,92 @@ test("provider models route returns the local catalog for OAuth-backed Qwen connassert.ok(Array.isArray(body.models));});+test("provider models route filters hidden models from the static Claude catalog when requested", async () => {+ const connection = await seedConnection("claude", {+ authType: "oauth",+ accessToken: "claude-access",+ apiKey: null,+ });+ modelsDb.mergeModelCompatOverride("claude", "claude-sonnet-4-6", { isHidden: true });++ const response = await callRoute(connection.id, "?excludeHidden=true");+ const body = await response.json();++ assert.equal(response.status, 200);+ assert.equal(body.provider, "claude");+ assert.equal(+ body.models.some((model) => model.id === "claude-sonnet-4-6"),+ false+ );+ assert.ok(body.models.some((model) => model.id === "claude-opus-4-6"));+});++test("provider models route rejects Anthropic-compatible providers without a base URL", async () => {+ const connection = await seedConnection("anthropic-compatible-demo", {+ apiKey: "sk-anthropic-compatible",+ });++ const response = await callRoute(connection.id);++ assert.equal(response.status, 400);+ assert.deepEqual(await response.json(), {+ error: "No base URL configured for Anthropic compatible provider",+ });+});++test("provider models route trims Anthropic-compatible message URLs and filters hidden upstream models", async () => {+ const connection = await seedConnection("anthropic-compatible-demo", {+ apiKey: "sk-anthropic-compatible",+ accessToken: "anthropic-access",+ providerSpecificData: {+ baseUrl: "https://proxy.example.com/v1/messages",+ },+ });+ modelsDb.mergeModelCompatOverride("anthropic-compatible-demo", "hidden-model", {+ isHidden: true,+ });++ globalThis.fetch = async (url, init = {}) => {+ assert.equal(String(url), "https://proxy.example.com/v1/models");+ assert.equal(init.method, "GET");+ assert.equal(init.headers["Content-Type"], "application/json");+ assert.equal(init.headers["x-api-key"], "sk-anthropic-compatible");+ assert.equal(init.headers.Authorization, "Bearer anthropic-access");+ assert.equal(init.headers["anthropic-version"], "2023-06-01");++ return Response.json({+ data: [+ { id: "visible-model", name: "Visible Model" },+ { id: "hidden-model", name: "Hidden Model" },+ ],+ });+ };++ const response = await callRoute(connection.id, "?excludeHidden=true");+ const body = await response.json();++ assert.equal(response.status, 200);+ assert.deepEqual(body.models, [{ id: "visible-model", name: "Visible Model" }]);+});++test("provider models route forwards Anthropic-compatible upstream failures", async () => {+ const connection = await seedConnection("anthropic-compatible-demo", {+ apiKey: "sk-anthropic-compatible",+ providerSpecificData: {+ baseUrl: "https://proxy.example.com/v1/messages",+ },+ });++ globalThis.fetch = async () => new Response("upstream unavailable", { status: 502 });++ const response = await callRoute(connection.id);++ assert.equal(response.status, 502);+ assert.deepEqual(await response.json(), {+ error: "Failed to fetch models: 502",+ });+});+test("provider models route paginates generic providers and filters hidden models when requested", async () => {const connection = await seedConnection("gemini", {apiKey: "gm-key",@@ -332,3 +432,27 @@ test("provider models route rejects unsupported providers without a models confierror: "Provider unsupported-provider does not support models listing",});});++test("provider models route uses provider-specific auth headers for Kimi Coding", async () => {+ const connection = await seedConnection("kimi-coding", {+ apiKey: "kimi-coding-key",+ });++ globalThis.fetch = async (url, init = {}) => {+ assert.equal(String(url), "https://api.kimi.com/coding/v1/models");+ assert.equal(init.method, "GET");+ assert.equal(init.headers["x-api-key"], "kimi-coding-key");+ assert.equal(init.headers.Authorization, undefined);++ return Response.json({+ data: [{ id: "kimi-k2.5", name: "Kimi K2.5" }],+ });+ };++ const response = await callRoute(connection.id);+ const body = await response.json();++ assert.equal(response.status, 200);+ assert.equal(body.provider, "kimi-coding");+ assert.deepEqual(body.models, [{ id: "kimi-k2.5", name: "Kimi K2.5" }]);+});diff --git a/tests/unit/proxy-management-v1-route.test.mjs b/tests/unit/proxy-management-v1-route.test.mjsindex 90b309ad09..e02f2e267c 100644--- a/tests/unit/proxy-management-v1-route.test.mjs+++ b/tests/unit/proxy-management-v1-route.test.mjs@@ -37,11 +37,32 @@ async function withEnv(name, value, fn) {}async function resetStorage() {+ delete process.env.INITIAL_PASSWORD;core.resetDbInstance();fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });fs.mkdirSync(TEST_DATA_DIR, { recursive: true });}+async function withPrepareFailure(match, message, fn) {+ const db = core.getDbInstance();+ const originalPrepare = db.prepare.bind(db);++ db.prepare = (sql, ...args) => {+ const sqlText = String(sql);+ const matched = typeof match === "function" ? match(sqlText) : sqlText.includes(match);+ if (matched) {+ throw new Error(message);+ }+ return originalPrepare(sql, ...args);+ };++ try {+ return await fn();+ } finally {+ db.prepare = originalPrepare;+ }+}+test.after(async () => {core.resetDbInstance();fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });@@ -88,6 +109,294 @@ test("v1 management proxies supports create/list/pagination", async () => {assert.equal(listPayload.page.total >= 2, true);});+test("v1 management proxies main route covers auth, lookup variants, update and delete branches", async () => {+ await resetStorage();++ await withEnv("INITIAL_PASSWORD", "secret", async () => {+ const getAuthRes = await proxyV1Route.GET(+ new Request("http://localhost/api/v1/management/proxies")+ );+ assert.equal(getAuthRes.status, 401);++ const postAuthRes = await proxyV1Route.POST(+ new Request("http://localhost/api/v1/management/proxies", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: "Bearer invalid-management-token",+ },+ body: JSON.stringify({+ name: "Denied Proxy",+ type: "http",+ host: "denied.local",+ port: 8080,+ }),+ })+ );+ assert.equal(postAuthRes.status, 403);++ const patchAuthRes = await proxyV1Route.PATCH(+ new Request("http://localhost/api/v1/management/proxies", {+ method: "PATCH",+ headers: { Authorization: "Bearer invalid-management-token" },+ body: JSON.stringify({ id: "proxy-1", notes: "denied" }),+ })+ );+ assert.equal(patchAuthRes.status, 403);++ const deleteAuthRes = await proxyV1Route.DELETE(+ new Request("http://localhost/api/v1/management/proxies?id=proxy-1", {+ method: "DELETE",+ })+ );+ assert.equal(deleteAuthRes.status, 401);+ });++ const providerConn = await providersDb.createProviderConnection({+ provider: "openai",+ authType: "apikey",+ name: "v1-main-route",+ apiKey: "sk-test-main-route",+ });++ const createdRes = await proxyV1Route.POST(+ new Request("http://localhost/api/v1/management/proxies", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ name: "Primary Proxy",+ type: "http",+ host: "primary.local",+ port: 8080,+ }),+ })+ );+ assert.equal(createdRes.status, 201);+ const created = await createdRes.json();++ const defaultListRes = await proxyV1Route.GET(+ new Request("http://localhost/api/v1/management/proxies")+ );+ assert.equal(defaultListRes.status, 200);+ const defaultListBody = await defaultListRes.json();+ assert.equal(defaultListBody.page.limit, 50);+ assert.equal(defaultListBody.page.offset, 0);+ assert.equal(defaultListBody.items.length, 1);++ const byIdRes = await proxyV1Route.GET(+ new Request(`http://localhost/api/v1/management/proxies?id=${created.id}`)+ );+ assert.equal(byIdRes.status, 200);+ const byIdBody = await byIdRes.json();+ assert.equal(byIdBody.id, created.id);++ const assignRes = await proxyAssignmentsV1Route.PUT(+ new Request("http://localhost/api/v1/management/proxies/assignments", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ scope: "account",+ scopeId: providerConn.id,+ proxyId: created.id,+ }),+ })+ );+ assert.equal(assignRes.status, 200);++ const whereUsedRes = await proxyV1Route.GET(+ new Request(`http://localhost/api/v1/management/proxies?id=${created.id}&where_used=1`)+ );+ assert.equal(whereUsedRes.status, 200);+ const whereUsedBody = await whereUsedRes.json();+ assert.equal(whereUsedBody.count, 1);+ assert.equal(whereUsedBody.assignments[0].scopeId, providerConn.id);++ const missingGetRes = await proxyV1Route.GET(+ new Request("http://localhost/api/v1/management/proxies?id=missing-proxy")+ );+ assert.equal(missingGetRes.status, 404);++ const updatedRes = await proxyV1Route.PATCH(+ new Request("http://localhost/api/v1/management/proxies", {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ id: created.id,+ host: "updated.local",+ port: 9090,+ notes: "updated via patch",+ }),+ })+ );+ assert.equal(updatedRes.status, 200);+ const updatedBody = await updatedRes.json();+ assert.equal(updatedBody.host, "updated.local");+ assert.equal(updatedBody.port, 9090);++ const missingPatchRes = await proxyV1Route.PATCH(+ new Request("http://localhost/api/v1/management/proxies", {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ id: "missing-proxy",+ notes: "not found",+ }),+ })+ );+ assert.equal(missingPatchRes.status, 404);++ const missingIdDeleteRes = await proxyV1Route.DELETE(+ new Request("http://localhost/api/v1/management/proxies", {+ method: "DELETE",+ })+ );+ assert.equal(missingIdDeleteRes.status, 400);++ const missingDeleteRes = await proxyV1Route.DELETE(+ new Request("http://localhost/api/v1/management/proxies?id=missing-proxy", {+ method: "DELETE",+ })+ );+ assert.equal(missingDeleteRes.status, 404);++ const inUseDeleteRes = await proxyV1Route.DELETE(+ new Request(`http://localhost/api/v1/management/proxies?id=${created.id}`, {+ method: "DELETE",+ })+ );+ assert.equal(inUseDeleteRes.status, 409);+ const inUseDeleteBody = await inUseDeleteRes.json();+ assert.match(inUseDeleteBody.error.message, /remove assignments first/i);++ const forceDeleteRes = await proxyV1Route.DELETE(+ new Request(`http://localhost/api/v1/management/proxies?id=${created.id}&force=1`, {+ method: "DELETE",+ })+ );+ assert.equal(forceDeleteRes.status, 200);+ assert.deepEqual(await forceDeleteRes.json(), { success: true });+});++test("v1 management proxies main route validates malformed and invalid payloads", async () => {+ await resetStorage();++ const invalidPostJsonRes = await proxyV1Route.POST(+ new Request("http://localhost/api/v1/management/proxies", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: "{",+ })+ );+ assert.equal(invalidPostJsonRes.status, 400);++ const invalidPostBodyRes = await proxyV1Route.POST(+ new Request("http://localhost/api/v1/management/proxies", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ name: "Missing Host",+ type: "http",+ port: 8080,+ }),+ })+ );+ assert.equal(invalidPostBodyRes.status, 400);++ const invalidPatchJsonRes = await proxyV1Route.PATCH(+ new Request("http://localhost/api/v1/management/proxies", {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: "{",+ })+ );+ assert.equal(invalidPatchJsonRes.status, 400);++ const invalidPatchBodyRes = await proxyV1Route.PATCH(+ new Request("http://localhost/api/v1/management/proxies", {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ id: "",+ port: 70000,+ }),+ })+ );+ assert.equal(invalidPatchBodyRes.status, 400);+});++test("v1 management proxies main route returns server errors when persistence fails", async () => {+ await resetStorage();++ await withPrepareFailure(+ "ORDER BY datetime(updated_at) DESC, name ASC",+ "list proxy failure",+ async () => {+ const response = await proxyV1Route.GET(+ new Request("http://localhost/api/v1/management/proxies")+ );+ assert.equal(response.status, 500);+ assert.match((await response.json()).error.message, /list proxy failure/i);+ }+ );++ await withPrepareFailure("INSERT INTO proxy_registry", "create proxy failure", async () => {+ const response = await proxyV1Route.POST(+ new Request("http://localhost/api/v1/management/proxies", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ name: "Broken Create",+ type: "http",+ host: "broken-create.local",+ port: 8080,+ }),+ })+ );+ assert.equal(response.status, 500);+ assert.match((await response.json()).error.message, /create proxy failure/i);+ });++ const createdRes = await proxyV1Route.POST(+ new Request("http://localhost/api/v1/management/proxies", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ name: "Broken Update",+ type: "http",+ host: "broken-update.local",+ port: 8081,+ }),+ })+ );+ assert.equal(createdRes.status, 201);+ const created = await createdRes.json();++ await withPrepareFailure("UPDATE proxy_registry", "update proxy failure", async () => {+ const response = await proxyV1Route.PATCH(+ new Request("http://localhost/api/v1/management/proxies", {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ id: created.id,+ notes: "should fail",+ }),+ })+ );+ assert.equal(response.status, 500);+ assert.match((await response.json()).error.message, /update proxy failure/i);+ });++ await withPrepareFailure("DELETE FROM proxy_registry", "delete proxy failure", async () => {+ const response = await proxyV1Route.DELETE(+ new Request(`http://localhost/api/v1/management/proxies?id=${created.id}`, {+ method: "DELETE",+ })+ );+ assert.equal(response.status, 500);+ assert.match((await response.json()).error.message, /delete proxy failure/i);+ });+});+test("v1 management assignments supports put and filtered get", async () => {await resetStorage();@@ -136,6 +445,82 @@ test("v1 management assignments supports put and filtered get", async () => {assert.equal(payload.items[0].proxyId, created.id);});+test("v1 management assignments covers unfiltered listing and error branches", async () => {+ await resetStorage();++ const listRes = await proxyAssignmentsV1Route.GET(+ new Request("http://localhost/api/v1/management/proxies/assignments?limit=5&offset=0")+ );+ assert.equal(listRes.status, 200);+ const listPayload = await listRes.json();+ assert.deepEqual(listPayload.items, []);+ assert.equal(listPayload.page.limit, 5);+ assert.equal(listPayload.page.offset, 0);+ assert.equal(listPayload.page.total, 0);++ await withPrepareFailure(+ "FROM proxy_assignments ORDER BY scope, scope_id",+ "assignment list failure",+ async () => {+ const response = await proxyAssignmentsV1Route.GET(+ new Request("http://localhost/api/v1/management/proxies/assignments")+ );+ assert.equal(response.status, 500);+ assert.match((await response.json()).error.message, /assignment list failure/i);+ }+ );++ const invalidJsonRes = await proxyAssignmentsV1Route.PUT(+ new Request("http://localhost/api/v1/management/proxies/assignments", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: "{",+ })+ );+ assert.equal(invalidJsonRes.status, 400);+ assert.match((await invalidJsonRes.json()).error.message, /invalid json body/i);++ const invalidPayloadRes = await proxyAssignmentsV1Route.PUT(+ new Request("http://localhost/api/v1/management/proxies/assignments", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ scope: "account",+ }),+ })+ );+ assert.equal(invalidPayloadRes.status, 400);+ const invalidPayloadBody = await invalidPayloadRes.json();+ assert.equal(invalidPayloadBody.error.type, "invalid_request");+ assert.equal(Array.isArray(invalidPayloadBody.error.details), true);++ const clearGlobalRes = await proxyAssignmentsV1Route.PUT(+ new Request("http://localhost/api/v1/management/proxies/assignments", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ scope: "global",+ proxyId: null,+ }),+ })+ );+ assert.equal(clearGlobalRes.status, 200);+ assert.deepEqual(await clearGlobalRes.json(), { success: true, assignment: null });++ const missingProxyRes = await proxyAssignmentsV1Route.PUT(+ new Request("http://localhost/api/v1/management/proxies/assignments", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ scope: "global",+ proxyId: "missing-proxy",+ }),+ })+ );+ assert.equal(missingProxyRes.status, 404);+ assert.match((await missingProxyRes.json()).error.message, /proxy not found/i);+});+test("v1 management health endpoint aggregates proxy log metrics", async () => {await resetStorage();@@ -181,6 +566,40 @@ test("v1 management health endpoint aggregates proxy log metrics", async () => {assert.equal(row.errorCount >= 1, true);});+test("v1 management health endpoint covers default window and error handling", async () => {+ await resetStorage();++ const createdRes = await proxyV1Route.POST(+ new Request("http://localhost/api/v1/management/proxies", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ name: "Proxy Health Default",+ type: "http",+ host: "health-default.local",+ port: 8080,+ }),+ })+ );+ assert.equal(createdRes.status, 201);++ const defaultRes = await proxyHealthV1Route.GET(+ new Request("http://localhost/api/v1/management/proxies/health")+ );+ assert.equal(defaultRes.status, 200);+ const defaultBody = await defaultRes.json();+ assert.equal(defaultBody.windowHours, 24);+ assert.equal(defaultBody.total, 1);++ await withPrepareFailure("FROM proxy_registry p", "proxy health failure", async () => {+ const errorRes = await proxyHealthV1Route.GET(+ new Request("http://localhost/api/v1/management/proxies/health")+ );+ assert.equal(errorRes.status, 500);+ assert.match((await errorRes.json()).error.message, /proxy health failure/i);+ });+});+test("v1 bulk assignment updates multiple scope IDs in one request", async () => {await resetStorage();diff --git a/tests/unit/route-edge-coverage.test.mjs b/tests/unit/route-edge-coverage.test.mjsindex 7f68b5bd88..2e962c2bb2 100644--- a/tests/unit/route-edge-coverage.test.mjs+++ b/tests/unit/route-edge-coverage.test.mjs@@ -80,6 +80,47 @@ async function seedOpenAIConnection({});}+async function withPrepareFailure(match, message, fn) {+ const db = core.getDbInstance();+ const originalPrepare = db.prepare.bind(db);++ db.prepare = (sql, ...args) => {+ const sqlText = String(sql);+ const matched = typeof match === "function" ? match(sqlText) : sqlText.includes(match);+ if (matched) {+ throw new Error(message);+ }+ return originalPrepare(sql, ...args);+ };++ try {+ return await fn();+ } finally {+ db.prepare = originalPrepare;+ }+}++async function withPrepareOverride(match, override, fn) {+ const db = core.getDbInstance();+ const originalPrepare = db.prepare.bind(db);++ db.prepare = (sql, ...args) => {+ const sqlText = String(sql);+ const matched = typeof match === "function" ? match(sqlText) : sqlText.includes(match);+ const statement = originalPrepare(sql, ...args);+ if (!matched) {+ return statement;+ }+ return override({ sqlText, statement, args });+ };++ try {+ return await fn();+ } finally {+ db.prepare = originalPrepare;+ }+}+test.beforeEach(async () => {await resetStorage();});@@ -347,6 +388,118 @@ test("settings proxy route prefers proxy registry assignments and enforces socksassert.equal(enabledSocksBody.global.type, "socks5");});+test("settings proxy route covers default types, null maps, registry fallback, and server-error branches", async () => {+ const defaultTypePut = await settingsProxyRoute.PUT(+ makeRequest("http://localhost/api/settings/proxy", {+ method: "PUT",+ body: {+ level: "global",+ proxy: { host: "default-type.local", port: "8088" },+ },+ })+ );+ assert.equal(defaultTypePut.status, 200);+ const defaultTypeBody = await defaultTypePut.json();+ assert.equal(defaultTypeBody.global.type, "http");++ const clearMapPut = await settingsProxyRoute.PUT(+ makeRequest("http://localhost/api/settings/proxy", {+ method: "PUT",+ body: {+ global: null,+ providers: { openai: null },+ },+ })+ );+ assert.equal(clearMapPut.status, 200);+ const clearMapBody = await clearMapPut.json();+ assert.equal(clearMapBody.global, null);+ assert.equal(Object.prototype.hasOwnProperty.call(clearMapBody.providers || {}, "openai"), false);++ await settingsProxyRoute.PUT(+ makeRequest("http://localhost/api/settings/proxy", {+ method: "PUT",+ body: {+ level: "global",+ proxy: { type: "https", host: "legacy-fallback.local", port: "9443" },+ },+ })+ );++ const missingRegistryProxy = await localDb.createProxy({+ name: "Missing Registry Proxy",+ type: "http",+ host: "missing-registry.local",+ port: 8080,+ });+ await localDb.assignProxyToScope("global", null, missingRegistryProxy.id);++ await withPrepareOverride(+ "FROM proxy_registry WHERE id = ?",+ ({ statement }) => ({+ ...statement,+ get() {+ return undefined;+ },+ }),+ async () => {+ const response = await settingsProxyRoute.GET(+ new Request("http://localhost/api/settings/proxy?level=global")+ );+ assert.equal(response.status, 200);+ const body = await response.json();+ assert.equal(body.level, "global");+ assert.equal(body.proxy.host, "legacy-fallback.local");+ }+ );++ await withPrepareFailure(+ "SELECT key, value FROM key_value WHERE namespace = 'proxyConfig'",+ "proxy config read failure",+ async () => {+ const response = await settingsProxyRoute.GET(+ new Request("http://localhost/api/settings/proxy")+ );+ assert.equal(response.status, 500);+ assert.match((await response.json()).error.message, /proxy config read failure/i);+ }+ );++ await withPrepareFailure(+ "INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES ('proxyConfig', 'global', ?)",+ "proxy config write failure",+ async () => {+ const response = await settingsProxyRoute.PUT(+ makeRequest("http://localhost/api/settings/proxy", {+ method: "PUT",+ body: {+ level: "global",+ proxy: { host: "broken-write.local", port: "8080" },+ },+ })+ );+ assert.equal(response.status, 500);+ const body = await response.json();+ assert.equal(body.error.type, "server_error");+ assert.match(body.error.message, /proxy config write failure/i);+ }+ );++ await withPrepareFailure(+ "INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES ('proxyConfig', 'global', ?)",+ "proxy config delete failure",+ async () => {+ const response = await settingsProxyRoute.DELETE(+ new Request("http://localhost/api/settings/proxy?level=global", {+ method: "DELETE",+ })+ );+ assert.equal(response.status, 500);+ assert.match((await response.json()).error.message, /proxy config delete failure/i);+ }+ );+});+test("management proxies route covers auth, pagination, lookup, where-used, patch and delete flows", async () => {await enableManagementAuth();const managementKey = await createManagementKey();@@ -598,3 +751,336 @@ test("embeddings route enforces caller auth, missing credentials and provider raassert.equal(allRateLimited.status, 429);assert.match(allRateLimitedBody.error.message, /All accounts rate limited/);});++test("embeddings route tolerates custom-model and provider-node lookup failures", async () => {+ await seedOpenAIConnection();++ const originalFetch = globalThis.fetch;+ globalThis.fetch = async () =>+ Response.json({+ data: [{ object: "embedding", index: 0, embedding: [0.1, 0.2] }],+ usage: { prompt_tokens: 3, total_tokens: 3 },+ });++ try {+ await withPrepareFailure(+ "SELECT key, value FROM key_value WHERE namespace = 'customModels'",+ "custom models unavailable",+ async () => {+ const response = await embeddingsRoute.GET();+ const body = await response.json();++ assert.equal(response.status, 200);+ assert.ok(body.data.some((model) => model.id === "openai/text-embedding-3-small"));+ }+ );++ await withPrepareFailure(+ "SELECT * FROM provider_nodes",+ "provider nodes unavailable",+ async () => {+ const response = await embeddingsRoute.POST(+ makeRequest("http://localhost/v1/embeddings", {+ method: "POST",+ body: { model: "openai/text-embedding-3-small", input: "hello" },+ })+ );+ const body = await response.json();++ assert.equal(response.status, 200);+ assert.equal(body.model, "openai/text-embedding-3-small");+ }+ );+ } finally {+ globalThis.fetch = originalFetch;+ }+});++test("embeddings route supports local provider nodes without credentials and enforces model policy", async () => {+ await providersDb.createProviderNode({+ id: "local-embed-node",+ type: "openai-compatible",+ name: "Local Embed Node",+ prefix: "localembed",+ apiType: "chat",+ baseUrl: "http://localhost:7788/v1",+ });++ const localFetchCalls = [];+ const originalFetch = globalThis.fetch;+ globalThis.fetch = async (url, init = {}) => {+ localFetchCalls.push({+ url: String(url),+ headers: init.headers,+ body: JSON.parse(String(init.body)),+ });+ return Response.json({+ data: [{ object: "embedding", index: 0, embedding: [0.9, 0.1] }],+ usage: { prompt_tokens: 2, total_tokens: 2 },+ });+ };++ try {+ const localResponse = await embeddingsRoute.POST(+ makeRequest("http://localhost/v1/embeddings", {+ method: "POST",+ body: {+ model: "localembed/demo-embed",+ input: "hello",+ user: "user-123",+ },+ })+ );+ const localBody = await localResponse.json();++ assert.equal(localResponse.status, 200);+ assert.equal(localBody.model, "localembed/demo-embed");+ assert.equal(localFetchCalls.length, 1);+ assert.equal(localFetchCalls[0].url, "http://localhost:7788/v1/embeddings");+ assert.equal(localFetchCalls[0].headers.Authorization, undefined);+ assert.equal(localFetchCalls[0].body.model, "demo-embed");+ assert.equal(localFetchCalls[0].body.user, "user-123");++ process.env.REQUIRE_API_KEY = "true";+ const restrictedKey = await apiKeysDb.createApiKey("embeddings-policy", MACHINE_ID);+ await apiKeysDb.updateApiKeyPermissions(restrictedKey.id, {+ allowedModels: ["openai/text-embedding-ada-002"],+ });++ const rejected = await embeddingsRoute.POST(+ new Request("http://localhost/v1/embeddings", {+ method: "POST",+ headers: {+ "content-type": "application/json",+ authorization: `Bearer ${restrictedKey.key}`,+ },+ body: JSON.stringify({+ model: "openai/text-embedding-3-small",+ input: "hello",+ }),+ })+ );+ const rejectedBody = await rejected.json();++ assert.equal(rejected.status, 403);+ assert.match(rejectedBody.error.message, /not allowed/i);+ } finally {+ globalThis.fetch = originalFetch;+ }+});++test("embeddings route returns normalized upstream failures", async () => {+ await seedOpenAIConnection();++ const originalFetch = globalThis.fetch;+ globalThis.fetch = async () => new Response("upstream boom", { status: 502 });++ try {+ const response = await embeddingsRoute.POST(+ makeRequest("http://localhost/v1/embeddings", {+ method: "POST",+ body: { model: "openai/text-embedding-3-small", input: "hello" },+ })+ );+ const body = await response.json();++ assert.equal(response.status, 502);+ assert.equal(body.error.message, "upstream boom");+ assert.equal(body.error.type, "upstream_error");+ } finally {+ globalThis.fetch = originalFetch;+ }+});++test("embeddings route GET skips malformed, non-embedding, and duplicate custom model rows", async () => {+ await modelsDb.addCustomModel(+ "openai",+ "text-embedding-3-small",+ "Duplicate OpenAI Embed",+ "manual",+ "responses",+ ["embeddings"]+ );++ const db = core.getDbInstance();+ db.prepare(+ "INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES ('customModels', ?, ?)"+ ).run("broken-embed-provider", JSON.stringify({ invalid: true }));+ db.prepare(+ "INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES ('customModels', ?, ?)"+ ).run(+ "mixed-embed-provider",+ JSON.stringify([+ { name: "Missing Id", supportedEndpoints: ["embeddings"] },+ { id: "chat-only", supportedEndpoints: ["chat"] },+ { id: "edge-embed", supportedEndpoints: ["embeddings"] },+ ])+ );++ const response = await embeddingsRoute.GET();+ const body = await response.json();+ const ids = body.data.map((model) => model.id);++ assert.equal(response.status, 200);+ assert.equal(ids.filter((id) => id === "openai/text-embedding-3-small").length, 1);+ assert.ok(ids.includes("mixed-embed-provider/edge-embed"));+ assert.equal(ids.includes("mixed-embed-provider/chat-only"), false);+ assert.equal(ids.includes("broken-embed-provider/edge-embed"), false);+});++test("embeddings route tolerates non-array provider nodes and remote fallback lookup errors", async () => {+ await seedOpenAIConnection();++ const originalFetch = globalThis.fetch;+ globalThis.fetch = async () =>+ Response.json({+ data: [{ object: "embedding", index: 0, embedding: [0.3, 0.4] }],+ usage: { prompt_tokens: 2, total_tokens: 2 },+ });++ try {+ await withPrepareOverride(+ "SELECT * FROM provider_nodes",+ ({ statement }) =>+ new Proxy(statement, {+ get(target, prop, receiver) {+ if (prop === "all") {+ return () => ({ broken: true });+ }+ return Reflect.get(target, prop, receiver);+ },+ }),+ async () => {+ const response = await embeddingsRoute.POST(+ makeRequest("http://localhost/v1/embeddings", {+ method: "POST",+ body: { model: "openai/text-embedding-3-small", input: "hello" },+ })+ );+ assert.equal(response.status, 200);+ }+ );++ let providerNodeSelects = 0;+ const remoteFallback = await withPrepareOverride(+ "SELECT * FROM provider_nodes",+ ({ statement }) =>+ new Proxy(statement, {+ get(target, prop, receiver) {+ if (prop === "all") {+ return (...args) => {+ providerNodeSelects++;+ if (providerNodeSelects === 1) {+ return [];+ }+ throw new Error("remote provider node lookup failed");+ };+ }+ return Reflect.get(target, prop, receiver);+ },+ }),+ async () =>+ embeddingsRoute.POST(+ makeRequest("http://localhost/v1/embeddings", {+ method: "POST",+ body: { model: "remote/demo-embed", input: "hello" },+ })+ )+ );+ const remoteFallbackBody = await remoteFallback.json();++ assert.equal(remoteFallback.status, 400);+ assert.match(remoteFallbackBody.error.message, /Unknown embedding provider|No matching/i);+ } finally {+ globalThis.fetch = originalFetch;+ }+});++test("embeddings route handles responses provider nodes, invalid local nodes, and id-less remote fallback", async () => {+ await providersDb.createProviderNode({+ type: "openai-compatible",+ name: "Local Responses Embed Node",+ prefix: "localresponses",+ apiType: "responses",+ baseUrl: "http://localhost:7790/v1",+ });+ await providersDb.createProviderNode({+ type: "openai-compatible",+ name: "Invalid URL Node",+ prefix: "badurl",+ apiType: "chat",+ baseUrl: "not a valid url",+ });+ await providersDb.createProviderNode({+ type: "openai-compatible",+ name: "Invalid Prefix Node",+ prefix: "bad/prefix",+ apiType: "chat",+ baseUrl: "http://localhost:7791/v1",+ });+ await providersDb.createProviderConnection({+ provider: "remoteprefix",+ authType: "apikey",+ name: "remoteprefix-key",+ apiKey: "sk-remoteprefix",+ });++ const originalFetch = globalThis.fetch;+ const fetchCalls = [];+ globalThis.fetch = async (url, init = {}) => {+ fetchCalls.push({+ url: String(url),+ headers: init.headers,+ body: JSON.parse(String(init.body)),+ });+ return Response.json({+ data: [{ object: "embedding", index: 0, embedding: [0.7, 0.8] }],+ usage: { prompt_tokens: 4, total_tokens: 4 },+ });+ };++ try {+ const localResponse = await embeddingsRoute.POST(+ makeRequest("http://localhost/v1/embeddings", {+ method: "POST",+ body: { model: "localresponses/demo-embed", input: "hello" },+ })+ );+ assert.equal(localResponse.status, 200);+ assert.equal(fetchCalls[0].url, "http://localhost:7790/v1/embeddings");++ const remoteResponse = await withPrepareOverride(+ "SELECT * FROM provider_nodes",+ ({ statement }) =>+ new Proxy(statement, {+ get(target, prop, receiver) {+ if (prop === "all") {+ return () => [+ {+ prefix: "remoteprefix",+ apiType: "responses",+ baseUrl: "https://remote.example.com/v1beta/openai",+ },+ ];+ }+ return Reflect.get(target, prop, receiver);+ },+ }),+ async () =>+ embeddingsRoute.POST(+ makeRequest("http://localhost/v1/embeddings", {+ method: "POST",+ body: { model: "remoteprefix/demo-embed", input: "hello" },+ })+ )+ );+ const remoteBody = await remoteResponse.json();++ assert.equal(remoteResponse.status, 200);+ assert.equal(fetchCalls[1].url, "https://remote.example.com/v1beta/openai/embeddings");+ assert.equal(fetchCalls[1].headers.Authorization, "Bearer sk-remoteprefix");+ assert.equal(remoteBody.model, "remoteprefix/demo-embed");+ } finally {+ globalThis.fetch = originalFetch;+ }+});diff --git a/tests/unit/sse-auth.test.mjs b/tests/unit/sse-auth.test.mjsindex 5f1b13e23a..d451c1cd7b 100644--- a/tests/unit/sse-auth.test.mjs+++ b/tests/unit/sse-auth.test.mjs@@ -518,14 +518,14 @@ test("getProviderCredentials least-used prefers the oldest timestamp when all actest("getProviderCredentials cost-optimized selects the lowest priority account", async () => {await settingsDb.updateSettings({ fallbackStrategy: "cost-optimized" });- await seedConnection("openai", {- name: "cost-high",- priority: 8,- });const cheapest = await seedConnection("openai", {name: "cost-low",priority: 1,});+ await seedConnection("openai", {+ name: "cost-high",+ priority: 8,+ });const selected = await auth.getProviderCredentials("openai");diff --git a/tests/unit/usage-migrations.test.mjs b/tests/unit/usage-migrations.test.mjsnew file mode 100644index 0000000000..48d577da41--- /dev/null+++ b/tests/unit/usage-migrations.test.mjs@@ -0,0 +1,347 @@+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 ORIGINAL_HOME = process.env.HOME;+const ORIGINAL_DATA_DIR = process.env.DATA_DIR;+const ORIGINAL_NEXT_PHASE = process.env.NEXT_PHASE;++const TEST_HOME_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-usage-migrations-home-"));+const TEST_DATA_DIR = path.join(TEST_HOME_DIR, "data");++process.env.HOME = TEST_HOME_DIR;+process.env.DATA_DIR = TEST_DATA_DIR;+delete process.env.NEXT_PHASE;++const migrations = await import("../../src/lib/usage/migrations.ts");+const { getDbInstance } = await import("../../src/lib/db/core.ts");++const LEGACY_DATA_DIR = path.join(TEST_HOME_DIR, ".omniroute");+const LEGACY_USAGE_JSON_FILE = path.join(LEGACY_DATA_DIR, "usage.json");+const LEGACY_CALL_LOGS_JSON_FILE = path.join(LEGACY_DATA_DIR, "call_logs.json");+const USAGE_JSON_FILE = path.join(TEST_DATA_DIR, "usage.json");+const CALL_LOGS_JSON_FILE = path.join(TEST_DATA_DIR, "call_logs.json");+const CURRENT_REQUEST_LOGS_DIR = path.join(TEST_DATA_DIR, "logs");+const CURRENT_REQUEST_SUMMARY_FILE = path.join(TEST_DATA_DIR, "log.txt");+const MARKER_PATH = migrations.LOG_ARCHIVES_DIR+ ? path.join(migrations.LOG_ARCHIVES_DIR, "legacy-request-logs.json")+ : null;++function writeJson(filePath, value) {+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, JSON.stringify(value, null, 2));+}++function removePath(targetPath) {+ if (!targetPath) return;+ fs.rmSync(targetPath, { recursive: true, force: true });+}++function resetDbTables() {+ const db = getDbInstance();+ db.prepare("DELETE FROM usage_history").run();+ db.prepare("DELETE FROM call_logs").run();+}++function readJson(filePath) {+ return JSON.parse(fs.readFileSync(filePath, "utf8"));+}++function seedLegacyRequestTargets() {+ fs.mkdirSync(CURRENT_REQUEST_LOGS_DIR, { recursive: true });+ fs.writeFileSync(path.join(CURRENT_REQUEST_LOGS_DIR, "placeholder.txt"), "legacy");+ fs.writeFileSync(CURRENT_REQUEST_SUMMARY_FILE, "legacy summary\n");+}++test.beforeEach(() => {+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });+ removePath(LEGACY_DATA_DIR);+ removePath(USAGE_JSON_FILE);+ removePath(`${USAGE_JSON_FILE}.migrated`);+ removePath(CALL_LOGS_JSON_FILE);+ removePath(`${CALL_LOGS_JSON_FILE}.migrated`);+ removePath(CURRENT_REQUEST_LOGS_DIR);+ removePath(CURRENT_REQUEST_SUMMARY_FILE);+ removePath(migrations.CALL_LOGS_DIR);+ removePath(migrations.LOG_ARCHIVES_DIR);+ resetDbTables();+});++test.after(() => {+ try {+ const db = getDbInstance();+ if (db?.open) db.close();+ } catch {+ // Database may already be closed.+ }++ if (ORIGINAL_HOME === undefined) {+ delete process.env.HOME;+ } else {+ process.env.HOME = ORIGINAL_HOME;+ }++ if (ORIGINAL_DATA_DIR === undefined) {+ delete process.env.DATA_DIR;+ } else {+ process.env.DATA_DIR = ORIGINAL_DATA_DIR;+ }++ if (ORIGINAL_NEXT_PHASE === undefined) {+ delete process.env.NEXT_PHASE;+ } else {+ process.env.NEXT_PHASE = ORIGINAL_NEXT_PHASE;+ }++ removePath(TEST_HOME_DIR);+});++test("archiveLegacyRequestLogs returns null when there are no targets or the marker already exists", async () => {+ assert.equal(await migrations.archiveLegacyRequestLogs(), null);++ seedLegacyRequestTargets();+ assert.ok(MARKER_PATH, "marker path should exist in local test mode");+ fs.mkdirSync(path.dirname(MARKER_PATH), { recursive: true });+ fs.writeFileSync(MARKER_PATH, JSON.stringify({ archiveFilename: "done.zip" }, null, 2));++ assert.equal(await migrations.archiveLegacyRequestLogs(), null);+ assert.equal(fs.existsSync(CURRENT_REQUEST_LOGS_DIR), true);+ assert.equal(fs.existsSync(CURRENT_REQUEST_SUMMARY_FILE), true);+});++test("migrateLegacyUsageFiles copies legacy JSON files once and does not overwrite existing targets", () => {+ writeJson(LEGACY_USAGE_JSON_FILE, { history: [{ provider: "legacy-openai" }] });+ writeJson(LEGACY_CALL_LOGS_JSON_FILE, { logs: [{ id: "legacy-call" }] });++ migrations.migrateLegacyUsageFiles();++ assert.deepEqual(readJson(USAGE_JSON_FILE), { history: [{ provider: "legacy-openai" }] });+ assert.deepEqual(readJson(CALL_LOGS_JSON_FILE), { logs: [{ id: "legacy-call" }] });++ writeJson(USAGE_JSON_FILE, { history: [{ provider: "current-openai" }] });+ writeJson(CALL_LOGS_JSON_FILE, { logs: [{ id: "current-call" }] });+ writeJson(LEGACY_USAGE_JSON_FILE, { history: [{ provider: "legacy-should-not-win" }] });+ writeJson(LEGACY_CALL_LOGS_JSON_FILE, { logs: [{ id: "legacy-should-not-win" }] });++ migrations.migrateLegacyUsageFiles();++ assert.deepEqual(readJson(USAGE_JSON_FILE), { history: [{ provider: "current-openai" }] });+ assert.deepEqual(readJson(CALL_LOGS_JSON_FILE), { logs: [{ id: "current-call" }] });+});++test("migrateUsageJsonToSqlite migrates usage history aliases and TTFT fallbacks", () => {+ writeJson(USAGE_JSON_FILE, {+ history: [+ {+ provider: "openai",+ model: "gpt-4o-mini",+ connectionId: "conn-openai",+ apiKeyId: "key-1",+ apiKeyName: "Primary Key",+ tokens: {+ prompt_tokens: 11,+ completion_tokens: 7,+ cached_tokens: 2,+ cache_creation_input_tokens: 3,+ reasoning_tokens: 5,+ },+ status: "error",+ success: false,+ latencyMs: "17",+ errorCode: "timeout",+ timestamp: "2026-01-01T00:00:00.000Z",+ },+ {+ provider: "gemini",+ model: "gemini-2.5-flash",+ tokens: {+ input: 9,+ output: 4,+ cacheRead: 1,+ cacheCreation: 2,+ reasoning: 3,+ },+ latencyMs: "99",+ timeToFirstTokenMs: "13",+ timestamp: "2026-01-02T00:00:00.000Z",+ },+ ],+ });++ migrations.migrateUsageJsonToSqlite();++ assert.equal(fs.existsSync(`${USAGE_JSON_FILE}.migrated`), true);++ const db = getDbInstance();+ const rows = db+ .prepare(+ `+ SELECT provider, model, connection_id, api_key_id, api_key_name,+ tokens_input, tokens_output, tokens_cache_read, tokens_cache_creation,+ tokens_reasoning, status, success, latency_ms, ttft_ms, error_code+ FROM usage_history+ ORDER BY timestamp ASC+ `+ )+ .all();++ assert.deepEqual(rows, [+ {+ provider: "openai",+ model: "gpt-4o-mini",+ connection_id: "conn-openai",+ api_key_id: "key-1",+ api_key_name: "Primary Key",+ tokens_input: 11,+ tokens_output: 7,+ tokens_cache_read: 2,+ tokens_cache_creation: 3,+ tokens_reasoning: 5,+ status: "error",+ success: 0,+ latency_ms: 17,+ ttft_ms: 17,+ error_code: "timeout",+ },+ {+ provider: "gemini",+ model: "gemini-2.5-flash",+ connection_id: null,+ api_key_id: null,+ api_key_name: null,+ tokens_input: 9,+ tokens_output: 4,+ tokens_cache_read: 1,+ tokens_cache_creation: 2,+ tokens_reasoning: 3,+ status: null,+ success: 1,+ latency_ms: 99,+ ttft_ms: 13,+ error_code: null,+ },+ ]);+});++test("migrateUsageJsonToSqlite migrates call logs, serializes payloads, and ignores duplicate ids", () => {+ writeJson(CALL_LOGS_JSON_FILE, {+ logs: [+ {+ id: "call-1",+ timestamp: "2026-02-01T00:00:00.000Z",+ method: "GET",+ path: "/v1/chat/completions",+ status: 201,+ model: "gpt-4o-mini",+ provider: "openai",+ account: "acct-a",+ connectionId: "conn-a",+ duration: 31,+ tokens: { in: 12, out: 8 },+ sourceFormat: "openai",+ targetFormat: "openai",+ apiKeyId: "key-a",+ apiKeyName: "Key A",+ comboName: "combo-a",+ requestBody: { messages: [{ role: "user", content: "hi" }] },+ responseBody: { id: "resp-1" },+ error: "bad upstream",+ },+ {+ id: "call-1",+ timestamp: "2026-02-01T01:00:00.000Z",+ method: "PATCH",+ path: "/should-be-ignored",+ },+ {+ timestamp: "2026-02-02T00:00:00.000Z",+ requestBody: { foo: "bar" },+ },+ ],+ });++ migrations.migrateUsageJsonToSqlite();++ assert.equal(fs.existsSync(`${CALL_LOGS_JSON_FILE}.migrated`), true);++ const db = getDbInstance();+ const rows = db+ .prepare(+ `+ SELECT id, method, path, status, provider, account, connection_id,+ request_body, response_body, error+ FROM call_logs+ ORDER BY timestamp ASC+ `+ )+ .all();++ assert.equal(rows.length, 2);+ assert.deepEqual(rows[0], {+ id: "call-1",+ method: "GET",+ path: "/v1/chat/completions",+ status: 201,+ provider: "openai",+ account: "acct-a",+ connection_id: "conn-a",+ request_body: JSON.stringify({ messages: [{ role: "user", content: "hi" }] }),+ response_body: JSON.stringify({ id: "resp-1" }),+ error: "bad upstream",+ });+ assert.equal(rows[1].id.length > 0, true);+ assert.equal(rows[1].method, "POST");+ assert.equal(rows[1].path, null);+ assert.equal(rows[1].status, 0);+ assert.equal(rows[1].provider, null);+ assert.equal(rows[1].account, null);+ assert.equal(rows[1].connection_id, null);+ assert.deepEqual(JSON.parse(rows[1].request_body), { foo: "bar" });+ assert.equal(rows[1].response_body, null);+ assert.equal(rows[1].error, null);+});++test("migrateUsageJsonToSqlite renames empty JSON payloads without inserting rows", () => {+ writeJson(USAGE_JSON_FILE, { history: [] });+ writeJson(CALL_LOGS_JSON_FILE, { logs: [] });++ migrations.migrateUsageJsonToSqlite();++ assert.equal(fs.existsSync(`${USAGE_JSON_FILE}.migrated`), true);+ assert.equal(fs.existsSync(`${CALL_LOGS_JSON_FILE}.migrated`), true);++ const db = getDbInstance();+ assert.equal(db.prepare("SELECT COUNT(*) AS count FROM usage_history").get().count, 0);+ assert.equal(db.prepare("SELECT COUNT(*) AS count FROM call_logs").get().count, 0);+});++test("migrateUsageJsonToSqlite leaves malformed JSON files in place and reports both failures", () => {+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });+ fs.writeFileSync(USAGE_JSON_FILE, "{bad json");+ fs.writeFileSync(CALL_LOGS_JSON_FILE, "{bad json");++ const errors = [];+ const originalConsoleError = console.error;+ console.error = (...args) => {+ errors.push(args.map(String).join(" "));+ };++ try {+ migrations.migrateUsageJsonToSqlite();+ } finally {+ console.error = originalConsoleError;+ }++ assert.equal(fs.existsSync(USAGE_JSON_FILE), true);+ assert.equal(fs.existsSync(`${USAGE_JSON_FILE}.migrated`), false);+ assert.equal(fs.existsSync(CALL_LOGS_JSON_FILE), true);+ assert.equal(fs.existsSync(`${CALL_LOGS_JSON_FILE}.migrated`), false);++ const db = getDbInstance();+ assert.equal(db.prepare("SELECT COUNT(*) AS count FROM usage_history").get().count, 0);+ assert.equal(db.prepare("SELECT COUNT(*) AS count FROM call_logs").get().count, 0);+ assert.ok(errors.some((entry) => entry.includes("Failed to migrate usage.json")));+ assert.ok(errors.some((entry) => entry.includes("Failed to migrate call_logs.json")));+});