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
fix: stamp Story Builder runs with their session and settle the dead-end kickoff paths (#3905)
[._.]/ Adam Eivy91954793c35e
diff --git a/client/src/hooks/useStoryStepRuns.jsx b/client/src/hooks/useStoryStepRuns.jsxindex 91950ed024..c91bcfc8a5 100644--- a/client/src/hooks/useStoryStepRuns.jsx+++ b/client/src/hooks/useStoryStepRuns.jsx@@ -50,7 +50,14 @@ function StepRunStream({ sessionId, stepId, runId, onPhase, onEnd }) {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).+ // Each slot records the session it belongs to. The reset effect below can only+ // run AFTER the render in which `sessionId` changed, so without this stamp the+ // old session's slots would render one frame against the NEW id — opening an+ // EventSource on a URL that pairs another story with this step.const [runs, setRuns] = useState({});+ const ownRuns = Object.fromEntries(+ Object.entries(runs).filter(([, run]) => run.sessionId === sessionId),+ );// 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.@@ -113,32 +120,45 @@ export function StoryStepRunProvider({ sessionId, children }) {// 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;+ if (ownRuns[stepId] || startedRef.current.has(stepId)) return;const startedUnder = sessionRef.current;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; });+ setRuns((prev) => ({ ...prev, [stepId]: { sessionId: startedUnder, runId: null, op, phase: 'Starting…', meta } }));+ const res = await kickoff().then((r) => ({ r }), (err) => ({ err }));// The user opened a different story while the POST was in flight. The run- // is the old session's; the effect above already dropped its slot.+ // belongs to the story they left — the reset effect already dropped its+ // slot, and reporting its outcome into the story now on screen would be a+ // toast about work the user can no longer see.if (sessionRef.current !== startedUnder) return;- if (!res) { clear(stepId); return; }+ if (res.err || !res.r) {+ clear(stepId);+ if (res.err) handlers.onError?.(res.err);+ 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) {+ if (res.r.conflict) {clear(stepId);handlers.onError?.(new Error('Another operation is already running for this step — try again once it finishes.'));return;}+ // A 2xx with no run id has nothing to subscribe to. Settling here keeps the+ // slot from sticking "busy" forever with no stream that could ever clear it.+ if (!res.r.runId) {+ clear(stepId);+ handlers.onError?.(new Error('The server did not return a run to track — try again.'));+ return;+ }handlersRef.current[stepId] = handlers;- setRuns((prev) => ({ ...prev, [stepId]: { runId: res.runId, op, phase: 'Starting…', meta } }));- }, [runs, clear]);+ setRuns((prev) => ({ ...prev, [stepId]: { sessionId: startedUnder, runId: res.r.runId, op, phase: 'Starting…', meta } }));+ }, [ownRuns, clear]);return (- <StoryStepRunContext.Provider value={{ runs, start }}>- {Object.entries(runs).map(([stepId, run]) => (run.runId ? (+ <StoryStepRunContext.Provider value={{ runs: ownRuns, start }}>+ {Object.entries(ownRuns).map(([stepId, run]) => (run.runId ? (<StepRunStreamkey={`${stepId}:${run.runId}`}sessionId={sessionId}diff --git a/client/src/hooks/useStoryStepRuns.test.jsx b/client/src/hooks/useStoryStepRuns.test.jsxindex 9b74818a6f..098f37640d 100644--- a/client/src/hooks/useStoryStepRuns.test.jsx+++ b/client/src/hooks/useStoryStepRuns.test.jsx@@ -136,6 +136,64 @@ describe('useStoryStepRuns', () => {expect(screen.getByTestId('state-plotArc').textContent).toBe('idle');});+ it('settles instead of sticking busy when the kickoff returns no run id', async () => {+ const onError = vi.fn();+ const kickoff = vi.fn().mockResolvedValue({});+ 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(/did not return a run/);+ expect(MockEventSource.instances).toHaveLength(0);+ expect(screen.getByTestId('state-plotArc').textContent).toBe('idle');+ });++ // A slot stamped with the story it was started under: the reset effect only+ // runs AFTER the render in which sessionId changed, so an unstamped slot would+ // render one frame against the new id and open a stream on the wrong story.+ it('never subscribes another story to a run started on the previous one', async () => {+ const onComplete = vi.fn();+ let resolveKickoff;+ const kickoff = vi.fn(() => new Promise((res) => { resolveKickoff = res; }));+ const { rerender } = render(+ <StoryStepRunProvider sessionId="s1">+ <StepPanel stepId="plotArc" kickoff={kickoff} onComplete={onComplete} onError={vi.fn()} />+ </StoryStepRunProvider>,+ );+ click('run-plotArc');++ rerender(+ <StoryStepRunProvider sessionId="s2">+ <StepPanel stepId="plotArc" kickoff={kickoff} onComplete={onComplete} onError={vi.fn()} />+ </StoryStepRunProvider>,+ );+ await act(async () => { resolveKickoff({ runId: 'r1' }); });++ expect(MockEventSource.instances).toHaveLength(0);+ expect(onComplete).not.toHaveBeenCalled();+ expect(screen.getByTestId('state-plotArc').textContent).toBe('idle');+ });++ it('never re-points a live run\'s stream at a newly-opened story', async () => {+ const kickoff = vi.fn().mockResolvedValue({ runId: 'r1' });+ const { rerender } = render(+ <StoryStepRunProvider sessionId="s1">+ <StepPanel stepId="plotArc" kickoff={kickoff} onComplete={vi.fn()} onError={vi.fn()} />+ </StoryStepRunProvider>,+ );+ click('run-plotArc');+ await waitFor(() => expect(MockEventSource.instances).toHaveLength(1));++ rerender(+ <StoryStepRunProvider sessionId="s2">+ <StepPanel stepId="plotArc" kickoff={kickoff} onComplete={vi.fn()} onError={vi.fn()} />+ </StoryStepRunProvider>,+ );+ // The run belongs to s1; no stream may ever open against s2's URL.+ expect(MockEventSource.instances.filter((es) => es.url.includes('/s2/'))).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() }} />);diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsxindex da5b3ea798..bb166b7038 100644--- a/client/src/pages/StoryBuilder.jsx+++ b/client/src/pages/StoryBuilder.jsx@@ -1,4 +1,4 @@-import { useState, useEffect, useCallback, useMemo } from 'react';+import { useState, useEffect, useCallback, useMemo, useRef } from 'react';import { useParams, useNavigate, useSearchParams, useLocation, Link } from 'react-router';import PageSkeleton from '../components/ui/PageSkeleton';import { filterSelectableModels } from '../utils/providers';@@ -1074,8 +1074,18 @@ function StoryBuilderDetail({ storyId, stepParam }) {const [loading, setLoading] = useState(true);const [syncBusy, setSyncBusy] = useState(false);+ // Runs on different steps can now finish while the user is elsewhere in the+ // wizard (#3905), so two `reload()`s can be in flight at once — and this one+ // awaits three round trips before it writes. Without a generation stamp the+ // SLOWER reload wins every setter it reaches last, painting the view with+ // records fetched before the newer completion landed.+ const reloadGenRef = useRef(0);+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);setStaleSteps(s.staleSteps || []);@@ -1086,10 +1096,12 @@ function StoryBuilderDetail({ storyId, stepParam }) {s.universeId ? getUniverse(s.universeId, { silent: true }).catch(() => null) : Promise.resolve(null),s.seriesId ? getPipelineSeries(s.seriesId, { silent: true }).catch(() => null) : Promise.resolve(null),]);+ if (!isCurrent()) return;setUniverse(u);setSeries(ser);if (s.seriesId) {const iss = await listPipelineIssues(s.seriesId, { silent: true }).catch(() => []);+ if (!isCurrent()) return;setIssues(Array.isArray(iss) ? iss : (iss?.items || []));}setLoading(false);