# Collaboration

> Synchronise annotations, form values, page structure and presence between reviewers over your own transport, with fixed conflict rules and a reference relay server.

Several people can work on the same PDF at once. The package turns local changes into small JSON messages, merges the messages of others with fixed rules, and leaves the transport to you: a WebSocket, Server-Sent Events, WebRTC or a message bus all work, because messages may arrive late, twice or out of order.

There are four channels:

| Channel | Carries | Kept for late joiners |
| --- | --- | --- |
| `annotations` | add, update, remove and replies | yes |
| `forms` | one value per form field | yes |
| `pages` | rotate, delete, reorder, insert blank page | yes |
| `presence` | who is there, the page they look at, cursor and selection | no |

## Connect the viewer

Wrap your connection in a transport with `send` and `subscribe`, and pass `createSyncChannel(transport)` as `annotationSync`:

```ts
import { createPdfViewer, createSyncChannel, type SyncTransport } from '@birchui/pdf';

declare const bytes: Uint8Array;
declare const socket: WebSocket;

const transport: SyncTransport = {
  actorId: crypto.randomUUID(),
  send: (message) => socket.send(JSON.stringify(message)),
  subscribe(receive) {
    const onMessage = (event: MessageEvent<string>) => receive(JSON.parse(event.data));
    socket.addEventListener('message', onMessage);
    return () => socket.removeEventListener('message', onMessage);
  },
};

const viewer = createPdfViewer(document.querySelector<HTMLElement>('#review')!, {
  document: bytes,
  currentUser: { name: 'Dana Whitfield', id: 'u-17' },
  annotationSync: createSyncChannel(transport, {
    onPresenceChange: (collaborators) => console.info(collaborators.map((peer) => peer.name)),
  }),
});

const reviewers = viewer.getCollaborators();
```

A message is `{ channel, operations }`, or `{ channel: 'presence', message }`. `actorId` must be unique per open viewer, not per user: one person with two tabs is two actors. `createSyncChannel` accepts `channels` to switch some off (`['annotations', 'presence']` behaves like earlier versions), `actorId`, `color`, `snapshot`, `presenceTimeout`, `onConflict` and `onPresenceChange`.

The viewer starts listening when the document has loaded. Messages your transport delivers before that are lost unless the transport holds them back; the relay client below does.

`annotationSync` also still accepts a hand-written channel object. The annotation and cursor callbacks are described under [Real-time sync](https://docs.birchui.com/pdf/annotations.md#real-time-sync); the other channels are the optional members `sendFormValues` and `onRemoteFormValues`, `sendPageOperations` and `onRemotePageOperations`, with `onFormConflict`, `onPageConflict`, `onPresenceChange` and `presenceTimeout`. A channel without them synchronises annotations and cursors only, exactly as before.

## Conflict rules

Every operation carries a logical clock `{ counter, actor }`. A higher counter is later; equal counters are decided by comparing the actor ids. The rules are the same on every peer, so all peers end with the same document once they have seen the same operations.

| Channel | Rule |
| --- | --- |
| Annotations | The latest write wins per property group of an annotation; a removal beats every update. See [Real-time sync](https://docs.birchui.com/pdf/annotations.md#real-time-sync). |
| Form values | The latest write wins per field. Calculated fields are not sent; each peer recalculates them. |
| Page rotation | The latest absolute rotation wins per page. |
| Page order | Each page has a position key between its neighbours. The latest position wins per page; pages with the same key are ordered by page id. |
| Page deletion | Deletion wins over every concurrent or later rotate and move of that page and is final. |
| Blank-page insert | Every insert is kept. Two inserts at the same place both appear, in the same order everywhere. |
| Presence | The newest message of each peer wins by the sender's timestamp; a leave message wins a tie. A peer that is silent for `presenceTimeout` (30 s) is dropped. |

### Form values

A change made with the keyboard, `setFormValue`, an import, a reset or undo is sent as `{ kind: 'set', field, value, clock }`. Incoming values are applied through `setFieldValues` with `source: 'remote'`, so formatting and calculations run as for a local fill and `formFieldChange` fires for each field that changed. `onFormConflict` is called when an incoming value loses to a later one from someone else.

A remote value is a step on the local undo stack. Undoing it restores the previous value and sends that as a new write.

### Page structure

Pages are addressed by a stable id, not by index: `p0`, `p1`, … for the pages of the file in their original order, and the inserting peer's `actor:counter` for a blank page. An index would mean a different page on each peer as soon as someone reorders.

- **Rotate** sends the resulting rotation, not the turn. Two people who both turn a page by 90° get 90°, not 180°.
- **Move** gives the moved pages a new position key between their new neighbours and leaves every other page alone, so concurrent moves of different pages are both applied.
- **Delete** is a tombstone. A rotate or move that arrives for a deleted page is ignored and reported through `onPageConflict` with the reason `removed`. Undoing a synchronised deletion locally removes the page again, because the other peers cannot restore it.
- **Insert blank page** carries the position key and the page size.
- If concurrent deletions remove every page, each peer shows one blank US Letter placeholder page, which disappears when a page is inserted.

With the page channel on, annotation operations carry the page id as well, so a note stays on its page while someone else reorders, and a page move sends no annotation updates.

Remote page changes are steps on the local undo stack, like remote form values.

Not synchronised: pages merged or inserted from another PDF (their bytes would have to travel; such pages stay local and annotations on them are addressed by index), duplicated pages, crops and page boxes, resizing, page labels, content edits, applied redactions, watermarks and headers, form field design, bookmarks, attachments and encryption settings. Do those before the session starts or after it ends.

### Presence

Each viewer announces its user name, colour, the page in view (`viewPageIndex`), the pointer position (`pageIndex` and `point`, in page coordinates) and the selected annotation ids. Pointer moves are sent at most every 60 ms and a heartbeat every third of `presenceTimeout`. Presence is never part of a snapshot or of the saved file. `viewer.getCollaborators()` returns the current list, `onPresenceChange` reports changes, and other reviewers' pointers are drawn as named cursors.

Closing the document sends a leave message. A peer whose connection drops without one disappears after the timeout, or sooner if your transport reports the disconnect as a leave message, as the relay client does.

## Late joiners

Everyone must start from the same file. Someone who joins later needs the operations sent so far, in any order, or a snapshot:

```ts
import type { PdfViewerApi, SyncSnapshot } from '@birchui/pdf';

declare const viewer: PdfViewerApi;
declare const lateViewer: PdfViewerApi;

const snapshot: SyncSnapshot | undefined = viewer.getSyncSnapshot();
if (snapshot) lateViewer.mergeSyncSnapshot(snapshot);
```

The snapshot is JSON and contains the annotation, form and page state of the channels that are on. You can also pass it as `snapshot` to `createSyncChannel`. For long sessions store a snapshot from time to time next to the original file instead of an ever-growing operation log.

## Without the viewer

The same merge logic runs on the headless document, for a server-side participant or for tests:

```ts
import {
  createAnnotationSync,
  createFormSync,
  createPageSync,
  formSyncHost,
  pageSyncHost,
  type SyncMessage,
} from '@birchui/pdf';
import { openPdfDocument } from '@birchui/pdf/engine';

declare const bytes: Uint8Array;
declare const wire: { post(message: SyncMessage): void; onMessage(handler: (message: SyncMessage) => void): void };

const pdf = openPdfDocument(bytes);
const actorId = 'archive-bot-1';

const pages = createPageSync(pageSyncHost(pdf), {
  actorId,
  send: (operations) => wire.post({ channel: 'pages', operations }),
  onApply: () => annotations.refresh(),
});
const annotations = createAnnotationSync(pdf, {
  actorId,
  send: (operations) => wire.post({ channel: 'annotations', operations }),
  pageIds: () => pages.pageIds(),
});
const forms = createFormSync(formSyncHost(pdf), {
  actorId,
  send: (operations) => wire.post({ channel: 'forms', operations }),
});

wire.onMessage((message) => {
  if (message.channel === 'pages') pages.receive(message.operations);
  else if (message.channel === 'annotations') annotations.receive(message.operations);
  else if (message.channel === 'forms') forms.receive(message.operations);
});
```

Create the page sync first and pass its `pageIds` to the annotation sync; `onApply` lets annotations that waited for a page appear once the page exists. Each sync has `receive`, `snapshot()`, `merge(snapshot)` and `destroy()`. `createFormSync` and `createPageSync` take a small host interface (`FormSyncHost`, `PageSyncHost`), so they can drive something other than a `PdfDocument`.

## Reference relay

`packages/pdf/examples/collab-relay` in the repository is a small relay you can read in one sitting and copy. It uses only Node built-ins: clients receive over Server-Sent Events and send with POST.

- one room per document id;
- an `authenticate(request)` hook that returns `{ userId, name }` or `null`; unauthenticated requests get 401;
- a bounded operation log per room that is replayed to late joiners and after a reconnect; presence is forwarded but never logged;
- join and leave events, which the client turns into the peer list and a presence leave message;
- limits for message size, message rate and peers per room.

Its browser client, `createRelayTransport(url, room, token)`, returns a transport for `createSyncChannel`. It reconnects, resumes from the last sequence number it saw, and holds messages back until the viewer listens.

It is a reference, not a product: it keeps everything in memory, loses the log when the room empties or the process restarts, does not terminate TLS, runs as a single process and checks who may join but not what a client sends. A client that is allowed into a room can send any operation, including forged clocks. Put it behind your own TLS proxy and authentication, and validate or persist operations on the server if your threat model needs it.

## Limits

- All peers start from the same file and run the same version of the package.
- Two peers that reuse one `actorId` at the same time break the tie-break rule and can end in different states.
- Clocks are logical, not wall-clock: "later" means "has seen more operations", which is not always who typed last.
- Remote annotation changes do not enter the local undo stack; remote form and page changes do.
- With `tabs`, the channel follows the active tab only.
