Skip to content

feat: implement real-time collaborative editing using Yjs - #723

Merged
pikann merged 4 commits into
masterfrom
feature/implement-realtime-collaborative-editing
Nov 10, 2026
Merged

pikann merged 4 commits into
masterfrom
feature/implement-realtime-collaborative-editing

Conversation

@pikann

@pikann pikann commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Real-time multiplayer editing (Yjs) for the BlockNote editors of project docs and task descriptions. Several people can type in the same doc or description at once and see each other's cursors. Comment editors are intentionally not collaborative: a comment composer is one person's draft.

How it works

Realtime service (services/realtime/src/collab.ts, wired in server.ts / index.ts)

  • CollabHub keeps one in-memory Y.Doc + awareness per edited resource and relays updates over the existing Socket.IO connection (no second WebSocket server).
  • Events: collab:join (ack), collab:update, collab:awareness, collab:leave; server → client collab:revoked.
  • Authorization: joining and every update require docs:write / tasks:write on the exact resource, checked through the shared AccessDecider. When IAM changes, every member is re-checked and evicted if access was lost. Ids are validated as UUIDs; updates are capped at 5 MB; rooms are capped.
  • Persistence stays in the REST API. Clients still save block JSON through the existing routes, so MCP, search and exports are unchanged. The room is a live relay and is dropped 30 s after the last editor leaves.
  • Seeding: the first joiner of an empty room is told seed: true and is the only client that writes the stored content into the Y.Doc. A room holding only BlockNote's empty placeholder paragraph still counts as empty.
  • The join snapshot is taken after the socket enters the broadcast room, so no update can fall between the two.

Web (apps/web)

  • lib/collab-session.ts: a reference-counted CollabSession (Y.Doc + awareness) per resource. Handles binary payloads arriving as ArrayBuffer, rejoins and exchanges missing state after a reconnect, and retries the join if the socket drops mid-join. Seeding retries until the write actually reaches the shared doc.
  • hooks/use-collab-session.ts: joins the room only when the user can edit; otherwise (no write access, realtime service unreachable) the editors fall back to the previous single-user behavior.
  • doc-editor.tsx, description-section.tsx: BlockNote is built with its collaboration option; peers' edits don't mark the local editor dirty, so only the author saves. While collaborating, the shared doc is the source of truth: refetched content from a peer's save is not replayed into it. "Write with AI" on task descriptions is applied once, from the requesting user's client.
  • Works in React StrictMode (the seed is not cancelled by StrictMode's simulated unmount).
  • New direct deps: yjs, y-protocols (apps/web, services/realtime).

Known limitations

  • A REST write (an agent or MCP) while editors have the room open is not merged into the live doc; the next editor save overwrites it. The room re-seeds from stored content once it is empty.
  • Rooms live in one process's memory. Running several realtime replicas needs sticky routing per resource (or a Socket.IO adapter plus shared doc state). Documented in services/realtime/README.md.
  • A first editor who opens a doc from stale cached content seeds the room with it.

Testing

  • services/realtime: new collab.test.ts (authorization, seeding, relay, revocation, reconnect, placeholder rooms); all 51 tests pass, tsc and biome clean.
  • apps/web: collab-session.test.ts (join, retry on drop, echo suppression, revocation) and doc-editor.collab.test.tsx (seeding under StrictMode); tsc -b clean, full suite passed before the last two fixes (StrictMode seed, join retry), which were covered by targeted tests only.
  • apps/e2e: new tests/realtime/collaborative-editing.spec.ts (+ .feature): two members in separate browsers share a doc and a task description (content appears once, live typing both ways, REST copy holds both edits). 20/20 repeats on Chromium; the existing docs, task-detail and realtime specs also pass (108).
  • Not covered: mobile-chrome, a read-only user, losing access mid-edit, and a manual check in a dev (StrictMode) browser session after the final fix.

- Added a new `CollabHub` class to manage collaborative editing sessions for project documents and task descriptions.
- Introduced socket events for joining, updating, and leaving collaboration rooms.
- Implemented awareness updates for cursor presence among collaborators.
- Updated the server to handle collaborative editing events and integrate with existing Socket.IO infrastructure.
- Enhanced documentation in `README.md` to cover collaborative editing features and usage.
- Added tests for the collaborative editing functionality to ensure reliability and correctness.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

The relay's authorization, eviction and ordering logic hold up, but the seed lifecycle and the join/fallback path have failure modes that leave a document blank and then overwrite its stored content, and one revocation path is weaker than the README claims.

Reviewed changes

  • Realtime hub (services/realtime/src/collab.ts, server.ts, index.ts): in-memory Y.Doc + awareness per doc/task relayed over Socket.IO, per-update IAM checks, IAM-change eviction, UUID/5 MB/2 000-room limits and a 30 s room grace period.
  • Client session (apps/web/src/lib/collab-session.ts, hooks/use-collab-session.ts): reference-counted session, rejoin with missing-state exchange, seed retry loop, off | connecting | ready state machine.
  • Editor integration (doc-editor.tsx, description-section.tsx, lib/utils.ts): BlockNote collaboration option, peer edits excluded via the yjs-remote change source, seeding only by the client the room picks.
  • Tests and docs: collab.test.ts, collab-session.test.ts, doc-editor.collab.test.tsx, the new e2e spec and feature file, and the realtime README section.

I verified the load-bearing third-party contracts against the actual packages: BlockNote 0.48.1 maps y-sync$ transactions to { type: "yjs-remote" } and accepts a { awareness } provider, and socket.io-client 4.8.1 starts the ack timer immediately even for buffered packets.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

Comment thread services/realtime/src/collab.ts Resolved
Comment thread services/realtime/src/collab.ts Resolved
Comment thread services/realtime/src/index.ts Resolved
Comment thread apps/web/src/lib/collab-session.ts Resolved
Comment thread services/realtime/src/collab.ts Resolved
Comment thread services/realtime/src/collab.ts Resolved

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Incremental review — fe2a47a

The seed-lifecycle and ghost-member fixes are in and verified. The seed grant now has a 10 s deadline, a handover to another member, and a collab:seed event; the client-side whenSeeder/isCollabDocEmpty guard and the per-account room cap are sound. Tests pass: bun test 55/55, vitest 10/10, tsc --noEmit clean on both workspaces.

One issue found

⚠️ The seed timer keeps cycling between the same idle members (services/realtime/src/collab.ts:445). reassignSeed picks the first member whose id differs from the current seeder, so a room with two idle members and no content alternates A → B → A → B every 10 s, emitting collab:seed each time. A client that already has seed set ignores the event, so the practical effect is repeated no-op events and a timer that never stops for an empty room. Excluding the previous seeder (or tracking the members already tried) would end the cycle.

Nits

  • apps/web/src/components/projects/docs/doc-editor.tsx:198 and apps/web/src/components/projects/interactions/task-detail/description-section.tsx:247: whenSeeder returns an unsubscribe that the effect never calls. mountedRef makes the listener a no-op, but the listener stays in the set until the session is destroyed.
  • services/realtime/README.md:147: the "Limits" bullet is now duplicated; the old one at line 149 covers REST-write conflicts.
  • apps/web/src/lib/collab-session.ts:428: isCollabDocEmpty runs fragment.toString() on every one of the 20 seed attempts; the server's isEmpty does the same per update. Not a correctness issue, but O(n) per attempt on a large document.

Verified

  • collab.ts join now rejects a dead socket (isAlive) before adding a member, and the test covers the leak.
  • seedTimer / markSeeded / reassignSeed / destroy clear the timer on every path.
  • MAX_ROOMS_PER_USER is checked before the room is created; excluding the current room from roomsOf keeps rejoins working.
  • The client retry no longer retries on a timeout; the "dropped" sentinel only retries on a disconnect.
  • useCollabSession falls back to OFF when the user query resolves without a user.
  • seedingRef is now read in both handleChange handlers.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

Comment thread services/realtime/src/collab.ts Resolved
Comment thread services/realtime/README.md Resolved

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

This run reviewed 1c7dc42, the fix-only delta on top of the previous incremental review; every open thread from both prior reviews is now addressed and resolved.

  • Stopped the seed-grant cycle — collab.ts gained Room.seedTried: grantSeed records the member it grants, reassignSeed only picks untried members, and when none is left it frees the grant and clears the timer instead of alternating A → B → A → B. markSeeded clears the set, and the join path still grants seed: true to a new joiner, so a freed grant is recoverable. A test asserts both halves (granted stays ["b"], then c joins with seed: true).
  • Dropped the whenSeeder listener on real unmount — both doc-editor.tsx and description-section.tsx keep the unsubscribe in seedUnsubRef and call it from the mount effect's cleanup through a setTimeout(…, 0) gated on mountedRef.current, so StrictMode's synchronous simulated unmount keeps the listener and a real unmount removes it. The seed effect is still initializedRef-guarded, so at most one listener is ever registered.
  • De-duplicated the README bullets — the two "Limits" entries are now Capacity and REST writes.

Verified locally: bun test in services/realtime (56 pass), the two collab vitest suites in apps/web (11 pass), and tsc clean in both workspaces. The one remaining prior nit (isCollabDocEmpty/isEmpty serializing the fragment per attempt) is unchanged and informational only.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Incremental review — c4c9979

✅ No new issues found.

The delta is a hardening pass over the prior review's concerns and is verified: fail-open access checks, seed hand-off cancellation, awareness ownership, per-room/per-socket capacity limits, and a tree-walking isEmpty replacing the XML-string regex.

Tests: bun test in services/realtime 64/64; bunx vitest run src/lib/collab-session.test.ts src/components/projects/docs/doc-editor.collab.test.tsx in apps/web 14/14; tsc --noEmit in services/realtime and tsc -b in apps/web clean.

Verified

  • canWrite returns boolean | undefined; join fails closed on undefined, update drops only that update and emits collab:error, recheck only evicts on false. A transient API blip no longer evicts every editor.
  • collab:seed-cancel is sent to the previous seeder before the grant moves; the client's seedRevoked stops seedCollabDoc, and grantSeed clears it on a later grant.
  • awarenessClientIds parses the y-protocols wire format; Room.awarenessOwners rejects a socket speaking for another client's id; evict clears its own ids.
  • MAX_ROOM_BYTES, RATE_BURST/RATE_PER_SEC, MAX_PENDING_UPDATES are enforced; enqueue returns false and the client gets backlog.
  • hasContent walks Y.XmlFragment/Y.XmlElement/Y.XmlText/Y.XmlHook. Y.XmlText is not a Y.XmlFragment, so text is checked first; Y.XmlElement is a Y.XmlFragment, so placeholder elements fall through to recursion. Placeholder-only trees return true; real text or non-placeholder blocks return false.
  • onServerError re-joins once at a time (resyncing guard, 1 s delay) and applies the result; applyJoin re-sends the client's missing state.

Nits (non-blocking)

  • room.bytes is incremented before Y.applyUpdate; a failed apply leaves the counter slightly high (conservative, bounded).
  • buckets is only cleared on leaveAll, not on a single leave; minor memory retention.

All prior Pullfrog threads remain resolved.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

@pikann
pikann merged commit 31d75c4 into master Nov 10, 2026
4 checks passed
@pikann
pikann deleted the feature/implement-realtime-collaborative-editing branch November 10, 2026 10:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant