Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

test: end the shared-port flakiness in the server-booting suites

nirholas06ea34112310
diff --git a/tests/api-method-guard.test.js b/tests/api-method-guard.test.js
index cce92f655..ba5e099a9 100644
--- a/tests/api-method-guard.test.js
+++ b/tests/api-method-guard.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
-import { spawn } from 'node:child_process';
import { readFileSync } from 'node:fs';
+import { startTestServer } from './helpers/test-server.js';
import { fileURLToPath } from 'node:url';
import { globSync } from 'node:fs';
@@ -40,28 +40,15 @@ describe('method() guard is negated at every call site', () => {
});
describe('POST /api/diorama answers instead of hanging', () => {
- const PORT = 18477;
- const BASE = `http://127.0.0.1:${PORT}`;
+ let BASE;
let server;
beforeAll(async () => {
- server = spawn(process.execPath, ['server/index.mjs'], {
- cwd: repoRoot,
- env: { ...process.env, PORT: String(PORT), NODE_ENV: 'test' },
- stdio: 'ignore',
- });
- const deadline = Date.now() + 20000;
- while (Date.now() < deadline) {
- try {
- const res = await fetch(`${BASE}/api/diorama`, { redirect: 'manual' });
- if (res.status > 0) return;
- } catch { /* not up yet */ }
- await new Promise((r) => setTimeout(r, 250));
- }
- throw new Error('server did not start in time');
+ server = await startTestServer();
+ BASE = server.base;
}, 30000);
- afterAll(() => server?.kill());
+ afterAll(() => server?.close());
// The unknown-action branch sits after the method guard and before any rate
// limiter, LLM call, or DB read — so this asserts the guard alone, with no
diff --git a/tests/api/material-studio-store.test.js b/tests/api/material-studio-store.test.js
index 93db1c20c..cd9627ef8 100644
--- a/tests/api/material-studio-store.test.js
+++ b/tests/api/material-studio-store.test.js
@@ -15,17 +15,27 @@ import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
const FIXTURE_GLB_PATH = resolve(process.cwd(), 'public/avatars/fox.glb');
-const FIXTURE_URL = 'https://cdn.three.ws/fixtures/fox.glb';
+const FIXTURE_URL = 'https://three.ws/cdn/fixtures/fox.glb';
let fixtureBytes;
let uploadedObjects;
let watsonxReply;
+// The stand-in CDN origin these tests assert against. publicUrl() is mocked
+// away entirely, so the real S3_PUBLIC_DOMAIN never applies here; what matters
+// is that every URL assertion below is anchored to the SAME base the mock
+// returns. Three of them once hardcoded a different host and silently failed
+// the moment the mock's base changed.
+const CDN_BASE = 'https://three.ws/cdn';
+/** Matches a persisted object URL under `prefix`, e.g. material-studio/restyle. */
+const persistedGlbUrl = (prefix) =>
+ new RegExp(`^${CDN_BASE.replace(/[.\\/]/g, '\\$&')}/${prefix}/.+\\.glb$`);
+
vi.mock('../../api/_lib/r2.js', () => ({
putObject: vi.fn(async ({ key, body }) => {
uploadedObjects.push({ key, bytes: body.length ?? body.byteLength, body: Buffer.from(body) });
}),
- publicUrl: vi.fn((key) => `https://cdn.three.ws/${key}`),
+ publicUrl: vi.fn((key) => `https://three.ws/cdn/${key}`),
}));
vi.mock('../../api/_lib/ssrf.js', () => ({
@@ -93,7 +103,7 @@ describe('restyleMaterialFromInstruction', () => {
instruction: 'make it chrome',
});
- expect(result.glbUrl).toMatch(/^https:\/\/cdn\.three\.ws\/material-studio\/restyle\/.+\.glb$/);
+ expect(result.glbUrl).toMatch(persistedGlbUrl('material-studio/restyle'));
expect(result.sourceGlbUrl).toBe(FIXTURE_URL);
expect(result.factors.metallicFactor).toBe(1);
expect(result.materialsEdited).toBeGreaterThan(0);
@@ -118,7 +128,7 @@ describe('restyleMaterialFromInstruction', () => {
const { restyleMaterialFromInstruction } = await import('../../api/_lib/material-studio-store.js');
const parentLineage = [
{ index: 0, parentIndex: null, glbUrl: FIXTURE_URL, refKind: 'origin' },
- { index: 1, parentIndex: 0, glbUrl: 'https://cdn.three.ws/material-studio/variants/abc.glb', instruction: 'Chrome 3', refKind: 'variant' },
+ { index: 1, parentIndex: 0, glbUrl: 'https://three.ws/cdn/material-studio/variants/abc.glb', instruction: 'Chrome 3', refKind: 'variant' },
];
const result = await restyleMaterialFromInstruction({
glbUrl: FIXTURE_URL,
@@ -212,7 +222,7 @@ describe('generateSeededVariants', () => {
expect(a.variants).toHaveLength(3);
expect(a.variants.map((v) => v.config.color)).toEqual(b.variants.map((v) => v.config.color));
expect(a.variants.map((v) => v.seed)).toEqual(b.variants.map((v) => v.seed));
- for (const v of a.variants) expect(v.glbUrl).toMatch(/^https:\/\/cdn\.three\.ws\/material-studio\/variants\/.+\.glb$/);
+ for (const v of a.variants) expect(v.glbUrl).toMatch(persistedGlbUrl('material-studio/variants'));
});
it('fans every variant off the SAME shared parent rather than chaining them', async () => {
@@ -257,7 +267,7 @@ describe('validateAndPersistGlb', () => {
it('accepts a real GLB and rejects non-GLB bytes', async () => {
const { validateAndPersistGlb, MaterialStudioError } = await import('../../api/_lib/material-studio-store.js');
const good = await validateAndPersistGlb(fixtureBytes, { keyPrefix: 'material-studio/checkpoints' });
- expect(good.url).toMatch(/^https:\/\/cdn\.three\.ws\/material-studio\/checkpoints\/.+\.glb$/);
+ expect(good.url).toMatch(persistedGlbUrl('material-studio/checkpoints'));
await expect(validateAndPersistGlb(Buffer.from('not a glb'))).rejects.toBeInstanceOf(MaterialStudioError);
});
diff --git a/tests/helpers/test-server.js b/tests/helpers/test-server.js
new file mode 100644
index 000000000..214321952
--- /dev/null
+++ b/tests/helpers/test-server.js
@@ -0,0 +1,69 @@
+// Boot the real server on a port claimed at run time.
+//
+// Several suites spawn `server/index.mjs` and probe it over HTTP. They used to
+// hardcode a port each, which broke two ways: two suites picked the SAME port
+// (18453 was used by both server-api-traversal and x402-probe-challenge, so any
+// full-suite run raced them), and any second concurrent vitest run in the same
+// worktree collided with the first. Both surface as `SocketError: other side
+// closed` on a varying subset of tests — a failure that reads like a product
+// bug and moves between runs.
+//
+// Claiming the port from the OS removes the class entirely.
+
+import { spawn } from 'node:child_process';
+import { createServer } from 'node:net';
+import { fileURLToPath } from 'node:url';
+
+const repoRoot = fileURLToPath(new URL('../..', import.meta.url));
+
+/** An OS-assigned free TCP port, released immediately before the caller reuses it. */
+export function freePort() {
+ return new Promise((resolve, reject) => {
+ const probe = createServer();
+ probe.on('error', reject);
+ probe.listen(0, '127.0.0.1', () => {
+ const { port } = probe.address();
+ probe.close((err) => (err ? reject(err) : resolve(port)));
+ });
+ });
+}
+
+/**
+ * Spawn server/index.mjs on a free port and resolve once it answers /api/healthz.
+ *
+ * @param {object} [opts]
+ * @param {Record<string,string>} [opts.env] extra env for the child (merged over process.env)
+ * @param {number} [opts.timeoutMs] how long to wait for readiness
+ * @returns {Promise<{ base: string, port: number, close: () => void }>}
+ * `base` is the origin to fetch against; call `close()` in afterAll.
+ */
+export async function startTestServer({ env = {}, timeoutMs = 20_000 } = {}) {
+ const port = await freePort();
+ const base = `http://127.0.0.1:${port}`;
+ const child = spawn(process.execPath, ['server/index.mjs'], {
+ cwd: repoRoot,
+ env: { ...process.env, PORT: String(port), NODE_ENV: 'test', ...env },
+ stdio: 'ignore',
+ });
+
+ // A crashed child never becomes reachable. Capturing its exit lets readiness
+ // fail with the actual status instead of burning the whole timeout on a
+ // vague "did not start".
+ let exited = null;
+ child.on('exit', (code, signal) => {
+ exited = signal ? `signal ${signal}` : `code ${code}`;
+ });
+
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ if (exited !== null) throw new Error(`server exited before becoming ready (${exited})`);
+ try {
+ const res = await fetch(`${base}/api/healthz`);
+ if (res.status > 0) break;
+ } catch { /* not up yet */ }
+ if (Date.now() >= deadline) throw new Error(`server did not start in time (${base})`);
+ await new Promise((r) => setTimeout(r, 250));
+ }
+
+ return { base, port, close: () => child.kill('SIGKILL') };
+}
diff --git a/tests/server-api-traversal.test.js b/tests/server-api-traversal.test.js
index 73ab3b6d1..eac6bf020 100644
--- a/tests/server-api-traversal.test.js
+++ b/tests/server-api-traversal.test.js
@@ -1,6 +1,5 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
-import { spawn } from 'node:child_process';
-import { fileURLToPath } from 'node:url';
+import { startTestServer } from './helpers/test-server.js';
// Guards a critical auth/route-gating bypass: dispatchApi() splits the /api path
// on "/" and only THEN percent-decodes each segment. An encoded separator
@@ -13,35 +12,16 @@ import { fileURLToPath } from 'node:url';
// This test boots the real server and asserts traversal probes 404 while normal
// routes still resolve.
-const repoRoot = fileURLToPath(new URL('..', import.meta.url));
-const PORT = 18453;
-const BASE = `http://127.0.0.1:${PORT}`;
-
+let BASE;
let server;
-async function waitForServer(timeoutMs = 20000) {
- const deadline = Date.now() + timeoutMs;
- while (Date.now() < deadline) {
- try {
- const res = await fetch(`${BASE}/api/healthz`, { redirect: 'manual' });
- if (res.status > 0) return;
- } catch { /* not up yet */ }
- await new Promise((r) => setTimeout(r, 250));
- }
- throw new Error('server did not start in time');
-}
-
beforeAll(async () => {
- server = spawn(process.execPath, ['server/index.mjs'], {
- cwd: repoRoot,
- env: { ...process.env, PORT: String(PORT), NODE_ENV: 'test' },
- stdio: 'ignore',
- });
- await waitForServer();
+ server = await startTestServer();
+ BASE = server.base;
}, 30000);
afterAll(() => {
- server?.kill('SIGKILL');
+ server?.close();
});
describe('api dispatcher rejects path traversal', () => {
diff --git a/tests/server-rewrite-query.test.js b/tests/server-rewrite-query.test.js
index a12e22bf7..556e1d596 100644
--- a/tests/server-rewrite-query.test.js
+++ b/tests/server-rewrite-query.test.js
@@ -1,6 +1,5 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
-import { spawn } from 'node:child_process';
-import { fileURLToPath } from 'node:url';
+import { startTestServer } from './helpers/test-server.js';
// Guards a real production outage class: vercel.json pretty routes that rewrite
// to an API function with query captures ("/oracle/coin/<mint>" →
@@ -13,38 +12,20 @@ import { fileURLToPath } from 'node:url';
//
// This test boots the real server and asserts the pretty route serves the page.
-const repoRoot = fileURLToPath(new URL('..', import.meta.url));
-const PORT = 18452;
-const BASE = `http://127.0.0.1:${PORT}`;
// Any syntactically valid base58 mint works: the page must render its shell
// even when the DB and pump.fun are unreachable (both are best-effort).
const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+let BASE;
let server;
-async function waitForServer(timeoutMs = 20000) {
- const deadline = Date.now() + timeoutMs;
- while (Date.now() < deadline) {
- try {
- const res = await fetch(`${BASE}/api/oracle-share`, { redirect: 'manual' });
- if (res.status > 0) return;
- } catch { /* not up yet */ }
- await new Promise((r) => setTimeout(r, 250));
- }
- throw new Error('server did not start in time');
-}
-
beforeAll(async () => {
- server = spawn(process.execPath, ['server/index.mjs'], {
- cwd: repoRoot,
- env: { ...process.env, PORT: String(PORT), NODE_ENV: 'test' },
- stdio: 'ignore',
- });
- await waitForServer();
+ server = await startTestServer();
+ BASE = server.base;
}, 30000);
afterAll(() => {
- server?.kill('SIGKILL');
+ server?.close();
});
describe('rewrite-dest query params reach handlers on req.url', () => {
diff --git a/tests/x402-probe-challenge.test.js b/tests/x402-probe-challenge.test.js
index 3682b9927..b98fa4c3f 100644
--- a/tests/x402-probe-challenge.test.js
+++ b/tests/x402-probe-challenge.test.js
@@ -1,6 +1,5 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
-import { spawn } from 'node:child_process';
-import { fileURLToPath } from 'node:url';
+import { startTestServer } from './helpers/test-server.js';
// Guards the x402 discovery contract: registry probes (x402scan, 402index,
// Bazaar validators) hit paid routes with whatever method they like, carrying
@@ -15,43 +14,23 @@ import { fileURLToPath } from 'node:url';
// The server boots with a Base receiver configured so challenges carry a
// non-empty accepts[]; no facilitator, DB, or Redis is needed to emit a 402.
-const repoRoot = fileURLToPath(new URL('..', import.meta.url));
-const PORT = 18453;
-const BASE = `http://127.0.0.1:${PORT}`;
-
+let BASE;
let server;
-async function waitForServer(timeoutMs = 20000) {
- const deadline = Date.now() + timeoutMs;
- while (Date.now() < deadline) {
- try {
- const res = await fetch(`${BASE}/api/healthz`);
- if (res.status > 0) return;
- } catch { /* not up yet */ }
- await new Promise((r) => setTimeout(r, 250));
- }
- throw new Error('server did not start in time');
-}
-
beforeAll(async () => {
- server = spawn(process.execPath, ['server/index.mjs'], {
- cwd: repoRoot,
+ server = await startTestServer({
env: {
- ...process.env,
- PORT: String(PORT),
- NODE_ENV: 'test',
// Minimal payable-lane env so buildRequirements() yields a Base accept.
X402_PAY_TO_BASE: '0x4022de2d36c334e73c7a108805cea11c0564f402',
X402_ASSET_ADDRESS_BASE: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
X402_ADVERTISE_BASE: 'true',
},
- stdio: 'ignore',
});
- await waitForServer();
+ BASE = server.base;
}, 30000);
afterAll(() => {
- server?.kill('SIGKILL');
+ server?.close();
});
async function expectChallenge(res) {