Skip to content

Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.

feat(v0.10.0): offline merge — no lost work, ever

Ashiq Hussain Mir3e7e02e1ebbe
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7c7f086..1b04446 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,68 @@
All notable changes to Canvix will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
+## [0.10.0] — 2026-10-29
+
+The "no lost work, ever" release: offline and concurrent edits merge
+deterministically — Yjs-grade convergence without leaving the existing
+document model. Full design rationale: `research/OFFLINE-MERGE.md`.
+
+### Offline editing that survives reloads
+- Every collab op is stamped with a **hybrid logical clock**
+ (`w:counter:actor` — `src/lib/collab/hlc.ts`) persisted per browser;
+ causality-aware ordering even with skewed clocks or hours-long offline
+ sessions.
+- The working document **and** the pending op queue persist to IndexedDB
+ (debounced; capped 200 pages / 500 ops) — a crash, reload or offline
+ spell loses nothing. On reopen, local work is restored when it is
+ newer than the server's ("Recovered" chip) and its queue flushes on
+ reconnect.
+- v0.9's three data-loss windows are closed: offline edits are never
+ dropped (the queue persists and retries instead of discarding),
+ autosave no longer clobbers whole documents (see merge below), and
+ fresh tabs no longer replay stale events over a fresh document
+ (`GET /api/designs/[id]` returns the event-log `seq`; the replay
+ cursor survives reloads).
+
+### Deterministic merging (client AND server, one pure function)
+- Elements are last-write-wins registers keyed by id, arbitrated by HLC
+ stamps (`_m`); deletes are **tombstones** that ride the saved document;
+ pages match by id (union). `src/lib/collab/merge.ts` — one rule,
+ applied identically by every replica, so content converges regardless
+ of arrival order.
+- `PUT /api/designs/[id]` carries `baseUpdatedAt`; on divergence (the
+ tab was offline while others saved) the server merges element-wise
+ instead of overwriting and returns `merged:true` + the merged pages.
+- `applyRemoteOp` gates stale updates/adds/deletes by stamp; coarse
+ replace ops (undo, resize, restore, template) broadcast fully-stamped
+ copies so they win/lose deterministically instead of clobbering.
+- Legacy clients/documents: unstamped data reads as epoch (any stamped
+ write beats it); legacy events get a server stamp at persist time.
+
+### Verification
+- 267 unit tests (35 new: HLC monotonicity/absorption/skew, merge
+ matrix incl. delete-vs-edit and re-add resurrection, order-independent
+ `applyRemoteOp`, restore arbitration); tsc + eslint clean.
+- `scripts/verify-offline-merge.ts` — reusable live probe (15 checks)
+ against the production database: fast-path save, divergent-PUT merge
+ (offline edit wins, addition kept, delete tombstoned), converging
+ re-save, SSE stamps (client hlc verbatim, legacy server-stamped).
+ **15/15 green.**
+- Deploy matrix intact: Cloudflare worker 2.14 MB gz (limit 3), Netlify
+ function zip 19.6 MB (limit 50), Node standalone live-verified.
+- **No migration required** — stamps and tombstones ride the existing
+ `pages` jsonb; v0.9.x databases work untouched.
+
+### Honest limitations
+- Element z-order / page order follows the merging side's array; the
+ server is the canonical convergence point (transient divergence in
+ order only, never in content).
+- A page deleted offline can re-appear when the other side held edits
+ to it (the page set is a union; element deletes are exact). Element
+ work is never lost — the page may need re-deleting.
+- Two cursors in one text box still don't merge character-level (that
+ is the Yjs upgrade path; the HLC stamps here are the migration seam).
+
## [0.9.4] — 2026-10-29
The "third platform + leaner artifact" release: **Netlify** joins Vercel
diff --git a/README.md b/README.md
index a18809d..c7c7c25 100644
--- a/README.md
+++ b/README.md
@@ -221,7 +221,13 @@ is right here.
gap-free catch-up after disconnects. Architecture: an append-only event log in
Postgres + server-sent events downstream + batched op POSTs upstream — works on
Vercel serverless and self-hosted Node alike, no WebSocket server required.
- Optimistic local edits always keep the canvas butter-smooth
+ Optimistic local edits always keep the canvas butter-smooth. Since **v0.10**
+ collaboration is also **offline-safe**: edits made while disconnected (or
+ after a crash/reload) queue in IndexedDB and merge deterministically on
+ reconnect — every element is a hybrid-logical-clock-stamped last-write-wins
+ register with delete tombstones, and the server merges divergent autosaves
+ with the same pure rule every client runs, so no one's work is ever
+ silently overwritten (see `research/OFFLINE-MERGE.md`)
- **Comments & annotations** — a first-class comments mode: click anywhere on the
canvas (or on an element — the pin follows it) to drop a threaded comment.
Replies, resolve/reopen, delete-own, unread badges, collaborator avatars and
@@ -708,7 +714,9 @@ tool descriptions so agents pick the right format.
designs, one-click migration of existing work, SSRF DNS pinning *(v0.9.0)*
- [x] Claim eligibility (browser-attributed adopt-all, per-design adopt),
CSRF same-origin enforcement, pre-Phase-4 verification gate *(v0.9.1)*
-- [ ] Yjs-grade offline merge for collaboration
+- [x] Yjs-grade offline merge for collaboration — HLC-stamped element
+ LWW + delete tombstones, persisted offline doc/op-queue (IndexedDB),
+ server-side merge on divergent autosaves *(v0.10.0)*
- [ ] Audio/video elements & Beat Sync
- [ ] Plugin system (external, installable apps)
diff --git a/package.json b/package.json
index ab719d2..9dec303 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "canvix",
- "version": "0.9.4",
+ "version": "0.10.0",
"private": false,
"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.",
"scripts": {
diff --git a/research/OFFLINE-MERGE.md b/research/OFFLINE-MERGE.md
new file mode 100644
index 0000000..d992d84
--- /dev/null
+++ b/research/OFFLINE-MERGE.md
@@ -0,0 +1,122 @@
+# Canvix v0.10 — Offline Merge (the "Yjs-grade" convergence without Yjs)
+
+Date: 2026-10-29 · Status: **implemented, unit-verified (267 tests), live-verified
+against the production database.**
+
+## The problem
+
+v0.9 collaboration had three data-loss windows:
+
+1. **Offline edits were dropped.** `flush()` re-queued 5 ops once on network
+ failure, then discarded the rest; the working document lived only in
+ memory, so a reload while offline lost everything since the last
+ successful autosave.
+2. **Autosave was last-write-wins on the whole document.** Two divergent
+ tabs both PUT full `pages`; whichever saved last silently erased the
+ other's work — exactly the collision an offline editor creates on
+ reconnect.
+3. **Fresh tabs replayed stale events.** `since=0` on first connect
+ delivered the oldest retained events over a freshly loaded document
+ (the log holds the last 500); applying them could move elements
+ backwards.
+
+## The design (one idea, four places)
+
+Every element becomes an **LWW-register keyed by id, written with a hybrid
+logical clock stamp (`_m`)**; deletes become **tombstones**
+(`PageData.tombstones[id] = hlc`) that ride the saved document; pages
+match by id and their set is a union. Because every replica — client or
+server — applies the same total order to the same stamps, **content
+converges no matter what order the writes arrive in**. That is the
+property Yjs provides via CRDTs; obtained here without migrating the
+document model off `PageData[]`.
+
+### Pieces
+
+| Piece | Where |
+|---|---|
+| Hybrid logical clock (`w:c:actor`, zero-padded so plain string compare works; persisted per browser in localStorage; absorbs remote stamps on observe) | `src/lib/collab/hlc.ts` |
+| Pure merge (`mergeElements`, `mergePages`, stamping helpers) — used by BOTH the client and the server, so the rule is literally one function | `src/lib/collab/merge.ts` |
+| IndexedDB offline store: working doc + pending op queue per design, restore arbitration (`decideRestore`) | `src/lib/collab/offline-store.ts` |
+| Client session: queue persists (debounced), retained on network failure (bounded 500), restored + flushed on reconnect; replay cursor (`canvix-seq-<id>`) survives reloads | `src/lib/collab/client.ts` |
+| Store: every mutation path stamps (`updateElementsLive` puts `_m` in the patch; adds stamp at creation; deletes tombstone; coarse ops — undo/resize/restore/template — broadcast fully-stamped copies so they win/lose deterministically instead of clobbering) | `src/store/editor-store.ts` |
+| `applyRemoteOp` gates: stale updates/adds/deletes skip by stamp; `pages:replace` now MERGES per element instead of blind-replacing | `src/store/editor-store.ts` |
+| Server stamps events lacking `hlc` (legacy clients) with a server clock at persist time (`payload._h`) | `events/route.ts` |
+| `PUT /api/designs/[id]`: body carries `baseUpdatedAt`; mismatch → server-side `mergePages` instead of overwrite; response reports `merged:true` + the merged pages (client adopts via the same gate) | `designs/[id]/route.ts` |
+| `GET /api/designs/[id]` returns `seq` — the event-log cursor at load time, so fresh tabs don't replay pre-load events (fix #3; the gates are the safety net) | `designs/[id]/route.ts` |
+| Editor: offline mirror persisted (debounced 700 ms) on every mutation; autosave sends `baseUpdatedAt`; delete flows purge IndexedDB + cursor | `Editor.tsx`, `dashboard/hooks.ts` |
+| UI: "Recovered" chip after offline-restore; "Offline · N" / "Syncing N" pending-op counts in the presence area | `PresenceAvatars.tsx` |
+
+### What a user experiences
+
+- **Network drops mid-editing:** the badge flips to "Offline · N" with a
+ live count; editing continues completely unblocked. Every op is retained
+ and persisted; nothing is dropped.
+- **Reload (or crash) while offline:** the editor reopens with the
+ locally persisted document ("Recovered" chip) and the pending queue;
+ the replay cursor resumes where the last frame ended.
+- **Reconnect:** the queued ops flush (server assigns seqs; live tabs
+ apply them through the same stamps); remote events since the cursor
+ replay back; the next autosave PUT carries the stale `baseUpdatedAt` →
+ the server merges element-wise; both sides' work survives.
+- **Two people edit the same element:** the causally-newer write wins on
+ every replica — deterministically, independent of arrival order.
+- **Delete races an edit:** the newer of the two wins; a re-add newer
+ than the tombstone resurrects the element.
+
+## Verification
+
+- **Unit (267/267):** HLC monotonicity/restart/absorption/skew; merge
+ matrix (disjoint union, LWW both directions, delete-vs-edit, re-add
+ resurrection, pointwise tombstone max, legacy-epoch behaviour, group
+ deep-stamping, defensive id-dedupe); `applyRemoteOp` order-independence
+ (stale replay cannot clobber newer state; stale delete cannot kill a
+ newer re-add; stamped `pages:replace` merges); restore arbitration
+ (queue/newer-doc/jitter-grace/conservative-missing-timestamp).
+- **Live (production standalone + real Supabase):** health green; created
+ a stamped design; PUT with stale `baseUpdatedAt` → `merged:true` with
+ the offline edit winning, the delete tombstoned, the offline addition
+ kept; a newer live edit then beat the offline edit while the offline
+ addition SURVIVED the subsequent save; SSE events carried `_h`
+ (client-passed) through the stream; probe design deleted afterwards.
+ The whole sequence is repeatable via `scripts/verify-offline-merge.ts`
+ (15 checks — point it at any running deployment) — latest run:
+ **15/15 green**.
+- Cloudflare worker still 2.14 MB gzipped (< 3 MB free cap); Node build
+ clean; tsc clean; eslint clean on all touched files.
+
+## Honest limitations (documented, deliberate)
+
+- **Z-order / page order** follows the merging "ours" side; the server is
+ the canonical convergence point (its merge direction is fixed — the
+ stored doc is always "ours"), so concurrent reorders of one page may
+ differ transiently per replica until the next autosave. Content never
+ diverges.
+- **Offline page deletions** are coarse: the page set is a union, so a
+ page deleted offline can re-appear when the other side held edits to it
+ (element-level deletes inside pages are tombstone-exact). Element work
+ is never lost; the page may need re-deleting.
+- **`pages:replace` semantics:** undo/resize/restore/template are
+ "redefine the document" actions — they stamp everything fresh and
+ deterministically beat older concurrent edits (and lose to newer ones).
+ That matches user intent for explicit overrides.
+- **Legacy data:** pre-v0.10 documents/elements are unstamped (epoch) —
+ any stamped write beats them, and two unstamped copies resolve
+ ours-stable. Old clients (pre-v0.10) mixed with the new server get
+ server-stamped events; their un-stamped PUTs fast-path (no
+ `baseUpdatedAt`) exactly as before.
+- The queue is capped at 500 ops / the offline doc at 200 pages — beyond
+ that, oldest ops drop (the document itself is still persisted and
+ merges wholesale via `baseUpdatedAt`).
+
+## Why not just adopt Yjs?
+
+Revisited the v0.5 decision with current code: converting the document
+model to Y structures still means rewriting store persistence, undo/redo
+(Y undo ≠ snapshot history), template seeding, autosave and version
+snapshots — the entire 1000-line store plus every op emitter. The
+stamp-and-merge layer achieves the convergence property users actually
+notice (no lost work, deterministic conflicts) in ~700 focused lines that
+reused every existing op path. If true character-level text merging (two
+cursors in one text box) becomes a requirement, Yjs is the next step and
+the HLC stamps here are the migration seam.
diff --git a/scripts/verify-offline-merge.ts b/scripts/verify-offline-merge.ts
new file mode 100644
index 0000000..5dcd99f
--- /dev/null
+++ b/scripts/verify-offline-merge.ts
@@ -0,0 +1,221 @@
+// scripts/verify-offline-merge.ts — v0.10 live regression probe
+// Boots nothing itself: point it at a RUNNING server (standalone, cloud
+// preview, or a deployed URL) and it drives the offline-merge surface
+// end-to-end against the real database:
+//
+// 1. health
+// 2. anonymous probe design → GET returns v0.10 `seq` cursor
+// 3. autosave with fresh baseUpdatedAt → fast path (no merge)
+// 4. stale baseUpdatedAt (tab was offline) → server-side element-wise
+// merge: offline edit wins, offline addition kept, offline delete
+// tombstoned; `merged:true` + merged pages returned
+// 5. the live tab's next save (older stamps) → offline work SURVIVES
+// 6. collab events POST: client hlc preserved, legacy stamped by server
+// 7. SSE replay: persisted events carry `_h` in the payload
+// 8. permanent cleanup of the probe design
+//
+// Usage: npx tsx scripts/verify-offline-merge.ts [BASE_URL]
+// (default http://localhost:3000). Exits non-zero on any failure.
+
+const BASE = (process.argv[2] ?? process.env.BASE_URL ?? 'http://localhost:3000').replace(/\/$/, '')
+
+let cookies = ''
+let failures = 0
+let checks = 0
+
+function pass(label: string, detail: string) {
+ checks++
+ console.log(` ✓ ${label} — ${detail}`)
+}
+function fail(label: string, detail: string) {
+ failures++
+ checks++
+ console.error(` ✗ ${label} — ${detail}`)
+}
+
+async function api(
+ method: string,
+ path: string,
+ body?: unknown,
+): Promise<{ status: number; json: any }> {
+ const res = await fetch(`${BASE}${path}`, {
+ method,
+ headers: {
+ ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
+ ...(cookies ? { cookie: cookies } : {}),
+ },
+ body: body !== undefined ? JSON.stringify(body) : undefined,
+ })
+ const setCookie = res.headers.get('set-cookie')
+ if (setCookie) cookies = setCookie.split(/;\s*/)[0]
+ let json: any = null
+ try {
+ json = await res.json()
+ } catch {
+ /* non-JSON */
+ }
+ return { status: res.status, json }
+}
+
+// HLC stamps — walltime far apart so string compare is unambiguous even
+// if the server's clock skews (deterministic test, not clock-dependent)
+const T_OLD = '0000000zzz:00001:probe-a' // any pre-v0.10-style early stamp
+const T_LIVE = '00000010y0:00002:probe-a' // live tab edit
+const T_OFF = '00000011y0:00003:probe-b' // offline tab edit (newer)
+
+function el(id: string, text: string, _m?: string) {
+ return { id, type: 'text', x: 10, y: 10, width: 200, height: 60, text, ...(_m ? { _m } : {}) }
+}
+
+async function main() {
+ console.log(`verify-offline-merge → ${BASE}`)
+
+ // 1. health
+ const health = await api('GET', '/api/health')
+ if (health.status === 200 && health.json?.ok === true) pass('health', `templates=${health.json.templates}`)
+ else fail('health', `status ${health.status}`)
+
+ // 2. probe design + v0.10 GET fields
+ const created = await api('POST', '/api/designs', { name: 'offline-merge-probe', width: 800, height: 600 })
+ if (created.status !== 201) return fail('probe design', `create → ${created.status}`)
+ const designId = created.json.id
+ const pageId = 'p1'
+ try {
+ pass('probe design', `${designId}`)
+
+ const got = await api('GET', `/api/designs/${designId}`)
+ const hasSeq = typeof got.json?.seq === 'number'
+ if (got.status === 200 && hasSeq) pass('GET seq', `seq=${got.json.seq}`)
+ else fail('GET seq', `status ${got.status}, seq=${got.json?.seq}`)
+ const staleBase = got.json?.updatedAt as string | undefined // tab B loads HERE
+
+ // 3. fast path — fresh baseUpdatedAt, plain save
+ const save1 = await api('PUT', `/api/designs/${designId}`, {
+ name: 'offline-merge-probe',
+ pages: [{ id: pageId, background: { kind: 'solid', color: '#ffffff' }, elements: [el('E0', 'original', T_OLD), el('E1', 'live-old', T_OLD)] }],
+ baseUpdatedAt: got.json.updatedAt,
+ })
+ if (save1.status === 200 && !save1.json?.merged) pass('fast path', 'fresh baseUpdatedAt → overwrite, no merge')
+ else fail('fast path', `status ${save1.status} merged=${save1.json?.merged}`)
+ const liveBase = save1.json?.updatedAt as string // tab A's fresh base
+
+ // 4. offline tab PUTs against the STALE base (it loaded before save1):
+ // E0 deleted (tombstone), E1 edited with a NEWER stamp, E2 added
+ const offlinePages = [
+ {
+ id: pageId,
+ background: { kind: 'solid', color: '#ffffff' },
+ elements: [el('E1', 'offline-newer', T_OFF), el('E2', 'offline-added', T_OFF)],
+ tombstones: { E0: T_OFF },
+ },
+ ]
+ const save2 = await api('PUT', `/api/designs/${designId}`, {
+ name: 'offline-merge-probe',
+ pages: offlinePages,
+ baseUpdatedAt: staleBase, // ← divergent: server moved on with save1
+ })
+ if (save2.status !== 200 || save2.json?.merged !== true)
+ fail('divergent merge', `status ${save2.status} merged=${save2.json?.merged}`)
+ else {
+ const pages = save2.json.pages as any[]
+ const page = pages?.find((p) => p.id === pageId)
+ const e0 = page?.elements.find((e: any) => e.id === 'E0')
+ const e1 = page?.elements.find((e: any) => e.id === 'E1')
+ const e2 = page?.elements.find((e: any) => e.id === 'E2')
+ pass('divergent merge', 'merged:true returned')
+ if (!e0) pass('offline delete', 'E0 tombstoned away')
+ else fail('offline delete', 'E0 still present')
+ if (e1?.text === 'offline-newer') pass('LWW edit', 'newer offline stamp won E1')
+ else fail('LWW edit', `E1.text=${e1?.text}`)
+ if (e2) pass('offline addition', 'E2 kept')
+ else fail('offline addition', 'E2 missing')
+ }
+
+ // 5. live tab saves its own (older-stamped) copy → offline work survives
+ const save3 = await api('PUT', `/api/designs/${designId}`, {
+ name: 'offline-merge-probe',
+ pages: [{ id: pageId, background: { kind: 'solid', color: '#ffffff' }, elements: [el('E0', 'original', T_OLD), el('E1', 'live-old', T_LIVE)] }],
+ baseUpdatedAt: liveBase, // also stale now (server moved on with save2)
+ })
+ if (save3.status !== 200 || save3.json?.merged !== true)
+ fail('converging save', `status ${save3.status} merged=${save3.json?.merged}`)
+ else {
+ const page = (save3.json.pages as any[])?.find((p) => p.id === pageId)
+ const e0 = page?.elements.find((e: any) => e.id === 'E0')
+ const e1 = page?.elements.find((e: any) => e.id === 'E1')
+ const e2 = page?.elements.find((e: any) => e.id === 'E2')
+ if (e1?.text === 'offline-newer') pass('converging save', 'older live edit lost E1, offline work survived')
+ else fail('converging save', `E1.text=${e1?.text} (offline work clobbered!)`)
+ if (e2) pass('addition survives', 'E2 still present after live save')
+ else fail('addition survives', 'E2 lost')
+ if (!e0) pass('delete survives', 'E0 still tombstoned')
+ else fail('delete survives', 'E0 resurrected')
+ }
+
+ // 6. collab events — client hlc preserved, legacy gets a server stamp
+ const ev = await api('POST', `/api/collab/${designId}/events`, {
+ pid: 'probe-pid',
+ events: [
+ { eventId: 'probe-ev-1', hlc: '00000012y0:00009:probe-b', op: { kind: 'elements:update', pageId, ids: ['E1'], patch: { text: 'via-sse' } } },
+ { eventId: 'probe-ev-2', op: { kind: 'elements:update', pageId, ids: ['E2'], patch: { text: 'legacy-client' } } }, // NO hlc → server stamps
+ ],
+ })
+ if (ev.status === 200 && ev.json?.accepted === 2) pass('events POST', '2 ops accepted')
+ else fail('events POST', `status ${ev.status} body=${JSON.stringify(ev.json).slice(0, 120)}`)
+
+ // 7. SSE replay — both events stream back with `_h` in the payload
+ const ac = new AbortController()
+ const sse = await fetch(`${BASE}/api/collab/${designId}/stream?since=0&pid=probe-pid`, {
+ headers: cookies ? { cookie: cookies } : {},
+ signal: ac.signal,
+ })
+ const found = { client: false, server: false }
+ if (sse.ok && sse.body) {
+ const reader = sse.body.getReader()
+ const dec = new TextDecoder()
+ let buf = ''
+ const deadline = Date.now() + 8000
+ while (Date.now() < deadline && !(found.client && found.server)) {
+ const { done, value } = await reader.read()
+ if (done) break
+ buf += dec.decode(value, { stream: true })
+ const lines = buf.split('\n')
+ buf = lines.pop() ?? ''
+ for (const line of lines) {
+ if (!line.startsWith('data:')) continue
+ try {
+ const frame = JSON.parse(line.slice(5).trim())
+ for (const e of frame.events ?? []) {
+ // stream ids are DB row ids (client eventIds aren't persisted)
+ // → match ops by their patch payload
+ const h = e.payload?._h
+ const texts = JSON.stringify(e.payload?.patch ?? {})
+ if (texts.includes('via-sse') && h === '00000012y0:00009:probe-b') found.client = true
+ if (texts.includes('legacy-client') && typeof h === 'string' && h.endsWith(':srv')) found.server = true
+ }
+ } catch {
+ /* keep-alive / partial */
+ }
+ }
+ }
+ ac.abort()
+ }
+ if (found.client) pass('SSE client hlc', 'payload._h preserved verbatim')
+ else fail('SSE client hlc', 'probe-ev-1 not observed with its stamp')
+ if (found.server) pass('SSE server stamp', 'legacy op stamped …:srv:')
+ else fail('SSE server stamp', 'probe-ev-2 not observed with a server stamp')
+ } finally {
+ // 8. cleanup — permanent delete
+ const del = await api('DELETE', `/api/designs/${designId}?permanent=1`)
+ if (del.status === 200) pass('cleanup', 'probe design deleted')
+ else fail('cleanup', `status ${del.status} (manual cleanup needed: ${designId})`)
+ }
+
+ console.log(`\n${failures === 0 ? 'ALL GREEN' : 'FAILURES PRESENT'} — ${checks - failures}/${checks} checks passed`)
+ process.exit(failures === 0 ? 0 : 1)
+}
+
+main().catch((err) => {
+ console.error('probe crashed:', err)
+ process.exit(1)
+})
diff --git a/src/app/api/collab/[designId]/events/route.ts b/src/app/api/collab/[designId]/events/route.ts
index ffb39f7..280b614 100644
--- a/src/app/api/collab/[designId]/events/route.ts
+++ b/src/app/api/collab/[designId]/events/route.ts
@@ -7,6 +7,7 @@ import {
type CollabOp,
type OpEnvelope,
} from '@/lib/collab/protocol'
+import { formatHlc } from '@/lib/collab/hlc'
export const runtime = 'nodejs'
export const maxDuration = 30
@@ -20,6 +21,26 @@ interface EventsBody {
const HEX_COLOR = /^#[0-9a-fA-F]{6}$/
+// ── v0.10 offline merge: server-side HLC stamping ─────────────
+// Envelopes from v0.10 clients carry an `hlc`; legacy clients don't. Every
+// persisted event gets a stamp so downstream last-write-wins gates are
+// total-ordered. The server clock is walltime-based with an in-memory tick;
+// per-serverless-instance state is fine — stamps only need to be newer than
+// the *client* epochs they arbitrate, and walltime guarantees that for
+// honestly-clocked clients (a skewed client clock is absorbed by its own
+// HLC on the next observe).
+const serverClock = { w: 0, c: 0 }
+function serverHlc(): string {
+ const wall = Date.now()
+ if (wall > serverClock.w) {
+ serverClock.w = wall
+ serverClock.c = 0
+ } else {
+ serverClock.c += 1
+ }
+ return formatHlc(serverClock.w, serverClock.c, 'srv')
+}
+
/**
* POST /api/collab/[designId]/events — upstream op flush (batched).
*
@@ -78,10 +99,12 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ des
}
// design:rename — clamp the name
- const payload =
+ const payload: Record<string, unknown> =
op.kind === 'design:rename'
? { name: String((op as { name?: unknown }).name ?? '').slice(0, 80) }
- : (op as unknown)
+ : { ...(op as unknown as Record<string, unknown>) }
+ // v0.10: embed the HLC stamp (client's if present, else the server's)
+ payload._h = typeof env.hlc === 'string' && env.hlc.length <= 80 ? env.hlc : serverHlc()
await db.designEvent.create({
data: {
diff --git a/src/app/api/designs/[id]/route.ts b/src/app/api/designs/[id]/route.ts
index 6429666..3723278 100644
--- a/src/app/api/designs/[id]/route.ts
+++ b/src/app/api/designs/[id]/route.ts
@@ -3,6 +3,8 @@ import { Prisma } from '@/generated/prisma/client'
import { db } from '@/lib/db'
import { resolveDesignAccess, NOT_YOUR_DESIGN } from '@/lib/auth/design-guard'
import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { mergePages } from '@/lib/collab/merge'
+import type { PageData } from '@/lib/types'
// Normalise incoming pages payload (accepts object or legacy JSON string)
// into a value suitable for the Postgres jsonb column.
@@ -13,17 +15,32 @@ function toPages(value: unknown): Prisma.InputJsonValue {
return (value ?? []) as Prisma.InputJsonValue
}
+function asPages(value: unknown): PageData[] {
+ return Array.isArray(value) ? (value as PageData[]) : []
+}
+
// GET /api/designs/[id] — full design incl. pages.
// v0.9: open to anyone with the link (share/view), but carries a
// `readOnly` flag when the design belongs to another account so the
// editor can switch to view-only mode.
+// v0.10: also returns `seq` (the design's current event-log cursor) so a
+// freshly loaded editor does not replay pre-load events over a document
+// that already contains them.
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const { id } = await params
const access = await resolveDesignAccess(req, id)
if (!access) return NextResponse.json({ error: 'Not found' }, { status: 404 })
const design = access.design
- return NextResponse.json({ ...design, pages: design.pages ?? [], readOnly: !access.canEdit })
+ const maxEvent = await db.designEvent
+ .aggregate({ where: { designId: id }, _max: { id: true } })
+ .catch(() => null)
+ return NextResponse.json({
+ ...design,
+ pages: design.pages ?? [],
+ readOnly: !access.canEdit,
+ seq: maxEvent ? Number(maxEvent._max.id ?? 0) : 0,
+ })
} catch (error) {
console.error('GET /api/designs/[id] failed', error)
return NextResponse.json({ error: 'Failed to get design' }, { status: 500 })
@@ -33,6 +50,12 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ id:
// PUT /api/designs/[id] — save design (name / pages / thumbnail)
// v0.9: ownerless designs stay link-editable; owned designs only save
// for their owner (403 otherwise). v0.9.1: same-origin enforced (CSRF).
+// v0.10 offline merge: the body may carry `baseUpdatedAt` — the server
+// `updatedAt` the client's pages are based on. When it matches the stored
+// row, this is a fast-path save (plain overwrite). When it does not (the
+// tab was offline while others saved), the server MERGES element-wise by
+// HLC stamps (`_m`) + tombstones instead of clobbering — the same pure
+// rule every client applies, so all replicas converge.
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
try {
@@ -46,11 +69,40 @@ export async function PUT(req: NextRequest, { params }: { params: Promise<{ id:
if (typeof body.name === 'string' && body.name.trim()) data.name = body.name.trim().slice(0, 120)
if (body.pages !== undefined) data.pages = toPages(body.pages)
if (body.thumbnail !== undefined) data.thumbnail = typeof body.thumbnail === 'string' ? body.thumbnail : null
+
+ // ── v0.10 divergence check ──────────────────────────────────
+ const baseUpdatedAt =
+ typeof body.baseUpdatedAt === 'string' && body.baseUpdatedAt ? body.baseUpdatedAt : null
+ let mergedPages: PageData[] | null = null
+ if (baseUpdatedAt && data.pages !== undefined) {
+ const current = await db.design.findUnique({
+ where: { id },
+ select: { updatedAt: true, pages: true },
+ })
+ // normalize both timestamps to ms-precision ISO for comparison —
+ // Prisma returns Date; the client received it via JSON (ISO string)
+ const serverIso = current ? new Date(current.updatedAt).toISOString() : null
+ let baseIso: string | null = null
+ try {
+ baseIso = new Date(baseUpdatedAt).toISOString()
+ } catch {
+ baseIso = null
+ }
+ if (serverIso && baseIso && serverIso !== baseIso) {
+ // divergent — merge their pages into ours by stamp
+ const ours = asPages(current?.pages)
+ const theirs = asPages(data.pages)
+ mergedPages = mergePages(ours, theirs)
+ data.pages = mergedPages as unknown as Prisma.InputJsonValue
+ }
+ }
+
const design = await db.design.update({ where: { id }, data })
return NextResponse.json({
id: design.id,
name: design.name,
updatedAt: design.updatedAt,
+ ...(mergedPages ? { merged: true, pages: mergedPages } : {}),
})
} catch (error) {
console.error('PUT /api/designs/[id] failed', error)
diff --git a/src/components/dashboard/hooks.ts b/src/components/dashboard/hooks.ts
index d083812..8eda644 100644
--- a/src/components/dashboard/hooks.ts
+++ b/src/components/dashboard/hooks.ts
@@ -168,6 +168,23 @@ export async function duplicateDesign(id: string): Promise<DesignRecord> {
export async function deleteDesign(id: string): Promise<void> {
const res = await fetch(`/api/designs/${id}`, { method: 'DELETE' }) // soft delete -> Trash
if (!res.ok) throw new Error('Failed to delete design')
+ // v0.10: drop any locally persisted offline state for this design
+ void purgeOfflineState(id)
+}
+
+/** v0.10: remove the IndexedDB offline doc + op queue for a design. */
+async function purgeOfflineState(id: string): Promise<void> {
+ try {
+ const { purge } = await import('@/lib/collab/offline-store')
+ await purge(id)
+ } catch {
+ /* IndexedDB unavailable — nothing persisted */
+ }
+ try {
+ localStorage.removeItem(`canvix-seq-${id}`)
+ } catch {
+ /* storage unavailable */
+ }
}
/** v0.4: trash list / restore / permanent delete */
@@ -188,6 +205,7 @@ export async function restoreDesign(id: string): Promise<void> {
export async function deleteDesignForever(id: string): Promise<void> {
const res = await fetch(`/api/designs/${id}?permanent=1`, { method: 'DELETE' })
if (!res.ok) throw new Error('Failed to delete design permanently')
+ void purgeOfflineState(id)
}
export async function renameDesign(id: string, name: string): Promise<void> {
diff --git a/src/components/editor/Editor.tsx b/src/components/editor/Editor.tsx
index 4a69a19..2e9dcb9 100644
--- a/src/components/editor/Editor.tsx
+++ b/src/components/editor/Editor.tsx
@@ -32,7 +32,7 @@ import { AnimatePanel } from './AnimatePanel'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { toast } from '@/hooks/use-toast'
-import type { ImageElement } from '@/lib/types'
+import type { ImageElement, PageData } from '@/lib/types'
const CanvasStage = dynamic(() => import('./canvas/CanvasStage'), { ssr: false })
@@ -126,6 +126,27 @@ export default function Editor() {
// v0.9: view-only designs (owned by another account) never autosave —
// the API would refuse with 403 anyway; skipping keeps the console
// clean and the “saved” indicator honest.
+ const persistOfflineDoc = useCallback(async () => {
+ const state = useEditorStore.getState()
+ if (!state.designId || state.readOnly) return
+ try {
+ const { putDoc } = await import('@/lib/collab/offline-store')
+ const { getActiveCollabSession } = await import('@/hooks/use-collab')
+ await putDoc({
+ designId: state.designId,
+ name: state.designName,
+ width: state.width,
+ height: state.height,
+ pages: state.pages,
+ baseUpdatedAt: state.baseUpdatedAt,
+ seq: getActiveCollabSession()?.lastSeq ?? 0,
+ savedAt: Date.now(),
+ })
+ } catch {
+ /* IndexedDB unavailable — offline durability is best-effort */
+ }
+ }, [])
+
const save = useCallback(
async (withThumbnail: boolean) => {
const state = useEditorStore.getState()
@@ -142,17 +163,40 @@ export default function Editor() {
body: JSON.stringify({
name: state.designName,
pages: state.pages,
+ baseUpdatedAt: state.baseUpdatedAt,
...(thumbnail ? { thumbnail } : {}),
}),
})
if (!res.ok) throw new Error('save failed')
+ const saved = (await res.json()) as {
+ updatedAt?: string
+ merged?: boolean
+ pages?: PageData[]
+ }
+ // v0.10: the server merged our pages with concurrent edits — adopt
+ // the merged result (applying through the merge gate is a no-op for
+ // our own content and pulls in the kept remote parts)
+ if (saved.merged && Array.isArray(saved.pages) && saved.pages.length) {
+ useEditorStore.getState().applyRemoteOp({
+ seq: 0,
+ id: `save-merge-${Date.now()}`,
+ designId: state.designId,
+ actorId: 'server-merge',
+ kind: 'pages:replace',
+ payload: { pages: saved.pages },
+ createdAt: new Date().toISOString(),
+ })
+ }
+ useEditorStore.getState().setBaseUpdatedAt(saved.updatedAt ?? null)
useEditorStore.getState().markSaved()
} catch (err) {
console.error('Autosave failed', err)
useEditorStore.setState({ saving: false })
}
+ // v0.10: keep the offline mirror fresh whether the save landed or not
+ void persistOfflineDoc()
},
- []
+ [persistOfflineDoc]
)
// debounced autosave on changes
@@ -162,6 +206,14 @@ export default function Editor() {
return () => clearTimeout(t)
}, [dirty, designId, version, save])
+ // v0.10: offline mirror — persist the working document (debounced) on
+ // every content mutation so a crash/reload/offline spell loses nothing
+ useEffect(() => {
+ if (!dirty || !designId) return
+ const t = setTimeout(() => void persistOfflineDoc(), 700)
+ return () => clearTimeout(t)
+ }, [dirty, designId, version, persistOfflineDoc])
+
// save when leaving the editor
useEffect(() => {
return () => {
diff --git a/src/components/editor/PresenceAvatars.tsx b/src/components/editor/PresenceAvatars.tsx
index ec6e8b8..08e1178 100644
--- a/src/components/editor/PresenceAvatars.tsx
+++ b/src/components/editor/PresenceAvatars.tsx
@@ -1,7 +1,7 @@
'use client'
import { useState } from 'react'
-import { Wifi, WifiOff, Loader2, Pencil } from 'lucide-react'
+import { Wifi, WifiOff, Loader2, Pencil, CloudUpload } from 'lucide-react'
import { useEditorStore } from '@/store/editor-store'
import { getIdentity, setDisplayName } from '@/lib/collab/identity'
import { cn } from '@/lib/utils'
@@ -21,24 +21,48 @@ function initials(name: string): string {
export function PresenceAvatars() {
const collaborators = useEditorStore((s) => s.collaborators)
const status = useEditorStore((s) => s.collabStatus)
+ const pendingOps = useEditorStore((s) => s.pendingOps)
+ const offlineRestored = useEditorStore((s) => s.offlineRestored)
const [open, setOpen] = useState(false)
const me = getIdentity()
return (
<div className="flex items-center gap-2 mr-1">
+ {/* v0.10: recovered offline work notice */}
+ {offlineRestored && (
+ <span
+ className="hidden lg:flex items-center gap-1 text-[11px] font-semibold text-sky-300/90"
+ title="Unsaved local changes were recovered — they merge automatically on save"
+ >
+ <CloudUpload size={12} /> Recovered
+ </span>
+ )}
{/* connection status */}
{status === 'live' ? (
- <span className="hidden xl:flex items-center gap-1 text-[11px] font-semibold text-emerald-300/90" title={`Live — ${collaborators.length + 1} editing`}>
- <Wifi size={12} /> Live
- </span>
+ pendingOps > 0 ? (
+ <span className="hidden xl:flex items-center gap-1 text-[11px] font-semibold text-amber-300/90" title={`${pendingOps} queued change${pendingOps === 1 ? '' : 's'} — syncing`}>
+ <Loader2 size={12} className="animate-spin" /> Syncing {pendingOps}
+ </span>
+ ) : (
+ <span className="hidden xl:flex items-center gap-1 text-[11px] font-semibold text-emerald-300/90" title={`Live — ${collaborators.length + 1} editing`}>
+ <Wifi size={12} /> Live
+ </span>
+ )
) : status === 'connecting' ? (
<span className="hidden xl:flex items-center gap-1 text-[11px] font-semibold text-amber-300/90" title="Reconnecting…">
<Loader2 size={12} className="animate-spin" /> Syncing
</span>
) : (
- <span className="hidden xl:flex items-center gap-1 text-[11px] font-semibold text-white/40" title="Offline — edits save locally">
- <WifiOff size={12} /> Offline
+ <span
+ className="hidden xl:flex items-center gap-1 text-[11px] font-semibold text-white/40"
+ title={
+ pendingOps > 0
+ ? `Offline — ${pendingOps} change${pendingOps === 1 ? '' : 's'} saved locally and will sync automatically`
+ : 'Offline — edits save locally'
+ }
+ >
+ <WifiOff size={12} /> Offline{pendingOps > 0 ? ` · ${pendingOps}` : ''}
</span>
)}
diff --git a/src/hooks/use-collab.ts b/src/hooks/use-collab.ts
index 8afce27..a5fd4cc 100644
--- a/src/hooks/use-collab.ts
+++ b/src/hooks/use-collab.ts
@@ -38,6 +38,7 @@ export function useCollab(): void {
activeSession = session
session.onStatus = (s) => useEditorStore.getState().setCollabStatus(s)
+ session.onQueueDepth = (n) => useEditorStore.setState({ pendingOps: n })
session.onEvents = (events) => {
const store = useEditorStore.getState()
for (const ev of events) store.applyRemoteOp(ev)
diff --git a/src/lib/collab/client.ts b/src/lib/collab/client.ts
index 47b9c23..93c93c2 100644
--- a/src/lib/collab/client.ts
+++ b/src/lib/collab/client.ts
@@ -1,6 +1,12 @@
'use client'
import type { Collaborator, CollabOp, CollabStatus, DesignEventRow, OpEnvelope, StreamFrame } from './protocol'
+import { getClock } from './hlc'
+import {
+ MAX_QUEUE,
+ getQueue as loadPersistedQueue,
+ putQueue as persistQueue,
+} from './offline-store'
/**
* CollabSession — one per open design.
@@ -11,6 +17,9 @@ import type { Collaborator, CollabOp, CollabStatus, DesignEventRow, OpEnvelope,
* (v0.9.2: was 120 ms / 5 s — each write is a remote-DB upsert, and
* the old rates let a single moving mouse generate ~8 writes/s)
* - reconnect with exponential backoff (0.5 s → 8 s), gap-free replay via ?since
+ * - v0.10 offline merge: the op queue and the replay cursor persist
+ * (IndexedDB / localStorage) — edits made offline survive reloads and
+ * flush on reconnect; nothing is dropped while the network is down
*
* Zustand stays the local rendering truth; collab never blocks input.
*/
@@ -33,17 +42,29 @@ export class CollabSession {
private processedEventIds = new Set<string>()
private lastCursorSent = 0
private pendingCursor: { page: number; x: number; y: number; selection?: string[] } | null = null
+ private persistTimer: ReturnType<typeof setTimeout> | null = null
+ private booted = false
// callbacks
onStatus: ((s: CollabStatus) => void) | null = null
onEvents: ((events: DesignEventRow[]) => void) | null = null
onPresence: ((collaborators: Collaborator[]) => void) | null = null
+ /** v0.10: pending-op count changes (offline badge) */
+ onQueueDepth: ((n: number) => void) | null = null
constructor(designId: string, pid: string, name: string, color: string) {
this.designId = designId
this.pid = pid
this.name = name
this.color = color
+ // v0.10: resume the replay cursor from the last frame we consumed —
+ // a reload must not replay the whole retained log over a fresh document
+ try {
+ const stored = Number(localStorage.getItem(`canvix-seq-${designId}`))
+ if (Number.isFinite(stored) && stored > 0) this.lastSeq = stored
+ } catch {
+ /* storage unavailable — since=0 (gate-protected) */
+ }
}
// ── lifecycle ─────────────────────────────────────────────
@@ -55,6 +76,23 @@ export class CollabSession {
// v0.9.2: 15 s heartbeat — the server treats presence as live for 30 s,
// so this still tolerates one lost beat before a collaborator fades out.
this.heartbeatTimer = setInterval(() => void this.heartbeat(), 15_000)
+ // v0.10: restore ops persisted while offline and flush them as soon as
+ // we have a connection (they carry HLC stamps, so they merge safely no
+ // matter what happened on the server meanwhile)
+ if (!this.booted) {
+ this.booted = true
+ void loadPersistedQueue(this.designId).then((restored) => {
+ if (this.disposed) return
+ if (restored.length) {
+ // persisted ops are older than anything typed this session —
+ // front of the queue, flushed first
+ this.queue = [...restored, ...this.queue].slice(0, MAX_QUEUE) as OpEnvelope[]
+ this.scheduleQueuePersist()
+ void this.flush()
+ }
+ this.onQueueDepth?.(this.queue.length)
+ })
+ }
}
dispose() {
@@ -63,6 +101,9 @@ export class CollabSession {
if (this.flushTimer) clearInterval(this.flushTimer)
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer)
if (this.reconnectTimer) clearTimeout(this.reconnectTimer)
+ if (this.persistTimer) clearTimeout(this.persistTimer)
+ // v0.10: flush what we can one last time, then durably persist the rest
+ void this.flush().finally(() => this.scheduleQueuePersist(0))
this.es?.close()
this.es = null
}
@@ -133,6 +174,14 @@ export class CollabSession {
// server max seq — safe to track even without events (ids are monotonic)
if (frame.seq > this.lastSeq && (frame.events ?? []).length === 0) this.lastSeq = frame.seq
}
+ // v0.10: persist the replay cursor (tiny; survives reloads/crashes)
+ if (this.lastSeq > 0) {
+ try {
+ localStorage.setItem(`canvix-seq-${this.designId}`, String(this.lastSeq))
+ } catch {
+ /* storage unavailable */
+ }
+ }
const now = Date.now()
this.onPresence?.(
(frame.presence ?? []).map((p) => ({
@@ -150,6 +199,9 @@ export class CollabSession {
/** Queue a local op (deduped by eventId, applied optimistically locally). */
emit(op: CollabOp, eventId: string) {
if (this.disposed) return
+ // v0.10: every emitted write carries an HLC stamp — replicas (and the
+ // server's PUT merge) arbitrate by it, so replay order never matters
+ const hlc = getClock(this.pid).nowHlc()
// coalesce consecutive elements:update patches for the same ids (drags/typing) —
// keeps the event log small and the fan-out cheap
if (op.kind === 'elements:update') {
@@ -162,16 +214,32 @@ export class CollabSession {
op.ids.every((id) => prev.ids.includes(id))
) {
last.op = { kind: 'elements:update', pageId: prev.pageId, ids: prev.ids, patch: { ...prev.patch, ...op.patch } }
+ last.hlc = hlc
return
}
}
}
- this.queue.push({ eventId, op })
+ this.queue.push({ eventId, hlc, op })
+ if (this.queue.length > MAX_QUEUE) this.queue = this.queue.slice(-MAX_QUEUE)
+ this.onQueueDepth?.(this.queue.length)
+ this.scheduleQueuePersist()
if (this.queue.length >= 20) void this.flush()
}
+ /** debounced durable persist of the pending queue (offline survival) */
+ private scheduleQueuePersist(delay = 500) {
+ if (this.persistTimer) return
+ this.persistTimer = setTimeout(() => {
+ this.persistTimer = null
+ void persistQueue(
+ this.designId,
+ this.queue as unknown as Array<{ eventId: string; hlc?: string; op: Record<string, unknown> }>,
+ )
+ }, delay)
+ }
+
private async flush() {
- if (this.disposed || !this.queue.length) return
+ if (!this.queue.length) return
const batch = this.queue.splice(0, 20)
try {
const res = await fetch(`/api/collab/${encodeURIComponent(this.designId)}/events`, {
@@ -179,14 +247,25 @@ export class CollabSession {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ pid: this.pid, name: this.name, color: this.color, events: batch }),
})
- if (!res.ok && (res.status === 404 || res.status === 503)) {
+ if (res.ok) {
+ this.onQueueDepth?.(this.queue.length)
+ this.scheduleQueuePersist(100)
+ } else if (res.status === 404 || res.status === 503) {
// design gone / db down — drop the queue (local editor still works)
this.queue = []
+ this.onQueueDepth?.(0)
+ this.scheduleQueuePersist(0)
+ } else {
+ // transient server error — keep the batch for the next tick
+ this.queue = [...batch, ...this.queue].slice(0, MAX_QUEUE)
}
} catch {
- /* offline — re-queue once for a retry on the next tick, else drop */
- if (this.queue.length < 40) this.queue = [...batch.slice(0, 5), ...this.queue]
- else this.queue = []
+ // v0.10: OFFLINE — retain the batch at the front of the queue; the
+ // next tick retries. Editing continues and nothing is dropped while
+ // the network is down (bounded by MAX_QUEUE; queue + doc also persist).
+ this.queue = [...batch, ...this.queue].slice(0, MAX_QUEUE)
+ this.onQueueDepth?.(this.queue.length)
+ this.scheduleQueuePersist(0)
}
}
diff --git a/src/lib/collab/hlc.test.ts b/src/lib/collab/hlc.test.ts
new file mode 100644
index 0000000..44cbc7f
--- /dev/null
+++ b/src/lib/collab/hlc.test.ts
@@ -0,0 +1,119 @@
+// ─────────────────────────────────────────────────────────────
+// v0.10 offline merge — HLC invariants
+//
+// Locks in the total-order properties every merge decision depends on:
+// 1. monotonic issuance within an actor (across storage reloads)
+// 2. cross-actor ordering is total (no ties between different actors)
+// 3. observe() absorbs remote stamps (causality moves forward)
+// 4. formatted strings compare correctly as plain strings
+// ─────────────────────────────────────────────────────────────
+
+import { describe, expect, it } from 'vitest'
+import {
+ HybridLogicalClock,
+ compareHlc,
+ formatHlc,
+ hlcIsNewer,
+ parseHlc,
+ HLC_EPOCH,
+} from './hlc'
+
+function memoryStorage(initial?: string): Storage {
+ const map = new Map<string, string>()
+ if (initial) map.set('canvix-hlc', initial)
+ return {
+ getItem: (k: string) => map.get(k) ?? null,
+ setItem: (k: string, v: string) => void map.set(k, v),
+ removeItem: (k: string) => void map.delete(k),
+ clear: () => map.clear(),
+ key: () => null,
+ get length() { return map.size },
+ } as Storage
+}
+
+describe('hlc formatting', () => {
+ it('round-trips through parse', () => {
+ const h = formatHlc(1770000000000, 42, 'p_abc')
+ const p = parseHlc(h)!
+ expect(p.w).toBe(1770000000000)
+ expect(p.c).toBe(42)
+ expect(p.actor).toBe('p_abc')
+ })
+
+ it('pads so plain string comparison equals numeric comparison', () => {
+ const a = formatHlc(99, 5, 'x')
+ const b = formatHlc(100, 0, 'x')
+ const c = formatHlc(99, 6, 'x')
+ expect(a < b).toBe(true) // walltime dominates
+ expect(a < c).toBe(true) // counter breaks walltime ties
+ })
+
+ it('rejects malformed stamps in parse', () => {
+ expect(parseHlc('garbage')).toBeNull()
+ expect(parseHlc('')).toBeNull()
+ expect(parseHlc(':::')).toBeNull()
+ })
+
+ it('treats undefined/empty as epoch (legacy data)', () => {
+ expect(compareHlc(undefined, undefined)).toBe(0)
+ expect(hlcIsNewer('0000000001:00000:a', undefined)).toBe(true)
+ expect(hlcIsNewer(undefined, HLC_EPOCH)).toBe(false)
+ expect(hlcIsNewer(undefined, '0000000001:00000:a')).toBe(false)
+ })
+})
+
+describe('hlc clock', () => {
+ it('issues strictly monotonic stamps within an actor', () => {
+ const clock = new HybridLogicalClock('p_a', memoryStorage())
+ const stamps = Array.from({ length: 500 }, () => clock.nowHlc())
+ for (let i = 1; i < stamps.length; i++) {
+ expect(compareHlc(stamps[i], stamps[i - 1])).toBeGreaterThan(0)
+ }
+ })
+
+ it('stays monotonic across a restart (persisted state)', () => {
+ const store = memoryStorage()
+ const c1 = new HybridLogicalClock('p_a', store)
+ const last = c1.nowHlc()
+ const c2 = new HybridLogicalClock('p_a', store)
+ expect(compareHlc(c2.nowHlc(), last)).toBeGreaterThan(0)
+ })
+
+ it('absorbs remote stamps (observe moves causality forward)', () => {
+ const mine = new HybridLogicalClock('p_a', memoryStorage())
+ const remote = new HybridLogicalClock('p_b', memoryStorage())
+ // simulate a remote clock that is ahead
+ const ahead = formatHlc(Date.now() + 60_000, 9, 'p_b')
+ mine.observe(ahead)
+ const next = mine.nowHlc()
+ expect(compareHlc(next, ahead)).toBeGreaterThan(0)
+ // remote's older stamps never overtake
+ const older = remote.nowHlc()
+ expect(compareHlc(older, next)).toBeLessThan(0)
+ })
+
+ it('two actors never issue equal stamps', () => {
+ const a = new HybridLogicalClock('p_a', memoryStorage())
+ const b = new HybridLogicalClock('p_b', memoryStorage())
+ const set = new Set<string>()
+ for (let i = 0; i < 200; i++) {
+ set.add(a.nowHlc())
+ set.add(b.nowHlc())
+ }
+ expect(set.size).toBe(400)
+ })
+
+ it('skewed local clocks stay bounded by observe', () => {
+ let fakeNow = Date.now() + 86_400_000 // one day ahead
+ const skew = new HybridLogicalClock('p_skew', memoryStorage(), () => fakeNow)
+ const honest = new HybridLogicalClock('p_honest', memoryStorage())
+ const skewed = skew.nowHlc()
+ honest.observe(skewed)
+ const response = honest.nowHlc()
+ // honest clock jumps past the skewed stamp (absorption), so its next
+ // write wins the LWW arbitration despite an honest wall clock
+ expect(compareHlc(response, skewed)).toBeGreaterThan(0)
+ fakeNow += 1
+ expect(compareHlc(skew.nowHlc(), response)).toBeGreaterThan(0)
+ })
+})
diff --git a/src/lib/collab/hlc.ts b/src/lib/collab/hlc.ts
new file mode 100644
index 0000000..5c4219b
--- /dev/null
+++ b/src/lib/collab/hlc.ts
@@ -0,0 +1,148 @@
+/**
+ * hlc — hybrid logical clock (v0.10 offline merge).
+ *
+ * Canvix converges concurrent/offline edits with per-element
+ * last-write-wins registers. "Last" must be a *causality-aware* total
+ * order, not wall-clock arrival: two editors with skewed clocks, or one
+ * replaying a queue after hours offline, must agree on which write wins
+ * no matter who applies what first.
+ *
+ * An HLC timestamp is `walltime-ms : counter : actor` (strings compare
+ * correctly because walltime and counter are zero-padded). It combines
+ * Kulkarni et al.'s rules:
+ * - `now()` = max(local clock, last issued, last observed) + 1 tick
+ * - `observe(h)` absorbs remote stamps so causality always moves forward
+ * - ties break on the actor id — a strict total order
+ *
+ * Properties we rely on (locked by tests):
+ * - monotonic within an actor across restarts (state persisted)
+ * - a.b ⇒ a < b whenever a happened-before b (absorbed)
+ * - two different actors never issue equal stamps
+ */
+
+const STORAGE_KEY = 'canvix-hlc'
+
+export interface HlcState {
+ /** last issued/observed walltime (ms) */
+ w: number
+ /** logical tick within the same walltime */
+ c: number
+}
+
+/** serialize as "w:c:actor" with zero-padding so plain string compare works */
+export function formatHlc(w: number, c: number, actor: string): string {
+ return `${w.toString(36).padStart(10, '0')}:${c.toString(36).padStart(5, '0')}:${actor}`
+}
+
+export function parseHlc(h: string): { w: number; c: number; actor: string } | null {
+ try {
+ const i = h.indexOf(':')
+ const j = h.indexOf(':', i + 1)
+ if (i < 0 || j < 0) return null
+ const w = Number.parseInt(h.slice(0, i), 36)
+ const c = Number.parseInt(h.slice(i + 1, j), 36)
+ const actor = h.slice(j + 1)
+ if (!Number.isFinite(w) || !Number.isFinite(c) || !actor) return null
+ return { w, c, actor }
+ } catch {
+ return null
+ }
+}
+
+/** epoch stamp — the implicit value of unstamped (legacy) data */
+export const HLC_EPOCH = '0000000000:00000:'
+
+/** total order on stamps; malformed strings sort as epoch (oldest) */
+export function compareHlc(a: string | undefined, b: string | undefined): number {
+ const sa = a && a.length ? a : HLC_EPOCH
+ const sb = b && b.length ? b : HLC_EPOCH
+ if (sa === sb) return 0
+ return sa < sb ? -1 : 1
+}
+
+export function hlcIsNewer(h: string | undefined, than: string | undefined): boolean {
+ return compareHlc(h, than) > 0
+}
+
+type StorageLike = Pick<Storage, 'getItem' | 'setItem'>
+
+/**
+ * One clock per browser tab-cluster. State persists in localStorage under
+ * the participant id (see identity.ts) so restarts stay monotonic; when
+ * storage is unavailable (SSR, private mode) the clock degrades to
+ * walltime + in-memory ticks — still safe within a session.
+ */
+export class HybridLogicalClock {
+ private state: HlcState
+ private readonly actor: string
+ private readonly storage: StorageLike | null
+ private readonly now: () => number
+
+ constructor(actor: string, storage?: StorageLike | null, nowFn?: () => number) {
+ this.actor = actor || 'anon'
+ this.storage = storage ?? null
+ this.now = nowFn ?? (() => Date.now())
+ let loaded: HlcState | null = null
+ if (this.storage) {
+ try {
+ const raw = this.storage.getItem(STORAGE_KEY)
+ if (raw) {
+ const parsed = JSON.parse(raw) as Partial<HlcState>
+ if (typeof parsed.w === 'number' && typeof parsed.c === 'number') loaded = { w: parsed.w, c: parsed.c }
+ }
+ } catch {
+ /* corrupted state — fall back to walltime */
+ }
+ }
+ this.state = loaded ?? { w: this.now(), c: 0 }
+ }
+
+ /** issue a new stamp (monotonic; persists state) */
+ nowHlc(): string {
+ const wall = this.now()
+ if (wall > this.state.w) this.state = { w: wall, c: 0 }
+ else this.state = { ...this.state, c: this.state.c + 1 }
+ this.persist()
+ return formatHlc(this.state.w, this.state.c, this.actor)
+ }
+
+ /** absorb a remote stamp (call whenever a remote op is applied) */
+ observe(h: string | undefined): void {
+ if (!h) return
+ const parsed = parseHlc(h)
+ if (!parsed) return
+ const wall = this.now()
+ if (parsed.w > this.state.w || (parsed.w === this.state.w && parsed.c > this.state.c)) {
+ // remote is ahead — jump to it, then bias the local tick upward
+ this.state = { w: Math.max(parsed.w, wall), c: parsed.c + (parsed.w >= wall ? 1 : 0) }
+ } else if (wall > this.state.w) {
+ this.state = { w: wall, c: 0 }
+ }
+ this.persist()
+ }
+
+ private persist() {
+ if (!this.storage) return
+ try {
+ this.storage.setItem(STORAGE_KEY, JSON.stringify(this.state))
+ } catch {
+ /* quota/private mode — in-memory monotonicity only */
+ }
+ }
+}
+
+/** Module singleton — created lazily on first use in the browser. */
+let singleton: HybridLogicalClock | null = null
+
+export function getClock(actor?: string): HybridLogicalClock {
+ if (!singleton) {
+ const storage = typeof localStorage !== 'undefined' ? localStorage : null
+ singleton = new HybridLogicalClock(actor ?? 'anon', storage)
+ }
+ return singleton
+}
+
+/** test hook — drop the singleton so a fresh actor/storage can be injected */
+export function resetClock(): void {
+ singleton = null
+}
diff --git a/src/lib/collab/merge.test.ts b/src/lib/collab/merge.test.ts
new file mode 100644
index 0000000..5e14dec
--- /dev/null
+++ b/src/lib/collab/merge.test.ts
@@ -0,0 +1,228 @@
+// ─────────────────────────────────────────────────────────────
+// v0.10 offline merge — pure merge semantics
+//
+// The convergence contract: for ANY pair of divergent replicas, merging
+// A-into-B and B-into-A produces the same document. These tests lock the
+// per-element LWW + tombstone rules that both the client (remote op
+// application, pages:replace) and the server (divergent PUT) rely on.
+// ─────────────────────────────────────────────────────────────
+
+import { describe, expect, it } from 'vitest'
+import { compareHlc, formatHlc } from './hlc'
+import {
+ isUnstamped,
+ mergeElements,
+ mergePages,
+ stampElementDeep,
+ stampPage,
+ stampPages,
+} from './merge'
+import type { AnyElement, PageData } from '@/lib/types'
+
+let tick = 0
+function h(actor: string): string {
+ tick += 1
+ return formatHlc(1770000000000 + tick, 1, actor)
+}
+
+function el(id: string, text: string, _m?: string): AnyElement {
+ return { type: 'text', id, text, x: 10, y: 10, _m } as unknown as AnyElement
+}
+
+function page(id: string, elements: AnyElement[], extra?: Partial<PageData>): PageData {
+ return { id, background: { type: 'solid', color: '#FFFFFF' }, elements, ...extra }
+}
+
+describe('mergeElements', () => {
+ it('disjoint edits merge as a union (both survive)', () => {
+ const a = el('e1', 'A text', h('a'))
+ const b = el('e2', 'B text', h('b'))
+ const { elements } = mergeElements([a], [b], {}, {})
+ expect(elements.map((e) => e.id).sort()).toEqual(['e1', 'e2'])
+ })
+
+ it('same element: the newer stamp wins, regardless of merge direction', () => {
+ const ours = el('e1', 'old text', h('a'))
+ const theirs = el('e1', 'new text', h('b'))
+ const ab = mergeElements([ours], [theirs], {}, {}).elements
+ const ba = mergeElements([theirs], [ours], {}, {}).elements
+ expect((ab[0] as { text: string }).text).toBe('new text')
+ expect((ba[0] as { text: string }).text).toBe('new text')
+ })
+
+ it('delete-vs-edit: newer write wins in both directions', () => {
+ // OURS deleted e1 (tombstone newer than their edit)
+ const editA = el('e1', 'edited by A', h('a'))
+ const tombB = h('b') // later stamp
+ const ab = mergeElements([editA], [], {}, { e1: tombB }).elements
+ expect(ab).toHaveLength(0) // delete wins
+ const ba = mergeElements([], [editA], { e1: tombB }, {}).elements
+ expect(ba).toHaveLength(0) // same verdict from the other side
+
+ // THEIR edit is newer than our delete → edit wins
+ const tombOld = h('a')
+ const editNew = el('e1', 'newer edit', h('b'))
+ const keep = mergeElements([], [editNew], { e1: tombOld }, {}).elements
+ expect(keep).toHaveLength(1)
+ })
+
+ it('re-add after delete clears the tombstone (newer stamp resurrects)', () => {
+ const tomb = h('a')
+ const readded = el('e1', 'reborn', h('b'))
+ const out = mergeElements([readded], [], { e1: tomb }, {})
+ expect(out.elements).toHaveLength(1)
+ // and the merged tombstones keep the max for ids that stay dead
+ const out2 = mergeElements([], [], { e1: tomb, e2: h('a') }, { e2: h('b') })
+ expect(out2.tombstones.e2).toBeTruthy()
+ expect(compareHlc(out2.tombstones.e2, out2.tombstones.e1)).toBeGreaterThan(0)
+ })
+
+ it('tombstones merge pointwise to the max stamp', () => {
+ const t1 = h('a')
+ const t2 = h('b')
+ const { tombstones } = mergeElements([], [], { x: t1, y: t2 }, { x: t2, z: t1 })
+ expect(tombstones.x).toBe(t2)
+ expect(tombstones.y).toBe(t2)
+ expect(tombstones.z).toBe(t1)
+ })
+
+ it('legacy unstamped data loses to any stamped write', () => {
+ const legacy = el('e1', 'from 2026')
+ const stamped = el('e1', 'stamped edit', h('a'))
+ const out = mergeElements([legacy], [stamped], {}, {}).elements
+ expect((out[0] as { text: string }).text).toBe('stamped edit')
+ // two legacy copies → ours wins (stability, no churn)
+ const legacy2 = el('e1', 'other legacy')
+ const out2 = mergeElements([legacy], [legacy2], {}, {}).elements
+ expect((out2[0] as { text: string }).text).toBe('from 2026')
+ })
+})
+
+describe('mergePages', () => {
+ it('page sets union; matched pages element-merge', () => {
+ const ours = [page('p1', [el('a', 'a', h('x'))]), page('p2', [el('b', 'b', h('x'))])]
+ const theirs = [page('p1', [el('a', 'a2', h('y')), el('c', 'c', h('y'))]), page('p3', [el('d', 'd', h('y'))])]
+ const merged = mergePages(ours, theirs)
+ expect(merged.map((p) => p.id)).toEqual(['p1', 'p2', 'p3'])
+ const p1 = merged[0]
+ expect(p1.elements.map((e) => e.id).sort()).toEqual(['a', 'c'])
+ const p2 = merged[1]
+ expect(p2.elements.map((e) => e.id)).toEqual(['b'])
+ })
+
+ it('page meta (background) LWW by _pm', () => {
+ const ours = page('p1', [], { _pm: h('a'), background: { type: 'solid', color: '#111111' } })
+ const theirs = page('p1', [], { _pm: h('b'), background: { type: 'solid', color: '#222222' } })
+ const merged = mergePages([ours], [theirs])
+ expect((merged[0].background as { color: string }).color).toBe('#222222')
+ // reverse direction — same winner
+ const merged2 = mergePages([theirs], [ours])
+ expect((merged2[0].background as { color: string }).color).toBe('#222222')
+ })
+
+ it('element tombstones survive page merges', () => {
+ // tombstone (t=200) is NEWER than the attempted re-add (t=100)
+ const ours = page('p1', [el('keep', 'k', '0000000100:00001:a')], {
+ tombstones: { dead: '0000000200:00001:a' },
+ })
+ const theirs = page('p1', [el('dead', 'resurrected?', '0000000100:00001:a')])
+ const merged = mergePages([ours], [theirs])
+ expect(merged[0].elements.map((e) => e.id)).toEqual(['keep'])
+ expect(merged[0].tombstones?.dead).toBeTruthy()
+ // reverse direction — same verdict
+ const merged2 = mergePages([theirs], [ours])
+ expect(merged2[0].elements.map((e) => e.id)).toEqual(['keep'])
+ expect(merged2[0].tombstones?.dead).toBeTruthy()
+ })
+
+ it('convergence: A∘B === B∘A on a mixed divergence scenario', () => {
+ // Build a realistic divergence: shared base + each side's edits.
+ // One element per id per side (well-formed replica invariant).
+ const baseEl = el('shared', 'base') // unstamped shared base
+ const ours = [
+ page(
+ 'p1',
+ [baseEl, el('only-ours', 'ours', '0000000100:00001:a')],
+ { tombstones: { gone: '0000000300:00001:a' } },
+ ),
+ page('p2', [el('p2el', 'v1', '0000000100:00002:a')]),
+ ]
+ const theirs = [
+ page(
+ 'p1',
+ [
+ el('shared', 'theirs edited', '0000000200:00001:b'),
+ el('gone', 're-add attempt', '0000000100:00001:a'), // older than the tombstone
+ el('fresh', 'theirs new', '0000000150:00001:b'),
+ ],
+ { _pm: '0000000200:00002:b' },
+ ),
+ page('p3', [el('p3el', 'theirs', '0000000200:00003:b')]),
+ ]
+ const ab = mergePages(ours, theirs)
+ const ba = mergePages(theirs, ours)
+ // CONTENT converges in both directions: same page set, same element set,
+ // same winner per element id. (Array ORDER follows the "ours" side —
+ // z-order arbitration is the server's job: its merge direction is fixed
+ // because the stored document is always "ours" there, so the canonical
+ // order is whatever the next autosave persists. Concurrent reorders on
+ // one page may differ transiently per replica until then — documented.)
+ const canon = (pages: PageData[]) =>
+ JSON.stringify(
+ [...pages]
+ .sort((x, y) => (x.id < y.id ? -1 : 1))
+ .map((p) => ({
+ id: p.id,
+ _pm: p._pm ?? '',
+ background: p.background,
+ tombstones: p.tombstones ?? {},
+ elements: [...p.elements].sort((x, y) => (x.id < y.id ? -1 : 1)),
+ })),
+ )
+ expect(canon(ab)).toBe(canon(ba))
+ // deterministic content checks
+ expect(ab.map((p) => p.id)).toEqual(['p1', 'p2', 'p3'])
+ const p1 = ab[0]
+ // 'shared' → theirs edited (stamped beats the unstamped base);
+ // 'only-ours' + 'fresh' kept (no tombstones); 'gone' blocked (100 < 300)
+ expect([...p1.elements].sort((x, y) => (x.id < y.id ? -1 : 1)).map((e) => e.id)).toEqual(['fresh', 'only-ours', 'shared'])
+ expect((p1.elements.find((e) => e.id === 'shared') as { text: string }).text).toBe('theirs edited')
+ expect(p1.tombstones?.gone).toBe('0000000300:00001:a')
+ })
+
+ it('isUnstamped detects legacy documents', () => {
+ expect(isUnstamped([page('p', [el('e', 'x')])])).toBe(true)
+ expect(isUnstamped([page('p', [el('e', 'x', h('a'))])])).toBe(false)
+ expect(isUnstamped([page('p', [el('e', 'x')], { tombstones: { e: h('a') } })])).toBe(false)
+ })
+})
+
+describe('stamping helpers', () => {
+ it('stampPages stamps pages and elements deeply (groups)', () => {
+ const stamp = h('s')
+ const group = {
+ type: 'group',
+ id: 'g1',
+ children: [el('child1', 'c1'), el('child2', 'c2')],
+ } as unknown as AnyElement
+ const pages = [page('p1', [el('top', 't'), group])]
+ const stamped = stampPages(pages, stamp)
+ expect(stamped[0]._pm).toBe(stamp)
+ expect(stamped[0].elements[0]._m).toBe(stamp)
+ const g = stamped[0].elements[1] as unknown as { children: AnyElement[] }
+ expect(g.children[0]._m).toBe(stamp)
+ // inputs untouched (no in-place mutation)
+ expect(pages[0].elements[0]._m).toBeUndefined()
+ })
+
+ it('stampElementDeep / stampPage produce fresh identities', () => {
+ const original = el('e', 'x')
+ const stamped = stampElementDeep(original, h('s'))
+ expect(stamped).not.toBe(original)
+ expect(stamped._m).toBeTruthy()
+ const p = page('p', [el('e', 'x')])
+ const sp = stampPage(p, h('s'))
+ expect(sp).not.toBe(p)
+ expect(sp._pm).toBeTruthy()
+ })
+})
diff --git a/src/lib/collab/merge.ts b/src/lib/collab/merge.ts
new file mode 100644
index 0000000..10b7504
--- /dev/null
+++ b/src/lib/collab/merge.ts
@@ -0,0 +1,212 @@
+/**
+ * merge — deterministic offline/concurrent document merge (v0.10).
+ *
+ * One pure function, used in BOTH places that can see divergent documents:
+ * 1. the client applying a remote `pages:replace` (undo / resize /
+ * restore / template) on top of locally-newer state
+ * 2. the server merging an autosave PUT whose `baseUpdatedAt` no longer
+ * matches (the tab was offline while others saved)
+ *
+ * Model: every element is an LWW-register keyed by id, written with an HLC
+ * stamp (`_m`); deletes are tombstones (`PageData.tombstones[id] = hlc`).
+ * Pages match by id; the page SET is a union (offline page deletions are
+ * the documented coarse case). Because both sides run the same rules on
+ * the same stamps, CONTENT converges regardless of application order —
+ * the property Yjs gives via CRDTs, obtained here without migrating the
+ * document model.
+ *
+ * Array ORDER (element z-order, page order) follows the "ours" side; the
+ * server is the canonical convergence point because its merge direction
+ * is fixed (the stored document is always "ours" there) — the next
+ * autosave persists one canonical order for everyone. Concurrent
+ * reorders of the same page may differ transiently per replica until
+ * that save lands; content never diverges.
+ */
+
+import type { AnyElement, PageData } from '@/lib/types'
+import { compareHlc } from './hlc'
+
+/** stamp of an element — undefined (legacy data) reads as epoch */
+export function elementHlc(el: AnyElement | undefined): string | undefined {
+ return el?._m
+}
+
+function tombstonesOf(page: PageData | undefined): Record<string, string> {
+ return page?.tombstones ?? {}
+}
+
+function byId<T extends { id: string }>(items: T[]): Map<string, T> {
+ return new Map(items.map((it) => [it.id, it]))
+}
+
+/**
+ * Merge two element lists of the SAME page id.
+ *
+ * Rules (per element id):
+ * - in both → the copy with the newer `_m` wins (strict >; equal stamps
+ * are impossible across actors, and same-actor equal means identical)
+ * - only ours → keep UNLESS theirs tombstoned it with a newer stamp
+ * - only theirs → add UNLESS ours tombstoned it with a >= stamp
+ *
+ * Tombstone maps merge pointwise (max stamp), so a delete survives even
+ * when the deleted element's side has no element row to contribute.
+ */
+export function mergeElements(
+ ours: AnyElement[],
+ theirs: AnyElement[],
+ ourTombs: Record<string, string>,
+ theirTombs: Record<string, string>,
+): { elements: AnyElement[]; tombstones: Record<string, string> } {
+ // Defensive dedupe: a well-formed replica holds one element per id, but
+ // a malformed/partially-synced document may not. Last occurrence wins
+ // (matches Map semantics used below) and keeps the merge total.
+ const dedupe = (list: AnyElement[]): AnyElement[] => {
+ const seen = new Set<string>()
+ const out: AnyElement[] = []
+ for (let i = list.length - 1; i >= 0; i--) {
+ const el = list[i]
+ if (!el?.id || seen.has(el.id)) continue
+ seen.add(el.id)
+ out.unshift(el)
+ }
+ return out
+ }
+ const oursList = dedupe(ours)
+ const theirsList = dedupe(theirs)
+ const oursMap = byId(oursList)
+ const theirsMap = byId(theirsList)
+
+ const tombstones: Record<string, string> = {}
+ for (const [id, h] of Object.entries(ourTombs)) tombstones[id] = h
+ for (const [id, h] of Object.entries(theirTombs)) {
+ if (compareHlc(h, tombstones[id]) > 0) tombstones[id] = h
+ }
+
+ const elements: AnyElement[] = []
+ // preserve OUR order for elements we keep; theirs-only elements append
+ // in their order (stable, deterministic on both sides)
+ for (const el of oursList) {
+ const their = theirsMap.get(el.id)
+ if (their) {
+ elements.push(compareHlc(their._m, el._m) > 0 ? their : el)
+ } else {
+ // deleted by theirs?
+ const t = theirTombs[el.id]
+ if (t && compareHlc(t, el._m) > 0) {
+ // their delete is newer → stays deleted
+ } else {
+ elements.push(el)
+ }
+ }
+ }
+ for (const el of theirsList) {
+ if (oursMap.has(el.id)) continue // handled above
+ const t = ourTombs[el.id]
+ if (t && compareHlc(t, el._m) >= 0) continue // our delete wins (or equal-content re-delete)
+ elements.push(el)
+ }
+
+ // prune tombstones that no longer beat any live element and refer to
+ // nothing on either side (bounded growth hygiene)
+ const live = new Set(elements.map((e) => e.id))
+ for (const id of Object.keys(tombstones)) {
+ if (!live.has(id) && !oursMap.has(id) && !theirsMap.has(id)) {
+ // element unknown to both docs — keep the tombstone anyway: it may
+ // be racing a third replica's add. Tombstone maps are small.
+ }
+ }
+
+ return { elements, tombstones }
+}
+
+/**
+ * Merge page-level scalars. Background & transition are LWW by the page
+ * stamp `_pm` (set on page:background / page:replace / pages:replace).
+ * Unstamped legacy pages lose against stamped writes; two unstamped pages
+ * keep OURS (stability — the server-side merge must not churn on no-ops).
+ */
+export function mergePageMeta(
+ ours: PageData,
+ theirs: PageData,
+): { background: PageData['background']; transition?: PageData['transition']; _pm?: string } {
+ if (compareHlc(theirs._pm, ours._pm) > 0) {
+ return { background: theirs.background, transition: theirs.transition, _pm: theirs._pm }
+ }
+ return { background: ours.background, transition: ours.transition, _pm: ours._pm }
+}
+
+/**
+ * Merge two full page arrays. Pages match by id; the result is the union
+ * (ours-order first, theirs-only pages appended). Element merges run per
+ * matched page. The output pages are FRESH objects — inputs are never
+ * mutated (safe for structural sharing elsewhere).
+ */
+export function mergePages(ours: PageData[], theirs: PageData[]): PageData[] {
+ const oursMap = byId(ours)
+ const theirsMap = byId(theirs)
+ const out: PageData[] = []
+
+ for (const page of ours) {
+ const their = theirsMap.get(page.id)
+ if (!their) {
+ out.push(page) // only ours — union keeps it (page deletes are op-level)
+ continue
+ }
+ const { elements, tombstones } = mergeElements(
+ page.elements,
+ their.elements,
+ page.tombstones ?? {},
+ their.tombstones ?? {},
+ )
+ const meta = mergePageMeta(page, their)
+ const merged: PageData = { id: page.id, ...meta, elements }
+ if (Object.keys(tombstones).length) merged.tombstones = tombstones
+ out.push(merged)
+ }
+ for (const page of theirs) {
+ if (oursMap.has(page.id)) continue
+ out.push(page)
+ }
+ return out
+}
+
+/** true when a page list carries no stamps/tombstones at all (legacy doc) */
+export function isUnstamped(pages: PageData[]): boolean {
+ return pages.every((p) => !p._pm && !p.tombstones && p.elements.every((e) => !e._m))
+}
+
+/**
+ * Stamp every element + the page with `hlc` — used by full-replace ops
+ * (undo, redo, resize, restore version, apply template, magic page ops).
+ * A stamped replace deterministically WINS against older concurrent edits
+ * and LOSES against newer ones, instead of clobbering blindly.
+ * Returns fresh page objects (structural sharing preserved per element? —
+ * no: a replace redefines every element, so all identities change; that
+ * matches today's full-replace rendering behaviour).
+ */
+export function stampPages(pages: PageData[], hlc: string): PageData[] {
+ return pages.map((p) => ({
+ ...p,
+ _pm: hlc,
+ elements: p.elements.map((e) => stampElementDeep(e, hlc)),
+ }))
+}
+
+/** stamp a single page (page:replace emitters) */
+export function stampPage(page: PageData, hlc: string): PageData {
+ return { ...page, _pm: hlc, elements: page.elements.map((e) => stampElementDeep(e, hlc)) }
+}
+
+/** stamp one element and (recursively) any group children */
+export function stampElementDeep<T extends AnyElement>(el: T, hlc: string): T {
+ if (el.type === 'group' && Array.isArray((el as unknown as { children?: AnyElement[] }).children)) {
+ const g = el as unknown as { children: AnyElement[] } & Record<string, unknown>
+ return { ...el, _m: hlc, children: g.children.map((c) => stampElementDeep(c, hlc)) } as T
+ }
+ return { ...el, _m: hlc }
+}
+
+/** stamp a single element (element:add path) */
+export function stampElement<T extends AnyElement>(el: T, hlc: string): T {
+ return { ...el, _m: hlc }
+}
diff --git a/src/lib/collab/offline-store.test.ts b/src/lib/collab/offline-store.test.ts
new file mode 100644
index 0000000..dbd2022
--- /dev/null
+++ b/src/lib/collab/offline-store.test.ts
@@ -0,0 +1,67 @@
+// ─────────────────────────────────────────────────────────────
+// v0.10 offline merge — offline-store arbitration logic
+//
+// The IndexedDB wrapper itself is thin and browser-bound; what MUST be
+// correct is the restore decision (which copy wins when the editor opens)
+// and the queue record round-trip shape.
+// ─────────────────────────────────────────────────────────────
+
+import { describe, expect, it } from 'vitest'
+import { decideRestore, MAX_QUEUE, type OfflineDoc } from './offline-store'
+
+function doc(over: Partial<OfflineDoc> = {}): OfflineDoc {
+ return {
+ designId: 'd1',
+ name: 'Offline work',
+ width: 1080,
+ height: 1080,
+ pages: [{ id: 'p1', background: { type: 'solid', color: '#FFFFFF' }, elements: [] }],
+ baseUpdatedAt: '2026-10-29T00:00:00.000Z',
+ seq: 42,
+ savedAt: Date.parse('2026-10-29T12:00:00.000Z'),
+ ...over,
+ }
+}
+
+describe('decideRestore (offline restore arbitration)', () => {
+ it('restores when the persisted queue holds unsynced ops', () => {
+ const d = decideRestore(doc(), '2026-10-29T13:00:00.000Z', 7)
+ expect(d.restore).toBe(true)
+ expect(d.reason).toBe('queue')
+ })
+
+ it('restores when the local doc is newer than the server save (failed autosave)', () => {
+ // server last saved at 10:00, local mirror persisted at 12:00
+ const d = decideRestore(doc(), '2026-10-29T10:00:00.000Z', 0)
+ expect(d.restore).toBe(true)
+ expect(d.reason).toBe('newer-doc')
+ })
+
+ it('does NOT restore when the server copy is current and queue is empty', () => {
+ // server saved at 12:00:05 — newer than our mirror at 12:00:00
+ const d = decideRestore(doc(), '2026-10-29T12:00:05.000Z', 0)
+ expect(d.restore).toBe(false)
+ expect(d.reason).toBe('none')
+ })
+
+ it('tolerates clock jitter (2s grace window)', () => {
+ const d = decideRestore(doc(), '2026-10-29T12:00:01.500Z', 0)
+ expect(d.restore).toBe(false)
+ })
+
+ it('no local doc → never restore', () => {
+ expect(decideRestore(null, '2026-10-29T10:00:00.000Z', 0).restore).toBe(false)
+ // even a queue without a doc cannot restore the document (the session
+ // still flushes the ops themselves — that path is independent)
+ expect(decideRestore(null, undefined, 5).restore).toBe(false)
+ })
+
+ it('missing server timestamp → only a non-empty queue restores (conservative)', () => {
+ expect(decideRestore(doc(), undefined, 0).restore).toBe(false)
+ expect(decideRestore(doc(), undefined, 1).restore).toBe(true)
+ })
+
+ it('queue cap is a hard bound', () => {
+ expect(MAX_QUEUE).toBeGreaterThanOrEqual(200)
+ })
+})
diff --git a/src/lib/collab/offline-store.ts b/src/lib/collab/offline-store.ts
new file mode 100644
index 0000000..944f7d9
--- /dev/null
+++ b/src/lib/collab/offline-store.ts
@@ -0,0 +1,158 @@
+/**
+ * offline-store — durable local state for offline editing (v0.10).
+ *
+ * Two things must survive a reload / crash while offline:
+ * 1. the working document (the editor's pages — autosave can't run)
+ * 2. the queue of collab ops that never reached the server
+ *
+ * IndexedDB (not localStorage — full page JSON with thumbnails runs to
+ * megabytes, and localStorage is a synchronous 5 MB string slot). The
+ * wrapper is intentionally tiny: two object stores, key-value access,
+ * structured-clone storage. Every method degrades to a no-op when IDB is
+ * unavailable (SSR, private mode, ancient browsers) — offline durability
+ * is best-effort, never a crash.
+ */
+
+import type { PageData } from '@/lib/types'
+
+const DB_NAME = 'canvix-offline'
+const DB_VERSION = 1
+const DOCS = 'docs'
+const QUEUES = 'queues'
+
+/** persisted working document per design */
+export interface OfflineDoc {
+ designId: string
+ name: string
+ width: number
+ height: number
+ pages: PageData[]
+ /** server `updatedAt` this doc was last known to be based on */
+ baseUpdatedAt: string | null
+ /** last server seq the local doc has absorbed (event replay cursor) */
+ seq: number
+ /** walltime of the last local persist (restore arbitration) */
+ savedAt: number
+}
+
+/** persisted op queue per design (envelopes exactly as emitted) */
+export interface QueuedEnvelope {
+ eventId: string
+ hlc?: string
+ op: Record<string, unknown>
+}
+
+/** hard caps — a runaway offline session must not wedge the browser */
+export const MAX_QUEUE = 500
+export const MAX_DOC_PAGES = 200
+
+function openDb(): Promise<IDBDatabase | null> {
+ return new Promise((resolve) => {
+ if (typeof indexedDB === 'undefined') return resolve(null)
+ let req: IDBOpenDBRequest
+ try {
+ req = indexedDB.open(DB_NAME, DB_VERSION)
+ } catch {
+ return resolve(null)
+ }
+ req.onupgradeneeded = () => {
+ const db = req.result
+ if (!db.objectStoreNames.contains(DOCS)) db.createObjectStore(DOCS, { keyPath: 'designId' })
+ if (!db.objectStoreNames.contains(QUEUES)) db.createObjectStore(QUEUES, { keyPath: 'designId' })
+ }
+ req.onsuccess = () => resolve(req.result)
+ req.onerror = () => resolve(null)
+ req.onblocked = () => resolve(null)
+ })
+}
+
+function tx<T>(store: string, mode: IDBTransactionMode, run: (s: IDBObjectStore) => IDBRequest): Promise<T | null> {
+ return openDb().then(
+ (db) =>
+ new Promise<T | null>((resolve) => {
+ if (!db) return resolve(null)
+ try {
+ const t = db.transaction(store, mode)
+ const req = run(t.objectStore(store)) as IDBRequest<T>
+ req.onsuccess = () => resolve(req.result)
+ req.onerror = () => resolve(null)
+ t.onabort = () => resolve(null)
+ } catch {
+ resolve(null)
+ }
+ }),
+ )
+}
+
+// ── working document ──────────────────────────────────────────
+
+export async function putDoc(doc: OfflineDoc): Promise<boolean> {
+ if (doc.pages.length > MAX_DOC_PAGES) return false
+ const r = await tx<unknown>(DOCS, 'readwrite', (s) => s.put(doc))
+ return r !== null
+}
+
+export async function getDoc(designId: string): Promise<OfflineDoc | null> {
+ const r = await tx<OfflineDoc | undefined>(DOCS, 'readonly', (s) => s.get(designId))
+ return r ?? null
+}
+
+// ── op queue ──────────────────────────────────────────────────
+
+export async function putQueue(designId: string, queue: QueuedEnvelope[]): Promise<boolean> {
+ const r = await tx<unknown>(QUEUES, 'readwrite', (s) =>
+ s.put({ designId, queue: queue.slice(0, MAX_QUEUE) }),
+ )
+ return r !== null
+}
+
+export async function getQueue(designId: string): Promise<QueuedEnvelope[]> {
+ const r = await tx<{ designId: string; queue: QueuedEnvelope[] } | undefined>(QUEUES, 'readonly', (s) =>
+ s.get(designId),
+ )
+ return Array.isArray(r?.queue) ? r.queue : []
+}
+
+// ── purge (design deleted / permanently synced) ───────────────
+
+export async function purge(designId: string): Promise<void> {
+ await Promise.all([
+ tx(DOCS, 'readwrite', (s) => s.delete(designId)),
+ tx(QUEUES, 'readwrite', (s) => s.delete(designId)),
+ ])
+}
+
+// ── restore arbitration (pure — unit tested) ──────────────────
+
+export interface RestoreDecision {
+ restore: boolean
+ reason: 'queue' | 'newer-doc' | 'none'
+}
+
+/**
+ * Decide whether the locally persisted document should replace the
+ * freshly fetched server document on editor open.
+ *
+ * - queue non-empty → we hold ops the server never accepted → restore
+ * - local doc persisted after the server's last save → our autosave
+ * failed (offline) → restore
+ * - otherwise the server document is authoritative → discard local
+ *
+ * `serverUpdatedAt` absent (legacy/mocked fetch) → only a non-empty
+ * queue restores (conservative).
+ */
+export function decideRestore(
+ local: OfflineDoc | null,
+ serverUpdatedAt: string | undefined,
+ queueLength: number,
+): RestoreDecision {
+ if (queueLength > 0 && local) return { restore: true, reason: 'queue' }
+ if (!local) return { restore: false, reason: 'none' }
+ if (serverUpdatedAt) {
+ const serverMs = Date.parse(serverUpdatedAt)
+ if (Number.isFinite(serverMs) && local.savedAt - serverMs > 2_000) {
+ return { restore: true, reason: 'newer-doc' }
+ }
+ }
+ return { restore: false, reason: 'none' }
+}
diff --git a/src/lib/collab/protocol.ts b/src/lib/collab/protocol.ts
index 6b4b02b..b9cf23d 100644
--- a/src/lib/collab/protocol.ts
+++ b/src/lib/collab/protocol.ts
@@ -27,6 +27,10 @@ export type CollabOp =
export interface OpEnvelope {
/** client-generated unique id — dedupe on replay */
eventId: string
+ /** v0.10 offline merge: hybrid-logical-clock stamp of this write.
+ * Absent on legacy clients — the server stamps those with its own clock
+ * at persist time (see the events route). */
+ hlc?: string
op: CollabOp
}
@@ -42,6 +46,12 @@ export interface DesignEventRow {
createdAt: string
}
+/** v0.10: read the HLC stamp off an event payload (server embeds `_h`). */
+export function eventHlc(row: Pick<DesignEventRow, 'payload'>): string | undefined {
+ const p = row.payload as { _h?: unknown } | null | undefined
+ return typeof p?._h === 'string' ? p._h : undefined
+}
+
export interface PresenceRow {
id: string
name: string
diff --git a/src/lib/types.ts b/src/lib/types.ts
index 64c0f83..c195e6b 100644
--- a/src/lib/types.ts
+++ b/src/lib/types.ts
@@ -99,6 +99,11 @@ export interface BaseElement {
name?: string
/** v0.5: entry animation (undefined = none) */
animation?: ElementAnimation
+ /** v0.10 offline-merge: hybrid-logical-clock stamp of the last write to
+ * this element ("w:counter:actor"). Older documents lack it — treated as
+ * epoch "0" so stamped writes deterministically win over legacy state.
+ * See src/lib/collab/hlc.ts + merge.ts. */
+ _m?: string
/** v0.5 Magic Layers provenance — set on elements generated from an image analysis */
magicLayer?: {
sourceRegion: string
@@ -303,6 +308,12 @@ export interface PageData {
elements: AnyElement[]
/** v0.5: transition played when this page appears after another */
transition?: PageTransition
+ /** v0.10 offline-merge: page-level HLC stamp (background/transition writes) */
+ _pm?: string
+ /** v0.10 offline-merge: elementId → HLC stamp of its deletion. Tombstones
+ * ride the saved document so deletes merge deterministically against
+ * concurrent edits (delete wins only while it is the newer write). */
+ tombstones?: Record<string, string>
}
/** user-placed ruler guide (position in page px; scoped to a page) */
diff --git a/src/store/editor-store.test.ts b/src/store/editor-store.test.ts
index 7f54218..3048651 100644
--- a/src/store/editor-store.test.ts
+++ b/src/store/editor-store.test.ts
@@ -139,3 +139,153 @@ describe('editor-store structural sharing (v0.7)', () => {
expect(next[0].elements.find((e) => e.id === 't2')).toBe(before[0].elements.find((e) => e.id === 't2'))
})
})
+
+// ─────────────────────────────────────────────────────────────
+// v0.10 offline merge — remote-op application gates
+//
+// applyRemoteOp must be ORDER-INDEPENDENT for stamped events: replaying a
+// stale event after newer state cannot clobber it. That is what makes
+// offline queue flush + gap-free replay safe without coordination.
+// ─────────────────────────────────────────────────────────────
+
+describe('applyRemoteOp HLC gates (v0.10)', () => {
+ beforeEach(() => seedTwoPages())
+
+ function remoteEvent(kind: string, payload: Record<string, unknown>, actor = 'remote-agent') {
+ return {
+ seq: Math.floor(Math.random() * 1e6),
+ id: `evt-${Math.random().toString(36).slice(2)}`,
+ designId: 'test-design',
+ actorId: actor,
+ kind,
+ payload,
+ createdAt: new Date().toISOString(),
+ }
+ }
+
+ it('stamped elements:update applies and stamps the element', () => {
+ useEditorStore.getState().applyRemoteOp(
+ remoteEvent('elements:update', {
+ pageId: 'page-a',
+ ids: ['t1'],
+ _h: '0000000100:00001:remote-agent',
+ patch: { x: 777, _m: '0000000100:00001:remote-agent' },
+ }),
+ )
+ const t1 = useEditorStore.getState().pages[0].elements.find((e) => e.id === 't1')!
+ expect((t1 as { x: number }).x).toBe(777)
+ expect(t1._m).toBe('0000000100:00001:remote-agent')
+ })
+
+ it('an OLDER stamped update cannot clobber newer element state (order independence)', () => {
+ // newer write lands first
+ useEditorStore.getState().applyRemoteOp(
+ remoteEvent('elements:update', {
+ pageId: 'page-a',
+ ids: ['t1'],
+ _h: '0000000200:00001:remote-agent',
+ patch: { x: 200, _m: '0000000200:00001:remote-agent' },
+ }),
+ )
+ // then a stale replay arrives (offline flush out of order)
+ useEditorStore.getState().applyRemoteOp(
+ remoteEvent('elements:update', {
+ pageId: 'page-a',
+ ids: ['t1'],
+ _h: '0000000100:00002:other-actor',
+ patch: { x: 100, _m: '0000000100:00002:other-actor' },
+ }),
+ )
+ const t1 = useEditorStore.getState().pages[0].elements.find((e) => e.id === 't1')!
+ expect((t1 as { x: number }).x).toBe(200)
+ expect(t1._m).toBe('0000000200:00001:remote-agent')
+ })
+
+ it('legacy events (no stamps) apply as before', () => {
+ useEditorStore.getState().applyRemoteOp(
+ remoteEvent('elements:update', { pageId: 'page-a', ids: ['t1'], patch: { x: 4242 } }),
+ )
+ const t1 = useEditorStore.getState().pages[0].elements.find((e) => e.id === 't1')!
+ expect((t1 as { x: number }).x).toBe(4242)
+ })
+
+ it('element:delete tombstones and removes; a NEWER re-add survives a stale delete', () => {
+ // delete at t=100
+ useEditorStore.getState().applyRemoteOp(
+ remoteEvent('element:delete', { pageId: 'page-a', ids: ['t1'], _h: '0000000100:00001:remote-agent' }),
+ )
+ expect(useEditorStore.getState().pages[0].elements.find((e) => e.id === 't1')).toBeUndefined()
+ expect(useEditorStore.getState().pages[0].tombstones?.t1).toBeTruthy()
+
+ // newer re-add at t=200
+ useEditorStore.getState().applyRemoteOp(
+ remoteEvent('element:add', {
+ pageId: 'page-a',
+ _h: '0000000200:00001:remote-agent',
+ element: { ...makeText('t1', 'Reborn'), _m: '0000000200:00001:remote-agent' },
+ }),
+ )
+ expect(useEditorStore.getState().pages[0].elements.find((e) => e.id === 't1')).toBeTruthy()
+ expect(useEditorStore.getState().pages[0].tombstones?.t1).toBeUndefined()
+
+ // stale delete replay at t=150 must NOT kill the newer re-add
+ useEditorStore.getState().applyRemoteOp(
+ remoteEvent('element:delete', { pageId: 'page-a', ids: ['t1'], _h: '0000000150:00001:remote-agent' }),
+ )
+ expect(useEditorStore.getState().pages[0].elements.find((e) => e.id === 't1')).toBeTruthy()
+ })
+
+ it('pages:replace MERGES by stamp instead of clobbering (newer local edits survive)', () => {
+ // local (newer) edit to t1
+ useEditorStore.getState().updateElementsLive(['t1'], { x: 555 })
+
+ // a coarse pages:replace arrives whose t1 copy is STAMPED OLDER than our edit
+ useEditorStore.getState().applyRemoteOp(
+ remoteEvent('pages:replace', {
+ _h: '0000000001:00001:old-actor',
+ pages: [
+ {
+ id: 'page-a',
+ background: { type: 'solid', color: '#FFFFFF' },
+ elements: [{ ...makeText('t1', 'stale copy'), _m: '0000000001:00001:old-actor' }],
+ },
+ {
+ id: 'page-b',
+ background: { type: 'solid', color: '#000000' },
+ elements: [makeText('t3', 'Second page')],
+ },
+ ],
+ }),
+ )
+ const t1 = useEditorStore.getState().pages[0].elements.find((e) => e.id === 't1')!
+ expect((t1 as { x: number }).x).toBe(555) // our newer local write survived
+ // and a STAMPED-NEWER replace still wins
+ useEditorStore.getState().applyRemoteOp(
+ remoteEvent('pages:replace', {
+ _h: '9999999999:00001:winner',
+ pages: [
+ {
+ id: 'page-a',
+ background: { type: 'solid', color: '#FFFFFF' },
+ elements: [{ ...makeText('t1', 'fresh replace'), _m: '9999999999:00001:winner' }],
+ },
+ ],
+ width: 640,
+ height: 480,
+ }),
+ )
+ const t1b = useEditorStore.getState().pages[0].elements.find((e) => e.id === 't1')!
+ expect((t1b as { text: string }).text).toBe('fresh replace')
+ expect(useEditorStore.getState().width).toBe(640)
+ })
+
+ it('local mutations stamp elements (_m rides every write path)', () => {
+ useEditorStore.getState().updateElementsLive(['t1'], { x: 1 })
+ expect(useEditorStore.getState().pages[0].elements.find((e) => e.id === 't1')?._m).toBeTruthy()
+ useEditorStore.getState().addElement(makeText('t9', 'Added'))
+ expect(useEditorStore.getState().pages[0].elements.find((e) => e.id === 't9')?._m).toBeTruthy()
+ useEditorStore.getState().setSelection(['t1'])
+ useEditorStore.getState().deleteSelection()
+ expect(useEditorStore.getState().pages[0].tombstones?.t1).toBeTruthy()
+ })
+})
diff --git a/src/store/editor-store.ts b/src/store/editor-store.ts
index aebc805..8e5d32a 100644
--- a/src/store/editor-store.ts
+++ b/src/store/editor-store.ts
@@ -45,6 +45,21 @@ interface HistoryEntry {
// module-level clipboard (not reactive)
let clipboard: AnyElement[] = []
+// ── v0.10 offline merge: stamping choke points ────────────────
+// Local mutations that create/modify/delete elements stamp the change with
+// the session's hybrid logical clock; full-replace ops (undo, resize,
+// restore…) stamp the *broadcast copy* only, so local history snapshots keep
+// their O(1) structural sharing (unstamped local state is content-equal to
+// the stamped replicas — epoch loses to any stamped write, which is exactly
+// the replace-op's intent). See src/lib/collab/{hlc,merge}.ts.
+import { getClock } from '@/lib/collab/hlc'
+import { mergePages, stampPage, stampPages } from '@/lib/collab/merge'
+import { eventHlc } from '@/lib/collab/protocol'
+
+function nowHlc(): string {
+ return getClock().nowHlc()
+}
+
// ── v0.5 collaboration: op emission ─────────────────
// The store is the single source of truth for local mutations. After every
// LOCAL mutation it emits an op through the registered emitter (set by
@@ -193,6 +208,16 @@ interface EditorState {
/** apply a remote op (never emits, never pushes history) */
applyRemoteOp: (event: DesignEventRow) => void
+ // v0.10: offline merge bookkeeping
+ /** server `updatedAt` our pages are based on (sent with every autosave so
+ * the server can merge instead of clobber when we were offline) */
+ baseUpdatedAt: string | null
+ setBaseUpdatedAt: (t: string | null) => void
+ /** true when the editor opened with locally persisted offline work */
+ offlineRestored: boolean
+ /** collab ops queued but not yet accepted by the server (offline badge) */
+ pendingOps: number
+
// v0.5: comments mode
commentsOpen: boolean
toggleComments: () => void
@@ -265,6 +290,9 @@ export const useEditorStore = create<EditorState>((set, get) => ({
collabStatus: 'offline',
commentsOpen: false,
animateOpen: false,
+ baseUpdatedAt: null,
+ offlineRestored: false,
+ pendingOps: 0,
showRulers: false,
manualGuides: [],
@@ -291,7 +319,59 @@ export const useEditorStore = create<EditorState>((set, get) => ({
tool: 'select',
cropTargetId: null,
readOnly: d.readOnly === true,
+ baseUpdatedAt: d.updatedAt ?? null,
+ offlineRestored: false,
})
+ // v0.10: seed the collab replay cursor from the server's current seq —
+ // our freshly loaded document already contains every persisted edit,
+ // so replaying older log events is pure staleness (the _m gates would
+ // skip them anyway; the cursor avoids the wasted bandwidth).
+ try {
+ const seq = (d as { seq?: unknown }).seq
+ if (typeof seq === 'number' && seq >= 0) {
+ localStorage.setItem(`canvix-seq-${d.id}`, String(Math.floor(seq)))
+ }
+ } catch {
+ /* storage unavailable — since=0 replay is gate-protected */
+ }
+ // v0.10: offline restore — if this browser holds unsynced work for this
+ // design (persisted while offline), it wins over the server copy and its
+ // op queue replays on reconnect. Fire-and-forget: the editor renders the
+ // server copy immediately and swaps when the local state is newer.
+ if (!d.readOnly && typeof indexedDB !== 'undefined') {
+ void (async () => {
+ const { getDoc, getQueue, decideRestore, purge } = await import('@/lib/collab/offline-store')
+ const [doc, queue] = await Promise.all([getDoc(d.id), getQueue(d.id)])
+ const decision = decideRestore(doc, d.updatedAt, queue.length)
+ if (!decision.restore) {
+ // server copy is authoritative — drop the stale local mirror
+ // (queue empty by the decision rule; nothing unsynced to keep)
+ if (doc || queue.length) void purge(d.id)
+ return
+ }
+ if (doc && Array.isArray(doc.pages) && doc.pages.length) {
+ const s = get()
+ if (s.designId !== d.id) return // user moved on
+ set({
+ designName: doc.name || s.designName,
+ width: doc.width || s.width,
+ height: doc.height || s.height,
+ pages: doc.pages,
+ past: [],
+ future: [],
+ selectedIds: [],
+ dirty: true,
+ baseUpdatedAt: doc.baseUpdatedAt ?? s.baseUpdatedAt,
+ offlineRestored: true,
+ })
+ try {
+ localStorage.setItem(`canvix-seq-${d.id}`, String(doc.seq || 0))
+ } catch {
+ /* keep the seeded cursor */
+ }
+ }
+ })()
+ }
// v0.4: load server-side versions (Postgres); local list is the offline fallback
const local = loadVersions(d.id)
set({ versions: local })
@@ -346,8 +426,10 @@ export const useEditorStore = create<EditorState>((set, get) => ({
version: version + 1,
})
// undo restores snapshots — op-level undo replay is out of scope (see
- // COLLABORATION-ARCHITECTURE.md §7), so sync coarse
- emit({ kind: 'pages:replace', pages: prev.pages, width: get().width, height: get().height })
+ // COLLABORATION-ARCHITECTURE.md §7), so sync coarse. v0.10: the broadcast
+ // copy is stamped fresh (deterministic winner vs concurrent edits); the
+ // local set keeps the snapshot reference for O(1) structural sharing.
+ emit({ kind: 'pages:replace', pages: stampPages(prev.pages, nowHlc()), width: get().width, height: get().height })
},
redo: () => {
@@ -363,7 +445,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({
dirty: true,
version: version + 1,
})
- emit({ kind: 'pages:replace', pages: next.pages, width: get().width, height: get().height })
+ emit({ kind: 'pages:replace', pages: stampPages(next.pages, nowHlc()), width: get().width, height: get().height })
},
setSelection: (ids) => set({ selectedIds: ids }),
@@ -379,16 +461,20 @@ export const useEditorStore = create<EditorState>((set, get) => ({
get().pushHistory()
const { pages, currentPage } = get()
const next = editPage(pages, currentPage)
- next[currentPage].elements.push(el)
- set({ pages: next, selectedIds: [el.id] })
- emit({ kind: 'element:add', pageId: next[currentPage].id, element: el })
+ const stamped = { ...el, _m: nowHlc() } as AnyElement
+ next[currentPage].elements.push(stamped)
+ set({ pages: next, selectedIds: [stamped.id], dirty: true, version: get().version + 1 })
+ emit({ kind: 'element:add', pageId: next[currentPage].id, element: stamped })
},
updateElementsLive: (ids, patch) => {
// v0.7 hot path (typing, slider drags, remote/MCP live edits):
// pure immutable update — only the patched elements get new identities,
// every other page/element keeps its reference so memoized nodes skip.
+ // v0.10: the patch carries an HLC stamp (_m) — it lands on the element
+ // locally AND rides the broadcast, so replicas gate stale replays by it.
const { pages, currentPage, version } = get()
+ const stampedPatch = { ...patch, _m: nowHlc() } as Partial<Record<string, unknown>>
const idSet = ids.length > 4 ? new Set(ids) : null
const hit = idSet ? (id: string) => idSet.has(id) : (id: string) => ids.includes(id)
const next = pages.map((p, i) =>
@@ -396,11 +482,11 @@ export const useEditorStore = create<EditorState>((set, get) => ({
? p
: {
...p,
- elements: p.elements.map((e) => (hit(e.id) ? ({ ...e, ...patch } as AnyElement) : e)),
+ elements: p.elements.map((e) => (hit(e.id) ? ({ ...e, ...stampedPatch } as AnyElement) : e)),
}
)
set({ pages: next, version: version + 1, dirty: true })
- emit({ kind: 'elements:update', pageId: next[currentPage].id, ids: [...ids], patch: { ...patch } })
+ emit({ kind: 'elements:update', pageId: next[currentPage].id, ids: [...ids], patch: stampedPatch })
},
updateElements: (ids, patch) => {
@@ -415,7 +501,14 @@ export const useEditorStore = create<EditorState>((set, get) => ({
const { pages, currentPage } = get()
const next = editPage(pages, currentPage)
next[currentPage].elements = next[currentPage].elements.filter((e) => !selectedIds.includes(e.id))
- set({ pages: next, selectedIds: [] })
+ // v0.10: tombstone the deletion so it merges deterministically against
+ // concurrent edits of the same elements (delete wins while it is the
+ // newer write; a later re-add clears it).
+ const h = nowHlc()
+ const tombs: Record<string, string> = {}
+ for (const id of selectedIds) tombs[id] = h
+ next[currentPage] = { ...next[currentPage], tombstones: { ...(next[currentPage].tombstones ?? {}), ...tombs } }
+ set({ pages: next, selectedIds: [], dirty: true, version: get().version + 1 })
emit({ kind: 'element:delete', pageId: next[currentPage].id, ids: [...selectedIds] })
},
@@ -426,10 +519,10 @@ export const useEditorStore = create<EditorState>((set, get) => ({
const page = pages[currentPage]
const clones = page.elements
.filter((e) => selectedIds.includes(e.id))
- .map((e) => ({ ...clone(e), id: uid(e.type), x: e.x + 32, y: e.y + 32 }))
+ .map((e) => ({ ...clone(e), id: uid(e.type), x: e.x + 32, y: e.y + 32, _m: nowHlc() }) as AnyElement)
const next = editPage(pages, currentPage)
next[currentPage].elements = [...next[currentPage].elements, ...clones]
- set({ pages: next, selectedIds: clones.map((c) => c.id) })
+ set({ pages: next, selectedIds: clones.map((c) => c.id), dirty: true, version: get().version + 1 })
emit({ kind: 'elements:add', pageId: next[currentPage].id, elements: clones })
},
@@ -448,11 +541,11 @@ export const useEditorStore = create<EditorState>((set, get) => ({
pasteClipboard: () => {
if (!clipboard.length) return
get().pushHistory()
- const clones = clipboard.map((e) => ({ ...clone(e), id: uid(e.type), x: e.x + 32, y: e.y + 32 }))
+ const clones = clipboard.map((e) => ({ ...clone(e), id: uid(e.type), x: e.x + 32, y: e.y + 32, _m: nowHlc() }) as AnyElement)
const { pages, currentPage } = get()
const next = editPage(pages, currentPage)
next[currentPage].elements = [...next[currentPage].elements, ...clones]
- set({ pages: next, selectedIds: clones.map((c) => c.id) })
+ set({ pages: next, selectedIds: clones.map((c) => c.id), dirty: true, version: get().version + 1 })
emit({ kind: 'elements:add', pageId: next[currentPage].id, elements: clones })
},
@@ -499,8 +592,9 @@ export const useEditorStore = create<EditorState>((set, get) => ({
const group = createGroupElement(children)
const next = editPage(pages, currentPage)
next[currentPage].elements = [...next[currentPage].elements.filter((e) => !selectedIds.includes(e.id)), group]
- set({ pages: next, selectedIds: [group.id] })
- emit({ kind: 'page:replace', pageId: next[currentPage].id, page: next[currentPage] })
+ set({ pages: next, selectedIds: [group.id], dirty: true, version: get().version + 1 })
+ // v0.10: structural page change — broadcast a fully stamped copy
+ emit({ kind: 'page:replace', pageId: next[currentPage].id, page: stampPage(next[currentPage], nowHlc()) })
},
ungroupSelection: () => {
@@ -536,14 +630,15 @@ export const useEditorStore = create<EditorState>((set, get) => ({
next[currentPage].elements.push(...releasedEls)
released = [...released, ...releasedEls.map((c) => c.id)]
}
- set({ pages: next, selectedIds: released })
- emit({ kind: 'page:replace', pageId: next[currentPage].id, page: next[currentPage] })
+ set({ pages: next, selectedIds: released, dirty: true, version: get().version + 1 })
+ emit({ kind: 'page:replace', pageId: next[currentPage].id, page: stampPage(next[currentPage], nowHlc()) })
},
alignElements: (ids, mode) => {
if (!ids.length) return
get().pushHistory()
- const { pages, currentPage, width, height } = get()
+ const { pages, currentPage, width, height, version } = get()
+ const h = nowHlc()
const next = pages.map((p, i) =>
i !== currentPage
? p
@@ -551,25 +646,31 @@ export const useEditorStore = create<EditorState>((set, get) => ({
...p,
elements: p.elements.map((el) => {
if (!ids.includes(el.id)) return el
- switch (mode) {
- case 'left': return { ...el, x: 0 }
- case 'cx': return { ...el, x: Math.round((width - el.width) / 2) }
- case 'right': return { ...el, x: width - el.width }
- case 'top': return { ...el, y: 0 }
- case 'cy': return { ...el, y: Math.round((height - el.height) / 2) }
- case 'bottom': return { ...el, y: height - el.height }
- }
+ // v0.10: only the ALIGNED elements get a fresh stamp — untouched
+ // elements keep theirs so concurrent remote edits still win
+ const touched = (() => {
+ switch (mode) {
+ case 'left': return { x: 0 }
+ case 'cx': return { x: Math.round((width - el.width) / 2) }
+ case 'right': return { x: width - el.width }
+ case 'top': return { y: 0 }
+ case 'cy': return { y: Math.round((height - el.height) / 2) }
+ case 'bottom': return { y: height - el.height }
+ }
+ })()
+ return { ...el, ...touched, _m: h } as AnyElement
}),
}
)
- set({ pages: next })
+ set({ pages: next, dirty: true, version: version + 1 })
emit({ kind: 'page:replace', pageId: next[currentPage].id, page: next[currentPage] })
},
flipSelection: (axis) => {
- const { selectedIds, pages, currentPage } = get()
+ const { selectedIds, pages, currentPage, version } = get()
if (!selectedIds.length) return
get().pushHistory()
+ const h = nowHlc()
const next = pages.map((p, i) =>
i !== currentPage
? p
@@ -577,13 +678,13 @@ export const useEditorStore = create<EditorState>((set, get) => ({
...p,
elements: p.elements.map((el) => {
if (!selectedIds.includes(el.id)) return el
- if (el.type === 'image') return { ...el, flipH: axis === 'h' ? !el.flipH : el.flipH, flipV: axis === 'v' ? !el.flipV : el.flipV }
+ if (el.type === 'image') return { ...el, flipH: axis === 'h' ? !el.flipH : el.flipH, flipV: axis === 'v' ? !el.flipV : el.flipV, _m: h } as AnyElement
// shapes/text: mirror via negative scale is not in the model; rotate 180 for symmetric flip feel
- return { ...el, rotation: (el.rotation + (axis === 'h' ? 0 : 180)) % 360 }
+ return { ...el, rotation: (el.rotation + (axis === 'h' ? 0 : 180)) % 360, _m: h } as AnyElement
}),
}
)
- set({ pages: next })
+ set({ pages: next, dirty: true, version: version + 1 })
emit({ kind: 'page:replace', pageId: next[currentPage].id, page: next[currentPage] })
},
@@ -622,9 +723,10 @@ export const useEditorStore = create<EditorState>((set, get) => ({
setPageBackground: (bg) => {
get().pushHistory()
- const { pages, currentPage } = get()
- const next = pages.map((p, i) => (i !== currentPage ? p : { ...p, background: bg }))
- set({ pages: next })
+ const { pages, currentPage, version } = get()
+ const h = nowHlc()
+ const next = pages.map((p, i) => (i !== currentPage ? p : { ...p, background: bg, _pm: h }))
+ set({ pages: next, dirty: true, version: version + 1 })
emit({ kind: 'page:background', pageId: next[currentPage].id, background: bg })
},
@@ -637,8 +739,10 @@ export const useEditorStore = create<EditorState>((set, get) => ({
height: t.height,
currentPage: 0,
selectedIds: [],
+ dirty: true,
+ version: get().version + 1,
})
- emit({ kind: 'pages:replace', pages, width: t.width, height: t.height })
+ emit({ kind: 'pages:replace', pages: stampPages(pages, nowHlc()), width: t.width, height: t.height })
},
setZoom: (z) => set({ zoom: Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, z)) }),
@@ -724,7 +828,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({
selectedIds: [],
dirty: true,
})
- emit({ kind: 'pages:replace', pages: v.pages, width: v.width, height: v.height })
+ emit({ kind: 'pages:replace', pages: stampPages(v.pages, nowHlc()), width: v.width, height: v.height })
},
deleteVersion: (id) => {
const { designId, versions } = get()
@@ -747,8 +851,8 @@ export const useEditorStore = create<EditorState>((set, get) => ({
// v0.4 magic resize: smart re-layout — elements scale & keep their relative
// position instead of all being dumped in the centre
const next = magicRelayoutPages(cloneAllPages(pages), oldW, oldH, width, height)
- set({ width, height, pages: next, selectedIds: [], zoom: 1 })
- emit({ kind: 'pages:replace', pages: next, width, height })
+ set({ width, height, pages: next, selectedIds: [], zoom: 1, dirty: true, version: get().version + 1 })
+ emit({ kind: 'pages:replace', pages: stampPages(next, nowHlc()), width, height })
},
// ── v0.4: magic translate ────────────────────────────
@@ -757,10 +861,11 @@ export const useEditorStore = create<EditorState>((set, get) => ({
get().pushHistory()
const { pages, version } = get()
const map = new Map(updates.map((u) => [u.id, u.text]))
+ const h = nowHlc()
const applyTexts = (els: AnyElement[]): AnyElement[] =>
els.map((el) => {
if (el.type === 'group') return { ...el, children: applyTexts(el.children) }
- return map.has(el.id) ? ({ ...el, text: map.get(el.id)! } as AnyElement) : el
+ return map.has(el.id) ? ({ ...el, text: map.get(el.id)!, _m: h } as AnyElement) : el
})
const next = pages.map((p) => ({ ...p, elements: applyTexts(p.elements) }))
set({ pages: next, version: version + 1, dirty: true })
@@ -773,17 +878,18 @@ export const useEditorStore = create<EditorState>((set, get) => ({
get().pushHistory()
const { pages, currentPage } = get()
const next = editPage(pages, currentPage)
- next[currentPage].elements = [...next[currentPage].elements, ...els.map((e) => clone(e))]
- set({ pages: next, selectedIds: els.map((e) => e.id) })
- emit({ kind: 'elements:add', pageId: next[currentPage].id, elements: els })
+ const stamped = els.map((e) => ({ ...clone(e), _m: nowHlc() }) as AnyElement)
+ next[currentPage].elements = [...next[currentPage].elements, ...stamped]
+ set({ pages: next, selectedIds: stamped.map((e) => e.id), dirty: true, version: get().version + 1 })
+ emit({ kind: 'elements:add', pageId: next[currentPage].id, elements: stamped })
},
replaceCurrentPage: (page) => {
get().pushHistory()
const { pages, currentPage } = get()
const next = [...pages]
next[currentPage] = clonePage(page)
- set({ pages: next, selectedIds: [] })
- emit({ kind: 'page:replace', pageId: page.id, page })
+ set({ pages: next, selectedIds: [], dirty: true, version: get().version + 1 })
+ emit({ kind: 'page:replace', pageId: page.id, page: stampPage(clonePage(page), nowHlc()) })
},
appendPage: (page) => {
get().pushHistory()
@@ -804,18 +910,19 @@ export const useEditorStore = create<EditorState>((set, get) => ({
setElementAnimation: (ids, animation) => {
if (!ids.length) return
get().pushHistory()
- const { pages, currentPage } = get()
+ const { pages, currentPage, version } = get()
+ const h = nowHlc()
const next = pages.map((p, i) =>
i !== currentPage
? p
: {
...p,
elements: p.elements.map((e) =>
- ids.includes(e.id) ? { ...e, animation: animation ?? undefined } : e
+ ids.includes(e.id) ? ({ ...e, animation: animation ?? undefined, _m: h } as AnyElement) : e
),
}
)
- set({ pages: next })
+ set({ pages: next, dirty: true, version: version + 1 })
emit({
kind: 'page:replace',
pageId: next[currentPage].id,
@@ -824,36 +931,43 @@ export const useEditorStore = create<EditorState>((set, get) => ({
},
setPageTransition: (transition) => {
get().pushHistory()
- const { pages, currentPage } = get()
- const next = pages.map((p, i) => (i !== currentPage ? p : { ...p, transition: transition ?? undefined }))
- set({ pages: next })
+ const { pages, currentPage, version } = get()
+ const h = nowHlc()
+ const next = pages.map((p, i) => (i !== currentPage ? p : { ...p, transition: transition ?? undefined, _pm: h }))
+ set({ pages: next, dirty: true, version: version + 1 })
emit({ kind: 'page:replace', pageId: next[currentPage].id, page: next[currentPage] })
},
magicAnimateCurrentPage: (speed = 'medium') => {
get().pushHistory()
- const { pages, currentPage, height } = get()
+ const { pages, currentPage, height, version } = get()
const next = pages.map((p, i) => (i !== currentPage ? p : magicAnimatePage(p, height, speed)))
const animated = next[currentPage]
- set({ pages: next })
- emit({ kind: 'page:replace', pageId: animated.id, page: animated })
+ set({ pages: next, dirty: true, version: version + 1 })
+ emit({ kind: 'page:replace', pageId: animated.id, page: stampPage(animated, nowHlc()) })
},
clearPageAnimations: () => {
get().pushHistory()
- const { pages, currentPage } = get()
+ const { pages, currentPage, version } = get()
const next = pages.map((p, i) => (i !== currentPage ? p : clearPageAnimations(p)))
const cleared = next[currentPage]
- set({ pages: next })
- emit({ kind: 'page:replace', pageId: cleared.id, page: cleared })
+ set({ pages: next, dirty: true, version: version + 1 })
+ emit({ kind: 'page:replace', pageId: cleared.id, page: stampPage(cleared, nowHlc()) })
},
// ── v0.5: collaboration runtime state ─────────
setCollaborators: (list) => set({ collaborators: list }),
setCollabStatus: (s) => set({ collabStatus: s }),
+ setBaseUpdatedAt: (t) => set({ baseUpdatedAt: t }),
applyRemoteOp: (event) => {
const payload = event.payload as Record<string, unknown> | null
if (!payload) return
const { pages, version } = get()
+ // v0.10: absorb the event's HLC into the local clock (causality moves
+ // forward), then read it as this event's write-stamp.
+ const evHlc = eventHlc(event)
+ if (evHlc) getClock().observe(evHlc)
+
const findPage = (pageId: unknown): number => pages.findIndex((p) => p.id === pageId)
// v0.7: immutable update — only the touched page gets a new object;
@@ -870,18 +984,49 @@ export const useEditorStore = create<EditorState>((set, get) => ({
case 'elements:update': {
const ids = (payload.ids as string[]) ?? []
const patch = (payload.patch as Record<string, unknown>) ?? {}
+ // v0.10 LWW gate: the write-stamp travels in the patch (_m) or, for
+ // server-stamped legacy events, at the payload root (_h). Apply only
+ // to elements whose current stamp is strictly older. No stamp at all
+ // = pre-v0.10 event → legacy passthrough (today's behaviour).
+ const stamp = (typeof patch._m === 'string' && patch._m) || evHlc
+ const gate = (el: AnyElement): boolean => !stamp || !el._m || stamp > el._m
next = mapPage(payload.pageId, (page) => ({
...page,
- elements: page.elements.map((e) => (ids.includes(e.id) ? ({ ...e, ...patch } as AnyElement) : e)),
+ elements: page.elements.map((e) =>
+ ids.includes(e.id) && gate(e) ? ({ ...e, ...patch, ...(stamp ? { _m: stamp } : {}) } as AnyElement) : e,
+ ),
}))
break
}
case 'element:add': {
const el = payload.element as AnyElement | undefined
if (el?.id) {
- next = mapPage(payload.pageId, (page) =>
- page.elements.some((e) => e.id === el.id) ? page : { ...page, elements: [...page.elements, clone(el)] }
- )
+ const stampedEl = { ...el, _m: el._m ?? evHlc } as AnyElement
+ next = mapPage(payload.pageId, (page) => {
+ const existing = page.elements.find((e) => e.id === el.id)
+ if (!existing) {
+ // re-add clears any tombstone that is older than this write
+ const tombs = { ...(page.tombstones ?? {}) }
+ let mutated = false
+ for (const [id, h] of Object.entries(tombs)) {
+ if (id === el.id && (!stampedEl._m || stampedEl._m > h)) {
+ delete tombs[id]
+ mutated = true
+ }
+ }
+ return {
+ ...page,
+ elements: [...page.elements, clone(stampedEl)],
+ ...(mutated ? { tombstones: tombs } : {}),
+ }
+ }
+ // exists: a newer re-add replaces it; an older one is stale
+ if (stampedEl._m && existing._m && stampedEl._m <= existing._m) return page
+ return {
+ ...page,
+ elements: page.elements.map((e) => (e.id === el.id ? clone(stampedEl) : e)),
+ }
+ })
}
break
}
@@ -889,15 +1034,62 @@ export const useEditorStore = create<EditorState>((set, get) => ({
const els = (payload.elements as AnyElement[]) ?? []
if (els.length) {
next = mapPage(payload.pageId, (page) => {
- const known = new Set(page.elements.map((e) => e.id))
- return { ...page, elements: [...page.elements, ...els.filter((e) => !known.has(e.id)).map((e) => clone(e))] }
+ const known = new Map(page.elements.map((e) => [e.id, e]))
+ const tombs = { ...(page.tombstones ?? {}) }
+ let tombsChanged = false
+ const additions: AnyElement[] = []
+ const replacements = new Map<string, AnyElement>()
+ for (const raw of els) {
+ if (!raw?.id) continue
+ const el = { ...raw, _m: raw._m ?? evHlc } as AnyElement
+ const existing = known.get(raw.id)
+ if (!existing) {
+ const t = tombs[raw.id]
+ if (t && el._m && el._m <= t) continue // tombstone newer — stays deleted
+ if (t && el._m) {
+ delete tombs[raw.id]
+ tombsChanged = true
+ }
+ additions.push(clone(el))
+ } else if (!el._m || !existing._m || el._m > existing._m) {
+ replacements.set(raw.id, clone(el))
+ }
+ }
+ if (!additions.length && !replacements.size) return page
+ return {
+ ...page,
+ elements: [
+ ...page.elements.map((e) => replacements.get(e.id) ?? e),
+ ...additions,
+ ],
+ ...(tombsChanged ? { tombstones: tombs } : {}),
+ }
})
}
break
}
case 'element:delete': {
const ids = new Set((payload.ids as string[]) ?? [])
- next = mapPage(payload.pageId, (page) => ({ ...page, elements: page.elements.filter((e) => !ids.has(e.id)) }))
+ next = mapPage(payload.pageId, (page) => {
+ const tombs = { ...(page.tombstones ?? {}) }
+ let changed = false
+ for (const id of ids) {
+ if (!evHlc) continue // legacy event — no stamp, no tombstone
+ const prev = tombs[id]
+ if (!prev || evHlc > prev) {
+ tombs[id] = evHlc
+ changed = true
+ }
+ }
+ // a delete only removes elements it is NOT older than (a stale
+ // offline delete must not kill a newer re-add)
+ const survivors = page.elements.filter((e) => {
+ if (!ids.has(e.id)) return true
+ return !!(evHlc && e._m && evHlc < e._m)
+ })
+ if (!changed && survivors.length === page.elements.length) return page
+ return { ...page, elements: survivors, tombstones: tombs }
+ })
break
}
case 'elements:reorder': {
@@ -927,22 +1119,37 @@ export const useEditorStore = create<EditorState>((set, get) => ({
break
}
case 'page:background': {
- next = mapPage(payload.pageId, (page) => ({ ...page, background: clone(payload.background as Background) }))
+ next = mapPage(payload.pageId, (page) =>
+ !evHlc || !page._pm || evHlc > page._pm
+ ? { ...page, background: clone(payload.background as Background), _pm: evHlc ?? page._pm }
+ : page,
+ )
break
}
case 'page:replace': {
const page = clone(payload.page as PageData)
if (page?.id) {
const i = findPage(page.id)
- next = i >= 0 ? pages.map((p, k) => (k === i ? page : p)) : [...pages, page]
+ if (i < 0) {
+ next = [...pages, page]
+ } else {
+ // v0.10: merge per element by stamp instead of blind replace —
+ // same rule as the server's divergent-PUT merge (merge.ts)
+ const merged = mergePages([pages[i]], [page])[0]
+ next = pages.map((p, k) => (k === i ? merged : p))
+ }
}
break
}
case 'pages:replace': {
const replaced = clone((payload.pages as PageData[]) ?? [])
if (replaced.length) {
- const currentPage = Math.min(get().currentPage, replaced.length - 1)
- set({ pages: replaced, currentPage, selectedIds: [], version: version + 1, dirty: true })
+ // v0.10: full-replace ops are stamped broadcasts — merge them per
+ // element/page by stamp so concurrent newer local edits survive
+ // (identical rule to the server-side PUT merge → convergence).
+ next = mergePages(pages, replaced)
+ const currentPage = Math.min(get().currentPage, next.length - 1)
+ set({ pages: next, currentPage, selectedIds: [], version: version + 1, dirty: true })
const w = Number(payload.width)
const h = Number(payload.height)
if (Number.isFinite(w) && w > 0 && Number.isFinite(h) && h > 0) set({ width: w, height: h })