From 8e1b9576c5a15440215d7d4f35954ef8d22ad478 Mon Sep 17 00:00:00 2001 From: Exelo Date: Sun, 29 Nov 2026 11:48:56 +0100 Subject: [PATCH 1/4] docs(docs): record the real-time collaboration model in adr 0008 --- docs/adr/0008-real-time-collaboration.md | 155 +++++++++++++++++++++++ docs/specs/code-editor.md | 2 +- docs/specs/history-panel.md | 2 +- 3 files changed, 157 insertions(+), 2 deletions(-) create mode 100644 docs/adr/0008-real-time-collaboration.md diff --git a/docs/adr/0008-real-time-collaboration.md b/docs/adr/0008-real-time-collaboration.md new file mode 100644 index 00000000..f47dbe8a --- /dev/null +++ b/docs/adr/0008-real-time-collaboration.md @@ -0,0 +1,155 @@ +# 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) + +## 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: + +- **One server per project.** `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 `/gw-`. The API checks access when a session opens one + (`api.gatewayProject`), and `ProjectRegistry.get` then lets in only the sessions holding the grant + (`session.projects`). OFFLINE sessions are all let in, and their user is the OS user + (`{ id: 'local' }`). +- **Saves already reach other sessions**, at file level: the watcher's `fs.changes` stream feeds + `DocumentBackend.onDidChange`, and a session with unsaved edits gets a conflict. Unsaved typing + doesn't reach anyone. +- **Every edit is text.** Code is the source of truth: the ECS and scene editors, codegen and the + settings UI write `.ts` and `.json` files (`docs/specs/ecs.md`, `docs/specs/scene.md`). Typing + lives in the Monaco model behind `OpenDocument`, with Monaco's own undo. Operations + (`DocumentService.edit`: codegen, ECS, scene) are `HistoryStack` steps. +- **The seams.** `HistoryStack.record` adds a change applied elsewhere as a step that can't be + undone. `CommandOrigin` already has a `remote` kind. The `DocumentBackend` seam was kept for + collaboration (`docs/specs/code-editor.md`). Its whole-file `read`/`write`, though, can't carry + live typing. +- **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 settings + edits are text edits of those files, so the same model covers them: no separate model for + structured edits. Binary and custom documents (images, audio) stay file-level: last save wins, + through the watcher, 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 it targets + a file nobody has open, it joins the file's doc if one exists, and otherwise writes through the + backend as today. `DocumentBackend` stays the store of files that nobody shares. +- New 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, that is, the + users the API let open the gateway project. 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): the host shares their editor through the existing guards. The editor listens + on a non-loopback `HOST` with `ALLOW_REMOTE_OFFLINE=1`, behind an `EDITOR_TOKEN`. The host sends + the token link, and **every guest has the host's rights**: it runs project code as the host's OS + user. Two tabs of one user are two sessions and sync the same way. +- **Identity**: ONLINE uses the API user (`id`, `name`). In LOCAL every session is `local`, so each + session picks a display name when it joins (kept in a cookie). Its id is the session id. + +### Relay and persistence + +- **The server holds each shared doc** while at least one session has the file open, and drops it + when the project closes. A doc is created from the file on disk, or from the first client's + unsaved text, as the unsaved store restores it today. Each doc has a **generation id**: a client + that comes back with a doc from another generation (after a server restart, for example) drops + it and re-applies its unsaved text as one edit on the new doc. It never merges docs of two + generations, because that would duplicate the text. +- **Messages go over the existing WebSocket**, in a new RPC namespace in `packages/protocol`. Yjs + sync and update messages travel per document, and awareness messages per project. The channels + live in the server process and are keyed by project id. +- **Reconnect**: the Yjs sync handshake (state vectors). Edits made while disconnected merge when + the socket comes back. +- **Explicit save, by the server.** Any participant's Save makes the server write the doc's text, + checking the hash of the last version it saw on disk. The save clears the dirty state for + everyone. A shared file is dirty when its text differs from the last version saved or read. + Nothing is saved automatically. + +### Conflicts + +- **Concurrent edits** of one file merge through the CRDT, including the edits made through + `DocumentService.edit`. +- **A file changed on disk while shared** (git pull or checkout, a hand edit, another tool): the + server applies the new disk text to the doc as one change, by diff, with origin `disk`. It merges + with everyone's unsaved edits. This replaces the conflict dialog for shared files; unshared files + keep it. +- **Git** works on the one shared checkout: the server's commit and push in ONLINE, the git plugin + in LOCAL. A commit holds the saved state of every user's files. Unsaved shared edits are not in + it. Any participant may commit. + +### Presence + +- **Yjs awareness, per project**: user id, name, color, open file, selection, and the entity being + edited. It is never stored. It is throttled, at a rate #233 sets. A session's entry goes when its + last socket closes. +- Names are shown next to colors, never color alone. Colors pass contrast in both themes. + +### Undo and history + +- **Undo is local only.** A shared doc's undo is a `Y.UndoManager` tracking the local origin, in + place of Monaco's undo. Undo reverts only your own changes. Where a remote change touched the + same range, it 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: }`, 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 + +- Joining a document or presence channel goes through `ProjectRegistry.get`, so a session can't + join a project it doesn't hold. Leaving follows the grant. +- Yjs messages are untrusted input: + - there is a size cap per message 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. +- The host guard (`ALLOWED_HOSTS`), the origin check and the launch token stay in front of the + WebSocket. +- A project plugin's server entry still never runs in a hosted editor: the relay adds no path to + one. +- Sharing a LOCAL editor gives the guests the host's machine, since project code runs unsandboxed. + The share flow must say so before it shows the link. + +## 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 + it is 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. **Clients write the file** through `DocumentBackend.write(expectedHash)`: clients race on save, + and the losers get conflicts. Not chosen. +5. **Autosave of shared docs.** It would change the save UX for everyone. Not chosen. +6. **Global undo** (undo the last change on the file, whoever made it). It surprises users when two + people type. Not chosen. + +## 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, so the same routing is needed even without collaboration. +- **Server restart.** Unsaved shared text that no reconnecting client brings back is lost. Explicit + save keeps the disk as the durable copy. +- **Disk changes merge silently.** A git checkout of another branch merges into open shared docs, + with no dialog. Revisit if users lose work this way. +- **LOCAL guests have the host's rights.** A restricted guest role (no runtime, no install, no + terminal) is not part of this decision. +- **Work items:** + - #230: the relay, the channels, the limits and the generation ids; + - #231: the Monaco binding, `DocumentService.edit` on shared docs and the server save; + - #232: remote operations in the history; + - #233: presence, plus the LOCAL display name and share flow; + - the LOCAL share flow needs a home in one of them. +- Check under Bun, not only in the Node unit tests: `yjs` and `lib0` on the server, and the + WebSocket messages. diff --git a/docs/specs/code-editor.md b/docs/specs/code-editor.md index 5871ec89..5fedc51b 100644 --- a/docs/specs/code-editor.md +++ b/docs/specs/code-editor.md @@ -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 diff --git a/docs/specs/history-panel.md b/docs/specs/history-panel.md index 58fdf8c6..0b0f8255 100644 --- a/docs/specs/history-panel.md +++ b/docs/specs/history-panel.md @@ -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. From 3f3df48c38cd1c812787cf3f10e7c3c9a64ff718 Mon Sep 17 00:00:00 2001 From: Exelo Date: Sun, 29 Nov 2026 12:10:11 +0100 Subject: [PATCH 2/4] docs(docs): settle saves, file lifecycle, local guests and undo in adr 0008 --- docs/adr/0008-real-time-collaboration.md | 300 +++++++++++++++-------- 1 file changed, 195 insertions(+), 105 deletions(-) diff --git a/docs/adr/0008-real-time-collaboration.md b/docs/adr/0008-real-time-collaboration.md index f47dbe8a..19fdfe27 100644 --- a/docs/adr/0008-real-time-collaboration.md +++ b/docs/adr/0008-real-time-collaboration.md @@ -2,30 +2,45 @@ - Status: accepted (2026-11-29) - Related: #98 (epic), #229 (this ADR), #230 (server relay), #231 (collaborative documents), - #232 (history with authors), #233 (presence) + #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: - -- **One server per project.** `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 `/gw-`. The API checks access when a session opens one - (`api.gatewayProject`), and `ProjectRegistry.get` then lets in only the sessions holding the grant - (`session.projects`). OFFLINE sessions are all let in, and their user is the OS user - (`{ id: 'local' }`). -- **Saves already reach other sessions**, at file level: the watcher's `fs.changes` stream feeds - `DocumentBackend.onDidChange`, and a session with unsaved edits gets a conflict. Unsaved typing - doesn't reach anyone. -- **Every edit is text.** Code is the source of truth: the ECS and scene editors, codegen and the - settings UI write `.ts` and `.json` files (`docs/specs/ecs.md`, `docs/specs/scene.md`). Typing - lives in the Monaco model behind `OpenDocument`, with Monaco's own undo. Operations - (`DocumentService.edit`: codegen, ECS, scene) are `HistoryStack` steps. -- **The seams.** `HistoryStack.record` adds a change applied elsewhere as a step that can't be - undone. `CommandOrigin` already has a `remote` kind. The `DocumentBackend` seam was kept for - collaboration (`docs/specs/code-editor.md`). Its whole-file `read`/`write`, though, can't carry - live typing. +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 `/gw-`. 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. @@ -34,72 +49,131 @@ they happen. What the code does at this point: ### Sync model -- **Yjs CRDT, one `Y.Doc` per shared text file**, its text in a `Y.Text`. ECS, scene and settings - edits are text edits of those files, so the same model covers them: no separate model for - structured edits. Binary and custom documents (images, audio) stay file-level: last save wins, - through the watcher, 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 it targets - a file nobody has open, it joins the file's doc if one exists, and otherwise writes through the - backend as today. `DocumentBackend` stays the store of files that nobody shares. -- New dependencies: `yjs` and `y-protocols`, in a `pnpm-workspace.yaml` catalog. Whether to use +- **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, that is, the - users the API let open the gateway project. 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): the host shares their editor through the existing guards. The editor listens - on a non-loopback `HOST` with `ALLOW_REMOTE_OFFLINE=1`, behind an `EDITOR_TOKEN`. The host sends - the token link, and **every guest has the host's rights**: it runs project code as the host's OS - user. Two tabs of one user are two sessions and sync the same way. -- **Identity**: ONLINE uses the API user (`id`, `name`). In LOCAL every session is `local`, so each - session picks a display name when it joins (kept in a cookie). Its id is the session id. - -### Relay and persistence - -- **The server holds each shared doc** while at least one session has the file open, and drops it - when the project closes. A doc is created from the file on disk, or from the first client's - unsaved text, as the unsaved store restores it today. Each doc has a **generation id**: a client - that comes back with a doc from another generation (after a server restart, for example) drops - it and re-applies its unsaved text as one edit on the new doc. It never merges docs of two - generations, because that would duplicate the text. -- **Messages go over the existing WebSocket**, in a new RPC namespace in `packages/protocol`. Yjs - sync and update messages travel per document, and awareness messages per project. The channels - live in the server process and are keyed by project id. -- **Reconnect**: the Yjs sync handshake (state vectors). Edits made while disconnected merge when - the socket comes back. -- **Explicit save, by the server.** Any participant's Save makes the server write the doc's text, - checking the hash of the last version it saw on disk. The save clears the dirty state for - everyone. A shared file is dirty when its text differs from the last version saved or read. - Nothing is saved automatically. - -### Conflicts - -- **Concurrent edits** of one file merge through the CRDT, including the edits made through - `DocumentService.edit`. -- **A file changed on disk while shared** (git pull or checkout, a hand edit, another tool): the - server applies the new disk text to the doc as one change, by diff, with origin `disk`. It merges - with everyone's unsaved edits. This replaces the conflict dialog for shared files; unshared files - keep it. -- **Git** works on the one shared checkout: the server's commit and push in ONLINE, the git plugin - in LOCAL. A commit holds the saved state of every user's files. Unsaved shared edits are not in - it. Any participant may commit. +- **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 whose requests come from a loopback address. Any other session is a + guest. + - 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 (a new token) drops every guest. +- **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. +- **Creating a doc.** A new doc starts from the file on disk. A client's unsaved text (its browser + store) seeds it only when the store's base hash is the file's current hash. Otherwise that client + gets today's conflict. +- **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, the user's autosave, a scene step, Play's `saveBeforePlay`. + - 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. + - 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. +- **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, and its stored state goes. Each + session that had the file open keeps the text in today's "deleted on disk" conflict, where saving + creates the file again. +- **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 id, name, color, open file, selection, and the entity being - edited. It is never stored. It is throttled, at a rate #233 sets. A session's entry goes when its - last socket closes. -- Names are shown next to colors, never color alone. Colors pass contrast in both themes. +- **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.** A shared doc's undo is a `Y.UndoManager` tracking the local origin, in - place of Monaco's undo. Undo reverts only your own changes. Where a remote change touched the - same range, it reverts what is left of yours. +- **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. Its + `HistoryStack` step undoes through a `Y.UndoManager` scoped to that transaction, and its check + looks at that transaction's own items, not at a fingerprint of the whole file. Remote edits + elsewhere in the file leave it undoable. + - 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: }`, so it shows muted, with the author's name, and can't be @@ -107,49 +181,65 @@ they happen. What the code does at this point: ## Security -- Joining a document or presence channel goes through `ProjectRegistry.get`, so a session can't - join a project it doesn't hold. Leaving follows the grant. -- Yjs messages are untrusted input: - - there is a size cap per message 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. -- The host guard (`ALLOWED_HOSTS`), the origin check and the launch token stay in front of the - WebSocket. -- A project plugin's server entry still never runs in a hosted editor: the relay adds no path to - one. -- Sharing a LOCAL editor gives the guests the host's machine, since project code runs unsandboxed. - The share flow must say so before it shows the link. +- **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 - it is not real-time co-editing, which #98 asks for. Not chosen. + 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. **Clients write the file** through `DocumentBackend.write(expectedHash)`: clients race on save, +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. -5. **Autosave of shared docs.** It would change the save UX for everyone. Not chosen. -6. **Global undo** (undo the last change on the file, whoever made it). It surprises users when two +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. ## 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, so the same routing is needed even without collaboration. -- **Server restart.** Unsaved shared text that no reconnecting client brings back is lost. Explicit - save keeps the disk as the durable copy. -- **Disk changes merge silently.** A git checkout of another branch merges into open shared docs, - with no dialog. Revisit if users lose work this way. -- **LOCAL guests have the host's rights.** A restricted guest role (no runtime, no install, no - terminal) is not part of this decision. + pod's disk anyway. +- **Storage.** `DATA_DIR` grows with the shared docs. Saving compacts them, and deleting a file + removes its doc. Documents in a hosted editor share the pod's disk. +- **Saves carry everyone's text.** A save, or Play, writes a collaborator's unfinished line. That is + what explicit save means with several users. +- **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: the relay, the channels, the limits and the generation ids; - - #231: the Monaco binding, `DocumentService.edit` on shared docs and the server save; - - #232: remote operations in the history; - - #233: presence, plus the LOCAL display name and share flow; - - the LOCAL share flow needs a home in one of them. -- Check under Bun, not only in the Node unit tests: `yjs` and `lib0` on the server, and the + - #230: relay, channels, limits, doc storage and generations, server save, disk merge, and + delete and rename handling on the server; + - #231: Monaco binding, `DocumentService.edit` and every save caller on shared docs, the + generation conflict, delete and rename in the code editor, 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 and guests, the required token, 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. From 0f87f2b7db66657fd5ab3dc1d675e4709a25f313 Mon Sep 17 00:00:00 2001 From: Exelo Date: Sun, 29 Nov 2026 12:14:54 +0100 Subject: [PATCH 3/4] docs(docs): settle autosave, the host link and deleted docs in adr 0008 --- docs/adr/0008-real-time-collaboration.md | 70 ++++++++++++++++-------- 1 file changed, 48 insertions(+), 22 deletions(-) diff --git a/docs/adr/0008-real-time-collaboration.md b/docs/adr/0008-real-time-collaboration.md index 19fdfe27..93420958 100644 --- a/docs/adr/0008-real-time-collaboration.md +++ b/docs/adr/0008-real-time-collaboration.md @@ -70,15 +70,18 @@ they happen. What the code does at this point (`main` at 7ef2df9): 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 whose requests come from a loopback address. Any other session is a - guest. + - 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 (a new token) drops every guest. + - 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. @@ -95,9 +98,14 @@ they happen. What the code does at this point (`main` at 7ef2df9): - **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. -- **Creating a doc.** A new doc starts from the file on disk. A client's unsaved text (its browser - store) seeds it only when the store's base hash is the file's current hash. Otherwise that client - gets today's conflict. +- **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 @@ -116,13 +124,16 @@ they happen. What the code does at this point (`main` at 7ef2df9): ### 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, the user's autosave, a scene step, Play's `saveBeforePlay`. + 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. + 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. + 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. @@ -139,9 +150,12 @@ they happen. What the code does at this point (`main` at 7ef2df9): 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, and its stored state goes. Each - session that had the file open keeps the text in today's "deleted on disk" conflict, where saving - creates the file again. +- **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. + - 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 @@ -169,10 +183,13 @@ they happen. What the code does at this point (`main` at 7ef2df9): - **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. Its - `HistoryStack` step undoes through a `Y.UndoManager` scoped to that transaction, and its check - looks at that transaction's own items, not at a fingerprint of the whole file. Remote edits - elsewhere in the file leave it undoable. + - 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 @@ -218,6 +235,10 @@ they happen. What the code does at this point (`main` at 7ef2df9): 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 @@ -225,21 +246,26 @@ they happen. What the code does at this point (`main` at 7ef2df9): 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. Documents in a hosted editor share the pod's disk. -- **Saves carry everyone's text.** A save, or Play, writes a collaborator's unfinished line. That is - what explicit save means with several users. + removes its doc. +- **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 and rename handling on the server; + delete (trash) and rename handling on the server; - #231: Monaco binding, `DocumentService.edit` and every save caller on shared docs, the - generation conflict, delete and rename in the code editor, and the `AGENTS.md` rule; + 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 and guests, the required token, display names and the share flow. + - #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. From 12d837a04fff95bfd80f82f897bb2d6df0211418 Mon Sep 17 00:00:00 2001 From: Exelo Date: Sun, 29 Nov 2026 12:21:04 +0100 Subject: [PATCH 4/4] docs(docs): keep unsaved text of files deleted on disk in adr 0008 --- docs/adr/0008-real-time-collaboration.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/adr/0008-real-time-collaboration.md b/docs/adr/0008-real-time-collaboration.md index 93420958..3b20415a 100644 --- a/docs/adr/0008-real-time-collaboration.md +++ b/docs/adr/0008-real-time-collaboration.md @@ -155,6 +155,8 @@ they happen. What the code does at this point (`main` at 7ef2df9): - 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. @@ -246,7 +248,8 @@ they happen. What the code does at this point (`main` at 7ef2df9): 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. + 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.