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 manuscript saves before a format switch (#3399)

[._.]/ Adam Eivyff2caacc3c59
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f5ff23b800..8781bb1827 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -44,3 +44,4 @@
- **Touch targets**: City HUD, writers dock, and music surfaces meet the 44px convention
- ~90 new falsifiability-verified tests across the changed surfaces; creative-director autopilot runs gain a 45-minute idle backstop
- **Manuscript issue tabs show which issues hold an unsaved edit.** Sections only persist onBlur, so typing in issue 3 and tabbing to issue 7 left the pending text with no cue anywhere on screen. The saved-content baselines the unload guard already tracked are now state rather than a bare ref, so the tab strip subscribes to them: an issue with content drifting from its last server-confirmed save gets a dot (and an "unsaved edits" tooltip) that clears when the save lands — and stays put when the save fails. (#3399)
+- **Switching manuscript formats no longer discards an unsaved section edit.** Sections save onBlur, but a format switch replaced the whole section list — and its baselines — so an edit that hadn't blurred (or whose save had failed) was dropped, and switching back refetched the server's older text. The switch now flushes pending saves first and aborts if one fails, leaving the text and its tab dot on screen. Saves are also queued per section, so the blur save and the switch's flush can't PATCH the same text twice and snapshot a redundant version. (#3399)
diff --git a/client/src/pages/PipelineManuscriptEditor.jsx b/client/src/pages/PipelineManuscriptEditor.jsx
index b83f4c0b1b..8aca3e0915 100644
--- a/client/src/pages/PipelineManuscriptEditor.jsx
+++ b/client/src/pages/PipelineManuscriptEditor.jsx
@@ -387,9 +387,20 @@ export default function PipelineManuscriptEditor() {
return reviewing ? 'Running editorial review…' : 'Run editorial review';
}, [reviewActive, reviewLatest, reviewing]);
+ // Switching formats replaces `sections` (and their baselines) wholesale, so an
+ // unsaved edit in the outgoing format would be dropped on the floor — the
+ // refetch on switching back returns the server's older text. Flush first and
+ // bail out if that save failed, leaving the text (and its tab dot) on screen.
+ // `flushPendingSectionSaves` is declared below; this only runs on click, long
+ // after the component body has evaluated.
const changeView = async (type) => {
if (type === viewType || switching) return;
setSwitching(true);
+ if (!(await flushPendingSectionSaves())) {
+ setSwitching(false);
+ toast('Kept this format open — your unsaved edit could not be saved');
+ return;
+ }
const manuscript = await getPipelineManuscript(seriesId, type, { silent: true }).catch((err) => {
toast.error(err.message || 'Failed to load that format');
return null;
@@ -419,11 +430,21 @@ export default function PipelineManuscriptEditor() {
const setSectionContent = (issueId, content) => patchSection(issueId, { content });
+ // Saves in flight, keyed by section. Two paths can target the same section at
+ // once — the onBlur save and the flush below (clicking the format switcher
+ // blurs the textarea, then immediately asks to swap formats) — and firing both
+ // PATCHes would snapshot a redundant version. Queuing behind the in-flight
+ // save lets the second call re-read the baseline and no-op once the first
+ // persisted that same text.
+ const pendingSaves = useRef(new Map());
+
const saveSectionContent = async (section, content) => {
const key = baselineKey(section);
+ const prior = pendingSaves.current.get(key);
+ if (prior) await prior;
if (baselineRef.current.get(key) === content) return;
setSaveState((prev) => ({ ...prev, [section.issueId]: 'saving' }));
- const result = await savePipelineManuscriptSection(
+ const run = savePipelineManuscriptSection(
seriesId,
section.issueId,
{ stageId: section.stageId, output: content },
@@ -432,6 +453,9 @@ export default function PipelineManuscriptEditor() {
toast.error(err.message || 'Failed to save manuscript edit');
return null;
});
+ pendingSaves.current.set(key, run);
+ const result = await run;
+ if (pendingSaves.current.get(key) === run) pendingSaves.current.delete(key);
if (result?.section) {
setBaseline(key, result.section.content);
patchSection(section.issueId, { versions: result.section.versions });
@@ -440,6 +464,17 @@ export default function PipelineManuscriptEditor() {
return result;
};
+ // Persist every pending onBlur edit before an action that swaps `sections`
+ // out from under them. Returns false when a save FAILED, so the caller aborts
+ // rather than discarding the user's text — `undefined` means the save was a
+ // no-op (an in-flight save already persisted it), which is not a failure.
+ const flushPendingSectionSaves = async () => {
+ const dirty = liveSectionsRef.current.filter((s) => isSectionDirty(baselineRef.current, s));
+ if (dirty.length === 0) return true;
+ const results = await Promise.all(dirty.map((s) => saveSectionContent(s, s.content)));
+ return results.every((r) => r !== null);
+ };
+
const saveSection = (section) => saveSectionContent(section, section.content);
// Clean up paste artifacts (PDF drop-caps, hyphen splits, hard-wrapped lines)
diff --git a/client/src/pages/PipelineManuscriptEditor.test.jsx b/client/src/pages/PipelineManuscriptEditor.test.jsx
index 0598d0a4fd..e36563fd4c 100644
--- a/client/src/pages/PipelineManuscriptEditor.test.jsx
+++ b/client/src/pages/PipelineManuscriptEditor.test.jsx
@@ -262,6 +262,66 @@ describe('PipelineManuscriptEditor', () => {
expect(screen.getByLabelText('Issue 1 has unsaved edits')).toBeInTheDocument();
});
+ // A format switch replaces `sections` (and their baselines) wholesale, so an
+ // unsaved edit in the outgoing format has to be persisted first or it's gone.
+ const mockBothFormats = () => api.getPipelineManuscript.mockImplementation((_id, type) => Promise.resolve(type === 'teleplay'
+ ? { sections: [{ issueId: 'iss-1', number: 1, title: 'One', stageId: 'teleplay', content: 'INT. ROOM - DAY' }], viewType: 'teleplay', availableTypes: ['prose', 'teleplay'] }
+ : { sections: [{ issueId: 'iss-1', number: 1, title: 'One', stageId: 'prose', content: 'The hero walked in. She left.' }], viewType: 'prose', pinnedPrimary: 'prose', availableTypes: ['prose', 'teleplay'] }));
+
+ const savedProse = {
+ section: { issueId: 'iss-1', number: 1, title: 'One', stageId: 'prose', content: 'The hero walked in. She stayed.', versions: [] },
+ };
+
+ it('flushes an unblurred edit before switching formats, so it is not discarded (#3399)', async () => {
+ mockBothFormats();
+ api.savePipelineManuscriptSection.mockResolvedValue(savedProse);
+ renderEditor();
+ const ta = await screen.findByDisplayValue('The hero walked in. She left.');
+ fireEvent.change(ta, { target: { value: 'The hero walked in. She stayed.' } });
+
+ // No blur — the switch itself has to persist the pending text.
+ fireEvent.click(screen.getByText('Teleplay'));
+
+ expect(await screen.findByDisplayValue('INT. ROOM - DAY')).toBeInTheDocument();
+ expect(api.savePipelineManuscriptSection).toHaveBeenCalledWith(
+ 'ser-1', 'iss-1', { stageId: 'prose', output: 'The hero walked in. She stayed.' }, { silent: true },
+ );
+ // …and the format fetch waited for it, so it can't read back pre-save text.
+ expect(api.savePipelineManuscriptSection.mock.invocationCallOrder[0])
+ .toBeLessThan(api.getPipelineManuscript.mock.invocationCallOrder.at(-1));
+ });
+
+ it('does not double-PATCH when the blur save and the format flush race (#3399)', async () => {
+ mockBothFormats();
+ api.savePipelineManuscriptSection.mockResolvedValue(savedProse);
+ renderEditor();
+ const ta = await screen.findByDisplayValue('The hero walked in. She left.');
+ fireEvent.change(ta, { target: { value: 'The hero walked in. She stayed.' } });
+
+ // A real click blurs the textarea first, so the blur save is already in
+ // flight when the switch flushes — the flush must queue behind it and
+ // no-op, not snapshot a second version of identical text.
+ fireEvent.blur(ta);
+ fireEvent.click(screen.getByText('Teleplay'));
+
+ expect(await screen.findByDisplayValue('INT. ROOM - DAY')).toBeInTheDocument();
+ expect(api.savePipelineManuscriptSection).toHaveBeenCalledTimes(1);
+ });
+
+ it('aborts a format switch when the pending edit fails to save (#3399)', async () => {
+ api.savePipelineManuscriptSection.mockResolvedValue(null);
+ renderEditor();
+ const ta = await screen.findByDisplayValue('The hero walked in. She left.');
+ fireEvent.change(ta, { target: { value: 'The hero walked in. She stayed.' } });
+ fireEvent.click(screen.getByText('Teleplay'));
+
+ await waitFor(() => expect(api.savePipelineManuscriptSection).toHaveBeenCalled());
+ // Still on prose, with the edit and its tab marker intact.
+ expect(screen.getByDisplayValue('The hero walked in. She stayed.')).toBeInTheDocument();
+ expect(screen.getByLabelText('Issue 1 has unsaved edits')).toBeInTheDocument();
+ expect(api.getPipelineManuscript).not.toHaveBeenCalledWith('ser-1', 'teleplay', { silent: true });
+ });
+
it('Review mode renders annotated prose with an Edit toggle that swaps in the textarea', async () => {
renderEditor();
await screen.findByText('My Series');