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([story-builder-sse-progress]): don't coalesce a new run onto a completed one in the SSE grace window

[._.]/ Adam Eivy3876bdc2b196
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsx
index 5fa8668eb3..cb7d751f5e 100644
--- a/client/src/pages/StoryBuilder.jsx
+++ b/client/src/pages/StoryBuilder.jsx
@@ -392,10 +392,16 @@ function useStepStream(sessionId, stepId) {
const [phase, setPhase] = useState('');
const [op, setOp] = useState(null);
const handlersRef = useRef(null);
+ // The runId we're waiting on. useSseProgress only resets its `latest` a render
+ // AFTER `enabled` flips true, so on the subscribe render `latest` still holds
+ // the PREVIOUS run's terminal frame. Gating the terminal branches on a frame's
+ // runId stops that stale frame from firing the new run's onComplete instantly.
+ const runIdRef = useRef(null);
const { latest, closed } = useStoryStepProgress(sessionId, stepId, { enabled: active });
const settle = useCallback(() => {
setActive(false); setPhase(''); setOp(null);
+ runIdRef.current = null;
const h = handlersRef.current; handlersRef.current = null;
return h;
}, []);
@@ -408,9 +414,12 @@ function useStepStream(sessionId, stepId) {
// (server pruned a fast run, or the connection dropped) so the button unsticks.
useEffect(() => {
if (!active) return;
- if (latest && typeof latest.label === 'string' && latest.label) setPhase(latest.label);
- if (latest?.type === 'complete') settle()?.onComplete?.(latest);
- else if (latest?.type === 'error') settle()?.onError?.(new Error(latest.error || 'Generation failed'));
+ // Ignore frames belonging to a previous run (stale `latest` not yet reset by
+ // the SSE hook). closed is reset on every (re)subscribe, so it never lingers.
+ const mine = latest && latest.runId === runIdRef.current;
+ if (mine && typeof latest.label === 'string' && latest.label) setPhase(latest.label);
+ if (mine && latest.type === 'complete') settle()?.onComplete?.(latest);
+ else if (mine && latest.type === 'error') settle()?.onError?.(new Error(latest.error || 'Generation failed'));
else if (closed) settle()?.onError?.(new Error('Lost connection to the generation stream'));
}, [latest, closed, active, settle]);
@@ -431,6 +440,7 @@ function useStepStream(sessionId, stepId) {
return;
}
handlersRef.current = handlers;
+ runIdRef.current = res.runId; // only frames from this run drive our handlers
setActive(true); // enable the SSE subscription now that the run is registered
}, [starting, active]);
diff --git a/server/lib/sseUtils.js b/server/lib/sseUtils.js
index 1afccf2da8..a04ae436e7 100644
--- a/server/lib/sseUtils.js
+++ b/server/lib/sseUtils.js
@@ -51,9 +51,23 @@ export const attachSseClient = (jobs, jobId, res) => {
// Drains any late-connecting EventSource clients then removes the job
// from the per-provider job map. Both providers do this on child exit.
-export const closeJobAfterDelay = (jobs, jobId, delay = SSE_CLEANUP_DELAY_MS) => {
+//
+// `expectedJob` (optional) guards against a fresh run replacing this one under
+// the same key during the grace window: if the map no longer holds the job this
+// timer was scheduled for, end only the original job's lingering clients and
+// leave the replacement (and the map entry) untouched. Without it, restarting a
+// run for the same key inside SSE_CLEANUP_DELAY_MS would have the old timer
+// evict the new run and close its clients. Callers that never restart within
+// the window can omit it for the original delete-by-key behavior.
+export const closeJobAfterDelay = (jobs, jobId, delay = SSE_CLEANUP_DELAY_MS, expectedJob = null) => {
setTimeout(() => {
const job = jobs.get(jobId);
+ if (expectedJob && job !== expectedJob) {
+ // A newer run took this key — drain the stale job's clients but don't
+ // delete the live entry.
+ for (const c of expectedJob.clients || []) c.end();
+ return;
+ }
if (job) for (const c of job.clients) c.end();
jobs.delete(jobId);
}, delay);
diff --git a/server/lib/sseUtils.test.js b/server/lib/sseUtils.test.js
index 979930dac3..27f7970e4c 100644
--- a/server/lib/sseUtils.test.js
+++ b/server/lib/sseUtils.test.js
@@ -154,4 +154,32 @@ describe('closeJobAfterDelay', () => {
closeJobAfterDelay(jobs, 'missing', 10);
expect(() => vi.advanceTimersByTime(10)).not.toThrow();
});
+
+ it('leaves a replacement job untouched when expectedJob no longer holds the key', () => {
+ const jobs = new Map();
+ const stale = { clients: [makeRes()] };
+ const fresh = { clients: [makeRes()] };
+ jobs.set('j1', stale);
+
+ // Schedule cleanup for `stale`, then a new run replaces it under the same key.
+ closeJobAfterDelay(jobs, 'j1', 100, stale);
+ jobs.set('j1', fresh);
+
+ vi.advanceTimersByTime(100);
+ // The stale run's lingering client is drained, but the live entry survives.
+ expect(stale.clients[0].end).toHaveBeenCalled();
+ expect(fresh.clients[0].end).not.toHaveBeenCalled();
+ expect(jobs.get('j1')).toBe(fresh);
+ });
+
+ it('deletes the job when expectedJob still holds the key', () => {
+ const jobs = new Map();
+ const job = { clients: [makeRes()] };
+ jobs.set('j1', job);
+
+ closeJobAfterDelay(jobs, 'j1', 100, job);
+ vi.advanceTimersByTime(100);
+ expect(job.clients[0].end).toHaveBeenCalled();
+ expect(jobs.has('j1')).toBe(false);
+ });
});
diff --git a/server/routes/storyBuilder.js b/server/routes/storyBuilder.js
index f42db527aa..b247e5b83e 100644
--- a/server/routes/storyBuilder.js
+++ b/server/routes/storyBuilder.js
@@ -108,7 +108,12 @@ router.post('/:id/steps/:stepId/generate', asyncHandler(async (req, res) => {
assertStep(req.params.stepId);
const input = validateRequest(storyStepGenerateSchema, req.body || {});
await getStorySession(req.params.id).catch((err) => { throw mapServiceError(err); });
- const run = startStepRun(req.params.id, req.params.stepId, { op: 'generate', ...input });
+ // Backfill (fromDownstream) and forward generate both dispatch through
+ // generateStep, but tag distinct ops so the client's backfill button (op:
+ // 'backfill') re-attaches to an in-flight backfill instead of being told a
+ // different op is running. The runner routes any non-'refine' op to generateStep.
+ const op = input.fromDownstream ? 'backfill' : 'generate';
+ const run = startStepRun(req.params.id, req.params.stepId, { op, ...input });
res.json({ ...run, sseUrl: `/api/story-builder/${req.params.id}/steps/${req.params.stepId}/progress` });
}));
diff --git a/server/services/storyBuilderRunner.js b/server/services/storyBuilderRunner.js
index f854724c1c..cdff72963e 100644
--- a/server/services/storyBuilderRunner.js
+++ b/server/services/storyBuilderRunner.js
@@ -62,9 +62,15 @@ export function startStepRun(sessionId, stepId, { op = 'generate', ...options }
// from a different-op collision (a refine landing on an in-flight generate).
// The two ops persist to the same records, so the client must NOT bind a
// refine's success handler to a generate's terminal frame.
- if (runs.has(key)) {
- const existing = runs.get(key);
- return { runId: existing.runId, alreadyRunning: true, op: existing.op };
+ //
+ // Only coalesce onto a run that's still WORKING. 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 under the same key.
+ const inFlight = runs.get(key);
+ if (inFlight && !inFlight.done) {
+ return { runId: inFlight.runId, alreadyRunning: true, op: inFlight.op };
}
const runId = randomUUID();
@@ -75,6 +81,7 @@ export function startStepRun(sessionId, stepId, { op = 'generate', ...options }
startedAt: new Date().toISOString(),
stepId,
op,
+ done: false,
};
runs.set(key, record);
@@ -88,7 +95,7 @@ export function startStepRun(sessionId, stepId, { op = 'generate', ...options }
// must never break the run.
const onProgress = (frame) => {
try {
- broadcast(key, { type: 'progress', ...frame });
+ broadcast(key, { type: 'progress', runId, ...frame });
} catch (err) {
console.error(`❌ story-builder progress emit failed: ${err?.message || err}`);
}
@@ -117,9 +124,14 @@ export function startStepRun(sessionId, stepId, { op = 'generate', ...options }
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).
- closeJobAfterDelay(runs, key);
+ // 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);
}
})();
diff --git a/server/services/storyBuilderRunner.test.js b/server/services/storyBuilderRunner.test.js
index 540ef4d88b..620c81c5a9 100644
--- a/server/services/storyBuilderRunner.test.js
+++ b/server/services/storyBuilderRunner.test.js
@@ -103,6 +103,22 @@ describe('storyBuilderRunner', () => {
expect(conductor.refineStep).toHaveBeenCalledWith('stb-2', 'universeAesthetic', expect.objectContaining({ feedback: 'tighter' }));
});
+ it('starts a fresh run (not a stale coalesce) for a kickoff during the replay grace window', async () => {
+ // First run completes synchronously; its record lingers in `runs` for the
+ // closeJobAfterDelay grace window (done: true). A second kickoff in that
+ // window must run real work, not coalesce onto the finished record.
+ conductor.generateStep.mockResolvedValue({ providerId: 'p1' });
+ const first = startStepRun('stb-1', 'idea', { op: 'generate' });
+ await flush(); // first run reaches its terminal frame + marks done
+ expect(conductor.generateStep).toHaveBeenCalledTimes(1);
+
+ const second = startStepRun('stb-1', 'idea', { op: 'generate' });
+ expect(second.alreadyRunning).toBe(false);
+ expect(second.runId).not.toBe(first.runId);
+ await flush();
+ expect(conductor.generateStep).toHaveBeenCalledTimes(2);
+ });
+
it('attachClient returns false when no run is active for the step', () => {
const res = fakeRes();
expect(attachClient('stb-none', 'idea', res)).toBe(false);