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: keep Story Builder step generation alive when the user navigates the step rail (#3905)

[._.]/ Adam Eivy0d5532813c95
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 4fbb74b0dd..4f8902ecf4 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -62,3 +62,4 @@
- Keyboard-shortcut hints across the client now render the right modifier for the machine they're on. `client/src/utils/platform.js` exports a `modKey` (`⌘` / `Ctrl`) label, but only the command palette and the keyboard-help sheet read it — five other hints hardcoded a glyph instead: the 404 page and the Ask composer advertised `⌘K` / `⌘/Ctrl + Enter` to Windows and Linux users, the OpenClaw composer printed both forms side by side, the Writers Room save button's tooltip said `Ctrl/Cmd+S`, and the digital-twin enrichment prompt said `Ctrl+Enter` on a Mac. All five now read `modKey`, which prefers `navigator.userAgentData.platform` over the deprecated `navigator.platform` and degrades to non-Mac when neither exists — behaviour the module now has tests for.
- Leaving the SongBook editor with unsaved edits now asks first. The editor holds every change — sheet text, practice notes, metadata — in an in-memory draft until an explicit Save, so clicking View, following the "All songs" link, or closing the tab dropped the work silently. The page now compares the draft against the saved song (numerically for capo, since the number input hands back a string and retyping the stored value would otherwise read as an edit) and defers those exits behind an inline "Discard your unsaved changes?" band under the header, with Discard resetting the draft and Keep editing leaving it intact; a tab close or reload arms the browser's own prompt. Saving clears an armed confirm, since the draft is no longer dirty.
- `client/src/utils/cityChronotype.js` now exports only `computeChronotypeEnergy`. Its six internal pieces — the two range constants, the neutral-modifier sentinel, and the `parseHour` / `computeEnergy` / `energyModifiers` steps — were exported purely so the unit tests could reach them, but the utils barrel re-exports every module flat, so generic names like `parseHour` and `computeEnergy` sat in the shared namespace waiting to collide with a future module. The tests now drive every one of those behaviors through the public entry point (an unparseable or out-of-range peak window yields the neutral no-op; the `:30` half-hour still lands the peak center at 11.25), plus one assertion that the module's export list stays a single name.
+- An AI generate or refine started in the Story Builder now survives clicking another step on the left rail. The step panel is keyed by the active step, so navigating away unmounted it — which tore down the SSE progress stream and threw away the completion handlers, leaving the run to finish on the server with no phase updates, no success or failure toast, and a stale view until a manual refresh. Each run's stream, phase and handlers now live in a provider mounted above the rail (`client/src/hooks/useStoryStepRuns.jsx`), one slot per step id, so runs on different steps can be in flight at once and the panel picks its own run back up — including which character a refine targets — when the user navigates back to it.
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index b4914da3f0..8397354492 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -52,6 +52,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useMediaJobSse` | Imperative per-job `/{kind}-gen/:id/events` SSE; `attach()` returns a Promise that settles on the terminal frame. | POST-then-attach media render flows that await completion (ImageGen/VideoGen). |
| `useOpenClawStream` | OpenClaw SSE chat stream. | OpenClaw file-browser chat surface only. |
| `usePipelineProgress` | Id-derived runner SSE stream: builds the URL from `(urlBuilder, ids)`, connects only when every id is truthy. | Any runner SSE keyed by record ids (pipeline auto-run, editorial, manuscript completeness, volume beats, story steps). |
+| `useStoryStepRuns` | Story Builder step generate/refine runs hoisted above the step rail: `<StoryStepRunProvider sessionId>` owns one run slot per step id (SSE subscription, phase, `onComplete`/`onError` handlers, arbitrary `meta`), `useStoryStepRun(stepId)` reads/drives it. | Any Story Builder surface that starts a step run — the panel unmounts on rail navigation, so run state must not live in it (#3905). |
| `useSeriesEditorial` | Editorial-roadmap aggregate + batch lifecycle (load, re-attach, SSE, start/cancel, reload). | Any view of the editorial roadmap (panel or Reader Map page). |
| `useReaderPanel` | Reader-panel snapshot (four personas + mined disagreements) + convene lifecycle (load, re-attach, per-persona SSE, run/cancel, reload). | The Reader Map page's Reader Panel tab (#2170). |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 43d0d8015d..7674d69ee4 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -116,6 +116,7 @@ export * from './usePipelineProgress.js';
export * from './useReaderPanel.js';
export * from './useSeriesEditorial.js';
export * from './useSseProgress.js';
+export * from './useStoryStepRuns.jsx';
export * from './useModelDownloadStatus.js';
// === Media (annotations, completion, attachments) ===
diff --git a/client/src/hooks/useStoryStepRuns.jsx b/client/src/hooks/useStoryStepRuns.jsx
new file mode 100644
index 0000000000..d1ceb3a6e2
--- /dev/null
+++ b/client/src/hooks/useStoryStepRuns.jsx
@@ -0,0 +1,168 @@
+import { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';
+import { storyStepProgressSseUrl } from '../services/api';
+import { usePipelineProgress } from './usePipelineProgress';
+
+// Story Builder generate/refine runs, hoisted OUT of the step panel that starts
+// them (#3905). The panel is keyed by the active step id, so clicking another
+// step on the rail unmounts it — when the SSE subscription and the
+// onComplete/onError handlers lived inside that panel, navigating mid-run tore
+// the stream down and the user got no phase updates, no completion toast, and a
+// stale view until a manual refresh. Mounting this provider ABOVE the step rail
+// keeps each run's subscription and handlers alive for as long as the story
+// session is open, whichever step is on screen.
+//
+// One run per step id: the server rejects a second concurrent op on the same
+// step (`conflict`), so the per-step slot mirrors that. Runs on DIFFERENT steps
+// coexist — each active run renders its own <StepRunStream>, so a user can kick
+// off the arc, move to the reader map, and start that one too.
+const StoryStepRunContext = createContext(null);
+
+// Subscribes to one run's progress stream. Mounted only once the kickoff POST
+// has resolved (so the run is registered server-side before the EventSource
+// connects) and unmounted the moment the run settles — which is also why the
+// `latest`-reset race the old inline hook guarded against can't happen here: a
+// fresh mount starts with a null frame. The runId check stays as defense against
+// a replayed terminal frame from the step's previous run.
+function StepRunStream({ sessionId, stepId, runId, onPhase, onEnd }) {
+ const { latest, closed } = usePipelineProgress(storyStepProgressSseUrl, [sessionId, stepId]);
+ // One effect owns every end-of-run path. A terminal frame and `closed` land on
+ // the same render, so the ordered branches (plus this ref) guarantee exactly
+ // one onEnd. The bare-`closed` branch covers a stream that died before any
+ // terminal frame — server pruned a fast run, or the connection dropped.
+ const endedRef = useRef(false);
+
+ useEffect(() => {
+ if (endedRef.current) return;
+ const mine = latest && latest.runId === runId;
+ if (mine && typeof latest.label === 'string' && latest.label) onPhase(latest.label);
+ if (mine && latest.type === 'complete') { endedRef.current = true; onEnd({ ok: true, frame: latest }); }
+ else if (mine && latest.type === 'error') { endedRef.current = true; onEnd({ ok: false, error: new Error(latest.error || 'Generation failed') }); }
+ else if (closed) { endedRef.current = true; onEnd({ ok: false, error: new Error('Lost connection to the generation stream') }); }
+ }, [latest, closed, runId, onPhase, onEnd]);
+
+ return null;
+}
+
+/**
+ * Hosts every in-flight Story Builder step run for one session. Mount it above
+ * anything that unmounts on step navigation.
+ */
+export function StoryStepRunProvider({ sessionId, children }) {
+ // { [stepId]: { runId | null, op, phase, meta } } — a slot with runId === null
+ // is still in kickoff (busy, but nothing to subscribe to yet).
+ const [runs, setRuns] = useState({});
+ // Handlers are closures over the panel that started the run — they must NOT be
+ // state (they'd re-render the whole tree) and they must survive that panel's
+ // unmount, which is the entire point of this provider.
+ const handlersRef = useRef({});
+ // 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());
+
+ // A different story session means none of these runs belong to the view
+ // anymore. Drop them rather than fanning their toasts into the new session.
+ useEffect(() => {
+ setRuns({});
+ handlersRef.current = {};
+ startedRef.current = new Set();
+ }, [sessionId]);
+
+ const clear = useCallback((stepId) => {
+ setRuns((prev) => {
+ if (!(stepId in prev)) return prev;
+ const next = { ...prev };
+ delete next[stepId];
+ return next;
+ });
+ const h = handlersRef.current[stepId];
+ delete handlersRef.current[stepId];
+ startedRef.current.delete(stepId);
+ return h;
+ }, []);
+
+ // Returning `prev` unchanged for a repeat label matters: the stream's effect
+ // re-runs whenever this provider re-renders (its callback props are fresh
+ // arrows), so a setPhase that always allocated a new state object would loop
+ // render → effect → setPhase → render forever.
+ const setPhase = useCallback((stepId, label) => {
+ setRuns((prev) => {
+ const run = prev[stepId];
+ if (!run || run.phase === label) return prev;
+ return { ...prev, [stepId]: { ...run, phase: label } };
+ });
+ }, []);
+
+ const endRun = useCallback((stepId, result) => {
+ const h = clear(stepId);
+ if (result.ok) h?.onComplete?.(result.frame);
+ else h?.onError?.(result.error);
+ }, [clear]);
+
+ /**
+ * Start a run on `stepId`. `kickoff` POSTs the run and resolves to the
+ * server's `{ runId }` (or `{ conflict: true }`); the stream subscribes only
+ * after it lands. `meta` is arbitrary per-run data the UI needs to restore
+ * itself after a remount (e.g. which character is being refined).
+ */
+ const start = useCallback(async (stepId, op, kickoff, handlers = {}, meta = null) => {
+ // The ref, not just the `runs` snapshot: two clicks inside one render tick
+ // both read the same (empty) snapshot, and the second would fire a duplicate
+ // kickoff the server only rejects after a round trip.
+ if (runs[stepId] || startedRef.current.has(stepId)) return;
+ startedRef.current.add(stepId);
+ setRuns((prev) => ({ ...prev, [stepId]: { runId: null, op, phase: 'Starting…', meta } }));
+ const res = await kickoff().catch((err) => { handlers.onError?.(err); return null; });
+ if (!res) { clear(stepId); 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
+ // frame would misreport. Don't subscribe — report it and leave the run alone.
+ // (A same-work re-click returns alreadyRunning without conflict.)
+ if (res.conflict) {
+ clear(stepId);
+ handlers.onError?.(new Error('Another operation is already running for this step — try again once it finishes.'));
+ return;
+ }
+ handlersRef.current[stepId] = handlers;
+ setRuns((prev) => ({ ...prev, [stepId]: { runId: res.runId, op, phase: 'Starting…', meta } }));
+ }, [runs, clear]);
+
+ return (
+ <StoryStepRunContext.Provider value={{ runs, start }}>
+ {Object.entries(runs).map(([stepId, run]) => (run.runId ? (
+ <StepRunStream
+ key={`${stepId}:${run.runId}`}
+ sessionId={sessionId}
+ stepId={stepId}
+ runId={run.runId}
+ onPhase={(label) => setPhase(stepId, label)}
+ onEnd={(result) => endRun(stepId, result)}
+ />
+ ) : null))}
+ {children}
+ </StoryStepRunContext.Provider>
+ );
+}
+
+/**
+ * Read/drive the run slot for one step. Drop-in for the old panel-local hook:
+ * `{ start, busy, phase, op }` — plus `meta`, so a panel remounted mid-run can
+ * restore which entry the run targets instead of losing it to unmounted state.
+ */
+export function useStoryStepRun(stepId) {
+ const ctx = useContext(StoryStepRunContext);
+ if (!ctx) throw new Error('useStoryStepRun must be used inside a <StoryStepRunProvider>');
+ const run = ctx.runs[stepId] || null;
+ const { start } = ctx;
+ const startForStep = useCallback(
+ (op, kickoff, handlers, meta) => start(stepId, op, kickoff, handlers, meta),
+ [start, stepId],
+ );
+ return {
+ start: startForStep,
+ busy: Boolean(run),
+ phase: run?.phase || '',
+ op: run?.op || null,
+ meta: run?.meta ?? null,
+ };
+}
diff --git a/client/src/hooks/useStoryStepRuns.test.jsx b/client/src/hooks/useStoryStepRuns.test.jsx
new file mode 100644
index 0000000000..9b74818a6f
--- /dev/null
+++ b/client/src/hooks/useStoryStepRuns.test.jsx
@@ -0,0 +1,147 @@
+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';
+
+vi.mock('../services/api', () => ({
+ storyStepProgressSseUrl: (sessionId, stepId) => `/api/story-builder/${sessionId}/steps/${stepId}/progress`,
+}));
+
+beforeEach(() => {
+ MockEventSource.reset();
+ global.EventSource = MockEventSource;
+});
+
+afterEach(() => {
+ delete global.EventSource;
+});
+
+// Stands in for StepPanel: it is keyed by the active step in the real page, so
+// navigating the rail UNMOUNTS it mid-run. That is the bug this hook fixes.
+function StepPanel({ stepId, kickoff, onComplete, onError, meta }) {
+ const { start, busy, phase, op, meta: runMeta } = useStoryStepRun(stepId);
+ return (
+ <div>
+ <button onClick={() => start('generate', kickoff, { onComplete, onError }, meta)}>run-{stepId}</button>
+ <span data-testid={`state-${stepId}`}>{busy ? `busy:${op}:${phase}` : 'idle'}</span>
+ <span data-testid={`meta-${stepId}`}>{runMeta?.entryId || 'none'}</span>
+ </div>
+ );
+}
+
+function Harness({ panelProps, sessionId = 's1' }) {
+ const [stepId, setStepId] = useState(panelProps.stepId);
+ return (
+ <StoryStepRunProvider sessionId={sessionId}>
+ <button onClick={() => setStepId('other')}>navigate</button>
+ <StepPanel key={stepId} {...panelProps} stepId={stepId} />
+ </StoryStepRunProvider>
+ );
+}
+
+const click = (label) => act(() => { screen.getByText(label).click(); });
+
+describe('useStoryStepRuns', () => {
+ it('subscribes only after the kickoff resolves, then reports the live phase', async () => {
+ const kickoff = vi.fn().mockResolvedValue({ runId: 'r1' });
+ render(<Harness panelProps={{ stepId: 'plotArc', kickoff, onComplete: vi.fn(), onError: vi.fn() }} />);
+
+ click('run-plotArc');
+ expect(MockEventSource.instances).toHaveLength(0); // not until the POST lands
+ await waitFor(() => expect(MockEventSource.instances).toHaveLength(1));
+ expect(lastEventSource().url).toBe('/api/story-builder/s1/steps/plotArc/progress');
+
+ act(() => lastEventSource().emit({ runId: 'r1', type: 'progress', label: 'Planning…' }));
+ expect(screen.getByTestId('state-plotArc').textContent).toBe('busy:generate:Planning…');
+ });
+
+ it('keeps the stream alive and still fires onComplete when the panel unmounts mid-run', async () => {
+ const onComplete = vi.fn();
+ const kickoff = vi.fn().mockResolvedValue({ runId: 'r1' });
+ render(<Harness panelProps={{ stepId: 'plotArc', kickoff, onComplete, onError: vi.fn() }} />);
+
+ click('run-plotArc');
+ await waitFor(() => expect(MockEventSource.instances).toHaveLength(1));
+
+ click('navigate'); // remounts the panel on another step — the old bug's trigger
+ expect(lastEventSource().closed).toBe(false);
+
+ act(() => lastEventSource().emit({ runId: 'r1', type: 'complete', changes: ['a'] }));
+ expect(onComplete).toHaveBeenCalledWith(expect.objectContaining({ type: 'complete' }));
+ });
+
+ it('restores the run phase and meta when the panel remounts on the same step', async () => {
+ const kickoff = vi.fn().mockResolvedValue({ runId: 'r1' });
+ const { rerender } = render(
+ <StoryStepRunProvider sessionId="s1">
+ <StepPanel stepId="characters" kickoff={kickoff} onComplete={vi.fn()} onError={vi.fn()} meta={{ entryId: 'char-1' }} />
+ </StoryStepRunProvider>,
+ );
+ click('run-characters');
+ await waitFor(() => expect(MockEventSource.instances).toHaveLength(1));
+ act(() => lastEventSource().emit({ runId: 'r1', type: 'progress', label: 'Refining…' }));
+
+ rerender(
+ <StoryStepRunProvider sessionId="s1">
+ <div key="remount">
+ <StepPanel stepId="characters" kickoff={kickoff} onComplete={vi.fn()} onError={vi.fn()} meta={{ entryId: 'char-1' }} />
+ </div>
+ </StoryStepRunProvider>,
+ );
+ expect(screen.getByTestId('state-characters').textContent).toBe('busy:generate:Refining…');
+ expect(screen.getByTestId('meta-characters').textContent).toBe('char-1');
+ });
+
+ // A replayed terminal frame from the step's PREVIOUS run must never be
+ // reported as this run's success. The underlying SSE hook closes the stream on
+ // any terminal-typed frame, so the run settles through the lost-connection
+ // path instead — an honest failure, not a false "Generated" toast.
+ it('never reports a replayed previous-run terminal frame as this run completing', async () => {
+ const onComplete = vi.fn();
+ const onError = vi.fn();
+ const kickoff = vi.fn().mockResolvedValue({ runId: 'r2' });
+ render(<Harness panelProps={{ stepId: 'plotArc', kickoff, onComplete, onError }} />);
+ click('run-plotArc');
+ await waitFor(() => expect(MockEventSource.instances).toHaveLength(1));
+
+ act(() => lastEventSource().emit({ runId: 'r1', type: 'complete' }));
+ await waitFor(() => expect(onError).toHaveBeenCalledTimes(1));
+ expect(onComplete).not.toHaveBeenCalled();
+ expect(screen.getByTestId('state-plotArc').textContent).toBe('idle');
+ });
+
+ it('settles with an error when the stream closes without a terminal frame', async () => {
+ const onError = vi.fn();
+ const kickoff = vi.fn().mockResolvedValue({ runId: 'r1' });
+ render(<Harness panelProps={{ stepId: 'plotArc', kickoff, onComplete: vi.fn(), onError }} />);
+ click('run-plotArc');
+ await waitFor(() => expect(MockEventSource.instances).toHaveLength(1));
+
+ act(() => lastEventSource().fail());
+ await waitFor(() => expect(onError).toHaveBeenCalledTimes(1));
+ expect(onError.mock.calls[0][0].message).toMatch(/Lost connection/);
+ expect(screen.getByTestId('state-plotArc').textContent).toBe('idle');
+ });
+
+ it('reports a kickoff conflict through onError without subscribing', async () => {
+ const onError = vi.fn();
+ const kickoff = vi.fn().mockResolvedValue({ conflict: true });
+ render(<Harness panelProps={{ stepId: 'plotArc', kickoff, onComplete: vi.fn(), onError }} />);
+ click('run-plotArc');
+
+ await waitFor(() => expect(onError).toHaveBeenCalledTimes(1));
+ expect(onError.mock.calls[0][0].message).toMatch(/Another operation is already running/);
+ expect(MockEventSource.instances).toHaveLength(0);
+ expect(screen.getByTestId('state-plotArc').textContent).toBe('idle');
+ });
+
+ it('refuses a second kickoff on the same step while one is in flight', async () => {
+ const kickoff = vi.fn().mockResolvedValue({ runId: 'r1' });
+ render(<Harness panelProps={{ stepId: 'plotArc', kickoff, onComplete: vi.fn(), onError: vi.fn() }} />);
+ click('run-plotArc');
+ click('run-plotArc');
+ await waitFor(() => expect(MockEventSource.instances).toHaveLength(1));
+ expect(kickoff).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsx
index a5956a30cf..da5b3ea798 100644
--- a/client/src/pages/StoryBuilder.jsx
+++ b/client/src/pages/StoryBuilder.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
+import { useState, useEffect, useCallback, useMemo } from 'react';
import { useParams, useNavigate, useSearchParams, useLocation, Link } from 'react-router';
import PageSkeleton from '../components/ui/PageSkeleton';
import { filterSelectableModels } from '../utils/providers';
@@ -20,12 +20,12 @@ import {
import toast from '../components/ui/Toast';
import Banner from '../components/ui/Banner';
import { useLockToggle } from '../hooks/useLockToggle';
-import { usePipelineProgress } from '../hooks/usePipelineProgress';
+import { StoryStepRunProvider, useStoryStepRun } from '../hooks/useStoryStepRuns.jsx';
import {
getStoryBuilderSteps, listStorySessions, getStorySession, createStorySession,
updateStorySession, setStoryCurrentStep, lockStoryStep, unlockStoryStep,
generateStoryStep, refineStoryStep, setStoryIssueLock, generateStoryIssues,
- setStorySessionSync, reconcileStorySession, storyStepProgressSseUrl,
+ setStorySessionSync, reconcileStorySession,
getUniverse, getPipelineSeries, listPipelineIssues,
analyzeImport, commitImport, retryImporterIssues, IMPORTER_CONTENT_TYPES,
getProviders, listCatalogIngredientsByIds,
@@ -636,76 +636,6 @@ function ReaderMapView({ readerMap, tickingClock }) {
);
}
-// Kick off a step generate/refine and drive its SSE progress stream. The POST
-// returns immediately; we enable the stream only after it resolves so the run
-// is registered server-side before the EventSource connects (matches the
-// pipeline auto-run). The result content lives in the universe/series records,
-// so callers refetch via `onComplete` rather than reading a payload off the
-// frame. `op` lets a panel show the live phase on the button that triggered the
-// run while leaving sibling buttons merely disabled.
-function useStepStream(sessionId, stepId) {
- const [starting, setStarting] = useState(false);
- const [active, setActive] = useState(false);
- 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);
- // Enable only after the kickoff POST resolves (so the run is registered
- // server-side before the EventSource connects) — see the step runner below.
- const { latest, closed } = usePipelineProgress(storyStepProgressSseUrl, [sessionId, stepId], { enabled: active });
-
- const settle = useCallback(() => {
- setActive(false); setPhase(''); setOp(null);
- runIdRef.current = null;
- const h = handlersRef.current; handlersRef.current = null;
- return h;
- }, []);
-
- // One effect handles every end-of-run path. A terminal frame and the stream's
- // `closed` flag arrive together on completion, so the ordered branches (and
- // settle() flipping `active` false) ensure exactly one of onComplete/onError
- // fires — a separate `closed` effect would double-fire on the same render. The
- // bare-`closed` branch covers a stream that died before any terminal frame
- // (server pruned a fast run, or the connection dropped) so the button unsticks.
- useEffect(() => {
- if (!active) return;
- // 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]);
-
- const start = useCallback(async (nextOp, kickoff, handlers = {}) => {
- if (starting || active) return;
- setStarting(true); setPhase('Starting…'); setOp(nextOp);
- const res = await kickoff().catch((err) => { handlers.onError?.(err); return null; });
- setStarting(false);
- if (!res) { setPhase(''); setOp(null); return; }
- // The kickoff collided with a DIFFERENT in-flight request for this step (a
- // different op, or a refine of a different target/note). That run persists to
- // the same records, so binding THIS button's success handler to its terminal
- // frame would misreport. Don't subscribe — report it and leave the run alone.
- // (A same-work re-click returns alreadyRunning without conflict and re-attaches.)
- if (res.conflict) {
- setPhase(''); setOp(null);
- handlers.onError?.(new Error('Another operation is already running for this step — try again once it finishes.'));
- 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]);
-
- return { start, busy: starting || active, phase, op };
-}
-
function RefineBox({ onRefine, disabled, busy, running, phase }) {
const [feedback, setFeedback] = useState('');
return (
@@ -732,7 +662,7 @@ function RefineBox({ onRefine, disabled, busy, running, phase }) {
}
function StepPanel({ session, universe, series, issues, stepId, locked, onChanged, onSeriesUpdate, onIssuesUpdate, onFlushPending, onUniverseCharRef }) {
- const { start, busy, phase, op } = useStepStream(session.id, stepId);
+ const { start, busy, phase, op } = useStoryStepRun(stepId);
const arc = series?.arc || {};
const isRunning = (which) => busy && op === which;
@@ -930,8 +860,12 @@ function StepCharacters({ session, universe, locked, onChanged, onUniverseCharRe
const cast = universe?.characters || [];
// Universe canon renders, so they resolve the universe's pin ladder (see renderPinLadder).
const { imageCfg } = useImageRenderSettings({ record: universe, target: RENDER_TARGET.UNIVERSE_BIBLE });
- const [refiningId, setRefiningId] = useState(null);
- const { start: startRefine, busy: refineBusy, phase: refinePhase } = useStepStream(session.id, 'characters');
+ // Which character the in-flight refine targets rides on the RUN (`meta`), not
+ // on local state — this panel unmounts when the user clicks another step on
+ // the rail, and the run outlives it (#3905), so local state would come back
+ // empty and the spinner would land on nobody.
+ const { start: startRefine, busy: refineBusy, phase: refinePhase, meta: refineMeta } = useStoryStepRun('characters');
+ const refiningId = refineMeta?.entryId || null;
// Section-local renders now carry a durable `universeRun.entryRef` tag (#1362),
// so the server-side `appendEntryImageRef` hook persists the filename onto the
@@ -971,15 +905,14 @@ function StepCharacters({ session, universe, locked, onChanged, onUniverseCharRe
const refineChar = (entryId) => {
if (refineBusy) return;
- setRefiningId(entryId);
startRefine('refine',
() => refineStoryStep(session.id, 'characters', { entryId }, { silent: true }),
{ onComplete: (frame) => {
- setRefiningId(null);
toast.success(frame.changes?.length ? `Refined — ${frame.changes.length} change(s)` : 'Refined');
onChanged();
},
- onError: (err) => { setRefiningId(null); toast.error(err?.message || 'Refine failed'); } });
+ onError: (err) => toast.error(err?.message || 'Refine failed') },
+ { entryId });
};
return (
@@ -1484,5 +1417,12 @@ function StoryBuilderDetail({ storyId, stepParam }) {
export default function StoryBuilder() {
const { storyId, step } = useParams();
if (!storyId) return <StoryBuilderIndex />;
- return <StoryBuilderDetail storyId={storyId} stepParam={step} />;
+ // The provider sits ABOVE the detail view (which itself swaps out for a
+ // skeleton on reload and for a "not found" notice on a deleted session), so an
+ // in-flight generate/refine survives step navigation AND those swaps (#3905).
+ return (
+ <StoryStepRunProvider sessionId={storyId}>
+ <StoryBuilderDetail storyId={storyId} stepParam={step} />
+ </StoryStepRunProvider>
+ );
}
diff --git a/client/src/pages/StoryBuilder.test.jsx b/client/src/pages/StoryBuilder.test.jsx
index e4e80d8b15..79008725a0 100644
--- a/client/src/pages/StoryBuilder.test.jsx
+++ b/client/src/pages/StoryBuilder.test.jsx
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, waitFor } from '@testing-library/react';
+import { act, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter, Routes, Route } from 'react-router';
+import { MockEventSource, lastEventSource } from '../test/mockEventSource';
const STEPS = [
{ id: 'idea', label: 'Idea', description: 'Capture a starter idea.' },
@@ -648,4 +649,34 @@ describe('StoryBuilder — detail stepper', () => {
// without a full refetch.
await waitFor(() => expect(screen.getByText(/re-review and re-lock/i)).toBeTruthy());
});
+
+ // #3905 — the step panel is keyed by the active step, so clicking the rail
+ // mid-run used to unmount it, sever the SSE stream, and drop the completion
+ // toast. The run now lives above the rail.
+ it('a generate started on one step survives rail navigation and still toasts on completion', async () => {
+ const { fireEvent } = await import('@testing-library/react');
+ MockEventSource.reset();
+ global.EventSource = MockEventSource;
+ api.generateStoryStep.mockResolvedValue({ runId: 'run-1' });
+ api.getPipelineSeries.mockResolvedValue({ id: 's1', arc: { logline: 'AL', summary: 'AS', readerMap: null } });
+ api.getStorySession.mockResolvedValue({
+ 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: '' },
+ });
+ renderAt('/story-builder/stb-1/readerMap');
+ await waitFor(() => expect(screen.getByText('Generate reader map')).toBeTruthy());
+
+ fireEvent.click(screen.getByText('Generate reader map'));
+ await waitFor(() => expect(MockEventSource.instances).toHaveLength(1));
+
+ // Navigate the rail to another step — the panel unmounts.
+ fireEvent.click(screen.getByRole('button', { name: /Characters/ }));
+ await waitFor(() => expect(screen.getByRole('heading', { name: 'Characters' })).toBeTruthy());
+ expect(lastEventSource().closed).toBe(false);
+
+ await act(async () => { lastEventSource().emit({ runId: 'run-1', type: 'complete' }); });
+ await waitFor(() => expect(toastMock.success).toHaveBeenCalledWith('Generated'));
+ delete global.EventSource;
+ });
});