From 89d3304a93305b6cf7c0e89b17e11230d44db735 Mon Sep 17 00:00:00 2001 From: diegosouzapw Date: Wed, 27 May 2026 19:24:14 -0300 Subject: [PATCH 1/5] feat(db): add migrations 073/074/075 agent_bridge + inspector (F2) --- src/lib/db/migrations/073_agent_bridge.sql | 24 +++++++++++++++++++ .../migrations/074_inspector_custom_hosts.sql | 11 +++++++++ .../db/migrations/075_inspector_sessions.sql | 18 ++++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 src/lib/db/migrations/073_agent_bridge.sql create mode 100644 src/lib/db/migrations/074_inspector_custom_hosts.sql create mode 100644 src/lib/db/migrations/075_inspector_sessions.sql diff --git a/src/lib/db/migrations/073_agent_bridge.sql b/src/lib/db/migrations/073_agent_bridge.sql new file mode 100644 index 0000000000..a04ba633ca --- /dev/null +++ b/src/lib/db/migrations/073_agent_bridge.sql @@ -0,0 +1,24 @@ +CREATE TABLE IF NOT EXISTS agent_bridge_state ( + agent_id TEXT PRIMARY KEY, + dns_enabled INTEGER NOT NULL DEFAULT 0, + cert_trusted INTEGER NOT NULL DEFAULT 0, + setup_completed INTEGER NOT NULL DEFAULT 0, + last_started_at TEXT, + last_error TEXT +); + +CREATE TABLE IF NOT EXISTS agent_bridge_mappings ( + agent_id TEXT NOT NULL, + source_model TEXT NOT NULL, + target_model TEXT NOT NULL, + updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (agent_id, source_model) +); + +CREATE TABLE IF NOT EXISTS agent_bridge_bypass ( + pattern TEXT PRIMARY KEY, + source TEXT NOT NULL CHECK (source IN ('default','user')), + created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX IF NOT EXISTS idx_agent_bridge_mappings_agent ON agent_bridge_mappings(agent_id); diff --git a/src/lib/db/migrations/074_inspector_custom_hosts.sql b/src/lib/db/migrations/074_inspector_custom_hosts.sql new file mode 100644 index 0000000000..3870ed0210 --- /dev/null +++ b/src/lib/db/migrations/074_inspector_custom_hosts.sql @@ -0,0 +1,11 @@ +CREATE TABLE IF NOT EXISTS inspector_custom_hosts ( + host TEXT PRIMARY KEY, + enabled INTEGER NOT NULL DEFAULT 1, + label TEXT, + kind TEXT NOT NULL DEFAULT 'custom' CHECK (kind IN ('llm','app','custom')), + added_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + last_seen_at TEXT +); + +CREATE INDEX IF NOT EXISTS idx_inspector_custom_hosts_enabled + ON inspector_custom_hosts(enabled); diff --git a/src/lib/db/migrations/075_inspector_sessions.sql b/src/lib/db/migrations/075_inspector_sessions.sql new file mode 100644 index 0000000000..15e038e3f9 --- /dev/null +++ b/src/lib/db/migrations/075_inspector_sessions.sql @@ -0,0 +1,18 @@ +CREATE TABLE IF NOT EXISTS inspector_sessions ( + id TEXT PRIMARY KEY, + name TEXT, + started_at TEXT NOT NULL, + ended_at TEXT, + request_count INTEGER NOT NULL DEFAULT 0, + profile TEXT CHECK (profile IN ('llm','custom','all')) +); + +CREATE TABLE IF NOT EXISTS inspector_session_requests ( + session_id TEXT NOT NULL REFERENCES inspector_sessions(id) ON DELETE CASCADE, + seq INTEGER NOT NULL, + payload TEXT NOT NULL, + PRIMARY KEY (session_id, seq) +); + +CREATE INDEX IF NOT EXISTS idx_inspector_session_requests_sid + ON inspector_session_requests(session_id); From 45f602606bf9bf5c2f91336867e973a0b9c92c08 Mon Sep 17 00:00:00 2001 From: diegosouzapw Date: Wed, 27 May 2026 19:24:19 -0300 Subject: [PATCH 2/5] feat(db): add agentBridge state/mappings/bypass CRUD modules (F2) --- src/lib/db/_rowTypes.ts | 45 ++++++++++++ src/lib/db/agentBridgeBypass.ts | 79 ++++++++++++++++++++ src/lib/db/agentBridgeMappings.ts | 47 ++++++++++++ src/lib/db/agentBridgeState.ts | 115 ++++++++++++++++++++++++++++++ 4 files changed, 286 insertions(+) create mode 100644 src/lib/db/_rowTypes.ts create mode 100644 src/lib/db/agentBridgeBypass.ts create mode 100644 src/lib/db/agentBridgeMappings.ts create mode 100644 src/lib/db/agentBridgeState.ts diff --git a/src/lib/db/_rowTypes.ts b/src/lib/db/_rowTypes.ts new file mode 100644 index 0000000000..f16ae44aea --- /dev/null +++ b/src/lib/db/_rowTypes.ts @@ -0,0 +1,45 @@ +/** + * Row types for F2 DB modules (AgentBridge + Inspector). + * These are local type definitions used by the CRUD modules in this directory. + * F1 will create canonical Zod schemas in src/shared/schemas/; F10 reconciles them. + */ + +export interface AgentBridgeStateRow { + agent_id: string; + dns_enabled: boolean; + cert_trusted: boolean; + setup_completed: boolean; + last_started_at: string | null; + last_error: string | null; +} + +export interface AgentBridgeMappingRow { + agent_id: string; + source_model: string; + target_model: string; + updated_at: string; +} + +export interface AgentBridgeBypassRow { + pattern: string; + source: "default" | "user"; + created_at: string; +} + +export interface InspectorCustomHostRow { + host: string; + enabled: boolean; + label: string | null; + kind: "llm" | "app" | "custom"; + added_at: string; + last_seen_at: string | null; +} + +export interface InspectorSessionRow { + id: string; + name: string | null; + started_at: string; + ended_at: string | null; + request_count: number; + profile: "llm" | "custom" | "all" | null; +} diff --git a/src/lib/db/agentBridgeBypass.ts b/src/lib/db/agentBridgeBypass.ts new file mode 100644 index 0000000000..457a6413b4 --- /dev/null +++ b/src/lib/db/agentBridgeBypass.ts @@ -0,0 +1,79 @@ +/** + * Database module: AgentBridgeBypass + * CRUD + seed for agent_bridge_bypass table. + */ + +import { getDbInstance } from "./core"; +import type { AgentBridgeBypassRow } from "./_rowTypes"; + +// SQLite rows have source as plain string +interface AgentBridgeBypassDbRow { + pattern: string; + source: string; + created_at: string; +} + +function mapRow(row: AgentBridgeBypassDbRow): AgentBridgeBypassRow { + return { + pattern: row.pattern, + source: row.source as "default" | "user", + created_at: row.created_at, + }; +} + +export function getAllBypassPatterns(): AgentBridgeBypassRow[] { + const db = getDbInstance(); + const rows = db + .prepare("SELECT pattern, source, created_at FROM agent_bridge_bypass ORDER BY source ASC, pattern ASC") + .all() as AgentBridgeBypassDbRow[]; + return rows.map(mapRow); +} + +export function getUserBypassPatterns(): string[] { + const db = getDbInstance(); + const rows = db + .prepare("SELECT pattern FROM agent_bridge_bypass WHERE source = 'user' ORDER BY pattern ASC") + .all() as Array<{ pattern: string }>; + return rows.map((r) => r.pattern); +} + +export function replaceUserBypassPatterns(patterns: string[]): void { + const db = getDbInstance(); + const now = new Date().toISOString(); + + const deleteUserStmt = db.prepare("DELETE FROM agent_bridge_bypass WHERE source = 'user'"); + const insertStmt = db.prepare( + `INSERT INTO agent_bridge_bypass (pattern, source, created_at) VALUES (?, 'user', ?)` + ); + + const runTransaction = db.transaction(() => { + deleteUserStmt.run(); + for (const pattern of patterns) { + insertStmt.run(pattern, now); + } + }); + + runTransaction(); +} + +/** + * Seeds default bypass patterns — idempotent. + * Only inserts a pattern if it does not already exist in the table. + * Called at app boot by the AgentBridge manager (F3 will wire this). + */ +export function seedDefaultBypassPatterns(defaults: string[]): void { + const db = getDbInstance(); + const now = new Date().toISOString(); + + const insertIfMissing = db.prepare( + `INSERT OR IGNORE INTO agent_bridge_bypass (pattern, source, created_at) VALUES (?, 'default', ?)` + ); + + const runTransaction = db.transaction(() => { + for (const pattern of defaults) { + insertIfMissing.run(pattern, now); + } + }); + + runTransaction(); +} diff --git a/src/lib/db/agentBridgeMappings.ts b/src/lib/db/agentBridgeMappings.ts new file mode 100644 index 0000000000..200cb2412e --- /dev/null +++ b/src/lib/db/agentBridgeMappings.ts @@ -0,0 +1,47 @@ +/** + * Database module: AgentBridgeMappings + * CRUD operations for agent_bridge_mappings table. + */ + +import { getDbInstance } from "./core"; +import type { AgentBridgeMappingRow } from "./_rowTypes"; + +export function getMappingsForAgent(agentId: string): AgentBridgeMappingRow[] { + const db = getDbInstance(); + const rows = db + .prepare( + "SELECT agent_id, source_model, target_model, updated_at FROM agent_bridge_mappings WHERE agent_id = ? ORDER BY source_model ASC" + ) + .all(agentId) as AgentBridgeMappingRow[]; + return rows; +} + +export function setMappings( + agentId: string, + mappings: Array<{ source: string; target: string }> +): void { + const db = getDbInstance(); + const now = new Date().toISOString(); + + const deleteStmt = db.prepare("DELETE FROM agent_bridge_mappings WHERE agent_id = ?"); + const insertStmt = db.prepare( + `INSERT INTO agent_bridge_mappings (agent_id, source_model, target_model, updated_at) + VALUES (?, ?, ?, ?)` + ); + + const runTransaction = db.transaction(() => { + deleteStmt.run(agentId); + for (const mapping of mappings) { + insertStmt.run(agentId, mapping.source, mapping.target, now); + } + }); + + runTransaction(); +} + +export function deleteMapping(agentId: string, source: string): void { + const db = getDbInstance(); + db.prepare( + "DELETE FROM agent_bridge_mappings WHERE agent_id = ? AND source_model = ?" + ).run(agentId, source); +} diff --git a/src/lib/db/agentBridgeState.ts b/src/lib/db/agentBridgeState.ts new file mode 100644 index 0000000000..2cda21cd8d --- /dev/null +++ b/src/lib/db/agentBridgeState.ts @@ -0,0 +1,115 @@ +/** + * Database module: AgentBridgeState + * CRUD operations for agent_bridge_state table. + */ + +import { getDbInstance } from "./core"; +import type { AgentBridgeStateRow } from "./_rowTypes"; + +// SQLite stores booleans as 0/1 integers +interface AgentBridgeStateDbRow { + agent_id: string; + dns_enabled: number; + cert_trusted: number; + setup_completed: number; + last_started_at: string | null; + last_error: string | null; +} + +function mapRow(row: AgentBridgeStateDbRow): AgentBridgeStateRow { + return { + agent_id: row.agent_id, + dns_enabled: row.dns_enabled === 1, + cert_trusted: row.cert_trusted === 1, + setup_completed: row.setup_completed === 1, + last_started_at: row.last_started_at, + last_error: row.last_error, + }; +} + +export function getAllAgentBridgeStates(): AgentBridgeStateRow[] { + const db = getDbInstance(); + const rows = db + .prepare("SELECT * FROM agent_bridge_state ORDER BY agent_id ASC") + .all() as AgentBridgeStateDbRow[]; + return rows.map(mapRow); +} + +export function getAgentBridgeState(agentId: string): AgentBridgeStateRow | null { + const db = getDbInstance(); + const row = db + .prepare("SELECT * FROM agent_bridge_state WHERE agent_id = ?") + .get(agentId) as AgentBridgeStateDbRow | undefined; + return row ? mapRow(row) : null; +} + +export function upsertAgentBridgeState( + row: Partial & { agent_id: string } +): void { + const db = getDbInstance(); + const existing = getAgentBridgeState(row.agent_id); + + if (!existing) { + db.prepare( + `INSERT INTO agent_bridge_state + (agent_id, dns_enabled, cert_trusted, setup_completed, last_started_at, last_error) + VALUES (?, ?, ?, ?, ?, ?)` + ).run( + row.agent_id, + row.dns_enabled !== undefined ? (row.dns_enabled ? 1 : 0) : 0, + row.cert_trusted !== undefined ? (row.cert_trusted ? 1 : 0) : 0, + row.setup_completed !== undefined ? (row.setup_completed ? 1 : 0) : 0, + row.last_started_at ?? null, + row.last_error ?? null + ); + } else { + const fields: string[] = []; + const values: (string | number | null)[] = []; + + if (row.dns_enabled !== undefined) { + fields.push("dns_enabled = ?"); + values.push(row.dns_enabled ? 1 : 0); + } + if (row.cert_trusted !== undefined) { + fields.push("cert_trusted = ?"); + values.push(row.cert_trusted ? 1 : 0); + } + if (row.setup_completed !== undefined) { + fields.push("setup_completed = ?"); + values.push(row.setup_completed ? 1 : 0); + } + if (row.last_started_at !== undefined) { + fields.push("last_started_at = ?"); + values.push(row.last_started_at); + } + if (row.last_error !== undefined) { + fields.push("last_error = ?"); + values.push(row.last_error); + } + + if (fields.length === 0) return; + + values.push(row.agent_id); + db.prepare(`UPDATE agent_bridge_state SET ${fields.join(", ")} WHERE agent_id = ?`).run( + ...values + ); + } +} + +export function setLastStarted(agentId: string, ts: string): void { + const db = getDbInstance(); + db.prepare( + `INSERT INTO agent_bridge_state (agent_id, last_started_at) + VALUES (?, ?) + ON CONFLICT(agent_id) DO UPDATE SET last_started_at = excluded.last_started_at` + ).run(agentId, ts); +} + +export function setLastError(agentId: string, err: string | null): void { + const db = getDbInstance(); + db.prepare( + `INSERT INTO agent_bridge_state (agent_id, last_error) + VALUES (?, ?) + ON CONFLICT(agent_id) DO UPDATE SET last_error = excluded.last_error` + ).run(agentId, err); +} From 9fcfc2bd0bc08d021a4a205838307792a48fb3ba Mon Sep 17 00:00:00 2001 From: diegosouzapw Date: Wed, 27 May 2026 19:24:22 -0300 Subject: [PATCH 3/5] feat(db): add inspector custom hosts + sessions CRUD modules (F2) --- src/lib/db/inspectorCustomHosts.ts | 77 +++++++++++++++++++ src/lib/db/inspectorSessions.ts | 117 +++++++++++++++++++++++++++++ 2 files changed, 194 insertions(+) create mode 100644 src/lib/db/inspectorCustomHosts.ts create mode 100644 src/lib/db/inspectorSessions.ts diff --git a/src/lib/db/inspectorCustomHosts.ts b/src/lib/db/inspectorCustomHosts.ts new file mode 100644 index 0000000000..9874def829 --- /dev/null +++ b/src/lib/db/inspectorCustomHosts.ts @@ -0,0 +1,77 @@ +/** + * Database module: InspectorCustomHosts + * CRUD operations for inspector_custom_hosts table. + */ + +import { getDbInstance } from "./core"; +import type { InspectorCustomHostRow } from "./_rowTypes"; + +// SQLite stores booleans as integers +interface InspectorCustomHostDbRow { + host: string; + enabled: number; + label: string | null; + kind: string; + added_at: string; + last_seen_at: string | null; +} + +function mapRow(row: InspectorCustomHostDbRow): InspectorCustomHostRow { + return { + host: row.host, + enabled: row.enabled === 1, + label: row.label, + kind: row.kind as "llm" | "app" | "custom", + added_at: row.added_at, + last_seen_at: row.last_seen_at, + }; +} + +export function listCustomHosts(opts?: { enabledOnly?: boolean }): InspectorCustomHostRow[] { + const db = getDbInstance(); + const enabledOnly = opts?.enabledOnly === true; + + const rows = enabledOnly + ? (db + .prepare( + "SELECT * FROM inspector_custom_hosts WHERE enabled = 1 ORDER BY host ASC" + ) + .all() as InspectorCustomHostDbRow[]) + : (db + .prepare("SELECT * FROM inspector_custom_hosts ORDER BY host ASC") + .all() as InspectorCustomHostDbRow[]); + + return rows.map(mapRow); +} + +export function addCustomHost( + host: string, + kind: "llm" | "app" | "custom" = "custom", + label?: string +): void { + const db = getDbInstance(); + const now = new Date().toISOString(); + db.prepare( + `INSERT OR IGNORE INTO inspector_custom_hosts (host, enabled, label, kind, added_at) + VALUES (?, 1, ?, ?, ?)` + ).run(host, label ?? null, kind, now); +} + +export function removeCustomHost(host: string): void { + const db = getDbInstance(); + db.prepare("DELETE FROM inspector_custom_hosts WHERE host = ?").run(host); +} + +export function toggleCustomHost(host: string, enabled: boolean): void { + const db = getDbInstance(); + db.prepare("UPDATE inspector_custom_hosts SET enabled = ? WHERE host = ?").run( + enabled ? 1 : 0, + host + ); +} + +export function touchLastSeen(host: string): void { + const db = getDbInstance(); + const now = new Date().toISOString(); + db.prepare("UPDATE inspector_custom_hosts SET last_seen_at = ? WHERE host = ?").run(now, host); +} diff --git a/src/lib/db/inspectorSessions.ts b/src/lib/db/inspectorSessions.ts new file mode 100644 index 0000000000..c0d102c99b --- /dev/null +++ b/src/lib/db/inspectorSessions.ts @@ -0,0 +1,117 @@ +/** + * Database module: InspectorSessions + * CRUD + snapshot for inspector_sessions and inspector_session_requests tables. + */ + +import { randomUUID } from "crypto"; +import { getDbInstance } from "./core"; +import type { InspectorSessionRow } from "./_rowTypes"; + +interface InspectorSessionDbRow { + id: string; + name: string | null; + started_at: string; + ended_at: string | null; + request_count: number; + profile: string | null; +} + +interface InspectorSessionRequestDbRow { + session_id: string; + seq: number; + payload: string; +} + +function mapSessionRow(row: InspectorSessionDbRow): InspectorSessionRow { + return { + id: row.id, + name: row.name, + started_at: row.started_at, + ended_at: row.ended_at, + request_count: row.request_count, + profile: row.profile as "llm" | "custom" | "all" | null, + }; +} + +export function createSession(opts?: { + name?: string; + profile?: "llm" | "custom" | "all"; +}): { id: string; started_at: string } { + const db = getDbInstance(); + const id = randomUUID(); + const started_at = new Date().toISOString(); + + db.prepare( + `INSERT INTO inspector_sessions (id, name, started_at, profile) VALUES (?, ?, ?, ?)` + ).run(id, opts?.name ?? null, started_at, opts?.profile ?? null); + + return { id, started_at }; +} + +export function stopSession(id: string): void { + const db = getDbInstance(); + const ended_at = new Date().toISOString(); + db.prepare("UPDATE inspector_sessions SET ended_at = ? WHERE id = ?").run(ended_at, id); +} + +export function renameSession(id: string, name: string): void { + const db = getDbInstance(); + db.prepare("UPDATE inspector_sessions SET name = ? WHERE id = ?").run(name, id); +} + +export function listSessions(): InspectorSessionRow[] { + const db = getDbInstance(); + const rows = db + .prepare("SELECT * FROM inspector_sessions ORDER BY started_at DESC") + .all() as InspectorSessionDbRow[]; + return rows.map(mapSessionRow); +} + +export function getSession(id: string): InspectorSessionRow | null { + const db = getDbInstance(); + const row = db + .prepare("SELECT * FROM inspector_sessions WHERE id = ?") + .get(id) as InspectorSessionDbRow | undefined; + return row ? mapSessionRow(row) : null; +} + +export function appendSessionRequest(sessionId: string, payload: string): void { + const db = getDbInstance(); + + const runTransaction = db.transaction(() => { + // Get next seq atomically within transaction + const seqRow = db + .prepare( + "SELECT COALESCE(MAX(seq), 0) + 1 AS next_seq FROM inspector_session_requests WHERE session_id = ?" + ) + .get(sessionId) as { next_seq: number }; + + const nextSeq = seqRow.next_seq; + + db.prepare( + `INSERT INTO inspector_session_requests (session_id, seq, payload) VALUES (?, ?, ?)` + ).run(sessionId, nextSeq, payload); + + db.prepare( + "UPDATE inspector_sessions SET request_count = request_count + 1 WHERE id = ?" + ).run(sessionId); + }); + + runTransaction(); +} + +export function getSessionRequests(sessionId: string): Array<{ seq: number; payload: string }> { + const db = getDbInstance(); + const rows = db + .prepare( + "SELECT seq, payload FROM inspector_session_requests WHERE session_id = ? ORDER BY seq ASC" + ) + .all(sessionId) as InspectorSessionRequestDbRow[]; + return rows.map((r) => ({ seq: r.seq, payload: r.payload })); +} + +export function deleteSession(id: string): void { + const db = getDbInstance(); + // Cascade via FK ON DELETE CASCADE for inspector_session_requests + db.prepare("DELETE FROM inspector_sessions WHERE id = ?").run(id); +} From 47c0dce062a9ed41f7a4ae0ebf97830538ac907b Mon Sep 17 00:00:00 2001 From: diegosouzapw Date: Wed, 27 May 2026 19:24:26 -0300 Subject: [PATCH 4/5] chore(env): document AgentBridge + Inspector env vars and re-exports (F2) --- .env.example | 16 ++++++++++++++++ src/lib/localDb.ts | 7 +++++++ 2 files changed, 23 insertions(+) diff --git a/.env.example b/.env.example index c7e4911e4a..2c3547142a 100644 --- a/.env.example +++ b/.env.example @@ -1311,3 +1311,19 @@ APP_LOG_TO_FILE=true # ELECTRON_SMOKE_DATA_DIR= # ELECTRON_SMOKE_KEEP_DATA=0 # ELECTRON_SMOKE_STREAM_LOGS=0 + +# AgentBridge + Traffic Inspector (Group A) + +# AgentBridge +AGENTBRIDGE_UPSTREAM_CA_CERT= + +# Inspector +INSPECTOR_BUFFER_SIZE=1000 +INSPECTOR_HTTP_PROXY_PORT=8080 +INSPECTOR_HTTP_PROXY_AUTOSTART=false +INSPECTOR_TLS_INTERCEPT=false +INSPECTOR_SYSTEM_PROXY_GUARD_MINUTES=30 +INSPECTOR_MAX_BODY_KB=1024 +INSPECTOR_MASK_SECRETS=true +INSPECTOR_LLM_HOSTS_EXTRA= +INSPECTOR_INTERNAL_INGEST_TOKEN= diff --git a/src/lib/localDb.ts b/src/lib/localDb.ts index 648c03f658..dd912f891e 100755 --- a/src/lib/localDb.ts +++ b/src/lib/localDb.ts @@ -508,3 +508,10 @@ export { } from "./db/freeProxies"; export type { FreeProxyRecord, FreeProxyStats } from "./db/freeProxies"; + +// T-A-F2: AgentBridge state/mappings/bypass + Inspector custom hosts/sessions +export * from "./db/agentBridgeState"; +export * from "./db/agentBridgeMappings"; +export * from "./db/agentBridgeBypass"; +export * from "./db/inspectorCustomHosts"; +export * from "./db/inspectorSessions"; From 80fa37f30f73eb674fc73a126b174d570ae07a83 Mon Sep 17 00:00:00 2001 From: diegosouzapw Date: Wed, 27 May 2026 19:24:30 -0300 Subject: [PATCH 5/5] test(db): unit tests for F2 modules --- tests/unit/db-agent-bridge-bypass.test.ts | 133 +++++++++++++++++ tests/unit/db-agent-bridge-mappings.test.ts | 126 ++++++++++++++++ tests/unit/db-agent-bridge-state.test.ts | 113 ++++++++++++++ tests/unit/db-inspector-custom-hosts.test.ts | 141 ++++++++++++++++++ tests/unit/db-inspector-sessions.test.ts | 149 +++++++++++++++++++ 5 files changed, 662 insertions(+) create mode 100644 tests/unit/db-agent-bridge-bypass.test.ts create mode 100644 tests/unit/db-agent-bridge-mappings.test.ts create mode 100644 tests/unit/db-agent-bridge-state.test.ts create mode 100644 tests/unit/db-inspector-custom-hosts.test.ts create mode 100644 tests/unit/db-inspector-sessions.test.ts diff --git a/tests/unit/db-agent-bridge-bypass.test.ts b/tests/unit/db-agent-bridge-bypass.test.ts new file mode 100644 index 0000000000..a45e8f8831 --- /dev/null +++ b/tests/unit/db-agent-bridge-bypass.test.ts @@ -0,0 +1,133 @@ +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-db-agent-bridge-bypass-") +); +process.env.DATA_DIR = TEST_DATA_DIR; + +const core = await import("../../src/lib/db/core.ts"); +const mod = await import("../../src/lib/db/agentBridgeBypass.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 (error: any) { + if ((error?.code === "EBUSY" || error?.code === "EPERM") && attempt < 9) { + await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1))); + } else { + throw error; + } + } + } + + 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 }); +}); + +const DEFAULT_PATTERNS = [ + "*.googleapis.com", + "*.gstatic.com", + "accounts.google.com", + "login.microsoftonline.com", +]; + +test("getAllBypassPatterns returns empty array when table is empty", () => { + const rows = mod.getAllBypassPatterns(); + assert.deepEqual(rows, []); +}); + +test("seedDefaultBypassPatterns inserts default patterns with source=default", () => { + mod.seedDefaultBypassPatterns(DEFAULT_PATTERNS); + + const rows = mod.getAllBypassPatterns(); + assert.equal(rows.length, DEFAULT_PATTERNS.length); + + for (const row of rows) { + assert.equal(row.source, "default"); + assert.ok(DEFAULT_PATTERNS.includes(row.pattern)); + } +}); + +test("seedDefaultBypassPatterns is idempotent — calling twice does not duplicate", () => { + mod.seedDefaultBypassPatterns(DEFAULT_PATTERNS); + mod.seedDefaultBypassPatterns(DEFAULT_PATTERNS); + + const rows = mod.getAllBypassPatterns(); + assert.equal(rows.length, DEFAULT_PATTERNS.length); +}); + +test("getUserBypassPatterns returns only user patterns", () => { + mod.seedDefaultBypassPatterns(DEFAULT_PATTERNS); + mod.replaceUserBypassPatterns(["*.internal.example.com", "localhost"]); + + const userPatterns = mod.getUserBypassPatterns(); + assert.equal(userPatterns.length, 2); + assert.ok(userPatterns.includes("*.internal.example.com")); + assert.ok(userPatterns.includes("localhost")); + + // Defaults should not appear in user patterns + for (const p of DEFAULT_PATTERNS) { + assert.ok(!userPatterns.includes(p)); + } +}); + +test("replaceUserBypassPatterns replaces only user entries — defaults untouched", () => { + mod.seedDefaultBypassPatterns(DEFAULT_PATTERNS); + mod.replaceUserBypassPatterns(["custom.host.1"]); + mod.replaceUserBypassPatterns(["custom.host.2", "custom.host.3"]); + + const allRows = mod.getAllBypassPatterns(); + const defaultRows = allRows.filter((r) => r.source === "default"); + const userRows = allRows.filter((r) => r.source === "user"); + + assert.equal(defaultRows.length, DEFAULT_PATTERNS.length); + assert.equal(userRows.length, 2); + + const userPatterns = userRows.map((r) => r.pattern); + assert.ok(!userPatterns.includes("custom.host.1"), "old user pattern must be replaced"); + assert.ok(userPatterns.includes("custom.host.2")); + assert.ok(userPatterns.includes("custom.host.3")); +}); + +test("replaceUserBypassPatterns with empty array clears all user patterns", () => { + mod.seedDefaultBypassPatterns(DEFAULT_PATTERNS); + mod.replaceUserBypassPatterns(["temp.host"]); + mod.replaceUserBypassPatterns([]); + + const userPatterns = mod.getUserBypassPatterns(); + assert.equal(userPatterns.length, 0); + + // Defaults remain + const allRows = mod.getAllBypassPatterns(); + assert.equal(allRows.length, DEFAULT_PATTERNS.length); +}); + +test("getAllBypassPatterns returns both default and user patterns", () => { + mod.seedDefaultBypassPatterns(["*.example.com"]); + mod.replaceUserBypassPatterns(["custom.host"]); + + const allRows = mod.getAllBypassPatterns(); + assert.equal(allRows.length, 2); + + const sources = new Set(allRows.map((r) => r.source)); + assert.ok(sources.has("default")); + assert.ok(sources.has("user")); +}); diff --git a/tests/unit/db-agent-bridge-mappings.test.ts b/tests/unit/db-agent-bridge-mappings.test.ts new file mode 100644 index 0000000000..5c03d24fa4 --- /dev/null +++ b/tests/unit/db-agent-bridge-mappings.test.ts @@ -0,0 +1,126 @@ +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-db-agent-bridge-mappings-") +); +process.env.DATA_DIR = TEST_DATA_DIR; + +const core = await import("../../src/lib/db/core.ts"); +const mod = await import("../../src/lib/db/agentBridgeMappings.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 (error: any) { + if ((error?.code === "EBUSY" || error?.code === "EPERM") && attempt < 9) { + await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1))); + } else { + throw error; + } + } + } + + 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 }); +}); + +test("getMappingsForAgent returns empty array when no mappings exist", () => { + const rows = mod.getMappingsForAgent("antigravity"); + assert.deepEqual(rows, []); +}); + +test("setMappings inserts and retrieves mappings for an agent", () => { + mod.setMappings("copilot", [ + { source: "gpt-4", target: "openai/gpt-4.1" }, + { source: "gpt-3.5-turbo", target: "openai/gpt-4o-mini" }, + ]); + + const rows = mod.getMappingsForAgent("copilot"); + assert.equal(rows.length, 2); + + const sources = rows.map((r) => r.source_model); + assert.ok(sources.includes("gpt-4")); + assert.ok(sources.includes("gpt-3.5-turbo")); + + const gpt4Row = rows.find((r) => r.source_model === "gpt-4"); + assert.equal(gpt4Row?.target_model, "openai/gpt-4.1"); + assert.equal(gpt4Row?.agent_id, "copilot"); +}); + +test("setMappings is transactional — replaces all mappings idempotently", () => { + // First set + mod.setMappings("cursor", [ + { source: "claude-3-5-sonnet", target: "anthropic/claude-sonnet-4-5" }, + ]); + + // Second set — should replace (not accumulate) + mod.setMappings("cursor", [ + { source: "claude-3-opus", target: "anthropic/claude-opus-4" }, + { source: "gpt-4o", target: "openai/gpt-4.1" }, + ]); + + const rows = mod.getMappingsForAgent("cursor"); + assert.equal(rows.length, 2); + + const sources = rows.map((r) => r.source_model); + assert.ok(!sources.includes("claude-3-5-sonnet"), "old mapping should be replaced"); + assert.ok(sources.includes("claude-3-opus")); + assert.ok(sources.includes("gpt-4o")); +}); + +test("setMappings with empty array clears all mappings for agent", () => { + mod.setMappings("zed", [{ source: "gpt-4", target: "openai/gpt-4.1" }]); + mod.setMappings("zed", []); + + const rows = mod.getMappingsForAgent("zed"); + assert.equal(rows.length, 0); +}); + +test("setMappings does not affect mappings for other agents", () => { + mod.setMappings("kiro", [{ source: "gpt-4", target: "openai/gpt-4.1" }]); + mod.setMappings("codex", [{ source: "o3", target: "openai/o3" }]); + mod.setMappings("kiro", [{ source: "gpt-4o", target: "openai/gpt-4o" }]); + + const codexRows = mod.getMappingsForAgent("codex"); + assert.equal(codexRows.length, 1); + assert.equal(codexRows[0].source_model, "o3"); +}); + +test("deleteMapping removes a specific source mapping", () => { + mod.setMappings("antigravity", [ + { source: "gpt-4", target: "openai/gpt-4.1" }, + { source: "gpt-3.5-turbo", target: "openai/gpt-4o-mini" }, + ]); + + mod.deleteMapping("antigravity", "gpt-4"); + + const rows = mod.getMappingsForAgent("antigravity"); + assert.equal(rows.length, 1); + assert.equal(rows[0].source_model, "gpt-3.5-turbo"); +}); + +test("deleteMapping is a no-op when mapping does not exist", () => { + mod.setMappings("claude-code", [{ source: "claude-3", target: "anthropic/claude-opus-4" }]); + mod.deleteMapping("claude-code", "nonexistent-model"); + + const rows = mod.getMappingsForAgent("claude-code"); + assert.equal(rows.length, 1); +}); diff --git a/tests/unit/db-agent-bridge-state.test.ts b/tests/unit/db-agent-bridge-state.test.ts new file mode 100644 index 0000000000..919c17646b --- /dev/null +++ b/tests/unit/db-agent-bridge-state.test.ts @@ -0,0 +1,113 @@ +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-db-agent-bridge-state-")); +process.env.DATA_DIR = TEST_DATA_DIR; + +const core = await import("../../src/lib/db/core.ts"); +const mod = await import("../../src/lib/db/agentBridgeState.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 (error: any) { + if ((error?.code === "EBUSY" || error?.code === "EPERM") && attempt < 9) { + await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1))); + } else { + throw error; + } + } + } + + 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 }); +}); + +test("migration is idempotent — running getDbInstance twice does not throw", () => { + // First init + const db1 = core.getDbInstance(); + assert.ok(db1); + core.resetDbInstance(); + + // Second init — migrations should skip already-applied files + const db2 = core.getDbInstance(); + assert.ok(db2); +}); + +test("getAgentBridgeState returns null for unknown agent", () => { + const result = mod.getAgentBridgeState("unknown-agent"); + assert.equal(result, null); +}); + +test("upsertAgentBridgeState creates a new row with defaults", () => { + mod.upsertAgentBridgeState({ agent_id: "copilot" }); + const row = mod.getAgentBridgeState("copilot"); + + assert.ok(row); + assert.equal(row.agent_id, "copilot"); + assert.equal(row.dns_enabled, false); + assert.equal(row.cert_trusted, false); + assert.equal(row.setup_completed, false); + assert.equal(row.last_started_at, null); + assert.equal(row.last_error, null); +}); + +test("upsertAgentBridgeState updates an existing row", () => { + mod.upsertAgentBridgeState({ agent_id: "cursor" }); + mod.upsertAgentBridgeState({ agent_id: "cursor", dns_enabled: true, cert_trusted: true }); + + const row = mod.getAgentBridgeState("cursor"); + assert.ok(row); + assert.equal(row.dns_enabled, true); + assert.equal(row.cert_trusted, true); + assert.equal(row.setup_completed, false); +}); + +test("setLastStarted persists timestamp and auto-creates row if missing", () => { + const ts = new Date().toISOString(); + mod.setLastStarted("kiro", ts); + + const row = mod.getAgentBridgeState("kiro"); + assert.ok(row); + assert.equal(row.last_started_at, ts); +}); + +test("setLastError persists error string and clears it with null", () => { + mod.upsertAgentBridgeState({ agent_id: "codex" }); + mod.setLastError("codex", "upstream timeout"); + + let row = mod.getAgentBridgeState("codex"); + assert.equal(row?.last_error, "upstream timeout"); + + mod.setLastError("codex", null); + row = mod.getAgentBridgeState("codex"); + assert.equal(row?.last_error, null); +}); + +test("getAllAgentBridgeStates returns all rows", () => { + mod.upsertAgentBridgeState({ agent_id: "antigravity" }); + mod.upsertAgentBridgeState({ agent_id: "zed" }); + + const rows = mod.getAllAgentBridgeStates(); + assert.ok(rows.length >= 2); + const ids = rows.map((r) => r.agent_id); + assert.ok(ids.includes("antigravity")); + assert.ok(ids.includes("zed")); +}); diff --git a/tests/unit/db-inspector-custom-hosts.test.ts b/tests/unit/db-inspector-custom-hosts.test.ts new file mode 100644 index 0000000000..39ad298ae8 --- /dev/null +++ b/tests/unit/db-inspector-custom-hosts.test.ts @@ -0,0 +1,141 @@ +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-db-inspector-custom-hosts-") +); +process.env.DATA_DIR = TEST_DATA_DIR; + +const core = await import("../../src/lib/db/core.ts"); +const mod = await import("../../src/lib/db/inspectorCustomHosts.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 (error: any) { + if ((error?.code === "EBUSY" || error?.code === "EPERM") && attempt < 9) { + await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1))); + } else { + throw error; + } + } + } + + 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 }); +}); + +test("listCustomHosts returns empty array initially", () => { + const rows = mod.listCustomHosts(); + assert.deepEqual(rows, []); +}); + +test("addCustomHost inserts a host with defaults", () => { + mod.addCustomHost("api.openai.com"); + + const rows = mod.listCustomHosts(); + assert.equal(rows.length, 1); + assert.equal(rows[0].host, "api.openai.com"); + assert.equal(rows[0].enabled, true); + assert.equal(rows[0].kind, "custom"); + assert.equal(rows[0].label, null); + assert.equal(rows[0].last_seen_at, null); + assert.ok(rows[0].added_at); +}); + +test("addCustomHost respects kind and label parameters", () => { + mod.addCustomHost("api.anthropic.com", "llm", "Anthropic API"); + + const rows = mod.listCustomHosts(); + const row = rows.find((r) => r.host === "api.anthropic.com"); + assert.ok(row); + assert.equal(row.kind, "llm"); + assert.equal(row.label, "Anthropic API"); +}); + +test("addCustomHost is idempotent — duplicate inserts are ignored", () => { + mod.addCustomHost("api.openai.com"); + mod.addCustomHost("api.openai.com"); + + const rows = mod.listCustomHosts(); + assert.equal(rows.length, 1); +}); + +test("toggleCustomHost disables an enabled host", () => { + mod.addCustomHost("api.openai.com"); + mod.toggleCustomHost("api.openai.com", false); + + const rows = mod.listCustomHosts(); + assert.equal(rows[0].enabled, false); +}); + +test("toggleCustomHost re-enables a disabled host", () => { + mod.addCustomHost("api.openai.com"); + mod.toggleCustomHost("api.openai.com", false); + mod.toggleCustomHost("api.openai.com", true); + + const rows = mod.listCustomHosts(); + assert.equal(rows[0].enabled, true); +}); + +test("listCustomHosts with enabledOnly=true excludes disabled hosts", () => { + mod.addCustomHost("api.openai.com"); + mod.addCustomHost("api.anthropic.com"); + mod.toggleCustomHost("api.anthropic.com", false); + + const all = mod.listCustomHosts(); + const enabledOnly = mod.listCustomHosts({ enabledOnly: true }); + + assert.equal(all.length, 2); + assert.equal(enabledOnly.length, 1); + assert.equal(enabledOnly[0].host, "api.openai.com"); +}); + +test("removeCustomHost deletes the host", () => { + mod.addCustomHost("api.openai.com"); + mod.addCustomHost("api.anthropic.com"); + + mod.removeCustomHost("api.openai.com"); + + const rows = mod.listCustomHosts(); + assert.equal(rows.length, 1); + assert.equal(rows[0].host, "api.anthropic.com"); +}); + +test("removeCustomHost is a no-op for non-existent hosts", () => { + mod.addCustomHost("api.openai.com"); + mod.removeCustomHost("nonexistent.host"); + + const rows = mod.listCustomHosts(); + assert.equal(rows.length, 1); +}); + +test("touchLastSeen updates last_seen_at timestamp", () => { + mod.addCustomHost("api.openai.com"); + + const before = mod.listCustomHosts()[0]; + assert.equal(before.last_seen_at, null); + + mod.touchLastSeen("api.openai.com"); + + const after = mod.listCustomHosts()[0]; + assert.ok(after.last_seen_at !== null); + assert.ok(Date.parse(after.last_seen_at as string) > 0); +}); diff --git a/tests/unit/db-inspector-sessions.test.ts b/tests/unit/db-inspector-sessions.test.ts new file mode 100644 index 0000000000..5131a35433 --- /dev/null +++ b/tests/unit/db-inspector-sessions.test.ts @@ -0,0 +1,149 @@ +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-db-inspector-sessions-") +); +process.env.DATA_DIR = TEST_DATA_DIR; + +const core = await import("../../src/lib/db/core.ts"); +const mod = await import("../../src/lib/db/inspectorSessions.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 (error: any) { + if ((error?.code === "EBUSY" || error?.code === "EPERM") && attempt < 9) { + await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1))); + } else { + throw error; + } + } + } + + 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 }); +}); + +test("createSession returns a uuid and started_at timestamp", () => { + const { id, started_at } = mod.createSession(); + + assert.match(id, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i); + assert.ok(Date.parse(started_at) > 0); +}); + +test("createSession persists name and profile", () => { + const { id } = mod.createSession({ name: "My Session", profile: "llm" }); + + const row = mod.getSession(id); + assert.ok(row); + assert.equal(row.name, "My Session"); + assert.equal(row.profile, "llm"); + assert.equal(row.ended_at, null); + assert.equal(row.request_count, 0); +}); + +test("listSessions returns all created sessions", () => { + const { id: id1 } = mod.createSession({ name: "First" }); + const { id: id2 } = mod.createSession({ name: "Second" }); + + const sessions = mod.listSessions(); + assert.ok(sessions.length >= 2); + + const ids = sessions.map((s) => s.id); + assert.ok(ids.includes(id1), "First session should be in the list"); + assert.ok(ids.includes(id2), "Second session should be in the list"); +}); + +test("appendSessionRequest increments seq atomically and updates request_count", () => { + const { id } = mod.createSession(); + + mod.appendSessionRequest(id, JSON.stringify({ a: 1 })); + mod.appendSessionRequest(id, JSON.stringify({ a: 2 })); + mod.appendSessionRequest(id, JSON.stringify({ a: 3 })); + + const session = mod.getSession(id); + assert.equal(session?.request_count, 3); + + const requests = mod.getSessionRequests(id); + assert.equal(requests.length, 3); + assert.equal(requests[0].seq, 1); + assert.equal(requests[1].seq, 2); + assert.equal(requests[2].seq, 3); +}); + +test("getSessionRequests returns payloads in seq order", () => { + const { id } = mod.createSession(); + + mod.appendSessionRequest(id, "payload-A"); + mod.appendSessionRequest(id, "payload-B"); + mod.appendSessionRequest(id, "payload-C"); + + const requests = mod.getSessionRequests(id); + assert.equal(requests[0].payload, "payload-A"); + assert.equal(requests[1].payload, "payload-B"); + assert.equal(requests[2].payload, "payload-C"); +}); + +test("stopSession sets ended_at timestamp", () => { + const { id } = mod.createSession(); + + const before = mod.getSession(id); + assert.equal(before?.ended_at, null); + + mod.stopSession(id); + + const after = mod.getSession(id); + assert.ok(after?.ended_at !== null); + assert.ok(Date.parse(after?.ended_at as string) > 0); +}); + +test("renameSession updates the name", () => { + const { id } = mod.createSession({ name: "Old Name" }); + mod.renameSession(id, "New Name"); + + const row = mod.getSession(id); + assert.equal(row?.name, "New Name"); +}); + +test("deleteSession removes session and cascade-deletes requests", () => { + const { id } = mod.createSession(); + mod.appendSessionRequest(id, "payload-1"); + mod.appendSessionRequest(id, "payload-2"); + + mod.deleteSession(id); + + const session = mod.getSession(id); + assert.equal(session, null); + + const requests = mod.getSessionRequests(id); + assert.equal(requests.length, 0); +}); + +test("getSession returns null for non-existent id", () => { + const row = mod.getSession("00000000-0000-4000-8000-000000000000"); + assert.equal(row, null); +}); + +test("getSessionRequests returns empty array for session with no requests", () => { + const { id } = mod.createSession(); + const requests = mod.getSessionRequests(id); + assert.deepEqual(requests, []); +});