diff --git a/packages/studio/src/hooks/usePersistentEditHistory.test.ts b/packages/studio/src/hooks/usePersistentEditHistory.test.ts index da36d4eaba..ec2c898679 100644 --- a/packages/studio/src/hooks/usePersistentEditHistory.test.ts +++ b/packages/studio/src/hooks/usePersistentEditHistory.test.ts @@ -724,3 +724,87 @@ it("stores DOM targets in existing history and retains them through undo and red await act(() => hook().redo({ readFile })); expect(history.list().at(-1)?.targets).toEqual(targets); }); + +it("three quick drags are three entries in the list as soon as each drag's saves are in", async () => { + const { hook, save, history } = await studio(); + const moves = [ + ["A", "B"], + ["B", "C"], + ["C", "D"], + ] as const; + for (const [i, [before, after]] of moves.entries()) { + // A drag claims under its own key with no idle limit, as a plain move does, and settles after its save. + const drag = beginStudioPendingEdit(() => () => {}); + save(after); + const saved = hook().recordEdit({ + label: "Move layer", + coalesceKey: `move:${i}`, + coalesceMs: Number.POSITIVE_INFINITY, + files: { "index.html": { before, after } }, + }); + drag.settle(saved); + await act(() => saved); + } + await vi.waitFor(() => + expect(history.list().filter((entry) => entry.label === "Move layer")).toHaveLength(3), + ); +}); + +it("the next drag's claim reaches the server after the settled drag's empty claim, however slow that one is", async () => { + const { hook, save } = await studio(); + const forward = globalThis.fetch; + const arrived: string[] = []; + let release = () => {}; + const held = new Promise((resolve) => (release = resolve)); + vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => { + const claim = url.endsWith("/claim") + ? (JSON.parse(String(init?.body)) as { paths: string[] }) + : null; + if (claim && !claim.paths.length) await held; + if (claim) arrived.push(claim.paths.length ? "claim" : "empty"); + return forward(url, init); + }); + const drag = (i: number, before: string, after: string) => { + const pending = beginStudioPendingEdit(() => () => {}); + save(after); + const saved = hook().recordEdit({ + label: "Move layer", + coalesceKey: `move:${i}`, + coalesceMs: Number.POSITIVE_INFINITY, + files: { "index.html": { before, after } }, + }); + pending.settle(saved); + return saved; + }; + await act(() => drag(0, "A", "B")); + const next = drag(1, "B", "C"); + await new Promise((resolve) => setTimeout(resolve, 20)); + release(); + await act(() => next); + expect(arrived.slice(0, 3)).toEqual(["claim", "empty", "claim"]); +}); + +it("a gesture that writes twice under one key stays one entry once it settles", async () => { + const { hook, save, history } = await studio(); + const resize = beginStudioPendingEdit(() => () => {}); + const writes = (async () => { + for (const [before, after] of [ + ["A", "B"], + ["B", "C"], + ] as const) { + save(after); + await hook().recordEdit({ + label: "Resize layer", + coalesceKey: "tx:resize", + coalesceMs: Number.POSITIVE_INFINITY, + files: { "index.html": { before, after } }, + }); + } + })(); + resize.settle(writes); + await act(() => writes); + await vi.waitFor(() => + expect(history.list().filter((entry) => entry.label === "Resize layer")).toHaveLength(1), + ); + expect(history.list().find((entry) => entry.label === "Resize layer")?.files.length).toBe(1); +}); diff --git a/packages/studio/src/hooks/usePersistentEditHistory.ts b/packages/studio/src/hooks/usePersistentEditHistory.ts index f34d4be9eb..6e367b6fc5 100644 --- a/packages/studio/src/hooks/usePersistentEditHistory.ts +++ b/packages/studio/src/hooks/usePersistentEditHistory.ts @@ -3,7 +3,10 @@ import type { HistoryListItem, HistoryResult } from "@hyperframes/studio-server" import { studioFileContentVersion, studioWriteHeaders } from "../utils/studioFileVersion"; import type { RestoreFiles } from "../utils/gsapUndoRestore"; import { studioApiFetch } from "../utils/studioApiFetch"; -import { setStudioPendingEditClaimClock } from "../utils/studioPendingEdits"; +import { + setStudioPendingEditClaimClock, + setStudioPendingEditsSettled, +} from "../utils/studioPendingEdits"; import type { RecordEditInput } from "../utils/studioFileHistory"; import { generateId } from "../utils/generateId"; @@ -41,6 +44,7 @@ interface HistoryView { forward: NextStep | null; } +const APP_KEEPS_NO_HISTORY = 404; const EMPTY: HistoryView = { entries: [], back: null, forward: null }; /** ponytail: the newest entries' content is kept; older ones step through the server only. */ const OWN_ENTRIES_KEPT = 100; @@ -201,12 +205,28 @@ function redoneAt(view: HistoryView): number | null { return view.entries.find((entry) => entry.id === undo?.undoes)?.endedAt ?? null; } +function closeHeldClaimWithAClaimOfNothing( + projectId: string, + heldClaimRef: { current: { paths: string[]; at: number } | null }, + refresh: () => Promise, +): Promise { + if (!heldClaimRef.current) return Promise.resolve(); + heldClaimRef.current = null; + return post(historyUrl(projectId, "/claim"), { label: "Edited in Studio", paths: [] }).then( + (reply) => { + if (reply.ok) void refresh(); + }, + ); +} + /** Studio's undo over the server's project history: an edit claims what it wrote; Cmd+Z steps the person's. */ +// fallow-ignore-next-line complexity export function usePersistentEditHistory({ projectId }: UsePersistentEditHistoryOptions) { const [view, setView] = useState(EMPTY); const [loaded, setLoaded] = useState(false); // A coalescing claim the server just took, until `refresh()` brings its entry into `view`. const heldClaimRef = useRef<{ paths: string[]; at: number } | null>(null); + const claimsAfterTheClose = useRef>(Promise.resolve()); const projectIdRef = useRef(projectId); projectIdRef.current = projectId; const [own] = useState(createOwnHistory); @@ -239,11 +259,24 @@ export function usePersistentEditHistory({ projectId }: UsePersistentEditHistory return () => setStudioPendingEditClaimClock(null); }, [own]); + useEffect(() => { + if (!projectId) return; + setStudioPendingEditsSettled(() => { + claimsAfterTheClose.current = closeHeldClaimWithAClaimOfNothing( + projectId, + heldClaimRef, + refresh, + ); + }); + return () => setStudioPendingEditsSettled(null); + }, [projectId, refresh]); + const recordEdit = useCallback( async ({ label, coalesceKey, coalesceMs, files, targets, created = [] }: RecordEditInput) => { if (!projectId) return; const paths = [...Object.keys(files), ...created]; own.overtake(); + await claimsAfterTheClose.current; const reply = await post(historyUrl(projectId, "/claim"), { label, paths, @@ -286,8 +319,8 @@ export function usePersistentEditHistory({ projectId }: UsePersistentEditHistory ); heldClaimRef.current = null; void refresh(); - // 404: this app keeps no history, so there is nothing to step. - if (!posted.ok && posted.status === 404) return { ok: false, reason: "empty" }; + if (!posted.ok && posted.status === APP_KEEPS_NO_HISTORY) + return { ok: false, reason: "empty" }; if (!posted.ok) return { ok: false, reason: "failed", message: posted.error }; const reply = posted.body as HistoryResult; if (!reply.ok) { diff --git a/packages/studio/src/utils/studioPendingEdits.test.ts b/packages/studio/src/utils/studioPendingEdits.test.ts index 15785bc93c..834de7962e 100644 --- a/packages/studio/src/utils/studioPendingEdits.test.ts +++ b/packages/studio/src/utils/studioPendingEdits.test.ts @@ -1,6 +1,7 @@ // @vitest-environment jsdom import { describe, expect, it, vi } from "vitest"; import { + setStudioPendingEditsSettled, addStudioPendingEditFlushListener, adoptingStudioPendingEdit, beginStudioPendingEdit, @@ -514,3 +515,22 @@ it("counts an edit whose later write failed as saved once an earlier write lande const shown = paintBackNewestStudioPendingEdit()!; await expect(shown.landed()).resolves.toBe(true); }); + +describe("every pending edit settled", () => { + it("is told once, when the last of two overlapping edits settles", async () => { + const told = vi.fn(); + setStudioPendingEditsSettled(told); + try { + const first = beginStudioPendingEdit(null); + const second = beginStudioPendingEdit(null); + first.settle(); + await Promise.resolve(); + await Promise.resolve(); + expect(told).not.toHaveBeenCalled(); + second.settle(); + await vi.waitFor(() => expect(told).toHaveBeenCalledOnce()); + } finally { + setStudioPendingEditsSettled(null); + } + }); +}); diff --git a/packages/studio/src/utils/studioPendingEdits.ts b/packages/studio/src/utils/studioPendingEdits.ts index f4fb7093fd..1e9ad6eeec 100644 --- a/packages/studio/src/utils/studioPendingEdits.ts +++ b/packages/studio/src/utils/studioPendingEdits.ts @@ -33,6 +33,12 @@ let historyClaims: () => number = () => 0; export function setStudioPendingEditClaimClock(read: (() => number) | null): void { historyClaims = read ?? (() => 0); } + +let allSettled: (() => void) | null = null; + +export function setStudioPendingEditsSettled(run: (() => void) | null): void { + allSettled = run; +} const NOT_SAVED = () => Promise.resolve(false); let cancelWaitingPress: (() => boolean) | null = null; @@ -119,10 +125,11 @@ export function trackStudioPendingEdit( showAgain: null, claimsAtBegin: historyClaims(), }); - promise.then( - () => pendingEdits.delete(promise), - () => pendingEdits.delete(promise), - ); + const done = () => { + pendingEdits.delete(promise); + if (!pendingEdits.size) allSettled?.(); + }; + promise.then(done, done); return promise; } diff --git a/packages/studio/tests/e2e/edit-accuracy/report.mjs b/packages/studio/tests/e2e/edit-accuracy/report.mjs index ef461460f7..9b01a02df6 100644 --- a/packages/studio/tests/e2e/edit-accuracy/report.mjs +++ b/packages/studio/tests/e2e/edit-accuracy/report.mjs @@ -96,6 +96,7 @@ export function score(spec, r) { undo: !r.undoTimeout && r.undo.groups !== false && + r.undo.listed !== false && r.undo.bytes && r.undo.redoBytes && Math.max(r.undo.box, r.undo.redoBox) <= LIMIT_PX && diff --git a/packages/studio/tests/e2e/edit-accuracy/sequences.mjs b/packages/studio/tests/e2e/edit-accuracy/sequences.mjs index bf721f16be..389b31c0ed 100644 --- a/packages/studio/tests/e2e/edit-accuracy/sequences.mjs +++ b/packages/studio/tests/e2e/edit-accuracy/sequences.mjs @@ -124,9 +124,11 @@ export function watchVersions(dir, files) { /** Studio's own history replies in arrival order: each claim's group, each undo or redo's entry and what it reverts. */ function watchHistory(page) { const replies = []; + const at = { list: null }; const read = (response) => { const kind = /\/history\/(claim|step|undo)$/.exec(new URL(response.url()).pathname)?.[1]; if (!kind || response.request().method() !== "POST") return; + at.list ??= response.url().replace(/\/(claim|step|undo)$/, ""); const status = response.status(); replies.push( response @@ -141,7 +143,20 @@ function watchHistory(page) { ); }; page.on("response", read); - return { replies, stop: () => page.off("response", read) }; + return { replies, at, stop: () => page.off("response", read) }; +} + +/** Whether every group the gestures took is already an entry in the history list, polled for `ms`. */ +async function groupsListed(listUrl, ids, ms = 3000) { + if (!listUrl || !ids.length) return null; + for (const deadline = Date.now() + ms; ; await sleep(100)) { + const view = await fetch(listUrl) + .then((r) => r.json()) + .catch(() => null); + const listed = new Set((view?.entries ?? []).map((entry) => entry.id)); + if (ids.every((id) => listed.has(id))) return true; + if (Date.now() > deadline) return false; + } } /** The groups left to undo, oldest first: a claim opens one unless it names the newest (one gesture writing @@ -523,6 +538,8 @@ async function measureSequence({ spec, dir, files, evidence }, session, control, const groups = historyGroups(await Promise.all(history.replies)); const ids = groups.stack.toReversed(); const groupsOk = !groups.faults.length && groups.stack.length === state.depth; + // Each gesture is its own entry in the list once its saves are in, before anything else happens. + const listed = await groupsListed(history.at.list, groups.stack); // A settled case knows each step's bytes (its saves ended before the next step); a fast one only // where all are undone and all redone, since one gesture may write more than once. const stack = []; @@ -619,6 +636,7 @@ async function measureSequence({ spec, dir, files, evidence }, session, control, reloaded: { ...reloaded, time: state.time }, undo: { groups: groupsOk, + listed, bytes: undo.ok && sameFiles(committedFiles, expected ?? {}), box: quadDistance(undone.visible, pre.visible), redoBytes: redo.ok,