Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(dev): resolve dev ports in orchestrator and inject via env (#16641)

Inneia84caf71563e
diff --git a/scripts/devStartupSequence.mts b/scripts/devStartupSequence.mts
index f5b9aa5d005..24315f3c9bd 100644
--- a/scripts/devStartupSequence.mts
+++ b/scripts/devStartupSequence.mts
@@ -17,17 +17,70 @@ const isWindows = process.platform === 'win32';
const NEXT_HOST = 'localhost';
+const MAX_PORT_SCAN_ATTEMPTS = 100;
+
+// Probe loopback addresses in addition to the wildcard: a server bound only to
+// 127.0.0.1 would not conflict with a wildcard bind (SO_REUSEADDR on BSD), yet
+// it still hijacks the localhost URLs every dev consumer actually hits.
+const PROBE_HOSTS: (string | undefined)[] = ['127.0.0.1', '::1', undefined];
+
+const canBind = (port: number, host?: string) =>
+ new Promise<boolean>((resolve) => {
+ const server = net.createServer();
+ server.unref();
+ server.once('error', (error: NodeJS.ErrnoException) => {
+ // An unavailable address family (e.g. no IPv6) is not "port busy".
+ resolve(error.code !== 'EADDRINUSE' && error.code !== 'EACCES');
+ });
+ server.listen({ host, port }, () => {
+ server.close(() => resolve(true));
+ });
+ });
+
+const isPortFree = async (port: number): Promise<boolean> => {
+ for (const host of PROBE_HOSTS) {
+ if (!(await canBind(port, host))) return false;
+ }
+ return true;
+};
+
+const findFreePort = async (startPort: number): Promise<number> => {
+ for (let port = startPort; port < startPort + MAX_PORT_SCAN_ATTEMPTS; port++) {
+ if (await isPortFree(port)) return port;
+ }
+ throw new Error(`No free port found in range ${startPort}-${startPort + MAX_PORT_SCAN_ATTEMPTS - 1}`);
+};
+
/**
* Resolve the Next.js dev port.
- * Priority: -p CLI flag > PORT env var > 3010.
+ * Priority: -p CLI flag > PORT env var > first free port from 3010.
+ * An explicitly requested port is used verbatim so conflicts fail loudly.
*/
-const resolveNextPort = (): number => {
+const resolveNextPort = async (): Promise<number> => {
const pIndex = process.argv.indexOf('-p');
if (pIndex !== -1 && process.argv[pIndex + 1]) {
return Number(process.argv[pIndex + 1]);
}
if (process.env.PORT) return Number(process.env.PORT);
- return 3010;
+ return findFreePort(3010);
+};
+
+/**
+ * Resolve the port for the Vite dev server this orchestrator spawns and expose
+ * it to children via env: the mode-specific listen var consumed by
+ * vite.config.ts, plus VITE_DEV_PORT — the single contract the Next side reads
+ * to locate the Vite dev server (no fs port file involved).
+ */
+const resolveVitePortEnv = async (): Promise<number> => {
+ const isMobile = process.env.MOBILE === 'true';
+ const envName = isMobile ? 'MOBILE_SPA_PORT' : 'SPA_PORT';
+ const explicit = Number(process.env[envName]);
+ const port = explicit || (await findFreePort(isMobile ? 3012 : 9876));
+
+ process.env[envName] = String(port);
+ process.env.VITE_DEV_PORT = String(port);
+
+ return port;
};
const NEXT_READY_TIMEOUT_MS = 180_000;
@@ -238,8 +291,11 @@ const watchChildExit = (child: ChildProcess, name: 'next' | 'vite') => {
const main = async () => {
loadEnv();
- nextPort = resolveNextPort();
+ nextPort = await resolveNextPort();
+ process.env.PORT = String(nextPort);
nextRootUrl = `http://${NEXT_HOST}:${nextPort}/`;
+ const vitePort = await resolveVitePortEnv();
+ console.log(`🔌 dev ports — next: ${nextPort}, vite: ${vitePort}`);
const forwardedSignals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGHUP'];
for (const sig of forwardedSignals) {
@@ -288,6 +344,9 @@ const isMainModule = () => {
export const __testing = {
createPackageScriptProcessConfig,
createDevProcessHandle,
+ findFreePort,
+ resolveNextPort,
+ resolveVitePortEnv,
sendSignalToDevProcess,
};
diff --git a/src/server/spaHtml.ts b/src/server/spaHtml.ts
index 0735c872282..3cb290df2f5 100644
--- a/src/server/spaHtml.ts
+++ b/src/server/spaHtml.ts
@@ -2,12 +2,18 @@ import { analyticsEnv } from '@/envs/analytics';
import { serializeForHtml } from '@/server/utils/serializeForHtml';
import { type AnalyticsConfig } from '@/types/spaServerConfig';
-export const VITE_DEV_ORIGIN = 'http://localhost:9876';
+// VITE_DEV_PORT is injected by scripts/devStartupSequence.mts with the actual
+// port of the Vite dev server it spawned; 9876 matches the standalone default.
+export const resolveViteDevOrigin = () =>
+ `http://localhost:${Number(process.env.VITE_DEV_PORT) || 9876}`;
const SERVER_CONFIG_PLACEHOLDER =
/window\.__SERVER_CONFIG__\s*=\s*undefined;\s*\/\*\s*SERVER_CONFIG\s*\*\//;
-async function rewriteViteAssetUrls(html: string, origin = VITE_DEV_ORIGIN): Promise<string> {
+async function rewriteViteAssetUrls(
+ html: string,
+ origin = resolveViteDevOrigin(),
+): Promise<string> {
const { parseHTML } = await import('linkedom');
const { document } = parseHTML(html);
@@ -56,7 +62,7 @@ globalThis.Worker.prototype=O.prototype;
export async function fetchViteDevTemplate(
pathname = '/',
- origin = VITE_DEV_ORIGIN,
+ origin = resolveViteDevOrigin(),
): Promise<string> {
const res = await fetch(`${origin}${pathname}`);
const html = await res.text();
diff --git a/vite.config.ts b/vite.config.ts
index 97f695f006f..00362fd6065 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -305,6 +305,10 @@ export default defineConfig({
: isAuth
? Number(process.env.AUTH_SPA_PORT) || 3013
: Number(process.env.SPA_PORT) || 9876,
+ // The dev orchestrator (scripts/devStartupSequence.mts) pre-resolves a free
+ // port and injects it via env; never silently drift to another port, since
+ // downstream consumers locate this server through that env contract.
+ strictPort: true,
proxy: {
'/api': `http://localhost:${process.env.PORT || 3010}`,
'/oidc': `http://localhost:${process.env.PORT || 3010}`,