# Live editing

Two devices on the same synced vault can edit a note at the same time. Edits, properties and cursors show up as you type.

## How it works

1. Opening a note in a synced vault joins its room on the Hatch server.
2. Alone, nothing is shared and the note works as usual.
3. When a second device opens it, the first one sends its copy of the note. Everyone starts from that copy.
4. After that each device sends its edits as ProseMirror steps. The server puts them in order and sends them to everyone (prosemirror-collab).
5. Properties (frontmatter) go as their own message. The last change wins.

## Privacy

- Room names are keyed hashes of the note path, so the server doesn't learn note names.
- For end-to-end encrypted vaults every message is sealed with the vault key. The server only puts them in order.
- Rooms live in memory. When everyone leaves, the room is gone and the note file is the record.

## Saving

- Every device saves the note to its own disk as usual.
- One device in the room (the leader) uploads it to the server and tells the others what each upload holds.
- The others hold that file in sync until they leave. On leaving they wait to hear that a save holds everything they typed, then take the server's copy. If that never comes, the normal sync rules apply, which keep both versions rather than lose one.
- When the leader leaves, the next device takes over from the last upload it was told about.
- If you edited a note offline and then open it while others are in the room, your version is kept as a copy named "(my changes)".

## Code

- `apps/server/src/live.ts`: rooms, ordering and limits. The WebSocket is `/api/live`, entered with a one-time ticket from `POST /api/live/ticket`.
- `packages/live`: the connection (`LiveClient`) and one note's session (`LiveNote`).
- `packages/editor/src/collab.ts`: the editor side, plus other people's cursors.
- `packages/sync`: `hold`, `wins` and `follow` keep file sync and live editing from fighting.
- `scripts/e2e-live.py`: two devices editing one encrypted note.

## Not yet

- Showing who changed what.

People a vault is shared with (see `apps/server/src/sharing.ts`) join the same rooms. Peers show as the person's name with their device. A shared vault's rooms follow its owner's plan, and anyone who loses access is sent out of the rooms they're in.
