Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix graceful-shutdown hang from double-closing the server socket.io already closed
[._.]/ Adam Eivy79af00173199
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f618028724..afc0f16cb4 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -89,6 +89,7 @@## Fixed+- **PortOS self-restart / reconcile no longer hangs at "stopping apps" and leaves the server down** — restarting the PortOS app (Apps → restart, or a reconcile) sends `portos-server` a SIGINT, but the graceful-shutdown handler hung forever, so PM2's default 1600ms `kill_timeout` SIGKILLed the process — and the tree-kill took the in-flight restart orchestration down with it, so the server never came back and had to be restarted by hand. **Root cause:** the handler called `httpServer.close()` *after* `io.close()`, but socket.io's `io.close()` already closes its current `this.httpServer` — and since every `io.attach()` reassigns that reference (`socket.io` index.js:303), with HTTPS enabled it's the loopback mirror, not `:5555`. Calling `close()` a second time on an already-closed server makes Node register the callback as a one-time `'close'` listener for an event that already fired — so it never runs and the `await` blocks until the 10s force-exit timer (which PM2 pre-empted with SIGKILL). The rewritten `shutdown()`: force-drops long-lived SSE/keep-alive sockets with `closeAllConnections()` up front; closes socket.io + **both** HTTP servers idempotently (`ERR_SERVER_NOT_RUNNING` = already-closed = success), each behind a short bounded backstop so a WebSocket-upgraded socket that neither `closeAllConnections()` nor the server's connection tracker can reach can't stall the exit; bounds the DB-pool `close()` the same way (a leaked/`LISTEN` client can't hang it); and `unref()`s the force-exit timer so it can't itself hold the loop open. Graceful shutdown now completes in well under a second with the DB pool closed cleanly, every time (down from a 10s hang that ended in SIGKILL). As a backstop, `portos-server` also gains an explicit PM2 `kill_timeout: 12000` (just above the app's own 10s force-exit) so even a future stall defers to the app's clean exit instead of an abrupt SIGKILL. (`server/index.js`, `ecosystem.config.cjs`)- **[issue-1922] Music-video federation's bundled track tombstone is now ack-tracked, closing a narrow track-GC strand window** — #1858 bundles a music-video project's linked track record (`linkedTrack`) so a Music-Videos-only peer (no `track` subscription) can resolve it, and a track delete fans the tombstone out the same way. But `computeAckedDeletesFromPayload` (`peerSyncReceive.js`) only looked at `record`/`issues`, never `linkedTrack`, so such a peer could never ack a bundled track delete through any cursor — and the sender's `track`-tombstone GC cohort (`tombstoneGc.js`) only ever waited on peers with a direct `track` subscription, so it was entirely blind to a musicVideoProjects-only peer regardless of the ack fix. Implemented option (a) from the deferred #1858 review: `computeAckedDeletesFromPayload` now folds in a bundled `linkedTrack` tombstone's `deletedAt`, and the `track` GC cutoff additionally folds `musicVideoProject` subscribers into its cohort, reading their confirmed-delivery floor off a new bundle-specific `lastConfirmedTrackBundleAtMs` (stamped only when the bundled track merge actually succeeded — not the generic `lastConfirmedPushedAt`, which advances even when the bundle failed or was stripped for a legacy peer). Local subscription-state addition only; no wire-payload shape change, so no schema-version bump. (#1922)- **[issue-1858] Music-video federation now ships the linked track to a Music-Videos-only subscriber** — a music-video project created the normal way stores a `trackId` with `uploadedAudioFilename: null`, so a peer subscribed to the **Music Videos** category only (not Music/Tracks) received the project and scene clips but no master audio, and its render failed with `Linked track not found` / `AUDIO_MISSING`. Because the receiver's `resolveMasterAudioPath()` looks the track up by id *before* touching any file, shipping the bytes alone wasn't enough — the push now bundles the linked **track record** itself (`linkedTrack`, merged via `mergeTracksFromSync` and gated by the same tombstone/opt-out rules as `linkedCollection`) *and* its `audioFilename` bytes in the music-video asset manifest. Additive optional payload key, so no schema-version bump and older peers ignore it; dedup-by-`music:<filename>` keeps a separately-federated track from double-shipping. A linked-track edit now also fans a push out to every music-video project that links it (so the bundled audio stays fresh on a Music-Videos-only peer), the receiver requires the bundle's id to match the project's `trackId` (no smuggling an unrelated track), and the bundle rides the push hash + schema gate + delivery-pending ack exactly like the existing `linkedCollection`/`manuscriptReview` bundles. (#1858)- **[issue-1845] Client fetch hygiene — effect fetches now abort on cleanup and `window` is read lazily** — `StagePromptModelPicker` fired two effect `fetch`es guarded only by a `cancelled` flag, so rapid `stageName` changes wasted in-flight round-trips; it now passes an `AbortController` `signal` to both and aborts on cleanup. `LocalSetupPanel`'s `/setup/check` fetch had no abort and its `setChecking(false)` `finally` could fire after unmount; it now aborts the prior/in-flight check (so a stale response can't clobber a newer one) and guards every state set behind a `mountedRef`. `VoiceCapture` read `window.SpeechRecognition` at module scope — a `ReferenceError` when the file is imported in an SSR/Node test context — now resolved lazily via a `useState` initializer that only runs in the browser. And `useArmedAction`'s `fire` is wrapped in `useCallback` so memoized children stay stable. (#1845)diff --git a/ecosystem.config.cjs b/ecosystem.config.cjsindex 301582d307..32b77435c1 100644--- a/ecosystem.config.cjs+++ b/ecosystem.config.cjs@@ -100,7 +100,17 @@ module.exports = {// and add `'**/data/**'` (plus `'**/node_modules'`, `'**/logs/**'`,// `'**/.cache/**'`, `'**/portos-stepwise-*/**'`) to `ignore_watch`.watch: false,- max_memory_restart: SERVER_MAX_MEMORY+ max_memory_restart: SERVER_MAX_MEMORY,+ // PM2's default kill_timeout (1600ms) is shorter than the server's own+ // GRACEFUL_SHUTDOWN_TIMEOUT_MS (10s) force-exit in server/index.js, so if+ // shutdown ever stalls, PM2 would SIGKILL the process before its graceful+ // handler (or its own force-exit) could run — losing the clean DB-pool close+ // and, when the killed process is the one orchestrating a self-restart,+ // leaving the app down. Give PM2 a ceiling just above the app's internal+ // force-exit so the app always controls its own exit. (The graceful path now+ // completes in ~1s — the double-close hang it used to stall on is fixed in+ // server/index.js's shutdown() — so this ceiling is a backstop, not the norm.)+ kill_timeout: 12000// NOTE: do NOT set `treekill: false` here to protect long media jobs from// restart-SIGINT. Tried 2026-06-14: pm2 then fails to reap the old node// process on restart, so it lingers holding :5555 and the new instancediff --git a/server/index.js b/server/index.jsindex e042797796..ba537a9054 100644--- a/server/index.js+++ b/server/index.js@@ -1056,13 +1056,40 @@ ensureSelf()process.exit(1);});-const closeServer = (server, label) => new Promise((resolve) => {- if (!server) return resolve();- server.close((err) => {- if (err) console.error(`⚠️ Error closing ${label}: ${err.message}`);- else console.log(`✅ ${label} closed`);+// Run an async close but resolve anyway after `ms` — so a close that never+// settles (e.g. a WebSocket-upgraded socket the server no longer tracks, or a+// leaked DB client) can't hang shutdown; process.exit() reclaims the resources at+// the OS level. `run(finish)` receives a settle-once callback: finish() /+// finish(successMsg) / finish(errMsg, true). The backstop is .unref()'d so it+// never keeps the event loop alive on its own.+const withGrace = (label, ms, run) => new Promise((resolve) => {+ let settled = false;+ const finish = (msg, isErr) => {+ if (settled) return;+ settled = true;+ if (msg) (isErr ? console.error : console.log)(msg);resolve();+ };+ run(finish);+ setTimeout(() => finish(`⚠️ ${label} close exceeded ${ms}ms — proceeding`, true), ms).unref?.();+});++// graceMs is deliberately short: closeAllConnections() force-drops every+// connection, so there is no graceful drain left to wait for — the only thing that+// can outlast it is a WebSocket-upgraded socket the server no longer tracks (and+// io.close()'s engine.close() already tore those down protocol-side; the OS reaps+// the TCP remnant on process.exit). So don't tax every restart waiting on it.+// ERR_SERVER_NOT_RUNNING means it was already closed (io.close() closes whichever+// server is its current this.httpServer) — success for us, not a failure.+const closeServer = (server, label, graceMs = 250) => withGrace(label, graceMs, (finish) => {+ if (!server) return finish();+ server.close((err) => {+ if (err && err.code !== 'ERR_SERVER_NOT_RUNNING') finish(`⚠️ Error closing ${label}: ${err.message}`, true);+ else finish(`✅ ${label} closed`);});+ // Order matters: close() above stops accepting NEW connections; NOW force-drop+ // the existing long-lived ones (SSE + keep-alive). (Node 18.2+.)+ server.closeAllConnections?.();});// Hard ceiling on graceful shutdown: if Socket.IO/HTTP don't close within this@@ -1089,21 +1116,40 @@ const shutdown = async (signal) => {console.error('⚠️ Graceful shutdown timed out, forcing exit');process.exit(1);}, GRACEFUL_SHUTDOWN_TIMEOUT_MS);+ // Don't let the safety timer itself keep the event loop alive — if every+ // other handle has closed we should exit immediately, not wait out the timer.+ forceExitTimer.unref?.();- await new Promise((resolve) => {- io.close((err) => {- if (err) console.error(`⚠️ Error closing Socket.IO: ${err.message}`);- else console.log('✅ Socket.IO server closed');- resolve();- });- });- await closeServer(httpServer, 'HTTP server');- await closeServer(localHttpServer, 'Local HTTP server');+ // Drop existing long-lived sockets (SSE + keep-alive) up front so the closes+ // below don't wait on connections that never end on their own.+ try { httpServer.closeAllConnections?.(); } catch (e) { console.error(`⚠️ closeAllConnections(http): ${e.message}`); }+ try { localHttpServer?.closeAllConnections?.(); } catch (e) { console.error(`⚠️ closeAllConnections(mirror): ${e.message}`); }++ // socket.io's io.close() closes engine.io AND its current this.httpServer — and+ // every io.attach() reassigns this.httpServer (socket.io index.js:303), so with+ // HTTPS on (io.attach(localHttpServer) at boot) io.close() closes the *mirror*,+ // not the primary :5555 server. The historical bug was calling close() a second+ // time on that already-closed server: Node registers the callback as a one-time+ // 'close' listener for an event that already fired, so it never runs and shutdown+ // hangs forever — the real cause of the reconcile "stopping apps" hang.+ await withGrace('Socket.IO', 3000, (finish) =>+ io.close((err) => finish(err ? `⚠️ Error closing Socket.IO: ${err.message}` : '✅ Socket.IO closed', !!err)));+ // Close BOTH servers explicitly. Whichever one io.close() already closed resolves+ // immediately (ERR_SERVER_NOT_RUNNING → treated as success by closeServer), and+ // the bounded backstop in closeServer guarantees neither can hang shutdown even+ // if a future socket.io version changes which server it owns.+ await Promise.all([+ closeServer(httpServer, 'HTTP server'),+ closeServer(localHttpServer, 'Local HTTP mirror')+ ]);const { close } = await import('./lib/db.js');if (typeof close === 'function') {- await close();- console.log('✅ DB pool closed');+ // Bound the DB pool close: pool.end() waits for every checked-out client to+ // be released, so one hung/leaked connection (e.g. a LISTEN channel) would+ // otherwise stall shutdown until the force-exit timer.+ await withGrace('DB pool', 3000, (finish) =>+ close().then(() => finish('✅ DB pool closed'), (err) => finish(`⚠️ DB pool close failed: ${err.message}`, true)));} else {console.warn('ℹ️ DB pool close not available; skipping DB shutdown');}