Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

Merge branch 'release/v3.8.8' into feat/quota-share-redesign

diegosouzapw58a7d97b3fd7
diff --cc open-sse/mcp-server/server.ts
index 25d7a93394,64d3ed9fb8..dc3d23d835
--- a/open-sse/mcp-server/server.ts
+++ b/open-sse/mcp-server/server.ts
@@@ -970,17 -973,21 +973,20 @@@ export function createMcpServer(): McpS
// @ts-ignore: dynamic zod access
inputSchema: toolDef.inputSchema,
},
- withScopeEnforcement(toolDef.name, async (args) => {
- try {
- const parsedArgs = toolDef.inputSchema.parse(args ?? {});
- // @ts-expect-error - handler type lost through dynamic Object.values() access
- const result = await toolDef.handler(parsedArgs);
- return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
- }
- })
+ withScopeEnforcement(
+ toolDef.name,
+ async (args) => {
+ try {
+ const parsedArgs = toolDef.inputSchema.parse(args ?? {});
- // @ts-expect-error - handler type lost through dynamic Object.values() access
+ const result = await toolDef.handler(parsedArgs);
+ return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
+ }
+ },
+ toolDef.scopes
+ )
);
});
@@@ -993,17 -1000,21 +999,20 @@@
// @ts-ignore: dynamic zod access
inputSchema: toolDef.inputSchema,
},
- withScopeEnforcement(toolDef.name, async (args) => {
- try {
- const parsedArgs = toolDef.inputSchema.parse(args ?? {});
- // @ts-expect-error - handler type lost through dynamic Object.values() access
- const result = await toolDef.handler(parsedArgs);
- return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
- }
- })
+ withScopeEnforcement(
+ toolDef.name,
+ async (args) => {
+ try {
+ const parsedArgs = toolDef.inputSchema.parse(args ?? {});
- // @ts-expect-error - handler type lost through dynamic Object.values() access
+ const result = await toolDef.handler(parsedArgs);
+ return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
+ }
+ },
+ toolDef.scopes
+ )
);
});
@@@ -1062,17 -1077,21 +1075,20 @@@
// @ts-ignore: dynamic zod access
inputSchema: toolDef.inputSchema,
},
- withScopeEnforcement(toolDef.name, async (args) => {
- try {
- const parsedArgs = toolDef.inputSchema.parse(args ?? {});
- // @ts-expect-error - handler type lost through dynamic Object.values() access
- const result = await toolDef.handler(parsedArgs);
- return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
- }
- })
+ withScopeEnforcement(
+ toolDef.name,
+ async (args) => {
+ try {
+ const parsedArgs = toolDef.inputSchema.parse(args ?? {});
- // @ts-expect-error - handler type lost through dynamic Object.values() access
+ const result = await toolDef.handler(parsedArgs);
+ return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
+ }
+ },
+ toolDef.scopes
+ )
);
});
diff --cc scripts/dev/run-standalone.mjs
index b1bef083b4,c3dbfcd50e..531322da77
--- a/scripts/dev/run-standalone.mjs
+++ b/scripts/dev/run-standalone.mjs
@@@ -10,15 -10,17 +11,24 @@@ import { bootstrapEnv } from "../build/
const env = bootstrapEnv();
const runtimePorts = resolveRuntimePorts(env);
+ const childEnv = withRuntimePortEnv(env, runtimePorts);
+
+ // #2939: honor OMNIROUTE_MEMORY_MB (default 512), the same knob
+ // `omniroute serve` uses, so Docker users can control the server heap under
+ // load / large SQLite DBs. A trailing --max-old-space-size wins, so this
+ // overrides the image fallback without clobbering any other NODE_OPTIONS flags.
+ const maxOldSpaceMb = resolveMaxOldSpaceMb(childEnv.OMNIROUTE_MEMORY_MB);
+ childEnv.NODE_OPTIONS =
+ `${childEnv.NODE_OPTIONS || ""} --max-old-space-size=${maxOldSpaceMb}`.trim();
-spawnWithForwardedSignals("node", ["server.js"], {
+// Prefer the WS-aware wrapper (server-ws.mjs) over the bare Next standalone
+// server.js: it installs the trusted peer-IP stamp (scripts/dev/peer-stamp.mjs)
+// that the authz middleware needs to allow loopback/LAN access to LOCAL_ONLY
+// routes. Falling back to server.js fails CLOSED (every LOCAL_ONLY request 403s)
+// rather than trusting the spoofable Host header.
+const entry = existsSync("server-ws.mjs") ? "server-ws.mjs" : "server.js";
+
+spawnWithForwardedSignals("node", [entry], {
stdio: "inherit",
- env: withRuntimePortEnv(env, runtimePorts),
+ env: childEnv,
});
diff --cc src/lib/db/apiKeys.ts
index 301214c7d0,c1c1bcc772..aa619c669d
--- a/src/lib/db/apiKeys.ts
+++ b/src/lib/db/apiKeys.ts
@@@ -160,7 -160,7 +164,8 @@@ const API_KEY_COLUMN_FALLBACKS =
{ name: "is_banned", definition: "is_banned INTEGER NOT NULL DEFAULT 0" },
{ name: "key_hash", definition: "key_hash TEXT" },
{ name: "allowed_endpoints", definition: "allowed_endpoints TEXT" },
+ { name: "allowed_quotas", definition: "allowed_quotas TEXT NOT NULL DEFAULT '[]'" },
+ { name: "stream_default_mode", definition: "stream_default_mode TEXT NOT NULL DEFAULT 'legacy'" },
] as const;
// Cache for model permission checks
@@@ -360,7 -360,7 +365,7 @@@ function getPreparedStatements(db: ApiK
"SELECT id, expires_at, revoked_at, is_active, is_banned FROM api_keys WHERE key = ? OR key_hash = ?"
);
_stmtGetKeyMetadata = db.prepare<ApiKeyRow>(
- "SELECT id, name, machine_id, allowed_models, allowed_combos, allowed_connections, allowed_quotas, no_log, auto_resolve, is_active, access_schedule, max_requests_per_day, max_requests_per_minute, throttle_delay_ms, max_sessions, revoked_at, expires_at, ip_allowlist, scopes, rate_limits, is_banned, key_hash, allowed_endpoints FROM api_keys WHERE key = ? OR key_hash = ?"
- "SELECT id, name, machine_id, allowed_models, allowed_combos, allowed_connections, no_log, auto_resolve, is_active, access_schedule, max_requests_per_day, max_requests_per_minute, throttle_delay_ms, max_sessions, revoked_at, expires_at, ip_allowlist, scopes, rate_limits, is_banned, key_hash, allowed_endpoints, stream_default_mode FROM api_keys WHERE key = ? OR key_hash = ?"
++ "SELECT id, name, machine_id, allowed_models, allowed_combos, allowed_connections, allowed_quotas, no_log, auto_resolve, is_active, access_schedule, max_requests_per_day, max_requests_per_minute, throttle_delay_ms, max_sessions, revoked_at, expires_at, ip_allowlist, scopes, rate_limits, is_banned, key_hash, allowed_endpoints, stream_default_mode FROM api_keys WHERE key = ? OR key_hash = ?"
);
_stmtInsertKey = db.prepare(
"INSERT INTO api_keys (id, name, key, machine_id, allowed_models, no_log, created_at, key_prefix, key_hash, scopes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
diff --cc src/lib/db/migrationRunner.ts
index c09653287f,3cf9a60856..92a89087ea
--- a/src/lib/db/migrationRunner.ts
+++ b/src/lib/db/migrationRunner.ts
@@@ -444,10 -444,11 +444,16 @@@ function isSchemaAlreadyApplied
// mid-file and skip the CREATE INDEX that follows, leaving the index
// missing on DBs that re-execute the script after a partial first run.
return hasColumn(db, "memories", "needs_reindex");
- case "087":
- // Quota groups migration: the table + column are already present when
- // group_id exists on quota_pools (ensures the backfill UPDATE also ran).
+ case "085":
+ // Retroactive guard for quota_pools migration renumbered from 077 → 085
+ // (077 collided with 077_api_key_stream_default_mode). DBs that already
+ // applied quota_pools under the old 077 number should not re-run as 085.
+ return hasTable(db, "quota_pools") && hasTable(db, "quota_allocations");
++ case "088":
++ // Quota groups migration (renumbered 087 → 088 on merge into v3.8.8).
++ // The table + column are already present when group_id exists on
++ // quota_pools (ensures the backfill UPDATE also ran).
+ return hasTable(db, "quota_groups") && hasColumn(db, "quota_pools", "group_id");
default:
return false;
}
diff --cc src/lib/db/migrations/086_api_key_allowed_quotas.sql
index 21e85399f3,0000000000..21e85399f3
mode 100644,000000..100644
--- a/src/lib/db/migrations/086_api_key_allowed_quotas.sql
+++ b/src/lib/db/migrations/086_api_key_allowed_quotas.sql
diff --cc src/lib/db/migrations/087_quota_pool_connections.sql
index e823ff68db,0000000000..e823ff68db
mode 100644,000000..100644
--- a/src/lib/db/migrations/087_quota_pool_connections.sql
+++ b/src/lib/db/migrations/087_quota_pool_connections.sql
diff --cc src/lib/db/migrations/088_quota_groups.sql
index c69a3bcfba,0000000000..c69a3bcfba
mode 100644,000000..100644
--- a/src/lib/db/migrations/088_quota_groups.sql
+++ b/src/lib/db/migrations/088_quota_groups.sql
diff --cc tests/unit/quota-groups-migration.test.ts
index f1217d80cd,0000000000..95dcab2608
mode 100644,000000..100644
--- a/tests/unit/quota-groups-migration.test.ts
+++ b/tests/unit/quota-groups-migration.test.ts
@@@ -1,225 -1,0 +1,225 @@@
+/**
+ * tests/unit/quota-groups-migration.test.ts
+ *
+ * Task B1 — first-class quota Group entity.
+ *
+ * Coverage:
- * - Migration file 087_quota_groups.sql exists and contains the expected SQL.
++ * - Migration file 088_quota_groups.sql exists and contains the expected SQL.
+ * - After migrations run (fresh DB), quota_groups has a 'group-demo' row.
+ * - createPool without groupId → pool.groupId === 'group-demo'.
+ * - createPool with groupId: 'g1' (group pre-inserted) → pool.groupId === 'g1'.
+ * - getPool and listPools both surface groupId.
+ * - updatePool with groupId updates the group assignment.
+ */
+
+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";
+
+// ── DB harness (mirrors quota-pool-connections.test.ts) ─────────────────────
+const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-quota-groups-"));
+process.env.DATA_DIR = TEST_DATA_DIR;
+
+const core = await import("../../src/lib/db/core.ts");
+const poolsDb = await import("../../src/lib/db/quotaPools.ts");
+
+async function resetStorage() {
+ core.resetDbInstance();
+ for (let attempt = 0; attempt < 10; attempt++) {
+ try {
+ if (fs.existsSync(TEST_DATA_DIR)) {
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ }
+ break;
+ } catch (err: any) {
+ if ((err?.code === "EBUSY" || err?.code === "EPERM") && attempt < 9) {
+ await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
+ } else {
+ throw err;
+ }
+ }
+ }
+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
+}
+
+test.beforeEach(async () => {
+ await resetStorage();
+});
+
+test.after(async () => {
+ core.resetDbInstance();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+});
+
+// Helper to get a raw DB handle for inspection / seeding.
+function getDb() {
+ return core.getDbInstance() as unknown as {
+ prepare: <TRow = unknown>(sql: string) => {
+ all: (...params: unknown[]) => TRow[];
+ get: (...params: unknown[]) => TRow | undefined;
+ run: (...params: unknown[]) => { changes: number };
+ };
+ };
+}
+
+// ── B1.1: Migration file content ─────────────────────────────────────────────
+
+test("migration 087 file exists", () => {
- const migrationPath = path.resolve("src/lib/db/migrations/087_quota_groups.sql");
++ const migrationPath = path.resolve("src/lib/db/migrations/088_quota_groups.sql");
+ assert.ok(fs.existsSync(migrationPath), `migration file not found: ${migrationPath}`);
+});
+
+test("migration 087 contains quota_groups CREATE TABLE", () => {
+ const sql = fs.readFileSync(
- path.resolve("src/lib/db/migrations/087_quota_groups.sql"),
++ path.resolve("src/lib/db/migrations/088_quota_groups.sql"),
+ "utf8"
+ );
+ assert.ok(sql.includes("quota_groups"), "migration SQL should reference quota_groups");
+ assert.ok(
+ sql.includes("CREATE TABLE IF NOT EXISTS quota_groups"),
+ "migration SQL should create quota_groups with IF NOT EXISTS"
+ );
+});
+
+test("migration 087 seeds group-demo", () => {
+ const sql = fs.readFileSync(
- path.resolve("src/lib/db/migrations/087_quota_groups.sql"),
++ path.resolve("src/lib/db/migrations/088_quota_groups.sql"),
+ "utf8"
+ );
+ assert.ok(
+ sql.includes("group-demo"),
+ "migration SQL should insert the 'group-demo' seed row"
+ );
+ assert.ok(
+ sql.includes("INSERT OR IGNORE INTO quota_groups"),
+ "migration SQL should use INSERT OR IGNORE for idempotency"
+ );
+});
+
+test("migration 087 adds group_id column to quota_pools", () => {
+ const sql = fs.readFileSync(
- path.resolve("src/lib/db/migrations/087_quota_groups.sql"),
++ path.resolve("src/lib/db/migrations/088_quota_groups.sql"),
+ "utf8"
+ );
+ assert.ok(
+ sql.includes("ALTER TABLE quota_pools ADD COLUMN group_id"),
+ "migration SQL should ALTER TABLE quota_pools to add group_id"
+ );
+});
+
+test("migration 087 contains backfill UPDATE for existing pools", () => {
+ const sql = fs.readFileSync(
- path.resolve("src/lib/db/migrations/087_quota_groups.sql"),
++ path.resolve("src/lib/db/migrations/088_quota_groups.sql"),
+ "utf8"
+ );
+ assert.ok(
+ sql.includes("UPDATE quota_pools SET group_id = 'group-demo'"),
+ "migration SQL should backfill existing pools to group-demo"
+ );
+ assert.ok(
+ sql.includes("group_id IS NULL OR group_id = ''"),
+ "backfill should only touch pools without a group"
+ );
+});
+
+// ── B1.2: Schema after migration ──────────────────────────────────────────────
+
+test("after migrations run, quota_groups has a group-demo row named GroupDemo", () => {
+ // Trigger DB initialisation (runs all migrations including 087).
+ const db = getDb();
+
+ const row = db
+ .prepare<{ id: string; name: string }>(
+ "SELECT id, name FROM quota_groups WHERE id = 'group-demo'"
+ )
+ .get();
+
+ assert.ok(row, "group-demo row should exist in quota_groups");
+ assert.equal(row!.id, "group-demo");
+ assert.equal(row!.name, "GroupDemo");
+});
+
+test("quota_pools has a group_id column after migration", () => {
+ const db = getDb();
+ const cols = db
+ .prepare<{ name: string }>("PRAGMA table_info(quota_pools)")
+ .all()
+ .map((r) => r.name);
+ assert.ok(cols.includes("group_id"), "quota_pools should have a group_id column");
+});
+
+// ── B1.3: createPool defaults ─────────────────────────────────────────────────
+
+test("createPool without groupId → pool.groupId === 'group-demo'", () => {
+ // Ensure migrations have run.
+ getDb();
+
+ const pool = poolsDb.createPool({
+ connectionId: "conn-1",
+ name: "Default Group Pool",
+ });
+
+ assert.equal(pool.groupId, "group-demo", "groupId should default to 'group-demo'");
+
+ // Re-read from DB to confirm persistence.
+ const reread = poolsDb.getPool(pool.id);
+ assert.ok(reread, "pool should be findable after creation");
+ assert.equal(reread!.groupId, "group-demo", "persisted groupId should be 'group-demo'");
+});
+
+test("createPool with explicit groupId persists the given group", () => {
+ const db = getDb();
+
+ // Seed a custom group first (raw SQL, as quotaGroups module is not yet implemented).
+ db.prepare("INSERT OR IGNORE INTO quota_groups (id, name) VALUES ('g1', 'Group One')").run();
+
+ const pool = poolsDb.createPool({
+ connectionId: "conn-g1",
+ name: "G1 Pool",
+ groupId: "g1",
+ });
+
+ assert.equal(pool.groupId, "g1", "groupId should be 'g1'");
+
+ const reread = poolsDb.getPool(pool.id);
+ assert.ok(reread, "pool should be findable after creation");
+ assert.equal(reread!.groupId, "g1", "persisted groupId should be 'g1'");
+});
+
+// ── B1.4: listPools surfaces groupId ─────────────────────────────────────────
+
+test("listPools returns groupId on every pool", () => {
+ const db = getDb();
+ db.prepare("INSERT OR IGNORE INTO quota_groups (id, name) VALUES ('g2', 'Group Two')").run();
+
+ poolsDb.createPool({ connectionId: "lp-1", name: "Pool Default" });
+ poolsDb.createPool({ connectionId: "lp-2", name: "Pool G2", groupId: "g2" });
+
+ const pools = poolsDb.listPools();
+ assert.equal(pools.length, 2);
+
+ const pDef = pools.find((p) => p.name === "Pool Default")!;
+ assert.equal(pDef.groupId, "group-demo");
+
+ const pG2 = pools.find((p) => p.name === "Pool G2")!;
+ assert.equal(pG2.groupId, "g2");
+});
+
+// ── B1.5: updatePool groupId ──────────────────────────────────────────────────
+
+test("updatePool with groupId updates the group assignment", () => {
+ const db = getDb();
+ db.prepare("INSERT OR IGNORE INTO quota_groups (id, name) VALUES ('g3', 'Group Three')").run();
+
+ const pool = poolsDb.createPool({ connectionId: "up-1", name: "Update Group Pool" });
+ assert.equal(pool.groupId, "group-demo");
+
+ const updated = poolsDb.updatePool(pool.id, { groupId: "g3" });
+ assert.ok(updated, "updatePool should return the updated pool");
+ assert.equal(updated!.groupId, "g3", "groupId should be updated to 'g3'");
+
+ const reread = poolsDb.getPool(pool.id);
+ assert.equal(reread!.groupId, "g3", "persisted groupId should be 'g3'");
+});
diff --cc tests/unit/quota-pool-connections.test.ts
index 6a5f93aab6,0000000000..2aaa710f40
mode 100644,000000..100644
--- a/tests/unit/quota-pool-connections.test.ts
+++ b/tests/unit/quota-pool-connections.test.ts
@@@ -1,211 -1,0 +1,211 @@@
+/**
+ * tests/unit/quota-pool-connections.test.ts
+ *
+ * Phase D1 — Multi-provider quota pools.
+ *
+ * Coverage:
+ * - Migration file exists and contains expected SQL.
+ * - createPool with connectionIds: [a, b] → getPool returns connectionIds.length === 2
+ * and connectionId === a (primary).
+ * - updatePool replacing connectionIds → getPool reflects new set.
+ * - deletePool removes join rows.
+ * - Pool created the old way (single connectionId, no connectionIds arg) →
+ * connectionIds === [connectionId] (back-compat).
+ */
+
+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";
+
+// ── DB harness (same pattern as db-quota-pools.test.ts) ────────────────────
+const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-pool-conn-"));
+process.env.DATA_DIR = TEST_DATA_DIR;
+
+const core = await import("../../src/lib/db/core.ts");
+const poolsDb = await import("../../src/lib/db/quotaPools.ts");
+
+async function resetStorage() {
+ core.resetDbInstance();
+ for (let attempt = 0; attempt < 10; attempt++) {
+ try {
+ if (fs.existsSync(TEST_DATA_DIR)) {
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ }
+ break;
+ } catch (err: any) {
+ if ((err?.code === "EBUSY" || err?.code === "EPERM") && attempt < 9) {
+ await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
+ } else {
+ throw err;
+ }
+ }
+ }
+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
+}
+
+test.beforeEach(async () => {
+ await resetStorage();
+});
+
+test.after(async () => {
+ core.resetDbInstance();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+});
+
+// ── D1.1: Migration file ────────────────────────────────────────────────────
+
+test("migration 086 file exists and contains quota_pool_connections DDL", () => {
+ const migrationPath = path.resolve(
- "src/lib/db/migrations/086_quota_pool_connections.sql"
++ "src/lib/db/migrations/087_quota_pool_connections.sql"
+ );
+ assert.ok(fs.existsSync(migrationPath), `migration file not found: ${migrationPath}`);
+
+ const sql = fs.readFileSync(migrationPath, "utf8");
+ assert.ok(
+ sql.includes("quota_pool_connections"),
+ "migration SQL should reference quota_pool_connections"
+ );
+ assert.ok(
+ sql.includes("INSERT OR IGNORE INTO quota_pool_connections"),
+ "migration SQL should contain the backfill INSERT"
+ );
+ assert.ok(
+ sql.includes("SELECT id, connection_id FROM quota_pools"),
+ "backfill SELECT should reference quota_pools columns"
+ );
+});
+
+// ── D1.2: createPool with connectionIds ────────────────────────────────────
+
+test("createPool with connectionIds: [a, b] → connectionIds.length === 2, connectionId === a", () => {
+ const pool = poolsDb.createPool({
+ connectionId: "conn-a",
+ name: "Multi-conn Pool",
+ connectionIds: ["conn-a", "conn-b"],
+ });
+
+ assert.ok(pool.id, "pool should have an id");
+ assert.equal(pool.connectionId, "conn-a", "primary connectionId should be conn-a");
+ assert.equal(pool.connectionIds.length, 2, "connectionIds should have 2 members");
+ assert.ok(pool.connectionIds.includes("conn-a"), "conn-a should be a member");
+ assert.ok(pool.connectionIds.includes("conn-b"), "conn-b should be a member");
+ assert.equal(pool.connectionIds[0], "conn-a", "first connectionId should be the primary");
+});
+
+test("getPool reflects both connectionIds after multi-connection create", () => {
+ const created = poolsDb.createPool({
+ connectionId: "p-a",
+ name: "Pool ABC",
+ connectionIds: ["p-a", "p-b", "p-c"],
+ });
+
+ const found = poolsDb.getPool(created.id)!;
+ assert.ok(found, "pool should be found");
+ assert.equal(found.connectionId, "p-a");
+ assert.equal(found.connectionIds.length, 3);
+ assert.deepEqual([...found.connectionIds].sort(), ["p-a", "p-b", "p-c"].sort());
+});
+
+// ── D1.3: updatePool replacing connectionIds ────────────────────────────────
+
+test("updatePool with new connectionIds replaces the join rows", () => {
+ const pool = poolsDb.createPool({
+ connectionId: "old-a",
+ name: "Updatable Pool",
+ connectionIds: ["old-a", "old-b"],
+ });
+
+ const updated = poolsDb.updatePool(pool.id, {
+ connectionIds: ["new-x", "new-y"],
+ });
+
+ assert.ok(updated, "updatePool should return the updated pool");
+ assert.equal(updated!.connectionId, "new-x", "primary should be updated to new-x");
+ assert.equal(updated!.connectionIds.length, 2);
+ assert.ok(updated!.connectionIds.includes("new-x"), "new-x should be a member");
+ assert.ok(updated!.connectionIds.includes("new-y"), "new-y should be a member");
+ assert.ok(!updated!.connectionIds.includes("old-a"), "old-a should be removed");
+ assert.ok(!updated!.connectionIds.includes("old-b"), "old-b should be removed");
+
+ // Re-read from DB to confirm persistence.
+ const reread = poolsDb.getPool(pool.id)!;
+ assert.equal(reread.connectionId, "new-x");
+ assert.deepEqual([...reread.connectionIds].sort(), ["new-x", "new-y"].sort());
+});
+
+test("updatePool without connectionIds leaves join rows untouched", () => {
+ const pool = poolsDb.createPool({
+ connectionId: "stable-a",
+ name: "Stable Pool",
+ connectionIds: ["stable-a", "stable-b"],
+ });
+
+ poolsDb.updatePool(pool.id, { name: "Renamed Pool" });
+
+ const reread = poolsDb.getPool(pool.id)!;
+ assert.equal(reread.name, "Renamed Pool");
+ assert.equal(reread.connectionIds.length, 2, "connectionIds should be unchanged");
+ assert.ok(reread.connectionIds.includes("stable-a"));
+ assert.ok(reread.connectionIds.includes("stable-b"));
+});
+
+// ── D1.4: deletePool removes join rows ────────────────────────────────────
+
+test("deletePool removes quota_pool_connections rows", () => {
+ const pool = poolsDb.createPool({
+ connectionId: "del-a",
+ name: "To Delete",
+ connectionIds: ["del-a", "del-b"],
+ });
+
+ const deleted = poolsDb.deletePool(pool.id);
+ assert.equal(deleted, true, "deletePool should return true");
+
+ // Pool should be gone.
+ assert.equal(poolsDb.getPool(pool.id), null, "pool should be null after deletion");
+
+ // The join rows are cleaned up — no ghost references.
+ // We verify indirectly: creating a new pool with the same connection IDs should work
+ // without PK conflicts in quota_pool_connections.
+ const newPool = poolsDb.createPool({
+ connectionId: "del-a",
+ name: "Reused conn",
+ connectionIds: ["del-a", "del-b"],
+ });
+ assert.ok(newPool.id, "new pool with same conn IDs should be created without conflict");
+});
+
+// ── D1.5: Back-compat — single connectionId, no connectionIds arg ──────────
+
+test("pool created with single connectionId (legacy) returns connectionIds === [connectionId]", () => {
+ const pool = poolsDb.createPool({
+ connectionId: "legacy-conn",
+ name: "Legacy Pool",
+ });
+
+ assert.equal(pool.connectionId, "legacy-conn");
+ assert.deepEqual(pool.connectionIds, ["legacy-conn"]);
+
+ const found = poolsDb.getPool(pool.id)!;
+ assert.deepEqual(found.connectionIds, ["legacy-conn"]);
+});
+
+test("listPools returns connectionIds on every pool", () => {
+ poolsDb.createPool({ connectionId: "lc-1", name: "Pool 1" });
+ poolsDb.createPool({
+ connectionId: "lc-2",
+ name: "Pool 2",
+ connectionIds: ["lc-2", "lc-3"],
+ });
+
+ const pools = poolsDb.listPools();
+ assert.equal(pools.length, 2);
+
+ const p1 = pools.find((p) => p.name === "Pool 1")!;
+ assert.deepEqual(p1.connectionIds, ["lc-1"]);
+
+ const p2 = pools.find((p) => p.name === "Pool 2")!;
+ assert.equal(p2.connectionIds.length, 2);
+});