Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat: add dynamic port allocation with preferred port fallback (#223)

Rohit Malhotra3207d90e7292
diff --git a/__tests__/scripts/dev-safe.test.ts b/__tests__/scripts/dev-safe.test.ts
index 1ef45b65d8..eaa7505191 100644
--- a/__tests__/scripts/dev-safe.test.ts
+++ b/__tests__/scripts/dev-safe.test.ts
@@ -1,3 +1,4 @@
+import net from "node:net";
import { spawn } from "node:child_process";
import { once } from "node:events";
import { homedir } from "node:os";
@@ -5,13 +6,16 @@ import path from "node:path";
import process from "node:process";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath } from "node:url";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, afterEach } from "vitest";
import {
buildSafeDevConfig,
+ buildSafeDevConfigAsync,
buildNpmScriptCommand,
buildAgentServerCommand,
formatMissingUvxGuidance,
validateLocalAgentServerPath,
+ findFreePort,
+ findFreePorts,
} from "../../scripts/dev-safe.mjs";
import { mkdtempSync, mkdirSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -21,6 +25,177 @@ const repoRoot = path.resolve(
"../..",
);
+describe("findFreePort", () => {
+ const servers: net.Server[] = [];
+
+ afterEach(() => {
+ // Clean up any servers we created
+ for (const server of servers) {
+ server.close();
+ }
+ servers.length = 0;
+ });
+
+ it("returns preferred port when available", async () => {
+ // Port 9999 should be free (unlikely to be in use during tests)
+ const port = await findFreePort(9999, "127.0.0.1");
+ expect(port).toBe(9999);
+ });
+
+ it("falls back to OS-assigned port when preferred is busy", async () => {
+ // Create a server that holds a port
+ const busyPort = await new Promise<number>((resolve, reject) => {
+ const server = net.createServer();
+ server.listen(0, "127.0.0.1", () => {
+ const addr = server.address();
+ if (addr && typeof addr === "object") {
+ servers.push(server);
+ resolve(addr.port);
+ } else {
+ server.close();
+ reject(new Error("Failed to get server address"));
+ }
+ });
+ });
+
+ // Now try to get that busy port
+ const allocatedPort = await findFreePort(busyPort, "127.0.0.1");
+
+ // Should get a different port since busyPort is taken
+ expect(allocatedPort).not.toBe(busyPort);
+ expect(typeof allocatedPort).toBe("number");
+ expect(allocatedPort).toBeGreaterThan(0);
+ });
+
+ it("returns OS-assigned port when preferredPort is 0", async () => {
+ const port = await findFreePort(0, "127.0.0.1");
+ expect(typeof port).toBe("number");
+ expect(port).toBeGreaterThan(0);
+ });
+});
+
+describe("findFreePorts", () => {
+ const servers: net.Server[] = [];
+
+ afterEach(() => {
+ for (const server of servers) {
+ server.close();
+ }
+ servers.length = 0;
+ });
+
+ it("allocates all requested ports when all preferred are available", async () => {
+ // Use high ports unlikely to be in use
+ const result = await findFreePorts([
+ { name: "portA", preferred: 19891 },
+ { name: "portB", preferred: 19892 },
+ ]);
+
+ // Check ports are valid - they may be the preferred or fallbacks
+ expect(typeof result.portA).toBe("number");
+ expect(result.portA).toBeGreaterThan(0);
+ expect(typeof result.portB).toBe("number");
+ expect(result.portB).toBeGreaterThan(0);
+ // Ports should be different
+ expect(result.portA).not.toBe(result.portB);
+ });
+
+ it("returns unique ports for each name", async () => {
+ // Use preferred: 0 to get OS-assigned ports
+ const result = await findFreePorts([
+ { name: "port1", preferred: 0 },
+ { name: "port2", preferred: 0 },
+ { name: "port3", preferred: 0 },
+ ]);
+
+ const ports = [result.port1, result.port2, result.port3];
+ const uniquePorts = new Set(ports);
+
+ expect(uniquePorts.size).toBe(3);
+ for (const port of ports) {
+ expect(typeof port).toBe("number");
+ expect(port).toBeGreaterThan(0);
+ }
+ });
+
+ it("falls back when preferred port is busy", async () => {
+ // Create a server that holds a port
+ const busyPort = await new Promise<number>((resolve, reject) => {
+ const server = net.createServer();
+ server.listen(0, "127.0.0.1", () => {
+ const addr = server.address();
+ if (addr && typeof addr === "object") {
+ servers.push(server);
+ resolve(addr.port);
+ } else {
+ server.close();
+ reject(new Error("Failed to get server address"));
+ }
+ });
+ });
+
+ const result = await findFreePorts([
+ { name: "busy", preferred: busyPort },
+ { name: "free", preferred: 19800 }, // high port unlikely to be busy
+ ]);
+
+ // "busy" should get a different port since it's taken
+ expect(result.busy).not.toBe(busyPort);
+ expect(typeof result.busy).toBe("number");
+ expect(result.busy).toBeGreaterThan(0);
+
+ // "free" should get the requested port if available
+ // (or a fallback if 19800 happens to be busy)
+ expect(typeof result.free).toBe("number");
+ expect(result.free).toBeGreaterThan(0);
+ });
+});
+
+describe("buildSafeDevConfigAsync", () => {
+ const servers: net.Server[] = [];
+
+ afterEach(() => {
+ for (const server of servers) {
+ server.close();
+ }
+ servers.length = 0;
+ });
+
+ it("returns config with dynamically allocated ports", async () => {
+ const config = await buildSafeDevConfigAsync(repoRoot, {});
+
+ expect(typeof config.backendPort).toBe("number");
+ expect(config.backendPort).toBeGreaterThan(0);
+ expect(typeof config.vscodePort).toBe("number");
+ expect(config.vscodePort).toBeGreaterThan(0);
+ // Ports should be different
+ expect(config.backendPort).not.toBe(config.vscodePort);
+ });
+
+ it("falls back when preferred ports are busy", async () => {
+ // Block a specific high port we'll request
+ const busyPort = 19600;
+ const server = net.createServer();
+ await new Promise<void>((resolve, reject) => {
+ server.listen(busyPort, "127.0.0.1", () => {
+ servers.push(server);
+ resolve();
+ });
+ server.on("error", reject);
+ });
+
+ // Request the busy port via env var
+ const config = await buildSafeDevConfigAsync(repoRoot, {
+ OH_CANVAS_SAFE_BACKEND_PORT: busyPort.toString(),
+ });
+
+ // Backend port should NOT be busyPort since it's taken
+ expect(config.backendPort).not.toBe(busyPort);
+ expect(typeof config.backendPort).toBe("number");
+ expect(config.backendPort).toBeGreaterThan(0);
+ });
+});
+
describe("formatMissingUvxGuidance", () => {
it("includes install, PATH, README, and fallback workflow hints", () => {
const guidance = formatMissingUvxGuidance(
diff --git a/__tests__/scripts/dev-with-automation.test.ts b/__tests__/scripts/dev-with-automation.test.ts
index f47f70af0a..c47d034173 100644
--- a/__tests__/scripts/dev-with-automation.test.ts
+++ b/__tests__/scripts/dev-with-automation.test.ts
@@ -1,10 +1,11 @@
+import net from "node:net";
import { spawn } from "node:child_process";
import { once } from "node:events";
import { homedir } from "node:os";
import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath } from "node:url";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, afterEach } from "vitest";
import {
buildAutomationCommand,
buildConfig,
@@ -112,96 +113,164 @@ describe("buildAutomationCommand", () => {
});
describe("buildConfig", () => {
- it("builds default config with correct ports", () => {
- const config = buildConfig({}, {});
+ const servers: net.Server[] = [];
- expect(config.ingressPort).toBe(8000);
- expect(config.agentServerPort).toBe(DEFAULT_BACKEND_PORT);
- expect(config.autoBackendPort).toBe(DEFAULT_AUTOMATION_PORT);
- expect(config.vitePort).toBe(3001);
- expect(config.vscodePort).toBe(DEFAULT_BACKEND_PORT + 1000);
+ afterEach(() => {
+ for (const server of servers) {
+ server.close();
+ }
+ servers.length = 0;
+ });
+
+ it("builds default config with correct ports", async () => {
+ const config = await buildConfig({}, {});
+
+ // Ports should be allocated (either defaults if free, or alternatives)
+ expect(typeof config.ingressPort).toBe("number");
+ expect(config.ingressPort).toBeGreaterThan(0);
+ expect(typeof config.agentServerPort).toBe("number");
+ expect(config.agentServerPort).toBeGreaterThan(0);
+ expect(typeof config.autoBackendPort).toBe("number");
+ expect(config.autoBackendPort).toBeGreaterThan(0);
+ expect(typeof config.vitePort).toBe("number");
+ expect(config.vitePort).toBeGreaterThan(0);
+ expect(config.vscodePort).toBe(config.agentServerPort + 1000);
+
+ // All four main ports should be unique
+ const ports = new Set([
+ config.ingressPort,
+ config.agentServerPort,
+ config.autoBackendPort,
+ config.vitePort,
+ ]);
+ expect(ports.size).toBe(4);
});
- it("respects port from args", () => {
- const config = buildConfig({ port: 9000 }, {});
+ it("respects preferred port from args when available", async () => {
+ // Use a high port unlikely to be busy
+ const preferredPort = 19500;
+ const config = await buildConfig({ port: preferredPort }, {});
+
+ expect(config.ingressPort).toBe(preferredPort);
+ });
+
+ it("falls back to alternative port when ingress port is busy", async () => {
+ const busyPort = 8100;
+
+ // Block port 8100
+ const server = net.createServer();
+ await new Promise<void>((resolve, reject) => {
+ server.listen(busyPort, "127.0.0.1", () => {
+ servers.push(server);
+ resolve();
+ });
+ server.on("error", reject);
+ });
+
+ // Request the busy port
+ const config = await buildConfig({ port: busyPort }, {});
+
+ // Should get a different port since busyPort is taken
+ expect(config.ingressPort).not.toBe(busyPort);
+ expect(config.ingressPort).toBeGreaterThan(0);
+ });
- expect(config.ingressPort).toBe(9000);
+ it("allocates valid ports for all services", async () => {
+ const config = await buildConfig({}, {});
+
+ // All service ports should be valid
+ expect(config.agentServerPort).toBeGreaterThan(0);
+ expect(config.autoBackendPort).toBeGreaterThan(0);
+ expect(config.vitePort).toBeGreaterThan(0);
+ expect(config.vscodePort).toBeGreaterThan(0);
+
+ // All service ports should be different from each other
+ const servicePorts = [
+ config.agentServerPort,
+ config.autoBackendPort,
+ config.vitePort,
+ config.ingressPort,
+ ];
+ expect(new Set(servicePorts).size).toBe(servicePorts.length);
});
- it("respects PORT from env", () => {
- const config = buildConfig({}, { PORT: "9001" });
+ it("respects preferred PORT from env when available", async () => {
+ // Use a high port unlikely to be busy
+ const preferredPort = "19501";
+ const config = await buildConfig({}, { PORT: preferredPort });
- expect(config.ingressPort).toBe(9001);
+ expect(config.ingressPort).toBe(19501);
});
- it("args.port takes precedence over env.PORT", () => {
- const config = buildConfig({ port: 9002 }, { PORT: "9999" });
+ it("args.port takes precedence over env.PORT", async () => {
+ // Use high ports unlikely to be busy
+ const config = await buildConfig({ port: 19502 }, { PORT: "19599" });
- expect(config.ingressPort).toBe(9002);
+ expect(config.ingressPort).toBe(19502);
});
- it("applies automationGitRef from args to env", () => {
+ it("applies automationGitRef from args to env", async () => {
const env: Record<string, string> = {};
- buildConfig({ automationGitRef: "my-branch" }, env);
+ await buildConfig({ automationGitRef: "my-branch" }, env);
expect(env.OH_AUTOMATION_GIT_REF).toBe("my-branch");
});
- it("applies automationRepo from args to env", () => {
+ it("applies automationRepo from args to env", async () => {
const env: Record<string, string> = {};
- buildConfig({ automationRepo: "https://example.com/repo" }, env);
+ await buildConfig({ automationRepo: "https://example.com/repo" }, env);
expect(env.OH_AUTOMATION_REPO).toBe("https://example.com/repo");
});
- it("uses correct state directory path", () => {
- const config = buildConfig({}, {});
+ it("uses correct state directory path", async () => {
+ const config = await buildConfig({}, {});
expect(config.stateDir).toBe(
path.join(homedir(), ".openhands", "agent-canvas"),
);
});
- it("passes verbose flag through", () => {
- const config = buildConfig({ verbose: true }, {});
+ it("passes verbose flag through", async () => {
+ const config = await buildConfig({ verbose: true }, {});
expect(config.verbose).toBe(true);
});
- it("auto-generates random local API key by default", () => {
- const config = buildConfig({}, {});
+ it("auto-generates random local API key by default", async () => {
+ const config = await buildConfig({}, {});
// Default is a 64-char hex string (256-bit random key)
expect(config.localApiKey).toMatch(/^[0-9a-f]{64}$/);
});
- it("respects custom AUTOMATION_LOCAL_API_KEY from env", () => {
- const config = buildConfig({}, { AUTOMATION_LOCAL_API_KEY: "my-custom-key" });
+ it("respects custom AUTOMATION_LOCAL_API_KEY from env", async () => {
+ const config = await buildConfig({}, { AUTOMATION_LOCAL_API_KEY: "my-custom-key" });
expect(config.localApiKey).toBe("my-custom-key");
});
- it("auto-generates random session API key by default", () => {
- const config = buildConfig({}, {});
+ it("auto-generates random session API key by default", async () => {
+ const config = await buildConfig({}, {});
// Default is a 64-char hex string (256-bit random key)
expect(config.sessionApiKey).toMatch(/^[0-9a-f]{64}$/);
});
- it("reads sessionApiKey from SESSION_API_KEY", () => {
- const config = buildConfig({}, { SESSION_API_KEY: "my-session-key" });
+ it("reads sessionApiKey from SESSION_API_KEY", async () => {
+ const config = await buildConfig({}, { SESSION_API_KEY: "my-session-key" });
expect(config.sessionApiKey).toBe("my-session-key");
});
- it("reads sessionApiKey from VITE_SESSION_API_KEY as fallback", () => {
- const config = buildConfig({}, { VITE_SESSION_API_KEY: "vite-session-key" });
+ it("reads sessionApiKey from VITE_SESSION_API_KEY as fallback", async () => {
+ const config = await buildConfig({}, { VITE_SESSION_API_KEY: "vite-session-key" });
expect(config.sessionApiKey).toBe("vite-session-key");
});
- it("SESSION_API_KEY takes precedence over VITE_SESSION_API_KEY", () => {
- const config = buildConfig({}, {
+ it("SESSION_API_KEY takes precedence over VITE_SESSION_API_KEY", async () => {
+ const config = await buildConfig({}, {
SESSION_API_KEY: "session-key",
VITE_SESSION_API_KEY: "vite-key",
});
@@ -209,14 +278,14 @@ describe("buildConfig", () => {
expect(config.sessionApiKey).toBe("session-key");
});
- it("reads sessionApiKey from OH_SESSION_API_KEYS_0 (agent-server V1 env)", () => {
- const config = buildConfig({}, { OH_SESSION_API_KEYS_0: "v1-session-key" });
+ it("reads sessionApiKey from OH_SESSION_API_KEYS_0 (agent-server V1 env)", async () => {
+ const config = await buildConfig({}, { OH_SESSION_API_KEYS_0: "v1-session-key" });
expect(config.sessionApiKey).toBe("v1-session-key");
});
- it("SESSION_API_KEY takes precedence over OH_SESSION_API_KEYS_0", () => {
- const config = buildConfig({}, {
+ it("SESSION_API_KEY takes precedence over OH_SESSION_API_KEYS_0", async () => {
+ const config = await buildConfig({}, {
SESSION_API_KEY: "v0-key",
OH_SESSION_API_KEYS_0: "v1-key",
});
@@ -224,8 +293,8 @@ describe("buildConfig", () => {
expect(config.sessionApiKey).toBe("v0-key");
});
- it("SESSION_API_KEY takes precedence over all other session key env vars", () => {
- const config = buildConfig({}, {
+ it("SESSION_API_KEY takes precedence over all other session key env vars", async () => {
+ const config = await buildConfig({}, {
SESSION_API_KEY: "v0-key",
OH_SESSION_API_KEYS_0: "v1-key",
VITE_SESSION_API_KEY: "vite-key",
diff --git a/scripts/dev-safe.mjs b/scripts/dev-safe.mjs
index c326b99a1c..e91600a6b0 100644
--- a/scripts/dev-safe.mjs
+++ b/scripts/dev-safe.mjs
@@ -15,6 +15,7 @@ import { setTimeout as delay } from "node:timers/promises";
import { pathToFileURL } from "node:url";
const DEFAULT_BACKEND_PORT = 18000;
+const DEFAULT_VITE_PORT = 3001;
const DEFAULT_WAIT_TIMEOUT_MS = 30_000;
const DEFAULT_AGENT_SERVER_PACKAGE = "openhands-agent-server";
const AGENT_SERVER_GIT_REPO = "https://github.com/OpenHands/software-agent-sdk";
@@ -54,6 +55,106 @@ function isEnoentError(error) {
);
}
+/**
+ * Find a free port, preferring the specified port if available.
+ *
+ * Tries the preferred port first; if it's busy, falls back to letting
+ * the OS assign any available port. This preserves predictable defaults
+ * while gracefully handling port conflicts.
+ *
+ * **Note on race conditions:** There is a small window between when this
+ * function checks port availability and when the calling service actually
+ * binds to the port. During this window, another process could theoretically
+ * grab the port. This is an accepted limitation of the "check-then-use"
+ * approach. Callers (like agent-server) should handle EADDRINUSE gracefully.
+ * For Vite, `strictPort: true` ensures a fast failure if this occurs.
+ *
+ * @param {number} preferredPort - The port to try first
+ * @param {string} host - The host to bind to (default: "127.0.0.1")
+ * @returns {Promise<number>} The actual port that was acquired
+ */
+export async function findFreePort(preferredPort, host = "127.0.0.1") {
+ // If preferredPort is 0, skip the check and go straight to OS assignment
+ if (preferredPort > 0) {
+ const preferredAvailable = await tryPort(preferredPort, host);
+ if (preferredAvailable) {
+ return preferredPort;
+ }
+ }
+
+ // Fall back to OS-assigned port
+ return new Promise((resolve, reject) => {
+ const server = net.createServer();
+ server.once("error", reject);
+ server.listen(0, host, () => {
+ const { port } = server.address();
+ server.close(() => resolve(port));
+ });
+ });
+}
+
+/**
+ * Check if a port is available by attempting to bind to it.
+ *
+ * @param {number} port - The port to check
+ * @param {string} host - The host to bind to
+ * @returns {Promise<boolean>} True if the port is available
+ */
+function tryPort(port, host = "127.0.0.1") {
+ return new Promise((resolve) => {
+ const server = net.createServer();
+ server.once("error", () => resolve(false));
+ server.listen(port, host, () => {
+ server.close(() => resolve(true));
+ });
+ });
+}
+
+/**
+ * Find multiple free ports at once, each preferring its specified default.
+ *
+ * Allocates ports sequentially to avoid race conditions between checks.
+ *
+ * @param {Array<{name: string, preferred: number}>} portConfigs - Port configurations
+ * @param {string} host - The host to bind to (default: "127.0.0.1")
+ * @returns {Promise<Record<string, number>>} Map of name to actual port
+ */
+export async function findFreePorts(portConfigs, host = "127.0.0.1") {
+ const result = {};
+ const usedPorts = new Set();
+
+ for (const { name, preferred } of portConfigs) {
+ // Try preferred if not already taken by a previous allocation
+ // Skip if preferred is 0 (means "any port") or already used
+ if (preferred > 0 && !usedPorts.has(preferred)) {
+ const available = await tryPort(preferred, host);
+ if (available) {
+ result[name] = preferred;
+ usedPorts.add(preferred);
+ continue;
+ }
+ }
+
+ // Fall back to OS-assigned port, retrying if we get a collision
+ let port;
+ let attempts = 0;
+ const maxAttempts = 100;
+ do {
+ port = await findFreePort(0, host);
+ if (++attempts > maxAttempts) {
+ throw new Error(
+ `Could not allocate unique port for "${name}" after ${maxAttempts} attempts`,
+ );
+ }
+ } while (usedPorts.has(port));
+
+ result[name] = port;
+ usedPorts.add(port);
+ }
+
+ return result;
+}
+
export function formatMissingUvxGuidance(cwd = process.cwd()) {
const readmePath = path.join(cwd, "README.md");
@@ -186,6 +287,22 @@ function parsePort(value, fallback) {
return parsed;
}
+/**
+ * Build safe dev configuration (synchronous version).
+ *
+ * Uses the port values from environment variables or defaults WITHOUT checking
+ * port availability. Use this when:
+ * - You need synchronous config (e.g., for test setup, config inspection)
+ * - Ports are already known to be available (e.g., specified via env vars)
+ * - You're building config objects for downstream use, not starting services
+ *
+ * For scripts that actually start services (dev-safe.mjs main, dev-with-automation.mjs),
+ * use {@link buildSafeDevConfigAsync} instead to handle port conflicts gracefully.
+ *
+ * @param {string} cwd - Current working directory
+ * @param {Record<string, string | undefined>} env - Environment variables
+ * @returns {SafeDevConfig} Configuration object
+ */
export function buildSafeDevConfig(cwd = process.cwd(), env = process.env) {
const backendPort = parsePort(
env.OH_CANVAS_SAFE_BACKEND_PORT,
@@ -195,6 +312,85 @@ export function buildSafeDevConfig(cwd = process.cwd(), env = process.env) {
env.OH_CANVAS_SAFE_VSCODE_PORT,
backendPort + 1,
);
+
+ return buildConfigFromPorts({ backendPort, vscodePort }, cwd, env);
+}
+
+/**
+ * Build safe dev configuration with dynamic port allocation.
+ *
+ * Tries preferred ports first; if busy, finds available alternatives.
+ * This is the recommended entry point for scripts that start services.
+ *
+ * @param {string} cwd - Current working directory
+ * @param {Record<string, string | undefined>} env - Environment variables
+ * @returns {Promise<SafeDevConfig>} Configuration object with allocated ports
+ */
+export async function buildSafeDevConfigAsync(
+ cwd = process.cwd(),
+ env = process.env,
+) {
+ // Get preferred ports from env or defaults
+ const preferredBackendPort = parsePort(
+ env.OH_CANVAS_SAFE_BACKEND_PORT,
+ DEFAULT_BACKEND_PORT,
+ );
+ const preferredVscodePort = parsePort(
+ env.OH_CANVAS_SAFE_VSCODE_PORT,
+ preferredBackendPort + 1,
+ );
+
+ // Find available ports, preferring the defaults
+ const ports = await findFreePorts([
+ { name: "backend", preferred: preferredBackendPort },
+ { name: "vscode", preferred: preferredVscodePort },
+ ]);
+
+ // Log if we're using non-default ports
+ if (ports.backend !== preferredBackendPort) {
+ console.log(
+ ` β„Ή Port ${preferredBackendPort} busy, using ${ports.backend} for agent-server`,
+ );
+ }
+ if (ports.vscode !== preferredVscodePort) {
+ console.log(
+ ` β„Ή Port ${preferredVscodePort} busy, using ${ports.vscode} for vscode`,
+ );
+ }
+
+ return buildConfigFromPorts(
+ { backendPort: ports.backend, vscodePort: ports.vscode },
+ cwd,
+ env,
+ );
+}
+
+/**
+ * @typedef {object} SafeDevConfig
+ * @property {string} cwd
+ * @property {number} backendPort
+ * @property {number} vscodePort
+ * @property {string} stateDir
+ * @property {string} tmuxTmpDir
+ * @property {string} conversationsPath
+ * @property {string} workspacesPath
+ * @property {string} bashEventsDir
+ * @property {string} backendBaseUrl
+ * @property {string} backendHost
+ * @property {string} workingDir
+ * @property {string} secretKey
+ * @property {string} sessionApiKey
+ */
+
+/**
+ * Internal helper to build config from already-resolved ports.
+ * @param {{backendPort: number, vscodePort: number}} ports
+ * @param {string} cwd
+ * @param {Record<string, string | undefined>} env
+ * @returns {SafeDevConfig}
+ */
+function buildConfigFromPorts(ports, cwd, env) {
+ const { backendPort, vscodePort } = ports;
const stateDir = path.resolve(
cwd,
env.OH_CANVAS_SAFE_STATE_DIR ||
@@ -338,7 +534,11 @@ function spawnProcess(command, args, options) {
}
async function main() {
- const config = buildSafeDevConfig();
+ console.log("Starting isolated agent-server + frontend dev stack...");
+ console.log("Allocating ports...");
+
+ // Use async config builder with dynamic port allocation
+ const config = await buildSafeDevConfigAsync();
if (process.env.OH_AGENT_SERVER_LOCAL_PATH) {
validateLocalAgentServerPath(process.env.OH_AGENT_SERVER_LOCAL_PATH);
@@ -367,7 +567,6 @@ async function main() {
? "custom (from env)"
: "auto-generated (random)";
- console.log("Starting isolated agent-server + frontend dev stack...");
console.log(`- agent-server: ${agentServerCmd.source}`);
console.log(`- backend: ${config.backendBaseUrl}`);
console.log(`- vscode port: ${config.vscodePort}`);
diff --git a/scripts/dev-static.mjs b/scripts/dev-static.mjs
index 9badbdfe17..65f4892be3 100644
--- a/scripts/dev-static.mjs
+++ b/scripts/dev-static.mjs
@@ -565,7 +565,7 @@ function printBanner(config) {
async function main() {
const args = parseArgs();
- const config = buildConfig(args);
+ const config = await buildConfig(args);
console.log("");
console.log(
diff --git a/scripts/dev-with-automation.mjs b/scripts/dev-with-automation.mjs
index ef0c2727b4..07feb2c436 100644
--- a/scripts/dev-with-automation.mjs
+++ b/scripts/dev-with-automation.mjs
@@ -52,6 +52,7 @@ import {
buildNpmScriptCommand,
formatMissingUvxGuidance,
generateRandomApiKey,
+ findFreePorts,
} from "./dev-safe.mjs";
const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -220,7 +221,7 @@ function buildAutomationCommand(env = process.env) {
};
}
-function buildConfig(args, env = process.env) {
+async function buildConfig(args, env = process.env) {
// Apply args to env for buildAutomationCommand
if (args.automationGitRef) {
env.OH_AUTOMATION_GIT_REF = args.automationGitRef;
@@ -229,11 +230,36 @@ function buildConfig(args, env = process.env) {
env.OH_AUTOMATION_REPO = args.automationRepo;
}
- const ingressPort = args.port || parseInt(env.PORT, 10) || 8000;
- const backendPort = DEFAULT_BACKEND_PORT;
- const automationPort = DEFAULT_AUTOMATION_PORT;
- const vitePort = 3001;
- const vscodePort = backendPort + 1000;
+ // Preferred ports (from env or defaults)
+ const preferredIngressPort = args.port || parseInt(env.PORT, 10) || 8000;
+ const preferredBackendPort = DEFAULT_BACKEND_PORT;
+ const preferredAutomationPort = DEFAULT_AUTOMATION_PORT;
+ const preferredVitePort = 3001;
+
+ // Find available ports, preferring the defaults
+ logStep("ports", "Allocating ports...");
+ const ports = await findFreePorts([
+ { name: "ingress", preferred: preferredIngressPort },
+ { name: "backend", preferred: preferredBackendPort },
+ { name: "automation", preferred: preferredAutomationPort },
+ { name: "vite", preferred: preferredVitePort },
+ ]);
+
+ // Log any port changes
+ if (ports.ingress !== preferredIngressPort) {
+ logService("ports", `Port ${preferredIngressPort} busy, using ${ports.ingress} for ingress`, c.yellow);
+ }
+ if (ports.backend !== preferredBackendPort) {
+ logService("ports", `Port ${preferredBackendPort} busy, using ${ports.backend} for agent-server`, c.yellow);
+ }
+ if (ports.automation !== preferredAutomationPort) {
+ logService("ports", `Port ${preferredAutomationPort} busy, using ${ports.automation} for automation`, c.yellow);
+ }
+ if (ports.vite !== preferredVitePort) {
+ logService("ports", `Port ${preferredVitePort} busy, using ${ports.vite} for vite`, c.yellow);
+ }
+
+ const vscodePort = ports.backend + 1000;
// Local API key for automation backend auth
const localApiKey = env.AUTOMATION_LOCAL_API_KEY || DEFAULT_LOCAL_API_KEY;
@@ -245,19 +271,19 @@ function buildConfig(args, env = process.env) {
const safeConfig = buildSafeDevConfig(projectRoot, {
...env,
OH_CANVAS_SAFE_STATE_DIR: stateDir,
- OH_CANVAS_SAFE_BACKEND_PORT: backendPort.toString(),
+ OH_CANVAS_SAFE_BACKEND_PORT: ports.backend.toString(),
OH_CANVAS_SAFE_VSCODE_PORT: vscodePort.toString(),
});
const sessionApiKey = safeConfig.sessionApiKey;
return {
// Ingress port (main entry point)
- ingressPort,
+ ingressPort: ports.ingress,
// Service ports (internal)
- agentServerPort: backendPort,
- autoBackendPort: automationPort,
- vitePort,
+ agentServerPort: ports.backend,
+ autoBackendPort: ports.automation,
+ vitePort: ports.vite,
vscodePort,
// Paths
@@ -660,7 +686,6 @@ function printBanner(config) {
async function main() {
const args = parseArgs();
- const config = buildConfig(args);
console.log("");
console.log(`${c.cyan}${c.bold}Agent Canvas + Automation Development Stack${c.reset}`);
@@ -668,6 +693,9 @@ async function main() {
// Setup phase
checkPrerequisites();
+
+ // Build config with dynamic port allocation
+ const config = await buildConfig(args);
ensureDirectories(config);
// Start services phase
diff --git a/vite.config.ts b/vite.config.ts
index 628834658c..21e0071973 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -154,6 +154,7 @@ export default defineConfig(({ mode }) => {
},
server: {
port: FE_PORT,
+ strictPort: true, // Fail if port is busy (dynamic allocation handles fallback)
host: true,
allowedHosts: true,
proxy: {