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: retain editor changes across draft transitions and failed saves

[._.]/ Adam Eivyc77a8b958817
diff --git a/client/src/components/writers-room/ExercisePanel.jsx b/client/src/components/writers-room/ExercisePanel.jsx
index 347eaa3812..dafccde269 100644
--- a/client/src/components/writers-room/ExercisePanel.jsx
+++ b/client/src/components/writers-room/ExercisePanel.jsx
@@ -20,7 +20,7 @@ const DURATION_PRESETS = [
{ label: '25 min', seconds: 1500 },
];
-export default function ExercisePanel({ activeWork, onClose, editorDirty = false, onWorkChange }) {
+export default function ExercisePanel({ activeWork, onClose, editorDirty = false, onWorkChange, draftMutation = null, beginDraftMutation, endDraftMutation }) {
const [history, setHistory] = useState([]);
const [duration, setDuration] = useState(600);
const [prompt, setPrompt] = useState('');
@@ -30,6 +30,11 @@ export default function ExercisePanel({ activeWork, onClose, editorDirty = false
const tickRef = useRef(null);
const mountedRef = useMounted();
+ const promotingRef = useRef(false);
+ const [promoting, setPromoting] = useState(false);
+ const ownerKey = `${activeWork?.id || ''}:${activeWork?.activeDraftVersionId || ''}`;
+ const ownerKeyRef = useRef(ownerKey);
+ ownerKeyRef.current = ownerKey;
const refresh = useCallback(async () => {
// Capture the workId we asked for so a slow response from the previous
@@ -106,14 +111,23 @@ export default function ExercisePanel({ activeWork, onClose, editorDirty = false
};
const promote = async (exercise) => {
+ if (promotingRef.current || editorDirty || draftMutation || exercise.workId !== activeWork?.id) return;
+ const startOwner = ownerKeyRef.current;
+ const transaction = beginDraftMutation?.(startOwner, 'exercise');
+ if (beginDraftMutation && !transaction) return;
+ promotingRef.current = true;
+ setPromoting(true);
const result = await promoteWritersRoomExercise(exercise.id, { silent: true }).catch((err) => {
toast.error(`Could not add to draft: ${err.message}`);
return null;
});
- if (!result) return;
+ endDraftMutation?.(transaction);
+ promotingRef.current = false;
+ if (mountedRef.current) setPromoting(false);
+ if (!result || ownerKeyRef.current !== startOwner) return;
toast.success(`Added ${countWords(exercise.appendedText)} words to draft`);
- onWorkChange?.(result.work);
- await refresh();
+ onWorkChange?.(result.work, { ownerKey: startOwner });
+ if (mountedRef.current) await refresh();
};
// Toast once when the timer crosses into expired. The ref guards against
@@ -233,8 +247,8 @@ export default function ExercisePanel({ activeWork, onClose, editorDirty = false
{ex.status === 'finished' && ex.appendedText && ex.workId === activeWork?.id && !ex.promotedAt && (
<button
onClick={() => promote(ex)}
- disabled={editorDirty}
- title={editorDirty ? 'Save first' : 'Add to draft'}
+ disabled={editorDirty || promoting || !!draftMutation}
+ title={editorDirty ? 'Save first' : promoting || draftMutation ? 'Wait for the draft update' : 'Add to draft'}
aria-label="Add sprint text to draft"
className="min-h-[44px] min-w-[44px] flex items-center justify-center text-port-accent disabled:text-gray-600"
>
diff --git a/client/src/components/writers-room/ExercisePanel.test.jsx b/client/src/components/writers-room/ExercisePanel.test.jsx
index 4f20389413..461c392dd3 100644
--- a/client/src/components/writers-room/ExercisePanel.test.jsx
+++ b/client/src/components/writers-room/ExercisePanel.test.jsx
@@ -88,7 +88,7 @@ describe('ExercisePanel promote-to-draft button (#5300)', () => {
await act(async () => { fireEvent.click(promoteButton()); });
expect(promoteWritersRoomExercise).toHaveBeenCalledWith('wr-ex-1', { silent: true });
- expect(onWorkChange).toHaveBeenCalledWith({ id: 'wr-work-1', activeDraftBody: 'The hero wakes.\n\nThen he runs.\n' });
+ expect(onWorkChange).toHaveBeenCalledWith({ id: 'wr-work-1', activeDraftBody: 'The hero wakes.\n\nThen he runs.\n' }, { ownerKey: 'wr-work-1:wr-draft-1' });
expect(toast.success).toHaveBeenCalledWith('Added 3 words to draft');
// Mount load + the post-promote refresh, so the row can flip to the marker.
expect(listWritersRoomExercises).toHaveBeenCalledTimes(2);
diff --git a/client/src/components/writers-room/PolishPanel.jsx b/client/src/components/writers-room/PolishPanel.jsx
index 6be489fdfa..01ebcd52e8 100644
--- a/client/src/components/writers-room/PolishPanel.jsx
+++ b/client/src/components/writers-room/PolishPanel.jsx
@@ -33,7 +33,7 @@ const PHASE_LABEL = {
* onBodyChanged — async () => void; called after a completed run or a revert
* so the editor reloads the server-mutated body
*/
-export default function PolishPanel({ work, dirty, onBodyChanged }) {
+export default function PolishPanel({ work, dirty, blocked = false, onBusyChange, onBodyChanged }) {
const mountedRef = useMounted();
const [cycles, setCycles] = useState(1);
const [sseUrl, setSseUrl] = useState(null);
@@ -43,6 +43,10 @@ export default function PolishPanel({ work, dirty, onBodyChanged }) {
const { frames, latest, closed } = useSseProgress(sseUrl, { enabled: !!sseUrl });
const running = !!sseUrl && !closed;
+ useEffect(() => {
+ onBusyChange?.(starting || running || reverting != null);
+ return () => onBusyChange?.(false);
+ }, [starting, running, reverting, onBusyChange]);
const refreshSnapshots = useCallback(async () => {
const list = await listWritersRoomPolishSnapshots(work.id).catch(() => []);
@@ -81,7 +85,7 @@ export default function PolishPanel({ work, dirty, onBodyChanged }) {
}, [closed]);
const start = async () => {
- if (running || starting) return;
+ if (blocked || running || starting) return;
if (dirty) { toast.error('Save your draft first — polish runs on the saved version'); return; }
setStarting(true);
const res = await startWritersRoomPolish(work.id, { cycles }, { silent: true }).catch((err) => {
@@ -100,6 +104,7 @@ export default function PolishPanel({ work, dirty, onBodyChanged }) {
};
const revert = async (snapshotId) => {
+ if (blocked) return;
if (running) { toast.error('Wait for the current run to finish before reverting'); return; }
setReverting(snapshotId);
const ok = await revertWritersRoomPolishSnapshot(work.id, snapshotId, { silent: true }).catch((err) => {
@@ -161,7 +166,7 @@ export default function PolishPanel({ work, dirty, onBodyChanged }) {
) : (
<button
onClick={start}
- disabled={starting || dirty}
+ disabled={blocked || starting || dirty}
title={dirty ? 'Save your draft first — polish runs on the saved version' : 'Run the polish loop'}
className={`flex items-center gap-1.5 px-3 py-1.5 rounded text-sm ${
starting || dirty ? 'bg-port-bg text-gray-500' : 'bg-port-accent text-white hover:bg-port-accent/80'
@@ -237,7 +242,7 @@ export default function PolishPanel({ work, dirty, onBodyChanged }) {
padding so the snapshot list keeps its density. */}
<button
onClick={() => revert(s.id)}
- disabled={running || reverting === s.id}
+ disabled={blocked || running || reverting === s.id}
title="Revert the draft to this snapshot"
className="shrink-0 flex items-center justify-center gap-1 min-w-[44px] min-h-[44px] px-2 -my-1.5 -mr-2 text-gray-400 hover:text-white disabled:opacity-40 text-[11px]"
>
diff --git a/client/src/components/writers-room/PolishPanel.test.jsx b/client/src/components/writers-room/PolishPanel.test.jsx
index 43c5942a07..a497a3d451 100644
--- a/client/src/components/writers-room/PolishPanel.test.jsx
+++ b/client/src/components/writers-room/PolishPanel.test.jsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { render, screen, cleanup } from '@testing-library/react';
+import { act, fireEvent, render, screen, cleanup } from '@testing-library/react';
vi.mock('../../services/apiWritersRoom', () => ({
startWritersRoomPolish: vi.fn(),
@@ -17,6 +17,8 @@ import PolishPanel from './PolishPanel';
import {
getWritersRoomPolishStatus,
listWritersRoomPolishSnapshots,
+ startWritersRoomPolish,
+ revertWritersRoomPolishSnapshot,
} from '../../services/apiWritersRoom';
describe('PolishPanel', () => {
@@ -42,3 +44,25 @@ describe('PolishPanel', () => {
expect(revertBtn.className).toContain('min-w-[44px]');
});
});
+
+
+it('blocks server body mutations during a draft transition and reports pending revert ownership', async () => {
+ getWritersRoomPolishStatus.mockResolvedValue({ active: false });
+ listWritersRoomPolishSnapshots.mockResolvedValue([{ id: 'snap-1', label: 'Earlier draft', createdAt: '2026-01-01T00:00:00Z' }]);
+ const busy = vi.fn();
+ let resolve;
+ revertWritersRoomPolishSnapshot.mockReturnValueOnce(new Promise((yes) => { resolve = yes; }));
+ const props = { work: { id: 'work-1' }, dirty: false, onBusyChange: busy };
+ const view = render(<PolishPanel {...props} blocked />);
+ const revert = await screen.findByRole('button', { name: /revert/i });
+ expect(revert).toBeDisabled();
+ fireEvent.click(revert);
+ expect(revertWritersRoomPolishSnapshot).not.toHaveBeenCalled();
+ expect(startWritersRoomPolish).not.toHaveBeenCalled();
+ view.rerender(<PolishPanel {...props} />);
+ fireEvent.click(revert);
+ expect(busy).toHaveBeenLastCalledWith(true);
+ await act(async () => { resolve({ ok: true }); });
+ expect(busy).toHaveBeenLastCalledWith(false);
+ expect(revert).toBeEnabled();
+});
diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsx
index b5f9d2fe48..f5f7dedef1 100644
--- a/client/src/components/writers-room/WorkEditor.jsx
+++ b/client/src/components/writers-room/WorkEditor.jsx
@@ -108,8 +108,9 @@ function readSidebarTab() {
return STORYBOARD_TAB_VALUES.includes(stored) ? stored : STORYBOARD_TAB.BOARDS;
}
-export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOpen, onDirtyChange, headerCollapsed = false }) {
+export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOpen, onDirtyChange, headerCollapsed = false, draftMutation = null, beginDraftMutation, endDraftMutation }) {
const navigate = useNavigate();
+ const exercisePending = draftMutation?.kind === 'exercise';
const [body, setBody] = useState(work.activeDraftBody || '');
const [title, setTitle] = useState(work.title);
const [promoting, setPromoting] = useState(false);
@@ -118,6 +119,9 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
const [status, setStatus] = useState(work.status);
const [savedBody, setSavedBody] = useState(work.activeDraftBody || '');
const [saving, setSaving] = useState(false);
+ const [switchingDraft, setSwitchingDraft] = useState(false);
+ const [polishBusy, setPolishBusy] = useState(false);
+ const draftTransitionRef = useRef(false);
const [readingTheme, setReadingTheme] = useState(readReadingTheme);
const [characters, setCharacters] = useState([]);
const [places, setPlaces] = useState([]);
@@ -164,7 +168,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
// instantly; re-synced from the prop. The panel's imperative suggest fn and
// the post-typing debounce live in useLiveSuggest (below).
const [liveMode, setLiveMode] = useState(work.liveMode || null);
- useEffect(() => { setLiveMode(work.liveMode || null); }, [work.liveMode]);
+ useEffect(() => { setLiveMode(work.liveMode || null); }, [work.id, work.activeDraftVersionId, work.liveMode]);
// Shared live text-suggest usage counter. The continuation panel and the CD
// bridge BOTH draw on the same server-side daily budget, so a single mirror
// lives here (not one per panel) — otherwise the panel that didn't make the
@@ -271,8 +275,8 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
setTitle(work.title);
}, [work.id, work.activeDraftVersionId, work.activeDraftBody, work.title, savedBody, dirty]);
- useEffect(() => { setStatus(work.status); }, [work.status]);
- useEffect(() => { setTitle(work.title); }, [work.title]);
+ useEffect(() => { setStatus(work.status); }, [work.id, work.activeDraftVersionId, work.status]);
+ useEffect(() => { setTitle(work.title); }, [work.id, work.activeDraftVersionId, work.title]);
// The CharactersBible / PlacesBible drawers are the canonical editors;
// mirror their lists here so the storyboard's image-prompt enrichment picks
@@ -301,7 +305,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
return () => { active = false; };
}, [work.id]);
- useEffect(() => { onDirtyChange?.(dirty); }, [dirty, onDirtyChange]);
+ useEffect(() => { onDirtyChange?.(dirty || polishBusy || !!runningKind); }, [dirty, polishBusy, runningKind, onDirtyChange]);
const wordCount = useMemo(() => countWords(body), [body]);
// Live mirror of `body` for callbacks that only READ the prose (#3387).
@@ -330,17 +334,21 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
const savingRef = useRef(false);
const handleSaveRef = useRef(null);
handleSaveRef.current = async () => {
- if (savingRef.current) return;
+ if (savingRef.current || draftTransitionRef.current || polishBusy || exercisePending) return;
+ const startOwner = ownerKeyRef.current;
+ const transaction = beginDraftMutation?.(startOwner, 'save');
+ if (beginDraftMutation && !transaction) return;
savingRef.current = true;
setSaving(true);
const updated = await saveWritersRoomDraft(work.id, body, { silent: true }).catch((err) => {
if (mountedRef.current) toast.error(`Save failed: ${err.message}`);
return null;
});
+ endDraftMutation?.(transaction);
savingRef.current = false;
if (!mountedRef.current) return;
setSaving(false);
- if (!updated) return;
+ if (!updated || ownerKeyRef.current !== startOwner) return;
setSavedBody(body);
onChange?.(updated);
toast.success('Saved');
@@ -362,7 +370,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
// close/reload, and any in-app navigation (sidebar link, ⌘K, voice
// `ui_navigate`, browser Back) — otherwise the body reset in the effect above
// silently discards them. The confirm renders below the header banners.
- const routeGuard = useUnsavedChangesGuard(dirty);
+ const routeGuard = useUnsavedChangesGuard(dirty || switchingDraft || exercisePending);
const { proceed: proceedExit } = routeGuard;
const discardAndExit = useCallback(() => {
setBody(savedBody);
@@ -372,15 +380,25 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
useClickOutside(overflowRef, overflowOpen, () => setOverflowOpen(false));
const handleSnapshot = async () => {
+ if (savingRef.current || draftTransitionRef.current || polishBusy || runningKind || exercisePending) return;
if (dirty) {
toast('Save before snapshotting', { icon: '⚠️' });
return;
}
+ const startOwner = ownerKeyRef.current;
+ const transaction = beginDraftMutation?.(startOwner, 'version');
+ if (beginDraftMutation && !transaction) return;
+ draftTransitionRef.current = true;
+ setSwitchingDraft(true);
const updated = await snapshotWritersRoomDraft(work.id, undefined, { silent: true }).catch((err) => {
if (mountedRef.current) toast.error(`Snapshot failed: ${err.message}`);
return null;
});
- if (!updated || !mountedRef.current) return;
+ endDraftMutation?.(transaction);
+ draftTransitionRef.current = false;
+ if (!mountedRef.current) return;
+ setSwitchingDraft(false);
+ if (!updated || ownerKeyRef.current !== startOwner) return;
onChange?.({ ...updated, activeDraftBody: body });
toast.success(`Created ${updated.drafts[updated.drafts.length - 1].label}`);
};
@@ -415,39 +433,41 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
navigate(`/creative-director/${encodeURIComponent(work.cdProjectId)}/overview`);
};
+ const publishMetadata = useCallback((updated, fields, startOwner) => {
+ if (!updated || !mountedRef.current || ownerKeyRef.current !== startOwner) return false;
+ onChange?.(updated, { fields, ownerKey: startOwner });
+ return true;
+ }, [onChange, mountedRef]);
+
const commitTitle = async () => {
if (title === work.title) return;
+ const startOwner = ownerKeyRef.current;
const updated = await updateWritersRoomWork(work.id, { title }, { silent: true }).catch((err) => {
if (mountedRef.current) toast.error(`Title save failed: ${err.message}`);
return null;
});
- if (!updated || !mountedRef.current) return;
+ if (!publishMetadata(updated, ['title'], startOwner)) return;
if (updated.title !== title) setTitle(updated.title);
- onChange?.({ ...updated, activeDraftBody: body });
};
// useCallback + bodyRef: this is a StoryboardPanel prop, and the panel is
// memoized — a fresh identity per keystroke would defeat the memo boundary.
const commitImageStyle = useCallback(async (next) => {
- // Snapshot the buffer BEFORE awaiting: `updated` is this work's manifest, so
- // the body folded back into it must be the one that was on screen when the
- // style was committed. Reading bodyRef after the round-trip would splice a
- // different work's prose in if the user swapped works mid-flight.
- const bodyAtCommit = bodyRef.current;
+ const startOwner = ownerKeyRef.current;
const updated = await updateWritersRoomWork(work.id, { imageStyle: next }, { silent: true }).catch((err) => {
if (mountedRef.current) toast.error(`Style save failed: ${err.message}`);
return null;
});
- if (updated && mountedRef.current) {
- onChange?.({ ...updated, activeDraftBody: bodyAtCommit });
+ if (publishMetadata(updated, ['imageStyle'], startOwner)) {
toast.success(next.presetId === 'none' ? 'World style cleared' : 'World style saved');
}
- }, [work.id, onChange, mountedRef]);
+ }, [work.id, publishMetadata, mountedRef]);
// Persist the voice exemplars (#2179). Drop rows with a blank passage before
// sending (the server prunes them too, but this keeps the round-tripped state
// honest) and clear the drawer's dirty edits into the saved work.
const saveVoice = async () => {
+ const startOwner = ownerKeyRef.current;
const clean = (list) => (Array.isArray(list) ? list : [])
.map((e) => ({ passage: (e.passage || '').trim(), note: (e.note || '').trim() }))
.filter((e) => e.passage)
@@ -462,10 +482,9 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
});
if (!mountedRef.current) return;
setSavingVoice(false);
- if (updated) {
+ if (publishMetadata(updated, ['voiceExemplars', 'voiceAntiExemplars'], startOwner)) {
setVoiceExemplars(updated.voiceExemplars || []);
setVoiceAntiExemplars(updated.voiceAntiExemplars || []);
- onChange?.({ ...updated, activeDraftBody: body });
toast.success('Voice exemplars saved');
setDrawer(null);
}
@@ -507,6 +526,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
// restore focus + caret after the inserted text so the writer keeps flowing.
const insertAtCursor = useCallback((opt) => {
const ta = textareaRef.current;
+ if (draftTransitionRef.current || exercisePending) return;
const snippet = opt?.text || '';
if (!snippet) return;
const text = bodyRef.current;
@@ -525,59 +545,70 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
el.setSelectionRange(caret, caret);
});
toast('Inserted — save to persist', { icon: '✍️' });
- }, []);
+ }, [exercisePending]);
// Debounce a suggest after the writer pauses typing. Only arms while live
// mode is on and we're in the edit textarea; cleared on every keystroke and
// on unmount so a deferred fire can't hit a dead/closed editor.
const { registerTrigger: registerLiveTrigger, scheduleSuggest: scheduleLiveSuggest } = useLiveSuggest({
- enabled: liveEnabled && viewMode === 'edit',
+ enabled: liveEnabled && viewMode === 'edit' && !switchingDraft && !exercisePending,
debounceMs: liveDebounceMs,
});
const toggleLiveMode = useCallback(async () => {
+ const startOwner = ownerKeyRef.current;
const nextEnabled = !liveEnabled;
// Optimistic flip; the PATCH returns the persisted liveMode (with defaults
// filled in for a first opt-in) which we fold back through onChange.
setLiveMode((prev) => ({ ...(prev || {}), enabled: nextEnabled }));
const updated = await updateWritersRoomWork(work.id, { liveMode: { enabled: nextEnabled } }, { silent: true }).catch((err) => {
- if (mountedRef.current) {
+ if (mountedRef.current && ownerKeyRef.current === startOwner) {
toast.error(`Live mode save failed: ${err.message}`);
setLiveMode(work.liveMode || null);
}
return null;
});
- if (!updated || !mountedRef.current) return;
+ if (!publishMetadata(updated, ['liveMode'], startOwner)) return;
setLiveMode(updated.liveMode || null);
- onChange?.({ ...updated, activeDraftBody: body });
toast.success(nextEnabled ? 'Live director on' : 'Live director off');
- }, [liveEnabled, work.id, work.liveMode, body, onChange, mountedRef]);
+ }, [liveEnabled, work.id, work.liveMode, publishMetadata, mountedRef]);
const commitStatus = async (next) => {
if (next === status) return;
+ const startOwner = ownerKeyRef.current;
setStatus(next);
const updated = await updateWritersRoomWork(work.id, { status: next }, { silent: true }).catch((err) => {
- if (mountedRef.current) {
+ if (mountedRef.current && ownerKeyRef.current === startOwner) {
toast.error(`Status save failed: ${err.message}`);
setStatus(work.status);
}
return null;
});
- if (updated && mountedRef.current) onChange?.({ ...updated, activeDraftBody: body });
+ if (publishMetadata(updated, ['status'], startOwner)) setStatus(updated.status);
};
const switchToDraft = async (draftId) => {
- if (draftId === work.activeDraftVersionId) return;
+ if (draftId === work.activeDraftVersionId || draftTransitionRef.current || savingRef.current || polishBusy || runningKind || exercisePending) return;
if (dirty) {
toast('Save or snapshot before switching versions', { icon: '⚠️' });
return;
}
+ const startOwner = ownerKeyRef.current;
+ const transaction = beginDraftMutation?.(startOwner, 'version');
+ if (beginDraftMutation && !transaction) return;
+ draftTransitionRef.current = true;
+ setSwitchingDraft(true);
const updated = await setWritersRoomActiveDraft(work.id, draftId, { silent: true }).catch((err) => {
if (mountedRef.current) toast.error(`Switch failed: ${err.message}`);
return null;
});
- if (!updated || !mountedRef.current) return;
+ endDraftMutation?.(transaction);
+ draftTransitionRef.current = false;
+ if (!mountedRef.current) return;
+ setSwitchingDraft(false);
+ if (!updated || ownerKeyRef.current !== startOwner) return;
onChange?.(updated);
+ setDrawer(null);
};
// Shared analysis runner — the storyboard, overflow menu, and per-scene
@@ -586,7 +617,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
// back out by simply not saving. Characters refreshes the bible cache so
// the storyboard's prompt enrichment picks up new profiles immediately.
const runAnalysis = useCallback(async (kind) => {
- if (runningKind) return false;
+ if (runningKind || draftTransitionRef.current || savingRef.current || polishBusy || exercisePending) return false;
const startOwner = ownerKeyRef.current;
const startBody = bodyRef.current;
// Analysis reads the SAVED draft, so a buffer that was already dirty is not what gets formatted.
@@ -607,7 +638,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
if (!snapshot) return false;
// The writer moved to another work/draft while this ran; its result belongs
// to the old owner and must not touch the current buffer or bible lists.
- if (ownerKeyRef.current !== startOwner) return false;
+ if (ownerKeyRef.current !== startOwner || draftTransitionRef.current) return false;
if (snapshot.status === 'failed') {
toast.error(`${ANALYSIS_LABELS[kind] || kind} failed: ${snapshot.error || 'unknown'}`);
return false;
@@ -635,7 +666,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
}
}
return true;
- }, [runningKind, work.id]);
+ }, [runningKind, work.id, polishBusy, exercisePending]);
// Sequential pipeline for the 3-step storyboard setup. Run characters →
// places → script in order so each later step has the earlier bible to
@@ -650,6 +681,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
}, [runAnalysis, runningKind]);
const applyFormatText = (text) => {
+ if (draftTransitionRef.current || savingRef.current || exercisePending) return;
setBody(text);
toast('Applied to editor — save to persist', { icon: '💾' });
};
@@ -658,11 +690,12 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
// keep/revert). After a completed run or a manual revert, pull the fresh body
// back into the editor as the new saved baseline so the buffer isn't stale.
const reloadBodyFromServer = useCallback(async () => {
+ if (draftTransitionRef.current || exercisePending) return;
const startOwner = ownerKeyRef.current;
const startBody = bodyRef.current;
const wasDirty = startBody !== savedBodyRef.current;
const fresh = await getWritersRoomWork(work.id).catch(() => null);
- if (!fresh || !mountedRef.current || ownerKeyRef.current !== startOwner) return;
+ if (!fresh || !mountedRef.current || ownerKeyRef.current !== startOwner || draftTransitionRef.current) return;
const nextBody = fresh.activeDraftBody || '';
// Adopt the server body as the saved baseline always; replace the buffer
// only when the writer had nothing unsaved and typed nothing during the GET.
@@ -670,7 +703,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
if (!wasDirty && bodyRef.current === startBody) setBody(nextBody);
setSavedBody(nextBody);
onChange?.(fresh);
- }, [work.id, onChange, mountedRef]);
+ }, [work.id, onChange, mountedRef, exercisePending]);
const activeDraft = useMemo(
() => work.drafts?.find((d) => d.id === work.activeDraftVersionId),
@@ -831,7 +864,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
</div>
<button
onClick={handleSave}
- disabled={!dirty || saving}
+ disabled={!dirty || saving || switchingDraft || polishBusy || exercisePending}
className={`flex shrink-0 items-center justify-center gap-1 w-24 px-3 py-1 min-h-[44px] sm:min-h-0 text-xs rounded ${
dirty ? 'bg-port-accent text-white hover:bg-port-accent/80' : 'bg-port-bg text-gray-500'
}`}
@@ -843,7 +876,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
</button>
<button
onClick={handleSnapshot}
- disabled={dirty}
+ disabled={dirty || saving || switchingDraft || polishBusy || exercisePending}
aria-label="Snapshot"
className={`${headerCollapsed ? 'hidden' : 'flex'} items-center gap-1 px-3 py-1 min-h-[44px] sm:min-h-0 text-xs rounded bg-port-bg border border-port-border text-gray-300 hover:text-white disabled:text-gray-600 disabled:cursor-not-allowed`}
title="Snapshot the active draft as a new version"
@@ -863,11 +896,11 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
{overflowOpen && (
<div className="absolute right-0 top-full mt-1 z-30 w-60 rounded-md border border-port-border bg-port-card shadow-xl py-1 text-xs">
<MenuSection label="AI">
- <MenuItem icon={Clapperboard} label="Run Adapt (rebuild storyboard)" running={runningKind === ANALYSIS_KIND.SCRIPT} disabled={dirty} title={dirty ? 'Save first' : undefined} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.SCRIPT))} />
- <MenuItem icon={Users} label="Refresh characters" running={runningKind === ANALYSIS_KIND.CHARACTERS} disabled={dirty} title={dirty ? 'Save first' : undefined} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.CHARACTERS))} />
- <MenuItem icon={MapPin} label="Refresh places" running={runningKind === ANALYSIS_KIND.PLACES} disabled={dirty} title={dirty ? 'Save first' : undefined} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.PLACES))} />
- <MenuItem icon={Sparkles} label="Editorial pass" running={runningKind === ANALYSIS_KIND.EVALUATE} disabled={dirty} title={dirty ? 'Save first' : undefined} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.EVALUATE))} />
- <MenuItem icon={FileSignature} label="Format pass" running={runningKind === ANALYSIS_KIND.FORMAT} disabled={dirty} title={dirty ? 'Save first' : undefined} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.FORMAT))} />
+ <MenuItem icon={Clapperboard} label="Run Adapt (rebuild storyboard)" running={runningKind === ANALYSIS_KIND.SCRIPT} disabled={dirty || saving || switchingDraft || polishBusy || exercisePending} title={dirty ? 'Save first' : undefined} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.SCRIPT))} />
+ <MenuItem icon={Users} label="Refresh characters" running={runningKind === ANALYSIS_KIND.CHARACTERS} disabled={dirty || saving || switchingDraft || polishBusy || exercisePending} title={dirty ? 'Save first' : undefined} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.CHARACTERS))} />
+ <MenuItem icon={MapPin} label="Refresh places" running={runningKind === ANALYSIS_KIND.PLACES} disabled={dirty || saving || switchingDraft || polishBusy || exercisePending} title={dirty ? 'Save first' : undefined} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.PLACES))} />
+ <MenuItem icon={Sparkles} label="Editorial pass" running={runningKind === ANALYSIS_KIND.EVALUATE} disabled={dirty || saving || switchingDraft || polishBusy || exercisePending} title={dirty ? 'Save first' : undefined} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.EVALUATE))} />
+ <MenuItem icon={FileSignature} label="Format pass" running={runningKind === ANALYSIS_KIND.FORMAT} disabled={dirty || saving || switchingDraft || polishBusy || exercisePending} title={dirty ? 'Save first' : undefined} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.FORMAT))} />
<MenuItem icon={Wand2} label="Polish (cut → revise)" onClick={closeOverflowAnd(() => setDrawer(DRAWER.POLISH))} />
<MenuItem icon={Quote} label="Voice exemplars" onClick={closeOverflowAnd(() => setDrawer(DRAWER.VOICE))} />
<MenuItem icon={Zap} label={liveEnabled ? 'Disable live director' : 'Enable live director'} active={liveEnabled} onClick={closeOverflowAnd(toggleLiveMode)} />
@@ -906,9 +939,10 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
{/* A save in flight is about to settle the draft clean, and the guard
releases the parked navigation on its own — no confirm to flash. */}
+ {exercisePending && <div role="status" className="px-3 py-2 text-sm text-port-warning">Adding sprint text to draft…</div>}
<UnsavedChangesConfirm
guard={routeGuard}
- when={!saving}
+ when={!saving && !switchingDraft && !exercisePending}
question="Discard your unsaved changes to this work?"
label={`Discard unsaved changes to ${title || 'this work'}`}
onDiscard={discardAndExit}
@@ -978,7 +1012,9 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
<ProseEditor
ref={textareaRef}
value={body}
- onChange={(e) => { setBody(e.target.value); scheduleLiveSuggest(); }}
+ readOnly={switchingDraft || exercisePending}
+ aria-busy={switchingDraft || exercisePending}
+ onChange={(e) => { if (draftTransitionRef.current || exercisePending) return; setBody(e.target.value); scheduleLiveSuggest(); }}
readingTheme={readingTheme}
className="w-full h-full resize-none px-6 py-6 text-base focus:outline-none"
/>
@@ -1109,14 +1145,14 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
onStopOne={queueStopOne}
/>
- <Drawer open={drawer === DRAWER.VERSIONS} onClose={() => setDrawer(null)} title="Versions">
- <WorkEditorVersions work={work} dirty={dirty} onSwitch={(id) => { switchToDraft(id); setDrawer(null); }} />
+ <Drawer open={drawer === DRAWER.VERSIONS} onClose={() => { if (!draftTransitionRef.current) setDrawer(null); }} title="Versions">
+ <WorkEditorVersions work={work} dirty={dirty} pending={switchingDraft} disabled={saving || polishBusy || !!runningKind || exercisePending} onSwitch={switchToDraft} />
</Drawer>
<Drawer open={drawer === DRAWER.HISTORY} onClose={() => setDrawer(null)} title="Analysis history">
<AnalysisHistory work={work} activeHash={activeHash} onApplyFormat={applyFormatText} />
</Drawer>
- <Drawer open={drawer === DRAWER.POLISH} onClose={() => setDrawer(null)} title="Polish" size="md">
- <PolishPanel work={work} dirty={dirty} onBodyChanged={reloadBodyFromServer} />
+ <Drawer open={drawer === DRAWER.POLISH} onClose={() => { if (!polishBusy) setDrawer(null); }} title="Polish" size="md">
+ <PolishPanel work={work} dirty={dirty} blocked={switchingDraft || saving || exercisePending} onBusyChange={setPolishBusy} onBodyChanged={reloadBodyFromServer} />
</Drawer>
<Drawer open={drawer === DRAWER.VOICE} onClose={() => setDrawer(null)} title="Voice exemplars" size="md">
<WorkEditorVoicePanel
diff --git a/client/src/components/writers-room/WorkEditor.test.jsx b/client/src/components/writers-room/WorkEditor.test.jsx
index d4b296d331..809cb1af81 100644
--- a/client/src/components/writers-room/WorkEditor.test.jsx
+++ b/client/src/components/writers-room/WorkEditor.test.jsx
@@ -31,6 +31,11 @@ vi.mock('../../services/apiWritersRoom', async (importOriginal) => ({
listWritersRoomWorks: vi.fn(async () => []),
getWritersRoomWork: vi.fn(),
saveWritersRoomDraft: vi.fn(),
+ updateWritersRoomWork: vi.fn(),
+ setWritersRoomActiveDraft: vi.fn(),
+ snapshotWritersRoomDraft: vi.fn(),
+ listWritersRoomExercises: vi.fn(async () => []),
+ promoteWritersRoomExercise: vi.fn(),
runWritersRoomAnalysis: vi.fn(),
listWritersRoomCharacters: vi.fn(async () => []),
listWritersRoomPlaces: vi.fn(async () => []),
@@ -47,7 +52,7 @@ vi.mock('./LibraryPane', () => ({ default: () => <div>Library controls</div> }))
import WorkEditor from './WorkEditor';
import WritersRoom from '../../pages/WritersRoom';
-import { getWritersRoomWork, runWritersRoomAnalysis, saveWritersRoomDraft } from '../../services/apiWritersRoom';
+import { getWritersRoomWork, runWritersRoomAnalysis, saveWritersRoomDraft, updateWritersRoomWork, setWritersRoomActiveDraft, snapshotWritersRoomDraft, listWritersRoomExercises, promoteWritersRoomExercise } from '../../services/apiWritersRoom';
const work = {
id: 'wr-work-1',
@@ -446,3 +451,171 @@ describe('WorkEditor async buffer ownership (#9738)', () => {
expect(screen.getByRole('button', { name: 'Saved' })).toBeDisabled();
});
});
+
+
+describe('Writers Room metadata and draft transition safety', () => {
+ const versioned = { ...work, drafts: [...work.drafts, { id: 'draft-2', label: 'v2', wordCount: 2 }] };
+ const destination = { ...versioned, activeDraftVersionId: 'draft-2', activeDraftBody: 'Destination prose.' };
+ const deferred = () => {
+ let resolve;
+ let reject;
+ const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
+ return { promise, resolve, reject };
+ };
+ const renderPage = async () => {
+ getWritersRoomWork.mockResolvedValue(versioned);
+ const router = createMemoryRouter([
+ { path: '/writers-room/works/:workId', element: <WritersRoom /> },
+ { path: '/dashboard', element: <div>Destination page</div> },
+ ], { initialEntries: ['/writers-room/works/wr-work-1'] });
+ const view = render(<RouterProvider router={router} />);
+ await act(async () => {});
+ return { ...view, router, area: view.container.querySelector('textarea') };
+ };
+ const versions = async () => {
+ fireEvent.click(screen.getByLabelText('Work menu'));
+ fireEvent.click(screen.getByRole('button', { name: 'Versions' }));
+ await act(async () => {});
+ };
+
+ it('merges delayed metadata without restoring prose after a newer save or overwriting unrelated fields', async () => {
+ const status = deferred();
+ updateWritersRoomWork.mockImplementation((_id, patch) => patch.status ? status.promise : Promise.resolve({ ...versioned, title: 'New title' }));
+ const { area } = await renderPage();
+ fireEvent.change(screen.getByLabelText('Status'), { target: { value: 'complete' } });
+ fireEvent.change(screen.getByLabelText('Work title'), { target: { value: 'New title' } });
+ await act(async () => { fireEvent.blur(screen.getByLabelText('Work title')); });
+ fireEvent.change(area, { target: { value: 'New saved prose.' } });
+ saveWritersRoomDraft.mockResolvedValueOnce({ ...versioned, title: 'New title', activeDraftBody: 'New saved prose.' });
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Save' })); });
+ await act(async () => { status.resolve({ ...versioned, status: 'complete' }); });
+ expect(area).toHaveValue('New saved prose.');
+ expect(screen.getByLabelText('Status')).toHaveValue('complete');
+ expect(screen.getByLabelText('Work title')).toHaveValue('New title');
+ expect(screen.getByRole('button', { name: 'Saved' })).toBeDisabled();
+ });
+
+ it('keeps unsaved prose and drops metadata completion owned by a previous draft', async () => {
+ const first = deferred();
+ updateWritersRoomWork.mockReturnValueOnce(first.promise);
+ const { area } = await renderPage();
+ fireEvent.change(screen.getByLabelText('Status'), { target: { value: 'complete' } });
+ fireEvent.change(area, { target: { value: 'Unsaved prose.' } });
+ await act(async () => { first.resolve({ ...versioned, status: 'complete' }); });
+ expect(area).toHaveValue('Unsaved prose.');
+ expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled();
+ saveWritersRoomDraft.mockResolvedValueOnce({ ...versioned, status: 'complete', activeDraftBody: 'Unsaved prose.' });
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Save' })); });
+ const stale = deferred();
+ updateWritersRoomWork.mockReturnValueOnce(stale.promise);
+ fireEvent.change(screen.getByLabelText('Status'), { target: { value: 'drafting' } });
+ setWritersRoomActiveDraft.mockResolvedValueOnce(destination);
+ await versions();
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: /v2/ })); });
+ await act(async () => { stale.resolve({ ...versioned, status: 'drafting' }); });
+ expect(area).toHaveValue('Destination prose.');
+ expect(screen.getByRole('button', { name: 'Saved' })).toBeDisabled();
+ });
+
+ it('holds editing, repeated switches, shortcuts, snapshots and navigation until a pending switch settles', async () => {
+ const pending = deferred();
+ setWritersRoomActiveDraft.mockReturnValueOnce(pending.promise);
+ const { area, router } = await renderPage();
+ await versions();
+ fireEvent.click(screen.getByRole('button', { name: /v2/ }));
+ fireEvent.click(screen.getByRole('button', { name: /v2/ }));
+ expect(area).toHaveAttribute('readonly');
+ expect(screen.getByRole('button', { name: 'Snapshot' })).toBeDisabled();
+ expect(screen.getByRole('status')).toHaveTextContent('Switching draft');
+ fireEvent.change(area, { target: { value: 'Must not enter old draft' } });
+ fireEvent.keyDown(window, { key: 's', ctrlKey: true });
+ expect(saveWritersRoomDraft).not.toHaveBeenCalled();
+ expect(snapshotWritersRoomDraft).not.toHaveBeenCalled();
+ expect(setWritersRoomActiveDraft).toHaveBeenCalledOnce();
+ expect(area).toHaveValue(work.activeDraftBody);
+ await act(async () => { await router.navigate('/dashboard'); });
+ expect(router.state.location.pathname).toContain('/writers-room/');
+ await act(async () => { pending.resolve(destination); });
+ expect(screen.getByText('Destination page')).toBeInTheDocument();
+ });
+
+ it('restores controls after switch rejection and prevents switching while saving', async () => {
+ const pending = deferred();
+ setWritersRoomActiveDraft.mockReturnValueOnce(pending.promise);
+ const { area } = await renderPage();
+ await versions();
+ fireEvent.click(screen.getByRole('button', { name: /v2/ }));
+ await act(async () => { pending.reject(new Error('offline')); });
+ expect(area).not.toHaveAttribute('readonly');
+ expect(area).toHaveValue(work.activeDraftBody);
+ expect(screen.getByRole('button', { name: /v2/ })).toBeEnabled();
+ const save = deferred();
+ saveWritersRoomDraft.mockReturnValueOnce(save.promise);
+ fireEvent.change(area, { target: { value: 'New prose' } });
+ fireEvent.keyDown(window, { key: 's', ctrlKey: true });
+ expect(screen.getByRole('button', { name: /v2/ })).toBeDisabled();
+ fireEvent.click(screen.getByRole('button', { name: /v2/ }));
+ expect(setWritersRoomActiveDraft).toHaveBeenCalledOnce();
+ await act(async () => { save.resolve({ ...versioned, activeDraftBody: 'New prose' }); });
+ expect(screen.getByRole('button', { name: /v2/ })).toBeEnabled();
+ });
+
+ const openExercise = async () => {
+ listWritersRoomExercises.mockResolvedValue([{
+ id: 'exercise-1', workId: work.id, status: 'finished', appendedText: 'Sprint prose.', wordsAdded: 2,
+ }]);
+ fireEvent.click(screen.getByLabelText('Work menu'));
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Write for 10' })); });
+ };
+
+ it('holds promotion ownership after panel dismissal and excludes save, snapshot, switch, and navigation', async () => {
+ const promotion = deferred();
+ promoteWritersRoomExercise.mockReturnValueOnce(promotion.promise);
+ const { area, router } = await renderPage();
+ await openExercise();
+ fireEvent.click(screen.getByRole('button', { name: 'Add sprint text to draft' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Close exercise' }));
+ expect(area).toHaveAttribute('readonly');
+ expect(screen.getByRole('status')).toHaveTextContent('Adding sprint text');
+ fireEvent.keyDown(window, { key: 's', ctrlKey: true });
+ fireEvent.click(screen.getByRole('button', { name: 'Snapshot' }));
+ await versions();
+ expect(screen.getByRole('button', { name: /v2/ })).toBeDisabled();
+ fireEvent.click(screen.getByRole('button', { name: /v2/ }));
+ expect(saveWritersRoomDraft).not.toHaveBeenCalled();
+ expect(snapshotWritersRoomDraft).not.toHaveBeenCalled();
+ expect(setWritersRoomActiveDraft).not.toHaveBeenCalled();
+ await act(async () => { await router.navigate('/dashboard'); });
+ expect(router.state.location.pathname).toContain('/writers-room/');
+ await act(async () => { promotion.resolve({ work: { ...versioned, activeDraftBody: 'The hero wakes. Sprint prose.' } }); });
+ expect(screen.getByText('Destination page')).toBeInTheDocument();
+ expect(promoteWritersRoomExercise).toHaveBeenCalledOnce();
+ });
+
+ it('refuses promotion during a version transaction, then adopts a matching promotion into that destination', async () => {
+ const switching = deferred();
+ const promotion = deferred();
+ setWritersRoomActiveDraft.mockReturnValueOnce(switching.promise);
+ promoteWritersRoomExercise.mockReturnValueOnce(promotion.promise);
+ const { area } = await renderPage();
+ await openExercise();
+ await versions();
+ const promote = screen.getByRole('button', { name: 'Add sprint text to draft' });
+ act(() => {
+ fireEvent.click(screen.getByRole('button', { name: /v2/ }));
+ fireEvent.click(promote);
+ });
+ expect(promoteWritersRoomExercise).not.toHaveBeenCalled();
+ expect(promote).toBeDisabled();
+ await act(async () => { switching.resolve(destination); });
+ expect(promote).toBeEnabled();
+ fireEvent.click(promote);
+ fireEvent.click(promote);
+ expect(promoteWritersRoomExercise).toHaveBeenCalledOnce();
+ await act(async () => { promotion.resolve({ work: { ...destination, activeDraftBody: 'Destination prose. Sprint prose.' } }); });
+ expect(area).toHaveValue('Destination prose. Sprint prose.');
+ expect(area).not.toHaveAttribute('readonly');
+ expect(screen.getByRole('button', { name: 'Saved' })).toBeDisabled();
+ });
+
+});
diff --git a/client/src/components/writers-room/WorkEditorVersions.jsx b/client/src/components/writers-room/WorkEditorVersions.jsx
index ebe731a946..d76d7b37c2 100644
--- a/client/src/components/writers-room/WorkEditorVersions.jsx
+++ b/client/src/components/writers-room/WorkEditorVersions.jsx
@@ -5,7 +5,7 @@ import { listCatalogIngredientsForRef } from '../../services/apiCatalog';
// WorkEditorVersions — the Versions drawer body for WorkEditor: the draft
// version list with the referenced-ingredient chips under each row.
// Extracted from WorkEditor (#3387).
-export default function WorkEditorVersions({ work, dirty, onSwitch }) {
+export default function WorkEditorVersions({ work, dirty, pending = false, disabled = false, onSwitch }) {
const drafts = (work.drafts || []).slice().reverse();
// Resolve referenced ingredient ids (stored per draft version) into display
@@ -37,6 +37,7 @@ export default function WorkEditorVersions({ work, dirty, onSwitch }) {
}
return (
<>
+ {pending && <div role="status">Switching draft…</div>}
{dirty && (
<div className="mb-2 px-2 py-1.5 text-[11px] border border-port-warning/40 bg-port-warning/5 text-port-warning rounded">
Save or snapshot before switching versions — unsaved edits will be lost.
@@ -50,7 +51,7 @@ export default function WorkEditorVersions({ work, dirty, onSwitch }) {
<li key={draft.id}>
<button
onClick={() => onSwitch(draft.id)}
- disabled={isActive}
+ disabled={isActive || dirty || pending || disabled}
className={`w-full flex items-center justify-between gap-2 px-2 py-1.5 rounded text-left ${
isActive ? 'bg-port-accent/20 text-port-accent cursor-default' : 'text-gray-400 hover:bg-port-bg hover:text-white'
}`}
diff --git a/client/src/pages/VideoTimelineEditor.jsx b/client/src/pages/VideoTimelineEditor.jsx
index 8f34d7ae98..1d7a0816a3 100644
--- a/client/src/pages/VideoTimelineEditor.jsx
+++ b/client/src/pages/VideoTimelineEditor.jsx
@@ -29,6 +29,8 @@ import {
import { NumberField, FadeFields, RemoveButton } from '../components/media/VideoTimelineInspector';
import PageSkeleton from '../components/ui/PageSkeleton';
import TabPills from '../components/ui/TabPills';
+import UnsavedChangesConfirm from '../components/ui/UnsavedChangesConfirm';
+import useUnsavedChangesGuard from '../hooks/useUnsavedChangesGuard';
import {
assetUrl,
segmentDuration,
@@ -332,26 +334,40 @@ function TimelineProjectEditor({ projectId }) {
return next;
}, []);
+ const [pendingLanes, setPendingLanes] = useState(null);
+ const [saveError, setSaveError] = useState(null);
+ const [savePending, setSavePending] = useState(false);
const saveTimeline = useCallback((next) => queueWrite(async () => {
if (updatedAtRef.current == null) return false;
+ setSavePending(true);
+ setSaveError(null);
const updated = await api.updateTimelineProject(projectId, {
...timelinePatch(next),
expectedUpdatedAt: updatedAtRef.current,
}, { silent: true }).catch((err) => {
if (err.code === 'CONFLICT') {
- toast.error('Project was modified elsewhere — reloading');
- refresh();
+ if (pendingLanesRef.current) {
+ setSaveError('Project was modified elsewhere. Your edits are retained; retry after resolving the conflict, or discard to leave.');
+ } else {
+ toast.error('Project was modified elsewhere — reloading');
+ refresh();
+ }
return null;
}
+ setSaveError(`Save failed: ${err.message}`);
toast.error(`Save failed: ${err.message}`);
return null;
});
+ setSavePending(false);
if (!updated) return false;
updatedAtRef.current = updated.updatedAt;
setProject((p) => ({ ...p, updatedAt: updated.updatedAt }));
return true;
}).then((saved) => {
- if (saved && pendingLanesRef.current === next) pendingLanesRef.current = null;
+ if (saved && pendingLanesRef.current === next) {
+ pendingLanesRef.current = null;
+ setPendingLanes(null);
+ }
return saved;
}), [projectId, refresh, queueWrite]);
@@ -363,22 +379,28 @@ function TimelineProjectEditor({ projectId }) {
const queueSave = useCallback((next) => {
clearTimeout(saveTimerRef.current);
pendingLanesRef.current = next;
+ setPendingLanes(next);
saveTimerRef.current = setTimeout(() => {
saveTimerRef.current = null;
saveTimeline(next);
}, 400);
}, [saveTimeline]);
- // Keep the browser's native leave prompt active only while edits await save.
- useEffect(() => {
- const preventLeavingWithPendingSave = (event) => {
- if (pendingLanesRef.current == null) return;
- event.preventDefault();
- event.returnValue = '';
- };
- window.addEventListener('beforeunload', preventLeavingWithPendingSave);
- return () => window.removeEventListener('beforeunload', preventLeavingWithPendingSave);
- }, []);
+ // Both router navigation and tab close remain guarded until the latest
+ // snapshot succeeds. A failure must not turn an in-memory edit into "saved".
+ const routeGuard = useUnsavedChangesGuard(pendingLanes !== null);
+ const retrySave = () => {
+ clearTimeout(saveTimerRef.current);
+ saveTimerRef.current = null;
+ if (pendingLanesRef.current) saveTimeline(pendingLanesRef.current);
+ };
+ const discardAndExit = () => {
+ clearTimeout(saveTimerRef.current);
+ saveTimerRef.current = null;
+ pendingLanesRef.current = null;
+ setPendingLanes(null);
+ routeGuard.proceed();
+ };
// Navigation can unmount the editor before the debounce fires. Flush the
// latest lanes so the final edit is persisted instead of silently dropped.
@@ -899,6 +921,21 @@ function TimelineProjectEditor({ projectId }) {
return (
<div className="space-y-3">
+ {(saveError || routeGuard.blocked) && (
+ <div role="status" aria-label="Timeline save status" className="flex items-center gap-2 text-sm text-port-warning">
+ <span>{saveError || 'Saving timeline changes before leaving…'}</span>
+ <button type="button" onClick={retrySave} disabled={savePending} className="px-3 py-2 border border-port-border rounded disabled:opacity-50">
+ {savePending ? 'Saving…' : 'Retry save'}
+ </button>
+ </div>
+ )}
+ <UnsavedChangesConfirm
+ guard={routeGuard}
+ when={!savePending}
+ question="Discard your unsaved timeline changes?"
+ label="Discard unsaved timeline changes"
+ onDiscard={discardAndExit}
+ />
<div className="flex flex-wrap items-center justify-between gap-2 pb-3 border-b border-port-border">
<div className="flex items-center gap-2 flex-1 min-w-[120px]">
<button
diff --git a/client/src/pages/VideoTimelineEditor.keyboard.test.jsx b/client/src/pages/VideoTimelineEditor.keyboard.test.jsx
index 4e2a22ff8f..a2da6eb409 100644
--- a/client/src/pages/VideoTimelineEditor.keyboard.test.jsx
+++ b/client/src/pages/VideoTimelineEditor.keyboard.test.jsx
@@ -1,3 +1,4 @@
+import { createMemoryRouter, RouterProvider } from 'react-router';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import { awaitPageLoaded } from '../test/pageLoadBarrier';
@@ -18,11 +19,6 @@ vi.mock('../components/ui/Toast', () => ({
default: Object.assign(vi.fn(), { error: toastError, success: vi.fn() }),
}));
-vi.mock('react-router', () => ({
- useParams: () => ({ projectId: 'p1' }),
- useNavigate: () => vi.fn(),
-}));
-
vi.mock('../hooks/useSseProgress', () => ({
useSseProgress: () => ({ latest: null, closed: false }),
isTerminalSseFrame: () => false,
@@ -68,7 +64,8 @@ beforeEach(() => {
afterEach(() => restoreLayout());
const renderEditor = async () => {
- render(<VideoTimelineEditor />);
+ const router = createMemoryRouter([{ path: '/media/timeline/:projectId', element: <VideoTimelineEditor /> }], { initialEntries: ['/media/timeline/p1'] });
+ render(<RouterProvider router={router} />);
await awaitPageLoaded('Loading timeline project');
};
diff --git a/client/src/pages/VideoTimelineEditor.test.jsx b/client/src/pages/VideoTimelineEditor.test.jsx
index 38a66a64e0..2b8396c525 100644
--- a/client/src/pages/VideoTimelineEditor.test.jsx
+++ b/client/src/pages/VideoTimelineEditor.test.jsx
@@ -93,6 +93,7 @@ beforeEach(() => {
const renderEditorRoute = ({ strict = false } = {}) => {
const router = createMemoryRouter([
{ path: '/media/timeline/:projectId', element: <VideoTimelineEditor /> },
+ { path: '/media/timeline', element: <div>Project index</div> },
], { initialEntries: ['/media/timeline/p1'] });
const provider = <RouterProvider router={router} />;
return { ...render(strict ? <StrictMode>{provider}</StrictMode> : provider), router };
@@ -137,7 +138,7 @@ describe('route and refresh ownership', () => {
}), { silent: true });
});
- it('flushes A once through its existing write tail without owning B pending edits or token', async () => {
+ it('holds navigation until all A edits save through their tail, then gives B its own token', async () => {
const firstSave = deferred();
api.getTimelineProject.mockImplementation(async (id) => project({
id, name: id === 'p1' ? 'Example A' : 'Example B', updatedAt: id === 'p1' ? 'a1' : 'b1',
@@ -149,12 +150,12 @@ describe('route and refresh ownership', () => {
await waitFor(() => expect(api.updateTimelineProject).toHaveBeenCalledOnce(), { timeout: 1500 });
fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));
await act(async () => { await view.router.navigate('/media/timeline/p2'); });
- expect(await screen.findByRole('textbox', { name: 'Project name' })).toHaveValue('Example B');
+ expect(screen.getByRole('textbox', { name: 'Project name' })).toHaveValue('Example A');
+ await act(async () => { firstSave.resolve({ updatedAt: 'a2' }); });
+ await waitFor(() => expect(api.updateTimelineProject).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(screen.getByRole('textbox', { name: 'Project name' })).toHaveValue('Example B'));
expect(screen.getByText(/Add clips, stills, overlays and audio/)).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));
-
- await act(async () => { firstSave.resolve({ updatedAt: 'a2' }); });
- expect(api.updateTimelineProject).toHaveBeenCalledTimes(2);
expect(api.updateTimelineProject.mock.calls[1]).toEqual(['p1', expect.objectContaining({
expectedUpdatedAt: 'a2', segments: [expect.objectContaining({ clipId: CLIP_A }), expect.objectContaining({ clipId: CLIP_A })],
}), { silent: true }]);
@@ -598,3 +599,54 @@ describe('source-aware playback', () => {
});
});
});
+
+
+describe('timeline navigation after save failure', () => {
+ it('retains failed edits, guards internal navigation, and retries the latest snapshot before proceeding', async () => {
+ const view = renderEditorRoute();
+ await awaitPageLoaded('Loading timeline project');
+ vi.useFakeTimers();
+ try {
+ api.updateTimelineProject.mockRejectedValueOnce(new Error('offline'));
+ fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));
+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });
+ expect(screen.getByRole('status', { name: 'Timeline save status' })).toHaveTextContent('Save failed: offline');
+ fireEvent.click(screen.getByRole('button', { name: 'Back to projects' }));
+ expect(screen.getByRole('button', { name: 'Keep editing' })).toBeInTheDocument();
+ expect(view.router.state.location.pathname).toBe('/media/timeline/p1');
+ fireEvent.click(screen.getByRole('button', { name: 'Keep editing' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Back to projects' }));
+ const retry = deferred();
+ api.updateTimelineProject.mockReturnValueOnce(retry.promise);
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry save' })); });
+ expect(api.updateTimelineProject.mock.calls[1][1]).toMatchObject({ expectedUpdatedAt: 'u1', segments: [expect.any(Object), expect.any(Object)] });
+ const unload = new Event('beforeunload', { cancelable: true });
+ window.dispatchEvent(unload);
+ expect(unload.defaultPrevented).toBe(true);
+ expect(view.router.state.location.pathname).toBe('/media/timeline/p1');
+ await act(async () => { retry.resolve({ updatedAt: 'u2' }); });
+ expect(screen.getByText('Project index')).toBeInTheDocument();
+ expect(api.updateTimelineProject).toHaveBeenCalledTimes(2);
+ } finally { vi.useRealTimers(); }
+ });
+
+ it('keeps conflicting edits and requires explicit discard to leave without another write', async () => {
+ const view = renderEditorRoute();
+ await awaitPageLoaded('Loading timeline project');
+ vi.useFakeTimers();
+ try {
+ api.updateTimelineProject.mockRejectedValueOnce(Object.assign(new Error('conflict'), { code: 'CONFLICT' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Add to timeline' }));
+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });
+ expect(screen.getByRole('status', { name: 'Timeline save status' })).toHaveTextContent('Your edits are retained');
+ expect(api.getTimelineProject).toHaveBeenCalledOnce();
+ await act(async () => { await view.router.navigate('/media/timeline'); });
+ expect(view.router.state.location.pathname).toBe('/media/timeline/p1');
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Discard' })); });
+ expect(screen.getByText('Project index')).toBeInTheDocument();
+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });
+ expect(api.updateTimelineProject).toHaveBeenCalledOnce();
+ } finally { vi.useRealTimers(); }
+ });
+});
diff --git a/client/src/pages/WritersRoom.jsx b/client/src/pages/WritersRoom.jsx
index c8655b6729..8ab1f362c1 100644
--- a/client/src/pages/WritersRoom.jsx
+++ b/client/src/pages/WritersRoom.jsx
@@ -1,4 +1,4 @@
-import { useEffect, useState, useCallback } from 'react';
+import { useEffect, useState, useCallback, useRef } from 'react';
import { useParams, useNavigate, Link } from 'react-router';
import { NotebookPen, PanelLeftOpen, BookOpen, ChevronUp, ChevronDown } from 'lucide-react';
import PageHeader from '../components/PageHeader';
@@ -35,6 +35,15 @@ export default function WritersRoom() {
const [loadingWork, setLoadingWork] = useState(false);
const [showExercise, setShowExercise] = useState(false);
const [editorDirty, setEditorDirty] = useState(false);
+ const [draftMutation, setDraftMutation] = useState(null);
+ const draftMutationRef = useRef(null);
+ const activeWorkRef = useRef(activeWork);
+ activeWorkRef.current = activeWork;
+ const editorDirtyRef = useRef(editorDirty);
+ const handleEditorDirty = useCallback((dirty) => {
+ editorDirtyRef.current = dirty;
+ setEditorDirty(dirty);
+ }, []);
const [headerCollapsed, , toggleHeader] = useLocalStorageBool('wr.headerCollapsed', false);
// Opening a work collapses the library on mobile and desktop. Header
// controls have their own persisted disclosure for focused writing.
@@ -47,6 +56,24 @@ export default function WritersRoom() {
// page unmounts (rapid nav across pages).
const mountedRef = useMounted();
+ // The editor and its exercise sibling both write the active draft. Admission
+ // is synchronous; the state mirror only renders the pending controls. Keep
+ // ownership here so dismissing the exercise panel cannot release its write.
+ const beginDraftMutation = useCallback((ownerKey, kind) => {
+ const current = activeWorkRef.current;
+ if (draftMutationRef.current || !current || `${current.id}:${current.activeDraftVersionId || ''}` !== ownerKey) return null;
+ if (kind === 'exercise' && editorDirtyRef.current) return null;
+ const transaction = { ownerKey, kind };
+ draftMutationRef.current = transaction;
+ setDraftMutation(transaction);
+ return transaction;
+ }, []);
+ const endDraftMutation = useCallback((transaction) => {
+ if (draftMutationRef.current !== transaction) return;
+ draftMutationRef.current = null;
+ if (mountedRef.current) setDraftMutation(null);
+ }, [mountedRef]);
+
const refreshLibrary = useCallback(() => foldersResource.retry(), [foldersResource.retry]);
// Load the active work when the URL changes
@@ -83,19 +110,22 @@ export default function WritersRoom() {
if (!workId) setLibraryCollapsed(false);
}, [workId, setLibraryCollapsed]);
- const handleWorkChange = (updated) => {
- // Caller (WorkEditor) hands us the freshest manifest + activeDraftBody —
- // the server-side endpoints (PUT draft, POST snapshot, PATCH version,
- // PATCH work) all return the full shape now, so no separate reload is
- // required and there's no inconsistency window between server pointer
- // and client view.
+ const handleWorkChange = (updated, patch) => {
+ // Draft operations replace the owned record; metadata responses merge only
+ // their canonical fields so an older manifest cannot restore saved prose.
if (!mountedRef.current) return;
- setActiveWork(updated);
+ const fields = patch?.fields && Object.fromEntries(patch.fields.map((field) => [field, updated[field]]));
+ setActiveWork((current) => {
+ if (current?.id !== updated.id) return current;
+ if (patch?.ownerKey && `${current.id}:${current.activeDraftVersionId || ''}` !== patch.ownerKey) return current;
+ return fields ? { ...current, ...fields } : updated;
+ });
// Splice the updated row into the library list (title / status / word
// count) without refetching N manifests on every save.
setWorks((prev) => {
const activeDraft = (updated.drafts || []).find((d) => d.id === updated.activeDraftVersionId);
- const summary = {
+ const idx = prev.findIndex((w) => w.id === updated.id);
+ const summary = (idx >= 0 && fields) || {
id: updated.id,
folderId: updated.folderId,
title: updated.title,
@@ -107,7 +137,6 @@ export default function WritersRoom() {
createdAt: updated.createdAt,
updatedAt: updated.updatedAt,
};
- const idx = prev.findIndex((w) => w.id === updated.id);
const merged = idx < 0 ? summary : { ...prev[idx], ...summary };
const others = idx < 0 ? prev : [...prev.slice(0, idx), ...prev.slice(idx + 1)];
// Library is sorted by updatedAt desc — re-sort after the merge so a
@@ -238,7 +267,10 @@ export default function WritersRoom() {
onChange={handleWorkChange}
onToggleExercise={() => setShowExercise((s) => !s)}
exerciseOpen={showExercise}
- onDirtyChange={setEditorDirty}
+ onDirtyChange={handleEditorDirty}
+ draftMutation={draftMutation}
+ beginDraftMutation={beginDraftMutation}
+ endDraftMutation={endDraftMutation}
/>
</>
)}
@@ -246,7 +278,15 @@ export default function WritersRoom() {
{showExercise && (
<aside className="border-t lg:border-t-0 lg:border-l border-port-border bg-port-card/30 p-3 min-h-0 lg:overflow-y-auto">
- <ExercisePanel activeWork={activeWork} editorDirty={editorDirty} onWorkChange={handleWorkChange} onClose={() => setShowExercise(false)} />
+ <ExercisePanel
+ activeWork={activeWork}
+ editorDirty={editorDirty}
+ draftMutation={draftMutation}
+ beginDraftMutation={beginDraftMutation}
+ endDraftMutation={endDraftMutation}
+ onWorkChange={handleWorkChange}
+ onClose={() => setShowExercise(false)}
+ />
</aside>
)}
</div>