Skip to content

Commit 4713138

Browse files
fix(studio): drain pending edits before reload (#2989)
* fix(studio): drain pending edits before reload * fix(studio): address drain review feedback (#2989) - prioritize conflicts and clear recovered DOM queue errors - cover delayed blur effects and missing drain branches - document stacked consumers and extend write-token retention * test(studio): satisfy drain audit gate (#2989) - share the editor-save hook harness across drain regressions - extract settled failure inspection from the drain loop
1 parent 552419c commit 4713138

9 files changed

Lines changed: 513 additions & 48 deletions
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
// @vitest-environment happy-dom
2+
import { act } from "react";
3+
import { createRoot } from "react-dom/client";
4+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5+
import { useEditorSave, type EditorSaveHandle } from "./useEditorSave";
6+
import { StudioFileConflictError } from "../utils/studioSaveDiagnostics";
7+
8+
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
9+
10+
type WriteProjectFile = (path: string, content: string, expectedContent?: string) => Promise<void>;
11+
12+
async function mountEditorSave(writeProjectFile: WriteProjectFile) {
13+
const captured: { handle: EditorSaveHandle | null } = { handle: null };
14+
15+
function Probe() {
16+
captured.handle = useEditorSave({
17+
editingPathRef: { current: "index.html" },
18+
projectIdRef: { current: "project-a" },
19+
readProjectFile: vi.fn(async () => "before"),
20+
writeProjectFile,
21+
recordEdit: vi.fn(async () => undefined),
22+
domEditSaveTimestampRef: { current: 0 },
23+
setRefreshKey: vi.fn(),
24+
showToast: vi.fn(),
25+
});
26+
return null;
27+
}
28+
29+
const root = createRoot(document.createElement("div"));
30+
await act(async () => root.render(<Probe />));
31+
if (!captured.handle) throw new Error("Editor save handle was not mounted");
32+
33+
return {
34+
handle: captured.handle,
35+
unmount: () => act(async () => root.unmount()),
36+
};
37+
}
38+
39+
describe("useEditorSave pending work", () => {
40+
beforeEach(() => {
41+
vi.stubGlobal(
42+
"requestAnimationFrame",
43+
vi.fn(() => 41),
44+
);
45+
vi.stubGlobal("cancelAnimationFrame", vi.fn());
46+
});
47+
48+
afterEach(() => vi.unstubAllGlobals());
49+
50+
it("exposes and flushes the latest rAF-buffered source candidate", async () => {
51+
const writeProjectFile = vi.fn(async () => undefined);
52+
const mounted = await mountEditorSave(writeProjectFile);
53+
act(() => mounted.handle.handleContentChange("studio candidate"));
54+
55+
expect(mounted.handle.getPendingCandidate()).toEqual({
56+
projectId: "project-a",
57+
path: "index.html",
58+
content: "studio candidate",
59+
});
60+
await expect(mounted.handle.flushPendingSave()).resolves.toEqual({ status: "clean" });
61+
expect(writeProjectFile).toHaveBeenCalledWith("index.html", "studio candidate", "before");
62+
63+
await mounted.unmount();
64+
});
65+
66+
it("joins an in-flight source save instead of writing the frozen candidate twice", async () => {
67+
let frame: FrameRequestCallback | null = null;
68+
vi.stubGlobal(
69+
"requestAnimationFrame",
70+
vi.fn((callback: FrameRequestCallback) => {
71+
frame = callback;
72+
return 42;
73+
}),
74+
);
75+
let finishWrite!: () => void;
76+
const writeProjectFile = vi
77+
.fn()
78+
.mockImplementationOnce(
79+
() =>
80+
new Promise<void>((resolve) => {
81+
finishWrite = resolve;
82+
}),
83+
)
84+
.mockResolvedValue(undefined);
85+
const mounted = await mountEditorSave(writeProjectFile);
86+
act(() => mounted.handle.handleContentChange("candidate"));
87+
act(() => frame?.(0));
88+
await vi.waitFor(() => expect(writeProjectFile).toHaveBeenCalledOnce());
89+
90+
const drained = mounted.handle.flushPendingSave();
91+
expect(writeProjectFile).toHaveBeenCalledOnce();
92+
finishWrite();
93+
await expect(drained).resolves.toEqual({ status: "clean" });
94+
expect(writeProjectFile).toHaveBeenCalledOnce();
95+
await mounted.unmount();
96+
});
97+
98+
it("preserves conflict details when flushing a buffered source candidate", async () => {
99+
const conflict = new StudioFileConflictError({
100+
filePath: "index.html",
101+
currentVersion: "external-v2",
102+
currentContent: "external",
103+
attemptedContent: "studio candidate",
104+
});
105+
const mounted = await mountEditorSave(async () => {
106+
throw conflict;
107+
});
108+
act(() => mounted.handle.handleContentChange("studio candidate"));
109+
110+
await expect(mounted.handle.flushPendingSave()).resolves.toEqual({
111+
status: "conflict",
112+
error: conflict,
113+
});
114+
115+
await mounted.unmount();
116+
});
117+
118+
it("discards an rAF-buffered candidate without persisting it", async () => {
119+
const writeProjectFile = vi.fn(async () => undefined);
120+
const mounted = await mountEditorSave(writeProjectFile);
121+
act(() => mounted.handle.handleContentChange("discard me"));
122+
act(() => mounted.handle.discardPendingSave());
123+
124+
expect(mounted.handle.getPendingCandidate()).toBeNull();
125+
await expect(mounted.handle.flushPendingSave()).resolves.toEqual({ status: "clean" });
126+
expect(writeProjectFile).not.toHaveBeenCalled();
127+
expect(cancelAnimationFrame).toHaveBeenCalledWith(41);
128+
129+
await mounted.unmount();
130+
});
131+
});

‎packages/studio/src/hooks/useEditorSave.ts‎

Lines changed: 113 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@ import { useCallback, useRef } from "react";
22
import { saveProjectFilesWithHistory } from "../utils/studioFileHistory";
33
import type { EditHistoryKind } from "../utils/editHistory";
44
import { trackStudioEvent } from "../utils/studioTelemetry";
5+
import {
6+
StudioFileConflictError,
7+
type StudioSaveDrainResult,
8+
} from "../utils/studioSaveDiagnostics";
59

610
interface RecordEditInput {
711
label: string;
@@ -21,6 +25,25 @@ interface UseEditorSaveOptions {
2125
showToast: (message: string, tone?: "error" | "info") => void;
2226
}
2327

28+
export interface EditorSaveCandidate {
29+
projectId: string;
30+
path: string;
31+
content: string;
32+
}
33+
34+
export type EditorSaveDrainResult = StudioSaveDrainResult;
35+
36+
export interface EditorSaveHandle {
37+
saveRafRef: React.MutableRefObject<number | null>;
38+
handleContentChange: (content: string) => void;
39+
/** Read by the external-reload reconciliation introduced in stack PR #2993. */
40+
getPendingCandidate: () => EditorSaveCandidate | null;
41+
/** Wired into the external-reload drain by stack PR #2993. */
42+
flushPendingSave: () => Promise<EditorSaveDrainResult>;
43+
/** Used by PR #2993 when the external version wins. */
44+
discardPendingSave: () => void;
45+
}
46+
2447
export function useEditorSave({
2548
editingPathRef,
2649
projectIdRef,
@@ -30,12 +53,70 @@ export function useEditorSave({
3053
domEditSaveTimestampRef,
3154
setRefreshKey,
3255
showToast,
33-
}: UseEditorSaveOptions) {
56+
}: UseEditorSaveOptions): EditorSaveHandle {
3457
const saveRafRef = useRef<number | null>(null);
3558
const refreshRafRef = useRef<number | null>(null);
3659
// One error toast per burst of failures — every keystroke retries the save,
3760
// and error toasts persist until dismissed, so don't stack duplicates.
3861
const lastFailureToastAtRef = useRef(0);
62+
const pendingCandidateRef = useRef<EditorSaveCandidate | null>(null);
63+
const inFlightRef = useRef<Promise<EditorSaveDrainResult> | null>(null);
64+
const inFlightCandidateRef = useRef<EditorSaveCandidate | null>(null);
65+
66+
const reportFailure = useCallback(
67+
(path: string, error: unknown) => {
68+
trackStudioEvent("save_failure", {
69+
source: "code_editor",
70+
error_message: error instanceof Error ? error.message : "unknown",
71+
});
72+
const now = Date.now();
73+
if (now - lastFailureToastAtRef.current > 5000) {
74+
lastFailureToastAtRef.current = now;
75+
showToast(
76+
`Couldn't save ${path} — your latest edits are NOT persisted. Check the preview server; editing again retries the save.`,
77+
"error",
78+
);
79+
}
80+
},
81+
[showToast],
82+
);
83+
84+
const persistCandidate = useCallback(
85+
(candidate: EditorSaveCandidate): Promise<EditorSaveDrainResult> => {
86+
const task = saveProjectFilesWithHistory({
87+
projectId: candidate.projectId,
88+
label: "Edit source",
89+
kind: "source",
90+
coalesceKey: `source:${candidate.path}`,
91+
files: { [candidate.path]: candidate.content },
92+
readFile: readProjectFile,
93+
writeFile: writeProjectFile,
94+
recordEdit,
95+
})
96+
.then<EditorSaveDrainResult>(() => {
97+
if (pendingCandidateRef.current === candidate) pendingCandidateRef.current = null;
98+
if (refreshRafRef.current != null) cancelAnimationFrame(refreshRafRef.current);
99+
refreshRafRef.current = requestAnimationFrame(() => setRefreshKey((k) => k + 1));
100+
return { status: "clean" };
101+
})
102+
.catch<EditorSaveDrainResult>((error: unknown) => {
103+
reportFailure(candidate.path, error);
104+
return error instanceof StudioFileConflictError
105+
? { status: "conflict", error }
106+
: { status: "failed", error };
107+
})
108+
.finally(() => {
109+
if (inFlightRef.current === task) {
110+
inFlightRef.current = null;
111+
inFlightCandidateRef.current = null;
112+
}
113+
});
114+
inFlightRef.current = task;
115+
inFlightCandidateRef.current = candidate;
116+
return task;
117+
},
118+
[readProjectFile, recordEdit, reportFailure, setRefreshKey, writeProjectFile],
119+
);
39120

40121
const handleContentChange = useCallback(
41122
(content: string) => {
@@ -44,53 +125,46 @@ export function useEditorSave({
44125
const path = editingPathRef.current;
45126
if (!path) return;
46127

128+
const candidate = { projectId: pid, path, content };
129+
pendingCandidateRef.current = candidate;
130+
47131
if (saveRafRef.current != null) cancelAnimationFrame(saveRafRef.current);
48132
saveRafRef.current = requestAnimationFrame(() => {
133+
saveRafRef.current = null;
49134
domEditSaveTimestampRef.current = Date.now();
50-
saveProjectFilesWithHistory({
51-
projectId: pid,
52-
label: "Edit source",
53-
kind: "source",
54-
coalesceKey: `source:${path}`,
55-
files: { [path]: content },
56-
readFile: readProjectFile,
57-
writeFile: writeProjectFile,
58-
recordEdit,
59-
})
60-
.then(() => {
61-
if (refreshRafRef.current != null) cancelAnimationFrame(refreshRafRef.current);
62-
refreshRafRef.current = requestAnimationFrame(() => setRefreshKey((k) => k + 1));
63-
})
64-
.catch((error) => {
65-
trackStudioEvent("save_failure", {
66-
source: "code_editor",
67-
error_message: error instanceof Error ? error.message : "unknown",
68-
});
69-
const now = Date.now();
70-
if (now - lastFailureToastAtRef.current > 5000) {
71-
lastFailureToastAtRef.current = now;
72-
showToast(
73-
`Couldn't save ${path} — your latest edits are NOT persisted. Check the preview server; editing again retries the save.`,
74-
"error",
75-
);
76-
}
77-
});
135+
void persistCandidate(candidate);
78136
});
79137
},
80-
[
81-
domEditSaveTimestampRef,
82-
editingPathRef,
83-
projectIdRef,
84-
readProjectFile,
85-
recordEdit,
86-
setRefreshKey,
87-
showToast,
88-
writeProjectFile,
89-
],
138+
[domEditSaveTimestampRef, editingPathRef, projectIdRef, persistCandidate],
90139
);
91140

141+
const flushPendingSave = useCallback(async (): Promise<EditorSaveDrainResult> => {
142+
if (saveRafRef.current != null) {
143+
cancelAnimationFrame(saveRafRef.current);
144+
saveRafRef.current = null;
145+
}
146+
const candidate = pendingCandidateRef.current;
147+
if (candidate && candidate === inFlightCandidateRef.current && inFlightRef.current) {
148+
return inFlightRef.current;
149+
}
150+
if (candidate) {
151+
domEditSaveTimestampRef.current = Date.now();
152+
return persistCandidate(candidate);
153+
}
154+
return (await inFlightRef.current) ?? { status: "clean" };
155+
}, [domEditSaveTimestampRef, persistCandidate]);
156+
157+
const discardPendingSave = useCallback(() => {
158+
if (saveRafRef.current != null) cancelAnimationFrame(saveRafRef.current);
159+
saveRafRef.current = null;
160+
pendingCandidateRef.current = null;
161+
}, []);
162+
92163
return {
93164
saveRafRef,
94165
handleContentChange,
166+
getPendingCandidate: () => pendingCandidateRef.current,
167+
flushPendingSave,
168+
discardPendingSave,
95169
};
96170
}

‎packages/studio/src/utils/domEditSaveQueue.test.ts‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { afterEach, describe, expect, it, vi } from "vitest";
22
import { createDomEditSaveQueue } from "./domEditSaveQueue";
3-
import { StudioSaveHttpError } from "./studioSaveDiagnostics";
3+
import { StudioFileConflictError, StudioSaveHttpError } from "./studioSaveDiagnostics";
44

55
describe("dom edit save queue", () => {
66
afterEach(() => {
@@ -115,6 +115,23 @@ describe("dom edit save queue", () => {
115115
queue.destroy();
116116
});
117117

118+
it("clears a stale drain failure after a successful save", async () => {
119+
const failure = new Error("temporary failure");
120+
const queue = createDomEditSaveQueue();
121+
122+
await expect(
123+
queue.enqueue(async () => {
124+
throw failure;
125+
}),
126+
).rejects.toBe(failure);
127+
await expect(queue.waitForIdle()).resolves.toEqual({ status: "failed", error: failure });
128+
129+
await queue.enqueue(async () => undefined);
130+
131+
await expect(queue.waitForIdle()).resolves.toEqual({ status: "clean" });
132+
queue.destroy();
133+
});
134+
118135
it("pauses immediately on a file conflict instead of retrying stale work", async () => {
119136
const onOpen = vi.fn();
120137
const queue = createDomEditSaveQueue({ failureThreshold: 5, onOpen });
@@ -133,4 +150,23 @@ describe("dom edit save queue", () => {
133150
await expect(queue.enqueue(async () => {})).rejects.toThrow("Auto-save is paused");
134151
queue.destroy();
135152
});
153+
154+
it("returns the original conflict from a drain instead of erasing it", async () => {
155+
const conflict = new StudioFileConflictError({
156+
filePath: "index.html",
157+
currentVersion: "external-v2",
158+
currentContent: "external",
159+
attemptedContent: "studio",
160+
});
161+
const queue = createDomEditSaveQueue();
162+
163+
await expect(
164+
queue.enqueue(async () => {
165+
throw conflict;
166+
}),
167+
).rejects.toBe(conflict);
168+
169+
await expect(queue.waitForIdle()).resolves.toEqual({ status: "conflict", error: conflict });
170+
queue.destroy();
171+
});
136172
});

0 commit comments

Comments
 (0)