AI-native design editor. Open-source Figma alternative.
feat(collab)!: sync layer trees as a CRDT and open each room in its own tab (#902)
Danila Poyarkov9dce9fdcbcc1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a55fa9a20..4f7b4a707 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,8 @@- `openpencil documents` is now a command group: list open documents with `openpencil documents list`.- The MCP `close_file` tool no longer asks in the app whether to save unsaved changes, a question an agent could not answer and that left the call timing out. With unsaved changes it now fails unless `unsaved` is `"save"` or `"discard"`, and it is marked as a write tool.- OpenPencil's plugin-data keys are defined once in `OPEN_PENCIL_PLUGIN_DATA` from `@open-pencil/scene-graph`, each with the schema that reads and writes it, and read or replaced with `readPluginData` and `withPluginData`. `@open-pencil/fig/node-change` no longer exports `OPEN_PENCIL_PLUGIN_ID` (now in `@open-pencil/scene-graph`), the `*_PLUGIN_KEY` constants, `upsertPluginData`, `removePluginData`, or `getOpenPencilPluginValue`; read a `.fig` record's value with `readNodeChangePluginData`. `@open-pencil/core` no longer exports `SOURCE_LIBRARY_PUBLICATION_PLUGIN_KEY`, and `SourceLibraryPublication` moved to `@open-pencil/scene-graph`.+- `fractionalPosition`, `orderKeyBetween`, and `siblingOrderKeys` moved from `@open-pencil/fig/node-change` to `@open-pencil/scene-graph/order-keys`; the `@open-pencil/core` root still exports `fractionalPosition`. `orderKeyBetween` now always returns a key: when no printable key sorts between its bounds it returns a key above `lo`, which `hasOrderKeyBetween` detects, and it takes an optional suffix that `siblingOrderKeys` can request through `{ suffix }`.+- Shared rooms record the layer tree in a new format, so people on this version and on earlier versions can no longer join each other's rooms. A room this browser saved with an earlier version converts when you open it again.- `SceneGraph.hitTestFrame` is now `hitTestDropTarget`, which returns only layers that take a drop, as in Figma: it skips groups, boolean operations, component sets, and locked layers, follows rotation, and respects clipping. The editor's `adoptNodesIntoSection` is now `adoptCoveredLayers`, which also takes a frame, and leaves locked layers out.### Added@@ -38,7 +40,7 @@- Copy the document's variables as a CSS stylesheet or a Tailwind v4 theme from the variables dialog's collection menu, or print them with `openpencil tokens`. Each collection's default mode goes in `:root` (or `@theme`, with a `@custom-variant` per mode), other modes override under their condition, `[data-theme="dark"]` unless the mode names a selector or `@media` query, and aliases stay `var()` references that follow the mode. Variables CSS cannot express, such as booleans, are named instead of written.- Follow collaborators and their AI agents from the avatars in the toolbar: an avatar counts that person's agents, hovering lists what each is doing and on which page, and clicking follows. A frame in their color and a “Following …” bar show whom you follow; Escape, clicking, scrolling, zooming, or switching pages stops it. Your own avatar renames your agents and leaves the room.- See where the built-in AI chat is working: while it replies, a cursor whose outlined label shows a sparkle and a callsign such as *Fern* marks the layers it edits. In a shared room, collaborators see each other's agents in the color of the person running them.-- See which pages people and AI agents are working on: the Pages panel marks those pages in their colors, the command palette names who is there, and the chat offers **Go to page** while its reply works on a page you're not viewing.+- See which pages people and AI agents are working on: the Pages panel marks those pages in their colors and, on hover, shows who is there with what their agents are doing and a button to follow them; the command palette names who is there, and the chat offers **Go to page** while its reply works on a page you're not viewing. On phones, the room pill shows the people in the room as avatars beside the room's status.- Hide, lock, and constrain layers in design JSX with `visible={false}`, `locked`, and `constraints={{ horizontal, vertical }}`, set italic text with `italic`, and describe strokes fully with `strokes`, `strokeWeights`, `strokeCap`, `strokeJoin`, and the node-level `dashPattern`. JSX export now writes these together with stacked, gradient, and image fills, every effect, absolutely positioned children, size limits, vertical text alignment, masks, and variable bindings, so rendering exported JSX reproduces them and `diff_jsx` reports changes to them.- Jump between pages from the command palette: it lists the pages you visited recently in the tab, **Go to page…** lists every page, and typing a page name finds it.- Choose how much an AI model thinks for each message from the chat composer, from Off to Extra high or the provider default. Anthropic, Google, DeepSeek, OpenAI, OpenRouter, and compatible models apply it, where reasoning effort previously reached only OpenAI and OpenRouter models. A model profile's thinking level, which replaces its free-text reasoning effort, sets the starting choice, and finished reasoning shows how long the model thought.@@ -58,6 +60,8 @@- Create and fill slots as in Figma. **Create slot** turns a frame of a main component into a slot, or wraps other selected layers in a new one, and the Slots section sets its name, description, layer limits, and preferred components or removes it. In instances, drop, paste, or move layers into a slot, or add components from **Add instances** in the properties panel, which shows each slot as Default or Modified with its item count and limits; **Reset slot** brings back the component content and **Delete contents** empties it. Slots are outlined in pink on the canvas and marked in the layers panel, and parts of an instance outside its slots cannot be dropped into, grouped, wrapped, or deleted, as in Figma.- Create and inspect slots from scripts run through `eval` and from AI and MCP tools, as in Figma: `component.createSlot()` adds a slot frame and its `SLOT` property, slot frames read `type: 'SLOT'` with `resetSlot()` and `limitViolations`, `appendChild`, `insertChild`, and `remove()` work inside slots and refuse the rest of an instance, and `addComponentProperty` and `editComponentProperty` take a `description` and `slotSettings`.- Control the running app from the CLI and MCP: `openpencil documents` opens, creates, saves, closes, and brings documents to the front, `openpencil undo` and `redo` step back through changes made through the CLI and MCP, refusing to revert edits made in the editor, and `openpencil settings get` and `set` read and change theme, language, animations, snapping, canvas rendering, recovery, chat, and design check settings. MCP clients get the same through `activate_document`, `undo`, `redo`, `get_settings`, and `update_settings`; credentials, models, MCP connections, storage, and tool access stay out of reach. `openpencil tool list`, `describe`, and `call` run any MCP tool from the shell, against the running app or headlessly on a file.+- Be in several shared rooms at once, each in its own tab and syncing in the background. Join a room from Home with **Join room…**, and from a browser on a computer open it in the desktop app with **Open in desktop app** (`openpencil://join?room=<id>`).+- Join a shared room right away under a generated name such as *Teal Fox*, and set the one name every room shows in Settings or the share panel.### Changed@@ -79,6 +83,7 @@- `openpencil://` and web `?node=` links select the layer on another page when the current page has none, switching to that page.- Generate Tailwind JSX with the same class mapping as Tailwind HTML export, so both describe a design the same way, and write opaque colors as hex in HTML, CSS, and Tailwind output. `openpencil export -f jsx --style tailwind` now exports a whole page when no `--node` is given.- Show download progress with a percentage and transferred size while installing a desktop update, instead of an indeterminate message that lasted until the restart.+- Opening a share link or joining a room opens it in a tab of its own, so a document you already have open is never changed. Until the room's file arrives the tab says it is joining or, when nobody who has the file is online, explains why it is waiting; reloading rejoins, and leaving a room you joined keeps its file as a local unsaved copy.### Fixed@@ -109,6 +114,9 @@- Render the canvas with the Vue SDK's `CanvasRoot` and `CanvasSurface`; CanvasKit never started there and the canvas stayed blank.- Keep the view centered on what you were looking at when zooming to 100% or another fixed level, instead of jumping elsewhere whenever the zoom changes.- Draw collaborators' names on their cursors with proper letter spacing and fallback fonts, and end long names with an ellipsis.+- Keep one layer tree in a shared room when people move layers into each other at the same time. Both moves used to apply, making each layer the other's parent, which hid both and froze the editor of anyone in the room; now every peer undoes the latest move that would close the loop, a layer moved into a parent someone else deleted returns to its previous parent, and a layer left without any parent goes back to its page ([#888](https://github.com/open-pencil/open-pencil/issues/888)).+- Show every peer in a shared room the same layer list in the same order. A layer moved to another parent stayed listed under its old one for others, reordering layers did not reach them, and layers added at the same time could end up in different orders or drop out of the Layers panel; now moves, reorders, and additions by different people merge, and only two people moving the same layer at once have one move win ([#889](https://github.com/open-pencil/open-pencil/issues/889)).+- Keep every layer two people add at the same time in a shared room. Each editor window started its layer IDs from the same counter, so layers added at once could get the same IDs and one person's would replace the other's; each window now mints IDs under a random session of its own, while the CLI and MCP server keep giving a file's layers the same IDs on every run.- Keep line breaks in multi-line text when exporting OpenPencil JSX, so `get_jsx` output and `openpencil export -f jsx` render back to the same text instead of joining the lines with spaces.- Announce unavailable commands in the command palette as disabled to screen readers.- Show an imported Figma page's background, and keep a background you change when you switch pages or save the document.@@ -146,6 +154,7 @@- Work with pages other than the one on screen through MCP, `eval`, and the CLI against the running app without switching to them: `openpencil export --page` and `--page-id` export that page instead of the selection, `export_image` and `openpencil export --node` export layers from any page instead of failing with "Raster export selection must stay on a single page", and a `.fig` page that has not been shown yet gets its layers, fonts, and layout before a command reads or changes it.- Fill the open subpaths of filled, unstroked SVG paths as if they were closed, as SVG does, in icons from `insert_icon` and Design JSX `<Icon>`, inline Design JSX `<svg>`, SVG from `import_svg` or dropped and pasted files, and SVG clip paths. Icons that cut holes with open subpaths, such as some Font Awesome icons, no longer render with those holes filled in, and filled `<polyline>` elements render filled instead of not at all.- Keep round and other stroke caps and joins after saving and reopening the file on icons from `insert_icon` and Design JSX `<Icon>`, and on vectors from inline Design JSX `<svg>`, `import_svg`, and dropped or pasted SVG files. They were set only on the stroke paint, which `.fig` does not store, so outline icons such as Lucide's reopened with butt caps and miter joins and showed gaps where their strokes meet.+- Join the right room from a pasted link that ends in a query, `#`, or `/`, and say so when pasted text is not a room link instead of joining an empty room.### Performancediff --git a/desktop/AGENTS.md b/desktop/AGENTS.mdindex 725aaf35e..5a8a719e9 100644--- a/desktop/AGENTS.md+++ b/desktop/AGENTS.md@@ -10,3 +10,4 @@ Check `desktop/Cargo.toml`, `desktop/capabilities/**`, and `desktop/tauri.conf.j- Run `bun run generate:icons --target desktop` before direct Cargo checks; native icons are generated, not committed.- `build_fig_file` performs `.fig` export on desktop; the browser path uses fflate (`packages/fig/AGENTS.md`).- The embedded WebDriver plugin compiles only with the `native-test` Cargo feature and must never be enabled in development or production binaries. Native tests use `bun run test:native` (`tests/AGENTS.md`).+- `openpencil://` links are parsed in `desktop/src/deep_link.rs`: `open` queues files through `take_pending_open`, `join` queues validated room IDs through `take_pending_rooms`; second launches forward their link arguments through the single-instance handler (`deep_link` unit tests).diff --git a/desktop/src/deep_link.rs b/desktop/src/deep_link.rsindex b913dadb9..7882ea2b4 100644--- a/desktop/src/deep_link.rs+++ b/desktop/src/deep_link.rs@@ -8,6 +8,18 @@ pub struct DeepLinkOpen {pub node: Option<String>,}+/// A collaboration room to open, from `openpencil://join?room=<id>`.+#[derive(Debug, PartialEq, Eq)]+pub struct DeepLinkJoin {+ pub room: String,+}++#[derive(Debug, PartialEq, Eq)]+pub enum DeepLink {+ Open(DeepLinkOpen),+ Join(DeepLinkJoin),+}+#[derive(Debug, PartialEq, Eq)]pub enum DeepLinkError {UnknownAction(String),@@ -15,10 +27,40 @@ pub enum DeepLinkError {AbsolutePath,ParentSegment,BadExtension,+ BadRoom,+}++/// Room IDs are 32 lowercase base36 characters (`ROOM_ID_LENGTH` and `ROOM_ID_CHARS` in+/// `src/constants.ts`); anything else is refused before it reaches the frontend.+const ROOM_ID_LENGTH: usize = 32;++fn is_room_id(room: &str) -> bool {+ room.len() == ROOM_ID_LENGTH+ && room+ .bytes()+ .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())+}++pub fn parse_deep_link(url: &Url) -> Result<DeepLink, DeepLinkError> {+ // openpencil://<action>?… → host is the action.+ match url.host_str().unwrap_or("") {+ "open" => parse_open_url(url).map(DeepLink::Open),+ "join" => parse_join_url(url).map(DeepLink::Join),+ action => Err(DeepLinkError::UnknownAction(action.to_string())),+ }+}++fn parse_join_url(url: &Url) -> Result<DeepLinkJoin, DeepLinkError> {+ let room = url+ .query_pairs()+ .find(|(key, _)| key == "room")+ .map(|(_, value)| value.into_owned())+ .filter(|room| is_room_id(room))+ .ok_or(DeepLinkError::BadRoom)?;+ Ok(DeepLinkJoin { room })}pub fn parse_open_url(url: &Url) -> Result<DeepLinkOpen, DeepLinkError> {- // openpencil://open?… → host is the action.let action = url.host_str().unwrap_or("");if action != "open" {return Err(DeepLinkError::UnknownAction(action.to_string()));@@ -149,6 +191,46 @@ mod tests {assert_eq!(parse("openpencil://open?file=a.pen").unwrap().node, None);}+ const ROOM: &str = "abcdefghijklmnopqrstuvwxyz012345";++ #[test]+ fn join_with_room() {+ assert_eq!(+ parse_deep_link(&Url::parse(&format!("openpencil://join?room={ROOM}")).unwrap()),+ Ok(DeepLink::Join(DeepLinkJoin { room: ROOM.into() }))+ );+ }++ #[test]+ fn join_refuses_a_room_that_is_not_a_room_id() {+ for url in [+ "openpencil://join".to_string(),+ "openpencil://join?room=".to_string(),+ "openpencil://join?room=short".to_string(),+ format!("openpencil://join?room={}", ROOM.to_uppercase()),+ format!("openpencil://join?room={ROOM}x"),+ format!("openpencil://join?room={}%2F", &ROOM[..31]),+ ] {+ assert_eq!(+ parse_deep_link(&Url::parse(&url).unwrap()),+ Err(DeepLinkError::BadRoom),+ "{url}"+ );+ }+ }++ #[test]+ fn deep_link_routes_open_and_refuses_other_actions() {+ assert!(matches!(+ parse_deep_link(&Url::parse("openpencil://open?file=a.pen").unwrap()),+ Ok(DeepLink::Open(_))+ ));+ assert_eq!(+ parse_deep_link(&Url::parse("openpencil://export?file=a.pen").unwrap()),+ Err(DeepLinkError::UnknownAction("export".into()))+ );+ }+#[test]fn unknown_action() {assert_eq!(diff --git a/desktop/src/lib.rs b/desktop/src/lib.rsindex 30cb693a2..9dbc3744b 100644--- a/desktop/src/lib.rs+++ b/desktop/src/lib.rs@@ -41,6 +41,18 @@ struct PendingOpenFile {struct PendingOpen(Mutex<Vec<PendingOpenFile>>);+/// Rooms from `openpencil://join` links, waiting for the frontend to open them.+struct PendingRooms(Mutex<Vec<String>>);++#[tauri::command]+fn take_pending_rooms(state: tauri::State<PendingRooms>) -> Vec<String> {+ state+ .0+ .lock()+ .map(|mut pending| pending.drain(..).collect())+ .unwrap_or_default()+}+#[tauri::command]fn take_pending_open(state: tauri::State<PendingOpen>) -> Vec<PendingOpenFile> {state@@ -243,23 +255,46 @@ fn queue_open_paths<R: tauri::Runtime>(app: &tauri::AppHandle<R>, paths: Vec<Pat/// `fs_scope().allow_file`: the frontend resolves them against open tabs or the/// file picker and allows the resolved absolute path there.fn queue_deep_links<R: tauri::Runtime>(app: &tauri::AppHandle<R>, urls: Vec<url::Url>) {- let files: Vec<PendingOpenFile> = urls- .iter()- .filter(|url| url.scheme() == "openpencil")- .filter_map(|url| match deep_link::parse_open_url(url) {- Ok(open) => Some(PendingOpenFile {+ let mut files = Vec::new();+ let mut rooms = Vec::new();+ for url in urls.iter().filter(|url| url.scheme() == "openpencil") {+ match deep_link::parse_deep_link(url) {+ Ok(deep_link::DeepLink::Open(open)) => files.push(PendingOpenFile {path: open.file,node: open.node,deep_link: true,}),- Err(error) => {- eprintln!("[deep-link] refused {url}: {error:?}");- None- }- })- .collect();+ Ok(deep_link::DeepLink::Join(join)) => rooms.push(join.room),+ Err(error) => eprintln!("[deep-link] refused {url}: {error:?}"),+ }+ }queue_pending(app, files);+ queue_rooms(app, rooms);+}++fn queue_rooms<R: tauri::Runtime>(app: &tauri::AppHandle<R>, rooms: Vec<String>) {+ if rooms.is_empty() {+ return;+ }++ if let Ok(mut pending) = app.state::<PendingRooms>().0.lock() {+ pending.extend(rooms);+ }++ let _ = app.emit("open-room-links", ());+ if let Some(window) = app.get_webview_window("main") {+ let _ = window.set_focus();+ }+}++/// `openpencil://` URLs among a second launch's arguments: Windows and Linux start a new+/// process for a link, and the single-instance plugin hands its arguments to this one.+fn deep_links_from_args(args: &[String]) -> Vec<url::Url> {+ args.iter()+ .filter(|arg| arg.starts_with("openpencil://"))+ .filter_map(|arg| url::Url::parse(arg).ok())+ .collect()}fn startup_open_paths() -> Vec<PathBuf> {@@ -285,6 +320,7 @@ pub fn run() {))]{builder = builder.plugin(tauri_plugin_single_instance::init(|app, args, cwd| {+ queue_deep_links(app, deep_links_from_args(&args));queue_open_paths(app, open_paths_from_args(args, Path::new(&cwd)));}));}@@ -293,6 +329,7 @@ pub fn run() {builder.manage(PendingOpen(Mutex::new(Vec::new())))+ .manage(PendingRooms(Mutex::new(Vec::new()))).invoke_handler(tauri::generate_handler![build_fig_file,credential_read,@@ -311,6 +348,7 @@ pub fn run() {native_menu_checked,set_native_menu_checked,take_pending_open,+ take_pending_rooms,webview_version]).plugin(tauri_plugin_opener::init())diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.tsindex f4be9a53d..5b3a75fea 100644--- a/packages/core/src/clipboard.ts+++ b/packages/core/src/clipboard.ts@@ -5,6 +5,7 @@ import { placeSlotContent } from '@open-pencil/fig/node-change'import { initCodec } from '@open-pencil/kiwi/fig/codec'import type { GUID, NodeChange as KiwiNodeChange } from '@open-pencil/kiwi/fig/codec'import { ownsSlotContent, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'+import { fractionalPosition } from '@open-pencil/scene-graph/order-keys'import {appendVariableNodeChanges,@@ -18,8 +19,7 @@ import {sceneNodeToKiwi,makeDocumentNodeChange,makeCanvasNodeChange,- buildFontDigestMap,- fractionalPosition+ buildFontDigestMap} from './kiwi/fig/node-change/serialize'import { buildDerivedTextDataV4 } from './text/derived-text/clipboard'diff --git a/packages/core/src/editor/component-sync.ts b/packages/core/src/editor/component-sync.tsindex ff893f68e..bc134f9e7 100644--- a/packages/core/src/editor/component-sync.ts+++ b/packages/core/src/editor/component-sync.ts@@ -1,7 +1,9 @@-import type { SceneGraph } from '@open-pencil/scene-graph'+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { computeAllLayouts } from '#core/layout'+const isComponent = (node: SceneNode) => node.type === 'COMPONENT'+function componentSyncOrder(graph: SceneGraph, seeds: Set<string>): string[] {const dependents = new Map<string, Set<string>>()const discover = (id: string): void => {@@ -9,10 +11,7 @@ function componentSyncOrder(graph: SceneGraph, seeds: Set<string>): string[] {const parents = new Set<string>()dependents.set(id, parents)for (const instance of graph.getInstances(id)) {- let parent = instance.parentId ? graph.getNode(instance.parentId) : undefined- while (parent && parent.type !== 'COMPONENT') {- parent = parent.parentId ? graph.getNode(parent.parentId) : undefined- }+ const parent = instance.parentId ? graph.closest(instance.parentId, isComponent) : undefinedif (parent) parents.add(parent.id)}for (const parent of parents) discover(parent)@@ -38,12 +37,7 @@ type ComputeLayouts = (graph: SceneGraph, scopeId?: string) => void/** Pages are `CANVAS` nodes; layout recomputation is scoped to them. */function pageIdOf(graph: SceneGraph, nodeId: string): string | null {- let current = graph.getNode(nodeId)- while (current) {- if (current.type === 'CANVAS') return current.id- current = current.parentId ? graph.getNode(current.parentId) : undefined- }- return null+ return graph.closest(nodeId, (node) => node.type === 'CANVAS')?.id ?? null}/**@@ -86,14 +80,8 @@ export function createComponentSyncScheduler(const graph = getGraph()const componentIds = new Set<string>()for (const id of ids) {- let current = graph.getNode(id)- while (current) {- if (current.type === 'COMPONENT') {- componentIds.add(current.id)- break- }- current = current.parentId ? graph.getNode(current.parentId) : undefined- }+ const component = graph.closest(id, isComponent)+ if (component) componentIds.add(component.id)}for (const compId of componentSyncOrder(graph, componentIds)) {graph.syncInstances(compId)diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 7961629bb..0459ff2f7 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -298,9 +298,9 @@ export {decompressFigKiwiDataAsync,buildFontDigestMap,sceneNodeToKiwi,- fractionalPosition,mapToFigmaType} from './kiwi/fig/node-change/serialize'+export { fractionalPosition } from '@open-pencil/scene-graph/order-keys'export { buildDerivedTextDataV4 } from './text/derived-text/clipboard'export { renderJSX, renderTree } from './design-jsx'diff --git a/packages/core/src/io/formats/fig/export.ts b/packages/core/src/io/formats/fig/export.tsindex 4ecaa4823..6409f24ca 100644--- a/packages/core/src/io/formats/fig/export.ts+++ b/packages/core/src/io/formats/fig/export.ts@@ -15,6 +15,7 @@ import { initCodec, getCompiledSchema, getSchemaBytes } from '@open-pencil/kiwi/import type { NodeChange } from '@open-pencil/kiwi/fig/codec'import { decodeBinarySchema, compileSchema, ByteBuffer } from '@open-pencil/kiwi/schema-runtime'import { ownsSlotContent, type SceneGraph } from '@open-pencil/scene-graph'+import { fractionalPosition } from '@open-pencil/scene-graph/order-keys'import type { GUID } from '@open-pencil/scene-graph/primitives'import type { SkiaRenderer } from '#core/canvas'@@ -24,7 +25,6 @@ import { findFigThumbnailPageId } from '#core/io/formats/fig/thumbnail-page'import { renderThumbnail } from '#core/io/formats/raster'import {sceneNodeToKiwi,- fractionalPosition,buildFontDigestMap,makeDocumentNodeChange,makeCanvasNodeChangediff --git a/packages/core/src/io/formats/fig/variable-export.ts b/packages/core/src/io/formats/fig/variable-export.tsindex bc6ff1af4..c93254308 100644--- a/packages/core/src/io/formats/fig/variable-export.ts+++ b/packages/core/src/io/formats/fig/variable-export.ts@@ -10,8 +10,9 @@ import {type SceneNode,type VariableValue} from '@open-pencil/scene-graph'+import { fractionalPosition } from '@open-pencil/scene-graph/order-keys'-import { fractionalPosition, safeColor } from '#core/kiwi/fig/node-change/serialize'+import { safeColor } from '#core/kiwi/fig/node-change/serialize'/*** Identity allocation shared by the two writers. The document exporter and the clipboarddiff --git a/packages/core/src/kiwi/fig/node-change/serialize.ts b/packages/core/src/kiwi/fig/node-change/serialize.tsindex 840395589..35d448d66 100644--- a/packages/core/src/kiwi/fig/node-change/serialize.ts+++ b/packages/core/src/kiwi/fig/node-change/serialize.ts@@ -12,7 +12,6 @@ export {buildFigKiwi,decompressFigKiwiDataAsync,FIG_KIWI_DEFAULT_VERSION,- fractionalPosition,makeCanvasNodeChange,makeDocumentNodeChange,mapToFigmaType,diff --git a/packages/docs/de/programmable/collaboration.md b/packages/docs/de/programmable/collaboration.mdindex 49273e198..a51c12eb6 100644--- a/packages/docs/de/programmable/collaboration.md+++ b/packages/docs/de/programmable/collaboration.md@@ -10,10 +10,20 @@ Mehrere Personen können dasselbe Dokument gleichzeitig bearbeiten. Die Teilnehm## Raum teilen1. Schaltfläche „Teilen“ oben rechts öffnen.-2. Den erzeugten Link `app.openpencil.dev/share/<room-id>` kopieren.+2. **Diese Datei teilen** wählen – der Link `app.openpencil.dev/share/<room-id>` wird kopiert.3. Link an die anderen Teilnehmer senden.-Jede Person mit dem Link kann beitreten. Der Raum bleibt erreichbar, solange mindestens ein Teilnehmer die Seite geöffnet hat.+Nur „Teilen“ bringt ein Dokument in einen Raum: Der Tab, aus dem Sie teilen, wird zum Tab des Raums und bleibt mit seiner Datei verbunden. Jede Person mit dem Link kann beitreten.++## Raum beitreten++Öffnen Sie den Link oder fügen Sie ihn (oder nur die Raumkennung) unter **Beitreten** im Teilen-Panel oder unter **Raum beitreten…** auf der Startseite ein. Der Raum öffnet sich in einem eigenen Tab, sodass bereits geöffnete Dokumente unverändert bleiben. Auf einem Computer bietet der Browser außerdem **In der Desktop-App öffnen** an; der Raum öffnet sich dann über einen `openpencil://join`-Link in OpenPencil.++Sie treten sofort unter einem erzeugten Namen wie *Teal Fox* bei. Ihren eigenen Namen legen Sie im Teilen-Panel oder in den Einstellungen fest; er gilt in jedem Raum.++Räume werden nicht auf einem Server gespeichert: Die Datei liegt auf den Geräten der Personen, die im Raum waren, daher öffnet ein Raum-Tab sein Dokument nur, solange eine von ihnen online ist. Bis dahin zeigt er an, dass er wartet, erklärt den Grund und öffnet die Datei, sobald jemand beitritt, der sie hat. Ein Raum, in dem Sie schon waren, öffnet sich sofort aus der Kopie auf diesem Gerät und synchronisiert Ihre Änderungen, sobald andere zurückkehren.++**Raum verlassen** im Teilen-Panel beendet Ihre Teilnahme am Raum. Ein Tab, der sein Dokument geteilt hat, wird wieder zu diesem Dokument; ein beigetretener Tab behält die Datei des Raums als lokale, ungespeicherte Kopie, die Sie speichern können. Jeder Raum-Tab hat eine eigene Verbindung, sodass Sie in mehreren Räumen gleichzeitig sein können.## Synchronisierte Daten@@ -34,7 +44,13 @@ Das Teilen-Panel listet alle Personen im Raum mit den Agenten auf, die sie ausfWebRTC überträgt die Designdaten direkt zwischen den Teilnehmern. Ein zentraler Anwendungsserver leitet die Änderungen nicht weiter.-Yjs synchronisiert den Dokumentzustand als CRDT und führt gleichzeitige Änderungen automatisch zusammen. IndexedDB speichert den lokalen Stand, sodass ein erneutes Öffnen desselben Raums ihn wiederherstellt.+Yjs synchronisiert den Dokumentzustand als CRDT und führt gleichzeitige Änderungen automatisch zusammen.++Auch das Verschieben und Umordnen von Ebenen wird zusammengeführt. Jede Ebene merkt sich jedes Elternelement, in das sie verschoben wurde, und ihre Position unter ihren Geschwistern; jeder Teilnehmer leitet daraus denselben Ebenenbaum ab ([Evan Wallaces Baum-CRDT](https://madebyevan.com/algos/crdt-mutable-tree-hierarchy/)). Verschiebungen, Umordnungen und neue Ebenen verschiedener Personen werden alle übernommen; verschieben zwei Personen gleichzeitig dieselbe Ebene, setzt sich bei allen dieselbe Verschiebung durch. Würden gleichzeitige Verschiebungen zwei Ebenen ineinander legen, wird die spätere rückgängig gemacht, und eine Ebene, deren neues Elternelement inzwischen gelöscht wurde, kehrt an ihren vorherigen Platz zurück.++Alle Teilnehmer eines Raums brauchen eine OpenPencil-Version, die den Ebenenbaum auf dieselbe Weise speichert; Versionen, die ihn anders speichern, sehen die Räume der jeweils anderen nicht.++IndexedDB speichert den lokalen Stand: Beim Neuladen der Seite treten Sie dem Raum automatisch mit demselben Stand wieder bei.## Hinweisediff --git a/packages/docs/pl/programmable/collaboration.md b/packages/docs/pl/programmable/collaboration.mdindex 1ed644ef4..1aaf66371 100644--- a/packages/docs/pl/programmable/collaboration.md+++ b/packages/docs/pl/programmable/collaboration.md@@ -10,10 +10,20 @@ Kilka osób może jednocześnie edytować jeden dokument. Uczestnicy łączą si## Udostępnianie pokoju1. Kliknij przycisk „Udostępnij” w prawym górnym rogu.-2. Skopiuj odnośnik `app.openpencil.dev/share/<room-id>`.+2. Kliknij **Udostępnij ten plik** — odnośnik `app.openpencil.dev/share/<room-id>` zostanie skopiowany.3. Wyślij go innym uczestnikom.-Dołączyć może każda osoba znająca odnośnik. Pokój pozostaje dostępny, dopóki co najmniej jeden uczestnik ma otwartą stronę.+Tylko udostępnienie umieszcza dokument w pokoju: karta, z której udostępniasz, staje się kartą pokoju i pozostaje powiązana ze swoim plikiem. Dołączyć może każda osoba znająca odnośnik.++## Dołączanie do pokoju++Otwórz odnośnik albo wklej go (lub sam identyfikator pokoju) w polu **Dołącz** w panelu udostępniania lub w **Dołącz do pokoju…** na ekranie startowym. Pokój otwiera się we własnej karcie, więc dokumenty, które masz już otwarte, się nie zmieniają. Na komputerze przeglądarka oferuje też **Otwórz w aplikacji na komputer**, co otwiera pokój w OpenPencil przez odnośnik `openpencil://join`.++Dołączasz od razu pod wygenerowaną nazwą, na przykład *Teal Fox*. Własną nazwę ustawisz w panelu udostępniania lub w ustawieniach; będzie używana w każdym pokoju.++Pokoje nie są przechowywane na serwerze: plik znajduje się na urządzeniach osób, które były w pokoju, więc karta pokoju otwiera dokument tylko wtedy, gdy któraś z nich jest online. Do tego czasu karta informuje, że czeka, wyjaśnia, dlaczego i otwiera plik, gdy tylko dołączy ktoś, kto go ma. Pokój, w którym już byłeś, otwiera się od razu z kopii na tym urządzeniu, a Twoje zmiany synchronizują się, gdy inni wrócą.++**Opuść pokój** w panelu udostępniania kończy Twój udział w pokoju. Karta, która udostępniła swój dokument, znów staje się tym dokumentem; karta, która dołączyła, zachowuje plik pokoju jako lokalną, niezapisaną kopię, którą możesz zapisać. Każda karta pokoju ma własne połączenie, więc możesz być w kilku pokojach jednocześnie.## Synchronizowane dane@@ -34,7 +44,13 @@ Panel udostępniania wyświetla wszystkich uczestników pokoju wraz z ich agentaUczestnicy łączą się bezpośrednio przez WebRTC, dlatego dane dokumentu są przesyłane między przeglądarkami bez centralnego serwera.-Stan dokumentu jest synchronizowany przez Yjs CRDT, który automatycznie łączy równoczesne zmiany. IndexedDB przechowuje stan lokalny, aby można go było odtworzyć po ponownym otwarciu tego samego pokoju.+Stan dokumentu jest synchronizowany przez Yjs CRDT, który automatycznie łączy równoczesne zmiany.++Przenoszenie i zmiana kolejności warstw również się scalają. Każda warstwa pamięta każdego rodzica, do którego została przeniesiona, i swoje miejsce wśród rodzeństwa, a każdy uczestnik wyznacza z tej historii to samo drzewo warstw ([CRDT drzewa Evana Wallace’a](https://madebyevan.com/algos/crdt-mutable-tree-hierarchy/)). Przeniesienia, zmiany kolejności i nowe warstwy od różnych osób są stosowane; jeśli dwie osoby jednocześnie przeniosą tę samą warstwę, u wszystkich wygrywa to samo przeniesienie. Gdy równoczesne przeniesienia umieściłyby dwie warstwy jedna w drugiej, późniejsze przeniesienie jest cofane, a warstwa, której nowy rodzic został w międzyczasie usunięty, wraca na swoje miejsce.++Wszyscy w pokoju potrzebują wersji OpenPencil, która zapisuje drzewo warstw w ten sam sposób; wersje zapisujące je inaczej nie widzą nawzajem swoich pokojów.++IndexedDB przechowuje stan lokalny: po odświeżeniu strony automatycznie wracasz do pokoju z tym samym stanem.## Wskazówkidiff --git a/packages/docs/programmable/collaboration.md b/packages/docs/programmable/collaboration.mdindex a66e2c231..6a3811085 100644--- a/packages/docs/programmable/collaboration.md+++ b/packages/docs/programmable/collaboration.md@@ -10,10 +10,20 @@ Edit designs together in real time. Peers connect directly — no server relays## Sharing a Room1. Click the share button in the top-right corner-2. Copy the generated link (`app.openpencil.dev/share/<room-id>`)+2. Click **Share this file** — the link (`app.openpencil.dev/share/<room-id>`) is copied3. Send it to your collaborators-Anyone with the link can join. The room stays active as long as at least one participant has the page open.+Only Share puts a document into a room: the tab you share from becomes the room's tab and stays tied to its file. Anyone with the link can join.++## Joining a Room++Open the link, or paste it (or just the room ID) into **Join** in the share panel or **Join room…** on Home. The room opens in a tab of its own, so the documents you already have open are never changed. On a computer, a browser also offers **Open in desktop app**, which opens the room in OpenPencil through an `openpencil://join` link.++You join right away under a generated name such as *Teal Fox*; set your own in the share panel or in Settings, and it is used in every room.++Rooms are not stored on a server: the file lives on the devices of the people who have been in the room, so a room tab opens its document only while one of them is online. Until then it says it is waiting, explains why, and opens the file as soon as someone who has it joins. A room you have been in before opens from this device's copy right away and syncs your changes when others return.++**Leave room** in the share panel ends your part in the room. A tab that shared its document goes back to being that document; a tab that joined keeps the room's file as a local unsaved copy you can save. Each room tab keeps its own connection, so you can be in several rooms at once.## What Syncs@@ -34,7 +44,11 @@ The share panel lists everyone in the room with the agents they run, what each aPeers connect directly via WebRTC — your design data goes straight from browser to browser, never through a central server. The document state uses a CRDT (conflict-free replicated data type), so concurrent edits merge automatically without conflicts.-The room persists locally — if you refresh the page, you rejoin with the same state.+Moving and reordering layers merges too. Each layer remembers every parent it has been moved into and its position among its siblings, and every peer works out the same layer tree from that history ([Evan Wallace's tree CRDT](https://madebyevan.com/algos/crdt-mutable-tree-hierarchy/)). Moves, reorders, and new layers from different people all apply; if two people move the same layer at once, one move wins on every peer. When moves made at the same time would put two layers inside each other, the later move is undone, and a layer whose new parent was deleted meanwhile returns to where it was.++Everyone in a room needs a version of OpenPencil that records the layer tree the same way; versions that record it differently do not see each other's rooms.++The room persists locally — if you refresh the page, you rejoin it automatically with the same state.## Tipsdiff --git a/packages/docs/ru/programmable/collaboration.md b/packages/docs/ru/programmable/collaboration.mdindex e7ff62acf..aa59b3833 100644--- a/packages/docs/ru/programmable/collaboration.md+++ b/packages/docs/ru/programmable/collaboration.md@@ -10,10 +10,20 @@ description: Одновременное редактирование напря## Отправка ссылки1. Нажмите кнопку «Поделиться» в правом верхнем углу.-2. Скопируйте ссылку `app.openpencil.dev/share/<room-id>`.+2. Нажмите **Поделиться файлом** — ссылка `app.openpencil.dev/share/<room-id>` будет скопирована.3. Отправьте её другим участникам.-Присоединиться может любой, у кого есть ссылка. Комната остаётся доступной, пока хотя бы один участник держит страницу открытой.+Документ попадает в комнату только через «Поделиться»: вкладка, из которой вы делитесь, становится вкладкой комнаты и остаётся связанной со своим файлом. Присоединиться может любой, у кого есть ссылка.++## Вход в комнату++Откройте ссылку или вставьте её (или только идентификатор комнаты) в поле **Войти** на панели «Поделиться» либо в **Войти в комнату…** на начальном экране. Комната открывается в отдельной вкладке, поэтому уже открытые документы не меняются. На компьютере браузер также предлагает **Открыть в настольном приложении** — комната откроется в OpenPencil по ссылке `openpencil://join`.++Вы входите сразу под сгенерированным именем, например *Teal Fox*. Своё имя можно задать на панели «Поделиться» или в настройках; оно используется во всех комнатах.++Комнаты не хранятся на сервере: файл находится на устройствах тех, кто был в комнате, поэтому вкладка комнаты открывает документ, только пока кто-то из них в сети. До тех пор она сообщает, что ждёт, объясняет почему и открывает файл, как только войдёт тот, у кого он есть. Комната, в которой вы уже были, сразу открывается из копии на этом устройстве, а ваши изменения синхронизируются, когда вернутся остальные.++**Покинуть комнату** на панели «Поделиться» завершает ваше участие. Вкладка, которая поделилась своим документом, снова становится этим документом; вкладка, которая вошла в комнату, сохраняет файл комнаты как локальную несохранённую копию, которую можно сохранить. У каждой вкладки комнаты своё соединение, поэтому можно быть в нескольких комнатах одновременно.## Что синхронизируется@@ -34,7 +44,13 @@ description: Одновременное редактирование напряУчастники соединяются напрямую через WebRTC, поэтому данные документа передаются из одного браузера в другой без центрального сервера.-Состояние документа синхронизируется с помощью Yjs CRDT. Одновременные изменения автоматически объединяются. IndexedDB хранит локальное состояние, поэтому после перезагрузки той же комнаты его можно восстановить.+Состояние документа синхронизируется с помощью Yjs CRDT. Одновременные изменения автоматически объединяются.++Перемещение и изменение порядка слоёв тоже объединяются. Каждый слой помнит всех родителей, в которые его перемещали, и своё место среди соседних слоёв, и каждый участник выводит из этой истории одно и то же дерево слоёв ([CRDT дерева Эвана Уоллеса](https://madebyevan.com/algos/crdt-mutable-tree-hierarchy/)). Перемещения, изменения порядка и новые слои от разных людей применяются все; если двое одновременно переместят один и тот же слой, у всех побеждает одно и то же перемещение. Если одновременные перемещения вложили бы два слоя друг в друга, более позднее отменяется, а слой, нового родителя которого тем временем удалили, возвращается на прежнее место.++Всем в комнате нужна версия OpenPencil, которая записывает дерево слоёв одинаково; версии, записывающие его по-разному, не видят комнат друг друга.++IndexedDB хранит локальное состояние: после перезагрузки страницы вы автоматически возвращаетесь в комнату с тем же состоянием.## Советыdiff --git a/packages/fig/src/node-change/basics.ts b/packages/fig/src/node-change/basics.tsindex dd12c961d..407eacab1 100644--- a/packages/fig/src/node-change/basics.ts+++ b/packages/fig/src/node-change/basics.ts@@ -42,113 +42,6 @@ export function mapToFigmaType(type: SceneNode['type']): string {}}-/** Generate a printable, lexicographically ordered parent position. */-export function fractionalPosition(index: number): string {- const BASE = 94- const FIRST = 33- const TILDE = 126- const numTildes = Math.floor(index / BASE)- const lastChar = String.fromCharCode(FIRST + (index % BASE))- return String.fromCharCode(TILDE).repeat(numTildes) + lastChar-}--const ORDER_KEY_MIN = 33 // '!'-const ORDER_KEY_MAX = 126 // '~'-const ORDER_KEY_MID = 'O'--/**- * A printable key strictly between `lo` and `hi` (either may be open), or null when none- * exists. Splits at the first character where they differ when a character fits between;- * otherwise keeps that character and recurses into the remainder, relying on string order.- */-export function orderKeyBetween(lo: string | null, hi: string | null): string | null {- if (lo !== null && hi !== null && lo >= hi) return null- const low = lo ?? ''- // An open upper bound shares no prefix, so the empty string ends the scan immediately.- const high = hi ?? ''- let i = 0- while (i < low.length && i < high.length && low[i] === high[i]) i++- const a = i < low.length ? low.charCodeAt(i) : ORDER_KEY_MIN - 1- const b = hi !== null && i < hi.length ? hi.charCodeAt(i) : ORDER_KEY_MAX + 1- if (b - a > 1) return low.slice(0, i) + String.fromCharCode(Math.floor((a + b) / 2))- // Keep lo's character: anything above the rest of lo then sorts below hi.- if (i < low.length) {- return low.slice(0, i + 1) + (orderKeyBetween(low.slice(i + 1), null) ?? ORDER_KEY_MID)- }- // lo is a prefix of hi whose next character can't be lowered: keep it and go below the rest.- const rest = hi?.slice(i + 1) ?? ''- if (!hi || rest === '') return null- return hi.slice(0, i + 1) + (orderKeyBetween(null, rest) ?? '')-}--/** Indices of the longest strictly increasing run of keys, so a moved layer re-keys alone. */-function increasingKeyIndices(sourceKeys: ReadonlyArray<string | null | undefined>): Set<number> {- const tails: number[] = []- const previous = new Map<number, number>()- for (let index = 0; index < sourceKeys.length; index++) {- const key = sourceKeys[index]- if (!key) continue- let low = 0- let high = tails.length- while (low < high) {- const mid = (low + high) >> 1- if ((sourceKeys[tails[mid]] ?? '') < key) low = mid + 1- else high = mid- }- // A key with nothing below it cannot start the run once a sibling has to precede it.- if (low === 0 && index > 0 && orderKeyBetween(null, key) === null) continue- if (low > 0) previous.set(index, tails[low - 1])- tails[low] = index- }- const kept = new Set<number>()- for (let index = tails.at(-1); index !== undefined; index = previous.get(index)) kept.add(index)- return kept-}--/**- * Order keys for siblings in their current order. The longest increasing run of imported keys- * is kept; other siblings get the index key when it fits between their neighbours, and- * otherwise a key between them, so no two siblings share a key.- */-export function siblingOrderKeys(sourceKeys: ReadonlyArray<string | null | undefined>): string[] {- const keys: string[] = []- let prev: string | null = null- let pending: number[] = []-- const fill = (upper: string | null): string[] | null => {- const filled: string[] = []- let lo = prev- for (const index of pending) {- const candidate = fractionalPosition(index)- const key =- (lo === null || candidate > lo) && (upper === null || candidate < upper)- ? candidate- : orderKeyBetween(lo, upper)- if (key === null) return null- filled.push(key)- lo = key- }- return filled- }-- const kept = increasingKeyIndices(sourceKeys)- for (let index = 0; index < sourceKeys.length; index++) {- const key = sourceKeys[index]- const filled = key && kept.has(index) ? fill(key) : null- if (key && filled) {- pending.forEach((pendingIndex, i) => (keys[pendingIndex] = filled[i]))- keys[index] = key- prev = key- pending = []- } else {- pending.push(index)- }- }- const rest = fill(null) ?? []- pending.forEach((pendingIndex, i) => (keys[pendingIndex] = rest[i]))- return keys-}-export function computeExportTransform(node: SceneNode): Matrix {const sx = node.flipX ? -1 : 1const cos = Math.cos((node.rotation * Math.PI) / 180)diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.tsindex 1e914e5fa..d11f1b960 100644--- a/packages/fig/src/node-change/export/node.ts+++ b/packages/fig/src/node-change/export/node.ts@@ -14,10 +14,10 @@ import {OPEN_PENCIL_PLUGIN_DATA,withPluginData} from '@open-pencil/scene-graph'+import { siblingOrderKeys } from '@open-pencil/scene-graph/order-keys'import type { GUID, Matrix, Vector } from '@open-pencil/scene-graph/primitives'/* eslint-disable max-lines */-import { siblingOrderKeys } from '../basics'import { bytesToHex } from '../bytes'import { exportCanvasGuides } from '../canvas-guides'import { snapshotInstanceGeometry } from '../instance/geometry'diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.tsindex 92dda06a1..c6f1ee667 100644--- a/packages/fig/src/node-change/serialize.ts+++ b/packages/fig/src/node-change/serialize.ts@@ -4,9 +4,10 @@ import {weightToStyle,withPluginData} from '@open-pencil/scene-graph'+import { fractionalPosition } from '@open-pencil/scene-graph/order-keys'import { effectiveFigmaRawNodeFields } from '../source-metadata'-import { computeExportTransform, fractionalPosition, mapToFigmaType } from './basics'+import { computeExportTransform, mapToFigmaType } from './basics'import { bytesToHex } from './bytes'import { buildDerivedTextData as buildSharedDerivedTextData } from './derived-text/data'import { EMPTY_EXPORT_RUNTIME, type FigNodeChangeExportRuntime } from './export/runtime'diff --git a/packages/fig/tests/node-change/export.test.ts b/packages/fig/tests/node-change/export.test.tsindex 86da3eef5..1aca79603 100644--- a/packages/fig/tests/node-change/export.test.ts+++ b/packages/fig/tests/node-change/export.test.ts@@ -5,19 +5,18 @@ import { componentPropDefsOf, componentPropRefsOf } from '#fig-tests/helpers/comimport { symbolDataOf } from '#fig/instance-overrides/types'import {buildComponentPropIndex,- fractionalPosition,mapToFigmaType,sceneNodeToKiwi,type FigNodeChangeExportRuntime} from '#fig/node-change/index'import { SceneGraph } from '@open-pencil/scene-graph'+import { fractionalPosition } from '@open-pencil/scene-graph/order-keys'import type { GUID } from '@open-pencil/scene-graph/primitives'describe('@open-pencil/fig SceneGraph export policy', () => {- test('maps node types and sibling positions deterministically', () => {+ test('maps node types deterministically', () => {expect(mapToFigmaType('COMPONENT')).toBe('SYMBOL')- expect([0, 93, 94, 188].map(fractionalPosition)).toEqual(['!', '~', '~!', '~~!'])})test('exports one ordering scheme when preserved and generated siblings are mixed', () => {@@ -471,3 +470,35 @@ describe('@open-pencil/fig SceneGraph export policy', () => {])})})++function expectStrictlyIncreasing(keys: string[]) {+ for (let i = 1; i < keys.length; i++) expect(keys[i] > keys[i - 1]).toBe(true)+}++describe('Figma export order keys', () => {+ test('a layer added before imported siblings does not share their keys', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const frame = graph.createNode('FRAME', page.id, { name: 'Frame' })+ for (const [name, orderKey] of [+ ['A', '!'],+ ['B', '"'],+ ['C', '#']+ ]) {+ const child = graph.createNode('RECTANGLE', frame.id, { name })+ child.source.orderKey = orderKey+ }+ const inserted = graph.createNode('RECTANGLE', frame.id, { name: 'Inserted' })+ frame.childIds = [inserted.id, ...frame.childIds.filter((id) => id !== inserted.id)]++ const changes = sceneNodeToKiwi(frame, { sessionID: 1, localID: 1 }, 0, { value: 2 }, graph, [])+ const children = changes.slice(1)+ const positions = children.map((change) => change.parentIndex?.position ?? '')++ expect(children.map((change) => change.name)).toEqual(['Inserted', 'A', 'B', 'C'])+ // Nothing sorts before '!', so A is re-keyed; B and C keep their imported keys.+ expect(positions.slice(2)).toEqual(['"', '#'])+ expect(new Set(positions).size).toBe(4)+ expectStrictlyIncreasing(positions)+ })+})diff --git a/packages/scene-graph/AGENTS.md b/packages/scene-graph/AGENTS.mdindex 6503b3547..7e4be1219 100644--- a/packages/scene-graph/AGENTS.md+++ b/packages/scene-graph/AGENTS.md@@ -3,6 +3,8 @@Framework-neutral document model. Owns node types, primitives, geometry, matrices, copy/snap/undo helpers, variables, instances, hit testing, and checkpoint recovery.- Nodes live in a flat `Map<string, SceneNode>`; runtime hierarchy uses `parentId` and `childIds`. Frames do not clip by default.+- Walk up the tree with `SceneGraph.closest()` or `isDescendant()`, which stop on a parent cycle in bad data, rather than a hand-written `parentId` loop (`packages/scene-graph/tests/basic/graph.test.ts`).+- Change a live graph's hierarchy through `reparentNode`, `reorderChild`, `insertChildAt`, or `updateNode`, which emit the events collaboration syncs; assign `childIds` directly only on a graph copy or nodes created in the same edit (`sortInstanceChildren` in `packages/scene-graph/src/instances/sync.ts`).- Geometry is built on the matrices in `packages/scene-graph/src/matrix.ts` and `packages/scene-graph/src/coordinate.ts` (`getWorldMatrix`, `getAxisAlignedWorldBounds`, `getNodeLocalMatrix`). Add new transform, bounds, or inverse helpers here beside them; do not interpret ancestor rotations or reflections independently elsewhere. LINE pivots remain at the origin; other nodes rotate around their centers.- Bounds accumulation goes through the helpers in `packages/scene-graph/src/geometry.ts` (`computeBounds`, `computeAbsoluteBounds`, `computeVisualBounds`); do not add another min/max loop.- Reparenting preserves child world positions; groups preserve them too. Sort children geometrically before creating auto-layout. Consumers such as layer trees must react to reparenting rather than retaining stale child references.@@ -10,7 +12,7 @@ Framework-neutral document model. Owns node types, primitives, geometry, matrice- Instance children map to component children through `componentId`; runtime overrides use the structured `InstanceOverrideState` (`self` and `descendants` maps) in `packages/scene-graph/src/instance-overrides.ts`.- A bound numeric field records its unit conversion in `variableBindingScales`; preserve it through clone, copy, and transfer so a binding keeps meaning in its new scope. Core reconciles bindings and layout together in `packages/core/src/layout/variables.ts`, which the editor and the Figma API both call rather than reimplementing.- `componentScale` records an occurrence's coordinates relative to its component definition. Shared rescaling lives in `packages/scene-graph/src/scaling/`; Core's Figma API delegates there instead of scaling nodes itself.-- Shared primitives that format packages need live here: color conversion and management under `@open-pencil/scene-graph/color` and text/layout direction under `@open-pencil/scene-graph/text-direction`.+- Shared primitives that format packages and collaboration need live here: color conversion and management under `@open-pencil/scene-graph/color`, text/layout direction under `@open-pencil/scene-graph/text-direction`, and fractional sibling order keys under `@open-pencil/scene-graph/order-keys` (`packages/scene-graph/tests/order-keys.test.ts`).- CSS values that become scene-graph types, such as grid track lists, are parsed in `@open-pencil/scene-graph/css` on `postcss-value-parser`; design-jsx and dom-css call it instead of splitting or matching CSS by hand (`packages/scene-graph/tests/css`).- Every plugin-data key OpenPencil writes is a field of `OPEN_PENCIL_PLUGIN_DATA` in `packages/scene-graph/src/plugin-data/fields.ts`, with the Valibot schema that reads it; read and replace entries with `readPluginData` and `withPluginData` instead of matching `pluginId` and `key` by hand. The fields test checks that keys stay unique.- Vector network types live here; the reverse-engineered `vectorNetworkBlob` codecs live in `packages/core/src/vector/`.diff --git a/packages/scene-graph/package.json b/packages/scene-graph/package.jsonindex 6db84f577..214f115e3 100644--- a/packages/scene-graph/package.json+++ b/packages/scene-graph/package.json@@ -173,6 +173,12 @@"import": "./dist/random.js","default": "./dist/random.js"},+ "./order-keys": {+ "types": "./dist/order-keys.d.ts",+ "bun": "./src/order-keys.ts",+ "import": "./dist/order-keys.js",+ "default": "./dist/order-keys.js"+ },"./parse-path": {"types": "./dist/parse-path.d.ts","bun": "./src/parse-path.ts",diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex 6f2ce4d86..5161e7a87 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -103,10 +103,26 @@ export {vectorNetworksEqual} from './vector-network'+const MAX_ID_SESSION = 0xffffffff++let idSession = 0let nextLocalID = 1+/**+ * Sets the session part of the IDs this process mints, as in Figma's `sessionID:localID` GUIDs.+ * Headless tools keep session 0, so a file's layers get the same IDs on every run. The editor+ * picks a random session at startup, as Yjs picks each document's `clientID`, so peers editing+ * one shared room never mint the same ID. Call it before creating any graph.+ */+export function setIdSession(sessionId: number): void {+ if (!Number.isInteger(sessionId) || sessionId < 0 || sessionId > MAX_ID_SESSION) {+ throw new RangeError('sessionId must be an unsigned 32-bit integer')+ }+ idSession = sessionId+}+export function generateId(): string {- return `0:${nextLocalID++}`+ return `${idSession}:${nextLocalID++}`}function stripUndefinedProps<T extends object>(obj: T): T {@@ -331,12 +347,20 @@ export class SceneGraph {}isDescendant(childId: string, ancestorId: string): boolean {- let current = this.nodes.get(childId)- while (current) {- if (current.id === ancestorId) return true+ return this.closest(childId, (node) => node.id === ancestorId) !== undefined+ }++ /**+ * The node itself or its nearest ancestor that matches. The walk visits at most as many nodes+ * as the graph holds, so a parent cycle in bad data cannot hang it.+ */+ closest(id: string, match: (node: SceneNode) => boolean): SceneNode | undefined {+ let current = this.nodes.get(id)+ for (let steps = 0; current && steps < this.nodes.size; steps++) {+ if (match(current)) return currentcurrent = current.parentId ? this.nodes.get(current.parentId) : undefined}- return false+ return undefined}clearAbsPosCache(): void {diff --git a/packages/scene-graph/src/instances/sync.ts b/packages/scene-graph/src/instances/sync.tsindex 9f104dbc4..a2efa8d1d 100644--- a/packages/scene-graph/src/instances/sync.ts+++ b/packages/scene-graph/src/instances/sync.ts@@ -362,7 +362,13 @@ function sortInstanceChildren(const componentIndex = mapped ? orderMap.get(mapped) : undefinedranks.set(childId, componentIndex ?? compChildOrder.length + index)}- instParent.childIds.sort((left, right) => (ranks.get(left) ?? 0) - (ranks.get(right) ?? 0))+ const sorted = instParent.childIds.toSorted(+ (left, right) => (ranks.get(left) ?? 0) - (ranks.get(right) ?? 0)+ )+ // Move through the graph so the reorder is reported, as collaboration syncs it.+ sorted.forEach((childId, index) => {+ if (instParent.childIds[index] !== childId) graph.insertChildAt(childId, instParentId, index)+ })}/** True when syncing `compParentId` into `instParentId` would form a cycle. */diff --git a/packages/scene-graph/src/order-keys.ts b/packages/scene-graph/src/order-keys.tsnew file mode 100644index 000000000..2e0a3f8ea--- /dev/null+++ b/packages/scene-graph/src/order-keys.ts@@ -0,0 +1,162 @@+/**+ * Fractional order keys: printable-ASCII strings (`!` to `~`) that order siblings by plain string+ * comparison, as Figma writes `parentIndex.position`. A new key fits between two neighbours+ * without renumbering the others.+ */++const ORDER_KEY_MIN = 33 // '!'+const ORDER_KEY_MAX = 126 // '~'+const ORDER_KEY_MID = 'O'+const INDEX_KEY_BASE = ORDER_KEY_MAX - ORDER_KEY_MIN + 1++/** The order key for position `index` of a freshly numbered sibling list. */+export function fractionalPosition(index: number): string {+ const numTildes = Math.floor(index / INDEX_KEY_BASE)+ const lastChar = String.fromCharCode(ORDER_KEY_MIN + (index % INDEX_KEY_BASE))+ return String.fromCharCode(ORDER_KEY_MAX).repeat(numTildes) + lastChar+}++/**+ * The shortest key strictly between `lo` and `hi` (either may be open), or null when the+ * printable alphabet has none. Splits at the first character where they differ when a character+ * fits between; otherwise keeps that character and recurses into the remainder.+ */+function keyBetween(lo: string | null, hi: string | null): string | null {+ if (lo !== null && hi !== null && lo >= hi) return null+ const low = lo ?? ''+ // An open upper bound shares no prefix, so the empty string ends the scan immediately.+ const high = hi ?? ''+ let i = 0+ while (i < low.length && i < high.length && low[i] === high[i]) i+++ const a = i < low.length ? low.charCodeAt(i) : ORDER_KEY_MIN - 1+ const b = hi !== null && i < hi.length ? hi.charCodeAt(i) : ORDER_KEY_MAX + 1+ if (b - a > 1) return low.slice(0, i) + String.fromCharCode(Math.floor((a + b) / 2))+ // Keep lo's character: anything above the rest of lo then sorts below hi.+ if (i < low.length) {+ return low.slice(0, i + 1) + (keyBetween(low.slice(i + 1), null) ?? ORDER_KEY_MID)+ }+ // lo is a prefix of hi whose next character can't be lowered: keep it and go below the rest.+ const rest = hi?.slice(i + 1) ?? ''+ if (!hi || rest === '') return null+ return hi.slice(0, i + 1) + (keyBetween(null, rest) ?? '')+}++/** A key above `lo` that has room for `suffix` while staying below `hi`, or null. */+function keyWithSuffix(lo: string | null, hi: string, suffix: string): string | null {+ // A key that is a prefix of hi leaves no room after it; go one level deeper until it is not.+ for (let key = keyBetween(lo, hi); key !== null; key = keyBetween(key, hi)) {+ if (key + suffix < hi) return key + suffix+ if (!hi.startsWith(key)) return null+ }+ return null+}++/**+ * A key above `lo` and below `hi`; either bound may be open.+ *+ * `suffix`, a few random printable characters, is appended where it fits, so two peers that+ * insert at the same spot at once get distinct keys with room between them. The key stays short:+ * it grows by about one character for every five keys inserted into the same gap.+ *+ * Every pair of bounds gets a key. When no printable key sorts between them, because `lo` is not+ * below `hi` or `hi` is `lo` followed only by `!`, the result is the key `orderKeyBetween(lo, null)`+ * gives, which is above `lo` but not below `hi`, and the caller must re-key `hi`.+ */+export function orderKeyBetween(lo: string | null, hi: string | null, suffix = ''): string {+ const key = keyBetween(lo, hi)+ if (key === null) return (keyBetween(lo, null) ?? ORDER_KEY_MID) + suffix+ if (!suffix) return key+ if (hi === null) return key + suffix+ return keyWithSuffix(lo, hi, suffix) ?? key+}++/** Whether some printable key sorts strictly between `lo` and `hi`. */+export function hasOrderKeyBetween(lo: string | null, hi: string | null): boolean {+ return keyBetween(lo, hi) !== null+}++/** Indices of the longest strictly increasing run of keys, so a moved layer re-keys alone. */+function increasingKeyIndices(sourceKeys: ReadonlyArray<string | null | undefined>): Set<number> {+ const tails: number[] = []+ const previous = new Map<number, number>()+ for (let index = 0; index < sourceKeys.length; index++) {+ const key = sourceKeys[index]+ if (!key) continue+ let low = 0+ let high = tails.length+ while (low < high) {+ const mid = (low + high) >> 1+ if ((sourceKeys[tails[mid]] ?? '') < key) low = mid + 1+ else high = mid+ }+ // A key with nothing below it cannot start the run once a sibling has to precede it.+ if (low === 0 && index > 0 && !hasOrderKeyBetween(null, key)) continue+ if (low > 0) previous.set(index, tails[low - 1])+ tails[low] = index+ }+ const kept = new Set<number>()+ for (let index = tails.at(-1); index !== undefined; index = previous.get(index)) kept.add(index)+ return kept+}++export interface SiblingOrderKeyOptions {+ /**+ * Returns a suffix for each key the function makes up, as `orderKeyBetween` takes. Without it,+ * a sibling that needs a key gets its index key when that fits between its neighbours.+ */+ suffix?: () => string+}++/**+ * Order keys for siblings in their current order. The longest increasing run of existing keys+ * is kept; other siblings get the index key when it fits between their neighbours (or a key with+ * a suffix, when `options.suffix` is given), and otherwise a key between them, so no two siblings+ * share a key.+ */+export function siblingOrderKeys(+ sourceKeys: ReadonlyArray<string | null | undefined>,+ options: SiblingOrderKeyOptions = {}+): string[] {+ const keys: string[] = []+ let prev: string | null = null+ let pending: number[] = []++ const nextKey = (index: number, lo: string | null, upper: string | null): string | null => {+ if (options.suffix) {+ const key = orderKeyBetween(lo, upper, options.suffix())+ return upper === null || key < upper ? key : null+ }+ const candidate = fractionalPosition(index)+ if ((lo === null || candidate > lo) && (upper === null || candidate < upper)) return candidate+ return keyBetween(lo, upper)+ }++ const fill = (upper: string | null): string[] | null => {+ const filled: string[] = []+ let lo = prev+ for (const index of pending) {+ const key = nextKey(index, lo, upper)+ if (key === null) return null+ filled.push(key)+ lo = key+ }+ return filled+ }++ const kept = increasingKeyIndices(sourceKeys)+ for (let index = 0; index < sourceKeys.length; index++) {+ const key = sourceKeys[index]+ const filled = key && kept.has(index) ? fill(key) : null+ if (key && filled) {+ pending.forEach((pendingIndex, i) => (keys[pendingIndex] = filled[i]))+ keys[index] = key+ prev = key+ pending = []+ } else {+ pending.push(index)+ }+ }+ const rest = fill(null) ?? []+ pending.forEach((pendingIndex, i) => (keys[pendingIndex] = rest[i]))+ return keys+}diff --git a/packages/scene-graph/tests/basic/graph.test.ts b/packages/scene-graph/tests/basic/graph.test.tsindex 2b24ef4ec..995388999 100644--- a/packages/scene-graph/tests/basic/graph.test.ts+++ b/packages/scene-graph/tests/basic/graph.test.ts@@ -265,6 +265,17 @@ describe('SceneGraph', () => {expect(graph.getAbsolutePosition(child)).toEqual({ x: 110, y: 110 })})+ test('ancestor walks stop on a parent cycle', () => {+ const graph = new SceneGraph()+ const first = graph.createNode('FRAME', pageId(graph))+ const second = graph.createNode('FRAME', first.id)+ graph.updateNode(first.id, { parentId: second.id })++ expect(graph.isDescendant(second.id, pageId(graph))).toBe(false)+ expect(graph.closest(second.id, (node) => node.type === 'CANVAS')).toBeUndefined()+ expect(graph.closest(second.id, (node) => node.id === first.id)).toBe(first)+ })+test('children order', () => {const graph = new SceneGraph()rect(graph, 'A')diff --git a/packages/scene-graph/tests/basic/id-generator.test.ts b/packages/scene-graph/tests/basic/id-generator.test.tsindex ee946e0c1..ee2097ad2 100644--- a/packages/scene-graph/tests/basic/id-generator.test.ts+++ b/packages/scene-graph/tests/basic/id-generator.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from 'bun:test'-import { SceneGraph } from '@open-pencil/scene-graph'+import { SceneGraph, setIdSession } from '@open-pencil/scene-graph'import { pageId } from './helpers'@@ -64,6 +64,24 @@ describe('SceneGraph ID generator', () => {expect(new Set(ids).size).toBe(ids.length)})+ test('the ID session prefixes every ID minted afterwards', () => {+ try {+ setIdSession(4_000_000_000)+ const graph = new SceneGraph()+ const ids = [graph.rootId, pageId(graph), graph.createCollection('Colors').id]+ for (const id of ids) expect(id).toMatch(/^4000000000:\d+$/)+ } finally {+ setIdSession(0)+ }+ expect(new SceneGraph().rootId).toMatch(/^0:\d+$/)+ })++ test('rejects an ID session that is not an unsigned 32-bit integer', () => {+ for (const value of [-1, 1.5, 2 ** 32, Number.NaN]) {+ expect(() => setIdSession(value)).toThrow(RangeError)+ }+ })+test('gives a new collection and its default mode different IDs even if the generator repeats', () => {const ids = ['7:1', '7:2', 'same', 'same', '7:3']const graph = new SceneGraph(() => ids.shift() ?? 'exhausted')diff --git a/packages/fig/tests/node-change/order-keys.test.ts b/packages/scene-graph/tests/order-keys.test.tssimilarity index 54%rename from packages/fig/tests/node-change/order-keys.test.tsrename to packages/scene-graph/tests/order-keys.test.tsindex e37f95f35..8cb65bde9 100644--- a/packages/fig/tests/node-change/order-keys.test.ts+++ b/packages/scene-graph/tests/order-keys.test.ts@@ -2,21 +2,26 @@ import { describe, expect, test } from 'bun:test'import {fractionalPosition,+ hasOrderKeyBetween,orderKeyBetween,- sceneNodeToKiwi,siblingOrderKeys-} from '@open-pencil/fig/node-change'-import { SceneGraph } from '@open-pencil/scene-graph'--function requireKey(key: string | null, label: string): string {- if (key === null) throw new Error(`expected a key ${label}`)- return key-}+} from '@open-pencil/scene-graph/order-keys'function expectStrictlyIncreasing(keys: string[]) {for (let i = 1; i < keys.length; i++) expect(keys[i] > keys[i - 1]).toBe(true)}+function expectBetween(key: string, lo: string | null, hi: string | null) {+ if (lo !== null) expect(key > lo).toBe(true)+ if (hi !== null) expect(key < hi).toBe(true)+}++describe('fractionalPosition', () => {+ test('numbers siblings with printable keys that sort in index order', () => {+ expect([0, 93, 94, 188].map(fractionalPosition)).toEqual(['!', '~', '~!', '~~!'])+ })+})+describe('orderKeyBetween', () => {test('returns a key strictly between its bounds', () => {for (const [lo, hi] of [@@ -26,30 +31,74 @@ describe('orderKeyBetween', () => {['a', 'b'],[null, null]] as const) {- const key = requireKey(orderKeyBetween(lo, hi), `between ${lo} and ${hi}`)- if (lo !== null) expect(key > lo).toBe(true)- if (hi !== null) expect(key < hi).toBe(true)+ expectBetween(orderKeyBetween(lo, hi), lo, hi)}})test('stops at a longer prefix of hi when no character can be lowered', () => {expect(orderKeyBetween('a', 'a!!')).toBe('a!')expect(orderKeyBetween(null, '!!')).toBe('!')- expect(orderKeyBetween('a', 'a!')).toBeNull()})test('keeps keys short when many keys are appended one after another', () => {let lo = '$'for (let n = 0; n < 500; n++) {- const key = requireKey(orderKeyBetween(lo, null), 'after ' + lo)+ const key = orderKeyBetween(lo, null)expect(key > lo).toBe(true)lo = key}expect(lo.length).toBeLessThan(100)})- test('returns null when nothing sorts before the smallest key', () => {- expect(orderKeyBetween(null, '!')).toBeNull()+ test('returns a key above lo when no printable key fits below hi', () => {+ for (const [lo, hi] of [+ [null, '!'],+ ['a', 'a!'],+ ['b', 'a'],+ ['a', 'a']+ ] as const) {+ expect(hasOrderKeyBetween(lo, hi)).toBe(false)+ const key = orderKeyBetween(lo, hi)+ expect(key).toBe(orderKeyBetween(lo, null))+ if (lo !== null) expect(key > lo).toBe(true)+ }+ })++ test('appends a suffix that keeps the key between its bounds', () => {+ for (const [lo, hi] of [+ [null, null],+ ['!', '#'],+ ['a', 'a!!!'],+ ['~', null],+ [null, '"']+ ] as const) {+ expectBetween(orderKeyBetween(lo, hi, 'xyz'), lo, hi)+ }+ expect(orderKeyBetween('!', '#', 'xyz')).toBe('"xyz')+ })++ test('drops the suffix when only a bare key fits', () => {+ // 'a!' is the only printable key between these bounds; nothing can follow it.+ expect(orderKeyBetween('a', 'a!!', 'xyz')).toBe('a!')+ })++ test('gives inserts at one spot with different suffixes distinct keys with room between', () => {+ const first = orderKeyBetween('!', '#', 'AAA')+ const second = orderKeyBetween('!', '#', 'zzz')+ expect(first < second).toBe(true)+ expectBetween(orderKeyBetween(first, second, 'mmm'), first, second)+ })++ test('keeps keys bounded when many keys are inserted into one gap', () => {+ const suffixes = ['Kq7', '#a~', 'P0P', '!!z', '~~~']+ let hi = '#'+ for (let n = 0; n < 1000; n++) {+ const key = orderKeyBetween('!', hi, suffixes[n % suffixes.length])+ expectBetween(key, '!', hi)+ hi = key+ }+ // Each character halves the gap about six times, so a key grows by one every few inserts.+ expect(hi.length).toBeLessThan(250)})})@@ -100,13 +149,26 @@ describe('siblingOrderKeys', () => {expect(new Set(keys).size).toBe(keys.length)expectStrictlyIncreasing(keys)})++ test('re-keys a sibling that leaves no room before the next key', () => {+ const keys = siblingOrderKeys(['a', undefined, 'a!'])+ expect(new Set(keys).size).toBe(3)+ expectStrictlyIncreasing(keys)+ })++ test('suffixes the keys it makes up when asked to', () => {+ const keys = siblingOrderKeys(['!', undefined, undefined, '%'], { suffix: () => 'Q' })+ expect(keys[0]).toBe('!')+ expect(keys[3]).toBe('%')+ expect(keys[1].endsWith('Q')).toBe(true)+ expectStrictlyIncreasing(keys)+ })})describe('Figma keys containing spaces', () => {// Real Figma files use keys such as '&RQTOt7CO O'; the space sorts below the printable range.test('finds a key between a key and its space-extended successor', () => {- const key = requireKey(orderKeyBetween('&RQTOt7CO', '&RQTOt7CO O'), 'before the space key')- expect(key > '&RQTOt7CO' && key < '&RQTOt7CO O').toBe(true)+ expectBetween(orderKeyBetween('&RQTOt7CO', '&RQTOt7CO O'), '&RQTOt7CO', '&RQTOt7CO O')})test('keeps space-bearing imported keys and fits new layers between them', () => {@@ -118,31 +180,3 @@ describe('Figma keys containing spaces', () => {expectStrictlyIncreasing(keys)})})--describe('Figma export order keys', () => {- test('a layer added before imported siblings does not share their keys', () => {- const graph = new SceneGraph()- const page = graph.getPages()[0]- const frame = graph.createNode('FRAME', page.id, { name: 'Frame' })- for (const [name, orderKey] of [- ['A', '!'],- ['B', '"'],- ['C', '#']- ]) {- const child = graph.createNode('RECTANGLE', frame.id, { name })- child.source.orderKey = orderKey- }- const inserted = graph.createNode('RECTANGLE', frame.id, { name: 'Inserted' })- frame.childIds = [inserted.id, ...frame.childIds.filter((id) => id !== inserted.id)]-- const changes = sceneNodeToKiwi(frame, { sessionID: 1, localID: 1 }, 0, { value: 2 }, graph, [])- const children = changes.slice(1)- const positions = children.map((change) => change.parentIndex?.position ?? '')-- expect(children.map((change) => change.name)).toEqual(['Inserted', 'A', 'B', 'C'])- // Nothing sorts before '!', so A is re-keyed; B and C keep their imported keys.- expect(positions.slice(2)).toEqual(['"', '#'])- expect(new Set(positions).size).toBe(4)- expectStrictlyIncreasing(positions)- })-})diff --git a/packages/scene-graph/tsdown.config.ts b/packages/scene-graph/tsdown.config.tsindex c918a3cd2..a698af812 100644--- a/packages/scene-graph/tsdown.config.ts+++ b/packages/scene-graph/tsdown.config.ts@@ -29,6 +29,7 @@ export default defineConfig({resize: './src/resize.ts','parse-path': './src/parse-path.ts',random: './src/random.ts',+ 'order-keys': './src/order-keys.ts',color: './src/color/index.ts',css: './src/css/index.ts','text-direction': './src/text-direction.ts'diff --git a/packages/vue/src/i18n/locales/de/collaboration.json b/packages/vue/src/i18n/locales/de/collaboration.jsonindex a430d9004..8f15cbdfd 100644--- a/packages/vue/src/i18n/locales/de/collaboration.json+++ b/packages/vue/src/i18n/locales/de/collaboration.json@@ -1,5 +1,6 @@{"inThisRoom": "In diesem Raum",+ "onThisPage": "Auf dieser Seite","yourName": "Dein Name","enterYourName": "Deinen Namen eingeben","shareThisFile": "Diese Datei teilen",@@ -23,5 +24,35 @@"agentName": "Agentenname","agentThinking": "Denkt nach","agentEditing": "Bearbeitet",- "agentIdle": "Inaktiv"+ "agentIdle": "Inaktiv",+ "sharedFile": "Geteilte Datei",+ "invalidRoomLink": "Das ist kein Raumlink und keine Raum-ID.",+ "joiningTitle": "Raum wird betreten…",+ "connectingDescription": "Verbindung zu den Servern des Raums wird hergestellt.",+ "lookingDescription": "Personen in diesem Raum werden gesucht.",+ "receivingDescription": "Die Datei kommt von {name}.",+ "othersWaiting": "Ebenfalls am Warten: {names}",+ "unreachableTitle": "Die Server des Raums sind nicht erreichbar",+ "unreachableDescription": "Prüfe deine Internetverbindung. OpenPencil versucht es weiter und öffnet die Datei, sobald die Verbindung steht.",+ "waitingTitle": "Warten auf jemanden, der diese Datei hat",+ "waitingDescription": "Räume werden nicht auf einem Server gespeichert. Die Datei liegt auf den Geräten der Personen, die im Raum waren, und lässt sich nur öffnen, solange eine davon online ist.",+ "waitingAskSharer": "Bitte die Person, die den Link geteilt hat, ihn zu öffnen.",+ "waitingCheckLink": "Prüfe, ob der Link vollständig ist.",+ "waitingOpensAutomatically": "Die Datei öffnet sich hier, sobald jemand mit ihr beitritt.",+ "copyLink": "Link kopieren",+ "linkCopied": "Kopiert",+ "leave": "Verlassen",+ "statusLive": "Live · {count} hier",+ "statusAlone": "Nur du bist hier – Änderungen werden synchronisiert, sobald andere beitreten",+ "leftRoomTitle": "Du hast diesen Raum verlassen",+ "leftRoomDescription": "Das ist jetzt eine lokale Kopie. Speichere sie, um sie zu behalten.",+ "dismiss": "Schließen",+ "openInDesktopApp": "In der Desktop-App öffnen",+ "downloadDesktopApp": "Herunterladen",+ "appearsAs": "Du erscheinst als {name}",+ "changeName": "Ändern",+ "joinRoomEllipsis": "Raum beitreten…",+ "joinRoomDescription": "Füge einen Raumlink oder eine Raum-ID ein, um eine Datei zu öffnen, die jemand mit dir geteilt hat.",+ "nameSettingTitle": "Dein Name",+ "nameSettingDescription": "Andere sehen diesen Namen in geteilten Räumen neben deinem Cursor."}diff --git a/packages/vue/src/i18n/locales/es/collaboration.json b/packages/vue/src/i18n/locales/es/collaboration.jsonindex d691fc71e..96f8db0f3 100644--- a/packages/vue/src/i18n/locales/es/collaboration.json+++ b/packages/vue/src/i18n/locales/es/collaboration.json@@ -1,5 +1,6 @@{"inThisRoom": "En esta sala",+ "onThisPage": "En esta página","yourName": "Tu nombre","enterYourName": "Introduce tu nombre","shareThisFile": "Compartir este archivo",@@ -23,5 +24,35 @@"agentName": "Nombre del agente","agentThinking": "Pensando","agentEditing": "Editando",- "agentIdle": "Inactivo"+ "agentIdle": "Inactivo",+ "sharedFile": "Archivo compartido",+ "invalidRoomLink": "Eso no es un enlace ni un ID de sala.",+ "joiningTitle": "Entrando en la sala…",+ "connectingDescription": "Conectando con los servidores de la sala.",+ "lookingDescription": "Buscando personas en esta sala.",+ "receivingDescription": "Recibiendo el archivo de {name}.",+ "othersWaiting": "También esperan: {names}",+ "unreachableTitle": "No se puede llegar a los servidores de la sala",+ "unreachableDescription": "Comprueba tu conexión a internet. OpenPencil sigue intentándolo y abrirá el archivo en cuanto se conecte.",+ "waitingTitle": "Esperando a alguien que tenga este archivo",+ "waitingDescription": "Las salas no se guardan en un servidor. El archivo está en los dispositivos de quienes han estado en la sala, así que solo se abre mientras alguno de ellos esté conectado.",+ "waitingAskSharer": "Pide a quien compartió el enlace que lo abra.",+ "waitingCheckLink": "Comprueba que el enlace esté completo.",+ "waitingOpensAutomatically": "El archivo se abrirá aquí en cuanto se una alguien que lo tenga.",+ "copyLink": "Copiar enlace",+ "linkCopied": "Copiado",+ "leave": "Salir",+ "statusLive": "En vivo · {count} aquí",+ "statusAlone": "Solo estás tú: los cambios se sincronizan cuando otros se unan",+ "leftRoomTitle": "Has salido de esta sala",+ "leftRoomDescription": "Ahora es una copia local. Guárdala para conservarla.",+ "dismiss": "Cerrar",+ "openInDesktopApp": "Abrir en la app de escritorio",+ "downloadDesktopApp": "Descargar",+ "appearsAs": "Aparecerás como {name}",+ "changeName": "Cambiar",+ "joinRoomEllipsis": "Unirse a una sala…",+ "joinRoomDescription": "Pega un enlace o ID de sala para abrir un archivo que alguien compartió contigo.",+ "nameSettingTitle": "Tu nombre",+ "nameSettingDescription": "Los demás ven este nombre junto a tu cursor en las salas compartidas."}diff --git a/packages/vue/src/i18n/locales/fr/collaboration.json b/packages/vue/src/i18n/locales/fr/collaboration.jsonindex 70e1c887c..58f214e35 100644--- a/packages/vue/src/i18n/locales/fr/collaboration.json+++ b/packages/vue/src/i18n/locales/fr/collaboration.json@@ -1,5 +1,6 @@{"inThisRoom": "Dans cette salle",+ "onThisPage": "Sur cette page","yourName": "Votre nom","enterYourName": "Entrez votre nom","shareThisFile": "Partager ce fichier",@@ -23,5 +24,35 @@"agentName": "Nom de l’agent","agentThinking": "Réfléchit","agentEditing": "Modifie",- "agentIdle": "Inactif"+ "agentIdle": "Inactif",+ "sharedFile": "Fichier partagé",+ "invalidRoomLink": "Ce n’est ni un lien ni un identifiant de salle.",+ "joiningTitle": "Connexion à la salle…",+ "connectingDescription": "Connexion aux serveurs de la salle.",+ "lookingDescription": "Recherche des personnes de cette salle.",+ "receivingDescription": "Réception du fichier de {name}.",+ "othersWaiting": "Attendent aussi : {names}",+ "unreachableTitle": "Impossible de joindre les serveurs de la salle",+ "unreachableDescription": "Vérifiez votre connexion internet. OpenPencil continue d’essayer et ouvrira le fichier dès la connexion établie.",+ "waitingTitle": "En attente d’une personne qui a ce fichier",+ "waitingDescription": "Les salles ne sont pas stockées sur un serveur. Le fichier se trouve sur les appareils des personnes passées par la salle ; il ne s’ouvre donc que lorsque l’une d’elles est en ligne.",+ "waitingAskSharer": "Demandez à la personne qui a partagé le lien de l’ouvrir.",+ "waitingCheckLink": "Vérifiez que le lien est complet.",+ "waitingOpensAutomatically": "Le fichier s’ouvrira ici dès qu’une personne qui l’a rejoindra la salle.",+ "copyLink": "Copier le lien",+ "linkCopied": "Copié",+ "leave": "Quitter",+ "statusLive": "En direct · {count} ici",+ "statusAlone": "Vous êtes seul ici — les modifications se synchronisent quand d’autres arrivent",+ "leftRoomTitle": "Vous avez quitté cette salle",+ "leftRoomDescription": "C’est maintenant une copie locale. Enregistrez-la pour la conserver.",+ "dismiss": "Fermer",+ "openInDesktopApp": "Ouvrir dans l’app de bureau",+ "downloadDesktopApp": "Télécharger",+ "appearsAs": "Vous apparaîtrez comme {name}",+ "changeName": "Modifier",+ "joinRoomEllipsis": "Rejoindre une salle…",+ "joinRoomDescription": "Collez un lien ou un identifiant de salle pour ouvrir un fichier qu’on vous a partagé.",+ "nameSettingTitle": "Votre nom",+ "nameSettingDescription": "Les autres voient ce nom à côté de votre curseur dans les salles partagées."}diff --git a/packages/vue/src/i18n/locales/it/collaboration.json b/packages/vue/src/i18n/locales/it/collaboration.jsonindex 8e39c32fb..0ac2d1d01 100644--- a/packages/vue/src/i18n/locales/it/collaboration.json+++ b/packages/vue/src/i18n/locales/it/collaboration.json@@ -1,5 +1,6 @@{"inThisRoom": "In questa stanza",+ "onThisPage": "In questa pagina","yourName": "Il tuo nome","enterYourName": "Inserisci il tuo nome","shareThisFile": "Condividi questo file",@@ -23,5 +24,35 @@"agentName": "Nome dell’agente","agentThinking": "Sta pensando","agentEditing": "Sta modificando",- "agentIdle": "Inattivo"+ "agentIdle": "Inattivo",+ "sharedFile": "File condiviso",+ "invalidRoomLink": "Non è un link né un ID di stanza.",+ "joiningTitle": "Accesso alla stanza…",+ "connectingDescription": "Connessione ai server della stanza.",+ "lookingDescription": "Ricerca delle persone in questa stanza.",+ "receivingDescription": "Ricezione del file da {name}.",+ "othersWaiting": "In attesa anche: {names}",+ "unreachableTitle": "Impossibile raggiungere i server della stanza",+ "unreachableDescription": "Controlla la connessione a internet. OpenPencil continua a provare e aprirà il file appena si connette.",+ "waitingTitle": "In attesa di qualcuno che abbia questo file",+ "waitingDescription": "Le stanze non sono salvate su un server. Il file si trova sui dispositivi di chi è stato nella stanza, quindi si apre solo mentre uno di loro è online.",+ "waitingAskSharer": "Chiedi a chi ha condiviso il link di aprirlo.",+ "waitingCheckLink": "Controlla che il link sia completo.",+ "waitingOpensAutomatically": "Il file si aprirà qui appena entra qualcuno che lo ha.",+ "copyLink": "Copia link",+ "linkCopied": "Copiato",+ "leave": "Esci",+ "statusLive": "Live · {count} qui",+ "statusAlone": "Ci sei solo tu: le modifiche si sincronizzano quando entrano altri",+ "leftRoomTitle": "Hai lasciato questa stanza",+ "leftRoomDescription": "Ora è una copia locale. Salvala per conservarla.",+ "dismiss": "Chiudi",+ "openInDesktopApp": "Apri nell’app desktop",+ "downloadDesktopApp": "Scarica",+ "appearsAs": "Apparirai come {name}",+ "changeName": "Cambia",+ "joinRoomEllipsis": "Entra in una stanza…",+ "joinRoomDescription": "Incolla un link o un ID di stanza per aprire un file che qualcuno ha condiviso con te.",+ "nameSettingTitle": "Il tuo nome",+ "nameSettingDescription": "Gli altri vedono questo nome accanto al tuo cursore nelle stanze condivise."}diff --git a/packages/vue/src/i18n/locales/ja/collaboration.json b/packages/vue/src/i18n/locales/ja/collaboration.jsonindex 39f64b718..38ff7dde6 100644--- a/packages/vue/src/i18n/locales/ja/collaboration.json+++ b/packages/vue/src/i18n/locales/ja/collaboration.json@@ -1,5 +1,6 @@{"inThisRoom": "このルーム内",+ "onThisPage": "このページ","yourName": "お名前","enterYourName": "名前を入力してください","shareThisFile": "このファイルを共有",@@ -23,5 +24,35 @@"agentName": "エージェント名","agentThinking": "考え中","agentEditing": "編集中",- "agentIdle": "待機中"+ "agentIdle": "待機中",+ "sharedFile": "共有ファイル",+ "invalidRoomLink": "ルームのリンクまたはIDではありません。",+ "joiningTitle": "ルームに参加しています…",+ "connectingDescription": "ルームのサーバーに接続しています。",+ "lookingDescription": "このルームの参加者を探しています。",+ "receivingDescription": "{name} からファイルを受け取っています。",+ "othersWaiting": "ほかに待っている人: {names}",+ "unreachableTitle": "ルームのサーバーに接続できません",+ "unreachableDescription": "インターネット接続を確認してください。OpenPencil は接続を試み続け、接続できしだいファイルを開きます。",+ "waitingTitle": "このファイルを持っている人を待っています",+ "waitingDescription": "ルームはサーバーに保存されません。ファイルはルームに参加した人のデバイスにあるため、そのうち誰かがオンラインのときだけ開けます。",+ "waitingAskSharer": "リンクを共有した人に開いてもらってください。",+ "waitingCheckLink": "リンクが途中で切れていないか確認してください。",+ "waitingOpensAutomatically": "ファイルを持っている人が参加すると、ここに自動で開きます。",+ "copyLink": "リンクをコピー",+ "linkCopied": "コピーしました",+ "leave": "退出",+ "statusLive": "ライブ · {count}人",+ "statusAlone": "参加者はあなただけです。他の人が参加すると変更が同期されます",+ "leftRoomTitle": "このルームから退出しました",+ "leftRoomDescription": "これはローカルのコピーです。残すには保存してください。",+ "dismiss": "閉じる",+ "openInDesktopApp": "デスクトップアプリで開く",+ "downloadDesktopApp": "ダウンロード",+ "appearsAs": "{name} として表示されます",+ "changeName": "変更",+ "joinRoomEllipsis": "ルームに参加…",+ "joinRoomDescription": "共有されたファイルを開くには、ルームのリンクまたはIDを貼り付けてください。",+ "nameSettingTitle": "あなたの名前",+ "nameSettingDescription": "共有ルームでは、この名前がカーソルの横に表示されます。"}diff --git a/packages/vue/src/i18n/locales/pl/collaboration.json b/packages/vue/src/i18n/locales/pl/collaboration.jsonindex cd3c5b7f2..0ec8a3268 100644--- a/packages/vue/src/i18n/locales/pl/collaboration.json+++ b/packages/vue/src/i18n/locales/pl/collaboration.json@@ -1,5 +1,6 @@{"inThisRoom": "W tym pokoju",+ "onThisPage": "Na tej stronie","yourName": "Twoje imię","enterYourName": "Wpisz swoje imię","shareThisFile": "Udostępnij ten plik",@@ -23,5 +24,35 @@"agentName": "Nazwa agenta","agentThinking": "Myśli","agentEditing": "Edytuje",- "agentIdle": "Bezczynny"+ "agentIdle": "Bezczynny",+ "sharedFile": "Udostępniony plik",+ "invalidRoomLink": "To nie jest link ani identyfikator pokoju.",+ "joiningTitle": "Dołączanie do pokoju…",+ "connectingDescription": "Łączenie z serwerami pokoju.",+ "lookingDescription": "Szukanie osób w tym pokoju.",+ "receivingDescription": "Pobieranie pliku od: {name}.",+ "othersWaiting": "Czekają też: {names}",+ "unreachableTitle": "Nie można połączyć się z serwerami pokoju",+ "unreachableDescription": "Sprawdź połączenie z internetem. OpenPencil próbuje dalej i otworzy plik, gdy tylko się połączy.",+ "waitingTitle": "Czekamy na kogoś, kto ma ten plik",+ "waitingDescription": "Pokoje nie są przechowywane na serwerze. Plik znajduje się na urządzeniach osób, które były w pokoju, więc otworzy się tylko wtedy, gdy któraś z nich jest online.",+ "waitingAskSharer": "Poproś osobę, która udostępniła link, aby go otworzyła.",+ "waitingCheckLink": "Sprawdź, czy link jest kompletny.",+ "waitingOpensAutomatically": "Plik otworzy się tutaj, gdy tylko dołączy ktoś, kto go ma.",+ "copyLink": "Kopiuj link",+ "linkCopied": "Skopiowano",+ "leave": "Opuść",+ "statusLive": "Na żywo · {count} tutaj",+ "statusAlone": "Jesteś tu tylko ty — zmiany zsynchronizują się, gdy dołączą inni",+ "leftRoomTitle": "Opuszczono ten pokój",+ "leftRoomDescription": "To jest teraz lokalna kopia. Zapisz ją, aby ją zachować.",+ "dismiss": "Zamknij",+ "openInDesktopApp": "Otwórz w aplikacji na komputer",+ "downloadDesktopApp": "Pobierz",+ "appearsAs": "Inni zobaczą Cię jako {name}",+ "changeName": "Zmień",+ "joinRoomEllipsis": "Dołącz do pokoju…",+ "joinRoomDescription": "Wklej link lub identyfikator pokoju, aby otworzyć plik, który ktoś Ci udostępnił.",+ "nameSettingTitle": "Twoje imię",+ "nameSettingDescription": "Inni widzą to imię obok Twojego kursora w udostępnionych pokojach."}diff --git a/packages/vue/src/i18n/locales/ru/collaboration.json b/packages/vue/src/i18n/locales/ru/collaboration.jsonindex 37cd2ccda..ad59c2fc8 100644--- a/packages/vue/src/i18n/locales/ru/collaboration.json+++ b/packages/vue/src/i18n/locales/ru/collaboration.json@@ -1,5 +1,6 @@{"inThisRoom": "В этой комнате",+ "onThisPage": "На этой странице","yourName": "Ваше имя","enterYourName": "Введите ваше имя","shareThisFile": "Поделиться файлом",@@ -23,5 +24,35 @@"agentName": "Имя агента","agentThinking": "Думает","agentEditing": "Редактирует",- "agentIdle": "Неактивен"+ "agentIdle": "Неактивен",+ "sharedFile": "Общий файл",+ "invalidRoomLink": "Это не ссылка и не ID комнаты.",+ "joiningTitle": "Подключение к комнате…",+ "connectingDescription": "Подключаемся к серверам комнаты.",+ "lookingDescription": "Ищем участников этой комнаты.",+ "receivingDescription": "Получаем файл от {name}.",+ "othersWaiting": "Тоже ждут: {names}",+ "unreachableTitle": "Не удаётся связаться с серверами комнаты",+ "unreachableDescription": "Проверьте подключение к интернету. OpenPencil продолжает попытки и откроет файл, как только подключится.",+ "waitingTitle": "Ждём того, у кого есть этот файл",+ "waitingDescription": "Комнаты не хранятся на сервере. Файл есть на устройствах тех, кто был в комнате, поэтому он откроется, только пока кто-то из них в сети.",+ "waitingAskSharer": "Попросите того, кто поделился ссылкой, открыть её.",+ "waitingCheckLink": "Проверьте, что ссылка скопирована полностью.",+ "waitingOpensAutomatically": "Файл откроется здесь, как только подключится тот, у кого он есть.",+ "copyLink": "Скопировать ссылку",+ "linkCopied": "Скопировано",+ "leave": "Выйти",+ "statusLive": "В сети · {count} здесь",+ "statusAlone": "Здесь только вы — изменения синхронизируются, когда подключатся другие",+ "leftRoomTitle": "Вы вышли из этой комнаты",+ "leftRoomDescription": "Теперь это локальная копия. Сохраните её, чтобы не потерять.",+ "dismiss": "Закрыть",+ "openInDesktopApp": "Открыть в настольном приложении",+ "downloadDesktopApp": "Скачать",+ "appearsAs": "Другие увидят вас как {name}",+ "changeName": "Изменить",+ "joinRoomEllipsis": "Войти в комнату…",+ "joinRoomDescription": "Вставьте ссылку или ID комнаты, чтобы открыть файл, которым с вами поделились.",+ "nameSettingTitle": "Ваше имя",+ "nameSettingDescription": "Другие видят это имя рядом с вашим курсором в общих комнатах."}diff --git a/packages/vue/src/i18n/locales/zh-cn/collaboration.json b/packages/vue/src/i18n/locales/zh-cn/collaboration.jsonindex 563866a54..9630683f4 100644--- a/packages/vue/src/i18n/locales/zh-cn/collaboration.json+++ b/packages/vue/src/i18n/locales/zh-cn/collaboration.json@@ -1,5 +1,6 @@{"inThisRoom": "此房间中",+ "onThisPage": "在此页面","yourName": "你的名字","enterYourName": "请输入你的名字","shareThisFile": "分享此文件",@@ -23,5 +24,35 @@"agentName": "智能体名称","agentThinking": "思考中","agentEditing": "编辑中",- "agentIdle": "空闲"+ "agentIdle": "空闲",+ "sharedFile": "共享文件",+ "invalidRoomLink": "这不是房间链接或 ID。",+ "joiningTitle": "正在加入房间…",+ "connectingDescription": "正在连接房间的服务器。",+ "lookingDescription": "正在寻找此房间中的人。",+ "receivingDescription": "正在从 {name} 接收文件。",+ "othersWaiting": "也在等待:{names}",+ "unreachableTitle": "无法连接到房间的服务器",+ "unreachableDescription": "请检查网络连接。OpenPencil 会继续尝试,连接后即打开文件。",+ "waitingTitle": "正在等待拥有此文件的人",+ "waitingDescription": "房间不存储在服务器上。文件保存在去过该房间的人的设备上,所以只有其中有人在线时才能打开。",+ "waitingAskSharer": "请让分享链接的人打开它。",+ "waitingCheckLink": "请检查链接是否完整。",+ "waitingOpensAutomatically": "只要有拥有此文件的人加入,文件就会在这里打开。",+ "copyLink": "复制链接",+ "linkCopied": "已复制",+ "leave": "离开",+ "statusLive": "在线 · {count} 人",+ "statusAlone": "只有你在这里——其他人加入后更改会同步",+ "leftRoomTitle": "你已离开此房间",+ "leftRoomDescription": "这现在是本地副本。保存即可保留。",+ "dismiss": "关闭",+ "openInDesktopApp": "在桌面应用中打开",+ "downloadDesktopApp": "下载",+ "appearsAs": "你将显示为 {name}",+ "changeName": "更改",+ "joinRoomEllipsis": "加入房间…",+ "joinRoomDescription": "粘贴房间链接或 ID,打开别人与你共享的文件。",+ "nameSettingTitle": "你的名字",+ "nameSettingDescription": "在共享房间中,其他人会在你的光标旁看到此名字。"}diff --git a/packages/vue/src/i18n/messages/collaboration.ts b/packages/vue/src/i18n/messages/collaboration.tsindex 788b638dc..a0a84430c 100644--- a/packages/vue/src/i18n/messages/collaboration.ts+++ b/packages/vue/src/i18n/messages/collaboration.ts@@ -4,6 +4,7 @@ import { i18n } from '#vue/i18n/create'export const collaborationMessageDefaults = {inThisRoom: 'In this room',+ onThisPage: 'On this page',yourName: 'Your name',enterYourName: 'Enter your name',shareThisFile: 'Share this file',@@ -27,7 +28,39 @@ export const collaborationMessageDefaults = {agentName: 'Agent name',agentThinking: 'Thinking',agentEditing: 'Editing',- agentIdle: 'Idle'+ agentIdle: 'Idle',+ sharedFile: 'Shared file',+ invalidRoomLink: 'That isn’t a room link or ID.',+ joiningTitle: 'Joining the room…',+ connectingDescription: 'Connecting to the room’s servers.',+ lookingDescription: 'Looking for people in this room.',+ receivingDescription: params('Getting the file from {name}.'),+ othersWaiting: params('Also waiting: {names}'),+ unreachableTitle: 'Can’t reach the room’s servers',+ unreachableDescription:+ 'Check your internet connection. OpenPencil keeps trying and opens the file once it connects.',+ waitingTitle: 'Waiting for someone who has this file',+ waitingDescription:+ 'Rooms aren’t stored on a server. The file lives on the devices of the people who’ve been in the room, so it can only open while one of them is online.',+ waitingAskSharer: 'Ask the person who shared the link to open it.',+ waitingCheckLink: 'Check that the link is complete.',+ waitingOpensAutomatically: 'The file opens here as soon as someone with it joins.',+ copyLink: 'Copy link',+ linkCopied: 'Copied',+ leave: 'Leave',+ statusLive: params('Live · {count} here'),+ statusAlone: 'Only you here — changes sync when others join',+ leftRoomTitle: 'You left this room',+ leftRoomDescription: 'This is now a local copy. Save it to keep it.',+ dismiss: 'Dismiss',+ openInDesktopApp: 'Open in desktop app',+ downloadDesktopApp: 'Download',+ appearsAs: params('You’ll appear as {name}'),+ changeName: 'Change',+ joinRoomEllipsis: 'Join room…',+ joinRoomDescription: 'Paste a room link or ID to open a file someone shared with you.',+ nameSettingTitle: 'Your name',+ nameSettingDescription: 'Others see this name next to your cursor in shared rooms.'} as constexport const collaborationMessages = i18n('collaboration', collaborationMessageDefaults)diff --git a/src/AGENTS.md b/src/AGENTS.mdindex 3eac46655..c86badc44 100644--- a/src/AGENTS.md+++ b/src/AGENTS.md@@ -24,6 +24,9 @@ Root Tauri/Vite app. Services and state live under `src/app/**`, views under `sr- ACP transport lives under `src/app/ai/acp/**`; provider definitions in `packages/core/src/constants.ts`; profiles in `src/app/ai/models/**`. Keep provider connections, reusable profiles, and role assignments separate, and resolve credentials lazily. ACP process changes require checking `desktop/capabilities/**`.- Browser-native WebMCP registration lives under `src/app/automation/webmcp/`, consumes per-tool exposure metadata, and is feature-detected through `document.modelContext`. App completion under `src/app/automation/execution/` loads fonts after commit.- Collaboration lives under `src/app/collab/**` on Trystero, Yjs, and awareness; preserve crypto-safe room IDs and peer cleanup.+- A room is a document: every room tab owns its session (`src/app/collab/rooms.ts`, `session.ts`), joining always opens a new tab, and only Share binds an existing document; the collaboration UI reads the active tab's room through `useCollab()` and publishes cursors through the canvas's own tab (`tests/app/collab/session.test.ts`, `tests/e2e/collab/rooms.spec.ts`).+- A shared document records each layer's parent history, order key and page, never `parentId` or `childIds`, and only Share or a room's conversion sets its root in `meta`; local edits are written by `writeLocalPlacement` and remote changes applied by `applySharedTree` in `src/app/collab/shared-tree/sync.ts`, which resolve the tree with `LayerTree` from `src/app/collab/tree/` (`tests/app/collab/random-edits.test.ts`).+- Changing how a shared document records data bumps `TREE_FORMAT` and `COLLAB_APP_ID` together, so mismatched builds never meet, and converts saved rooms in `src/app/collab/shared-tree/migration.ts` (`tests/app/collab/shared-tree/migration.test.ts`).## Browser baselinediff --git a/src/app/browser-bridge.ts b/src/app/browser-bridge.tsindex 4ca7146bc..d61cf55ef 100644--- a/src/app/browser-bridge.ts+++ b/src/app/browser-bridge.ts@@ -1,6 +1,7 @@import type { ChatTransport, UIMessage } from 'ai'import type { CollabReturn } from '@/app/collab/context'+import type { RoomStatus } from '@/app/collab/room/status'import type { EditorStore } from '@/app/editor/session/create'import { createNavigationBenchmarkHooks } from '@/app/performance/navigation/hooks'import type { NavigationBenchmarkHooks } from '@/app/performance/navigation/hooks'@@ -14,10 +15,15 @@ export interface OpenPencilTestHooks {navigation?: NavigationBenchmarkHookscollab?: Pick<CollabReturn,- 'connect' | 'disconnect' | 'updateCursor' | 'updateSelection' | 'setLocalName'+ 'disconnect' | 'updateCursor' | 'updateSelection' | 'setLocalName'> & {+ /** Joins a room in a tab of its own, as pasting its link does. */+ connect: (roomId: string) => boolean+ /** Puts the active tab's document into the room, as Share does. */+ share: (roomId: string) => voidpeerCount: () => numberpeerSelections: () => Array<string[] | undefined>+ status: () => RoomStatus | null}}@@ -49,18 +55,25 @@ export function setOpenPencilStore(store: EditorStore) {}}-export function exposeCollaborationActions(collab: CollabReturn) {+export function exposeCollaborationActions(+ collab: CollabReturn,+ joinRoom: (roomId: string) => boolean+) {if (!IS_BROWSER || !import.meta.env.DEV) returnif (!appRuntimeConfig.test) returnconst testHooks = (windowAPI().test ??= {})testHooks.collab = {- connect: collab.connect,+ connect: joinRoom,disconnect: collab.disconnect,updateCursor: collab.updateCursor,updateSelection: collab.updateSelection,setLocalName: collab.setLocalName,peerCount: () => collab.remotePeers.value.length,- peerSelections: () => collab.remotePeers.value.map((peer) => peer.selection)+ peerSelections: () => collab.remotePeers.value.map((peer) => peer.selection),+ share: (roomId: string) => {+ collab.shareCurrentDoc(roomId)+ },+ status: () => collab.state.value.status}}diff --git a/src/app/collab/guest-name.ts b/src/app/collab/guest-name.tsnew file mode 100644index 000000000..c612dfd9e--- /dev/null+++ b/src/app/collab/guest-name.ts@@ -0,0 +1,47 @@+import { randomIndex } from '@open-pencil/scene-graph/random'++/** Friendly words for a guest who has not set a name: "Teal Fox". */+const GUEST_COLORS = [+ 'Amber',+ 'Azure',+ 'Coral',+ 'Cobalt',+ 'Copper',+ 'Crimson',+ 'Indigo',+ 'Ivory',+ 'Jade',+ 'Lilac',+ 'Olive',+ 'Ruby',+ 'Saffron',+ 'Scarlet',+ 'Teal',+ 'Violet'+] as const++const GUEST_ANIMALS = [+ 'Badger',+ 'Crane',+ 'Dolphin',+ 'Falcon',+ 'Fox',+ 'Gecko',+ 'Heron',+ 'Ibis',+ 'Koala',+ 'Lynx',+ 'Marten',+ 'Otter',+ 'Panda',+ 'Puffin',+ 'Raven',+ 'Wombat'+] as const++/** A color and an animal, as a placeholder name until the person sets their own. */+export function generateGuestName(pick: (length: number) => number = randomIndex): string {+ const color = GUEST_COLORS[pick(GUEST_COLORS.length)] ?? GUEST_COLORS[0]+ const animal = GUEST_ANIMALS[pick(GUEST_ANIMALS.length)] ?? GUEST_ANIMALS[0]+ return `${color} ${animal}`+}diff --git a/src/app/collab/identity.ts b/src/app/collab/identity.tsnew file mode 100644index 000000000..34c51e6eb--- /dev/null+++ b/src/app/collab/identity.ts@@ -0,0 +1,29 @@+import { createGlobalState, useLocalStorage } from '@vueuse/core'+import { computed } from 'vue'++import type { Color } from '@open-pencil/scene-graph/primitives'+import { randomIndex } from '@open-pencil/scene-graph/random'++import { generateGuestName } from '@/app/collab/guest-name'+import { PEER_COLORS } from '@/constants'++export const COLLAB_NAME_STORAGE_KEY = 'op-collab-name'++/**+ * Who this person is in every room: one name for the whole app, kept across sessions, and one+ * color for this session. Until they set a name they join as a generated one, such as+ * "Teal Fox", so a room opens without asking first.+ */+export const useCollabIdentity = createGlobalState(() => {+ const storedName = useLocalStorage(COLLAB_NAME_STORAGE_KEY, '')+ const guestName = generateGuestName()+ const color: Color = PEER_COLORS[randomIndex(PEER_COLORS.length)] ?? PEER_COLORS[0]+ const name = computed(() => storedName.value.trim() || guestName)+ const hasChosenName = computed(() => storedName.value.trim().length > 0)++ function setName(next: string) {+ storedName.value = next.trim()+ }++ return { name, color, hasChosenName, setName }+})diff --git a/src/app/collab/join.ts b/src/app/collab/join.tsnew file mode 100644index 000000000..2a02237d5--- /dev/null+++ b/src/app/collab/join.ts@@ -0,0 +1,17 @@+import { useCollaborationMessages } from '@open-pencil/vue'++import { parseRoomInput } from '@/app/collab/room/id'+import { joinRoom } from '@/app/collab/rooms'++/**+ * Joins the room in a pasted link or ID, in a tab of its own. False when the text is not a room+ * link or ID, so the caller can say so instead of joining a room nobody shared.+ */+export function useJoinRoom() {+ const messages = useCollaborationMessages()+ return (input: string): boolean => {+ const roomId = parseRoomInput(input)+ if (!roomId) return false+ return joinRoom(roomId, { tabName: messages.value.sharedFile }) !== null+ }+}diff --git a/src/app/collab/local-awareness.ts b/src/app/collab/local-awareness.tsindex bc54fd873..a7776b2d3 100644--- a/src/app/collab/local-awareness.ts+++ b/src/app/collab/local-awareness.ts@@ -1,69 +1,10 @@-import { watch, type Ref } from 'vue'+import { watch } from 'vue'import type { Awareness } from 'y-protocols/awareness'import type { Color } from '@open-pencil/scene-graph/primitives'-import { buildRemotePeers } from '@/app/collab/awareness'-import type { CollabState } from '@/app/collab/types'import type { EditorStore } from '@/app/editor/active-store'-import { presenceOf, setOwnerColor, setPeers } from '@/app/presence/registry'--type LocalAwarenessOptions = {- state: Ref<CollabState>- storedName: Ref<string>- getStore: () => EditorStore- getAwareness: () => Awareness | null-}--export function createLocalAwarenessActions({- state,- storedName,- getStore,- getAwareness-}: LocalAwarenessOptions) {- function broadcastAwareness() {- const awareness = getAwareness()- if (!awareness) return- awareness.setLocalStateField('user', {- name: state.value.localName,- color: state.value.localColor- })- }-- function updateCursor(x: number, y: number, pageId: string) {- const awareness = getAwareness()- if (!awareness) return- awareness.setLocalStateField('cursor', { x, y, pageId, zoom: getStore().state.zoom })- }-- function updateSelection(ids: string[]) {- const awareness = getAwareness()- if (!awareness) return- awareness.setLocalStateField('selection', ids)- }-- function updatePeersList() {- const awareness = getAwareness()- if (!awareness) return-- const store = getStore()- const peers = buildRemotePeers(- awareness.getStates() as Map<number, Record<string, unknown>>,- awareness.clientID- )-- state.value.peers = peers- setPeers(store, peers)- }-- function setLocalName(name: string) {- state.value.localName = name- storedName.value = name- broadcastAwareness()- }-- return { broadcastAwareness, updateCursor, updateSelection, updatePeersList, setLocalName }-}+import { presenceOf, setOwnerColor } from '@/app/presence/registry'/** Publish our agents to the room while connected; they take our collaborator color. */export function publishLocalAgents(diff --git a/src/app/collab/node-codec.ts b/src/app/collab/node-codec.tsindex 6b2f6fddf..648cf4e4e 100644--- a/src/app/collab/node-codec.ts+++ b/src/app/collab/node-codec.ts@@ -11,7 +11,20 @@ import { copyFills } from '@open-pencil/scene-graph/copy'import { createDefaultSourceMetadata } from '@open-pencil/scene-graph/node-defaults'import type { Matrix, Vector } from '@open-pencil/scene-graph/primitives'+import { ORDER_KEY_FIELD, PAGE_FIELD, PARENTS_FIELD } from '@/app/collab/shared-tree/fields'+const DERIVED_NODE_FIELDS = new Set<keyof SceneNode>(['textPicture'])+/**+ * The layer tree syncs as parent entries, order keys and pages (`src/app/collab/shared-tree/fields.ts`), so a+ * layer's own fields leave out its place in the tree, and decoding skips the tree's fields.+ */+const TREE_FIELDS = new Set<string>([+ 'parentId',+ 'childIds',+ PARENTS_FIELD,+ ORDER_KEY_FIELD,+ PAGE_FIELD+])const FILL_TYPES = new Set<FillType>(['SOLID','GRADIENT_LINEAR',@@ -32,7 +45,7 @@ type YjsNodeLike = {export function encodeNodeForYjs(node: SceneNode): Record<string, unknown> {const encoded: Record<string, unknown> = {}for (const [key, value] of Object.entries(node)) {- if (DERIVED_NODE_FIELDS.has(key as keyof SceneNode)) continue+ if (DERIVED_NODE_FIELDS.has(key as keyof SceneNode) || TREE_FIELDS.has(key)) continueencoded[key] = structuredClone(value)}return encoded@@ -58,7 +71,7 @@ export function syncEncodedNodeToYMap(export function decodeNodeFromYjs(ynode: YjsNodeLike): Partial<SceneNode> {const props: Record<string, unknown> = {}for (const [key, value] of ynode.entries()) {- if (DERIVED_NODE_FIELDS.has(key as keyof SceneNode)) continue+ if (DERIVED_NODE_FIELDS.has(key as keyof SceneNode) || TREE_FIELDS.has(key)) continueprops[key] = structuredClone(value)}diff --git a/src/app/collab/room.ts b/src/app/collab/room/connection.tssimilarity index 98%rename from src/app/collab/room.tsrename to src/app/collab/room/connection.tsindex c7978cd32..18c582bc3 100644--- a/src/app/collab/room.ts+++ b/src/app/collab/room/connection.ts@@ -8,7 +8,6 @@ export type CollabRoomOptions = {roomId: stringydoc: Y.Docawareness: awarenessProtocol.Awareness- setConnected: () => voidupdatePeersList: () => voidjoinRoom?: JoinCollabRoom}@@ -40,7 +39,6 @@ export function connectCollabRoom({roomId,ydoc,awareness,- setConnected,updatePeersList,joinRoom = joinCollabRoom}: CollabRoomOptions): CollabRoomConnection {@@ -89,7 +87,6 @@ export function connectCollabRoom({)room.onPeerJoin((peerId) => {- setConnected()sendSyncStep1(Y.encodeStateVector(ydoc), peerId)sendAwareness(awarenessProtocol.encodeAwarenessUpdate(awareness, [awareness.clientID]), peerId)})diff --git a/src/app/collab/room/id.ts b/src/app/collab/room/id.tsnew file mode 100644index 000000000..6cdece2c6--- /dev/null+++ b/src/app/collab/room/id.ts@@ -0,0 +1,26 @@+import * as v from 'valibot'++import { ROOM_ID_CHARS, ROOM_ID_LENGTH } from '@/constants'++// The alphabet is plain lowercase letters and digits, so it needs no escaping in a class.+const roomIdSchema = v.pipe(+ v.string(),+ v.regex(new RegExp(`^[${ROOM_ID_CHARS}]{${ROOM_ID_LENGTH}}$`))+)++export function isRoomId(value: string): boolean {+ return v.is(roomIdSchema, value)+}++/**+ * The room ID in what someone pasted: a bare ID or a share link, with any query, hash, or+ * trailing slash. Null when it is not a room ID, so a mistyped link never joins another room.+ */+export function parseRoomInput(text: string): string | null {+ let candidate = text.trim()+ const shareIndex = candidate.lastIndexOf('/share/')+ if (shareIndex !== -1) candidate = candidate.slice(shareIndex + '/share/'.length)+ candidate = candidate.split(/[?#]/)[0] ?? ''+ candidate = candidate.replace(/\/+$/, '')+ return isRoomId(candidate) ? candidate : null+}diff --git a/src/app/collab/room/links.ts b/src/app/collab/room/links.tsnew file mode 100644index 000000000..1f49d996d--- /dev/null+++ b/src/app/collab/room/links.ts@@ -0,0 +1,34 @@+import * as v from 'valibot'++import { isTauri } from '@/app/tauri/env'++/** Desktop events and commands for `openpencil://join?room=<id>` links (`desktop/src/lib.rs`). */+export const ROOM_LINKS_EVENT = 'open-room-links'+const TAKE_PENDING_ROOMS = 'take_pending_rooms'++const pendingRoomsSchema = v.array(v.string())++export function roomLinkURL(roomId: string): string {+ return `openpencil://join?room=${encodeURIComponent(roomId)}`+}++/**+ * Opens the rooms of `openpencil://join` links the desktop app received, at startup and while+ * running. The native side validates each room ID; `open` validates it again before joining.+ */+export async function bindDesktopRoomLinks(open: (roomId: string) => void): Promise<() => void> {+ if (!isTauri()) return () => undefined+ const [{ invoke }, { listen }] = await Promise.all([+ import('@tauri-apps/api/core'),+ import('@tauri-apps/api/event')+ ])+ async function drain() {+ const rooms = v.parse(pendingRoomsSchema, await invoke<unknown>(TAKE_PENDING_ROOMS))+ for (const roomId of rooms) open(roomId)+ }+ const stop = await listen(ROOM_LINKS_EVENT, () => {+ void drain().catch((error: unknown) => console.error('[Room link]', error))+ })+ await drain()+ return stop+}diff --git a/src/app/collab/room/status.ts b/src/app/collab/room/status.tsnew file mode 100644index 000000000..5e2ebba20--- /dev/null+++ b/src/app/collab/room/status.ts@@ -0,0 +1,61 @@+/**+ * Where a room tab stands, from what this peer can actually observe:+ * - `connecting`: this device's saved copy is loading, or the service that introduces peers has+ * not answered yet;+ * - `looking`: that service answered, and people already in the room have not had time to meet+ * this peer yet;+ * - `receiving`: someone who has the file is here and it is on its way;+ * - `waiting`: nobody who has the file is online;+ * - `unreachable`: the service that introduces peers cannot be reached;+ * - `live`: the room's file is here and other people are too;+ * - `alone`: the room's file is here, from this device's copy, and nobody else is.+ */+export type RoomStatus =+ | 'connecting'+ | 'looking'+ | 'receiving'+ | 'waiting'+ | 'unreachable'+ | 'live'+ | 'alone'++/** The states a room tab shows its own screen for, until the room's file arrives. */+export type PendingRoomStatus = Exclude<RoomStatus, 'live' | 'alone'>++export interface RoomStatusInput {+ /** Whether the room's root is known, from a peer or from this device's saved copy. */+ hasDocument: boolean+ /** Whether this device's saved copy of the room has loaded. */+ savedCopyLoaded: boolean+ /** How long the tab has been in the room. */+ openFor: number+ /** How long the peer has been connected to the service that introduces peers, if it is. */+ connectedFor: number | null+ /** How long after connecting everyone already in the room has met this peer. */+ discoveryMs: number+ /** How long without connecting before the tab says the service cannot be reached. */+ unreachableMs: number+ peerCount: number+ /** Peers who have the room's file. */+ peersWithFile: number+}++export function deriveRoomStatus(input: RoomStatusInput): RoomStatus {+ if (input.hasDocument) return input.peerCount > 0 ? 'live' : 'alone'+ if (!input.savedCopyLoaded) return 'connecting'+ if (input.peersWithFile > 0) return 'receiving'+ if (input.connectedFor === null) {+ return input.openFor >= input.unreachableMs ? 'unreachable' : 'connecting'+ }+ return input.connectedFor < input.discoveryMs ? 'looking' : 'waiting'+}++/** Whether the room's file is shown, rather than the room's own screen. */+export function showsRoomDocument(status: RoomStatus): status is 'live' | 'alone' {+ return status === 'live' || status === 'alone'+}++/** Whether the tab is still trying to get the room's file, so it shows progress. */+export function isFetchingRoom(status: RoomStatus): boolean {+ return status === 'connecting' || status === 'looking' || status === 'receiving'+}diff --git a/src/app/collab/rooms.ts b/src/app/collab/rooms.tsnew file mode 100644index 000000000..749f5162b--- /dev/null+++ b/src/app/collab/rooms.ts@@ -0,0 +1,117 @@+import { computed, shallowRef, watch } from 'vue'++import { generateRoomId } from '@/app/collab/awareness'+import { isRoomId } from '@/app/collab/room/id'+import { openRoomSession, type RoomSession } from '@/app/collab/session'+import type { JoinCollabRoom } from '@/app/collab/transport'+import type { EditorStore } from '@/app/editor/active-store'+import { activeTab, allTabs, closeTab, createTab, getTabForStore, switchTab } from '@/app/tabs'++/**+ * Rooms by tab. A room is a document: joining opens it in a tab of its own, and only Share+ * puts an existing tab's document into a room. Every room tab keeps its own session, so several+ * rooms can be live at once and keep syncing in the background.+ */+const sessions = shallowRef<readonly RoomSession[]>([])++/** Tabs that left a room they joined and kept its document as a local copy. */+const leftRooms = shallowRef<readonly EditorStore[]>([])++export const activeRoom = computed(() => {+ const store = activeTab.value?.store+ return store ? roomForStore(store) : undefined+})++export const activeTabLeftRoom = computed(() => {+ const store = activeTab.value?.store+ return store ? leftRooms.value.includes(store) : false+})++export function roomForStore(store: EditorStore): RoomSession | undefined {+ return sessions.value.find((session) => session.store === store)+}++export function roomById(roomId: string): RoomSession | undefined {+ return sessions.value.find((session) => session.roomId === roomId)+}++function addSession(session: RoomSession) {+ sessions.value = [...sessions.value, session]+ leftRooms.value = leftRooms.value.filter((store) => store !== session.store)+}++function removeSession(session: RoomSession) {+ session.dispose()+ sessions.value = sessions.value.filter((candidate) => candidate !== session)+}++/** Puts a tab's document into a new room, or returns the room it is already in. */+export function shareDocument(store: EditorStore, roomId = generateRoomId()): RoomSession {+ const existing = roomForStore(store)+ if (existing) return existing+ const session = openRoomSession({ roomId, store, origin: 'shared' })+ addSession(session)+ session.shareDocument()+ return session+}++export interface JoinRoomOptions {+ /** What the new tab is called until the room's document brings its own name. */+ tabName: string+ transport?: JoinCollabRoom+}++/**+ * Opens a room in a tab of its own, or switches to the tab already showing it. Null when the+ * ID is not a room ID. The new tab shows the joining screen until the room's document arrives.+ */+export function joinRoom(+ roomId: string,+ { tabName, transport }: JoinRoomOptions+): RoomSession | null {+ if (!isRoomId(roomId)) return null+ const existing = roomById(roomId)+ if (existing) {+ const tab = getTabForStore(existing.store)+ if (tab) switchTab(tab.id)+ return existing+ }+ const tab = createTab()+ tab.store.state.documentName = tabName+ const session = openRoomSession({+ roomId,+ store: tab.store,+ origin: 'joined',+ joinRoom: transport+ })+ addSession(session)+ return session+}++/**+ * Leaves a room. A tab that shared its document goes back to being that document. A tab that+ * joined keeps the room's document as a local unsaved copy, or closes when nothing arrived.+ */+export function leaveRoom(session: RoomSession): void {+ removeSession(session)+ if (session.origin === 'shared') return+ const tab = getTabForStore(session.store)+ if (!tab) return+ if (session.hasDocument.value) {+ leftRooms.value = [...leftRooms.value, session.store]+ return+ }+ void closeTab(tab.id, 'discard')+}++export function dismissLeftRoomNote(store: EditorStore): void {+ leftRooms.value = leftRooms.value.filter((candidate) => candidate !== store)+}++// A closed tab takes its room with it.+watch(allTabs, () => {+ for (const session of sessions.value) {+ if (!getTabForStore(session.store)) removeSession(session)+ }+ leftRooms.value = leftRooms.value.filter((store) => getTabForStore(store) !== undefined)+})diff --git a/src/app/collab/route.ts b/src/app/collab/route.tsnew file mode 100644index 000000000..6b7d638a3--- /dev/null+++ b/src/app/collab/route.ts@@ -0,0 +1,33 @@+import { watch } from 'vue'+import type { RouteLocationNormalizedLoaded, Router } from 'vue-router'++import { activeRoom } from '@/app/collab/rooms'++export const SHARE_ROUTE_PREFIX = '/share/'++export function shareRoutePath(roomId: string): string {+ return `${SHARE_ROUTE_PREFIX}${roomId}`+}++/** The path for the active tab's room: its share link, or `/` after leaving a share link. */+function roomPathFor(roomId: string | null, currentPath: string): string {+ if (roomId) return shareRoutePath(roomId)+ return currentPath.startsWith(SHARE_ROUTE_PREFIX) ? '/' : currentPath+}++/**+ * Keeps the address bar on the active tab's room: `/share/<id>` while a room tab is active, and+ * back to `/` when the active tab is not in a room, so a reload or a copied URL opens what is+ * on screen.+ */+export function syncRoomRoute(router: Router, route: RouteLocationNormalizedLoaded): () => void {+ return watch(+ () => activeRoom.value?.roomId ?? null,+ (roomId) => {+ const path = roomPathFor(roomId, route.path)+ if (path === route.path) return+ void router.replace({ path, query: route.query, hash: route.hash })+ },+ { immediate: true }+ )+}diff --git a/src/app/collab/session.ts b/src/app/collab/session.tsindex 4a82c9808..1c07b030a 100644--- a/src/app/collab/session.ts+++ b/src/app/collab/session.ts@@ -1,242 +1,246 @@-import { shallowRef, type Ref, type ShallowRef } from 'vue'+import { useIntervalFn } from '@vueuse/core'+import { computed, ref, shallowRef, watch, type ComputedRef, type Ref } from 'vue'import { IndexeddbPersistence } from 'y-indexeddb'import * as awarenessProtocol from 'y-protocols/awareness'-import type { Awareness } from 'y-protocols/awareness'import * as Y from 'yjs'-import { randomIndex } from '@open-pencil/scene-graph/random'-+import { buildRemotePeers } from '@/app/collab/awareness'+import { useCollabIdentity } from '@/app/collab/identity'import { publishLocalAgents } from '@/app/collab/local-awareness'-import { connectCollabRoom } from '@/app/collab/room'-import type { CollabRoomTransport } from '@/app/collab/transport'-import type { CollabState } from '@/app/collab/types'-import { bindCollabGraphEvents, registerYjsObservers } from '@/app/collab/yjs-sync'+import { connectCollabRoom } from '@/app/collab/room/connection'+import { deriveRoomStatus, type RoomStatus } from '@/app/collab/room/status'+import {+ readRoomName,+ readRoot,+ TREE_FORMAT,+ writeRoomName,+ type YNodes+} from '@/app/collab/shared-tree/fields'+import type { JoinCollabRoom } from '@/app/collab/transport'+import type { RemotePeer } from '@/app/collab/types'+import {+ bindCollabGraphEvents,+ createYjsGraphSync,+ registerYjsObservers+} from '@/app/collab/yjs-sync'import type { EditorStore } from '@/app/editor/active-store'import { setPeers } from '@/app/presence/registry'-import { PEER_COLORS } from '@/constants'--export type CollabRuntime = {- ydoc: Y.Doc | null- awareness: awarenessProtocol.Awareness | null- ynodes: Y.Map<Y.Map<unknown>> | null- yimages: Y.Map<Uint8Array> | null- room: CollabRoomTransport | null- persistence: IndexeddbPersistence | null- /** Reactive, so what depends on the room's document follows connects and disconnects. */- connectedStore: ShallowRef<EditorStore | null>- suppressGraphSync: boolean- suppressYjsEvents: boolean- unbindGraphEvents: (() => void) | null- stopZoomWatch: (() => void) | null- stopAgentSync: (() => void) | null-}--type ConnectCollabSessionOptions = {- roomId: string- runtime: CollabRuntime- state: Ref<CollabState>- store: EditorStore- disconnect: () => void- updatePeersList: () => void- broadcastAwareness: () => void- applyYjsToGraph: (events: Y.YEvent<Y.Map<unknown>>[]) => void- syncNodeToYjs: (nodeId: string) => void+import { ROOM_STATUS_TICK_MS, ROOM_UNREACHABLE_MS } from '@/constants'++/** How a tab came to be in a room: by sharing its own document, or by joining someone's. */+export type RoomOrigin = 'shared' | 'joined'++/** One room, live in one tab: its document, presence, connection, and saved copy. */+export interface RoomSession {+ readonly roomId: string+ readonly store: EditorStore+ readonly origin: RoomOrigin+ readonly peers: Readonly<Ref<RemotePeer[]>>+ readonly status: ComputedRef<RoomStatus>+ /** Whether the room's document has reached this tab, from a peer or the saved copy. */+ readonly hasDocument: Readonly<Ref<boolean>>+ updateCursor(x: number, y: number, pageId: string): void+ updateSelection(ids: string[]): void+ /** Writes the tab's whole document into the room and makes its root the room's. */+ shareDocument(): void+ /** Leaves the room and releases its connection, presence, and saved-copy handle. */+ dispose(): void}-type CollabConnectionActionsOptions = {- runtime: CollabRuntime- state: Ref<CollabState>- getStore: () => EditorStore- updatePeersList: () => void- broadcastAwareness: () => void- applyYjsToGraph: (events: Y.YEvent<Y.Map<unknown>>[]) => void- syncNodeToYjs: (nodeId: string) => void+/** This device's saved copy of a room, so it opens before anyone else is online. */+export interface RoomSavedCopy {+ whenSynced: Promise<unknown>+ destroy(): unknown}-type CollabSessionResources = {+export interface RoomSessionOptions {+ roomId: stringstore: EditorStore- room: CollabRoomTransport | null- awareness: awarenessProtocol.Awareness | null- persistence: IndexeddbPersistence | null- ydoc: Y.Doc | null- unbindGraphEvents: (() => void) | null- stopZoomWatch: (() => void) | null- stopAgentSync: (() => void) | null+ origin: RoomOrigin+ joinRoom?: JoinCollabRoom+ openSavedCopy?: (roomId: string, ydoc: Y.Doc) => RoomSavedCopy+ /** How long the tab tries to reach the service that introduces peers before saying it cannot. */+ unreachableMs?: number+ /** How often the tab rechecks its connection while it waits for the file. */+ tickMs?: number}-export function createCollabRuntime(): CollabRuntime {- return {- ydoc: null,- awareness: null,- ynodes: null,- yimages: null,- room: null,- persistence: null,- connectedStore: shallowRef<EditorStore | null>(null),- suppressGraphSync: false,- suppressYjsEvents: false,- unbindGraphEvents: null,- stopZoomWatch: null,- stopAgentSync: null- }+function openIndexedDBCopy(roomId: string, ydoc: Y.Doc): RoomSavedCopy {+ return new IndexeddbPersistence(`op-room-${roomId}`, ydoc)}-export function createInitialCollabState(localName: string): CollabState {- return {- connected: false,- roomId: null,- peers: [],- localName,- localColor: PEER_COLORS[randomIndex(PEER_COLORS.length)]- }-}+type CursorState = { x: number; y: number; pageId: string; zoom: number }-export function createCollabConnectionActions({- runtime,- state,- getStore,- updatePeersList,- broadcastAwareness,- applyYjsToGraph,- syncNodeToYjs-}: CollabConnectionActionsOptions) {- function connect(roomId: string) {- connectCollabSession({- roomId,- runtime,- state,- store: getStore(),- disconnect,- updatePeersList,- broadcastAwareness,- applyYjsToGraph,- syncNodeToYjs+export function openRoomSession({+ roomId,+ store,+ origin,+ joinRoom,+ openSavedCopy = openIndexedDBCopy,+ unreachableMs = ROOM_UNREACHABLE_MS,+ tickMs = ROOM_STATUS_TICK_MS+}: RoomSessionOptions): RoomSession {+ const identity = useCollabIdentity()+ const ydoc = new Y.Doc()+ const awareness = new awarenessProtocol.Awareness(ydoc)+ const ynodes: YNodes = ydoc.getMap('nodes')+ const yimages = ydoc.getMap<Uint8Array>('images')+ const meta = ydoc.getMap<unknown>('meta')+ const persistence = openSavedCopy(roomId, ydoc)++ const peers = shallowRef<RemotePeer[]>([])+ const hasDocument = ref(false)+ const savedCopyLoaded = ref(false)+ const openedAt = Date.now()+ const now = ref(openedAt)+ /** When the current stretch of being connected to the service that introduces peers began. */+ const connectedSince = ref<number | null>(null)+ let suppressYjsEvents = false+ let suppressGraphSync = false+ let disposed = false++ const status = computed(() =>+ deriveRoomStatus({+ hasDocument: hasDocument.value,+ savedCopyLoaded: savedCopyLoaded.value,+ openFor: now.value - openedAt,+ connectedFor: connectedSince.value === null ? null : now.value - connectedSince.value,+ discoveryMs: connection.room.discoveryMs,+ unreachableMs,+ peerCount: peers.value.length,+ peersWithFile: peers.value.filter((peer) => peer.hasFile).length})- }+ )- function disconnect() {- const store = runtime.connectedStore.value ?? getStore()- disposeCollabSessionResources({- store,- room: runtime.room,- awareness: runtime.awareness,- persistence: runtime.persistence,- ydoc: runtime.ydoc,- unbindGraphEvents: runtime.unbindGraphEvents,- stopZoomWatch: runtime.stopZoomWatch,- stopAgentSync: runtime.stopAgentSync- })- resetCollabRuntime(runtime)- resetCollabConnectionState(state)+ const sync = createYjsGraphSync({+ getStore: () => store,+ getYdoc: () => (disposed ? null : ydoc),+ getYnodes: () => (disposed ? null : ynodes),+ getYimages: () => (disposed ? null : yimages),+ setSuppressYjsEvents: (value) => {+ suppressYjsEvents = value+ }+ })++ function refreshDocument() {+ if (disposed) return+ const rootId = readRoot(meta)+ hasDocument.value = rootId !== undefined && store.graph.rootId === rootId+ // Newcomers wait for someone who has the file, so peers say whether they do.+ if (awareness.getLocalState()?.hasFile !== hasDocument.value) {+ awareness.setLocalStateField('hasFile', hasDocument.value)+ }+ const name = readRoomName(meta)+ if (hasDocument.value && name && origin === 'joined') store.state.documentName = name}- return { connect, disconnect }-}+ function updatePeers() {+ const next = buildRemotePeers(+ awareness.getStates() as Map<number, Record<string, unknown>>,+ awareness.clientID+ )+ peers.value = next+ setPeers(store, next)+ }-export function watchAwarenessZoom(store: EditorStore, getAwareness: () => Awareness | null) {- return store.onEditorEvent('viewport:changed', (viewport) => {- const awareness = getAwareness()- if (!awareness) return- const prev = awareness.getLocalState()?.cursor as- | { x: number; y: number; pageId: string; zoom: number }- | undefined- if (prev) {- awareness.setLocalStateField('cursor', { ...prev, zoom: viewport.zoom })- }- })-}+ function broadcastIdentity() {+ awareness.setLocalStateField('user', { name: identity.name.value, color: identity.color })+ awareness.setLocalStateField('treeFormat', TREE_FORMAT)+ }-export function connectCollabSession({- roomId,- runtime,- state,- store,- disconnect,- updatePeersList,- broadcastAwareness,- applyYjsToGraph,- syncNodeToYjs-}: ConnectCollabSessionOptions) {- if (runtime.room) disconnect()-- runtime.connectedStore.value = store- state.value.roomId = roomId- runtime.ydoc = new Y.Doc()- runtime.awareness = new awarenessProtocol.Awareness(runtime.ydoc)- runtime.ynodes = runtime.ydoc.getMap('nodes')- runtime.yimages = runtime.ydoc.getMap('images')- runtime.persistence = new IndexeddbPersistence(`op-room-${roomId}`, runtime.ydoc)-- // Peer updates also move the view of anyone following them.- runtime.awareness.on('change', updatePeersList)-- registerYjsObservers({+ const unregisterYjsObservers = registerYjsObservers({store,- ynodes: runtime.ynodes,- yimages: runtime.yimages,- getSuppressYjsEvents: () => runtime.suppressYjsEvents,+ ynodes,+ yimages,+ getSuppressYjsEvents: () => suppressYjsEvents,setSuppressGraphSync: (value) => {- runtime.suppressGraphSync = value+ suppressGraphSync = value},- applyYjsToGraph+ applyYjsToGraph: (events) => {+ sync.applyYjsToGraph(events)+ refreshDocument()+ }})+ meta.observe(refreshDocument)+ awareness.on('change', updatePeers)- const roomConnection = connectCollabRoom({+ const connection = connectCollabRoom({roomId,- ydoc: runtime.ydoc,- awareness: runtime.awareness,- setConnected: () => {- state.value.connected = true- },- updatePeersList+ ydoc,+ awareness,+ updatePeersList: updatePeers,+ joinRoom})- runtime.room = roomConnection.room- state.value.connected = true- broadcastAwareness()+ broadcastIdentity()- runtime.stopZoomWatch = watchAwarenessZoom(store, () => runtime.awareness)- runtime.stopAgentSync = publishLocalAgents(store, () => runtime.awareness, state.value.localColor)-- runtime.unbindGraphEvents = bindCollabGraphEvents({+ void persistence.whenSynced.then(() => {+ if (disposed) return undefined+ savedCopyLoaded.value = true+ refreshDocument()+ return undefined+ })+ // Signaling services report no events, so the tab polls while it waits for the file.+ function checkConnection() {+ now.value = Date.now()+ if (!connection.room.signalingConnected()) connectedSince.value = null+ else connectedSince.value ??= now.value+ }+ checkConnection()+ const connectionTimer = useIntervalFn(() => {+ if (!hasDocument.value) checkConnection()+ }, tickMs)++ const stopNameWatch = watch(identity.name, broadcastIdentity)+ const stopZoomWatch = store.onEditorEvent('viewport:changed', (viewport) => {+ const cursor = awareness.getLocalState()?.cursor as CursorState | undefined+ if (cursor) awareness.setLocalStateField('cursor', { ...cursor, zoom: viewport.zoom })+ })+ const stopAgentSync = publishLocalAgents(store, () => awareness, identity.color)+ const unbindGraphEvents = bindCollabGraphEvents({store,- getYdoc: () => runtime.ydoc,- getYnodes: () => runtime.ynodes,- getSuppressGraphSync: () => runtime.suppressGraphSync,- setSuppressYjsEvents: (value) => {- runtime.suppressYjsEvents = value- },- syncNodeToYjs+ getYdoc: () => (disposed ? null : ydoc),+ getYnodes: () => (disposed ? null : ynodes),+ getSuppressGraphSync: () => suppressGraphSync,+ syncLocalEdit: sync.syncLocalEdit})-}--export function resetCollabRuntime(runtime: CollabRuntime) {- runtime.unbindGraphEvents = null- runtime.stopZoomWatch = null- runtime.stopAgentSync = null- runtime.room = null- runtime.awareness = null- runtime.persistence = null- runtime.ydoc = null- runtime.ynodes = null- runtime.yimages = null- runtime.connectedStore.value = null-}-export function resetCollabConnectionState(state: Ref<CollabState>) {- state.value.connected = false- state.value.roomId = null- state.value.peers = []-}--export function disposeCollabSessionResources(resources: CollabSessionResources) {- resources.unbindGraphEvents?.()- resources.stopZoomWatch?.()- void resources.room?.leave()- resources.awareness?.destroy()- if (resources.persistence) {- void resources.persistence.destroy()+ return {+ roomId,+ store,+ origin,+ peers,+ status,+ hasDocument,+ updateCursor(x, y, pageId) {+ awareness.setLocalStateField('cursor', { x, y, pageId, zoom: store.state.zoom })+ },+ updateSelection(ids) {+ awareness.setLocalStateField('selection', ids)+ },+ shareDocument() {+ sync.syncAllNodesToYjs()+ writeRoomName(meta, store.state.documentName)+ refreshDocument()+ },+ dispose() {+ if (disposed) return+ // Unbinding writes an edit still waiting to be sent, so it runs while the room is open.+ unbindGraphEvents()+ disposed = true+ connectionTimer.pause()+ stopNameWatch()+ stopZoomWatch()+ stopAgentSync()+ meta.unobserve(refreshDocument)+ unregisterYjsObservers()+ // Destroying the awareness can emit a last change; nothing here should react to it.+ awareness.off('change', updatePeers)+ void connection.room.leave()+ awareness.destroy()+ void persistence.destroy()+ ydoc.destroy()+ peers.value = []+ setPeers(store, [])+ }}- resources.ydoc?.destroy()- resources.stopAgentSync?.()- setPeers(resources.store, [])}diff --git a/src/app/collab/shared-tree/fields.ts b/src/app/collab/shared-tree/fields.tsnew file mode 100644index 000000000..bc9c9eef0--- /dev/null+++ b/src/app/collab/shared-tree/fields.ts@@ -0,0 +1,143 @@+import * as v from 'valibot'+import * as Y from 'yjs'++import { randomIndex } from '@open-pencil/scene-graph/random'++/**+ * How a shared document records the layer tree. Each layer's map holds `parents`, a nested map+ * from every parent the layer has been moved under to the move counter, and `orderKey`, its+ * fractional position among siblings, and `page`, the page this peer last placed it on, where it+ * goes once no recorded parent is left; `parentId` and `childIds` are derived on each peer+ * (`src/app/collab/tree/layer-tree.ts`). The document-wide `meta` map holds the room's root and+ * name, the move clock, and the tree format.+ */+export const TREE_FORMAT = 2+export const PARENTS_FIELD = 'parents'+export const ORDER_KEY_FIELD = 'orderKey'+export const PAGE_FIELD = 'page'++const ROOT_KEY = 'root'+const NAME_KEY = 'name'+const CLOCK_KEY = 'clock'+const FORMAT_KEY = 'treeFormat'+const KEY_SUFFIX_LENGTH = 3+const KEY_SUFFIX_FIRST = 33 // '!'+const KEY_SUFFIX_RANGE = 94 // '!' to '~'+const MAX_ORDER_KEY_LENGTH = 4096++export type YNodes = Y.Map<Y.Map<unknown>>+export type YMeta = Y.Map<unknown>++const counterSchema = v.pipe(v.number(), v.safeInteger(), v.minValue(0))+const orderKeySchema = v.pipe(+ v.string(),+ v.minLength(1),+ v.maxLength(MAX_ORDER_KEY_LENGTH),+ v.regex(/^[\x20-\x7e]+$/)+)+const layerIdSchema = v.pipe(v.string(), v.minLength(1))+const MAX_ROOM_NAME_LENGTH = 256+const roomNameSchema = v.pipe(v.string(), v.minLength(1), v.maxLength(MAX_ROOM_NAME_LENGTH))++export function readCounter(value: unknown): number | undefined {+ const result = v.safeParse(counterSchema, value)+ return result.success ? result.output : undefined+}++/** A layer's parent entries, or undefined when its map does not record them yet. */+export function readParentEntries(ynode: Y.Map<unknown>): Map<string, number> | undefined {+ const parents = ynode.get(PARENTS_FIELD)+ if (!(parents instanceof Y.Map)) return undefined+ const entries = new Map<string, number>()+ for (const [parentId, value] of parents.entries()) {+ const counter = readCounter(value)+ if (counter !== undefined) entries.set(parentId, counter)+ }+ return entries+}++export function readOrderKey(ynode: Y.Map<unknown>): string | undefined {+ const result = v.safeParse(orderKeySchema, ynode.get(ORDER_KEY_FIELD))+ return result.success ? result.output : undefined+}++export function readPage(ynode: Y.Map<unknown>): string | undefined {+ const result = v.safeParse(layerIdSchema, ynode.get(PAGE_FIELD))+ return result.success ? result.output : undefined+}++/**+ * The room's root: the root of the document someone shared into it, or the one a saved room's+ * conversion picked. Only Share and conversion write it, and a fresh room has one sharer while+ * converting peers pick the same root, so it never has two values; peers that joined never write+ * their own document into a room.+ */+export function readRoot(meta: YMeta): string | undefined {+ const result = v.safeParse(layerIdSchema, meta.get(ROOT_KEY))+ return result.success ? result.output : undefined+}++export function claimRoot(meta: YMeta, rootId: string): void {+ if (readRoot(meta) === undefined) meta.set(ROOT_KEY, rootId)+}++/** The name of the document shared into the room, so joiners' tabs show it. */+export function readRoomName(meta: YMeta): string | undefined {+ const result = v.safeParse(roomNameSchema, meta.get(NAME_KEY))+ return result.success ? result.output : undefined+}++export function writeRoomName(meta: YMeta, name: string): void {+ if (name.length > 0 && meta.get(NAME_KEY) !== name) meta.set(NAME_KEY, name)+}++export function writeParentEntry(ynode: Y.Map<unknown>, parentId: string, counter: number): void {+ let parents = ynode.get(PARENTS_FIELD)+ if (!(parents instanceof Y.Map)) {+ parents = new Y.Map<number>()+ ynode.set(PARENTS_FIELD, parents)+ }+ if (parents instanceof Y.Map && parents.get(parentId) !== counter) parents.set(parentId, counter)+}++/** Marks the root: a layer whose `parents` map is empty. */+export function writeRootEntries(ynode: Y.Map<unknown>): void {+ if (!(ynode.get(PARENTS_FIELD) instanceof Y.Map)) ynode.set(PARENTS_FIELD, new Y.Map<number>())+}++export function writeOrderKey(ynode: Y.Map<unknown>, orderKey: string): void {+ if (ynode.get(ORDER_KEY_FIELD) !== orderKey) ynode.set(ORDER_KEY_FIELD, orderKey)+}++export function writePage(ynode: Y.Map<unknown>, pageId: string): void {+ if (ynode.get(PAGE_FIELD) !== pageId) ynode.set(PAGE_FIELD, pageId)+}++/** Random printable characters for an order key, so concurrent inserts do not share a key. */+export function randomKeySuffix(): string {+ let suffix = ''+ for (let index = 0; index < KEY_SUFFIX_LENGTH; index++) {+ suffix += String.fromCharCode(KEY_SUFFIX_FIRST + randomIndex(KEY_SUFFIX_RANGE))+ }+ return suffix+}++/**+ * A Lamport clock for moves: one more than the highest counter this peer has seen, from the+ * document's `meta.clock` or any layer's entries. Concurrent moves may share a counter; the+ * parent id breaks the tie.+ */+export function createMoveClock() {+ let highest = 0+ return {+ next(meta: YMeta, seen: number): number {+ highest = Math.max(highest, seen, readCounter(meta.get(CLOCK_KEY)) ?? 0) + 1+ meta.set(CLOCK_KEY, highest)+ return highest+ }+ }+}++export function markTreeFormat(meta: YMeta): void {+ if (meta.get(FORMAT_KEY) !== TREE_FORMAT) meta.set(FORMAT_KEY, TREE_FORMAT)+}diff --git a/src/app/collab/shared-tree/migration.ts b/src/app/collab/shared-tree/migration.tsnew file mode 100644index 000000000..8a274edff--- /dev/null+++ b/src/app/collab/shared-tree/migration.ts@@ -0,0 +1,157 @@+import * as v from 'valibot'+import * as Y from 'yjs'++import { siblingOrderKeys } from '@open-pencil/scene-graph/order-keys'++import { topEdge } from '@/app/collab/tree/entries'++import {+ claimRoot,+ markTreeFormat,+ PARENTS_FIELD,+ readOrderKey,+ readParentEntries,+ readRoot,+ writeOrderKey,+ writePage,+ writeParentEntry,+ writeRootEntries,+ type YMeta,+ type YNodes+} from './fields'++/** Fields format 1 synced directly and format 2 derives. */+const LEGACY_TREE_FIELDS = ['parentId', 'childIds'] as const+const legacyParentSchema = v.nullable(v.string())+const legacyChildIdsSchema = v.array(v.string())++/** The origin of a migration this peer writes; the change that triggered it applies it. */+export const TREE_MIGRATION_ORIGIN = Symbol('collab-tree-migration')++export function isLegacyLayer(ynode: Y.Map<unknown>): boolean {+ return !(ynode.get(PARENTS_FIELD) instanceof Y.Map) && ynode.has('parentId')+}++function legacyParentOf(ynode: Y.Map<unknown>): string | null | undefined {+ const result = v.safeParse(legacyParentSchema, ynode.get('parentId'))+ return result.success ? result.output : undefined+}++function legacyChildIdsOf(ynode: Y.Map<unknown> | undefined): string[] {+ const result = v.safeParse(legacyChildIdsSchema, ynode?.get('childIds'))+ return result.success ? result.output : []+}++/**+ * Converts layers a format 1 document recorded to format 2: each layer's synced parent becomes+ * its only entry, with counter 0, and its position in that parent's synced `childIds` becomes an+ * order key, and the page its synced ancestors reach becomes its page; siblings already converted+ * keep theirs. The root with the most children becomes the room's root. The result depends only on the document, so+ * peers that convert the same layers at once write the same values. Returns the converted ids.+ */+export function migrateLegacyLayers(+ ydoc: Y.Doc,+ ynodes: YNodes,+ meta: YMeta,+ layerIds: Iterable<string>+): string[] {+ const legacy = [...new Set(layerIds)].filter((id) => {+ const ynode = ynodes.get(id)+ return ynode !== undefined && isLegacyLayer(ynode)+ })+ if (legacy.length === 0) return []++ const byParent = new Map<string | null, Set<string>>()+ for (const id of legacy) {+ const parentId = legacyParentOf(ynodes.get(id) ?? new Y.Map())+ if (parentId === undefined) continue+ let siblings = byParent.get(parentId)+ if (!siblings) {+ siblings = new Set()+ byParent.set(parentId, siblings)+ }+ siblings.add(id)+ }++ // Pages are found before any layer drops its synced parent.+ const pages = new Map(legacy.map((id) => [id, legacyPageOf(ynodes, id)]))++ ydoc.transact(() => {+ for (const [parentId, migrating] of byParent) {+ if (parentId === null) {+ for (const id of migrating) {+ const ynode = ynodes.get(id)+ if (ynode) writeRootEntries(ynode)+ }+ claimLegacyRoot(ynodes, meta, migrating)+ continue+ }+ const listed = legacyChildIdsOf(ynodes.get(parentId)).filter(+ (id) => ynodes.get(id) && (migrating.has(id) || legacyParentOrEntry(ynodes, id, parentId))+ )+ const order = [...new Set(listed)]+ const unlisted = [...migrating].filter((id) => !order.includes(id)).sort()+ order.push(...unlisted)+ const keys = siblingOrderKeys(+ order.map((id) => {+ const ynode = ynodes.get(id)+ return ynode && !migrating.has(id) ? readOrderKey(ynode) : undefined+ })+ )+ order.forEach((id, index) => {+ const ynode = ynodes.get(id)+ if (!ynode || !migrating.has(id)) return+ writeParentEntry(ynode, parentId, 0)+ writeOrderKey(ynode, keys[index])+ const pageId = pages.get(id)+ if (pageId !== undefined) writePage(ynode, pageId)+ })+ }+ for (const id of legacy) {+ const ynode = ynodes.get(id)+ if (!ynode || !(ynode.get(PARENTS_FIELD) instanceof Y.Map)) continue+ for (const field of LEGACY_TREE_FIELDS) if (ynode.has(field)) ynode.delete(field)+ }+ markTreeFormat(meta)+ }, TREE_MIGRATION_ORIGIN)+ return legacy+}++/** Whether a converted sibling still lists `parentId` among its entries. */+function legacyParentOrEntry(ynodes: YNodes, id: string, parentId: string): boolean {+ const ynode = ynodes.get(id)+ return ynode !== undefined && readParentEntries(ynode)?.has(parentId) === true+}++/**+ * The nearest page above a layer, following each ancestor's synced parent, or its newest entry+ * once it has been converted. Undefined for the root and the pages themselves.+ */+function legacyPageOf(ynodes: YNodes, id: string): string | undefined {+ if (ynodes.get(id)?.get('type') === 'CANVAS') return undefined+ let current = ynodes.get(id)+ for (let steps = 0; current && steps < ynodes.size; steps++) {+ const entries = readParentEntries(current)+ const parentId = entries ? topEdge(entries)?.parentId : legacyParentOf(current)+ if (!parentId) return undefined+ current = ynodes.get(parentId)+ if (current?.get('type') === 'CANVAS') return parentId+ }+ return undefined+}++/**+ * Claims the room's root for a converted document. Format 1 rooms could hold several parentless+ * layers, such as a joiner's own document; the one with the most children, then the lowest id,+ * is the room's, so every converting peer claims the same one.+ */+function claimLegacyRoot(ynodes: YNodes, meta: YMeta, roots: ReadonlySet<string>): void {+ if (readRoot(meta) !== undefined) return+ // Sorting is stable, so roots with as many children stay in id order.+ const ranked = [...roots]+ .sort()+ .map((id) => ({ id, children: legacyChildIdsOf(ynodes.get(id)).length }))+ .sort((a, b) => b.children - a.children)+ const root = ranked.at(0)+ if (root) claimRoot(meta, root.id)+}diff --git a/src/app/collab/shared-tree/sync.ts b/src/app/collab/shared-tree/sync.tsnew file mode 100644index 000000000..c49a8ac33--- /dev/null+++ b/src/app/collab/shared-tree/sync.ts@@ -0,0 +1,339 @@+import { isEqual } from 'es-toolkit/predicate'+import type * as Y from 'yjs'++import type { SceneGraph } from '@open-pencil/scene-graph'+import { siblingOrderKeys } from '@open-pencil/scene-graph/order-keys'++import { LayerTree, type TreeMove } from '@/app/collab/tree/layer-tree'++import {+ createMoveClock,+ markTreeFormat,+ randomKeySuffix,+ readOrderKey,+ readPage,+ readParentEntries,+ readRoot,+ writeOrderKey,+ writePage,+ writeParentEntry,+ type YMeta,+ type YNodes+} from './fields'++/** What one local edit changed, collected from graph events and written in one transaction. */+export interface LocalEdit {+ /** Layers whose own properties changed, or that were created. */+ changed: Set<string>+ /** Layers that moved or were reordered: their parent entry and order key are rewritten. */+ placed: Set<string>+ /** Parents whose child list was assigned directly, such as by a rollback. */+ reordered: Set<string>+ /** Parents layers left; displaced layers on their paths are re-recorded. */+ previousParents: Set<string>+ deleted: Set<string>+}++export function createLocalEdit(): LocalEdit {+ return {+ changed: new Set(),+ placed: new Set(),+ reordered: new Set(),+ previousParents: new Set(),+ deleted: new Set()+ }+}++export function isLocalEditEmpty(edit: LocalEdit): boolean {+ return Object.values(edit).every((ids: Set<string>) => ids.size === 0)+}++/** The resolved layer tree of one shared document, kept beside the scene graph it mirrors. */+export type SharedTree = ReturnType<typeof createSharedTree>++export function createSharedTree(+ ydoc: Y.Doc,+ getGraph: () => SceneGraph,+ getYnodes: () => YNodes | null+) {+ let rootId: string | null = null+ const clock = createMoveClock()+ const tree: LayerTree = new LayerTree({+ orphanParentOf(layerId: string): string | null {+ if (rootId === null || layerId === rootId) return null+ const root = rootId+ const graph = getGraph()+ if (graph.getNode(layerId)?.type === 'CANVAS') return root+ const isPage = (id: string) =>+ tree.parentOf(id) === root && graph.getNode(id)?.type === 'CANVAS'+ // The page the layer was last placed on; failing that, the first page in the shared+ // order, so every peer picks the same one.+ const ynode = getYnodes()?.get(layerId)+ const recorded = ynode ? readPage(ynode) : undefined+ if (recorded !== undefined && isPage(recorded)) return recorded+ return tree.childrenOf(root).find(isPage) ?? root+ }+ })+ return {+ ydoc,+ tree,+ clock,+ get rootId() {+ return rootId+ },+ setRoot(id: string) {+ rootId = id+ }+ }+}++/**+ * Writes where this peer put the layers an edit placed: a parent entry with a new counter for+ * each layer whose parent changed, the same for displaced layers on the paths the moves touched+ * (so a move cannot pull another layer back into a parent it was kept out of), the page of each+ * moved layer and of the layers under it, and order keys between each placed layer's+ * neighbours. Call inside the edit's transaction.+ */+export function writeLocalPlacement(+ shared: SharedTree,+ graph: SceneGraph,+ ynodes: YNodes,+ meta: YMeta,+ edit: LocalEdit+): void {+ const { moved, pathStarts } = findMoves(shared, graph, ynodes, edit)+ recordMoves(shared, graph, ynodes, meta, moved, pathStarts)+ writePages(graph, ynodes, moved)++ const keyed = new Set([...edit.placed, ...moved])+ const parents = new Set(edit.reordered)+ for (const id of keyed) {+ const parentId = graph.getNode(id)?.parentId+ if (parentId) parents.add(parentId)+ }+ for (const parentId of parents) writeSiblingKeys(shared.tree, graph, ynodes, parentId, keyed)+}++/** Layers the edit left under a parent other than the shared tree's, and the paths they touch. */+function findMoves(shared: SharedTree, graph: SceneGraph, ynodes: YNodes, edit: LocalEdit) {+ const { tree } = shared+ const candidates = new Set([...edit.placed, ...edit.changed])+ for (const parentId of edit.reordered) {+ for (const childId of graph.getNode(parentId)?.childIds ?? []) candidates.add(childId)+ }+ const moved: string[] = []+ const pathStarts: (string | null | undefined)[] = [...edit.previousParents]+ for (const id of candidates) {+ const parentId = graph.getNode(id)?.parentId+ if (!parentId || !ynodes.has(id)) continue+ if (!tree.has(id) || tree.parentOf(id) !== parentId) {+ moved.push(id)+ pathStarts.push(tree.parentOf(id), parentId)+ }+ }+ return { moved, pathStarts }+}++/**+ * Gives every moved layer a parent entry with one new counter, and re-records displaced layers+ * on the touched paths under their current parent, as Evan Wallace's algorithm does, so this+ * move cannot pull them back into a parent they were kept out of.+ */+function recordMoves(+ shared: SharedTree,+ graph: SceneGraph,+ ynodes: YNodes,+ meta: YMeta,+ moved: readonly string[],+ pathStarts: readonly (string | null | undefined)[]+): void {+ const { tree } = shared+ const movedIds = new Set(moved)+ const kept = tree.displacedAncestors(pathStarts).filter((id) => !movedIds.has(id))+ if (moved.length === 0 && kept.length === 0) return+ const counter = shared.clock.next(meta, tree.maxCounter)+ const placements = [+ ...kept.map((id) => [id, tree.parentOf(id)] as const),+ ...moved.map((id) => [id, graph.getNode(id)?.parentId] as const)+ ]+ for (const [id, parentId] of placements) {+ const ynode = ynodes.get(id)+ if (!parentId || !ynode) continue+ writeParentEntry(ynode, parentId, counter)+ tree.placeLocally(id, parentId, counter)+ }+ markTreeFormat(meta)+}++/** The page a layer sits on, or undefined for the root and the pages themselves. */+export function pageOf(graph: SceneGraph, layerId: string): string | undefined {+ if (graph.getNode(layerId)?.type === 'CANVAS') return undefined+ return graph.closest(layerId, (node) => node.type === 'CANVAS')?.id+}++/** Records the page of each moved layer and, when it changed, of every layer under it. */+function writePages(graph: SceneGraph, ynodes: YNodes, moved: readonly string[]): void {+ for (const id of moved) {+ const pageId = pageOf(graph, id)+ if (pageId === undefined) continue+ const stack = [id]+ for (let layerId = stack.pop(); layerId !== undefined; layerId = stack.pop()) {+ const ynode = ynodes.get(layerId)+ if (!ynode || readPage(ynode) === pageId) continue+ writePage(ynode, pageId)+ stack.push(...(graph.getNode(layerId)?.childIds ?? []))+ }+ }+}++/** Keys a parent's children in their local order, re-keying only the layers that need it. */+function writeSiblingKeys(+ tree: LayerTree,+ graph: SceneGraph,+ ynodes: YNodes,+ parentId: string,+ keyed: ReadonlySet<string>+): void {+ const children = (graph.getNode(parentId)?.childIds ?? []).filter(+ (id) => tree.parentOf(id) === parentId && ynodes.has(id)+ )+ const keys = siblingOrderKeys(+ children.map((id) => (keyed.has(id) ? undefined : tree.orderKeyOf(id))),+ { suffix: randomKeySuffix }+ )+ children.forEach((id, index) => {+ const key = keys[index]+ const ynode = ynodes.get(id)+ if (!ynode || tree.orderKeyOf(id) === key) return+ writeOrderKey(ynode, key)+ tree.setOrderKey(id, key)+ })+}++/**+ * Brings the scene graph to the tree the shared document describes after a change to the given+ * layers: records their entries and keys, resolves the tree, moves layers whose parent changed,+ * and sorts every parent the change touched by (order key, id). Moves go through+ * `insertChildAt`, so the graph's usual events fire.+ */+export function applySharedTree(+ shared: SharedTree,+ graph: SceneGraph,+ ynodes: YNodes,+ meta: YMeta,+ changed: Iterable<string>,+ deleted: Iterable<string>+): void {+ const { tree } = shared+ const touched = new Set<string>()+ const placed: string[] = []+ for (const id of changed) {+ const ynode = ynodes.get(id)+ const entries = ynode ? readParentEntries(ynode) : undefined+ if (!ynode || !entries || !graph.getNode(id)) continue+ const orderKey = readOrderKey(ynode)+ // Most changes edit a layer's own fields; its place and its siblings stay as they are.+ if (tree.has(id) && tree.orderKeyOf(id) === orderKey && isEqual(tree.entriesOf(id), entries)) {+ continue+ }+ const previousParent = tree.parentOf(id)+ if (previousParent) touched.add(previousParent)+ tree.setLayer(id, entries, orderKey)+ placed.push(id)+ }+ for (const id of deleted) tree.deleteLayer(id)+ adoptRoot(shared, graph, meta)++ // A second pass places layers whose page was itself placed in the first.+ const moves = [...tree.resolve(), ...tree.resolve()]+ applyMoves(graph, moves, touched)+ for (const id of placed) {+ const parentId = tree.parentOf(id)+ if (parentId) touched.add(parentId)+ }+ for (const parentId of touched) sortChildren(graph, tree, parentId)+}++/**+ * Removes the layers outside the room's tree from an edit, so they stay local: a peer that joined+ * a room keeps its own earlier document, which undo can still reach.+ */+export function keepSharedLayers(shared: SharedTree, graph: SceneGraph, edit: LocalEdit): void {+ const rootId = shared.rootId+ const isShared = (id: string) =>+ rootId !== null && graph.closest(id, (node) => node.id === rootId) !== undefined+ for (const ids of [edit.changed, edit.placed, edit.reordered, edit.previousParents]) {+ for (const id of ids) if (!isShared(id)) ids.delete(id)+ }+}++/** Records layers this peer wrote itself, such as when sharing its document. */+export function recordLocalLayers(+ shared: SharedTree,+ ynodes: YNodes,+ meta: YMeta,+ layerIds: Iterable<string>+) {+ for (const id of layerIds) {+ const ynode = ynodes.get(id)+ const entries = ynode ? readParentEntries(ynode) : undefined+ if (!ynode || !entries) continue+ shared.tree.setLayer(id, entries, readOrderKey(ynode))+ }+ const rootId = readRoot(meta)+ if (rootId !== undefined) shared.setRoot(rootId)+ shared.tree.resolve()+}++/**+ * Follows the root the room records. Layers under any other root, such as a joiner's own earlier+ * document, stay in the shared tree but out of the graph's pages.+ */+function adoptRoot(shared: SharedTree, graph: SceneGraph, meta: YMeta): void {+ const rootId = readRoot(meta)+ if (rootId === undefined || rootId === shared.rootId || !shared.tree.has(rootId)) return+ shared.setRoot(rootId)+ graph.rootId = rootId+}++function applyMoves(graph: SceneGraph, moves: TreeMove[], touched: Set<string>): void {+ const pending = new Map<string, string>()+ for (const move of moves) {+ if (move.to === null) pending.delete(move.layerId)+ else pending.set(move.layerId, move.to)+ }+ // The resolved tree has no loops, but reaching it can need one move before another.+ for (let progressed = true; progressed && pending.size > 0;) {+ progressed = false+ for (const [id, parentId] of pending) {+ const node = graph.getNode(id)+ const parent = graph.getNode(parentId)+ if (!node || !parent) {+ pending.delete(id)+ continue+ }+ if (node.parentId === parentId) {+ pending.delete(id)+ touched.add(parentId)+ continue+ }+ if (graph.isDescendant(parentId, id)) continue+ if (node.parentId) touched.add(node.parentId)+ touched.add(parentId)+ graph.insertChildAt(id, parentId, parent.childIds.length)+ pending.delete(id)+ progressed = true+ }+ }+}++function sortChildren(graph: SceneGraph, tree: LayerTree, parentId: string): void {+ const parent = graph.getNode(parentId)+ if (!parent) return+ const shared = tree.childrenOf(parentId).filter((id) => graph.getNode(id)?.parentId === parentId)+ const sharedIds = new Set(shared)+ const desired = [...shared, ...parent.childIds.filter((id) => !sharedIds.has(id))]+ desired.forEach((id, index) => {+ if (parent.childIds[index] !== id) graph.insertChildAt(id, parentId, index)+ })+}diff --git a/src/app/collab/transport/test.ts b/src/app/collab/transport/test.tsindex 0f2e93b6b..e17dca9d9 100644--- a/src/app/collab/transport/test.ts+++ b/src/app/collab/transport/test.ts@@ -1,9 +1,11 @@import { appRuntimeConfig } from '@/app/runtime/config'-import { IS_BROWSER } from '@/constants'+import { COLLAB_APP_ID, IS_BROWSER } from '@/constants'import type { CollabAction, CollabActionReceiver, CollabRoomTransport } from './types'const MAX_TEST_MESSAGE_BYTES = 8 * 1024 * 1024+/** The relay introduces peers as soon as they say hello. */+const TEST_DISCOVERY_MS = 1000type TestTransportMessage =| { type: 'hello'; senderId: string; targetId?: string }@@ -52,7 +54,8 @@ function relayURL(roomId: string): URL {const configured = appRuntimeConfig.collaborationRelayURLif (!configured) throw new Error('Test collaboration transport requires collabRelay')const url = new URL(configured)- url.searchParams.set('roomId', roomId)+ // Namespaced like Trystero's rooms, so only builds with the same document format meet.+ url.searchParams.set('roomId', `${COLLAB_APP_ID}:${roomId}`)return url}@@ -140,6 +143,8 @@ export function joinTestCollabRoom(roomId: string): CollabRoomTransport {onPeerLeave(handler) {leaveHandler = handler},+ signalingConnected: () => socket.readyState === WebSocket.OPEN,+ discoveryMs: TEST_DISCOVERY_MS,async leave() {if (left) returnleft = truediff --git a/src/app/collab/transport/trystero.ts b/src/app/collab/transport/trystero.tsindex de74fc993..88e28431d 100644--- a/src/app/collab/transport/trystero.ts+++ b/src/app/collab/transport/trystero.ts@@ -1,13 +1,19 @@-import { joinRoom as joinTrysteroRoom } from 'trystero/mqtt'+import { getRelaySockets, joinRoom as joinTrysteroRoom } from 'trystero/mqtt'-import { TRYSTERO_APP_ID } from '@/constants'+import { COLLAB_APP_ID } from '@/constants'import type { CollabAction, JoinCollabRoom } from './types'+/**+ * Trystero announces a peer to the room's brokers about every 5.3 seconds, so after two rounds+ * and a WebRTC handshake everyone already in the room has met a newcomer.+ */+const TRYSTERO_DISCOVERY_MS = 12_000+export const joinTrysteroCollabRoom: JoinCollabRoom = (roomId) => {const room = joinTrysteroRoom({- appId: TRYSTERO_APP_ID,+ appId: COLLAB_APP_ID,rtcConfig: {iceServers: [{ urls: 'stun:stun.l.google.com:19302' },@@ -38,6 +44,10 @@ export const joinTrysteroCollabRoom: JoinCollabRoom = (roomId) => {},onPeerJoin: (handler) => room.onPeerJoin(handler),onPeerLeave: (handler) => room.onPeerLeave(handler),+ // Brokers are shared by every room this window joins; any one of them carries announcements.+ signalingConnected: () =>+ Object.values(getRelaySockets()).some((socket) => socket.readyState === WebSocket.OPEN),+ discoveryMs: TRYSTERO_DISCOVERY_MS,leave: async () => {await room.leave()}diff --git a/src/app/collab/transport/types.ts b/src/app/collab/transport/types.tsindex e05e270d2..54d182951 100644--- a/src/app/collab/transport/types.ts+++ b/src/app/collab/transport/types.ts@@ -8,6 +8,13 @@ export interface CollabRoomTransport {makeAction(namespace: string): CollabActiononPeerJoin(handler: (peerId: string) => void): voidonPeerLeave(handler: (peerId: string) => void): void+ /**+ * Whether this peer has reached the service that introduces peers to each other, so that+ * silence from the room means nobody is in it rather than that nobody could hear us yet.+ */+ signalingConnected(): boolean+ /** How long after reaching that service everyone already in the room has met this peer. */+ readonly discoveryMs: numberleave(): Promise<void>}diff --git a/src/app/collab/tree/entries.ts b/src/app/collab/tree/entries.tsnew file mode 100644index 000000000..332b96a5e--- /dev/null+++ b/src/app/collab/tree/entries.ts@@ -0,0 +1,44 @@+/**+ * A layer's parent history: every parent it has been placed under, each with the move counter+ * of its latest placement there. The entry with the highest counter is where the layer belongs.+ */+export type ParentEntries = ReadonlyMap<string, number>++/** One placement of a layer, as the tree resolution ranks it. */+export interface ParentEdge {+ parentId: string+ counter: number+}++/** Newer placements first; equal counters from concurrent moves fall back to the parent id. */+export function compareEdges(a: ParentEdge, b: ParentEdge): number {+ if (a.counter !== b.counter) return b.counter - a.counter+ if (a.parentId === b.parentId) return 0+ return a.parentId < b.parentId ? 1 : -1+}++export function rankedEdges(entries: ParentEntries): ParentEdge[] {+ return [...entries].map(([parentId, counter]) => ({ parentId, counter })).sort(compareEdges)+}++/** The entry a layer would sit under if nothing stopped it. */+export function topEdge(entries: ParentEntries): ParentEdge | undefined {+ let top: ParentEdge | undefined+ for (const [parentId, counter] of entries) {+ const edge = { parentId, counter }+ if (!top || compareEdges(edge, top) < 0) top = edge+ }+ return top+}++/** Siblings sort by order key, and layers that share a key by id, so every peer agrees. */+export function compareSiblings(+ a: { id: string; orderKey: string | undefined },+ b: { id: string; orderKey: string | undefined }+): number {+ const keyA = a.orderKey ?? ''+ const keyB = b.orderKey ?? ''+ if (keyA !== keyB) return keyA < keyB ? -1 : 1+ if (a.id === b.id) return 0+ return a.id < b.id ? -1 : 1+}diff --git a/src/app/collab/tree/layer-tree.ts b/src/app/collab/tree/layer-tree.tsnew file mode 100644index 000000000..48bf9260b--- /dev/null+++ b/src/app/collab/tree/layer-tree.ts@@ -0,0 +1,278 @@+import {+ compareSiblings,+ rankedEdges,+ topEdge,+ type ParentEdge,+ type ParentEntries+} from './entries'++/**+ * The layer tree a shared document describes, resolved the same way on every peer.+ *+ * Each layer records every parent it has been moved under with a move counter (`ParentEntries`)+ * and an order key among its siblings. Following Evan Wallace's mutable tree hierarchy CRDT+ * (https://madebyevan.com/algos/crdt-mutable-tree-hierarchy/), a layer sits under the parent with+ * the highest counter, ties broken by parent id. When concurrent moves close a loop, the layer in+ * the loop whose placement has the highest (counter, layer id) — the latest move — falls back to+ * its next entry, until no loop is left. A layer none of whose parents exist, or can take it+ * without a loop, goes where `orphanParentOf` says: its page. Siblings sort by (order key, id).+ *+ * The resolved tree is a function of the entries alone, so peers that hold the same entries hold+ * the same tree whatever order the changes reached them in. Resolution is incremental: it+ * revisits only the layers that changed, lost a parent, or sit somewhere other than their newest+ * entry.+ */+export interface LayerTreeOptions {+ /** Where a layer that no recorded parent can take goes, or null to leave it out of the tree. */+ orphanParentOf(layerId: string): string | null+}++/** A layer whose resolved parent changed; `from` is undefined for a layer new to the tree. */+export interface TreeMove {+ layerId: string+ from: string | null | undefined+ to: string | null+}++interface TreeLayer {+ entries: ParentEntries+ orderKey: string | undefined+}++/** Marks the walk state of a layer while looking for loops. */+const ON_PATH = 1+const SETTLED = 2++export class LayerTree {+ private readonly layers = new Map<string, TreeLayer>()+ private readonly resolved = new Map<string, string | null>()+ private readonly children = new Map<string, Set<string>>()+ /** Layers that sit somewhere other than their newest entry, so a change can move them back. */+ private readonly displaced = new Set<string>()+ private readonly pending = new Set<string>()+ private highestCounter = 0++ constructor(private readonly options: LayerTreeOptions) {}++ has(layerId: string): boolean {+ return this.layers.has(layerId)+ }++ get size(): number {+ return this.layers.size+ }++ /** The highest move counter any layer's entries hold. */+ get maxCounter(): number {+ return this.highestCounter+ }++ entriesOf(layerId: string): ParentEntries | undefined {+ return this.layers.get(layerId)?.entries+ }++ orderKeyOf(layerId: string): string | undefined {+ return this.layers.get(layerId)?.orderKey+ }++ /** The resolved parent: null for the root, undefined for a layer the tree does not hold. */+ parentOf(layerId: string): string | null | undefined {+ return this.resolved.get(layerId)+ }++ /** A parent's children by (order key, id). */+ childrenOf(parentId: string): string[] {+ return [...(this.children.get(parentId) ?? [])]+ .map((id) => ({ id, orderKey: this.layers.get(id)?.orderKey }))+ .sort(compareSiblings)+ .map((child) => child.id)+ }++ /** Whether the layer sits somewhere other than its newest entry. */+ isDisplaced(layerId: string): boolean {+ return this.displaced.has(layerId)+ }++ /**+ * Displaced layers on the paths from `startIds` to the root. A move re-records their current+ * parent with a new counter, so it cannot pull a layer back into a parent it was kept out of.+ */+ displacedAncestors(startIds: Iterable<string | null | undefined>): string[] {+ const found = new Set<string>()+ const visited = new Set<string>()+ for (const start of startIds) {+ for (let id = start; id != null && !visited.has(id); id = this.resolved.get(id)) {+ visited.add(id)+ if (this.displaced.has(id)) found.add(id)+ }+ }+ return [...found]+ }++ /** Records a layer's shared entries and order key; `resolve` places it. */+ setLayer(layerId: string, entries: ParentEntries, orderKey: string | undefined): void {+ this.layers.set(layerId, { entries, orderKey })+ for (const counter of entries.values()) this.noteCounter(counter)+ this.pending.add(layerId)+ }++ setOrderKey(layerId: string, orderKey: string): void {+ const layer = this.layers.get(layerId)+ if (layer) layer.orderKey = orderKey+ }++ /**+ * Records a move this peer made: the layer is already under `parentId`, and `counter` is newer+ * than every entry the layer has, so the resolution agrees without revisiting it.+ */+ placeLocally(layerId: string, parentId: string, counter: number): void {+ const layer = this.layers.get(layerId)+ const entries = new Map(layer?.entries)+ entries.set(parentId, counter)+ this.layers.set(layerId, { entries, orderKey: layer?.orderKey })+ this.noteCounter(counter)+ this.place(layerId, parentId)+ this.updateDisplaced(layerId)+ }++ /** Removes a layer; its children are placed again on the next `resolve`. */+ deleteLayer(layerId: string): void {+ if (!this.layers.delete(layerId)) return+ for (const childId of this.children.get(layerId) ?? []) this.pending.add(childId)+ this.children.delete(layerId)+ this.unplace(layerId)+ this.resolved.delete(layerId)+ this.displaced.delete(layerId)+ this.pending.delete(layerId)+ }++ /** Places every layer changed since the last call and returns the layers that moved. */+ resolve(): TreeMove[] {+ const work = new Set<string>()+ for (const id of this.pending) if (this.layers.has(id)) work.add(id)+ for (const id of this.displaced) work.add(id)+ this.pending.clear()++ const assignment = this.assign(work)+ const moves: TreeMove[] = []+ for (const [id, to] of assignment) {+ const from = this.resolved.get(id)+ if (from !== to || !this.resolved.has(id)) {+ this.place(id, to)+ moves.push({ layerId: id, from, to })+ }+ this.updateDisplaced(id)+ }+ return moves+ }++ /**+ * Starts every layer in `work` at its newest valid entry and drops the latest placement in each+ * loop until none is left. Layers outside `work` sit at their newest entry already, so a loop+ * always runs through a layer in `work`, and the outcome does not depend on visiting order.+ */+ private assign(work: Set<string>): Map<string, string | null> {+ const ranked = new Map<string, ParentEdge[]>()+ const choice = new Map<string, number>()+ const assigned = new Map<string, string | null>()+ const counters = new Map<string, number>()++ const assignOne = (id: string) => {+ const entries = this.layers.get(id)?.entries ?? new Map<string, number>()+ let edges = ranked.get(id)+ if (!edges) {+ edges = rankedEdges(entries).filter(+ (edge) => edge.parentId !== id && this.layers.has(edge.parentId)+ )+ ranked.set(id, edges)+ }+ const index = choice.get(id) ?? 0+ const edge = edges.at(index)+ if (edge) {+ assigned.set(id, edge.parentId)+ counters.set(id, edge.counter)+ } else if (entries.size === 0) {+ assigned.set(id, null)+ counters.set(id, -1)+ } else {+ // Past the orphan placement there is nowhere left; leave the layer out of the tree.+ assigned.set(id, index === edges.length ? this.options.orphanParentOf(id) : null)+ counters.set(id, -1)+ }+ }++ for (const id of work) assignOne(id)+ const parentOf = (id: string) => (assigned.has(id) ? assigned.get(id) : this.resolved.get(id))++ for (let loops = this.findLoops(work, parentOf); loops.length;) {+ for (const loop of loops) {+ for (const id of loop) {+ if (work.has(id)) continue+ work.add(id)+ assignOne(id)+ }+ const latest = loop.reduce((a, b) => (isLater(b, a, counters) ? b : a))+ choice.set(latest, (choice.get(latest) ?? 0) + 1)+ assignOne(latest)+ }+ loops = this.findLoops(work, parentOf)+ }+ return assigned+ }++ /** The loops the parents of `starts` run into, each listed once. */+ private findLoops(+ starts: Iterable<string>,+ parentOf: (id: string) => string | null | undefined+ ): string[][] {+ const state = new Map<string, number>()+ const loops: string[][] = []+ for (const start of starts) {+ const path: string[] = []+ let id: string | null | undefined = start+ while (id != null && !state.has(id) && this.layers.has(id)) {+ state.set(id, ON_PATH)+ path.push(id)+ id = parentOf(id)+ }+ if (id != null && state.get(id) === ON_PATH) loops.push(path.slice(path.indexOf(id)))+ for (const visited of path) state.set(visited, SETTLED)+ }+ return loops+ }++ private place(layerId: string, parentId: string | null): void {+ this.unplace(layerId)+ this.resolved.set(layerId, parentId)+ if (parentId === null) return+ let siblings = this.children.get(parentId)+ if (!siblings) {+ siblings = new Set()+ this.children.set(parentId, siblings)+ }+ siblings.add(layerId)+ }++ private unplace(layerId: string): void {+ const previous = this.resolved.get(layerId)+ if (previous != null) this.children.get(previous)?.delete(layerId)+ }++ private updateDisplaced(layerId: string): void {+ const entries = this.layers.get(layerId)?.entries+ const newest = entries ? (topEdge(entries)?.parentId ?? null) : null+ if (this.resolved.get(layerId) === newest) this.displaced.delete(layerId)+ else this.displaced.add(layerId)+ }++ private noteCounter(counter: number): void {+ if (counter > this.highestCounter) this.highestCounter = counter+ }+}++/** Whether `a`'s placement is later than `b`'s: higher counter, then higher layer id. */+function isLater(a: string, b: string, counters: ReadonlyMap<string, number>): boolean {+ const counterA = counters.get(a) ?? -1+ const counterB = counters.get(b) ?? -1+ return counterA === counterB ? a > b : counterA > counterB+}diff --git a/src/app/collab/types.ts b/src/app/collab/types.tsindex da716bdce..076cbfa38 100644--- a/src/app/collab/types.ts+++ b/src/app/collab/types.ts@@ -1,5 +1,6 @@import type { Color } from '@open-pencil/scene-graph/primitives'+import type { RoomStatus } from '@/app/collab/room/status'import type { AgentPresence, PersonPoint } from '@/app/presence/types'export interface RemotePeer {@@ -10,20 +11,31 @@ export interface RemotePeer {selection?: string[]/** Agents this person runs, as they publish them. */agents: AgentPresence[]+ /** The layer tree format the peer's build syncs, when it says. */+ treeFormat?: number+ /** Whether the peer has the room's file, so a newcomer can get it from them. */+ hasFile?: boolean}+/** The active tab's room, as the collaboration UI shows it. */export interface CollabState {- connected: boolean+ /** Whether the active tab is in a room. */+ inRoom: booleanroomId: string | null+ status: RoomStatus | nullpeers: RemotePeer[]localName: stringlocalColor: Color+ /** Whether the person has set their own name rather than joining as a generated one. */+ hasChosenName: boolean}export const DEFAULT_COLLAB_STATE: CollabState = {- connected: false,+ inRoom: false,roomId: null,+ status: null,peers: [],localName: '',- localColor: { r: 0.5, g: 0.5, b: 0.5, a: 1 }+ localColor: { r: 0.5, g: 0.5, b: 0.5, a: 1 },+ hasChosenName: false}diff --git a/src/app/collab/use.ts b/src/app/collab/use.tsindex 39ed8846c..5c201a739 100644--- a/src/app/collab/use.ts+++ b/src/app/collab/use.ts@@ -1,85 +1,90 @@-import { tryOnScopeDispose, useLocalStorage } from '@vueuse/core'-import { computed, ref } from 'vue'+import { computed } from 'vue'-import { generateRoomId } from '@/app/collab/awareness'-import { createLocalAwarenessActions } from '@/app/collab/local-awareness'+import { useCollabIdentity } from '@/app/collab/identity'import {- createCollabConnectionActions,- createCollabRuntime,- createInitialCollabState-} from '@/app/collab/session'+ activeRoom,+ activeTabLeftRoom,+ dismissLeftRoomNote,+ joinRoom,+ leaveRoom,+ shareDocument,+ type JoinRoomOptions+} from '@/app/collab/rooms'import { DEFAULT_COLLAB_STATE, type CollabState, type RemotePeer } from '@/app/collab/types'-import { createYjsGraphSync } from '@/app/collab/yjs-sync'-import type { EditorStore } from '@/app/editor/active-store'import { follow, presenceOf } from '@/app/presence/registry'import type { FollowTarget } from '@/app/presence/types'+import { activeTab } from '@/app/tabs'export { COLLAB_KEY, useCollabInjected } from '@/app/collab/context'export { DEFAULT_COLLAB_STATE }export type { CollabState, RemotePeer }-export function useCollab(storeOrGetter: EditorStore | (() => EditorStore)) {- const getStore = () =>- typeof storeOrGetter === 'function' ? (storeOrGetter as () => EditorStore)() : storeOrGetter- const storedName = useLocalStorage('op-collab-name', '')- const state = ref<CollabState>(createInitialCollabState(storedName.value))- const runtime = createCollabRuntime()- const remotePeers = computed(() => state.value.peers)- const getActiveStore = () => runtime.connectedStore.value ?? getStore()+/**+ * The collaboration UI's view of the active tab: its room, if it is in one, and the app-wide+ * identity. Each room tab keeps its own session in `src/app/collab/rooms.ts`; switching tabs+ * switches what this shows.+ */+export function useCollab() {+ const identity = useCollabIdentity()- const following = computed(() => presenceOf(getActiveStore()).following.value)- const followingPeer = computed(() =>- following.value?.kind === 'person' ? following.value.clientId : null- )- const { broadcastAwareness, updateCursor, updateSelection, updatePeersList, setLocalName } =- createLocalAwarenessActions({- state,- storedName,- getStore: getActiveStore,- getAwareness: () => runtime.awareness- })-- const { syncNodeToYjs, syncAllNodesToYjs, applyYjsToGraph } = createYjsGraphSync({- getStore: getActiveStore,- getYdoc: () => runtime.ydoc,- getYnodes: () => runtime.ynodes,- getYimages: () => runtime.yimages,- setSuppressYjsEvents: (value) => {- runtime.suppressYjsEvents = value+ const state = computed<CollabState>(() => {+ const room = activeRoom.value+ return {+ inRoom: room !== undefined,+ roomId: room?.roomId ?? null,+ status: room?.status.value ?? null,+ peers: room?.peers.value ?? [],+ localName: identity.name.value,+ localColor: identity.color,+ hasChosenName: identity.hasChosenName.value}})- const { connect, disconnect } = createCollabConnectionActions({- runtime,- state,- getStore,- updatePeersList,- broadcastAwareness,- applyYjsToGraph,- syncNodeToYjs+ const remotePeers = computed(() => state.value.peers)+ const leftRoom = computed(() => activeTabLeftRoom.value)+ const following = computed(() => {+ const store = activeTab.value?.store+ return store ? presenceOf(store).following.value : null})+ const followingPeer = computed(() =>+ following.value?.kind === 'person' ? following.value.clientId : null+ )- function shareCurrentDoc(): string {- const roomId = generateRoomId()- connect(roomId)- syncAllNodesToYjs()- return roomId+ function followTarget(target: FollowTarget | null) {+ const store = activeTab.value?.store+ if (store) follow(store, target)}- tryOnScopeDispose(disconnect)-return {state,remotePeers,- followingPeer,- connect,- disconnect,- shareCurrentDoc,- updateCursor,- updateSelection,- setLocalName,+ leftRoom,following,- follow: (target: FollowTarget | null) => follow(getActiveStore(), target),+ followingPeer,+ /** Opens a room in its own tab; false when the ID is not a room ID. */+ join: (roomId: string, options: JoinRoomOptions) => joinRoom(roomId, options) !== null,+ /** Puts the active tab's document into a room and returns the room ID. */+ shareCurrentDoc: (roomId?: string): string | null => {+ const store = activeTab.value?.store+ if (!store || activeTab.value?.kind === 'home') return null+ return shareDocument(store, roomId).roomId+ },+ disconnect: () => {+ const room = activeRoom.value+ if (room) leaveRoom(room)+ },+ updateCursor: (x: number, y: number, pageId: string) => {+ activeRoom.value?.updateCursor(x, y, pageId)+ },+ updateSelection: (ids: string[]) => {+ activeRoom.value?.updateSelection(ids)+ },+ dismissLeftRoomNote: () => {+ const store = activeTab.value?.store+ if (store) dismissLeftRoomNote(store)+ },+ setLocalName: identity.setName,+ follow: followTarget,followPeer: (clientId: number | null) =>- follow(getActiveStore(), clientId === null ? null : { kind: 'person', clientId })+ followTarget(clientId === null ? null : { kind: 'person', clientId })}}diff --git a/src/app/collab/yjs-sync.ts b/src/app/collab/yjs-sync.tsindex c1963d90e..56f3f95fa 100644--- a/src/app/collab/yjs-sync.ts+++ b/src/app/collab/yjs-sync.ts@@ -1,9 +1,33 @@import * as Y from 'yjs'+import type { SceneGraph } from '@open-pencil/scene-graph'+import { siblingOrderKeys } from '@open-pencil/scene-graph/order-keys'+import { decodeNodeFromYjs, syncEncodedNodeToYMap } from '@/app/collab/node-codec'+import {+ claimRoot,+ markTreeFormat,+ writeOrderKey,+ writePage,+ writeParentEntry,+ writeRootEntries,+ type YNodes+} from '@/app/collab/shared-tree/fields'+import { migrateLegacyLayers, TREE_MIGRATION_ORIGIN } from '@/app/collab/shared-tree/migration'+import {+ applySharedTree,+ createLocalEdit,+ createSharedTree,+ isLocalEditEmpty,+ keepSharedLayers,+ pageOf,+ recordLocalLayers,+ writeLocalPlacement,+ type LocalEdit,+ type SharedTree+} from '@/app/collab/shared-tree/sync'import type { EditorStore } from '@/app/editor/active-store'-type YNodes = Y.Map<Y.Map<unknown>>type YImages = Y.Map<Uint8Array>type GraphBindingOptions = {@@ -11,14 +35,13 @@ type GraphBindingOptions = {getYdoc: () => Y.Doc | nullgetYnodes: () => YNodes | nullgetSuppressGraphSync: () => boolean- setSuppressYjsEvents: (value: boolean) => void- syncNodeToYjs: (nodeId: string) => void+ syncLocalEdit: (edit: LocalEdit) => void}type YjsObserverOptions = {store: EditorStore- ynodes: Y.Map<Y.Map<unknown>>- yimages: Y.Map<Uint8Array>+ ynodes: YNodes+ yimages: YImagesgetSuppressYjsEvents: () => booleansetSuppressGraphSync: (value: boolean) => voidapplyYjsToGraph: (events: Y.YEvent<Y.Map<unknown>>[]) => void@@ -36,43 +59,66 @@ function logCollabSyncError(context: string, error: unknown) {console.error(`[Collab] ${context}:`, error)}+/**+ * Collects the graph events of one edit and syncs them once, after the edit, in one Yjs+ * transaction, so a move writes its parent entry and order key against the final layer order.+ */export function bindCollabGraphEvents({store,getYdoc,getYnodes,getSuppressGraphSync,- setSuppressYjsEvents,- syncNodeToYjs+ syncLocalEdit}: GraphBindingOptions) {- function onGraphMutation(nodeId: string) {- if (!getSuppressGraphSync() && getYdoc() && getYnodes()) {- syncNodeToYjs(nodeId)- }+ let edit = createLocalEdit()+ let bound = true++ function record(update: (pending: LocalEdit) => void) {+ if (getSuppressGraphSync() || !getYdoc() || !getYnodes()) return+ if (isLocalEditEmpty(edit)) queueMicrotask(flush)+ update(edit)+ }++ function flush() {+ const pending = edit+ edit = createLocalEdit()+ if (bound && getYdoc() && getYnodes()) syncLocalEdit(pending)}const unbinds = [- store.onEditorEvent('node:updated', (id) => onGraphMutation(id)),- store.onEditorEvent('node:created', (node) => onGraphMutation(node.id)),- store.onEditorEvent('node:reparented', (nodeId) => onGraphMutation(nodeId)),- store.onEditorEvent('node:reordered', (nodeId) => onGraphMutation(nodeId)),- store.onEditorEvent('node:deleted', (id) => {- const ydoc = getYdoc()- const ynodes = getYnodes()- if (!getSuppressGraphSync() && ydoc && ynodes) {- setSuppressYjsEvents(true)- try {- ydoc.transact(() => {- ynodes.delete(id)- })- } catch (error) {- logCollabSyncError('Failed to delete synced node', error)- } finally {- setSuppressYjsEvents(false)- }- }- })+ store.onEditorEvent('node:updated', (id, changes) =>+ record((pending) => {+ // A direct parentId write, as a checkpoint restore makes, syncs as a move when it+ // differs from the shared tree; a childIds write re-keys the children out of order.+ pending.changed.add(id)+ if ('childIds' in changes) pending.reordered.add(id)+ })+ ),+ store.onEditorEvent('node:created', (node) =>+ record((pending) => {+ pending.changed.add(node.id)+ pending.placed.add(node.id)+ })+ ),+ store.onEditorEvent('node:reparented', (nodeId, oldParentId) =>+ record((pending) => {+ pending.changed.add(nodeId)+ pending.placed.add(nodeId)+ if (oldParentId) pending.previousParents.add(oldParentId)+ })+ ),+ store.onEditorEvent('node:reordered', (nodeId, _parentId, _index, previousParentId) =>+ record((pending) => {+ pending.placed.add(nodeId)+ if (previousParentId) pending.previousParents.add(previousParentId)+ })+ ),+ store.onEditorEvent('node:deleted', (id) => record((pending) => pending.deleted.add(id)))]return () => {+ // An edit made just before leaving still reaches the room.+ if (!isLocalEditEmpty(edit)) flush()+ bound = falsefor (const unbind of unbinds) unbind()}}@@ -84,9 +130,10 @@ export function registerYjsObservers({getSuppressYjsEvents,setSuppressGraphSync,applyYjsToGraph-}: YjsObserverOptions) {- ynodes.observeDeep((events) => {- if (getSuppressYjsEvents()) return+}: YjsObserverOptions): () => void {+ function onNodes(events: Y.YEvent<Y.Map<unknown>>[], transaction: Y.Transaction) {+ // A migration this peer wrote was applied by the change that triggered it.+ if (getSuppressYjsEvents() || transaction.origin === TREE_MIGRATION_ORIGIN) returnsetSuppressGraphSync(true)try {applyYjsToGraph(events)@@ -96,9 +143,9 @@ export function registerYjsObservers({} finally {setSuppressGraphSync(false)}- })+ }- yimages.observe((event) => {+ function onImages(event: Y.YMapEvent<Uint8Array>) {if (getSuppressYjsEvents()) returntry {for (const [key, change] of event.changes.keys) {@@ -113,7 +160,14 @@ export function registerYjsObservers({} catch (error) {logCollabSyncError('Failed to apply remote image changes', error)}- })+ }++ ynodes.observeDeep(onNodes)+ yimages.observe(onImages)+ return () => {+ ynodes.unobserveDeep(onNodes)+ yimages.unobserve(onImages)+ }}export function createYjsGraphSync({@@ -124,69 +178,105 @@ export function createYjsGraphSync({setSuppressYjsEvents}: YjsGraphSyncOptions) {let pendingPageSwitch: { store: EditorStore; pageId: string } | undefined+ let shared: SharedTree | null = null- function syncNodeToYjs(nodeId: string) {- const store = getStore()- const ydoc = getYdoc()- const ynodes = getYnodes()- if (!ydoc || !ynodes) return- const node = store.graph.getNode(nodeId)+ function sharedTreeOf(ydoc: Y.Doc): SharedTree {+ if (shared?.ydoc !== ydoc) {+ shared = createSharedTree(ydoc, () => getStore().graph, getYnodes)+ }+ return shared+ }++ function writeNode(graph: SceneGraph, ynodes: YNodes, nodeId: string): void {+ const node = graph.getNode(nodeId)if (!node) return+ let ynode = ynodes.get(nodeId)+ if (!ynode) {+ ynode = new Y.Map()+ ynodes.set(nodeId, ynode)+ }+ syncEncodedNodeToYMap(node, ynode)const localYimages = getYimages()+ if (!localYimages) return+ for (const fill of node.fills) {+ if (fill.imageHash && !localYimages.has(fill.imageHash)) {+ const data = graph.images.get(fill.imageHash)+ if (data) localYimages.set(fill.imageHash, data)+ }+ }+ }++ /** Writes one local edit: changed layers' fields, deletions, and where layers now sit. */+ function syncLocalEdit(edit: LocalEdit) {+ const graph = getStore().graph+ const ydoc = getYdoc()+ const ynodes = getYnodes()+ if (!ydoc || !ynodes) return+ const tree = sharedTreeOf(ydoc)setSuppressYjsEvents(true)try {ydoc.transact(() => {- let ynode = ynodes.get(nodeId)- if (!ynode) {- ynode = new Y.Map()- ynodes.set(nodeId, ynode)- }- syncEncodedNodeToYMap(node, ynode)-- if (localYimages) {- for (const fill of node.fills) {- if (fill.imageHash && !localYimages.has(fill.imageHash)) {- const data = store.graph.images.get(fill.imageHash)- if (data) localYimages.set(fill.imageHash, data)- }+ for (const id of edit.deleted) {+ if (graph.getNode(id)) {+ // Deleted and restored within the edit, as an undo can.+ edit.changed.add(id)+ edit.placed.add(id)+ continue}+ ynodes.delete(id)+ tree.tree.deleteLayer(id)}+ keepSharedLayers(tree, graph, edit)+ for (const id of edit.changed) writeNode(graph, ynodes, id)+ for (const id of edit.placed) if (!ynodes.has(id)) writeNode(graph, ynodes, id)+ writeLocalPlacement(tree, graph, ynodes, ydoc.getMap('meta'), edit)})} catch (error) {- logCollabSyncError(`Failed to sync node ${nodeId}`, error)+ logCollabSyncError('Failed to sync local edit', error)} finally {setSuppressYjsEvents(false)}}+ function syncNodeToYjs(nodeId: string) {+ const edit = createLocalEdit()+ edit.changed.add(nodeId)+ syncLocalEdit(edit)+ }++ /**+ * Shares this peer's whole document, as Share does: every layer, its parent with counter 0, its+ * order, and its page, with its root as the room's.+ */function syncAllNodesToYjs() {- const store = getStore()+ const graph = getStore().graphconst ydoc = getYdoc()const ynodes = getYnodes()if (!ydoc || !ynodes) return- const localYimages = getYimages()setSuppressYjsEvents(true)try {ydoc.transact(() => {- for (const node of store.graph.getAllNodes()) {- let ynode = ynodes.get(node.id)- if (!ynode) {- ynode = new Y.Map()- ynodes.set(node.id, ynode)- }- syncEncodedNodeToYMap(node, ynode)+ for (const node of graph.getAllNodes()) writeNode(graph, ynodes, node.id)+ for (const node of graph.getAllNodes()) {+ const ynode = ynodes.get(node.id)+ if (!ynode) continue+ if (node.parentId === null) writeRootEntries(ynode)+ const pageId = pageOf(graph, node.id)+ if (pageId !== undefined) writePage(ynode, pageId)+ const children = node.childIds.filter((id) => graph.getNode(id)?.parentId === node.id)+ const keys = siblingOrderKeys(children.map(() => undefined))+ children.forEach((childId, index) => {+ const child = ynodes.get(childId)+ if (!child) return+ writeParentEntry(child, node.id, 0)+ writeOrderKey(child, keys[index])+ })}+ claimRoot(ydoc.getMap('meta'), graph.rootId)+ markTreeFormat(ydoc.getMap('meta'))})- if (localYimages) {- ydoc.transact(() => {- for (const [hash, data] of store.graph.images) {- if (!localYimages.has(hash)) {- localYimages.set(hash, data)- }- }- })- }+ recordLocalLayers(sharedTreeOf(ydoc), ynodes, ydoc.getMap('meta'), ynodes.keys())} catch (error) {logCollabSyncError('Failed to sync document', error)} finally {@@ -196,56 +286,46 @@ export function createYjsGraphSync({function applyYjsToGraph(events: Y.YEvent<Y.Map<unknown>>[]) {const store = getStore()+ const ydoc = getYdoc()const ynodes = getYnodes()- if (!ynodes) return+ if (!ydoc || !ynodes) return+ const changed = new Set<string>()+ const deleted = new Set<string>()for (const event of events) {if (event.target === ynodes) {for (const [key, change] of event.changes.keys) {- if (change.action === 'add') {- const ynode = ynodes.get(key)- if (ynode) applyYnodeToGraph(key, ynode)- } else if (change.action === 'delete') {- store.graph.deleteNode(key)- }- }- } else if (event.target.parent === ynodes) {- const nodeId = findNodeIdForYMap(event.target)- if (nodeId) {- const ynode = ynodes.get(nodeId)- if (ynode) applyYnodeToGraph(nodeId, ynode)+ if (change.action === 'delete') deleted.add(key)+ else changed.add(key)}+ continue}+ // The path from the nodes map starts with the layer's id, whether its own field changed+ // or an entry of its nested parents map did.+ const [nodeId] = event.path+ if (typeof nodeId === 'string') changed.add(nodeId)}- }- function findNodeIdForYMap(ymap: Y.Map<unknown>): string | null {- const ynodes = getYnodes()- if (!ynodes) return null- for (const [key, value] of ynodes.entries()) {- if (value === ymap) return key+ migrateLegacyLayers(ydoc, ynodes, ydoc.getMap('meta'), changed)+ for (const nodeId of changed) {+ const ynode = ynodes.get(nodeId)+ if (ynode) applyYnodeToGraph(store.graph, nodeId, ynode)}- return null+ const gone = [...deleted].filter((nodeId) => !ynodes.has(nodeId))+ // Moves go first, so a layer moved out of a deleted parent survives the deletion.+ applySharedTree(sharedTreeOf(ydoc), store.graph, ynodes, ydoc.getMap('meta'), changed, gone)+ for (const nodeId of gone) store.graph.deleteNode(nodeId)+ ensureCurrentPageExists(store)}- function applyYnodeToGraph(nodeId: string, ynode: Y.Map<unknown>) {- const store = getStore()- const existing = store.graph.getNode(nodeId)+ /** Applies a layer's own fields; `applySharedTree` places it in the tree afterwards. */+ function applyYnodeToGraph(graph: SceneGraph, nodeId: string, ynode: Y.Map<unknown>) {const props = decodeNodeFromYjs(ynode)- const parentId = typeof props.parentId === 'string' ? props.parentId : null-- if (existing) {- store.graph.updateNode(nodeId, props)- if (parentId === null) store.graph.rootId = nodeId- ensureCurrentPageExists(store)+ if (graph.getNode(nodeId)) {+ graph.updateNode(nodeId, props)return}-const type = props.type- if (!type) return- // Parent childIds may arrive before or after the child node.- store.graph.createNodeWithId(nodeId, type, parentId, props)- if (parentId === null) store.graph.rootId = nodeId- ensureCurrentPageExists(store)+ if (type) graph.createNodeWithId(nodeId, type, null, { ...props, childIds: [] })}function ensureCurrentPageExists(store: EditorStore) {@@ -267,5 +347,5 @@ export function createYjsGraphSync({})}- return { syncNodeToYjs, syncAllNodesToYjs, applyYjsToGraph }+ return { syncNodeToYjs, syncLocalEdit, syncAllNodesToYjs, applyYjsToGraph }}diff --git a/src/app/editor/canvas/collaboration-awareness.ts b/src/app/editor/canvas/collaboration-awareness.tsindex 4f8547d15..6bfa23539 100644--- a/src/app/editor/canvas/collaboration-awareness.ts+++ b/src/app/editor/canvas/collaboration-awareness.ts@@ -1,16 +1,27 @@-import type { useCollabInjected } from '@/app/collab/use'-import type { EditorStore } from '@/app/editor/active-store'+import { tryOnScopeDispose } from '@vueuse/core'-type Collaboration = ReturnType<typeof useCollabInjected>+import { roomForStore } from '@/app/collab/rooms'+import { getActiveEditorStore, type EditorStore } from '@/app/editor/active-store'++/**+ * Publishes a canvas's cursor and selection to the room its own tab is in, and no other.+ *+ * Canvases read the editor through a proxy that follows the active tab, which no room is keyed+ * by. Every canvas is keyed by its tab, so the tab's own store is the active one while it mounts.+ */+export function useCanvasCollaborationAwareness(store: EditorStore) {+ const tabStore = getActiveEditorStore()-export function useCanvasCollaborationAwareness(store: EditorStore, collab: Collaboration) {function updateCursor(cx: number, cy: number) {store.state.cursorCanvasX = cxstore.state.cursorCanvasY = cy- collab?.updateCursor(cx, cy, store.state.currentPageId)+ roomForStore(tabStore)?.updateCursor(cx, cy, tabStore.state.currentPageId)}- store.onEditorEvent('selection:changed', (ids) => collab?.updateSelection(ids))+ const stopSelection = tabStore.onEditorEvent('selection:changed', (ids) =>+ roomForStore(tabStore)?.updateSelection(ids)+ )+ tryOnScopeDispose(stopSelection)return { updateCursor }}diff --git a/src/app/editor/design-check/pages.ts b/src/app/editor/design-check/pages.tsindex c7d58b29b..662afe3a2 100644--- a/src/app/editor/design-check/pages.ts+++ b/src/app/editor/design-check/pages.ts@@ -24,10 +24,7 @@ export interface PageChecksOptions {/** The page holding a layer, or the page itself. */export function pageOf(graph: SceneGraph, nodeId: string | null | undefined): string | null {- let node = nodeId ? graph.getNode(nodeId) : undefined- while (node && node.type !== 'CANVAS')- node = node.parentId ? graph.getNode(node.parentId) : undefined- return node?.id ?? null+ return nodeId ? (graph.closest(nodeId, (node) => node.type === 'CANVAS')?.id ?? null) : null}/**diff --git a/src/app/presence/registry.ts b/src/app/presence/registry.tsindex 56309863d..33891bed6 100644--- a/src/app/presence/registry.ts+++ b/src/app/presence/registry.ts@@ -72,7 +72,8 @@ export interface PagePresenceEntry {color: Color}-function agentPage(agent: AgentPresence): string | undefined {+/** The page an agent is working on, or undefined while it is idle. */+export function agentPage(agent: AgentPresence): string | undefined {return agent.status === 'idle' ? undefined : (agent.pageId ?? agent.cursor?.pageId)}diff --git a/src/app/presence/schema.ts b/src/app/presence/schema.tsindex 419d39d2c..59836a12a 100644--- a/src/app/presence/schema.ts+++ b/src/app/presence/schema.ts@@ -41,6 +41,8 @@ const peerState = v.object({user: v.object({ name: lenient(name), color: lenient(color) }),cursor: lenient(personPoint),selection: lenient(selection),+ treeFormat: lenient(v.pipe(v.number(), v.integer(), v.minValue(1))),+ hasFile: lenient(v.boolean()),agents: v.fallback(v.optional(v.pipe(v.array(v.fallback(v.nullable(agent), null)), v.maxLength(MAX_AGENTS_PER_PEER))@@ -53,13 +55,15 @@ const peerState = v.object({export function parsePeer(clientId: number, state: unknown): RemotePeer | null {const result = v.safeParse(peerState, state)if (!result.success) return null- const { user, cursor, selection: selected, agents } = result.output+ const { user, cursor, selection: selected, agents, treeFormat, hasFile } = result.outputreturn {clientId,name: user.name ?? 'Anonymous',color: user.color ?? PEER_COLORS[clientId % PEER_COLORS.length],cursor,selection: selected,- agents: (agents ?? []).flatMap((entry) => (entry ? [entry] : []))+ agents: (agents ?? []).flatMap((entry) => (entry ? [entry] : [])),+ treeFormat,+ hasFile: hasFile === true}}diff --git a/src/boot.ts b/src/boot.tsindex 4e399c6a0..cbb1ce5fd 100644--- a/src/boot.ts+++ b/src/boot.ts@@ -1,6 +1,8 @@import { createHead } from '@unhead/vue/client'import { createApp, nextTick } from 'vue'+import { setIdSession } from '@open-pencil/scene-graph'+import { randomInt } from '@open-pencil/scene-graph/random'import { createRetainedScopePlugin } from '@open-pencil/vue'import './app.css'@@ -19,6 +21,8 @@ import router from './router'* evaluates the app bundle and can still show the gate's guidance.*/export async function boot(): Promise<void> {+ // A session of its own, so layers this window creates never share IDs with a collaborator's.+ setIdSession(randomInt() >>> 0)preloadFonts()const head = createHead()const app = createApp(App)diff --git a/src/components/EditorCanvas.vue b/src/components/EditorCanvas.vueindex 9b0aa93df..365bf44e1 100644--- a/src/components/EditorCanvas.vue+++ b/src/components/EditorCanvas.vue@@ -28,7 +28,6 @@ import {} from '@open-pencil/vue'import { useAIChat } from '@/app/ai/chat/use'-import { useCollabInjected } from '@/app/collab/use'import { useEditorStore } from '@/app/editor/active-store'import { useCanvasCollaborationAwareness } from '@/app/editor/canvas/collaboration-awareness'import { createCanvasContextSelection } from '@/app/editor/canvas/context-selection'@@ -51,7 +50,6 @@ const { paneId } = defineProps<{}>()const store = useEditorStore()-const collab = useCollabInjected()const sceneCanvasRef = ref<HTMLCanvasElement | null>(null)const canvasRef = ref<HTMLCanvasElement | null>(null)@@ -72,7 +70,7 @@ const onViewportResize = (width: number, height: number) => {if (isActivePane.value) store.setViewportSize(width, height)}-const { updateCursor } = useCanvasCollaborationAwareness(store, collab)+const { updateCursor } = useCanvasCollaborationAwareness(store)const { selectAtContextPoint } = createCanvasContextSelection(canvasRef, store)const shouldSuspendRender = () =>diff --git a/src/components/MobileHud/MobilePresencePopover.vue b/src/components/MobileHud/MobilePresencePopover.vueindex de88daba0..057eee5ba 100644--- a/src/components/MobileHud/MobilePresencePopover.vue+++ b/src/components/MobileHud/MobilePresencePopover.vue@@ -1,28 +1,25 @@<script setup lang="ts">import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'-import { colorToCSS } from '@open-pencil/scene-graph/color'--import { initials } from '@/app/shell/ui'import HudButton from '@/components/mobile-hud/HudButton.vue'import { useMobileHudContext } from '@/components/MobileHud/context'+import AvatarStack from '@/components/presence/AvatarStack.vue'+import PresenceList from '@/components/presence/PresenceList.vue'import AppButton from '@/components/ui/button/AppButton.vue'-import { avatar } from '@/theme/collaboration/avatar'import { presencePopover } from '@/theme/mobile/presence-popover'const hud = useMobileHudContext()const styles = presencePopover()--function peerAvatarClass(following: boolean) {- return avatar({ size: 'md', following, interactive: true })-}</script><template>- <PopoverRoot v-if="hud.collabState.connected">+ <PopoverRoot v-if="hud.collabState.inRoom"><PopoverTrigger as-child>- <HudButton :label="`Online: ${hud.onlineCount}`">- <template #leading><span :class="styles.dot()" /></template>+ <HudButton :label="hud.peopleLabel" data-test-id="mobile-presence" :class="styles.trigger()">+ <span :class="styles.summary()">+ <span :class="styles.dot()" :data-status="hud.collabState.status" />+ <AvatarStack :people="hud.people" :max="4" />+ </span></HudButton></PopoverTrigger><PopoverPortal>@@ -32,44 +29,17 @@ function peerAvatarClass(following: boolean) {side="bottom"align="center":class="styles.content()"+ @open-auto-focus.prevent>- <div class="mb-2 text-[11px] tracking-wider text-muted uppercase">- {{ hud.messages.inThisRoom }}- </div>- <div class="flex flex-col gap-2">- <div class="flex items-center gap-2">- <div- :class="avatar({ size: 'md' })"- :style="{ background: colorToCSS(hud.collabState.localColor) }"- >- {{ initials(hud.collabState.localName || 'You') }}- </div>- <span class="min-w-0 flex-1 truncate text-xs text-surface">- {{ hud.collabState.localName || 'You' }}- </span>- <span class="text-[10px] text-muted">{{ hud.common.youSuffix }}</span>- </div>-- <div- v-for="peer in hud.collabPeers"- :key="peer.clientId"- :data-following="hud.followingPeer === peer.clientId || undefined"- :class="styles.peerRow()"- @click="hud.toggleFollowPeer(peer.clientId)"- >- <div- :class="peerAvatarClass(hud.followingPeer === peer.clientId)"- :style="{ background: colorToCSS(peer.color) }"- >- {{ initials(peer.name) }}- </div>- <span class="min-w-0 flex-1 truncate text-xs text-surface">{{ peer.name }}</span>- <span v-if="hud.followingPeer === peer.clientId" class="text-[10px] text-accent">- following- </span>- </div>- </div>-+ <p class="mb-2 text-xs text-surface" data-test-id="mobile-room-status">+ {{ hud.statusText }}+ </p>+ <PresenceList+ :rows="hud.people"+ :following="hud.following"+ @follow="hud.follow"+ @rename="hud.renameAgent"+ /><AppButton variant="outline" class="mt-3 w-full" @click="hud.disconnect">{{ hud.messages.disconnect }}</AppButton>diff --git a/src/components/MobileHud/context.ts b/src/components/MobileHud/context.tsindex a03cfa317..7211e5637 100644--- a/src/components/MobileHud/context.ts+++ b/src/components/MobileHud/context.ts@@ -1,7 +1,6 @@import { useClipboard } from '@vueuse/core'import { computed, inject, provide, proxyRefs } from 'vue'import type { InjectionKey, ShallowUnwrapRef } from 'vue'-import { useRouter } from 'vue-router'import IconFilePlus from '~icons/lucide/file-plus'import IconFolderOpen from '~icons/lucide/folder-open'import IconImageDown from '~icons/lucide/image-down'@@ -11,18 +10,21 @@ import IconZoomIn from '~icons/lucide/zoom-in'import { useEditorCommands, useI18n } from '@open-pencil/vue'import { DEFAULT_COLLAB_STATE, useCollabInjected } from '@/app/collab/use'-import { useEditorStore } from '@/app/editor/active-store'+import { useActiveEditorStoreRef, useEditorStore } from '@/app/editor/active-store'import { toolIcons } from '@/app/editor/icons'import { useNotificationMessages } from '@/app/i18n/notifications'+import { presenceOf, renameAgent as renameLocalAgent } from '@/app/presence/registry'+import type { FollowTarget } from '@/app/presence/types'import { openFileDialog } from '@/app/shell/menu/use'import { toast } from '@/app/shell/ui'+import { roomStatusText } from '@/components/collab-room/statusText'+import { presenceRows } from '@/components/presence/rows'import type { ToolbarActionItem } from '@/components/Toolbar/types'import { getShareURL } from '@/constants'type MenuAction = ToolbarActionItemfunction createMobileHudContext() {- const router = useRouter()const collab = useCollabInjected()const store = useEditorStore()const { copy } = useClipboard()@@ -32,8 +34,26 @@ function createMobileHudContext() {const collabState = computed(() => collab?.state.value ?? DEFAULT_COLLAB_STATE)const collabPeers = computed(() => collab?.remotePeers.value ?? [])- const followingPeer = computed(() => collab?.followingPeer.value ?? null)- const onlineCount = computed(() => collabPeers.value.length + 1)+ const following = computed(() => collab?.following.value ?? null)+ // The active tab's own store: presence is kept per store, and the editor proxy is not one.+ const tabStore = useActiveEditorStoreRef()+ /** You first, then everyone else in the room, each with the agents they run. */+ const people = computed(() => {+ const own = tabStore.value+ return presenceRows(+ {+ name: collabState.value.localName,+ color: collabState.value.localColor,+ agents: own ? presenceOf(own).agents.value : []+ },+ collabPeers.value,+ (pageId) => own?.graph.getNode(pageId)?.name+ )+ })+ const peopleLabel = computed(+ () =>+ `${collaboration.value.inThisRoom}: ${people.value.map((person) => person.name || common.value.you).join(', ')}`+ )const activeToolIcon = computed(() => toolIcons[store.state.activeTool])const actionToast = computed(() => store.state.actionToast)@@ -57,22 +77,31 @@ function createMobileHudContext() {getCommand('edit.redo').run()}+ const statusText = computed(() =>+ collabState.value.status+ ? roomStatusText(collaboration.value, collabState.value.status, collabPeers.value.length)+ : ''+ )++ /** Copies the room's link; a tab not in a room is shared first, never a room it opened. */function share() {if (!collab) return- const roomId = collab.shareCurrentDoc()- void router.push(`/share/${roomId}`)+ const roomId = collabState.value.roomId ?? collab.shareCurrentDoc()+ if (!roomId) returnvoid copy(getShareURL(roomId))toast.info(notifications.value.linkCopied)}function disconnect() {- if (!collab) return- collab.disconnect()- void router.push('/')+ collab?.disconnect()+ }++ function follow(target: FollowTarget | null) {+ collab?.follow(target)}- function toggleFollowPeer(clientId: number) {- collab?.followPeer(followingPeer.value === clientId ? null : clientId)+ function renameAgent(agentId: string, name: string) {+ if (tabStore.value) renameLocalAgent(tabStore.value, agentId, name)}return {@@ -80,9 +109,10 @@ function createMobileHudContext() {common,messages: collaboration,collabState,- collabPeers,- followingPeer,- onlineCount,+ people,+ peopleLabel,+ following,+ statusText,activeToolIcon,actionToast,menuItems,@@ -90,7 +120,8 @@ function createMobileHudContext() {redo,share,disconnect,- toggleFollowPeer+ follow,+ renameAgent}}diff --git a/src/components/PagesPanel.vue b/src/components/PagesPanel.vueindex f3869f63e..409d3005a 100644--- a/src/components/PagesPanel.vue+++ b/src/components/PagesPanel.vue@@ -17,6 +17,7 @@ import { useActiveEditorStoreRef } from '@/app/editor/active-store'import { presenceByPage } from '@/app/presence/registry'import { appPreferences } from '@/app/settings/preferences/store'import PageIssueBadge from '@/components/design-check/PageIssueBadge.vue'+import PagePresenceHover from '@/components/presence/PagePresenceHover.vue'import PresenceMarkers from '@/components/presence/PresenceMarkers.vue'import IconButton from '@/components/ui/button/IconButton.vue'import { useMenuUI } from '@/components/ui/menu/menu'@@ -149,20 +150,21 @@ function setupPageRowRef(><div :class="pageStyles(pg, currentPageId).dividerLine()" /></div>- <button- v-else- data-test-id="pages-item"- :class="pageStyles(pg, currentPageId).item()"- @click="actions.switch(pg.id)"- @dblclick="startRename(pg, actions.rename)"- >- <icon-lucide-file :class="pageStyles(pg, currentPageId).icon()" />- <span :class="pageStyles(pg, currentPageId).label()">{{ pg.name }}</span>- <span :class="pageStyles(pg, currentPageId).trailing()">- <PresenceMarkers :entries="pagePresence.get(pg.id) ?? []" />- <PageIssueBadge :counts="pageIssues(pg.id)" />- </span>- </button>+ <PagePresenceHover v-else :page-id="pg.id">+ <button+ data-test-id="pages-item"+ :class="pageStyles(pg, currentPageId).item()"+ @click="actions.switch(pg.id)"+ @dblclick="startRename(pg, actions.rename)"+ >+ <icon-lucide-file :class="pageStyles(pg, currentPageId).icon()" />+ <span :class="pageStyles(pg, currentPageId).label()">{{ pg.name }}</span>+ <span :class="pageStyles(pg, currentPageId).trailing()">+ <PresenceMarkers :entries="pagePresence.get(pg.id) ?? []" />+ <PageIssueBadge :counts="pageIssues(pg.id)" />+ </span>+ </button>+ </PagePresenceHover><divv-if="pageDropPosition(pg) === 'after'"data-test-id="pages-drop-indicator"diff --git a/src/components/collab-panel/CollabAvatarStack.vue b/src/components/collab-panel/CollabAvatarStack.vueindex da3c03954..32dc65cfd 100644--- a/src/components/collab-panel/CollabAvatarStack.vue+++ b/src/components/collab-panel/CollabAvatarStack.vue@@ -10,7 +10,8 @@ const collab = useCollabPanelContext()<PresenceAvatars:rows="collab.presenceRows":following="collab.following"- :connected="collab.state.connected"+ :connected="collab.state.status === 'live'"+ :in-room="collab.state.inRoom"@follow="collab.follow"@rename="collab.renameLocalAgent"@leave="collab.disconnect"diff --git a/src/components/collab-panel/CollabSharePopover.vue b/src/components/collab-panel/CollabSharePopover.vueindex 4ae581aa3..93f5f261c 100644--- a/src/components/collab-panel/CollabSharePopover.vue+++ b/src/components/collab-panel/CollabSharePopover.vue@@ -2,9 +2,9 @@import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'import { computed } from 'vue'+import { showsRoomDocument } from '@/app/collab/room/status'import ConnectedRoom from '@/components/collab-panel/ConnectedRoom.vue'import { useCollabPanelContext } from '@/components/collab-panel/context'-import JoinRoomPrompt from '@/components/collab-panel/JoinRoomPrompt.vue'import ShareOrJoinRoom from '@/components/collab-panel/ShareOrJoinRoom.vue'import { usePopoverUI } from '@/components/ui/overlay/popover'import { shareButton } from '@/theme/collaboration/share-button'@@ -12,9 +12,9 @@ import { shareButton } from '@/theme/collaboration/share-button'const collab = useCollabPanelContext()const cls = usePopoverUI({ content: 'z-50 w-72 p-3' })const connection = computed(() => {- if (collab.state.connected) return 'connected'- if (collab.isJoining) return 'joining'- return 'idle'+ const status = collab.state.status+ if (!status) return 'idle'+ return showsRoomDocument(status) ? 'connected' : 'joining'})</script>@@ -27,7 +27,7 @@ const connection = computed(() => {:class="shareButton({ connection })"><icon-lucide-share-2 class="size-3.5" />- {{ collab.isJoining ? collab.messages.joinRoom : collab.messages.share }}+ {{ collab.messages.share }}</button></PopoverTrigger>@@ -38,9 +38,9 @@ const connection = computed(() => {:side-offset="8"side="bottom"align="end"+ @open-auto-focus.prevent>- <ConnectedRoom v-if="collab.state.connected" />- <JoinRoomPrompt v-else-if="collab.isJoining" />+ <ConnectedRoom v-if="collab.state.inRoom" /><ShareOrJoinRoom v-else /></PopoverContent></PopoverPortal>diff --git a/src/components/collab-panel/ConnectedRoom.vue b/src/components/collab-panel/ConnectedRoom.vueindex e8a2f7ac7..f8a22d087 100644--- a/src/components/collab-panel/ConnectedRoom.vue+++ b/src/components/collab-panel/ConnectedRoom.vue@@ -1,19 +1,36 @@<script setup lang="ts">+import { computed } from 'vue'+import { selectTarget } from '@open-pencil/vue'import { useCollabPanelContext } from '@/components/collab-panel/context'+import { roomStatusText } from '@/components/collab-room/statusText'+import { useRoomActions } from '@/components/collab-room/useRoomActions'import AppButton from '@/components/ui/button/AppButton.vue'import AppInput from '@/components/ui/input/AppInput.vue'+import { roomStatus } from '@/theme/collaboration/room-status'const collab = useCollabPanelContext()+const room = useRoomActions()+const ui = roomStatus()++const statusText = computed(() =>+ roomStatusText(collab.messages, collab.state.status ?? 'connecting', collab.state.peers.length)+)</script><template>- <div class="mb-3 text-xs font-medium text-surface">{{ collab.messages.roomLink }}</div>- <div class="flex items-center gap-1.5">+ <p :class="ui.root()" :data-status="collab.state.status" data-test-id="collab-room-status">+ <span :class="ui.dot()" aria-hidden="true" />+ {{ statusText }}+ </p>++ <div class="mb-1.5 text-xs font-medium text-surface">{{ collab.messages.roomLink }}</div>+ <div class="mb-3 flex items-center gap-1.5"><AppInput:model-value="collab.shareURL"readonly+ :aria-label="collab.messages.roomLink"data-test-id="collab-room-link"class="min-w-0 flex-1"@focus="selectTarget($event)"@@ -28,7 +45,55 @@ const collab = useCollabPanelContext()<icon-lucide-check v-if="collab.copied" class="size-3" /><icon-lucide-copy v-else class="size-3" /></template>- {{ collab.copied ? 'Copied' : 'Copy' }}+ {{ collab.copied ? collab.messages.linkCopied : collab.messages.copyLink }}+ </AppButton>+ </div>++ <label for="collab-room-name-input" class="mb-1 block text-xs text-muted">+ {{ collab.messages.yourName }}+ </label>+ <AppInput+ id="collab-room-name-input"+ v-model="collab.nameDraft"+ data-test-id="collab-name-input"+ :placeholder="collab.state.localName"+ @enter="collab.saveName"+ @change="collab.saveName"+ />++ <div class="mt-3 flex items-center justify-between gap-2 border-t border-border pt-3">+ <p+ v-if="room.desktopLink.value"+ class="flex shrink-0 items-center gap-1.5 text-[11px] whitespace-nowrap text-muted"+ >+ <a+ :href="room.desktopLink.value"+ class="text-accent underline-offset-2 hover:underline focus-visible:underline focus-visible:outline-none"+ data-test-id="collab-open-desktop"+ >+ {{ collab.messages.openInDesktopApp }}+ </a>+ <template v-if="room.downloadURL.value">+ <span aria-hidden="true">·</span>+ <a+ :href="room.downloadURL.value"+ target="_blank"+ rel="noopener noreferrer"+ class="text-accent underline-offset-2 hover:underline focus-visible:underline focus-visible:outline-none"+ data-test-id="collab-download-desktop"+ >+ {{ collab.messages.downloadDesktopApp }}+ </a>+ </template>+ </p>+ <span v-else />+ <AppButton+ color="neutral"+ variant="ghost"+ data-test-id="collab-leave"+ @click="collab.disconnect"+ >+ {{ collab.messages.leaveRoom }}</AppButton></div></template>diff --git a/src/components/collab-panel/JoinRoomPrompt.vue b/src/components/collab-panel/JoinRoomPrompt.vuedeleted file mode 100644index 2e5cbc168..000000000--- a/src/components/collab-panel/JoinRoomPrompt.vue+++ /dev/null@@ -1,38 +0,0 @@-<script setup lang="ts">-import { useCollabPanelContext } from '@/components/collab-panel/context'-import AppButton from '@/components/ui/button/AppButton.vue'-import AppInput from '@/components/ui/input/AppInput.vue'--const collab = useCollabPanelContext()-</script>--<template>- <div class="mb-1 text-xs font-medium text-surface">{{ collab.messages.joinCollaboration }}</div>- <div class="mb-3 text-[11px] text-muted">- Someone shared this file with you. Enter your name to join.- </div>-- <div class="mb-3">- <label class="mb-1 block text-xs text-muted">{{ collab.messages.yourName }}</label>- <AppInput- v-model="collab.nameDraft"- data-test-id="collab-name-input"- :placeholder="collab.messages.enterYourName"- autofocus- @enter="collab.join"- />- </div>-- <AppButton- size="md"- color="primary"- variant="solid"- class="w-full"- data-test-id="collab-join-button"- :disabled="!collab.nameDraft.trim()"- @click="collab.join"- >- <template #leading><icon-lucide-users class="size-3.5" /></template>- Join room- </AppButton>-</template>diff --git a/src/components/collab-panel/PresenceAvatars.stories.ts b/src/components/collab-panel/PresenceAvatars.stories.tsindex 07e6667b3..58a1eb2a7 100644--- a/src/components/collab-panel/PresenceAvatars.stories.ts+++ b/src/components/collab-panel/PresenceAvatars.stories.ts@@ -2,9 +2,9 @@ import type { Meta, StoryObj } from '@storybook/vue3-vite'import { expect, fn, userEvent, within } from 'storybook/test'import type { FollowTarget } from '@/app/presence/types'+import { colors, room } from '@/components/presence/examples/room'+import type { PresencePersonRow } from '@/components/presence/rows'-import { colors, room } from './examples/room'-import type { PresencePersonRow } from './presence'import PresenceAvatars from './PresenceAvatars.vue'const crowd: PresencePersonRow[] = [@@ -14,7 +14,12 @@ const crowd: PresencePersonRow[] = [{ clientId: 6, name: 'Fay', color: colors.ana, agents: [] }]-type Args = { rows: PresencePersonRow[]; following: FollowTarget | null; connected: boolean }+type Args = {+ rows: PresencePersonRow[]+ following: FollowTarget | null+ connected: boolean+ inRoom: boolean+}const meta = {title: 'Collaboration/Presence Avatars',@@ -24,6 +29,7 @@ const meta = {rows: room,following: null,connected: true,+ inRoom: true,onFollow: fn(),onRename: fn(),onLeave: fn()@@ -60,5 +66,5 @@ export const ManyPeople: Story = {}export const Alone: Story = {- args: { rows: room.slice(0, 1), connected: false }+ args: { rows: room.slice(0, 1), connected: false, inRoom: false }}diff --git a/src/components/collab-panel/PresenceAvatars.vue b/src/components/collab-panel/PresenceAvatars.vueindex df0f224e5..f282ca398 100644--- a/src/components/collab-panel/PresenceAvatars.vue+++ b/src/components/collab-panel/PresenceAvatars.vue@@ -9,32 +9,33 @@ import {PopoverRoot,PopoverTrigger} from 'reka-ui'-import { computed } from 'vue'-import { colorToCSS } from '@open-pencil/scene-graph/color'import { useI18n } from '@open-pencil/vue'import type { FollowTarget } from '@/app/presence/types'-import { initials } from '@/app/shell/ui'+import AvatarStack from '@/components/presence/AvatarStack.vue'+import PersonAvatar from '@/components/presence/PersonAvatar.vue'+import PresenceList from '@/components/presence/PresenceList.vue'+import { isFollowing, type PresencePersonRow } from '@/components/presence/rows'import AppButton from '@/components/ui/button/AppButton.vue'-import { avatar } from '@/theme/collaboration/avatar'import { presenceAvatars } from '@/theme/collaboration/presence-avatars'-import { isFollowing, type PresencePersonRow } from './presence'-import PresenceList from './PresenceList.vue'--/** How many collaborators the stack shows before "+N". */+/** How many collaborators the stack shows besides you before "+N". */const MAX_PEERS = 3const {rows,following,- connected = false+ connected = false,+ inRoom = false} = defineProps<{/** Ourselves first, then everyone else in the room. */rows: PresencePersonRow[]following: FollowTarget | null+ /** Whether someone else in the room answered, so the room is live. */connected?: boolean+ /** Whether we are in a room at all, so we can leave it. */+ inRoom?: boolean}>()const emit = defineEmits<{@@ -46,10 +47,6 @@ const emit = defineEmits<{const { common, collaboration: messages } = useI18n()const ui = presenceAvatars()-const self = computed(() => rows[0])-const peers = computed(() => rows.slice(1, MAX_PEERS + 1))-const hidden = computed(() => Math.max(0, rows.length - 1 - MAX_PEERS))-function personTarget(clientId: number): FollowTarget {return { kind: 'person', clientId }}@@ -61,136 +58,124 @@ function toggleFollow(clientId: number) {</script><template>- <div data-test-id="collab-avatars" :class="ui.root()">- <PopoverRoot v-if="self">- <PopoverTrigger as-child>- <button- type="button"- data-test-id="collab-local-avatar"- :aria-label="`${self.name || common.you} (${common.youSuffix})`"- :class="ui.trigger()"- >- <span- :class="avatar({ bordered: true, interactive: true })"- :style="{ background: colorToCSS(self.color) }"- >- {{ initials(self.name || common.you) }}- </span>- <span- v-if="connected"- data-test-id="collab-live"- role="img"- :aria-label="messages.connected"- :class="ui.live()"- />- <span- v-if="self.agents.length > 0"- :class="ui.badge()"- :style="{ color: colorToCSS(self.color) }"+ <AvatarStack data-test-id="collab-avatars" :people="rows" :max="MAX_PEERS + 1">+ <template #person="{ person }">+ <PopoverRoot v-if="person.clientId === undefined">+ <PopoverTrigger as-child>+ <button+ type="button"+ data-test-id="collab-local-avatar"+ :aria-label="`${person.name || common.you} (${common.youSuffix})`"+ :class="ui.trigger()">- <icon-lucide-sparkle :class="ui.badgeIcon()" />{{ self.agents.length }}- </span>- </button>- </PopoverTrigger>- <PopoverPortal>- <PopoverContent- data-test-id="collab-self-menu"- :class="ui.card()"- :side-offset="8"- align="end"- >- <PresenceList- :rows="[self]"- :following="following"- @follow="emit('follow', $event)"- @rename="(id, name) => emit('rename', id, name)"- />- <AppButton- v-if="connected"- variant="outline"- :class="ui.leave()"- data-test-id="collab-leave-room"- @click="emit('leave')"+ <PersonAvatar+ :name="person.name || common.you"+ :color="person.color"+ :agent-count="person.agents.length"+ interactive+ />+ <span+ v-if="connected"+ data-test-id="collab-live"+ role="img"+ :aria-label="messages.connected"+ :class="ui.live()"+ />+ </button>+ </PopoverTrigger>+ <PopoverPortal>+ <PopoverContent+ data-test-id="collab-self-menu"+ :class="ui.card()"+ :side-offset="8"+ align="end">- {{ messages.leaveRoom }}- </AppButton>- </PopoverContent>- </PopoverPortal>- </PopoverRoot>+ <PresenceList+ :rows="[person]"+ :following="following"+ @follow="emit('follow', $event)"+ @rename="(id, name) => emit('rename', id, name)"+ />+ <AppButton+ v-if="inRoom"+ variant="outline"+ :class="ui.leave()"+ data-test-id="collab-leave-room"+ @click="emit('leave')"+ >+ {{ messages.leaveRoom }}+ </AppButton>+ </PopoverContent>+ </PopoverPortal>+ </PopoverRoot>- <HoverCardRoot v-for="peer in peers" :key="peer.clientId" :open-delay="250" :close-delay="150">- <HoverCardTrigger as-child>- <button- v-if="peer.clientId !== undefined"- type="button"- data-test-id="collab-peer-avatar"- :data-following="isFollowing(following, personTarget(peer.clientId)) || undefined"- :aria-label="- isFollowing(following, personTarget(peer.clientId))- ? messages.stopFollowing({ name: peer.name })- : messages.follow({ name: peer.name })- "- :class="ui.trigger()"- @click="toggleFollow(peer.clientId)"- >- <span- :class="- avatar({- bordered: true,- interactive: true,- following: isFollowing(following, personTarget(peer.clientId))- })+ <HoverCardRoot v-else :open-delay="250" :close-delay="150">+ <HoverCardTrigger as-child>+ <button+ type="button"+ data-test-id="collab-peer-avatar"+ :data-following="isFollowing(following, personTarget(person.clientId)) || undefined"+ :aria-label="+ isFollowing(following, personTarget(person.clientId))+ ? messages.stopFollowing({ name: person.name })+ : messages.follow({ name: person.name })"- :style="{ background: colorToCSS(peer.color) }"+ :class="ui.trigger()"+ @click="toggleFollow(person.clientId)">- {{ initials(peer.name) }}- </span>- <span- v-if="peer.agents.length > 0"- :class="ui.badge()"- :style="{ color: colorToCSS(peer.color) }"+ <PersonAvatar+ :name="person.name"+ :color="person.color"+ :agent-count="person.agents.length"+ :following="isFollowing(following, personTarget(person.clientId))"+ interactive+ />+ </button>+ </HoverCardTrigger>+ <HoverCardPortal>+ <HoverCardContent+ data-test-id="collab-peer-card"+ :class="ui.card()"+ :side-offset="8"+ align="end">- <icon-lucide-sparkle :class="ui.badgeIcon()" />{{ peer.agents.length }}- </span>- </button>- </HoverCardTrigger>- <HoverCardPortal>- <HoverCardContent- data-test-id="collab-peer-card"- :class="ui.card()"- :side-offset="8"- align="end"- >- <PresenceList :rows="[peer]" :following="following" @follow="emit('follow', $event)" />- </HoverCardContent>- </HoverCardPortal>- </HoverCardRoot>+ <PresenceList+ :rows="[person]"+ :following="following"+ @follow="emit('follow', $event)"+ />+ </HoverCardContent>+ </HoverCardPortal>+ </HoverCardRoot>+ </template><!-- Everyone, by click or keyboard: hover cards are mouse-only. -->- <PopoverRoot v-if="rows.length > 1">- <PopoverTrigger as-child>- <button- type="button"- data-test-id="collab-everyone"- :aria-label="- hidden > 0 ? messages.morePeople({ count: String(hidden) }) : messages.inThisRoom- "- :class="ui.overflow()"- >- <template v-if="hidden > 0">+{{ hidden }}</template>- <icon-lucide-chevron-down v-else :class="ui.badgeIcon()" />- </button>- </PopoverTrigger>- <PopoverPortal>- <PopoverContent :class="ui.card()" :side-offset="8" align="end">- <PresenceList- :rows="rows"- :following="following"- @follow="emit('follow', $event)"- @rename="(id, name) => emit('rename', id, name)"- />- </PopoverContent>- </PopoverPortal>- </PopoverRoot>- </div>+ <template #overflow="{ hidden }">+ <PopoverRoot v-if="rows.length > 1">+ <PopoverTrigger as-child>+ <button+ type="button"+ data-test-id="collab-everyone"+ :aria-label="+ hidden > 0 ? messages.morePeople({ count: String(hidden) }) : messages.inThisRoom+ "+ :class="ui.overflow()"+ >+ <template v-if="hidden > 0">+{{ hidden }}</template>+ <icon-lucide-chevron-down v-else :class="ui.chevron()" />+ </button>+ </PopoverTrigger>+ <PopoverPortal>+ <PopoverContent :class="ui.card()" :side-offset="8" align="end">+ <PresenceList+ :rows="rows"+ :following="following"+ @follow="emit('follow', $event)"+ @rename="(id, name) => emit('rename', id, name)"+ />+ </PopoverContent>+ </PopoverPortal>+ </PopoverRoot>+ </template>+ </AvatarStack></template>diff --git a/src/components/collab-panel/ShareOrJoinRoom.vue b/src/components/collab-panel/ShareOrJoinRoom.vueindex 6d6c191ab..989cd6288 100644--- a/src/components/collab-panel/ShareOrJoinRoom.vue+++ b/src/components/collab-panel/ShareOrJoinRoom.vue@@ -4,15 +4,19 @@ import AppButton from '@/components/ui/button/AppButton.vue'import AppInput from '@/components/ui/input/AppInput.vue'const collab = useCollabPanelContext()+const JOIN_ERROR_ID = 'collab-join-error'</script><template><div class="mb-3">- <label class="mb-1 block text-xs text-muted">{{ collab.messages.yourName }}</label>+ <label for="collab-name-input" class="mb-1 block text-xs text-muted">+ {{ collab.messages.yourName }}+ </label><AppInput+ id="collab-name-input"v-model="collab.nameDraft"data-test-id="collab-name-input"- :placeholder="collab.messages.enterYourName"+ :placeholder="collab.state.localName"@enter="collab.share"/></div>@@ -23,7 +27,6 @@ const collab = useCollabPanelContext()variant="solid"class="mb-3 w-full"data-test-id="collab-share-file"- :disabled="!collab.nameDraft.trim()"@click="collab.share"><template #leading><icon-lucide-share-2 class="size-3.5" /></template>@@ -41,17 +44,31 @@ const collab = useCollabPanelContext()v-model="collab.joinInput"data-test-id="collab-join-input":placeholder="collab.messages.pasteRoomLinkOrId"+ :aria-label="collab.messages.pasteRoomLinkOrId"+ :state="collab.joinError ? 'invalid' : 'idle'"+ :aria-invalid="collab.joinError"+ :aria-describedby="collab.joinError ? JOIN_ERROR_ID : undefined"class="min-w-0 flex-1"+ @update:model-value="collab.clearJoinError"@enter="collab.join"/><AppButtoncolor="primary"variant="solid"data-test-id="collab-join-room-button"- :disabled="!collab.joinInput.trim() || !collab.nameDraft.trim()"+ :disabled="!collab.joinInput.trim()"@click="collab.join">- Join+ {{ collab.messages.join }}</AppButton></div>+ <p+ v-if="collab.joinError"+ :id="JOIN_ERROR_ID"+ data-test-id="collab-join-error"+ class="mt-1.5 text-xs text-error"+ role="alert"+ >+ {{ collab.messages.invalidRoomLink }}+ </p></template>diff --git a/src/components/collab-panel/context.ts b/src/components/collab-panel/context.tsindex 74d693043..e4c638237 100644--- a/src/components/collab-panel/context.ts+++ b/src/components/collab-panel/context.ts@@ -1,35 +1,40 @@import { useClipboard } from '@vueuse/core'import { computed, inject, provide, proxyRefs, ref, watch } from 'vue'import type { InjectionKey, ShallowUnwrapRef } from 'vue'-import { useRoute, useRouter } from 'vue-router'import { useI18n } from '@open-pencil/vue'+import { useJoinRoom } from '@/app/collab/join'import { DEFAULT_COLLAB_STATE, useCollabInjected } from '@/app/collab/use'import { useActiveEditorStoreRef } from '@/app/editor/active-store'import { useNotificationMessages } from '@/app/i18n/notifications'import { presenceOf, renameAgent } from '@/app/presence/registry'import type { FollowTarget } from '@/app/presence/types'import { toast } from '@/app/shell/ui'+import { presenceRows as buildPresenceRows } from '@/components/presence/rows'import { getShareURL } from '@/constants'-import { presenceRows as buildPresenceRows } from './presence'-function createCollabPanelContext() {- const route = useRoute()- const router = useRouter()const collab = useCollabInjected()+ const joinRoomFromInput = useJoinRoom()const { copy, copied } = useClipboard({ copiedDuring: 2000 })const { common, collaboration } = useI18n()const notifications = useNotificationMessages()+ const state = computed(() => collab?.state.value ?? DEFAULT_COLLAB_STATE)const joinInput = ref('')- const nameDraft = ref(collab?.state.value.localName ?? '')- const pendingRoomId = computed(() =>- typeof route.params.roomId === 'string' ? route.params.roomId : null+ const joinError = ref(false)+ const nameDraft = ref('')+ const popoverOpen = ref(false)+ // Each time the panel opens it shows the current name, or stays empty while the person has+ // none of their own, so the field shows the generated one as its placeholder.+ watch(+ popoverOpen,+ (open) => {+ if (open) nameDraft.value = state.value.hasChosenName ? state.value.localName : ''+ },+ { immediate: true })- const popoverOpen = ref(!!pendingRoomId.value)- const state = computed(() => collab?.state.value ?? DEFAULT_COLLAB_STATE)const peers = computed(() => collab?.remotePeers.value ?? [])const following = computed(() => collab?.following.value ?? null)const storeRef = useActiveEditorStoreRef()@@ -45,19 +50,7 @@ function createCollabPanelContext() {(pageId) => store?.graph.getNode(pageId)?.name)})- const shareURL = computed(() => {- if (!state.value.roomId) return ''- return getShareURL(state.value.roomId)- })- const isJoining = computed(() => !!pendingRoomId.value && !state.value.connected)-- watch(- pendingRoomId,- (roomId) => {- if (!state.value.connected) popoverOpen.value = !!roomId- },- { immediate: true }- )+ const shareURL = computed(() => (state.value.roomId ? getShareURL(state.value.roomId) : ''))function copyLink() {if (!shareURL.value) return@@ -65,31 +58,39 @@ function createCollabPanelContext() {toast.info(notifications.value.linkCopied)}+ function saveName() {+ const name = nameDraft.value.trim()+ if (name && name !== state.value.localName) collab?.setLocalName(name)+ }+function share() {- if (!collab || !nameDraft.value.trim()) return- collab.setLocalName(nameDraft.value.trim())+ if (!collab) return+ saveName()const roomId = collab.shareCurrentDoc()- void router.push(`/share/${roomId}`)+ if (!roomId) returnvoid copy(getShareURL(roomId))toast.info(notifications.value.linkCopied)popoverOpen.value = false}function join() {- if (!collab) return- const roomId = pendingRoomId.value || joinInput.value.trim().replace(/.*\/share\//, '')- if (!roomId || !nameDraft.value.trim()) return- collab.setLocalName(nameDraft.value.trim())- collab.connect(roomId)- void router.push(`/share/${roomId}`)+ saveName()+ if (!joinRoomFromInput(joinInput.value)) {+ joinError.value = true+ return+ }+ joinInput.value = ''+ joinError.value = falsepopoverOpen.value = false}+ function clearJoinError() {+ joinError.value = false+ }+function disconnect() {- if (!collab) return- collab.disconnect()+ collab?.disconnect()popoverOpen.value = false- void router.push('/')}function follow(target: FollowTarget | null) {@@ -105,16 +106,18 @@ function createCollabPanelContext() {messages: collaboration,copied,joinInput,+ joinError,nameDraft,popoverOpen,state,following,presenceRows,shareURL,- isJoining,copyLink,+ saveName,share,join,+ clearJoinError,disconnect,follow,renameLocalAgentdiff --git a/src/components/collab-room/ActiveRoomOverlay.vue b/src/components/collab-room/ActiveRoomOverlay.vuenew file mode 100644index 000000000..1b226ce42--- /dev/null+++ b/src/components/collab-room/ActiveRoomOverlay.vue@@ -0,0 +1,25 @@+<script setup lang="ts">+import LeftRoomNotice from './LeftRoomNotice.vue'+import RoomScreen from './RoomScreen.vue'+import { useRoomActions } from './useRoomActions'++/** The active room tab's screen while its document is on the way, or the note after leaving. */+const room = useRoomActions()+</script>++<template>+ <RoomScreen+ v-if="room.pendingStatus.value"+ :status="room.pendingStatus.value"+ :sender="room.sender.value"+ :others-waiting="room.othersWaiting.value"+ :name="room.state.value.localName"+ :copied="room.copied.value"+ :desktop-link="room.desktopLink.value"+ :downloadURL="room.downloadURL.value"+ @copy-link="room.copyLink"+ @leave="room.leave"+ @rename="room.rename"+ />+ <LeftRoomNotice v-else-if="room.leftRoom.value" @dismiss="room.dismissLeftRoomNote" />+</template>diff --git a/src/components/collab-room/LeftRoomNotice.stories.ts b/src/components/collab-room/LeftRoomNotice.stories.tsnew file mode 100644index 000000000..eab94e94d--- /dev/null+++ b/src/components/collab-room/LeftRoomNotice.stories.ts@@ -0,0 +1,30 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, fn, userEvent, within } from 'storybook/test'++import LeftRoomNotice from './LeftRoomNotice.vue'++type Args = { onDismiss: () => void }++const meta = {+ title: 'Collaboration/Left Room Notice',+ component: LeftRoomNotice,+ tags: ['autodocs'],+ args: { onDismiss: fn() },+ render: (args) => ({+ components: { LeftRoomNotice },+ setup: () => ({ args }),+ template: '<div class="relative h-40 bg-canvas"><LeftRoomNotice v-bind="args" /></div>'+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++export const Default: Story = {}++export const Dismiss: Story = {+ play: async ({ canvasElement, args }) => {+ await userEvent.click(within(canvasElement).getByRole('button', { name: 'Dismiss' }))+ await expect(args.onDismiss).toHaveBeenCalledOnce()+ }+}diff --git a/src/components/collab-room/LeftRoomNotice.vue b/src/components/collab-room/LeftRoomNotice.vuenew file mode 100644index 000000000..9ca069961--- /dev/null+++ b/src/components/collab-room/LeftRoomNotice.vue@@ -0,0 +1,24 @@+<script setup lang="ts">+import { useCollaborationMessages } from '@open-pencil/vue'++import IconButton from '@/components/ui/button/IconButton.vue'+import { roomNotice } from '@/theme/collaboration/room-screen'++const emit = defineEmits<{ dismiss: [] }>()++const messages = useCollaborationMessages()+const ui = roomNotice()+</script>++<template>+ <div :class="ui.root()" role="status" data-test-id="left-room-notice">+ <icon-lucide-log-out :class="ui.icon()" aria-hidden="true" />+ <div :class="ui.content()">+ <span :class="ui.title()">{{ messages.leftRoomTitle }}</span>+ <span :class="ui.description()">{{ messages.leftRoomDescription }}</span>+ </div>+ <IconButton :label="messages.dismiss" data-test-id="left-room-dismiss" @click="emit('dismiss')">+ <icon-lucide-x class="size-3.5" />+ </IconButton>+ </div>+</template>diff --git a/src/components/collab-room/RoomNameLine.vue b/src/components/collab-room/RoomNameLine.vuenew file mode 100644index 000000000..b28d70d36--- /dev/null+++ b/src/components/collab-room/RoomNameLine.vue@@ -0,0 +1,64 @@+<script setup lang="ts">+import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'+import { ref, watch } from 'vue'++import { useCollaborationMessages, useCommonMessages } from '@open-pencil/vue'++import AppButton from '@/components/ui/button/AppButton.vue'+import AppInput from '@/components/ui/input/AppInput.vue'+import { usePopoverUI } from '@/components/ui/overlay/popover'+import { roomScreen } from '@/theme/collaboration/room-screen'++/** "You'll appear as Teal Fox · Change": the name others will see, renamed in a small popover. */+const { name } = defineProps<{ name: string }>()+const emit = defineEmits<{ rename: [name: string] }>()++const messages = useCollaborationMessages()+const common = useCommonMessages()+const ui = roomScreen()+const cls = usePopoverUI({ content: 'z-50 flex w-64 flex-col gap-2 p-3' })+const open = ref(false)+const draft = ref('')++watch(open, (isOpen) => {+ if (isOpen) draft.value = name+})++function save() {+ const next = draft.value.trim()+ if (next && next !== name) emit('rename', next)+ open.value = false+}+</script>++<template>+ <p :class="ui.footnote()" data-test-id="room-name-line">+ <span>{{ messages.appearsAs({ name }) }}</span>+ <span aria-hidden="true">·</span>+ <PopoverRoot v-model:open="open">+ <PopoverTrigger as-child>+ <button type="button" :class="ui.link()" data-test-id="room-name-change">+ {{ messages.changeName }}+ </button>+ </PopoverTrigger>+ <PopoverPortal>+ <PopoverContent :class="cls.content" :side-offset="6" align="center">+ <label for="room-name-input" class="text-xs text-muted">{{ messages.yourName }}</label>+ <div class="flex items-center gap-1.5">+ <AppInput+ id="room-name-input"+ v-model="draft"+ autofocus+ class="min-w-0 flex-1"+ data-test-id="room-name-input"+ @enter="save"+ />+ <AppButton color="primary" variant="solid" :disabled="!draft.trim()" @click="save">+ {{ common.save }}+ </AppButton>+ </div>+ </PopoverContent>+ </PopoverPortal>+ </PopoverRoot>+ </p>+</template>diff --git a/src/components/collab-room/RoomScreen.stories.ts b/src/components/collab-room/RoomScreen.stories.tsnew file mode 100644index 000000000..038068c9b--- /dev/null+++ b/src/components/collab-room/RoomScreen.stories.ts@@ -0,0 +1,100 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, fn, userEvent, within } from 'storybook/test'++import type { PendingRoomStatus } from '@/app/collab/room/status'++import RoomScreen from './RoomScreen.vue'++type Args = {+ status: PendingRoomStatus+ sender: string | null+ othersWaiting: string[]+ name: string+ copied: boolean+ desktopLink: string | null+ downloadURL: string | null+ onCopyLink: () => void+ onLeave: () => void+ onRename: (name: string) => void+}++const meta = {+ title: 'Collaboration/Room Screen',+ component: RoomScreen,+ tags: ['autodocs'],+ args: {+ status: 'waiting',+ sender: null,+ othersWaiting: [],+ name: 'Teal Fox',+ copied: false,+ desktopLink: null,+ downloadURL: null,+ onCopyLink: fn(),+ onLeave: fn(),+ onRename: fn()+ },+ render: (args) => ({+ components: { RoomScreen },+ setup: () => ({ args }),+ template: '<div class="relative h-[480px] bg-canvas"><RoomScreen v-bind="args" /></div>'+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++export const Connecting: Story = {+ args: { status: 'connecting' }+}++export const LookingForPeople: Story = {+ args: { status: 'looking' }+}++export const ReceivingTheFile: Story = {+ args: { status: 'receiving', sender: 'Ana' }+}++export const Unreachable: Story = {+ args: { status: 'unreachable' }+}++export const WaitingWithOthers: Story = {+ args: { othersWaiting: ['Ben', 'Teal Fox'] }+}++export const Waiting: Story = {}++export const WaitingInDesktopBrowser: Story = {+ args: {+ desktopLink: 'openpencil://join?room=abcdefghijklmnopqrstuvwxyz012345',+ downloadURL: 'https://github.com/open-pencil/open-pencil/releases/latest'+ }+}++export const LinkCopied: Story = {+ args: { copied: true }+}++export const Actions: Story = {+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement)+ await userEvent.click(canvas.getByRole('button', { name: 'Copy link' }))+ await expect(args.onCopyLink).toHaveBeenCalledOnce()+ await userEvent.click(canvas.getByRole('button', { name: 'Leave' }))+ await expect(args.onLeave).toHaveBeenCalledOnce()+ }+}++export const Rename: Story = {+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement)+ await userEvent.click(canvas.getByRole('button', { name: 'Change' }))+ const body = within(canvasElement.ownerDocument.body)+ const input = await body.findByLabelText('Your name')+ await userEvent.clear(input)+ await userEvent.type(input, 'Dana{Enter}')+ await expect(args.onRename).toHaveBeenCalledWith('Dana')+ }+}diff --git a/src/components/collab-room/RoomScreen.vue b/src/components/collab-room/RoomScreen.vuenew file mode 100644index 000000000..24f1b9095--- /dev/null+++ b/src/components/collab-room/RoomScreen.vue@@ -0,0 +1,177 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useCollaborationMessages } from '@open-pencil/vue'++import { isFetchingRoom, type PendingRoomStatus } from '@/app/collab/room/status'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'+import { roomScreen } from '@/theme/collaboration/room-screen'++import RoomNameLine from './RoomNameLine.vue'++/**+ * What a room tab shows instead of the editor until the room's document arrives: what it is doing+ * to get the file, why nothing is here yet when nobody who has it is online, or that it cannot+ * reach the room at all. Nothing on it can edit the document.+ */+const {+ status,+ sender = null,+ othersWaiting = [],+ name,+ copied = false,+ desktopLink = null,+ downloadURL = null+} = defineProps<{+ status: PendingRoomStatus+ /** Who the file is coming from, while it is on its way. */+ sender?: string | null+ /** People in the room who are waiting for the file too. */+ othersWaiting?: string[]+ /** The person's name in the room, generated until they set one. */+ name: string+ copied?: boolean+ /** An `openpencil://join` link, offered in desktop browsers. */+ desktopLink?: string | null+ /** Where to get the desktop app, offered beside `desktopLink`. */+ downloadURL?: string | null+}>()++const emit = defineEmits<{+ copyLink: []+ leave: []+ rename: [name: string]+}>()++const messages = useCollaborationMessages()+const ui = roomScreen()++const fetching = computed(() => isFetchingRoom(status))+const progress = computed(() => {+ if (status === 'receiving' && sender) return messages.value.receivingDescription({ name: sender })+ if (status === 'looking') return messages.value.lookingDescription+ return messages.value.connectingDescription+})+</script>++<template>+ <div+ :class="ui.root()"+ data-test-id="room-screen"+ :data-status="status"+ role="status"+ aria-live="polite"+ :aria-busy="fetching"+ >+ <AppPlaceholder+ v-if="fetching"+ size="page"+ label-as="h2"+ :label="messages.joiningTitle"+ :description="progress"+ :ui="{ label: ui.title(), description: ui.description() }"+ >+ <template #icon>+ <icon-lucide-loader-circle :class="ui.spinner()" />+ </template>+ <template #action>+ <AppButton+ color="neutral"+ variant="ghost"+ data-test-id="room-screen-leave"+ @click="emit('leave')"+ >+ {{ messages.leave }}+ </AppButton>+ </template>+ </AppPlaceholder>++ <AppPlaceholder+ v-else-if="status === 'unreachable'"+ size="page"+ label-as="h2"+ :label="messages.unreachableTitle"+ :description="messages.unreachableDescription"+ :ui="{ label: ui.title(), description: ui.description() }"+ >+ <template #icon>+ <icon-lucide-wifi-off class="size-5" />+ </template>+ <template #action>+ <AppButton+ color="neutral"+ variant="ghost"+ data-test-id="room-screen-leave"+ @click="emit('leave')"+ >+ {{ messages.leave }}+ </AppButton>+ </template>+ </AppPlaceholder>++ <AppPlaceholder+ v-else+ size="page"+ label-as="h2"+ :label="messages.waitingTitle"+ :description="`${messages.waitingDescription} ${messages.waitingOpensAutomatically}`"+ :ui="{ label: ui.title(), description: ui.description() }"+ >+ <template #icon>+ <icon-lucide-users class="size-5" />+ </template>+ <ul :class="ui.steps()">+ <li>{{ messages.waitingAskSharer }}</li>+ <li>{{ messages.waitingCheckLink }}</li>+ </ul>+ <p v-if="othersWaiting.length" :class="ui.othersWaiting()" data-test-id="room-others-waiting">+ {{ messages.othersWaiting({ names: othersWaiting.join(', ') }) }}+ </p>+ <template #action>+ <div :class="ui.actions()">+ <div :class="ui.buttons()">+ <AppButton+ color="neutral"+ variant="outline"+ data-test-id="room-screen-copy-link"+ @click="emit('copyLink')"+ >+ <template #leading>+ <icon-lucide-check v-if="copied" class="size-3" />+ <icon-lucide-copy v-else class="size-3" />+ </template>+ {{ copied ? messages.linkCopied : messages.copyLink }}+ </AppButton>+ <AppButton+ color="neutral"+ variant="ghost"+ data-test-id="room-screen-leave"+ @click="emit('leave')"+ >+ {{ messages.leave }}+ </AppButton>+ </div>+ <RoomNameLine :name="name" @rename="emit('rename', $event)" />+ <p v-if="desktopLink" :class="ui.footnote()">+ <a :href="desktopLink" :class="ui.link()" data-test-id="room-screen-open-desktop">+ {{ messages.openInDesktopApp }}+ </a>+ <template v-if="downloadURL">+ <span aria-hidden="true">·</span>+ <a+ :href="downloadURL"+ target="_blank"+ rel="noopener noreferrer"+ :class="ui.link()"+ data-test-id="room-screen-download-desktop"+ >+ {{ messages.downloadDesktopApp }}+ </a>+ </template>+ </p>+ </div>+ </template>+ </AppPlaceholder>+ </div>+</template>diff --git a/src/components/collab-room/statusText.ts b/src/components/collab-room/statusText.tsnew file mode 100644index 000000000..0ac12974f--- /dev/null+++ b/src/components/collab-room/statusText.ts@@ -0,0 +1,18 @@+import type { useCollaborationMessages } from '@open-pencil/vue'++import type { RoomStatus } from '@/app/collab/room/status'++type CollaborationMessages = ReturnType<typeof useCollaborationMessages>['value']++/** A room's state in words: "Live · 3 here", "Only you here — …", joining, waiting, or offline. */+export function roomStatusText(+ messages: CollaborationMessages,+ status: RoomStatus,+ peerCount: number+): string {+ if (status === 'live') return messages.statusLive({ count: peerCount + 1 })+ if (status === 'alone') return messages.statusAlone+ if (status === 'waiting') return messages.waitingTitle+ if (status === 'unreachable') return messages.unreachableTitle+ return messages.joiningTitle+}diff --git a/src/components/collab-room/useRoomActions.ts b/src/components/collab-room/useRoomActions.tsnew file mode 100644index 000000000..b72ea17ca--- /dev/null+++ b/src/components/collab-room/useRoomActions.ts@@ -0,0 +1,77 @@+import { useClipboard } from '@vueuse/core'+import { computed } from 'vue'++import { useViewportKind } from '@open-pencil/vue'++import { roomLinkURL } from '@/app/collab/room/links'+import { showsRoomDocument, type PendingRoomStatus } from '@/app/collab/room/status'+import { DEFAULT_COLLAB_STATE, useCollabInjected } from '@/app/collab/use'+import { useNotificationMessages } from '@/app/i18n/notifications'+import { toast } from '@/app/shell/ui'+import { DESKTOP_DOWNLOAD_URL, getShareURL, IS_BROWSER, IS_TAURI } from '@/constants'++/** What the room screens offer for the active tab's room: its link, a desktop handoff, Leave. */+export function useRoomActions() {+ const collab = useCollabInjected()+ const notifications = useNotificationMessages()+ const { isMobile } = useViewportKind()+ const { copy, copied } = useClipboard({ copiedDuring: 2000 })++ const state = computed(() => collab?.state.value ?? DEFAULT_COLLAB_STATE)+ const leftRoom = computed(() => collab?.leftRoom.value ?? false)+ /** Whether the room's document has yet to arrive, so its screen shows instead of the editor. */+ const pendingStatus = computed<PendingRoomStatus | null>(() => {+ const status = state.value.status+ return status && !showsRoomDocument(status) ? status : null+ })+ const pending = computed(() => pendingStatus.value !== null)+ /** Who the file is coming from, while it is on its way. */+ const sender = computed(() => state.value.peers.find((peer) => peer.hasFile)?.name ?? null)+ /** People in the room who are waiting for the file too. */+ const othersWaiting = computed(() =>+ state.value.peers.filter((peer) => !peer.hasFile).map((peer) => peer.name)+ )+ // Browsers on a computer can hand the room to the desktop app; phones and the app cannot.+ const desktopLink = computed(() => {+ const roomId = state.value.roomId+ if (!roomId || !IS_BROWSER || IS_TAURI || isMobile.value) return null+ return roomLinkURL(roomId)+ })+ /** Offered beside the desktop link, for people without the app. */+ const downloadURL = computed(() => (desktopLink.value ? DESKTOP_DOWNLOAD_URL : null))++ function copyLink() {+ const roomId = state.value.roomId+ if (!roomId) return+ void copy(getShareURL(roomId))+ toast.info(notifications.value.linkCopied)+ }++ function leave() {+ collab?.disconnect()+ }++ function rename(name: string) {+ collab?.setLocalName(name)+ }++ function dismissLeftRoomNote() {+ collab?.dismissLeftRoomNote()+ }++ return {+ state,+ leftRoom,+ pending,+ pendingStatus,+ sender,+ othersWaiting,+ copied,+ desktopLink,+ downloadURL,+ copyLink,+ leave,+ rename,+ dismissLeftRoomNote+ }+}diff --git a/src/components/editor/EditorWorkspace.vue b/src/components/editor/EditorWorkspace.vueindex 095726545..671f889c9 100644--- a/src/components/editor/EditorWorkspace.vue+++ b/src/components/editor/EditorWorkspace.vue@@ -13,6 +13,8 @@ import { activeTab } from '@/app/tabs'import BrandMark from '@/components/brand/BrandMark.vue'import CanvasSplitRoot from '@/components/canvas/CanvasSplitRoot.vue'import CollabPanel from '@/components/collab-panel/CollabPanel.vue'+import ActiveRoomOverlay from '@/components/collab-room/ActiveRoomOverlay.vue'+import { useRoomActions } from '@/components/collab-room/useRoomActions'import EditorCanvas from '@/components/EditorCanvas.vue'import LayersPanel from '@/components/LayersPanel.vue'import MobileDrawer from '@/components/MobileDrawer.vue'@@ -33,11 +35,21 @@ const { editor } = useI18n()const { isMobile } = useViewportKind()const initialEditorLayout = loadEditorLayout()const horizontalSplitterStyles = tv(splitterTheme)({ direction: 'horizontal' })+// Until a room's document arrives there is nothing to edit, so its screen replaces the editor.+const { pending: roomPending } = useRoomActions()</script><template>+ <div+ v-if="roomPending"+ :key="'room-' + activeTab?.id"+ class="relative flex flex-1 overflow-hidden"+ >+ <ActiveRoomOverlay />+ </div>+<SplitterGroup- v-if="!isMobile && showChrome && store.state.showUI"+ v-else-if="!isMobile && showChrome && store.state.showUI":key="activeTab?.id"direction="horizontal"class="flex-1 overflow-hidden"@@ -61,6 +73,7 @@ const horizontalSplitterStyles = tv(splitterTheme)({ direction: 'horizontal' })<SplitterPanel id="canvas" :default-size="initialEditorLayout[1]" :min-size="30" class="flex"><div class="relative flex min-w-0 flex-1"><CanvasSplitRoot />+ <ActiveRoomOverlay /><Toolbar /></div></SplitterPanel>@@ -88,6 +101,7 @@ const horizontalSplitterStyles = tv(splitterTheme)({ direction: 'horizontal' })><div class="relative flex min-w-0 flex-1"><EditorCanvas />+ <ActiveRoomOverlay /><MobileHud /><Toolbar /></div>@@ -101,6 +115,7 @@ const horizontalSplitterStyles = tv(splitterTheme)({ direction: 'horizontal' })><div class="relative flex min-w-0 flex-1"><EditorCanvas />+ <ActiveRoomOverlay /><divv-if="!isMobile"class="absolute top-7 left-7 z-10 flex items-center gap-2 rounded-lg border border-border bg-panel px-2 py-1 shadow-sm"@@ -124,6 +139,7 @@ const horizontalSplitterStyles = tv(splitterTheme)({ direction: 'horizontal' })<div v-else :key="'bare-' + activeTab?.id" class="flex flex-1 overflow-hidden"><div class="relative flex min-w-0 flex-1"><EditorCanvas />+ <ActiveRoomOverlay /></div></div></template>diff --git a/src/components/home/search/HomeJoinRoom.vue b/src/components/home/search/HomeJoinRoom.vuenew file mode 100644index 000000000..66a897bab--- /dev/null+++ b/src/components/home/search/HomeJoinRoom.vue@@ -0,0 +1,80 @@+<script setup lang="ts">+import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'+import { ref } from 'vue'++import { useCollaborationMessages } from '@open-pencil/vue'++import { useJoinRoom } from '@/app/collab/join'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppInput from '@/components/ui/input/AppInput.vue'+import { usePopoverUI } from '@/components/ui/overlay/popover'++/** "Join room…" on Home: paste a room link or ID to open someone's shared file in a new tab. */+const { size = 'md' } = defineProps<{ size?: 'md' | 'lg' }>()++const messages = useCollaborationMessages()+const joinRoomFromInput = useJoinRoom()+const cls = usePopoverUI({ content: 'z-50 flex w-80 flex-col gap-2 p-3' })+const open = ref(false)+const input = ref('')+const invalid = ref(false)+const ERROR_ID = 'home-join-room-error'++function join() {+ if (!joinRoomFromInput(input.value)) {+ invalid.value = true+ return+ }+ input.value = ''+ invalid.value = false+ open.value = false+}+</script>++<template>+ <PopoverRoot v-model:open="open">+ <PopoverTrigger as-child>+ <AppButton :size="size" variant="outline" data-test-id="home-join-room">+ <template #leading><icon-lucide-users class="size-3.5" /></template>+ {{ messages.joinRoomEllipsis }}+ </AppButton>+ </PopoverTrigger>+ <PopoverPortal>+ <PopoverContent+ :class="cls.content"+ :side-offset="8"+ align="end"+ data-test-id="home-join-room-popover"+ >+ <p class="text-xs text-muted">{{ messages.joinRoomDescription }}</p>+ <div class="flex items-center gap-1.5">+ <AppInput+ v-model="input"+ autofocus+ data-test-id="home-join-room-input"+ class="min-w-0 flex-1"+ :placeholder="messages.pasteRoomLinkOrId"+ :aria-label="messages.pasteRoomLinkOrId"+ :state="invalid ? 'invalid' : 'idle'"+ :aria-invalid="invalid"+ :aria-describedby="invalid ? ERROR_ID : undefined"+ @update:model-value="invalid = false"+ @enter="join"+ />+ <AppButton+ color="primary"+ variant="solid"+ data-test-id="home-join-room-submit"+ :disabled="!input.trim()"+ @click="join"+ >+ {{ messages.join }}+ </AppButton>+ </div>+ <p v-if="invalid" :id="ERROR_ID" class="text-xs text-error" role="alert">+ {{ messages.invalidRoomLink }}+ </p>+ </PopoverContent>+ </PopoverPortal>+ </PopoverRoot>+</template>diff --git a/src/components/home/search/HomeSearchActions.vue b/src/components/home/search/HomeSearchActions.vueindex a9ac4e919..877e0ecd0 100644--- a/src/components/home/search/HomeSearchActions.vue+++ b/src/components/home/search/HomeSearchActions.vue@@ -9,6 +9,8 @@ import { activeTab } from '@/app/tabs'import AppButton from '@/components/ui/button/AppButton.vue'import AppInput from '@/components/ui/input/AppInput.vue'+import HomeJoinRoom from './HomeJoinRoom.vue'+const emit = defineEmits<{ 'new-document': [] }>()const query = defineModel<string>({ required: true })const { menu, files } = useI18n()@@ -54,6 +56,9 @@ watch(<template #leading><icon-lucide-search class="size-4" /></template></AppInput><div class="grid grid-cols-2 gap-2 md:contents">+ <div class="col-span-2 grid md:contents">+ <HomeJoinRoom :size="isMobile ? 'lg' : 'md'" />+ </div><AppButton:size="isMobile ? 'lg' : 'md'"variant="outline"diff --git a/src/components/presence/AvatarStack.stories.ts b/src/components/presence/AvatarStack.stories.tsnew file mode 100644index 000000000..eec6ad093--- /dev/null+++ b/src/components/presence/AvatarStack.stories.ts@@ -0,0 +1,41 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'++import AvatarStack from './AvatarStack.vue'+import { room } from './examples/room'+import type { PresencePersonRow } from './rows'++type Args = {+ people: PresencePersonRow[]+ max: number+ size: 'sm' | 'md'+ label: string+}++const meta = {+ title: 'Collaboration/Avatar Stack',+ component: AvatarStack,+ tags: ['autodocs'],+ args: { people: room, max: 3, size: 'sm', label: 'In this room: Dana, Ana, Ben' },+ render: (args) => ({+ components: { AvatarStack },+ setup: () => ({ args }),+ template: '<div class="bg-panel p-4"><AvatarStack v-bind="args" /></div>'+ })+} satisfies Meta<Args>++export default meta+type Story = StoryObj<typeof meta>++export const Room: Story = {}++export const Large: Story = {+ args: { size: 'md' }+}++export const MoreThanFit: Story = {+ args: { max: 2 }+}++export const Alone: Story = {+ args: { people: room.slice(0, 1), label: 'In this room: Dana' }+}diff --git a/src/components/presence/AvatarStack.vue b/src/components/presence/AvatarStack.vuenew file mode 100644index 000000000..b643e82c6--- /dev/null+++ b/src/components/presence/AvatarStack.vue@@ -0,0 +1,51 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useCommonMessages } from '@open-pencil/vue'++import { avatarStack } from '@/theme/collaboration/avatar-stack'++import PersonAvatar from './PersonAvatar.vue'+import type { PresencePersonRow } from './rows'++/**+ * The people in a room or on a page, overlapping, each with how many agents they run, then+ * "+N". Interactive places wrap each person through the `person` slot and the rest through+ * `overflow`; elsewhere it is one picture named by `label`.+ */+const {+ people,+ max = 3,+ size = 'sm',+ label+} = defineProps<{+ people: PresencePersonRow[]+ max?: number+ size?: 'sm' | 'md'+ /** The stack's accessible name, when it is a picture rather than a set of controls. */+ label?: string+}>()++const common = useCommonMessages()+const ui = computed(() => avatarStack({ size }))+const shown = computed(() => people.slice(0, max))+const hidden = computed(() => people.length - shown.value.length)+</script>++<template>+ <div :class="ui.root()" :role="label ? 'img' : undefined" :aria-label="label">+ <template v-for="person in shown" :key="person.clientId ?? 'self'">+ <slot name="person" :person="person">+ <PersonAvatar+ :name="person.name || common.you"+ :color="person.color"+ :agent-count="person.agents.length"+ :size="size"+ />+ </slot>+ </template>+ <slot name="overflow" :hidden="hidden">+ <span v-if="hidden > 0" :class="ui.overflow()">+{{ hidden }}</span>+ </slot>+ </div>+</template>diff --git a/src/components/presence/PagePresenceHover.vue b/src/components/presence/PagePresenceHover.vuenew file mode 100644index 000000000..ddd885214--- /dev/null+++ b/src/components/presence/PagePresenceHover.vue@@ -0,0 +1,70 @@+<script setup lang="ts">+import { HoverCardContent, HoverCardPortal, HoverCardRoot, HoverCardTrigger } from 'reka-ui'+import { computed } from 'vue'++import { useCollaborationMessages } from '@open-pencil/vue'++import { DEFAULT_COLLAB_STATE, useCollabInjected } from '@/app/collab/use'+import { useActiveEditorStoreRef } from '@/app/editor/active-store'+import { follow, presenceOf } from '@/app/presence/registry'+import type { FollowTarget } from '@/app/presence/types'+import { pagePresence } from '@/theme/collaboration/page-presence'++import AvatarStack from './AvatarStack.vue'+import PresenceList from './PresenceList.vue'+import { pagePresenceRows } from './rows'++/**+ * Wraps a page in a page list: hovering it shows who is on that page and what their agents are+ * doing there, and lets you follow them.+ */+const { pageId } = defineProps<{ pageId: string }>()++const collab = useCollabInjected()+const messages = useCollaborationMessages()+const tabStore = useActiveEditorStoreRef()+const ui = pagePresence()++const people = computed(() => {+ const store = tabStore.value+ if (!store) return []+ const state = collab?.state.value ?? DEFAULT_COLLAB_STATE+ const presence = presenceOf(store)+ return pagePresenceRows(+ { name: state.localName, color: state.localColor, agents: presence.agents.value },+ presence.peers.value,+ pageId+ )+})+const following = computed(() =>+ tabStore.value ? presenceOf(tabStore.value).following.value : null+)++function followTarget(target: FollowTarget | null) {+ if (tabStore.value) follow(tabStore.value, target)+}+</script>++<template>+ <HoverCardRoot v-if="people.length > 0" :open-delay="350" :close-delay="150">+ <HoverCardTrigger as-child>+ <slot />+ </HoverCardTrigger>+ <HoverCardPortal>+ <HoverCardContent+ data-test-id="page-presence-card"+ :class="ui.card()"+ side="right"+ align="start"+ :side-offset="8"+ >+ <div :class="ui.header()">+ <AvatarStack :people="people" size="md" />+ <span :class="ui.title()">{{ messages.onThisPage }}</span>+ </div>+ <PresenceList :rows="people" :following="following" @follow="followTarget" />+ </HoverCardContent>+ </HoverCardPortal>+ </HoverCardRoot>+ <slot v-else />+</template>diff --git a/src/components/presence/PersonAvatar.vue b/src/components/presence/PersonAvatar.vuenew file mode 100644index 000000000..efb9ef62a--- /dev/null+++ b/src/components/presence/PersonAvatar.vue@@ -0,0 +1,41 @@+<script setup lang="ts">+import { colorToCSS } from '@open-pencil/scene-graph/color'+import type { Color } from '@open-pencil/scene-graph/primitives'++import { initials } from '@/app/shell/ui'+import { avatar } from '@/theme/collaboration/avatar'+import { avatarStack } from '@/theme/collaboration/avatar-stack'++/** A person's initials on their color, with how many agents they run. */+const {+ name,+ color,+ agentCount = 0,+ size = 'sm',+ following = false,+ interactive = false+} = defineProps<{+ name: string+ color: Color+ agentCount?: number+ size?: 'sm' | 'md'+ following?: boolean+ interactive?: boolean+}>()++const ui = avatarStack()+</script>++<template>+ <span :class="ui.person()">+ <span+ :class="avatar({ size, bordered: true, following, interactive })"+ :style="{ background: colorToCSS(color) }"+ >+ {{ initials(name) }}+ </span>+ <span v-if="agentCount > 0" :class="ui.badge()" :style="{ color: colorToCSS(color) }">+ <icon-lucide-sparkle :class="ui.badgeIcon()" />{{ agentCount }}+ </span>+ </span>+</template>diff --git a/src/components/collab-panel/PresenceList.stories.ts b/src/components/presence/PresenceList.stories.tssimilarity index 97%rename from src/components/collab-panel/PresenceList.stories.tsrename to src/components/presence/PresenceList.stories.tsindex 4b402aeb7..2ad9f1db5 100644--- a/src/components/collab-panel/PresenceList.stories.ts+++ b/src/components/presence/PresenceList.stories.ts@@ -4,8 +4,8 @@ import { expect, fn, userEvent, within } from 'storybook/test'import type { FollowTarget } from '@/app/presence/types'import { room } from './examples/room'-import type { PresencePersonRow } from './presence'import PresenceList from './PresenceList.vue'+import type { PresencePersonRow } from './rows'type Args = { rows: PresencePersonRow[]; following: FollowTarget | null }diff --git a/src/components/collab-panel/PresenceList.vue b/src/components/presence/PresenceList.vuesimilarity index 99%rename from src/components/collab-panel/PresenceList.vuerename to src/components/presence/PresenceList.vueindex 6b15d0382..0d0ca2349 100644--- a/src/components/collab-panel/PresenceList.vue+++ b/src/components/presence/PresenceList.vue@@ -8,7 +8,7 @@ import IconButton from '@/components/ui/button/IconButton.vue'import { avatar } from '@/theme/collaboration/avatar'import { presenceList } from '@/theme/collaboration/presence-list'-import { isFollowing, type PresenceAgentRow, type PresencePersonRow } from './presence'+import { isFollowing, type PresenceAgentRow, type PresencePersonRow } from './rows'const { rows, following } = defineProps<{rows: PresencePersonRow[]diff --git a/src/components/collab-panel/examples/room.ts b/src/components/presence/examples/room.tssimilarity index 93%rename from src/components/collab-panel/examples/room.tsrename to src/components/presence/examples/room.tsindex e32f6d303..ec06a7fba 100644--- a/src/components/collab-panel/examples/room.ts+++ b/src/components/presence/examples/room.ts@@ -1,4 +1,4 @@-import type { PresencePersonRow } from '../presence'+import type { PresencePersonRow } from '../rows'/** Sample collaborators for presence stories: you, then Ana with two agents, then Ben. */export const colors = {diff --git a/src/components/collab-panel/presence.ts b/src/components/presence/rows.tssimilarity index 65%rename from src/components/collab-panel/presence.tsrename to src/components/presence/rows.tsindex 1aa008d8b..9c41f6f0c 100644--- a/src/components/collab-panel/presence.ts+++ b/src/components/presence/rows.ts@@ -1,6 +1,7 @@import type { Color } from '@open-pencil/scene-graph/primitives'import type { RemotePeer } from '@/app/collab/types'+import { agentPage } from '@/app/presence/registry'import type { AgentPresence, AgentStatus, FollowTarget } from '@/app/presence/types'export interface PresenceAgentRow {@@ -51,6 +52,32 @@ export function presenceRows(]}+/**+ * The people on one page, each with only the agents they run there: collaborators whose cursor is+ * on it, and anyone, you included, whose agents work there.+ */+export function pagePresenceRows(+ self: { name: string; color: Color; agents: readonly AgentPresence[] },+ peers: readonly RemotePeer[],+ pageId: string+): PresencePersonRow[] {+ const onPage = (agents: readonly AgentPresence[]) =>+ agentRows(+ agents.filter((agent) => agentPage(agent) === pageId),+ () => undefined,+ false+ )+ const rows: PresencePersonRow[] = []+ const ownAgents = onPage(self.agents)+ if (ownAgents.length > 0) rows.push({ name: self.name, color: self.color, agents: ownAgents })+ for (const peer of peers) {+ const agents = onPage(peer.agents)+ if (peer.cursor?.pageId !== pageId && agents.length === 0) continue+ rows.push({ clientId: peer.clientId, name: peer.name, color: peer.color, agents })+ }+ return rows+}+export function isFollowing(following: FollowTarget | null, target: FollowTarget): boolean {if (!following || following.kind !== target.kind) return falsereturn following.kind === 'person'diff --git a/src/components/settings/general/CollaborationNameSection.vue b/src/components/settings/general/CollaborationNameSection.vuenew file mode 100644index 000000000..4d767b0fd--- /dev/null+++ b/src/components/settings/general/CollaborationNameSection.vue@@ -0,0 +1,39 @@+<script setup lang="ts">+import { ref } from 'vue'++import { useCollaborationMessages } from '@open-pencil/vue'++import { useCollabIdentity } from '@/app/collab/identity'+import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'+import SettingsSection from '@/components/settings/layout/SettingsSection.vue'+import AppInput from '@/components/ui/input/AppInput.vue'++/** The one name others see in every shared room; while empty, rooms use a generated one. */+const messages = useCollaborationMessages()+const identity = useCollabIdentity()+const draft = ref(identity.hasChosenName.value ? identity.name.value : '')++function save() {+ identity.setName(draft.value)+}+</script>++<template>+ <SettingsSection>+ <template #title>{{ messages.nameSettingTitle }}</template>+ <template #description>{{ messages.nameSettingDescription }}</template>+ <SettingsGroup>+ <div class="px-3 py-2.5">+ <AppInput+ v-model="draft"+ data-test-id="settings-collab-name"+ class="w-full sm:w-72"+ :aria-label="messages.nameSettingTitle"+ :placeholder="messages.enterYourName"+ @change="save"+ @enter="save"+ />+ </div>+ </SettingsGroup>+ </SettingsSection>+</template>diff --git a/src/components/settings/general/GeneralSettingsPanel.vue b/src/components/settings/general/GeneralSettingsPanel.vueindex 958e52fe6..c17e569b5 100644--- a/src/components/settings/general/GeneralSettingsPanel.vue+++ b/src/components/settings/general/GeneralSettingsPanel.vue@@ -9,6 +9,7 @@ import { appPreferences } from '@/app/settings/preferences/store'import { animationPreference } from '@/app/shell/motion'import { useAppTheme } from '@/app/shell/theme'import CredentialSettingsSection from '@/components/settings/credentials/CredentialSettingsSection.vue'+import CollaborationNameSection from '@/components/settings/general/CollaborationNameSection.vue'import RenderingSettingsSection from '@/components/settings/general/RenderingSettingsSection.vue'import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'import SettingsSection from '@/components/settings/layout/SettingsSection.vue'@@ -101,6 +102,8 @@ const snapToPixelGrid = computed({</SettingsGroup></SettingsSection>+ <CollaborationNameSection />+<SettingsSection><template #title>{{ recovery.settingsTitle }}</template>diff --git a/src/components/ui/feedback/AppPlaceholder.vue b/src/components/ui/feedback/AppPlaceholder.vueindex 576176e37..ea1aaa0ed 100644--- a/src/components/ui/feedback/AppPlaceholder.vue+++ b/src/components/ui/feedback/AppPlaceholder.vue@@ -14,9 +14,12 @@ const {description,fill = true,size = 'panel',+ labelAs = 'p',ui} = defineProps<{label: string+ /** A heading level when the placeholder stands for a whole page or view. */+ labelAs?: 'p' | 'h2' | 'h3'description?: stringfill?: booleansize?: PlaceholderVariants['size']@@ -32,6 +35,7 @@ const styles = computed(() => {icon: theme.icon({ class: ui?.icon }),label: theme.label({ class: ui?.label }),description: theme.description({ class: ui?.description }),+ body: theme.body({ class: ui?.body }),action: theme.action({ class: ui?.action })}})@@ -43,10 +47,15 @@ const styles = computed(() => {<div v-if="slots.icon" :class="styles.icon" data-slot="placeholder-icon" aria-hidden="true"><slot name="icon" /></div>- <p :class="styles.label" data-slot="placeholder-label">{{ label }}</p>+ <component :is="labelAs" :class="styles.label" data-slot="placeholder-label">+ {{ label }}+ </component><p v-if="description" :class="styles.description" data-slot="placeholder-description">{{ description }}</p>+ <div v-if="slots.default" :class="styles.body" data-slot="placeholder-body">+ <slot />+ </div><div v-if="slots.action" :class="styles.action" data-slot="placeholder-action"><slot name="action" /></div>diff --git a/src/constants.ts b/src/constants.tsindex 6b14d1b6d..8de718763 100644--- a/src/constants.ts+++ b/src/constants.ts@@ -63,13 +63,23 @@ export {import type { Color } from '@open-pencil/scene-graph/primitives'-export const TRYSTERO_APP_ID = 'openpencil'+/**+ * The collaboration namespace. It names the shared document format, so builds that sync the layer+ * tree differently never join each other's rooms; change it with the format.+ */+export const COLLAB_APP_ID = 'openpencil/2'// 32 base36 characters provide roughly 165 bits of entropy. The room ID is a// bearer credential and must resist offline enumeration from public signaling topics.export const ROOM_ID_LENGTH = 32export const ROOM_ID_CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789'+/** How long a room tab tries to reach the service that introduces peers before saying it cannot. */+export const ROOM_UNREACHABLE_MS = 20_000+/** How often a room tab rechecks its connection while it waits for the file. */+export const ROOM_STATUS_TICK_MS = 500export const WEB_APP_ORIGIN = 'https://app.openpencil.dev'+/** Where the desktop app's installers are published. */+export const DESKTOP_DOWNLOAD_URL = 'https://github.com/open-pencil/open-pencil/releases/latest'export function getShareURL(roomId: string): string {const base = IS_TAURI || !IS_BROWSER ? WEB_APP_ORIGIN : window.location.origindiff --git a/src/theme/collaboration/avatar-stack.ts b/src/theme/collaboration/avatar-stack.tsnew file mode 100644index 000000000..04a225c5d--- /dev/null+++ b/src/theme/collaboration/avatar-stack.ts@@ -0,0 +1,21 @@+import { tv } from 'tailwind-variants'++/** People overlapping in a row, each with their agent count, then "+N". */+export const avatarStack = tv({+ slots: {+ root: 'flex items-center -space-x-1.5',+ person: 'relative inline-flex shrink-0',+ badge:+ 'absolute -right-1.5 -bottom-1 flex items-center gap-px rounded-full border border-panel bg-panel px-0.5 text-[8px] leading-none font-semibold',+ badgeIcon: 'size-2',+ overflow:+ 'relative flex shrink-0 items-center justify-center rounded-full border-2 border-panel bg-hover text-[9px] font-semibold text-surface'+ },+ variants: {+ size: {+ sm: { overflow: 'size-6' },+ md: { overflow: 'size-7' }+ }+ },+ defaultVariants: { size: 'sm' }+})diff --git a/src/theme/collaboration/page-presence.ts b/src/theme/collaboration/page-presence.tsnew file mode 100644index 000000000..4b7da031d--- /dev/null+++ b/src/theme/collaboration/page-presence.ts@@ -0,0 +1,13 @@+import { tv } from 'tailwind-variants'++import { motionStyles } from '@/theme/motion/styles'+import { floatingSurface } from '@/theme/overlay'++/** The card a page shows on hover: who is on the page, and what their agents do there. */+export const pagePresence = tv({+ slots: {+ card: ['z-50 w-60 p-2', floatingSurface, motionStyles.floating],+ header: 'mb-2 flex items-center gap-2 border-b border-border px-1 pb-2',+ title: 'text-xs text-muted'+ }+})diff --git a/src/theme/collaboration/presence-avatars.ts b/src/theme/collaboration/presence-avatars.tsindex b15fb8ce6..427453bff 100644--- a/src/theme/collaboration/presence-avatars.ts+++ b/src/theme/collaboration/presence-avatars.ts@@ -3,15 +3,12 @@ import { tv } from 'tailwind-variants'import { motionStyles } from '@/theme/motion/styles'import { floatingSurface } from '@/theme/overlay'-/** The avatar stack in the toolbar: you, collaborators with their agent counts, then "+N". */+/** The toolbar's avatar stack controls: your menu, collaborators to follow, and everyone. */export const presenceAvatars = tv({slots: {- root: 'flex items-center -space-x-1.5',trigger:'relative shrink-0 rounded-full outline-none focus-visible:ring-2 focus-visible:ring-accent',- badge:- 'absolute -right-1.5 -bottom-1 flex items-center gap-px rounded-full border border-panel bg-panel px-0.5 text-[8px] leading-none font-semibold',- badgeIcon: 'size-2',+ chevron: 'size-2',/** On your avatar while you are in a room. */live: 'absolute -top-0.5 -right-0.5 size-2 rounded-full border border-panel bg-[var(--color-success-bg)]',overflow:diff --git a/src/theme/collaboration/room-screen.ts b/src/theme/collaboration/room-screen.tsnew file mode 100644index 000000000..188bcaf6d--- /dev/null+++ b/src/theme/collaboration/room-screen.ts@@ -0,0 +1,32 @@+import { tv } from 'tailwind-variants'++/**+ * The room tab's screen while its document is on the way, centred like the app's other empty+ * states (`AppPlaceholder`) over the whole tab.+ */+export const roomScreen = tv({+ slots: {+ root: 'absolute inset-0 z-20 flex overflow-y-auto bg-canvas',+ title: 'text-sm font-semibold',+ description: 'mt-1.5 text-balance',+ spinner: 'size-5 animate-spin motion-reduce:animate-none',+ steps:+ 'mx-auto flex w-fit list-disc flex-col gap-1 pl-4 text-left text-xs leading-relaxed text-muted',+ othersWaiting: 'mt-3 text-xs text-muted',+ actions: 'flex flex-col items-center gap-3',+ buttons: 'flex items-center justify-center gap-2',+ footnote: 'flex flex-wrap items-center justify-center gap-1.5 text-[11px] text-muted',+ link: 'text-accent underline-offset-2 hover:underline focus-visible:underline focus-visible:outline-none'+ }+})++/** A note across the top of the canvas, such as after leaving a room. */+export const roomNotice = tv({+ slots: {+ root: 'absolute top-3 left-1/2 z-20 flex max-w-[calc(100%-2rem)] -translate-x-1/2 items-center gap-3 rounded-lg border border-border bg-panel px-3 py-2 shadow-sm',+ icon: 'size-4 shrink-0 text-muted',+ content: 'flex min-w-0 flex-col',+ title: 'text-xs font-medium text-surface',+ description: 'text-[11px] text-muted'+ }+})diff --git a/src/theme/collaboration/room-status.ts b/src/theme/collaboration/room-status.tsnew file mode 100644index 000000000..8f9a07110--- /dev/null+++ b/src/theme/collaboration/room-status.ts@@ -0,0 +1,9 @@+import { tv } from 'tailwind-variants'++/** A room's state as one line: a dot that is green while others are here, and the words. */+export const roomStatus = tv({+ slots: {+ root: 'group mb-3 flex items-start gap-2 text-xs leading-snug text-surface',+ dot: 'mt-1 size-2 shrink-0 rounded-full bg-muted group-data-[status=live]:bg-success group-data-[status=connecting]:animate-pulse group-data-[status=looking]:animate-pulse group-data-[status=receiving]:animate-pulse group-data-[status=unreachable]:bg-warning-text motion-reduce:animate-none'+ }+})diff --git a/src/theme/feedback/placeholder.ts b/src/theme/feedback/placeholder.tsindex 6af741486..45757bb31 100644--- a/src/theme/feedback/placeholder.ts+++ b/src/theme/feedback/placeholder.ts@@ -5,6 +5,7 @@ const placeholderTheme = {icon: 'mb-3 flex size-10 items-center justify-center rounded-full bg-panel-field text-muted',label: 'text-xs font-medium text-surface',description: 'mt-1 text-xs leading-relaxed text-muted',+ body: 'mt-3 w-full',action: 'mt-4 flex w-full items-center justify-center gap-2'},variants: {diff --git a/src/theme/mobile/presence-popover.ts b/src/theme/mobile/presence-popover.tsindex d4b32093b..fdd003f80 100644--- a/src/theme/mobile/presence-popover.ts+++ b/src/theme/mobile/presence-popover.ts@@ -3,11 +3,16 @@ import { tv } from 'tailwind-variants'import { motionStyles } from '@/theme/motion/styles'import { floatingSurface } from '@/theme/overlay'+/** The mobile HUD's room pill: the room's state, the people in it, and the list it opens. */export const presencePopover = tv({slots: {- dot: 'size-2 rounded-full bg-green-500',- content: ['z-50 w-56 p-3', floatingSurface, motionStyles.floating],- peerRow:- 'flex cursor-pointer items-center gap-2 rounded-md px-0.5 py-0.5 outline-none select-none active:bg-hover focus-visible:ring-1 focus-visible:ring-accent'+ trigger: 'pl-3 pr-1.5',+ summary: 'flex items-center gap-2',+ dot: [+ 'block size-2 shrink-0 rounded-full bg-muted',+ 'data-[status=live]:bg-success data-[status=unreachable]:bg-warning-text',+ 'data-[status=connecting]:animate-pulse data-[status=looking]:animate-pulse data-[status=receiving]:animate-pulse motion-reduce:animate-none'+ ],+ content: ['z-50 w-60 p-3', floatingSurface, motionStyles.floating]}})diff --git a/src/views/WorkspaceView.vue b/src/views/WorkspaceView.vueindex f5215ae75..d275b1925 100644--- a/src/views/WorkspaceView.vue+++ b/src/views/WorkspaceView.vue@@ -4,9 +4,14 @@ import { useEventListener } from '@vueuse/core'import { onMounted, onUnmounted, provide, ref } from 'vue'import { useRoute, useRouter } from 'vue-router'+import { useI18n } from '@open-pencil/vue'+import { startMCPRuntime, stopMCPRuntime } from '@/app/automation/mcp/runtime'import { startWebMCP } from '@/app/automation/webmcp/runtime'import { exposeCollaborationActions } from '@/app/browser-bridge'+import { useJoinRoom } from '@/app/collab/join'+import { bindDesktopRoomLinks } from '@/app/collab/room/links'+import { syncRoomRoute } from '@/app/collab/route'import { COLLAB_KEY, useCollab } from '@/app/collab/use'import { createDemoShapes } from '@/app/demo/document'import type { PendingOpenFile } from '@/app/document/io/pending-open'@@ -26,7 +31,8 @@ import {createTab,getActiveStore,getTabsSnapshot,- tabCount+ tabCount,+ type Tab} from '@/app/tabs'import { isTauri } from '@/app/tauri/env'import ColorSpaceBanner from '@/components/canvas/ColorSpaceBanner.vue'@@ -47,9 +53,22 @@ const shouldCreateHome =!appRuntimeConfig.test &&!route.meta.demo &&(isTauri() || appRuntimeConfig.recentFiles)+const { collaboration } = useI18n()+const joinRoomFromInput = useJoinRoom()++/** A share link opens its room in a tab of its own, so nothing editable shows before it. */+function openFirstTab(): Tab {+ const roomId = typeof route.params.roomId === 'string' ? route.params.roomId : null+ if (roomId) {+ if (joinRoomFromInput(roomId) && activeTab.value) return activeTab.value+ toast.error(collaboration.value.invalidRoomLink)+ }+ return shouldCreateHome ? createHomeTab() : createTab()+}+// Block-scoped so the view does not keep the first tab's store after that tab closes.{- const firstTab = activeTab.value ?? (shouldCreateHome ? createHomeTab() : createTab())+ const firstTab = activeTab.value ?? openFirstTab()if (createdInitialTab && route.meta.demo && !appRuntimeConfig.test) {void createDemoShapes(firstTab.store)}@@ -60,9 +79,10 @@ useKeyboard()useEditorMenu()useDocumentDrop()-const collab = useCollab(getActiveStore)+const collab = useCollab()provide(COLLAB_KEY, collab)-exposeCollaborationActions(collab)+exposeCollaborationActions(collab, joinRoomFromInput)+syncRoomRoute(router, route)useEventListener(document,@@ -74,6 +94,7 @@ useEventListener()const fileAssociationCleanup = ref<(() => void) | null>(null)+const roomLinksCleanup = ref<(() => void) | null>(null)/*** A drain that fails wholesale — the `take_pending_open` invoke, the event binding —@@ -156,6 +177,14 @@ onMounted(async () => {reportOpenFailure(error)}+ try {+ roomLinksCleanup.value = await bindDesktopRoomLinks((roomId) => {+ if (!joinRoomFromInput(roomId)) toast.error(collaboration.value.invalidRoomLink)+ })+ } catch (error) {+ console.error('[Room link]', error)+ }+// The browser twin of the deep link: the desktop build takes its links through the// deep-link plugin above, so only a real browser reads them off the address bar.if (IS_BROWSER && !isTauri()) {@@ -174,6 +203,7 @@ onUnmounted(() => {stopWebMCP?.()void stopMCPRuntime()fileAssociationCleanup.value?.()+ roomLinksCleanup.value?.()})</script>diff --git a/tests/app/collab/concurrent-edits.test.ts b/tests/app/collab/concurrent-edits.test.tsindex baf228e74..b6d034d7e 100644--- a/tests/app/collab/concurrent-edits.test.ts+++ b/tests/app/collab/concurrent-edits.test.ts@@ -1,9 +1,16 @@import { describe, expect, test } from 'bun:test'+import type * as Y from 'yjs'+import type { SceneGraph } from '@open-pencil/scene-graph'import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'-import { type SyncedStores, withSyncedStores } from '#tests/helpers/collab/synced-stores'+import {+ expectSameLayerTree,+ settleGraphSync,+ type SyncedStores,+ withSyncedStores+} from '#tests/helpers/collab/synced-stores'import { connectYDocs } from '#tests/helpers/yjs'/** Edit both peers while their documents are disconnected, then reconnect them. */@@ -13,12 +20,14 @@ async function withConcurrentEdits(check: (stores: SyncedStores, pageId: string) => void) {await withSyncedStores(- (stores) => {+ async (stores) => {const pageId = expectDefined(stores.hostStore.graph.getPages()[0], 'first page').idseed(stores.hostStore.graph, pageId)stores.hostSync.syncAllNodesToYjs()+ await settleGraphSync()expectDefined(stores.disconnectYDocs, 'connected peers to disconnect')()edit(stores, pageId)+ await settleGraphSync()const disconnect = connectYDocs(stores.hostDoc, stores.peerDoc)try {check(stores, pageId)@@ -30,6 +39,10 @@ async function withConcurrentEdits()}+function secondPageOf(graph: SceneGraph): string {+ return expectDefined(graph.getPages()[1], 'second page').id+}+describe('collab concurrent edits', () => {test('concurrent additions to one parent keep both nodes on both peers', async () => {await withConcurrentEdits(@@ -84,4 +97,192 @@ describe('collab concurrent edits', () => {})})+ test('concurrent additions to one parent converge on the same layer order', async () => {+ await withConcurrentEdits(+ (graph, pageId) => {+ graph.createNode('RECTANGLE', pageId, { id: 'seed:1' })+ },+ ({ hostStore, peerStore }, pageId) => {+ hostStore.graph.createNode('RECTANGLE', pageId, { id: 'host:1' })+ peerStore.graph.createNode('RECTANGLE', pageId, { id: 'peer:1' })+ },+ (stores, pageId) => {+ const layers = expectSameLayerTree(stores, [pageId])+ expect([...layers]).toEqual(expect.arrayContaining(['seed:1', 'host:1', 'peer:1']))+ }+ )+ })++ test('moving two layers into each other at once converges on one acyclic tree', async () => {+ await withConcurrentEdits(+ (graph, pageId) => {+ graph.createNode('FRAME', pageId, { id: 'frame:a' })+ graph.createNode('FRAME', pageId, { id: 'frame:b' })+ },+ ({ hostStore, peerStore }) => {+ hostStore.graph.reparentNode('frame:a', 'frame:b')+ peerStore.graph.reparentNode('frame:b', 'frame:a')+ },+ (stores, pageId) => {+ const layers = expectSameLayerTree(stores, [pageId])+ expect([...layers]).toEqual(expect.arrayContaining(['frame:a', 'frame:b']))+ // Both moves share a counter, so the move of the higher layer id is the one undone.+ const host = stores.hostStore.graph+ expect(getNodeOrThrow(host, 'frame:a').parentId).toBe('frame:b')+ expect(getNodeOrThrow(host, 'frame:b').parentId).toBe(pageId)+ }+ )+ })++ test('concurrent moves of one layer settle on one parent on both peers', async () => {+ await withConcurrentEdits(+ (graph, pageId) => {+ for (const id of ['frame:a', 'frame:b', 'rect:1']) {+ graph.createNode(id === 'rect:1' ? 'RECTANGLE' : 'FRAME', pageId, { id })+ }+ },+ ({ hostStore, peerStore }) => {+ hostStore.graph.reparentNode('rect:1', 'frame:a')+ peerStore.graph.reparentNode('rect:1', 'frame:b')+ },+ (stores, pageId) => {+ expectSameLayerTree(stores, [pageId])+ // Equal counters: the higher parent id wins.+ expect(getNodeOrThrow(stores.hostStore.graph, 'rect:1').parentId).toBe('frame:b')+ expect(getNodeOrThrow(stores.hostStore.graph, 'frame:a').childIds).toEqual([])+ }+ )+ })++ test('three layers moved into a loop by two peers drop only the latest move', async () => {+ await withConcurrentEdits(+ (graph, pageId) => {+ for (const id of ['frame:a', 'frame:b', 'frame:c'])+ graph.createNode('FRAME', pageId, { id })+ },+ ({ hostStore, peerStore }) => {+ hostStore.graph.reparentNode('frame:a', 'frame:b')+ peerStore.graph.reparentNode('frame:b', 'frame:c')+ peerStore.graph.reparentNode('frame:c', 'frame:a')+ },+ (stores, pageId) => {+ const layers = expectSameLayerTree(stores, [pageId])+ expect([...layers]).toEqual(expect.arrayContaining(['frame:a', 'frame:b', 'frame:c']))+ const host = stores.hostStore.graph+ expect(getNodeOrThrow(host, 'frame:a').parentId).toBe('frame:b')+ expect(getNodeOrThrow(host, 'frame:b').parentId).toBe('frame:c')+ expect(getNodeOrThrow(host, 'frame:c').parentId).toBe(pageId)+ }+ )+ })++ test('a layer moved into a parent deleted at the same time returns to its previous parent', async () => {+ await withConcurrentEdits(+ (graph, pageId) => {+ graph.createNode('FRAME', pageId, { id: 'frame:1' })+ graph.createNode('FRAME', pageId, { id: 'frame:2' })+ graph.createNode('RECTANGLE', 'frame:1', { id: 'rect:1' })+ },+ ({ hostStore, peerStore }) => {+ hostStore.graph.reparentNode('rect:1', 'frame:2')+ peerStore.graph.deleteNode('frame:2')+ },+ (stores, pageId) => {+ expectSameLayerTree(stores, [pageId])+ for (const graph of [stores.hostStore.graph, stores.peerStore.graph]) {+ expect(graph.getNode('frame:2')).toBeUndefined()+ expect(getNodeOrThrow(graph, 'rect:1').parentId).toBe('frame:1')+ }+ }+ )+ })++ test('a layer whose parents were all deleted goes back to its own page', async () => {+ await withConcurrentEdits(+ (graph) => {+ graph.addPage('Second')+ graph.createNode('FRAME', secondPageOf(graph), { id: 'frame:1' })+ },+ ({ hostStore, peerStore }) => {+ hostStore.graph.createNode('RECTANGLE', 'frame:1', { id: 'rect:1' })+ peerStore.graph.deleteNode('frame:1')+ },+ (stores, pageId) => {+ const secondPageId = secondPageOf(stores.hostStore.graph)+ expectSameLayerTree(stores, [pageId, secondPageId])+ for (const graph of [stores.hostStore.graph, stores.peerStore.graph]) {+ expect(getNodeOrThrow(graph, 'rect:1').parentId).toBe(secondPageId)+ }+ }+ )+ })++ test('inserts at the same spot keep both layers in one order with distinct keys', async () => {+ await withConcurrentEdits(+ (graph, pageId) => {+ graph.createNode('RECTANGLE', pageId, { id: 'rect:1' })+ graph.createNode('RECTANGLE', pageId, { id: 'rect:2' })+ },+ ({ hostStore, peerStore }, pageId) => {+ const host = hostStore.graph.createNode('RECTANGLE', pageId, { id: 'host:1' })+ hostStore.graph.reorderChild(host.id, pageId, 1)+ const peer = peerStore.graph.createNode('RECTANGLE', pageId, { id: 'peer:1' })+ peerStore.graph.reorderChild(peer.id, pageId, 1)+ },+ (stores, pageId) => {+ expectSameLayerTree(stores, [pageId])+ const order = getNodeOrThrow(stores.hostStore.graph, pageId).childIds+ expect(order[0]).toBe('rect:1')+ expect(order[3]).toBe('rect:2')+ expect(order.slice(1, 3)).toEqual(expect.arrayContaining(['host:1', 'peer:1']))+ const ynodes = stores.hostDoc.getMap<Y.Map<unknown>>('nodes')+ const keys = order.map((id) => ynodes.get(id)?.get('orderKey'))+ expect(new Set(keys).size).toBe(4)+ }+ )+ })++ test('concurrent reorders of one parent converge on one order', async () => {+ await withConcurrentEdits(+ (graph, pageId) => {+ for (const id of ['rect:1', 'rect:2', 'rect:3', 'rect:4']) {+ graph.createNode('RECTANGLE', pageId, { id })+ }+ },+ ({ hostStore, peerStore }, pageId) => {+ hostStore.graph.reorderChild('rect:4', pageId, 0)+ peerStore.graph.reorderChild('rect:1', pageId, 3)+ peerStore.graph.reorderChild('rect:4', pageId, 2)+ },+ (stores, pageId) => {+ const layers = expectSameLayerTree(stores, [pageId])+ expect([...layers]).toEqual(+ expect.arrayContaining(['rect:1', 'rect:2', 'rect:3', 'rect:4'])+ )+ }+ )+ })++ test('a layer kept out of a loop stays put when the other layer moves away', async () => {+ await withConcurrentEdits(+ (graph, pageId) => {+ graph.createNode('FRAME', pageId, { id: 'frame:a' })+ graph.createNode('FRAME', pageId, { id: 'frame:b' })+ },+ ({ hostStore, peerStore }) => {+ hostStore.graph.reparentNode('frame:a', 'frame:b')+ peerStore.graph.reparentNode('frame:b', 'frame:a')+ },+ (stores, pageId) => {+ const host = stores.hostStore.graph+ expect(getNodeOrThrow(host, 'frame:b').parentId).toBe(pageId)+ // frame:b's newest entry is frame:a; moving frame:a out of frame:b must not revive it.+ host.reparentNode('frame:a', pageId)+ stores.hostSync.syncNodeToYjs('frame:a')+ expectSameLayerTree(stores, [pageId])+ expect(getNodeOrThrow(host, 'frame:b').parentId).toBe(pageId)+ expect(getNodeOrThrow(stores.peerStore.graph, 'frame:b').parentId).toBe(pageId)+ }+ )+ })})diff --git a/tests/app/collab/graph-binding.test.ts b/tests/app/collab/graph-binding.test.tsnew file mode 100644index 000000000..10d3c0235--- /dev/null+++ b/tests/app/collab/graph-binding.test.ts@@ -0,0 +1,31 @@+import { describe, expect, test } from 'bun:test'++import type * as Y from 'yjs'++import { bindCollabGraphEvents } from '@/app/collab/yjs-sync'++import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'+import { settleGraphSync, withSyncedStores } from '#tests/helpers/collab/synced-stores'++describe('collab graph binding', () => {+ test('an edit made just before leaving still reaches the room', async () => {+ await withSyncedStores(async (stores) => {+ const { hostStore, peerStore, hostSync, hostDoc } = stores+ hostSync.syncAllNodesToYjs()+ await settleGraphSync()+ const unbind = bindCollabGraphEvents({+ store: hostStore,+ getYdoc: () => hostDoc,+ getYnodes: () => hostDoc.getMap<Y.Map<unknown>>('nodes'),+ getSuppressGraphSync: () => stores.hostSuppressGraphSync,+ syncLocalEdit: hostSync.syncLocalEdit+ })+ const pageId = expectDefined(hostStore.graph.getPages()[0], 'first page').id+ hostStore.graph.createNode('RECTANGLE', pageId, { id: 'rect:1' })+ // Leaving before the edit's batch is written, as disconnecting can.+ unbind()+ await settleGraphSync()+ expect(getNodeOrThrow(peerStore.graph, 'rect:1').parentId).toBe(pageId)+ })+ })+})diff --git a/tests/app/collab/guest-name.test.ts b/tests/app/collab/guest-name.test.tsnew file mode 100644index 000000000..35fbceea6--- /dev/null+++ b/tests/app/collab/guest-name.test.ts@@ -0,0 +1,14 @@+import { describe, expect, test } from 'bun:test'++import { generateGuestName } from '@/app/collab/guest-name'++describe('guest names', () => {+ test('pairs a color with an animal', () => {+ expect(generateGuestName(() => 0)).toBe('Amber Badger')+ expect(generateGuestName((length) => length - 1)).toBe('Violet Wombat')+ })++ test('picks from the whole word lists', () => {+ expect(generateGuestName()).toMatch(/^[A-Z][a-z]+ [A-Z][a-z]+$/)+ })+})diff --git a/tests/app/collab/random-edits.test.ts b/tests/app/collab/random-edits.test.tsnew file mode 100644index 000000000..564e62983--- /dev/null+++ b/tests/app/collab/random-edits.test.ts@@ -0,0 +1,87 @@+import { describe, expect, test } from 'bun:test'++import { create as createPRNG, oneOf, real53, type PRNG } from 'lib0/prng'+import { TestConnector, type TestYInstance } from 'yjs/testHelper'++import type { SceneGraph } from '@open-pencil/scene-graph'++import { expectDefined } from '#tests/helpers/assert'+import {+ expectSameLayerTree,+ settleGraphSync,+ withSyncedStores+} from '#tests/helpers/collab/synced-stores'++/** Layers under the page. */+function layersUnder(graph: SceneGraph, pageId: string): string[] {+ return graph.flattenTree(pageId).map((entry) => entry.node.id)+}++/** One random layer edit on a peer, as its user would make it through the graph. */+function randomEdit(random: PRNG, graph: SceneGraph, pageId: string, nextId: () => string) {+ const layers = layersUnder(graph, pageId)+ const frames = [pageId, ...layers.filter((id) => graph.getNode(id)?.type === 'FRAME')]+ const roll = real53(random)+ if (layers.length < 4 || roll < 0.25) {+ graph.createNode(real53(random) < 0.5 ? 'FRAME' : 'RECTANGLE', oneOf(random, frames), {+ id: nextId()+ })+ return+ }+ const id = oneOf(random, layers)+ if (roll < 0.3) {+ graph.deleteNode(id)+ } else if (roll < 0.65) {+ // reparentNode refuses a move into the layer's own subtree, as the editor does.+ graph.reparentNode(id, oneOf(random, frames))+ } else {+ const parentId = expectDefined(graph.getNode(id)?.parentId, 'parent of a layer')+ const siblings = graph.getNode(parentId)?.childIds.length ?? 1+ graph.reorderChild(id, parentId, Math.floor(real53(random) * siblings))+ }+}++describe('collab random concurrent edits', () => {+ for (const seed of [11, 23, 37, 41, 59, 67, 73, 89]) {+ test(`peers converge on one layer tree through the Yjs test connector (seed ${seed})`, async () => {+ const random = createPRNG(seed)+ const connector = new TestConnector(createPRNG(seed))+ const hostDoc: TestYInstance = connector.createY(1)+ const peerDoc: TestYInstance = connector.createY(2)+ connector.syncAll()++ await withSyncedStores(+ async (stores) => {+ const { hostStore, peerStore } = stores+ const pageId = expectDefined(hostStore.graph.getPages()[0], 'first page').id+ stores.hostSync.syncAllNodesToYjs()+ connector.flushAllMessages()+ let counter = 0+ const idFor = (prefix: string) => () => `${prefix}:${++counter}`++ for (let round = 0; round < 6; round++) {+ hostDoc.disconnect()+ peerDoc.disconnect()+ for (let step = 0; step < 8; step++) {+ randomEdit(random, hostStore.graph, pageId, idFor('host'))+ await settleGraphSync()+ randomEdit(random, peerStore.graph, pageId, idFor('peer'))+ await settleGraphSync()+ }+ hostDoc.connect()+ peerDoc.connect()+ while (connector.flushRandomMessage()) await settleGraphSync()+ await settleGraphSync()++ const layers = expectSameLayerTree(stores, [pageId])+ layers.delete(pageId)+ for (const graph of [hostStore.graph, peerStore.graph]) {+ expect([...layers].sort()).toEqual(layersUnder(graph, pageId).sort())+ }+ }+ },+ { hostDoc, peerDoc, connectImmediately: false, bindGraphEvents: true }+ )+ })+ }+})diff --git a/tests/app/collab/room/id.test.ts b/tests/app/collab/room/id.test.tsnew file mode 100644index 000000000..5542bc082--- /dev/null+++ b/tests/app/collab/room/id.test.ts@@ -0,0 +1,34 @@+import { describe, expect, test } from 'bun:test'++import { parseRoomInput } from '@/app/collab/room/id'++const ROOM = 'abcdefghijklmnopqrstuvwxyz012345'++describe('room links and IDs', () => {+ test('reads the room ID from a bare ID or a share link, whatever surrounds it', () => {+ for (const input of [+ ROOM,+ ` ${ROOM} `,+ `https://app.openpencil.dev/share/${ROOM}`,+ `https://app.openpencil.dev/share/${ROOM}/`,+ `https://app.openpencil.dev/share/${ROOM}?test#layers`,+ `open-pencil.localhost/share/${ROOM}#x`+ ]) {+ expect(parseRoomInput(input)).toBe(ROOM)+ }+ })++ test('refuses text that is not a room ID, so it never joins a room nobody shared', () => {+ for (const input of [+ '',+ 'e2e-collaboration-room',+ ROOM.slice(1),+ `${ROOM}0`,+ ROOM.toUpperCase(),+ `https://app.openpencil.dev/share/${ROOM.slice(0, 31)}!`,+ `https://app.openpencil.dev/demo`+ ]) {+ expect(parseRoomInput(input)).toBeNull()+ }+ })+})diff --git a/tests/app/collab/room/status.test.ts b/tests/app/collab/room/status.test.tsnew file mode 100644index 000000000..c1beec635--- /dev/null+++ b/tests/app/collab/room/status.test.ts@@ -0,0 +1,51 @@+import { describe, expect, test } from 'bun:test'++import { deriveRoomStatus, type RoomStatusInput } from '@/app/collab/room/status'++const DISCOVERY_MS = 12_000+const UNREACHABLE_MS = 20_000++const base: RoomStatusInput = {+ hasDocument: false,+ savedCopyLoaded: true,+ openFor: 0,+ connectedFor: null,+ discoveryMs: DISCOVERY_MS,+ unreachableMs: UNREACHABLE_MS,+ peerCount: 0,+ peersWithFile: 0+}++describe('room tab status', () => {+ test('connects while the saved copy loads and until the signaling service answers', () => {+ expect(deriveRoomStatus({ ...base, savedCopyLoaded: false, connectedFor: 30_000 })).toBe(+ 'connecting'+ )+ expect(deriveRoomStatus({ ...base, openFor: UNREACHABLE_MS - 1 })).toBe('connecting')+ })++ test('says the room cannot be reached when the signaling service never answers', () => {+ expect(deriveRoomStatus({ ...base, openFor: UNREACHABLE_MS })).toBe('unreachable')+ })++ test('looks for people until everyone already in the room has had time to meet this peer', () => {+ expect(deriveRoomStatus({ ...base, openFor: 30_000, connectedFor: 0 })).toBe('looking')+ expect(deriveRoomStatus({ ...base, connectedFor: DISCOVERY_MS - 1 })).toBe('looking')+ })++ test('waits once nobody who has the file showed up, even with other guests here', () => {+ expect(deriveRoomStatus({ ...base, connectedFor: DISCOVERY_MS })).toBe('waiting')+ expect(deriveRoomStatus({ ...base, connectedFor: DISCOVERY_MS, peerCount: 2 })).toBe('waiting')+ })++ test('receives the file as soon as someone who has it is here, however long it takes', () => {+ const withSharer = { ...base, peerCount: 1, peersWithFile: 1 }+ expect(deriveRoomStatus({ ...withSharer, connectedFor: 0 })).toBe('receiving')+ expect(deriveRoomStatus({ ...withSharer, connectedFor: DISCOVERY_MS * 3 })).toBe('receiving')+ })++ test('shows the file live with others, and alone from the saved copy', () => {+ expect(deriveRoomStatus({ ...base, hasDocument: true, peerCount: 2 })).toBe('live')+ expect(deriveRoomStatus({ ...base, hasDocument: true })).toBe('alone')+ })+})diff --git a/tests/app/collab/session.test.ts b/tests/app/collab/session.test.tsnew file mode 100644index 000000000..4f24eb9b4--- /dev/null+++ b/tests/app/collab/session.test.ts@@ -0,0 +1,165 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'++import { openRoomSession, type RoomSession, type RoomSessionOptions } from '@/app/collab/session'+import { createEditorStore, type EditorStore } from '@/app/editor/session'+import { presenceOf } from '@/app/presence/registry'++import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'+import { createMemoryRooms } from '#tests/helpers/collab/memory-transport'++const ROOM_A = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'+const ROOM_B = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'++const noSavedCopy = () => ({ whenSynced: Promise.resolve(), destroy: () => undefined })++async function withRooms(+ run: (+ open: (options: Omit<RoomSessionOptions, 'joinRoom'>) => RoomSession,+ settle: () => Promise<void>+ ) => Promise<void>+) {+ const rooms = createMemoryRooms()+ const sessions: RoomSession[] = []+ const stores: EditorStore[] = []+ try {+ await run((options) => {+ stores.push(options.store)+ const session = openRoomSession({+ openSavedCopy: noSavedCopy,+ ...options,+ joinRoom: rooms.join+ })+ sessions.push(session)+ return session+ }, rooms.settle)+ } finally {+ for (const session of sessions) session.dispose()+ for (const store of stores) store.preparationController.dispose()+ }+}++function newStore(name = 'Untitled') {+ const store = createEditorStore(new SceneGraph())+ store.state.documentName = name+ return store+}++function firstPageId(store: EditorStore) {+ return expectDefined(store.graph.getPages()[0], 'first page').id+}++describe('room sessions', () => {+ test("a joined tab shows the sharer's document, with its name, once it arrives", async () => {+ await withRooms(async (open, settle) => {+ const host = newStore('Checkout flow')+ host.graph.createNode('RECTANGLE', firstPageId(host), { id: 'host:1', name: 'Card' })+ const shared = open({ roomId: ROOM_A, store: host, origin: 'shared' })+ shared.shareDocument()+ const guest = newStore('Shared file')+ const joined = open({ roomId: ROOM_A, store: guest, origin: 'joined' })+ expect(joined.status.value).toBe('connecting')++ await settle()+ expect(joined.status.value).toBe('live')+ expect(shared.status.value).toBe('live')+ expect(guest.graph.rootId).toBe(host.graph.rootId)+ expect(getNodeOrThrow(guest.graph, 'host:1').name).toBe('Card')+ expect(guest.state.documentName).toBe('Checkout flow')+ })+ })++ test('a room nobody with the document is in waits, then opens when the sharer comes', async () => {+ await withRooms(async (open, settle) => {+ const guest = newStore()+ const joined = open({ roomId: ROOM_A, store: guest, origin: 'joined' })+ await settle()+ expect(joined.status.value).toBe('waiting')+ expect(joined.hasDocument.value).toBe(false)++ const host = newStore('Late')+ open({ roomId: ROOM_A, store: host, origin: 'shared' }).shareDocument()+ await settle()+ expect(joined.status.value).toBe('live')+ expect(guest.graph.rootId).toBe(host.graph.rootId)+ })+ })++ test('two rooms in two tabs stay apart: edits and cursors reach only their own room', async () => {+ await withRooms(async (open, settle) => {+ const hostA = newStore('A')+ const hostB = newStore('B')+ const roomA = open({ roomId: ROOM_A, store: hostA, origin: 'shared' })+ const roomB = open({ roomId: ROOM_B, store: hostB, origin: 'shared' })+ roomA.shareDocument()+ roomB.shareDocument()+ const guestA = newStore()+ const guestB = newStore()+ const joinedA = open({ roomId: ROOM_A, store: guestA, origin: 'joined' })+ const joinedB = open({ roomId: ROOM_B, store: guestB, origin: 'joined' })+ await settle()++ guestA.graph.createNode('RECTANGLE', firstPageId(guestA), { id: 'guest:a' })+ joinedA.updateCursor(10, 20, firstPageId(guestA))+ await settle()++ expect(hostA.graph.getNode('guest:a')).toBeDefined()+ expect(hostB.graph.getNode('guest:a')).toBeUndefined()+ expect(guestB.graph.getNode('guest:a')).toBeUndefined()+ expect(roomA.peers.value.map((peer) => peer.cursor?.x)).toEqual([10])+ expect(roomB.peers.value.map((peer) => peer.cursor)).toEqual([undefined])+ expect(joinedB.status.value).toBe('live')+ })+ })++ test('an edit in a tab whose room has no document yet stays in that tab', async () => {+ await withRooms(async (open, settle) => {+ const guest = newStore()+ open({ roomId: ROOM_A, store: guest, origin: 'joined' })+ guest.graph.createNode('RECTANGLE', firstPageId(guest), { id: 'early' })+ await settle()++ const host = newStore()+ open({ roomId: ROOM_A, store: host, origin: 'shared' }).shareDocument()+ await settle()+ expect(host.graph.getNode('early')).toBeUndefined()+ })+ })++ test('peers say whether they have the file, so a newcomer knows whom it is waiting for', async () => {+ await withRooms(async (open, settle) => {+ const host = newStore('Shared')+ open({ roomId: ROOM_A, store: host, origin: 'shared' }).shareDocument()+ const early = open({ roomId: ROOM_B, store: newStore(), origin: 'joined' })+ const other = open({ roomId: ROOM_B, store: newStore(), origin: 'joined' })+ const guest = open({ roomId: ROOM_A, store: newStore(), origin: 'joined' })+ await settle()++ expect(guest.peers.value.map((peer) => peer.hasFile)).toEqual([true])+ expect(early.peers.value.map((peer) => peer.hasFile)).toEqual([false])+ expect(early.status.value).toBe('waiting')+ expect(other.status.value).toBe('waiting')+ })+ })++ test('a room a tab has left no longer changes that tab or its people', async () => {+ await withRooms(async (open, settle) => {+ const host = newStore('Shared')+ const shared = open({ roomId: ROOM_A, store: host, origin: 'shared' })+ shared.shareDocument()+ const guest = newStore()+ const joined = open({ roomId: ROOM_A, store: guest, origin: 'joined' })+ await settle()+ expect(joined.peers.value).toHaveLength(1)++ joined.dispose()+ host.graph.createNode('RECTANGLE', firstPageId(host), { id: 'after-leave' })+ shared.updateCursor(10, 10, firstPageId(host))+ await settle()+ expect(guest.graph.getNode('after-leave')).toBeUndefined()+ expect(joined.peers.value).toEqual([])+ expect(presenceOf(guest).peers.value).toEqual([])+ })+ })+})diff --git a/tests/app/collab/shared-tree/fields.test.ts b/tests/app/collab/shared-tree/fields.test.tsnew file mode 100644index 000000000..d4a88829b--- /dev/null+++ b/tests/app/collab/shared-tree/fields.test.ts@@ -0,0 +1,27 @@+import { describe, expect, test } from 'bun:test'++import * as Y from 'yjs'++import { claimRoot, readRoot } from '@/app/collab/shared-tree/fields'++function meta(): Y.Map<unknown> {+ return new Y.Doc().getMap('meta')+}++describe('collab room root', () => {+ test('the first claim sets the root and later claims leave it', () => {+ const claims = meta()+ expect(readRoot(claims)).toBeUndefined()+ claimRoot(claims, 'z')+ claimRoot(claims, 'a')+ expect(readRoot(claims)).toBe('z')+ })++ test('a malformed root is ignored and replaced by the next claim', () => {+ const claims = meta()+ claims.set('root', 7)+ expect(readRoot(claims)).toBeUndefined()+ claimRoot(claims, 'a')+ expect(readRoot(claims)).toBe('a')+ })+})diff --git a/tests/app/collab/shared-tree/migration.test.ts b/tests/app/collab/shared-tree/migration.test.tsnew file mode 100644index 000000000..05ebc3ae0--- /dev/null+++ b/tests/app/collab/shared-tree/migration.test.ts@@ -0,0 +1,167 @@+import { describe, expect, test } from 'bun:test'++import * as Y from 'yjs'++import { SceneGraph } from '@open-pencil/scene-graph'++import { encodeNodeForYjs } from '@/app/collab/node-codec'+import {+ claimRoot,+ readOrderKey,+ readPage,+ readParentEntries,+ readRoot,+ TREE_FORMAT+} from '@/app/collab/shared-tree/fields'+import { migrateLegacyLayers } from '@/app/collab/shared-tree/migration'++import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'+import {+ expectSameLayerTree,+ settleGraphSync,+ type SyncedStores,+ withSyncedStores+} from '#tests/helpers/collab/synced-stores'+import { connectYDocs } from '#tests/helpers/yjs'++/** A document as format 1 wrote it: each layer's map holds its parentId and childIds. */+function legacyDocument(): { update: Uint8Array; graph: SceneGraph; pageId: string } {+ const graph = new SceneGraph()+ const pageId = expectDefined(graph.getPages()[0], 'first page').id+ graph.createNode('FRAME', pageId, { id: 'frame:1' })+ graph.createNode('RECTANGLE', 'frame:1', { id: 'rect:2' })+ graph.createNode('RECTANGLE', 'frame:1', { id: 'rect:1' })+ graph.createNode('RECTANGLE', pageId, { id: 'rect:3' })+ graph.reorderChild('rect:3', pageId, 0)++ const doc = new Y.Doc()+ const ynodes = doc.getMap<Y.Map<unknown>>('nodes')+ doc.transact(() => {+ for (const node of graph.getAllNodes()) {+ const ynode = new Y.Map<unknown>()+ ynodes.set(node.id, ynode)+ for (const [key, value] of Object.entries(encodeNodeForYjs(node))) ynode.set(key, value)+ ynode.set('parentId', node.parentId)+ ynode.set('childIds', [...node.childIds])+ }+ })+ const update = Y.encodeStateAsUpdate(doc)+ doc.destroy()+ return { update, graph, pageId }+}++function expectMatchesLegacy(graph: SceneGraph, legacy: SceneGraph) {+ for (const node of legacy.getAllNodes()) {+ const synced = getNodeOrThrow(graph, node.id)+ expect(synced.parentId).toBe(node.parentId)+ expect(synced.childIds).toEqual(node.childIds)+ }+}++function sharedTreeFields(doc: Y.Doc) {+ const fields: Record<string, unknown> = {}+ for (const [id, ynode] of doc.getMap<Y.Map<unknown>>('nodes')) {+ fields[id] = {+ parents: Object.fromEntries(readParentEntries(ynode) ?? []),+ orderKey: readOrderKey(ynode),+ page: readPage(ynode),+ legacy: ynode.has('parentId') || ynode.has('childIds')+ }+ }+ return fields+}++async function withLegacyRoom(run: (stores: SyncedStores) => void | Promise<void>) {+ await withSyncedStores(run, { connectImmediately: false })+}++describe('collab tree format migration', () => {+ test('opening a format 1 document converts its tree and keeps it', async () => {+ const legacy = legacyDocument()+ await withLegacyRoom(({ hostStore, hostDoc }) => {+ Y.applyUpdate(hostDoc, legacy.update)++ expectMatchesLegacy(hostStore.graph, legacy.graph)+ expect(hostStore.graph.rootId).toBe(legacy.graph.rootId)+ expect(readRoot(hostDoc.getMap('meta'))).toBe(legacy.graph.rootId)+ expect(hostDoc.getMap('meta').get('treeFormat')).toBe(TREE_FORMAT)+ const fields = sharedTreeFields(hostDoc)+ expect(fields['rect:2']).toMatchObject({+ parents: { 'frame:1': 0 },+ page: legacy.pageId,+ legacy: false+ })+ expect(fields['rect:3']).toMatchObject({ page: legacy.pageId })+ expect(fields[legacy.pageId]).toMatchObject({ page: undefined })+ expect(fields[legacy.graph.rootId]).toMatchObject({ parents: {}, legacy: false })+ const first = expectDefined(readOrderKey(getYnode(hostDoc, 'rect:2')), 'first key')+ const second = expectDefined(readOrderKey(getYnode(hostDoc, 'rect:1')), 'second key')+ expect(first < second).toBe(true)+ })+ })++ test('two peers converting the same document at once write the same tree', async () => {+ const legacy = legacyDocument()+ await withLegacyRoom(async (stores) => {+ const { hostStore, peerStore, hostDoc, peerDoc } = stores+ Y.applyUpdate(hostDoc, legacy.update)+ Y.applyUpdate(peerDoc, legacy.update)+ expect(sharedTreeFields(peerDoc)).toEqual(sharedTreeFields(hostDoc))++ const disconnect = connectYDocs(hostDoc, peerDoc)+ try {+ await settleGraphSync()+ expectSameLayerTree(stores, [legacy.pageId])+ expectMatchesLegacy(hostStore.graph, legacy.graph)+ expectMatchesLegacy(peerStore.graph, legacy.graph)+ } finally {+ disconnect()+ }+ })+ })++ test('a converted layer moves like any other', async () => {+ const legacy = legacyDocument()+ await withSyncedStores(+ async (stores) => {+ const { hostStore, peerStore, hostDoc } = stores+ Y.applyUpdate(hostDoc, legacy.update)+ hostStore.graph.reparentNode('rect:3', 'frame:1')+ await settleGraphSync()+ expect(getNodeOrThrow(peerStore.graph, 'rect:3').parentId).toBe('frame:1')+ expectSameLayerTree(stores, [legacy.pageId])+ },+ { bindGraphEvents: true }+ )+ })++ test('converting an already converted document writes nothing', async () => {+ const legacy = legacyDocument()+ await withLegacyRoom(({ hostDoc }) => {+ Y.applyUpdate(hostDoc, legacy.update)+ let updates = 0+ const count = () => updates+++ hostDoc.on('update', count)+ const ynodes = hostDoc.getMap<Y.Map<unknown>>('nodes')+ const migrated = migrateLegacyLayers(hostDoc, ynodes, hostDoc.getMap('meta'), ynodes.keys())+ hostDoc.off('update', count)+ expect(migrated).toEqual([])+ expect(updates).toBe(0)+ })+ })++ test('converting a room keeps a root already shared into it', () => {+ const legacy = legacyDocument()+ const doc = new Y.Doc()+ const meta = doc.getMap('meta')+ claimRoot(meta, 'shared-root')+ Y.applyUpdate(doc, legacy.update)+ const ynodes = doc.getMap<Y.Map<unknown>>('nodes')+ migrateLegacyLayers(doc, ynodes, meta, ynodes.keys())+ expect(readRoot(meta)).toBe('shared-root')+ })+})++function getYnode(doc: Y.Doc, id: string): Y.Map<unknown> {+ return expectDefined(doc.getMap<Y.Map<unknown>>('nodes').get(id), `ynode ${id}`)+}diff --git a/tests/app/collab/shared-tree/sync.test.ts b/tests/app/collab/shared-tree/sync.test.tsnew file mode 100644index 000000000..850945417--- /dev/null+++ b/tests/app/collab/shared-tree/sync.test.ts@@ -0,0 +1,274 @@+import { describe, expect, test } from 'bun:test'++import type * as Y from 'yjs'++import { captureGraphCheckpoint } from '@open-pencil/scene-graph'++import { readPage } from '@/app/collab/shared-tree/fields'++import { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'+import {+ expectSameLayerTree,+ settleGraphSync,+ type SyncedStores,+ withSyncedStores+} from '#tests/helpers/collab/synced-stores'+import { connectYDocs } from '#tests/helpers/yjs'++/** Seeds layers on the host page, syncs them, and runs a live edit on connected peers. */+async function withLiveEdit(+ seed: (stores: SyncedStores, pageId: string) => void,+ edit: (stores: SyncedStores, pageId: string) => void,+ check: (stores: SyncedStores, pageId: string) => void+) {+ await withSyncedStores(+ async (stores) => {+ const pageId = expectDefined(stores.hostStore.graph.getPages()[0], 'first page').id+ seed(stores, pageId)+ stores.hostSync.syncAllNodesToYjs()+ await settleGraphSync()+ edit(stores, pageId)+ await settleGraphSync()+ check(stores, pageId)+ },+ { bindGraphEvents: true }+ )+}++describe('collab layer tree', () => {+ test('moving a layer updates both parents on the other peer', async () => {+ await withLiveEdit(+ ({ hostStore }, pageId) => {+ hostStore.graph.createNode('FRAME', pageId, { id: 'frame:1' })+ hostStore.graph.createNode('RECTANGLE', pageId, { id: 'rect:1' })+ },+ ({ hostStore }) => {+ hostStore.graph.reparentNode('rect:1', 'frame:1')+ },+ (stores, pageId) => {+ const peer = stores.peerStore.graph+ expect(getNodeOrThrow(peer, pageId).childIds).not.toContain('rect:1')+ expect(getNodeOrThrow(peer, 'frame:1').childIds).toEqual(['rect:1'])+ expectSameLayerTree(stores, [pageId])+ }+ )+ })++ test('reordering layers within a parent syncs their order', async () => {+ await withLiveEdit(+ ({ hostStore }, pageId) => {+ for (const id of ['rect:1', 'rect:2', 'rect:3']) {+ hostStore.graph.createNode('RECTANGLE', pageId, { id })+ }+ },+ ({ hostStore }, pageId) => {+ hostStore.graph.reorderChild('rect:3', pageId, 0)+ },+ (stores, pageId) => {+ expect(getNodeOrThrow(stores.peerStore.graph, pageId).childIds).toEqual([+ 'rect:3',+ 'rect:1',+ 'rect:2'+ ])+ expectSameLayerTree(stores, [pageId])+ }+ )+ })++ test('layers created on the peer keep their order on the host', async () => {+ await withLiveEdit(+ () => undefined,+ ({ peerStore }, pageId) => {+ for (const id of ['rect:3', 'rect:1', 'rect:2']) {+ peerStore.graph.createNode('RECTANGLE', pageId, { id })+ }+ },+ (stores, pageId) => {+ expect(getNodeOrThrow(stores.hostStore.graph, pageId).childIds).toEqual([+ 'rect:3',+ 'rect:1',+ 'rect:2'+ ])+ expectSameLayerTree(stores, [pageId])+ }+ )+ })++ test('undo and redo of a move reach the other peer', async () => {+ await withSyncedStores(+ async (stores) => {+ const { hostStore, peerStore } = stores+ const pageId = expectDefined(hostStore.graph.getPages()[0], 'first page').id+ hostStore.graph.createNode('FRAME', pageId, { id: 'frame:1' })+ hostStore.graph.createNode('RECTANGLE', pageId, { id: 'rect:1' })+ hostStore.graph.createNode('RECTANGLE', pageId, { id: 'rect:2' })+ stores.hostSync.syncAllNodesToYjs()+ await settleGraphSync()++ hostStore.reorderChildWithUndo('rect:1', 'frame:1', 0)+ await settleGraphSync()+ hostStore.undoAction()+ await settleGraphSync()+ expect(getNodeOrThrow(peerStore.graph, 'rect:1').parentId).toBe(pageId)+ expect(getNodeOrThrow(peerStore.graph, pageId).childIds).toEqual([+ 'frame:1',+ 'rect:1',+ 'rect:2'+ ])++ hostStore.redoAction()+ await settleGraphSync()+ expect(getNodeOrThrow(peerStore.graph, 'rect:1').parentId).toBe('frame:1')+ expectSameLayerTree(stores, [pageId])+ },+ { bindGraphEvents: true }+ )+ })++ test('a checkpoint rollback moves restored layers back on the other peer', async () => {+ await withSyncedStores(+ async (stores) => {+ const { hostStore, peerStore } = stores+ const pageId = expectDefined(hostStore.graph.getPages()[0], 'first page').id+ hostStore.graph.createNode('FRAME', pageId, { id: 'frame:1' })+ hostStore.graph.createNode('RECTANGLE', pageId, { id: 'rect:1' })+ hostStore.graph.createNode('RECTANGLE', pageId, { id: 'rect:2' })+ stores.hostSync.syncAllNodesToYjs()+ await settleGraphSync()++ const checkpoint = captureGraphCheckpoint(hostStore.graph)+ hostStore.graph.reparentNode('rect:1', 'frame:1')+ hostStore.graph.reorderChild('rect:2', pageId, 0)+ await settleGraphSync()+ expect(getNodeOrThrow(peerStore.graph, 'rect:1').parentId).toBe('frame:1')++ // The restore assigns parentId and childIds directly and reports them as updates.+ checkpoint.restore()+ await settleGraphSync()+ expect(getNodeOrThrow(peerStore.graph, 'rect:1').parentId).toBe(pageId)+ expect(getNodeOrThrow(peerStore.graph, pageId).childIds).toEqual([+ 'frame:1',+ 'rect:1',+ 'rect:2'+ ])+ expectSameLayerTree(stores, [pageId])+ },+ { bindGraphEvents: true }+ )+ })++ test('an edit that moves several layers sends one update', async () => {+ await withSyncedStores(+ async (stores) => {+ const { hostStore, peerStore, hostDoc } = stores+ const pageId = expectDefined(hostStore.graph.getPages()[0], 'first page').id+ hostStore.graph.createNode('FRAME', pageId, { id: 'frame:1' })+ for (const id of ['rect:1', 'rect:2', 'rect:3']) {+ hostStore.graph.createNode('RECTANGLE', pageId, { id })+ }+ stores.hostSync.syncAllNodesToYjs()+ await settleGraphSync()++ let updates = 0+ const count = () => updates+++ hostDoc.on('update', count)+ try {+ hostStore.reparentNodes(['rect:1', 'rect:2', 'rect:3'], 'frame:1')+ await settleGraphSync()+ } finally {+ hostDoc.off('update', count)+ }+ expect(updates).toBe(1)+ expect(getNodeOrThrow(peerStore.graph, 'frame:1').childIds).toEqual([+ 'rect:1',+ 'rect:2',+ 'rect:3'+ ])+ },+ { bindGraphEvents: true }+ )+ })++ test("a joiner's edit to its own earlier document leaves the room's pages alone", async () => {+ await withSyncedStores(+ async ({ hostStore, peerStore, hostSync }) => {+ const peerOwnPage = expectDefined(peerStore.graph.getPages()[0], 'peer page').id+ const hostRoot = hostStore.graph.rootId+ const hostPages = hostStore.graph.getPages().map((page) => page.id)+ hostSync.syncAllNodesToYjs()+ await settleGraphSync()+ expect(peerStore.graph.rootId).toBe(hostRoot)++ // An undo of an edit made before joining can still reach the joiner's own page.+ peerStore.graph.createNode('RECTANGLE', peerOwnPage, { id: 'rect:1' })+ await settleGraphSync()+ for (const graph of [hostStore.graph, peerStore.graph]) {+ expect(graph.rootId).toBe(hostRoot)+ expect(graph.getPages().map((page) => page.id)).toEqual(hostPages)+ }+ expect(hostStore.graph.getNode('rect:1')).toBeUndefined()+ },+ { bindGraphEvents: true }+ )+ })++ test('edits in a room nobody has shared stay local', async () => {+ await withSyncedStores(+ async ({ hostStore, peerStore, hostDoc }) => {+ const pageId = expectDefined(hostStore.graph.getPages()[0], 'first page').id+ hostStore.graph.createNode('RECTANGLE', pageId, { id: 'rect:1' })+ await settleGraphSync()+ expect(hostDoc.getMap('nodes').size).toBe(0)+ expect(peerStore.graph.getNode('rect:1')).toBeUndefined()+ },+ { bindGraphEvents: true }+ )+ })++ test("a joiner who edits before the room reaches them keeps the sharer's root", async () => {+ await withSyncedStores(+ async ({ hostStore, peerStore, hostSync, hostDoc, peerDoc }) => {+ const hostRoot = hostStore.graph.rootId+ const hostPages = hostStore.graph.getPages().map((page) => page.id)+ const peerOwnPage = expectDefined(peerStore.graph.getPages()[0], 'peer page').id+ // The joiner edits first; with nobody's root known yet, the edit stays on their device.+ peerStore.graph.createNode('RECTANGLE', peerOwnPage, { id: 'rect:1' })+ await settleGraphSync()+ hostSync.syncAllNodesToYjs()++ const disconnect = connectYDocs(hostDoc, peerDoc)+ try {+ await settleGraphSync()+ for (const graph of [hostStore.graph, peerStore.graph]) {+ expect(graph.rootId).toBe(hostRoot)+ expect(graph.getPages().map((page) => page.id)).toEqual(hostPages)+ }+ } finally {+ disconnect()+ }+ },+ { bindGraphEvents: true, connectImmediately: false }+ )+ })++ test('moving a frame to another page records that page for the layers inside it', async () => {+ await withLiveEdit(+ ({ hostStore }, pageId) => {+ hostStore.graph.addPage('Second')+ hostStore.graph.createNode('FRAME', pageId, { id: 'frame:1' })+ hostStore.graph.createNode('RECTANGLE', 'frame:1', { id: 'rect:1' })+ },+ ({ hostStore }) => {+ const secondPageId = expectDefined(hostStore.graph.getPages()[1], 'second page').id+ hostStore.graph.reparentNode('frame:1', secondPageId)+ },+ ({ hostStore, peerDoc }) => {+ const secondPageId = expectDefined(hostStore.graph.getPages()[1], 'second page').id+ const ynodes = peerDoc.getMap<Y.Map<unknown>>('nodes')+ for (const id of ['frame:1', 'rect:1']) {+ expect(readPage(expectDefined(ynodes.get(id), id))).toBe(secondPageId)+ }+ }+ )+ })+})diff --git a/tests/app/collab/tree/layer-tree.test.ts b/tests/app/collab/tree/layer-tree.test.tsnew file mode 100644index 000000000..6798fc0a1--- /dev/null+++ b/tests/app/collab/tree/layer-tree.test.ts@@ -0,0 +1,278 @@+import { describe, expect, test } from 'bun:test'++import { create as createPRNG, oneOf, real53 } from 'lib0/prng'++import type { ParentEntries } from '@/app/collab/tree/entries'+import { LayerTree } from '@/app/collab/tree/layer-tree'++const ROOT = 'root'+const PAGE = 'page'++type LayerRecord = { entries: Map<string, number>; orderKey: string | undefined }+type TreeState = Map<string, LayerRecord>++function seedState(layers: Record<string, string>): TreeState {+ const state: TreeState = new Map([+ [ROOT, { entries: new Map(), orderKey: undefined }],+ [PAGE, { entries: new Map([[ROOT, 0]]), orderKey: '!' }]+ ])+ for (const [id, parentId] of Object.entries(layers)) {+ state.set(id, { entries: new Map([[parentId, 0]]), orderKey: 'O' })+ }+ return state+}++function treeOf(state: TreeState): LayerTree {+ const tree = new LayerTree({ orphanParentOf: (id) => (id === PAGE ? ROOT : PAGE) })+ for (const [id, layer] of state) tree.setLayer(id, new Map(layer.entries), layer.orderKey)+ tree.resolve()+ return tree+}++function parents(tree: LayerTree, ids: Iterable<string>): Record<string, string | null> {+ const result: Record<string, string | null> = {}+ for (const id of ids) result[id] = tree.parentOf(id) ?? null+ return result+}++/** Every layer reaches the root without visiting a layer twice. */+function expectAcyclic(tree: LayerTree, ids: Iterable<string>) {+ for (const id of ids) {+ const seen = new Set<string>()+ for (let current: string | null | undefined = id; current != null;) {+ expect(seen.has(current)).toBe(false)+ seen.add(current)+ current = tree.parentOf(current)+ }+ expect(seen.has(ROOT)).toBe(true)+ }+}++function move(state: TreeState, id: string, parentId: string, counter: number) {+ const layer = state.get(id)+ if (!layer) throw new Error(`no layer ${id}`)+ layer.entries.set(parentId, counter)+}++describe('layer tree resolution', () => {+ test('a layer sits under its newest parent, ties broken by parent id', () => {+ const state = seedState({ a: PAGE, b: PAGE, x: PAGE })+ move(state, 'x', 'a', 3)+ move(state, 'x', 'b', 3)+ expect(treeOf(state).parentOf('x')).toBe('b')+ move(state, 'x', 'a', 4)+ expect(treeOf(state).parentOf('x')).toBe('a')+ })++ test('two layers moved into each other keep the earlier move', () => {+ const state = seedState({ a: PAGE, b: PAGE })+ move(state, 'a', 'b', 1)+ move(state, 'b', 'a', 2)+ const tree = treeOf(state)+ expect(parents(tree, ['a', 'b'])).toEqual({ a: 'b', b: PAGE })+ expect(tree.isDisplaced('b')).toBe(true)+ expectAcyclic(tree, ['a', 'b'])+ })++ test('a three-layer loop drops only its latest move', () => {+ const state = seedState({ a: PAGE, b: PAGE, c: PAGE })+ move(state, 'a', 'b', 1)+ move(state, 'b', 'c', 3)+ move(state, 'c', 'a', 2)+ const tree = treeOf(state)+ expect(parents(tree, ['a', 'b', 'c'])).toEqual({ a: 'b', b: PAGE, c: 'a' })+ expectAcyclic(tree, ['a', 'b', 'c'])+ })++ test('a loop of equal counters drops the move of the highest layer id', () => {+ const state = seedState({ a: PAGE, b: PAGE })+ move(state, 'a', 'b', 1)+ move(state, 'b', 'a', 1)+ expect(parents(treeOf(state), ['a', 'b'])).toEqual({ a: 'b', b: PAGE })+ })++ test('a layer falls back past every entry that closes a loop', () => {+ const state = seedState({ f: PAGE, a: 'f', b: 'f', x: 'f' })+ move(state, 'a', 'x', 1)+ move(state, 'b', 'x', 2)+ move(state, 'x', 'a', 3)+ move(state, 'x', 'b', 4)+ // x's moves into b and then into a each close a loop and are later than the move they meet.+ const tree = treeOf(state)+ expect(parents(tree, ['x', 'a', 'b'])).toEqual({ x: 'f', a: 'x', b: 'x' })+ expectAcyclic(tree, ['x', 'a', 'b', 'f'])+ })++ test('a layer whose newest parent was deleted falls back to its previous one', () => {+ const state = seedState({ f: PAGE, g: PAGE, x: PAGE })+ move(state, 'x', 'f', 1)+ move(state, 'x', 'g', 2)+ const tree = treeOf(state)+ expect(tree.parentOf('x')).toBe('g')+ tree.deleteLayer('g')+ expect(tree.resolve()).toEqual([{ layerId: 'x', from: 'g', to: 'f' }])+ expect(tree.isDisplaced('x')).toBe(true)+ })++ test('a layer with no remaining parent goes to its page', () => {+ const state = seedState({ f: PAGE, x: 'f' })+ const tree = treeOf(state)+ tree.deleteLayer('f')+ tree.resolve()+ expect(tree.parentOf('x')).toBe(PAGE)+ })++ test('a displaced layer returns when its newest parent comes back', () => {+ const state = seedState({ f: PAGE, x: 'f' })+ move(state, 'x', 'g', 1)+ const tree = treeOf(state)+ expect(tree.parentOf('x')).toBe('f')+ tree.setLayer('g', new Map([[PAGE, 2]]), 'a')+ tree.resolve()+ expect(tree.parentOf('x')).toBe('g')+ expect(tree.isDisplaced('x')).toBe(false)+ })++ test('siblings sort by order key, then by id', () => {+ const tree = new LayerTree({ orphanParentOf: () => PAGE })+ tree.setLayer(ROOT, new Map(), undefined)+ tree.setLayer(PAGE, new Map([[ROOT, 0]]), '!')+ tree.setLayer('c', new Map([[PAGE, 0]]), 'a')+ tree.setLayer('b', new Map([[PAGE, 0]]), 'b')+ tree.setLayer('a', new Map([[PAGE, 0]]), 'b')+ tree.resolve()+ expect(tree.childrenOf(PAGE)).toEqual(['c', 'a', 'b'])+ })++ test('reports the displaced layers on a move path so the move can keep them', () => {+ const state = seedState({ a: PAGE, b: PAGE })+ move(state, 'a', 'b', 1)+ move(state, 'b', 'a', 2)+ const tree = treeOf(state)+ expect(tree.displacedAncestors(['a'])).toEqual(['b'])+ expect(tree.displacedAncestors([PAGE])).toEqual([])+ })+})++interface SimPeer {+ state: TreeState+ deleted: Set<string>+ tree: LayerTree+ clock: number+}++function createPeer(state: TreeState): SimPeer {+ return { state: cloneState(state), deleted: new Set(), tree: treeOf(state), clock: 0 }+}++function cloneState(state: TreeState): TreeState {+ return new Map(+ [...state].map(([id, layer]) => [+ id,+ { entries: new Map(layer.entries), orderKey: layer.orderKey }+ ])+ )+}++function isUnder(tree: LayerTree, id: string, ancestorId: string): boolean {+ const seen = new Set<string>()+ for (let current: string | null | undefined = id; current != null;) {+ if (current === ancestorId) return true+ if (seen.has(current)) return false+ seen.add(current)+ current = tree.parentOf(current)+ }+ return false+}++/** A local move as the app makes one: newest counter, and displaced ancestors re-recorded. */+function moveOnPeer(peer: SimPeer, id: string, parentId: string) {+ const counter = Math.max(peer.clock, peer.tree.maxCounter) + 1+ peer.clock = counter+ const keep = peer.tree.displacedAncestors([peer.tree.parentOf(id), parentId])+ for (const keptId of keep) {+ const keptParent = peer.tree.parentOf(keptId)+ if (keptParent == null) continue+ move(peer.state, keptId, keptParent, counter)+ peer.tree.placeLocally(keptId, keptParent, counter)+ }+ move(peer.state, id, parentId, counter)+ peer.tree.placeLocally(id, parentId, counter)+}++function deleteOnPeer(peer: SimPeer, id: string) {+ const subtree = [id]+ // Iterating an array visits the elements pushed onto it during the loop.+ for (const current of subtree) subtree.push(...peer.tree.childrenOf(current))+ for (const removed of subtree) {+ peer.state.delete(removed)+ peer.deleted.add(removed)+ peer.tree.deleteLayer(removed)+ }+ peer.tree.resolve()+}++/** Delivers `from`'s state to `to`: deletions win, and each entry keeps its highest counter. */+function deliver(from: SimPeer, to: SimPeer) {+ for (const id of from.deleted) {+ if (to.deleted.has(id)) continue+ to.deleted.add(id)+ to.state.delete(id)+ to.tree.deleteLayer(id)+ }+ for (const [id, layer] of from.state) {+ if (to.deleted.has(id)) continue+ const target = to.state.get(id)+ if (!target) continue+ let changed = false+ for (const [parentId, counter] of layer.entries) {+ if ((target.entries.get(parentId) ?? -1) < counter) {+ target.entries.set(parentId, counter)+ changed = true+ }+ }+ if (changed) to.tree.setLayer(id, new Map(target.entries) as ParentEntries, target.orderKey)+ }+ to.tree.resolve()+}++describe('layer tree convergence', () => {+ for (const seed of Array.from({ length: 20 }, (_, index) => index + 1)) {+ test(`random concurrent moves and deletes converge (seed ${seed})`, () => {+ const random = createPRNG(seed)+ const pick = <T>(items: readonly T[]): T => oneOf(random, items.slice())+ const layout: Record<string, string> = {}+ const ids = Array.from({ length: 10 }, (_, index) => `n${index}`)+ for (const [index, id] of ids.entries()) {+ layout[id] = index < 3 ? PAGE : pick(ids.slice(0, index))+ }+ const initial = seedState(layout)+ const peers = [createPeer(initial), createPeer(initial), createPeer(initial)]++ for (let round = 0; round < 8; round++) {+ for (let step = 0; step < 12; step++) {+ const peer = pick(peers)+ const alive = ids.filter((id) => peer.tree.has(id))+ if (alive.length === 0) continue+ const id = pick(alive)+ if (real53(random) < 0.06) {+ deleteOnPeer(peer, id)+ continue+ }+ const targets = [PAGE, ...alive].filter((target) => !isUnder(peer.tree, target, id))+ moveOnPeer(peer, id, pick(targets))+ }+ for (const from of peers) for (const to of peers) if (from !== to) deliver(from, to)++ const reference = peers[0]+ const alive = ids.filter((id) => reference.tree.has(id))+ expectAcyclic(reference.tree, alive)+ const fresh = treeOf(reference.state)+ expect(parents(fresh, alive)).toEqual(parents(reference.tree, alive))+ for (const peer of peers.slice(1)) {+ expect(parents(peer.tree, alive)).toEqual(parents(reference.tree, alive))+ }+ }+ })+ }+})diff --git a/tests/app/editor/design-check/pages.test.ts b/tests/app/editor/design-check/pages.test.tsindex ffb21b244..678741a1d 100644--- a/tests/app/editor/design-check/pages.test.ts+++ b/tests/app/editor/design-check/pages.test.ts@@ -103,4 +103,14 @@ describe('pageOf', () => {expect(pageOf(graph, page.id)).toBe(page.id)expect(pageOf(graph, null)).toBeNull()})++ test('returns no page for layers whose parents form a cycle', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const first = graph.createNode('FRAME', page.id)+ const second = graph.createNode('FRAME', first.id)+ graph.updateNode(first.id, { parentId: second.id })++ expect(pageOf(graph, second.id)).toBeNull()+ })})diff --git a/tests/app/presence/schema.test.ts b/tests/app/presence/schema.test.tsindex 1041ae987..966051848 100644--- a/tests/app/presence/schema.test.ts+++ b/tests/app/presence/schema.test.ts@@ -46,4 +46,13 @@ describe('parsePeer', () => {expect(parsePeer(7, { user, agents: tooMany })?.agents).toEqual([])expect(parsePeer(7, { user: { name: 'x'.repeat(200) } })?.name).toBe('Anonymous')})++ test('reads the layer tree format a peer syncs, and ignores a malformed one', () => {+ expect(parsePeer(7, { user, treeFormat: 2 })?.treeFormat).toBe(2)+ expect(parsePeer(7, { user, treeFormat: 'two' })).toMatchObject({+ name: 'Ana',+ treeFormat: undefined+ })+ expect(parsePeer(7, { user })?.treeFormat).toBeUndefined()+ })})diff --git a/tests/e2e/collab/agents.spec.ts b/tests/e2e/collab/agents.spec.tsindex 533eeecb9..440634c49 100644--- a/tests/e2e/collab/agents.spec.ts+++ b/tests/e2e/collab/agents.spec.ts@@ -4,6 +4,7 @@ import { startAgent } from '#tests/helpers/collab/agent'import {collaborationErrors,connect,+ share,createPeer,startRelay,type Peer@@ -28,7 +29,7 @@ test("a guest's agent shows on their avatar and can be followed until Escape", atry {host = await createPeer(browser, 'Host', relay.url)guest = await createPeer(browser, 'Guest', relay.url)- await connect(host)+ await share(host)await connect(guest)await expect.poll(() => host?.page.evaluate(() => window.openPencil?.test?.collab?.peerCount()))diff --git a/tests/e2e/collab/rooms.spec.ts b/tests/e2e/collab/rooms.spec.tsnew file mode 100644index 000000000..0dfc3d042--- /dev/null+++ b/tests/e2e/collab/rooms.spec.ts@@ -0,0 +1,224 @@+import { expect, test, type Page } from '@playwright/test'++import {+ collaborationErrors,+ connect,+ createPeer,+ roomStatus,+ ROOM_ID,+ SECOND_ROOM_ID,+ share,+ shareLinkPath,+ startRelay,+ type Peer+} from '#tests/helpers/collab/room'++/** Adds a named rectangle to the active tab's first page and returns its ID. */+function addRectangle(page: Page, name: string) {+ return page.evaluate((layerName) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const pageId = store.graph.getPages()[0]?.id+ if (!pageId) throw new Error('No page')+ return store.graph.createNode('RECTANGLE', pageId, { name: layerName, width: 80, height: 60 })+ .id+ }, name)+}++function layerName(page: Page, id: string) {+ return page.evaluate((nodeId) => window.openPencil?.getStore?.().graph.getNode(nodeId)?.name, id)+}++async function closeAll(peers: (Peer | null)[], relay: { close: () => Promise<void> }) {+ for (const peer of peers) await peer?.context.close()+ await relay.close()+}++test('a share link opens the room in its own tab, waiting until someone with it is online', async ({+ browser+}) => {+ test.setTimeout(90_000)+ const relay = await startRelay()+ let host: Peer | null = null+ let guest: Peer | null = null+ try {+ guest = await createPeer(browser, 'Guest', relay.url, { path: shareLinkPath() })+ const screen = guest.page.getByTestId('room-screen')+ // It connects and looks for people before it says nobody who has the file is here.+ await expect(screen).toHaveAttribute('data-status', /^(connecting|looking)$/)+ await expect(screen).toHaveAttribute('data-status', 'waiting', { timeout: 15_000 })+ await expect(+ guest.page.getByRole('heading', { name: 'Waiting for someone who has this file' })+ ).toBeVisible()+ // A browser on a computer can hand the room to the desktop app, or point to its download.+ await expect(guest.page.getByRole('link', { name: 'Open in desktop app' })).toHaveAttribute(+ 'href',+ `openpencil://join?room=${ROOM_ID}`+ )+ await expect(guest.page.getByRole('link', { name: 'Download' })).toHaveAttribute(+ 'href',+ 'https://github.com/open-pencil/open-pencil/releases/latest'+ )++ host = await createPeer(browser, 'Host', relay.url)+ const nodeId = await addRectangle(host.page, 'Shared card')+ await share(host)++ await expect(screen).toHaveCount(0)+ await expect.poll(() => roomStatus(guest as Peer)).toBe('live')+ await expect.poll(() => layerName((guest as Peer).page, nodeId)).toBe('Shared card')+ await expect(guest.page).toHaveURL(new RegExp(`/share/${ROOM_ID}\\?`))+ expect(collaborationErrors(guest)).toEqual([])+ } finally {+ await closeAll([guest, host], relay)+ }+})++test('joining from a document opens a new tab and leaves that document alone', async ({+ browser+}) => {+ const relay = await startRelay()+ let host: Peer | null = null+ let guest: Peer | null = null+ try {+ host = await createPeer(browser, 'Host', relay.url)+ const hostNode = await addRectangle(host.page, 'Room card')+ await share(host)++ guest = await createPeer(browser, 'Guest', relay.url)+ const ownNode = await addRectangle(guest.page, 'My own work')+ await guest.page.getByTestId('collab-share-button').click()+ await guest.page.getByTestId('collab-join-input').fill(`https://example.test/share/${ROOM_ID}/`)+ await guest.page.getByTestId('collab-join-room-button').click()++ await expect.poll(() => layerName((guest as Peer).page, hostNode)).toBe('Room card')+ expect(await layerName(guest.page, ownNode)).toBeUndefined()+ await expect(guest.page.getByTestId('tabbar-tab')).toHaveCount(2)++ await guest.page.getByTestId('tabbar-tab').first().click()+ await expect.poll(() => layerName((guest as Peer).page, ownNode)).toBe('My own work')+ expect(await roomStatus(guest)).toBeNull()+ await expect(guest.page).not.toHaveURL(/\/share\//)+ await expect+ .poll(() => host?.page.evaluate(() => window.openPencil?.test?.collab?.peerCount()))+ .toBe(1)+ expect(await layerName(host.page, ownNode)).toBeUndefined()+ } finally {+ await closeAll([guest, host], relay)+ }+})++test('a pasted link that is not a room says so and joins nothing', async ({ browser }) => {+ const relay = await startRelay()+ let guest: Peer | null = null+ try {+ guest = await createPeer(browser, 'Guest', relay.url)+ await guest.page.getByTestId('collab-share-button').click()+ await guest.page.getByTestId('collab-join-input').fill('https://example.test/share/nope')+ await guest.page.getByTestId('collab-join-room-button').click()+ await expect(guest.page.getByTestId('collab-join-error')).toBeVisible()+ await expect(guest.page.getByTestId('tabbar-tab')).toHaveCount(1)+ expect(await roomStatus(guest)).toBeNull()+ } finally {+ await closeAll([guest], relay)+ }+})++test('reloading a room tab rejoins it, and leaving keeps an unsaved copy', async ({ browser }) => {+ test.setTimeout(90_000)+ const relay = await startRelay()+ let host: Peer | null = null+ let guest: Peer | null = null+ try {+ host = await createPeer(browser, 'Host', relay.url)+ const nodeId = await addRectangle(host.page, 'Kept card')+ await share(host)++ guest = await createPeer(browser, 'Guest', relay.url, { path: shareLinkPath() })+ await expect.poll(() => layerName((guest as Peer).page, nodeId)).toBe('Kept card')++ await guest.page.reload()+ await expect.poll(() => roomStatus(guest as Peer)).toBe('live')+ await expect.poll(() => layerName((guest as Peer).page, nodeId)).toBe('Kept card')++ await guest.page.getByTestId('collab-share-button').click()+ await guest.page.getByTestId('collab-leave').click()+ await expect(guest.page.getByTestId('left-room-notice')).toBeVisible()+ expect(await roomStatus(guest)).toBeNull()+ expect(await layerName(guest.page, nodeId)).toBe('Kept card')+ expect(+ await guest.page.evaluate(() => window.openPencil?.getStore?.().hasUnsavedChanges())+ ).toBe(true)+ await expect(guest.page).not.toHaveURL(/\/share\//)+ await expect+ .poll(() => host?.page.evaluate(() => window.openPencil?.test?.collab?.peerCount()))+ .toBe(0)+ } finally {+ await closeAll([guest, host], relay)+ }+})++test('two room tabs stay live at once, each syncing with its own room', async ({ browser }) => {+ const relay = await startRelay()+ let hostA: Peer | null = null+ let hostB: Peer | null = null+ let guest: Peer | null = null+ try {+ hostA = await createPeer(browser, 'Host A', relay.url)+ await share(hostA, ROOM_ID)+ hostB = await createPeer(browser, 'Host B', relay.url)+ await share(hostB, SECOND_ROOM_ID)++ guest = await createPeer(browser, 'Guest', relay.url)+ await connect(guest, ROOM_ID)+ await expect.poll(() => roomStatus(guest as Peer)).toBe('live')+ const inRoomA = await addRectangle(guest.page, 'For A')+ await connect(guest, SECOND_ROOM_ID)+ await expect.poll(() => roomStatus(guest as Peer)).toBe('live')+ await expect(guest.page).toHaveURL(new RegExp(`/share/${SECOND_ROOM_ID}\\?`))++ await expect.poll(() => layerName((hostA as Peer).page, inRoomA)).toBe('For A')+ expect(await layerName(hostB.page, inRoomA)).toBeUndefined()+ for (const host of [hostA, hostB]) {+ await expect+ .poll(() => host.page.evaluate(() => window.openPencil?.test?.collab?.peerCount()))+ .toBe(1)+ }+ } finally {+ await closeAll([guest, hostA, hostB], relay)+ }+})++test("a guest's page list shows which page the sharer is on, and who is there on hover", async ({+ browser+}) => {+ test.setTimeout(90_000)+ const relay = await startRelay()+ let host: Peer | null = null+ let guest: Peer | null = null+ try {+ host = await createPeer(browser, 'Host', relay.url)+ await addRectangle(host.page, 'Card')+ await share(host)+ guest = await createPeer(browser, 'Guest', relay.url, { path: shareLinkPath() })+ await expect(guest.page.getByTestId('room-screen')).toHaveCount(0, { timeout: 15_000 })++ // A real pointer over the canvas, as people move it, not the test hook.+ const box = await host.canvas.canvas.boundingBox()+ if (!box) throw new Error('Canvas has no bounding box')+ await host.page.mouse.move(box.x + 120, box.y + 80)+ await host.page.mouse.move(box.x + 160, box.y + 100, { steps: 4 })++ const marker = guest.page.getByTestId('pages-item').getByTestId('presence-markers')+ await expect(marker).toHaveAttribute('aria-label', 'Host')++ // Hovering the page shows who is there and lets the guest follow them.+ await guest.page.getByTestId('pages-item').hover()+ const card = guest.page.getByTestId('page-presence-card')+ await expect(card).toBeVisible()+ await expect(card.getByRole('button', { name: 'Follow Host' })).toBeVisible()+ expect(collaborationErrors(guest)).toEqual([])+ } finally {+ await closeAll([guest, host], relay)+ }+})diff --git a/tests/e2e/collab/session.spec.ts b/tests/e2e/collab/session.spec.tsindex c6290b163..ef7e4b717 100644--- a/tests/e2e/collab/session.spec.ts+++ b/tests/e2e/collab/session.spec.ts@@ -3,6 +3,7 @@ import { expect, test } from '@playwright/test'import {collaborationErrors,connect,+ share,createPeer,startRelay,type Peer@@ -14,8 +15,8 @@ test('mobile presence popover returns focus and disconnects the peer', async ({try {peer = await createPeer(browser, 'Mobile', relay.url)await peer.page.setViewportSize({ width: 390, height: 844 })- await connect(peer)- const trigger = peer.page.getByRole('button', { name: 'Online: 1', exact: true })+ await share(peer)+ const trigger = peer.page.getByRole('button', { name: 'In this room: Mobile', exact: true })await expect(trigger).toBeVisible()await trigger.focus()await trigger.press('Enter')@@ -45,7 +46,7 @@ test('two browser peers synchronize editing, awareness, departure, and reconnectconst guest = await createPeer(browser, 'Guest', relay.url)guestToClose = guest- await connect(host)+ await share(host)await connect(guest)await expect.poll(() => host.page.evaluate(() => window.openPencil?.test?.collab?.peerCount()))diff --git a/tests/e2e/settings/tabs.spec.ts-snapshots/settings-tabs-general-openpencil-darwin.png b/tests/e2e/settings/tabs.spec.ts-snapshots/settings-tabs-general-openpencil-darwin.pngindex 90de81735..c834756d0 100644Binary files a/tests/e2e/settings/tabs.spec.ts-snapshots/settings-tabs-general-openpencil-darwin.png and b/tests/e2e/settings/tabs.spec.ts-snapshots/settings-tabs-general-openpencil-darwin.png differdiff --git a/tests/engine/collab/yjs-sync.test.ts b/tests/engine/collab/yjs-sync.test.tsindex 69258ee3c..429d38762 100644--- a/tests/engine/collab/yjs-sync.test.ts+++ b/tests/engine/collab/yjs-sync.test.ts@@ -14,33 +14,6 @@ import { decodeNodeFromYjs, syncEncodedNodeToYMap } from '@/app/collab/node-codeimport { expectDefined, getNodeOrThrow } from '#tests/helpers/assert'import { withSyncedStores } from '#tests/helpers/collab/synced-stores'-// Test copy of the private apply path.-function applyYnodeToGraph(peer: SceneGraph, nodeId: string, ynode: Y.Map<unknown>) {- const props = decodeNodeFromYjs(ynode)- if (peer.getNode(nodeId)) {- peer.updateNode(nodeId, props as Partial<SceneNode>)- return- }- const type = props.type as SceneNode['type'] | undefined- if (!type) return- const parentId = typeof props.parentId === 'string' ? props.parentId : null- peer.createNodeWithId(nodeId, type, parentId, props as Partial<SceneNode>)- if (parentId === null) peer.rootId = nodeId-}--function seedHostIntoYjs(host: SceneGraph): Y.Map<Y.Map<unknown>> {- const doc = new Y.Doc()- const ynodes = doc.getMap<Y.Map<unknown>>('nodes')- doc.transact(() => {- for (const node of host.getAllNodes()) {- const ynode = new Y.Map<unknown>()- ynodes.set(node.id, ynode)- syncEncodedNodeToYMap(node, ynode)- }- })- return ynodes-}-function firstPage(graph: SceneGraph): SceneNode {return expectDefined(graph.getPages()[0], 'first page')}@@ -178,51 +151,33 @@ describe('collab yjs-sync', () => {expect(Array.isArray(props.strokeGeometry)).toBe(true)})- test('a fresh peer reconstructs one ellipse, no duplicate childIds, order-independent', () => {- const host = new SceneGraph()- const hostPage = firstPage(host)- const ellipse = host.createNode('ELLIPSE', hostPage.id, { width: 80, height: 60 })-- const ynodes = seedHostIntoYjs(host)-- const peer = new SceneGraph()- const ids = [...ynodes.keys()].reverse()- for (const id of ids) applyYnodeToGraph(peer, id, expectDefined(ynodes.get(id), `ynode ${id}`))-- const peerEllipse = getNodeOrThrow(peer, ellipse.id)- expect(peerEllipse.type).toBe('ELLIPSE')- expect(peerEllipse.parentId).toBe(hostPage.id)-- const peerPage = getNodeOrThrow(peer, hostPage.id)- const refs = peerPage.childIds.filter((c) => c === ellipse.id)- expect(refs).toHaveLength(1)- expect(peer.getPages().map((page) => page.id)).toContain(hostPage.id)- })-- test('a live-created node links into its parent even when the parent childIds was not re-synced', () => {- const host = new SceneGraph()- const hostPage = firstPage(host)- const rect = host.createNode('RECTANGLE', hostPage.id, { width: 50, height: 50 })-- const doc = new Y.Doc()- const ynodes = doc.getMap<Y.Map<unknown>>('nodes')- doc.transact(() => {- const pageYnode = new Y.Map<unknown>()- ynodes.set(hostPage.id, pageYnode)- syncEncodedNodeToYMap({ ...hostPage, childIds: [] } as SceneNode, pageYnode)-- const rectYnode = new Y.Map<unknown>()- ynodes.set(rect.id, rectYnode)- syncEncodedNodeToYMap(rect, rectYnode)- })-- const peer = new SceneGraph()- applyYnodeToGraph(peer, hostPage.id, expectDefined(ynodes.get(hostPage.id), 'page ynode'))- applyYnodeToGraph(peer, rect.id, expectDefined(ynodes.get(rect.id), 'rect ynode'))-- const peerPage = getNodeOrThrow(peer, hostPage.id)- expect(peerPage.childIds).toEqual([rect.id])- expect(getNodeOrThrow(peer, rect.id).type).toBe('RECTANGLE')+ test('a fresh peer reconstructs one ellipse with no duplicate child entries', async () => {+ await withSyncedStores(+ ({ hostStore, peerStore, hostSync, hostDoc, peerDoc }) => {+ const hostPage = firstPage(hostStore.graph)+ const ellipse = hostStore.graph.createNode('ELLIPSE', hostPage.id, {+ width: 80,+ height: 60+ })+ hostSync.syncAllNodesToYjs()+ Y.applyUpdate(peerDoc, Y.encodeStateAsUpdate(hostDoc))++ const peer = peerStore.graph+ const peerEllipse = getNodeOrThrow(peer, ellipse.id)+ expect(peerEllipse.type).toBe('ELLIPSE')+ expect(peerEllipse.parentId).toBe(hostPage.id)+ const refs = getNodeOrThrow(peer, hostPage.id).childIds.filter((c) => c === ellipse.id)+ expect(refs).toHaveLength(1)+ expect(peer.getPages().map((page) => page.id)).toContain(hostPage.id)+ expect(() =>+ nodeVisualBounds(peerEllipse, (id) => {+ const n = peer.getNode(id)+ return { x: n?.x ?? 0, y: n?.y ?? 0 }+ })+ ).not.toThrow()+ },+ { connectImmediately: false }+ )})test('deduplicates a pending page switch and handles its rejection', async () => {@@ -383,6 +338,7 @@ describe('collab yjs-sync', () => {test('image fills sync image bytes', async () => {await withSyncedStores(({ hostStore, peerStore, hostSync }) => {const hostPage = firstPage(hostStore.graph)+ hostSync.syncAllNodesToYjs()const imageHash = 'image-hash'const imageFill: Fill = {type: 'IMAGE',@@ -402,24 +358,4 @@ describe('collab yjs-sync', () => {).toEqual([9, 8, 7])})})-- test('synced node does not crash the visual-bounds helper', () => {- const host = new SceneGraph()- const hostPage = firstPage(host)- const ellipse = host.createNode('ELLIPSE', hostPage.id, { width: 120, height: 90 })-- const ynodes = seedHostIntoYjs(host)- const peer = new SceneGraph()- for (const id of ynodes.keys()) {- applyYnodeToGraph(peer, id, expectDefined(ynodes.get(id), `ynode ${id}`))- }-- const peerEllipse = getNodeOrThrow(peer, ellipse.id)- expect(() =>- nodeVisualBounds(peerEllipse, (id) => {- const n = peer.getNode(id)- return { x: n?.x ?? 0, y: n?.y ?? 0 }- })- ).not.toThrow()- })})diff --git a/tests/helpers/collab/memory-transport.ts b/tests/helpers/collab/memory-transport.tsnew file mode 100644index 000000000..1309130af--- /dev/null+++ b/tests/helpers/collab/memory-transport.ts@@ -0,0 +1,77 @@+import type { CollabRoomTransport, JoinCollabRoom } from '@/app/collab/transport'+import type { CollabActionReceiver } from '@/app/collab/transport/types'++type MemoryPeer = {+ id: string+ receivers: Map<string, CollabActionReceiver>+ joinHandlers: ((peerId: string) => void)[]+ leaveHandlers: ((peerId: string) => void)[]+}++/**+ * Rooms in memory, for tests: every peer that joins a room ID meets the others in it, and+ * messages arrive on a later microtask, as they would over a network.+ */+export function createMemoryRooms(): { join: JoinCollabRoom; settle: () => Promise<void> } {+ const rooms = new Map<string, Set<MemoryPeer>>()+ let nextPeer = 1++ const join: JoinCollabRoom = (roomId): CollabRoomTransport => {+ const room = rooms.get(roomId) ?? new Set<MemoryPeer>()+ rooms.set(roomId, room)+ const self: MemoryPeer = {+ id: `peer-${nextPeer++}`,+ receivers: new Map(),+ joinHandlers: [],+ leaveHandlers: []+ }+ const others = () => [...room].filter((peer) => peer !== self)+ // Peers meet once both sides have registered their handlers, as after a real handshake.+ queueMicrotask(() => {+ room.add(self)+ for (const peer of others()) {+ for (const handler of peer.joinHandlers) handler(self.id)+ for (const handler of self.joinHandlers) handler(peer.id)+ }+ })+ return {+ makeAction(namespace) {+ return [+ (data, peerId) => {+ for (const peer of others()) {+ if (peerId && peer.id !== peerId) continue+ const copy = data.slice()+ queueMicrotask(() => peer.receivers.get(namespace)?.(copy, self.id))+ }+ },+ (handler) => {+ self.receivers.set(namespace, handler)+ }+ ]+ },+ onPeerJoin(handler) {+ self.joinHandlers.push(handler)+ },+ onPeerLeave(handler) {+ self.leaveHandlers.push(handler)+ },+ signalingConnected: () => true,+ discoveryMs: 0,+ async leave() {+ room.delete(self)+ for (const peer of room) for (const handler of peer.leaveHandlers) handler(self.id)+ }+ }+ }++ /** Lets queued messages and the replies they trigger arrive. */+ async function settle() {+ for (let round = 0; round < 20; round++) {+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 0)+ })+ }+ }++ return { join, settle }+}diff --git a/tests/helpers/collab/room.ts b/tests/helpers/collab/room.tsindex b896a44d1..df5cf64b8 100644--- a/tests/helpers/collab/room.ts+++ b/tests/helpers/collab/room.ts@@ -4,7 +4,9 @@ import { WebSocketServer, type WebSocket } from 'ws'import { CanvasHelper } from '#tests/helpers/canvas'/** Two-browser collaboration: a local WebSocket relay and peers connected through it. */-export const ROOM_ID = 'e2e-collaboration-room'+export const ROOM_ID = 'e2ecollaborationroom000000000000'+/** A second room, for a peer in two rooms at once. */+export const SECOND_ROOM_ID = 'e2ecollaborationroom111111111111'export type TestRelay = {url: string@@ -101,17 +103,37 @@ export type Peer = {canvas: CanvasHelper}-export async function createPeer(browser: Browser, name: string, relayURL: string): Promise<Peer> {+/** The app URL for a path, on the test transport through the given relay. */+export function relayURLFor(path: string, relayURL: string): string {+ return `${path}?test&collabTransport=test&collabRelay=${encodeURIComponent(relayURL)}`+}++export function shareLinkPath(roomId = ROOM_ID): string {+ return `/share/${roomId}`+}++/**+ * A browser with the app open at `path`: `/` by default, or a share link. A share link shows the+ * room's screen instead of a canvas until the room's document arrives, so only `/` waits for the+ * canvas.+ */+export async function createPeer(+ browser: Browser,+ name: string,+ relayURL: string,+ { path = '/' }: { path?: string } = {}+): Promise<Peer> {const context = await browser.newContext({ viewport: { width: 1280, height: 800 } })try {const page = await context.newPage()- await page.goto(`/?test&collabTransport=test&collabRelay=${encodeURIComponent(relayURL)}`)+ await page.goto(relayURLFor(path, relayURL))+ await page.waitForFunction(() => window.openPencil?.test?.collab !== undefined)await page.evaluate((localName) => window.openPencil?.test?.collab?.setLocalName(localName),name)const canvas = new CanvasHelper(page)- await canvas.waitForInit()+ if (path === '/') await canvas.waitForInit()canvas.errors.length = 0return { context, page, canvas }} catch (error) {@@ -124,10 +146,25 @@ export function collaborationErrors(peer: Peer): string[] {return peer.canvas.errors.filter((error) => !error.includes('127.0.0.1:7600'))}-export async function connect(peer: Peer) {- await peer.page.evaluate((roomId) => {+/** Joins the room in a tab of its own, as pasting its link does. */+export async function connect(peer: Peer, roomId = ROOM_ID) {+ await peer.page.evaluate((id) => {+ const collab = window.openPencil?.test?.collab+ if (!collab) throw new Error('Collaboration bridge unavailable')+ if (!collab.connect(id)) throw new Error(`Not a room ID: ${id}`)+ }, roomId)+}++/** Shares the peer's document into the test room, as Share does. */+export async function share(peer: Peer, roomId = ROOM_ID) {+ await peer.page.evaluate((id) => {const collab = window.openPencil?.test?.collabif (!collab) throw new Error('Collaboration bridge unavailable')- collab.connect(roomId)- }, ROOM_ID)+ collab.share(id)+ }, roomId)+}++/** The active tab's room status, from the test bridge. */+export function roomStatus(peer: Peer) {+ return peer.page.evaluate(() => window.openPencil?.test?.collab?.status() ?? null)}diff --git a/tests/helpers/collab/synced-stores.ts b/tests/helpers/collab/synced-stores.tsindex 637af95c8..ad6028996 100644--- a/tests/helpers/collab/synced-stores.ts+++ b/tests/helpers/collab/synced-stores.ts@@ -1,3 +1,5 @@+import { expect } from 'bun:test'+import * as Y from 'yjs'import { SceneGraph } from '@open-pencil/scene-graph'@@ -9,6 +11,7 @@ import {} from '@/app/collab/yjs-sync'import { createEditorStore } from '@/app/editor/session'+import { getNodeOrThrow } from '#tests/helpers/assert'import { connectYDocs } from '#tests/helpers/yjs'/** Host and peer editor stores whose Yjs documents sync through the app's collab code. */@@ -83,20 +86,14 @@ export function createSyncedStores(options: SyncedStoreOptions = {}) {getYdoc: () => hostDoc,getYnodes: () => hostNodes,getSuppressGraphSync: () => hostSuppressGraphSync,- setSuppressYjsEvents: (value) => {- hostSuppressYjsEvents = value- },- syncNodeToYjs: hostSync.syncNodeToYjs+ syncLocalEdit: hostSync.syncLocalEdit}),bindCollabGraphEvents({store: peerStore,getYdoc: () => peerDoc,getYnodes: () => peerNodes,getSuppressGraphSync: () => peerSuppressGraphSync,- setSuppressYjsEvents: (value) => {- peerSuppressYjsEvents = value- },- syncNodeToYjs: peerSync.syncNodeToYjs+ syncLocalEdit: peerSync.syncLocalEdit})]: []@@ -140,3 +137,35 @@ export async function withSyncedStores(stores.cleanup()}}++/** Lets the sync a local edit schedules after its graph events run. */+export async function settleGraphSync() {+ await Promise.resolve()+}++/**+ * Both peers hold the same acyclic tree under `rootIds`, and every layer in it sits in its parent's+ * `childIds`. Returns the layers the tree reaches.+ */+export function expectSameLayerTree(+ { hostStore, peerStore }: SyncedStores,+ rootIds: string[]+): Set<string> {+ const host = hostStore.graph+ const peer = peerStore.graph+ const visited = new Set<string>()+ const pending = [...rootIds]+ for (let id = pending.pop(); id !== undefined; id = pending.pop()) {+ expect(visited.has(id)).toBe(false)+ visited.add(id)+ const hostNode = getNodeOrThrow(host, id)+ const peerNode = getNodeOrThrow(peer, id)+ expect(peerNode.parentId).toBe(hostNode.parentId)+ expect(peerNode.childIds).toEqual(hostNode.childIds)+ for (const childId of hostNode.childIds) {+ expect(getNodeOrThrow(host, childId).parentId).toBe(id)+ pending.push(childId)+ }+ }+ return visited+}diff --git a/tests/helpers/tauri/clipboard-mock.ts b/tests/helpers/tauri/clipboard-mock.tsindex 23e77116d..abc455767 100644--- a/tests/helpers/tauri/clipboard-mock.ts+++ b/tests/helpers/tauri/clipboard-mock.ts@@ -44,6 +44,7 @@ export async function installTauriClipboardMock(page: Page): Promise<TauriClipboreturn state.html || state.textcase 'list_system_fonts':case 'take_pending_open':+ case 'take_pending_rooms':return []case 'load_system_font':case 'plugin:event|listen':diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex c7d3d8701..4dbe203ed 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -69,7 +69,10 @@ ja:code.editorHTMLCSSLabelja:code.noSelectionDesignJSXja:code.noSelectionTailwindJSXja:code.writeJSX+ja:collaboration.invalidRoomLink+ja:collaboration.joinRoomDescriptionja:collaboration.pasteRoomLinkOrId+ja:collaboration.unreachableDescriptionja:commands.paletteDescriptionja:credentials.apiKeyja:credentials.getAPIKey@@ -213,7 +216,10 @@ zh-cn:code.editorHTMLCSSLabelzh-cn:code.noSelectionDesignJSXzh-cn:code.noSelectionTailwindJSXzh-cn:code.writeJSX+zh-cn:collaboration.invalidRoomLink+zh-cn:collaboration.joinRoomDescriptionzh-cn:collaboration.pasteRoomLinkOrId+zh-cn:collaboration.unreachableDescriptionzh-cn:commands.paletteDescriptionzh-cn:credentials.apiKeyzh-cn:credentials.getAPIKey