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

refactor([issue-1343]): migrate autoRunner/volumeBeatsRunner/storyBuilderRunner onto createSseRunner

[._.]/ Adam Eivyd0d498de23e6
diff --git a/server/lib/sseUtils.js b/server/lib/sseUtils.js
index 77dfd3e677..6dcfde87c5 100644
--- a/server/lib/sseUtils.js
+++ b/server/lib/sseUtils.js
@@ -97,13 +97,25 @@ export const closeJobAfterDelay = (jobs, jobId, delay = SSE_CLEANUP_DELAY_MS, ex
// The caller supplies only the per-run `work({ runId, signal, record, broadcast })`
// async function — it owns its own `start`/`complete`/`canceled` frames and any
// seeding; the factory owns the `error` frame, `finished` flag, and cleanup.
+// (A caller whose error frame carries extra fields — e.g. `stepId`/`op`, or a
+// status side-effect like the auto-runner's `updateIssue('needs-review')` — keeps
+// its own try/catch inside `work` and swallows, so the factory's generic catch is
+// only the safety net for an unexpected throw.)
//
// `logLabel` is interpolated into the failure log (`❌ <logLabel> failed — …`).
//
+// `start(key, work, { sig, meta })` supports OPTIONAL signature-based coalescing
+// for callers (e.g. storyBuilderRunner) that key a single map slot to work whose
+// identity depends on more than the key. When `sig` is passed, a second kickoff
+// while a run is in flight coalesces only if the signatures match; a DIFFERENT
+// signature returns `{ alreadyRunning: true, conflict: true, ...meta }` (the live
+// run's `meta`, e.g. `{ op }`) so the caller can refuse to bind onto unrelated
+// work. Omit `sig` (the default) and any in-flight run coalesces unconditionally.
+//
// Returns `{ runs, isActive, attachClient, cancel, start }`. `runs` is exposed
// so a module can re-export it as `__testing.runs`.
export function createSseRunner({ logLabel = 'sse run' } = {}) {
- // runs: Map<key, { runId, clients[], lastPayload, cancelRequested, finished, cleanupTimer, startedAt, abort }>
+ // runs: Map<key, { runId, clients[], lastPayload, cancelRequested, finished, cleanupTimer, startedAt, abort, sig, meta }>
// A finished run lingers in the map for SSE_CLEANUP_DELAY_MS so late-attaching
// clients can replay its terminal frame — but `finished` lets `isActive` and
// the restart guard treat it as done, so an immediate re-run isn't swallowed.
@@ -136,10 +148,18 @@ export function createSseRunner({ logLabel = 'sse run' } = {}) {
};
// Kick off a run for `key`. Re-calling while a run is in flight resolves to the
- // existing runId (no second coordinator). `work` runs inside the IIFE below.
- const start = (key, work) => {
+ // existing runId (no second coordinator) — unless `sig` is passed and differs
+ // from the in-flight run's, in which case it reports a `conflict` instead of
+ // coalescing (see the factory doc above). `work` runs inside the IIFE below.
+ const start = (key, work, { sig = null, meta = null } = {}) => {
const existing = runs.get(key);
if (existing && !existing.finished) {
+ // A different signature means different work — refuse to coalesce so the
+ // caller doesn't bind onto an unrelated in-flight run; surface the live
+ // run's meta (e.g. its `op`) for the conflict report.
+ if (sig !== null && existing.sig !== sig) {
+ return { runId: existing.runId, alreadyRunning: true, conflict: true, ...(existing.meta || {}) };
+ }
return { runId: existing.runId, alreadyRunning: true };
}
if (existing) {
@@ -159,6 +179,8 @@ export function createSseRunner({ logLabel = 'sse run' } = {}) {
cleanupTimer: null,
startedAt: new Date().toISOString(),
abort,
+ sig,
+ meta,
};
runs.set(key, record);
diff --git a/server/lib/sseUtils.test.js b/server/lib/sseUtils.test.js
index be9b51b2d5..14d12c31eb 100644
--- a/server/lib/sseUtils.test.js
+++ b/server/lib/sseUtils.test.js
@@ -218,6 +218,34 @@ describe('createSseRunner', () => {
expect(work2).not.toHaveBeenCalled();
});
+ it('coalesces a same-signature second start but reports a conflict (+ meta) for a different one', () => {
+ const runner = createSseRunner({ logLabel: 'test' });
+ const first = runner.start('k1', () => pending(), { sig: 'a', meta: { op: 'generate' } });
+
+ // Same signature → safe re-attach onto the in-flight run.
+ const same = runner.start('k1', () => pending(), { sig: 'a', meta: { op: 'generate' } });
+ expect(same.runId).toBe(first.runId);
+ expect(same.alreadyRunning).toBe(true);
+ expect(same.conflict).toBeUndefined();
+
+ // Different signature → different work; refuse to coalesce and surface the
+ // live run's meta (e.g. its op) so the caller won't bind onto it.
+ const other = runner.start('k1', () => pending(), { sig: 'b', meta: { op: 'refine' } });
+ expect(other.runId).toBe(first.runId);
+ expect(other.alreadyRunning).toBe(true);
+ expect(other.conflict).toBe(true);
+ expect(other.op).toBe('generate'); // the in-flight run's op, not the caller's
+ });
+
+ it('without a sig, any in-flight run coalesces (no conflict)', () => {
+ const runner = createSseRunner({ logLabel: 'test' });
+ const first = runner.start('k1', () => pending());
+ const second = runner.start('k1', () => pending(), { meta: { op: 'x' } });
+ expect(second.runId).toBe(first.runId);
+ expect(second.alreadyRunning).toBe(true);
+ expect(second.conflict).toBeUndefined();
+ });
+
it('broadcasts frames to attached clients and caches the last frame for replay', async () => {
const runner = createSseRunner({ logLabel: 'test' });
let release;
diff --git a/server/services/pipeline/autoRunner.js b/server/services/pipeline/autoRunner.js
index c6438ef83d..54fad16941 100644
--- a/server/services/pipeline/autoRunner.js
+++ b/server/services/pipeline/autoRunner.js
@@ -15,32 +15,32 @@
* grace window in lib/sseUtils.js.
*/
-import { randomUUID } from 'crypto';
-import { broadcastSse, attachSseClient, closeJobAfterDelay } from '../../lib/sseUtils.js';
+import { broadcastSse, createSseRunner } from '../../lib/sseUtils.js';
import { generateStage } from './textStages.js';
import { getIssue, updateIssue, isStageReady } from './issues.js';
import { startEpisodeVideoForIssue, ERR_NO_STORYBOARDS } from './episodeVideo.js';
-// runs: Map<issueId, { runId, clients[], lastPayload, cancelRequested, startedAt }>
-const runs = new Map();
+// Shared SSE run-lifecycle: a `runs` map keyed by issueId, plus the
+// coalesce/restart/grace-window/finished/cleanup semantics. This runner keeps
+// its own error handling inside `work` (it must flip the issue to
+// 'needs-review' and emit a matching error frame), so the factory's generic
+// catch is only the safety net.
+const runner = createSseRunner({ logLabel: 'pipeline auto-run' });
export function isAutoRunActive(issueId) {
- return runs.has(issueId);
+ return runner.isActive(issueId);
}
export function attachClient(issueId, res) {
- return attachSseClient(runs, issueId, res);
+ return runner.attachClient(issueId, res);
}
export function cancelAutoRun(issueId) {
- const run = runs.get(issueId);
- if (!run) return false;
- run.cancelRequested = true;
- return true;
+ return runner.cancel(issueId);
}
function broadcast(issueId, payload) {
- const run = runs.get(issueId);
+ const run = runner.runs.get(issueId);
if (!run) return;
broadcastSse(run, payload);
}
@@ -51,21 +51,9 @@ function broadcast(issueId, payload) {
* run is in flight resolves to the existing runId.
*/
export async function startAutoRunTextStages(issueId, options = {}) {
- if (runs.has(issueId)) return { runId: runs.get(issueId).runId, alreadyRunning: true };
- const runId = randomUUID();
- const record = {
- runId,
- clients: [],
- lastPayload: null,
- cancelRequested: false,
- startedAt: new Date().toISOString(),
- };
- runs.set(issueId, record);
-
- // Kick off the coordinator without awaiting. The outer try/catch is the one
- // permitted boundary use of try/catch in this module — without it an LLM
- // rejection would surface as an unhandledRejection on Node ≥15 and kill the
- // process. See ~/.claude skill `nodejs-async-event-listener-unhandled-rejection`.
+ if (runner.isActive(issueId)) {
+ return { runId: runner.runs.get(issueId).runId, alreadyRunning: true };
+ }
// Which script stages to adapt from prose. Defaults to both (manual auto-run
// from the UI); callers targeting a single format (e.g. Series Autopilot on a
// comic-only series) pass `scripts: ['comicScript']` to skip the off-target
@@ -75,10 +63,13 @@ export async function startAutoRunTextStages(issueId, options = {}) {
? VALID_SCRIPTS.filter((s) => options.scripts.includes(s))
: VALID_SCRIPTS;
- (async () => {
+ return runner.start(issueId, async ({ runId, record }) => {
await updateIssue(issueId, { status: 'running' }).catch(() => null);
broadcast(issueId, { type: 'start', runId, stages: ['idea', 'prose', ...scripts] });
+ // Own the error frame + status flip here (and swallow) so the factory's
+ // generic catch doesn't double-emit; without it an LLM rejection would
+ // surface as an unhandledRejection on Node ≥15 and kill the process.
try {
// Stage 1: idea — skip if already ready/edited and not force-rerun
if (!record.cancelRequested) {
@@ -166,14 +157,11 @@ export async function startAutoRunTextStages(issueId, options = {}) {
console.error(`❌ Pipeline auto-run failed — issue=${issueId.slice(0, 8)} ${message}`);
await updateIssue(issueId, { status: 'needs-review' }).catch(() => null);
broadcast(issueId, { type: 'error', runId, error: message, failedAt: new Date().toISOString() });
- } finally {
- // Hold the SSE list open briefly so late-attaching clients still see
- // the terminal frame via replay (matches mediaJobQueue's behavior).
- closeJobAfterDelay(runs, issueId);
+ // Swallow: the error frame + status flip above are the terminal handling.
+ // The factory's finally marks the run finished and schedules the replay
+ // grace-window cleanup.
}
- })();
-
- return { runId, alreadyRunning: false };
+ });
}
async function runStageIfNeeded(issueId, stageId, options) {
@@ -220,4 +208,4 @@ export async function recoverStuckAutoRuns() {
}
// Export internals for tests.
-export const __testing = { runs };
+export const __testing = { runs: runner.runs };
diff --git a/server/services/pipeline/autoRunner.test.js b/server/services/pipeline/autoRunner.test.js
index 2946f79488..1345e232a3 100644
--- a/server/services/pipeline/autoRunner.test.js
+++ b/server/services/pipeline/autoRunner.test.js
@@ -217,8 +217,9 @@ describe('pipeline auto-runner', () => {
await waitFor(() => generated.length >= 1);
autoRunner.cancelAutoRun(issue.id);
// Coordinator must broadcast a terminal frame (canceled or complete)
- // before we assert. `isAutoRunActive` stays true for the SSE cleanup
- // grace window (5s), so we read the broadcast frame directly.
+ // before we assert. The finished run lingers in `runs` for the SSE replay
+ // grace window (so its `lastPayload` is still readable) even though
+ // `isAutoRunActive` already reports false — so we read the frame directly.
await waitFor(() => {
const run = autoRunner.__testing.runs.get(issue.id);
const t = run?.lastPayload?.type;
diff --git a/server/services/pipeline/volumeBeatsRunner.js b/server/services/pipeline/volumeBeatsRunner.js
index c784fa80ee..b9bcf7a6df 100644
--- a/server/services/pipeline/volumeBeatsRunner.js
+++ b/server/services/pipeline/volumeBeatsRunner.js
@@ -26,36 +26,34 @@
* { type: 'error', runId, error, failedAt }
*/
-import { randomUUID } from 'crypto';
-import { broadcastSse, attachSseClient, closeJobAfterDelay } from '../../lib/sseUtils.js';
+import { broadcastSse, createSseRunner } from '../../lib/sseUtils.js';
import { generateStage } from './textStages.js';
import { listIssues, isStageReady } from './issues.js';
import { getSeries } from './series.js';
import { compareIssuesByPosition } from './arcPlanner.js';
import { getSeason } from './seasons.js';
-// runs: Map<seasonId, { runId, clients[], lastPayload, cancelRequested, startedAt }>
-const runs = new Map();
+// Shared SSE run-lifecycle keyed by seasonId. This runner keeps its own error
+// frame + per-issue catch inside `work`, so the factory's generic catch is only
+// the safety net.
+const runner = createSseRunner({ logLabel: 'pipeline volume-beats' });
export const VOLUME_BEATS_MODES = Object.freeze(['skip-existing', 'regenerate-all']);
export function isVolumeBeatsRunActive(seasonId) {
- return runs.has(seasonId);
+ return runner.isActive(seasonId);
}
export function attachClient(seasonId, res) {
- return attachSseClient(runs, seasonId, res);
+ return runner.attachClient(seasonId, res);
}
export function cancelVolumeBeatsRun(seasonId) {
- const run = runs.get(seasonId);
- if (!run) return false;
- run.cancelRequested = true;
- return true;
+ return runner.cancel(seasonId);
}
function broadcast(seasonId, payload) {
- const run = runs.get(seasonId);
+ const run = runner.runs.get(seasonId);
if (!run) return;
broadcastSse(run, payload);
}
@@ -65,8 +63,8 @@ function broadcast(seasonId, payload) {
* progress lands via SSE. Idempotent when a run is in flight for this volume.
*/
export async function startVolumeBeatsRun(seriesId, seasonId, options = {}) {
- if (runs.has(seasonId)) {
- return { runId: runs.get(seasonId).runId, alreadyRunning: true };
+ if (runner.isActive(seasonId)) {
+ return { runId: runner.runs.get(seasonId).runId, alreadyRunning: true };
}
// Validate scope up front — bad ids should 404 before we kick off, not
// surface as a deferred SSE error frame.
@@ -74,19 +72,11 @@ export async function startVolumeBeatsRun(seriesId, seasonId, options = {}) {
await getSeason(seriesId, seasonId);
const mode = VOLUME_BEATS_MODES.includes(options.mode) ? options.mode : 'skip-existing';
- const runId = randomUUID();
- const record = {
- runId,
- clients: [],
- lastPayload: null,
- cancelRequested: false,
- startedAt: new Date().toISOString(),
- };
- runs.set(seasonId, record);
-
- (async () => {
- // Outer try/catch is the one permitted boundary — without it an LLM
- // rejection would surface as an unhandledRejection and kill the process.
+
+ return runner.start(seasonId, async ({ runId, record }) => {
+ // Own the error frame here (and swallow) so the factory's generic catch
+ // doesn't double-emit; without it an LLM rejection would surface as an
+ // unhandledRejection and kill the process.
try {
const all = await listIssues({ seriesId });
const volumeIssues = all
@@ -178,13 +168,11 @@ export async function startVolumeBeatsRun(seriesId, seasonId, options = {}) {
const message = (err?.message || String(err)).slice(0, 1000);
console.error(`❌ Pipeline volume-beats failed — season=${seasonId.slice(0, 8)} ${message}`);
broadcast(seasonId, { type: 'error', runId, error: message, failedAt: new Date().toISOString() });
- } finally {
- closeJobAfterDelay(runs, seasonId);
+ // Swallow: the error frame above is the terminal handling. The factory's
+ // finally marks the run finished and schedules the replay-window cleanup.
}
- })();
-
- return { runId, alreadyRunning: false };
+ });
}
// Export internals for tests.
-export const __testing = { runs };
+export const __testing = { runs: runner.runs };
diff --git a/server/services/storyBuilderRunner.js b/server/services/storyBuilderRunner.js
index 826aebdc19..b764f0fab5 100644
--- a/server/services/storyBuilderRunner.js
+++ b/server/services/storyBuilderRunner.js
@@ -23,25 +23,28 @@
* the frame (matches the pipeline auto-run's refetch-on-terminal pattern).
*/
-import { randomUUID } from 'crypto';
-import { broadcastSse, attachSseClient, closeJobAfterDelay } from '../lib/sseUtils.js';
+import { broadcastSse, createSseRunner } from '../lib/sseUtils.js';
import { generateStep, refineStep } from './storyBuilder.js';
-// runs: Map<runKey, { runId, clients[], lastPayload, startedAt, stepId, op }>
-const runs = new Map();
+// Shared SSE run-lifecycle keyed by `${sessionId}::${stepId}`. This runner uses
+// the factory's OPTIONAL signature-based coalescing (a `refine` of a different
+// target is different work and must not bind onto an in-flight `generate`), and
+// keeps its own error frame inside `work` (it carries `stepId`/`op`), so the
+// factory's generic catch is only the safety net.
+const runner = createSseRunner({ logLabel: 'story-builder' });
const runKey = (sessionId, stepId) => `${sessionId}::${stepId}`;
export function isStepRunActive(sessionId, stepId) {
- return runs.has(runKey(sessionId, stepId));
+ return runner.isActive(runKey(sessionId, stepId));
}
export function attachClient(sessionId, stepId, res) {
- return attachSseClient(runs, runKey(sessionId, stepId), res);
+ return runner.attachClient(runKey(sessionId, stepId), res);
}
function broadcast(key, payload) {
- const run = runs.get(key);
+ const run = runner.runs.get(key);
if (!run) return;
broadcastSse(run, payload);
}
@@ -67,40 +70,14 @@ const requestSig = (op, { entryId, feedback, fromDownstream } = {}) =>
export function startStepRun(sessionId, stepId, { op = 'generate', ...options } = {}) {
const key = runKey(sessionId, stepId);
const sig = requestSig(op, options);
- // Coalesce a second click onto the in-flight run only when it's doing the SAME
- // work (matching signature) — a reload mid-run re-attaching to its own request.
- // A different signature (different op, or a refine of a different target/note)
- // would do different work, so we refuse to coalesce and report `conflict` so
- // the client doesn't bind its success handler to the running request's frame.
- //
- // Only a still-WORKING run blocks. A completed run lingers in `runs` for the
- // SSE replay grace window (closeJobAfterDelay); coalescing onto it would re-run
- // no work and replay the stale terminal frame as a false success. A fresh
- // kickoff in that window starts a new run that replaces the lingering record.
- const inFlight = runs.get(key);
- if (inFlight && !inFlight.done) {
- if (inFlight.sig === sig) return { runId: inFlight.runId, alreadyRunning: true };
- return { runId: inFlight.runId, alreadyRunning: true, conflict: true, op: inFlight.op };
- }
-
- const runId = randomUUID();
- const record = {
- runId,
- clients: [],
- lastPayload: null,
- startedAt: new Date().toISOString(),
- stepId,
- op,
- sig,
- done: false,
- };
- runs.set(key, record);
-
- // Fire-and-forget the work. The outer try/catch is the permitted boundary
- // use of try/catch in this module — without it an LLM rejection would surface
- // as an unhandledRejection and kill the process (the POST has already
- // returned, so there's no `next(err)` to bubble to).
- (async () => {
+ // The factory coalesces a second click onto the in-flight run only when the
+ // signatures match (a reload mid-run re-attaching to its own request). A
+ // different signature (different op, or a refine of a different target/note)
+ // does different work, so it reports `conflict` + the live run's `op` (via
+ // `meta`) instead — the client then refuses to bind its success handler to the
+ // running request's frame. A finished run lingering in the replay grace window
+ // does NOT block: the factory starts a fresh run that replaces it.
+ return runner.start(key, async ({ runId }) => {
broadcast(key, { type: 'start', runId, stepId, op });
// Best-effort phase emitter handed to the conductor; an onProgress throw
// must never break the run.
@@ -112,6 +89,8 @@ export function startStepRun(sessionId, stepId, { op = 'generate', ...options }
}
};
+ // Own the error frame here (and swallow) so the factory's generic catch
+ // doesn't double-emit; this frame carries `stepId`/`op` the client reads.
try {
const result = op === 'refine'
? await refineStep(sessionId, stepId, { ...options, onProgress })
@@ -134,20 +113,9 @@ export function startStepRun(sessionId, stepId, { op = 'generate', ...options }
const message = (err?.message || String(err)).slice(0, 1000);
console.error(`❌ story-builder ${op} failed — session=${sessionId.slice(0, 8)} step=${stepId} ${message}`);
broadcast(key, { type: 'error', runId, stepId, op, error: message, failedAt: new Date().toISOString() });
- } finally {
- // Mark terminal so a kickoff during the grace window starts a fresh run
- // instead of coalescing onto this finished one.
- record.done = true;
- // Hold the SSE list open briefly so a client that attached just after the
- // terminal frame still replays it (matches the auto-runner / mediaJobQueue).
- // Pass this record as `expectedJob` so a replacement run that took the key
- // during the window isn't evicted by this timer.
- closeJobAfterDelay(runs, key, undefined, record);
}
- })();
-
- return { runId, alreadyRunning: false };
+ }, { sig, meta: { op } });
}
// Export internals for tests.
-export const __testing = { runs, runKey };
+export const __testing = { runs: runner.runs, runKey };