diff --git a/src/server/apps.ts b/src/server/apps.ts index 4bc7a9d..1224134 100644 --- a/src/server/apps.ts +++ b/src/server/apps.ts @@ -96,7 +96,8 @@ export function readLogs(appName: string, date?: string, tail?: number): string[ return lines } -export function initApps() { +export async function initApps() { + await killStaleProcesses() initPortPool() setupShutdownHandlers() rotateLogs() @@ -466,6 +467,25 @@ function handleHealthCheckFailure(app: App) { } } +async function killStaleProcesses() { + const result = Bun.spawnSync(['lsof', '-ti', `:${MIN_PORT - 1}-${MAX_PORT}`]) + const output = result.stdout.toString().trim() + if (!output) return + + const pids = output.split('\n').map(Number).filter(pid => pid && pid !== process.pid) + if (pids.length === 0) return + + hostLog(`Found ${pids.length} stale process(es) on ports ${MIN_PORT - 1}-${MAX_PORT}`) + for (const pid of pids) { + try { + process.kill(pid, 'SIGKILL') + hostLog(`Killed stale process ${pid}`) + } catch { + // Process already gone + } + } +} + function initPortPool() { _availablePorts.length = 0 for (let port = MIN_PORT; port <= MAX_PORT; port++) { diff --git a/src/server/index.tsx b/src/server/index.tsx index 53bb048..248cb78 100644 --- a/src/server/index.tsx +++ b/src/server/index.tsx @@ -53,7 +53,7 @@ app.all('/api/tools/:tool/:path{.+}', async c => { }) }) -initApps() +await initApps() export default { ...app.defaults,