Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix: retry document updates and recover Yjs sync after reconnect (#265)

LILAC6b2930cbd6f4
diff --git a/src/lib/yjsClient.ts b/src/lib/yjsClient.ts
index e7b382f..443583e 100644
--- a/src/lib/yjsClient.ts
+++ b/src/lib/yjsClient.ts
@@ -1,183 +1,9 @@
-/**
- * Browser-side Y.Doc session for a single collaborative document.
- *
- * One YDocSession per opened document. It owns a Y.Doc + Awareness
- * instance and bridges them to the existing WsClient: outbound updates
- * are emitted as `doc.update` envelopes, inbound `doc.update` /
- * `doc.sync` / `doc.awareness` frames are applied locally.
- *
- * We deliberately don't use y-websocket — the existing Cumora WS path
- * already handles auth + reconnect + tenant scoping, so an extra socket
- * would just duplicate state. Yjs binary updates are b64-wrapped so
- * they fit the JSON envelope the rest of the app speaks.
- */
-import * as Y from 'yjs'
-import { Awareness, applyAwarenessUpdate, encodeAwarenessUpdate, removeAwarenessStates } from 'y-protocols/awareness'
-import { ws, type WsEvent } from '@/api/client'
-import { applyServerSyncAndGetLocalReplay, replayFitsDocFrame } from './yjsSync'
+import { ws } from '@/api/client'
+import { createDocumentSession, type OpenDocumentOptions } from './yjsSession'
-function bytesToB64(bytes: Uint8Array): string {
- let binary = ''
- const chunk = 0x8000
- for (let i = 0; i < bytes.length; i += chunk) {
- binary += String.fromCharCode(...bytes.subarray(i, i + chunk))
- }
- return btoa(binary)
-}
-
-function b64ToBytes(b64: string): Uint8Array {
- const binary = atob(b64)
- const out = new Uint8Array(binary.length)
- for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i)
- return out
-}
-
-export interface YDocSession {
- doc: Y.Doc
- awareness: Awareness
- /** True after the server has sent its initial state. The UI can wait
- * on this to avoid showing an empty editor for a brief moment before
- * the doc loads. */
- synced: Promise<void>
- /** Tear down listeners + flush an awareness-clear so other clients
- * drop the local cursor immediately. */
- destroy: () => void
-}
-
-export interface OpenDocumentOptions {
- documentId: string
- /** Free-form identity stamped on awareness so peers can render
- * "<name> is editing". Typically the user's display name. */
- user: { id: string; name: string; color: string }
- /** Called when local state cannot fit in one authorized replay frame, and
- * again with null after a later sync recovers. */
- onSyncState?: (error: Error | null) => void
-}
-
-export function openDocument(opts: OpenDocumentOptions): YDocSession {
- const { documentId, user } = opts
- const doc = new Y.Doc()
- // The default top-level Y.Text used by the editor binding. Same key
- // the server-side agent tools use so an agent edit shows up here.
- doc.getText('content')
-
- const awareness = new Awareness(doc)
- awareness.setLocalState({ user: { id: user.id, name: user.name, color: user.color } })
-
- let resolveSynced: () => void = () => { /* assigned below */ }
- const synced = new Promise<void>((r) => { resolveSynced = r })
-
- // Outbound: any local update goes upstream. Origin `remote` means the
- // update came in via the WS path — skip echoing it back.
- const handleUpdate = (update: Uint8Array, origin: unknown) => {
- if (origin === 'remote') return
- ws.send({
- type: 'doc.update',
- documentId,
- updateB64: bytesToB64(update),
- })
- }
- doc.on('update', handleUpdate)
-
- const handleAwarenessChange = (
- changes: { added: number[]; updated: number[]; removed: number[] },
- origin: unknown,
- ) => {
- if (origin === 'remote') return
- const clients = [...changes.added, ...changes.updated, ...changes.removed]
- if (!clients.length) return
- const update = encodeAwarenessUpdate(awareness, clients)
- ws.send({
- type: 'doc.awareness',
- documentId,
- updateB64: bytesToB64(update),
- })
- }
- awareness.on('update', handleAwarenessChange)
-
- const subscribe = () => {
- // The server replies with `doc.sync` carrying the encoded state.
- if (ws.isOpen()) {
- ws.send({ type: 'doc.subscribe', documentId, replaySupported: true })
- }
- }
-
- const onWsEvent = (e: WsEvent) => {
- if (e.type === 'hello') {
- // Reconnected — re-subscribe and re-broadcast our awareness so
- // peers refresh our cursor on the new socket.
- subscribe()
- const clientId = doc.clientID
- const update = encodeAwarenessUpdate(awareness, [clientId])
- ws.send({
- type: 'doc.awareness',
- documentId,
- updateB64: bytesToB64(update),
- })
- return
- }
- if (e.type === 'doc.sync' && e.documentId === documentId) {
- const replay = applyServerSyncAndGetLocalReplay(doc, b64ToBytes(e.stateB64))
- if (!replayFitsDocFrame(replay, documentId)) {
- opts.onSyncState?.(new Error('document replay exceeds the sync frame limit'))
- return
- }
- if (replay.byteLength > 0) {
- ws.send({
- type: 'doc.update',
- documentId,
- updateB64: bytesToB64(replay),
- })
- }
- opts.onSyncState?.(null)
- resolveSynced()
- return
- }
- if (e.type === 'doc.update' && e.documentId === documentId) {
- Y.applyUpdate(doc, b64ToBytes(e.updateB64), 'remote')
- return
- }
- if (e.type === 'doc.awareness' && e.documentId === documentId) {
- applyAwarenessUpdate(awareness, b64ToBytes(e.updateB64), 'remote')
- return
- }
- }
-
- const off = ws.on(onWsEvent)
- // Kick off the connection if it isn't already open, then send subscribe.
- void ws.connect().then(() => subscribe())
-
- return {
- doc,
- awareness,
- synced,
- destroy() {
- off()
- doc.off('update', handleUpdate)
- awareness.off('update', handleAwarenessChange)
- // Clear local awareness so peers see us leave.
- removeAwarenessStates(awareness, [doc.clientID], 'local')
- if (ws.isOpen()) {
- ws.send({ type: 'doc.unsubscribe', documentId })
- }
- doc.destroy()
- },
- }
-}
-
-/** Awareness peer state as broadcast by openDocument. */
-export interface AwarenessPeer {
- clientId: number
- user: { id: string; name: string; color: string }
-}
+export { readPeers } from './yjsSession'
+export type { AwarenessPeer, OpenDocumentOptions, YDocSession } from './yjsSession'
-export function readPeers(awareness: Awareness, selfClientId: number): AwarenessPeer[] {
- const peers: AwarenessPeer[] = []
- awareness.getStates().forEach((state, clientId) => {
- if (clientId === selfClientId) return
- const u = (state as { user?: { id: string; name: string; color: string } }).user
- if (!u) return
- peers.push({ clientId, user: u })
- })
- return peers
+export function openDocument(opts: OpenDocumentOptions) {
+ return createDocumentSession(opts, ws)
}
diff --git a/src/lib/yjsSession.ts b/src/lib/yjsSession.ts
new file mode 100644
index 0000000..ecf5c06
--- /dev/null
+++ b/src/lib/yjsSession.ts
@@ -0,0 +1,216 @@
+/**
+ * Browser-side Y.Doc session for a single collaborative document.
+ *
+ * One YDocSession per opened document. It owns a Y.Doc + Awareness
+ * instance and bridges them to the existing WsClient: outbound updates
+ * are emitted as `doc.update` envelopes, inbound `doc.update` /
+ * `doc.sync` / `doc.awareness` frames are applied locally.
+ *
+ * We deliberately don't use y-websocket — the existing Cumora WS path
+ * already handles auth + reconnect + tenant scoping, so an extra socket
+ * would just duplicate state. Yjs binary updates are b64-wrapped so
+ * they fit the JSON envelope the rest of the app speaks.
+ */
+import * as Y from 'yjs'
+import { Awareness, applyAwarenessUpdate, encodeAwarenessUpdate, removeAwarenessStates } from 'y-protocols/awareness'
+import type { WsEvent } from '@/api/client'
+import { applyServerSyncAndGetLocalReplay, replayFitsDocFrame } from './yjsSync'
+
+function bytesToB64(bytes: Uint8Array): string {
+ let binary = ''
+ const chunk = 0x8000
+ for (let i = 0; i < bytes.length; i += chunk) {
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk))
+ }
+ return btoa(binary)
+}
+
+function b64ToBytes(b64: string): Uint8Array {
+ const binary = atob(b64)
+ const out = new Uint8Array(binary.length)
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i)
+ return out
+}
+
+export interface YDocSession {
+ doc: Y.Doc
+ awareness: Awareness
+ /** True after the server has sent its initial state. The UI can wait
+ * on this to avoid showing an empty editor for a brief moment before
+ * the doc loads. */
+ synced: Promise<void>
+ /** Tear down listeners + flush an awareness-clear so other clients
+ * drop the local cursor immediately. */
+ destroy: () => void
+}
+
+export interface OpenDocumentOptions {
+ documentId: string
+ /** Free-form identity stamped on awareness so peers can render
+ * "<name> is editing". Typically the user's display name. */
+ user: { id: string; name: string; color: string }
+ /** Called when pending local state exceeds the frame limit, and with null
+ * after local state has been handed to the socket (not a persistence ACK). */
+ onSyncState?: (error: Error | null) => void
+}
+
+export interface DocumentTransport {
+ send(payload: unknown): boolean
+ isOpen(): boolean
+ connect(): Promise<void>
+ on(listener: (event: WsEvent) => void): () => void
+}
+
+export function createDocumentSession(opts: OpenDocumentOptions, ws: DocumentTransport): YDocSession {
+ const { documentId, user } = opts
+ const doc = new Y.Doc()
+ // The default top-level Y.Text used by the editor binding. Same key
+ // the server-side agent tools use so an agent edit shows up here.
+ doc.getText('content')
+
+ const awareness = new Awareness(doc)
+ awareness.setLocalState({ user: { id: user.id, name: user.name, color: user.color } })
+
+ let resolveSynced: () => void = () => { /* assigned below */ }
+ const synced = new Promise<void>((r) => { resolveSynced = r })
+
+ let destroyed = false
+ let receivedSnapshot = false
+ let pendingUpdate: Uint8Array | null = null
+ let retryTimer: ReturnType<typeof setTimeout> | undefined
+
+ const retry = () => {
+ if (destroyed || retryTimer !== undefined) return
+ retryTimer = setTimeout(() => {
+ retryTimer = undefined
+ if (!ws.isOpen()) return // hello will replay the Y.Doc after reconnect.
+ if (receivedSnapshot) flushPending()
+ else subscribe()
+ }, 500)
+ }
+
+ const flushPending = () => {
+ if (destroyed || !receivedSnapshot || !pendingUpdate) return
+ if (!replayFitsDocFrame(pendingUpdate, documentId)) {
+ opts.onSyncState?.(new Error('document replay exceeds the sync frame limit'))
+ return
+ }
+ if (!ws.send({ type: 'doc.update', documentId, updateB64: bytesToB64(pendingUpdate) })) {
+ retry()
+ return
+ }
+ pendingUpdate = null
+ opts.onSyncState?.(null)
+ resolveSynced()
+ }
+
+ // Outbound: any local update goes upstream. Origin `remote` means the
+ // update came in via the WS path — skip echoing it back.
+ const handleUpdate = (update: Uint8Array, origin: unknown) => {
+ if (origin === 'remote') return
+ // While subscribing, the Y.Doc retains edits for the snapshot diff.
+ if (!receivedSnapshot) return
+ pendingUpdate = pendingUpdate ? Y.mergeUpdates([pendingUpdate, update]) : update
+ flushPending()
+ }
+ doc.on('update', handleUpdate)
+
+ const handleAwarenessChange = (
+ changes: { added: number[]; updated: number[]; removed: number[] },
+ origin: unknown,
+ ) => {
+ if (origin === 'remote') return
+ const clients = [...changes.added, ...changes.updated, ...changes.removed]
+ if (!clients.length) return
+ const update = encodeAwarenessUpdate(awareness, clients)
+ ws.send({
+ type: 'doc.awareness',
+ documentId,
+ updateB64: bytesToB64(update),
+ })
+ }
+ awareness.on('update', handleAwarenessChange)
+
+ const subscribe = () => {
+ if (destroyed) return
+ // The server replies with `doc.sync` carrying the encoded state.
+ if (ws.isOpen()) {
+ if (!ws.send({ type: 'doc.subscribe', documentId, replaySupported: true })) retry()
+ }
+ }
+
+ const onWsEvent = (e: WsEvent) => {
+ if (e.type === 'hello') {
+ receivedSnapshot = false
+ // Reconnected — re-subscribe and re-broadcast our awareness so
+ // peers refresh our cursor on the new socket.
+ subscribe()
+ const clientId = doc.clientID
+ const update = encodeAwarenessUpdate(awareness, [clientId])
+ ws.send({
+ type: 'doc.awareness',
+ documentId,
+ updateB64: bytesToB64(update),
+ })
+ return
+ }
+ if (e.type === 'doc.sync' && e.documentId === documentId) {
+ const replay = applyServerSyncAndGetLocalReplay(doc, b64ToBytes(e.stateB64))
+ receivedSnapshot = true
+ // Include even edits accepted by the old socket but lost in transit.
+ pendingUpdate = replay
+ flushPending()
+ return
+ }
+ if (e.type === 'doc.update' && e.documentId === documentId) {
+ Y.applyUpdate(doc, b64ToBytes(e.updateB64), 'remote')
+ return
+ }
+ if (e.type === 'doc.awareness' && e.documentId === documentId) {
+ applyAwarenessUpdate(awareness, b64ToBytes(e.updateB64), 'remote')
+ return
+ }
+ }
+
+ const off = ws.on(onWsEvent)
+ // Kick off the connection if it isn't already open, then send subscribe.
+ void ws.connect().then(() => subscribe())
+
+ return {
+ doc,
+ awareness,
+ synced,
+ destroy() {
+ if (destroyed) return
+ destroyed = true
+ if (retryTimer !== undefined) clearTimeout(retryTimer)
+ off()
+ doc.off('update', handleUpdate)
+ awareness.off('update', handleAwarenessChange)
+ // Clear local awareness so peers see us leave.
+ removeAwarenessStates(awareness, [doc.clientID], 'local')
+ if (ws.isOpen()) {
+ ws.send({ type: 'doc.unsubscribe', documentId })
+ }
+ awareness.destroy()
+ doc.destroy()
+ },
+ }
+}
+
+/** Awareness peer state as broadcast by openDocument. */
+export interface AwarenessPeer {
+ clientId: number
+ user: { id: string; name: string; color: string }
+}
+
+export function readPeers(awareness: Awareness, selfClientId: number): AwarenessPeer[] {
+ const peers: AwarenessPeer[] = []
+ awareness.getStates().forEach((state, clientId) => {
+ if (clientId === selfClientId) return
+ const u = (state as { user?: { id: string; name: string; color: string } }).user
+ if (!u) return
+ peers.push({ clientId, user: u })
+ })
+ return peers
+}
diff --git a/tests/yjs-session.test.ts b/tests/yjs-session.test.ts
new file mode 100644
index 0000000..bf5075a
--- /dev/null
+++ b/tests/yjs-session.test.ts
@@ -0,0 +1,167 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import * as Y from 'yjs'
+import type { WsEvent } from '../src/api/client'
+import { createDocumentSession, type DocumentTransport } from '../src/lib/yjsSession'
+
+const documentId = 'test-document'
+const options = { documentId, user: { id: 'user', name: 'User', color: '#123456' } }
+
+class Transport implements DocumentTransport {
+ server = new Y.Doc()
+ open = true
+ subscribed = false
+ failUpdates = false
+ dropUpdates = false
+ failSubscribe = false
+ sent: Array<{ type: string; updateB64?: string }> = []
+ listeners = new Set<(event: WsEvent) => void>()
+
+ async connect() {}
+ isOpen() { return this.open }
+ on(listener: (event: WsEvent) => void) {
+ this.listeners.add(listener)
+ return () => { this.listeners.delete(listener) }
+ }
+ send(payload: unknown) {
+ const frame = payload as { type: string; updateB64?: string }
+ this.sent.push(frame)
+ if (!this.open) return false
+ if (frame.type === 'doc.subscribe') {
+ if (this.failSubscribe) return false
+ this.subscribed = true
+ }
+ if (frame.type === 'doc.unsubscribe') this.subscribed = false
+ if (frame.type === 'doc.update') {
+ if (this.failUpdates) return false
+ if (this.subscribed && !this.dropUpdates) {
+ Y.applyUpdate(this.server, Buffer.from(frame.updateB64!, 'base64'))
+ }
+ }
+ return true
+ }
+ emit(event: WsEvent) { this.listeners.forEach((listener) => { listener(event) }) }
+ disconnect() { this.open = false; this.subscribed = false }
+ hello() {
+ this.open = true
+ this.emit({ type: 'hello' } as WsEvent)
+ }
+ snapshot() {
+ assert.ok(this.subscribed)
+ this.emit({ type: 'doc.sync', documentId, originId: 'server',
+ stateB64: Buffer.from(Y.encodeStateAsUpdate(this.server)).toString('base64') })
+ }
+}
+
+for (const dropUpdates of [false, true]) {
+ test(`offline edit, reconnect, continue, reopen (silent loss: ${dropUpdates})`, async (t) => {
+ const transport = new Transport()
+ transport.server.getText('content').insert(0, 'A')
+ const session = createDocumentSession(options, transport)
+ t.after(() => { session.destroy(); transport.server.destroy() })
+ await Promise.resolve()
+ transport.snapshot()
+ await session.synced
+
+ if (dropUpdates) transport.dropUpdates = true
+ else transport.disconnect()
+ session.doc.getText('content').insert(1, 'B')
+ assert.equal(transport.server.getText('content').toString(), 'A')
+
+ transport.disconnect()
+ transport.dropUpdates = false
+ transport.hello()
+ transport.snapshot()
+ session.doc.getText('content').insert(2, 'C')
+ assert.equal(session.doc.getText('content').toString(), 'ABC')
+ assert.equal(transport.server.getText('content').toString(), 'ABC')
+
+ session.destroy()
+ const reopened = createDocumentSession(options, transport)
+ t.after(() => reopened.destroy())
+ await Promise.resolve()
+ transport.snapshot()
+ await reopened.synced
+ assert.equal(reopened.doc.getText('content').toString(), 'ABC')
+ })
+}
+
+test('failed replay retries without another edit or reconnect and does not signal success early', async (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] })
+ const transport = new Transport()
+ const states: Array<Error | null> = []
+ const session = createDocumentSession({ ...options, onSyncState: (error) => states.push(error) }, transport)
+ t.after(() => { session.destroy(); transport.server.destroy() })
+ await Promise.resolve()
+ session.doc.getText('content').insert(0, 'A')
+ transport.failUpdates = true
+ transport.snapshot()
+ let synced = false
+ void session.synced.then(() => { synced = true })
+ await Promise.resolve()
+ assert.equal(synced, false)
+ assert.deepEqual(states, [])
+ transport.failUpdates = false
+ t.mock.timers.tick(500)
+ await session.synced
+ assert.deepEqual(states, [null])
+ assert.equal(transport.server.getText('content').toString(), 'A')
+})
+
+test('failed live updates retain Yjs dependencies when later edits are sent', async (t) => {
+ const transport = new Transport()
+ const session = createDocumentSession(options, transport)
+ t.after(() => { session.destroy(); transport.server.destroy() })
+ await Promise.resolve()
+ transport.snapshot()
+ transport.failUpdates = true
+ session.doc.getText('content').insert(0, 'B')
+ transport.failUpdates = false
+ session.doc.getText('content').insert(1, 'C')
+ assert.equal(transport.server.getText('content').toString(), 'BC')
+})
+
+test('reconnect merges offline deletion, remote edits, and edits while awaiting snapshot', async (t) => {
+ const transport = new Transport()
+ transport.server.getText('content').insert(0, 'AB')
+ const session = createDocumentSession(options, transport)
+ t.after(() => { session.destroy(); transport.server.destroy() })
+ await Promise.resolve()
+ transport.snapshot()
+ transport.disconnect()
+ session.doc.getText('content').delete(1, 1)
+ transport.server.getText('content').insert(2, 'R')
+ transport.hello()
+ const before = transport.sent.length
+ session.doc.getText('content').insert(1, 'C')
+ assert.equal(transport.sent.length, before)
+ transport.snapshot()
+ const result = session.doc.getText('content').toString()
+ assert.ok(result.includes('A') && result.includes('C') && result.includes('R'))
+ assert.ok(!result.includes('B'))
+ assert.equal(transport.server.getText('content').toString(), result)
+})
+
+test('failed subscription retries; destroying a session cancels retry and deferred connect', async (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] })
+ const transport = new Transport()
+ transport.failSubscribe = true
+ const session = createDocumentSession(options, transport)
+ t.after(() => transport.server.destroy())
+ await Promise.resolve()
+ assert.equal(transport.subscribed, false)
+ transport.failSubscribe = false
+ t.mock.timers.tick(500)
+ assert.equal(transport.subscribed, true)
+ transport.failUpdates = true
+ transport.snapshot()
+ session.destroy()
+ const count = transport.sent.length
+ t.mock.timers.tick(1000)
+ assert.equal(transport.sent.length, count)
+ const immediatelyClosed = createDocumentSession(options, transport)
+ immediatelyClosed.destroy()
+ const closedCount = transport.sent.length
+ await Promise.resolve()
+ assert.equal(transport.sent.length, closedCount)
+})