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: recover active Story Builder step runs after reload (#10065)

[._.]/ Adam Eivyfd401158f14f
diff --git a/client/src/hooks/useStoryStepRuns.jsx b/client/src/hooks/useStoryStepRuns.jsx
index ec8a943446..df20a9ca95 100644
--- a/client/src/hooks/useStoryStepRuns.jsx
+++ b/client/src/hooks/useStoryStepRuns.jsx
@@ -46,6 +46,15 @@ function StepRunStream({ sessionId, stepId, runId, onPhase, onEnd }) {
/**
* Hosts every in-flight Story Builder step run for one session. Mount it above
* anything that unmounts on step navigation.
+ *
+ * A run this mount did not start — discovered on the session read after a
+ * reload / second tab, or the holder of a kickoff conflict (#10065) — is
+ * ADOPTED: the same progress stream is attached, but there is no originating
+ * request whose success handler could fire. The page registers (via
+ * `useStoryRunMonitor`) `onAdoptedEnd({ ok, stepId, op, frame | error })` to
+ * refresh the session once on settlement, and `onKickoffUncertain`, which fires
+ * when a kickoff POST rejects: the server may have registered the run before the
+ * acknowledgement was lost, so the page re-reads the session (re-discovering it).
*/
export function StoryStepRunProvider({ sessionId, children }) {
// { [stepId]: { epoch, runId | null, op, phase, meta } } — a slot with
@@ -58,6 +67,14 @@ export function StoryStepRunProvider({ sessionId, children }) {
// Step ids with a kickoff in flight or a live run — the synchronous mirror of
// `runs`, so the re-entrancy guard in `start` doesn't depend on a re-render.
const startedRef = useRef(new Set());
+ // Run ids that already settled in this mount — a stale discovery response must
+ // not re-adopt a run whose terminal frame this provider already handled.
+ const settledRunsRef = useRef(new Set());
+ const sessionIdRef = useRef(sessionId);
+ sessionIdRef.current = sessionId;
+ // Latest page callbacks (registered by useStoryRunMonitor), read at call time
+ // so adopted runs never capture a stale closure.
+ const callbacksRef = useRef({});
// Opening a different story invalidates every run here. The reset must happen
// DURING the render that changed `sessionId` (React's "adjusting state on a
@@ -77,6 +94,7 @@ export function StoryStepRunProvider({ sessionId, children }) {
setRuns({});
handlersRef.current = {};
startedRef.current = new Set();
+ settledRunsRef.current = new Set();
}
const ownRuns = Object.fromEntries(
Object.entries(runs).filter(([, run]) => run.epoch === epochRef.current),
@@ -107,12 +125,41 @@ export function StoryStepRunProvider({ sessionId, children }) {
});
}, []);
- const endRun = useCallback((stepId, result) => {
+ const endRun = useCallback((stepId, result, runId) => {
+ if (runId) settledRunsRef.current.add(runId);
const h = clear(stepId);
if (result.ok) h?.onComplete?.(result.frame);
else h?.onError?.(result.error);
}, [clear]);
+ // Attach to a run this mount did not start. Returns true when a slot was
+ // created. Guards: the session must still be the one the run belongs to (a late
+ // response for a story the user left is dropped), the step must have no slot or
+ // in-flight kickoff of its own, and a run this mount already settled is never
+ // resurrected by a stale snapshot.
+ const adopt = useCallback((forSessionId, { stepId, runId, op, phase, entryId }) => {
+ if (forSessionId !== sessionIdRef.current || !stepId || !runId) return false;
+ if (startedRef.current.has(stepId) || settledRunsRef.current.has(runId)) return false;
+ const epoch = epochRef.current;
+ startedRef.current.add(stepId);
+ handlersRef.current[stepId] = {
+ onComplete: (frame) => callbacksRef.current.onAdoptedEnd?.({ ok: true, stepId, op, frame }),
+ onError: (error) => callbacksRef.current.onAdoptedEnd?.({ ok: false, stepId, op, error }),
+ };
+ setRuns((prev) => ({
+ ...prev,
+ [stepId]: { epoch, runId, op: op || 'generate', phase: phase || 'Running…', meta: entryId ? { entryId } : null, adopted: true },
+ }));
+ return true;
+ }, []);
+
+ // Adopt every live run a session read reported. Idempotent — safe to call on
+ // every reload.
+ const adoptActive = useCallback((forSessionId, activeSteps) => {
+ if (!Array.isArray(activeSteps)) return;
+ for (const run of activeSteps) adopt(forSessionId, run);
+ }, [adopt]);
+
/**
* Start a run on `stepId`. `kickoff` POSTs the run and resolves to the
* server's `{ runId }` (or `{ conflict: true }`); the stream subscribes only
@@ -132,7 +179,14 @@ export function StoryStepRunProvider({ sessionId, children }) {
// a visit that is over — its slot is already gone, and reporting its outcome
// now would toast about work the user can no longer see.
if (epochRef.current !== epoch) return;
- if (res.err) { clear(stepId); handlers.onError?.(res.err); return; }
+ if (res.err) {
+ clear(stepId);
+ handlers.onError?.(res.err);
+ // The POST may have reached the server before its acknowledgement was
+ // lost — let the page re-read the session so a live run is re-discovered.
+ callbacksRef.current.onKickoffUncertain?.();
+ return;
+ }
// The kickoff collided with a DIFFERENT in-flight request for this step (a
// different op, or a refine of another target/note). That run persists to the
// same records, so binding THIS button's success handler to its terminal
@@ -140,7 +194,12 @@ export function StoryStepRunProvider({ sessionId, children }) {
// (A same-work re-click returns alreadyRunning without conflict.)
if (res.r?.conflict) {
clear(stepId);
- handlers.onError?.(new Error('Another operation is already running for this step — try again once it finishes.'));
+ // Observe the holder (never bind THIS request's handlers to it) so its
+ // progress and completion stay visible instead of a dead-end refusal.
+ const adopted = adopt(sessionIdRef.current, { stepId, runId: res.r.runId, op: res.r.op, entryId: res.r.entryId });
+ handlers.onError?.(new Error(adopted
+ ? `A ${res.r.op || 'different'} run is already in progress for this step — now monitoring it. Try again once it finishes.`
+ : 'Another operation is already running for this step — try again once it finishes.'));
return;
}
// A resolved-but-empty response (or a 2xx carrying no run id) has nothing to
@@ -153,10 +212,10 @@ export function StoryStepRunProvider({ sessionId, children }) {
}
handlersRef.current[stepId] = handlers;
setRuns((prev) => ({ ...prev, [stepId]: { epoch, runId: res.r.runId, op, phase: 'Starting…', meta } }));
- }, [ownRuns, clear]);
+ }, [ownRuns, clear, adopt]);
return (
- <StoryStepRunContext.Provider value={{ runs: ownRuns, start }}>
+ <StoryStepRunContext.Provider value={{ runs: ownRuns, start, adoptActive, callbacksRef }}>
{Object.entries(ownRuns).map(([stepId, run]) => (run.runId ? (
<StepRunStream
key={`${stepId}:${run.runId}`}
@@ -164,7 +223,7 @@ export function StoryStepRunProvider({ sessionId, children }) {
stepId={stepId}
runId={run.runId}
onPhase={(label) => setPhase(stepId, label)}
- onEnd={(result) => endRun(stepId, result)}
+ onEnd={(result) => endRun(stepId, result, run.runId)}
/>
) : null))}
{children}
@@ -194,3 +253,24 @@ export function useStoryStepRun(stepId) {
meta: run?.meta ?? null,
};
}
+
+/**
+ * Every run slot this provider currently holds (own kickoffs + adopted ones) as
+ * `[{ stepId, op, phase, adopted, meta }]`, plus `adoptActive(sessionId,
+ * activeSteps)` to attach the live runs a session read reported. The page uses
+ * the list for its active-run banner and the adopter on each session load, and
+ * passes the settlement / lost-acknowledgement callbacks documented on the provider.
+ */
+export function useStoryRunMonitor({ onAdoptedEnd, onKickoffUncertain } = {}) {
+ const ctx = useContext(StoryStepRunContext);
+ if (!ctx) throw new Error('useStoryRunMonitor must be used inside a <StoryStepRunProvider>');
+ const { callbacksRef } = ctx;
+ useEffect(() => {
+ callbacksRef.current = { onAdoptedEnd, onKickoffUncertain };
+ return () => { callbacksRef.current = {}; };
+ }, [callbacksRef, onAdoptedEnd, onKickoffUncertain]);
+ const runs = Object.entries(ctx.runs)
+ .filter(([, run]) => run.runId)
+ .map(([stepId, run]) => ({ stepId, op: run.op, phase: run.phase, adopted: Boolean(run.adopted), meta: run.meta }));
+ return { runs, adoptActive: ctx.adoptActive };
+}
diff --git a/client/src/hooks/useStoryStepRuns.test.jsx b/client/src/hooks/useStoryStepRuns.test.jsx
index f21f06ef22..7018b48fbf 100644
--- a/client/src/hooks/useStoryStepRuns.test.jsx
+++ b/client/src/hooks/useStoryStepRuns.test.jsx
@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { act, render, screen, waitFor } from '@testing-library/react';
import { useState } from 'react';
import { MockEventSource, lastEventSource } from '../test/mockEventSource';
-import { StoryStepRunProvider, useStoryStepRun } from './useStoryStepRuns.jsx';
+import { StoryStepRunProvider, useStoryStepRun, useStoryRunMonitor } from './useStoryStepRuns.jsx';
vi.mock('../services/api', () => ({
storyStepProgressSseUrl: (sessionId, stepId) => `/api/story-builder/${sessionId}/steps/${stepId}/progress`,
@@ -225,4 +225,107 @@ describe('useStoryStepRuns', () => {
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1));
expect(kickoff).toHaveBeenCalledTimes(1);
});
+
+ describe('adopting runs this mount did not start (#10065)', () => {
+ // Stands in for the page: feeds a session read's activeSteps into the
+ // provider and records what the page callbacks receive.
+ function Monitor({ sessionId, discovered, onAdoptedEnd, onKickoffUncertain }) {
+ const { runs, adoptActive } = useStoryRunMonitor({ onAdoptedEnd, onKickoffUncertain });
+ return (
+ <div>
+ <button onClick={() => adoptActive(sessionId, discovered)}>discover</button>
+ <button onClick={() => adoptActive('other-session', discovered)}>discover-stale</button>
+ <span data-testid="runs">{runs.map((r) => `${r.stepId}:${r.op}:${r.phase}:${r.adopted}`).join('|') || 'none'}</span>
+ </div>
+ );
+ }
+ const renderMonitor = (props, panel = null) => render(
+ <StoryStepRunProvider sessionId="s1">
+ <Monitor sessionId="s1" {...props} />
+ {panel}
+ </StoryStepRunProvider>,
+ );
+
+ it('attaches to a discovered run without a kickoff and settles through onAdoptedEnd once', async () => {
+ const onAdoptedEnd = vi.fn();
+ renderMonitor({ discovered: [{ stepId: 'plotArc', runId: 'r7', op: 'refine', phase: 'Rewriting…', entryId: 'c1' }], onAdoptedEnd });
+ click('discover');
+ await waitFor(() => expect(MockEventSource.instances).toHaveLength(1));
+ expect(lastEventSource().url).toBe('/api/story-builder/s1/steps/plotArc/progress');
+ expect(screen.getByTestId('runs').textContent).toBe('plotArc:refine:Rewriting…:true');
+
+ act(() => lastEventSource().emit({ runId: 'r7', type: 'complete' }));
+ expect(onAdoptedEnd).toHaveBeenCalledTimes(1);
+ expect(onAdoptedEnd).toHaveBeenCalledWith(expect.objectContaining({ ok: true, stepId: 'plotArc', op: 'refine' }));
+ expect(screen.getByTestId('runs').textContent).toBe('none');
+
+ // A stale snapshot listing the settled run must not resurrect it.
+ click('discover');
+ expect(screen.getByTestId('runs').textContent).toBe('none');
+ expect(MockEventSource.instances).toHaveLength(1);
+ });
+
+ it('ignores a discovery response that belongs to a different story', () => {
+ renderMonitor({ discovered: [{ stepId: 'plotArc', runId: 'r7', op: 'generate' }] });
+ click('discover-stale');
+ expect(screen.getByTestId('runs').textContent).toBe('none');
+ expect(MockEventSource.instances).toHaveLength(0);
+ });
+
+ it('does not displace a step that already has its own run', async () => {
+ const kickoff = vi.fn().mockResolvedValue({ runId: 'own' });
+ renderMonitor(
+ { discovered: [{ stepId: 'plotArc', runId: 'other', op: 'refine' }] },
+ <StepPanel stepId="plotArc" kickoff={kickoff} onComplete={vi.fn()} onError={vi.fn()} />,
+ );
+ click('run-plotArc');
+ await waitFor(() => expect(MockEventSource.instances).toHaveLength(1));
+ click('discover');
+ expect(MockEventSource.instances).toHaveLength(1);
+ expect(screen.getByTestId('state-plotArc').textContent).toMatch(/busy:generate/);
+ });
+
+ it('adopts the conflict holder, keeps the refused op\'s success handler unfired, and reports the refusal', async () => {
+ const onComplete = vi.fn();
+ const onError = vi.fn();
+ const onAdoptedEnd = vi.fn();
+ const kickoff = vi.fn().mockResolvedValue({ conflict: true, runId: 'holder', op: 'refine', entryId: 'c9' });
+ renderMonitor({ discovered: [], onAdoptedEnd },
+ <StepPanel stepId="characters" kickoff={kickoff} onComplete={onComplete} onError={onError} />);
+ click('run-characters');
+
+ await waitFor(() => expect(MockEventSource.instances).toHaveLength(1));
+ expect(onError.mock.calls[0][0].message).toMatch(/refine run is already in progress.*monitoring/);
+ expect(screen.getByTestId('state-characters').textContent).toBe('busy:refine:Running…');
+ expect(screen.getByTestId('meta-characters').textContent).toBe('c9');
+
+ act(() => lastEventSource().emit({ runId: 'holder', type: 'complete' }));
+ expect(onComplete).not.toHaveBeenCalled(); // the refused request's success never fires
+ expect(onAdoptedEnd).toHaveBeenCalledWith(expect.objectContaining({ ok: true, op: 'refine' }));
+ });
+
+ it('asks the page to re-read the session when a kickoff rejects (lost acknowledgement)', async () => {
+ const onKickoffUncertain = vi.fn();
+ const onError = vi.fn();
+ const kickoff = vi.fn().mockRejectedValue(new Error('network'));
+ renderMonitor({ discovered: [], onKickoffUncertain },
+ <StepPanel stepId="plotArc" kickoff={kickoff} onComplete={vi.fn()} onError={onError} />);
+ click('run-plotArc');
+ await waitFor(() => expect(onKickoffUncertain).toHaveBeenCalledTimes(1));
+ expect(onError).toHaveBeenCalledTimes(1);
+ });
+
+ it('drops an adopted run when the story changes', async () => {
+ const { rerender } = renderMonitor({ discovered: [{ stepId: 'plotArc', runId: 'r7', op: 'generate' }] });
+ click('discover');
+ await waitFor(() => expect(MockEventSource.instances).toHaveLength(1));
+ rerender(
+ <StoryStepRunProvider sessionId="s2">
+ <Monitor sessionId="s2" discovered={[]} />
+ </StoryStepRunProvider>,
+ );
+ expect(screen.getByTestId('runs').textContent).toBe('none');
+ expect(MockEventSource.instances.filter((es) => es.url.includes('/s2/'))).toHaveLength(0);
+ });
+ });
});
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsx
index 04c9e7f5ec..08b1d76140 100644
--- a/client/src/pages/StoryBuilder.jsx
+++ b/client/src/pages/StoryBuilder.jsx
@@ -20,7 +20,7 @@ import {
import toast from '../components/ui/Toast';
import Banner from '../components/ui/Banner';
import { useLockToggle } from '../hooks/useLockToggle';
-import { StoryStepRunProvider, useStoryStepRun } from '../hooks/useStoryStepRuns.jsx';
+import { StoryStepRunProvider, useStoryStepRun, useStoryRunMonitor } from '../hooks/useStoryStepRuns.jsx';
import {
getStoryBuilderSteps, listStorySessions, getStorySession, createStorySession,
updateStorySession, setStoryCurrentStep, lockStoryStep, unlockStoryStep,
@@ -1035,6 +1035,14 @@ function nextButtonReason({ locked, stale }) {
return 'Go to the next step.';
}
+// Wording for a run's operation, shared by the active-run banner and the
+// completion toast of a run this view only adopted.
+const RUN_OP_LABEL = {
+ generate: { active: 'Generating', done: 'Generation' },
+ refine: { active: 'Refining', done: 'Refinement' },
+ backfill: { active: 'Backfilling', done: 'Backfill' },
+};
+
function StoryBuilderDetail({ storyId, stepParam }) {
const navigate = useNavigate();
const [steps, setSteps] = useState([]);
@@ -1054,13 +1062,34 @@ function StoryBuilderDetail({ storyId, stepParam }) {
// records fetched before the newer completion landed.
const reloadGenRef = useRef(0);
+ // Runs this view did not start itself (a reload, a second tab, or the holder of
+ // a refused kickoff) are discovered on the session read and adopted by the
+ // provider (#10065). The callbacks go through a ref so they can call `reload`
+ // (defined just below) without re-registering on every render.
+ const reloadRef = useRef(null);
+ const handleAdoptedEnd = useCallback(({ ok, op, error }) => {
+ if (ok) toast.success(`${RUN_OP_LABEL[op]?.done || 'Run'} finished`);
+ else toast.error(error?.message || 'Run failed');
+ reloadRef.current?.();
+ }, []);
+ const handleKickoffUncertain = useCallback(() => { reloadRef.current?.(); }, []);
+ const { runs: activeRuns, adoptActive } = useStoryRunMonitor({
+ onAdoptedEnd: handleAdoptedEnd,
+ onKickoffUncertain: handleKickoffUncertain,
+ });
+
const reload = useCallback(async () => {
const gen = ++reloadGenRef.current;
const isCurrent = () => reloadGenRef.current === gen;
const s = await getStorySession(storyId, { silent: true }).catch(() => null);
if (!isCurrent()) return;
if (!s) { setSession(null); setLoading(false); return; }
- setSession(s);
+ // `activeSteps` is a live-run snapshot, not session state — hand it to the
+ // provider (which drops it if the story changed meanwhile) and keep it out of
+ // the record we hold.
+ const { activeSteps, ...record } = s;
+ adoptActive(storyId, activeSteps);
+ setSession(record);
setStaleSteps(s.staleSteps || []);
setSyncDrift(s.syncDrift === true);
// These GETs own their fallback (.catch → null/[]), so silence the helper's
@@ -1078,7 +1107,8 @@ function StoryBuilderDetail({ storyId, stepParam }) {
setIssues(Array.isArray(iss) ? iss : (iss?.items || []));
}
setLoading(false);
- }, [storyId]);
+ }, [storyId, adoptActive]);
+ reloadRef.current = reload;
// Optimistically mirror a completed character render onto the loaded
// universe's `imageRefs[]`. The Story Builder characters step now tags its
@@ -1317,6 +1347,31 @@ function StoryBuilderDetail({ storyId, stepParam }) {
)}
</div>
+ {/* Live runs — own kickoffs and ones adopted after a reload / second tab —
+ stay visible whichever step is open, with a way back to the step. */}
+ {activeRuns.length > 0 && (
+ <div role="status" aria-live="polite" className="mb-4 space-y-2">
+ {activeRuns.map((run) => {
+ const label = steps.find((st) => st.id === run.stepId)?.label || run.stepId;
+ return (
+ <div key={run.stepId} className="flex items-center flex-wrap gap-x-3 gap-y-1 text-sm bg-port-card border border-port-accent/40 rounded-lg px-3 py-2">
+ <Loader2 className="w-4 h-4 animate-spin text-port-accent shrink-0" aria-hidden="true" />
+ <span className="min-w-0 break-words">
+ <span className="font-medium">{RUN_OP_LABEL[run.op]?.active || 'Running'} {label}</span>
+ {run.phase ? <span className="text-gray-400"> — {run.phase}</span> : null}
+ {run.adopted ? <span className="text-xs text-gray-500"> (resumed monitoring)</span> : null}
+ </span>
+ {run.stepId !== activeStepId && (
+ <button type="button" onClick={() => goToStep(run.stepId)} className="ml-auto text-xs text-port-accent hover:underline">
+ Go to step
+ </button>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+
<div className="grid grid-cols-1 md:grid-cols-[220px_1fr] gap-6">
{/* Step rail */}
<nav className="space-y-1">
diff --git a/client/src/pages/StoryBuilder.test.jsx b/client/src/pages/StoryBuilder.test.jsx
index a295c37202..880c8269e7 100644
--- a/client/src/pages/StoryBuilder.test.jsx
+++ b/client/src/pages/StoryBuilder.test.jsx
@@ -907,4 +907,52 @@ describe('StoryBuilder — detail stepper', () => {
await waitFor(() => expect(toastMock.success).toHaveBeenCalledWith('Generated'));
delete global.EventSource;
});
+
+ // #10065 — a full reload / second tab starts with an empty provider, but the
+ // server run is still live. The session read now reports it; the page must
+ // re-attach to its stream (no second kickoff), show it, and refresh once on
+ // settlement.
+ describe('discovering a live run after a reload (#10065)', () => {
+ const liveSession = (activeSteps) => ({
+ id: 'stb-1', title: 'X', currentStep: 'readerMap', universeId: 'u1', seriesId: 's1',
+ steps: mkSteps({ idea: { locked: true }, universeAesthetic: { locked: true }, plotArc: { locked: true } }),
+ staleSteps: [], llm: { provider: '', model: '' }, activeSteps,
+ });
+ beforeEach(() => { MockEventSource.reset(); global.EventSource = MockEventSource; });
+ afterEach(() => { delete global.EventSource; });
+
+ it('attaches to the surviving run, shows it, disables the kickoff and reloads once on completion', async () => {
+ api.getStorySession.mockResolvedValue(liveSession([
+ { stepId: 'readerMap', runId: 'run-9', op: 'refine', startedAt: '2026-01-01T00:00:00.000Z', phase: 'Rewriting…' },
+ ]));
+ renderAt('/story-builder/stb-1/readerMap');
+
+ await waitFor(() => expect(MockEventSource.instances).toHaveLength(1));
+ expect(lastEventSource().url).toBe('/api/story-builder/stb-1/steps/readerMap/progress');
+ expect(screen.getByRole('status').textContent).toMatch(/Refining Reader Map/);
+ expect(screen.getByRole('status').textContent).toMatch(/resumed monitoring/);
+ // The control is busy off the discovered run — no second kickoff possible.
+ expect(screen.getByRole('button', { name: /Generate reader map|Re-generate|Working/ }).disabled).toBe(true);
+ expect(api.generateStoryStep).not.toHaveBeenCalled();
+ expect(api.refineStoryStep).not.toHaveBeenCalled();
+
+ api.getStorySession.mockClear();
+ api.getStorySession.mockResolvedValue(liveSession([]));
+ await act(async () => { lastEventSource().emit({ runId: 'run-9', type: 'complete' }); });
+ await waitFor(() => expect(toastMock.success).toHaveBeenCalledWith('Refinement finished'));
+ await waitFor(() => expect(api.getStorySession).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(screen.queryByRole('status')).toBeNull());
+ // Settled once — the post-settlement session read lists no live run, so nothing re-attaches.
+ expect(MockEventSource.instances).toHaveLength(1);
+ });
+
+ it('lets the operator reach a run on another step from the banner', async () => {
+ api.getStorySession.mockResolvedValue(liveSession([
+ { stepId: 'characters', runId: 'run-3', op: 'backfill', startedAt: '2026-01-01T00:00:00.000Z', phase: null },
+ ]));
+ renderAt('/story-builder/stb-1/readerMap');
+ await waitFor(() => expect(screen.getByRole('status').textContent).toMatch(/Backfilling Characters/));
+ expect(screen.getByRole('button', { name: 'Go to step' })).toBeTruthy();
+ });
+ });
});
diff --git a/server/lib/sseUtils.js b/server/lib/sseUtils.js
index 60819cf380..4b9a2791bb 100644
--- a/server/lib/sseUtils.js
+++ b/server/lib/sseUtils.js
@@ -206,7 +206,10 @@ export const createJobFailureFinalizer = ({
// 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
+// A caller's `work` may stamp `record.phase` (a short label) so `listActive` can
+// report the latest phase to a client that attaches mid-run.
+//
+// Returns `{ runs, isActive, attachClient, listActive, 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, sig, meta }>
@@ -233,6 +236,20 @@ export function createSseRunner({ logLabel = 'sse run' } = {}) {
const attachClient = (key, res) => attachSseClient(runs, key, res);
+ // Bounded read-only view of the runs still in flight whose key starts with
+ // `prefix` — a discovery surface for a client that lost its run slot (reload,
+ // second tab). Exposes only identity + the caller's own `meta` + the latest
+ // phase label, never the signature, clients, or abort controller, and a
+ // finished run lingering in its replay window is NOT listed (it is not running).
+ const listActive = (prefix = '') => {
+ const out = [];
+ for (const [key, run] of runs) {
+ if (run.finished || !String(key).startsWith(prefix)) continue;
+ out.push({ key, runId: run.runId, startedAt: run.startedAt, phase: run.phase ?? null, meta: { ...(run.meta || {}) } });
+ }
+ return out;
+ };
+
const cancel = (key) => {
const run = runs.get(key);
if (!run) return false;
@@ -302,5 +319,5 @@ export function createSseRunner({ logLabel = 'sse run' } = {}) {
return { runId, alreadyRunning: false };
};
- return { runs, isActive, attachClient, cancel, start };
+ return { runs, isActive, attachClient, listActive, cancel, start };
}
diff --git a/server/routes/storyBuilder.js b/server/routes/storyBuilder.js
index 33b6515cfa..04333add09 100644
--- a/server/routes/storyBuilder.js
+++ b/server/routes/storyBuilder.js
@@ -30,7 +30,7 @@ import {
ERR_NOT_FOUND,
ERR_VALIDATION,
} from '../services/storyBuilder.js';
-import { startStepRun, attachClient } from '../services/storyBuilderRunner.js';
+import { startStepRun, attachClient, listActiveStepRuns } from '../services/storyBuilderRunner.js';
const router = Router();
@@ -68,9 +68,13 @@ router.post('/', asyncHandler(async (req, res) => {
// flag (#730: this machine's live records diverged from the synced baseline).
const flattenView = (view) => ({ ...view.session, staleSteps: view.staleSteps, syncDrift: view.syncDrift });
+// `activeSteps` is the live-run discovery surface (#10065): which generate /
+// refine / backfill runs are still in flight for this session, so a reloaded or
+// second-tab client can re-attach to their progress streams. Computed from the
+// runner's in-memory map on read — it is never persisted and read-only.
router.get('/:id', asyncHandler(async (req, res) => {
const view = await getStorySessionView(req.params.id).catch((err) => { throw mapServiceError(err); });
- res.json(flattenView(view));
+ res.json({ ...flattenView(view), activeSteps: listActiveStepRuns(req.params.id) });
}));
router.patch('/:id', asyncHandler(async (req, res) => {
diff --git a/server/routes/storyBuilder.test.js b/server/routes/storyBuilder.test.js
index 165d06e645..963adefd4e 100644
--- a/server/routes/storyBuilder.test.js
+++ b/server/routes/storyBuilder.test.js
@@ -31,6 +31,7 @@ vi.mock('../services/storyBuilder.js', () => svc);
const runner = {
startStepRun: vi.fn(() => ({ runId: 'run-1', alreadyRunning: false })),
attachClient: vi.fn(() => true),
+ listActiveStepRuns: vi.fn(() => []),
};
vi.mock('../services/storyBuilderRunner.js', () => runner);
@@ -103,6 +104,17 @@ describe('GET /api/story-builder/:id', () => {
expect(res.body.id).toBe('stb-1');
expect(res.body.staleSteps).toEqual(['readerMap']);
expect(res.body.syncDrift).toBe(true);
+ expect(res.body.activeSteps).toEqual([]);
+ });
+
+ it('exposes the session\'s live step runs for post-reload re-attachment (#10065)', async () => {
+ const live = [{ stepId: 'plotArc', runId: 'run-9', op: 'refine', startedAt: '2026-01-01T00:00:00.000Z', phase: 'Planning…' }];
+ runner.listActiveStepRuns.mockReturnValueOnce(live);
+ const res = await request(makeApp()).get('/api/story-builder/stb-1');
+ expect(res.body.activeSteps).toEqual(live);
+ expect(runner.listActiveStepRuns).toHaveBeenCalledWith('stb-1');
+ expect(svc.generateStep).not.toHaveBeenCalled();
+ expect(svc.refineStep).not.toHaveBeenCalled();
});
it('maps a service NOT_FOUND to 404', async () => {
diff --git a/server/services/storyBuilderRunner.js b/server/services/storyBuilderRunner.js
index 4c1f6578ef..69cde5c6a3 100644
--- a/server/services/storyBuilderRunner.js
+++ b/server/services/storyBuilderRunner.js
@@ -43,6 +43,23 @@ export function attachClient(sessionId, stepId, res) {
return runner.attachClient(runKey(sessionId, stepId), res);
}
+// Bounded discovery projection of a session's in-flight step runs, for a client
+// that lost its run slot (full reload, second tab). Read-only: it inspects the
+// in-memory run map and never starts provider work. Deliberately omits the
+// request signature, feedback text, clients and abort controller — only the
+// identity a client needs to re-attach to the existing progress stream.
+export function listActiveStepRuns(sessionId) {
+ const prefix = runKey(sessionId, '');
+ return runner.listActive(prefix).map(({ key, runId, startedAt, phase, meta }) => ({
+ stepId: key.slice(prefix.length),
+ runId,
+ op: meta.op,
+ startedAt,
+ phase,
+ ...(meta.entryId ? { entryId: meta.entryId } : {}),
+ }));
+}
+
/**
* Kick off a step generate (op: 'generate') or refine (op: 'refine') for a
* session. Returns the runId immediately; progress lands via SSE. Re-calling
@@ -71,12 +88,15 @@ export function startStepRun(sessionId, stepId, { op = 'generate', ...options }
// `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 }) => {
+ return runner.start(key, async ({ runId, broadcast, record }) => {
broadcast({ type: 'start', runId, stepId, op });
// Best-effort phase emitter handed to the conductor; an onProgress throw
// must never break the run.
const onProgress = (frame) => {
try {
+ // Latest phase label, so a client that attaches mid-run (reload / second
+ // tab) can be told what the run is doing via listActiveStepRuns.
+ if (typeof frame?.label === 'string' && frame.label) record.phase = frame.label.slice(0, 200);
broadcast({ type: 'progress', runId, ...frame });
} catch (err) {
console.error(`❌ story-builder progress emit failed: ${err?.message || err}`);
@@ -108,7 +128,7 @@ export function startStepRun(sessionId, stepId, { op = 'generate', ...options }
console.error(`❌ story-builder ${op} failed — session=${sessionId.slice(0, 8)} step=${stepId} ${message}`);
broadcast({ type: 'error', runId, stepId, op, error: message, failedAt: new Date().toISOString() });
}
- }, { sig, meta: { op } });
+ }, { sig, meta: { op, ...(options.entryId ? { entryId: options.entryId } : {}) } });
}
// Export internals for tests.
diff --git a/server/services/storyBuilderRunner.test.js b/server/services/storyBuilderRunner.test.js
index c4b49ae365..64112ecc58 100644
--- a/server/services/storyBuilderRunner.test.js
+++ b/server/services/storyBuilderRunner.test.js
@@ -8,7 +8,7 @@ const conductor = {
};
vi.mock('./storyBuilder.js', () => conductor);
-const { startStepRun, isStepRunActive, attachClient, __testing } = await import('./storyBuilderRunner.js');
+const { startStepRun, isStepRunActive, attachClient, listActiveStepRuns, __testing } = await import('./storyBuilderRunner.js');
// Minimal SSE `res` double: captures written frames + close.
function fakeRes() {
@@ -141,4 +141,43 @@ describe('storyBuilderRunner', () => {
const res = fakeRes();
expect(attachClient('stb-none', 'idea', res)).toBe(false);
});
+
+ describe('listActiveStepRuns (discovery after reload)', () => {
+ it('lists only this session\'s in-flight runs with a bounded identity, the latest phase, and no request text', async () => {
+ let releaseRefine;
+ conductor.refineStep.mockImplementation(async (_id, _step, { onProgress }) => {
+ onProgress?.({ label: 'Rewriting Mira…', phase: 'refine' });
+ await new Promise((r) => { releaseRefine = r; });
+ return {};
+ });
+ conductor.generateStep.mockImplementation(() => new Promise(() => {}));
+ const refine = startStepRun('stb-1', 'characters', { op: 'refine', entryId: 'char-A', feedback: 'make her angrier' });
+ startStepRun('stb-1', 'plotArc', { op: 'backfill', fromDownstream: true });
+ startStepRun('stb-other', 'idea', { op: 'generate' });
+ await flush();
+
+ const active = listActiveStepRuns('stb-1');
+ expect(active.map((r) => r.stepId).sort()).toEqual(['characters', 'plotArc']);
+ const characters = active.find((r) => r.stepId === 'characters');
+ expect(characters).toEqual({
+ stepId: 'characters', runId: refine.runId, op: 'refine', entryId: 'char-A',
+ startedAt: expect.any(String), phase: 'Rewriting Mira…',
+ });
+ // Discovery must not leak the request text, and must not start provider work.
+ expect(JSON.stringify(active)).not.toContain('angrier');
+ expect(active.find((r) => r.stepId === 'plotArc')).toMatchObject({ op: 'backfill', phase: null });
+ expect(conductor.refineStep).toHaveBeenCalledTimes(1);
+ expect(conductor.generateStep).toHaveBeenCalledTimes(2);
+ releaseRefine();
+ await flush();
+ });
+
+ it('does not list a finished run still lingering in its replay window', async () => {
+ conductor.generateStep.mockResolvedValue({});
+ startStepRun('stb-1', 'idea', { op: 'generate' });
+ await flush();
+ expect(__testing.runs.size).toBe(1); // record still present for terminal replay
+ expect(listActiveStepRuns('stb-1')).toEqual([]);
+ });
+ });
});