Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: keep newer manuscript edits when fix, revert and undo responses land (#9954)

Adam Eivy5412b76a5b31
diff --git a/client/src/components/pipeline/manuscript/ManuscriptCommentCard.jsx b/client/src/components/pipeline/manuscript/ManuscriptCommentCard.jsx
index 92f9b7c3ba..4722fd0951 100644
--- a/client/src/components/pipeline/manuscript/ManuscriptCommentCard.jsx
+++ b/client/src/components/pipeline/manuscript/ManuscriptCommentCard.jsx
@@ -103,19 +103,41 @@ export function UndoFixToast({ t, count, onUndo }) {
);
}
+// The saved section(s) an accept/undo response carries, as a flat list.
+export function acceptedSectionsOf({ section, sections } = {}) {
+ return Array.isArray(sections) && sections.length ? sections : [section].filter(Boolean);
+}
+
+// `issueId:stageId` keys for the sections a set of edits (or a response) touches,
+// so the page can settle just those drafts before a mutation. null = unknown
+// (an edit without both ids) and means "every section".
+export function sectionKeysOf(items) {
+ if (!items.length || !items.every((e) => e?.issueId && e?.stageId)) return null;
+ return [...new Set(items.map((e) => `${e.issueId}:${e.stageId}`))];
+}
+
+// Stands in when no page-owned `onBeginMutation` is wired (the card also renders
+// standalone): resolves undefined — not null, which means "abort" — so the
+// mutation proceeds without a snapshot.
+const NO_SNAPSHOT = () => Promise.resolve(undefined);
+
// Show the accept confirmation + Undo toast. `applyResult` re-applies the undo's
-// { comment, section, sections } through the same handler an accept uses.
-export function showAcceptedFixToast({ seriesId, commentId, count, applyResult }) {
+// { comment, section, sections } through the same handler an accept uses; the
+// undo rewrites the same sections the accept did, so `keys` scopes the page's
+// settle-then-snapshot step (`onBeginMutation`) that guards edits typed since.
+export function showAcceptedFixToast({ seriesId, commentId, count, keys = null, onBeginMutation = NO_SNAPSHOT, applyResult }) {
toast(
(t) => (
<UndoFixToast
t={t}
count={count}
onUndo={async () => {
+ const snapshot = await onBeginMutation(keys);
+ if (snapshot === null) return false;
const undone = await undoPipelineManuscriptFix(seriesId, commentId, { silent: true })
.catch((err) => { toast.error(err.message || 'Failed to undo the fix'); return null; });
if (!undone) return false;
- applyResult?.(undone);
+ applyResult?.(undone, snapshot);
return true;
}}
/>
@@ -208,6 +230,7 @@ export function CommentCardFromProps({ comment, commentCardProps, idScope }) {
modelOverride={commentCardProps.modelOverride}
onCommentChange={commentCardProps.onCommentChange}
onAccepted={commentCardProps.onAccepted}
+ onBeginMutation={commentCardProps.onBeginMutation}
draft={commentCardProps.fixDrafts[comment.id]}
onDraftChange={(entry) => commentCardProps.setCommentDraft(comment.id, entry)}
nav={nav}
@@ -216,7 +239,7 @@ export function CommentCardFromProps({ comment, commentCardProps, idScope }) {
}
export default function ManuscriptCommentCard({
- comment, seriesId, providerOverride, modelOverride, onCommentChange, onAccepted, idScope, draft, onDraftChange, nav,
+ comment, seriesId, providerOverride, modelOverride, onCommentChange, onAccepted, onBeginMutation = NO_SNAPSHOT, idScope, draft, onDraftChange, nav,
}) {
// Namespace form ids so two copies of an open comment don't share ids.
const scope = idScope || comment.id;
@@ -267,13 +290,20 @@ export default function ManuscriptCommentCard({
toast('Select at least one suggested edit to apply');
return;
}
+ // Settle any unsaved draft of the touched sections first (the server edits
+ // the persisted text), and snapshot them so a keystroke typed while the
+ // request is in flight survives the response (#9954).
+ const snapshot = await onBeginMutation(sectionKeysOf(selected));
+ if (snapshot === null) return;
const result = await runAccept(selected);
if (!result) return;
- onAccepted(result);
+ onAccepted(result, snapshot);
showAcceptedFixToast({
seriesId,
commentId: result.comment?.id || comment.id,
count: selected.length,
+ keys: sectionKeysOf(acceptedSectionsOf(result)),
+ onBeginMutation,
applyResult: onAccepted,
});
};
@@ -295,14 +325,18 @@ export default function ManuscriptCommentCard({
find: comment.anchorQuote,
replace: manualText,
};
+ const snapshot = await onBeginMutation(sectionKeysOf([edit]));
+ if (snapshot === null) return;
const result = await runAccept([edit]);
if (!result) return;
setManualMode(false);
- onAccepted(result);
+ onAccepted(result, snapshot);
showAcceptedFixToast({
seriesId,
commentId: result.comment?.id || comment.id,
count: 1,
+ keys: sectionKeysOf(acceptedSectionsOf(result)),
+ onBeginMutation,
applyResult: onAccepted,
});
};
diff --git a/client/src/components/pipeline/manuscript/ManuscriptCommentCard.test.jsx b/client/src/components/pipeline/manuscript/ManuscriptCommentCard.test.jsx
index 46483944fa..28b451942b 100644
--- a/client/src/components/pipeline/manuscript/ManuscriptCommentCard.test.jsx
+++ b/client/src/components/pipeline/manuscript/ManuscriptCommentCard.test.jsx
@@ -116,9 +116,10 @@ describe('ManuscriptCommentCard keyboard shortcuts (#1603)', () => {
expect(screen.getByText('accept')).toBeTruthy();
expect(screen.getByText('regenerate')).toBeTruthy();
pressKey('a');
- expect(acceptPipelineManuscriptFix).toHaveBeenCalledWith('ser-1', 'c1', expect.objectContaining({
+ // The request waits on the page's settle-and-snapshot step first (#9954).
+ await waitFor(() => expect(acceptPipelineManuscriptFix).toHaveBeenCalledWith('ser-1', 'c1', expect.objectContaining({
edits: expect.arrayContaining([expect.objectContaining({ replace: 'new text' })]),
- }), { silent: true });
+ }), { silent: true }));
await settle();
});
@@ -203,7 +204,9 @@ describe('ManuscriptCommentCard — accept toast offers Undo (#1609)', () => {
acceptPipelineManuscriptFix.mockResolvedValue({ comment: { ...withFix, status: 'accepted' }, sections: [] });
undoPipelineManuscriptFix.mockResolvedValue({ comment: { ...withFix, status: 'open' }, sections: [] });
const onAccepted = vi.fn();
- renderCard({ comment: withFix, onAccepted });
+ const snapshot = new Map([['iss-1:prose', 'before']]);
+ const onBeginMutation = vi.fn().mockResolvedValue(snapshot);
+ renderCard({ comment: withFix, onAccepted, onBeginMutation });
pressKey('a');
await waitFor(() => expect(acceptPipelineManuscriptFix).toHaveBeenCalled());
@@ -214,9 +217,11 @@ describe('ManuscriptCommentCard — accept toast offers Undo (#1609)', () => {
fireEvent.click(undoBtn);
await waitFor(() => expect(undoPipelineManuscriptFix).toHaveBeenCalledWith('ser-1', 'c1', { silent: true }));
// The undo result is re-applied through onAccepted (re-opens the finding).
+ // …with a snapshot taken at Undo time, so edits typed since survive it.
await waitFor(() => expect(onAccepted).toHaveBeenCalledWith(expect.objectContaining({
comment: expect.objectContaining({ status: 'open' }),
- })));
+ }), snapshot));
+ expect(onBeginMutation).toHaveBeenCalledTimes(2);
expect(await screen.findByText(/Fix undone/i)).toBeTruthy();
});
});
diff --git a/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.jsx b/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.jsx
index a44f36aa73..fc05828ff7 100644
--- a/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.jsx
+++ b/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.jsx
@@ -23,7 +23,7 @@ import Modal from '../../ui/Modal';
import HunkDiff from '../../ui/HunkDiff';
import toast from '../../ui/Toast';
import { planManuscriptEdits } from '../../../lib/applyManuscriptEdits';
-import { selectedEditsFor } from './ManuscriptCommentCard';
+import { selectedEditsFor, sectionKeysOf } from './ManuscriptCommentCard';
import { acceptPipelineManuscriptFix } from '../../../services/api';
import { STAGE_LABEL } from './constants';
@@ -44,7 +44,7 @@ function editsBySectionKey(comments, fixDrafts) {
return map;
}
-export default function ManuscriptImpactPreview({ open, onClose, seriesId, sections, comments, fixDrafts, onAccepted }) {
+export default function ManuscriptImpactPreview({ open, onClose, seriesId, sections, comments, fixDrafts, onAccepted, onBeginMutation }) {
// null when idle, { done, total } while the accept-all pass runs.
const [acceptState, setAcceptState] = useState(null);
@@ -94,19 +94,31 @@ export default function ManuscriptImpactPreview({ open, onClose, seriesId, secti
if (!targets.length) return;
setAcceptState({ done: 0, total: targets.length });
const errors = [];
+ let applied = 0;
for (const target of targets) {
+ // Settle + snapshot the touched sections per member: a draft typed while an
+ // earlier member was in flight is saved first, and a keystroke typed during
+ // this one survives its response (#9954). A save failure stops the batch.
+ const snapshot = onBeginMutation ? await onBeginMutation(sectionKeysOf(target.edits)) : undefined;
+ if (!mountedRef.current) return;
+ if (snapshot === null) {
+ errors.push('an unsaved edit could not be saved first');
+ break;
+ }
const result = await acceptPipelineManuscriptFix(seriesId, target.comment.id, { edits: target.edits }, { silent: true })
.catch((err) => {
errors.push(err?.message || 'accept failed');
return null;
});
if (!mountedRef.current) return;
- if (result) onAccepted(result);
+ if (result) {
+ applied += 1;
+ onAccepted(result, snapshot);
+ }
setAcceptState((s) => (s ? { ...s, done: s.done + 1 } : s));
}
if (!mountedRef.current) return;
setAcceptState(null);
- const applied = targets.length - errors.length;
if (errors.length) {
toast.error(`Applied ${applied} of ${targets.length} notes — ${errors.length} failed (${errors[0]}). The failed notes stay in the preview; regenerate those fixes.`);
} else {
diff --git a/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.test.jsx b/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.test.jsx
index f07867e3f0..7a671d7444 100644
--- a/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.test.jsx
+++ b/client/src/components/pipeline/manuscript/ManuscriptImpactPreview.test.jsx
@@ -57,6 +57,29 @@ describe('ManuscriptImpactPreview accept-all', () => {
expect(toast.error).not.toHaveBeenCalled();
});
+ it('settles + snapshots the touched section before each member and hands the snapshot to onAccepted (#9954)', async () => {
+ acceptPipelineManuscriptFix.mockResolvedValue({ comment: { id: 'cx', status: 'accepted' }, sections: [] });
+ const snapshots = [new Map([['i1:prose', 'a']]), new Map([['i2:prose', 'b']])];
+ const onBeginMutation = vi.fn().mockImplementation(() => Promise.resolve(snapshots[onBeginMutation.mock.calls.length - 1]));
+ const { onAccepted, onClose } = renderPreview({ onBeginMutation });
+ fireEvent.click(screen.getByText('Accept all 2 edits'));
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+ expect(onBeginMutation.mock.calls).toEqual([[['i1:prose']], [['i2:prose']]]);
+ expect(onAccepted.mock.calls.map((c) => c[1])).toEqual(snapshots);
+ });
+
+ it('stops the batch, keeping the modal open, when a section\'s unsaved draft cannot be saved (#9954)', async () => {
+ const onBeginMutation = vi.fn().mockResolvedValue(null);
+ const { onAccepted, onClose } = renderPreview({ onBeginMutation });
+ fireEvent.click(screen.getByText('Accept all 2 edits'));
+ await waitFor(() => expect(toast.error).toHaveBeenCalled());
+ expect(acceptPipelineManuscriptFix).not.toHaveBeenCalled();
+ expect(onBeginMutation).toHaveBeenCalledTimes(1);
+ expect(onAccepted).not.toHaveBeenCalled();
+ expect(onClose).not.toHaveBeenCalled();
+ expect(toast.error.mock.calls[0][0]).toMatch(/Applied 0 of 2/);
+ });
+
it('reports a partial failure, applies the rest, and keeps the modal open', async () => {
acceptPipelineManuscriptFix
.mockResolvedValueOnce({ comment: { id: 'c1', status: 'accepted' }, sections: [] })
diff --git a/client/src/pages/PipelineManuscriptEditor.jsx b/client/src/pages/PipelineManuscriptEditor.jsx
index d1c4322d3f..ac6a97dbcf 100644
--- a/client/src/pages/PipelineManuscriptEditor.jsx
+++ b/client/src/pages/PipelineManuscriptEditor.jsx
@@ -51,6 +51,7 @@ import ManuscriptIssueTabs from '../components/pipeline/manuscript/ManuscriptIss
import ManuscriptImpactPreview from '../components/pipeline/manuscript/ManuscriptImpactPreview';
import ManuscriptReadAloud from '../components/pipeline/manuscript/ManuscriptReadAloud';
import { MANUSCRIPT_TYPES, STAGE_LABEL } from '../components/pipeline/manuscript/constants';
+import { acceptedSectionsOf } from '../components/pipeline/manuscript/ManuscriptCommentCard';
import {
getPipelineSeries, updatePipelineSeries, getPipelineManuscript, getPipelineManuscriptReview,
savePipelineManuscriptSection, reformatPipelineManuscriptText, restorePipelineStageVersion,
@@ -509,16 +510,19 @@ export default function PipelineManuscriptEditor() {
// 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 () => {
+ // `keys` (baselineKey values) scopes the flush to the sections a mutation is
+ // about to touch; omitted means every section.
+ const flushPendingSectionSaves = async (keys = null) => {
// Drain what's already queued first: a section can be mid-save while its
// live text happens to match the baseline (typed, blurred, then typed back),
// which reads as "clean" — switching formats under that in-flight save would
// swap `sections` out from under it and land its result on the new format's
// badge. Re-derive dirty afterwards, so a queued save that FAILED shows up
// here and gets retried rather than silently passing the gate.
- const queued = [...pendingSaves.current.values()];
+ const wanted = keys ? new Set(keys) : null;
+ const queued = [...pendingSaves.current].filter(([key]) => !wanted || wanted.has(key)).map(([, tail]) => tail);
if (queued.length) await Promise.all(queued);
- const dirty = liveSectionsRef.current.filter((s) => isSectionDirty(baselineRef.current, s));
+ const dirty = liveSectionsRef.current.filter((s) => (!wanted || wanted.has(baselineKey(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);
@@ -580,16 +584,55 @@ export default function PipelineManuscriptEditor() {
if (saved) toast.success('Reformatted with AI');
};
+ // Server-side mutations (revert, accept, undo) rewrite persisted section text
+ // while the textareas stay editable. Two halves keep a keystroke typed after
+ // the action started from being erased by its response (#9954):
+ // beginSectionMutation — settle the touched sections' unsaved drafts so the
+ // server mutates the text the writer sees (null = a save failed; abort),
+ // then snapshot every section's current text.
+ // adoptSectionResult — the server's text becomes the saved baseline; it
+ // replaces the editable buffer only if that buffer is still exactly what
+ // the mutation started from. A newer draft is kept (dirty against the new
+ // baseline) and is NOT auto-saved over the server change.
+ const beginSectionMutation = async (keys = null) => {
+ if (!(await flushPendingSectionSaves(keys))) {
+ toast('Not applied — your unsaved edit could not be saved first');
+ return null;
+ }
+ return new Map(liveSectionsRef.current.map((s) => [baselineKey(s), s.content]));
+ };
+
+ // Returns true when a newer local draft was retained instead of replaced.
+ const adoptSectionResult = ({ issueId, stageId, content, versions }, snapshot) => {
+ const key = `${issueId}:${stageId}`;
+ const live = liveSectionsRef.current.find((s) => baselineKey(s) === key);
+ const retain = !!live && (isSectionDirty(baselineRef.current, live)
+ || (snapshot?.has(key) && snapshot.get(key) !== live.content));
+ setBaseline(key, content);
+ if (retain) {
+ patchSection(issueId, { versions });
+ return true;
+ }
+ patchSection(issueId, { content, versions });
+ setSaveState((prev) => ({ ...prev, [issueId]: 'saved' }));
+ return false;
+ };
+
+ const RETAINED_MESSAGE = 'Server change applied — your newer draft was kept; review it before saving';
+
const revertSection = async (section, runId) => {
+ const snapshot = await beginSectionMutation([baselineKey(section)]);
+ if (!snapshot) return null;
const result = await restorePipelineStageVersion(section.issueId, section.stageId, runId, { silent: true })
.catch((err) => { toast.error(err.message || 'Failed to revert'); return null; });
if (!result?.stage) return null;
- const content = result.stage.output || '';
const versions = (result.stage.runHistory || []).map((h) => ({ runId: h.runId, createdAt: h.createdAt }));
- setBaseline(baselineKey(section), content);
- patchSection(section.issueId, { content, versions });
- setSaveState((prev) => ({ ...prev, [section.issueId]: 'saved' }));
- toast.success('Reverted to the selected version');
+ const retained = adoptSectionResult(
+ { issueId: section.issueId, stageId: section.stageId, content: result.stage.output || '', versions },
+ snapshot,
+ );
+ if (retained) toast(RETAINED_MESSAGE);
+ else toast.success('Reverted to the selected version');
return result;
};
@@ -631,16 +674,15 @@ export default function PipelineManuscriptEditor() {
else setOpenCommentId(null);
};
- const applyAccepted = ({ comment, section, sections: changedSections }) => {
- const list = Array.isArray(changedSections) && changedSections.length ? changedSections : [section].filter(Boolean);
- list.forEach((changed) => {
+ const applyAccepted = (result, snapshot) => {
+ let retained = false;
+ acceptedSectionsOf(result).forEach((changed) => {
if (changed?.issueId && changed.stageId === viewType) {
- patchSection(changed.issueId, { content: changed.content, versions: changed.versions });
- setBaseline(baselineKey(changed), changed.content);
- setSaveState((prev) => ({ ...prev, [changed.issueId]: 'saved' }));
+ retained = adoptSectionResult(changed, snapshot) || retained;
}
});
- if (comment) updateCommentLocal(comment);
+ if (retained) toast(RETAINED_MESSAGE);
+ if (result.comment) updateCommentLocal(result.comment);
};
// Open editorial comments anchorable to the on-screen format, grouped by issue
@@ -725,6 +767,7 @@ export default function PipelineManuscriptEditor() {
modelOverride,
onCommentChange: updateCommentLocal,
onAccepted: applyAccepted,
+ onBeginMutation: beginSectionMutation,
fixDrafts,
setCommentDraft,
openNav: {
@@ -1039,6 +1082,7 @@ export default function PipelineManuscriptEditor() {
comments={comments.filter((c) => c.status === 'open' && c.fix)}
fixDrafts={fixDrafts}
onAccepted={applyAccepted}
+ onBeginMutation={beginSectionMutation}
/>
<ManuscriptReadAloud
diff --git a/client/src/pages/PipelineManuscriptEditor.test.jsx b/client/src/pages/PipelineManuscriptEditor.test.jsx
index 3608cabdef..4828d9713b 100644
--- a/client/src/pages/PipelineManuscriptEditor.test.jsx
+++ b/client/src/pages/PipelineManuscriptEditor.test.jsx
@@ -13,6 +13,7 @@ const api = vi.hoisted(() => ({
patchPipelineManuscriptComment: vi.fn(),
generatePipelineManuscriptFix: vi.fn(),
acceptPipelineManuscriptFix: vi.fn(),
+ undoPipelineManuscriptFix: vi.fn(),
analyzePipelineManuscriptCompleteness: vi.fn(),
startPipelineManuscriptCompleteness: vi.fn(),
cancelPipelineManuscriptCompleteness: vi.fn(),
@@ -798,3 +799,172 @@ describe('PipelineManuscriptEditor — generate-edits streamed review', () => {
});
});
});
+
+// Section mutations (revert / accept / undo) resolve after the writer may have
+// typed more — the response must not erase that newer draft (#9954).
+describe('PipelineManuscriptEditor — mutation responses vs newer edits (#9954)', () => {
+ const BASE = 'The hero walked in. She left.';
+ const FIXED = 'The hero walked in. She left, but paused.';
+ const fixed = { find: 'She left.', replace: 'She left, but paused.' };
+ const fixComment = { ...comment, fix: fixed };
+ const section = (content, extra = {}) => ({ issueId: 'iss-1', number: 1, title: 'One', stageId: 'prose', content, ...extra });
+ const dirtyBadge = () => screen.queryByLabelText('Issue 1 has unsaved edits');
+ const deferred = () => {
+ let resolve;
+ const promise = new Promise((res) => { resolve = res; });
+ return { promise, resolve };
+ };
+
+ const openVersionsAndRevert = async () => {
+ fireEvent.click(await screen.findByTitle('Show prior saved versions'));
+ fireEvent.click(screen.getByRole('button', { name: /Revert/ }));
+ };
+
+ const mockRestore = (output = 'An older draft.') => {
+ const held = deferred();
+ api.restorePipelineStageVersion.mockReturnValue(held.promise);
+ return { held, resolveWith: () => held.resolve({ stage: { output, runHistory: [{ runId: 'v1', createdAt: 't' }] } }) };
+ };
+
+ beforeEach(() => {
+ api.getPipelineManuscript.mockResolvedValue({
+ sections: [section(BASE, { versions: [{ runId: 'v1', createdAt: 't' }] })],
+ viewType: 'prose', primaryStageId: 'prose', pinnedPrimary: 'prose', availableTypes: ['prose'],
+ });
+ });
+
+ it('keeps text typed after Revert started, with the restored version as the new baseline', async () => {
+ const restore = mockRestore();
+ api.savePipelineManuscriptSection.mockResolvedValue({ section: section(`${BASE} More.`) });
+ renderEditor();
+ const ta = await screen.findByDisplayValue(BASE);
+ await openVersionsAndRevert();
+ await waitFor(() => expect(api.restorePipelineStageVersion).toHaveBeenCalled());
+
+ fireEvent.change(ta, { target: { value: `${BASE} More.` } });
+ expect(dirtyBadge()).toBeInTheDocument();
+ await act(async () => { restore.resolveWith(); });
+
+ expect(screen.getByDisplayValue(`${BASE} More.`)).toBe(ta);
+ expect(dirtyBadge()).toBeInTheDocument();
+ // Not auto-saved over the restore; the writer's own blur persists it.
+ expect(api.savePipelineManuscriptSection).not.toHaveBeenCalled();
+ fireEvent.blur(ta);
+ await waitFor(() => expect(api.savePipelineManuscriptSection).toHaveBeenCalledWith(
+ 'ser-1', 'iss-1', { stageId: 'prose', output: `${BASE} More.` }, { silent: true },
+ ));
+ });
+
+ it('adopts the restored text and clears the dirty state when the buffer was not touched', async () => {
+ const restore = mockRestore();
+ renderEditor();
+ await screen.findByDisplayValue(BASE);
+ await openVersionsAndRevert();
+ await act(async () => { restore.resolveWith(); });
+
+ expect(await screen.findByDisplayValue('An older draft.')).toBeInTheDocument();
+ expect(dirtyBadge()).not.toBeInTheDocument();
+ });
+
+ it('saves an unblurred draft before reverting, and aborts the revert when that save fails', async () => {
+ api.savePipelineManuscriptSection.mockRejectedValue(new Error('disk full'));
+ renderEditor();
+ const ta = await screen.findByDisplayValue(BASE);
+ await openVersionsAndRevert();
+ await act(async () => {});
+ // First click above ran with a clean buffer; make a draft, then retry.
+ api.restorePipelineStageVersion.mockClear();
+ fireEvent.change(ta, { target: { value: `${BASE} Draft.` } });
+ fireEvent.click(screen.getByRole('button', { name: /Revert/ }));
+
+ await waitFor(() => expect(api.savePipelineManuscriptSection).toHaveBeenCalled());
+ await act(async () => {});
+ expect(api.restorePipelineStageVersion).not.toHaveBeenCalled();
+ expect(screen.getByDisplayValue(`${BASE} Draft.`)).toBeInTheDocument();
+ expect(dirtyBadge()).toBeInTheDocument();
+ });
+
+ describe('accepting a fix', () => {
+ const openCardInLive = async () => {
+ const ta = await screen.findByDisplayValue(BASE);
+ const idx = BASE.indexOf('She left.') + 2;
+ ta.selectionStart = idx; ta.selectionEnd = idx;
+ fireEvent.click(ta);
+ await screen.findByText('Editorial note');
+ return ta;
+ };
+ const acceptResult = () => ({
+ comment: { ...fixComment, status: 'accepted' },
+ section: section(FIXED, { versions: [{ runId: 'v2', createdAt: 't' }] }),
+ });
+
+ beforeEach(() => {
+ api.getPipelineManuscriptReview.mockResolvedValue({ schemaVersion: 1, comments: [fixComment] });
+ });
+
+ it('keeps prose typed in Live while Accept is pending; the fixed text becomes the baseline', async () => {
+ const held = deferred();
+ api.acceptPipelineManuscriptFix.mockReturnValue(held.promise);
+ renderEditor();
+ const ta = await openCardInLive();
+ fireEvent.click(screen.getByText('Accept'));
+ await waitFor(() => expect(api.acceptPipelineManuscriptFix).toHaveBeenCalled());
+
+ fireEvent.change(ta, { target: { value: `${BASE} Appended.` } });
+ await act(async () => { held.resolve(acceptResult()); });
+
+ expect(screen.getByDisplayValue(`${BASE} Appended.`)).toBe(ta);
+ expect(dirtyBadge()).toBeInTheDocument();
+ expect(api.savePipelineManuscriptSection).not.toHaveBeenCalled();
+ });
+
+ it('adopts the fixed text and marks the section clean when nothing was typed', async () => {
+ api.acceptPipelineManuscriptFix.mockResolvedValue(acceptResult());
+ renderEditor();
+ await openCardInLive();
+ fireEvent.click(screen.getByText('Accept'));
+
+ expect(await screen.findByDisplayValue(FIXED)).toBeInTheDocument();
+ expect(dirtyBadge()).not.toBeInTheDocument();
+ });
+
+ it('persists an unblurred draft before the server applies the fix, and blocks Accept when that save fails', async () => {
+ api.savePipelineManuscriptSection.mockRejectedValue(new Error('offline'));
+ renderEditor();
+ const ta = await openCardInLive();
+ fireEvent.change(ta, { target: { value: `${BASE} Draft.` } });
+ fireEvent.click(screen.getByText('Accept'));
+
+ await waitFor(() => expect(api.savePipelineManuscriptSection).toHaveBeenCalledWith(
+ 'ser-1', 'iss-1', { stageId: 'prose', output: `${BASE} Draft.` }, { silent: true },
+ ));
+ await act(async () => {});
+ expect(api.acceptPipelineManuscriptFix).not.toHaveBeenCalled();
+ expect(screen.getByDisplayValue(`${BASE} Draft.`)).toBeInTheDocument();
+ });
+
+ it('keeps text typed while the toast Undo is pending', async () => {
+ api.acceptPipelineManuscriptFix.mockResolvedValue(acceptResult());
+ const held = deferred();
+ api.undoPipelineManuscriptFix.mockReturnValue(held.promise);
+ const toast = (await import('../components/ui/Toast')).default;
+ renderEditor();
+ await openCardInLive();
+ fireEvent.click(screen.getByText('Accept'));
+ const ta = await screen.findByDisplayValue(FIXED);
+
+ const render = toast.mock.calls.map((c) => c[0]).find((arg) => typeof arg === 'function');
+ const { getByRole } = (await import('@testing-library/react')).render(render({ id: 't1' }));
+ fireEvent.click(getByRole('button', { name: /Undo/ }));
+ await waitFor(() => expect(api.undoPipelineManuscriptFix).toHaveBeenCalled());
+
+ fireEvent.change(ta, { target: { value: `${FIXED} Later.` } });
+ await act(async () => {
+ held.resolve({ comment: fixComment, section: section(BASE, { versions: [] }) });
+ });
+
+ expect(screen.getByDisplayValue(`${FIXED} Later.`)).toBe(ta);
+ expect(dirtyBadge()).toBeInTheDocument();
+ });
+ });
+});