feat(web): enable automatic port assignment if default is in use (#175)

This commit is contained in:
Bohdan Triapitsyn
2026-01-18 18:18:42 +02:00
committed by GitHub
parent 6c3b653fbd
commit 3df362b220
2 changed files with 131 additions and 83 deletions
+65 -24
View File
@@ -179,7 +179,7 @@ ENVIRONMENT:
OPENCHAMBER_UI_PASSWORD Alternative to --ui-password flag OPENCHAMBER_UI_PASSWORD Alternative to --ui-password flag
EXAMPLES: EXAMPLES:
openchamber # Start on default port 3000 openchamber # Start on default port 3000 (or a free port)
openchamber --port 8080 # Start on port 8080 openchamber --port 8080 # Start on port 8080
openchamber serve --daemon # Start in background openchamber serve --daemon # Start in background
openchamber --try-cf-tunnel # Start with Cloudflare Quick Tunnel openchamber --try-cf-tunnel # Start with Cloudflare Quick Tunnel
@@ -315,36 +315,40 @@ async function checkOpenCodeCLI() {
} }
async function isPortAvailable(port) { async function isPortAvailable(port) {
if (!Number.isFinite(port) || port <= 0) {
return false;
}
// Don't specify host here; `server.listen(port)` in the web server also doesn't,
// and on some platforms (notably macOS) IPv4/IPv6 binding differences can make
// a 127.0.0.1-only probe report "free" while the real server bind fails.
return await new Promise((resolve) => { return await new Promise((resolve) => {
const server = net.createServer(); const server = net.createServer();
server.unref(); server.unref();
server.on('error', () => resolve(false)); server.on('error', () => resolve(false));
server.listen({ port, host: '127.0.0.1' }, () => { server.listen({ port }, () => {
server.close(() => resolve(true)); server.close(() => resolve(true));
}); });
}); });
} }
async function resolveAvailablePort(desiredPort) { async function resolveAvailablePort(desiredPort) {
const startPort = Number.isFinite(desiredPort) ? Math.trunc(desiredPort) : DEFAULT_PORT; const startPort = Number.isFinite(desiredPort) ? Math.trunc(desiredPort) : DEFAULT_PORT;
// Only auto-pick when user didn't explicitly choose a port.
// If user explicitly chose a port (incl 0), respect it.
if (process.argv.includes('--port') || process.argv.includes('-p')) { if (process.argv.includes('--port') || process.argv.includes('-p')) {
return startPort; return startPort;
} }
// If default is busy, probe upward a bit. // Prefer the default port for predictable URLs, but fall back to an OS-assigned
// free port when it is already in use.
if (await isPortAvailable(startPort)) { if (await isPortAvailable(startPort)) {
return startPort; return startPort;
} }
for (let port = startPort + 1; port <= startPort + 50; port++) { console.warn(`Port ${startPort} in use; using a free port`);
if (await isPortAvailable(port)) { return 0;
console.warn(`Port ${startPort} in use; using ${port}`);
return port;
}
}
return startPort;
} }
async function getPidFilePath(port) { async function getPidFilePath(port) {
@@ -359,6 +363,7 @@ async function getInstanceFilePath(port) {
return path.join(tmpDir, `openchamber-${port}.json`); return path.join(tmpDir, `openchamber-${port}.json`);
} }
function readPidFile(pidFilePath) { function readPidFile(pidFilePath) {
try { try {
const content = fs.readFileSync(pidFilePath, 'utf8').trim(); const content = fs.readFileSync(pidFilePath, 'utf8').trim();
@@ -446,6 +451,12 @@ function isProcessRunning(pid) {
const commands = { const commands = {
async serve(options) { async serve(options) {
options.port = await resolveAvailablePort(options.port); options.port = await resolveAvailablePort(options.port);
const portWasSpecified = process.argv.includes('--port') || process.argv.includes('-p');
// When using dynamic port (port=0), don't use pid/instance files - the port is
// unknown until the server binds.
if (options.port !== 0) {
const pidFilePath = await getPidFilePath(options.port); const pidFilePath = await getPidFilePath(options.port);
const instanceFilePath = await getInstanceFilePath(options.port); const instanceFilePath = await getInstanceFilePath(options.port);
@@ -456,6 +467,12 @@ const commands = {
process.exit(1); process.exit(1);
} }
// Persist for restart/update to reuse the chosen port.
writeInstanceOptions(instanceFilePath, { ...options });
} else if (portWasSpecified) {
// Explicitly requested port=0; nothing to persist.
}
const opencodeBinary = await checkOpenCodeCLI(); const opencodeBinary = await checkOpenCodeCLI();
const serverPath = path.join(__dirname, '..', 'server', 'index.js'); const serverPath = path.join(__dirname, '..', 'server', 'index.js');
@@ -480,10 +497,9 @@ const commands = {
const runtimeBin = preferredRuntime === 'bun' ? BUN_BIN : process.execPath; const runtimeBin = preferredRuntime === 'bun' ? BUN_BIN : process.execPath;
if (options.daemon) { if (options.daemon) {
const child = spawn(runtimeBin, serverArgs, { const child = spawn(runtimeBin, serverArgs, {
detached: true, detached: true,
stdio: 'ignore', stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
env: { env: {
...process.env, ...process.env,
OPENCHAMBER_PORT: options.port.toString(), OPENCHAMBER_PORT: options.port.toString(),
@@ -495,13 +511,41 @@ const commands = {
child.unref(); child.unref();
setTimeout(() => { const resolvedPort = await new Promise((resolve) => {
let settled = false;
const timeout = setTimeout(() => {
if (settled) return;
settled = true;
resolve(options.port);
}, 5000);
child.on('message', (msg) => {
if (settled) return;
if (msg && msg.type === 'openchamber:ready' && typeof msg.port === 'number') {
settled = true;
clearTimeout(timeout);
resolve(msg.port);
}
});
child.on('exit', () => {
if (settled) return;
settled = true;
clearTimeout(timeout);
resolve(options.port);
});
});
if (isProcessRunning(child.pid)) { if (isProcessRunning(child.pid)) {
writePidFile(pidFilePath, child.pid); const pidFilePathResolved = await getPidFilePath(resolvedPort);
writeInstanceOptions(instanceFilePath, { ...options, uiPassword: effectiveUiPassword }); const instanceFilePathResolved = await getInstanceFilePath(resolvedPort);
console.log(`OpenChamber started in daemon mode on port ${options.port}`);
writePidFile(pidFilePathResolved, child.pid);
writeInstanceOptions(instanceFilePathResolved, { ...options, port: resolvedPort, uiPassword: effectiveUiPassword });
console.log(`OpenChamber started in daemon mode on port ${resolvedPort}`);
console.log(`PID: ${child.pid}`); console.log(`PID: ${child.pid}`);
console.log(`Visit: http://localhost:${options.port}`); console.log(`Visit: http://localhost:${resolvedPort}`);
if (showAutoGeneratedPassword) { if (showAutoGeneratedPassword) {
console.log(`\n🔐 Auto-generated password: \x1b[92m${effectiveUiPassword}\x1b[0m`); console.log(`\n🔐 Auto-generated password: \x1b[92m${effectiveUiPassword}\x1b[0m`);
console.log('⚠️ Save this password - it won\'t be shown again!\n'); console.log('⚠️ Save this password - it won\'t be shown again!\n');
@@ -510,9 +554,9 @@ const commands = {
console.error('Failed to start server in daemon mode'); console.error('Failed to start server in daemon mode');
process.exit(1); process.exit(1);
} }
}, 1000);
} else { return;
}
process.env.OPENCODE_BINARY = opencodeBinary; process.env.OPENCODE_BINARY = opencodeBinary;
if (typeof effectiveUiPassword === 'string') { if (typeof effectiveUiPassword === 'string') {
@@ -523,8 +567,6 @@ const commands = {
console.log('⚠️ Save this password - it won\'t be shown again!\n'); console.log('⚠️ Save this password - it won\'t be shown again!\n');
} }
writeInstanceOptions(instanceFilePath, { ...options, uiPassword: effectiveUiPassword });
// Prefer bun when installed (much faster PTY). If CLI is running under Node, // Prefer bun when installed (much faster PTY). If CLI is running under Node,
// run the server in a child process so Node doesn't have to load bun-pty. // run the server in a child process so Node doesn't have to load bun-pty.
if (preferredRuntime === 'bun' && !isBunRuntime()) { if (preferredRuntime === 'bun' && !isBunRuntime()) {
@@ -564,7 +606,6 @@ const commands = {
} }
}, },
}); });
}
}, },
async stop(options) { async stop(options) {
+8 -1
View File
@@ -1812,7 +1812,7 @@ async function main(options = {}) {
exitOnShutdown = options.exitOnShutdown; exitOnShutdown = options.exitOnShutdown;
} }
console.log(`Starting OpenChamber on port ${port}`); console.log(`Starting OpenChamber on port ${port === 0 ? 'auto' : port}`);
const app = express(); const app = express();
expressApp = app; expressApp = app;
@@ -4779,6 +4779,13 @@ async function main(options = {}) {
server.off('error', onError); server.off('error', onError);
const addressInfo = server.address(); const addressInfo = server.address();
activePort = typeof addressInfo === 'object' && addressInfo ? addressInfo.port : port; activePort = typeof addressInfo === 'object' && addressInfo ? addressInfo.port : port;
try {
process.send?.({ type: 'openchamber:ready', port: activePort });
} catch {
// ignore
}
console.log(`OpenChamber server running on port ${activePort}`); console.log(`OpenChamber server running on port ${activePort}`);
console.log(`Health check: http://localhost:${activePort}/health`); console.log(`Health check: http://localhost:${activePort}/health`);
console.log(`Web interface: http://localhost:${activePort}`); console.log(`Web interface: http://localhost:${activePort}`);