Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
274 changes: 274 additions & 0 deletions docs/adr/0008-real-time-collaboration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,274 @@
# ADR 0008 — Real-time collaboration: Yjs documents relayed by the editor server

- Status: accepted (2026-11-29)
- Related: #98 (epic), #229 (this ADR), #230 (server relay), #231 (collaborative documents),
#232 (history with authors), #233 (presence), #365 (sharing a local editor), #366 (undo history
dropped by an outside change)

## Context

Several users must be able to edit one project at the same time and see each other's changes as
they happen. What the code does at this point (`main` at 7ef2df9):

- **One server-side project per id.** `ProjectRegistry._getOrCreate` returns the same `OpenProject`
(one folder, one watcher) to every session that opens a project.
- ONLINE projects are git checkouts of their gateway in `<FS_ROOT>/gw-<gatewayId>`. The API
checks access when a session opens one (`api.gatewayProject`). `ProjectRegistry.get` then lets
in only the sessions holding the grant (`session.projects`).
- OFFLINE sessions are let into every open project, and can open and trust any folder under
`FS_ROOT`. Their user is the OS user (`{ id: 'local' }`).
- A session is one browser: a signed cookie. Its tabs share it, each with its own socket.
- **Saved files already reach other sessions, at file level.** The code editor watches
`ProjectFs.onDidChange`. An open document that has unsaved edits gets a conflict
(`EditorDocument.onDiskChange`), and a clean one reloads. `DocumentBackend.onDidChange` only
feeds `DocumentService._checkExternal`, for files no editor has open. Unsaved typing reaches no
one.
- **Code is the source of truth.**
- The ECS and scene editors and codegen edit `.ts` files through `DocumentService.edit`.
- Creating a scene or an item writes a new file through `fs`, and undoing it deletes the file.
- Project settings are written through `fs.write` with an `expectedHash`, not through a document.
- The file manager renames, moves and deletes files.
- **Typing and operations undo separately.** Typing stays in the Monaco model behind `OpenDocument`,
with Monaco's own undo. Operations (`DocumentService.edit`) are `HistoryStack` steps.
- Such a step checks itself with a fingerprint of the whole file. When the check fails,
`HistoryStack` drops the file's whole history (#366).
- **Saves are not only explicit.** There is a per-user autosave. Scene steps save after each edit.
Play saves every open document first (`saveBeforePlay`).
- **The seams.**
- `HistoryStack.record` adds a change applied elsewhere as a step that can't be undone.
- `CommandOrigin` already has a `remote` kind.
- `DocumentBackend` was kept for collaboration (`docs/specs/code-editor.md`), but its whole-file
`read`/`write` can't carry live typing.
- **Git** runs only in a local editor (`git.implementation.ts` refuses ONLINE). An ONLINE project
is pulled when it opens, and pushing from a hosted editor is planned for phase 14.
- **Transport and deployment.** One multiplexed WebSocket (`/rpc/ws`, ADR 0002) carries the RPC
streams. The hosted editor runs one replica (`nanoforge.yaml`, `replicaCount: 1`), with
projects on that pod's disk.

## Decision

### Sync model

- **Yjs CRDT, one `Y.Doc` per shared text file**, its text in a `Y.Text`. ECS, scene and codegen
edits are text edits of those files, so they need no model of their own.
- **File-level files.** Binary files (images, audio) and project settings stay file-level:
- binary files: last save wins, through the watcher, as today;
- settings: `fs.write` with `expectedHash`, as today.
- **The live seam is the open document**, not `DocumentBackend`.
- The code editor binds the Monaco model to the `Y.Text`.
- `DocumentService.edit` applies its edits to the shared doc. When the file isn't open in this
session, it joins the file's shared doc if one exists, and otherwise writes through the backend
as today.
- `DocumentBackend` stays the store of files that no one shares.
- **Dependencies:** `yjs` and `y-protocols`, in a `pnpm-workspace.yaml` catalog. Whether to use
`y-monaco` or a binding of our own is #231's choice (`y-monaco` pins Monaco versions).

### Modes and who may join

- **ONLINE:** the sessions that `ProjectRegistry.get(session, projectId)` lets in, so the users the
API let open the gateway project. There is no new API endpoint, and no roles: every member edits.
A session whose user changes or signs out loses its grants, and it leaves every channel of the
project.
- **LOCAL (OFFLINE):** a **host** and **guests** (built in #365).
- The host is a session that opened the **host link**, which the editor prints at start, with a
secret of its own. Any other session is a guest. Host status never comes from the peer address:
through an ssh tunnel or a local proxy, every guest would come from loopback.
- The host shares projects. A guest reaches only the shared projects. Opening another folder,
trusting a folder, and git (commit, pull, push, which use the host's credentials) stay with the
host.
- Guests connect through the existing guards. Sharing sets a non-loopback `HOST` with
`ALLOW_REMOTE_OFFLINE=1`, adds the LAN name to `ALLOWED_HOSTS`, and sets a random
`EDITOR_TOKEN`. `ALLOW_REMOTE_OFFLINE` without `EDITOR_TOKEN` is refused at startup.
- Stopping the share replaces the guest token and closes the guests' open sockets. The token is
checked only before the WebSocket upgrade, so the server closes them itself. The host keeps its
session.
- **Identity.**
- ONLINE uses the API user (`id`, `name`). In LOCAL, the host is the OS user, and a guest picks a
display name when it joins, kept in its session.
- **The server stamps** the author on every relayed change and the user on every presence
entry. Clients never send them.
- Presence and Yjs clients are keyed per tab (the Yjs client id), and grouped by user in the
presence list.

### Relay and storage

- **The server holds each shared doc and stores it.** While a doc is in use, it lives in memory.
Its Yjs updates are stored in `DATA_DIR`, per project and path, outside the project, so git never
sees them. They are compacted when the doc is saved.
- **A doc outlives sessions and the project.** It survives a closed project, an idle sweep, a
restart and a folder trust. The last tab closing with unsaved text leaves it dirty for the next
person to open the file.
- **A client's unsaved text** (its browser store, which outlives a reload, unlike its Yjs state)
follows one rule, whether the doc is new or already exists:
- it is applied as one edit only when the store's base hash is the file's current hash and the
doc has no unsaved changes;
- otherwise the client gets the conflict dialog with its text.

A new doc otherwise starts from the file on disk.

- **Generations.** Each doc has a generation id, which changes only when its stored state is lost
(`DATA_DIR` wiped). A client that comes back with a doc of another generation never merges it.
If its base hash is the file's hash and the new doc has no unsaved changes, its text is applied
as one edit against that base. Otherwise it gets the conflict dialog with its own text: compare,
keep mine, or take the shared one. Docs of two generations never merge, because that duplicates
the text.
- **Messages go over the existing WebSocket**, in a new RPC namespace in `packages/protocol`:
- Yjs sync and update messages per document;
- awareness messages per project.

The channels live in the server process, keyed by project id.

- **Reconnect** uses the Yjs sync handshake (state vectors). Edits made while disconnected merge
when the socket comes back.

### Saves

- **Every save of a shared file is a server save of its doc**, whoever triggers it and whatever
path triggers it: Save, Save all, a scene step, Play's `saveBeforePlay`, and the autosave of any
participant who has it on (the project owner's choice, 2026-11-29).
- It writes everyone's current text, a collaborator's half-typed line included.
- It clears the dirty state for everyone. A shared file is dirty when its text differs from the
last version saved or read. With one participant on autosave, the others rarely see it dirty.
- The server never saves on its own.
- **Actions on save** (format, organize imports) run in the client that saves, as edits on the
shared doc, before it asks the server to write. Its settings apply. Their result is applied as
the smallest diff, after checking that the text is still the one they formatted, so concurrent
typing isn't overwritten.
- **The server writes** with the hash of the last disk version it knows. It records the hash it
wrote, so the watcher event of its own write is not a disk change. On a mismatch, it applies the
disk change first (below), then writes.

### Conflicts and file lifecycle

- **Concurrent edits** of one file merge through the CRDT, the edits made through
`DocumentService.edit` included.
- **A file changed on disk while shared** (git pull or checkout, a hand edit, another tool) is a
three-way merge.
- The server diffs the last disk text it read or wrote against the new disk text. It applies
those hunks at the doc state it recorded at that last read or write (Yjs relative positions).
- Everyone's unsaved edits stay. Where they overlap the disk change, both texts stay, as with
concurrent edits.
- The sessions that have the file open are told that the disk change was merged. This replaces
the conflict dialog for shared files; files that no one shares keep it.
- **Deleted** (by anyone, or on disk): the doc closes for everyone. Each session that had the file
open keeps the text in today's "deleted on disk" conflict, where saving creates the file again.
- A doc with unsaved changes is kept with the trash entry, so undoing the delete brings back its
text, not only the disk copy.
- A delete of a file whose doc has unsaved changes warns first.
- A file deleted on disk (a git checkout, a hand delete) has no trash entry and gives no warning.
Its doc's unsaved text is then kept as a recoverable "deleted on disk" entry.
- The Files panel marks files with unsaved shared changes.
- **Renamed or moved:** the doc follows the file. Its stored state moves, and open editors are
retargeted, as the code editor does today.
- **Created:** a new file is not shared until someone opens it. An undo that would delete a file
another session has open is refused, with a message that names them. This covers undoing _New
scene_ or a created item.
- **Git** works on the one shared checkout. A commit holds the saved state of every user's files,
without unsaved shared edits. In LOCAL only the host runs git. In ONLINE there is no git action
yet: pushing from a hosted editor (phase 14) must follow the same rule.

### Presence

- **Yjs awareness, per project:** user (stamped by the server), color, open file, selection, and
the entity being edited. It is never stored, and its rate is throttled (set in #233). An entry
goes when its tab's socket closes.
- **Colors** come from a fixed palette, checked against both themes' editor and panel backgrounds.
- **Accessibility.**
- A name always goes with a color.
- The presence list is text with accessible names.
- Joins and leaves are announced in a polite live region, throttled, never on cursor moves.
- Remote cursor labels can be read as text. #233 picks the mechanism.
- A disk merge is a notification. Remote typing is not announced.

### Undo and history

- **Undo is local only.**
- Typing on a shared doc undoes through a `Y.UndoManager` tracking the local origin, in place of
Monaco's undo.
- An operation (`DocumentService.edit`) on a shared doc is one Yjs transaction with an origin of
its own. One `Y.UndoManager` per doc tracks the operations, and maps its stack items to their
`HistoryStack` steps. An item is dropped when its step leaves the stack.
- A step's check looks at that transaction's own items, not at a fingerprint of the whole file,
so remote edits elsewhere in the file leave it undoable.
- The typing manager leaves out the operations' origin, so Ctrl+Z never undoes an operation
twice.
- Where a remote change touched the same range, undo reverts what is left of yours.
- **Remote operations go into the history.** Each relayed `DocumentService.edit` carries its label
and author. Other sessions add it with `HistoryStack.record` and
`{ kind: 'remote', id: <author id> }`, so it shows muted, with the author's name, and can't be
undone. Remote typing stays out of the history, as local typing does.

## Security

- **ONLINE:** joining a document or presence channel goes through `ProjectRegistry.get`, so a
session can't join a project it holds no grant for. Leaving follows the grant.
- **LOCAL:** today, every OFFLINE session reaches every project under `FS_ROOT`. Under this
decision, guests reach only shared projects, and they can't open folders, trust them or run git
(#365).
- A guest can still run a shared, trusted project's code (Play, installs) on the host's machine.
The share flow says so before it shows the link.
- The link and the token cookie travel in clear on the LAN, so anyone who can listen there can
act as a guest. This is accepted for now, and the share flow says it.
- A guest's display name is self-declared, so one guest can pose as another. This is accepted;
the server still stamps the session, so a guest can't pose as the host.
- **Yjs messages are untrusted input.**
- There is a size cap per message, a size cap per stored doc, and a rate cap per socket.
- A message that doesn't decode removes that socket from the channel.
- A member can write anything they can already write with `fs.write`, and nothing more.
- **Guards:** the host guard (`ALLOWED_HOSTS`), the origin check and the launch token stay in front
of the WebSocket.
- **Plugin server entries:** a project plugin's server entry still never runs in a hosted editor.
The relay adds no path to one.

## Alternatives considered

1. **Server-ordered OT.** It needs no CRDT dependency, but we would write and maintain the
transforms, and edits made offline merge less well. Not chosen.
2. **One editor per file at a time** (a lock; the others read only and see saves). Simpler, but
not real-time co-editing, which #98 asks for. Not chosen.
3. **ONLINE only.** It needs no LOCAL identity and no share flow. Not chosen: the project owner
wants LAN sessions too (2026-11-29).
4. **Guests with the host's rights.** A guest could trust and run any folder under `FS_ROOT`. Not
chosen (2026-11-29).
5. **Docs in memory only.** A sweep, restart or trust would then lose unsaved shared text, or
force a merge across generations. Not chosen (2026-11-29).
6. **Clients write the file** through `DocumentBackend.write(expectedHash)`. Clients race on save,
and the losers get conflicts. Not chosen.
7. **The server saves on its own.** It would change the save UX for everyone. Not chosen.
8. **Global undo** (undo the last change on the file, whoever made it). It surprises users when two
people type. Not chosen.
9. **No autosave on shared files** (only explicit actions save them). It keeps the dirty marker
meaningful for everyone. Not chosen: the project owner keeps autosave (2026-11-29).
10. **The host is whoever connects from loopback.** Simpler, but every guest becomes host through
a tunnel or a local proxy. Not chosen (2026-11-29).

## Consequences

- **One replica.** The channels live in the server process, so all the sessions of a project must
reach the same server. Scaling out needs routing by project id. The projects folder is on the
pod's disk anyway.
- **Storage.** `DATA_DIR` grows with the shared docs. Saving compacts them, and deleting a file
removes its doc, except that unsaved changes are kept (with the trash entry, or as a "deleted on
disk" entry).
- **Hosted disk:** the hosted editor declares no volume (`nanoforge.yaml`). `DATA_DIR` and the
projects folder are on the pod's own disk, so a pod rescheduling loses both: the docs change
generation, and saved work not yet pushed is gone. A volume is phase 14's call.
- **Saves carry everyone's text.** A save, Play, or someone's autosave writes a collaborator's
unfinished line.
- **Disk changes merge, with a notification.** A git checkout of another branch merges into open
shared docs. Revisit if users lose work this way.
- **Changed rule:** `AGENTS.md` says an operation "never writes a file behind an open document".
For a shared file, the open document is the shared doc. #231 updates the rule.
- **Work items:**
- #230: relay, channels, limits, doc storage and generations, server save, disk merge, and
delete (trash) and rename handling on the server;
- #231: Monaco binding, `DocumentService.edit` and every save caller on shared docs, the
unsaved-text rule, actions on save as a minimal diff, delete and rename in the code editor, the
Files panel mark, and the `AGENTS.md` rule;
- #232: remote operations in the history, operation undo through Yjs, and refusing an undo that
deletes a file someone has open;
- #233: presence and its accessibility;
- #365: LOCAL host link and guests, the required token, closing guest sockets, display names and
the share flow.
- **Check under Bun,** not only in the Node unit tests: `yjs` and `lib0` on the server, and the
WebSocket messages.
2 changes: 1 addition & 1 deletion docs/specs/code-editor.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ Autosave and the actions on save apply to every save path (explicit, delayed, fo
- Debugger and breakpoints (needs the runtime inspector work, phase 11).
- Git gutter and blame (git plugin, 11.4).
- Refactorings beyond rename and organize imports; snippets.
- Real-time collaboration (the `DocumentBackend` seam stays ready for it).
- Real-time collaboration: decided in ADR 0008 (Yjs docs bound to the open document, not to `DocumentBackend`), built in #230 and #231.

## Done when

Expand Down
2 changes: 1 addition & 1 deletion docs/specs/history-panel.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Requirements session: 2026-09-27. Built-in plugin in `plugins/history-panel`, th

## Entries

- **Label**, **time** (relative, e.g. "2 min ago") and **origin**: _you_, a plugin (e.g. codegen), or later a collaborator. Changes of other origins cannot be undone and are shown muted.
- **Label**, **time** (relative, e.g. "2 min ago") and **origin**: _you_, a plugin (e.g. codegen), or a collaborator (ADR 0008: their operations, not their typing, with their name). Changes of other origins cannot be undone and are shown muted.
- **Grouped steps**: a transaction (one drag, one codegen operation) is one entry that expands to its steps.
- **Diff preview**: entries that edit a document show the changed lines, before and after, on hover or focus.
- The current position is marked. Undone steps (redo) stay listed below it, dimmed.
Expand Down
Loading