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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([story-builder-sse-progress]): stream step generate/refine progress over SSE
[._.]/ Adam Eivya7dfedd24dd4
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 496d0a4d93..bb503044ee 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -40,6 +40,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `usePipelineEditorialProgress` | Series editorial reader-emotion batch SSE. | Editorial Roadmap analysis UI only. || `usePipelineVolumeBeatsProgress` | Volume beat-sheet SSE. | Volume beat-sheet UI only. || `useSeriesEditorial` | Editorial-roadmap aggregate + batch lifecycle (load, re-attach, SSE, start/cancel, reload). | Any view of the editorial roadmap (panel or Reader Map page). |+| `useStoryStepProgress` | Generate/refine SSE for one Story Builder step. | Story Builder step generate/refine progress only. |## Media (annotations, completion, attachments)diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 62b596a6db..0858e1e1d2 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -49,6 +49,7 @@ export * from './usePipelineEditorialProgress.js';export * from './usePipelineVolumeBeatsProgress.js';export * from './useSeriesEditorial.js';export * from './useSseProgress.js';+export * from './useStoryStepProgress.js';export * from './useModelDownloadStatus.js';// === Media (annotations, completion, attachments) ===diff --git a/client/src/hooks/useStoryStepProgress.js b/client/src/hooks/useStoryStepProgress.jsnew file mode 100644index 0000000000..648d9e9efd--- /dev/null+++ b/client/src/hooks/useStoryStepProgress.js@@ -0,0 +1,13 @@+import { storyStepProgressSseUrl } from '../services/api';+import { useSseProgress } from './useSseProgress';++/**+ * Subscribe to the generate/refine SSE stream for one Story Builder step. Frame+ * shapes are documented in server/services/storyBuilderRunner.js. Enable only+ * after the kickoff POST resolves (so the run is registered server-side before+ * the EventSource connects) — see StoryBuilder.jsx's step runner.+ */+export function useStoryStepProgress(sessionId, stepId, { enabled = true } = {}) {+ const url = sessionId && stepId ? storyStepProgressSseUrl(sessionId, stepId) : null;+ return useSseProgress(url, { enabled });+}diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsxindex 8bc4a990b8..357e5e7bbf 100644--- a/client/src/pages/StoryBuilder.jsx+++ b/client/src/pages/StoryBuilder.jsx@@ -14,6 +14,7 @@ import {import toast from '../components/ui/Toast';import Banner from '../components/ui/Banner';import { useLockToggle } from '../hooks/useLockToggle';+import { useStoryStepProgress } from '../hooks/useStoryStepProgress';import {getStoryBuilderSteps, listStorySessions, getStorySession, createStorySession,updateStorySession, setStoryCurrentStep, lockStoryStep, unlockStoryStep,@@ -378,7 +379,57 @@ function ReaderMapView({ readerMap }) {);}-function RefineBox({ onRefine, busy, disabled }) {+// 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);+ const terminalRef = useRef(false);+ const { latest, closed } = useStoryStepProgress(sessionId, stepId, { enabled: active });++ const settle = useCallback(() => {+ setActive(false); setPhase(''); setOp(null);+ const h = handlersRef.current; handlersRef.current = null;+ return h;+ }, []);++ useEffect(() => {+ if (!latest || !active) return;+ if (typeof latest.label === 'string' && latest.label) setPhase(latest.label);+ if (latest.type === 'complete') { terminalRef.current = true; settle()?.onComplete?.(latest); }+ else if (latest.type === 'error') { terminalRef.current = true; settle()?.onError?.(new Error(latest.error || 'Generation failed')); }+ }, [latest, active, settle]);++ // The stream closed without a terminal frame (server pruned a fast run before+ // we attached, or the connection dropped) — recover so the button un-sticks.+ useEffect(() => {+ if (closed && active && !terminalRef.current) {+ settle()?.onError?.(new Error('Lost connection to the generation stream'));+ }+ }, [closed, active, settle]);++ const start = useCallback(async (nextOp, kickoff, handlers = {}) => {+ if (starting || active) return;+ setStarting(true); setPhase('Starting…'); setOp(nextOp); terminalRef.current = false;+ const res = await kickoff().catch((err) => { handlers.onError?.(err); return null; });+ setStarting(false);+ if (!res) { setPhase(''); setOp(null); return; }+ handlersRef.current = 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 (<div className="border-t border-port-border pt-3 mt-3">@@ -387,14 +438,15 @@ function RefineBox({ onRefine, busy, disabled }) {<inputtype="text" value={feedback} onChange={(e) => setFeedback(e.target.value)}placeholder="e.g. make the midpoint reveal land harder"- disabled={disabled}+ disabled={disabled || busy}className="flex-1 bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm disabled:opacity-50"/><buttononClick={() => onRefine(feedback)} disabled={busy || disabled}- className="inline-flex items-center gap-1 bg-port-card border border-port-border hover:border-port-accent px-3 py-1.5 rounded text-sm disabled:opacity-50"+ className="inline-flex items-center gap-1 bg-port-card border border-port-border hover:border-port-accent px-3 py-1.5 rounded text-sm disabled:opacity-50 whitespace-nowrap">- {busy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Wand2 className="w-4 h-4" />} Refine+ {running ? <Loader2 className="w-4 h-4 animate-spin" /> : <Wand2 className="w-4 h-4" />}+ {running ? (phase || 'Refining…') : 'Refine'}</button></div></div>@@ -402,8 +454,9 @@ function RefineBox({ onRefine, busy, disabled }) {}function StepPanel({ session, universe, series, issues, stepId, locked, onChanged }) {- const [busy, setBusy] = useState(false);+ const { start, busy, phase, op } = useStepStream(session.id, stepId);const arc = series?.arc || {};+ const isRunning = (which) => busy && op === which;// True when at least one issue already carries text content — the prerequisite// for backfilling an upstream step (idea / arc) FROM the downstream work.@@ -413,23 +466,17 @@ function StepPanel({ session, universe, series, issues, stepId, locked, onChange.some((sid) => (st[sid]?.input?.trim() || st[sid]?.output?.trim()));}), [issues]);- const runGenerate = async () => {- setBusy(true);- const res = await generateStoryStep(session.id, stepId, {}, { silent: true })- .catch((err) => { toast.error(err?.message || 'Generation failed'); return null; });- setBusy(false);- if (res) { toast.success('Generated'); onChanged(); }- };+ const runGenerate = () => start('generate',+ () => generateStoryStep(session.id, stepId, {}, { silent: true }),+ { onComplete: () => { toast.success('Generated'); onChanged(); },+ onError: (err) => toast.error(err?.message || 'Generation failed') });// Backfill: synthesize this upstream step from the series' existing issue// content instead of from its conventional upstream (start-from-anywhere).- const runBackfill = async () => {- setBusy(true);- const res = await generateStoryStep(session.id, stepId, { fromDownstream: true }, { silent: true })- .catch((err) => { toast.error(err?.message || 'Backfill failed'); return null; });- setBusy(false);- if (res) { toast.success('Backfilled from existing issues'); onChanged(); }- };+ const runBackfill = () => start('backfill',+ () => generateStoryStep(session.id, stepId, { fromDownstream: true }, { silent: true }),+ { onComplete: () => { toast.success('Backfilled from existing issues'); onChanged(); },+ onError: (err) => toast.error(err?.message || 'Backfill failed') });const backfillButton = () => (<button@@ -437,30 +484,28 @@ function StepPanel({ session, universe, series, issues, stepId, locked, onChangetitle="Reverse-engineer this step from the scripts / prose your issues already have"className="inline-flex items-center gap-2 bg-port-card border border-port-border hover:border-port-accent disabled:opacity-50 px-3 py-1.5 rounded text-sm">- {busy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Wand2 className="w-4 h-4" />}- Backfill from existing issues+ {isRunning('backfill') ? <Loader2 className="w-4 h-4 animate-spin" /> : <Wand2 className="w-4 h-4" />}+ {isRunning('backfill') ? (phase || 'Working…') : 'Backfill from existing issues'}</button>);- const runRefine = async (feedback, entryId) => {- setBusy(true);- const res = await refineStoryStep(session.id, stepId, { feedback, entryId }, { silent: true })- .catch((err) => { toast.error(err?.message || 'Refine failed'); return null; });- setBusy(false);- if (res) {- toast.success(res.changes?.length ? `Refined — ${res.changes.length} change(s)` : 'Refined');- onChanged();- }- };+ const runRefine = (feedback, entryId) => start('refine',+ () => refineStoryStep(session.id, stepId, { feedback, entryId }, { silent: true }),+ { onComplete: (frame) => {+ toast.success(frame.changes?.length ? `Refined — ${frame.changes.length} change(s)` : 'Refined');+ onChanged();+ },+ onError: (err) => toast.error(err?.message || 'Refine failed') });// Once a step has generated content, the button becomes "Re-generate" (with a- // refresh icon) so it's clear it has already been run.+ // refresh icon) so it's clear it has already been run. While running, the+ // button surfaces the live SSE phase ("Planning the plot arc…").const genButton = (label = 'Generate with AI', hasContent = false) => (<buttononClick={runGenerate} disabled={busy || locked}className="inline-flex items-center gap-2 bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white px-3 py-1.5 rounded text-sm">- {busy ? <Loader2 className="w-4 h-4 animate-spin" /> : (hasContent ? <RefreshCw className="w-4 h-4" /> : <Sparkles className="w-4 h-4" />)}- {hasContent ? 'Re-generate' : label}+ {isRunning('generate') ? <Loader2 className="w-4 h-4 animate-spin" /> : (hasContent ? <RefreshCw className="w-4 h-4" /> : <Sparkles className="w-4 h-4" />)}+ {isRunning('generate') ? (phase || 'Working…') : (hasContent ? 'Re-generate' : label)}</button>);@@ -499,7 +544,7 @@ function StepPanel({ session, universe, series, issues, stepId, locked, onChange</Link>)}</div>- {!locked && <RefineBox onRefine={(fb) => runRefine(fb)} busy={busy} />}+ {!locked && <RefineBox onRefine={(fb) => runRefine(fb)} busy={busy} running={isRunning('refine')} phase={phase} />}</div>);}@@ -531,7 +576,7 @@ function StepPanel({ session, universe, series, issues, stepId, locked, onChange<div className="space-y-3"><ReaderMapView readerMap={arc.readerMap} />{!locked && genButton('Generate reader map', Boolean(arc.readerMap))}- {!locked && arc.readerMap && <RefineBox onRefine={(fb) => runRefine(fb)} busy={busy} />}+ {!locked && arc.readerMap && <RefineBox onRefine={(fb) => runRefine(fb)} busy={busy} running={isRunning('refine')} phase={phase} />}</div>);}@@ -572,6 +617,7 @@ function StepCharacters({ session, universe, locked, onChanged }) {const [imageCfg, setImageCfg] = useState(PIPELINE_IMAGE_DEFAULTS);const [renderingJobs, setRenderingJobs] = useState({});const [refiningId, setRefiningId] = useState(null);+ const { start: startRefine, busy: refineBusy, phase: refinePhase } = useStepStream(session.id, 'characters');// MediaJobThumb's onFilename effect can fire more than once (StrictMode +// the unstable per-render onComplete arrow); guard so each (char, filename)// append runs exactly once.@@ -621,12 +667,17 @@ function StepCharacters({ session, universe, locked, onChanged }) {onChanged();};- const refineChar = async (entryId) => {+ const refineChar = (entryId) => {+ if (refineBusy) return;setRefiningId(entryId);- const res = await refineStoryStep(session.id, 'characters', { entryId }, { silent: true })- .catch((err) => { toast.error(err?.message || 'Refine failed'); return null; });- setRefiningId(null);- if (res) { toast.success(res.changes?.length ? `Refined — ${res.changes.length} change(s)` : 'Refined'); onChanged(); }+ 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'); } });};return (@@ -655,10 +706,11 @@ function StepCharacters({ session, universe, locked, onChanged }) {</div>{!locked && (<button- onClick={() => refineChar(c.id)} disabled={refiningId === c.id}- className="text-xs inline-flex items-center gap-1 border border-port-border rounded px-2 py-1 hover:border-port-accent disabled:opacity-50 shrink-0"+ onClick={() => refineChar(c.id)} disabled={refineBusy}+ className="text-xs inline-flex items-center gap-1 border border-port-border rounded px-2 py-1 hover:border-port-accent disabled:opacity-50 shrink-0 whitespace-nowrap">- {refiningId === c.id ? <Loader2 className="w-3 h-3 animate-spin" /> : <Wand2 className="w-3 h-3" />} Refine+ {refiningId === c.id ? <Loader2 className="w-3 h-3 animate-spin" /> : <Wand2 className="w-3 h-3" />}+ {refiningId === c.id ? (refinePhase || 'Refining…') : 'Refine'}</button>)}</div>diff --git a/client/src/pages/StoryBuilder.test.jsx b/client/src/pages/StoryBuilder.test.jsxindex 67a4ce79aa..f924e9fe12 100644--- a/client/src/pages/StoryBuilder.test.jsx+++ b/client/src/pages/StoryBuilder.test.jsx@@ -27,6 +27,7 @@ const api = vi.hoisted(() => ({unlockStoryStep: vi.fn(),generateStoryStep: vi.fn(),refineStoryStep: vi.fn(),+ storyStepProgressSseUrl: vi.fn((id, stepId) => `/api/story-builder/${id}/steps/${stepId}/progress`),setStoryIssueLock: vi.fn(),getUniverse: vi.fn(),getPipelineSeries: vi.fn(),diff --git a/client/src/services/apiStoryBuilder.js b/client/src/services/apiStoryBuilder.jsindex 2db9165161..b817076527 100644--- a/client/src/services/apiStoryBuilder.js+++ b/client/src/services/apiStoryBuilder.js@@ -36,6 +36,10 @@ export const lockStoryStep = (id, stepId, options = {}) =>export const unlockStoryStep = (id, stepId, options = {}) =>request(`/story-builder/${id}/steps/${stepId}/unlock`, { method: 'POST', ...options });+// generate / refine kick off a background run and return { runId, alreadyRunning,+// sseUrl }. Subscribe to progress via storyStepProgressSseUrl (see+// hooks/useStoryStepProgress.js); the result lands on the stream's `complete`+// frame and the persisted content is read back by refetching the session view.export const generateStoryStep = (id, stepId, payload = {}, options = {}) =>request(`/story-builder/${id}/steps/${stepId}/generate`, {method: 'POST',@@ -50,6 +54,11 @@ export const refineStoryStep = (id, stepId, payload = {}, options = {}) =>...options,});+// Deterministic SSE URL for a step's generate/refine progress stream. Mirrors+// pipelineAutoRunSseUrl — derived from ids, not the kickoff response.+export const storyStepProgressSseUrl = (id, stepId) =>+ `/api/story-builder/${encodeURIComponent(id)}/steps/${encodeURIComponent(stepId)}/progress`;+export const generateStoryIssues = (id, payload = {}, options = {}) =>request(`/story-builder/${id}/issues/generate`, {method: 'POST',diff --git a/server/routes/storyBuilder.js b/server/routes/storyBuilder.jsindex c5290ecd53..f42db527aa 100644--- a/server/routes/storyBuilder.js+++ b/server/routes/storyBuilder.js@@ -12,6 +12,7 @@ import {import { STEPS, isValidStepId } from '../lib/storyBuilderSteps.js';import {listStorySessions,+ getStorySession,getStorySessionView,createStorySession,updateStorySession,@@ -20,12 +21,11 @@ import {unlockStep,setCurrentStep,setIssueLock,- generateStep,- refineStep,generateIssuesFromArc,ERR_NOT_FOUND,ERR_VALIDATION,} from '../services/storyBuilder.js';+import { startStepRun, attachClient } from '../services/storyBuilderRunner.js';const router = Router();@@ -98,20 +98,36 @@ router.post('/:id/steps/:stepId/unlock', asyncHandler(async (req, res) => {res.json(updated);}));+// Generate / refine kick off in the background and stream progress over SSE —+// a long arc-overview would otherwise block the request with only a spinner.+// The POST returns immediately with the runId + sseUrl; the result lands on the+// progress stream and the client refetches the session view on `complete`.+// Validate the session exists up front so a bad id returns 404 here rather than+// surfacing as a background error after a 200.router.post('/:id/steps/:stepId/generate', asyncHandler(async (req, res) => {assertStep(req.params.stepId);const input = validateRequest(storyStepGenerateSchema, req.body || {});- const result = await generateStep(req.params.id, req.params.stepId, input).catch((err) => { throw mapServiceError(err); });- res.json(result);+ await getStorySession(req.params.id).catch((err) => { throw mapServiceError(err); });+ const run = startStepRun(req.params.id, req.params.stepId, { op: 'generate', ...input });+ res.json({ ...run, sseUrl: `/api/story-builder/${req.params.id}/steps/${req.params.stepId}/progress` });}));router.post('/:id/steps/:stepId/refine', asyncHandler(async (req, res) => {assertStep(req.params.stepId);const input = validateRequest(storyStepRefineSchema, req.body || {});- const result = await refineStep(req.params.id, req.params.stepId, input).catch((err) => { throw mapServiceError(err); });- res.json(result);+ await getStorySession(req.params.id).catch((err) => { throw mapServiceError(err); });+ const run = startStepRun(req.params.id, req.params.stepId, { op: 'refine', ...input });+ res.json({ ...run, sseUrl: `/api/story-builder/${req.params.id}/steps/${req.params.stepId}/progress` });}));+router.get('/:id/steps/:stepId/progress', (req, res) => {+ assertStep(req.params.stepId);+ const attached = attachClient(req.params.id, req.params.stepId, res);+ if (!attached) {+ res.status(404).json({ error: 'No active run for this step' });+ }+});+// ── Issues step: seed issues from the arc + per-issue locks ──────────────────// Generate the per-episode breakdown for the linked series' seasons anddiff --git a/server/routes/storyBuilder.test.js b/server/routes/storyBuilder.test.jsindex a96cc55a9c..e6912fa4a6 100644--- a/server/routes/storyBuilder.test.js+++ b/server/routes/storyBuilder.test.js@@ -23,6 +23,15 @@ const svc = {};vi.mock('../services/storyBuilder.js', () => svc);+// generate/refine kick off through the SSE runner; the route returns the runId ++// sseUrl and the work streams in the background. Stub the runner so the route+// test verifies dispatch + the kickoff response shape, not the run lifecycle.+const runner = {+ startStepRun: vi.fn(() => ({ runId: 'run-1', alreadyRunning: false })),+ attachClient: vi.fn(() => true),+};+vi.mock('../services/storyBuilderRunner.js', () => runner);+const { default: storyBuilderRoutes } = await import('./storyBuilder.js');const makeApp = () => {@@ -98,13 +107,38 @@ describe('step state machine routes', () => {expect(svc.setCurrentStep).toHaveBeenCalledWith('stb-1', 'universeAesthetic');});- it('generates and refines a step', async () => {+ it('kicks off a generate run and returns the runId + sseUrl', async () => {const g = await request(makeApp()).post('/api/story-builder/stb-1/steps/readerMap/generate').send({});expect(g.status).toBe(200);- expect(svc.generateStep).toHaveBeenCalledWith('stb-1', 'readerMap', expect.any(Object));+ expect(runner.startStepRun).toHaveBeenCalledWith('stb-1', 'readerMap', expect.objectContaining({ op: 'generate' }));+ expect(g.body.runId).toBe('run-1');+ expect(g.body.sseUrl).toBe('/api/story-builder/stb-1/steps/readerMap/progress');+ });++ it('kicks off a refine run with the validated feedback', async () => {const r = await request(makeApp()).post('/api/story-builder/stb-1/steps/readerMap/refine').send({ feedback: 'tighter' });expect(r.status).toBe(200);- expect(r.body.changes).toEqual(['c']);+ expect(runner.startStepRun).toHaveBeenCalledWith('stb-1', 'readerMap', expect.objectContaining({ op: 'refine', feedback: 'tighter' }));+ expect(r.body.sseUrl).toBe('/api/story-builder/stb-1/steps/readerMap/progress');+ });++ it('404s a kickoff for a missing session before starting a run', async () => {+ svc.getStorySession.mockRejectedValueOnce(Object.assign(new Error('nope'), { code: svc.ERR_NOT_FOUND }));+ const res = await request(makeApp()).post('/api/story-builder/stb-x/steps/readerMap/generate').send({});+ expect(res.status).toBe(404);+ expect(runner.startStepRun).not.toHaveBeenCalled();+ });++ it('rejects an unknown step id on the progress stream with 400', async () => {+ const res = await request(makeApp()).get('/api/story-builder/stb-1/steps/bogus/progress');+ expect(res.status).toBe(400);+ expect(runner.attachClient).not.toHaveBeenCalled();+ });++ it('404s the progress stream when no run is active', async () => {+ runner.attachClient.mockReturnValueOnce(false);+ const res = await request(makeApp()).get('/api/story-builder/stb-1/steps/readerMap/progress');+ expect(res.status).toBe(404);});});diff --git a/server/services/storyBuilder.js b/server/services/storyBuilder.jsindex cd76d9a615..d2619b87ae 100644--- a/server/services/storyBuilder.js+++ b/server/services/storyBuilder.js@@ -522,10 +522,14 @@ export async function generateStep(id, stepId, options = {}) {// selection at the top of the Story Builder drives every operation.const reqProviderId = options.providerId || session.llm?.provider || undefined;const reqModel = options.model || session.llm?.model || undefined;+ // Best-effort phase emitter for the SSE runner; a no-op on the synchronous+ // path (no onProgress passed) so this call stays byte-for-byte unchanged there.+ const emit = (label, phase) => options.onProgress?.({ label, phase });if (stepId === 'idea') {// Backfill: reverse-engineer the idea from existing issue content when the// user started downstream. Rendered only when present, so the forward path// (seed-only) is byte-for-byte unchanged.+ if (options.fromDownstream) emit('Reading existing issues…', 'collect');const sourceMaterial = options.fromDownstream ? await collectIssueSourceText(session.seriesId) : '';if (options.fromDownstream && !sourceMaterial) {throw makeErr(@@ -533,6 +537,7 @@ export async function generateStep(id, stepId, options = {}) {ERR_VALIDATION,);}+ emit('Expanding the idea…', 'generate');const { content, runId, providerId, model } = await runStagedLLM('story-builder-idea-expand',{ universeName: session.title, seedIdea: session.seedIdea || '', sourceMaterial },@@ -540,6 +545,7 @@ export async function generateStep(id, stepId, options = {}) {);const expandedIdea = isStr(content?.expandedIdea) ? content.expandedIdea.trim() : '';const logline = isStr(content?.logline) ? content.logline.trim() : '';+ emit('Saving…', 'persist');// Seed the universe starter + series premise/logline from the expansion.// Honor downstream lock keys: locking the universeAesthetic step sets// universe.locked.{logline,...} via applyUnderlyingLock, but@@ -560,6 +566,7 @@ export async function generateStep(id, stepId, options = {}) {if (stepId === 'universeAesthetic') {if (!session.universeId) throw makeErr('No universe linked', ERR_VALIDATION);const universe = await getUniverse(session.universeId);+ emit('Expanding the aesthetic…', 'generate');const expanded = await expandWorldTemplate({starterPrompt: universe.starterPrompt || session.seedIdea || universe.name,influences: universe.influences,@@ -570,6 +577,7 @@ export async function generateStep(id, stepId, options = {}) {providerId: reqProviderId,model: reqModel,});+ emit('Saving…', 'persist');const updated = await updateUniverse(session.universeId, {logline: expanded.logline,premise: expanded.premise,@@ -585,6 +593,7 @@ export async function generateStep(id, stepId, options = {}) {// Backfill: extract the arc + seasons from the issues that already exist// (the user drafted scripts/prose first). Reuses the importer's// arc-extraction prompt via arcPlanner.generateArcFromSource.+ emit('Reading existing issues…', 'collect');const sourceText = await collectIssueSourceText(session.seriesId);if (!sourceText) {throw makeErr(@@ -592,10 +601,12 @@ export async function generateStep(id, stepId, options = {}) {ERR_VALIDATION,);}+ emit('Extracting the plot arc…', 'generate');arcGenResult = await generateArcFromSource(session.seriesId, {sourceText, providerOverride: reqProviderId, modelOverride: reqModel,});} else {+ emit('Planning the plot arc…', 'generate');arcGenResult = await generateArcOverview(session.seriesId, {providerOverride: reqProviderId, modelOverride: reqModel,});@@ -609,15 +620,18 @@ export async function generateStep(id, stepId, options = {}) {// Canvas's regenerate uses. A plain updateSeries({ arc, seasons }) would// bypass mergeArcWithLocks / mergeSeasonsWithLocks / buildSeasonRemap and// silently wipe locked seasons and orphan their issues.+ emit('Saving seasons…', 'persist');const series = await getSeries(session.seriesId);const { series: updated } = await commitSeasonsWithRemap(series, { arc, seasons });return { result: updated, runId, providerId, model };}if (stepId === 'readerMap') {if (!session.seriesId) throw makeErr('No series linked', ERR_VALIDATION);+ emit('Mapping reader emotion…', 'generate');const { readerMap, runId, providerId, model } = await generateReaderMap(session.seriesId, {providerOverride: reqProviderId, modelOverride: reqModel,});+ emit('Saving…', 'persist');const series = await getSeries(session.seriesId);const updated = await updateSeries(session.seriesId, { arc: { ...(series.arc || {}), readerMap } });return { result: updated, runId, providerId, model };@@ -625,14 +639,16 @@ export async function generateStep(id, stepId, options = {}) {throw makeErr(`Generate is not supported for step "${stepId}"`, ERR_VALIDATION);}-export async function refineStep(id, stepId, { feedback, entryId, providerId, model } = {}) {+export async function refineStep(id, stepId, { feedback, entryId, providerId, model, onProgress } = {}) {const session = await getStorySession(id);// Same fallback as generateStep: explicit override → session picker choice.const reqProviderId = providerId || session.llm?.provider || undefined;const reqModel = model || session.llm?.model || undefined;+ const emit = (label, phase) => onProgress?.({ label, phase });if (stepId === 'universeAesthetic') {if (!session.universeId) throw makeErr('No universe linked', ERR_VALIDATION);const universe = await getUniverse(session.universeId);+ emit('Refining the aesthetic…', 'generate');const refined = await refineWorldPrompts({starterPrompt: universe.starterPrompt || universe.name,logline: universe.logline,@@ -644,6 +660,7 @@ export async function refineStep(id, stepId, { feedback, entryId, providerId, moproviderId: reqProviderId,model: reqModel,});+ emit('Saving…', 'persist');const updated = await updateUniverse(session.universeId, {logline: refined.logline,premise: refined.premise,@@ -654,7 +671,9 @@ export async function refineStep(id, stepId, { feedback, entryId, providerId, mo}if (stepId === 'readerMap') {if (!session.seriesId) throw makeErr('No series linked', ERR_VALIDATION);+ emit('Refining the reader map…', 'generate');const { readerMap, changes, rationale, runId } = await refineReaderMap(session.seriesId, feedback, { providerId: reqProviderId, model: reqModel });+ emit('Saving…', 'persist');const series = await getSeries(session.seriesId);const updated = await updateSeries(session.seriesId, { arc: { ...(series.arc || {}), readerMap } });return { result: updated, changes, rationale, runId };@@ -662,6 +681,7 @@ export async function refineStep(id, stepId, { feedback, entryId, providerId, moif (stepId === 'characters') {if (!session.universeId) throw makeErr('No universe linked', ERR_VALIDATION);if (!isStr(entryId)) throw makeErr('entryId is required to refine a character', ERR_VALIDATION);+ emit('Refining the character…', 'generate');const out = await refineUniverseCharacter(session.universeId, entryId, { providerId: reqProviderId, model: reqModel });return { result: out.universe, changes: out.changes || [], rationale: out.rationale || '' };}diff --git a/server/services/storyBuilderRunner.js b/server/services/storyBuilderRunner.jsnew file mode 100644index 0000000000..9305758a4e--- /dev/null+++ b/server/services/storyBuilderRunner.js@@ -0,0 +1,122 @@+/**+ * Story Builder — SSE runner for step generate / refine.+ *+ * `generateStep` / `refineStep` in storyBuilder.js are a single LLM call plus a+ * record persist. Run synchronously they block the HTTP request — a long+ * arc-overview leaves the button spinning with no signal. This runner mirrors+ * the pipeline auto-runner (server/services/pipeline/autoRunner.js): the POST+ * kicks the work off in the background and returns immediately; progress and+ * the terminal result land on attached SSE clients.+ *+ * SSE: a single in-memory `runs` map keyed by `${sessionId}::${stepId}` so two+ * different steps can stream concurrently while a second click on the same step+ * coalesces onto the in-flight run. Late-connecting clients receive the last+ * broadcast frame via attachSseClient's replay grace window in lib/sseUtils.js.+ *+ * Frame shapes (consumed by client/src/hooks/useStoryStepProgress.js):+ * { type: 'start', runId, stepId, op }+ * { type: 'progress', label, phase } // phase labels during the run+ * { type: 'complete', runId, stepId, op, changes, rationale, providerId, model }+ * { type: 'error', runId, stepId, op, error }+ * The completed content lives in the universe/series records — the client+ * refetches the session view on `complete` rather than carrying the payload in+ * 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 { generateStep, refineStep } from './storyBuilder.js';++// runs: Map<runKey, { runId, clients[], lastPayload, startedAt, stepId, op }>+const runs = new Map();++const runKey = (sessionId, stepId) => `${sessionId}::${stepId}`;++export function isStepRunActive(sessionId, stepId) {+ return runs.has(runKey(sessionId, stepId));+}++export function attachClient(sessionId, stepId, res) {+ return attachSseClient(runs, runKey(sessionId, stepId), res);+}++function broadcast(key, payload) {+ const run = runs.get(key);+ if (!run) return;+ broadcastSse(run, payload);+}++/**+ * Kick off a step generate (op: 'generate') or refine (op: 'refine') for a+ * session. Returns the runId immediately; progress lands via SSE. Re-calling+ * while a run is in flight for the same step resolves to the existing runId.+ *+ * `options` is forwarded verbatim to generateStep/refineStep (providerId,+ * model, fromDownstream for generate; feedback, entryId, providerId, model for+ * refine) plus an `onProgress` callback the conductor uses to emit phase frames.+ */+export function startStepRun(sessionId, stepId, { op = 'generate', ...options } = {}) {+ const key = runKey(sessionId, stepId);+ if (runs.has(key)) return { runId: runs.get(key).runId, alreadyRunning: true };++ const runId = randomUUID();+ const record = {+ runId,+ clients: [],+ lastPayload: null,+ startedAt: new Date().toISOString(),+ stepId,+ op,+ };+ 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 () => {+ broadcast(key, { 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 {+ broadcast(key, { type: 'progress', ...frame });+ } catch (err) {+ console.error(`❌ story-builder progress emit failed: ${err?.message || err}`);+ }+ };++ try {+ const result = op === 'refine'+ ? await refineStep(sessionId, stepId, { ...options, onProgress })+ : await generateStep(sessionId, stepId, { ...options, onProgress });+ broadcast(key, {+ type: 'complete',+ runId,+ stepId,+ op,+ // Surface the refine attribution the client toast + UI read; generate+ // returns these only on some steps, so guard each.+ changes: Array.isArray(result?.changes) ? result.changes : undefined,+ rationale: typeof result?.rationale === 'string' ? result.rationale : undefined,+ providerId: result?.providerId,+ model: result?.model,+ completedAt: new Date().toISOString(),+ });+ console.log(`✅ story-builder ${op} complete — session=${sessionId.slice(0, 8)} step=${stepId} runId=${runId.slice(0, 8)}`);+ } catch (err) {+ 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 {+ // 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);+ }+ })();++ return { runId, alreadyRunning: false };+}++// Export internals for tests.+export const __testing = { runs, runKey };diff --git a/server/services/storyBuilderRunner.test.js b/server/services/storyBuilderRunner.test.jsnew file mode 100644index 0000000000..46ffa7e15f--- /dev/null+++ b/server/services/storyBuilderRunner.test.js@@ -0,0 +1,95 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Stub the conductor so the runner test exercises the SSE lifecycle, not the+// LLM/record work.+const conductor = {+ generateStep: vi.fn(),+ refineStep: vi.fn(),+};+vi.mock('./storyBuilder.js', () => conductor);++const { startStepRun, isStepRunActive, attachClient, __testing } = await import('./storyBuilderRunner.js');++// Minimal SSE `res` double: captures written frames + close.+function fakeRes() {+ const writes = [];+ return {+ writes,+ frames: () => writes+ .filter((w) => w.startsWith('data: '))+ .map((w) => JSON.parse(w.slice(6).trim())),+ writeHead: vi.fn(),+ write: vi.fn((s) => writes.push(s)),+ end: vi.fn(),+ req: { on: vi.fn() },+ };+}++const flush = () => new Promise((r) => setTimeout(r, 0));++beforeEach(() => {+ vi.clearAllMocks();+ __testing.runs.clear();+});++describe('storyBuilderRunner', () => {+ it('streams start → progress → complete and clears the run', async () => {+ conductor.generateStep.mockImplementation(async (_id, _step, { onProgress }) => {+ // Yield first so the client attaches (after the kickoff returns) before+ // the progress/complete frames broadcast — mirrors the real HTTP flow+ // where the GET /progress lands after the POST and the `start` frame.+ await Promise.resolve();+ onProgress?.({ label: 'Planning…', phase: 'generate' });+ await Promise.resolve();+ return { providerId: 'p1', model: 'm1' };+ });++ const { runId, alreadyRunning } = startStepRun('stb-1', 'plotArc', { op: 'generate', providerId: 'p1' });+ expect(alreadyRunning).toBe(false);+ expect(isStepRunActive('stb-1', 'plotArc')).toBe(true);++ const res = fakeRes();+ expect(attachClient('stb-1', 'plotArc', res)).toBe(true);++ await flush();+ const types = res.frames().map((f) => f.type);+ expect(types).toContain('start');+ expect(types).toContain('progress');+ expect(types).toContain('complete');+ const complete = res.frames().find((f) => f.type === 'complete');+ expect(complete.runId).toBe(runId);+ expect(complete.providerId).toBe('p1');+ // generateStep was called with the forwarded option (op stripped off).+ expect(conductor.generateStep).toHaveBeenCalledWith('stb-1', 'plotArc', expect.objectContaining({ providerId: 'p1' }));+ expect(conductor.generateStep.mock.calls[0][2].op).toBeUndefined();+ });++ it('coalesces a second start for the same step onto the in-flight run', async () => {+ let resolve;+ conductor.generateStep.mockImplementation(() => new Promise((r) => { resolve = () => r({}); }));+ const first = startStepRun('stb-1', 'idea', { op: 'generate' });+ const second = startStepRun('stb-1', 'idea', { op: 'generate' });+ expect(second.alreadyRunning).toBe(true);+ expect(second.runId).toBe(first.runId);+ expect(conductor.generateStep).toHaveBeenCalledTimes(1);+ resolve();+ await flush();+ });++ it('surfaces a refine failure as an error frame', async () => {+ conductor.refineStep.mockRejectedValue(new Error('LLM down'));+ startStepRun('stb-2', 'universeAesthetic', { op: 'refine', feedback: 'tighter' });+ const res = fakeRes();+ attachClient('stb-2', 'universeAesthetic', res);+ await flush();+ const err = res.frames().find((f) => f.type === 'error');+ expect(err).toBeTruthy();+ expect(err.error).toContain('LLM down');+ expect(conductor.refineStep).toHaveBeenCalledWith('stb-2', 'universeAesthetic', expect.objectContaining({ feedback: 'tighter' }));+ });++ it('attachClient returns false when no run is active for the step', () => {+ const res = fakeRes();+ expect(attachClient('stb-none', 'idea', res)).toBe(false);+ });+});