Skip to content

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

fix: sweep expired FableLoom hosted sessions instead of leaking them (#5660)

Adam Eivy8d382bf29f48
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index 50b5061b23..09b1ec3013 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -119,6 +119,7 @@ import { initMortalLoomStore } from './mortalLoomStore.js';
import { initUniverseBuilderCollectionHook } from './universeBuilderCollectionHook.js';
import { initCatalogImageAttachHook } from './catalogImageAttachHook.js';
import { initWritersRoomSceneImageHook } from './writersRoomSceneImageHook.js';
+import { startHostedSessionSweep, stopHostedSessionSweep } from './fableLoom/hostedSession.js';
import { initFableLoomSceneImageHook } from './fableLoomSceneImageHook.js';
import { initFableLoomSceneVideoHook } from './fableLoomSceneVideoHook.js';
import { initMusicVideoSceneImageHook } from './musicVideoSceneImageHook.js';
@@ -359,6 +360,10 @@ const startBackgroundServices = ({ spawnerReady }) => {
// under AGENTS.md's "No cold-bootstrap LLM calls". Off in practice until the
// user sets an idle window (0 = never, the default).
startIdleReaper();
+ // Arm the FableLoom hosted-session sweeper. Timer only — it walks in-memory
+ // QR play sessions and tears down the ones past their TTL, making no AI
+ // provider call, so it is safe under AGENTS.md's "No cold-bootstrap LLM calls".
+ startHostedSessionSweep({ io });
// Initialize brain scheduler for daily digests and weekly reviews
startBrainScheduler();
// Initialize activity-digest scheduler — OFF by default; drafts daily-log
@@ -856,6 +861,9 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>
// -shutdown would `pm2 stop` a model server the user never asked to lose,
// and PortOS is about to stop being the thing that could restart it.
stopIdleReaper();
+ // Same reasoning for the hosted-session sweeper: a tick mid-shutdown would
+ // emit into a namespace we are about to close.
+ stopHostedSessionSweep();
// Diagnostic context for the shutdown trigger. ppid tells us whether the
// signal came from PM2 (parent is the PM2 god process), a TTY (parent is
// the user's shell), or some external orchestrator. pm_* env vars are set
diff --git a/server/services/fableLoom/README.md b/server/services/fableLoom/README.md
index c49c122354..8717335eef 100644
--- a/server/services/fableLoom/README.md
+++ b/server/services/fableLoom/README.md
@@ -14,7 +14,7 @@ intent to a transition and moves them through the graph until an ending.
| `editorialAutopilot.js` | User-triggered bounded editor/reviewer loop: remediate, exercise every bounded branch variation, judge story quality, then complete, pause on residuals/plateau, fail, or cancel cooperatively. |
| `editorialSelfImprove.js` | Opt-in, budget-gated post-mortem for paused/failed editorial-autopilot runs. Sends only content-free counters to a diagnostic stage and queues a deduplicated, approval-gated PortOS CoS task for confident workflow defects. |
| `formats.js` | Scene formats (`prose` / `teleplay`) and the prompt contracts each generative stage renders for them. |
-| `hostedSession.js` | Scoped QR-hosted play session lifecycle, HTTPS readiness preflight, token hashing, live voice gate revalidation, and half-duplex turn taking (#5383). |
+| `hostedSession.js` | Scoped QR-hosted play session lifecycle, HTTPS readiness preflight, token hashing, live voice gate revalidation, half-duplex turn taking (#5383), and the expired-session sweeper armed from bootstrap (#5660). |
| `production.js` | Episodic production orchestration: batch planning, DAG generation, cancellable batch runs, and user-triggered episodic continuity review (#5384). |
| `falVideoAutomation.js` | User-triggered, serialized Playwright automation over the persistent PortOS CDP browser: uploads a scene still + full shot prompt to fal.ai H3 Max, downloads the finished MP4 into shared video history, and attaches it to the originating scene. |
| `store.js` | PostgreSQL/file backend facade (`fableloom_stories`; collectionStore escape hatch for tests). |
diff --git a/server/services/fableLoom/hostedSession.js b/server/services/fableLoom/hostedSession.js
index 2da8428c12..6be70e22ce 100644
--- a/server/services/fableLoom/hostedSession.js
+++ b/server/services/fableLoom/hostedSession.js
@@ -52,6 +52,15 @@ const activeSessions = new Map();
export const DEFAULT_SESSION_TTL_MINUTES = 30;
export const MAX_SESSION_TTL_MINUTES = 180;
+// How often the sweeper walks `activeSessions` looking for expired records.
+// TTLs run 1-180 minutes and a machine hosts at most a handful of sessions at
+// once, so one unref'd interval is cheaper than arming (and having to cancel)
+// a per-session timeout.
+export const HOSTED_SESSION_SWEEP_INTERVAL_MS = 60_000;
+
+/** True once a session record is past its TTL. */
+const isExpired = (session) => new Date(session.expiresAt).getTime() <= Date.now();
+
/** Helper to derive initial playback phase for a node */
export function initialPhaseForNode(node) {
if (!node) return 'ended';
@@ -325,7 +334,7 @@ export function verifyHostedToken(sessionId, token) {
if (!sessionId || !token || typeof token !== 'string') return false;
const session = activeSessions.get(sessionId);
if (!session || session.status !== 'active') return false;
- if (new Date(session.expiresAt).getTime() <= Date.now()) {
+ if (isExpired(session)) {
session.status = 'ended';
return false;
}
@@ -343,7 +352,7 @@ export function getHostedSession(sessionId) {
if (!sessionId) return null;
const session = activeSessions.get(sessionId);
if (!session) return null;
- if (session.status === 'active' && new Date(session.expiresAt).getTime() <= Date.now()) {
+ if (session.status === 'active' && isExpired(session)) {
session.status = 'ended';
}
return sanitizeHostedSession(session);
@@ -351,9 +360,19 @@ export function getHostedSession(sessionId) {
/**
* Internal session record retrieval for socket and service operations.
+ *
+ * Evaluates the TTL, so an expired record reads as absent even when nothing has
+ * swept it yet — that is what stops a host reconnecting into the
+ * `/fableloom-hosted` namespace minutes after its session should have died.
*/
export function _getInternalSession(sessionId) {
- return activeSessions.get(sessionId) || null;
+ const session = activeSessions.get(sessionId);
+ if (!session) return null;
+ if (session.status === 'active' && isExpired(session)) {
+ session.status = 'ended';
+ }
+ if (session.status !== 'active') return null;
+ return session;
}
/**
@@ -688,10 +707,65 @@ export function abortHostedTurn(sessionId, { reason = 'aborted', io } = {}) {
return { ok: true };
}
+let sweepTimer = null;
+let sweepIo = null;
+
+/**
+ * Arm the expired-session sweeper.
+ *
+ * Expiry used to be evaluated only when something happened to look a session up,
+ * and even then it just flipped `status` — so the normal end of a QR play
+ * session (guest closes the tab, host navigates away) left the record, its node
+ * history and its live `AbortController` resident for the process lifetime, and
+ * the room never saw `hosted:session:ended`. The sweep reuses `endHostedSession`
+ * so teardown stays in one place.
+ */
+export function startHostedSessionSweep({ intervalMs = HOSTED_SESSION_SWEEP_INTERVAL_MS, io = null } = {}) {
+ sweepIo = io || sweepIo;
+ if (sweepTimer) return sweepTimer;
+ sweepTimer = setInterval(() => {
+ // Timer callback — outside the request lifecycle, so an uncaught throw here
+ // would take the process down instead of reaching error middleware.
+ try {
+ sweepExpiredHostedSessions();
+ } catch (err) {
+ console.error(`❌ FableLoom hosted-session sweep failed: ${err.message}`);
+ }
+ }, intervalMs);
+ sweepTimer.unref?.();
+ return sweepTimer;
+}
+
+/** Disarm the sweeper (graceful shutdown, tests). */
+export function stopHostedSessionSweep() {
+ if (sweepTimer) clearInterval(sweepTimer);
+ sweepTimer = null;
+ sweepIo = null;
+}
+
+/**
+ * Tear down every expired or already-ended session. Exported so a test (and a
+ * future manual "clean up" action) can run one tick without waiting on wall time.
+ */
+export function sweepExpiredHostedSessions({ io = sweepIo } = {}) {
+ const doomed = [];
+ for (const [id, session] of activeSessions) {
+ if (session.status !== 'active' || isExpired(session)) doomed.push(id);
+ }
+ for (const id of doomed) {
+ endHostedSession(id, { reason: 'expired', io });
+ }
+ if (doomed.length) {
+ console.log(`🧹 Swept ${doomed.length} expired FableLoom hosted session(s)`);
+ }
+ return doomed.length;
+}
+
/**
* Test helper to reset in-memory sessions between test runs.
*/
export function _resetHostedSessions() {
+ stopHostedSessionSweep();
for (const session of activeSessions.values()) {
if (session.activeTurn?.abortController) {
session.activeTurn.abortController.abort('reset');
diff --git a/server/services/fableLoom/hostedSession.test.js b/server/services/fableLoom/hostedSession.test.js
index fd398c2e31..babfb92746 100644
--- a/server/services/fableLoom/hostedSession.test.js
+++ b/server/services/fableLoom/hostedSession.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest';
import {
_getInternalSession,
_resetHostedSessions,
@@ -12,6 +12,8 @@ import {
revalidateLiveConversationGate,
sanitizeHostedSession,
startHostedListening,
+ startHostedSessionSweep,
+ stopHostedSessionSweep,
updateHostedSession,
verifyHostedToken,
} from './hostedSession.js';
@@ -302,4 +304,89 @@ describe('fableLoom hostedSession', () => {
expect(getHostedSession(session.id)).toBeNull();
});
});
+
+ describe('expired-session sweep', () => {
+ // A stub Socket.IO surface that records every namespace emit.
+ const makeIo = () => {
+ const emits = [];
+ return {
+ emits,
+ of: () => ({
+ to: (room) => ({
+ emit: (event, payload) => emits.push({ room, event, payload }),
+ }),
+ }),
+ };
+ };
+
+ // Age a session past its TTL without waiting out 30 real minutes.
+ const expire = (sessionId) => {
+ const internal = _getInternalSession(sessionId);
+ internal.expiresAt = new Date(Date.now() - 1000).toISOString();
+ return internal;
+ };
+
+ afterEach(() => {
+ stopHostedSessionSweep();
+ vi.useRealTimers();
+ });
+
+ it('deletes an expired session on the next sweep tick, aborting its turn and notifying the room', async () => {
+ const io = makeIo();
+ const { session } = await createHostedSession('loom-1', 'ep-1');
+ await startHostedListening(session.id);
+ const internal = expire(session.id);
+ const { signal } = internal.activeTurn.abortController;
+ expect(signal.aborted).toBe(false);
+
+ vi.useFakeTimers();
+ startHostedSessionSweep({ intervalMs: 60_000, io });
+ // Arming alone tears nothing down; the first tick does.
+ expect(io.emits).toHaveLength(0);
+ vi.advanceTimersByTime(60_000);
+
+ expect(signal.aborted).toBe(true);
+ expect(getHostedSession(session.id)).toBeNull();
+ expect(io.emits).toContainEqual({
+ room: `session:${session.id}`,
+ event: 'hosted:session:ended',
+ payload: { sessionId: session.id, reason: 'expired' },
+ });
+ });
+
+ it('leaves an unexpired session untouched', async () => {
+ const io = makeIo();
+ const { session } = await createHostedSession('loom-1', 'ep-1');
+
+ vi.useFakeTimers();
+ startHostedSessionSweep({ intervalMs: 60_000, io });
+ vi.advanceTimersByTime(180_000);
+
+ expect(getHostedSession(session.id)?.status).toBe('active');
+ expect(io.emits).toHaveLength(0);
+ });
+
+ it('rejects a late reconnect: _getInternalSession returns null once the TTL has passed', async () => {
+ const { session, token } = await createHostedSession('loom-1', 'ep-1');
+ expect(_getInternalSession(session.id)).not.toBeNull();
+
+ expire(session.id);
+
+ // What the /fableloom-hosted handshake gates on, for host and audience alike.
+ expect(_getInternalSession(session.id)).toBeNull();
+ expect(verifyHostedToken(session.id, token)).toBe(false);
+ });
+
+ it('arms an unref\'d timer once and clears it on stop', () => {
+ vi.useFakeTimers();
+ const first = startHostedSessionSweep({ intervalMs: 60_000 });
+ expect(first.unref).toBeTypeOf('function');
+ // Re-arming is a no-op rather than a second leaked interval.
+ expect(startHostedSessionSweep({ intervalMs: 60_000 })).toBe(first);
+ expect(vi.getTimerCount()).toBe(1);
+
+ stopHostedSessionSweep();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+ });
});
diff --git a/server/services/fableLoom/index.js b/server/services/fableLoom/index.js
index 4abebbdac6..aa496053aa 100644
--- a/server/services/fableLoom/index.js
+++ b/server/services/fableLoom/index.js
@@ -87,6 +87,7 @@ export {
} from './visualConditioning.js';
export {
DEFAULT_SESSION_TTL_MINUTES,
+ HOSTED_SESSION_SWEEP_INTERVAL_MS,
MAX_SESSION_TTL_MINUTES,
_getInternalSession,
_resetHostedSessions,
@@ -100,6 +101,9 @@ export {
revalidateLiveConversationGate,
sanitizeHostedSession,
startHostedListening,
+ startHostedSessionSweep,
+ stopHostedSessionSweep,
+ sweepExpiredHostedSessions,
updateHostedSession,
verifyHostedToken,
} from './hostedSession.js';