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: keep Story Builder read failures recoverable (#10686)
Adam Eivy44a4d8a7a479
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsxindex 08b1d76140..1afc1f8baf 100644--- a/client/src/pages/StoryBuilder.jsx+++ b/client/src/pages/StoryBuilder.jsx@@ -1045,7 +1045,11 @@ const RUN_OP_LABEL = {function StoryBuilderDetail({ storyId, stepParam }) {const navigate = useNavigate();- const [steps, setSteps] = useState([]);+ const [steps, setSteps] = useState(null);+ const [manifestError, setManifestError] = useState(null);+ const [sessionError, setSessionError] = useState(null);+ const [sessionMissing, setSessionMissing] = useState(false);+ const [readBusy, setReadBusy] = useState(false);const [session, setSession] = useState(null);const [staleSteps, setStaleSteps] = useState([]);const [syncDrift, setSyncDrift] = useState(false);@@ -1061,6 +1065,7 @@ function StoryBuilderDetail({ storyId, stepParam }) {// SLOWER reload wins every setter it reaches last, painting the view with// records fetched before the newer completion landed.const reloadGenRef = useRef(0);+ const manifestGenRef = 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@@ -1081,9 +1086,28 @@ function StoryBuilderDetail({ storyId, stepParam }) {const reload = useCallback(async () => {const gen = ++reloadGenRef.current;const isCurrent = () => reloadGenRef.current === gen;- const s = await getStorySession(storyId, { silent: true }).catch(() => null);+ setReadBusy(true);+ const result = await getStorySession(storyId, { silent: true }).then((record) => ({ record })).catch((error) => {+ if (!isCurrent()) return;+ if (error.status === 404 || error.code === 'NOT_FOUND') {+ setSessionMissing(true);+ setSession(null);+ setSessionError(null);+ } else {+ setSessionError(error.message || 'The story session is unavailable.');+ }+ return null;+ });if (!isCurrent()) return;- if (!s) { setSession(null); setLoading(false); return; }+ const s = result?.record;+ if (!s || typeof s !== 'object' || !s.id) {+ if (result) setSessionError('The story session could not be loaded.');+ setReadBusy(false);+ setLoading(false);+ return;+ }+ setSessionError(null);+ setSessionMissing(false);// `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.@@ -1106,6 +1130,7 @@ function StoryBuilderDetail({ storyId, stepParam }) {if (!isCurrent()) return;setIssues(Array.isArray(iss) ? iss : (iss?.items || []));}+ setReadBusy(false);setLoading(false);}, [storyId, adoptActive]);reloadRef.current = reload;@@ -1144,22 +1169,41 @@ function StoryBuilderDetail({ storyId, stepParam }) {silent: true,});- // Load the step manifest first; gate the loading spinner on BOTH it and the- // session so the detail view never renders with an empty step rail.- useEffect(() => {- let active = true;+ // A manifest failure is distinct from an empty rail. Retry bootstrap without+ // unmounting an already loaded workspace or its draft editors.+ const loadDetail = useCallback(async () => {+ const gen = ++manifestGenRef.current;setLoading(true);- getStoryBuilderSteps({ silent: true })- .then((r) => { if (active) setSteps(r.steps || []); })- .catch(() => {})- .finally(() => { if (active) reload(); });- return () => { active = false; };+ setReadBusy(true);+ const manifest = await getStoryBuilderSteps({ silent: true }).catch((error) => {+ if (manifestGenRef.current === gen) setManifestError(error.message || 'The step manifest is unavailable.');+ return null;+ });+ if (manifestGenRef.current !== gen) return;+ if (!Array.isArray(manifest?.steps) || manifest.steps.length === 0 ||+ manifest.steps.some((step) => !step?.id || !step?.label)) {+ setManifestError((error) => error || 'The step manifest could not be loaded.');+ setReadBusy(false);+ setLoading(false);+ return;+ }+ setSteps(manifest.steps);+ setManifestError(null);+ await reload();}, [reload]);- const stepIds = steps.map((s) => s.id);+ useEffect(() => {+ loadDetail();+ return () => {+ manifestGenRef.current++;+ reloadGenRef.current++;+ };+ }, [loadDetail]);++ const stepIds = (steps || []).map((s) => s.id);const activeStepId = stepIds.includes(stepParam) ? stepParam : (session?.currentStep || 'idea');const activeIdx = stepIds.indexOf(activeStepId);- const activeStep = steps[activeIdx];+ const activeStep = steps?.[activeIdx];const stepState = session?.steps?.[activeStepId] || { status: 'pending', locked: false };const isStale = staleSteps.includes(activeStepId);const nextHintId = useId();@@ -1271,7 +1315,22 @@ function StoryBuilderDetail({ storyId, stepParam }) {toast.success('Re-baselined to this machine');};- if (loading) {+ const readError = manifestError || sessionError;+ const readNotice = readError && (+ <Banner tone="warning" role="alert" size="md" icon={AlertTriangle} className="mb-4">+ <div>+ <p>{manifestError ? 'Couldn’t load story steps' : 'Couldn’t load the story session'}</p>+ <p className="text-sm">{readError}</p>+ {session && <p className="text-sm">Showing the last loaded story. Your edits and running work are preserved.</p>}+ <button type="button" onClick={manifestError ? loadDetail : reload} disabled={readBusy}+ className="mt-2 px-3 py-2 rounded border border-port-border text-port-accent disabled:opacity-50">+ {readBusy ? 'Retrying…' : 'Retry'}+ </button>+ </div>+ </Banner>+ );++ if (loading && !readError) {return (<div className="h-full overflow-y-auto p-4 md:p-6"><div className="max-w-5xl mx-auto">@@ -1280,11 +1339,18 @@ function StoryBuilderDetail({ storyId, stepParam }) {</div>);}- if (!session) return <div className="p-6 text-gray-400">Session not found. <Link to="/story-builder" className="text-port-accent">Back to Story Builder</Link></div>;+ if (sessionMissing) return <div className="p-6 text-gray-400">Session not found. <Link to="/story-builder" className="text-port-accent">Back to Story Builder</Link></div>;++ if (!session || !steps) return (+ <div className="h-full overflow-y-auto p-4 md:p-6">+ <div className="max-w-5xl mx-auto">{readNotice}</div>+ </div>+ );return (<div className="h-full overflow-y-auto p-4 md:p-6"><div className="max-w-5xl mx-auto">+ {readNotice}<header className="mb-4 flex items-start justify-between gap-4 flex-wrap"><div><Link to="/story-builder" className="text-xs text-gray-500 hover:text-port-accent">← All stories</Link>@@ -1488,7 +1554,7 @@ export default function StoryBuilder() {// in-flight generate/refine survives step navigation AND those swaps (#3905).return (<StoryStepRunProvider sessionId={storyId}>- <StoryBuilderDetail storyId={storyId} stepParam={step} />+ <StoryBuilderDetail key={storyId} storyId={storyId} stepParam={step} /></StoryStepRunProvider>);}diff --git a/client/src/pages/StoryBuilder.test.jsx b/client/src/pages/StoryBuilder.test.jsxindex de877a659a..a616c7b565 100644--- a/client/src/pages/StoryBuilder.test.jsx+++ b/client/src/pages/StoryBuilder.test.jsx@@ -1,6 +1,6 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { act, cleanup, render, screen, waitFor } from '@testing-library/react';-import { MemoryRouter, Routes, Route } from 'react-router';+import { MemoryRouter, Routes, Route, Link } from 'react-router';import { MockEventSource, lastEventSource } from '../test/mockEventSource';const STEPS = [@@ -517,6 +517,68 @@ describe('StoryBuilder — index', () => {});describe('StoryBuilder — detail stepper', () => {+ it.each([+ ['a server failure', Object.assign(new Error('Service unavailable'), { status: 503 })],+ ['a network failure', new Error('Network is down')],+ ])('offers a session retry after %s without claiming the story is missing', async (_name, error) => {+ const { fireEvent } = await import('@testing-library/react');+ api.getStorySession.mockRejectedValueOnce(error);+ renderAt('/story-builder/stb-1/idea');++ expect((await screen.findByRole('alert')).textContent).toContain('Couldn’t load the story session');+ expect(screen.queryByText(/Session not found/)).toBeNull();+ expect(screen.queryByRole('heading', { name: 'Idea' })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));++ expect(await screen.findByRole('heading', { name: 'Idea' })).toBeTruthy();+ expect(screen.queryByRole('alert')).toBeNull();+ });++ it('reserves the missing-session fallback for a confirmed 404', async () => {+ api.getStorySession.mockRejectedValueOnce(Object.assign(new Error('Missing record'), { status: 404 }));+ renderAt('/story-builder/stb-1/idea');+ expect(await screen.findByText(/Session not found/)).toBeTruthy();+ expect(screen.queryByRole('alert')).toBeNull();+ });++ it.each([+ ['a failed read', () => api.getStoryBuilderSteps.mockRejectedValueOnce(new Error('Manifest unavailable'))],+ ['an empty manifest', () => api.getStoryBuilderSteps.mockResolvedValueOnce({ steps: [] })],+ ])('gates the workspace on %s and restores navigation on retry', async (_name, setup) => {+ const { fireEvent } = await import('@testing-library/react');+ setup();+ renderAt('/story-builder/stb-1/idea');++ expect((await screen.findByRole('alert')).textContent).toContain('Couldn’t load story steps');+ expect(api.getStorySession).not.toHaveBeenCalled();+ expect(screen.queryByRole('button', { name: /Characters/ })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));++ expect(await screen.findByRole('button', { name: /Characters/ })).toBeTruthy();+ expect(screen.queryByRole('alert')).toBeNull();+ });++ it('ignores a late session response after selecting another story', async () => {+ const { fireEvent } = await import('@testing-library/react');+ let resolveOld;+ api.getStorySession.mockImplementation((id) => id === 'stb-old'+ ? new Promise((resolve) => { resolveOld = resolve; })+ : Promise.resolve({ id, title: 'Current story', currentStep: 'idea', steps: mkSteps() }));+ render(+ <MemoryRouter initialEntries={['/story-builder/stb-old/idea']}>+ <Link to="/story-builder/stb-new/idea">Select another story</Link>+ <Routes><Route path="/story-builder/:storyId/:step" element={<StoryBuilder />} /></Routes>+ </MemoryRouter>,+ );+ await waitFor(() => expect(resolveOld).toBeTypeOf('function'));+ fireEvent.click(screen.getByText('Select another story'));+ expect(await screen.findByRole('heading', { name: 'Current story' })).toBeTruthy();++ await act(async () => { resolveOld({ id: 'stb-old', title: 'Old story', currentStep: 'idea', steps: mkSteps() }); });+ expect(screen.getByRole('heading', { name: 'Current story' })).toBeTruthy();+ expect(screen.queryByText('Old story')).toBeNull();+ });+it('gates the Next button until the active step is locked', async () => {api.getStorySession.mockResolvedValue({id: 'stb-1', title: 'Salt Run', currentStep: 'idea', seedIdea: 'seed',@@ -948,6 +1010,43 @@ describe('StoryBuilder — detail stepper', () => {expect(MockEventSource.instances).toHaveLength(1);});+ it('retains drafts and a resumed run through a failed refresh and successful retry', async () => {+ const { fireEvent } = await import('@testing-library/react');+ const snapshot = liveSession([+ { stepId: 'characters', runId: 'run-3', op: 'backfill', startedAt: '2026-01-01T00:00:00.000Z', phase: null },+ ]);+ api.getStorySession.mockResolvedValue(snapshot);+ renderAt('/story-builder/stb-1/readerMap');+ await waitFor(() => expect(MockEventSource.instances).toHaveLength(1));+ const feedback = screen.getByLabelText('AI refinement feedback');+ fireEvent.change(feedback, { target: { value: 'Keep my unsaved feedback' } });++ // A rejected pointer move triggers the same reload used after completed work.+ api.setStoryCurrentStep.mockRejectedValueOnce(new Error('Could not switch'));+ api.getStorySession.mockRejectedValueOnce(Object.assign(new Error('Temporary read failure'), { status: 503 }));+ fireEvent.click(screen.getByRole('button', { name: /Idea/ }));++ expect((await screen.findByRole('alert')).textContent).toContain('Showing the last loaded story');+ expect(screen.queryByText(/Session not found/)).toBeNull();+ expect(screen.getByLabelText('AI refinement feedback')).toBe(feedback);+ expect(feedback.value).toBe('Keep my unsaved feedback');+ expect(screen.getByRole('status').textContent).toMatch(/Backfilling Characters/);+ expect(lastEventSource().closed).toBe(false);++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ await waitFor(() => expect(screen.queryByRole('alert')).toBeNull());+ expect(screen.getByLabelText('AI refinement feedback')).toBe(feedback);+ expect(feedback.value).toBe('Keep my unsaved feedback');+ expect(MockEventSource.instances).toHaveLength(1);+ expect(api.generateStoryStep).not.toHaveBeenCalled();+ expect(api.refineStoryStep).not.toHaveBeenCalled();++ api.getStorySession.mockResolvedValue(liveSession([]));+ await act(async () => { lastEventSource().emit({ runId: 'run-3', type: 'complete' }); });+ await waitFor(() => expect(toastMock.success).toHaveBeenCalledWith('Backfill finished'));+ expect(feedback.value).toBe('Keep my unsaved feedback');+ });+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 },