Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Test ports: each vitest worker picks from its own (#4412)

Milind Soni87768b5b4134
diff --git a/companion/test/proxy.test.ts b/companion/test/proxy.test.ts
index de2e5abb6b..e212a0b085 100644
--- a/companion/test/proxy.test.ts
+++ b/companion/test/proxy.test.ts
@@ -13,6 +13,7 @@ import { MAX_SSE_EVENT_BYTES } from "../src/wire.ts";
import { createConnectedDeviceTracker } from "../src/connected-devices.ts";
import type { CompanionEndpoint } from "../src/endpoints.ts";
import { removeTempDir, waitForExit } from "../../server/testing/cleanup.ts";
+import { workerPort } from "../../server/testing/worker-port.ts";
const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, "..", "..");
@@ -29,7 +30,7 @@ const freePorts = async (span = 1): Promise<number> => {
});
for (let attempt = 0; attempt < 40; attempt++) {
- const candidate = 20_000 + Math.floor(Math.random() * 9_000);
+ const candidate = workerPort(20_000, 9_000);
const held: Server[] = [];
let free = true;
for (let i = 0; i < span; i++) {
diff --git a/server/admin-activity.e2e.test.ts b/server/admin-activity.e2e.test.ts
index 36751b0b92..1445bc13c1 100644
--- a/server/admin-activity.e2e.test.ts
+++ b/server/admin-activity.e2e.test.ts
@@ -7,9 +7,10 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { SessionRegistry } from "./sessions.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
-const PORT = 28800 + Math.floor(Math.random() * 10_000);
+const PORT = workerPort(28800, 10_000);
const BASE = `http://127.0.0.1:${PORT}`;
const posixOnly = describe.skipIf(process.platform === "win32");
const BOSS = "[email protected]";
diff --git a/server/branching.test.ts b/server/branching.test.ts
index b36c9eff60..90868a7838 100644
--- a/server/branching.test.ts
+++ b/server/branching.test.ts
@@ -5,11 +5,12 @@ import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const FAKE_CLI = join(SERVER_DIR, "testing", "fake-acp-cli.ts");
-const PORT = 18800 + Math.floor(Math.random() * 10_000);
+const PORT = workerPort(18800, 10_000);
const BASE = `http://127.0.0.1:${PORT}`;
const posixOnly = describe.skipIf(process.platform === "win32");
diff --git a/server/bulk-delete-tasks.e2e.test.ts b/server/bulk-delete-tasks.e2e.test.ts
index bc3609a896..d073324dbf 100644
--- a/server/bulk-delete-tasks.e2e.test.ts
+++ b/server/bulk-delete-tasks.e2e.test.ts
@@ -7,10 +7,11 @@ import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const FAKE_CLAUDE = join(SERVER_DIR, "testing", "fake-claude-cli.ts");
-const PORT = 18800 + Math.floor(Math.random() * 10_000);
+const PORT = workerPort(18800, 10_000);
const BASE = `http://127.0.0.1:${PORT}`;
const posixOnly = describe.skipIf(process.platform === "win32");
diff --git a/server/card-answerers.e2e.test.ts b/server/card-answerers.e2e.test.ts
index 59af9f859c..15048f4d44 100644
--- a/server/card-answerers.e2e.test.ts
+++ b/server/card-answerers.e2e.test.ts
@@ -10,10 +10,11 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { DecisionRow } from "./decision-log.ts";
import { SessionRegistry } from "./sessions.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const FAKE_CLI = join(SERVER_DIR, "testing", "fake-acp-cli.ts");
-const PORT = 28800 + Math.floor(Math.random() * 10_000);
+const PORT = workerPort(28800, 10_000);
const BASE = `http://127.0.0.1:${PORT}`;
const posixOnly = describe.skipIf(process.platform === "win32");
const BOSS = "[email protected]";
diff --git a/server/cli.test.ts b/server/cli.test.ts
index 49e89bf448..040c8f3437 100644
--- a/server/cli.test.ts
+++ b/server/cli.test.ts
@@ -12,6 +12,7 @@ import { SetupCancelled } from "./cli-prompts.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
import { startControlPlaneStub } from "./testing/control-plane-stub.ts";
import { freePortBlock } from "./testing/ports.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const setup = vi.hoisted(() => ({ runSetup: vi.fn(), isSetupComplete: vi.fn(), readCliStartup: vi.fn(), saveCliStartup: vi.fn() }));
@@ -151,7 +152,7 @@ describe("openmausbot command line", () => {
it("serve: starts the server, prints the pairing link, and stops on SIGTERM", async () => {
const home = mkdtempSync(join(tmpdir(), "omb-cli-serve-"));
- const port = 21000 + Math.floor(Math.random() * 9000);
+ const port = workerPort(21000, 9000);
const child = spawn(process.execPath, ["--experimental-strip-types", join(SERVER_DIR, "openmausbot.ts"), "serve", "--port", String(port), "--data-dir", join(home, "data"), "--label", "cli test", "--public-url", "https://mini.example"], {
cwd: join(SERVER_DIR, ".."),
env: { PATH: process.env.PATH ?? "", HOME: home, USERPROFILE: home, OMB_WEBHOOK_PORT: String(port + 1), OMB_BROWSER_CONNECTION: join(home, "browser-connection.json") },
@@ -402,7 +403,7 @@ describe.skipIf(process.platform === "win32")("serve --tunnel", () => {
it("refuses without an account and says what to do; no local-only fallback", async () => {
const home = mkdtempSync(join(tmpdir(), "omb-cli-tunnel-none-"));
- const port = 21000 + Math.floor(Math.random() * 9000);
+ const port = workerPort(21000, 9000);
const child = cli(["serve", "--tunnel", "--port", String(port), "--data-dir", join(home, "data")], { HOME: home, USERPROFILE: home });
let err = "";
child.stderr?.on("data", (chunk) => (err += String(chunk)));
@@ -606,7 +607,7 @@ describe.skipIf(process.platform === "win32")("serve --domain", () => {
mkdirSync(dataDir, { recursive: true });
const fake = join(home, "fake-caddy");
writeFileSync(fake, `#!/bin/sh\necho "$@" > "${join(home, "caddy-args.txt")}"\necho $$ > "${join(home, "caddy.pid")}"\nexec sleep 300\n`, { mode: 0o755 });
- const port = 21000 + Math.floor(Math.random() * 9000);
+ const port = workerPort(21000, 9000);
const child = spawn(process.execPath, ["--experimental-strip-types", join(SERVER_DIR, "openmausbot.ts"), "serve", "--domain", "omb.example.test", "--port", String(port), "--data-dir", dataDir], {
cwd: join(SERVER_DIR, ".."),
env: { PATH: process.env.PATH ?? "", HOME: home, USERPROFILE: home, OMB_WEBHOOK_PORT: String(port + 1), OMB_BROWSER_CONNECTION: join(home, "browser-connection.json"), OMB_CADDY_PATH: fake },
diff --git a/server/codex-review.e2e.test.ts b/server/codex-review.e2e.test.ts
index f185921587..bed533193e 100644
--- a/server/codex-review.e2e.test.ts
+++ b/server/codex-review.e2e.test.ts
@@ -6,10 +6,11 @@ import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, expect, it } from "vitest";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
+import { workerPort } from "./testing/worker-port.ts";
const root = dirname(dirname(fileURLToPath(import.meta.url)));
const fake = join(root, "server", "testing", "fake-codex-app-server.ts");
-const port = 18800 + Math.floor(Math.random() * 10_000);
+const port = workerPort(18800, 10_000);
const base = `http://127.0.0.1:${port}`;
let home: string;
let child: ChildProcess;
diff --git a/server/comms.test.ts b/server/comms.test.ts
index ef646e3528..dbdbb9a435 100644
--- a/server/comms.test.ts
+++ b/server/comms.test.ts
@@ -12,11 +12,12 @@ import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { mentionedBots, normalizeGroupDefaultResponder, roomResponders } from "./store.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
import { readHandoffs } from "./testing/handoff-rows.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const FAKE_CLI = join(SERVER_DIR, "testing", "fake-acp-cli.ts");
const TEST_CAPABILITY_KEY = "comms-test-capability-key-0123456789abcdef";
-const PORT = 18800 + Math.floor(Math.random() * 10_000);
+const PORT = workerPort(18800, 10_000);
const BASE = `http://127.0.0.1:${PORT}`;
// A fresh connection per request: a request sent on an idle kept-alive socket while the server's event loop is busy
// (seconds, on a Windows runner) is reset when Node's keep-alive timeout fires before the server reads it (Node 24).
diff --git a/server/decision-log-wiring.test.ts b/server/decision-log-wiring.test.ts
index cb39e85511..f9e7ab74ee 100644
--- a/server/decision-log-wiring.test.ts
+++ b/server/decision-log-wiring.test.ts
@@ -9,10 +9,11 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { DecisionRow } from "./decision-log.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const FAKE_CLI = join(SERVER_DIR, "testing", "fake-acp-cli.ts");
-const PORT = 18800 + Math.floor(Math.random() * 10_000);
+const PORT = workerPort(18800, 10_000);
const BASE = `http://127.0.0.1:${PORT}`;
const posixOnly = describe.skipIf(process.platform === "win32");
diff --git a/server/digest.e2e.test.ts b/server/digest.e2e.test.ts
index ebbd83904a..257cf75738 100644
--- a/server/digest.e2e.test.ts
+++ b/server/digest.e2e.test.ts
@@ -6,10 +6,11 @@ import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const fake = (name: string) => join(SERVER_DIR, "testing", name);
-const PORT = 18800 + Math.floor(Math.random() * 10_000);
+const PORT = workerPort(18800, 10_000);
const BASE = `http://127.0.0.1:${PORT}`;
const posixOnly = describe.skipIf(process.platform === "win32");
diff --git a/server/email-signin.test.ts b/server/email-signin.test.ts
index b4fffd45dd..1c24bada8a 100644
--- a/server/email-signin.test.ts
+++ b/server/email-signin.test.ts
@@ -9,10 +9,11 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
import { startControlPlaneStub, type ControlPlaneStub } from "./testing/control-plane-stub.ts";
import { openSse } from "./testing/sse.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const ROOT = join(SERVER_DIR, "..");
-const PORT = 24000 + Math.floor(Math.random() * 5000);
+const PORT = workerPort(24000, 5000);
const HOST = "agentada.test";
let home: string;
diff --git a/server/helper-model.e2e.test.ts b/server/helper-model.e2e.test.ts
index f7a9372982..873d839dd8 100644
--- a/server/helper-model.e2e.test.ts
+++ b/server/helper-model.e2e.test.ts
@@ -10,6 +10,7 @@ import { CAPTURE_MARKER } from "./memory-capture.ts";
import { NO_TEXT_ENGINE } from "./memory-upkeep.ts";
import { SKILL_REVIEW_MARKER } from "./skill-review.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const fake = (name: string) => join(SERVER_DIR, "testing", name);
@@ -40,7 +41,7 @@ interface Row {
* whatever else the test puts in config.json. */
async function boot(extraConfig: Record<string, unknown>) {
for (const name of FAKES) chmodSync(fake(name), 0o755);
- const port = 18800 + Math.floor(Math.random() * 10_000);
+ const port = workerPort(18800, 10_000);
const base = `http://127.0.0.1:${port}`;
const home = mkdtempSync(join(tmpdir(), "omb-helper-model-"));
mkdirSync(join(home, ".openmausbot"), { recursive: true });
diff --git a/server/hooks.e2e.test.ts b/server/hooks.e2e.test.ts
index 52e5733469..f0b7e5ae5e 100644
--- a/server/hooks.e2e.test.ts
+++ b/server/hooks.e2e.test.ts
@@ -7,6 +7,7 @@ import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const FAKE_CLAUDE = join(SERVER_DIR, "testing", "fake-claude-cli.ts");
@@ -24,7 +25,7 @@ interface Msg {
const BIG = `line ${"x".repeat(80)}\n`.repeat(200); // ~17 KB: past the 6 KB preview
function harness(label: string, serverEnv: Record<string, string>, instanceEnv: Record<string, string> = {}) {
- const PORT = 18800 + Math.floor(Math.random() * 10_000);
+ const PORT = workerPort(18800, 10_000);
const BASE = `http://127.0.0.1:${PORT}`;
let child: ChildProcess;
let home: string;
diff --git a/server/index.test.ts b/server/index.test.ts
index 262094cf5a..661169ca4d 100644
--- a/server/index.test.ts
+++ b/server/index.test.ts
@@ -34,14 +34,15 @@ import {
phoneSecretAAD,
type PhoneSecretContext,
} from "./phone-secret.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const ROOT = join(SERVER_DIR, "..");
const FAKE_CLAUDE_CLI = join(SERVER_DIR, "testing", "fake-claude-cli.ts");
const FAKE_MCP_SERVER = join(SERVER_DIR, "testing", "fake-mcp-server.ts");
-const PORT = 18800 + Math.floor(Math.random() * 10_000);
+const PORT = workerPort(18800, 10_000);
const BASE = `http://127.0.0.1:${PORT}`;
-const WEBHOOK_PORT = 39000 + Math.floor(Math.random() * 10_000);
+const WEBHOOK_PORT = workerPort(39000, 10_000);
const WEBHOOK_BASE = `http://127.0.0.1:${WEBHOOK_PORT}`;
const TEST_CAPABILITY_KEY = "index-fixture-internal-capability";
diff --git a/server/legacy-migration.test.ts b/server/legacy-migration.test.ts
index e1dc0d0594..71f7a65b55 100644
--- a/server/legacy-migration.test.ts
+++ b/server/legacy-migration.test.ts
@@ -7,11 +7,12 @@ import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const ROOT = join(SERVER_DIR, "..");
-const PORT = 18800 + Math.floor(Math.random() * 10_000);
-const WEBHOOK_PORT = 39000 + Math.floor(Math.random() * 10_000);
+const PORT = workerPort(18800, 10_000);
+const WEBHOOK_PORT = workerPort(39000, 10_000);
let home: string;
let child: ChildProcess;
diff --git a/server/notification-wiring.test.ts b/server/notification-wiring.test.ts
index 80d91d89b0..0c8f9c7a08 100644
--- a/server/notification-wiring.test.ts
+++ b/server/notification-wiring.test.ts
@@ -8,11 +8,12 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
import { openSse } from "./testing/sse.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const FAKE_CLI = join(SERVER_DIR, "testing", "fake-acp-cli.ts");
-const PORT = 18800 + Math.floor(Math.random() * 10_000);
-const WEBHOOK_PORT = 39000 + Math.floor(Math.random() * 10_000);
+const PORT = workerPort(18800, 10_000);
+const WEBHOOK_PORT = workerPort(39000, 10_000);
const BASE = `http://127.0.0.1:${PORT}`;
const posixOnly = describe.skipIf(process.platform === "win32");
diff --git a/server/remote-sessions.test.ts b/server/remote-sessions.test.ts
index ceedfccd9e..a2a58af4e0 100644
--- a/server/remote-sessions.test.ts
+++ b/server/remote-sessions.test.ts
@@ -9,11 +9,12 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { LOCKOUT } from "./sessions.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
import { openSse } from "./testing/sse.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const ROOT = join(SERVER_DIR, "..");
-const PORT = 18800 + Math.floor(Math.random() * 10_000);
-const WEBHOOK_PORT = 39000 + Math.floor(Math.random() * 10_000);
+const PORT = workerPort(18800, 10_000);
+const WEBHOOK_PORT = workerPort(39000, 10_000);
const BASE = `http://127.0.0.1:${PORT}`;
const REMOTE_HOST = "mini.tail1234.ts.net:8799";
const PUBLIC_URL = "https://mini.tail1234.ts.net";
diff --git a/server/respond-replay.e2e.test.ts b/server/respond-replay.e2e.test.ts
index ff13177ea7..8e94eb6db7 100644
--- a/server/respond-replay.e2e.test.ts
+++ b/server/respond-replay.e2e.test.ts
@@ -8,10 +8,11 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { DecisionRow } from "./decision-log.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const FAKE_CLI = join(SERVER_DIR, "testing", "fake-acp-cli.ts");
-const PORT = 28800 + Math.floor(Math.random() * 10_000);
+const PORT = workerPort(28800, 10_000);
const BASE = `http://127.0.0.1:${PORT}`;
const posixOnly = describe.skipIf(process.platform === "win32");
const UNDELIVERED = "Couldn't deliver that answer";
diff --git a/server/routine-run-broadcast.e2e.test.ts b/server/routine-run-broadcast.e2e.test.ts
index afc4542596..d871cfe80a 100644
--- a/server/routine-run-broadcast.e2e.test.ts
+++ b/server/routine-run-broadcast.e2e.test.ts
@@ -7,10 +7,11 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { SessionRegistry } from "./sessions.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const FAKE_CLI = join(SERVER_DIR, "testing", "fake-acp-cli.ts");
-const PORT = 28800 + Math.floor(Math.random() * 10_000);
+const PORT = workerPort(28800, 10_000);
const BASE = `http://127.0.0.1:${PORT}`;
const OWNER = "[email protected]";
const posixOnly = describe.skipIf(process.platform === "win32");
diff --git a/server/steer-e2e.test.ts b/server/steer-e2e.test.ts
index d20d9b9808..aff124166e 100644
--- a/server/steer-e2e.test.ts
+++ b/server/steer-e2e.test.ts
@@ -7,12 +7,13 @@ import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { splitLaunchNote } from "./testing/launch-note.ts";
import { withoutTurnClock } from "./testing/turn-clock-text.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const FAKE_CLAUDE = join(SERVER_DIR, "testing", "fake-claude-cli.ts");
const FAKE_ACP = join(SERVER_DIR, "testing", "fake-acp-cli.ts");
const FAKE_CODEX = join(SERVER_DIR, "testing", "fake-codex-app-server.ts");
-const PORT = 18800 + Math.floor(Math.random() * 10_000);
+const PORT = workerPort(18800, 10_000);
const BASE = `http://127.0.0.1:${PORT}`;
const posixOnly = describe.skipIf(process.platform === "win32");
diff --git a/server/testing/ports.ts b/server/testing/ports.ts
index c542790b37..5bbbd28ff2 100644
--- a/server/testing/ports.ts
+++ b/server/testing/ports.ts
@@ -3,6 +3,7 @@ import { readFileSync } from "node:fs";
import { createServer } from "node:http";
import { mcpOAuthRedirectUri } from "../mcp-oauth.ts";
+import { forWorker } from "./worker-port.ts";
const isFree = (port: number): Promise<boolean> =>
new Promise((resolve) => {
@@ -11,11 +12,13 @@ const isFree = (port: number): Promise<boolean> =>
probe.listen(port, "127.0.0.1", () => probe.close(() => resolve(true)));
});
-/** A base where every `base + offset` is free (the harness also opens a webhook receiver one above
- * itself). A probe, not a reservation: the ports are released before they are returned. */
+/** A base of this worker where every `base + offset` is free (the harness also opens a webhook receiver one above
+ * itself). A probe, not a reservation: the ports are released before they are returned. A range too narrow to share is
+ * one a suite keeps to itself. */
export async function freePortBlock(offsets: number[], from = 19_600, span = 3_000): Promise<number> {
for (let attempt = 0; attempt < 40; attempt++) {
- const base = from + Math.floor(Math.random() * span);
+ const picked = from + Math.floor(Math.random() * span);
+ const base = span < 64 ? picked : forWorker(picked);
const checks = await Promise.all(offsets.map((offset) => isFree(base + offset)));
if (checks.every(Boolean)) return base;
}
diff --git a/server/testing/worker-port.test.ts b/server/testing/worker-port.test.ts
new file mode 100644
index 0000000000..9561aad3b7
--- /dev/null
+++ b/server/testing/worker-port.test.ts
@@ -0,0 +1,46 @@
+import { readdirSync, readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+
+import { forWorker, workerPort } from "./worker-port.ts";
+
+describe("a worker's ports", () => {
+ it("never meet another worker's, the port above included, whatever range each picks from", () => {
+ const taken = new Map<number, string>();
+ for (const worker of ["1", "2", "3", "4", "5", "6", "7", "8", "16"]) {
+ for (let picked = 18_800; picked < 19_800; picked++) {
+ const base = forWorker(picked, worker);
+ for (const port of [base, base + 1]) {
+ expect(taken.get(port) ?? worker, `port ${port}`).toBe(worker);
+ taken.set(port, worker);
+ }
+ }
+ }
+ });
+
+ it("stays near what was picked", () => {
+ for (const picked of [18_800, 18_831, 19_999, 38_799]) expect(Math.abs(forWorker(picked, "4") - picked)).toBeLessThan(32);
+ });
+
+ it("is what was picked outside a worker", () => {
+ expect(forWorker(19_999, "")).toBe(19_999);
+ expect(forWorker(19_999, "not a worker")).toBe(19_999);
+ });
+
+ it("picks from this worker's own", () => {
+ for (let i = 0; i < 200; i++) {
+ const port = workerPort(18_800, 10_000);
+ expect(forWorker(port), "already this worker's").toBe(port);
+ }
+ });
+});
+
+it("leaves no suite picking a raw random port another worker could pick too", () => {
+ const raw = /\d[\d_]{3,5} *\+ *Math\.floor\(Math\.random\(\) *\*/;
+ const root = new URL("../../", import.meta.url);
+ const offenders = ["server", "companion", "enterprise", "shared"].flatMap((dir) =>
+ (readdirSync(new URL(dir, root), { recursive: true }) as string[])
+ .filter((file) => /\.test\.[cm]?ts$/.test(file) && !file.includes("node_modules"))
+ .filter((file) => raw.test(readFileSync(new URL(`${dir}/${file}`, root), "utf8")))
+ .map((file) => `${dir}/${file}`));
+ expect(offenders).toEqual([]);
+});
diff --git a/server/testing/worker-port.ts b/server/testing/worker-port.ts
new file mode 100644
index 0000000000..df850bab93
--- /dev/null
+++ b/server/testing/worker-port.ts
@@ -0,0 +1,15 @@
+// CI runs test files side by side on vitest's workers, and a suite's ports are only probed, never reserved. So a port's
+// low bits name the worker that may use it: two workers never pick the same port, whatever range each asks for. Two
+// slots each, because a harness also listens one above its own port. Outside a worker a port stays as it was picked.
+const SLOTS = 32;
+
+export function forWorker(port: number, poolId: string | undefined = process.env.VITEST_POOL_ID): number {
+ const id = Number(poolId);
+ if (!Number.isSafeInteger(id) || id < 1) return port;
+ return port - (port % SLOTS) + ((id - 1) % (SLOTS / 2)) * 2;
+}
+
+/** A random port of this worker in `from`..`from + span`, for a suite that has no time to probe. */
+export function workerPort(from: number, span: number): number {
+ return forWorker(from + Math.floor(Math.random() * span));
+}
diff --git a/server/usage-attribution.e2e.test.ts b/server/usage-attribution.e2e.test.ts
index a51fb149d2..a9e7377fae 100644
--- a/server/usage-attribution.e2e.test.ts
+++ b/server/usage-attribution.e2e.test.ts
@@ -5,12 +5,13 @@ import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const FAKE_CLAUDE = join(SERVER_DIR, "testing", "fake-claude-cli.ts");
const FAKE_ACP = join(SERVER_DIR, "testing", "fake-acp-cli.ts");
const FAKE_CODEX = join(SERVER_DIR, "testing", "fake-codex-app-server.ts");
-const PORT = 18800 + Math.floor(Math.random() * 10_000);
+const PORT = workerPort(18800, 10_000);
const BASE = `http://127.0.0.1:${PORT}`;
const posixOnly = describe.skipIf(process.platform === "win32");
diff --git a/server/vps-routing.test.ts b/server/vps-routing.test.ts
index 7808661544..049930c300 100644
--- a/server/vps-routing.test.ts
+++ b/server/vps-routing.test.ts
@@ -19,10 +19,11 @@ import { VPS_CONTAINER_LABEL, VPS_IMAGE, VPS_MANAGED_LABEL, VPS_VIEWER_LABEL, vp
import { CONTROL_BUSY, CONTROL_REFUSAL_PLAIN, controlRefusal, createControlClient } from "./control-client.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
import type { RoutineSchedule } from "../shared/routines.ts";
+import { workerPort } from "./testing/worker-port.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const FAKE_CLI = join(SERVER_DIR, "testing", "fake-acp-cli.ts");
-const PORT = 18800 + Math.floor(Math.random() * 10_000);
+const PORT = workerPort(18800, 10_000);
const BASE = `http://127.0.0.1:${PORT}`;
const IMAGE_ID = `sha256:${"a".repeat(64)}`;
const CONTAINER_ID = "b".repeat(64);