packages/sync-client)Owner: WP-D, then DC2 (wave 3). ADRs 0019, 0007, 0008, 0006, 0401, 0410, 0103. Contracts: shared/src/session.ts (SyncClient, DocSession, Gesture), messages.ts, codec.ts, presence.ts. Server behaviour it relies on: realtime.md / ADR 0202.
Implemented (wave 1). DOM-free TypeScript for browsers and Node (MCP uses @linorahq/sync-client/connection).
packages/sync-client/src/
connection.ts RealtimeConnection: token reuse/refresh, WS lifecycle, hello (+ pipelined subscribes),
backoff, close codes, ping/idle, room routing. attach() = raw room for a replica;
openRoom() = RoomChannel with ACK promises for peers without a replica (MCP).
session.ts ReplicaSession (DocSession): replica, pending ops, per-key shadows, full rebase,
ACK settlement, tail matching, reload, gestures, undo/redo, presence.
pending.ts pending keys: (node, prop) -> {shadow, shadowSeq, last batch, live}; in-flight edits only
undo.ts UndoStack (limit 200) + gesture inverse compaction
presence.ts PresenceThrottle (<= 20 Hz, selection only on change) + PeerMap
client.ts RemoteSyncClient / createSyncClient: one connection per file, snapshot download, sessions
local.ts createLocalSession(doc) (offline, acked at once) + LocalHub (in-process sequencer)
env.ts injectable timers / WebSocket / fetch (tests run on a simulated clock)
getRealtimeToken() -> {token, url, expiresAt}; cached and reused across reconnects until 80% of its life; refreshed after a 4001 close or a failed upgrade. A 401/403 from the token call is fatal (unauthorized / forbidden).linora.v1, linora-rt.<token>; hello{protocol, rulesVersion, client, clientGrant?} with the page subscribes pipelined behind it -> welcome{clientId, clientGrant, role}. The grant is kept so reconnects keep the id space (new clientIds are rate limited server-side).GET .../snapshot (Content-Encoding gzip, inflated by fetch; X-Linora-Seq) -> docs.decodeSnapshot -> subscribe{pageId, sinceSeq, pendingFromClientSeq?, mode:'live'} -> tail -> synced -> live.retryAfterMs honoured). Close codes: 4001 new token, 4003 access revoked (fatal), 4009 version mismatch (fatal, app shows “reload”), 4010 retry after retryAfterMs. PING every 25 s; a socket silent for 60 s is closed and re-opened. role_changed reconnects with a fresh token to pick up the new role.Commits apply locally and join an open batch, sealed by a timer at most once per 16 ms (never inside the render loop; Node uses the same timer). Gesture SETs coalesce to the latest value per (node, prop) while unsent; gesture blob props (path points) are sent at most LIVE_BLOB_HZ. Messages are split at op boundaries to respect 4 MiB / 50,000 ops / MAX_BATCH_EXTRAS ids. TRANSFORM / SET_GEOMETRY ops above 262,144 ids (or more than fit a message) are split into id-range chunks at commit; the commit reports one verdict per op it was given. At most 64 batches in flight; further commits accumulate in the open batch until an ACK frees a slot. busy/rate_limited for clientSeq j: pause, resend only j after retryAfterMs (server-driven), and the later batches after j’s ACK (ADR 0410). protocol_error/too_large settle that batch as rejected. A subscribe refused with busy/rate_limited/internal is retried after retryAfterMs. RealtimeConnection.retryNow() skips the backoff (the app calls it on online / tab visible).
shadow) and its seq. A remote write to a key with a live pending write only updates the shadow. An ACK settles each key by seq: our value if our seq is newer than the shadow’s, else the shadow. This stays correct for dedupe ACKs that carry an older seq. CREATE / CREATE_BULK / RESTORE count as writes of every prop of the nodes they create.sequenced), write shadows, apply the remote batch, re-apply pending ops with local validation. Failing ops are predicted rejections, re-evaluated on every rebase (a later RESTORE can make them valid again). Cost O(pending ops), only on those batches.session.stats.synced, with pendingFromClientSeq; a dedupe ACK settles them like any ACK.snapshot_stale, seq gap, mismatch): fetch a fresh snapshot, re-apply pending ops on it, swap session.doc (onReload(cb) fires; the editor also detects the identity change), resubscribe from its seq. Batches acked at or below the snapshot seq are already contained in it and are not re-applied. Re-applied pending RESTOREs are checked structurally only: snapshots carry no tombstones, but the server still holds them.NOT_ALLOWED); read_only from the server downgrades the session and rolls back pending edits.Commits capture inverses (apply(..., {inverse: true})); undo/redo commit the inverse as a new transaction. Only this client’s transactions are on the stacks. A gesture is one entry (inverse compacted to the earliest value per key). Undo of a DELETE commits RESTORE ops (original ids; other clients’ ids are accepted while tombstoned, ADR 0101).
setPresence merges fields and sends at most once per 50 ms (leading edge, then trailing), selection, tool and follow only when they change (> 1,000 ids become count + bounds). After a reconnect the full state is resent. Interest management (ADR 0203): a peer cursor received outside the local viewport + PRESENCE_VIEW_MARGIN, or left outside by a pan, is stored hidden unless that peer is followed; the server resends it when it enters the view. Incoming PRESENCE_BATCH / peer_joined / peer_left update peers() and otherPeers (“+N”); unknown clients get a placeholder identity until their peer_joined.
No per-node memory (pending table = in-flight edits only, a few Maps); one message per frame at most; remote apply is O(changed ops) except the rebase cases above, which are O(pending ops); nothing runs inside the render loop (the engine drains doc changes on its next frame).
test/sim.test.ts, fixed seed in CI, LINORA_SYNC_SIM_SEEDS for sweeps): 5 networked sessions over a simulated realtime tier using the real ScanBatch + StructIndex, ADR 0202 ordering/dedupe/busy floors, random latency, disconnects, journal trims (snapshot_stale reloads), busy retries, 20K ops (creates, edits, reparents incl. cycles, deletes, undo/redo, gestures). Every replica equals a journal replay byte for byte. Status (wave 3, with TRANSFORM / SET_GEOMETRY in the op mix): seeds 1-1000 all byte-identical, 0 extra rejections, 0 mismatches (20 stale dedupe verdicts in 9 seeds, 373 retired batches; ADR 0410). Before the fix 11/1,000 seeds failed, one with a real divergence.test/conflicts.test.ts); reconnect resends dedupe, own-batch tail settlement, snapshot_stale recovery, presence <= 20 Hz, 64-in-flight backpressure, busy retry order, close codes and the MCP RoomChannel (test/connection.test.ts).createLocalSession, LocalHub and the networked session pass the same DocSession contract tests (test/session.test.ts).node packages/sync-client/test/live.e2e.ts (two writers, conflict + undo, presence, late joiner byte-identical).