diff --git a/apps/editor/scripts/offline-conflict-e2e.mjs b/apps/editor/scripts/offline-conflict-e2e.mjs new file mode 100644 index 000000000..2828c6424 --- /dev/null +++ b/apps/editor/scripts/offline-conflict-e2e.mjs @@ -0,0 +1,227 @@ +// Prerequisites in addition to the SDK private-device local runner: install the hosted +// Worker dependencies, build the local Worker WASM from runtime/ with +// rcargo --pull wasm32-unknown-unknown/wasm-release/mdbn_hosted_worker.wasm build --locked --target wasm32-unknown-unknown --profile wasm-release -p mdbn-hosted-worker --features local-rehearsal +// and run pnpm --filter mdbase-editor build:e2e. From the repository root: +// TMPDIR=/tmp PLAYWRIGHT_MODULE="$PWD/apps/editor/node_modules/@playwright/test/index.mjs" MDBASE_E2E_CARGO=rcargo fnm exec --using 24.22.2 node runtime/packages/sdk/scripts/app-private-device-local-e2e.mjs --editor-offline +import assert from "node:assert/strict"; +import { randomBytes, randomUUID } from "node:crypto"; +import { createReadStream, existsSync, statSync } from "node:fs"; +import { cp, readFile, writeFile } from "node:fs/promises"; +import { extname, join, resolve, sep } from "node:path"; +import { createRequire } from "node:module"; +import { pathToFileURL } from "node:url"; +import { availableTcpPort, poll } from "../../../scripts/lib/test-runtime.mjs"; + +// Start real hosted/escrow Workers for this one local cloud copy. The same +// verified local trust module is compiled into the browser and both Workers. +export async function cloudCopyServices({ checkout, run, sdkLocal, stack, env, cleanup }) { + const worker = join(checkout, "runtime/deploy/hosted-worker"); + const require = createRequire(join(worker, "package.json")); + const { Miniflare, convertV4MiniflareOptions } = require("miniflare"); + const { build } = require("esbuild"); + const wasm = await readFile(join(checkout, "runtime/target/wasm32-unknown-unknown/wasm-release/mdbn_hosted_worker.wasm")); + const literal = join(run, "local-worker-build.mjs"); + await writeFile(literal, "export const LOCAL_REHEARSAL_BUILD = true;\n"); + const { connectOrigin, logOrigin } = stack.config; + for (const origin of [connectOrigin, logOrigin]) { + const url = new URL(origin); + assert.ok(url.origin === origin && url.protocol === "http:" && url.hostname === "127.0.0.1" && url.port); + } + async function forward(request, origin, target) { + const url = new URL(request.url); + if (url.origin !== origin) return new Response(null, { status: 403 }); + const destination = new URL(target); + destination.pathname = url.pathname; + destination.search = url.search; + return fetch(destination, { + method: request.method, + headers: [...request.headers], + body: request.body ? await request.arrayBuffer() : undefined, + redirect: "error", + }); + } + const compiled = await build({ entryPoints: [join(worker, "src/worker.ts")], bundle: true, format: "esm", + platform: "browser", target: "es2022", write: false, external: ["cloudflare:workers"], + alias: { "#hosted-local-build": literal, "#hosted-release-trust": join(sdkLocal, "src/application/packaged-trust.ts") }, + plugins: [{ name: "native-wasm", setup(builder) { + // Keep the signed LOG_URL for custody. Use the Worker's service-binding + // transport for the loopback log, which speaks plain HTTP. + builder.onResolve({ filter: /^\.\/log\.js$/ }, ({ importer }) => + importer === join(worker, "src/worker.ts") ? { path: "local-log", namespace: "loopback" } : null); + builder.onLoad({ filter: /^local-log$/, namespace: "loopback" }, () => ({ + resolveDir: join(worker, "src"), + contents: `export * from "./log.ts"; + import { deploymentLog as select } from "./log.ts"; + export const deploymentLog = env => select({ LOG: env.LOG });`, + })); + builder.onResolve({ filter: /hosted\.wasm$/ }, () => ({ path: "hosted.wasm", external: true })); + } }] }); + const services = []; + for (const role of ["hosted", "escrow"]) { + const port = await availableTcpPort(), prefix = "MDBASE_NEXT_" + role.toUpperCase(); + env[prefix + "_SERVICE_URL"] = `http://127.0.0.1:${port}`; + services.push({ role, port, prefix }); + } + return async collectionId => { + for (const { role, port, prefix } of services) { + const runtime = new Miniflare(convertV4MiniflareOptions({ name: role, host: "127.0.0.1", port, + compatibilityDate: "2026-10-05", cf: false, + modules: [{ type: "ESModule", path: "worker.js", contents: compiled.outputFiles[0].text }, + { type: "CompiledWasm", path: "hosted.wasm", contents: wasm }], + bindings: { SERVICE_KIND: role, KMS_ENVIRONMENT: "local", CP_URL: connectOrigin, LOG_URL: logOrigin, + KMS_KEY_ARN: "arn:local:kms:local:000000000000:key/" + randomUUID(), LOCAL_KMS_KEY: randomBytes(32).toString("hex"), + KMS_COLLECTIONS: collectionId, HOSTED_SERVICE_TOKEN: env[prefix + "_SERVICE_TOKEN"], CP_INBOUND_TOKEN: env[prefix + "_INTERNAL_TOKEN"] }, + durableObjects: { COLLECTIONS: { className: "HostedCollection", useSQLite: true } }, + serviceBindings: { LOG: request => forward(request, "https://log.internal", logOrigin) }, + outboundService: request => forward(request, connectOrigin, connectOrigin), + })); + cleanup.push(() => runtime.dispose()); + await runtime.ready; + } + // Connect's periodic activation sender only accepts HTTPS deployments. + // Wake the real actor through its authenticated entry point on this local stack. + return async () => { + const response = await fetch(env.MDBASE_NEXT_HOSTED_SERVICE_URL + "/internal/v1/collections/activate", { + method: "POST", redirect: "error", headers: { "content-type": "application/json", + authorization: "Bearer " + env.MDBASE_NEXT_HOSTED_SERVICE_TOKEN }, + body: JSON.stringify({ collection: collectionId }), + }); + if (!response.ok) throw Error(`local hosted activation failed (${response.status})`); + assert.deepEqual(await response.json(), { activated: true }); + }; + }; +} + +export async function prepare({ checkout, run, sdkLocal, declaration }) { + const shell = join(run, "editor-shell"); + const dist = join(checkout, "apps/editor/dist"); + assert.ok(existsSync(join(dist, "tests/fixtures/editor-regressions.html")), "build Editor with build:e2e first"); + await cp(dist, shell, { recursive: true }); + await cp(join(sdkLocal, "dist"), join(shell, "local-sdk"), { recursive: true }); + const sdk = join(sdkLocal, "dist/index.js"); + const { build } = createRequire(import.meta.url)("esbuild"); + await build({ stdin: { resolveDir: checkout, contents: `import {createMdbase} from ${JSON.stringify(sdk)}; export const sdk=createMdbase(${JSON.stringify(declaration)});` }, + outfile: join(shell, "local-sdk/application/editor.js"), bundle: true, format: "esm", platform: "browser" }); + const { buildOfflineShell } = await import(pathToFileURL(join(sdkLocal, "dist/offline-shell-build.js"))); + await buildOfflineShell({ directory: shell, register: false }); + return shell; +} + +export function serve(shell, path, response) { + const file = resolve(shell, "." + path); + if (!file.startsWith(shell + sep) || !existsSync(file) || !statSync(file).isFile()) return false; + const mime = { ".js": "text/javascript", ".wasm": "application/wasm", ".json": "application/json", + ".html": "text/html", ".css": "text/css", ".woff2": "font/woff2", ".svg": "image/svg+xml" }; + response.writeHead(200, { "content-type": mime[extname(file)] ?? "application/octet-stream" }); + createReadStream(file).pipe(response); + return true; +} + +const trials = [["control", true, false], ["A", true, true], ["B", false, true]]; + +export async function seedTrials({ folder, mdbase, collectionId }) { + for (const [trial] of trials) { + const path = `offline-${trial}.md`; + await writeFile(join(folder, path), `BASE_${trial}\n`); + } + await poll(async () => { + for (const [trial] of trials) { + const record = await mdbase(["read", `offline-${trial}.md`, "-C", folder]); + if (record.body !== `BASE_${trial}\n`) return false; + } + const collection = (await mdbase(["collection", "list"])).find(c => c.id === collectionId); + return collection.sync.pending === 0; + }, "CLI did not sync the seed bodies"); +} + +async function pendingWrite(page, collectionId, path, body) { + return page.evaluate(async ({ collectionId, path, body }) => { + const { sdk } = await import("/local-sdk/application/editor.js"); + const records = sdk.connection(collectionId).records; + const record = await records.get({ path }, { include: { body: true } }); + if (record.state.state !== "pending" || record.body !== body) return null; + // With an observed revision the SDK submits body edits. Read the resulting + // text from the replica and identify its one captured update to this record. + const entries = (await records.pendingWrites()).filter(write => write.ops.some(op => + op.kind === "update" && op.id === record.id && (op.body !== undefined || op.bodyEdits?.length))); + if (entries.length !== 1) return null; + const { mutation, state } = await records.receipt(entries[0].receipt.mutation); + return state === "pending" && mutation === entries[0].receipt.mutation ? mutation : null; + }, { collectionId, path, body }); +} + +export async function runTrials({ context, page, appOrigin, collectionId, folder, mdbase }) { + const body = page.getByRole("textbox", { name: "Note body" }); + const url = new URL("/tests/fixtures/editor-regressions.html", appOrigin); + url.search = new URLSearchParams({ scenario: "local-stack", collection: collectionId }); + await page.goto(url.href, { waitUntil: "domcontentloaded", timeout: 90_000 }); + await page.evaluate(() => navigator.serviceWorker.register("/mdbase-shell-sw.js", { type: "module" }).then(() => undefined)); + await page.waitForFunction(() => !!navigator.serviceWorker.controller); + for (const [trial, reload, concurrent] of trials) { + console.log(`running Editor trial ${trial}`); + const path = `offline-${trial}.md`, base = `BASE_${trial}`, local = `EDITOR_${trial}`, remote = `CLI_${trial}`; + const disk = join(folder, path); + + await page.getByText(`offline-${trial}`, { exact: true }).first().click(); + await body.filter({ hasText: base }).waitFor({ timeout: 30_000 }); + let mutationId; + await context.setOffline(true); + try { + // Overlap the same line to force a true body conflict at head. + await body.fill(local); + await page.getByText(/saved on this device/i).first().waitFor({ timeout: 30_000 }); + await page.waitForFunction(() => !navigator.onLine); + mutationId = await poll(() => pendingWrite(page, collectionId, path, local), "missing pending receipt for the edited record"); + if (reload) { + await page.reload({ waitUntil: "domcontentloaded", timeout: 90_000 }); + await body.filter({ hasText: local }).waitFor({ timeout: 30_000 }); + assert.equal(await pendingWrite(page, collectionId, path, local), mutationId, "reload must preserve the exact pending write"); + } + assert.equal(await readFile(disk, "utf8"), base + "\n", "the offline edit reached the CLI before reconnect"); + if (concurrent) { + const counters = async () => (await mdbase(["collection", "list"])).find(c => c.id === collectionId).sync; + const before = await counters(); + await mdbase(["update", path, "--body", remote + "\n", "-C", folder]); + await poll(async () => { + const record = await mdbase(["read", path, "-C", folder]); + const sync = await counters(); + return record.body === remote + "\n" && sync.pending === 0 && sync.confirmed_through > before.confirmed_through; + }, "the CLI edit did not reach the log", 180, 200); + } + } finally { await context.setOffline(false); } + const terminal = await poll(async () => { + const receipt = await page.evaluate(async ({ collectionId, mutationId }) => { + const { sdk } = await import("/local-sdk/application/editor.js"); + const { mutation, state, status } = await sdk.connection(collectionId).records.receipt(mutationId); + return { mutation, state, status }; + }, { collectionId, mutationId }); + assert.equal(receipt.mutation, mutationId); + return ["confirmed", "rejected"].includes(receipt.state) && receipt; + }, "the offline write did not settle", 300, 200); + console.log(`Editor trial ${trial} exact receipt: ${terminal.state}/${terminal.status ?? "no status"}`); + if (concurrent) { + assert.equal(terminal.state, "rejected"); + const recovery = page.getByRole("status", { name: "Unsaved draft found" }); + await recovery.waitFor({ timeout: 60_000 }); + await recovery.getByText("Review recovered text").click(); + assert.equal(await recovery.locator("pre").first().innerText(), local); + assert.ok((await body.innerText()).includes(remote)); + assert.equal(await readFile(disk, "utf8"), remote + "\n"); + if (trial === "A") { + await recovery.getByRole("button", { name: "Restore unsaved edits" }).click(); + await page.getByRole("alert", { name: "Note changed elsewhere" }).waitFor(); + await page.getByRole("button", { name: "Keep my edits" }).click(); + } else { + await recovery.getByRole("button", { name: "Discard recovered edits" }).click(); + await recovery.waitFor({ state: "detached" }); + await page.reload({ waitUntil: "domcontentloaded", timeout: 90_000 }); + await body.filter({ hasText: remote }).waitFor(); + assert.equal(await recovery.count(), 0, "the discarded edit returned after reload"); + } + } + if (!concurrent) assert.equal(terminal.state, "confirmed"); + const chosen = trial === "B" ? remote + "\n" : local; + await poll(async () => (await readFile(disk, "utf8")) === chosen, "the chosen body never reached disk", 300, 200); + console.log(`ok - Editor offline trial ${trial} (reload=${reload}, concurrent=${concurrent})`); + } +} diff --git a/apps/editor/src/App.draft-recovery.test.tsx b/apps/editor/src/App.draft-recovery.test.tsx index 130b5aaae..a618c92f5 100644 --- a/apps/editor/src/App.draft-recovery.test.tsx +++ b/apps/editor/src/App.draft-recovery.test.tsx @@ -1,9 +1,11 @@ import type { ReactNode } from "react"; -import { fireEvent, render, screen, waitFor } from "./test/locale"; +import { act, fireEvent, render, screen, waitFor, within } from "./test/locale"; import { expect, it, vi } from "vitest"; import { MdbaseConnectError } from "./connect-types"; import { connectProblem } from "./connect-types"; import { App } from "./App"; +import { SdkEditorRoot } from "./SdkEditorRoot"; +import { closeNativeFixtures, readyFixture } from "./test/native-fixture"; import { DemoCollectionGateway } from "./demo-gateway"; vi.mock("./CodeEditor", () => ({ @@ -108,3 +110,36 @@ it("says when this browser refuses the recovery copy", async () => { fireEvent(window, new Event("pagehide")); expect(await screen.findByRole("alert")).toHaveTextContent("Unsaved edits cannot be backed up in this browser."); }); + +it.each([false, true])("preserves an offline capture and the remote body on late rejection (reload %s)", async (reload) => { + const fixture = await readyFixture({ confirmDelayMs: null }, replica => replica.seed({ path: "note.md", body: "Original" })); + try { + vi.spyOn(fixture.client, "awaitReceipt").mockImplementation(async mutation => ({ mutation, state: "pending" })); + const get = vi.spyOn(fixture.client, "get"); + const first = render(); + const body = () => screen.findByRole("textbox", { name: "Note body" }); + fireEvent.change(await body(), { target: { value: "Offline text" } }); + await waitFor(() => expect(fixture.client.ledger.getSnapshot().pending).toHaveLength(1)); + const [{ mutationId, records: [id] }] = fixture.client.ledger.getSnapshot().pending; + await waitFor(() => expect(get.mock.calls.some(([target]) => target === id)).toBe(true)); + const checkpoint = () => Object.keys(localStorage).find(key => key.startsWith("mdbase-editor:draft:v1:")); + await waitFor(() => expect(JSON.parse(localStorage.getItem(checkpoint()!)!).body).toBe("Offline text")); + if (reload) { + first.unmount(); + render(); + expect(await body()).toHaveValue("Offline text"); + expect(screen.queryByRole("button", { name: "Restore unsaved edits" })).toBeNull(); + } + act(() => { + fixture.replica.reject(mutationId); + fixture.replica.editElsewhere(id, { body: "CLI text" }); + }); + const recovery = await screen.findByRole("status", { name: "Unsaved draft found" }); + expect(await body()).toHaveValue("CLI text"); + expect(within(recovery).getByText("Offline text")).toBeInTheDocument(); + fireEvent.click(within(recovery).getByRole("button", { name: "Restore unsaved edits" })); + await screen.findByRole("alert", { name: "Note changed elsewhere" }); + expect(await body()).toHaveValue("Offline text"); + expect((await fixture.client.get(id, { include: { body: true } })).body).toBe("CLI text"); + } finally { closeNativeFixtures(); } +}); diff --git a/apps/editor/src/App.tsx b/apps/editor/src/App.tsx index c3d2f8d4d..ef6d8313d 100644 --- a/apps/editor/src/App.tsx +++ b/apps/editor/src/App.tsx @@ -60,7 +60,7 @@ import { ConnectScreen } from "./ConnectionScreens"; import type { LeaveIntent } from "@mdbase-dev/ui/collections"; import type { EditorCollectionSwitcher } from "./editor-collections"; import { ConflictResolver } from "./ConflictResolver"; -import { frontmatterPatch, recoveryDraftMatchesRecord, useDraftRecovery } from "./draft-recovery"; +import { frontmatterPatch, recoveryDraftMatchesRecord, type RecoveryDraft, useDraftRecovery } from "./draft-recovery"; import { connectServerUrl } from "./connect-endpoint"; import { ConfirmDialog } from "@mdbase-dev/ui/confirm-dialog"; import { CommandPalette, shortcutLabel } from "@mdbase-dev/ui/command-palette"; @@ -595,8 +595,12 @@ export function App({ gateway, collectionSwitcher, onFeedbackContext }: Collecti noteSessions.current.set(next.path, session); let previous = session.record.snapshot; const collection = mutationScope.current.token().collectionId!; - try { session.recoveryDraft = draftRecovery?.read(collection, next.path, next); } + // A replica can roll its pending projection back. Keep the last edit until + // a confirmed record contains it, including when this session opens offline. + let checkpoint: RecoveryDraft | undefined; + try { checkpoint = draftRecovery?.read(collection, next.path, next); } catch { session.recoveryError = recoveryUnavailable(); } + if (checkpoint && !recoveryDraftMatchesRecord(checkpoint, next)) session.recoveryDraft = checkpoint; if (!draftRecovery && !privateCollection) session.recoveryError = recoveryUnavailable(); const checkpointed = (ok: boolean) => { const error = ok ? undefined : recoveryUnavailable(); @@ -604,25 +608,40 @@ export function App({ gateway, collectionSwitcher, onFeedbackContext }: Collecti session.recoveryError = error; touchSession(session); }; + const keep = (draft: Omit) => { + checkpoint = { ...draft, savedAt: Date.now() }; + draftRecovery?.write(collection, session.document.path, draft, checkpointed); + }; + if (next.pendingSync && !checkpoint) { + keep({ body: next.body ?? "", patch: {}, baseBody: next.body ?? "", baseFrontmatter: next.frontmatter, awaitingSync: true }); + } session.record.subscribe(() => { const current = session.record.snapshot; - if (session.recoveryDraft && current.state === "saved" && recoveryDraftMatchesRecord(session.recoveryDraft, current.record)) { - session.recoveryDraft = undefined; - } - if (!session.recoveryDraft) { - try { - if (previous.record.path !== current.record.path) draftRecovery?.remove(collection, previous.record.path, current.record); - if (current.dirty) draftRecovery?.write(collection, current.record.path, { - body: current.body, baseBody: current.record.body ?? "", - patch: frontmatterPatch(current.record.frontmatter, current.frontmatter), - baseFrontmatter: current.record.frontmatter - }, checkpointed); - else { - draftRecovery?.remove(collection, current.record.path, current.record); - if (draftRecovery) session.recoveryError = undefined; + try { + if (previous.record.path !== current.record.path) draftRecovery?.remove(collection, previous.record.path, current.record); + if (session.recoveryDraft) { + if (current.state === "saved" && !current.record.pendingSync && recoveryDraftMatchesRecord(session.recoveryDraft, current.record)) { + session.recoveryDraft = undefined; } - } catch { session.recoveryError = recoveryUnavailable(); } - } + } else if (current.dirty) { + const original = previous.record.pendingSync || current.remote ? checkpoint : undefined; + const baseBody = original?.baseBody ?? current.record.body ?? ""; + const baseFrontmatter = original?.baseFrontmatter ?? current.record.frontmatter; + keep({ body: current.body, baseBody, patch: frontmatterPatch(baseFrontmatter, current.frontmatter), baseFrontmatter, + ...(current.record.pendingSync || original?.awaitingSync ? { awaitingSync: true } : {}) }); + } else if (checkpoint && (previous.record.pendingSync || current.record.pendingSync) + && !recoveryDraftMatchesRecord(checkpoint, current.record)) { + session.recoveryDraft = checkpoint; + } else if (current.record.pendingSync && checkpoint && !checkpoint.awaitingSync) { + keep({ ...checkpoint, awaitingSync: true }); + draftRecovery?.flush(); + } + if (!current.dirty && !current.record.pendingSync && !session.recoveryDraft) { + draftRecovery?.remove(collection, current.record.path, current.record); + checkpoint = undefined; + if (draftRecovery) session.recoveryError = undefined; + } + } catch { session.recoveryError = recoveryUnavailable(); } sessionChanged(session, previous); previous = current; }); @@ -678,7 +697,7 @@ export function App({ gateway, collectionSwitcher, onFeedbackContext }: Collecti const refreshCachedNote = useCallback(async (path: string, revision?: string) => { const session = noteSessions.current.get(path); - if (!session || session.deleted || (revision !== undefined && session.document.revision === revision)) return; + if (!session || session.deleted || (!session.document.pendingSync && revision !== undefined && session.document.revision === revision)) return; // Read behind this note's own writes; the session classifies the result. requireSaved(await session.record.refresh()); }, []); @@ -2301,7 +2320,7 @@ export function App({ gateway, collectionSwitcher, onFeedbackContext }: Collecti identity={noteSessions.current.active?.editorSessionKey ?? document?.path} onRetry={canEditNotes ? () => { void noteSessions.current.active?.record.save(); } : undefined} state={pendingNoteMutations.length > 0 ? "recovery" : saveState} - savedOnDevice={syncState === "saved_on_device"} + savedOnDevice={document?.pendingSync === true} activity={noteSessions.current.active?.activity} detail={noteSessions.current.active?.activityDetail} onCancel={noteSessions.current.active?.mutationCancellable ? cancelActiveMutation : undefined} @@ -2387,7 +2406,7 @@ export function App({ gateway, collectionSwitcher, onFeedbackContext }: Collecti {!mobileLayout && focused && noteLoading && Opening “{pendingNotePath}”…} {!mobileLayout && !isNew && !canEditNotes && Read only} {!mobileLayout && (focused ? noteSaveIndicator : session && )} + savedOnDevice={session.document.pendingSync === true} activity={session.activity} detail={session.activityDetail} />)} {mobileLayout && shownConnection !== "connected" &&
void refreshAfterConnectionGap()} />
} @@ -2435,8 +2454,9 @@ export function App({ gateway, collectionSwitcher, onFeedbackContext }: Collecti } {focused && !isNew && noteSessions.current.active?.recoveryError &&

{noteSessions.current.active.recoveryError}

} {focused && !isNew && noteSessions.current.active?.recoveryDraft &&
- Unsaved edits from an earlier session are available. -

Editing is paused until you restore or discard these edits. They stay in this browser for up to seven days, or until saved or discarded. Restoring does not overwrite a newer version without review.

+ {noteSessions.current.active.recoveryDraft.awaitingSync + ? This note changed elsewhere : Unsaved edits from an earlier session are available.} + {!noteSessions.current.active.recoveryDraft.awaitingSync &&

Editing is paused until you restore or discard these edits. They stay in this browser for up to seven days, or until saved or discarded. Restoring does not overwrite a newer version without review.

}
Review recovered text
{noteSessions.current.active.recoveryDraft.body}
{Object.keys(noteSessions.current.active.recoveryDraft.patch).length > 0 &&
{JSON.stringify(noteSessions.current.active.recoveryDraft.patch, null, 2)}
}
diff --git a/apps/editor/src/CollectionRail.tsx b/apps/editor/src/CollectionRail.tsx index 26b1ac8da..a92065af7 100644 --- a/apps/editor/src/CollectionRail.tsx +++ b/apps/editor/src/CollectionRail.tsx @@ -332,6 +332,7 @@ export function ConnectionStatus({ state, issue, onReconnect }: { state: ShownCo stopped: t`Collection stopped`, offline: t`Collection offline`, saved_on_device: t`Collection changes are saved on this device and will sync automatically when the connection returns`, + rejected: label, unsynced: label }[state]; const title = issue ?? (state === "saved_on_device" ? t`Changes are saved on this device and will sync automatically when the connection returns.` : label); @@ -346,6 +347,7 @@ export type ShownConnectionState = ConnectionState | Exclude = { get connected() { return t`Connected`; }, get reconnecting() { return t`Reconnecting`; }, + get rejected() { return t`The note change was rejected.`; }, get stopped() { return t`Sync stopped`; }, get offline() { return t`Offline`; }, get saved_on_device() { return t`Saved on this device · syncs automatically when online`; }, diff --git a/apps/editor/src/app-state-types.ts b/apps/editor/src/app-state-types.ts index 3fc4f64e5..12f1cd074 100644 --- a/apps/editor/src/app-state-types.ts +++ b/apps/editor/src/app-state-types.ts @@ -7,7 +7,7 @@ export type ConnectionState = "connected" | "reconnecting" | "stopped"; /** Whether changes reach the collection: "offline" while it can't be reached, * "saved_on_device" while changes are kept on this device until they sync, * "unsynced" in work before connecting, which is saved only in this browser. */ -export type EditorSyncState = "synced" | "offline" | "saved_on_device" | "unsynced"; +export type EditorSyncState = "synced" | "rejected" | "offline" | "saved_on_device" | "unsynced"; export type ContractCatalogLoadState = | { status: "idle" | "loading" } | { status: "ready"; catalog: ContractCatalog } diff --git a/apps/editor/src/draft-recovery.test.ts b/apps/editor/src/draft-recovery.test.ts index 2bf0f2d1c..15bf84cca 100644 --- a/apps/editor/src/draft-recovery.test.ts +++ b/apps/editor/src/draft-recovery.test.ts @@ -35,6 +35,18 @@ it("expires recovery copies after seven days and clears malformed copies", () => now.mockRestore(); }); +it("keeps an unconfirmed checkpoint past ordinary draft expiry and through an optimistic read", () => { + const store = new DraftRecovery(localStorage, "server"); + const now = vi.spyOn(Date, "now").mockReturnValue(1000); + store.write("one", "note.md", { ...draft, awaitingSync: true }, ignored); + store.flush(); + now.mockReturnValue(1001 + DRAFT_RETENTION_MS); + const saved = { body: draft.body, frontmatter: { title: "New" } }; + expect(store.read("one", "note.md", { ...saved, pendingSync: true })).toMatchObject(draft); + expect(store.read("one", "note.md", saved)).toBeUndefined(); + now.mockRestore(); +}); + it("does not hide storage failures or confuse deletions with unchanged properties", () => { const store = new DraftRecovery(localStorage, "server"); const write = vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { throw new DOMException("Full", "QuotaExceededError"); }); diff --git a/apps/editor/src/draft-recovery.ts b/apps/editor/src/draft-recovery.ts index 7bad032a8..44a676360 100644 --- a/apps/editor/src/draft-recovery.ts +++ b/apps/editor/src/draft-recovery.ts @@ -13,9 +13,11 @@ export interface RecoveryDraft { patch: JsonObject; baseFrontmatter: JsonObject; savedAt: number; + /** An accepted device write may remain offline beyond the unsent draft retention window. */ + awaitingSync?: true; } -interface SavedDraftRecord { body?: string; frontmatter: JsonObject } +interface SavedDraftRecord { pendingSync?: true; body?: string; frontmatter: JsonObject } /** A checkpoint is unnecessary only when its body AND every edited property are saved. */ export function recoveryDraftMatchesRecord(draft: RecoveryDraft, record: SavedDraftRecord): boolean { @@ -46,7 +48,7 @@ export class DraftRecovery { read(collection: string, path: string, saved?: SavedDraftRecord): RecoveryDraft | undefined { const draft = this.readKey(this.key(collection, path)); - if (draft && saved && recoveryDraftMatchesRecord(draft, saved)) { + if (draft && saved && !saved.pendingSync && recoveryDraftMatchesRecord(draft, saved)) { this.remove(collection, path, saved); return; } @@ -61,7 +63,7 @@ export class DraftRecovery { catch { this.storage.removeItem(key); return; } if (!value || typeof value.body !== "string" || typeof value.baseBody !== "string" || !object(value.patch) || !object(value.baseFrontmatter) - || !Number.isFinite(value.savedAt) || Date.now() - value.savedAt > DRAFT_RETENTION_MS) { + || !Number.isFinite(value.savedAt) || (value.awaitingSync !== true && Date.now() - value.savedAt > DRAFT_RETENTION_MS)) { this.storage.removeItem(key); return; } diff --git a/apps/editor/src/i18n/locales/de/messages.po b/apps/editor/src/i18n/locales/de/messages.po index e67859fcb..de693b0d8 100644 --- a/apps/editor/src/i18n/locales/de/messages.po +++ b/apps/editor/src/i18n/locales/de/messages.po @@ -5882,6 +5882,7 @@ msgstr "Der native Schreibvorgang hat seine Änderungsidentität gewechselt." msgid "The new type definition hasn’t been saved." msgstr "Die neue Typdefinition wurde noch nicht gespeichert." +#: src/CollectionRail.tsx #: src/next-editor-records.ts msgid "The note change was rejected." msgstr "Die Notizänderung wurde abgelehnt." @@ -6251,6 +6252,7 @@ msgstr "Diese Notizänderung ist nicht bestätigt. Prüfen Sie den unterbrochene msgid "This note changed after it was opened. Reload before saving." msgstr "Diese Notiz wurde nach dem Öffnen geändert. Laden Sie sie vor dem Speichern neu." +#: src/App.tsx #: src/ConflictResolver.tsx msgid "This note changed elsewhere" msgstr "Diese Notiz wurde an anderer Stelle geändert" diff --git a/apps/editor/src/i18n/locales/en/messages.po b/apps/editor/src/i18n/locales/en/messages.po index 865d0ce4f..bc7345ca0 100644 --- a/apps/editor/src/i18n/locales/en/messages.po +++ b/apps/editor/src/i18n/locales/en/messages.po @@ -5882,6 +5882,7 @@ msgstr "The native write changed its mutation identity." msgid "The new type definition hasn’t been saved." msgstr "The new type definition hasn’t been saved." +#: src/CollectionRail.tsx #: src/next-editor-records.ts msgid "The note change was rejected." msgstr "The note change was rejected." @@ -6251,6 +6252,7 @@ msgstr "This note change is not confirmed. Check the interrupted operation befor msgid "This note changed after it was opened. Reload before saving." msgstr "This note changed after it was opened. Reload before saving." +#: src/App.tsx #: src/ConflictResolver.tsx msgid "This note changed elsewhere" msgstr "This note changed elsewhere" diff --git a/apps/editor/src/i18n/locales/es/messages.po b/apps/editor/src/i18n/locales/es/messages.po index 19781137e..c39253491 100644 --- a/apps/editor/src/i18n/locales/es/messages.po +++ b/apps/editor/src/i18n/locales/es/messages.po @@ -5882,6 +5882,7 @@ msgstr "La escritura nativa cambió su identidad de mutación." msgid "The new type definition hasn’t been saved." msgstr "La nueva definición de tipo no se ha guardado." +#: src/CollectionRail.tsx #: src/next-editor-records.ts msgid "The note change was rejected." msgstr "Se rechazó el cambio de la nota." @@ -6251,6 +6252,7 @@ msgstr "Este cambio en la nota sigue sin confirmar. Revisa la operación interru msgid "This note changed after it was opened. Reload before saving." msgstr "Esta nota cambió después de abrirse. Vuelve a cargarla antes de guardar." +#: src/App.tsx #: src/ConflictResolver.tsx msgid "This note changed elsewhere" msgstr "Esta nota cambió en otro lugar" diff --git a/apps/editor/src/i18n/locales/fr/messages.po b/apps/editor/src/i18n/locales/fr/messages.po index b967e8b44..3baf77e6e 100644 --- a/apps/editor/src/i18n/locales/fr/messages.po +++ b/apps/editor/src/i18n/locales/fr/messages.po @@ -5882,6 +5882,7 @@ msgstr "L’écriture native a modifié l’identité de sa mutation." msgid "The new type definition hasn’t been saved." msgstr "La nouvelle définition de type n’a pas été enregistrée." +#: src/CollectionRail.tsx #: src/next-editor-records.ts msgid "The note change was rejected." msgstr "La modification de la note a été rejetée." @@ -6251,6 +6252,7 @@ msgstr "La modification de cette note n’est pas confirmée. Vérifiez l’opé msgid "This note changed after it was opened. Reload before saving." msgstr "Cette note a changé après son ouverture. Rechargez-la avant d’enregistrer." +#: src/App.tsx #: src/ConflictResolver.tsx msgid "This note changed elsewhere" msgstr "Cette note a changé ailleurs" diff --git a/apps/editor/src/i18n/locales/it/messages.po b/apps/editor/src/i18n/locales/it/messages.po index f5c53c870..72ef5ddb7 100644 --- a/apps/editor/src/i18n/locales/it/messages.po +++ b/apps/editor/src/i18n/locales/it/messages.po @@ -5882,6 +5882,7 @@ msgstr "La scrittura nativa ha cambiato la sua identità di mutazione." msgid "The new type definition hasn’t been saved." msgstr "La nuova definizione di tipo non è stata salvata." +#: src/CollectionRail.tsx #: src/next-editor-records.ts msgid "The note change was rejected." msgstr "La modifica della nota è stata respinta." @@ -6251,6 +6252,7 @@ msgstr "Questa modifica della nota non è confermata. Controllare l'operazione i msgid "This note changed after it was opened. Reload before saving." msgstr "Questa nota è cambiata dopo essere stata aperta. Ricarica prima di salvare." +#: src/App.tsx #: src/ConflictResolver.tsx msgid "This note changed elsewhere" msgstr "Questa nota è cambiata altrove" diff --git a/apps/editor/src/i18n/locales/ja/messages.po b/apps/editor/src/i18n/locales/ja/messages.po index a7f65cadd..c5d897067 100644 --- a/apps/editor/src/i18n/locales/ja/messages.po +++ b/apps/editor/src/i18n/locales/ja/messages.po @@ -5882,6 +5882,7 @@ msgstr "ネイティブの書き込みで変更操作の識別子が変わりま msgid "The new type definition hasn’t been saved." msgstr "新しい型定義はまだ保存されていません。" +#: src/CollectionRail.tsx #: src/next-editor-records.ts msgid "The note change was rejected." msgstr "ノートの変更は拒否されました。" @@ -6251,6 +6252,7 @@ msgstr "このノートの変更は未確認です。再試行前に中断され msgid "This note changed after it was opened. Reload before saving." msgstr "このノートは開いた後に変更されました。保存前に再読み込みしてください。" +#: src/App.tsx #: src/ConflictResolver.tsx msgid "This note changed elsewhere" msgstr "このノートは別の場所で変更されました" diff --git a/apps/editor/src/i18n/locales/ko/messages.po b/apps/editor/src/i18n/locales/ko/messages.po index af0d7a8ce..9fe16793f 100644 --- a/apps/editor/src/i18n/locales/ko/messages.po +++ b/apps/editor/src/i18n/locales/ko/messages.po @@ -5882,6 +5882,7 @@ msgstr "네이티브 쓰기의 변경 ID가 달라졌습니다." msgid "The new type definition hasn’t been saved." msgstr "새 유형 정의가 저장되지 않았습니다." +#: src/CollectionRail.tsx #: src/next-editor-records.ts msgid "The note change was rejected." msgstr "노트 변경이 거부되었습니다." @@ -6251,6 +6252,7 @@ msgstr "이 노트 변경은 확인되지 않았습니다. 다시 시도하기 msgid "This note changed after it was opened. Reload before saving." msgstr "노트를 연 후 변경되었습니다. 저장하기 전에 새로고침하세요." +#: src/App.tsx #: src/ConflictResolver.tsx msgid "This note changed elsewhere" msgstr "이 노트가 다른 곳에서 변경됨" diff --git a/apps/editor/src/i18n/locales/pt/messages.po b/apps/editor/src/i18n/locales/pt/messages.po index 837ba7077..c61c9c42f 100644 --- a/apps/editor/src/i18n/locales/pt/messages.po +++ b/apps/editor/src/i18n/locales/pt/messages.po @@ -5882,6 +5882,7 @@ msgstr "A gravação nativa alterou sua identidade de mutação." msgid "The new type definition hasn’t been saved." msgstr "A nova definição de tipo ainda não foi salva." +#: src/CollectionRail.tsx #: src/next-editor-records.ts msgid "The note change was rejected." msgstr "A alteração da nota foi rejeitada." @@ -6251,6 +6252,7 @@ msgstr "A alteração desta nota não foi confirmada. Verifique a operação int msgid "This note changed after it was opened. Reload before saving." msgstr "Esta nota mudou depois de ser aberta. Recarregue antes de salvar." +#: src/App.tsx #: src/ConflictResolver.tsx msgid "This note changed elsewhere" msgstr "Esta nota mudou em outro lugar" diff --git a/apps/editor/src/i18n/locales/ru/messages.po b/apps/editor/src/i18n/locales/ru/messages.po index 6b5c98bae..0e7db7a56 100644 --- a/apps/editor/src/i18n/locales/ru/messages.po +++ b/apps/editor/src/i18n/locales/ru/messages.po @@ -5882,6 +5882,7 @@ msgstr "При записи в источник изменился иденти msgid "The new type definition hasn’t been saved." msgstr "Новое определение типа ещё не сохранено." +#: src/CollectionRail.tsx #: src/next-editor-records.ts msgid "The note change was rejected." msgstr "Изменение заметки отклонено." @@ -6251,6 +6252,7 @@ msgstr "Изменение заметки не подтверждено. Про msgid "This note changed after it was opened. Reload before saving." msgstr "Заметка изменилась после открытия. Перезагрузите её перед сохранением." +#: src/App.tsx #: src/ConflictResolver.tsx msgid "This note changed elsewhere" msgstr "Эта заметка изменена в другом месте" diff --git a/apps/editor/src/i18n/locales/zh/messages.po b/apps/editor/src/i18n/locales/zh/messages.po index a22d71457..c0022fc97 100644 --- a/apps/editor/src/i18n/locales/zh/messages.po +++ b/apps/editor/src/i18n/locales/zh/messages.po @@ -5882,6 +5882,7 @@ msgstr "原生写入的变更标识发生了变化。" msgid "The new type definition hasn’t been saved." msgstr "新的类型定义尚未保存。" +#: src/CollectionRail.tsx #: src/next-editor-records.ts msgid "The note change was rejected." msgstr "笔记更改已被拒绝。" @@ -6251,6 +6252,7 @@ msgstr "此笔记更改尚未确认。请先检查中断的操作,再重试。 msgid "This note changed after it was opened. Reload before saving." msgstr "此笔记在打开后发生了更改。请在保存前重新加载。" +#: src/App.tsx #: src/ConflictResolver.tsx msgid "This note changed elsewhere" msgstr "此笔记已在其他位置更改" diff --git a/apps/editor/src/model.ts b/apps/editor/src/model.ts index 4f2d3e0ae..cb868b24d 100644 --- a/apps/editor/src/model.ts +++ b/apps/editor/src/model.ts @@ -18,7 +18,10 @@ export interface NoteSummary extends QueryRecord { effectiveFrontmatter: NoteFrontmatter; } -export type NoteDocument = RecordDocument; +export type NoteDocument = RecordDocument & { + /** The native record includes changes that can still be refused at the log head. */ + pendingSync?: true; +}; export interface CollectionSnapshot { description: CollectionDescription; diff --git a/apps/editor/src/native-gateway.ts b/apps/editor/src/native-gateway.ts index 1a0834548..c5bf79e82 100644 --- a/apps/editor/src/native-gateway.ts +++ b/apps/editor/src/native-gateway.ts @@ -181,7 +181,8 @@ export class NativeEditorGateway implements CollectionGateway { if (!this.current()) return "synced"; const phase = this.application.getSnapshot?.().phase; if (phase?.kind === "unsynced" && phase.collectionId === this.connection.id) return "unsynced"; - if (this.client.ledger.getSnapshot().saveState === "saved_on_device") return "saved_on_device"; + const { saveState } = this.client.ledger.getSnapshot(); + if (saveState === "rejected" || saveState === "saved_on_device") return saveState; const sync = phase?.kind === "ready" && phase.collectionId === this.connection.id ? this.application.getSnapshot?.().sync : null; return sync?.connection === "offline" || sync?.health === "unreachable" || this.client.status.connection === "offline" || this.client.link !== "open" ? "offline" : "synced"; } @@ -636,8 +637,9 @@ export class NativeEditorGateway implements CollectionGateway { private summary(): ConnectionSummary { const missing = this.missingCapabilities(); + const entry = this.entry(); return { collectionId: this.connection.id, role: this.role(), displayName: this.connection.displayName, operations: this.operations(), fileActions: this.fileActions(), - ...(this.entry()?.kind === "private" ? { private: true as const } : {}), + ...(entry?.kind === "private" || entry?.mode === "private" ? { private: true as const } : {}), ...(missing.length ? { missingCapabilities: missing } : {}) }; } diff --git a/apps/editor/src/next-editor-records.test.ts b/apps/editor/src/next-editor-records.test.ts index 0b00dd7f7..32ca5bdff 100644 --- a/apps/editor/src/next-editor-records.test.ts +++ b/apps/editor/src/next-editor-records.test.ts @@ -48,8 +48,8 @@ describe("NextEditorRecords (SDK stand-in, not LAB)", () => { expect(saved.body).toBe("Changed body\n"); expect(saved.frontmatter.status).toBe("done"); expect(update).toHaveBeenCalledWith(expect.objectContaining({ id: f.record.id, revision: base.revision }), - { patch: { status: "done" }, body: "Changed body\n", ifRevision: base.revision }, - expect.objectContaining({ mutationId: expect.any(String), signal: expect.any(AbortSignal) })); + { patch: { status: "done" }, body: "Changed body\n", ifRevision: base.revision, requireLive: true }, + expect.objectContaining({ mutationId: expect.any(String), conflictMode: "reject", signal: expect.any(AbortSignal) })); expect(f.adapter.pendingMutations()).toEqual([]); }); @@ -176,7 +176,7 @@ describe("NextEditorRecords (SDK stand-in, not LAB)", () => { const f = await fixture(true); const base = await f.adapter.read(f.record.path); vi.spyOn(f.client, "awaitReceipt").mockImplementation(async mutation => ({ mutation, state: "pending" })); - expect((await f.adapter.updateProperties(base.path, { status: "done" }, base.revision))?.frontmatter.status).toBe("done"); + expect(await f.adapter.updateProperties(base.path, { status: "done" }, base.revision)).toMatchObject({ pendingSync: true, frontmatter: { status: "done" } }); expect(f.adapter.pendingMutations()).toEqual([]); }); diff --git a/apps/editor/src/next-editor-records.ts b/apps/editor/src/next-editor-records.ts index e5cdd854d..fcb89834a 100644 --- a/apps/editor/src/next-editor-records.ts +++ b/apps/editor/src/next-editor-records.ts @@ -89,7 +89,8 @@ export class NextEditorRecords { patch: (change.patch ?? {}) as Record, ...(change.body === undefined ? {} : { body: change.body }), ifRevision: base.revision, - }, options), current) as Promise; + requireLive: true, + }, { ...options, conflictMode: "reject" }), current) as Promise; } async updateProperties(path: string, patch: JsonObject, revision: string, signal?: AbortSignal): Promise { @@ -218,10 +219,10 @@ export class NextEditorRecords { if (record.state.hold || record.state.unresolved) throw new MdbaseError({ code: "outcome_unknown", reason: "unqualified_readback", recovery: "resolve_outcome", message: t`The current note is protected. Keep the original operation for recovery before reporting it as saved.` }); this.unknown.delete(mutation.mutationId); - return this.remember(record); + return this.remember(record, receipt.state === "pending"); } - private remember(record: RecordView): NoteDocument { + private remember(record: RecordView, pendingReceipt = false): NoteDocument { completeSource(record); const key = JSON.stringify([record.path, record.revision]); const previous = this.seen.get(key); @@ -239,7 +240,8 @@ export class NextEditorRecords { this.seenBytes -= this.seen.get(oldest)!.bytes; this.seen.delete(oldest); } - return { path: record.path, revision: record.revision, types: [...record.types], + return { ...(pendingReceipt || record.state.state === "pending" ? { pendingSync: true as const } : {}), + path: record.path, revision: record.revision, types: [...record.types], frontmatter: record.frontmatter, effectiveFrontmatter: record.effective ?? record.frontmatter, body: record.body, document: record.document, file: { path: record.path, ...(record.mtime === undefined ? {} : { mtime: new Date(record.mtime).toISOString() }) } }; diff --git a/apps/editor/src/note-session.test.ts b/apps/editor/src/note-session.test.ts index 6ff4c5454..fb133d6f6 100644 --- a/apps/editor/src/note-session.test.ts +++ b/apps/editor/src/note-session.test.ts @@ -17,7 +17,7 @@ function document(path: string, overrides: Partial = {}): NoteDocu }; } -function session(note: NoteDocument, update = vi.fn(async (base: NoteDocument, change: MdbaseRecordChange) => ({ +function session(note: NoteDocument, update = vi.fn(async (base: NoteDocument, change: MdbaseRecordChange): Promise => ({ ...base, revision: "2", body: change.body ?? base.body }))) { const gateway = { update, read: vi.fn(async () => note), recoverNoteMutation: vi.fn(), pendingNoteMutations: () => [] }; @@ -67,6 +67,25 @@ describe("note sessions", () => { expect(note.draft).toMatchObject({ title: "Remote", body: "New body\n" }); }); + it.each([true, false])("reconciles a confirmed save with a newer readback (continued typing %s)", async (continued) => { + const base = document("one.md", { body: "Original" }); + const result = { ...base, revision: "3", body: "Later confirmed edit" }; + let acknowledge!: (record: NoteDocument) => void; + const update = vi.fn(() => new Promise(resolve => { acknowledge = resolve; })); + const { session: note } = session(base, update); + note.record.setBody("Submitted"); + const saving = note.record.save(); + await vi.waitFor(() => expect(update).toHaveBeenCalledOnce()); + if (continued) note.record.setBody("Typing continued"); + acknowledge(result); + await saving; + expect(note.record.snapshot.body).toBe(continued ? "Typing continued" : result.body); + expect(note.record.snapshot.state).toBe(continued ? "conflict" : "saved"); + expect(note.record.snapshot.remote).toEqual(continued ? result : null); + expect(update).toHaveBeenCalledOnce(); + note.record.dispose(); + }); + it("moves one session identity between paths", () => { const store = new NoteSessionStore(); const { session: note } = session(document("old.md")); diff --git a/apps/editor/src/note-session.ts b/apps/editor/src/note-session.ts index 26eb3c4de..672c8422c 100644 --- a/apps/editor/src/note-session.ts +++ b/apps/editor/src/note-session.ts @@ -112,6 +112,7 @@ export function noteRecordAdapter( ): MdbaseRecordSessionAdapter { return { revision: (note) => note.revision, + pendingSync: (note) => Boolean(note.pendingSync), body: (note) => note.body ?? "", frontmatter: (note) => note.frontmatter, write: (base, change) => outcome(() => guard(() => gateway.update(base, change))), diff --git a/apps/editor/src/record-session.ts b/apps/editor/src/record-session.ts index 8a603f43f..fc80e8cf5 100644 --- a/apps/editor/src/record-session.ts +++ b/apps/editor/src/record-session.ts @@ -23,6 +23,7 @@ export type MdbaseRecordSessionState = export interface MdbaseRecordSessionAdapter { revision(record: R): string; body(record: R): string; + pendingSync?(record: R): boolean; frontmatter?(record: R): JsonObject; write(base: R, change: MdbaseRecordChange, options?: ConnectRequestOptions): Promise>; read?(base: R, options?: ConnectRequestOptions): Promise>; @@ -358,7 +359,17 @@ export class MdbaseRecordSession { private acknowledge(result: R, sent: Sent): void { this.seen.add(this.adapter.revision(result)); this.record = result; - if (sent.body !== undefined) this.baseBody = sent.body; + const returned = this.adapter.body(result); + const submitted = sent.body ?? this.baseBody; + if (this.adapter.pendingSync?.(result)) { + // The pending receipt can race a rollback. The checkpoint owns the + // submitted text until the device learns the outcome. + this.baseBody = submitted; + } else { + if (this.body === submitted) this.body = returned; + else if (returned !== submitted && this.body !== returned) this.remote = result; + this.baseBody = returned; + } for (const [key, value] of Object.entries(sent.patch ?? {})) { if (key in this.patch && sameJson(this.patch[key], value)) delete this.patch[key]; } @@ -401,7 +412,10 @@ export class MdbaseRecordSession { } private classify(record: R): void { - if (this.adapter.revision(record) === this.adapter.revision(this.record)) return; + if (this.adapter.revision(record) === this.adapter.revision(this.record)) { + if (this.adapter.pendingSync?.(this.record) && !this.adapter.pendingSync(record)) this.record = record; + return; + } const baseBody = this.adapter.body(this.record); const remoteBody = this.adapter.body(record); const bodyChanged = remoteBody !== baseBody; diff --git a/apps/editor/tests/editor-regressions.spec.ts b/apps/editor/tests/editor-regressions.spec.ts index 62d93208f..aa05fa9be 100644 --- a/apps/editor/tests/editor-regressions.spec.ts +++ b/apps/editor/tests/editor-regressions.spec.ts @@ -134,3 +134,49 @@ test("the self-hosted form reports invalid codes and sends a full pasted code", await submit.click(); await expect.poll(() => submitted).toEqual(["12345678"]); }); + +for (const reload of [true, false]) { + test(`an offline edit survives a rejected write in Chromium (reload ${reload})`, async ({ page, context }) => { + type ReplicaWindow = Window & { offlineFixture: import("@mdbase-dev/sdk/testing").TestApp }; + await page.goto(`${fixture}?scenario=offline-replica`); + const editor = page.frameLocator('iframe[title="Editor"]'); + const body = editor.getByRole("textbox", { name: "Note body" }); + await expect(body).toHaveText("Base text"); + await page.evaluate(async () => { + await navigator.serviceWorker.register("/mdbase-shell-sw.js", { type: "module" }); + await navigator.serviceWorker.ready; + }); + await page.waitForFunction(() => !!navigator.serviceWorker.controller); + await context.setOffline(true); + await page.evaluate(() => (window as ReplicaWindow).offlineFixture.replica().setOnline(false)); + await body.fill("Browser offline edit"); + await expect.poll(() => page.evaluate(() => { + const key = Object.keys(localStorage).find(key => key.startsWith("mdbase-editor:draft:v1:")); + return key && JSON.parse(localStorage.getItem(key)!).awaitingSync; + })).toBe(true); + if (reload) { + const navigation = page.waitForEvent("framenavigated", frame => frame.url().endsWith("?scenario=offline-editor")); + await editor.locator("body").evaluate(() => location.reload()); + const reloaded = await navigation; + expect(await reloaded.evaluate(() => navigator.onLine)).toBe(false); + await expect(body).toHaveText("Browser offline edit"); + await expect(body).toBeEditable(); + } + await context.setOffline(false); + await page.evaluate(() => { + const fixture = (window as ReplicaWindow).offlineFixture; + const [pending] = fixture.client().ledger.getSnapshot().pending; + fixture.replica().reject(pending.mutationId); + fixture.replica().editElsewhere(pending.records[0], { body: "Concurrent remote edit" }); + fixture.replica().setOnline(true); + }); + const recovery = editor.getByRole("status", { name: "Unsaved draft found" }); + await expect(body).toHaveText("Concurrent remote edit"); + await recovery.getByText("Review recovered text").click(); + await expect(recovery.locator("pre")).toHaveText("Browser offline edit"); + await recovery.getByRole("button", { name: "Restore unsaved edits" }).click(); + await editor.getByRole("button", { name: "Keep my edits" }).click(); + await expect.poll(() => page.evaluate(() => + (window as ReplicaWindow).offlineFixture.replica().allRecords[0].body)).toBe("Browser offline edit"); + }); +} diff --git a/apps/editor/tests/fixtures/editor-regressions.tsx b/apps/editor/tests/fixtures/editor-regressions.tsx index 2a502c24c..1fac6d5ce 100644 --- a/apps/editor/tests/fixtures/editor-regressions.tsx +++ b/apps/editor/tests/fixtures/editor-regressions.tsx @@ -25,6 +25,27 @@ function render(content: React.ReactNode) { } async function start() { + if (scenario === "local-stack") { + // Served only by the loopback CLI/Chromium runner, with its own build-time trust. + const module = "/local-sdk/application/editor.js"; + const { sdk } = await import(/* @vite-ignore */ module); + render(); + return; + } + if (scenario === "offline-replica") { + // Keep the SDK test replica in the parent while the iframe reloads Editor. + const fixture = await createTestApp({ collections: [{ name: "Offline notes", + records: [{ path: "note.md", body: "Base text" }] }] }); + Object.assign(window, { offlineFixture: fixture }); + render(