diff --git a/tests/adapters/javascript/integration/javascript-attach-idle.test.ts b/tests/adapters/javascript/integration/javascript-attach-idle.test.ts index 3d0087b3..ca018dfd 100644 --- a/tests/adapters/javascript/integration/javascript-attach-idle.test.ts +++ b/tests/adapters/javascript/integration/javascript-attach-idle.test.ts @@ -39,7 +39,6 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import fs from 'node:fs'; import http from 'node:http'; -import net from 'node:net'; import path from 'node:path'; import { spawn, type ChildProcess } from 'node:child_process'; import { fileURLToPath } from 'node:url'; @@ -70,43 +69,36 @@ let server: StdioClientHandle; let targets: Target[] = []; const call = (name: string, args: Record = {}): Promise => server.call(name, args); -async function getFreePort(): Promise { - return new Promise((resolve, reject) => { - const probe = net.createServer(); - probe.listen(0, '127.0.0.1', () => { - const address = probe.address(); - const port = typeof address === 'object' && address ? address.port : 0; - probe.close(() => (port ? resolve(port) : reject(new Error('no free port')))); - }); - probe.on('error', reject); - }); -} - -/** Start a server fixture under `node --inspect` and wait for the port it prints. */ +/** Start a server fixture under `node --inspect=127.0.0.1:0` and read both kernel-assigned ports. */ async function startTarget(script: string): Promise { - const inspectPort = await getFreePort(); - const proc = spawn(process.execPath, [`--inspect=127.0.0.1:${inspectPort}`, script], { + const proc = spawn(process.execPath, ['--inspect=127.0.0.1:0', script], { cwd: path.dirname(script), windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); let buffer = ''; - const target: Target = { proc, inspectPort, httpPort: 0 }; + const target: Target = { proc, inspectPort: 0, httpPort: 0 }; // Register before readiness so afterEach also cleans up a failed startup. targets.push(target); - target.httpPort = await new Promise((resolve, reject) => { + const ports = await new Promise<{ inspectPort: number; httpPort: number }>((resolve, reject) => { const timer = setTimeout(() => reject(new Error(`the server did not print its port: ${buffer}`)), 30000); const onData = (chunk: Buffer) => { buffer += chunk.toString(); const listening = /listening (\d+)/.exec(buffer); + const inspector = /Debugger listening on ws:\/\/127\.0\.0\.1:(\d+)\//.exec(buffer); // The inspector's own banner goes to stderr first; wait for both. - if (listening && buffer.includes('Debugger listening on')) { clearTimeout(timer); resolve(Number(listening[1])); } + if (listening && inspector) { + clearTimeout(timer); + resolve({ inspectPort: Number(inspector[1]), httpPort: Number(listening[1]) }); + } }; proc.stdout!.on('data', onData); proc.stderr!.on('data', onData); proc.on('error', (error) => { clearTimeout(timer); reject(error); }); proc.on('exit', (code) => { clearTimeout(timer); reject(new Error(`the server exited ${code} before listening: ${buffer}`)); }); }); + target.inspectPort = ports.inspectPort; + target.httpPort = ports.httpPort; return target; } diff --git a/tests/adapters/javascript/integration/javascript-subprocess-attach.test.ts b/tests/adapters/javascript/integration/javascript-subprocess-attach.test.ts index b91c4416..465cc6a8 100644 --- a/tests/adapters/javascript/integration/javascript-subprocess-attach.test.ts +++ b/tests/adapters/javascript/integration/javascript-subprocess-attach.test.ts @@ -16,7 +16,6 @@ */ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import path from 'node:path'; -import net from 'node:net'; import { spawn, type ChildProcess } from 'node:child_process'; import { fileURLToPath } from 'node:url'; import { startStdioClient, type StdioClientHandle, type ToolAnswer } from '../../../test-utils/helpers/mcp-stdio-client.js'; @@ -81,22 +80,9 @@ async function pollUntil(read: () => Promise, accept: (value: T) => boolea return last; } -async function getFreePort(): Promise { - return new Promise((resolve, reject) => { - const probe = net.createServer(); - probe.listen(0, '127.0.0.1', () => { - const address = probe.address(); - const port = typeof address === 'object' && address ? address.port : 0; - probe.close(() => (port ? resolve(port) : reject(new Error('no free port')))); - }); - probe.on('error', reject); - }); -} - -/** Start a script under `node --inspect` and wait until its inspector listens. */ +/** Start a script under `node --inspect=127.0.0.1:0` and read the kernel-assigned inspector port. */ async function startTarget(script: string): Promise { - const port = await getFreePort(); - const proc = spawn(process.execPath, [`--inspect=127.0.0.1:${port}`, script], { + const proc = spawn(process.execPath, ['--inspect=127.0.0.1:0', script], { cwd: treeDir, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] @@ -104,14 +90,15 @@ async function startTarget(script: string): Promise { let buffer = ''; // close also waits for the output pipes, so the exit assertions see the final lines. const exited = new Promise((resolve) => proc.on('close', (code) => resolve(code))); - const target: Target = { proc, port, output: () => buffer, exited, go: (mode = 'go') => { proc.stdin!.write(`${mode}\n`); } }; + const target: Target = { proc, port: 0, output: () => buffer, exited, go: (mode = 'go') => { proc.stdin!.write(`${mode}\n`); } }; // Register before readiness so afterEach also cleans up a failed startup. targets.push(target); - await new Promise((resolve, reject) => { + target.port = await new Promise((resolve, reject) => { const timer = setTimeout(() => reject(new Error(`node --inspect not listening: ${buffer}`)), 30000); const onData = (chunk: Buffer) => { buffer += chunk.toString(); - if (buffer.includes('Debugger listening on')) { clearTimeout(timer); resolve(); } + const match = /Debugger listening on ws:\/\/127\.0\.0\.1:(\d+)\//.exec(buffer); + if (match) { clearTimeout(timer); resolve(Number(match[1])); } }; proc.stdout!.on('data', onData); proc.stderr!.on('data', onData); diff --git a/tests/adapters/python/integration/python-subprocess-attach.test.ts b/tests/adapters/python/integration/python-subprocess-attach.test.ts index b7a5f2f0..5755a2a7 100644 --- a/tests/adapters/python/integration/python-subprocess-attach.test.ts +++ b/tests/adapters/python/integration/python-subprocess-attach.test.ts @@ -96,13 +96,16 @@ interface Target { proc: ChildProcess; port: number; output: () => string; exite let targets: Target[] = []; +const PORT_IN_USE_PATTERN = /Address already in use|EADDRINUSE|10048/i; + /** * Start attach_parent.py under `python -m debugpy --listen` and wait for its * READY line. No TCP probe: a session-less connect makes the adapter exit * (docs/python/spike-notes-subprocess.md), and the script prints READY after - * debugpy has its listener up. + * debugpy has its listener up. Retries if a parallel test grabs the ephemeral + * port between `getFreePort()` closing its probe socket and `debugpy` binding. */ -async function startTarget(extraArgs: string[] = []): Promise { +async function startTargetOnce(extraArgs: string[] = []): Promise { const port = await getFreePort(); const proc = spawn(PYTHON, ['-m', 'debugpy', '--listen', `127.0.0.1:${port}`, ...extraArgs, attachParent], { cwd: treeDir, @@ -129,6 +132,24 @@ async function startTarget(extraArgs: string[] = []): Promise { return target; } +async function startTarget(extraArgs: string[] = []): Promise { + const maxAttempts = 4; + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + return await startTargetOnce(extraArgs); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + if (attempt < maxAttempts && PORT_IN_USE_PATTERN.test(message)) { + const failed = targets.pop(); + if (failed && failed.proc.exitCode === null) failed.proc.kill(); + continue; + } + throw error; + } + } + throw new Error('unreachable'); +} + /** The target's exit, with its own pipe's last lines: the proof that nothing killed it. */ async function targetRanToItsEnd(target: Target): Promise { let timer: ReturnType | undefined;