Skip to content

feat: implement external write handling in collaborative editing - #724

Merged
pikann merged 7 commits into
masterfrom
feature/implement-external-write-handling-in-collaborative-editing
Nov 10, 2026
Merged

pikann merged 7 commits into
masterfrom
feature/implement-external-write-handling-in-collaborative-editing

Conversation

@pikann

@pikann pikann commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Problem

When an agent (or MCP / a script) saves a doc or task description over REST while people are editing it, the live Yjs room never sees that write, and the editors' next save overwrites it. Neither side is told, and the agent's change is lost.

Change

services/realtime now folds such writes into the live room.

  • The API already announces doc.updated / task.updated with the changed field's old and new BlockNote JSON, so no API change is needed. subscriber.ts hands those events to CollabHub.handleContentEvent.
  • collab-blocks.ts (new) does a block-level three-way merge: base = old content, theirs = new content, ours = the live Y.Doc.
    • Added blocks are inserted after their previous sibling.
    • Changed blocks are replaced, and removed blocks deleted, only while the room's copy is still what it was before the write. A block someone edited live keeps their version (logged as a conflict) and their next save stores it.
    • Only the affected block nodes are touched, so other edits and cursors are unaffected.
    • Stored blocks do not need ids (the API only requires type), so missing or invented ids are recovered by aligning siblings on content.
  • CollabHub.applyExternal applies the merge in one transaction and broadcasts the diff to every editor. It is a no-op when the room is not open or not seeded yet.
  • The merge waits for editor updates already received but still in their access check, and external writes count against the room's byte budget.
  • Ids are rarely present (web saves strip them), so alignment is the normal path; a gap of leftover blocks is paired only when both sides have equally many.
  • An event whose actor is an account currently in the room is ignored: it is that editor's own save coming back.
  • Adds @blocknote/core to the realtime service, with server-side stub specs for the custom blocks and inline contents. These must stay in sync with apps/web/src/components/shared/blocknote-schema.tsx.
  • README: the old "REST writes are not merged" note is replaced with the new behaviour and its limits.

Known limits

  • Moves and reorders are not merged.
  • A user's own REST/MCP writes while that user is in the room are not merged live (the actor filter treats them as the editor's save).
  • The stored copy keeps the agent's version until an editor next saves. An editor save that races the merge by a few milliseconds can still overwrite the agent's write in the database. Closing that needs a version check on the REST update, which is a follow-up.
  • The non-collab fallback editor is unchanged.

Testing

  • bun test in services/realtime (79 pass), tsc --noEmit, biome check.
  • New tests: merge scenarios (live edit preserved elsewhere, conflict kept, editor-save echo is a no-op, inserts, guarded deletes, id-less and invented ids, nested blocks, empty-doc fill), hub behaviour (broadcast to all, ignore own save, no room, no-op merge) and the subscriber hook.
  • Not yet exercised against a real API, Valkey or browser.

- Added support for merging external writes (from agents or REST) into live collaborative rooms.
- Introduced `mergeExternalChange` function to handle block-level three-way merges.
- Created tests for various scenarios of external writes, including conflict resolution and block insertion.
- Updated `CollabHub` to process `doc.updated` and `task.updated` events, applying changes to the Y.Doc.
- Enhanced the subscriber to route content change events to the collaboration logic.
- Added utility functions for parsing content changes from event payloads.

@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 block-level merge approach is sound, but two correctness edges can silently drop a block (an editor's keystroke, or an agent's inserted block) and the external path skips the room's size budget. Details inline.

Reviewed changes

Full read of the diff at 9eac4f4, cross-checked against the API's activity payloads (services/api/internal/service/activity/service.go), the web BlockNote schema and the client save path.

  • Block merge (collab-blocks.ts, new) — three-way merge of the event's old/new BlockNote JSON into the live Y.Doc: id recovery by content alignment, inserts after the previous sibling, guarded replace/delete, conflicts keeping the room's copy, all in one transaction. Server-side stub specs mirror the web schema.
  • Hub integration (collab.ts) — parseContentChange reads doc.updated.content / task.updated.description out of the activity payload; handleContentEvent/applyExternal skip when no room exists, when the room is unseeded, or when the actor is a room member, then broadcast the diff to every editor.
  • Subscriber — optional onContentChange invoked from routeEvent for the two topics, wired to the hub in index.ts.
  • Dependency and docs — @blocknote/[email protected] added to services/realtime; README replaces the "REST writes are not merged" note with the new behaviour and its limits.
  • Tests — merge scenarios (live edit preserved, conflict, editor echo, inserts, guarded deletes, id-less/invented ids, nesting, empty-doc fill), hub broadcast/actor/no-room cases, and the subscriber routing hook.

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

@pullfrog

pullfrog Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Line-level findings (the details referenced in the review above; inline anchoring failed on submit, so they are collected here)

⚠️ resolveIds gap pairing can swap an inserted block with a modified one

services/realtime/src/collab-blocks.ts:259-270 pairs leftover base blocks with leftover target blocks positionally whenever their type matches. An external write that inserts a block and edits a neighbour in the same gap therefore gives the inserted block the edited block's id: with base = [A, B] and theirs = [X, A', B] (X prepended, A edited), X inherits A's id and A' gets a fresh one. If the room's A was edited live, the changed-block guard (:382-390) drops X and inserts the fresh-id A' instead — the insertion is lost and the agent's conflicting copy of A is kept, the opposite of "ours wins".

This is not a fallback path: cleanBlocks (apps/web/src/lib/utils.ts:10) strips block ids from every web save, so base/theirs normally arrive with no ids and content alignment is always exercised. Only pairing a gap positionally when the leftover counts match, and treating surplus targets as additions / surplus base blocks as removals otherwise, would keep the insertion. A test for [A, B] -> [X, A', B] with A edited live would fail today.

⚠️ External merges race in-flight client updates

services/realtime/src/collab.ts:449-455 reads and mutates room.doc synchronously from the Valkey callback, while a client's update reaches Y.applyUpdate only after update()'s queued job awaits canWrite (:347-373) — an API round trip whenever the 30 s decision cache misses (access.ts:72-92). An update in flight when the merge runs is invisible to the "the room's copy still equals base" guard, so the merge replaces that block's content node and the pending update then applies to the deleted node: the editor's keystrokes disappear from the room and from every peer (their broadcast lands after the merge and has no visible effect). Serializing applyExternal behind the room's update ordering, or listing this next to the database race in "Known limits", would close it.

ℹ️ External writes bypass the room byte budget

services/realtime/src/collab.ts:456-458 adds to room.bytes with no MAX_ROOM_BYTES check, while update() (:363-367) refuses updates past the cap. The "64 MB of accepted updates per room" limit in the README therefore only bounds editor traffic, and since room.bytes is a lifetime sum a write loop can grow the room's Y.Doc without limit. The check has to happen before the merge — after the transaction there is nothing left to refuse.

Pullfrog  | View workflow run | via Pullfrog | 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.

✅ No new issues found.

Reviewed changes

This run reviewed the delta since the prior pullfrog review at 9eac4f4 (commit be9469f), which resolves all three earlier findings.

  • Id recovery tightened — resolveIds now pairs a gap of leftover blocks positionally only when both sides have equally many left, so an inserted block can no longer inherit an edited neighbour's id. A regression test covers [A, B] -> [X, A', B] with a live edit on A.
  • External merges serialized and ordered after pending edits — handleContentEvent chains merges per room via externalChains, and applyExternal now awaits editor updates still waiting on their access check before reading the room, so in-flight keystrokes land first. A test holds an update on the access gate and asserts the merge sees it.
  • Byte budget applied to external writes — applyExternal checks MAX_ROOM_BYTES against the new content before merging and counts the emitted update bytes afterwards, with a test that spends the budget first.
  • Docs updated — the realtime README now describes the pending-update wait and the shared byte budget.

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.

ℹ️ No critical issues — minor docs and test suggestions inline.

Reviewed changes

This run reviewed the delta since the prior pullfrog review at be9469f (commit fc4994a).

  • Similarity pairing for id-less gaps — align now pairs a leftover gap with unequal counts using pairBySimilarity (shared text prefix/suffix, SIMILAR = 0.5) instead of leaving it unpaired, so an id-less save can change a block while the room carries BlockNote's trailing empty block; equal-count gaps keep positional pairing.
  • Unit coverage — two new cases cover a live edit with id-less stored content and a live edit next to the trailing empty paragraph.
  • E2E coverage — new feature scenarios and a spec cover an agent's REST write reaching both editors, a live edit surviving the write, an id-less insert, and a task description.

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

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 the delta since the prior pullfrog review at fc4994a (commit 440b03b), which addresses the three earlier minor suggestions.

  • README merge rules corrected — the id-recovery bullet now describes equal-count positional pairing and similarity pairing for unequal gaps, matching align / pairBySimilarity.
  • Live-edit coverage for the id-less insert scenario — the feature scenario and spec now type LIVE- into the first paragraph with saves held, then assert the member's text survives the agent's insert.
  • Deterministic stored-doc assertion — the agent-write spec now makes a local edit after releasing the held save so the merged document is persisted, instead of assuming the debounce beats the merge.

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.

ℹ️ No critical issues — minor suggestions inline.

Reviewed changes

This run reviewed the delta since the prior pullfrog review at 440b03b (commit cbf9bf5), which hardens the external-write merge against duplicate inserts and unbounded alignment work.

  • Added seed-race dedupe — mergeExternalChange returns early when the room's shape already matches the write, and insertBlock skips an added block when a same-shaped sibling exists that old and new do not know.
  • Capped alignment work per merge — MAX_ALIGN_CELLS is now a shared budget across both resolveIds passes and every recursion level, and the LCS and similarity tables use typed arrays.
  • Stopped hoisting inserts whose parent was deleted live — such a block is dropped and counted as a conflict instead of landing at the document root.
  • Required four characters before two blocks pair by similarity — MIN_SIMILAR_LEN keeps very short blocks from being taken for edits of each other.
  • Split merge notices from errors — conflicts and skips now go through a new onNotice (info) callback wired in server.ts; unexpected errors keep onError.
  • Extended unit coverage — seed-race dedupe, repeated and short-block cases, plus a schema-name parity check against the web editor schema.

ℹ️ Schema drift guard never runs in CI

collab-blocks.test.ts now reads apps/web/src/components/shared/blocknote-schema.tsx to catch stub-schema drift, but realtime-pr-ci.yml only runs Biome, tsc and the Docker build, and its path filter covers services/realtime/** alone. A web schema change therefore cannot fail the realtime workflow, so the guard only fires when someone runs bun test locally.

Technical details
# Schema drift guard not gated by CI

## Affected sites
- `.github/workflows/realtime-pr-ci.yml:49-56` — no `bun test` step.
- `.github/workflows/realtime-pr-ci.yml:5-7` — path filter excludes the web schema.
- `services/realtime/src/collab-blocks.test.ts:280-298` — the parity assertion.

## Required outcome
- A drift between the stub specs and the web schema fails a required check (add a test step and include the web schema file in the path filter).

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-blocks.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.

ℹ️ No critical issues — minor suggestions inline.

Reviewed changes

This run reviewed the delta since the prior pullfrog review at cbf9bf5 (commit 8e3ee3c), which closes the two inline findings and the CI-gating gap.

  • Position-aware dedupe — a candidate room block must sit immediately after the previous sibling's room copy and is consumed at most once, so identical additions are no longer collapsed onto one live sibling; skipped additions are counted as duplicates and surfaced through onNotice, and their children are no longer descended into.
  • New merge tests — the short-block case now uses an unequal gap with a live edit so it exercises MIN_SIMILAR_LEN, plus cases for a blank-paragraph insert, repeated identical additions, and the seeded collapse.
  • Test gate in CI — realtime-pr-ci.yml now runs bun test and triggers on the web editor schema, so stub-schema drift fails a check.

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-blocks.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.

✅ No new issues found.

Reviewed changes

This run reviewed the delta since the prior pullfrog review at 8e3ee3c (commit 5bfcd4d), which closes the one open thread from that review.

  • Insert anchor resolves deduped siblings — in insertBlock, the scan for a previous surviving sibling now maps each siblings[k].id through alias before looking it up in the room's group, so an addition that follows a deduplicated addition is inserted after the room's copy of it instead of before it.
  • Regression test — a new merge case (old [alpha], new [alpha, TODO, NEW], room [alpha, TODO, tail]) asserts one duplicate, no conflicts, and the write's order alpha, TODO, NEW, tail.

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

@pikann
pikann merged commit 133fdb0 into master Nov 10, 2026
3 checks passed
@pikann
pikann deleted the feature/implement-external-write-handling-in-collaborative-editing branch November 10, 2026 14:36
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