@ai-matrx/office 0.5.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/univer/collab/index.ts","../src/univer/collab/WorkbookCollabSession.ts"],"sourcesContent":["/**\n * The collab session shared by `/sheets` and `/docs` (was matrx-frontend `features/workbooks/collab`): the\n * Univer <-> Yjs bridge. It owns the Yjs import, so it is loaded on demand (`import()` when a workbook\n * or document goes live). The snapshot-insert subscription hook is its own entry,\n * `@ai-matrx/office/univer/realtime`, so a static import of the hook never carries Yjs into the editor\n * chunk. A transitional subpath, like `./univer`: it goes internal when the editors move.\n */\nexport * from \"./WorkbookCollabSession\";\n","/**\n * WorkbookCollabSession — the Univer ↔ Yjs bridge.\n *\n * Subscribes to Univer's public `commandService.onMutationExecutedForCollab`\n * hook for local mutations and pushes them onto a `Y.Array<MutationOp>` shared\n * via `SupabaseYjsProvider`. Inbound Yjs updates produce `IMutationInfo` ops\n * that are applied through `commandService.syncExecuteCommand` with the\n * `fromCollab` execution option flagged so the outbound listener short-\n * circuits and we don't echo our own apply.\n *\n * See `FEATURE.md` in this directory for the architecture, the \"do NOT use\n * the Pro preset\" verdict, and the host-election rule. This class is the\n * runtime side of that plan.\n *\n * Lifecycle:\n * - constructor: wire references, no side effects\n * - start(): create Y.Doc + Awareness, instantiate provider, subscribe to\n * command stream, subscribe to Yjs Array observer\n * - stop(): detach all listeners, dispose provider\n *\n * The session is one-shot per workbook open. Reload = stop() + new instance.\n */\n\"use client\";\n\nimport * as Y from \"yjs\";\nimport { Awareness } from \"y-protocols/awareness\";\n\nimport { electCollabHost, remoteOriginOf, REMOTE_PARAM_TAG } from \"@ai-matrx/data/realtime/collab\";\n\n/**\n * Structural transport contract. `SupabaseYjsProvider` satisfies it in\n * production; the verification harness injects an in-memory loopback\n * transport through the same seam. Keeping this structural (not the concrete\n * class) is what makes the session testable without network.\n */\nexport type CollabProviderLike = {\n connect(): Promise<void>;\n disconnect(): void;\n ready(): Promise<void>;\n /**\n * True when this is the only holder of its room in this tab allowed to act as\n * host (autosave). Same-tab holders share one client id and one uid, so\n * awareness cannot tell them apart. Absent = a lone holder = leader.\n */\n isTabLeader?(): boolean;\n};\n\n// Univer types are loose at the public hook boundary; we narrow with a\n// structural interface so we don't have to import the full Univer surface.\ntype MutationParams = Record<string, unknown> | unknown[] | null;\n\nexport type CollabMutationInfo = {\n id: string;\n type: number; // CommandType.MUTATION = 2 in Univer's enum\n params: MutationParams;\n /** Who made it (the person's uid), so a peer can tell its own other tab's edit from a stranger's. */\n uid?: string;\n};\n\ntype ExecuteOptions = {\n /** Per-Univer convention: when true, the command runs locally only and is\n * NOT broadcast to other plugins. We set this on inbound-apply so the\n * subsequent onMutationExecutedForCollab does NOT re-fire on our peer. */\n onlyLocal?: boolean;\n fromCollab?: boolean;\n};\n\nexport type CommandServiceLike = {\n onMutationExecutedForCollab(\n listener: (info: CollabMutationInfo, options?: ExecuteOptions) => void,\n ): {\n dispose: () => void;\n };\n syncExecuteCommand(\n id: string,\n params: MutationParams,\n options?: ExecuteOptions,\n ): unknown;\n};\n\nexport type WorkbookCollabSessionOptions = {\n workbookId: string;\n uid: string;\n clientId: string;\n commandService: CommandServiceLike;\n /** Factory so this file does not statically depend on the provider. */\n makeProvider: (args: {\n workbookId: string;\n clientId: string;\n doc: Y.Doc;\n awareness: Awareness;\n /** Wire to the provider so a host handover re-runs the election. */\n onLeaderChange: () => void;\n }) => CollabProviderLike;\n /** Called when the awareness set changes (peers join / leave / move cursor). */\n onAwarenessChange?: (awareness: Awareness) => void;\n /**\n * A peer replaced the whole content (history restore, Google update): the\n * newest saved snapshot is the content now. Reload it in place; never\n * re-announce. See `announceReplaced`.\n */\n onReplaced?: (snapshotId: string) => void;\n /**\n * TRUE when the room is bound to a Univer DOCUMENT unit (the Docs editor): there the `doc.mutation.*`\n * stream IS the content, so it must travel. Leave unset for a workbook, where `doc.mutation.*` is the\n * in-cell editor's scratch document and never travels (see `isCellEditorScratch`).\n */\n forwardDocumentMutations?: boolean;\n /**\n * The Univer unit id this seat mounted. Each seat can mount its own unit, so a peer's mutation\n * (addressed to the SENDER's unit) is re-addressed to this one before it is applied.\n */\n unitId?: () => string | null;\n /** A peer's mutation could not be applied here: the seat says so and re-syncs; never only a console line. */\n onApplyFailed?: (mutationId: string, error: unknown) => void;\n};\n\n/** What `announceReplaced` writes into the room's control map. */\ntype ReplacedSignal = { snapshotId: string; by: string; nonce: string };\n\nconst MUTATIONS_ARRAY_KEY = \"mutations\";\nconst CONTROL_MAP_KEY = \"control\";\nconst REPLACED_KEY = \"replaced\";\n\nexport class WorkbookCollabSession {\n private readonly options: WorkbookCollabSessionOptions;\n private doc: Y.Doc | null = null;\n private awareness: Awareness | null = null;\n private provider: CollabProviderLike | null = null;\n private commandDisposer: { dispose: () => void } | null = null;\n private yArrayObserver:\n ((event: Y.YArrayEvent<CollabMutationInfo>) => void) | null = null;\n private awarenessObserver: (() => void) | null = null;\n private controlObserver: ((event: Y.YMapEvent<unknown>) => void) | null = null;\n /** >0 while this client swaps its own content: its mutations are not edits. */\n private muted = 0;\n private started = false;\n private disposed = false;\n\n constructor(options: WorkbookCollabSessionOptions) {\n this.options = options;\n }\n\n async start(): Promise<void> {\n if (this.started || this.disposed) return;\n this.started = true;\n\n this.doc = new Y.Doc();\n this.awareness = new Awareness(this.doc);\n\n // Seed local awareness with the user identity. Cursor (sheetId/row/col)\n // is set later via setCursor().\n this.awareness.setLocalState({\n uid: this.options.uid,\n clientId: this.options.clientId,\n name: this.options.uid.slice(0, 8),\n color: pickColor(this.options.uid),\n sheetId: null,\n row: null,\n col: null,\n ts: Date.now(),\n });\n\n this.provider = this.options.makeProvider({\n workbookId: this.options.workbookId,\n clientId: this.options.clientId,\n doc: this.doc,\n awareness: this.awareness,\n onLeaderChange: () => {\n if (this.awareness) this.options.onAwarenessChange?.(this.awareness);\n },\n });\n\n // Subscribe to inbound Yjs array changes BEFORE connecting the provider,\n // so the initial-state replay (if any) hits our observer.\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n this.yArrayObserver = (event) => {\n // Local transactions are OUR OWN pushes from handleLocalMutation —\n // Univer already executed those mutations. Re-applying them here would\n // double-apply every local edit on the originator. Only act on\n // transactions that arrived via Y.applyUpdate (origin 'remote').\n if (event.transaction.local) return;\n for (const change of event.changes.delta) {\n if (!change.insert || !Array.isArray(change.insert)) continue;\n for (const op of change.insert as CollabMutationInfo[]) {\n this.applyRemoteMutation(op);\n }\n }\n };\n yArray.observe(this.yArrayObserver as Parameters<typeof yArray.observe>[0]);\n\n // Awareness change passthrough.\n if (this.options.onAwarenessChange) {\n const cb = this.options.onAwarenessChange;\n this.awarenessObserver = () => {\n if (this.awareness) cb(this.awareness);\n };\n this.awareness.on(\"change\", this.awarenessObserver);\n }\n\n // Subscribe to Univer's collab-grain mutation stream.\n this.commandDisposer =\n this.options.commandService.onMutationExecutedForCollab((info) =>\n this.handleLocalMutation(info),\n );\n\n await this.provider.connect();\n await this.provider.ready();\n\n // Whole-content replacement from a peer. Bound AFTER the initial sync: a\n // joiner already loaded the newest snapshot, so the signal it finds in\n // the room's state is history, not news (the editor also skips a\n // snapshot it already shows).\n if (this.disposed || !this.doc) return;\n const control = this.doc.getMap<unknown>(CONTROL_MAP_KEY);\n const seen = (control.get(REPLACED_KEY) as ReplacedSignal | undefined)?.nonce ?? null;\n this.controlObserver = (event) => {\n if (event.transaction.local || !event.keysChanged.has(REPLACED_KEY)) return;\n const signal = control.get(REPLACED_KEY) as ReplacedSignal | undefined;\n if (!signal?.snapshotId || signal.nonce === seen) return;\n this.options.onReplaced?.(signal.snapshotId);\n };\n control.observe(this.controlObserver);\n }\n\n stop(): void {\n if (this.disposed) return;\n this.disposed = true;\n\n this.commandDisposer?.dispose();\n this.commandDisposer = null;\n\n if (this.doc && this.yArrayObserver) {\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n yArray.unobserve(\n this.yArrayObserver as Parameters<typeof yArray.unobserve>[0],\n );\n this.yArrayObserver = null;\n }\n\n if (this.doc && this.controlObserver) {\n this.doc.getMap<unknown>(CONTROL_MAP_KEY).unobserve(this.controlObserver);\n this.controlObserver = null;\n }\n\n if (this.awareness && this.awarenessObserver) {\n this.awareness.off(\"change\", this.awarenessObserver);\n this.awarenessObserver = null;\n }\n\n this.provider?.disconnect();\n this.provider = null;\n\n if (this.awareness) {\n this.awareness.destroy();\n this.awareness = null;\n }\n\n if (this.doc) {\n this.doc.destroy();\n this.doc = null;\n }\n }\n\n /**\n * How many mutations the shared log holds right now. Read it BEFORE\n * `workbook.save()`: that many entries are guaranteed to be inside the\n * snapshot that save produces.\n */\n logLength(): number {\n return this.doc?.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY).length ?? 0;\n }\n\n /**\n * Drop the first `upTo` mutations from the shared log once a snapshot that\n * contains them has been SAVED. Without this a joiner loads the saved\n * workbook (which already has every mutation baked in) and then catches up\n * the whole log on top of it, replaying edits into a workbook that already\n * holds them — Univer refuses with \"Trying to overwrite value at key\"\n * (feedback 88184e53). Only the host calls this; peers receive it as a\n * delete, which the inbound observer ignores (it acts on inserts only).\n */\n compactLog(upTo: number): void {\n if (!this.doc || upTo <= 0) return;\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n const n = Math.min(upTo, yArray.length);\n if (n > 0) this.doc.transact(() => yArray.delete(0, n));\n }\n\n /**\n * This client replaced the whole content and SAVED it as `snapshotId`.\n * One transaction empties the shared mutation log (every entry targets the\n * content that is gone — a joiner must never replay them onto the new\n * snapshot) and tells every peer to reload the newest snapshot.\n */\n announceReplaced(snapshotId: string): void {\n if (!this.doc) return;\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n const control = this.doc.getMap<unknown>(CONTROL_MAP_KEY);\n const signal: ReplacedSignal = {\n snapshotId,\n by: this.options.clientId,\n nonce: `${this.options.clientId}:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`,\n };\n this.doc.transact(() => {\n if (yArray.length > 0) yArray.delete(0, yArray.length);\n control.set(REPLACED_KEY, signal);\n });\n }\n\n /**\n * Run `swap` (this client tearing its content down and mounting the new\n * one) without broadcasting what Univer emits while it does: those are not\n * edits, and peers reload the same snapshot themselves.\n */\n muteWhile<T>(swap: () => T): T {\n this.muted += 1;\n try {\n return swap();\n } finally {\n this.muted -= 1;\n }\n }\n\n /**\n * Update the local awareness cursor. Call this from Univer's selection\n * listener (`worksheet.onSelectionChange(...)`). Throttle at the call site\n * (~50ms is plenty); the provider broadcasts on its own debounced cycle.\n */\n setCursor(input: {\n sheetId: string | null;\n row: number | null;\n col: number | null;\n }): void {\n if (!this.awareness) return;\n const current = this.awareness.getLocalState() ?? {};\n this.awareness.setLocalState({\n ...current,\n sheetId: input.sheetId,\n row: input.row,\n col: input.col,\n ts: Date.now(),\n });\n }\n\n /**\n * Returns the deterministic host: the connected peer with the lowest uid\n * (lexicographic). Host is the only client that writes canonical snapshots.\n * No election protocol; recompute whenever awareness changes.\n */\n electHost(opts: { tabTieBreak?: boolean } = {}): { isHost: boolean; hostUid: string | null } {\n if (!this.awareness) return { isHost: false, hostUid: null };\n const states = Array.from(this.awareness.getStates().values()) as Array<\n Record<string, unknown>\n >;\n // Lowest uid wins ACROSS tabs; inside this tab only the room's tab leader\n // may be host, because every same-tab holder carries the same uid.\n const leader = this.provider?.isTabLeader?.() ?? true;\n return electCollabHost(states, this.options.uid, this.options.clientId, leader, opts.tabTieBreak ?? false);\n }\n\n // ─── internals ────────────────────────────────────────────────────────\n\n private handleLocalMutation(info: CollabMutationInfo): void {\n if (this.muted > 0) return;\n if (!this.options.forwardDocumentMutations && isCellEditorScratch(info)) return;\n // Inbound-applied mutations re-fire this listener because Univer's\n // syncExecuteCommand legitimately processes them through the full\n // pipeline. Skip by sniffing the sentinel we stamped on apply.\n if (\n info.params &&\n typeof info.params === \"object\" &&\n !Array.isArray(info.params) &&\n remoteOriginOf(info.params) !== null\n ) {\n return;\n }\n if (!this.doc) return;\n\n // Normalize params through a JSON round-trip BEFORE pushing into Yjs.\n // Yjs (and the Broadcast transport) only carry JSON-encodable values;\n // Univer types its mutation params as \"serializable\" but JS objects can\n // smuggle Date / Map / class instances through that promise. The\n // round-trip makes the failure mode deterministic: a non-encodable\n // mutation is skipped with a warning instead of corrupting the shared\n // doc or desyncing peers mid-session. What we push here is byte-for-byte\n // what remote peers will apply, so local-apply == remote-apply.\n let safeParams: MutationParams;\n try {\n safeParams =\n info.params === undefined || info.params === null\n ? null\n : (JSON.parse(JSON.stringify(info.params)) as MutationParams);\n } catch (err) {\n console.warn(\n `[collab] skipping non-serializable mutation \"${info.id}\" — peers will not receive it`,\n err,\n );\n return;\n }\n\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n yArray.push([{ id: info.id, type: info.type, params: safeParams, uid: this.options.uid }]);\n }\n\n private applyRemoteMutation(op: CollabMutationInfo): void {\n // Wrap params with the sentinel so handleLocalMutation knows not to\n // echo the apply back into Yjs.\n const ownUnit = this.options.unitId?.() ?? null;\n const taggedParams: MutationParams =\n op.params && typeof op.params === \"object\" && !Array.isArray(op.params)\n ? {\n ...(op.params as Record<string, unknown>),\n ...(ownUnit && typeof (op.params as { unitId?: unknown }).unitId === \"string\" ? { unitId: ownUnit } : {}),\n [REMOTE_PARAM_TAG]: op.uid ?? true,\n }\n : op.params;\n\n try {\n this.options.commandService.syncExecuteCommand(op.id, taggedParams, {\n onlyLocal: true,\n fromCollab: true,\n });\n } catch (err) {\n // One unappliable op (already baked into the loaded snapshot, or a\n // stale target) must not throw into the realtime channel handler and\n // abort the rest of the catch-up. Said, never swallowed.\n console.warn(\n `[collab] could not apply remote mutation \"${op.id}\" — skipped`,\n err,\n );\n this.options.onApplyFailed?.(op.id, err);\n }\n }\n}\n\n// ─── helpers ────────────────────────────────────────────────────────────\n\n/**\n * A workbook holds no Univer DOCUMENT units of its own: the `doc.mutation.*` stream a sheet emits is\n * the in-cell editor's scratch document (typing into a cell). The finished text reaches the sheet as\n * `sheet.mutation.set-range-values`, which does travel. Sending the scratch edits made a joiner replay\n * them against an editor unit it does not have (\"Trying to overwrite value at key\").\n */\nexport function isCellEditorScratch(info: Pick<CollabMutationInfo, \"id\">): boolean {\n return typeof info.id === \"string\" && info.id.startsWith(\"doc.mutation.\");\n}\n\nconst CURSOR_PALETTE = [\n \"#3b82f6\", // blue\n \"#10b981\", // emerald\n \"#f59e0b\", // amber\n \"#ef4444\", // red\n \"#8b5cf6\", // violet\n \"#06b6d4\", // cyan\n \"#ec4899\", // pink\n \"#84cc16\", // lime\n];\n\nfunction pickColor(uid: string): string {\n // Deterministic FNV-1a-ish hash so the same user is always the same color\n // across sessions and across other users' screens.\n let h = 2166136261;\n for (let i = 0; i < uid.length; i++) {\n h ^= uid.charCodeAt(i);\n h = Math.imul(h, 16777619);\n }\n return CURSOR_PALETTE[Math.abs(h) % CURSOR_PALETTE.length] ?? \"#ec4899\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACwBA,QAAmB;AACnB,uBAA0B;AAE1B,oBAAkE;AA6FlE,IAAM,sBAAsB;AAC5B,IAAM,kBAAkB;AACxB,IAAM,eAAe;AAEd,IAAM,wBAAN,MAA4B;AAAA,EAChB;AAAA,EACT,MAAoB;AAAA,EACpB,YAA8B;AAAA,EAC9B,WAAsC;AAAA,EACtC,kBAAkD;AAAA,EAClD,iBACwD;AAAA,EACxD,oBAAyC;AAAA,EACzC,kBAAkE;AAAA;AAAA,EAElE,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,WAAW;AAAA,EAEnB,YAAY,SAAuC;AACjD,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,MAAM,QAAuB;AAC3B,QAAI,KAAK,WAAW,KAAK,SAAU;AACnC,SAAK,UAAU;AAEf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EQ,oBAAoB,IAA8B;AAGxD,UAAM,UAAU,KAAK,QAAQ,SAAS,KAAK;AAC3C,UAAM,eACJ,GAAG,UAAU,OAAO,GAAG,WAAW,YAAY,CAAC,MAAM,QAAQ,GAAG,MAAM,IAClE;AAAA,MACE,GAAI,GAAG;AAAA,MACP,GAAI,WAAW,OAAQ,GAAG,OAAgC,WAAW,WAAW,EAAE,QAAQ,QAAQ,IAAI,CAAC;AAAA,MACvG,CAAC,8BAAgB,GAAG,GAAG,OAAO;AAAA,IAChC,IACA,GAAG;AAET,QAAI;AACF,WAAK,QAAQ,eAAe,mBAAmB,GAAG,IAAI,cAAc;AAAA,QAClE,WAAW;AAAA,QACX,YAAY;AAAA,MACd,CAAC;AAAA,IACH,SAAS,KAAK;AAIZ,cAAQ;AAAA,QACN,6CAA6C,GAAG,EAAE;AAAA,QAClD;AAAA,MACF;AACA,WAAK,QAAQ,gBAAgB,GAAG,IAAI,GAAG;AAAA,IACzC;AAAA,EACF;AACF;AAUO,SAAS,oBAAoB,MAA+C;AACjF,SAAO,OAAO,KAAK,OAAO,YAAY,KAAK,GAAG,WAAW,eAAe;AAC1E;AAEA,IAAM,iBAAiB;AAAA,EACrB;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AACF;AAEA,SAAS,UAAU,KAAqB;AAGtC,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,SAAK,IAAI,WAAW,CAAC;AACrB,QAAI,KAAK,KAAK,GAAG,QAAQ;AAAA,EAC3B;AACA,SAAO,eAAe,KAAK,IAAI,CAAC,IAAI,eAAe,MAAM,KAAK;AAChE;","names":[]}
1
+ {"version":3,"sources":["../src/univer/collab/index.ts","../src/univer/collab/WorkbookCollabSession.ts","../src/univer/collab/covered.ts"],"sourcesContent":["/**\n * The collab session shared by `/sheets` and `/docs` (was matrx-frontend `features/workbooks/collab`): the\n * Univer <-> Yjs bridge. It owns the Yjs import, so it is loaded on demand (`import()` when a workbook\n * or document goes live). The snapshot-insert subscription hook is its own entry,\n * `@ai-matrx/office/univer/realtime`, so a static import of the hook never carries Yjs into the editor\n * chunk. A transitional subpath, like `./univer`: it goes internal when the editors move.\n */\nexport * from \"./WorkbookCollabSession\";\n","/**\n * WorkbookCollabSession — the Univer ↔ Yjs bridge.\n *\n * Subscribes to Univer's public `commandService.onMutationExecutedForCollab`\n * hook for local mutations and pushes them onto a `Y.Array<MutationOp>` shared\n * via `SupabaseYjsProvider`. Inbound Yjs updates produce `IMutationInfo` ops\n * that are applied through `commandService.syncExecuteCommand` with the\n * `fromCollab` execution option flagged so the outbound listener short-\n * circuits and we don't echo our own apply.\n *\n * See `FEATURE.md` in this directory for the architecture, the \"do NOT use\n * the Pro preset\" verdict, and the host-election rule. This class is the\n * runtime side of that plan.\n *\n * Lifecycle:\n * - constructor: wire references, no side effects\n * - start(): create Y.Doc + Awareness, instantiate provider, subscribe to\n * command stream, subscribe to Yjs Array observer\n * - stop(): detach all listeners, dispose provider\n *\n * The session is one-shot per workbook open. Reload = stop() + new instance.\n */\n\"use client\";\n\nimport * as Y from \"yjs\";\nimport { Awareness } from \"y-protocols/awareness\";\n\nimport { electCollabHost, remoteOriginOf, REMOTE_PARAM_TAG } from \"@ai-matrx/data/realtime/collab\";\n\nexport { COLLAB_COVERED_KEY, stampCovered, takeCovered } from \"./covered\";\n\n/**\n * Structural transport contract. `SupabaseYjsProvider` satisfies it in\n * production; the verification harness injects an in-memory loopback\n * transport through the same seam. Keeping this structural (not the concrete\n * class) is what makes the session testable without network.\n */\nexport type CollabProviderLike = {\n connect(): Promise<void>;\n disconnect(): void;\n ready(): Promise<void>;\n /**\n * True when this is the only holder of its room in this tab allowed to act as\n * host (autosave). Same-tab holders share one client id and one uid, so\n * awareness cannot tell them apart. Absent = a lone holder = leader.\n */\n isTabLeader?(): boolean;\n};\n\n// Univer types are loose at the public hook boundary; we narrow with a\n// structural interface so we don't have to import the full Univer surface.\ntype MutationParams = Record<string, unknown> | unknown[] | null;\n\nexport type CollabMutationInfo = {\n id: string;\n type: number; // CommandType.MUTATION = 2 in Univer's enum\n params: MutationParams;\n /** Who made it (the person's uid), so a peer can tell its own other tab's edit from a stranger's. */\n uid?: string;\n /**\n * The entry's identity in the room (`<clientId>:<seq>`). A saved snapshot names the entries it holds\n * (`stampCovered`), so a seat that boots from that snapshot never replays them a second time.\n */\n eid?: string;\n};\n\n/**\n * What a seat booted from: the saved snapshot's row id and the room entries that snapshot already holds.\n * The session never replays a covered entry, and a seat that booted from an OLDER snapshot than the\n * room's newest checkpoint first reloads (the entries that checkpoint trimmed are only in that snapshot).\n */\nexport type CollabBase = {\n snapshotId: () => string | null;\n covered: () => ReadonlySet<string>;\n /** Show the newest saved snapshot (and make it the base). */\n reload: () => Promise<void>;\n};\n\ntype ExecuteOptions = {\n /** Per-Univer convention: when true, the command runs locally only and is\n * NOT broadcast to other plugins. We set this on inbound-apply so the\n * subsequent onMutationExecutedForCollab does NOT re-fire on our peer. */\n onlyLocal?: boolean;\n fromCollab?: boolean;\n};\n\nexport type CommandServiceLike = {\n onMutationExecutedForCollab(\n listener: (info: CollabMutationInfo, options?: ExecuteOptions) => void,\n ): {\n dispose: () => void;\n };\n syncExecuteCommand(\n id: string,\n params: MutationParams,\n options?: ExecuteOptions,\n ): unknown;\n};\n\nexport type WorkbookCollabSessionOptions = {\n workbookId: string;\n uid: string;\n clientId: string;\n commandService: CommandServiceLike;\n /** Factory so this file does not statically depend on the provider. */\n makeProvider: (args: {\n workbookId: string;\n clientId: string;\n doc: Y.Doc;\n awareness: Awareness;\n /** Wire to the provider so a host handover re-runs the election. */\n onLeaderChange: () => void;\n }) => CollabProviderLike;\n /** Called when the awareness set changes (peers join / leave / move cursor). */\n onAwarenessChange?: (awareness: Awareness) => void;\n /**\n * A peer replaced the whole content (history restore, Google update): the\n * newest saved snapshot is the content now. Reload it in place; never\n * re-announce. See `announceReplaced`.\n */\n onReplaced?: (snapshotId: string) => void;\n /**\n * TRUE when the room is bound to a Univer DOCUMENT unit (the Docs editor): there the `doc.mutation.*`\n * stream IS the content, so it must travel. Leave unset for a workbook, where `doc.mutation.*` is the\n * in-cell editor's scratch document and never travels (see `isCellEditorScratch`).\n */\n forwardDocumentMutations?: boolean;\n /**\n * The Univer unit id this seat mounted. Each seat can mount its own unit, so a peer's mutation\n * (addressed to the SENDER's unit) is re-addressed to this one before it is applied.\n */\n unitId?: () => string | null;\n /** A peer's mutation could not be applied here: the seat says so and re-syncs; never only a console line. */\n onApplyFailed?: (mutationId: string, error: unknown) => void;\n /**\n * The saved snapshot this seat booted from. Without it a reloading seat replays every entry still in\n * the room's log on top of a snapshot that already holds them: the text shows twice, and the next save\n * stores it twice (2026-10-16).\n */\n base?: CollabBase;\n};\n\n/** What `checkpoint` writes into the room's control map: the newest saved snapshot whose entries left the log. */\ntype CheckpointSignal = { snapshotId: string; by: string };\n\n/** What `announceReplaced` writes into the room's control map. */\ntype ReplacedSignal = { snapshotId: string; by: string; nonce: string };\n\nconst MUTATIONS_ARRAY_KEY = \"mutations\";\nconst CONTROL_MAP_KEY = \"control\";\nconst REPLACED_KEY = \"replaced\";\nconst CHECKPOINT_KEY = \"checkpoint\";\n\nexport class WorkbookCollabSession {\n private readonly options: WorkbookCollabSessionOptions;\n private doc: Y.Doc | null = null;\n private awareness: Awareness | null = null;\n private provider: CollabProviderLike | null = null;\n private commandDisposer: { dispose: () => void } | null = null;\n private yArrayObserver:\n ((event: Y.YArrayEvent<CollabMutationInfo>) => void) | null = null;\n private awarenessObserver: (() => void) | null = null;\n private controlObserver: ((event: Y.YMapEvent<unknown>) => void) | null = null;\n /** >0 while this client swaps its own content: its mutations are not edits. */\n private muted = 0;\n private started = false;\n private disposed = false;\n /** Room entries this seat holds in its content: applied from a peer, or made here. */\n private readonly applied = new Set<string>();\n /** Entries without an id (a peer on an older build) are applied once, by identity. */\n private readonly appliedRefs = new WeakSet<object>();\n private seq = 0;\n /** False until this seat has seen the room's content once (the join-time check runs then). */\n private joined = false;\n /** The base is being reloaded: entries wait in the log until it is shown. */\n private reloadingBase = false;\n\n constructor(options: WorkbookCollabSessionOptions) {\n this.options = options;\n }\n\n async start(): Promise<void> {\n if (this.started || this.disposed) return;\n this.started = true;\n\n this.doc = new Y.Doc();\n this.awareness = new Awareness(this.doc);\n\n // Seed local awareness with the user identity. Cursor (sheetId/row/col)\n // is set later via setCursor().\n this.awareness.setLocalState({\n uid: this.options.uid,\n clientId: this.options.clientId,\n name: this.options.uid.slice(0, 8),\n color: pickColor(this.options.uid),\n sheetId: null,\n row: null,\n col: null,\n ts: Date.now(),\n });\n\n this.provider = this.options.makeProvider({\n workbookId: this.options.workbookId,\n clientId: this.options.clientId,\n doc: this.doc,\n awareness: this.awareness,\n onLeaderChange: () => {\n if (this.awareness) this.options.onAwarenessChange?.(this.awareness);\n },\n });\n\n // Subscribe to inbound Yjs array changes BEFORE connecting the provider,\n // so the initial-state replay (if any) hits our observer.\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n this.yArrayObserver = (event) => {\n // Local transactions are OUR OWN pushes from handleLocalMutation —\n // Univer already executed those mutations. Re-applying them here would\n // double-apply every local edit on the originator. Only act on\n // transactions that arrived via Y.applyUpdate (origin 'remote').\n if (event.transaction.local) return;\n if (!event.changes.delta.some((change) => Array.isArray(change.insert) && change.insert.length > 0)) return;\n this.drain();\n };\n yArray.observe(this.yArrayObserver as Parameters<typeof yArray.observe>[0]);\n\n // Awareness change passthrough.\n if (this.options.onAwarenessChange) {\n const cb = this.options.onAwarenessChange;\n this.awarenessObserver = () => {\n if (this.awareness) cb(this.awareness);\n };\n this.awareness.on(\"change\", this.awarenessObserver);\n }\n\n // Subscribe to Univer's collab-grain mutation stream.\n this.commandDisposer =\n this.options.commandService.onMutationExecutedForCollab((info, options) =>\n this.handleLocalMutation(info, options),\n );\n\n await this.provider.connect();\n await this.provider.ready();\n this.drain();\n\n // Whole-content replacement from a peer. Bound AFTER the initial sync: a\n // joiner already loaded the newest snapshot, so the signal it finds in\n // the room's state is history, not news (the editor also skips a\n // snapshot it already shows).\n if (this.disposed || !this.doc) return;\n const control = this.doc.getMap<unknown>(CONTROL_MAP_KEY);\n const seen = (control.get(REPLACED_KEY) as ReplacedSignal | undefined)?.nonce ?? null;\n this.controlObserver = (event) => {\n if (event.transaction.local || !event.keysChanged.has(REPLACED_KEY)) return;\n const signal = control.get(REPLACED_KEY) as ReplacedSignal | undefined;\n if (!signal?.snapshotId || signal.nonce === seen) return;\n this.options.onReplaced?.(signal.snapshotId);\n };\n control.observe(this.controlObserver);\n }\n\n stop(): void {\n if (this.disposed) return;\n this.disposed = true;\n\n this.commandDisposer?.dispose();\n this.commandDisposer = null;\n\n if (this.doc && this.yArrayObserver) {\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n yArray.unobserve(\n this.yArrayObserver as Parameters<typeof yArray.unobserve>[0],\n );\n this.yArrayObserver = null;\n }\n\n if (this.doc && this.controlObserver) {\n this.doc.getMap<unknown>(CONTROL_MAP_KEY).unobserve(this.controlObserver);\n this.controlObserver = null;\n }\n\n if (this.awareness && this.awarenessObserver) {\n this.awareness.off(\"change\", this.awarenessObserver);\n this.awarenessObserver = null;\n }\n\n this.provider?.disconnect();\n this.provider = null;\n\n if (this.awareness) {\n this.awareness.destroy();\n this.awareness = null;\n }\n\n if (this.doc) {\n this.doc.destroy();\n this.doc = null;\n }\n }\n\n /** How many mutations the shared log holds right now. */\n logLength(): number {\n return this.doc?.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY).length ?? 0;\n }\n\n /**\n * The room entries this seat's content holds RIGHT NOW. Read it in the same synchronous step as the\n * content you are about to save, and save it with that content (`stampCovered`); after the save lands,\n * pass it to `checkpoint`.\n */\n coveredNow(): string[] {\n if (!this.doc) return [];\n const covered = this.options.base?.covered();\n const out: string[] = [];\n for (const op of this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY).toArray()) {\n if (op.eid && (this.applied.has(op.eid) || covered?.has(op.eid))) out.push(op.eid);\n }\n return out;\n }\n\n /**\n * The snapshot `snapshotId` was SAVED holding `covered` (from `coveredNow`): those entries leave the\n * shared log, and the room records the snapshot as its newest checkpoint. Removal is by entry id, never\n * by position — an entry that arrived while the save was in flight is not in the snapshot and stays.\n * Only the elected saver calls this; peers receive it as a delete (never replayed).\n */\n checkpoint(snapshotId: string, covered: readonly string[]): void {\n if (!this.doc) return;\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n const control = this.doc.getMap<unknown>(CONTROL_MAP_KEY);\n const drop = new Set(covered);\n const signal: CheckpointSignal = { snapshotId, by: this.options.clientId };\n this.doc.transact(() => {\n const entries = yArray.toArray();\n for (let i = entries.length - 1; i >= 0; i -= 1) {\n const eid = entries[i]?.eid;\n if (eid && drop.has(eid)) yArray.delete(i, 1);\n }\n control.set(CHECKPOINT_KEY, signal);\n });\n }\n\n /**\n * This client replaced the whole content and SAVED it as `snapshotId`.\n * One transaction empties the shared mutation log (every entry targets the\n * content that is gone — a joiner must never replay them onto the new\n * snapshot) and tells every peer to reload the newest snapshot.\n */\n announceReplaced(snapshotId: string): void {\n if (!this.doc) return;\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n const control = this.doc.getMap<unknown>(CONTROL_MAP_KEY);\n const signal: ReplacedSignal = {\n snapshotId,\n by: this.options.clientId,\n nonce: `${this.options.clientId}:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`,\n };\n this.doc.transact(() => {\n if (yArray.length > 0) yArray.delete(0, yArray.length);\n control.set(REPLACED_KEY, signal);\n control.set(CHECKPOINT_KEY, { snapshotId, by: this.options.clientId } satisfies CheckpointSignal);\n });\n }\n\n /**\n * Run `swap` (this client tearing its content down and mounting the new\n * one) without broadcasting what Univer emits while it does: those are not\n * edits, and peers reload the same snapshot themselves.\n */\n muteWhile<T>(swap: () => T): T {\n this.muted += 1;\n try {\n return swap();\n } finally {\n this.muted -= 1;\n }\n }\n\n /**\n * Update the local awareness cursor. Call this from Univer's selection\n * listener (`worksheet.onSelectionChange(...)`). Throttle at the call site\n * (~50ms is plenty); the provider broadcasts on its own debounced cycle.\n */\n setCursor(input: {\n sheetId: string | null;\n row: number | null;\n col: number | null;\n }): void {\n if (!this.awareness) return;\n const current = this.awareness.getLocalState() ?? {};\n this.awareness.setLocalState({\n ...current,\n sheetId: input.sheetId,\n row: input.row,\n col: input.col,\n ts: Date.now(),\n });\n }\n\n /**\n * Returns the deterministic host: the connected peer with the lowest uid\n * (lexicographic). Host is the only client that writes canonical snapshots.\n * No election protocol; recompute whenever awareness changes.\n */\n electHost(opts: { tabTieBreak?: boolean } = {}): { isHost: boolean; hostUid: string | null } {\n if (!this.awareness) return { isHost: false, hostUid: null };\n const states = Array.from(this.awareness.getStates().values()) as Array<\n Record<string, unknown>\n >;\n // Lowest uid wins ACROSS tabs; inside this tab only the room's tab leader\n // may be host, because every same-tab holder carries the same uid.\n const leader = this.provider?.isTabLeader?.() ?? true;\n return electCollabHost(states, this.options.uid, this.options.clientId, leader, opts.tabTieBreak ?? false);\n }\n\n // ─── internals ────────────────────────────────────────────────────────\n\n private handleLocalMutation(info: CollabMutationInfo, options?: ExecuteOptions): void {\n if (this.muted > 0) return;\n // Univer marks a mutation `onlyLocal` when every seat derives it itself (formula-engine recalculation,\n // layout results): relaying it turns every recalculation into network traffic and a logged op.\n if (options?.onlyLocal) return;\n if (!this.options.forwardDocumentMutations && isCellEditorScratch(info)) return;\n // Inbound-applied mutations re-fire this listener because Univer's\n // syncExecuteCommand legitimately processes them through the full\n // pipeline. Skip by sniffing the sentinel we stamped on apply.\n if (\n info.params &&\n typeof info.params === \"object\" &&\n !Array.isArray(info.params) &&\n remoteOriginOf(info.params) !== null\n ) {\n return;\n }\n if (!this.doc) return;\n\n // Normalize params through a JSON round-trip BEFORE pushing into Yjs.\n // Yjs (and the Broadcast transport) only carry JSON-encodable values;\n // Univer types its mutation params as \"serializable\" but JS objects can\n // smuggle Date / Map / class instances through that promise. The\n // round-trip makes the failure mode deterministic: a non-encodable\n // mutation is skipped with a warning instead of corrupting the shared\n // doc or desyncing peers mid-session. What we push here is byte-for-byte\n // what remote peers will apply, so local-apply == remote-apply.\n let safeParams: MutationParams;\n try {\n safeParams =\n info.params === undefined || info.params === null\n ? null\n : stripSenderView(JSON.parse(JSON.stringify(info.params)) as MutationParams);\n } catch (err) {\n console.warn(\n `[collab] skipping non-serializable mutation \"${info.id}\" — peers will not receive it`,\n err,\n );\n return;\n }\n\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n const eid = `${this.options.clientId}:${++this.seq}`;\n this.applied.add(eid);\n // An edit made here is made on what this seat shows: the join-time check is over.\n this.joined = true;\n yArray.push([{ id: info.id, type: info.type, params: safeParams, uid: this.options.uid, eid }]);\n }\n\n /**\n * Apply every log entry this seat's content does not hold yet, in the log's order. The first time the\n * room shows content, the join-time check runs: a seat that booted from a snapshot OLDER than the\n * room's newest checkpoint reloads first (the entries that checkpoint trimmed exist only in it).\n */\n private drain(): void {\n if (!this.doc || this.disposed || this.reloadingBase) return;\n const yArray = this.doc.getArray<CollabMutationInfo>(MUTATIONS_ARRAY_KEY);\n const entries = yArray.toArray();\n const base = this.options.base;\n if (!this.joined) {\n const control = this.doc.getMap<unknown>(CONTROL_MAP_KEY);\n const checkpoint = control.get(CHECKPOINT_KEY) as CheckpointSignal | undefined;\n if (entries.length === 0 && !checkpoint) return;\n this.joined = true;\n if (base && checkpoint?.snapshotId && checkpoint.snapshotId !== base.snapshotId()) {\n this.reloadingBase = true;\n void base\n .reload()\n .catch((error: unknown) => {\n console.warn(\"[collab] could not load the newest saved version on joining\", error);\n this.options.onApplyFailed?.(\"collab.join\", error);\n })\n .finally(() => {\n this.reloadingBase = false;\n this.drain();\n });\n return;\n }\n }\n const covered = base?.covered();\n for (const op of entries) {\n if (op.eid) {\n if (this.applied.has(op.eid) || covered?.has(op.eid)) continue;\n this.applied.add(op.eid);\n } else {\n if (this.appliedRefs.has(op)) continue;\n this.appliedRefs.add(op);\n }\n this.applyRemoteMutation(op);\n }\n }\n\n private applyRemoteMutation(op: CollabMutationInfo): void {\n // Wrap params with the sentinel so handleLocalMutation knows not to\n // echo the apply back into Yjs.\n const ownUnit = this.options.unitId?.() ?? null;\n const taggedParams: MutationParams =\n op.params && typeof op.params === \"object\" && !Array.isArray(op.params)\n ? {\n ...(op.params as Record<string, unknown>),\n ...(ownUnit && typeof (op.params as { unitId?: unknown }).unitId === \"string\" ? { unitId: ownUnit } : {}),\n [REMOTE_PARAM_TAG]: op.uid ?? true,\n }\n : op.params;\n\n try {\n this.options.commandService.syncExecuteCommand(op.id, taggedParams, {\n onlyLocal: true,\n fromCollab: true,\n });\n } catch (err) {\n // One unappliable op (already baked into the loaded snapshot, or a\n // stale target) must not throw into the realtime channel handler and\n // abort the rest of the catch-up. Said, never swallowed.\n console.warn(\n `[collab] could not apply remote mutation \"${op.id}\" — skipped`,\n err,\n );\n this.options.onApplyFailed?.(op.id, err);\n }\n }\n}\n\n// ─── helpers ────────────────────────────────────────────────────────────\n\n/**\n * A workbook holds no Univer DOCUMENT units of its own: the `doc.mutation.*` stream a sheet emits is\n * the in-cell editor's scratch document (typing into a cell). The finished text reaches the sheet as\n * `sheet.mutation.set-range-values`, which does travel. Sending the scratch edits made a joiner replay\n * them against an editor unit it does not have (\"Trying to overwrite value at key\").\n */\nexport const SENDER_VIEW_PARAMS: readonly string[] = [\"layoutState\", \"textRanges\", \"prevTextRanges\"];\n\n/**\n * Remove what describes the SENDER'S view (the editor's layout cache, caret and selection ranges) from a\n * mutation's params before it travels: a receiver would otherwise restore the sender's layout and caret.\n * Everything else (the content-changing `actions`, ids, addresses) is left as is.\n */\nexport function stripSenderView(params: MutationParams): MutationParams {\n if (!params || typeof params !== \"object\" || Array.isArray(params)) return params;\n const out: Record<string, unknown> = { ...params };\n for (const key of SENDER_VIEW_PARAMS) delete out[key];\n return out;\n}\n\nexport function isCellEditorScratch(info: Pick<CollabMutationInfo, \"id\">): boolean {\n return typeof info.id === \"string\" && info.id.startsWith(\"doc.mutation.\");\n}\n\nconst CURSOR_PALETTE = [\n \"#3b82f6\", // blue\n \"#10b981\", // emerald\n \"#f59e0b\", // amber\n \"#ef4444\", // red\n \"#8b5cf6\", // violet\n \"#06b6d4\", // cyan\n \"#ec4899\", // pink\n \"#84cc16\", // lime\n];\n\nfunction pickColor(uid: string): string {\n // Deterministic FNV-1a-ish hash so the same user is always the same color\n // across sessions and across other users' screens.\n let h = 2166136261;\n for (let i = 0; i < uid.length; i++) {\n h ^= uid.charCodeAt(i);\n h = Math.imul(h, 16777619);\n }\n return CURSOR_PALETTE[Math.abs(h) % CURSOR_PALETTE.length] ?? \"#ec4899\";\n}\n","/**\n * A saved snapshot names the collab-room entries it already holds, so a seat that boots from it never\n * replays them (2026-10-16: a reload showed the text twice). Pure — no Yjs — so the editors' model can\n * stamp and read it without loading the room.\n */\n\n/** The key a saved snapshot carries its covered room entries under (`stampCovered` / `takeCovered`). */\nexport const COLLAB_COVERED_KEY = \"__matrxCollabCovered\";\n\n/** The snapshot to SAVE: `snapshot` plus the room entries it holds (`WorkbookCollabSession.coveredNow`). */\nexport function stampCovered<T extends object>(snapshot: T, covered: readonly string[]): T {\n return { ...snapshot, [COLLAB_COVERED_KEY]: [...covered] };\n}\n\n/** A LOADED snapshot split into the content to mount and the room entries it already holds. */\nexport function takeCovered<T>(snapshot: T): { snapshot: T; covered: Set<string> } {\n if (!snapshot || typeof snapshot !== \"object\" || !(COLLAB_COVERED_KEY in (snapshot as object))) {\n return { snapshot, covered: new Set() };\n }\n const { [COLLAB_COVERED_KEY]: list, ...rest } = snapshot as Record<string, unknown>;\n return {\n snapshot: rest as T,\n covered: new Set(Array.isArray(list) ? list.filter((e): e is string => typeof e === \"string\") : []),\n };\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G,EAAE;AAAA,QAClD;AAAA,MACF;AACA,WAAK,QAAQ,gBAAgB,GAAG,IAAI,GAAG;AAAA,IACzC;AAAA,EACF;AACF;AAUO,IAAM,qBAAwC,CAAC,eAAe,cAAc,gBAAgB;AAO5F,SAAS,gBAAgB,QAAwC;AACtE,MAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,EAAG,QAAO;AAC3E,QAAM,MAA+B,EAAE,GAAG,OAAO;AACjD,aAAW,OAAO,mBAAoB,QAAO,IAAI,GAAG;AACpD,SAAO;AACT;AAEO,SAAS,oBAAoB,MAA+C;AACjF,SAAO,OAAO,KAAK,OAAO,YAAY,KAAK,GAAG,WAAW,eAAe;AAC1E;AAEA,IAAM,iBAAiB;AAAA,EACrB;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AACF;AAEA,SAAS,UAAU,KAAqB;AAGtC,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,SAAK,IAAI,WAAW,CAAC;AACrB,QAAI,KAAK,KAAK,GAAG,QAAQ;AAAA,EAC3B;AACA,SAAO,eAAe,KAAK,IAAI,CAAC,IAAI,eAAe,MAAM,KAAK;AAChE;","names":[]}
@@ -1,6 +1,21 @@
1
1
  import * as Y from 'yjs';
2
2
  import { Awareness } from 'y-protocols/awareness';
3
3
 
4
+ /**
5
+ * A saved snapshot names the collab-room entries it already holds, so a seat that boots from it never
6
+ * replays them (2026-10-16: a reload showed the text twice). Pure — no Yjs — so the editors' model can
7
+ * stamp and read it without loading the room.
8
+ */
9
+ /** The key a saved snapshot carries its covered room entries under (`stampCovered` / `takeCovered`). */
10
+ declare const COLLAB_COVERED_KEY = "__matrxCollabCovered";
11
+ /** The snapshot to SAVE: `snapshot` plus the room entries it holds (`WorkbookCollabSession.coveredNow`). */
12
+ declare function stampCovered<T extends object>(snapshot: T, covered: readonly string[]): T;
13
+ /** A LOADED snapshot split into the content to mount and the room entries it already holds. */
14
+ declare function takeCovered<T>(snapshot: T): {
15
+ snapshot: T;
16
+ covered: Set<string>;
17
+ };
18
+
4
19
  /**
5
20
  * Structural transport contract. `SupabaseYjsProvider` satisfies it in
6
21
  * production; the verification harness injects an in-memory loopback
@@ -25,6 +40,22 @@ type CollabMutationInfo = {
25
40
  params: MutationParams;
26
41
  /** Who made it (the person's uid), so a peer can tell its own other tab's edit from a stranger's. */
27
42
  uid?: string;
43
+ /**
44
+ * The entry's identity in the room (`<clientId>:<seq>`). A saved snapshot names the entries it holds
45
+ * (`stampCovered`), so a seat that boots from that snapshot never replays them a second time.
46
+ */
47
+ eid?: string;
48
+ };
49
+ /**
50
+ * What a seat booted from: the saved snapshot's row id and the room entries that snapshot already holds.
51
+ * The session never replays a covered entry, and a seat that booted from an OLDER snapshot than the
52
+ * room's newest checkpoint first reloads (the entries that checkpoint trimmed are only in that snapshot).
53
+ */
54
+ type CollabBase = {
55
+ snapshotId: () => string | null;
56
+ covered: () => ReadonlySet<string>;
57
+ /** Show the newest saved snapshot (and make it the base). */
58
+ reload: () => Promise<void>;
28
59
  };
29
60
  type ExecuteOptions = {
30
61
  /** Per-Univer convention: when true, the command runs locally only and is
@@ -74,6 +105,12 @@ type WorkbookCollabSessionOptions = {
74
105
  unitId?: () => string | null;
75
106
  /** A peer's mutation could not be applied here: the seat says so and re-syncs; never only a console line. */
76
107
  onApplyFailed?: (mutationId: string, error: unknown) => void;
108
+ /**
109
+ * The saved snapshot this seat booted from. Without it a reloading seat replays every entry still in
110
+ * the room's log on top of a snapshot that already holds them: the text shows twice, and the next save
111
+ * stores it twice (2026-10-16).
112
+ */
113
+ base?: CollabBase;
77
114
  };
78
115
  declare class WorkbookCollabSession {
79
116
  private readonly options;
@@ -88,25 +125,33 @@ declare class WorkbookCollabSession {
88
125
  private muted;
89
126
  private started;
90
127
  private disposed;
128
+ /** Room entries this seat holds in its content: applied from a peer, or made here. */
129
+ private readonly applied;
130
+ /** Entries without an id (a peer on an older build) are applied once, by identity. */
131
+ private readonly appliedRefs;
132
+ private seq;
133
+ /** False until this seat has seen the room's content once (the join-time check runs then). */
134
+ private joined;
135
+ /** The base is being reloaded: entries wait in the log until it is shown. */
136
+ private reloadingBase;
91
137
  constructor(options: WorkbookCollabSessionOptions);
92
138
  start(): Promise<void>;
93
139
  stop(): void;
140
+ /** How many mutations the shared log holds right now. */
141
+ logLength(): number;
94
142
  /**
95
- * How many mutations the shared log holds right now. Read it BEFORE
96
- * `workbook.save()`: that many entries are guaranteed to be inside the
97
- * snapshot that save produces.
143
+ * The room entries this seat's content holds RIGHT NOW. Read it in the same synchronous step as the
144
+ * content you are about to save, and save it with that content (`stampCovered`); after the save lands,
145
+ * pass it to `checkpoint`.
98
146
  */
99
- logLength(): number;
147
+ coveredNow(): string[];
100
148
  /**
101
- * Drop the first `upTo` mutations from the shared log once a snapshot that
102
- * contains them has been SAVED. Without this a joiner loads the saved
103
- * workbook (which already has every mutation baked in) and then catches up
104
- * the whole log on top of it, replaying edits into a workbook that already
105
- * holds them — Univer refuses with "Trying to overwrite value at key"
106
- * (feedback 88184e53). Only the host calls this; peers receive it as a
107
- * delete, which the inbound observer ignores (it acts on inserts only).
149
+ * The snapshot `snapshotId` was SAVED holding `covered` (from `coveredNow`): those entries leave the
150
+ * shared log, and the room records the snapshot as its newest checkpoint. Removal is by entry id, never
151
+ * by position — an entry that arrived while the save was in flight is not in the snapshot and stays.
152
+ * Only the elected saver calls this; peers receive it as a delete (never replayed).
108
153
  */
109
- compactLog(upTo: number): void;
154
+ checkpoint(snapshotId: string, covered: readonly string[]): void;
110
155
  /**
111
156
  * This client replaced the whole content and SAVED it as `snapshotId`.
112
157
  * One transaction empties the shared mutation log (every entry targets the
@@ -142,6 +187,12 @@ declare class WorkbookCollabSession {
142
187
  hostUid: string | null;
143
188
  };
144
189
  private handleLocalMutation;
190
+ /**
191
+ * Apply every log entry this seat's content does not hold yet, in the log's order. The first time the
192
+ * room shows content, the join-time check runs: a seat that booted from a snapshot OLDER than the
193
+ * room's newest checkpoint reloads first (the entries that checkpoint trimmed exist only in it).
194
+ */
195
+ private drain;
145
196
  private applyRemoteMutation;
146
197
  }
147
198
  /**
@@ -150,6 +201,13 @@ declare class WorkbookCollabSession {
150
201
  * `sheet.mutation.set-range-values`, which does travel. Sending the scratch edits made a joiner replay
151
202
  * them against an editor unit it does not have ("Trying to overwrite value at key").
152
203
  */
204
+ declare const SENDER_VIEW_PARAMS: readonly string[];
205
+ /**
206
+ * Remove what describes the SENDER'S view (the editor's layout cache, caret and selection ranges) from a
207
+ * mutation's params before it travels: a receiver would otherwise restore the sender's layout and caret.
208
+ * Everything else (the content-changing `actions`, ids, addresses) is left as is.
209
+ */
210
+ declare function stripSenderView(params: MutationParams): MutationParams;
153
211
  declare function isCellEditorScratch(info: Pick<CollabMutationInfo, "id">): boolean;
154
212
 
155
- export { type CollabMutationInfo, type CollabProviderLike, type CommandServiceLike, WorkbookCollabSession, type WorkbookCollabSessionOptions, isCellEditorScratch };
213
+ export { COLLAB_COVERED_KEY, type CollabBase, type CollabMutationInfo, type CollabProviderLike, type CommandServiceLike, SENDER_VIEW_PARAMS, WorkbookCollabSession, type WorkbookCollabSessionOptions, isCellEditorScratch, stampCovered, stripSenderView, takeCovered };
@@ -1,6 +1,21 @@
1
1
  import * as Y from 'yjs';
2
2
  import { Awareness } from 'y-protocols/awareness';
3
3
 
4
+ /**
5
+ * A saved snapshot names the collab-room entries it already holds, so a seat that boots from it never
6
+ * replays them (2026-10-16: a reload showed the text twice). Pure — no Yjs — so the editors' model can
7
+ * stamp and read it without loading the room.
8
+ */
9
+ /** The key a saved snapshot carries its covered room entries under (`stampCovered` / `takeCovered`). */
10
+ declare const COLLAB_COVERED_KEY = "__matrxCollabCovered";
11
+ /** The snapshot to SAVE: `snapshot` plus the room entries it holds (`WorkbookCollabSession.coveredNow`). */
12
+ declare function stampCovered<T extends object>(snapshot: T, covered: readonly string[]): T;
13
+ /** A LOADED snapshot split into the content to mount and the room entries it already holds. */
14
+ declare function takeCovered<T>(snapshot: T): {
15
+ snapshot: T;
16
+ covered: Set<string>;
17
+ };
18
+
4
19
  /**
5
20
  * Structural transport contract. `SupabaseYjsProvider` satisfies it in
6
21
  * production; the verification harness injects an in-memory loopback
@@ -25,6 +40,22 @@ type CollabMutationInfo = {
25
40
  params: MutationParams;
26
41
  /** Who made it (the person's uid), so a peer can tell its own other tab's edit from a stranger's. */
27
42
  uid?: string;
43
+ /**
44
+ * The entry's identity in the room (`<clientId>:<seq>`). A saved snapshot names the entries it holds
45
+ * (`stampCovered`), so a seat that boots from that snapshot never replays them a second time.
46
+ */
47
+ eid?: string;
48
+ };
49
+ /**
50
+ * What a seat booted from: the saved snapshot's row id and the room entries that snapshot already holds.
51
+ * The session never replays a covered entry, and a seat that booted from an OLDER snapshot than the
52
+ * room's newest checkpoint first reloads (the entries that checkpoint trimmed are only in that snapshot).
53
+ */
54
+ type CollabBase = {
55
+ snapshotId: () => string | null;
56
+ covered: () => ReadonlySet<string>;
57
+ /** Show the newest saved snapshot (and make it the base). */
58
+ reload: () => Promise<void>;
28
59
  };
29
60
  type ExecuteOptions = {
30
61
  /** Per-Univer convention: when true, the command runs locally only and is
@@ -74,6 +105,12 @@ type WorkbookCollabSessionOptions = {
74
105
  unitId?: () => string | null;
75
106
  /** A peer's mutation could not be applied here: the seat says so and re-syncs; never only a console line. */
76
107
  onApplyFailed?: (mutationId: string, error: unknown) => void;
108
+ /**
109
+ * The saved snapshot this seat booted from. Without it a reloading seat replays every entry still in
110
+ * the room's log on top of a snapshot that already holds them: the text shows twice, and the next save
111
+ * stores it twice (2026-10-16).
112
+ */
113
+ base?: CollabBase;
77
114
  };
78
115
  declare class WorkbookCollabSession {
79
116
  private readonly options;
@@ -88,25 +125,33 @@ declare class WorkbookCollabSession {
88
125
  private muted;
89
126
  private started;
90
127
  private disposed;
128
+ /** Room entries this seat holds in its content: applied from a peer, or made here. */
129
+ private readonly applied;
130
+ /** Entries without an id (a peer on an older build) are applied once, by identity. */
131
+ private readonly appliedRefs;
132
+ private seq;
133
+ /** False until this seat has seen the room's content once (the join-time check runs then). */
134
+ private joined;
135
+ /** The base is being reloaded: entries wait in the log until it is shown. */
136
+ private reloadingBase;
91
137
  constructor(options: WorkbookCollabSessionOptions);
92
138
  start(): Promise<void>;
93
139
  stop(): void;
140
+ /** How many mutations the shared log holds right now. */
141
+ logLength(): number;
94
142
  /**
95
- * How many mutations the shared log holds right now. Read it BEFORE
96
- * `workbook.save()`: that many entries are guaranteed to be inside the
97
- * snapshot that save produces.
143
+ * The room entries this seat's content holds RIGHT NOW. Read it in the same synchronous step as the
144
+ * content you are about to save, and save it with that content (`stampCovered`); after the save lands,
145
+ * pass it to `checkpoint`.
98
146
  */
99
- logLength(): number;
147
+ coveredNow(): string[];
100
148
  /**
101
- * Drop the first `upTo` mutations from the shared log once a snapshot that
102
- * contains them has been SAVED. Without this a joiner loads the saved
103
- * workbook (which already has every mutation baked in) and then catches up
104
- * the whole log on top of it, replaying edits into a workbook that already
105
- * holds them — Univer refuses with "Trying to overwrite value at key"
106
- * (feedback 88184e53). Only the host calls this; peers receive it as a
107
- * delete, which the inbound observer ignores (it acts on inserts only).
149
+ * The snapshot `snapshotId` was SAVED holding `covered` (from `coveredNow`): those entries leave the
150
+ * shared log, and the room records the snapshot as its newest checkpoint. Removal is by entry id, never
151
+ * by position — an entry that arrived while the save was in flight is not in the snapshot and stays.
152
+ * Only the elected saver calls this; peers receive it as a delete (never replayed).
108
153
  */
109
- compactLog(upTo: number): void;
154
+ checkpoint(snapshotId: string, covered: readonly string[]): void;
110
155
  /**
111
156
  * This client replaced the whole content and SAVED it as `snapshotId`.
112
157
  * One transaction empties the shared mutation log (every entry targets the
@@ -142,6 +187,12 @@ declare class WorkbookCollabSession {
142
187
  hostUid: string | null;
143
188
  };
144
189
  private handleLocalMutation;
190
+ /**
191
+ * Apply every log entry this seat's content does not hold yet, in the log's order. The first time the
192
+ * room shows content, the join-time check runs: a seat that booted from a snapshot OLDER than the
193
+ * room's newest checkpoint reloads first (the entries that checkpoint trimmed exist only in it).
194
+ */
195
+ private drain;
145
196
  private applyRemoteMutation;
146
197
  }
147
198
  /**
@@ -150,6 +201,13 @@ declare class WorkbookCollabSession {
150
201
  * `sheet.mutation.set-range-values`, which does travel. Sending the scratch edits made a joiner replay
151
202
  * them against an editor unit it does not have ("Trying to overwrite value at key").
152
203
  */
204
+ declare const SENDER_VIEW_PARAMS: readonly string[];
205
+ /**
206
+ * Remove what describes the SENDER'S view (the editor's layout cache, caret and selection ranges) from a
207
+ * mutation's params before it travels: a receiver would otherwise restore the sender's layout and caret.
208
+ * Everything else (the content-changing `actions`, ids, addresses) is left as is.
209
+ */
210
+ declare function stripSenderView(params: MutationParams): MutationParams;
153
211
  declare function isCellEditorScratch(info: Pick<CollabMutationInfo, "id">): boolean;
154
212
 
155
- export { type CollabMutationInfo, type CollabProviderLike, type CommandServiceLike, WorkbookCollabSession, type WorkbookCollabSessionOptions, isCellEditorScratch };
213
+ export { COLLAB_COVERED_KEY, type CollabBase, type CollabMutationInfo, type CollabProviderLike, type CommandServiceLike, SENDER_VIEW_PARAMS, WorkbookCollabSession, type WorkbookCollabSessionOptions, isCellEditorScratch, stampCovered, stripSenderView, takeCovered };
@@ -4,9 +4,28 @@
4
4
  import * as Y from "yjs";
5
5
  import { Awareness } from "y-protocols/awareness";
6
6
  import { electCollabHost, remoteOriginOf, REMOTE_PARAM_TAG } from "@ai-matrx/data/realtime/collab";
7
+
8
+ // src/univer/collab/covered.ts
9
+ var COLLAB_COVERED_KEY = "__matrxCollabCovered";
10
+ function stampCovered(snapshot, covered) {
11
+ return { ...snapshot, [COLLAB_COVERED_KEY]: [...covered] };
12
+ }
13
+ function takeCovered(snapshot) {
14
+ if (!snapshot || typeof snapshot !== "object" || !(COLLAB_COVERED_KEY in snapshot)) {
15
+ return { snapshot, covered: /* @__PURE__ */ new Set() };
16
+ }
17
+ const { [COLLAB_COVERED_KEY]: list, ...rest } = snapshot;
18
+ return {
19
+ snapshot: rest,
20
+ covered: new Set(Array.isArray(list) ? list.filter((e) => typeof e === "string") : [])
21
+ };
22
+ }
23
+
24
+ // src/univer/collab/WorkbookCollabSession.ts
7
25
  var MUTATIONS_ARRAY_KEY = "mutations";
8
26
  var CONTROL_MAP_KEY = "control";
9
27
  var REPLACED_KEY = "replaced";
28
+ var CHECKPOINT_KEY = "checkpoint";
10
29
  var WorkbookCollabSession = class {
11
30
  options;
12
31
  doc = null;
@@ -20,6 +39,15 @@ var WorkbookCollabSession = class {
20
39
  muted = 0;
21
40
  started = false;
22
41
  disposed = false;
42
+ /** Room entries this seat holds in its content: applied from a peer, or made here. */
43
+ applied = /* @__PURE__ */ new Set();
44
+ /** Entries without an id (a peer on an older build) are applied once, by identity. */
45
+ appliedRefs = /* @__PURE__ */ new WeakSet();
46
+ seq = 0;
47
+ /** False until this seat has seen the room's content once (the join-time check runs then). */
48
+ joined = false;
49
+ /** The base is being reloaded: entries wait in the log until it is shown. */
50
+ reloadingBase = false;
23
51
  constructor(options) {
24
52
  this.options = options;
25
53
  }
@@ -50,12 +78,8 @@ var WorkbookCollabSession = class {
50
78
  const yArray = this.doc.getArray(MUTATIONS_ARRAY_KEY);
51
79
  this.yArrayObserver = (event) => {
52
80
  if (event.transaction.local) return;
53
- for (const change of event.changes.delta) {
54
- if (!change.insert || !Array.isArray(change.insert)) continue;
55
- for (const op of change.insert) {
56
- this.applyRemoteMutation(op);
57
- }
58
- }
81
+ if (!event.changes.delta.some((change) => Array.isArray(change.insert) && change.insert.length > 0)) return;
82
+ this.drain();
59
83
  };
60
84
  yArray.observe(this.yArrayObserver);
61
85
  if (this.options.onAwarenessChange) {
@@ -66,10 +90,11 @@ var WorkbookCollabSession = class {
66
90
  this.awareness.on("change", this.awarenessObserver);
67
91
  }
68
92
  this.commandDisposer = this.options.commandService.onMutationExecutedForCollab(
69
- (info) => this.handleLocalMutation(info)
93
+ (info, options) => this.handleLocalMutation(info, options)
70
94
  );
71
95
  await this.provider.connect();
72
96
  await this.provider.ready();
97
+ this.drain();
73
98
  if (this.disposed || !this.doc) return;
74
99
  const control = this.doc.getMap(CONTROL_MAP_KEY);
75
100
  const seen = control.get(REPLACED_KEY)?.nonce ?? null;
@@ -112,28 +137,44 @@ var WorkbookCollabSession = class {
112
137
  this.doc = null;
113
138
  }
114
139
  }
115
- /**
116
- * How many mutations the shared log holds right now. Read it BEFORE
117
- * `workbook.save()`: that many entries are guaranteed to be inside the
118
- * snapshot that save produces.
119
- */
140
+ /** How many mutations the shared log holds right now. */
120
141
  logLength() {
121
142
  return this.doc?.getArray(MUTATIONS_ARRAY_KEY).length ?? 0;
122
143
  }
123
144
  /**
124
- * Drop the first `upTo` mutations from the shared log once a snapshot that
125
- * contains them has been SAVED. Without this a joiner loads the saved
126
- * workbook (which already has every mutation baked in) and then catches up
127
- * the whole log on top of it, replaying edits into a workbook that already
128
- * holds them — Univer refuses with "Trying to overwrite value at key"
129
- * (feedback 88184e53). Only the host calls this; peers receive it as a
130
- * delete, which the inbound observer ignores (it acts on inserts only).
145
+ * The room entries this seat's content holds RIGHT NOW. Read it in the same synchronous step as the
146
+ * content you are about to save, and save it with that content (`stampCovered`); after the save lands,
147
+ * pass it to `checkpoint`.
131
148
  */
132
- compactLog(upTo) {
133
- if (!this.doc || upTo <= 0) return;
149
+ coveredNow() {
150
+ if (!this.doc) return [];
151
+ const covered = this.options.base?.covered();
152
+ const out = [];
153
+ for (const op of this.doc.getArray(MUTATIONS_ARRAY_KEY).toArray()) {
154
+ if (op.eid && (this.applied.has(op.eid) || covered?.has(op.eid))) out.push(op.eid);
155
+ }
156
+ return out;
157
+ }
158
+ /**
159
+ * The snapshot `snapshotId` was SAVED holding `covered` (from `coveredNow`): those entries leave the
160
+ * shared log, and the room records the snapshot as its newest checkpoint. Removal is by entry id, never
161
+ * by position — an entry that arrived while the save was in flight is not in the snapshot and stays.
162
+ * Only the elected saver calls this; peers receive it as a delete (never replayed).
163
+ */
164
+ checkpoint(snapshotId, covered) {
165
+ if (!this.doc) return;
134
166
  const yArray = this.doc.getArray(MUTATIONS_ARRAY_KEY);
135
- const n = Math.min(upTo, yArray.length);
136
- if (n > 0) this.doc.transact(() => yArray.delete(0, n));
167
+ const control = this.doc.getMap(CONTROL_MAP_KEY);
168
+ const drop = new Set(covered);
169
+ const signal = { snapshotId, by: this.options.clientId };
170
+ this.doc.transact(() => {
171
+ const entries = yArray.toArray();
172
+ for (let i = entries.length - 1; i >= 0; i -= 1) {
173
+ const eid = entries[i]?.eid;
174
+ if (eid && drop.has(eid)) yArray.delete(i, 1);
175
+ }
176
+ control.set(CHECKPOINT_KEY, signal);
177
+ });
137
178
  }
138
179
  /**
139
180
  * This client replaced the whole content and SAVED it as `snapshotId`.
@@ -153,6 +194,7 @@ var WorkbookCollabSession = class {
153
194
  this.doc.transact(() => {
154
195
  if (yArray.length > 0) yArray.delete(0, yArray.length);
155
196
  control.set(REPLACED_KEY, signal);
197
+ control.set(CHECKPOINT_KEY, { snapshotId, by: this.options.clientId });
156
198
  });
157
199
  }
158
200
  /**
@@ -196,8 +238,9 @@ var WorkbookCollabSession = class {
196
238
  return electCollabHost(states, this.options.uid, this.options.clientId, leader, opts.tabTieBreak ?? false);
197
239
  }
198
240
  // ─── internals ────────────────────────────────────────────────────────
199
- handleLocalMutation(info) {
241
+ handleLocalMutation(info, options) {
200
242
  if (this.muted > 0) return;
243
+ if (options?.onlyLocal) return;
201
244
  if (!this.options.forwardDocumentMutations && isCellEditorScratch(info)) return;
202
245
  if (info.params && typeof info.params === "object" && !Array.isArray(info.params) && remoteOriginOf(info.params) !== null) {
203
246
  return;
@@ -205,7 +248,7 @@ var WorkbookCollabSession = class {
205
248
  if (!this.doc) return;
206
249
  let safeParams;
207
250
  try {
208
- safeParams = info.params === void 0 || info.params === null ? null : JSON.parse(JSON.stringify(info.params));
251
+ safeParams = info.params === void 0 || info.params === null ? null : stripSenderView(JSON.parse(JSON.stringify(info.params)));
209
252
  } catch (err) {
210
253
  console.warn(
211
254
  `[collab] skipping non-serializable mutation "${info.id}" \u2014 peers will not receive it`,
@@ -214,7 +257,49 @@ var WorkbookCollabSession = class {
214
257
  return;
215
258
  }
216
259
  const yArray = this.doc.getArray(MUTATIONS_ARRAY_KEY);
217
- yArray.push([{ id: info.id, type: info.type, params: safeParams, uid: this.options.uid }]);
260
+ const eid = `${this.options.clientId}:${++this.seq}`;
261
+ this.applied.add(eid);
262
+ this.joined = true;
263
+ yArray.push([{ id: info.id, type: info.type, params: safeParams, uid: this.options.uid, eid }]);
264
+ }
265
+ /**
266
+ * Apply every log entry this seat's content does not hold yet, in the log's order. The first time the
267
+ * room shows content, the join-time check runs: a seat that booted from a snapshot OLDER than the
268
+ * room's newest checkpoint reloads first (the entries that checkpoint trimmed exist only in it).
269
+ */
270
+ drain() {
271
+ if (!this.doc || this.disposed || this.reloadingBase) return;
272
+ const yArray = this.doc.getArray(MUTATIONS_ARRAY_KEY);
273
+ const entries = yArray.toArray();
274
+ const base = this.options.base;
275
+ if (!this.joined) {
276
+ const control = this.doc.getMap(CONTROL_MAP_KEY);
277
+ const checkpoint = control.get(CHECKPOINT_KEY);
278
+ if (entries.length === 0 && !checkpoint) return;
279
+ this.joined = true;
280
+ if (base && checkpoint?.snapshotId && checkpoint.snapshotId !== base.snapshotId()) {
281
+ this.reloadingBase = true;
282
+ void base.reload().catch((error) => {
283
+ console.warn("[collab] could not load the newest saved version on joining", error);
284
+ this.options.onApplyFailed?.("collab.join", error);
285
+ }).finally(() => {
286
+ this.reloadingBase = false;
287
+ this.drain();
288
+ });
289
+ return;
290
+ }
291
+ }
292
+ const covered = base?.covered();
293
+ for (const op of entries) {
294
+ if (op.eid) {
295
+ if (this.applied.has(op.eid) || covered?.has(op.eid)) continue;
296
+ this.applied.add(op.eid);
297
+ } else {
298
+ if (this.appliedRefs.has(op)) continue;
299
+ this.appliedRefs.add(op);
300
+ }
301
+ this.applyRemoteMutation(op);
302
+ }
218
303
  }
219
304
  applyRemoteMutation(op) {
220
305
  const ownUnit = this.options.unitId?.() ?? null;
@@ -237,6 +322,13 @@ var WorkbookCollabSession = class {
237
322
  }
238
323
  }
239
324
  };
325
+ var SENDER_VIEW_PARAMS = ["layoutState", "textRanges", "prevTextRanges"];
326
+ function stripSenderView(params) {
327
+ if (!params || typeof params !== "object" || Array.isArray(params)) return params;
328
+ const out = { ...params };
329
+ for (const key of SENDER_VIEW_PARAMS) delete out[key];
330
+ return out;
331
+ }
240
332
  function isCellEditorScratch(info) {
241
333
  return typeof info.id === "string" && info.id.startsWith("doc.mutation.");
242
334
  }
@@ -267,7 +359,12 @@ function pickColor(uid) {
267
359
  return CURSOR_PALETTE[Math.abs(h) % CURSOR_PALETTE.length] ?? "#ec4899";
268
360
  }
269
361
  export {
362
+ COLLAB_COVERED_KEY,
363
+ SENDER_VIEW_PARAMS,
270
364
  WorkbookCollabSession,
271
- isCellEditorScratch
365
+ isCellEditorScratch,
366
+ stampCovered,
367
+ stripSenderView,
368
+ takeCovered
272
369
  };
273
370
  //# sourceMappingURL=univer-collab.js.map