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 stage actions above scrolling work (#10694)

Adam Eivye8f9c9f3ca37
diff --git a/client/src/pages/StoryBuilder.browser.test.js b/client/src/pages/StoryBuilder.browser.test.js
new file mode 100644
index 0000000000..97efe98ec8
--- /dev/null
+++ b/client/src/pages/StoryBuilder.browser.test.js
@@ -0,0 +1,140 @@
+// @vitest-environment node
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { createServer } from 'vite';
+import react from '@vitejs/plugin-react';
+import { chromium } from 'playwright-core';
+import { BROWSER_FIXTURE_STARTUP_MS, startBrowserFixture } from '../test/browserFixture.js';
+
+const chrome = [process.env.CHROME_PATH, chromium.executablePath(),
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser',
+].find(path => path && existsSync(path));
+const steps = ['idea', 'universeAesthetic', 'plotArc', 'readerMap', 'characters', 'issues', 'production']
+ .map((id, index) => ({ id, label: ['Idea', 'Universe Aesthetic', 'Plot Arc', 'Reader Map', 'Characters', 'Issues', 'Production'][index], description: 'Review the current work.' }));
+
+// Browser geometry uniquely proves that long stage work cannot displace the
+// action and that sidebar/zoom/narrow-container widths drive the same navigator.
+describe.skipIf(!chrome)('Story Builder persistent stage workspace', () => {
+ let fixture;
+ beforeAll(async () => {
+ fixture = await startBrowserFixture({ name: 'story-workspace', createServer, chromium,
+ launchOptions: { executablePath: chrome }, viteConfig: temp => ({
+ configFile: false,
+ root: fileURLToPath(new URL('../..', import.meta.url)),
+ cacheDir: join(temp, 'vite-cache'),
+ optimizeDeps: { entries: ['src/pages/StoryBuilder.jsx'], include: ['react', 'react-dom/client', 'react-router'] },
+ plugins: [react(), {
+ name: 'story-workspace-fixture',
+ resolveId(id) { if (id === '/story-fixture.jsx') return '\0story-fixture.jsx'; },
+ load(id) {
+ if (id !== '\0story-fixture.jsx') return;
+ return `import React from 'react';
+ import { createRoot } from 'react-dom/client';
+ import { MemoryRouter, Routes, Route } from 'react-router';
+ import StoryBuilder from '/src/pages/StoryBuilder.jsx';
+ import '/src/index.css';
+ const h = React.createElement;
+ createRoot(document.getElementById('root')).render(
+ h(MemoryRouter, { initialEntries: ['/story-builder/example/' + (new URLSearchParams(location.search).get('step') || 'idea')] },
+ h(Routes, null, h(Route, { path: '/story-builder/:storyId/:step', element: h(StoryBuilder) }))));`;
+ },
+ configureServer(vite) {
+ vite.middlewares.use('/story-test', async (_req, res) => {
+ res.setHeader('Content-Type', 'text/html');
+ res.end(await vite.transformIndexHtml('/story-test',
+ '<style>html,body{height:100%;margin:0}#shell{display:flex;height:100%}#sidebar{flex:0 0 var(--sidebar,0px)}#root{flex:1;min-width:0;height:100%}</style><div id="shell"><aside id="sidebar"></aside><main id="root"></main></div><script type="module" src="/story-fixture.jsx"></script>'));
+ });
+ },
+ }],
+ server: { host: '127.0.0.1', port: 0 },
+ }) });
+ }, BROWSER_FIXTURE_STARTUP_MS);
+ afterAll(() => fixture?.close());
+
+ it('keeps work and actions visible across workspace widths, sidebar states and zoom', async () => {
+ const page = await fixture.browser.newPage();
+ const mutations = [];
+ const errors = [];
+ page.on('pageerror', error => errors.push(error.message));
+ await page.route('**/socket.io/**', route => route.abort());
+ await page.route('**/api/**', async route => {
+ const request = route.request();
+ const path = new URL(request.url()).pathname;
+ if (request.method() !== 'GET') mutations.push(path);
+ let data = {};
+ if (path === '/api/story-builder/steps') data = { steps };
+ else if (path === '/api/story-builder/example') data = {
+ id: 'example', title: 'Example story', seedIdea: 'Generated draft paragraph.\n'.repeat(300),
+ currentStep: 'idea', universeId: 'example-universe', seriesId: 'example-series',
+ steps: Object.fromEntries(steps.map(s => [s.id, { status: s.id === 'idea' ? 'locked' : 'ready', locked: s.id === 'idea' }])),
+ staleSteps: [], llm: {},
+ };
+ else if (path === '/api/universes/example-universe') data = { id: 'example-universe', logline: 'Example', premise: 'Generated premise.\n'.repeat(300), styleNotes: 'Example style', influences: {}, characters: [] };
+ else if (path === '/api/pipeline/series/example-series') data = { id: 'example-series', arc: {} };
+ else if (path.includes('/issues')) data = [];
+ else if (path === '/api/providers') data = { providers: [] };
+ else if (path === '/api/catalog/types') data = { types: [] };
+ await route.fulfill({ contentType: 'application/json', body: JSON.stringify(data) });
+ });
+ try {
+ for (const step of ['idea', 'universeAesthetic', 'production']) {
+ await page.goto(`${fixture.origin}story-test?step=${step}`);
+ await page.getByRole('heading', { name: steps.find(s => s.id === step).label, exact: true }).waitFor().catch(error => { throw new Error(errors.join('\n') || error.message); });
+ for (const width of [320, 375, 390, 768, 1024, 1280, 1440]) {
+ for (const expanded of [false, true]) {
+ for (const zoom of [1, 2]) {
+ await page.setViewportSize({ width, height: width === 1440 ? 900 : 812 });
+ await page.evaluate(({ expanded, zoom, width }) => {
+ document.body.style.zoom = String(zoom);
+ document.documentElement.style.setProperty('--sidebar', expanded && width >= 768 ? '240px' : '0px');
+ document.getElementById('root').style.maxWidth = '';
+ }, { expanded, zoom, width });
+ await assertGeometry(page, { step, width, expanded, zoom });
+ }
+ }
+ }
+ for (const width of [240, 320, 480]) {
+ await page.setViewportSize({ width: 1440, height: 900 });
+ await page.evaluate(width => {
+ document.body.style.zoom = '1';
+ document.documentElement.style.setProperty('--sidebar', '0px');
+ document.getElementById('root').style.maxWidth = `${width}px`;
+ }, width);
+ await assertGeometry(page);
+ }
+ const work = page.getByRole('region', { name: 'Stage work' });
+ const action = page.getByRole('button', { name: step === 'idea' ? 'Unlock to revise' : 'Lock & continue' });
+ const before = await action.boundingBox();
+ await work.evaluate(el => { el.scrollTop = el.scrollHeight; });
+ await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
+ expect(await action.boundingBox()).toEqual(before);
+ }
+ expect(mutations).toEqual([]);
+ } finally { await page.close(); }
+ }, 120000);
+});
+
+async function assertGeometry(page, context) {
+ await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
+ const geometry = await page.evaluate(() => {
+ const section = document.querySelector('[aria-label="Current story stage"]');
+ const bounds = section.getBoundingClientRect();
+ const work = section.querySelector('[aria-label="Stage work"]').getBoundingClientRect();
+ const actions = [...section.querySelectorAll('header button')].map(button => button.getBoundingClientRect().toJSON());
+ return { bounds: bounds.toJSON(), work: work.toJSON(), actions, height: innerHeight,
+ labels: [...document.querySelectorAll('[role="tab"]')].map(tab => tab.textContent),
+ horizontal: document.documentElement.scrollWidth <= innerWidth + 1 };
+ });
+ expect(geometry.labels).toEqual(steps.map(step => step.label));
+ expect(geometry.horizontal).toBe(true);
+ expect(geometry.work.height).toBeGreaterThan(30);
+ for (const action of geometry.actions) {
+ expect(action.x).toBeGreaterThanOrEqual(geometry.bounds.x);
+ expect(action.right, JSON.stringify(context)).toBeLessThanOrEqual(geometry.bounds.right + 1);
+ expect(action.bottom, JSON.stringify({ context, geometry })).toBeLessThanOrEqual(geometry.height);
+ expect(action.bottom).toBeLessThanOrEqual(geometry.work.top + 1);
+ }
+}
diff --git a/client/src/pages/StoryBuilder.css b/client/src/pages/StoryBuilder.css
new file mode 100644
index 0000000000..03b46baa73
--- /dev/null
+++ b/client/src/pages/StoryBuilder.css
@@ -0,0 +1,82 @@
+.story-builder-workspace {
+ container: story-builder / inline-size;
+}
+
+.story-stage-layout {
+ display: grid;
+ grid-template-rows: auto minmax(0, 1fr);
+ grid-template-columns: minmax(0, 1fr);
+}
+
+/* Compact navigation follows the workspace, including narrow desktop panes. */
+.story-stage-tabs [role='tab'] {
+ min-width: 44px;
+ min-height: 44px;
+ justify-content: center;
+}
+
+.story-stage-tabs [role='tab'] > span,
+.story-direction-label {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border-width: 0;
+}
+
+.story-stage-tabs > button {
+ display: flex;
+}
+
+@container story-builder (min-width: 52rem) {
+ .story-stage-layout {
+ grid-template-columns: 220px minmax(0, 1fr);
+ grid-template-rows: minmax(0, 1fr);
+ }
+
+ .story-stage-nav {
+ overflow-y: auto;
+ }
+
+ .story-stage-tabs [role='tablist'] {
+ flex-direction: column;
+ align-items: stretch;
+ border: 0;
+ }
+
+ .story-stage-tabs [role='tab'] {
+ justify-content: flex-start;
+ white-space: normal;
+ text-align: left;
+ }
+
+ .story-stage-tabs [role='tab'] > span {
+ position: static;
+ width: auto;
+ height: auto;
+ margin: 0;
+ overflow: visible;
+ clip: auto;
+ white-space: normal;
+ }
+
+ .story-stage-tabs > button {
+ display: none;
+ }
+}
+
+@container story-builder (min-width: 20rem) {
+ .story-direction-label {
+ position: static;
+ width: auto;
+ height: auto;
+ margin: 0;
+ overflow: visible;
+ clip: auto;
+ white-space: normal;
+ }
+}
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsx
index 1afc1f8baf..6929da5a50 100644
--- a/client/src/pages/StoryBuilder.jsx
+++ b/client/src/pages/StoryBuilder.jsx
@@ -16,6 +16,7 @@ import ProviderModelSelector from '../components/ProviderModelSelector';
import {
Sparkles, Lock, Unlock, Check, ChevronRight, ChevronLeft, AlertTriangle,
Plus, RefreshCw, Loader2, ExternalLink, Wand2, Cloud, CloudOff, Lightbulb, FileInput,
+ Palette, GitBranch, Map as MapIcon, Users, BookOpen, Clapperboard,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import Banner from '../components/ui/Banner';
@@ -39,6 +40,7 @@ import useDrawerTab from '../hooks/useDrawerTab';
import useStoryImportIntake from '../hooks/useStoryImportIntake';
import TabPills from '../components/ui/TabPills';
import { formatCount } from '../utils/formatters';
+import './StoryBuilder.css';
// Bible fields the embedded arc step flushes before an ArcCanvas generate/verify.
// The Story Builder edits these on their own steps (not inside the arc step), so
@@ -54,6 +56,8 @@ const INTAKE_TAB_ITEMS = [
{ id: 'import', label: 'Import a finished work', icon: FileInput },
];
+const STEP_ICONS = { idea: Lightbulb, universeAesthetic: Palette, plotArc: GitBranch, readerMap: MapIcon, characters: Users, issues: BookOpen, production: Clapperboard };
+
const CONTENT_TYPE_LABELS = {
'short-story': 'Short story', novel: 'Novel', screenplay: 'Screenplay', 'comic-script': 'Comic script',
};
@@ -1348,71 +1352,18 @@ function StoryBuilderDetail({ storyId, stepParam }) {
);
return (
- <div className="h-full overflow-y-auto p-4 md:p-6">
- <div className="max-w-5xl mx-auto">
+ <div className="story-builder-workspace h-full min-h-0 p-3">
+ <div className="max-w-5xl mx-auto w-full min-w-0 min-h-0 h-full flex flex-col">
{readNotice}
- <header className="mb-4 flex items-start justify-between gap-4 flex-wrap">
+ <header className="mb-3 shrink-0 min-w-0">
<div>
<Link to="/story-builder" className="text-xs text-gray-500 hover:text-port-accent">← All stories</Link>
<h1 className="text-2xl font-bold flex items-center gap-2 mt-1">
<Sparkles className="w-6 h-6 text-port-accent" /> {session.title}
</h1>
</div>
- {/* Applies to every operation in this story (idea expand, aesthetic,
- arc, reader map, character refine). */}
- <ProviderModelPicker
- value={{ provider: session.llm?.provider || '', model: session.llm?.model || '' }}
- onChange={saveLlm}
- />
</header>
- {/* Cross-machine resume (#730): opt this session into peer sync so it can
- resume on another federated machine, and re-baseline its staleness
- against the current machine's live records. Local-only is the default. */}
- <div className="mb-4 flex items-center flex-wrap gap-x-3 gap-y-2 text-sm bg-port-card border border-port-border rounded-lg px-3 py-2">
- <button
- type="button"
- onClick={toggleSync}
- disabled={syncBusy}
- aria-pressed={session.sync === true}
- className={`inline-flex items-center gap-2 px-3 py-1.5 rounded border disabled:opacity-50 ${
- session.sync === true
- ? 'border-port-accent text-port-accent bg-port-bg'
- : 'border-port-border text-gray-400 hover:text-white'
- }`}
- title="Toggle whether this session resumes across your federated machines"
- >
- {syncBusy ? <Loader2 className="w-4 h-4 animate-spin" /> : (session.sync === true ? <Cloud className="w-4 h-4" /> : <CloudOff className="w-4 h-4" />)}
- {session.sync === true ? 'Cross-machine resume on' : 'Cross-machine resume off'}
- </button>
-
- {session.sync === true && (
- <>
- <span className="text-xs text-gray-500">
- {syncDrift
- ? 'This machine’s records have drifted from the synced baseline.'
- : 'Baseline matches this machine.'}
- </span>
- <button
- type="button"
- onClick={reconcile}
- disabled={syncBusy || !syncDrift}
- className={`inline-flex items-center gap-2 px-3 py-1.5 rounded border disabled:opacity-40 ${
- syncDrift
- ? 'border-port-warning text-port-warning hover:bg-port-bg'
- : 'border-port-border text-gray-500'
- }`}
- title={syncDrift
- ? 'Adopt this machine’s current records as the new staleness baseline'
- : 'Nothing to reconcile — the baseline already matches this machine'}
- >
- {syncBusy ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
- Reconcile
- </button>
- </>
- )}
- </div>
-
{/* Live runs — own kickoffs and ones adopted after a reload / second tab —
stay visible whichever step is open, with a way back to the step. */}
{activeRuns.length > 0 && (
@@ -1438,106 +1389,152 @@ function StoryBuilderDetail({ storyId, stepParam }) {
</div>
)}
- <div className="grid grid-cols-1 md:grid-cols-[220px_1fr] gap-6">
- {/* Step rail */}
- <nav className="space-y-1">
- {steps.map((s, idx) => {
- const st = session.steps?.[s.id] || { status: 'pending', locked: false };
- const stale = staleSteps.includes(s.id);
- const isActive = s.id === activeStepId;
- // Navigation is never blocked (start-from-anywhere). The warning
- // icon flags a step whose upstream is unlocked or stale so the
- // user knows the order isn't conventional — but they may proceed.
- const unmet = firstUnmetUpstream(idx);
- return (
+ <div className="story-stage-layout min-h-0 flex-1 gap-3">
+ <nav className="story-stage-nav min-w-0 min-h-0" aria-label="Story stages">
+ <TabPills
+ tabs={steps.map((s, idx) => {
+ const st = session.steps?.[s.id] || { status: 'pending', locked: false };
+ const stale = staleSteps.includes(s.id);
+ const unmet = firstUnmetUpstream(idx);
+ return {
+ id: s.id, label: s.label, icon: STEP_ICONS[s.id] || Sparkles,
+ trailing: (stale || unmet)
+ ? <AlertTriangle aria-hidden="true" className="w-3.5 h-3.5 shrink-0 text-port-warning" title={stale ? 'Stale — re-review' : 'Earlier step not locked yet'} />
+ : st.locked ? <Lock aria-hidden="true" className="w-3.5 h-3.5 shrink-0 text-port-success" /> : null,
+ };
+ })}
+ activeTab={activeStepId}
+ onChange={goToStep}
+ ariaLabel="Story stages"
+ mobileCompact
+ variant="pills"
+ className="story-stage-tabs"
+ />
+ </nav>
+
+ {/* Active step: the header stays put while generated work scrolls. */}
+ <section className="min-w-0 min-h-0 flex flex-col bg-port-card border border-port-border rounded-lg" aria-label="Current story stage">
+ <header className="shrink-0 min-w-0 story-stage-actions border-b border-port-border p-2 space-y-2" aria-label="Stage actions">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <h2 className="min-w-0 break-words text-lg font-semibold">{activeStep?.label}</h2>
+ <span className={`text-xs ${STATUS_BADGE[stepState.status]?.cls}`}>
+ {isStale ? 'Stale — re-review' : stepState.locked ? 'Locked' : STATUS_BADGE[stepState.status]?.label}
+ </span>
+ </div>
+ {/* Existing lock and navigation handlers stay outside the scrolling work. */}
+ <div className="flex flex-wrap items-center gap-2">
<button
- key={s.id} onClick={() => goToStep(s.id)}
- className={`w-full text-left px-3 py-2 rounded border flex items-center justify-between gap-2 ${
- isActive ? 'border-port-accent bg-port-card' : 'border-transparent hover:bg-port-card'
+ onClick={() => lock.toggle(stepState.locked)} disabled={lock.busy}
+ className={`inline-flex max-w-full min-w-0 items-center gap-2 min-h-[44px] px-2 py-2 rounded text-sm disabled:opacity-50 ${
+ stepState.locked ? 'bg-port-card border border-port-success text-port-success' : 'bg-port-success hover:bg-port-success/80 text-white'
}`}
>
- <span className="flex items-center gap-2 text-sm">
- {st.locked ? <Lock className="w-3.5 h-3.5 text-port-success" /> : <span className="w-3.5 h-3.5 rounded-full border border-gray-600 inline-block" />}
- {s.label}
- </span>
- {(stale || unmet) && (
- <AlertTriangle
- className="w-3.5 h-3.5 text-port-warning"
- title={stale ? 'Stale — re-review' : 'Earlier step not locked yet'}
- />
- )}
+ {lock.busy ? <Loader2 className="w-4 h-4 shrink-0 animate-spin" /> : (stepState.locked ? <Unlock className="w-4 h-4 shrink-0" /> : <Check className="w-4 h-4 shrink-0" />)}
+ <span className="min-w-0 [overflow-wrap:anywhere]">{stepState.locked ? 'Unlock to revise' : 'Lock & continue'}</span>
</button>
- );
- })}
- </nav>
- {/* Active step */}
- <section className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
- <div className="flex items-start justify-between">
- <div>
- <h2 className="text-lg font-semibold">{activeStep?.label}</h2>
- <p className="text-sm text-gray-400">{activeStep?.description}</p>
+ <div className="flex flex-wrap items-center gap-2">
+ {activeIdx > 0 && (
+ <button onClick={() => goToStep(stepIds[activeIdx - 1])} className="inline-flex min-w-[44px] min-h-[44px] justify-center items-center gap-1 text-sm text-gray-400 hover:text-white">
+ <ChevronLeft className="w-4 h-4 shrink-0" /><span className="story-direction-label">Back</span>
+ </button>
+ )}
+ {activeIdx < steps.length - 1 && (
+ <>
+ {/* `aria-disabled` (not `disabled`) keeps the button focusable so
+ keyboard/screen-reader users can reach it and hear the reason via
+ the sr-only hint; `title` covers the mouse case. Same pattern as
+ ExtractCanonButton.jsx. */}
+ <button
+ type="button"
+ onClick={nextBlocked ? undefined : () => goToStep(stepIds[activeIdx + 1])}
+ aria-disabled={nextBlocked || undefined}
+ aria-describedby={nextHintId}
+ title={nextReason}
+ className={`inline-flex min-w-[44px] min-h-[44px] justify-center items-center gap-1 text-sm bg-port-accent text-white px-2 py-2 rounded ${
+ nextBlocked ? 'opacity-40 cursor-not-allowed' : 'hover:bg-port-accent/80'
+ }`}
+ >
+ <span className="story-direction-label">Next</span><ChevronRight className="w-4 h-4 shrink-0" />
+ </button>
+ <span id={nextHintId} className="sr-only">{nextReason}</span>
+ </>
+ )}
+ </div>
</div>
- <span className={`text-xs ${STATUS_BADGE[stepState.status]?.cls}`}>{STATUS_BADGE[stepState.status]?.label}</span>
- </div>
-
- {isStale && (
- <Banner tone="warning" size="md" icon={AlertTriangle} align="center">
- An earlier step changed after you locked this — re-review and re-lock to continue.
- </Banner>
- )}
-
- <StepPanel
- key={activeStepId}
- session={session} universe={universe} series={series} issues={issues}
- stepId={activeStepId} locked={stepState.locked} onChanged={reload}
- onSeriesUpdate={updateSeriesFromServer}
- onIssuesUpdate={handleIssuesUpdate}
- onFlushPending={flushPending}
- onRegisterDraftFlush={registerDraftFlush}
- onUniverseCharRef={applyUniverseCharRef}
- />
-
- {/* Footer: lock + navigation */}
- <div className="flex items-center justify-between border-t border-port-border pt-3 mt-3">
- <button
- onClick={() => lock.toggle(stepState.locked)} disabled={lock.busy}
- className={`inline-flex items-center gap-2 px-3 py-1.5 rounded text-sm disabled:opacity-50 ${
- stepState.locked ? 'bg-port-card border border-port-success text-port-success' : 'bg-port-success hover:bg-port-success/80 text-white'
- }`}
- >
- {lock.busy ? <Loader2 className="w-4 h-4 animate-spin" /> : (stepState.locked ? <Unlock className="w-4 h-4" /> : <Check className="w-4 h-4" />)}
- {stepState.locked ? 'Unlock to revise' : 'Lock & continue'}
- </button>
-
- <div className="flex items-center gap-2">
- {activeIdx > 0 && (
- <button onClick={() => goToStep(stepIds[activeIdx - 1])} className="inline-flex items-center gap-1 text-sm text-gray-400 hover:text-white">
- <ChevronLeft className="w-4 h-4" /> Back
- </button>
- )}
- {activeIdx < steps.length - 1 && (
- <>
- {/* `aria-disabled` (not `disabled`) keeps the button focusable so
- keyboard/screen-reader users can reach it and hear the reason via
- the sr-only hint; `title` covers the mouse case. Same pattern as
- ExtractCanonButton.jsx. */}
+ </header>
+ <div className="min-h-0 min-w-0 flex-1 overflow-y-auto p-3 space-y-3" aria-label="Stage work" role="region" key={activeStepId}>
+ <p className="text-sm text-gray-400">{activeStep?.description}</p>
+ {isStale && (
+ <Banner tone="warning" size="md" icon={AlertTriangle} align="center">
+ An earlier step changed after you locked this — re-review and re-lock to continue.
+ </Banner>
+ )}
+ <details className="min-w-0">
+ <summary className="cursor-pointer text-sm text-gray-400 min-h-[44px]">AI: {session.llm?.model || session.llm?.provider || 'stage default'} · Story settings</summary>
+ <div className="mt-2 min-w-0 space-y-3">
+ {/* Applies to every operation in this story. */}
+ <ProviderModelPicker
+ value={{ provider: session.llm?.provider || '', model: session.llm?.model || '' }}
+ onChange={saveLlm}
+ />
+ {/* Cross-machine resume (#730): opt this session into peer sync so it can
+ resume on another federated machine, and re-baseline its staleness
+ against the current machine's live records. Local-only is the default. */}
+ <div className="mb-4 flex items-center flex-wrap gap-x-3 gap-y-2 text-sm bg-port-card border border-port-border rounded-lg px-3 py-2">
<button
type="button"
- onClick={nextBlocked ? undefined : () => goToStep(stepIds[activeIdx + 1])}
- aria-disabled={nextBlocked || undefined}
- aria-describedby={nextHintId}
- title={nextReason}
- className={`inline-flex items-center gap-1 text-sm bg-port-accent text-white px-3 py-1.5 rounded ${
- nextBlocked ? 'opacity-40 cursor-not-allowed' : 'hover:bg-port-accent/80'
+ onClick={toggleSync}
+ disabled={syncBusy}
+ aria-pressed={session.sync === true}
+ className={`inline-flex items-center gap-2 px-3 py-1.5 rounded border disabled:opacity-50 ${
+ session.sync === true
+ ? 'border-port-accent text-port-accent bg-port-bg'
+ : 'border-port-border text-gray-400 hover:text-white'
}`}
+ title="Toggle whether this session resumes across your federated machines"
>
- Next <ChevronRight className="w-4 h-4" />
+ {syncBusy ? <Loader2 className="w-4 h-4 animate-spin" /> : (session.sync === true ? <Cloud className="w-4 h-4" /> : <CloudOff className="w-4 h-4" />)}
+ {session.sync === true ? 'Cross-machine resume on' : 'Cross-machine resume off'}
</button>
- <span id={nextHintId} className="sr-only">{nextReason}</span>
- </>
- )}
- </div>
+
+ {session.sync === true && (
+ <>
+ <span className="text-xs text-gray-500">
+ {syncDrift
+ ? 'This machine’s records have drifted from the synced baseline.'
+ : 'Baseline matches this machine.'}
+ </span>
+ <button
+ type="button"
+ onClick={reconcile}
+ disabled={syncBusy || !syncDrift}
+ className={`inline-flex items-center gap-2 px-3 py-1.5 rounded border disabled:opacity-40 ${
+ syncDrift
+ ? 'border-port-warning text-port-warning hover:bg-port-bg'
+ : 'border-port-border text-gray-500'
+ }`}
+ title={syncDrift
+ ? 'Adopt this machine’s current records as the new staleness baseline'
+ : 'Nothing to reconcile — the baseline already matches this machine'}
+ >
+ {syncBusy ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
+ Reconcile
+ </button>
+ </>
+ )}
+ </div>
+ </div>
+ </details>
+ <StepPanel
+ session={session} universe={universe} series={series} issues={issues}
+ stepId={activeStepId} locked={stepState.locked} onChanged={reload}
+ onSeriesUpdate={updateSeriesFromServer}
+ onIssuesUpdate={handleIssuesUpdate}
+ onFlushPending={flushPending}
+ onRegisterDraftFlush={registerDraftFlush}
+ onUniverseCharRef={applyUniverseCharRef}
+ />
</div>
</section>
</div>
diff --git a/client/src/pages/StoryBuilder.test.jsx b/client/src/pages/StoryBuilder.test.jsx
index a616c7b565..e0a300076f 100644
--- a/client/src/pages/StoryBuilder.test.jsx
+++ b/client/src/pages/StoryBuilder.test.jsx
@@ -554,7 +554,7 @@ describe('StoryBuilder — detail stepper', () => {
expect(screen.queryByRole('button', { name: /Characters/ })).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
- expect(await screen.findByRole('button', { name: /Characters/ })).toBeTruthy();
+ expect(await screen.findByRole('tab', { name: /Characters/ })).toBeTruthy();
expect(screen.queryByRole('alert')).toBeNull();
});
@@ -579,6 +579,23 @@ describe('StoryBuilder — detail stepper', () => {
expect(screen.queryByText('Old story')).toBeNull();
});
+ it('keeps one continuation control in the stage header and every destination in the shared navigator', async () => {
+ api.getStorySession.mockResolvedValue({
+ id: 'stb-1', title: 'Example story', currentStep: 'idea', seedIdea: 'Long generated work. '.repeat(1000),
+ universeId: 'u1', seriesId: 's1', steps: mkSteps(), staleSteps: [],
+ });
+ renderAt('/story-builder/stb-1/idea');
+ const action = await screen.findByRole('button', { name: 'Lock & continue' });
+ const work = screen.getByRole('region', { name: 'Stage work' });
+ expect(action.closest('header').getAttribute('aria-label')).toBe('Stage actions');
+ expect(work.contains(action)).toBe(false);
+ expect(screen.getAllByRole('button', { name: 'Lock & continue' })).toHaveLength(1);
+ expect(screen.getAllByRole('tab').map(tab => tab.textContent)).toEqual(STEPS.map(step => step.label));
+ expect(screen.getByRole('tab', { name: 'Idea' }).getAttribute('aria-selected')).toBe('true');
+ expect(api.generateStoryStep).not.toHaveBeenCalled();
+ expect(api.refineStoryStep).not.toHaveBeenCalled();
+ });
+
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',
@@ -779,7 +796,7 @@ describe('StoryBuilder — detail stepper', () => {
await waitFor(() => expect(screen.getByRole('heading', { name: 'Idea' })).toBeTruthy());
const callsBefore = api.getStorySession.mock.calls.length;
- fireEvent.click(screen.getByRole('button', { name: /Plot Arc/i }));
+ fireEvent.click(screen.getByRole('tab', { name: /Plot Arc/i }));
await waitFor(() => expect(api.setStoryCurrentStep).toHaveBeenCalledWith('stb-1', 'plotArc', expect.anything()));
// Rejection → the catch path toasts + resyncs (reload refetches the session),
// and the URL never advances, so the heading stays on Idea instead of
@@ -961,7 +978,7 @@ describe('StoryBuilder — detail stepper', () => {
await waitFor(() => expect(MockEventSource.instances).toHaveLength(1));
// Navigate the rail to another step — the panel unmounts.
- fireEvent.click(screen.getByRole('button', { name: /Characters/ }));
+ fireEvent.click(screen.getByRole('tab', { name: /Characters/ }));
await waitFor(() => expect(screen.getByRole('heading', { name: 'Characters' })).toBeTruthy());
expect(lastEventSource().closed).toBe(false);
@@ -1024,7 +1041,7 @@ describe('StoryBuilder — detail stepper', () => {
// 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/ }));
+ fireEvent.click(screen.getByRole('tab', { name: /Idea/ }));
expect((await screen.findByRole('alert')).textContent).toContain('Showing the last loaded story');
expect(screen.queryByText(/Session not found/)).toBeNull();