Files
OmniRoute/tests/unit/services/ServiceSupervisor.test.ts
Diego Rodrigues de Sa e Souza 35dbf0eea1 Release v3.8.25 (#3866)
* chore(release): continue v3.8.25 development cycle after main code-sync (r5)

main fast-forwarded to release/v3.8.25 (#3863): unblocked Build+Docker via
#3864, plus #3837 (mimocode proxy) and #3862 (trivy bump). This marker
re-opens the umbrella PR for further v3.8.25 work. No version bump.

* fix(db): persist the Keep-latest-backups retention setting (#3834) (#3867)

* fix(oauth): clear GitLab Duo setup message instead of 500 (#3861) (#3868)

* test(oauth): prove refresh_token preserved on real gemini-cli/antigravity dispatch (#3850) (#3869)

* feat(compression-ui): unified compression config UI — per-engine pages + combos editor + menu + WS default-on (#3860)

Integrated into release/v3.8.25 — feat(compression-ui): unified compression configuration UI (Compression Hub + per-engine Lite/Aggressive/Ultra pages + combos editor + sidebar entry + live-WS default-on). File-size re-baselined for sidebarVisibility.ts/chatCore.ts growth; orphan ws test relocated to a collected path.

* docs(changelog): complete the v3.8.25 release notes + credit all contributors

Audited every commit since v3.8.24 and filled the gaps the [3.8.25] section
was missing: a New Features section (compression engines + Compression Studios
#3848, compression UI #3860, injection-guard #3857, kiro discovery #3836, Veo
#3839, mimocode proxy #3837, Arena ELO flag #3821), 9 more Fixed entries
(#3811/#3807/#3759/#3849/#3838/#3835/#3814/#3820/#3819), a Security section
(CCR IDOR #3859, supply-chain #3824), and an Internal/Quality section. Every
contributor and issue reporter is now credited.

* docs(changelog): restore + complete the v3.8.25 release notes

Re-adds CHANGELOG.md (a prior server-side commit accidentally dropped it) with
the complete, audited [3.8.25] section: New Features, the full Fixed list,
Security & Hardening, and Internal/Quality — every contributor and issue
reporter credited.

* chore(release): finalize v3.8.25 — reconcile CHANGELOG + i18n mirrors, document OMNIROUTE_MAX_PENDING_MIGRATIONS, green the unit suite

Release-gate reconciliation for v3.8.25:
- CHANGELOG: dated 2026-06-14, linked #3826, rolled up file-size re-baselines (#3823/#3833),
  recorded the test-greening; re-synced all 41 i18n CHANGELOG mirrors.
- Documented OMNIROUTE_MAX_PENDING_MIGRATIONS (#3416) in .env.example + ENVIRONMENT.md.
- Greened the unit suite (was merged red on 4 CI shards): aligned 10 stale tests to this
  cycle's intended behavior (#3838/#3822/#3501/SOCKS5/Vertex-Express/Antigravity) and the
  same-provider 503 fall-through test; de-flaked the compression benchmark reproducibility
  and ServiceSupervisor crash tests. No production code changed.

* ci(security): clear OpenSSF Scorecard code-scanning noise + harden workflow token permissions

The Security tab held 155 open alerts, ALL from the advisory OpenSSF Scorecard tool
(#3824) — supply-chain/posture scores, not code vulnerabilities — which drowned out
real CodeQL findings.

- scorecard.yml: stop uploading SARIF to the code-scanning tab (drop the upload-sarif
  step + the now-unused security-events: write). The run still produces the OpenSSF
  badge (publish_results) and a downloadable SARIF artifact.
- TokenPermissions hardening (the high-severity, genuinely-valuable subset): set each
  workflow's top-level token to read-only and grant the exact writes at the job level
  that needs them — npm-publish (id-token/packages on publish jobs), docker-publish
  (packages on build), electron-release (contents on build/release, id-token/packages
  on publish-npm), build-fork (packages on build), claude (empty top-level; job grants
  its own). The 155 existing alerts were dismissed.

Not adopting repo-wide SHA-pinning (143 PinnedDependencies advisories) — declined.

* test(integration): align stale wiring/socks5 integration tests to this cycle's behavior

These were red on the CI Integration job (pre-existing). No production code changed:
- integration-wiring: the combos page no longer renders a per-page EmailPrivacyToggle
  (#3822 consolidated it into Settings → Appearance); the provider-detail test-result
  masking and upstream-proxy copy moved to decomposed components (#3501
  BatchTestResultsModal / UpstreamProxyCard) — assertions now read the owning files.
- api-routes-critical: SOCKS5 is now enabled by default (opt-out), so the disabled-
  rejection test must set ENABLE_SOCKS5_PROXY=false explicitly (an unset env now means
  enabled).

(The ~32 live-Gemini integration tests are gated on OMNIROUTE_API_KEY and skip in CI;
they only 'fail' locally when that key is present without a running server.)
2026-06-15 03:32:11 -03:00

207 lines
6.6 KiB
TypeScript

/**
* ServiceSupervisor unit tests.
*
* Uses a real Node.js child process (`node -e "..."`) to test lifecycle
* without mocking child_process — this gives realistic signal/exit behavior.
*
* A tiny HTTP health server is spawned inline for health-check tests.
*/
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";
import http from "node:http";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-supervisor-"));
process.env.DATA_DIR = TEST_DATA_DIR;
process.env.NODE_ENV = "test";
process.env.DISABLE_SQLITE_AUTO_BACKUP = "true";
// Import DB core first to trigger migration (creates version_manager with new columns)
const core = await import("../../../src/lib/db/core.ts");
// Seed the tool rows needed by tests
const db = core.getDbInstance();
db.prepare(
`INSERT OR IGNORE INTO version_manager (tool, status, port, auto_start, auto_update, provider_expose)
VALUES ('test-svc', 'stopped', 29999, 0, 0, 0)`
).run();
db.prepare(
`INSERT OR IGNORE INTO version_manager (tool, status, port, auto_start, auto_update, provider_expose)
VALUES ('test-crash', 'stopped', 29998, 0, 0, 0)`
).run();
db.prepare(
`INSERT OR IGNORE INTO version_manager (tool, status, port, auto_start, auto_update, provider_expose)
VALUES ('test-lock', 'stopped', 29997, 0, 0, 0)`
).run();
const { ServiceSupervisor } = await import("../../../src/lib/services/ServiceSupervisor.ts");
/** Starts a tiny HTTP health server on the given port that always returns 200. */
function startHealthServer(port: number): http.Server {
const server = http.createServer((_, res) => res.writeHead(200).end("ok"));
server.listen(port);
return server;
}
/** Config for a service that logs "tick" every second and stays alive. */
function tickConfig(tool: string, port: number) {
return {
tool,
port,
spawnArgs: () => ({
command: process.execPath,
args: ["-e", "setInterval(() => console.log('tick'), 500)"],
env: { ...process.env },
cwd: process.cwd(),
}),
healthUrl: () => `http://127.0.0.1:${port}/health`,
healthIntervalMs: 500,
stopTimeoutMs: 3_000,
logsBufferBytes: 1_048_576,
};
}
test.after(() => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
});
test("start spawns process and captures logs in ring buffer", async () => {
const healthServer = startHealthServer(29999);
const sup = new ServiceSupervisor(tickConfig("test-svc", 29999));
try {
const status = await sup.start();
assert.equal(status.state, "running");
assert.ok(status.pid !== null, "pid should be set");
// Wait briefly to let ticks accumulate
await new Promise((r) => setTimeout(r, 600));
const snap = sup.getRingBuffer().snapshot();
assert.ok(snap.length > 0, "ring buffer should have log entries");
assert.ok(
snap.some((e) => e.line.includes("tick")),
"should capture stdout lines"
);
} finally {
await sup.stop();
healthServer.close();
}
});
test("stop sends SIGTERM and waits, then SIGKILL if needed", async () => {
const healthServer = startHealthServer(29999);
const sup = new ServiceSupervisor({
...tickConfig("test-svc", 29999),
stopTimeoutMs: 500,
});
try {
await sup.start();
const status = await sup.stop();
assert.equal(status.state, "stopped");
assert.equal(status.pid, null);
} finally {
healthServer.close();
}
});
test("crash sets state=error and lastError (no auto-restart)", async () => {
const healthServer = startHealthServer(29998);
const crashConfig = {
...tickConfig("test-crash", 29998),
spawnArgs: () => ({
command: process.execPath,
// Exit after 1.5s — health server is up, so start() can return "running" first
args: ["-e", "setTimeout(() => process.exit(1), 1500)"],
env: { ...process.env },
cwd: process.cwd(),
}),
healthIntervalMs: 300,
};
const sup = new ServiceSupervisor(crashConfig);
const stateChanges: string[] = [];
sup.on("stateChange", (s) => stateChanges.push(s.state));
try {
await sup.start();
assert.equal(sup.getStatus().state, "running");
// Poll for the crash to be detected (process exits at 1.5s, health checker detects it
// within ~3 intervals). A fixed sleep flakes under CPU contention because the child's
// exit timer and the health-check intervals all slip; poll with a generous deadline.
const deadline = Date.now() + 10_000;
while (sup.getStatus().state !== "error" && Date.now() < deadline) {
await new Promise((r) => setTimeout(r, 100));
}
const status = sup.getStatus();
assert.equal(status.state, "error", "state should be error after crash");
assert.ok(status.lastError !== null, "lastError should be set");
assert.ok(
!stateChanges.filter((s) => s === "starting").length ||
stateChanges[stateChanges.length - 1] !== "starting",
"supervisor must not restart after crash"
);
} finally {
healthServer.close();
}
});
test("restart is atomic (concurrent calls serialize)", async () => {
const healthServer = startHealthServer(29999);
const sup = new ServiceSupervisor(tickConfig("test-svc", 29999));
try {
await sup.start();
// Fire 3 concurrent restarts — all should resolve without throwing
const [s1, s2, s3] = await Promise.all([sup.restart(), sup.restart(), sup.restart()]);
assert.equal(s1.state, "running");
assert.equal(s2.state, "running");
assert.equal(s3.state, "running");
const final = sup.getStatus();
assert.equal(final.state, "running");
} finally {
await sup.stop();
healthServer.close();
}
});
test("does NOT auto-restart on crash", async () => {
const healthServer = startHealthServer(29998);
const crashConfig = {
...tickConfig("test-crash", 29998),
spawnArgs: () => ({
command: process.execPath,
// Exit after 1.5s — same as crash test above
args: ["-e", "setTimeout(() => process.exit(2), 1500)"],
env: { ...process.env },
cwd: process.cwd(),
}),
healthIntervalMs: 300,
};
const sup = new ServiceSupervisor(crashConfig);
try {
await sup.start();
// Wait for crash + one more health interval
await new Promise((r) => setTimeout(r, 2_200));
const status = sup.getStatus();
// After crash: state must be "error" or "stopped", never "starting" again
assert.ok(
status.state === "error" || status.state === "stopped",
`supervisor should not auto-restart: state was "${status.state}"`
);
} finally {
healthServer.close();
}
});