feat(web): enable automatic port assignment if default is in use (#175)
This commit is contained in:
committed by
GitHub
parent
6c3b653fbd
commit
3df362b220
+65
-24
@@ -179,7 +179,7 @@ ENVIRONMENT:
|
||||
OPENCHAMBER_UI_PASSWORD Alternative to --ui-password flag
|
||||
|
||||
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 serve --daemon # Start in background
|
||||
openchamber --try-cf-tunnel # Start with Cloudflare Quick Tunnel
|
||||
@@ -315,36 +315,40 @@ async function checkOpenCodeCLI() {
|
||||
}
|
||||
|
||||
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) => {
|
||||
const server = net.createServer();
|
||||
server.unref();
|
||||
server.on('error', () => resolve(false));
|
||||
server.listen({ port, host: '127.0.0.1' }, () => {
|
||||
server.listen({ port }, () => {
|
||||
server.close(() => resolve(true));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
async function resolveAvailablePort(desiredPort) {
|
||||
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')) {
|
||||
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)) {
|
||||
return startPort;
|
||||
}
|
||||
|
||||
for (let port = startPort + 1; port <= startPort + 50; port++) {
|
||||
if (await isPortAvailable(port)) {
|
||||
console.warn(`Port ${startPort} in use; using ${port}`);
|
||||
return port;
|
||||
}
|
||||
}
|
||||
|
||||
return startPort;
|
||||
console.warn(`Port ${startPort} in use; using a free port`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
async function getPidFilePath(port) {
|
||||
@@ -359,6 +363,7 @@ async function getInstanceFilePath(port) {
|
||||
return path.join(tmpDir, `openchamber-${port}.json`);
|
||||
}
|
||||
|
||||
|
||||
function readPidFile(pidFilePath) {
|
||||
try {
|
||||
const content = fs.readFileSync(pidFilePath, 'utf8').trim();
|
||||
@@ -446,6 +451,12 @@ function isProcessRunning(pid) {
|
||||
const commands = {
|
||||
async serve(options) {
|
||||
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 instanceFilePath = await getInstanceFilePath(options.port);
|
||||
|
||||
@@ -456,6 +467,12 @@ const commands = {
|
||||
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 serverPath = path.join(__dirname, '..', 'server', 'index.js');
|
||||
@@ -480,10 +497,9 @@ const commands = {
|
||||
const runtimeBin = preferredRuntime === 'bun' ? BUN_BIN : process.execPath;
|
||||
|
||||
if (options.daemon) {
|
||||
|
||||
const child = spawn(runtimeBin, serverArgs, {
|
||||
detached: true,
|
||||
stdio: 'ignore',
|
||||
stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
|
||||
env: {
|
||||
...process.env,
|
||||
OPENCHAMBER_PORT: options.port.toString(),
|
||||
@@ -495,13 +511,41 @@ const commands = {
|
||||
|
||||
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)) {
|
||||
writePidFile(pidFilePath, child.pid);
|
||||
writeInstanceOptions(instanceFilePath, { ...options, uiPassword: effectiveUiPassword });
|
||||
console.log(`OpenChamber started in daemon mode on port ${options.port}`);
|
||||
const pidFilePathResolved = await getPidFilePath(resolvedPort);
|
||||
const instanceFilePathResolved = await getInstanceFilePath(resolvedPort);
|
||||
|
||||
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(`Visit: http://localhost:${options.port}`);
|
||||
console.log(`Visit: http://localhost:${resolvedPort}`);
|
||||
if (showAutoGeneratedPassword) {
|
||||
console.log(`\n🔐 Auto-generated password: \x1b[92m${effectiveUiPassword}\x1b[0m`);
|
||||
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');
|
||||
process.exit(1);
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
process.env.OPENCODE_BINARY = opencodeBinary;
|
||||
if (typeof effectiveUiPassword === 'string') {
|
||||
@@ -523,8 +567,6 @@ const commands = {
|
||||
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,
|
||||
// run the server in a child process so Node doesn't have to load bun-pty.
|
||||
if (preferredRuntime === 'bun' && !isBunRuntime()) {
|
||||
@@ -564,7 +606,6 @@ const commands = {
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
async stop(options) {
|
||||
|
||||
@@ -1812,7 +1812,7 @@ async function main(options = {}) {
|
||||
exitOnShutdown = options.exitOnShutdown;
|
||||
}
|
||||
|
||||
console.log(`Starting OpenChamber on port ${port}`);
|
||||
console.log(`Starting OpenChamber on port ${port === 0 ? 'auto' : port}`);
|
||||
|
||||
const app = express();
|
||||
expressApp = app;
|
||||
@@ -4779,6 +4779,13 @@ async function main(options = {}) {
|
||||
server.off('error', onError);
|
||||
const addressInfo = server.address();
|
||||
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(`Health check: http://localhost:${activePort}/health`);
|
||||
console.log(`Web interface: http://localhost:${activePort}`);
|
||||
|
||||
Reference in New Issue
Block a user