Files
OmniRoute/tests/unit/database-settings-maintenance.test.ts
Diego Rodrigues de Sa e Souza 191009dd23 Release v3.8.7 (#2919)
* feat(plugins): WordPress-style plugin system backend

* fix(plugins): address code review feedback

- Path traversal guard: validate entryPoint stays within plugin dir
- install() now handles direct plugin directories (not just parent dirs)
- Non-null assertion replaced with explicit null check
- require efficiency: allowedModules map moved outside function
- Source wrapper: add newlines to prevent trailing comment issues
- Config validation: validate values against configSchema on save
- Dynamic import comment: clarify Node.js caching behavior

Co-Authored-By: OpenClaude (mimo-v2.5-pro) <openclaude@gitlawb.com>

* fix(plugins): replace vm with child_process, add auth to all routes

Addresses all remaining code review feedback:

1. **Loader rewrite**: Replaced Node.js vm module with child_process.fork()
   for proper process-level isolation. Complies with Rule 3 (no eval).
   Each plugin runs in a separate Node.js process with IPC communication.

2. **Auth on all routes**: Added requireManagementAuth to all 6 plugin
   API route files (list, install, scan, details, activate, deactivate, config).

3. **Env filtering**: Only safe env vars passed to plugin processes unless
   "env" permission is granted.

Co-Authored-By: OpenClaude (mimo-v2.5-pro) <openclaude@gitlawb.com>

* fix(plugins): security + ESM fixes for loader and manager

loader.ts:
- Fix IPC: use process.send()/process.on("message") instead of worker_threads.parentPort
- Fix ESM: write host script as .mjs (not .js) to force ESM execution
- Add timeout: 10s default on callHook() with Promise.race
- Add SIGKILL escalation: SIGTERM first, then SIGKILL after 3s grace
- Fix env filtering: use allowlist (safeKeys) instead of passing all env vars
- Clear timeout on successful IPC response (no timer leak)

manager.ts:
- Fix path traversal: use fs.realpath() instead of startsWith()
- Fix imports: use registerHook/unregisterHooks from hooks.ts
- Register hooks individually via registerHook(event, name, handler)

hooks.ts:
- Copied from feat/plugin-custom-hooks (canonical registry)

* feat(discovery): add discovery tool stub service

Phase 1 scaffold for automated provider discovery:
- DiscoveryConfig, DiscoveryResult types
- probeEndpoint() for URL availability checking
- scanProvider() stub (Phase 2 will implement real scanning)
- getDiscoveryResults() stub
- Default config: disabled (opt-in)

* chore(plugins): slop cleanup — pino logger, remove redundant sorts

- index.ts: replace console.log/error with pino structured logging
- hooks.ts: remove redundant .sort() in emitHookBlocking/runOnResponse (already sorted on registration)
- manager.ts: add readFile import

* test(plugins): add scanner, loader, manager unit tests

- scanner: 9 tests (discovery, hidden dirs, validation, entry point, multiple)
- loader: 5 tests (type contracts, Plugin/PluginContext/PluginResult interfaces)
- manager: 6 tests (singleton, lifecycle methods, error on unknown)
- Total: 20 tests, all passing

* fix(settings): add missing home page pin keys to updateSettingsSchema

* feat(plugins): add i18n keys to all 42 locales

* fix(settings): add missing security keys to updateSettingsSchema and add tests

* fix(usage): analytics route reads combo_name/requested_model from call_logs only

The 3.8.6 variant of #2904 added SELECTs of combo_name/requested_model
against usage_history, but those columns only exist in call_logs (no
migration adds them to usage_history). This returned HTTP 500 on
/api/usage/analytics. Restore the working query shape from the 3.8.7
variant. Fixes 18 failing usage-analytics-route tests.

* fix(types,test): resolve noImplicitAny in progressiveAging + align semaphore test to #2903 gate pruning

- progressiveAging: type compression results so messages[0].content is
  indexable (was TS7053 against {}); restores typecheck:noimplicit:core gate.
- services-branch-hardening: #2903 (perf-ram) prunes idle rate-limit gates
  on zero; assert no-running/empty-queue without assuming the entry persists.

* fix(analytics): address merged review regressions

* fix(executor): normalize max effort for openai shape providers

* Make zero-latency combo optimizations opt-in

* Address zero-latency combo review feedback

* chore(release): sync v3.8.7 touchpoints + credit contributors

- llm.txt → 3.8.7 (Current version + Key Features header)
- CHANGELOG: add Dmitry Kuznetsov & Nikolay Alafuzov to 3.8.6 Hall of Contributors
- version already 3.8.7 across package.json/open-sse/electron/openapi (from #2909)

* fix(cleanup): restore usage history cutoff boundary

* docs(changelog): rank 3.8.6 contributors in a commits table with their PRs

* fix(dashboard): theme ReactFlow Controls +/- buttons for dark mode

* fix(settings): add missing home page pin keys to updateSettingsSchema

* fix(settings): add missing security keys to updateSettingsSchema and add tests

* fix(executor): normalize max effort for openai shape providers

* Make zero-latency combo optimizations opt-in

* Address zero-latency combo review feedback

* fix(analytics): address merged review regressions

* fix(cleanup): restore usage history cutoff boundary

* feat(plugins): WordPress-style plugin system backend

* fix(plugins): address code review feedback

- Path traversal guard: validate entryPoint stays within plugin dir
- install() now handles direct plugin directories (not just parent dirs)
- Non-null assertion replaced with explicit null check
- require efficiency: allowedModules map moved outside function
- Source wrapper: add newlines to prevent trailing comment issues
- Config validation: validate values against configSchema on save
- Dynamic import comment: clarify Node.js caching behavior

Co-Authored-By: OpenClaude (mimo-v2.5-pro) <openclaude@gitlawb.com>

* fix(plugins): replace vm with child_process, add auth to all routes

Addresses all remaining code review feedback:

1. **Loader rewrite**: Replaced Node.js vm module with child_process.fork()
   for proper process-level isolation. Complies with Rule 3 (no eval).
   Each plugin runs in a separate Node.js process with IPC communication.

2. **Auth on all routes**: Added requireManagementAuth to all 6 plugin
   API route files (list, install, scan, details, activate, deactivate, config).

3. **Env filtering**: Only safe env vars passed to plugin processes unless
   "env" permission is granted.

Co-Authored-By: OpenClaude (mimo-v2.5-pro) <openclaude@gitlawb.com>

* fix(plugins): security + ESM fixes for loader and manager

loader.ts:
- Fix IPC: use process.send()/process.on("message") instead of worker_threads.parentPort
- Fix ESM: write host script as .mjs (not .js) to force ESM execution
- Add timeout: 10s default on callHook() with Promise.race
- Add SIGKILL escalation: SIGTERM first, then SIGKILL after 3s grace
- Fix env filtering: use allowlist (safeKeys) instead of passing all env vars
- Clear timeout on successful IPC response (no timer leak)

manager.ts:
- Fix path traversal: use fs.realpath() instead of startsWith()
- Fix imports: use registerHook/unregisterHooks from hooks.ts
- Register hooks individually via registerHook(event, name, handler)

hooks.ts:
- Copied from feat/plugin-custom-hooks (canonical registry)

* feat(discovery): add discovery tool stub service

Phase 1 scaffold for automated provider discovery:
- DiscoveryConfig, DiscoveryResult types
- probeEndpoint() for URL availability checking
- scanProvider() stub (Phase 2 will implement real scanning)
- getDiscoveryResults() stub
- Default config: disabled (opt-in)

* chore(plugins): slop cleanup — pino logger, remove redundant sorts

- index.ts: replace console.log/error with pino structured logging
- hooks.ts: remove redundant .sort() in emitHookBlocking/runOnResponse (already sorted on registration)
- manager.ts: add readFile import

* test(plugins): add scanner, loader, manager unit tests

- scanner: 9 tests (discovery, hidden dirs, validation, entry point, multiple)
- loader: 5 tests (type contracts, Plugin/PluginContext/PluginResult interfaces)
- manager: 6 tests (singleton, lifecycle methods, error on unknown)
- Total: 20 tests, all passing

* feat(plugins): add i18n keys to all 42 locales

* chore(plugins): remove duplicate migration 059_create_plugins.sql

* chore(plugins): remove duplicate migration 059_create_plugins.sql (post-merge)

* fix(sse): guard non-string error.code in proxyFetch + harden model parsing (#2463) (#2923)

Integrated into release/v3.8.7

* fix(docker): add runner-web stage with Playwright Chromium (#2832) (#2846)

Integrated into release/v3.8.7

* docs(changelog): document NVIDIA NIM and error code type-crash fix (#2463)

* test: ignore NVIDIA_BASE_URL and NVIDIA_MODEL in env contract check

---------

Co-authored-by: oyi77 <oyi77@users.noreply.github.com>
Co-authored-by: OpenClaude (mimo-v2.5-pro) <openclaude@gitlawb.com>
Co-authored-by: Apostol Apostolov <theapoapostolov@gmail.com>
Co-authored-by: Halil Tezcan KARABULUT <info@hlltzcnkb.com>
Co-authored-by: R.D. <rogerproself@gmail.com>
2026-05-29 19:54:00 -03:00

222 lines
7.6 KiB
TypeScript

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-settings-"));
process.env.DATA_DIR = TEST_DATA_DIR;
process.env.DISABLE_SQLITE_AUTO_BACKUP = "true";
const core = await import("../../src/lib/db/core.ts");
const databaseSettings = await import("../../src/lib/db/databaseSettings.ts");
const databaseSettingsRoute = await import("../../src/app/api/settings/database/route.ts");
const settingsDb = await import("../../src/lib/db/settings.ts");
const cleanup = await import("../../src/lib/db/cleanup.ts");
const aggregateHistory = await import("../../src/lib/usage/aggregateHistory.ts");
type CountRow = {
count: number;
};
type UsageSummaryRow = {
total_requests: number;
total_input_tokens: number;
total_output_tokens: number;
total_cost: number;
};
function resetStorage() {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}
function makeJsonRequest(method: string, body?: unknown): Request {
return new Request("http://localhost/api/settings/database", {
method,
headers: { "Content-Type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
});
}
test.beforeEach(() => {
resetStorage();
});
test.after(() => {
resetStorage();
});
test("database settings route returns mapped stats and persists editable sections", async () => {
const current = databaseSettings.getUserDatabaseSettings();
const response = await databaseSettingsRoute.PATCH(
makeJsonRequest("PATCH", {
retention: { ...current.retention, callLogs: 12, autoCleanupEnabled: false },
aggregation: { ...current.aggregation, enabled: false, rawDataRetentionDays: 8 },
}) as never
);
const body = await response.json();
assert.equal(response.status, 200);
assert.equal(body.retention.callLogs, 12);
assert.equal(body.aggregation.rawDataRetentionDays, 8);
assert.equal(typeof body.location.databasePath, "string");
assert.equal(typeof body.location.dataDir, "string");
assert.equal(typeof body.location.walSizeBytes, "number");
assert.equal(typeof body.stats.databaseSizeBytes, "number");
assert.equal(typeof body.stats.pageCount, "number");
assert.equal(typeof body.stats.freelistCount, "number");
const db = core.getDbInstance();
const stored = db
.prepare(
"SELECT value FROM key_value WHERE namespace = 'databaseSettings' AND key = 'retention.callLogs'"
)
.get() as { value: string } | undefined;
assert.equal(JSON.parse(stored?.value ?? "null"), 12);
const getResponse = await databaseSettingsRoute.GET(makeJsonRequest("GET") as never);
const getBody = await getResponse.json();
assert.equal(getResponse.status, 200);
assert.equal(getBody.retention.callLogs, 12);
assert.equal(getBody.aggregation.rawDataRetentionDays, 8);
});
test("database settings reader supports legacy flat keys and lets nested saves win", () => {
const db = core.getDbInstance();
db.prepare(
"INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES ('databaseSettings', ?, ?)"
).run("callLogs", JSON.stringify(99));
assert.equal(databaseSettings.getUserDatabaseSettings().retention.callLogs, 99);
databaseSettings.updateDatabaseSettings({
retention: {
...databaseSettings.getUserDatabaseSettings().retention,
callLogs: 7,
},
});
assert.equal(databaseSettings.getUserDatabaseSettings().retention.callLogs, 7);
});
test("database log settings mirror the runtime pipeline toggle", async () => {
await settingsDb.updateSettings({ call_log_pipeline_enabled: false });
assert.equal(databaseSettings.getUserDatabaseSettings().logs.callLogPipelineEnabled, false);
databaseSettings.updateDatabaseSettings({
logs: {
...databaseSettings.getUserDatabaseSettings().logs,
callLogPipelineEnabled: true,
},
});
const settings = await settingsDb.getSettings();
assert.equal(settings.call_log_pipeline_enabled, true);
assert.equal(databaseSettings.getUserDatabaseSettings().logs.callLogPipelineEnabled, true);
});
test("purgeDetailedLogs deletes request_detail_logs", async () => {
const db = core.getDbInstance();
db.prepare("INSERT INTO request_detail_logs (id, timestamp, duration_ms) VALUES (?, ?, ?)").run(
"detail-1",
new Date().toISOString(),
10
);
db.prepare("INSERT INTO request_detail_logs (id, timestamp, duration_ms) VALUES (?, ?, ?)").run(
"detail-2",
new Date().toISOString(),
20
);
const result = await cleanup.purgeDetailedLogs();
assert.equal(result.errors, 0);
assert.equal(result.deleted, 2);
assert.equal(
(db.prepare("SELECT COUNT(*) AS count FROM request_detail_logs").get() as CountRow).count,
0
);
});
test("usage aggregation upserts replace recomputed totals instead of adding them twice", async () => {
const db = core.getDbInstance();
const insertSnapshot = db.prepare(
`INSERT INTO quota_snapshots
(provider, connection_id, window_key, remaining_percentage, is_exhausted, raw_data, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`
);
insertSnapshot.run(
"openai",
"conn-1",
"daily",
90,
0,
JSON.stringify({ model: "gpt-test", input_tokens: 10, output_tokens: 4, cost: 0.25 }),
"2026-05-01 10:15:00"
);
insertSnapshot.run(
"openai",
"conn-1",
"daily",
80,
0,
JSON.stringify({ model: "gpt-test", input_tokens: 20, output_tokens: 6, cost: 0.5 }),
"2026-05-01 10:45:00"
);
await aggregateHistory.rollupDailyUsage("2026-05-01", "2026-05-01");
await aggregateHistory.rollupDailyUsage("2026-05-01", "2026-05-01");
await aggregateHistory.rollupHourlyQuota("2026-05-01 10:00:00", "2026-05-01 10:59:59");
await aggregateHistory.rollupHourlyQuota("2026-05-01 10:00:00", "2026-05-01 10:59:59");
const daily = db.prepare("SELECT * FROM daily_usage_summary").get() as UsageSummaryRow;
const hourly = db.prepare("SELECT * FROM hourly_usage_summary").get() as UsageSummaryRow;
assert.equal(daily.total_requests, 2);
assert.equal(daily.total_input_tokens, 30);
assert.equal(daily.total_output_tokens, 10);
assert.equal(daily.total_cost, 0.75);
assert.equal(hourly.total_requests, 2);
assert.equal(hourly.total_input_tokens, 30);
assert.equal(hourly.total_output_tokens, 10);
assert.equal(hourly.total_cost, 0.75);
});
test("cleanupUsageHistory rolls up and deletes old rows using the same day boundary", async () => {
const db = core.getDbInstance();
const oldTimestamp = "2024-01-01T12:00:00.000Z";
const recentTimestamp = new Date().toISOString();
databaseSettings.updateDatabaseSettings({
retention: {
...databaseSettings.getUserDatabaseSettings().retention,
usageHistory: 30,
},
});
const insertUsage = db.prepare(
`INSERT INTO usage_history (provider, model, timestamp, tokens_input, tokens_output, success, latency_ms)
VALUES (?, ?, ?, ?, ?, ?, ?)`
);
insertUsage.run("openai", "gpt-test", oldTimestamp, 100, 40, 1, 200);
insertUsage.run("openai", "gpt-test", recentTimestamp, 7, 3, 1, 100);
const result = await cleanup.cleanupUsageHistory();
assert.equal(result.errors, 0);
assert.equal(result.deleted, 1);
const remaining = db.prepare("SELECT COUNT(*) AS count FROM usage_history").get() as CountRow;
assert.equal(remaining.count, 1);
const daily = db.prepare("SELECT * FROM daily_usage_summary").get() as UsageSummaryRow;
assert.equal(daily.total_requests, 1);
assert.equal(daily.total_input_tokens, 100);
assert.equal(daily.total_output_tokens, 40);
});