diff --git a/apps/cloud/src/server.ts b/apps/cloud/src/server.ts index 48d62f4..d449c4f 100644 --- a/apps/cloud/src/server.ts +++ b/apps/cloud/src/server.ts @@ -2069,10 +2069,9 @@ export function startCloud( ); } - // Clear one page's edit history (#56): raises the truncation floor to - // just below the head and drops the unreachable ops + snapshots. Live - // bytes are untouched; storage frees immediately; lagging clients - // re-bootstrap via the #52 410/OpsTruncated path. Irreversible. + // Clear older history below the page's truncation floor. Live bytes + // are untouched; lagging clients re-bootstrap via 410. The response + // reports what was removed and whether older checkpoints remain. const clearMatch = /^\/api\/documents\/([^/]+)\/pages\/([^/]+)\/clear-history$/.exec(path); if (clearMatch && req.method === "POST") { diff --git a/apps/cloud/src/store.ts b/apps/cloud/src/store.ts index ec97368..0f8c31b 100644 --- a/apps/cloud/src/store.ts +++ b/apps/cloud/src/store.ts @@ -573,14 +573,15 @@ export class CloudStore { * bytes stay identical; lagging clients re-bootstrap via 410), then every * snapshot pinned below the floor (unreachable by stateAt, revert markers * included) is retired in that transaction. Files are removed after commit - * and usage triggers refund the bytes. No-op for blob pages and pages with no - * history before the current operation. + * and usage triggers refund the bytes. Checkpoints at/above the floor can + * share an op seq (notably tablet text edits at seq 0). Keep them: offline + * tablets can still name an older checkpoint as the base of their edits. */ clearPageHistory( user: string, doc: string, page: string, - ): { opsDeleted: number; snapshotsDeleted: number; floor: number } { + ): { opsDeleted: number; snapshotsDeleted: number; floor: number; olderCheckpointsRetained: boolean } { return this.publishPage(user, doc, page, () => { // After a successful clear only the head operation remains. Do not // create another checkpoint (and revision) when there is nothing to clear. @@ -597,7 +598,14 @@ export class CloudStore { ).all(user, doc, page, floor); this.notePrunedPublications(user, doc, page, retired); for (const row of retired) this.retiredPageFiles!.push(row.path); - return { opsDeleted, snapshotsDeleted: retired.length, floor }; + const latest = this.db.query<{ op_seq: number }, [string, string, string]>( + `SELECT op_seq FROM page_snapshots + WHERE user_id=? AND doc=? AND page=? ORDER BY seq DESC LIMIT 2`, + ).all(user, doc, page); + // A sole checkpoint is also restorable if newer ops follow it. + const olderCheckpointsRetained = latest.length > 1 || + (latest[0] !== undefined && latest[0].op_seq < this.latestOpSeq(user, doc, page)); + return { opsDeleted, snapshotsDeleted: retired.length, floor, olderCheckpointsRetained }; }); } diff --git a/apps/cloud/test/page-publication.test.ts b/apps/cloud/test/page-publication.test.ts index 45f7d2f..6bd7dc3 100644 --- a/apps/cloud/test/page-publication.test.ts +++ b/apps/cloud/test/page-publication.test.ts @@ -363,7 +363,9 @@ test.each(['ABORT', 'ROLLBACK'] as const)('a refused history clear (%s) preserve expect(store.getSnapshotBytes(...page, seq)).toBeNull() const cleared = store.deviceRevision(...page) const kept = readdirSync(path + '-files/snapshots').sort() - expect(store.clearPageHistory(...page)).toEqual({ opsDeleted: 0, snapshotsDeleted: 0, floor: 2 }) + expect(store.clearPageHistory(...page)).toEqual({ + opsDeleted: 0, snapshotsDeleted: 0, floor: 2, olderCheckpointsRetained: true, + }) expect(store.deviceRevision(...page)).toBe(cleared) expect(readdirSync(path + '-files/snapshots').sort()).toEqual(kept) } finally { diff --git a/apps/cloud/test/truncation.test.ts b/apps/cloud/test/truncation.test.ts index 83b2c81..67c4c26 100644 --- a/apps/cloud/test/truncation.test.ts +++ b/apps/cloud/test/truncation.test.ts @@ -19,7 +19,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { BelowFloorError, CloudStore, CheckpointUnavailableError } from "../src/store"; import { startCloud, type CloudServer } from "../src/server"; -import { Pen, PenColor, RmDocument, crdtId } from "@weft/rm-format"; +import { Pen, PenColor, RmDocument, crdtId, createRootText, insertText } from "@weft/rm-format"; import { polylineToPoints, type Xy } from "@weft/rm-ink/pure"; import { applyOps, @@ -497,11 +497,13 @@ test("POST /clear-history: live bytes identical, storage freed, old points gone, opsDeleted: number; snapshotsDeleted: number; floor: number; + olderCheckpointsRetained: boolean; }; // Clear history retains the head op. Usage counter updates are not ops. expect(body.opsDeleted).toBe(opsBefore - 1); expect(body.snapshotsDeleted).toBeGreaterThan(0); // the old checkpoints expect(body.floor).toBeGreaterThan(0); + expect(body.olderCheckpointsRetained).toBe(true); // boundary checkpoint // the live page is byte-identical const liveAfter = await ( @@ -533,7 +535,9 @@ test("POST /clear-history: live bytes identical, storage freed, old points gone, `${base}/api/documents/${DOC}/pages/${PAGE}/clear-history`, { method: "POST", headers: h() }, ); - expect(((await again.json()) as { opsDeleted: number }).opsDeleted).toBe(0); + expect(await again.json()).toEqual({ + opsDeleted: 0, snapshotsDeleted: 0, floor: body.floor, olderCheckpointsRetained: true, + }); // and the retained tail still streams fine from the floor expect( ( @@ -546,6 +550,80 @@ test("POST /clear-history: live bytes identical, storage freed, old points gone, }); +test("POST /clear-history reports retained same-cursor tablet checkpoints without changing them", async () => { + const DOC = "clear-tablet"; + const PAGE = "clear-tablet"; + const token = server.store.mintDeviceToken(USER, "clear history tablet"); + const endpoint = `${base}/api/documents/${DOC}/pages/${PAGE}`; + const deviceHeaders = { "x-device-token": token }; + const native = RmDocument.empty(WEB_AUTHOR); + const put = (revision?: string) => fetch(endpoint + "/rm", { + method: "PUT", + headers: { ...deviceHeaders, ...(revision ? { "x-base-revision": revision } : {}) }, + body: native.serialize() as unknown as BodyInit, + }); + const history = () => fetch(endpoint + "/history", { headers: h() }); + const clear = async () => { + const response = await fetch(endpoint + "/clear-history", { method: "POST", headers: h() }); + expect(response.status).toBe(200); + return response.json(); + }; + + expect((await put()).status).toBe(200); + const seeded = await (await history()).json(); + expect(seeded.points).toHaveLength(1); + expect(await clear()).toEqual({ + opsDeleted: 0, snapshotsDeleted: 0, floor: 0, olderCheckpointsRetained: false, + }); + + const first = await fetch(endpoint + "/rm", { headers: deviceHeaders }); + const tokenAtFirst = first.headers.get("x-rm-revision")!; + createRootText(native); + insertText(native, null, "tablet edit", { authorUuid: WEB_AUTHOR }); + expect((await put(tokenAtFirst)).status).toBe(200); + const before = await (await history()).json(); + expect(before.head).toBe(0); + expect(before.points.map(({ kind }: { kind: string }) => kind)).toEqual(["snapshot", "snapshot"]); + const bytesBefore = await (await fetch(endpoint + "/rm", { headers: deviceHeaders })).arrayBuffer(); + const quotaBefore = server.store.usageBytes(USER, "created"); + + expect(await clear()).toEqual({ + opsDeleted: 0, snapshotsDeleted: 0, floor: 0, olderCheckpointsRetained: true, + }); + expect(await (await history()).json()).toEqual(before); + expect(server.store.usageBytes(USER, "created")).toBe(quotaBefore); + expect(await (await fetch(endpoint + "/rm", { headers: deviceHeaders })).arrayBuffer()).toEqual(bytesBefore); + expect(server.store.getSnapshotBytes(USER, DOC, PAGE, seeded.points[0].snapSeq)).not.toBeNull(); +}); + +test("POST /clear-history reports a sole checkpoint older than the live head", async () => { + const doc = "clear-single-checkpoint"; + const page = "page"; + const endpoint = `${base}/api/documents/${doc}/pages/${page}`; + const snapSeq = server.store.putSnapshot(USER, doc, page, + encodeSnapshot(RmDocument.empty(WEB_AUTHOR).serialize(), { shapes: [] })); + server.store.appendOps(USER, doc, page, [encodeOp({ + op: "delete-object", id: "removed-object", version: { ts: 1, actor: "browser" }, + })], "browser"); + const history = () => fetch(endpoint + "/history", { headers: h() }).then(r => r.json()); + const before = await history(); + expect(before.head).toBeGreaterThan(0); + expect(before.points.filter(({ kind }: { kind: string }) => kind === "snapshot")).toEqual([ + expect.objectContaining({ seq: 0, snapSeq }), + ]); + const response = await fetch(endpoint + "/clear-history", { method: "POST", headers: h() }); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + opsDeleted: 0, snapshotsDeleted: 0, floor: 0, olderCheckpointsRetained: true, + }); + expect(await history()).toEqual(before); + const restore = await fetch(endpoint + "/revert", { + method: "POST", headers: h({ "content-type": "application/json" }), + body: JSON.stringify({ toSnapshot: snapSeq }), + }); + expect(restore.status).toBe(200); +}); + test("missing or corrupt history checkpoint refuses reads, reverts and trimming until restored", async () => { const dir = mkdtempSync(join(tmpdir(), "weft-required-checkpoint-")); const relay = startCloud({ port: 0, db: join(dir, "t.db") }); diff --git a/apps/web/src/lib/tldraw/HistoryPanel.tsx b/apps/web/src/lib/tldraw/HistoryPanel.tsx index 70c6be8..b3c770e 100644 --- a/apps/web/src/lib/tldraw/HistoryPanel.tsx +++ b/apps/web/src/lib/tldraw/HistoryPanel.tsx @@ -8,11 +8,40 @@ import { announceDockOpen, onOtherDockOpen } from './dock' import { useCallback, useEffect, useState } from 'react' -import { apiBase } from '../settings' -import { authHeaders } from '../authedAsset' +import { apiBase, clerkPublishableKey, watchRelayChange } from '../settings' +import { getAuthToken, hostedAccountRequest, localPreferenceOwner, selfHostJwt } from '../auth' import { ago, authorLabel, groupTimeline, type HistoryPoint, type TimelineRow } from './history-timeline' import { panelRow, rowAction, rowMeta } from './panel-styles' +type HistoryScope = { relay: string; provider: string; owner: string; revoked?: true } +const scopeChanged = 'The account or relay changed. Reopen history before trying again.' + +function historyScope(): HistoryScope | null { + const relay = apiBase() + const provider = clerkPublishableKey() + const owner = localPreferenceOwner() + return owner ? { relay, provider, owner } : null +} + +function stillSelected({ relay, provider, owner, revoked }: HistoryScope): boolean { + return !revoked && apiBase() === relay && clerkPublishableKey() === provider && localPreferenceOwner() === owner +} + +async function scopedHistoryHeaders(scope: HistoryScope): Promise> { + if (!stillSelected(scope)) throw new Error(scopeChanged) + let token: string | null + if (scope.provider) { + const auth = await hostedAccountRequest() + token = auth?.relay === scope.relay && auth.stillCurrent() ? auth.token : null + } else { + token = await getAuthToken() + // A password relay has exactly one account; its token is scoped to its URL. + if (token !== (scope.owner === 'self-hosted' ? selfHostJwt() : scope.owner)) token = null + } + if (!token || !stillSelected(scope)) throw new Error(scopeChanged) + return { authorization: `Bearer ${token}` } +} + export function HistoryPanel({ docId, pageId }: { docId: string; pageId: string }) { const [open, setOpen] = useState(false) useEffect(() => onOtherDockOpen('history', () => setOpen(false)), []) @@ -27,13 +56,52 @@ export function HistoryPanel({ docId, pageId }: { docId: string; pageId: string const [maxSnap, setMaxSnap] = useState(0) const [busy, setBusy] = useState(null) const [error, setError] = useState(null) + const [loadedScope, setLoadedScope] = useState(null) + const [confirmClear, setConfirmClear] = useState(null) + const [clearResult, setClearResult] = useState(null) + + const reportError = useCallback((e: unknown) => { + if (e instanceof Error && e.message === scopeChanged) { + setLoadedScope(null) + setConfirmClear(null) + setRows([]) + setClearResult(null) + } + setError(e instanceof Error ? e.message : String(e)) + }, []) - const load = useCallback(async () => { + useEffect(() => { + if (!loadedScope) return + const listener = new AbortController() + const check = () => { + if (!stillSelected(loadedScope)) { + // A detected switch also invalidates actions still awaiting a token. + loadedScope.revoked = true + reportError(new Error(scopeChanged)) + } + } + watchRelayChange(check, listener.signal) + window.addEventListener('storage', check, { signal: listener.signal }) + return () => listener.abort() + }, [loadedScope, reportError]) + + const load = useCallback(async (expected?: HistoryScope) => { setError(null) + setLoadedScope(null) + setConfirmClear(null) try { + const relay = apiBase() + const provider = clerkPublishableKey() + const initial = expected ?? historyScope() + // A cold hosted tab can learn its owner from its first bearer. + if (!initial) await getAuthToken() + const scope = initial ?? historyScope() + if (!scope || scope.relay !== relay || scope.provider !== provider) throw new Error(scopeChanged) + const headers = await scopedHistoryHeaders(scope) + if (!stillSelected(scope)) throw new Error(scopeChanged) const r = await fetch( - `${apiBase()}/api/documents/${docId}/pages/${pageId}/history?limit=500`, - { headers: await authHeaders() }, + `${scope.relay}/api/documents/${docId}/pages/${pageId}/history?limit=500`, + { headers }, ) if (!r.ok) throw new Error(`history ${r.status}`) const body = (await r.json()) as { @@ -41,6 +109,8 @@ export function HistoryPanel({ docId, pageId }: { docId: string; pageId: string head: number floor?: number } + if (!stillSelected(scope)) throw new Error(scopeChanged) + setLoadedScope(scope) setRows(groupTimeline(body.points)) setHead(body.head) setFloor(body.floor ?? 0) @@ -48,57 +118,74 @@ export function HistoryPanel({ docId, pageId }: { docId: string; pageId: string body.points.reduce((m, p) => Math.max(m, p.snapSeq ?? 0), 0), ) } catch (e) { - setError(String(e)) + reportError(e) } - }, [docId, pageId]) + }, [docId, pageId, reportError]) useEffect(() => { if (open) void load() }, [open, load]) + const postHistory = useCallback(async ( + scope: HistoryScope, action: 'revert' | 'clear-history', + target?: { toSeq: number } | { toSnapshot: number }, + ) => { + const headers = await scopedHistoryHeaders(scope) + if (!stillSelected(scope)) throw new Error(scopeChanged) + if (target) headers['content-type'] = 'application/json' + const r = await fetch( + `${scope.relay}/api/documents/${docId}/pages/${pageId}/${action}`, + { method: 'POST', headers, redirect: 'error', body: target && JSON.stringify(target) }, + ) + if (!stillSelected(scope)) throw new Error(scopeChanged) + if (!r.ok) throw new Error(`${action} ${r.status}`) + return r + }, [docId, pageId]) + const restore = useCallback( async (target: { toSeq: number } | { toSnapshot: number }, key: string) => { + if (!loadedScope) return setBusy(key) setError(null) + setClearResult(null) try { - const r = await fetch( - `${apiBase()}/api/documents/${docId}/pages/${pageId}/revert`, - { - method: 'POST', - headers: { ...(await authHeaders()), 'content-type': 'application/json' }, - body: JSON.stringify(target), - }, - ) - if (!r.ok) throw new Error(`revert ${r.status}`) - await load() + await postHistory(loadedScope, 'revert', target) + await load(loadedScope) } catch (e) { - setError(String(e)) + reportError(e) } finally { setBusy(null) } }, - [docId, pageId, load], + [loadedScope, load, postHistory, reportError], ) - // Clear this page's history: frees storage, live page untouched, - // irreversible (hence the two-click confirm). - const [confirmClear, setConfirmClear] = useState(false) - const clearHistory = useCallback(async () => { + // Clear older history without touching the current page. Some checkpoints + // stay available to offline tablets. Anything removed cannot be restored. + const clearHistory = useCallback(async (scope: HistoryScope) => { setBusy('clear-history') setError(null) + setClearResult(null) try { - const r = await fetch( - `${apiBase()}/api/documents/${docId}/pages/${pageId}/clear-history`, - { method: 'POST', headers: await authHeaders() }, + const r = await postHistory(scope, 'clear-history') + const result = (await r.json()) as { + opsDeleted: number + snapshotsDeleted: number + olderCheckpointsRetained?: boolean + } + if (!stillSelected(scope)) throw new Error(scopeChanged) + const removed = result.opsDeleted > 0 || result.snapshotsDeleted > 0 + setClearResult( + (removed ? 'Older history was removed.' : 'No history was removed.') + + (result.olderCheckpointsRetained ? ' Older checkpoints were kept for sync.' : ''), ) - if (!r.ok) throw new Error(`clear ${r.status}`) - await load() + await load(scope) } catch (e) { - setError(String(e)) + reportError(e) } finally { setBusy(null) } - }, [docId, pageId, load]) + }, [load, postHistory, reportError]) const badge: React.CSSProperties = { cursor: 'pointer', @@ -188,7 +275,7 @@ export function HistoryPanel({ docId, pageId }: { docId: string; pageId: string data-restore={ row.snapSeq !== undefined ? `snap-${row.snapSeq}` : `${row.seq}` } - disabled={busy !== null} + disabled={busy !== null || loadedScope === null} onClick={() => void restore( row.snapSeq !== undefined @@ -211,14 +298,16 @@ export function HistoryPanel({ docId, pageId }: { docId: string; pageId: string
+ {clearResult && ( +
+ {clearResult} +
+ )}
)} diff --git a/apps/web/src/lib/tldraw/TldrawApp.tsx b/apps/web/src/lib/tldraw/TldrawApp.tsx index c033753..a79afb6 100644 --- a/apps/web/src/lib/tldraw/TldrawApp.tsx +++ b/apps/web/src/lib/tldraw/TldrawApp.tsx @@ -1104,7 +1104,7 @@ export function TldrawApp({ docId, pageId, onController }: TldrawAppProps) { (desktop bottom-right, phones top-right — see .wf-dock) */}
- + {meta && ( { }); } +async function clickAfterSelectionChange(button: Locator, change: "account" | "relay") { + // A selection changed inside this document does not fire its own storage + // event; the panel must check separately before sending a mutation. + await button.evaluate((element, target) => { + const key = target === "account" ? "weft-dev-user" : "weft-server-url"; + const old = localStorage.getItem(key)!; + const next = target === "account" ? "second-history-account" : location.origin + "/another-relay"; + localStorage.setItem(key, next); + element.click(); + localStorage.setItem(key, old); + }, change); +} + async function opsCount(page: Page, pageId: string): Promise { const r = await page.request.get( `/api/documents/${NOTEBOOK}/pages/${pageId}/ops?since=0`, @@ -490,6 +503,14 @@ test("HISTORY UI: timeline lists edits; panel restore reverts and un-reverts", a await expect .poll(async () => page.locator(".tl-shape").count(), { timeout: 30_000 }) .toBe(shapesTwo); + const historyPanel = page.getByTestId("history-panel"); + const clear = historyPanel.getByTestId("history-clear"); + await clear.click(); + await expect(clear).toHaveText("remove older history? this cannot be undone"); + await clear.click(); + await expect(historyPanel.getByRole("status")).toHaveText( + "Older history was removed. Older checkpoints were kept for sync.", + ); }); test("HISTORY UI: CHECKPOINT rows are restorable (migrated page = checkpoints-only timeline)", async ({ @@ -617,7 +638,44 @@ test("HISTORY UI: a tablet-only page (zero ops, N snapshots) can restore an olde const rowCount = await page.getByTestId("history-row").count(); expect(await restoreButtons.count()).toBe(rowCount - 1); - // restore the oldest push (last row): back to one stroke's shapes + const historyPanel = page.getByTestId("history-panel"); + const clear = historyPanel.getByTestId("history-clear"); + await clear.click(); + await clear.click(); + const result = historyPanel.getByRole("status"); + await expect(result).toHaveText( + "No history was removed. Older checkpoints were kept for sync.", + ); + await expect(restoreButtons).toHaveCount(rowCount - 1); + + // An older relay doesn't know about retained checkpoints, but its counts + // still let the browser report that this action did not remove any history. + await page.route("**/clear-history", async (route) => { + const response = await route.fetch(); + const { opsDeleted, snapshotsDeleted, floor } = await response.json(); + await route.fulfill({ response, json: { opsDeleted, snapshotsDeleted, floor } }); + }); + await clear.click(); + await clear.click(); + await expect(result).toHaveText("No history was removed."); + await expect(restoreButtons).toHaveCount(rowCount - 1); + + // An older restore handle belongs to the account which loaded the timeline. + let reverts = 0; + const revertPath = `**/pages/${TABLET_PAGE}/revert`; + await page.route(revertPath, route => { + reverts++; + return route.abort(); + }); + await clickAfterSelectionChange(restoreButtons.last(), "account"); + await expect(historyPanel).toContainText("The account or relay changed. Reopen history before trying again."); + await expect(historyPanel.getByTestId("history-row")).toHaveCount(0); + expect(reverts).toBe(0); + await page.unroute(revertPath); + await page.getByTestId("history-toggle").click(); + await page.getByTestId("history-toggle").click(); + + // A fresh timeline can still restore the oldest push (one stroke). await restoreButtons.last().click(); await expect .poll(async () => page.locator(".tl-shape").count(), { timeout: 30_000 }) @@ -628,6 +686,42 @@ test("HISTORY UI: a tablet-only page (zero ops, N snapshots) can restore an olde await ctx.close(); }); +for (const change of ["account", "relay"] as const) { + test(`HISTORY UI: clearing requires a new confirmation when the ${change} changes`, async ({ page }) => { + const sheet = crypto.randomUUID(); + await devicePut(await deviceToken(), NOTEBOOK, sheet, await inkRm(1)); + await page.goto(`/app/${NOTEBOOK}/${sheet}`); + await waitForSynced(page); + + const panel = page.getByTestId("history-panel"); + await page.getByTestId("history-toggle").click(); + const button = panel.getByTestId("history-clear"); + await button.click(); + await expect(button).toHaveText("remove older history? this cannot be undone"); + + let clearPosts = 0; + await page.route("**/clear-history", route => { + clearPosts++; + return route.abort(); + }); + + await clickAfterSelectionChange(button, change); + await expect(panel).toContainText("The account or relay changed. Reopen history before trying again."); + await expect(panel.getByTestId("history-row")).toHaveCount(0); + expect(clearPosts).toBe(0); + + // Reselecting the original connection does not turn the failed click + // into permission to clear. Reopen and give a fresh two-click confirmation. + await page.unroute("**/clear-history"); + await page.getByTestId("history-toggle").click(); + await page.getByTestId("history-toggle").click(); + await button.click(); + await expect(button).toHaveText("remove older history? this cannot be undone"); + await button.click(); + await expect(panel.getByRole("status")).toHaveText("No history was removed."); + }); +} + test("DEVICE TEXT: native shape editing creates and edits the text column", async ({ page, }) => {