diff --git a/server/src/worktree-config.ts b/server/src/worktree-config.ts index 3656b7dc6a..55700a00e4 100644 --- a/server/src/worktree-config.ts +++ b/server/src/worktree-config.ts @@ -440,6 +440,14 @@ export function maybeRepairLegacyWorktreeConfigAndEnvFiles(): { return { repairedConfig, repairedEnv }; } +function isPortPinnedByRuntimeEnv(rawValue: string | null | undefined, selectedPort: number): boolean { + const normalized = nonEmpty(rawValue); + if (!normalized) return false; + const parsedPort = Number(normalized); + if (!Number.isInteger(parsedPort) || parsedPort <= 0) return true; + return parsedPort === selectedPort; +} + export function maybePersistWorktreeRuntimePorts(input: { serverPort: number; databasePort?: number | null; @@ -457,7 +465,7 @@ export function maybePersistWorktreeRuntimePorts(input: { const { config, changed } = applyRuntimePortSelectionToConfig(fileConfig, { serverPort: input.serverPort, databasePort: input.databasePort, - allowServerPortWrite: !nonEmpty(process.env.PORT), + allowServerPortWrite: !isPortPinnedByRuntimeEnv(process.env.PORT, input.serverPort), allowDatabasePortWrite: !nonEmpty(process.env.DATABASE_URL), }); @@ -465,3 +473,4 @@ export function maybePersistWorktreeRuntimePorts(input: { writeConfigFile(context.configPath, config); } } +