From bdb567de420b8d23f5e475dc7c61d13ca823673d Mon Sep 17 00:00:00 2001 From: bxff <51504045+bxff@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:47:25 +0530 Subject: [PATCH 1/3] Report what clearing page history actually removed --- apps/cloud/src/server.ts | 7 ++- apps/cloud/src/store.ts | 13 ++++-- apps/cloud/test/page-publication.test.ts | 4 +- apps/cloud/test/truncation.test.ts | 54 +++++++++++++++++++++++- apps/web/src/lib/tldraw/HistoryPanel.tsx | 23 ++++++++-- apps/web/src/lib/tldraw/TldrawApp.tsx | 2 +- e2e/ops-mode.spec.ts | 30 +++++++++++++ 7 files changed, 118 insertions(+), 15 deletions(-) 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..5204f6d 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,11 @@ 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 olderCheckpointsRetained = !!this.db.query( + `SELECT 1 FROM page_snapshots + WHERE user_id=? AND doc=? AND page=? ORDER BY seq DESC LIMIT 1 OFFSET 1`, + ).get(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..a912487 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,52 @@ 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("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..9e8654f 100644 --- a/apps/web/src/lib/tldraw/HistoryPanel.tsx +++ b/apps/web/src/lib/tldraw/HistoryPanel.tsx @@ -80,18 +80,30 @@ export function HistoryPanel({ docId, pageId }: { docId: string; pageId: string [docId, pageId, load], ) - // Clear this page's history: frees storage, live page untouched, - // irreversible (hence the two-click confirm). + // Clear older history without touching the current page. Some checkpoints + // stay available to offline tablets. Anything removed cannot be restored. const [confirmClear, setConfirmClear] = useState(false) + const [clearResult, setClearResult] = useState(null) const clearHistory = useCallback(async () => { 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() }, ) if (!r.ok) throw new Error(`clear ${r.status}`) + const result = (await r.json()) as { + opsDeleted: number + snapshotsDeleted: number + olderCheckpointsRetained?: boolean + } + 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.' : ''), + ) await load() } catch (e) { setError(String(e)) @@ -226,9 +238,14 @@ export function HistoryPanel({ docId, pageId }: { docId: string; pageId: string }} > {confirmClear - ? 'really clear? frees space, cannot be undone' + ? 'remove older history? this cannot be undone' : 'clear history…'} + {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 && ( 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,6 +625,28 @@ 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); + 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); + // restore the oldest push (last row): back to one stroke's shapes await restoreButtons.last().click(); await expect From 8dd64e6ad7cdcba90ca265f77a9c71bbb99d1cf4 Mon Sep 17 00:00:00 2001 From: bxff <51504045+bxff@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:55:18 +0530 Subject: [PATCH 2/3] Keep clear-history confirmation with its loaded account and relay --- apps/cloud/src/store.ts | 11 ++-- apps/cloud/test/truncation.test.ts | 28 ++++++++ apps/web/src/lib/tldraw/HistoryPanel.tsx | 81 +++++++++++++++++++----- e2e/ops-mode.spec.ts | 46 ++++++++++++++ 4 files changed, 147 insertions(+), 19 deletions(-) diff --git a/apps/cloud/src/store.ts b/apps/cloud/src/store.ts index 5204f6d..0f8c31b 100644 --- a/apps/cloud/src/store.ts +++ b/apps/cloud/src/store.ts @@ -598,10 +598,13 @@ export class CloudStore { ).all(user, doc, page, floor); this.notePrunedPublications(user, doc, page, retired); for (const row of retired) this.retiredPageFiles!.push(row.path); - const olderCheckpointsRetained = !!this.db.query( - `SELECT 1 FROM page_snapshots - WHERE user_id=? AND doc=? AND page=? ORDER BY seq DESC LIMIT 1 OFFSET 1`, - ).get(user, doc, page); + 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/truncation.test.ts b/apps/cloud/test/truncation.test.ts index a912487..67c4c26 100644 --- a/apps/cloud/test/truncation.test.ts +++ b/apps/cloud/test/truncation.test.ts @@ -596,6 +596,34 @@ test("POST /clear-history reports retained same-cursor tablet checkpoints withou 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 9e8654f..a9a9761 100644 --- a/apps/web/src/lib/tldraw/HistoryPanel.tsx +++ b/apps/web/src/lib/tldraw/HistoryPanel.tsx @@ -8,11 +8,41 @@ import { announceDockOpen, onOtherDockOpen } from './dock' import { useCallback, useEffect, useState } from 'react' -import { apiBase } from '../settings' +import { apiBase, clerkPublishableKey } from '../settings' import { authHeaders } from '../authedAsset' +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 } +const scopeChanged = 'The account or relay changed. Reopen history before clearing it.' + +function historyScope(): HistoryScope | null { + const relay = apiBase() + const provider = clerkPublishableKey() + const owner = localPreferenceOwner() + return owner ? { relay, provider, owner } : null +} + +function stillSelected({ relay, provider, owner }: HistoryScope): boolean { + return 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 +57,26 @@ 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 load = useCallback(async () => { + 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 +84,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) @@ -82,16 +127,17 @@ export function HistoryPanel({ docId, pageId }: { docId: string; pageId: string // Clear older history without touching the current page. Some checkpoints // stay available to offline tablets. Anything removed cannot be restored. - const [confirmClear, setConfirmClear] = useState(false) const [clearResult, setClearResult] = useState(null) - const clearHistory = useCallback(async () => { + const clearHistory = useCallback(async (scope: HistoryScope) => { setBusy('clear-history') setError(null) setClearResult(null) try { + const headers = await scopedHistoryHeaders(scope) + if (!stillSelected(scope)) throw new Error(scopeChanged) const r = await fetch( - `${apiBase()}/api/documents/${docId}/pages/${pageId}/clear-history`, - { method: 'POST', headers: await authHeaders() }, + `${scope.relay}/api/documents/${docId}/pages/${pageId}/clear-history`, + { method: 'POST', headers, redirect: 'error' }, ) if (!r.ok) throw new Error(`clear ${r.status}`) const result = (await r.json()) as { @@ -99,13 +145,15 @@ export function HistoryPanel({ docId, pageId }: { docId: string; pageId: string 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.' : ''), ) - await load() + await load(scope) } catch (e) { + if (e instanceof Error && e.message === scopeChanged) setLoadedScope(null) setError(String(e)) } finally { setBusy(null) @@ -223,14 +271,17 @@ export function HistoryPanel({ docId, pageId }: { docId: string; pageId: string