> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tuturuuu.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Docs realtime co-editing

> Evaluate Cloudflare Yjs co-editing for workspace documents and define the rollout gates.

## Decision

Extend the shared Meet document transport and TipTap bindings into a
Docs-scoped Cloudflare Worker and SQLite Durable Object room. Hold enablement
until Docs has one content writer per document and a tested recovery path.
Meet already co-edits its primary document and checkpoints into
`workspace_documents`. Standalone Docs opens that table through a JSON editor
and REST autosave. Sharing the table leaves the two editors competing for the
same content if both are writable.

## Repository evidence

| Surface | Behavior |
| - | - |
| Docs editor and API | `RichTextEditor` receives content, onChange and a flush callback. The editor's 500 ms debounce leads to a serialized TipTap JSON PATCH. The workspace handler checks membership and `manage_documents`, then updates by workspace and document with no expected revision predicate. Inventory the legacy document endpoint too before fencing writes. [Docs editor:213](https://github.com/tutur3u/platform/blob/4e3709499d/apps/web/src/app/%5Blocale%5D/%28dashboard%29/%5BwsId%5D/documents/%5BdocumentId%5D/document-editor.tsx#L213-L273), [editor bindings:428](https://github.com/tutur3u/platform/blob/4e3709499d/apps/web/src/app/%5Blocale%5D/%28dashboard%29/%5BwsId%5D/documents/%5BdocumentId%5D/document-editor.tsx#L428-L439), [workspace PATCH:37](https://github.com/tutur3u/platform/blob/4e3709499d/apps/web/src/app/api/v1/workspaces/%5BwsId%5D/documents/%5BdocumentId%5D/route.ts#L37-L117), [legacy update:118](https://github.com/tutur3u/platform/blob/4e3709499d/apps/web/src/legacy-api-routes/v1/documents/%5BdocumentId%5D/route.ts#L118-L130) |
| Shared UI and realtime | UI depends on TipTap Collaboration and CollaborationCaret. The extension builder wires the Y.Doc and caret provider and disables standalone undo for collab. The editor suppresses debounced REST callbacks in collaboration mode. `CloudflareDocumentProvider` batches Yjs updates and awareness, tracks checkpoint status, and sends retained in-memory state on reconnect. Task descriptions use a Cloudflare channel through a separate hook with client load/save callbacks. [UI package:87](https://github.com/tutur3u/platform/blob/4e3709499d/packages/ui/package.json#L87-L88), [extensions:102](https://github.com/tutur3u/platform/blob/4e3709499d/packages/ui/src/components/ui/text-editor/extensions.ts#L102-L125), [editor:366](https://github.com/tutur3u/platform/blob/4e3709499d/packages/ui/src/components/ui/text-editor/editor.tsx#L366-L391), [provider:13](https://github.com/tutur3u/platform/blob/4e3709499d/packages/realtime/src/documents/provider.ts#L13-L124), [task caller:573](https://github.com/tutur3u/platform/blob/4e3709499d/packages/tasks-ui/src/tu-do/shared/task-edit-dialog.tsx#L573) |
| Meet Worker and admission | `CHANNEL_ROOM` binds a SQLite Durable Object. The Meet join resolves the document from room admission and signs a short-lived ticket against its topic. The Meet editor instantiates the shared provider. The room caps updates and merged state at 512 KiB and normalizes awareness against the socket ticket. [Worker binding:28](https://github.com/tutur3u/platform/blob/4e3709499d/apps/meet-realtime/wrangler.jsonc#L28), [Meet admission:93](https://github.com/tutur3u/platform/blob/4e3709499d/packages/meet-core/src/features/call/server/documents.ts#L93-L168), [Meet editor:134](https://github.com/tutur3u/platform/blob/4e3709499d/packages/meet-core/src/features/call/components/document-editor.tsx#L134), [channel room:220](https://github.com/tutur3u/platform/blob/4e3709499d/apps/meet-realtime/src/channel-room-do.ts#L220-L267) |
| Meet checkpoint | The room batches local state persistence at about one second and uses hashes, a checkpoint deadline and a persisted retry budget when no editor is active. Only the primary room posts to Web. The endpoint checks the signed Meet topic, document, owner and version, verifies the hash and projects the `prosemirror` fragment to JSON. SQL links the private meeting row to the workspace document, refuses stale or conflicting writes and detects outside content changes. The private row holds the latest checkpoint. [Room cadence:374](https://github.com/tutur3u/platform/blob/4e3709499d/apps/meet-realtime/src/channel-room-do.ts#L374-L439), [checkpoint:19](https://github.com/tutur3u/platform/blob/4e3709499d/apps/web/src/app/api/v1/realtime/documents/checkpoint/route.ts#L19-L78), [projection:3](https://github.com/tutur3u/platform/blob/4e3709499d/packages/realtime/src/documents/server.ts#L3-L10), [meeting SQL:1](https://github.com/tutur3u/platform/blob/4e3709499d/apps/database/supabase/migrations/20261004141205_meeting_documents.sql#L1-L50) |
| Hive | Its Bun socket server loads server-scoped CRDT snapshots and persists merged Yjs state through Hive's own database adapter. Reuse the idea of a scoped snapshot and merge, with storage and admission owned by Docs. [Hive server:97](https://github.com/tutur3u/platform/blob/4e3709499d/apps/hive-realtime/src/server.ts#L97-L119), [Bun listener:233](https://github.com/tutur3u/platform/blob/4e3709499d/apps/hive-realtime/src/server.ts#L233), [Hive persistence:125](https://github.com/tutur3u/platform/blob/4e3709499d/apps/hive-realtime/src/hive-db.ts#L125-L148) |
| Chat and Colab | Chat's hibernating rooms illustrate stop checks at ingress and alarm execution and durable admission revocation. Colab uses a SQLite DO and hibernating sockets for workshop state and budgets. Its `packages/multiplayer` models workshops, teams and runs. These supply lifecycle examples. Meet supplies the rich-text transport. [Chat room:37](https://github.com/tutur3u/platform/blob/4e3709499d/apps/chat-realtime/src/room.ts#L37-L58), [Chat alarm:140](https://github.com/tutur3u/platform/blob/4e3709499d/apps/chat-realtime/src/room.ts#L133-L152), [Chat revocation:20](https://github.com/tutur3u/platform/blob/4e3709499d/apps/chat-realtime/src/room-admission.ts#L20-L37), [Colab room:25](https://github.com/tutur3u/platform/blob/4e3709499d/apps/colab/src/server/room.ts#L25-L40), [Colab sockets:553](https://github.com/tutur3u/platform/blob/4e3709499d/apps/colab/src/server/room.ts#L553-L571), [Multiplayer:24](https://github.com/tutur3u/platform/blob/4e3709499d/packages/multiplayer/src/index.ts#L24-L81) |

## Docs integration

1. **Authorization and isolation.** Authenticate the workspace session and
   resolve the document, membership and current edit permission before minting
   a ticket. Bind the audience, workspace, document, room epoch, actor, role and
   expiry. Start with authenticated editors only. Keep existing public views on
   the JSON projection. Give the Worker a separate service identity and restrict
   origins. Validate tickets again on renewal and use a revocation fence for
   removal, permission loss, deletion and epoch changes, including sockets
   already open. Load testing must include permission expiry while idle.
2. **One writer and one seed.** Atomically select a content mode and epoch
   against the row revision. Bootstrap a Y.Doc once from persisted content by
   parsing legacy JSON strings, JSON objects and empty content with the Docs
   TipTap schema. Use the same fragment in the editor and projector and prove
   round-trip parity for citations, inline metadata, images, tables and Markdown
   import. While the room owns content, reject all REST content writes,
   including delayed requests and the retry button, with an actionable conflict.
   Keep metadata updates on REST. Check ownership inside the content transaction
   so concurrent PATCH, deletion and mode changes cannot race the guard. Exclude
   Meet-owned rows from the Docs pilot. For those rows, resolve one writer or
   expose a read-only Docs view before admitting them.
3. **Durable state and publication.** Persist accepted CRDT updates before
   acknowledging durability. Coalesce them in the room for up to one second,
   use bounded compaction, and keep a durable cursor and dirty marker. Project
   the latest durable cursor to `workspace_documents.content` on a 30-second
   minimum cadence while dirty. Atomically compare epoch, cursor and hash in the
   database. A retry after a lost response returns the same result. A stale
   epoch, deleted row, unsupported schema or conflicting write ends the attempt
   and surfaces a recoverable state. Define separate UI states for offline
   edits, room durability and workspace publication. Existing readers, search
   and exports may lag by the checkpoint cadence. A user action requiring fresh
   content can wait for its target cursor within the same budget.
4. **Presence and offline.** Reuse Awareness and collaboration carets. Bind
   display identity to the authenticated connection and use document-scoped
   aliases. Coalesce cursors, remove them on expiry or disconnect and reserve
   durable storage for content. For the first pilot, retain pending edits while
   the tab lives, reconcile with the room on reconnect, and show an unsent state
   plus a download path before closing. Add browser persistence only after
   per-user/workspace/epoch isolation, quotas, logout cleanup, revocation and
   stale-epoch recovery are tested. Reconnecting to a new epoch can recover
   drafts into a copy after permission checks. Keep old updates out of the
   current room.
5. **Version history.** Meet's checkpoint revision orders synchronization. The
   inspected standalone PATCH writes a row without an immutable revision. Use
   the Docs history contract when available, keeping checkpoint cursors and
   user-visible revisions independent. A named save or an explicitly defined
   history interval captures a durable cursor into an immutable JSON snapshot
   once, with authenticated attribution. A restore should first preserve the
   current revision, then serialize the restore through the room as a new
   revision under a fresh epoch, with stale clients fenced before rejoining.
   Use the same ownership guard if Office revisions ship before co-editing,
   and verify REST-only edit/history behavior for documents outside the pilot.

## Pilot cost and shutdown gates

Treat these as starting limits for a private pilot. Enforce a finite admission
lease, at most 20 allowlisted rooms and eight sockets per room, a 64 KiB inbound
update, a 512 KiB merged snapshot, and a bounded update journal and resync
payload. Charge all accepted messages and recipients against operation and byte
budgets before merging or sending. Bound admission and renewal, awareness,
outbound messages and logging separately. Throttle presence first, then stop
accepting edits with a visible capacity status. Track daily room and pilot-wide
operation budgets, including rejected-work overhead. Set their numeric limits
from counted runtime evidence before enablement. Keep the Worker route
allowlisted and time-limited to bound ingress exposure.

Use one scheduled deadline per room, at most one checkpoint in flight, and at
most three reserved outbound checkpoint attempts over two minutes per failure
episode, including while editors are connected. Persist reservations before
outbound work. Rejoins, duplicates and restarts cannot refill the episode.
Successful cursor advancement clears it. Use an explicit operator recovery
path for exhausted state. Empty clean, exhausted, stopped and expired rooms
schedule no further work. Model idle baseline, active rooms and sustained
failure using actual billed requests, fanout, duration, alarm invocations,
storage reads/writes and downstream checkpoint calls. Record the envelope at
approved capacity in the adoption runbook before enabling the Worker.
See the [Cloudflare cost and stop controls](https://docs.tuturuuu.com/build/development-tools/oxc-cloudflare-adoption.md).

Use a service ingress switch and a durable stop epoch. The authenticated stop
operation persists the fence, closes sockets, cancels alarms and leaves accepted
updates recoverable. Each upgrade, message, retry, outbound call and alarm
reschedule checks it. The database checks the same epoch at commit time so a
request already in flight cannot publish after fencing. Stop must work with
Web ingress disabled. A controlled handoff can pause edits, drain the durable
cursor under the old ownership, verify the published hash, then fence and
return the row to REST in a new epoch. An emergency stop freezes writes for
recovery if any acknowledged edit remains unpublished. Preserve that state
until a reviewed recovery reconciles it.

## Phased acceptance

| Phase | Gate |
| - | - |
| 0. Contract and inventory | List every content writer and reader. Agree on schema compatibility, edit authorization, history and REST handoff. Hold mixed Meet and standalone rows until the owner is explicit. |
| 1. Isolated prototype | Loopback Worker and DO with disposable actors and storage. Two concurrent editors converge. Test load during seed, a stale PATCH during handoff, duplicate and out-of-order updates, reconnect, worker eviction, revocation, deletion, schema mismatch, and a round-trip of existing Docs content. |
| 2. Recovery and cost qualification | Count operations through real local alarms and injected DB failures, including stop racing an outbound call and a reschedule. Prove stable retry counts across restarts, no post-stop writes, idle quiescence, and restore with stale clients. Run exact-commit CI and staging against the emitted Worker. |
| 3. Limited workspace pilot | Flag a small set of internal documents. Measure convergence, lag, rejected updates, unresolved conflicts and billable operations. Drill shutdown and verified handoff from the staged artifact before expanding. |

Main risks are dual authority, schema drift, reconnect loss, stale access and
bill amplification from presence or retry loops. Keep standalone REST editing
as the default until the pilot gates and recovery drill pass.

## Local runtime drill

Run from the repository root with Bun, Node, Wrangler, and PostgreSQL client
and server binaries (`initdb`, `pg_ctl`, and `psql`) on `PATH`. The test uses a
private PostgreSQL cluster and applies the pilot migration to the fixture
document tables. It never uses an existing Supabase connection.

```sh theme={null}
DOCS_REALTIME_PROXY_DRILL=1 ttr resources run -- bun x vitest run --root apps/web \
  --config vitest.config.mts docs-realtime-proxy.test.ts --maxWorkers 1
bun x vitest run --root apps/web --config vitest.config.mts \
  src/lib/documents/realtime-content.test.ts --maxWorkers 1
```

The drill starts Wrangler in local mode at `127.0.0.1:8794`. The callback
fixture listens at `127.0.0.1:8795` and PostgreSQL uses socket `8796` in the
temporary directory with TCP disabled. The script generates disposable room IDs
and signing credentials. Wrangler restarts reuse the isolated SQLite state.
The script stops each Wrangler process by its recorded handle and stops the
disposable PostgreSQL cluster by its data directory. Its `finally` block closes
the clients and removes its temporary state. Allow four minutes for the
publication and failure windows.

The Worker, WebSocket handling, Durable Object storage, alarms and SQL fences
are real. The Web proxy bridge at `127.0.0.1:8798` runs Web proxy handlers
before forwarding admitted callbacks to the disposable SQL fixture. Staging qualification must exercise the Web auth and service
routes, cookie and origin policy, the full database migration chain, and the
emitted Worker against staging. See the
[Cloudflare rollout and operation accounting](https://docs.tuturuuu.com/build/development-tools/oxc-cloudflare-adoption.md#docs-realtime-pilot).

The seed fidelity tests exercise existing Docs schema attributes, citation
snapshots and locators, images, table markup, and Markdown import. Inputs with
unsupported nodes or fields remain outside live editing. The pilot uses an
accept-once epoch rather than a rolling session. A new tab can join the active
epoch, and each renewal rechecks workspace access. A revoked member may retain
a ticket for at most 60 seconds. Emergency revocation stops the full room.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.