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

feat(quota): quota_groups table + pools.group_id (migration 087)

diegosouzapw727616b2c028
diff --git a/src/lib/db/migrationRunner.ts b/src/lib/db/migrationRunner.ts
index d91e2984ac..c09653287f 100644
--- a/src/lib/db/migrationRunner.ts
+++ b/src/lib/db/migrationRunner.ts
@@ -444,6 +444,10 @@ 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).
+ return hasTable(db, "quota_groups") && hasColumn(db, "quota_pools", "group_id");
default:
return false;
}
diff --git a/src/lib/db/migrations/087_quota_groups.sql b/src/lib/db/migrations/087_quota_groups.sql
new file mode 100644
index 0000000000..c69a3bcfba
--- /dev/null
+++ b/src/lib/db/migrations/087_quota_groups.sql
@@ -0,0 +1,28 @@
+-- 087: Quota pool groups — quota_groups table + quota_pools.group_id (Part B1).
+--
+-- Introduces a first-class Group entity that organises quota pools.
+-- A key allocated to any pool of a group sees and may use every model
+-- of every pool in that group (scope/enforce wired in subsequent tasks).
+-- Idempotent via CREATE TABLE/INSERT OR IGNORE (new table) + the migration
+-- runner's "duplicate column name" catch (ALTER TABLE ADD COLUMN).
+-- The UPDATE backfill is a safe no-op after the first run (group_id is
+-- already non-NULL for all rows).
+
+CREATE TABLE IF NOT EXISTS quota_groups (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
+);
+
+-- Seed a default group so the UI always has at least one to select.
+-- Stable id ensures this INSERT is idempotent on any subsequent run.
+INSERT OR IGNORE INTO quota_groups (id, name) VALUES ('group-demo', 'GroupDemo');
+
+-- Add group_id to pools (nullable; backfilled below).
+-- Re-run safety: the migration runner catches "duplicate column name" and
+-- marks the migration as applied without re-executing the rest of the file,
+-- so the UPDATE below only runs on the first application.
+ALTER TABLE quota_pools ADD COLUMN group_id TEXT;
+
+-- Backfill: assign every existing pool with no group to the default group.
+UPDATE quota_pools SET group_id = 'group-demo' WHERE group_id IS NULL OR group_id = '';
diff --git a/src/lib/db/quotaPools.ts b/src/lib/db/quotaPools.ts
index c2e8b75bc3..e277668648 100644
--- a/src/lib/db/quotaPools.ts
+++ b/src/lib/db/quotaPools.ts
@@ -54,6 +54,8 @@ export interface QuotaPool {
/** All member connections (≥1 after backfill). Primary is always connectionIds[0]. */
connectionIds: string[];
name: string;
+ /** Group this pool belongs to. Defaults to 'group-demo' for legacy pools. */
+ groupId: string;
createdAt: string;
allocations: PoolAllocation[];
}
@@ -61,6 +63,8 @@ export interface QuotaPool {
export interface PoolCreate {
connectionId: string;
name: string;
+ /** Group to assign this pool to. Defaults to 'group-demo' when omitted. */
+ groupId?: string;
allocations?: PoolAllocation[];
/**
* Full member list. When provided, connectionId is ignored for the join table
@@ -72,6 +76,8 @@ export interface PoolCreate {
export interface PoolUpdate {
name?: string;
+ /** When provided, updates the pool's group assignment. */
+ groupId?: string;
allocations?: PoolAllocation[];
/**
* When provided, replaces the entire join-table membership for this pool.
@@ -125,6 +131,7 @@ interface PoolRow {
id: string;
connection_id: string;
name: string;
+ group_id: string | null;
created_at: string;
}
@@ -171,6 +178,7 @@ function rowToPool(row: PoolRow, allocations: PoolAllocation[]): QuotaPool {
connectionId: row.connection_id,
connectionIds: getConnectionIds(row.id, row.connection_id),
name: row.name,
+ groupId: row.group_id || "group-demo",
createdAt: row.created_at,
allocations,
};
@@ -204,7 +212,7 @@ function makeId(): string {
export function listPools(): QuotaPool[] {
const rows = getDb()
.prepare<PoolRow>(
- "SELECT id, connection_id, name, created_at FROM quota_pools ORDER BY created_at ASC"
+ "SELECT id, connection_id, name, group_id, created_at FROM quota_pools ORDER BY created_at ASC"
)
.all();
return rows.map((row) => rowToPool(row, getAllocations(row.id)));
@@ -215,7 +223,7 @@ export function listPools(): QuotaPool[] {
*/
export function getPool(id: string): QuotaPool | null {
const row = getDb()
- .prepare<PoolRow>("SELECT id, connection_id, name, created_at FROM quota_pools WHERE id = ?")
+ .prepare<PoolRow>("SELECT id, connection_id, name, group_id, created_at FROM quota_pools WHERE id = ?")
.get(id);
if (!row) return null;
return rowToPool(row, getAllocations(row.id));
@@ -242,11 +250,13 @@ export function createPool(input: PoolCreate): QuotaPool {
assertSingleProvider(input.connectionIds);
}
+ const groupId = input.groupId || "group-demo";
+
const database = getDb();
const doCreate = database.transaction(() => {
database
- .prepare("INSERT INTO quota_pools (id, connection_id, name, created_at) VALUES (?, ?, ?, ?)")
- .run(id, primaryConnectionId, input.name, now);
+ .prepare("INSERT INTO quota_pools (id, connection_id, name, group_id, created_at) VALUES (?, ?, ?, ?, ?)")
+ .run(id, primaryConnectionId, input.name, groupId, now);
const insertConn = database.prepare(
"INSERT OR IGNORE INTO quota_pool_connections (pool_id, connection_id) VALUES (?, ?)"
@@ -275,7 +285,7 @@ export function createPool(input: PoolCreate): QuotaPool {
doCreate();
const result = rowToPool(
- { id, connection_id: primaryConnectionId, name: input.name, created_at: now },
+ { id, connection_id: primaryConnectionId, name: input.name, group_id: groupId, created_at: now },
getAllocations(id)
);
@@ -294,7 +304,7 @@ export function createPool(input: PoolCreate): QuotaPool {
export function updatePool(id: string, input: PoolUpdate): QuotaPool | null {
const database = getDb();
const existing = database
- .prepare<PoolRow>("SELECT id, connection_id, name, created_at FROM quota_pools WHERE id = ?")
+ .prepare<PoolRow>("SELECT id, connection_id, name, group_id, created_at FROM quota_pools WHERE id = ?")
.get(id);
if (!existing) return null;
@@ -309,6 +319,11 @@ export function updatePool(id: string, input: PoolUpdate): QuotaPool | null {
existing.name = input.name;
}
+ if (input.groupId !== undefined) {
+ database.prepare("UPDATE quota_pools SET group_id = ? WHERE id = ?").run(input.groupId, id);
+ existing.group_id = input.groupId;
+ }
+
if (input.connectionIds !== undefined && input.connectionIds.length > 0) {
const newPrimary = input.connectionIds[0];
// Replace join rows.
diff --git a/tests/unit/quota-groups-migration.test.ts b/tests/unit/quota-groups-migration.test.ts
new file mode 100644
index 0000000000..f1217d80cd
--- /dev/null
+++ b/tests/unit/quota-groups-migration.test.ts
@@ -0,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.
+ * - 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");
+ 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"),
+ "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"),
+ "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"),
+ "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"),
+ "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'");
+});