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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: preserve Writers Room edits when async format and polish results arrive (#9738)
[._.]/ Adam Eivycbe8a9d8ceb2
diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsxindex 7042b3bf2b..9a4d9ea015 100644--- a/client/src/components/writers-room/WorkEditor.jsx+++ b/client/src/components/writers-room/WorkEditor.jsx@@ -314,6 +314,14 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO// the value is current before any child effect or event handler runs.const bodyRef = useRef(body);bodyRef.current = body;+ // Same idea for the saved baseline and the work/draft identity: async+ // completions (Format pass, Polish refresh) compare against these at+ // resolution time instead of the values closed over when they started (#9738).+ const savedBodyRef = useRef(savedBody);+ savedBodyRef.current = savedBody;+ const ownerKey = `${work.id}:${work.activeDraftVersionId || ''}`;+ const ownerKeyRef = useRef(ownerKey);+ ownerKeyRef.current = ownerKey;const mountedRef = useMounted();@@ -579,6 +587,8 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO// the storyboard's prompt enrichment picks up new profiles immediately.const runAnalysis = useCallback(async (kind) => {if (runningKind) return false;+ const startOwner = ownerKeyRef.current;+ const startBody = bodyRef.current;setRunningKind(kind);setRunStartedAt(Date.now());const snapshot = await runWritersRoomAnalysis(work.id, { kind }, { silent: true }).catch((err) => {@@ -593,6 +603,9 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOsetRunningKind(null);setRunStartedAt(null);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 (snapshot.status === 'failed') {toast.error(`${ANALYSIS_LABELS[kind] || kind} failed: ${snapshot.error || 'unknown'}`);return false;@@ -608,8 +621,16 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOsetObjects(snapshot.result.mergedProfiles);}if (kind === 'format' && snapshot.result?.formattedBody) {- setBody(snapshot.result.formattedBody);- toast('Format applied to draft buffer — save to persist', { icon: '💾' });+ // Apply only if the buffer is untouched since the pass started. Comparing+ // text (not just a dirty flag) also catches edit-then-save, where the+ // buffer is clean again but no longer the analyzed source. The result+ // stays in Analysis history for explicit application.+ if (bodyRef.current !== startBody) {+ toast('Format result not applied — you edited the draft meanwhile. Apply it from Analysis history.', { icon: 'ℹ️' });+ } else {+ setBody(snapshot.result.formattedBody);+ toast('Format applied to draft buffer — save to persist', { icon: '💾' });+ }}return true;}, [runningKind, work.id]);@@ -635,10 +656,16 @@ 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 () => {+ 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) return;+ if (!fresh || !mountedRef.current || ownerKeyRef.current !== startOwner) return;const nextBody = fresh.activeDraftBody || '';- setBody(nextBody);+ // 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.+ // Otherwise the local draft stays and the dirty indicator reflects the diff.+ if (!wasDirty && bodyRef.current === startBody) setBody(nextBody);setSavedBody(nextBody);onChange?.(fresh);}, [work.id, onChange, mountedRef]);diff --git a/client/src/components/writers-room/WorkEditor.test.jsx b/client/src/components/writers-room/WorkEditor.test.jsxindex 91cd84e2d6..d4b296d331 100644--- a/client/src/components/writers-room/WorkEditor.test.jsx+++ b/client/src/components/writers-room/WorkEditor.test.jsx@@ -1,3 +1,4 @@+import { useState } from 'react';import { describe, it, expect, vi, beforeEach } from 'vitest';import { act, fireEvent, render, screen, within } from '@testing-library/react';import { createMemoryRouter, RouterProvider } from 'react-router';@@ -30,17 +31,23 @@ vi.mock('../../services/apiWritersRoom', async (importOriginal) => ({listWritersRoomWorks: vi.fn(async () => []),getWritersRoomWork: vi.fn(),saveWritersRoomDraft: vi.fn(),+ runWritersRoomAnalysis: vi.fn(),listWritersRoomCharacters: vi.fn(async () => []),listWritersRoomPlaces: vi.fn(async () => []),listWritersRoomObjects: vi.fn(async () => []),}));+vi.mock('./PolishPanel', () => ({+ default: function PolishPanelStub({ onBodyChanged }) {+ return <button onClick={() => onBodyChanged?.()}>Stub polish refresh</button>;+ },+}));vi.mock('../CatalogCastPanel', () => ({ default: () => <div>Catalog cast controls</div> }));vi.mock('./LibraryPane', () => ({ default: () => <div>Library controls</div> }));import WorkEditor from './WorkEditor';import WritersRoom from '../../pages/WritersRoom';-import { getWritersRoomWork, saveWritersRoomDraft } from '../../services/apiWritersRoom';+import { getWritersRoomWork, runWritersRoomAnalysis, saveWritersRoomDraft } from '../../services/apiWritersRoom';const work = {id: 'wr-work-1',@@ -326,3 +333,116 @@ describe('Writers Room focused writing', () => {expect(area.value).toBe('Second edit.');});});++// #9738: async Format / Polish results must not clobber newer local edits.+describe('WorkEditor async buffer ownership (#9738)', () => {+ const deferred = () => {+ let resolve;+ const promise = new Promise((r) => { resolve = r; });+ return { promise, resolve };+ };+ const type = (area, value) => act(async () => { fireEvent.change(area, { target: { value } }); });+ const openMenuItem = async (name) => {+ await act(async () => { fireEvent.click(screen.getByLabelText('Work menu')); });+ await act(async () => { fireEvent.click(screen.getByRole('button', { name }) ); });+ };+ // Mirrors the real parent: onChange feeds the saved work back down as the prop.+ function StatefulParent() {+ const [w, setW] = useState(work);+ return <WorkEditor work={w} onChange={setW} />;+ }+ const renderStateful = async () => {+ const router = createMemoryRouter([+ { path: '/writers-room', element: <StatefulParent /> },+ ], { initialEntries: ['/writers-room'] });+ const view = render(<RouterProvider router={router} />);+ await act(async () => {});+ return view;+ };+ const formatResult = { status: 'complete', result: { formattedBody: 'Old formatted text.' } };++ it('applies the format result to a clean, untouched editor', async () => {+ const { container } = await renderEditor();+ runWritersRoomAnalysis.mockResolvedValueOnce(formatResult);+ await openMenuItem(/Format pass/);+ expect(container.querySelector('textarea').value).toBe('Old formatted text.');+ });++ it('keeps text typed while the format pass is pending', async () => {+ const { container } = await renderEditor();+ const d = deferred();+ runWritersRoomAnalysis.mockReturnValueOnce(d.promise);+ await openMenuItem(/Format pass/);+ const area = container.querySelector('textarea');+ await type(area, 'Newest prose.');+ await act(async () => { d.resolve(formatResult); });+ expect(area.value).toBe('Newest prose.');+ expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled();+ });++ it('keeps newer prose that was edited and saved before the format response', async () => {+ const { container } = await renderStateful();+ const d = deferred();+ runWritersRoomAnalysis.mockReturnValueOnce(d.promise);+ await openMenuItem(/Format pass/);+ const area = container.querySelector('textarea');+ await type(area, 'Saved newer prose.');+ saveWritersRoomDraft.mockResolvedValueOnce({ ...work, activeDraftBody: 'Saved newer prose.' });+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Save' })); });+ expect(screen.getByRole('button', { name: 'Saved' })).toBeDisabled();+ await act(async () => { d.resolve(formatResult); });+ expect(area.value).toBe('Saved newer prose.');+ });++ it('ignores a format result for a work the editor has since swapped away from', async () => {+ const d = deferred();+ runWritersRoomAnalysis.mockReturnValueOnce(d.promise);+ const router = (w) => createMemoryRouter([+ { path: '/writers-room', element: <WorkEditor work={w} onChange={() => {}} /> },+ ], { initialEntries: ['/writers-room'] });+ const { container, rerender } = render(<RouterProvider router={router(work)} />);+ await act(async () => {});+ await openMenuItem(/Format pass/);+ const other = { ...work, id: 'wr-work-2', activeDraftVersionId: 'wr-draft-2', activeDraftBody: 'Other work.' };+ await act(async () => { rerender(<RouterProvider router={router(other)} />); });+ await act(async () => { d.resolve(formatResult); });+ expect(container.querySelector('textarea').value).toBe('Other work.');+ });++ const refresh = async () => {+ await act(async () => { fireEvent.click(screen.getByLabelText('Work menu')); });+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: /Polish/ })); });+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Stub polish refresh' })); });+ };++ it('keeps edits made during the polish refresh GET and moves the baseline to the server body', async () => {+ const { container } = await renderEditor();+ const d = deferred();+ getWritersRoomWork.mockReturnValueOnce(d.promise);+ await refresh();+ const area = container.querySelector('textarea');+ await type(area, 'Typed during GET.');+ await act(async () => { d.resolve({ ...work, activeDraftBody: 'Polished body.' }); });+ expect(area.value).toBe('Typed during GET.');+ // Still unsaved relative to the server's polished body.+ expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled();+ });++ it('keeps edits that were already dirty when the polish refresh began', async () => {+ const { container } = await renderEditor();+ const area = container.querySelector('textarea');+ await type(area, 'Dirty before refresh.');+ getWritersRoomWork.mockResolvedValueOnce({ ...work, activeDraftBody: 'Polished body.' });+ await refresh();+ expect(area.value).toBe('Dirty before refresh.');+ expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled();+ });++ it('adopts the polished body on a clean editor', async () => {+ const { container } = await renderStateful();+ getWritersRoomWork.mockResolvedValueOnce({ ...work, activeDraftBody: 'Polished body.' });+ await refresh();+ expect(container.querySelector('textarea').value).toBe('Polished body.');+ expect(screen.getByRole('button', { name: 'Saved' })).toBeDisabled();+ });+});