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: flush pending Arc Canvas edits before Lock & continue locks the step (#3907)

[._.]/ Adam Eivyd1b110fd3069
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a7f3deb45d..c0c2dcd4f1 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -8,6 +8,7 @@
## Fixed
+- "Lock & continue" in the Story Builder no longer discards arc edits that are still on screen. Locking a step makes it read-only server-side and swaps the embedded Arc Canvas for read-only field blocks, so an open logline / summary / protagonist-arc editor was torn down with its unsaved draft and any dirty series-bible field lost its chance to save. The lock action now runs the same pre-flight flush the generate / verify / save paths use, and that flush reaches one level deeper: the arc editor hands its host a committer while it is open (`useArcCanvasSync` → `registerDraftFlush`), so the draft lands before the lock request goes out. Unlocking skips the flush — it re-opens the step and has nothing to preserve. The full Arc Canvas page gets the same coverage, so its Save and Generate buttons pick up an open arc editor too.
- Turning on scheduled backups now actually schedules them. The daily backup cron was registered once at server start, so if backups were off — or no destination folder was set — when PortOS booted, enabling them in Backup settings did nothing until the server was restarted, and no backup ever ran. The schedule is now kept in sync with your settings: enabling backups or picking a destination registers it immediately, editing the schedule re-registers it, and turning backups off cancels it.
- Canon entry cards in a universe bible are usable on a phone again. The card's icon action strip sat as a full-height column beside the entry's content, so on a phone it squeezed the description box and every collapsible editor under it to about a third of the card — the description was clipped after a few words and the "Reveal timing" and "Outfits" headers wrapped into tall centered stacks. The action strip now shares the entry's title row and the content spans the full card width beneath it. Long entry names wrap instead of being cut off mid-word (variation and reference-board rows on the same page too), a collapsed "Outfits" header clips its outfit list to one line, and the character colour rows leave their hex field enough room for the description beside it.
- Wrapped labels inside buttons no longer render as a centered ragged stack. Browsers center button text by default, which is invisible while a label fits on one line and only shows up once it wraps — so it surfaced on phones, in section headers across the app, and not on desktop. Buttons that lay their contents out in a row now read left-aligned unless they explicitly ask to be centered.
diff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsx
index 4567840619..2bbf07cb6d 100644
--- a/client/src/components/pipeline/ArcCanvas.jsx
+++ b/client/src/components/pipeline/ArcCanvas.jsx
@@ -39,7 +39,7 @@ import AddSeasonRow from './arcCanvas/AddSeasonRow.jsx';
export { default as ArcRoadmapChart } from './arcCanvas/ArcRoadmapChart.jsx';
-export default function ArcCanvas({ series, issues, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {
+export default function ArcCanvas({ series, issues, onSeriesUpdate, onIssuesUpdate, onFlushPending, onRegisterDraftFlush }) {
const seasons = useMemo(() => series.seasons || [], [series.seasons]);
const [activeSeasonId, setActiveSeasonId] = useState(seasons[0]?.id || null);
// Bucket + sort issues by season once per (seasons, issues) change rather than
@@ -80,6 +80,7 @@ export default function ArcCanvas({ series, issues, onSeriesUpdate, onIssuesUpda
onSeriesUpdate={onSeriesUpdate}
onIssuesUpdate={onIssuesUpdate}
onFlushPending={onFlushPending}
+ onRegisterDraftFlush={onRegisterDraftFlush}
/>
<EditorialRoadmapPanel series={series} seasons={seasons} issues={issues} />
</div>
diff --git a/client/src/components/pipeline/arcCanvas/ArcContent.jsx b/client/src/components/pipeline/arcCanvas/ArcContent.jsx
index 10feb56092..ec23a3396f 100644
--- a/client/src/components/pipeline/arcCanvas/ArcContent.jsx
+++ b/client/src/components/pipeline/arcCanvas/ArcContent.jsx
@@ -1,4 +1,4 @@
-import { useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import { Loader2 } from 'lucide-react';
import toast from '../../ui/Toast';
import { updatePipelineSeries } from '../../../services/api';
@@ -8,7 +8,7 @@ import TickingClockEditor from './TickingClockEditor.jsx';
import TickingClockCard from './TickingClockCard.jsx';
import ThemeChips from './ThemeChips.jsx';
-export default function ArcContent({ series, onSeriesUpdate }) {
+export default function ArcContent({ series, onSeriesUpdate, onRegisterDraftFlush }) {
const arc = series.arc;
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState(arc);
@@ -25,19 +25,43 @@ export default function ArcContent({ series, onSeriesUpdate }) {
setDraft(arc);
};
- const save = async () => {
+ // Latest editor state for the host-driven flush below, which is registered
+ // once and would otherwise close over the first render's draft.
+ const stateRef = useRef(null);
+ stateRef.current = { editing, draft, arc };
+
+ const persistDraft = useCallback(async (nextDraft) => {
setSaving(true);
- const updated = await updatePipelineSeries(series.id, { arc: draft }, { silent: true }).catch((err) => {
+ const updated = await updatePipelineSeries(series.id, { arc: nextDraft }, { silent: true }).catch((err) => {
toast.error(err.message || 'Save failed');
return null;
});
setSaving(false);
- if (!updated) return;
+ if (!updated) return null;
onSeriesUpdate(updated);
setEditing(false);
- toast.success('Arc saved');
+ return updated;
+ }, [series.id, onSeriesUpdate]);
+
+ const save = async () => {
+ if (await persistDraft(draft)) toast.success('Arc saved');
};
+ // Hand the host a committer for the OPEN editor, so any "flush before you
+ // act" path (Lock & continue, Generate arc, Save series) persists what is on
+ // screen instead of silently discarding it (#3907). Returns `true` only when
+ // it actually wrote. Unregisters on unmount so a torn-down editor can never
+ // be committed.
+ useEffect(() => {
+ if (!onRegisterDraftFlush) return undefined;
+ onRegisterDraftFlush(async () => {
+ const { editing: isEditing, draft: pending, arc: current } = stateRef.current;
+ if (!isEditing || JSON.stringify(pending ?? null) === JSON.stringify(current ?? null)) return false;
+ return Boolean(await persistDraft(pending));
+ });
+ return () => onRegisterDraftFlush(null);
+ }, [onRegisterDraftFlush, persistDraft]);
+
if (editing) {
return (
<div className="space-y-2">
diff --git a/client/src/components/pipeline/arcCanvas/ArcContent.test.jsx b/client/src/components/pipeline/arcCanvas/ArcContent.test.jsx
new file mode 100644
index 0000000000..fc86477e5e
--- /dev/null
+++ b/client/src/components/pipeline/arcCanvas/ArcContent.test.jsx
@@ -0,0 +1,107 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { act, fireEvent, render, screen } from '@testing-library/react';
+
+const updatePipelineSeries = vi.fn();
+vi.mock('../../../services/api', () => ({
+ updatePipelineSeries: (...args) => updatePipelineSeries(...args),
+}));
+
+const toastMock = vi.hoisted(() => {
+ const fn = vi.fn();
+ fn.success = vi.fn(); fn.error = vi.fn(); fn.loading = vi.fn(); fn.warning = vi.fn(); fn.dismiss = vi.fn();
+ return fn;
+});
+vi.mock('../../ui/Toast', () => ({ default: toastMock, toast: toastMock, Toaster: () => null }));
+
+// The shape picker / ticking-clock editor / theme chips pull their own graphs;
+// this suite is about the DRAFT COMMIT contract, so stub them inert.
+vi.mock('../StoryShapes', () => ({
+ ArcShapePicker: () => <div data-testid="shape-picker" />,
+ ArcShapeSparkline: () => <svg />,
+ getStoryShape: () => null,
+}));
+vi.mock('./TickingClockEditor.jsx', () => ({ default: () => <div /> }));
+vi.mock('./TickingClockCard.jsx', () => ({ default: () => <div /> }));
+vi.mock('./ThemeChips.jsx', () => ({ default: () => <div /> }));
+vi.mock('./FieldLockToggle.jsx', () => ({ default: () => <button type="button">lock</button> }));
+
+import ArcContent from './ArcContent.jsx';
+
+const SERIES = { id: 's1', arc: { logline: 'Old logline', summary: 'S', protagonistArc: 'P', themes: [] } };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ updatePipelineSeries.mockResolvedValue({ ...SERIES, arc: { ...SERIES.arc, logline: 'New logline' } });
+});
+
+// Grab the committer ArcContent hands up, so the tests can invoke it the way a
+// host's flushPending() does before locking / generating.
+const renderWithRegistry = (props = {}) => {
+ const registered = { fn: null };
+ const onRegisterDraftFlush = vi.fn((fn) => { registered.fn = fn; });
+ const onSeriesUpdate = vi.fn();
+ render(<ArcContent series={SERIES} onSeriesUpdate={onSeriesUpdate} onRegisterDraftFlush={onRegisterDraftFlush} {...props} />);
+ return { registered, onSeriesUpdate, onRegisterDraftFlush };
+};
+
+const openEditorAndType = (text) => {
+ fireEvent.click(screen.getByText('Edit arc'));
+ fireEvent.change(screen.getByPlaceholderText('One-sentence whole-arc pitch'), { target: { value: text } });
+};
+
+describe('ArcContent draft flush registration', () => {
+ it('commits the OPEN editor draft and reports the save', async () => {
+ const { registered, onSeriesUpdate } = renderWithRegistry();
+ openEditorAndType('New logline');
+
+ let did;
+ await act(async () => { did = await registered.fn(); });
+
+ expect(did).toBe(true);
+ expect(updatePipelineSeries).toHaveBeenCalledWith('s1', { arc: expect.objectContaining({ logline: 'New logline' }) }, { silent: true });
+ expect(onSeriesUpdate).toHaveBeenCalled();
+ // Committed → the editor closes, same as the explicit Save button.
+ expect(screen.getByText('Edit arc')).toBeTruthy();
+ });
+
+ it('is a no-op when the editor is closed', async () => {
+ const { registered } = renderWithRegistry();
+ let did;
+ await act(async () => { did = await registered.fn(); });
+ expect(did).toBe(false);
+ expect(updatePipelineSeries).not.toHaveBeenCalled();
+ });
+
+ it('is a no-op when the editor is open but untouched', async () => {
+ const { registered } = renderWithRegistry();
+ fireEvent.click(screen.getByText('Edit arc'));
+ let did;
+ await act(async () => { did = await registered.fn(); });
+ expect(did).toBe(false);
+ expect(updatePipelineSeries).not.toHaveBeenCalled();
+ });
+
+ it('reports no save (and keeps the editor open) when the PATCH rejects', async () => {
+ updatePipelineSeries.mockRejectedValue(new Error('boom'));
+ const { registered } = renderWithRegistry();
+ openEditorAndType('New logline');
+
+ let did;
+ await act(async () => { did = await registered.fn(); });
+ expect(did).toBe(false);
+ expect(toastMock.error).toHaveBeenCalled();
+ // Editor stays open so the unsaved text is still on screen and recoverable.
+ expect(screen.getByPlaceholderText('One-sentence whole-arc pitch')).toBeTruthy();
+ });
+
+ it('unregisters on unmount so a torn-down editor can never be committed', () => {
+ const registered = { fn: undefined };
+ const onRegisterDraftFlush = vi.fn((fn) => { registered.fn = fn; });
+ const { unmount } = render(
+ <ArcContent series={SERIES} onSeriesUpdate={vi.fn()} onRegisterDraftFlush={onRegisterDraftFlush} />,
+ );
+ expect(registered.fn).toBeTypeOf('function');
+ unmount();
+ expect(registered.fn).toBe(null);
+ });
+});
diff --git a/client/src/components/pipeline/arcCanvas/ArcHeader.jsx b/client/src/components/pipeline/arcCanvas/ArcHeader.jsx
index 0f5f55203a..0c3a731b59 100644
--- a/client/src/components/pipeline/arcCanvas/ArcHeader.jsx
+++ b/client/src/components/pipeline/arcCanvas/ArcHeader.jsx
@@ -34,7 +34,7 @@ const VERIFY_ARC_SCOPE = {
// ---- Arc header (logline, themes, action buttons) ----
-export default function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {
+export default function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending, onRegisterDraftFlush }) {
const arc = series.arc;
const arcLocked = !!series.locked?.arc;
const [running, setRunning] = useState(null); // 'generate' | 'verify' | 'resolve' | 'derive' | 'derive-commit' | 'completeness' | null
@@ -348,7 +348,7 @@ export default function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFl
) : null}
{arc ? (
- <ArcContent series={series} onSeriesUpdate={onSeriesUpdate} />
+ <ArcContent series={series} onSeriesUpdate={onSeriesUpdate} onRegisterDraftFlush={onRegisterDraftFlush} />
) : (
<p className="text-xs text-gray-500 italic">
No arc yet — describe the series in the bible, then click <em>Generate arc</em> to have an LLM propose a multi-volume spine + volume breakdown.
diff --git a/client/src/hooks/useArcCanvasSync.js b/client/src/hooks/useArcCanvasSync.js
index 89a71b3a3e..b4116e3a53 100644
--- a/client/src/hooks/useArcCanvasSync.js
+++ b/client/src/hooks/useArcCanvasSync.js
@@ -14,6 +14,14 @@ import { updatePipelineSeries } from '../services/api';
// run against the on-screen state. Returns `true` when a save
// occurred so the caller can surface a confirmation toast.
//
+// A fourth callback, `onRegisterDraftFlush` → registerDraftFlush(fn), lets a
+// descendant that owns an unsaved *draft* (the ArcContent logline / summary /
+// protagonist-arc editor) hand up a committer. flushPending() runs it after the
+// bible PATCH, so "flush before you act" covers an open arc editor too — without
+// which clicking Lock & continue / Generate / Save while the editor is open
+// silently discards what is on screen (#3907). The registered fn returns `true`
+// when it saved, and is expected to swallow its own errors.
+//
// Both PipelineSeries and the embedded StoryBuilder arc step used to hand-roll
// this identical contract; the only real divergence is WHICH bible fields each
// host flushes (PipelineSeries carries 10 + cover/style overrides; StoryBuilder
@@ -40,6 +48,12 @@ export function useArcCanvasSync({
if (series && lastSavedRef.current?.id !== series.id) lastSavedRef.current = series;
}, [series]);
+ // Committer handed up by an open draft editor (see the header comment). Held
+ // in a ref, not state — registering must not re-render the host, and
+ // flushPending only needs the latest value at call time.
+ const draftFlushRef = useRef(null);
+ const registerDraftFlush = useCallback((fn) => { draftFlushRef.current = fn || null; }, []);
+
const updateSeriesFromServer = useCallback((next) => {
setSeries(next);
lastSavedRef.current = next;
@@ -58,23 +72,30 @@ export function useArcCanvasSync({
const saved = lastSavedRef.current || series;
const dirty = flushFields.some((k) => (series[k] ?? '') !== (saved[k] ?? ''))
|| JSON.stringify(series.llm || {}) !== JSON.stringify(saved.llm || {});
- if (!dirty) return false;
- // Build the PATCH payload from the same field list, applying any per-field
- // empty-value default (e.g. `titleLogo: '' ` so the server clears rather than
- // sees `undefined`). `llm` is always sent.
- const patch = { llm: series.llm || { provider: null, model: null } };
- for (const k of flushFields) {
- patch[k] = k in payloadDefaults ? (series[k] || payloadDefaults[k]) : series[k];
+ let didSave = false;
+ if (dirty) {
+ // Build the PATCH payload from the same field list, applying any per-field
+ // empty-value default (e.g. `titleLogo: '' ` so the server clears rather than
+ // sees `undefined`). `llm` is always sent.
+ const patch = { llm: series.llm || { provider: null, model: null } };
+ for (const k of flushFields) {
+ patch[k] = k in payloadDefaults ? (series[k] || payloadDefaults[k]) : series[k];
+ }
+ const updated = await updatePipelineSeries(series.id, patch, { silent })
+ .catch((err) => {
+ if (onFlushError) onFlushError(err);
+ return null;
+ });
+ if (updated) {
+ updateSeriesFromServer(updated);
+ didSave = true;
+ }
}
- const updated = await updatePipelineSeries(series.id, patch, { silent })
- .catch((err) => {
- if (onFlushError) onFlushError(err);
- return null;
- });
- if (!updated) return false;
- updateSeriesFromServer(updated);
- return true;
+ // Bible PATCH first, THEN the draft — the draft committer's response then
+ // carries the bible fields too, so lastSavedRef ends on the freshest record.
+ if (draftFlushRef.current && await draftFlushRef.current()) didSave = true;
+ return didSave;
}, [series, flushFields, payloadDefaults, silent, onFlushError, updateSeriesFromServer]);
- return { updateSeriesFromServer, handleIssuesUpdate, flushPending };
+ return { updateSeriesFromServer, handleIssuesUpdate, flushPending, registerDraftFlush };
}
diff --git a/client/src/hooks/useArcCanvasSync.test.jsx b/client/src/hooks/useArcCanvasSync.test.jsx
index 586e5c3273..945ced7391 100644
--- a/client/src/hooks/useArcCanvasSync.test.jsx
+++ b/client/src/hooks/useArcCanvasSync.test.jsx
@@ -102,6 +102,50 @@ describe('useArcCanvasSync', () => {
expect(result.current.issues.map((i) => i.id)).toEqual(['i3']);
});
+ it('flushPending runs a registered draft committer AFTER the bible PATCH', async () => {
+ const server = { id: 's1', name: 'A' };
+ updatePipelineSeries.mockResolvedValue({ ...server, name: 'B' });
+ const order = [];
+ const draftFlush = vi.fn(async () => { order.push('draft'); return true; });
+ updatePipelineSeries.mockImplementation(async () => { order.push('bible'); return { ...server, name: 'B' }; });
+ const { result } = renderHook(() => useHarness(server, [], { flushFields: FLUSH_FIELDS, silent: true }));
+
+ act(() => { result.current.registerDraftFlush(draftFlush); });
+ act(() => { result.current.setSeries((s) => ({ ...s, name: 'B' })); });
+
+ let did;
+ await act(async () => { did = await result.current.flushPending(); });
+ expect(did).toBe(true);
+ expect(order).toEqual(['bible', 'draft']);
+ });
+
+ it('flushPending reports a save when ONLY the registered draft committer wrote', async () => {
+ const server = { id: 's1', name: 'A' };
+ const draftFlush = vi.fn(async () => true);
+ const { result } = renderHook(() => useHarness(server, [], { flushFields: FLUSH_FIELDS }));
+
+ act(() => { result.current.registerDraftFlush(draftFlush); });
+ let did;
+ await act(async () => { did = await result.current.flushPending(); });
+ // Nothing diverged in the bible, so the PATCH is skipped — but the open
+ // draft editor still committed, and the caller must hear about it.
+ expect(updatePipelineSeries).not.toHaveBeenCalled();
+ expect(draftFlush).toHaveBeenCalled();
+ expect(did).toBe(true);
+ });
+
+ it('registerDraftFlush(null) unregisters the committer', async () => {
+ const draftFlush = vi.fn(async () => true);
+ const { result } = renderHook(() => useHarness({ id: 's1', name: 'A' }, [], { flushFields: FLUSH_FIELDS }));
+
+ act(() => { result.current.registerDraftFlush(draftFlush); });
+ act(() => { result.current.registerDraftFlush(null); });
+ let did;
+ await act(async () => { did = await result.current.flushPending(); });
+ expect(draftFlush).not.toHaveBeenCalled();
+ expect(did).toBe(false);
+ });
+
it('updateSeriesFromServer keeps the baseline aligned so a follow-up flush is a no-op', async () => {
const server = { id: 's1', name: 'A' };
const { result } = renderHook(() => useHarness(server, [], { flushFields: FLUSH_FIELDS }));
diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsx
index fb701e7ece..66ac9d30c5 100644
--- a/client/src/pages/PipelineSeries.jsx
+++ b/client/src/pages/PipelineSeries.jsx
@@ -145,7 +145,7 @@ export default function PipelineSeries() {
// setters). Flushes the full bible field-set; the API helper's auto-toast is
// suppressed (silent) so `onFlushError` emits the single failure toast that
// tells the user their edits didn't persist.
- const { updateSeriesFromServer, handleIssuesUpdate, flushPending } = useArcCanvasSync({
+ const { updateSeriesFromServer, handleIssuesUpdate, flushPending, registerDraftFlush } = useArcCanvasSync({
series,
setSeries,
setIssues,
@@ -296,6 +296,7 @@ export default function PipelineSeries() {
onSeriesUpdate={updateSeriesFromServer}
onIssuesUpdate={handleIssuesUpdate}
onFlushPending={flushPending}
+ onRegisterDraftFlush={registerDraftFlush}
/>
</section>
</div>
diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsx
index bb166b7038..aa7314941a 100644
--- a/client/src/pages/StoryBuilder.jsx
+++ b/client/src/pages/StoryBuilder.jsx
@@ -661,7 +661,7 @@ function RefineBox({ onRefine, disabled, busy, running, phase }) {
);
}
-function StepPanel({ session, universe, series, issues, stepId, locked, onChanged, onSeriesUpdate, onIssuesUpdate, onFlushPending, onUniverseCharRef }) {
+function StepPanel({ session, universe, series, issues, stepId, locked, onChanged, onSeriesUpdate, onIssuesUpdate, onFlushPending, onRegisterDraftFlush, onUniverseCharRef }) {
const { start, busy, phase, op } = useStoryStepRun(stepId);
const arc = series?.arc || {};
const isRunning = (which) => busy && op === which;
@@ -796,6 +796,7 @@ function StepPanel({ session, universe, series, issues, stepId, locked, onChange
onSeriesUpdate={onSeriesUpdate}
onIssuesUpdate={onIssuesUpdate}
onFlushPending={onFlushPending}
+ onRegisterDraftFlush={onRegisterDraftFlush}
/>
</div>
) : (
@@ -1133,7 +1134,7 @@ function StoryBuilderDetail({ storyId, stepParam }) {
// server-confirmed setters. The flush is usually a no-op here (the bible
// fields are edited on their own steps, not inside the arc step), so a
// pre-flush save failure is swallowed (silent) rather than toasted.
- const { updateSeriesFromServer, handleIssuesUpdate, flushPending } = useArcCanvasSync({
+ const { updateSeriesFromServer, handleIssuesUpdate, flushPending, registerDraftFlush } = useArcCanvasSync({
series,
setSeries,
setIssues,
@@ -1173,7 +1174,15 @@ function StoryBuilderDetail({ storyId, stepParam }) {
}, [stepIds, session, staleSteps]);
const lock = useLockToggle({
- patchFn: (next) => (next ? lockStoryStep(storyId, activeStepId, { silent: true }) : unlockStoryStep(storyId, activeStepId, { silent: true })),
+ // Locking makes the step read-only server-side, so anything still pending
+ // on screen (dirty bible fields, an open Arc Canvas editor) must land
+ // FIRST — otherwise its save is rejected by the fresh lock and the user's
+ // last edits are silently lost (#3907). Unlocking re-opens the step and has
+ // nothing to preserve, so it skips the flush.
+ patchFn: async (next) => {
+ if (next) await flushPending();
+ return next ? lockStoryStep(storyId, activeStepId, { silent: true }) : unlockStoryStep(storyId, activeStepId, { silent: true });
+ },
onSuccess: (_updated, next) => {
reload();
// "Lock & continue" should actually continue — on a successful LOCK,
@@ -1387,6 +1396,7 @@ function StoryBuilderDetail({ storyId, stepParam }) {
onSeriesUpdate={updateSeriesFromServer}
onIssuesUpdate={handleIssuesUpdate}
onFlushPending={flushPending}
+ onRegisterDraftFlush={registerDraftFlush}
onUniverseCharRef={applyUniverseCharRef}
/>
diff --git a/client/src/pages/StoryBuilder.test.jsx b/client/src/pages/StoryBuilder.test.jsx
index 79008725a0..c7136a502b 100644
--- a/client/src/pages/StoryBuilder.test.jsx
+++ b/client/src/pages/StoryBuilder.test.jsx
@@ -65,11 +65,18 @@ const toastMock = vi.hoisted(() => {
});
vi.mock('../components/ui/Toast', () => ({ default: toastMock, toast: toastMock, Toaster: () => null }));
+// Stand-in for the committer ArcContent hands up through ArcCanvas when its
+// logline / summary / protagonist-arc editor is open with unsaved text.
+const arcDraftFlush = vi.hoisted(() => vi.fn(async () => true));
+
// The plotArc step embeds the full ArcCanvas roadmap editor; mock it to an
// inert sentinel so these tests assert the EMBEDDING (and its props) without
// pulling ArcCanvas's heavy import graph or its own API calls into scope.
vi.mock('../components/pipeline/ArcCanvas', () => ({
- default: ({ series }) => <div data-testid="arc-canvas">ArcCanvas[{series?.id}]</div>,
+ default: ({ series, onRegisterDraftFlush }) => {
+ onRegisterDraftFlush?.(arcDraftFlush);
+ return <div data-testid="arc-canvas">ArcCanvas[{series?.id}]</div>;
+ },
}));
import StoryBuilder, { composeSeedFromIngredients } from './StoryBuilder';
@@ -477,6 +484,42 @@ describe('StoryBuilder — detail stepper', () => {
await waitFor(() => expect(api.setStoryCurrentStep).toHaveBeenCalledWith('stb-1', 'universeAesthetic', expect.anything()));
});
+ it('"Lock & continue" flushes the open Arc Canvas draft BEFORE locking the step', async () => {
+ const { fireEvent } = await import('@testing-library/react');
+ api.getStorySession.mockResolvedValue({
+ id: 'stb-1', title: 'Salt Run', currentStep: 'plotArc', seedIdea: 'seed',
+ universeId: 'u1', seriesId: 's1',
+ steps: mkSteps({ idea: { locked: true }, universeAesthetic: { locked: true } }),
+ staleSteps: [], llm: { provider: '', model: '' },
+ });
+ renderAt('/story-builder/stb-1/plotArc');
+ await waitFor(() => expect(screen.getByTestId('arc-canvas')).toBeTruthy());
+
+ fireEvent.click(screen.getByText('Lock & continue'));
+ await waitFor(() => expect(api.lockStoryStep).toHaveBeenCalledWith('stb-1', 'plotArc', expect.anything()));
+ // Locking makes the step read-only (and unmounts the canvas), so the
+ // pending draft has to land first or the edit is silently lost.
+ expect(arcDraftFlush).toHaveBeenCalled();
+ expect(arcDraftFlush.mock.invocationCallOrder[0])
+ .toBeLessThan(api.lockStoryStep.mock.invocationCallOrder[0]);
+ });
+
+ it('"Unlock to revise" does NOT flush — unlocking re-opens the step, nothing to preserve', async () => {
+ const { fireEvent } = await import('@testing-library/react');
+ api.getStorySession.mockResolvedValue({
+ id: 'stb-1', title: 'Salt Run', currentStep: 'plotArc', seedIdea: 'seed',
+ universeId: 'u1', seriesId: 's1',
+ steps: mkSteps({ idea: { locked: true }, universeAesthetic: { locked: true }, plotArc: { locked: true } }),
+ staleSteps: [], llm: { provider: '', model: '' },
+ });
+ renderAt('/story-builder/stb-1/plotArc');
+ await waitFor(() => expect(screen.getByText('Unlock to revise')).toBeTruthy());
+
+ fireEvent.click(screen.getByText('Unlock to revise'));
+ await waitFor(() => expect(api.unlockStoryStep).toHaveBeenCalledWith('stb-1', 'plotArc', expect.anything()));
+ expect(arcDraftFlush).not.toHaveBeenCalled();
+ });
+
it('manual step click: a rejected pointer move stays put and resyncs (no navigation)', async () => {
const { fireEvent } = await import('@testing-library/react');
api.getStorySession.mockResolvedValue({