# Collaboration

> Connect Revise to your own Yjs transport and participate from Node with revise/server.

Every document is a [Yjs](https://yjs.dev) CRDT. Carets, presence, tracked changes, comments, and DOCX export work across concurrent editors. The SDK opens no sockets; your application owns the transport, auth, and persistence.

```tsx
import { HocuspocusProvider } from "@hocuspocus/provider";

const provider = new HocuspocusProvider({
  url: "wss://collab.example.com",
  name: "contract-1",
});

<ReviseEditor
  currentUser={{ id: user.id, name: user.name, image: user.avatarUrl }}
  initialDocuments={[
    {
      id: "contract-1",
      source: file,
      collaboration: { provider, synced },
    },
  ]}
/>;
```

## One copy of Yjs

Yjs checks types with `instanceof`, so your app and `revise` must resolve the same `yjs` instance (`npm ls yjs` must show one copy). Otherwise seeding throws `Unexpected content type in insert operation`.

In Vite:

```ts vite.config.ts
export default defineConfig({
  resolve: { dedupe: ["yjs", "y-protocols"] },
  optimizeDeps: { exclude: ["revise", "yjs", "y-protocols"] },
});
```

## Connect callback

The editor reserves eight top-level `Y.Doc` keys (`content`, `chrome`, `notes`, `comments`, `annotations`, `metadata`, `sdt-wrappers`, `paragraphs`). The recommended pattern lets the editor construct the `Y.Doc` and `Awareness` and pass them to your `connect` callback:

```ts
collaboration: {
  connect: (doc, awareness) =>
    new HocuspocusProvider({ url, name: "contract-1", document: doc, awareness }),
  synced,
}
```

Return the provider so the editor can identify remote transaction origins.

## Supplying a Y.Doc

When a transport creates its own `Y.Doc`, pass `provider` or explicit `{ ydoc, awareness, remoteOrigin }`:

```ts
collaboration: { provider } // reads document/doc/getYDoc() + awareness
collaboration: {
  ydoc,
  awareness,                 // omit or null to disable presence
  remoteOrigin: myTransport, // required when passing ydoc without provider
  synced: isSynced,
  seed: "if-empty",
}
```

Before writing, the editor validates the supplied `Y.Doc`:
- **Empty:** seeded (if `seed === "if-empty"`).
- **Existing Revise document:** joined.
- **Conflicting data under any reserved key:** rejected with an error naming the key. Keep non-Revise room state in a separate `Y.Doc`.

<Warning>
  The explicit `ydoc` form requires `remoteOrigin`: the transaction origin
  passed to `Y.applyUpdate`. Without it, peer edits are treated as local,
  breaking cursor restoration and undo isolation. Wrap transports that use a
  `null` origin.
</Warning>

## Seeding and sync state

| `seed` | Behavior |
| --- | --- |
| `"if-empty"` (default) | Writes `source` into an empty room; ignores `source` if content already exists. |
| `"never"` | Always joins; `source` may be omitted. |

Set `synced` to `true` after the initial sync completes. Until `synced` is `true`, the document stays closed rather than rendering an empty editable page or double-seeding:

```tsx
const [synced, setSynced] = useState(false);

useEffect(() => {
  provider.on("synced", () => setSynced(true));
}, [provider]);
```

Subsequent disconnects do not close the document; Yjs merges offline edits on reconnect and only presence is affected. Omitting `synced` opens immediately (and allows concurrent initial seeds).

## Presence and roster

Remote carets and `editor.collaboration` use `currentUser`:

```tsx
<ReviseEditor
  currentUser={{
    id: user.id,
    name: user.name,
    email: user.email,
    image: user.avatarUrl,  // URL or data: URI for caret flag
    color: user.brandColor, // optional; derived deterministically from id if omitted
  }}
/>
```

```ts
const { enabled, synced, peers } = editor.collaboration.getState();
// peers: [{ clientId, isLocal, id, name, email, image, color }]
useEffect(() => editor.collaboration.subscribe(setPresence), [editor]);
```

Participants without `currentUser` do not appear in `peers` or remote carets, and their tracked changes export authored by `"Anonymous"`.

## Server editing

[`revise/server`](https://revise.io/developer/docs/editor-sdk/api/backend) (bundled in `revise`) lets a Node server read, edit, seed, and export live Yjs rooms using the same converters and tool runtime as the browser. See the [library](https://revise.io/developer/docs/editor-sdk/api/library) and [server collaboration](https://revise.io/developer/docs/editor-sdk/api/server-collaboration) references for the complete API.

### Stored table proposals

Documents persisted before 4.2 with table proposals require a one-time migration into the review store (`tableRecordsMigrated`). Because browser clients connected to an external provider do not auto-migrate, call `migrateDocument(ydoc)` on the server after loading stored state and before serving clients (idempotent; run under a lock if multiple processes load the same room):

```ts
import { migrateDocument } from "revise/server";

migrateDocument(ydoc);
```

### Seeding from your own server

Seed rooms server-side so browser clients can pass `seed: "never"` with no `source`:

```ts
import * as Y from "yjs";
import { ReviseDocument, seedYDoc } from "revise/server";

// Safe on every load: leaves populated rooms untouched and repairs seed races.
await seedYDoc(ydoc, { bytes: docxBytes, filename: "agreement.docx" });

// Persist state as standard Yjs update bytes:
await store.put(roomId, Y.encodeStateAsUpdate(ydoc));

// Export without a browser (retains original .docx bytes for untouched content):
const doc = await ReviseDocument.fromYDoc(ydoc);
const { bytes } = await doc.export({ format: "docx" });
doc.dispose(); // does not destroy ydoc
```

### Editing a live room

```ts
import { ReviseDocument } from "revise/server";

const doc = await ReviseDocument.fromYDoc(ydoc, {
  documentId: "agreement-1",
  author: "Review bot",
});
try {
  // Suggesting mode by default: peers see tracked changes live.
  const edit = await doc.tools.call("replace", {
    search_result_id: searchResultId,
    replacements: [{ find: "Delaware", replace: "New York" }],
  });
  if (edit.ok) await notifyReviewers(edit.value.suggestionIds ?? []);
} finally {
  doc.dispose();
}
```

Pass `mode: "editing"` or `{ directMode: true }` to apply edits directly.

### Review across server and browser

`doc.tools.call()` and `editor.tools.execute()` return the same `ReviseToolResult` and `suggestionIds`. IDs created on the server can be settled in the browser via `editor.review.acceptSuggestions(ids)`, and human suggestions created in the browser can be inspected/settled on the server via `await doc.changes()`, `doc.accept({ ids })`, or `doc.reject({ ids })`.

### Working without a live transport

For stateless HTTP or queue workers, send an encoded Yjs state update and merge back only the delta:

```ts
// Client
const response = await api.review({ update: Y.encodeStateAsUpdate(ydoc) });
Y.applyUpdate(ydoc, response.delta, "my-backend");

// Server
import * as Y from "yjs";
import { ReviseDocument } from "revise/server";

const doc = await ReviseDocument.restore(update);
const baseline = Y.encodeStateVector(doc.ydoc);
// ...run tools...
const delta = Y.encodeStateAsUpdate(doc.ydoc, baseline);
doc.dispose();
```

## Boundaries

- **No network transport:** Sockets, auth, retries, and backoff belong to your provider.
- **No persistence:** Your server manages storage.
- **Non-destructive:** Unmounting clears local awareness without destroying a caller-supplied `Y.Doc`.
- **No server-side authz:** [Roles](https://revise.io/developer/docs/editor-sdk/guides/roles) are client-side only; enforce write permissions in your sync server.
