Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(canvas): add shared editing and multiplayer awareness (#8492)
Wolf Mermelstein6863e4635bf6
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 0add1d41bf..9699087574 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -74,6 +74,16 @@ new MutationObserver(() => {Then trigger the interaction and read `window.__inst.log`. `'1,2,3' → '' → '1,2,3'` (the same ids coming back) is a `<Suspense>` detach and re-attach. Fresh ids are a true remount. Nothing at all means the subtree never moved and the cause is elsewhere. Re-running the same interaction a second time is the cheapest way to prove a cold-cache cause: a once-per-session query settles after the first attempt, so the second attempt stays clean.+## Canvas collaboration++Saved canvases use the shared Loro runtime; the stored JSON is only the original+migration seed. Keep whole-file simple-save out of scene editing. Canvas+initialization, WAL/snapshot recovery and teardown live in+`features/block-canvas/queries/canvas-session.ts`; presence is ephemeral and+reference bookkeeping is excluded from scene undo. Run the feature tests and+`bunx playwright test --config src/features/block-canvas/browser-test/playwright.config.ts`+for multiplayer changes.+## Development PatternsKeep persistent list hotkeys free of mounted-view closures, and cleardiff --git a/apps/web/src/features/block-canvas/README.md b/apps/web/src/features/block-canvas/README.mdindex 622e3d50f4..89b3f7879b 100644--- a/apps/web/src/features/block-canvas/README.md+++ b/apps/web/src/features/block-canvas/README.md@@ -6,9 +6,11 @@ No rollout flag or local override is required.The frontend treats unversioned JSON (and explicit version 1) as legacy Canvas.It converts supported records on load to `{ version: 2, document, legacy? }`.`document` is the graphics scene; `legacy` retains the original JSON and migration-notes for recovery. No migration is saved merely by viewing a file. The first-committed edit writes version 2 using the existing JSON/simple-save endpoint.-Subsequent loads validate version 2 directly; they never replay the archived data.+notes for recovery. No migration is saved merely by viewing a file. The first editor opening a canvas initializes one versioned Loro snapshot in+SyncService. The server serializes initialization; competing openers import only+the winning seed. Subsequent opens use the shared scene and never replay the+original JSON over live edits. JSON remains the import/export format and retains+the legacy source for recovery.Unknown versions and invalid scenes fail closed without writing data.Migration preserves IDs, groups, stacking order, positions, shape labels,@@ -22,11 +24,25 @@ Markdown embeds explicitly pass `isEmbedded` to the editor and use this sameread-only surface, with Select and Hand tools and no property inspector. Selectiondoes not expose transform handles or mutate the scene; embedded views cannot savecanvas edits even when the viewer has edit permission on the original document.-Saves are debounced and serialized; failures keep edits dirty. Save state is not-shown in the canvas UI.--SyncService integration and collaboration remain a follow-up. This change keeps-the existing whole-file save behavior. See [Graphics and Canvas parity](../../../../../docs/design/graphics-parity.md)+Shared edits use the existing collaboration runtime, IndexedDB snapshot/WAL+recovery, and live SyncService transport. Whole-file simple-save has been removed.+Download/export reads the current shared scene; copying a canvas copies its+live room as well as its original JSON seed. Viewers and embeds join existing+rooms read-only and do not initialize a room. Before initialization they can view+the original JSON while waiting for an editor to share it. Initial connection or+local-storage failures keep the original file read-only with a Retry action;+a recovered local snapshot supports editing while disconnected. Undelivered edits+remain in the WAL and trigger a browser unload warning.+Failed local appends stay buffered in the open session; Retry saving retries+them without replacing the scene. Sources bind to the opening account and check+fresh access on reconnect; only edit/owner grants permit scene writes.++Other people see live cursors, selections, and drawing/transform previews. Presence+uses the shared awareness channel, publishes at most every 40–100 ms while moving,+heartbeats every three seconds, and expires after ten seconds without updates.+It never changes document data or undo. Mixed-content previews use bounds for+text, connectors, media, and document cards. Selection/camera/tools stay local.+Incoming scene changes cancel active canvas gestures; intent rebasing is deferred. See [Graphics and Canvas parity](../../../../../docs/design/graphics-parity.md)for the remaining editor and collaboration work.## Controls@@ -202,16 +218,18 @@ outline tolerance; a thick stroke does not gain another 3px outside its paint.- `primitives/`: Solid state, mixed values, creation defaults and UI actions.- `components/`: inspector and layer list with explicit props.- `views/`: editor surface and controls composed around a supplied editor/state.-- `canvas-next.tsx`: memory editor, Macro hotkey scope and clipboard wiring.+- `canvas-next.tsx`: shared Loro editor (or read-only JSON before sharing), hotkeys and clipboard.+- `queries/canvas-session.ts`: shared runtime, initialization, recovery, permissions and teardown.+- `primitives/create-canvas-presence.ts`: ephemeral cursor/selection/gesture publication.- `clipboard.ts` / `hotkeys.ts`: host adapters. No browser/app dependency in the core.-Core command and transform tests exercise both memory and Loro paths. Canvas Next-currently uses memory plus versioned whole-file saves; it does not install awareness-or production collaboration.--The view/state already accept an editor. The current composition root constructs-its own memory editor; a later collaboration checkpoint can inject Loro editors while-retaining the same rich-text measurement, renderer, clipboard and input ownership.+Core command and transform tests exercise both memory and Loro paths. Session+integration tests use three peers and cover merging, undo, competing initializers,+read-only access and recovery. The backend-free Playwright fixture runs the real+canvas session, shared backend and presence overlays with rendered editor surfaces:+`bunx playwright test --config src/features/block-canvas/browser-test/playwright.config.ts`+from `apps/web`. This exercises the runtime against an in-memory SyncService stand-in;+it does not establish a production participant limit or verify hosted transport.## Pencil checkpoint@@ -295,8 +313,10 @@ stores one `textContent` string register per text item or labeled shape, separatfrom pose. Concurrent edits choose one complete tree; no character-level mergingor shared caret is intended. Label layout metadata is separate from pose too, soadding a label and moving its owner can merge. Local typing undo stays in Lexical;-finished edits use the canvas backend's undo. Canvas Next does not yet have a-production SyncService connection.+finished edits use the canvas backend's undo. Canvas Next uses the production SyncService connection. An unchanged text draft+does not overwrite remote text on blur; remote deletion closes its draft, and+remote movement updates the draft position. Simultaneous text edits still choose+one completed content string rather than merging characters.Mixed selections containing text scale uniformly to preserve letter proportions;use a single text shape’s side edges to change wrapping width. Shape definitions@@ -386,16 +406,14 @@ existing embed or choose Interact to enter; Done, Escape, or a click elsewhere othis canvas returns input to the outer canvas. Resizing changes the editor viewport.The embedded block stays mounted when entering/leaving interaction mode.-Document cards participate in the shared entity-mention reference system. The-serialized save adapter registers one mention per target document and stores its-ID in optional `referenceTracking` file metadata. Duplicate cards share a mention;-deleting the last card removes it after the scene saves. Undo/redo reconciles the-saved targets. Failed saves retain created IDs for retry, and pending deletions-survive reload. Source ownership prevents copied canvases from deleting mentions-belonging to the original. Existing untracked cards register on the next edit;-opening a canvas does not write references. Tracking follows the shared mention-tracking flag. File saving and mention creation are separate server operations,-so an interrupted creation before the file save cannot be recovered transactionally.+Document cards participate in the shared entity-mention reference system. Shared+maps record mention IDs and durable pending removals, scoped by source canvas ID+so copied rooms cannot remove the original canvas's mentions. Concurrently created+mention IDs remain recorded independently. Removing a card retires its mentions+only after the scene deletion and retirement reach SyncService; failures retain+them for retry and reload recovery. Reference bookkeeping is excluded from scene+undo. Tracking follows the shared mention-tracking flag. Mention creation and the+CRDT commit are separate operations, so interruption between them is not transactional.`block-embed-adapter.tsx` mounts the existing unmanaged block loader with its ownpanel handle, toolbar, and hotkey scope. The existing editor owns permissions anddiff --git a/apps/web/src/features/block-canvas/browser-test/.gitignore b/apps/web/src/features/block-canvas/browser-test/.gitignorenew file mode 100644index 0000000000..7198a145bc--- /dev/null+++ b/apps/web/src/features/block-canvas/browser-test/.gitignore@@ -0,0 +1,4 @@+.vite/+.dist/+test-results/+playwright-report/diff --git a/apps/web/src/features/block-canvas/browser-test/README.md b/apps/web/src/features/block-canvas/browser-test/README.mdnew file mode 100644index 0000000000..02d0bc9dba--- /dev/null+++ b/apps/web/src/features/block-canvas/browser-test/README.md@@ -0,0 +1,19 @@+# Canvas multiplayer browser fixture++This fixture mounts three independent Canvas sessions (two editors and a viewer)+using the production Loro backend, session persistence contract, awareness adapter,+and graphics surface. An in-memory transport replaces hosted SyncService. It does+not mount the app shell or exercise hosted authentication.++From `apps/web`, run:++```sh+bunx playwright test --config src/features/block-canvas/browser-test/playwright.config.ts+```++The desktop case covers drag previews, cursors, remote selection and style,+local undo, session reopening, and peer departure. The touch case covers mobile+selection awareness. Each case runs only in its applicable device project.+Set `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` to use an installed Chromium.++diff --git a/apps/web/src/features/block-canvas/browser-test/collaboration.browser.e2e.ts b/apps/web/src/features/block-canvas/browser-test/collaboration.browser.e2e.tsnew file mode 100644index 0000000000..52fefd4d63--- /dev/null+++ b/apps/web/src/features/block-canvas/browser-test/collaboration.browser.e2e.ts@@ -0,0 +1,108 @@+import { expect, test } from '@playwright/test';++test('three rendered peers share drag edits, cursor/selection awareness, undo and reload', async ({+ page,+ isMobile,+}) => {+ test.skip(isMobile, 'Desktop pointer gesture coverage');+ const errors: string[] = [];+ page.on('pageerror', (error) => errors.push(error.message));+ await page.goto('/');+ const alice = page.locator('[data-person="Alice"]');+ const bob = page.locator('[data-person="Bob"]');+ const viewer = page.locator('[data-person="Viewer"]');+ await expect(alice.getByLabel('Graphics canvas')).toBeVisible();+ await expect(bob.getByLabel('Graphics canvas')).toBeVisible();+ await expect(viewer.getByLabel('Graphics canvas')).toBeVisible();+ const bounds = (await alice.getByLabel('Graphics canvas').boundingBox())!;+ await page.mouse.move(bounds.x + 130, bounds.y + 140);+ await page.mouse.down();+ await page.mouse.move(bounds.x + 180, bounds.y + 160, { steps: 5 });+ await expect(bob.locator('[data-presence-cursor]')).toHaveCount(1);+ await expect(bob.locator('[data-presence-preview="box"]')).toBeVisible();+ await page.mouse.up();+ await expect(bob.locator('[data-presence-selection]')).toHaveCount(1);+ await expect+ .poll(() =>+ page.evaluate(() => {+ const box =+ window.canvasFixture.people.get('Bob')!.editor.document.items.box;+ return box?.type === 'rectangle' ? box.transform[4] : undefined;+ })+ )+ .toBe(130);+ await page.evaluate(async () => {+ const bob = window.canvasFixture.people.get('Bob')!;+ bob.editor.select('box');+ bob.editor.setSelectionAppearance({ fill: 'red' });+ await bob.session.flush();+ });+ await expect+ .poll(() =>+ page.evaluate(() => {+ const box =+ window.canvasFixture.people.get('Viewer')!.editor.document.items.box;+ return box?.type === 'rectangle' ? box.appearance.fill : undefined;+ })+ )+ .toBe('red');+ await page.evaluate(async () => {+ const alice = window.canvasFixture.people.get('Alice')!;+ alice.editor.undo();+ await alice.session.flush();+ });+ await expect+ .poll(() =>+ page.evaluate(() => {+ const box =+ window.canvasFixture.people.get('Bob')!.editor.document.items.box;+ return box?.type === 'rectangle'+ ? { x: box.transform[4], fill: box.appearance.fill }+ : undefined;+ })+ )+ .toEqual({ x: 80, fill: 'red' });+ await page.evaluate(() => window.canvasFixture.reopen('Alice'));+ await expect(alice.getByLabel('Graphics canvas')).toBeVisible();+ await expect+ .poll(() =>+ page.evaluate(() => {+ const box =+ window.canvasFixture.people.get('Alice')?.editor.document.items.box;+ return box?.type === 'rectangle' ? box.appearance.fill : undefined;+ })+ )+ .toBe('red');+ await page.mouse.move(bounds.x + 140, bounds.y + 200);+ await expect(bob.locator('[data-presence-cursor]')).toHaveCount(1);+ await page.screenshot({+ path: '/tmp/canvas-multiplayer.png',+ fullPage: true,+ });+ await page.mouse.move(0, 0);+ await expect(bob.locator('[data-presence-cursor]')).toHaveCount(0);+ expect(errors).toEqual([]);+});++test('touch selection is visible to other editors and viewers', async ({+ page,+ isMobile,+}) => {+ test.skip(!isMobile, 'Touch input coverage');+ await page.goto('/');+ const alice = page+ .locator('[data-person="Alice"]')+ .getByLabel('Graphics canvas');+ await expect(alice).toBeVisible();+ await expect(+ page.locator('[data-person="Bob"]').getByLabel('Graphics canvas')+ ).toBeVisible();+ const bounds = (await alice.boundingBox())!;+ await page.touchscreen.tap(bounds.x + 100, bounds.y + 130);+ await expect(+ page.locator('[data-person="Bob"] [data-presence-selection]')+ ).toHaveCount(1);+ await expect(+ page.locator('[data-person="Viewer"] [data-presence-selection]')+ ).toHaveCount(1);+});diff --git a/apps/web/src/features/block-canvas/browser-test/fixture.tsx b/apps/web/src/features/block-canvas/browser-test/fixture.tsxnew file mode 100644index 0000000000..07af45e033--- /dev/null+++ b/apps/web/src/features/block-canvas/browser-test/fixture.tsx@@ -0,0 +1,144 @@+import { noopChatter } from '@macro-inc/collaboration/collab/chatter';+import { InMemoryWALStore } from '@macro-inc/collaboration/collab/wal';+import {+ createGraphicsEditorFromBackend,+ createScene,+ type GraphicsEditor,+ translation,+} from '@macro-inc/graphics';+import { createLoroGraphicsBackendFromDoc } from '@macro-inc/graphics/loro';+import { CollaborativeGraphicsSurface } from '@macro-inc/graphics/loro/solid';+import type { LoroDoc } from 'loro-crdt';+import { createSignal, For, onCleanup, Show } from 'solid-js';+import { render } from 'solid-js/web';+import { MemorySyncServer } from '../../block-fig/browser-test/memory-sync';+import { createCanvasPresence } from '../primitives/create-canvas-presence';+import {+ type CanvasSession,+ createCanvasSession,+} from '../queries/canvas-session';++const server = new MemorySyncServer();+const initial = {+ version: 2,+ document: createScene([+ {+ id: 'box',+ type: 'rectangle',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(80, 100),+ geometry: { width: 120, height: 80 },+ appearance: { fill: '#ddd', stroke: '#333' },+ },+ ]),+} as const;+const people = new Map<+ string,+ { editor: GraphicsEditor; session: CanvasSession }+>();+declare global {+ interface Window {+ canvasFixture: {+ people: typeof people;+ reopen: (name: string) => void;+ };+ }+}+function Person(props: { name: string }) {+ let snapshot: Uint8Array | null = null;+ const session = createCanvasSession({+ documentId: 'canvas-browser',+ initial,+ userId: props.name,+ canEdit: () => props.name !== 'Viewer',+ exists: () => server.exists(),+ initialize: (value) => server.initialize(value),+ connect: () => server.connect('canvas-browser'),+ persistence: {+ snapshots: {+ load: async () => snapshot,+ save: async (value) => {+ snapshot = value;+ },+ delete: async () => {+ snapshot = null;+ },+ },+ wal: new InMemoryWALStore(),+ makeChatter: noopChatter,+ },+ });+ const doc = () => {+ const state = session.state();+ return state.t === 'ready' ? state.doc : undefined;+ };+ return (+ <section data-person={props.name} style={{ flex: 1, 'min-width': 0 }}>+ <h2>{props.name}</h2>+ <div+ style={{+ position: 'relative',+ height: '480px',+ border: '1px solid #aaa',+ }}+ >+ <Show when={doc()} keyed>+ {(doc) => <Scene doc={doc} session={session} name={props.name} />}+ </Show>+ </div>+ </section>+ );+}+function Scene(props: { doc: LoroDoc; session: CanvasSession; name: string }) {+ const backend = createLoroGraphicsBackendFromDoc(+ props.doc,+ initial.document.rootId,+ () => props.name !== 'Viewer'+ );+ const editor = createGraphicsEditorFromBackend(backend);+ const presence = createCanvasPresence(+ editor,+ props.session,+ backend.getClock,+ (id) => id ?? 'Someone'+ );+ people.set(props.name, { editor, session: props.session });+ onCleanup(() => {+ people.delete(props.name);+ editor.dispose();+ backend.dispose();+ });+ return (+ <CollaborativeGraphicsSurface+ editor={editor}+ presence={presence}+ input={{ tool: () => 'select', editing: props.name !== 'Viewer' }}+ />+ );+}+function Fixture() {+ const [attempts, setAttempts] = createSignal({ Alice: 1, Bob: 1, Viewer: 1 });+ window.canvasFixture = {+ people,+ reopen: (name) =>+ setAttempts((value) => ({+ ...value,+ [name]: value[name as keyof typeof value] + 1,+ })),+ };+ return (+ <div style={{ display: 'flex', gap: '12px' }}>+ <For each={['Alice', 'Bob', 'Viewer']}>+ {(name) => (+ <Show+ when={attempts()[name as keyof ReturnType<typeof attempts>]}+ keyed+ >+ {(_attempt) => <Person name={name} />}+ </Show>+ )}+ </For>+ </div>+ );+}+render(() => <Fixture />, document.getElementById('root')!);diff --git a/apps/web/src/features/block-canvas/browser-test/index.html b/apps/web/src/features/block-canvas/browser-test/index.htmlnew file mode 100644index 0000000000..edccbb9712--- /dev/null+++ b/apps/web/src/features/block-canvas/browser-test/index.html@@ -0,0 +1 @@+<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1"/><style>:root{--color-red:#d33;--color-orange:#e80;--color-yellow:#aa0;--color-lime:#6a0;--color-green:#295;--color-teal:#088;--color-cyan:#089;--color-blue:#36c;--color-violet:#83c;--color-purple:#93a;--color-pink:#c48;--color-accent:#36c}body{font-family:system-ui}</style><title>Canvas multiplayer</title></head><body><div id="root"></div><script type="module" src="/fixture.tsx"></script></body></html>\ No newline at end of filediff --git a/apps/web/src/features/block-canvas/browser-test/multiplayer.png b/apps/web/src/features/block-canvas/browser-test/multiplayer.pngnew file mode 100644index 0000000000..d92eb1cf80Binary files /dev/null and b/apps/web/src/features/block-canvas/browser-test/multiplayer.png differdiff --git a/apps/web/src/features/block-canvas/browser-test/playwright.config.ts b/apps/web/src/features/block-canvas/browser-test/playwright.config.tsnew file mode 100644index 0000000000..ea1ab13e43--- /dev/null+++ b/apps/web/src/features/block-canvas/browser-test/playwright.config.ts@@ -0,0 +1,54 @@+import { fileURLToPath } from 'node:url';+import { defineConfig, devices } from '@playwright/test';++const directory = fileURLToPath(new URL('.', import.meta.url));+const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));+const externalBaseURL = process.env.CANVAS_BROWSER_BASE_URL;++export default defineConfig({+ testDir: directory,+ testMatch: '*.browser.e2e.ts',+ outputDir: `${directory}/test-results`,+ timeout: 60_000,+ expect: { timeout: 15_000 },+ fullyParallel: false,+ workers: 1,+ reporter: 'line',+ use: {+ baseURL: externalBaseURL ?? 'http://127.0.0.1:3027',+ trace: 'retain-on-failure',+ screenshot: 'only-on-failure',+ acceptDownloads: true,+ },+ webServer: externalBaseURL+ ? undefined+ : {+ command:+ 'bunx vite --config src/features/block-canvas/browser-test/vite.config.ts',+ cwd: webDirectory,+ url: 'http://127.0.0.1:3027',+ reuseExistingServer: true,+ timeout: 90_000,+ },+ projects: [+ {+ name: 'chromium',+ use: {+ ...devices['Desktop Chrome'],+ viewport: { width: 1440, height: 900 },+ launchOptions: {+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,+ },+ },+ },+ {+ name: 'mobile',+ use: {+ ...devices['Pixel 7'],+ launchOptions: {+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,+ },+ },+ },+ ],+});diff --git a/apps/web/src/features/block-canvas/browser-test/vite.config.ts b/apps/web/src/features/block-canvas/browser-test/vite.config.tsnew file mode 100644index 0000000000..658da22de1--- /dev/null+++ b/apps/web/src/features/block-canvas/browser-test/vite.config.ts@@ -0,0 +1,39 @@+import { fileURLToPath } from 'node:url';+import tailwind from '@tailwindcss/vite';+import { defineConfig } from 'vite';+import solidPlugin from 'vite-plugin-solid';+import solidSvg from 'vite-plugin-solid-svg';+import tsconfigPaths from 'vite-tsconfig-paths';++const directory = fileURLToPath(new URL('.', import.meta.url));+const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));+const workspaceDirectory = fileURLToPath(+ new URL('../../../../../../', import.meta.url)+);++export default defineConfig({+ root: directory,+ cacheDir: `${directory}/.vite`,+ plugins: [+ solidPlugin(),+ solidSvg({ defaultAsComponent: true }),+ tsconfigPaths({ projects: [`${webDirectory}/tsconfig.json`] }),+ tailwind(),+ ],+ resolve: {+ dedupe: ['solid-js', 'loro-crdt'],+ alias: { 'loro-crdt': 'loro-crdt/base64' },+ },+ server: {+ host: '127.0.0.1',+ port: 3027,+ strictPort: true,+ fs: { allow: [workspaceDirectory] },+ },+ worker: { format: 'es' },+ build: {+ target: 'esnext',+ outDir: `${directory}/.dist`,+ emptyOutDir: true,+ },+});diff --git a/apps/web/src/features/block-canvas/canvas-next-document.tsx b/apps/web/src/features/block-canvas/canvas-next-document.tsxindex 074096be22..7502012fa2 100644--- a/apps/web/src/features/block-canvas/canvas-next-document.tsx+++ b/apps/web/src/features/block-canvas/canvas-next-document.tsx@@ -1,3 +1,6 @@+import { ENABLE_MENTION_TRACKING } from '@core/constant/featureFlags';+import { useUserId } from '@core/context/user';+import { getDisplayName, tryMacroId } from '@core/user';import { fireAndForget } from '@core/util/fireAndForget';import type { GraphicsEditor } from '@macro-inc/graphics';import { debounce } from '@solid-primitives/scheduled';@@ -5,21 +8,27 @@ import {createEffect,createResource,createSignal,+ Match,onCleanup,Show,+ Switch,useContext,} from 'solid-js';import { CanvasNextEditor } from './canvas-next';import type { CanvasDocumentProps } from './component/CanvasDocument';+import { Loading } from './component/Loading';import { CanvasAncestry } from './context/canvas-ancestry';+import { readSharedCanvas } from './core/collaboration';import type { CanvasFile } from './core/document-format';import { createNumericParser } from './core/parse';-import { createDocumentPersistence } from './primitives/create-document-persistence';+import { createSharedReferenceTracking } from './primitives/create-shared-reference-tracking';import {fetchCanvasViewLocation,saveCanvasViewLocation,} from './queries/canvas-document';-import { canvasDocumentSource } from './queries/document';+import { createCanvasSession } from './queries/canvas-session';+import { canvasSyncSource } from './queries/canvas-sync';+import { canvasReferenceSource } from './queries/references';const parseLocation = createNumericParser<{x?: number;@@ -33,14 +42,51 @@ const parseLocation = createNumericParser<{export default function CanvasNextDocument(props: CanvasDocumentProps & { initial: CanvasFile }+) {+ const [attempt, setAttempt] = createSignal(1);+ return (+ <Show when={attempt()} keyed>+ {(_attempt) => (+ <CanvasDocumentSession+ {...props}+ retry={() => setAttempt((value) => value + 1)}+ />+ )}+ </Show>+ );+}++function CanvasDocumentSession(+ props: CanvasDocumentProps & { initial: CanvasFile; retry: () => void }) {const ancestors = useContext(CanvasAncestry);const documentId = props.documentId;const initial = props.initial;- const canEdit = () => props.canEdit && !props.isNested;const activePointers = new Set<number>();- const [persistence, setPersistence] =- createSignal<ReturnType<typeof createDocumentPersistence>>();+ const userId = useUserId();+ const openedBy = userId();+ const sync = canvasSyncSource(documentId, userId);+ const canEdit = () =>+ props.canEdit &&+ !props.isNested &&+ userId() === openedBy &&+ sync.canWrite();+ const session = createCanvasSession({+ documentId,+ initial,+ userId: userId(),+ canEdit,+ ...sync,+ });+ const sharedDoc = () => {+ const state = session.state();+ return state.t === 'ready' ? state.doc : undefined;+ };+ const error = () => {+ const state = session.state();+ return state.t === 'error' ? state.message : session.failure();+ };+ const [revision, setRevision] = createSignal(0);const [editor, setEditor] = createSignal<GraphicsEditor>();const [savedLocation] = createResource(async () =>props.isNested || props.view ? null : fetchCanvasViewLocation(documentId)@@ -73,7 +119,7 @@ export default function CanvasNextDocument(s: Math.round(camera.scale * 100),};};- const content = (+ const renderEditor = (doc?: import('loro-crdt').LoroDoc) => (<divclass="relative flex size-full min-h-0 flex-col"on:pointerdown={(event) => activePointers.add(event.pointerId)}@@ -83,21 +129,39 @@ export default function CanvasNextDocument(<CanvasNextEditordocumentId={documentId}initial={initial}- canEdit={props.canEdit}+ doc={doc}+ session={doc ? session : undefined}+ displayName={(userId) =>+ getDisplayName(tryMacroId(userId ?? ''), {+ emailFallback: 'local-part',+ }) || 'Someone'+ }+ canEdit={!!doc && canEdit()}isEmbedded={props.isNested}fitOnLoad={!location()}onReady={(current, finishText) => {setEditor(current);- const saving = createDocumentPersistence(- current,- initial,- canvasDocumentSource(documentId, canEdit, initial)+ if (doc)+ session.finishEditing(() => {+ if (canEdit()) finishText();+ });+ const detachDocument = current.subscribeDocument(() =>+ setRevision((value) => value + 1));- setPersistence(saving);+ if (doc && ENABLE_MENTION_TRACKING)+ createSharedReferenceTracking(+ doc,+ documentId,+ canEdit,+ session.flush,+ canvasReferenceSource(documentId)+ );props.registerMethods?.({exportCanvas: async () => {if (canEdit()) finishText();- return { ...initial, document: current.document };+ return doc+ ? readSharedCanvas(doc, documentId)+ : { ...initial, document: current.document };},goToLocationFromParams: (params) =>applyLocation(parseLocation(params)),@@ -141,11 +205,11 @@ export default function CanvasNextDocument(});const flush = () => {if (canEdit()) finishText();- fireAndForget(saving.flush(), 'canvas-persistence');+ if (doc) fireAndForget(session.flush(), 'canvas-session');};const beforeUnload = (event: BeforeUnloadEvent) => {flush();- if (saving.dirty()) {+ if (session.pending() || session.failure()) {event.preventDefault();event.returnValue = '';}@@ -154,7 +218,7 @@ export default function CanvasNextDocument(window.addEventListener('beforeunload', beforeUnload);onCleanup(() => {flush();- saving.dispose();+ detachDocument();unsubscribe();notifyLocation.clear();window.removeEventListener('pointerup', pointerEnd, true);@@ -169,9 +233,71 @@ export default function CanvasNextDocument(</Show></div>);+ const content = (+ <div class="relative size-full min-h-0">+ <Show when={error()}>+ {(message) => (+ <div+ role="alert"+ class="absolute top-2 left-2 z-50 rounded border border-edge-muted bg-panel p-2 text-sm"+ >+ {message()}{' '}+ <Show+ when={session.state().t === 'error'}+ fallback={+ <button+ type="button"+ class="underline"+ onClick={() =>+ fireAndForget(session.retrySave(), 'canvas-session')+ }+ >+ Retry saving+ </button>+ }+ >+ <button type="button" class="underline" onClick={props.retry}>+ Retry+ </button>+ </Show>+ </div>+ )}+ </Show>+ <Switch>+ <Match when={sharedDoc()} keyed>+ {(doc) => renderEditor(doc)}+ </Match>+ <Match+ when={+ session.state().t === 'unshared' || session.state().t === 'error'+ }+ >+ {renderEditor()}+ </Match>+ <Match when={session.state().t === 'loading'}>+ <Loading />+ </Match>+ </Switch>+ </div>+ );return props.children? props.children(content, {- savedFile: () => persistence()?.savedFile(),+ savedFile: () => {+ revision();+ const current = editor();+ if (!current) return;+ const doc = sharedDoc();+ return new Blob(+ [+ JSON.stringify(+ doc+ ? readSharedCanvas(doc, documentId)+ : { ...initial, document: current.document }+ ),+ ],+ { type: 'application/x-macro-canvas' }+ );+ },location: currentLocation,}): content;diff --git a/apps/web/src/features/block-canvas/canvas-next.tsx b/apps/web/src/features/block-canvas/canvas-next.tsxindex 154e95700c..f57437187c 100644--- a/apps/web/src/features/block-canvas/canvas-next.tsx+++ b/apps/web/src/features/block-canvas/canvas-next.tsx@@ -9,19 +9,31 @@ import {import { useHotkeyDOMScope } from '@core/hotkey/hotkeys';import { fireAndForget } from '@core/util/fireAndForget';import type { GraphicsEditor, TextMeasurer } from '@macro-inc/graphics';-import { createGraphicsEditor, screenToWorld } from '@macro-inc/graphics';+import {+ createGraphicsEditor,+ createGraphicsEditorFromBackend,+ screenToWorld,+} from '@macro-inc/graphics';+import {+ createLoroGraphicsBackendFromDoc,+ type GraphicsPresence,+} from '@macro-inc/graphics/loro';import { fetchDocumentMetadata } from '@queries/storage/document-metadata';+import type { LoroDoc } from 'loro-crdt';import { onCleanup, Show } from 'solid-js';import { CanvasBlockEmbed } from './block-embed-adapter';import { createCanvasClipboard } from './clipboard';+import { readSharedCanvas } from './core/collaboration';import type { CanvasFile } from './core/document-format';import { registerCanvasNextHotkeys } from './hotkeys';import { createAssetState } from './primitives/create-asset-state';+import { createCanvasPresence } from './primitives/create-canvas-presence';import { createCanvasState } from './primitives/create-canvas-state';import { createCanvasInsertState } from './primitives/create-insert-state';import { observeObjectSnapping } from './primitives/observe-object-snapping';import { importTextClipboard } from './primitives/text-lexical';import { canvasAssetSource } from './queries/assets';+import type { CanvasSession } from './queries/canvas-session';import { CanvasReadOnlyView } from './views/canvas-read-only-view';import { CanvasView } from './views/canvas-view';import { createCanvasTextMeasurer } from './views/text-content';@@ -29,6 +41,9 @@ import { createCanvasTextMeasurer } from './views/text-content';export function CanvasNextEditor(props: {documentId: string;initial: CanvasFile;+ doc?: LoroDoc;+ session?: CanvasSession;+ displayName?: (userId: string | undefined) => string;canEdit: boolean;isEmbedded?: boolean;fitOnLoad?: boolean;@@ -36,10 +51,35 @@ export function CanvasNextEditor(props: {}) {const measurement = createCanvasTextMeasurer();onCleanup(measurement.dispose);- const editor = createGraphicsEditor(props.initial.document, {- measureText: measurement.measure,- });+ const options = { measureText: measurement.measure };+ const backend = props.doc+ ? createLoroGraphicsBackendFromDoc(+ props.doc,+ readSharedCanvas(props.doc).document.rootId,+ () => {+ const state = props.session?.state();+ return (+ props.canEdit &&+ !props.isEmbedded &&+ (!state || (state.t === 'ready' && state.doc === props.doc))+ );+ }+ )+ : undefined;+ if (backend) onCleanup(backend.dispose);+ const editor = backend+ ? createGraphicsEditorFromBackend(backend, options)+ : createGraphicsEditor(props.initial.document, options);onCleanup(editor.dispose);+ const presence =+ backend && props.session+ ? createCanvasPresence(+ editor,+ props.session,+ backend.getClock,+ props.displayName ?? (() => 'Someone')+ )+ : undefined;let finishText = () => {};props.onReady?.(editor, () => finishText());return (@@ -47,12 +87,17 @@ export function CanvasNextEditor(props: {<Showwhen={props.canEdit && !props.isEmbedded}fallback={- <CanvasReadOnlyView editor={editor} fitOnLoad={props.fitOnLoad} />+ <CanvasReadOnlyView+ editor={editor}+ fitOnLoad={props.fitOnLoad}+ presence={presence}+ />}><EditableCanvasNextdocumentId={props.documentId}editor={editor}+ presence={presence}measureText={measurement.measure}fitOnLoad={props.fitOnLoad}canEdit={() => props.canEdit}@@ -68,6 +113,7 @@ export function CanvasNextEditor(props: {function EditableCanvasNext(props: {documentId: string;editor: GraphicsEditor;+ presence?: GraphicsPresence;measureText: TextMeasurer;fitOnLoad?: boolean;canEdit: () => boolean;@@ -131,6 +177,7 @@ function EditableCanvasNext(props: {<CanvasViewfitOnLoad={props.fitOnLoad}state={state}+ presence={props.presence}scopeId={scopeId}embedView={CanvasBlockEmbed}assets={assets}diff --git a/apps/web/src/features/block-canvas/context/document-source.ts b/apps/web/src/features/block-canvas/context/document-source.tsdeleted file mode 100644index 75aadcaf98..0000000000--- a/apps/web/src/features/block-canvas/context/document-source.ts+++ /dev/null@@ -1,7 +0,0 @@-import type { CanvasFile } from '../core/document-format';--/** The document session only needs permission and a completed JSON write. */-export type CanvasDocumentSource = {- canEdit: () => boolean;- save: (file: CanvasFile) => Promise<Blob>;-};diff --git a/apps/web/src/features/block-canvas/core/collaboration.ts b/apps/web/src/features/block-canvas/core/collaboration.tsnew file mode 100644index 0000000000..30a73ab8ac--- /dev/null+++ b/apps/web/src/features/block-canvas/core/collaboration.ts@@ -0,0 +1,74 @@+import {+ createLoroSeed,+ readLoroGraphicsDocument,+} from '@macro-inc/graphics/loro';+import { LoroDoc } from 'loro-crdt';+import { type CanvasFile, readCanvasFile } from './document-format';++const FORMAT = 1;++/** Only the server's winning seed is imported; never merge independent seeds. */+export function createCanvasSeed(+ file: CanvasFile,+ documentId?: string+): Uint8Array {+ const doc = new LoroDoc();+ try {+ doc.import(createLoroSeed(file.document));+ doc.setPeerId('0');+ const meta = doc.getMap('canvasMeta');+ meta.set('format', FORMAT);+ // Preserve migration and extension metadata without duplicating the scene.+ const { document, ...metadata } = file;+ meta.set('file', JSON.stringify(metadata));+ meta.set('rootId', document.rootId);+ if (documentId && file.referenceTracking?.sourceId === documentId) {+ const mentions = doc.getMap(`canvasMentions:${documentId}`);+ const retiring = doc.getMap(`canvasRetiring:${documentId}`);+ for (const mention of file.referenceTracking.mentions)+ mentions.set(mention.mentionId, mention.targetId);+ for (const id of file.referenceTracking.pendingRemoval)+ retiring.set(id, true);+ }+ doc.commit();+ return doc.export({ mode: 'snapshot' });+ } finally {+ doc.free();+ }+}++/** JSON exports and rendering always read the current shared scene. */+export function readSharedCanvas(+ doc: LoroDoc,+ documentId?: string+): CanvasFile {+ const meta = doc.getMap('canvasMeta');+ const format = meta.get('format');+ const rootId = meta.get('rootId');+ const file = meta.get('file');+ if (+ format !== FORMAT ||+ typeof rootId !== 'string' ||+ typeof file !== 'string'+ )+ throw new Error(+ 'This canvas uses an unsupported shared format. Update Macro to open it.'+ );+ return readCanvasFile({+ ...JSON.parse(file),+ ...(documentId+ ? {+ referenceTracking: {+ sourceId: documentId,+ mentions: Object.entries(+ doc.getMap(`canvasMentions:${documentId}`).toJSON()+ ).flatMap(([mentionId, targetId]) =>+ typeof targetId === 'string' ? [{ mentionId, targetId }] : []+ ),+ pendingRemoval: doc.getMap(`canvasRetiring:${documentId}`).keys(),+ },+ }+ : {}),+ document: readLoroGraphicsDocument(doc, rootId),+ });+}diff --git a/apps/web/src/features/block-canvas/core/presence.ts b/apps/web/src/features/block-canvas/core/presence.tsnew file mode 100644index 0000000000..69b6a90aa0--- /dev/null+++ b/apps/web/src/features/block-canvas/core/presence.ts@@ -0,0 +1,62 @@+import type { PeerPresence } from '@macro-inc/graphics/loro';+import { z } from 'zod';++const finite = z.number().finite();+const point = z.object({ x: finite, y: finite });+const presenceSchema = z.object({+ id: z.string().max(100),+ name: z.string().max(200),+ color: z.string().max(100),+ cursor: point.nullable(),+ selectedIds: z.array(z.string().max(200)).max(1000),+ clock: z.record(z.string(), z.number().int().nonnegative()),+ preview: z+ .object({+ kind: z.enum([+ 'draw',+ 'move',+ 'resize',+ 'scale',+ 'rotate',+ 'radius',+ 'marquee',+ ]),+ shapes: z+ .array(+ z.object({+ id: z.string().max(200),+ kind: z.enum(['rectangle', 'ellipse', 'pencil']),+ width: finite.nonnegative(),+ height: finite.nonnegative(),+ world: z.tuple([finite, finite, finite, finite, finite, finite]),+ pencil: z+ .object({+ points: z.array(z.tuple([finite, finite, finite])).max(2048),+ simulatePressure: z.boolean(),+ })+ .optional(),+ strokeWidth: finite.nonnegative().optional(),+ cornerRadius: finite.nonnegative().optional(),+ })+ )+ .max(256)+ .refine((shapes) =>+ shapes.every((shape) => shape.kind !== 'pencil' || !!shape.pencil)+ ),+ box: point+ .extend({ width: finite.nonnegative(), height: finite.nonnegative() })+ .nullable(),+ })+ .nullable(),+});++/** Presence is untrusted ephemeral input; invalid packets never reach rendering. */+export function decodeCanvasPresence(value: string): PeerPresence | null {+ if (typeof value !== 'string' || value.length > 128_000) return null;+ try {+ const parsed = presenceSchema.safeParse(JSON.parse(value));+ return parsed.success ? parsed.data : null;+ } catch {+ return null;+ }+}diff --git a/apps/web/src/features/block-canvas/primitives/create-canvas-presence.ts b/apps/web/src/features/block-canvas/primitives/create-canvas-presence.tsnew file mode 100644index 0000000000..f03c656893--- /dev/null+++ b/apps/web/src/features/block-canvas/primitives/create-canvas-presence.ts@@ -0,0 +1,117 @@+import { SyncSourceStatus } from '@macro-inc/collaboration/collab/source';+import type { GraphicsEditor, Point } from '@macro-inc/graphics';+import {+ capturePresence,+ type GraphicsPresence,+} from '@macro-inc/graphics/loro';+import { createEffect, on, onCleanup } from 'solid-js';+import type { CanvasSession } from '../queries/canvas-session';++/** Publish ephemeral gestures through the shared runtime's awareness channel. */+export function createCanvasPresence(+ editor: GraphicsEditor,+ session: CanvasSession,+ getClock: GraphicsPresence['getClock'],+ displayName: (userId: string | undefined) => string+): GraphicsPresence {+ let cursor: Point | null = null;+ let timer: ReturnType<typeof setTimeout> | undefined;+ let deadline: ReturnType<typeof setTimeout> | undefined;+ const clear = () => {+ clearTimeout(timer);+ clearTimeout(deadline);+ timer = deadline = undefined;+ };+ const publish = () => {+ clear();+ const presence = capturePresence(+ editor,+ {+ id: session.peerId,+ name: '',+ color: '',+ },+ getClock(),+ cursor+ );+ // Large selections/strokes retain cursors and selection awareness without+ // turning transient gestures into unbounded network payloads.+ presence.selectedIds = presence.selectedIds.slice(0, 1000);+ if (+ JSON.stringify(presence).length > 128_000 ||+ (presence.preview?.shapes.length ?? 0) > 256 ||+ presence.preview?.shapes.some(+ (shape) => (shape.pencil?.points.length ?? 0) > 2048+ )+ )+ presence.preview = null;+ session.awareness.updateLocalAwareness(presence);+ };+ const schedule = () => {+ clearTimeout(timer);+ timer = setTimeout(publish, 40);+ deadline ??= setTimeout(publish, 100);+ };+ const gesture = () => {+ const current = editor.getSession();+ if (current.transform || current.box || editor.getPreview()) schedule();+ else publish();+ };+ const detach = [+ editor.subscribeSession(gesture),+ editor.subscribePreview(gesture),+ editor.subscribeDocument(publish),+ ];+ const heartbeat = setInterval(publish, 3000);+ const listeners = new Set<() => void>();+ createEffect(+ on([session.awareness.remote, session.status], () => {+ for (const listener of listeners) listener();+ })+ );+ onCleanup(() => {+ clear();+ clearInterval(heartbeat);+ detach.forEach((unsubscribe) => unsubscribe());+ listeners.clear();+ session.awareness.updateLocalAwareness(undefined);+ });+ publish();+ return {+ getClock,+ getRemote: () =>+ session.status() === SyncSourceStatus.Connected+ ? session.awareness.remote().flatMap((peer) =>+ peer.selection && peer.user && typeof peer.user.peerId === 'string'+ ? [+ {+ ...peer.selection,+ id: peer.user.peerId,+ name: displayName(+ typeof peer.user.userId === 'string'+ ? peer.user.userId+ : undefined+ ),+ color:+ typeof peer.user.color === 'string' &&+ /^[a-z]+$/.test(peer.user.color)+ ? `var(--color-${peer.user.color}, var(--color-accent))`+ : 'var(--color-accent)',+ },+ ]+ : []+ )+ : [],+ subscribe(listener) {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ setCursor(next) {+ cursor = next;+ if (next) schedule();+ else publish();+ },+ };+}diff --git a/apps/web/src/features/block-canvas/primitives/create-document-persistence.test.ts b/apps/web/src/features/block-canvas/primitives/create-document-persistence.test.tsdeleted file mode 100644index 704865407e..0000000000--- a/apps/web/src/features/block-canvas/primitives/create-document-persistence.test.ts+++ /dev/null@@ -1,117 +0,0 @@-import {- createGraphicsEditor,- setShapeLabelCommand,-} from '@macro-inc/graphics';-import { afterEach, expect, it, vi } from 'vitest';-import type { CanvasFile } from '../core/document-format';-import { createCanvasNextScene } from '../core/seed-scene';-import { plainRichText } from '../core/text-codec';-import { createDocumentPersistence } from './create-document-persistence';--const cleanups: (() => void)[] = [];-afterEach(() => {- cleanups.splice(0).forEach((f) => f());- vi.useRealTimers();-});-function setup(- save = vi.fn(async (_file: CanvasFile) => new Blob()),- canEdit = () => true-) {- vi.useFakeTimers();- const initial: CanvasFile = { version: 2, document: createCanvasNextScene() };- const editor = createGraphicsEditor(initial.document);- const persistence = createDocumentPersistence(editor, initial, {- save,- canEdit,- });- cleanups.push(() => {- persistence.dispose();- editor.dispose();- });- const edit = (text: string) =>- editor.execute(setShapeLabelCommand, {- id: 'welcome-rectangle',- label: {- content: plainRichText(text),- fontSize: 24,- fontFamily: 'sans',- height: 32,- },- });- return { editor, persistence, edit, save };-}--it('does not save on load, view changes, or in read-only mode', async () => {- const { editor, persistence, edit, save } = setup(undefined, () => false);- editor.panBy({ x: 10, y: 20 });- await vi.advanceTimersByTimeAsync(1000);- await persistence.flush();- expect(save).not.toHaveBeenCalled();- edit('Blocked');- await vi.advanceTimersByTimeAsync(1000);- await persistence.flush();- expect(save).not.toHaveBeenCalled();-});--it('debounces edits and round-trips a versioned snapshot', async () => {- const { editor, persistence, edit, save } = setup();- await persistence.flush();- expect(save).not.toHaveBeenCalled();- edit('One');- edit('Two');- await vi.advanceTimersByTimeAsync(500);- expect(save).toHaveBeenCalledTimes(1);- expect(save.mock.calls[0]?.[0]).toEqual({- version: 2,- document: editor.document,- });- expect(persistence.dirty()).toBe(false);-});--it('serializes saves and drains edits made while a request is pending', async () => {- let finish!: (blob: Blob) => void;- const save = vi.fn(- (_file: CanvasFile) =>- new Promise<Blob>((resolve) => {- finish = resolve;- })- );- const { editor, persistence, edit } = setup(save);- edit('First');- const flushing = persistence.flush();- edit('Second');- await vi.advanceTimersByTimeAsync(500);- expect(save).toHaveBeenCalledTimes(1);- finish(new Blob());- await Promise.resolve();- expect(save).toHaveBeenCalledTimes(2);- expect(save.mock.calls[1]?.[0].document).toBe(editor.document);- finish(new Blob());- await flushing;- expect(persistence.status()).toBe('saved');-});--it('keeps failed edits dirty and retries the latest snapshot', async () => {- const save = vi- .fn(async (_file: CanvasFile) => new Blob())- .mockRejectedValueOnce(new Error('offline'));- const { editor, persistence, edit } = setup(save);- edit('Unsaved');- await persistence.flush();- expect(persistence.status()).toBe('error');- expect(persistence.dirty()).toBe(true);- edit('Newest');- await persistence.flush();- expect(save.mock.calls[1]?.[0].document).toBe(editor.document);- expect(persistence.dirty()).toBe(false);-});--it('rechecks permissions after a queued edit', async () => {- let writable = true;- const { persistence, edit, save } = setup(undefined, () => writable);- edit('Change');- writable = false;- await vi.advanceTimersByTimeAsync(500);- expect(save).not.toHaveBeenCalled();- expect(persistence.dirty()).toBe(true);-});diff --git a/apps/web/src/features/block-canvas/primitives/create-document-persistence.ts b/apps/web/src/features/block-canvas/primitives/create-document-persistence.tsdeleted file mode 100644index f5a2352050..0000000000--- a/apps/web/src/features/block-canvas/primitives/create-document-persistence.ts+++ /dev/null@@ -1,76 +0,0 @@-import { fireAndForget } from '@core/util/fireAndForget';-import type { GraphicsEditor } from '@macro-inc/graphics';-import { createSignal } from 'solid-js';-import type { CanvasDocumentSource } from '../context/document-source';-import type { CanvasFile } from '../core/document-format';--export function createDocumentPersistence(- editor: GraphicsEditor,- initial: CanvasFile,- source: CanvasDocumentSource-) {- const [status, setStatus] = createSignal<- 'saved' | 'pending' | 'saving' | 'error'- >('saved');- const [savedFile, setSavedFile] = createSignal<Blob>();- let saved = editor.document;- let timer: ReturnType<typeof setTimeout> | undefined;- let running: Promise<void> | undefined;- let disposed = false;- const dirty = () => editor.document !== saved;- async function drain() {- while (dirty() && source.canEdit()) {- const snapshot = editor.document;- setStatus('saving');- try {- const file = await source.save({ ...initial, document: snapshot });- saved = snapshot;- setSavedFile(file);- } catch {- setStatus('error');- return;- }- }- setStatus(dirty() ? 'pending' : 'saved');- }- function flush(): Promise<void> {- clearTimeout(timer);- if (running) return running;- running = drain();- return finishRun(running);- }- async function finishRun(promise: Promise<void>) {- try {- await promise;- } finally {- running = undefined;- }- }- const unsubscribe = editor.subscribeDocument(() => {- if (disposed) return;- if (!dirty()) {- clearTimeout(timer);- setStatus(running ? 'saving' : 'saved');- return;- }- if (!source.canEdit()) return;- setStatus('pending');- clearTimeout(timer);- timer = setTimeout(() => {- fireAndForget(flush(), 'canvas-persistence');- }, 500);- });- return {- status,- savedFile,- dirty,- flush,- dispose() {- disposed = true;- unsubscribe();- clearTimeout(timer);- // The captured source keeps this document's identity even after navigation.- fireAndForget(flush(), 'canvas-persistence');- },- };-}diff --git a/apps/web/src/features/block-canvas/primitives/create-shared-reference-tracking.test.ts b/apps/web/src/features/block-canvas/primitives/create-shared-reference-tracking.test.tsnew file mode 100644index 0000000000..0863ba99e3--- /dev/null+++ b/apps/web/src/features/block-canvas/primitives/create-shared-reference-tracking.test.ts@@ -0,0 +1,117 @@+import {+ createGraphicsEditorFromBackend,+ createScene,+ translation,+} from '@macro-inc/graphics';+import { createLoroGraphicsBackendFromDoc } from '@macro-inc/graphics/loro';+import { LoroDoc } from 'loro-crdt';+import { createRoot } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import { createCanvasSeed, readSharedCanvas } from '../core/collaboration';+import { createSharedReferenceTracking } from './create-shared-reference-tracking';++const cleanups: (() => void)[] = [];+afterEach(() => {+ cleanups+ .splice(0)+ .reverse()+ .forEach((close) => close());+ vi.useRealTimers();+});+it('keeps reference retirement durable until the scene reaches the server, then retries it on reopen', async () => {+ vi.useFakeTimers();+ const doc = new LoroDoc();+ doc.import(+ createCanvasSeed(+ {+ version: 2,+ document: createScene([+ {+ id: 'card',+ type: 'document',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(0, 0),+ appearance: { fill: 'none', stroke: 'none' },+ geometry: {+ documentId: 'target',+ fileType: 'md',+ name: 'Target',+ width: 340,+ height: 136,+ },+ },+ ]),+ },+ 'source'+ )+ );+ const backend = createLoroGraphicsBackendFromDoc(doc, 'scene-root');+ const editor = createGraphicsEditorFromBackend(backend);+ cleanups.push(() => {+ editor.dispose();+ backend.dispose();+ doc.free();+ });+ const create = vi.fn(async () => 'mention-1');+ const remove = vi.fn(async () => {});+ const delivered = vi.fn(async () => false);+ let stop = () => {};+ createRoot((dispose) => {+ stop = dispose;+ cleanups.push(dispose);+ createSharedReferenceTracking(doc, 'source', () => true, delivered, {+ create,+ remove,+ });+ });+ await vi.advanceTimersByTimeAsync(500);+ expect(create).toHaveBeenCalledOnce();+ expect(editor.getSession().canUndo).toBe(false);+ editor.select('card');+ editor.deleteSelection();+ await vi.advanceTimersByTimeAsync(500);+ expect(remove).not.toHaveBeenCalled();+ expect(+ readSharedCanvas(doc, 'source').referenceTracking?.pendingRemoval+ ).toEqual(['mention-1']);+ stop();+ delivered.mockResolvedValue(true);+ createRoot((dispose) => {+ cleanups.push(dispose);+ createSharedReferenceTracking(doc, 'source', () => true, delivered, {+ create,+ remove,+ });+ });+ await vi.advanceTimersByTimeAsync(500);+ expect(remove).toHaveBeenCalledWith('mention-1');+ expect(+ readSharedCanvas(doc, 'source').referenceTracking?.pendingRemoval+ ).toEqual([]);+});+it('a copied shared document exports no reference ids owned by the source canvas', () => {+ const doc = new LoroDoc();+ doc.import(+ createCanvasSeed(+ {+ version: 2,+ document: createScene([]),+ referenceTracking: {+ sourceId: 'source',+ mentions: [{ targetId: 'target', mentionId: 'original-mention' }],+ pendingRemoval: ['original-retiring'],+ },+ },+ 'source'+ )+ );+ try {+ expect(readSharedCanvas(doc, 'copy').referenceTracking).toEqual({+ sourceId: 'copy',+ mentions: [],+ pendingRemoval: [],+ });+ } finally {+ doc.free();+ }+});diff --git a/apps/web/src/features/block-canvas/primitives/create-shared-reference-tracking.ts b/apps/web/src/features/block-canvas/primitives/create-shared-reference-tracking.tsnew file mode 100644index 0000000000..d452ffd530--- /dev/null+++ b/apps/web/src/features/block-canvas/primitives/create-shared-reference-tracking.ts@@ -0,0 +1,73 @@+import { fireAndForget } from '@core/util/fireAndForget';+import { GRAPHICS_METADATA_ORIGIN } from '@macro-inc/graphics/loro';+import type { LoroDoc } from 'loro-crdt';+import { onCleanup } from 'solid-js';+import type { CanvasReferenceSource } from '../context/reference-source';+import { readSharedCanvas } from '../core/collaboration';+import { canvasReferenceTargets } from '../core/references';++/** Track mentions in shared maps, including every concurrently created mention. */+export function createSharedReferenceTracking(+ doc: LoroDoc,+ documentId: string,+ canEdit: () => boolean,+ delivered: () => Promise<boolean>,+ references: CanvasReferenceSource+) {+ const mentions = doc.getMap(`canvasMentions:${documentId}`);+ const retiring = doc.getMap(`canvasRetiring:${documentId}`);+ let disposed = false;+ let timer: ReturnType<typeof setTimeout> | undefined;+ let running = false;+ const targets = () => canvasReferenceTargets(readSharedCanvas(doc).document);+ const writable = () => !disposed && canEdit();+ async function reconcile() {+ if (!writable() || running) return;+ running = true;+ try {+ for (const target of targets()) {+ if (!writable()) return;+ if (Object.values(mentions.toJSON()).includes(target)) continue;+ const id = await references.create(target);+ if (!writable()) return;+ mentions.set(id, target);+ doc.commit({ origin: GRAPHICS_METADATA_ORIGIN });+ }+ for (const [id, target] of Object.entries(mentions.toJSON())) {+ if (!writable()) return;+ if (typeof target === 'string' && targets().has(target)) continue;+ retiring.set(id, true);+ mentions.delete(id);+ doc.commit({ origin: GRAPHICS_METADATA_ORIGIN });+ }+ if (!writable() || !retiring.keys().length || !(await delivered()))+ return;+ if (!writable()) return;+ // Never untrack a reference until its scene deletion and retirement are durable.+ for (const id of retiring.keys()) {+ if (!writable()) return;+ await references.remove(id);+ if (!writable()) return;+ retiring.delete(id);+ doc.commit({ origin: GRAPHICS_METADATA_ORIGIN });+ }+ } finally {+ running = false;+ }+ }+ const schedule = () => {+ if (!writable()) return;+ clearTimeout(timer);+ timer = setTimeout(+ () => fireAndForget(reconcile(), 'canvas-references'),+ 500+ );+ };+ const unsubscribe = doc.subscribe(schedule);+ schedule();+ onCleanup(() => {+ disposed = true;+ clearTimeout(timer);+ unsubscribe();+ });+}diff --git a/apps/web/src/features/block-canvas/primitives/create-text-state.test.ts b/apps/web/src/features/block-canvas/primitives/create-text-state.test.tsnew file mode 100644index 0000000000..2db8b47403--- /dev/null+++ b/apps/web/src/features/block-canvas/primitives/create-text-state.test.ts@@ -0,0 +1,100 @@+import {+ createGraphicsEditorFromBackend,+ createScene,+ translation,+} from '@macro-inc/graphics';+import { createLoroGraphicsBackendFromDoc } from '@macro-inc/graphics/loro';+import { LoroDoc } from 'loro-crdt';+import { createRoot } from 'solid-js';+import { afterEach, expect, it } from 'vitest';+import { createCanvasSeed } from '../core/collaboration';+import { plainRichText } from '../core/text-codec';+import { createTextState } from './create-text-state';++const dispose: (() => void)[] = [];+afterEach(() =>+ dispose+ .splice(0)+ .reverse()+ .forEach((close) => close())+);+function peers() {+ const scene = createScene([+ {+ id: 'text',+ type: 'text',+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: translation(10, 20),+ appearance: { fill: 'transparent', stroke: 'black' },+ geometry: {+ width: 100,+ height: 32,+ fontSize: 24,+ fontFamily: 'sans',+ autoWidth: true,+ content: plainRichText('Before'),+ },+ },+ ]);+ const seed = createCanvasSeed({ version: 2, document: scene });+ const make = () => {+ const doc = new LoroDoc();+ doc.import(seed);+ const backend = createLoroGraphicsBackendFromDoc(doc, scene.rootId);+ const editor = createGraphicsEditorFromBackend(backend);+ dispose.push(() => {+ editor.dispose();+ backend.dispose();+ doc.free();+ });+ const text = createRoot((close) => {+ dispose.push(close);+ return createTextState(+ editor,+ (geometry) => ({ width: geometry.width, height: geometry.height }),+ () => ({ fill: 'transparent', stroke: 'black' })+ );+ });+ return { doc, editor, text };+ };+ return { a: make(), b: make() };+}+it('finishing an unchanged draft preserves a remote text edit', () => {+ const { a, b } = peers();+ a.text.edit('text');+ b.text.edit('text');+ b.text.change(plainRichText('Remote'));+ b.text.finish();+ a.doc.import(b.doc.export({ mode: 'update' }));+ a.text.finish();+ expect(a.editor.document.items.text).toMatchObject({+ geometry: { content: plainRichText('Remote') },+ });+});+it('remote deletion closes a draft without resurrecting the text', () => {+ const { a, b } = peers();+ a.text.edit('text');+ a.text.change(plainRichText('Unsaved'));+ b.editor.select('text');+ b.editor.deleteSelection();+ a.doc.import(b.doc.export({ mode: 'update' }));+ expect(a.text.draft()).toBeUndefined();+ a.text.finish();+ expect(a.editor.document.items.text).toBeUndefined();+});+it('a remote move updates the typing overlay and survives the completed text edit', () => {+ const { a, b } = peers();+ a.text.edit('text');+ a.text.change(plainRichText('Local'));+ b.editor.select('text');+ b.editor.beginTransform('text', { x: 0, y: 0 });+ b.editor.updateTransform({ x: 60, y: 0 });+ b.editor.commitTransform();+ a.doc.import(b.doc.export({ mode: 'update' }));+ expect(a.text.draft()?.transform).toEqual(translation(70, 20));+ a.text.finish();+ expect(a.editor.document.items.text).toMatchObject({+ transform: translation(70, 20),+ geometry: { content: plainRichText('Local') },+ });+});diff --git a/apps/web/src/features/block-canvas/primitives/create-text-state.ts b/apps/web/src/features/block-canvas/primitives/create-text-state.tsindex 08848dad83..3991823bdc 100644--- a/apps/web/src/features/block-canvas/primitives/create-text-state.ts+++ b/apps/web/src/features/block-canvas/primitives/create-text-state.ts@@ -25,7 +25,7 @@ import {withShapeLabel,worldMatrix,} from '@macro-inc/graphics';-import { createSignal } from 'solid-js';+import { createSignal, onCleanup } from 'solid-js';import {plainRichText,richTextPlainText,@@ -41,6 +41,8 @@ export function createTextState(| { kind: 'text'; item: ShapeItem<'text'> }| { kind: 'label'; item: LabelShape };const [editing, setEditing] = createSignal<TextDraft>();+ let original: string | undefined;+ let existing = false;const draft = () => {const current = editing();if (current?.kind === 'label' && current.item.type === 'connector') {@@ -67,6 +69,28 @@ export function createTextState(Pick<TextGeometry, 'fontSize' | 'fontFamily' | 'autoWidth'>>({ fontSize: 24, fontFamily: 'sans', autoWidth: true });let flush: (() => void) | undefined;+ // Keep a typing draft attached to the current pose and never resurrect a+ // remotely deleted item when the local editor later blurs or unmounts.+ onCleanup(+ editor.subscribeDocument(() => {+ const current = editing();+ if (!current || !existing) return;+ const item = editor.document.items[current.item.id];+ if (!item || item.type !== current.item.type) {+ setEditing(undefined);+ flush = undefined;+ return;+ }+ const pose = {+ placement: item.placement,+ transform: item.transform,+ appearance: item.appearance,+ };+ if (current.kind === 'text')+ setEditing({ ...current, item: { ...current.item, ...pose } });+ else setEditing({ ...current, item: { ...current.item, ...pose } });+ })+ );const resize = (geometry: TextGeometry) =>textDefinition.freezeGeometry({ ...geometry, ...measure(geometry) });function update(patch: Partial<TextGeometry>) {@@ -105,6 +129,11 @@ export function createTextState(const current = editing();setEditing(undefined);flush = undefined;+ const value =+ current?.kind === 'text'+ ? current.item.geometry+ : current?.item.geometry.label;+ if (existing && JSON.stringify(value) === original) return;if (current?.kind === 'text') {if (richTextPlainText(current.item.geometry.content).trim())editor.execute(setTextCommand, current.item);@@ -156,6 +185,8 @@ export function createTextState(function begin(point: Point, width?: number) {finish();editor.select();+ existing = false;+ original = undefined;setEditing({kind: 'text',item: createItem(point, width, plainRichText()),@@ -178,6 +209,10 @@ export function createTextState(: item.geometry.label?.content;if (content !== undefined && !validCanvasText(content)) return;editor.select(id);+ existing = true;+ original = JSON.stringify(+ item.type === 'text' ? item.geometry : item.geometry.label+ );if (item.type === 'text') setEditing({ kind: 'text', item });else {const content = plainRichText('', 'center');diff --git a/apps/web/src/features/block-canvas/primitives/create-tracked-document-source.test.ts b/apps/web/src/features/block-canvas/primitives/create-tracked-document-source.test.tsdeleted file mode 100644index 8ac68ce7e4..0000000000--- a/apps/web/src/features/block-canvas/primitives/create-tracked-document-source.test.ts+++ /dev/null@@ -1,131 +0,0 @@-import { createScene, translation } from '@macro-inc/graphics';-import { expect, it, vi } from 'vitest';-import type { CanvasFile } from '../core/document-format';-import { readCanvasFile } from '../core/document-format';-import { createTrackedCanvasDocumentSource } from './create-tracked-document-source';--function canvas(...targets: string[]): CanvasFile {- return {- version: 2,- document: createScene(- targets.map((target, index) => ({- id: `shape-${index}`,- type: 'document' as const,- placement: { parentId: 'scene-root', sortKey: `a${index}` },- transform: translation(0, 0),- appearance: { fill: 'none', stroke: 'none' },- geometry: {- documentId: target,- name: target,- fileType: 'md',- width: 340,- height: 136,- },- }))- ),- };-}-function setup(initial = canvas()) {- const create = vi.fn(- async (target: string) => `${target}-${create.mock.calls.length}`- );- const remove = vi.fn(async (_id: string) => {});- const save = vi.fn(async (_file: CanvasFile) => new Blob());- const canEdit = vi.fn(() => true);- const source = createTrackedCanvasDocumentSource(- 'source',- initial,- { canEdit, save },- { create, remove }- );- return { source, create, remove, save, canEdit };-}--it('tracks one mention per target and preserves IDs across saves and reopening', async () => {- const s = setup();- await s.source.save(canvas('a', 'a', 'b'));- expect(s.create.mock.calls).toEqual([['a'], ['b']]);- const saved = readCanvasFile(s.save.mock.calls[0]![0]);- expect(saved.referenceTracking?.mentions).toHaveLength(2);- await s.source.save(canvas('a', 'b'));- expect(s.remove).not.toHaveBeenCalled();- expect(s.create).toHaveBeenCalledTimes(2);- const reopened = setup(saved);- await reopened.source.save(canvas('a', 'b'));- expect(reopened.create).not.toHaveBeenCalled();-});--it('untracks only after the last card is saved as removed and registers undo/redo', async () => {- const s = setup();- await s.source.save(canvas('a', 'a'));- await s.source.save(canvas('a'));- expect(s.remove).not.toHaveBeenCalled();- await s.source.save(canvas());- expect(- s.save.mock.calls.at(-1)?.[0].referenceTracking?.pendingRemoval- ).toEqual(['a-1']);- expect(s.remove).toHaveBeenCalledWith('a-1');- expect(s.save.mock.invocationCallOrder.at(-1)!).toBeLessThan(- s.remove.mock.invocationCallOrder[0]!- );- await s.source.save(canvas('a'));- expect(s.create).toHaveBeenCalledTimes(2);- await s.source.save(canvas());- expect(s.remove).toHaveBeenLastCalledWith('a-2');-});--it('keeps IDs across failed saves and defers untracking until a successful retry', async () => {- const s = setup();- s.save.mockRejectedValueOnce(new Error('offline'));- await expect(s.source.save(canvas('a'))).rejects.toThrow('offline');- await s.source.save(canvas('a'));- expect(s.create).toHaveBeenCalledOnce();- s.save.mockRejectedValueOnce(new Error('offline'));- await expect(s.source.save(canvas())).rejects.toThrow('offline');- expect(s.remove).not.toHaveBeenCalled();- await s.source.save(canvas());- expect(s.remove).toHaveBeenCalledWith('a-1');-});--it('persists pending removals so a reopened file can retry failed cleanup', async () => {- const s = setup();- await s.source.save(canvas('a'));- s.remove.mockRejectedValueOnce(new Error('offline'));- await expect(s.source.save(canvas())).rejects.toThrow('offline');- const reopened = setup(s.save.mock.calls.at(-1)![0]);- await reopened.source.save(canvas());- expect(reopened.remove).toHaveBeenCalledWith('a-1');- await reopened.source.save(canvas());- expect(- reopened.save.mock.calls.at(-1)?.[0].referenceTracking?.pendingRemoval- ).toEqual([]);-});--it('does not use another canvas’s tracking IDs or mutate read-only documents', async () => {- const initial = canvas('a');- const s = setup({- ...initial,- referenceTracking: {- sourceId: 'other',- mentions: [{ targetId: 'a', mentionId: 'foreign' }],- pendingRemoval: ['foreign-old'],- },- });- await s.source.save(initial);- expect(s.create).toHaveBeenCalledWith('a');- expect(s.remove).not.toHaveBeenCalled();- s.canEdit.mockReturnValue(false);- await expect(s.source.save(canvas())).rejects.toThrow('read-only');- expect(s.remove).not.toHaveBeenCalled();- expect(s.save).toHaveBeenCalledOnce();-});--it('retries a failed registration without creating duplicates for earlier targets', async () => {- const s = setup();- s.create- .mockResolvedValueOnce('mention-a')- .mockRejectedValueOnce(new Error('offline'));- await expect(s.source.save(canvas('a', 'b'))).rejects.toThrow('offline');- await s.source.save(canvas('a', 'b'));- expect(s.create.mock.calls).toEqual([['a'], ['b'], ['b']]);-});diff --git a/apps/web/src/features/block-canvas/primitives/create-tracked-document-source.ts b/apps/web/src/features/block-canvas/primitives/create-tracked-document-source.tsdeleted file mode 100644index f70c0ef771..0000000000--- a/apps/web/src/features/block-canvas/primitives/create-tracked-document-source.ts+++ /dev/null@@ -1,62 +0,0 @@-import type { CanvasDocumentSource } from '../context/document-source';-import type { CanvasReferenceSource } from '../context/reference-source';-import type { CanvasFile } from '../core/document-format';-import { canvasReferenceTargets } from '../core/references';--/** Called by serialized document persistence, so tracking follows saved snapshots. */-export function createTrackedCanvasDocumentSource(- sourceId: string,- initial: CanvasFile,- documentSource: CanvasDocumentSource,- references: CanvasReferenceSource-): CanvasDocumentSource {- // A file copied to a different canvas must never remove the original's mentions.- const stored =- initial.referenceTracking?.sourceId === sourceId- ? initial.referenceTracking- : undefined;- const active = new Map(- stored?.mentions.map(({ targetId, mentionId }) => [targetId, mentionId])- );- const retiring = new Set(stored?.pendingRemoval);- const requireEdit = () => {- if (!documentSource.canEdit()) throw new Error('This canvas is read-only');- };- return {- canEdit: documentSource.canEdit,- async save(canvas) {- requireEdit();- const targets = canvasReferenceTargets(canvas.document);- for (const [target, mention] of active) {- if (targets.has(target)) continue;- retiring.add(mention);- active.delete(target);- }- for (const target of targets) {- if (active.has(target)) continue;- requireEdit();- active.set(target, await references.create(target));- }- requireEdit();- const file = await documentSource.save({- ...canvas,- referenceTracking: {- sourceId,- mentions: Array.from(active, ([targetId, mentionId]) => ({- targetId,- mentionId,- })),- pendingRemoval: [...retiring],- },- });- // Never untrack a card until its deletion is durable. On failure these IDs- // remain both in memory and in the saved file for an idempotent retry.- for (const mention of retiring) {- requireEdit();- await references.remove(mention);- retiring.delete(mention);- }- return file;- },- };-}diff --git a/apps/web/src/features/block-canvas/queries/canvas-document.test.ts b/apps/web/src/features/block-canvas/queries/canvas-document.test.tsindex 520d07dc77..974f59bfcc 100644--- a/apps/web/src/features/block-canvas/queries/canvas-document.test.ts+++ b/apps/web/src/features/block-canvas/queries/canvas-document.test.ts@@ -1,11 +1,9 @@-import { createGraphicsEditor } from '@macro-inc/graphics';import { ok } from 'neverthrow';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { fetchCanvasViewLocation, saveCanvasDocument } from './canvas-document';+import { fetchCanvasViewLocation } from './canvas-document';const storageMocks = vi.hoisted(() => ({getDocumentMetadata: vi.fn(),- simpleSave: vi.fn(),}));vi.mock('@service-storage/client', () => ({@@ -28,28 +26,4 @@ describe('canvas document queries', () => {scale: 125,});});-- it('stores version 2 through the same JSON endpoint and MIME type', async () => {- storageMocks.simpleSave.mockResolvedValue(ok({}));- const editor = createGraphicsEditor();- const canvas = { version: 2 as const, document: editor.document };- const result = await saveCanvasDocument('canvas-next', canvas);- expect(result.saved).toBe(true);- expect(result.file.type).toBe('application/x-macro-canvas');- expect(JSON.parse(await readBlob(result.file))).toEqual(canvas);- expect(storageMocks.simpleSave).toHaveBeenCalledWith({- documentId: 'canvas-next',- file: result.file,- });- editor.dispose();- });});--function readBlob(blob: Blob) {- return new Promise<string>((resolve, reject) => {- const reader = new FileReader();- reader.addEventListener('load', () => resolve(String(reader.result)));- reader.addEventListener('error', () => reject(reader.error));- reader.readAsText(blob);- });-}diff --git a/apps/web/src/features/block-canvas/queries/canvas-document.ts b/apps/web/src/features/block-canvas/queries/canvas-document.tsindex d39d215556..c02a0b973e 100644--- a/apps/web/src/features/block-canvas/queries/canvas-document.ts+++ b/apps/web/src/features/block-canvas/queries/canvas-document.ts@@ -1,5 +1,4 @@import { storageServiceClient } from '@service-storage/client';-import type { CanvasFile } from '../core/document-format';export type CanvasViewLocation = {x?: number;@@ -29,21 +28,6 @@ export async function fetchCanvasViewLocation(};}-export async function saveCanvasDocument(- documentId: string,- canvas: CanvasFile-): Promise<{ file: Blob; saved: boolean }> {- const buffer = new TextEncoder().encode(JSON.stringify(canvas));- const file = new Blob([buffer], {- type: 'application/x-macro-canvas',- });- const result = await storageServiceClient.simpleSave({- documentId,- file,- });- return { file, saved: result.isOk() };-}-export async function saveCanvasViewLocation(documentId: string,state: { x: number; y: number; scale: number }diff --git a/apps/web/src/features/block-canvas/queries/canvas-session.test.ts b/apps/web/src/features/block-canvas/queries/canvas-session.test.tsnew file mode 100644index 0000000000..f6f12ebd7b--- /dev/null+++ b/apps/web/src/features/block-canvas/queries/canvas-session.test.ts@@ -0,0 +1,311 @@+import { noopChatter } from '@macro-inc/collaboration/collab/chatter';+import type { SnapshotStore } from '@macro-inc/collaboration/collab/snapshot-store';+import {+ createNoopLiveSyncSource,+ type SyncSourceEvent,+ SyncSourceStatus,+} from '@macro-inc/collaboration/collab/source';+import { InMemoryWALStore } from '@macro-inc/collaboration/collab/wal';+import {+ createGraphicsEditorFromBackend,+ translation,+ worldMatrix,+} from '@macro-inc/graphics';+import { createLoroGraphicsBackendFromDoc } from '@macro-inc/graphics/loro';+import { LoroDoc } from 'loro-crdt';+import { errAsync, okAsync } from 'neverthrow';+import { createEffect, createRoot, createSignal, on } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import { createCanvasSeed, readSharedCanvas } from '../core/collaboration';+import { createCanvasNextScene } from '../core/seed-scene';+import {+ type CanvasSession,+ type CanvasSessionOptions,+ createCanvasSession,+} from './canvas-session';++const initial = { version: 2, document: createCanvasNextScene() } as const;+const disposers: (() => void)[] = [];+afterEach(() => {+ disposers+ .splice(0)+ .reverse()+ .forEach((dispose) => dispose());+});++function persistence() {+ let stored: Uint8Array | null = null;+ const snapshots: SnapshotStore<Uint8Array> = {+ load: async () => stored,+ save: async (value) => {+ stored = value;+ },+ delete: async () => {+ stored = null;+ },+ };+ return {+ snapshots,+ wal: new InMemoryWALStore<Uint8Array>(),+ makeChatter: noopChatter,+ };+}+function ready(session: CanvasSession): Promise<LoroDoc> {+ return new Promise((resolve, reject) =>+ createRoot((dispose) => {+ disposers.push(dispose);+ createEffect(+ on(session.state, (state) => {+ if (state.t === 'ready') {+ dispose();+ resolve(state.doc);+ } else if (state.t === 'error') {+ dispose();+ reject(new Error(state.message));+ }+ })+ );+ })+ );+}+function open(+ options: Partial<CanvasSessionOptions> & Pick<CanvasSessionOptions, 'connect'>+) {+ return createRoot((dispose) => {+ disposers.push(dispose);+ const session = createCanvasSession({+ documentId: 'canvas-1',+ initial,+ canEdit: () => true,+ exists: async () => true,+ initialize: async () => {},+ persistence: persistence(),+ ...options,+ });+ return { ...session, close: dispose };+ });+}+function room() {+ const server = new LoroDoc();+ server.import(createCanvasSeed(initial, 'canvas-1'));+ disposers.push(() => server.free());+ const clients = new Set<(event: SyncSourceEvent) => void>();+ const [online, setOnline] = createSignal(true);+ const connect = () => {+ const listeners = new Set<(event: SyncSourceEvent) => void>();+ const emit = (event: SyncSourceEvent) => {+ for (const listener of listeners) listener(event);+ };+ clients.add(emit);+ return {+ source: {+ ...createNoopLiveSyncSource('canvas-1'),+ status: () =>+ online() ? SyncSourceStatus.Connected : SyncSourceStatus.Disconnected,+ listen: (listener: (event: SyncSourceEvent) => void) => {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ pushUpdate: async (updates: Uint8Array[]) => {+ if (!online()) return false;+ for (const update of updates) {+ server.import(update);+ for (const client of clients)+ if (client !== emit) client({ type: 'update', update });+ }+ return true;+ },+ requestUpdatesSince: (from: import('loro-crdt').VersionVector) =>+ okAsync(server.export({ mode: 'update', from })),+ requestSnapshot: () => okAsync(server.export({ mode: 'snapshot' })),+ pushAwareness: (awareness: Uint8Array) => {+ if (online())+ for (const client of clients)+ if (client !== emit) client({ type: 'awareness', awareness });+ },+ cleanup: () => {+ clients.delete(emit);+ },+ },+ doInitialSync: () =>+ online()+ ? okAsync({+ snapshot: server.export({ mode: 'snapshot' }),+ awareness: new Uint8Array(),+ })+ : errAsync({ type: 'connection_failed' } as const),+ };+ };+ const reconnect = () => {+ setOnline(true);+ const initial = {+ snapshot: server.export({ mode: 'snapshot' }),+ awareness: new Uint8Array(),+ };+ for (const client of clients) client({ type: 'reconnect', ...initial });+ };+ return {+ server,+ connect,+ setOnline,+ reconnect,+ emit: (event: SyncSourceEvent) => {+ for (const client of clients) client(event);+ },+ };+}+function editor(doc: LoroDoc, canEdit = () => true) {+ const backend = createLoroGraphicsBackendFromDoc(+ doc,+ initial.document.rootId,+ canEdit+ );+ const editor = createGraphicsEditorFromBackend(backend);+ disposers.push(backend.dispose, editor.dispose);+ return editor;+}++it('three durable sessions merge independent edits and undo only local history', async () => {+ const server = room();+ const sessions = [open(server), open(server), open(server)];+ const docs = await Promise.all(sessions.map(ready));+ const editors = docs.map((doc) => editor(doc));+ const id = 'welcome-rectangle';+ editors[0]!.select(id);+ editors[0]!.beginTransform(id, { x: 0, y: 0 });+ editors[0]!.updateTransform({ x: 40, y: 0 });+ editors[0]!.commitTransform();+ editors[1]!.select(id);+ editors[1]!.setSelectionAppearance({ fill: 'red' });+ editors[2]!.select(id);+ editors[2]!.setSelectionAppearance({ stroke: 'blue' });+ await Promise.all(sessions.map((session) => session.flush()));+ // A real remote document event settles after the engine's import mutex.+ await new Promise<void>((resolve) => queueMicrotask(resolve));+ for (const e of editors) {+ expect(e.document).toEqual(editors[0]!.document);+ expect(worldMatrix(e.document, id)[4]).toBe(140);+ expect(e.document.items[id]).toMatchObject({+ appearance: { fill: 'red', stroke: 'blue' },+ });+ }+ editors[0]!.undo();+ await sessions[0]!.flush();+ await new Promise<void>((resolve) => queueMicrotask(resolve));+ expect(editors[1]!.document.items[id]).toMatchObject({+ transform: translation(100, 100),+ appearance: { fill: 'red' },+ });+});++it('recovers undelivered local edits on reload and delivers them after reconnect', async () => {+ const server = room();+ const stored = persistence();+ const session = open({ ...server, persistence: stored });+ const local = editor(await ready(session));+ server.setOnline(false);+ local.select('welcome-rectangle');+ local.setSelectionAppearance({ fill: 'orange' });+ expect(await session.flush()).toBe(false);+ expect((await stored.wal.getAll()).length).toBeGreaterThan(0);+ const reopened = open({ ...server, persistence: stored });+ const recovered = await ready(reopened);+ expect(+ readSharedCanvas(recovered).document.items['welcome-rectangle']+ ).toMatchObject({ appearance: { fill: 'orange' } });+ server.reconnect();+ await reopened.flush();+ expect(+ readSharedCanvas(server.server).document.items['welcome-rectangle']+ ).toMatchObject({ appearance: { fill: 'orange' } });+});++it('uses the winning server seed when another initializer wins', async () => {+ const server = room();+ const initialize = vi.fn(async () => {+ throw new Error('conflict');+ });+ let calls = 0;+ const session = open({+ ...server,+ exists: async () => ++calls > 1,+ initialize,+ });+ await ready(session);+ expect(initialize).toHaveBeenCalledOnce();+ expect(readSharedCanvas(await ready(session))).toEqual(+ readSharedCanvas(server.server)+ );+});++it('read-only sessions cannot seed a canvas or commit scene edits', async () => {+ const server = room();+ const initialize = vi.fn(async () => {});+ const session = open({ ...server, canEdit: () => false, initialize });+ const shared = await ready(session);+ const view = editor(shared, () => false);+ const before = shared.export({ mode: 'snapshot' });+ view.select('welcome-rectangle');+ view.setSelectionAppearance({ fill: 'pink' });+ expect(shared.export({ mode: 'snapshot' })).toEqual(before);+ expect(initialize).not.toHaveBeenCalled();+});++it('retries failed local WAL appends without replacing or losing the live scene', async () => {+ const server = room();+ const stored = persistence();+ const session = open({ ...server, persistence: stored });+ const doc = await ready(session);+ const local = editor(doc);+ const append = vi+ .spyOn(stored.wal, 'append')+ .mockRejectedValue(new Error('Disk unavailable'));+ local.select('welcome-rectangle');+ local.setSelectionAppearance({ fill: 'purple' });+ expect(await session.flush()).toBe(false);+ expect(session.failure()).toBeDefined();+ expect(+ readSharedCanvas(doc).document.items['welcome-rectangle']+ ).toMatchObject({ appearance: { fill: 'purple' } });+ append.mockRestore();+ expect(await session.retrySave()).toBe(true);+ expect(session.failure()).toBeUndefined();+ expect(+ readSharedCanvas(server.server).document.items['welcome-rectangle']+ ).toMatchObject({ appearance: { fill: 'purple' } });+ const current = session.state();+ expect(current.t === 'ready' ? current.doc : undefined).toBe(doc);+});++it('replays undelivered edits before exposing a replacement document after sync recovery', async () => {+ const server = room();+ const session = open(server);+ const original = await ready(session);+ const local = editor(original);+ server.setOnline(false);+ local.select('welcome-rectangle');+ local.setSelectionAppearance({ fill: 'gold' });+ await session.flush();+ const replacement = new Promise<LoroDoc>((resolve, reject) =>+ createRoot((dispose) => {+ disposers.push(dispose);+ createEffect(+ on(session.state, (state) => {+ if (state.t === 'ready' && state.doc !== original) {+ dispose();+ resolve(state.doc);+ } else if (state.t === 'error') {+ dispose();+ reject(new Error(state.message));+ }+ })+ );+ })+ );+ server.emit({ type: 'update', update: new Uint8Array([0]) });+ expect(+ readSharedCanvas(await replacement).document.items['welcome-rectangle']+ ).toMatchObject({ appearance: { fill: 'gold' } });+});diff --git a/apps/web/src/features/block-canvas/queries/canvas-session.ts b/apps/web/src/features/block-canvas/queries/canvas-session.tsnew file mode 100644index 0000000000..79a825c826--- /dev/null+++ b/apps/web/src/features/block-canvas/queries/canvas-session.ts@@ -0,0 +1,534 @@+import {+ endTrackedDocumentSpan,+ registerDocumentSpan,+} from '@block-md/observability';+import { fireAndForget } from '@core/util/fireAndForget';+import { schema } from '@loro-mirror/core';+import { createAwareness } from '@macro-inc/collaboration/collab/awareness';+import type { Chatter } from '@macro-inc/collaboration/collab/chatter';+import { createSyncEngine } from '@macro-inc/collaboration/collab/engine';+import {+ LoroManager,+ LoroManagerError,+} from '@macro-inc/collaboration/collab/manager';+import {+ IDBSnapshotStore,+ LORO_SNAPSHOT_DB_NAME,+ loadCachedState,+ type SnapshotStore,+} from '@macro-inc/collaboration/collab/snapshot-store';+import {+ type InitialSync,+ type LiveSyncSource,+ SyncError,+ type SyncSourceEvent,+ SyncSourceStatus,+} from '@macro-inc/collaboration/collab/source';+import {+ BrowserWALStore,+ LORO_WAL_DB_NAME,+ type WALStore,+ WALSyncer,+} from '@macro-inc/collaboration/collab/wal';+import type { PeerPresence } from '@macro-inc/graphics/loro';+import { Telemetry } from '@macro-inc/observability';+import type { LoroDoc } from 'loro-crdt';+import { err, errAsync, type ResultAsync } from 'neverthrow';+import {+ type Accessor,+ createSignal,+ getOwner,+ onCleanup,+ runWithOwner,+} from 'solid-js';+import { createCanvasSeed, readSharedCanvas } from '../core/collaboration';+import type { CanvasFile } from '../core/document-format';+import { decodeCanvasPresence } from '../core/presence';++type CanvasConnection = {+ source: LiveSyncSource;+ doInitialSync: () => ResultAsync<InitialSync, SyncError>;+};+export type CanvasSessionOptions = {+ documentId: string;+ initial: CanvasFile;+ userId?: string;+ canEdit: Accessor<boolean>;+ exists: () => Promise<boolean>;+ initialize: (snapshot: Uint8Array) => Promise<void>;+ connect: () => CanvasConnection;+ authorize?: () => Promise<void>;+ persistence?: {+ snapshots: SnapshotStore<Uint8Array>;+ wal: WALStore<Uint8Array>;+ makeChatter?: (documentId: string) => Chatter;+ };+};+type CanvasSessionState =+ | { t: 'loading' }+ | { t: 'unshared' }+ | { t: 'ready'; doc: LoroDoc }+ | { t: 'error'; message: string };++// Successive mounts share an IndexedDB key. An old in-flight snapshot must+// finish before a replacement session loads its recovery base.+const snapshotOperations = new Map<string, Promise<void>>();+function serializeSnapshot<T>(+ id: string,+ operation: () => Promise<T>+): Promise<T> {+ const previous = snapshotOperations.get(id) ?? Promise.resolve();+ const run = async () => {+ await previous;+ return operation();+ };+ const result = run();+ const finish = async () => {+ try {+ await result;+ } catch {+ /* The caller observes the failure. */+ }+ if (snapshotOperations.get(id) === settled) snapshotOperations.delete(id);+ };+ const settled = finish();+ snapshotOperations.set(id, settled);+ return result;+}++/** Durable scene ownership uses the same engine, WAL and transport as documents. */+export function createCanvasSession(options: CanvasSessionOptions) {+ const owner = getOwner();+ let resetWork = Promise.resolve();+ class CanvasManager extends LoroManager {+ override reset(snapshot: Uint8Array) {+ const work = this.recoverSnapshot(snapshot);+ const settle = async () => {+ await work;+ };+ resetWork = settle();+ return work;+ }+ private async recoverSnapshot(snapshot: Uint8Array) {+ const from = this.doc.oplogVersion();+ const count = this.doc.opCount();+ try {+ // The engine stops before resetting. Capture a final typing draft in+ // the WAL explicitly, before replacing its document or history owner.+ finishEdits();+ if (this.doc.opCount() !== count)+ await wal.append(this.doc.export({ mode: 'update', from }));+ await lastAppend;+ if (disposed || failedUpdates.size)+ return err([+ {+ code: LoroManagerError.ImportFailed,+ message: 'Local canvas changes must be saved before recovery.',+ },+ ]);+ resetting = true;+ setState({ t: 'loading' });+ const result = await super.reset(snapshot);+ if (disposed) return result;+ if (result.isErr()) {+ setState({+ t: 'error',+ message:+ 'Unable to recover the shared canvas. Local changes were preserved.',+ });+ return result;+ }+ await replayWAL();+ if (disposed) return result;+ readSharedCanvas(this.doc);+ observeValidation();+ if (!disposed) setState({ t: 'ready', doc: this.doc });+ return result;+ } catch (cause) {+ if (!disposed && resetting)+ setState({+ t: 'error',+ message:+ 'Unable to recover canvas changes. Your local data was preserved.',+ });+ else if (!disposed)+ setFailure(+ 'Unable to recover canvas changes. Keep this tab open and download a copy.'+ );+ return err([+ {+ code: LoroManagerError.ImportFailed,+ message:+ cause instanceof Error+ ? cause.message+ : 'Canvas recovery failed.',+ },+ ]);+ } finally {+ from.free();+ resetting = false;+ }+ }+ }+ const manager = new CanvasManager(schema({}), {+ documentId: options.documentId,+ mirror: false,+ });+ const [state, setState] = createSignal<CanvasSessionState>({ t: 'loading' });+ const [connection, setConnection] = createSignal<CanvasConnection>();+ const [pending, setPending] = createSignal(false);+ const [appends, setAppends] = createSignal(0);+ const [failure, setFailure] = createSignal<string>();+ let disposed = false;+ let started = false;+ let resetting = false;+ const failedUpdates = new Set<Uint8Array>();+ let finishEdits = () => {};+ let validationDoc: LoroDoc | undefined;+ let stopValidation = () => {};+ let lastAppend = Promise.resolve();+ const walStore =+ options.persistence?.wal ??+ new BrowserWALStore<Uint8Array>(LORO_WAL_DB_NAME, options.documentId);+ const snapshotStore =+ options.persistence?.snapshots ??+ new IDBSnapshotStore<Uint8Array>(LORO_SNAPSHOT_DB_NAME, options.documentId);+ // Finish writes already in progress before releasing the document at teardown.+ let snapshotWork = Promise.resolve();+ const snapshots: SnapshotStore<Uint8Array> = {+ load: () =>+ serializeSnapshot(options.documentId, () => snapshotStore.load()),+ delete: () =>+ serializeSnapshot(options.documentId, () => snapshotStore.delete()),+ save(snapshot) {+ const save = async () => {+ if (disposed)+ throw new Error('Canvas session closed before snapshot save.');+ await snapshotStore.save(snapshot);+ };+ const work = serializeSnapshot(options.documentId, save);+ const settle = async () => {+ try {+ await work;+ } catch {+ /* Preserve the previous recovery base. */+ }+ };+ snapshotWork = settle();+ return work;+ },+ };+ class CanvasWAL extends WALSyncer<Uint8Array> {+ override append(update: Uint8Array): Promise<void> {+ setPending(true);+ setAppends((value) => value + 1);+ const previous = lastAppend;+ const work = super.append(update);+ const finish = async () => {+ try {+ await work;+ failedUpdates.delete(update);+ } catch {+ failedUpdates.add(update);+ setFailure(+ 'Canvas changes could not be saved locally. Keep this tab open.'+ );+ } finally {+ setAppends((value) => value - 1);+ }+ };+ const join = async () => {+ await Promise.all([previous, finish()]);+ };+ lastAppend = join();+ return lastAppend;+ }+ override async flush(): Promise<void> {+ await super.flush();+ if (!disposed) setPending((await this.summary()).dirty > 0);+ }+ }+ const wal = new CanvasWAL(+ walStore,+ (updates) =>+ options.canEdit()+ ? (connection()?.source.pushUpdate(updates) ?? Promise.resolve(false))+ : Promise.resolve(false),+ options.documentId+ );+ const awareness = createAwareness<string, PeerPresence | null>(+ manager.peerIdStr,+ options.userId,+ {+ encode: (value) => JSON.stringify(value),+ decode: decodeCanvasPresence,+ }+ );+ const listeners = new Set<(event: SyncSourceEvent) => void>();+ let peerId: bigint | undefined;+ const unavailable = () => errAsync(SyncError.connectionFailed());+ const live: LiveSyncSource = {+ documentId: options.documentId,+ status: () => connection()?.source.status() ?? SyncSourceStatus.Connecting,+ listen(listener) {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ pushUpdate: (updates) =>+ connection()?.source.pushUpdate(updates) ?? Promise.resolve(false),+ pushAwareness: (value) => connection()?.source.pushAwareness(value),+ registerPeerId(value) {+ peerId = value;+ connection()?.source.registerPeerId(value);+ },+ requestUpdatesSince: (version) =>+ connection()?.source.requestUpdatesSince(version) ?? unavailable(),+ requestSnapshot: () =>+ connection()?.source.requestSnapshot() ?? unavailable(),+ reconnect: () => connection()?.source.reconnect(),+ cleanup: () => connection()?.source.cleanup(),+ };+ const engine = createSyncEngine({+ loroManager: manager,+ awareness,+ syncs: { live, wal },+ bindings: { onRemoteState: () => {} },+ readonly: () => !options.canEdit(),+ snapshotStore: snapshots,+ makeChatter: options.persistence?.makeChatter,+ });+ const unsubscribeManager = manager.onStateChange(() => {+ if (!started || disposed || resetting) return;+ try {+ readSharedCanvas(manager.doc);+ observeValidation();+ setState({ t: 'ready', doc: manager.doc });+ } catch (cause) {+ setState({+ t: 'error',+ message:+ cause instanceof Error ? cause.message : 'Invalid shared canvas.',+ });+ }+ });+ function observeValidation() {+ if (validationDoc === manager.doc) return;+ stopValidation();+ validationDoc = manager.doc;+ stopValidation = manager.doc.subscribe((batch) => {+ if (disposed || batch.by !== 'import') return;+ try {+ readSharedCanvas(manager.doc);+ } catch (cause) {+ setState({+ t: 'error',+ message:+ cause instanceof Error ? cause.message : 'Invalid shared canvas.',+ });+ }+ });+ }+ async function start() {+ readSharedCanvas(manager.doc);+ await snapshots.save(manager.doc.export({ mode: 'snapshot' }));+ if (disposed) return;+ engine.start();+ started = true;+ observeValidation();+ setState({ t: 'ready', doc: manager.doc });+ if (options.canEdit()) await wal.flush();+ }+ async function accept(initial: InitialSync) {+ if (disposed) return;+ const result = manager.initialized+ ? manager.importUpdate(initial.snapshot)+ : await manager.initializeFromSnapshot(initial.snapshot);+ if (disposed) return;+ if (result.isErr())+ throw new Error(+ 'Unable to merge the shared canvas. Your local changes were preserved.'+ );+ // A lost/corrupt cache can leave valid undelivered WAL entries. Replay them+ // against the server seed too, before sending them or exposing the scene.+ await replayWAL();+ readSharedCanvas(manager.doc);+ if (initial.awareness.length)+ awareness.importRemoteAwareness(initial.awareness);+ if (!started) await start();+ if (options.canEdit()) await wal.flush();+ if (!failedUpdates.size) setFailure(undefined);+ }+ async function replayWAL() {+ for (const entry of await walStore.getAll()) {+ if (disposed) return;+ const replay = manager.importUpdate(entry.update);+ if (+ replay.isErr() &&+ !replay.error.every(+ (error) => error.code === LoroManagerError.ImportPending+ )+ )+ throw new Error(+ 'Unable to recover local canvas changes. Your local data was preserved.'+ );+ }+ }+ async function hydrate() {+ await wal.ready();+ if (disposed) return;+ const cached = await loadCachedState(manager, snapshots, walStore);+ if (disposed) return;+ if (cached) await start();+ await options.authorize?.();+ if (disposed) return;+ if (!cached && !(await options.exists())) {+ if (disposed) return;+ if (!options.canEdit()) setState({ t: 'unshared' });+ else {+ try {+ await options.initialize(+ createCanvasSeed(options.initial, options.documentId)+ );+ } catch (cause) {+ // A competing initializer wins atomically in the document's Durable Object.+ if (!(await options.exists())) throw cause;+ }+ }+ }+ if (disposed) return;+ const opened = runWithOwner(owner, options.connect);+ if (!opened) return;+ setConnection(opened);+ opened.source.listen((event) => {+ if (disposed) return;+ for (const listener of listeners) listener(event);+ if (event.type === 'connect' || event.type === 'reconnect') {+ fireAndForget(recover(event), 'canvas-session');+ }+ });+ if (peerId !== undefined) opened.source.registerPeerId(peerId);+ const initial = await opened.doInitialSync();+ if (disposed) return;+ if (initial.isErr()) {+ if (!started && state().t !== 'unshared')+ throw new Error('Unable to connect to this canvas.');+ return;+ }+ await accept(initial.value);+ }+ let hydration = Promise.resolve();+ function initialize() {+ hydration = runInitialization();+ return hydration;+ }+ async function runInitialization() {+ const span = Telemetry.span('canvas.open');+ span.setAttr('document.id', options.documentId);+ span.setAttr('document.type', 'canvas');+ registerDocumentSpan(options.documentId, span);+ try {+ await span.span('canvas.hydrate', hydrate);+ } catch (cause) {+ span.error(cause);+ if (!disposed && started)+ setFailure(+ 'Live canvas sync is unavailable. Local changes are preserved.'+ );+ else if (!disposed)+ setState({+ t: 'error',+ message:+ cause instanceof Error+ ? cause.message+ : 'Unable to open this canvas.',+ });+ } finally {+ endTrackedDocumentSpan(span);+ }+ }+ const initialization = initialize();+ let recovery = Promise.resolve();+ function recover(initial: InitialSync): Promise<void> {+ const previous = recovery;+ const run = async () => {+ await previous;+ await initialization;+ if (disposed) return;+ try {+ await accept(initial);+ } catch (cause) {+ if (!disposed)+ setFailure(+ cause instanceof Error+ ? cause.message+ : 'Unable to reconnect to this canvas.'+ );+ }+ };+ recovery = run();+ return recovery;+ }+ async function flush() {+ let appended: Promise<void>;+ do {+ appended = lastAppend;+ await appended;+ await wal.flush();+ } while (appended !== lastAppend);+ return !pending() && appends() === 0 && !failure();+ }+ async function retrySave() {+ await lastAppend;+ if (disposed) return false;+ for (const update of [...failedUpdates]) await wal.append(update);+ if (disposed) return false;+ if (!failedUpdates.size) setFailure(undefined);+ if (!connection()) await initialize();+ else live.reconnect();+ return flush();+ }+ async function close() {+ await initialization;+ await recovery;+ await hydration;+ await resetWork;+ await lastAppend;+ await snapshotWork;+ manager.dispose();+ }+ onCleanup(() => {+ finishEdits();+ disposed = true;+ // A replacement mount must not read the WAL before the final local append+ // from this mount finishes (including a text draft committed above).+ fireAndForget(+ serializeSnapshot(options.documentId, async () => {+ await lastAppend;+ }),+ 'canvas-session'+ );+ engine.stop();+ wal.destroy();+ live.cleanup();+ unsubscribeManager();+ stopValidation();+ listeners.clear();+ fireAndForget(close(), 'canvas-session');+ });+ return {+ state,+ pending: () => pending() || appends() > 0,+ failure,+ flush,+ retrySave,+ status: live.status,+ awareness,+ peerId: manager.peerIdStr,+ finishEditing: (finish: () => void) => {+ finishEdits = finish;+ },+ };+}+export type CanvasSession = ReturnType<typeof createCanvasSession>;diff --git a/apps/web/src/features/block-canvas/queries/canvas-sync.test.ts b/apps/web/src/features/block-canvas/queries/canvas-sync.test.tsnew file mode 100644index 0000000000..2fecd7970e--- /dev/null+++ b/apps/web/src/features/block-canvas/queries/canvas-sync.test.ts@@ -0,0 +1,115 @@+import { queryClient } from '@queries/client';+import { fetchFileDocumentOpenContext } from '@queries/storage/documentLoad/sync-document-context';+import { createSyncServiceSource } from '@service-sync/source';+import type { DocumentSyncAuthorization } from '@service-sync/source/authorization';+import { err, ok } from 'neverthrow';+import { createRoot, createSignal } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import { canvasSyncSource } from './canvas-sync';++vi.mock('@queries/client', () => ({+ queryClient: { invalidateQueries: vi.fn() },+}));+vi.mock('@queries/storage/documentLoad/sync-document-context', () => ({+ fetchFileDocumentOpenContext: vi.fn(),+}));+vi.mock('@service-sync/source', () => ({ createSyncServiceSource: vi.fn() }));+vi.mock('@service-sync/client', () => ({+ syncServiceClient: { exists: vi.fn(), initializeFromSnapshot: vi.fn() },+}));++const disposers: (() => void)[] = [];+const context = {+ syncService: true,+ fromCache: false,+ documentMetadata: {+ documentId: 'canvas-1',+ documentName: 'Shared canvas',+ documentVersionId: 1,+ owner: 'alice',+ fileType: 'canvas',+ },+} as const;+afterEach(() => {+ for (const dispose of disposers.splice(0)) dispose();+ vi.resetAllMocks();+});++function open() {+ return createRoot((dispose) => {+ disposers.push(dispose);+ const [userId, setUserId] = createSignal<string | undefined>('alice');+ return { ...canvasSyncSource('canvas-1', userId), setUserId };+ });+}+function connectedAuthorization(): DocumentSyncAuthorization {+ const value = vi.mocked(createSyncServiceSource).mock.calls.at(-1)?.[2];+ if (!value) throw new Error('Missing captured authorization');+ return value;+}++it('refreshes web access on reconnect and fences an old source after account changes', async () => {+ vi.mocked(fetchFileDocumentOpenContext).mockResolvedValue(+ ok({+ ...context,+ userAccessLevel: 'edit',+ token: 'initial',+ })+ );+ const sync = open();+ await sync.authorize?.();+ sync.connect();+ const authorization = connectedAuthorization();+ expect(await authorization.getToken()).toBe('initial');+ expect(authorization.canWrite()).toBe(true);+ vi.mocked(fetchFileDocumentOpenContext).mockResolvedValue(+ err([{ code: 'INVALID', message: 'Network unavailable' }])+ );+ await expect(authorization.getToken()).rejects.toThrow('Network unavailable');+ expect(sync.canWrite()).toBe(true);+ vi.mocked(fetchFileDocumentOpenContext).mockResolvedValue(+ ok({+ ...context,+ userAccessLevel: 'comment',+ token: 'refreshed',+ })+ );+ expect(await authorization.getToken()).toBe('refreshed');+ expect(queryClient.invalidateQueries).toHaveBeenCalledTimes(2);+ expect(authorization.canWrite()).toBe(false);+ expect(sync.canWrite()).toBe(false);+ const invalidated = vi.fn();+ authorization.onInvalidated(invalidated);+ sync.setUserId('bob');+ expect(authorization.isCurrent()).toBe(false);+ expect(invalidated).toHaveBeenCalledOnce();+ sync.setUserId('alice');+ expect(authorization.isCurrent()).toBe(false);+});++it('uses the native grant and disables edits when fresh authorization is downgraded', async () => {+ let writable = true;+ const captured: DocumentSyncAuthorization = {+ getToken: async () => 'native-token',+ canWrite: () => writable,+ isCurrent: () => true,+ onInvalidated: () => () => {},+ };+ vi.mocked(fetchFileDocumentOpenContext).mockResolvedValue(+ ok({+ ...context,+ userAccessLevel: 'edit',+ authorization: captured,+ })+ );+ const sync = open();+ await sync.authorize?.();+ sync.connect();+ const authorization = connectedAuthorization();+ expect(await authorization.getToken()).toBe('native-token');+ expect(sync.canWrite()).toBe(true);+ writable = false;+ await authorization.getToken();+ expect(sync.canWrite()).toBe(false);+ expect(authorization.canWrite()).toBe(false);+});diff --git a/apps/web/src/features/block-canvas/queries/canvas-sync.ts b/apps/web/src/features/block-canvas/queries/canvas-sync.tsnew file mode 100644index 0000000000..2c78823462--- /dev/null+++ b/apps/web/src/features/block-canvas/queries/canvas-sync.ts@@ -0,0 +1,142 @@+import {+ ThrownResultError,+ thrownResultErrorHasCode,+ throwOnErr,+} from '@core/util/result';+import { queryClient } from '@queries/client';+import { documentLoadKeys } from '@queries/storage/documentLoad/keys';+import { fetchFileDocumentOpenContext } from '@queries/storage/documentLoad/sync-document-context';+import { syncServiceClient } from '@service-sync/client';+import { createSyncServiceSource } from '@service-sync/source';+import type { DocumentSyncAuthorization } from '@service-sync/source/authorization';+import { type Accessor, createEffect, createSignal, on } from 'solid-js';+import type { CanvasSessionOptions } from './canvas-session';++export function canvasSyncSource(+ documentId: string,+ userId: Accessor<string | undefined>+): Pick<+ CanvasSessionOptions,+ 'exists' | 'initialize' | 'connect' | 'authorize'+> & { canWrite: Accessor<boolean> } {+ let authorization: DocumentSyncAuthorization | undefined;+ let token: string | undefined;+ let authorized = false;+ const openedBy = userId();+ let invalidated = false;+ const listeners = new Set<() => void>();+ const [canWrite, setCanWrite] = createSignal(true);+ createEffect(+ on(userId, (currentUser) => {+ if (currentUser === openedBy) return;+ invalidated = true;+ setCanWrite(false);+ for (const listener of listeners) listener();+ })+ );+ return {+ canWrite,+ async authorize() {+ const load = async (refresh = false) => {+ try {+ if (refresh)+ await queryClient.invalidateQueries({+ queryKey: documentLoadKeys.bundle(documentId).queryKey,+ exact: true,+ refetchType: 'none',+ });+ return await throwOnErr(() =>+ fetchFileDocumentOpenContext(documentId)+ );+ } catch (cause) {+ if (+ // The block loader also maps transient network failures to INVALID.+ // Preserve local editing until a fresh grant or confirmed denial.+ ['FORBIDDEN', 'NOT_FOUND', 'MISSING', 'GONE'].some((code) =>+ thrownResultErrorHasCode(cause, code)+ )+ )+ setCanWrite(false);+ throw cause;+ }+ };+ const context = await load();+ let editable =+ context.userAccessLevel === 'owner' ||+ context.userAccessLevel === 'edit';+ setCanWrite(editable);+ token = context.token;+ const captured = context.authorization;+ const current = () =>+ !invalidated &&+ userId() === openedBy &&+ (captured?.isCurrent() ?? true);+ let first: typeof context | undefined = context;+ authorization = {+ isCurrent: current,+ canWrite: () => current() && editable && (captured?.canWrite() ?? true),+ async getToken() {+ if (!current()) throw new Error('Canvas session changed.');+ let value: string | undefined;+ if (captured) value = await captured.getToken();+ else {+ const fresh = first ?? (await load(true));+ first = undefined;+ editable =+ fresh.userAccessLevel === 'owner' ||+ fresh.userAccessLevel === 'edit';+ value = fresh.token;+ }+ if (!value)+ throw new Error('Canvas authorization returned no token.');+ if (!current()) throw new Error('Canvas session changed.');+ setCanWrite(editable && (captured?.canWrite() ?? true));+ return value;+ },+ onInvalidated(listener) {+ listeners.add(listener);+ const stop = captured?.onInvalidated(() => {+ setCanWrite(false);+ listener();+ });+ if (invalidated || userId() !== openedBy) listener();+ return () => {+ listeners.delete(listener);+ stop?.();+ };+ },+ };+ setCanWrite(authorization.canWrite());+ authorized = true;+ },+ async exists() {+ const result = await syncServiceClient.exists({ documentId });+ if (result.isErr()) throw new ThrownResultError(result.error);+ return result.value.exists;+ },+ async initialize(snapshot) {+ if (+ !authorization ||+ !authorization.isCurrent() ||+ !authorization.canWrite()+ )+ throw new ThrownResultError([+ {+ code: 'FORBIDDEN',+ message: 'Canvas editing is no longer authorized.',+ },+ ]);+ await throwOnErr(() =>+ syncServiceClient.initializeFromSnapshot({+ documentId,+ snapshot,+ })+ );+ },+ connect: () => {+ if (!authorized)+ throw new Error('Canvas synchronization requires authorization.');+ return createSyncServiceSource(documentId, token, authorization);+ },+ };+}diff --git a/apps/web/src/features/block-canvas/queries/document.test.ts b/apps/web/src/features/block-canvas/queries/document.test.tsdeleted file mode 100644index 581e4d20b1..0000000000--- a/apps/web/src/features/block-canvas/queries/document.test.ts+++ /dev/null@@ -1,44 +0,0 @@-import { createGraphicsEditor } from '@macro-inc/graphics';-import { err, ok } from 'neverthrow';-import { afterEach, expect, it, vi } from 'vitest';-import { canvasDocumentSource } from './document';--const { simpleSave } = vi.hoisted(() => ({ simpleSave: vi.fn() }));-vi.mock('@service-storage/client', () => ({- storageServiceClient: { simpleSave },-}));-afterEach(() => vi.clearAllMocks());--it('surfaces rejected JSON saves so the session can retry', async () => {- const editor = createGraphicsEditor();- const source = canvasDocumentSource('canvas-id', () => true, {- version: 2,- document: editor.document,- });- simpleSave- .mockResolvedValueOnce(err('offline'))- .mockResolvedValueOnce(ok({}));- const file = { version: 2 as const, document: editor.document };- await expect(source.save(file)).rejects.toThrow('Could not save canvas');- await expect(source.save(file)).resolves.toBeInstanceOf(Blob);- expect(simpleSave).toHaveBeenLastCalledWith({- documentId: 'canvas-id',- file: expect.any(Blob),- });- editor.dispose();-});--it('never submits a read-only document', async () => {- const editor = createGraphicsEditor();- await expect(- canvasDocumentSource('viewer', () => false, {- version: 2,- document: editor.document,- }).save({- version: 2,- document: editor.document,- })- ).rejects.toThrow('read-only');- expect(simpleSave).not.toHaveBeenCalled();- editor.dispose();-});diff --git a/apps/web/src/features/block-canvas/queries/document.ts b/apps/web/src/features/block-canvas/queries/document.tsdeleted file mode 100644index 382dce086d..0000000000--- a/apps/web/src/features/block-canvas/queries/document.ts+++ /dev/null@@ -1,34 +0,0 @@-import { ENABLE_MENTION_TRACKING } from '@core/constant/featureFlags';-import type { CanvasDocumentSource } from '../context/document-source';-import type { CanvasFile } from '../core/document-format';-import { readCanvasFile } from '../core/document-format';-import { createTrackedCanvasDocumentSource } from '../primitives/create-tracked-document-source';-import { saveCanvasDocument } from './canvas-document';-import { canvasReferenceSource } from './references';--export function canvasDocumentSource(- documentId: string,- canEdit: () => boolean,- initial: CanvasFile-): CanvasDocumentSource {- const source: CanvasDocumentSource = {- canEdit,- async save(canvas) {- if (!canEdit()) throw new Error('This canvas is read-only');- const { file, saved } = await saveCanvasDocument(- documentId,- readCanvasFile(canvas)- );- if (!saved) throw new Error('Could not save canvas');- return file;- },- };- return ENABLE_MENTION_TRACKING- ? createTrackedCanvasDocumentSource(- documentId,- initial,- source,- canvasReferenceSource(documentId)- )- : source;-}diff --git a/apps/web/src/features/block-canvas/views/canvas-read-only-view.tsx b/apps/web/src/features/block-canvas/views/canvas-read-only-view.tsxindex d05f6bae52..2b077acdae 100644--- a/apps/web/src/features/block-canvas/views/canvas-read-only-view.tsx+++ b/apps/web/src/features/block-canvas/views/canvas-read-only-view.tsx@@ -1,6 +1,11 @@import { DocumentPreviewContent } from '@core/component/DocumentPreview';import { fileTypeToBlockName } from '@core/constant/allBlocks';import type { GraphicsEditor } from '@macro-inc/graphics';+import type { GraphicsPresence } from '@macro-inc/graphics/loro';+import {+ attachPresencePointer,+ GraphicsPresenceOverlay,+} from '@macro-inc/graphics/loro/solid';import {ConnectorView,EllipseView,@@ -8,7 +13,7 @@ import {RectangleView,TextView,} from '@macro-inc/graphics/solid';-import { createSignal, onCleanup, onMount } from 'solid-js';+import { createSignal, onCleanup, onMount, Show } from 'solid-js';import { CanvasDrawingToolbar, CanvasZoomToolbar } from './canvas-toolbars';import { CanvasMediaView } from './embedded-items';import { CanvasTextContent } from './text-content';@@ -16,6 +21,7 @@ import { CanvasTextContent } from './text-content';/** Viewers get navigation without mounting editing handlers or embedded editors. */export function CanvasReadOnlyView(props: {editor: GraphicsEditor;+ presence?: GraphicsPresence;fitOnLoad?: boolean;}) {const [tool, setTool] = createSignal<'select' | 'pan'>('select');@@ -50,6 +56,8 @@ export function CanvasReadOnlyView(props: {height: host.clientHeight,});onMount(() => {+ if (props.presence)+ onCleanup(attachPresencePointer(host, props.editor, props.presence));const observer = new ResizeObserver(([entry]) => {if (!entry?.contentRect.width || !entry.contentRect.height) return;if (props.fitOnLoad !== false) fit();@@ -120,6 +128,14 @@ export function CanvasReadOnlyView(props: {),}}/>+ <Show when={props.presence}>+ {(presence) => (+ <GraphicsPresenceOverlay+ editor={props.editor}+ presence={presence()}+ />+ )}+ </Show><CanvasDrawingToolbarreadOnlytool={tool()}diff --git a/apps/web/src/features/block-canvas/views/canvas-view.tsx b/apps/web/src/features/block-canvas/views/canvas-view.tsxindex 23e0fbd707..973a569abb 100644--- a/apps/web/src/features/block-canvas/views/canvas-view.tsx+++ b/apps/web/src/features/block-canvas/views/canvas-view.tsx@@ -11,6 +11,11 @@ import {styleCommand,} from '@macro-inc/graphics';import { attachConnectorControls } from '@macro-inc/graphics/browser';+import type { GraphicsPresence } from '@macro-inc/graphics/loro';+import {+ attachPresencePointer,+ GraphicsPresenceOverlay,+} from '@macro-inc/graphics/loro/solid';import {ConnectorView,EllipseView,@@ -66,6 +71,7 @@ import { TextEditingView } from './text-editing-view';export function CanvasView(props: {state: CanvasState;+ presence?: GraphicsPresence;fitOnLoad?: boolean;scopeId: string;embedView: Component<CanvasEmbedViewProps>;@@ -201,6 +207,8 @@ export function CanvasView(props: {});props.attachScope(root);props.onViewport(host);+ if (props.presence)+ onCleanup(attachPresencePointer(host, editor, props.presence));onCleanup(props.insert.attach(host));droppable(host);onCleanup(props.clipboard.attach(root));@@ -705,6 +713,14 @@ export function CanvasView(props: {)}</Show></GraphicsSurface>+ <Show when={props.presence}>+ {(presence) => (+ <GraphicsPresenceOverlay+ editor={editor}+ presence={presence()}+ />+ )}+ </Show></div></ContextMenu.Trigger><CanvasContextMenudiff --git a/crates/documents/AGENTS.md b/crates/documents/AGENTS.mdindex f664b1faae..d599ceafbb 100644--- a/crates/documents/AGENTS.md+++ b/crates/documents/AGENTS.md@@ -24,6 +24,9 @@ word docs, Illustrator/Photoshop files).## Scope+- Copying a canvas preserves its JSON seed and, when one exists, its live sync+ room; failed copies compensate destination storage and sync artifacts before+ removing the new document rows, logging cleanup failures independently.- Owns: document lifecycle (create/rename/purge/upgrade), content storage andmarkdown backfill, comments, AI-editing tools, and file-type domain services(spreadsheet, presentation, word, illustrator, photoshop).diff --git a/crates/documents/src/domain/ports.rs b/crates/documents/src/domain/ports.rsindex 220014d76b..637cb19c64 100644--- a/crates/documents/src/domain/ports.rs+++ b/crates/documents/src/domain/ports.rs@@ -343,6 +343,9 @@ pub trait PresignedUploadUrlPort: Send + Sync + 'static {destination_key: &str,) -> impl Future<Output = anyhow::Result<()>> + Send;+ /// Remove a destination object when a multi-part document copy fails.+ fn delete_object(&self, key: &str) -> impl Future<Output = anyhow::Result<()>> + Send;+/// Returns the raw bytes of the cached Loro snapshot, or `None` if no snapshot exists.fn get_snapshot(&self,diff --git a/crates/documents/src/domain/ports/sync.rs b/crates/documents/src/domain/ports/sync.rsindex ef4df91f6c..4502a0fd57 100644--- a/crates/documents/src/domain/ports/sync.rs+++ b/crates/documents/src/domain/ports/sync.rs@@ -23,4 +23,8 @@ pub trait DocumentSyncPort: Send + Sync + 'static {target_document_id: &str,version_id: Option<SyncServiceVersionID>,) -> impl Future<Output = anyhow::Result<()>> + Send;++ /// Remove collaborative content created by a failed document copy.+ fn delete_document(&self, document_id: &str)+ -> impl Future<Output = anyhow::Result<()>> + Send;}diff --git a/crates/documents/src/domain/service.rs b/crates/documents/src/domain/service.rsindex fada125ed9..fa1c861f82 100644--- a/crates/documents/src/domain/service.rs+++ b/crates/documents/src/domain/service.rs@@ -642,6 +642,18 @@ impl<}}+ async fn cleanup_canvas_copy(&self, document_id: &str, seed_key: Option<&str>, room: bool) {+ if let Some(key) = seed_key+ && let Err(error) = self.upload_url_service.delete_object(key).await+ {+ tracing::error!(?error, document_id, "failed to clean up copied canvas seed");+ }+ if room && let Err(error) = self.sync_service_client.delete_document(document_id).await {+ tracing::error!(?error, document_id, "failed to clean up copied canvas room");+ }+ self.cleanup_document(document_id).await;+ }+async fn team_task_metadata_for_document(&self,document_id: &str,@@ -1846,6 +1858,8 @@ impl<let new_document_id = new_metadata.document_id.clone();let new_owner = &new_metadata.owner;+ let mut canvas_seed_key = None;+ let mut canvas_room = false;// File-type-specific S3 operationslet copy_result = match file_type {@@ -1946,15 +1960,46 @@ impl<&new_document_id,new_metadata.document_version_id,);- self.upload_url_service+ if file_type == Some(FileType::Canvas) {+ canvas_seed_key = Some(dest_key.clone());+ }+ let copied = self+ .upload_url_service.copy_object(&source_key, &dest_key)- .await+ .await;+ if copied.is_err() || file_type != Some(FileType::Canvas) {+ copied+ } else {+ // Canvas keeps its original JSON as a migration seed, while+ // edits live in sync-service. A copy needs both representations.+ match self+ .sync_service_client+ .exists(&original_metadata.document_id)+ .await+ {+ Ok(true) => {+ // A failed response can follow a committed room copy.+ // Compensate the attempted destination in either case.+ canvas_room = true;+ self.sync_service_client+ .copy_document(+ &original_metadata.document_id,+ &new_document_id,+ sync_version_id,+ )+ .await+ }+ Ok(false) => Ok(()),+ Err(error) => Err(error),+ }+ }}};if let Err(e) = copy_result {tracing::error!(error=?e, "unable to copy document files");- self.cleanup_document(&new_document_id).await;+ self.cleanup_canvas_copy(&new_document_id, canvas_seed_key.as_deref(), canvas_room)+ .await;return Err(DocumentError::Internal(e));}@@ -1966,7 +2011,8 @@ impl<.await{tracing::error!(error=?e, document_id=?new_document_id, "failed to copy task properties");- self.cleanup_document(&new_document_id).await;+ self.cleanup_canvas_copy(&new_document_id, canvas_seed_key.as_deref(), canvas_room)+ .await;return Err(DocumentError::Internal(e));}@@ -1977,7 +2023,8 @@ impl<.await{tracing::error!(error=?e, document_id=?new_document_id, "failed to mark copied document content ready");- self.cleanup_document(&new_document_id).await;+ self.cleanup_canvas_copy(&new_document_id, canvas_seed_key.as_deref(), canvas_room)+ .await;return Err(DocumentError::Internal(e.into()));}@@ -1987,15 +2034,32 @@ impl<);}- let document_response_metadata =- DocumentResponseMetadata::from_document_metadata(&new_metadata).map_err(|e| {- tracing::error!(error=?e, "unable to convert document metadata");- DocumentError::Internal(anyhow!("unable to convert document metadata"))- })?;-- let team_task_metadata = self- .team_task_metadata_for_document(&new_document_id)- .await?;+ let response: Result<_, DocumentError> = async {+ let metadata = DocumentResponseMetadata::from_document_metadata(&new_metadata)+ .map_err(|e| {+ tracing::error!(error=?e, "unable to convert document metadata");+ DocumentError::Internal(anyhow!("unable to convert document metadata"))+ })?;+ let team = self+ .team_task_metadata_for_document(&new_document_id)+ .await?;+ Ok((metadata, team))+ }+ .await;+ let (document_response_metadata, team_task_metadata) = match response {+ Ok(response) => response,+ Err(error) => {+ if file_type == Some(FileType::Canvas) {+ self.cleanup_canvas_copy(+ &new_document_id,+ canvas_seed_key.as_deref(),+ canvas_room,+ )+ .await;+ }+ return Err(error);+ }+ };let attribution = Attribution::from(principal);self.publish_document_event(&DocumentMacroEvent::copied(diff --git a/crates/documents/src/domain/service/tests.rs b/crates/documents/src/domain/service/tests.rsindex 252a572fba..de226809c5 100644--- a/crates/documents/src/domain/service/tests.rs+++ b/crates/documents/src/domain/service/tests.rs@@ -117,6 +117,9 @@ fn bot_receipt(document_id: &str) -> EntityAccessReceipt<ViewAccessLevel> {struct TestUploadUrlPort;impl PresignedUploadUrlPort for TestUploadUrlPort {+ async fn delete_object(&self, _key: &str) -> anyhow::Result<()> {+ Ok(())+ }async fn put_document_storage_presigned_url(&self,_key: &str,@@ -2184,9 +2187,18 @@ async fn copy_document_best_effort_bumps_inherited_project_and_publishes_event()#[derive(Clone, Default)]struct RecordingUploadUrlPort {copies: Arc<Mutex<Vec<(String, String)>>>,+ deletions: Arc<Mutex<Vec<String>>>,+ fail_delete: bool,}impl PresignedUploadUrlPort for RecordingUploadUrlPort {+ async fn delete_object(&self, key: &str) -> anyhow::Result<()> {+ self.deletions.lock().unwrap().push(key.to_string());+ if self.fail_delete {+ anyhow::bail!("storage cleanup unavailable");+ }+ Ok(())+ }async fn put_document_storage_presigned_url(&self,_key: &str,@@ -3003,6 +3015,167 @@ fn spreadsheet_test_service()}+#[tokio::test]+async fn canvas_copy_preserves_live_content_and_legacy_canvases_still_copy() {+ for shared in [false, true] {+ let mut repo = make_mock_repo();+ let mut original = make_test_metadata();+ original.project_id = None;+ original.file_type = Some("canvas".to_string());+ repo.expect_get_document_metadata()+ .returning(move |_| Box::pin(std::future::ready(Ok(original.clone()))));+ let mut copied = make_test_metadata();+ copied.document_id = "doc-2".to_string();+ copied.project_id = None;+ copied.file_type = Some("canvas".to_string());+ repo.expect_copy_document()+ .returning(move |_, _| Box::pin(std::future::ready(Ok(copied.clone()))));+ repo.expect_get_owner_team()+ .returning(|_| Box::pin(std::future::ready(Ok(None))));+ repo.expect_get_latest_document_version_id()+ .returning(|_| Box::pin(std::future::ready(Ok((1, true)))));+ repo.expect_set_document_content()+ .returning(|_, _| Box::pin(std::future::ready(Ok(()))));+ repo.expect_get_team_task_metadata()+ .returning(|_| Box::pin(std::future::ready(Ok(None))));+ let mut sync = crate::domain::ports::sync::MockDocumentSyncPort::new();+ sync.expect_exists()+ .withf(|id| id == "doc-1")+ .times(1)+ .returning(move |_| Box::pin(std::future::ready(Ok(shared))));+ sync.expect_copy_document()+ .withf(|from, to, _| from == "doc-1" && to == "doc-2")+ .times(usize::from(shared))+ .returning(|_, _, _| Box::pin(std::future::ready(Ok(()))));+ let service = spreadsheet_test_service(repo, sync);+ let mut context = task_document_context("doc-1");+ context.file_type = Some("canvas".to_string());+ context.sub_type = None;+ service+ .copy_document(+ authenticated_receipt("doc-1"),+ context,+ &CreationPrincipal::User(test_user()),+ "copied canvas".to_string(),+ None,+ None,+ )+ .await+ .unwrap();+ }+}++#[tokio::test]+async fn canvas_copy_failure_compensates_only_its_destinations_and_still_removes_rows() {+ for phase in ["lookup", "copy", "ready", "legacy-ready", "metadata"] {+ let mut repo = make_mock_repo();+ let mut original = make_test_metadata();+ original.project_id = None;+ original.file_type = Some("canvas".to_string());+ repo.expect_get_document_metadata()+ .returning(move |_| Box::pin(std::future::ready(Ok(original.clone()))));+ let mut copied = make_test_metadata();+ copied.document_id = "doc-2".to_string();+ copied.project_id = None;+ copied.file_type = Some("canvas".to_string());+ repo.expect_copy_document()+ .returning(move |_, _| Box::pin(std::future::ready(Ok(copied.clone()))));+ repo.expect_get_owner_team()+ .returning(|_| Box::pin(std::future::ready(Ok(None))));+ repo.expect_get_latest_document_version_id()+ .returning(|_| Box::pin(std::future::ready(Ok((1, true)))));+ repo.expect_delete_document_by_id()+ .withf(|id| id == "doc-2")+ .times(1)+ .returning(|_| Box::pin(std::future::ready(Ok(()))));+ if phase.ends_with("ready") || phase == "metadata" {+ repo.expect_set_document_content()+ .times(1)+ .returning(move |_, _| {+ Box::pin(std::future::ready(if phase == "metadata" {+ Ok(())+ } else {+ Err(anyhow!("content update unavailable"))+ }))+ });+ }+ if phase == "metadata" {+ repo.expect_get_team_task_metadata()+ .times(1)+ .returning(|_| Box::pin(std::future::ready(Err(anyhow!("metadata unavailable")))));+ }+ let mut sync = crate::domain::ports::sync::MockDocumentSyncPort::new();+ sync.expect_exists()+ .withf(|id| id == "doc-1")+ .times(1)+ .returning(move |_| {+ Box::pin(std::future::ready(if phase == "lookup" {+ Err(anyhow!("lookup unavailable"))+ } else {+ Ok(phase != "legacy-ready")+ }))+ });+ let room_attempted = phase == "copy" || phase == "ready" || phase == "metadata";+ sync.expect_copy_document()+ .withf(|from, to, _| from == "doc-1" && to == "doc-2")+ .times(usize::from(room_attempted))+ .returning(move |_, _, _| {+ Box::pin(std::future::ready(if phase == "copy" {+ Err(anyhow!("room copy unavailable"))+ } else {+ Ok(())+ }))+ });+ sync.expect_delete_document()+ .withf(|id| id == "doc-2")+ .times(usize::from(room_attempted))+ .returning(move |_| {+ Box::pin(std::future::ready(if phase == "copy" {+ Err(anyhow!("room cleanup unavailable"))+ } else {+ Ok(())+ }))+ });+ // Cleanup failures must not prevent the remaining compensation steps.+ let uploads = RecordingUploadUrlPort {+ fail_delete: phase == "copy",+ ..Default::default()+ };+ let deleted = uploads.deletions.clone();+ let service = DocumentServiceImpl::new(+ repo,+ test_cloudfront_config(),+ sync,+ uploads,+ TestTaskPropertiesPort,+ TestConnectionService::default(),+ TestEntityAccessManagementService::default(),+ TestForeignEntityService::default(),+ TestEventBroker::default(),+ );+ let mut context = task_document_context("doc-1");+ context.file_type = Some("canvas".to_string());+ context.sub_type = None;+ assert!(+ service+ .copy_document(+ authenticated_receipt("doc-1"),+ context,+ &CreationPrincipal::User(test_user()),+ "copied canvas".to_string(),+ None,+ None,+ )+ .await+ .is_err()+ );+ assert_eq!(+ *deleted.lock().unwrap(),+ vec!["macro|[email protected]/doc-2/1"]+ );+ }+}+fn spreadsheet_document() -> NewDocument {let mut document = new_document(FileType::Spreadsheet);document.sha = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855".to_string();diff --git a/crates/documents/src/outbound/document_sync.rs b/crates/documents/src/outbound/document_sync.rsindex 6fdcc768e1..49971610ff 100644--- a/crates/documents/src/outbound/document_sync.rs+++ b/crates/documents/src/outbound/document_sync.rs@@ -10,6 +10,10 @@ const SPREADSHEET_GOLDEN_SNAPSHOT: &[u8] =include_bytes!("../../../../static_assets/spreadsheet-golden.1.bin");impl DocumentSyncPort for SyncServiceClient {+ async fn delete_document(&self, document_id: &str) -> anyhow::Result<()> {+ SyncServiceClient::delete(self, document_id).await+ }+async fn initialize_spreadsheet(&self, document_id: &str) -> anyhow::Result<()> {self.initialize_from_snapshot(document_id, SPREADSHEET_GOLDEN_SNAPSHOT).awaitdiff --git a/crates/documents/src/outbound/s3_upload_url.rs b/crates/documents/src/outbound/s3_upload_url.rsindex 9d4c0d4468..03174816e8 100644--- a/crates/documents/src/outbound/s3_upload_url.rs+++ b/crates/documents/src/outbound/s3_upload_url.rs@@ -37,6 +37,20 @@ impl S3UploadUrlAdapter {}impl PresignedUploadUrlPort for S3UploadUrlAdapter {+ #[tracing::instrument(skip(self), err)]+ async fn delete_object(&self, key: &str) -> anyhow::Result<()> {+ if macro_aws_config::is_local_aws() {+ return Ok(());+ }+ self.client+ .delete_object()+ .bucket(&self.document_storage_bucket)+ .key(key)+ .send()+ .await?;+ Ok(())+ }+#[tracing::instrument(skip(self), err)]async fn put_document_storage_presigned_url(&self,diff --git a/docs/agent-guide/canvas.md b/docs/agent-guide/canvas.mdindex c7016fa435..6bf711163c 100644--- a/docs/agent-guide/canvas.md+++ b/docs/agent-guide/canvas.md@@ -25,3 +25,27 @@ on desktop and uses the native share sheet on supported mobile devices.Controls are disabled while resolving the image source or running an action.Check an uploaded image and a workspace image, and confirm both actions disappearfor multiple selections, groups, videos, and non-image shapes.++## Multiplayer canvas++Open the same canvas as two editors and a viewer. Create/move a shape in one+editor and style it in the other; all three should converge. Undo the move and+confirm the remote styling survives. Check colored cursors, dashed remote+selections and live drag/drawing ghosts, including camera pan/zoom. Text, media,+connectors and document cards use bounds-only ghosts; connector endpoint drafts+are not broadcast. On touch, check selection and gesture awareness without hover.++Disconnect an initialized editor, edit, reopen from its local cache, then reconnect.+The unsent edits must survive and reach the other peers. Disconnecting removes+remote overlays locally; absent peers expire after ten seconds. If the first+connection or local storage fails, the original JSON opens read-only with Retry.+If a live session cannot save locally, keep it open and use Retry saving; the+live scene stays mounted until its buffered edits are persisted. Changing+accounts invalidates the old connection; refreshed view/comment grants disable+canvas edits.+A viewer may wait on the original JSON until the first editor initializes the room.++Downloads export the live scene, and Copy duplicates the shared room plus its+original JSON. Reload older open canvas tabs before collaborating: the previous+whole-file editor does not participate in shared state. Editing the same text+item concurrently chooses one completed content string; characters do not merge.diff --git a/docs/architecture/canvas-legacy-bridge.md b/docs/architecture/canvas-legacy-bridge.mdindex de862b2936..f0de18128f 100644--- a/docs/architecture/canvas-legacy-bridge.md+++ b/docs/architecture/canvas-legacy-bridge.md@@ -30,7 +30,9 @@ format cannot represent.Canvas Next opens all saved canvases without a rollout flag. Supported legacyfiles migrate in memory and retain their original JSON in migration metadata.-The first committed edit saves version 2; opening a file alone does not save it.+The first editor opening a canvas initializes its shared version 2 scene in+SyncService; viewers never seed it. The original JSON remains a migration seed+and is never replayed over shared edits. Downloads export the current scene.Unsupported records and unknown versions show an error without changing thesaved document. Validate any expanded import support against representativefixtures before allowing write-back.diff --git a/docs/architecture/canvas.md b/docs/architecture/canvas.mdindex b846705df1..b892cc62e1 100644--- a/docs/architecture/canvas.md+++ b/docs/architecture/canvas.md@@ -26,9 +26,20 @@ Graphics treats rich text as opaque content and assets as stable references. Itmust not depend on Macro services, Lexical, the DOM, Solid, object URLs, or themevariables. Canvas adapters resolve those concerns at the edge.-Saved Canvas Next documents use a versioned JSON boundary. The Loro backend and-two-peer harness prove the collaboration mapping, but production SyncService-integration and conflict-policy approval remain separate work.+JSON is the import/export boundary and original migration seed. Once initialized,+the authoritative scene is a Loro document in SyncService. The Canvas host uses+the shared collaboration engine, local snapshot/WAL and permission-token transport;+the graphics adapter binds to that host-owned document and owns only scene history.+Only editors initialize rooms; viewers and nested canvases receive live changes+without editing. The server's serialized initializer chooses a single seed.+Copying preserves both the live room and original JSON, and downloads serialize+the current shared scene. Whole-file saves no longer run for canvas edits.++Shared presence carries cursors, selections and pending gestures on the runtime's+awareness channel, independently of document history. Geometry conflicts choose+one coherent pose; text/labels choose one complete content string. Remote commits+cancel local scene previews. Character-level text collaboration and gesture-intent+rebasing are separate work. No production participant limit has been measured.## Principlesdiff --git a/docs/design/graphics-parity.md b/docs/design/graphics-parity.mdindex 376d846a3c..3354a55132 100644--- a/docs/design/graphics-parity.md+++ b/docs/design/graphics-parity.md@@ -2,7 +2,7 @@Canvas Next implements the shared graphics foundation and the main local editingflows. It is the editor for all saved canvases and embeds, migrates-older JSON at the host boundary, and writes the current versioned format.+older JSON at the host boundary, and shares edits through SyncService.## Current coverage@@ -12,8 +12,8 @@ older JSON at the host boundary, and writes the current versioned format.| Everyday editing | Selection, marquee, move, duplicate, clipboard, nudge, undo/redo, and context actions are implemented || Content | Shapes, pencil, rich text and labels, connectors, images, video, Macro entity cards, and document embeds are implemented || Presentation | Solid rendering, overlays, fit/pan/zoom, inspectors, and shared controls are implemented |-| Persistence | Versioned JSON loading, migration, and saving are connected at the Canvas host boundary |-| Collaboration | Loro mapping and two-peer tests exist; production transport, recovery, and rollout are not complete |+| Persistence | Versioned JSON import/export, single-winner shared initialization, snapshot/WAL recovery and live sync are connected |+| Collaboration | Production shared runtime and awareness are connected; three-peer and rendered collaboration tests exist; capacity is unmeasured |## Ownership@@ -26,7 +26,7 @@ migration, sharing, and product rollout.1. Expand legacy import coverage with explicit diagnostics for unsupported records.2. Lock down durable artwork colors separately from theme-driven application UI.-3. Integrate production collaboration, offline recovery, and permission handling.+3. Extend collaboration with character-level rich text, gesture rebasing, and measured multi-user capacity.4. Add high-value whiteboard gaps such as snapping, touch, crop, frames, export,and libraries as separate checkpoints.5. Measure mixed-content scenes before adding broad indexing or culling systems.diff --git a/packages/collaboration/src/collab/awareness.ts b/packages/collaboration/src/collab/awareness.tsindex 0187db0ff6..16eb2de650 100644--- a/packages/collaboration/src/collab/awareness.ts+++ b/packages/collaboration/src/collab/awareness.ts@@ -4,7 +4,13 @@ import {type PeerID,type Value,} from 'loro-crdt';-import { type Accessor, createSignal, untrack } from 'solid-js';+import {+ type Accessor,+ createSignal,+ getOwner,+ onCleanup,+ untrack,+} from 'solid-js';import { getRandomPaletteColor } from '../internal/palette';import type { RawUpdate } from './shared';@@ -95,6 +101,15 @@ export function createAwareness<const store = new EphemeralStore<Record<string, PeerAwarenessRaw<EncodedSelection> | undefined>>(options?.timeout ?? DEFAULT_AWARENESS_TIMEOUT);+ let disposed = false;+ if (getOwner())+ onCleanup(() =>+ queueMicrotask(() => {+ disposed = true;+ store.destroy();+ store.inner.free();+ })+ );// Initialize user awareness with a random colorconst color = getRandomPaletteColor();@@ -166,6 +181,7 @@ export function createAwareness<id: PeerID,selection: DecodedSelection | undefined) => {+ if (disposed) return;if (selection === undefined) {store.set(id, undefined);return;@@ -197,10 +213,12 @@ export function createAwareness<};const importRemoteAwareness = (update: RawUpdate) => {+ if (disposed) return;store.apply(update);};const getEncodedLocalAwareness = () => {+ if (disposed) return new Uint8Array();return store.encode(peerId);};@@ -209,6 +227,7 @@ export function createAwareness<// HACK: loro-crdt has a bug with [`EphemeralStore.subscribe`] which breaks// recursive aliasing. This is a workaround for now.queueMicrotask(() => {+ if (disposed) return;updateAwarenessSignals(update);});});diff --git a/packages/collaboration/src/collab/engine.test.ts b/packages/collaboration/src/collab/engine.test.tsindex a0ec0f5520..4d3789dde3 100644--- a/packages/collaboration/src/collab/engine.test.ts+++ b/packages/collaboration/src/collab/engine.test.ts@@ -1,5 +1,5 @@import { LoroDoc } from 'loro-crdt';-import { err, ResultAsync } from 'neverthrow';+import { err, ok, ResultAsync } from 'neverthrow';import { describe, expect, it, vi } from 'vitest';import { SyncEngine } from './engine';import { LoroManagerError } from './manager';@@ -26,6 +26,75 @@ function makeAwareness() {}describe('SyncEngine', () => {+ it.each(['snapshot', 'manager'] as const)(+ 'does not replace or restart a stopped owner during %s recovery',+ async (phase) => {+ const source = new MockLiveSyncSource();+ const { wal } = makeTestWAL(source);+ const manager = new MockLoroManager();+ const entered = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ const snapshot = emptySnapshot();+ if (phase === 'snapshot')+ source.requestSnapshot.mockImplementationOnce(() =>+ ResultAsync.fromSafePromise(+ (async () => {+ entered.resolve();+ await release.promise;+ return snapshot;+ })()+ )+ );+ else+ manager.reset.mockImplementationOnce(async () => {+ entered.resolve();+ await release.promise;+ return ok(undefined);+ });+ const engine = new SyncEngine({+ loroManager: manager,+ awareness: makeAwareness(),+ syncs: { wal, live: source },+ bindings: { onRemoteState: () => {} },+ });+ engine.start();+ const resetting = engine.reset();+ await entered.promise;+ engine.stop();+ release.resolve();+ await resetting;+ expect(engine.isRunning).toBe(false);+ expect(manager.reset).toHaveBeenCalledTimes(phase === 'snapshot' ? 0 : 1);+ wal.destroy();+ }+ );+ it('does not import a queued remote packet after its document owner stops', async () => {+ const source = new MockLiveSyncSource();+ const { wal } = makeTestWAL(source);+ const manager = new MockLoroManager();+ const entered = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ manager.syncToLoro.mockImplementationOnce(async () => {+ entered.resolve();+ await release.promise;+ return ok(undefined);+ });+ const engine = new SyncEngine({+ loroManager: manager,+ awareness: makeAwareness(),+ syncs: { wal, live: source },+ bindings: { onRemoteState: () => {} },+ });+ engine.start();+ const write = engine.syncStateToLoro({});+ await entered.promise;+ source.emit({ type: 'update', update: new Uint8Array([1, 2, 3]) });+ engine.stop();+ release.resolve();+ await write;+ expect(manager.importUpdate).not.toHaveBeenCalled();+ wal.destroy();+ });it('registers peer id and calls onRunningChange(true) on start', () => {const source = new MockLiveSyncSource();const manager = new MockLoroManager();diff --git a/packages/collaboration/src/collab/engine.ts b/packages/collaboration/src/collab/engine.tsindex 693a52270d..0927bec5ec 100644--- a/packages/collaboration/src/collab/engine.ts+++ b/packages/collaboration/src/collab/engine.ts@@ -230,10 +230,13 @@ export class SyncEngine<S extends GenericRootSchema, D> {if (wasRunning) {this.stop();}+ const generation = this.lifecycleGeneration;await this.syncLock.runExclusive(async () => {+ if (generation !== this.lifecycleGeneration) return;this.log('info', 'engine.reset: starting');const snapshot = await (snapshotThunk ?? this.defaultSnapshotThunk)();+ if (generation !== this.lifecycleGeneration) return;if (snapshot.isErr()) {this.log('error', 'engine.reset: failed to get snapshot', {err: String(snapshot.error),@@ -250,7 +253,7 @@ export class SyncEngine<S extends GenericRootSchema, D> {}});- if (wasRunning) {+ if (wasRunning && generation === this.lifecycleGeneration) {this.start();}}@@ -288,7 +291,9 @@ export class SyncEngine<S extends GenericRootSchema, D> {try {const doc = this.loroManager.doc;- this.log('debug', 'engine: persisting snapshot', { doc: doc.toJSON() });+ this.log('debug', 'engine: persisting snapshot', {+ operations: doc.opCount(),+ });const snapshot = doc.export({mode: 'shallow-snapshot',frontiers: doc.oplogFrontiers(),@@ -309,41 +314,49 @@ export class SyncEngine<S extends GenericRootSchema, D> {private async handleRemoteUpdate(update: RawUpdate): Promise<'applied' | 'pending' | 'reset'> {- return this.syncLock.runExclusive(() =>- telemetrySpan(this.syncs.live.documentId, 'edit.apply', async (span) => {- span.setAttr('update.bytes', update.length);- const importResult = this.loroManager.importUpdate(update);- await Promise.resolve();- if (importResult.isErr()) {- const pendingOnly = importResult.error.every(- (e) => e.code === LoroManagerError.ImportPending- );- if (pendingOnly) {- // Loro retains causally-ahead updates. Pull the missing operations- // rather than resetting the document.- this.log('debug', 'engine: remote update pending on missing ops');- span.setAttr('outcome', 'pending');- void this.convergeFromServer();- return 'pending';- }-- this.log(- 'error',- 'engine: failed to import remote update, resetting',- {- err: JSON.stringify(importResult.error),+ const generation = this.lifecycleGeneration;+ return this.syncLock.runExclusive(() => {+ // A queued packet can outlive stop/reset and its document's WASM owner.+ if (!this.isActiveGeneration(generation)) return 'applied';+ return telemetrySpan(+ this.syncs.live.documentId,+ 'edit.apply',+ async (span) => {+ span.setAttr('update.bytes', update.length);+ const importResult = this.loroManager.importUpdate(update);+ await Promise.resolve();+ if (!this.isActiveGeneration(generation)) return 'applied';+ if (importResult.isErr()) {+ const pendingOnly = importResult.error.every(+ (e) => e.code === LoroManagerError.ImportPending+ );+ if (pendingOnly) {+ // Loro retains causally-ahead updates. Pull the missing operations+ // rather than resetting the document.+ this.log('debug', 'engine: remote update pending on missing ops');+ span.setAttr('outcome', 'pending');+ void this.convergeFromServer();+ return 'pending';}- );- span.error(importResult.error);- span.setAttr('outcome', 'reset');- this.reset();- return 'reset';++ this.log(+ 'error',+ 'engine: failed to import remote update, resetting',+ {+ err: JSON.stringify(importResult.error),+ }+ );+ span.error(importResult.error);+ span.setAttr('outcome', 'reset');+ this.reset();+ return 'reset';+ }+ span.setAttr('outcome', 'applied');+ span.setAttr('did_change', importResult.value);+ return 'applied';}- span.setAttr('outcome', 'applied');- span.setAttr('did_change', importResult.value);- return 'applied';- })- );+ );+ });}private handleSourceEvent(event: SyncSourceEvent) {diff --git a/packages/graphics/README.md b/packages/graphics/README.mdindex 3a33ef674d..3f968d7d46 100644--- a/packages/graphics/README.md+++ b/packages/graphics/README.md@@ -9,7 +9,7 @@ Status reviewed 2026-09-28. The [parity plan](../../docs/design/graphics-parity.progress/next-checkpoint index. Canvas Next now includes rich text/mentions,shape labels, connectors, media, document cards and full embeds as the defaultcanvas editor. Versioned JSON persistence is wired at the Canvas host boundary.-The Loro adapter remains experimental; production collaboration is not wired.+Canvas Next binds the Loro adapter to its production shared collaboration runtime.The next product checkpoint is a[legacy bridge and color policy](../../docs/architecture/canvas-legacy-bridge.md), kept outsidethe pure core. Expanding peer support is deferred.@@ -236,7 +236,7 @@ queries are deliberate prototype limits. Text,connectors and embedded item contracts are implemented. Frames/clipping, layout,multi-surface documents, per-host core registries and runtime plugin loading are not.Affine reflection/shear compose correctly, but have no dedicated UI controls.-SyncService integration remains separate work. The two-peer Loro experiment uses+The Canvas host owns SyncService integration and persistence. Loro usesnative local undo; never apply local item-delta undo to a shared document.The [scene foundation specification](../../docs/architecture/graphics-scene-foundation.md)@@ -359,7 +359,9 @@ restores the previous selection. Solid keeps original keyed mounts intact.## Loro adapter-The in-memory peer harness gives tests two real Loro replicas with independent+`createLoroGraphicsBackendFromDoc` binds to a host-owned Loro document without+freeing it on disposal. Host bookkeeping tagged `GRAPHICS_METADATA_ORIGIN` is+excluded from scene undo. The in-memory peer harness gives tests two real Loro replicas with independentselection, camera and local undo. See [the adapter notes](src/loro/README.md) forits ordered tree mapping, geometry conflict policy, limitations and validation cases.diff --git a/packages/graphics/src/loro/README.md b/packages/graphics/src/loro/README.mdindex 8990fc1897..ac9ea2b00e 100644--- a/packages/graphics/src/loro/README.md+++ b/packages/graphics/src/loro/README.md@@ -1,13 +1,12 @@-# Two-peer scene experiment+# Collaborative scene backend-Status reviewed 2026-09-28. See the [main progress plan](../../../../docs/design/graphics-parity.md).-Automated mapping coverage now includes pencil, rich text/labels, connectors and-media/document references. Full Canvas Next integration is deferred while the-[legacy bridge and colors](../../../../docs/architecture/canvas-legacy-bridge.md) take priority.--`@macro-inc/graphics/loro` is an experimental adapter with an in-memory transport-harness used by tests. It uses the workspace Loro version (1.16.3). No SyncService,-network requests, local storage, or server changes are involved.+Canvas Next uses this adapter with the shared collaboration runtime and SyncService.+The package itself owns no network or storage: `createLoroGraphicsBackendFromDoc`+binds an externally owned document, observes remote tree changes and disposes only+its scene subscription/history/tree handle. The original snapshot-owning factory+remains useful for standalone hosts and the in-memory test harness.+Host bookkeeping uses `GRAPHICS_METADATA_ORIGIN` and is excluded from scene undo.+The workspace pins Loro 1.16.3.The root graphics export stays framework/DOM/Loro-free. `GraphicsBackend` is thesmall document/history contract; `createGraphicsEditorFromBackend` proposes local@@ -42,7 +41,7 @@ relative to the actual parent. This keeps both replicas valid and avoids interpran old local matrix in the wrong coordinate space. It is a derived interpretation:no repair operations or reconciliation loop are emitted.-**This is a policy to evaluate, not a settled production schema.** Such a node stays+The Canvas host currently uses this conflict policy. Such a node staysanchored in world space through subsequent parent transforms until it receives anew pose edit. Adapter diagnostics report these nodes. Captured world pose is thewinning edit's pose, not a guarantee that both concurrent geometric intentions@@ -94,12 +93,12 @@ seconds; states expire after 30 seconds without an update, checked on Loro'sGhosts are displayed only when their captured document clock matches the receiver'sclock. A commit therefore suppresses a delayed, obsolete gesture until freshpresence arrives. Selection IDs still resolve against the current committed scene.-The current ghost contract carries rectangle/ellipse dimensions and pencil samples,-using default renderers. It does not carry complete text, connector, media or document-geometry; do not assume every registered shape can render a valid ghost. A full-Canvas Next peer lab needs typed preview coverage or deliberate bounds-only previews-for these kinds, plus connector endpoint-draft awareness. Authenticated peer identity,-payload validation and real network presence transport remain integration work.+The ghost contract carries rectangle/ellipse dimensions and pencil samples. Text,+connectors, media and document references use bounds-only rectangle previews.+Canvas validates bounded presence payloads at its shared awareness boundary and+resolves names/colors from shared peer metadata. Connector endpoint-draft awareness+is not published; cursor/selection awareness still applies. The standalone packet+transport remains test-only; production uses the shared awareness runtime.The cursor is a colored pointer with a rounded name-only badge, shown only whilethe peer's cursor is on the canvas. Pending ghosts replace redundant transform@@ -124,12 +123,10 @@ previews, reordered packets, coalescing, offline/reconnect behavior and disposalMotion tests cover bounded debounce, mid-flight retargeting, shortest-arc rotation,stable ghost DOM, settling, reduced motion and animation cleanup.-Production integration still needs an accepted geometry/history conflict policy,-an explicit choice to retain cancellation or implement intent rebasing, mixed-content-editor validation, shared collaboration runtime integration, durable initialization,-permissions, reconnect/storage tests and deployment. Asset/text mappings now exist;-their production acceptance is separate from basic mapping tests. This transport is-only an in-memory test harness; do not turn it into another production sync engine.+Canvas Next now owns durable initialization, permissions, reconnect/storage and+shared-runtime integration. Tests exercise three sessions and rendered surfaces.+Character-level rich text, intent rebasing and production capacity measurement+remain follow-ups; the in-memory harness does not prove deployed transport limits.References: [Loro ordered trees](https://www.loro.dev/docs/tutorial/tree),[Loro undo](https://www.loro.dev/docs/advanced/undo),@@ -158,18 +155,11 @@ text-versus-move, new labels versus moves, and local undo preserving remote moveImage, video and document references use the existing shape geometry mapping.Their source bytes, resolved URLs, loading state and playback are host concerns.-### Next integration gates--Use the actual Canvas view, rich-text measurer and content/asset renderers with two-injected Loro editors. Exercise concurrent whole-string edits, text editing versus-remote movement, local text/scene undo, reference deletion, selection/gesture-awareness and mixed-content layering/focus. Keep embedded document editing under-its own existing permissions/sync; the outer scene shares only the embed reference-and display geometry. No character CRDT, durable seed or second network engine is-needed for this checkpoint.--For the later durable host, reuse the existing collaboration infrastructure and-the [spreadsheet session](../../../../apps/web/src/features/block-spreadsheet/queries/spreadsheet-session.ts)-as a reference for WAL/snapshot recovery and disposal. First audit canvas document-initialization, content routing, authorization and legacy readers; the lab does not-prove that enabling SyncService requires no server changes.+### Canvas host integration++`apps/web/src/features/block-canvas/queries/canvas-session.ts` owns shared initialization,+local snapshot/WAL recovery, live transport and teardown. The host imports only the+server's winning seed and preserves original JSON/legacy metadata for export.+Presence publication and validation stay in the host; the reusable overlay accepts+a transport-independent `GraphicsPresence` contract. Embedded documents retain+their own existing permissions/sync. The outer scene shares references and geometry.diff --git a/packages/graphics/src/loro/backend.ts b/packages/graphics/src/loro/backend.tsindex 11fcbdd58b..34e917ad53 100644--- a/packages/graphics/src/loro/backend.ts+++ b/packages/graphics/src/loro/backend.ts@@ -6,12 +6,27 @@ import { type NodeData, readScene, writeScene } from './scene-mapping';type Schema = { scene: LoroTree<NodeData> };type Source = Parameters<Parameters<GraphicsBackend['subscribe']>[0]>[0];+/** Host bookkeeping is durable but must not become a scene undo step. */+export const GRAPHICS_METADATA_ORIGIN = 'graphics:metadata';++// Loro's untyped host document cannot express the scene schema in getTree.+// readScene validates the projection before any data is exposed to the editor.+const sceneTree = (doc: LoroDoc) => doc.getTree('scene') as LoroTree<NodeData>;++export function readLoroGraphicsDocument(doc: LoroDoc, rootId: string) {+ const tree = sceneTree(doc);+ try {+ return readScene(tree, rootId).document;+ } finally {+ tree.free();+ }+}export function createLoroSeed(seed: GraphicsDocument): Uint8Array {const validated = freezeDocument(seed);const doc = new LoroDoc<Schema>();doc.setPeerId('0');- const tree = doc.getTree('scene');+ const tree = sceneTree(doc);tree.enableFractionalIndex(0);writeScene(tree,@@ -37,9 +52,31 @@ export function createLoroGraphicsBackend(const doc = new LoroDoc<Schema>();doc.import(snapshot);doc.setPeerId(peerId);- const tree = doc.getTree('scene');+ return graphicsBackend(doc, rootId, true);+}++/** Bind a scene to a document owned by the host's durable sync runtime. */+export function createLoroGraphicsBackendFromDoc(+ doc: LoroDoc,+ rootId: string,+ canEdit: () => boolean = () => true+) {+ return graphicsBackend(doc, rootId, false, canEdit);+}++function graphicsBackend(+ doc: LoroDoc,+ rootId: string,+ ownsDocument: boolean,+ canEdit: () => boolean = () => true+) {+ const tree = sceneTree(doc);tree.enableFractionalIndex(0);- const history = new UndoManager(doc, { mergeInterval: 0, maxUndoSteps: 100 });+ const history = new UndoManager(doc, {+ mergeInterval: 0,+ maxUndoSteps: 100,+ excludeOriginPrefixes: [GRAPHICS_METADATA_ORIGIN],+ });let projection = readScene(tree, rootId);let disposed = false;const listeners = new Set<(source: Source) => void>();@@ -49,7 +86,7 @@ export function createLoroGraphicsBackend(for (const listener of listeners) listener(source);};const local = (source: Source, action: () => void) => {- if (disposed) return;+ if (disposed || !canEdit()) return;const from = doc.oplogVersion();action();doc.commit();@@ -58,9 +95,15 @@ export function createLoroGraphicsBackend(refresh(source);for (const listener of updates) listener(bytes);};+ const unsubscribe = ownsDocument+ ? () => {}+ : tree.subscribe((batch) => {+ if (!disposed && batch.by === 'import') refresh('remote');+ });return {getDocument: () => projection.document,getClock() {+ if (disposed) return {};const version = doc.version();const clock = Object.fromEntries(version.toJSON());version.free();@@ -68,8 +111,8 @@ export function createLoroGraphicsBackend(},getFrameConflicts: () => projection.frameConflicts,getHistory: () => ({- canUndo: !disposed && history.canUndo(),- canRedo: !disposed && history.canRedo(),+ canUndo: !disposed && canEdit() && history.canUndo(),+ canRedo: !disposed && canEdit() && history.canRedo(),}),commit(next: GraphicsDocument) {const validated = freezeDocument(next);@@ -107,11 +150,12 @@ export function createLoroGraphicsBackend(dispose() {if (disposed) return;disposed = true;+ unsubscribe();listeners.clear();updates.clear();history.free();tree.free();- doc.free();+ if (ownsDocument) doc.free();},};}diff --git a/packages/graphics/src/loro/index.ts b/packages/graphics/src/loro/index.tsindex a1547f2503..781322cccf 100644--- a/packages/graphics/src/loro/index.ts+++ b/packages/graphics/src/loro/index.ts@@ -1,7 +1,10 @@export {createLoroGraphicsBackend,+ createLoroGraphicsBackendFromDoc,createLoroSeed,+ GRAPHICS_METADATA_ORIGIN,type LoroGraphicsBackend,+ readLoroGraphicsDocument,} from './backend';export {createGraphicsPresence,@@ -9,7 +12,9 @@ export {type PresencePacket,} from './presence';export {+ capturePresence,currentPresencePreview,type PeerPresence,type PresenceClock,+ type PresenceIdentity,} from './presence-state';diff --git a/packages/graphics/src/loro/presence-state.ts b/packages/graphics/src/loro/presence-state.tsindex eecead5606..49b1a63e86 100644--- a/packages/graphics/src/loro/presence-state.ts+++ b/packages/graphics/src/loro/presence-state.ts@@ -1,4 +1,4 @@-import type { Matrix } from '../core/affine';+import { type Matrix, multiply, translation } from '../core/affine';import { resolveAppearance } from '../core/appearance';import type { GraphicsEditor } from '../core/editor';import type { Bounds, Point, ShapeItem, ShapeKind } from '../core/model';@@ -36,12 +36,17 @@ const wireMatrix = (matrix: Matrix): WireMatrix => [...matrix];function presenceShape(node: ShapeItem, world: Matrix): PresenceShape {const bounds = shapeDefinition(node.type).bounds(node);+ const boundsOnly = !['rectangle', 'ellipse', 'pencil'].includes(node.type);return {id: node.id,- kind: node.type,+ // Host-specific text, media, references and connectors use bounds-only ghosts.+ // Their complete geometry/content is intentionally absent from presence.+ kind: boundsOnly ? 'rectangle' : node.type,width: bounds.width,height: bounds.height,- world: wireMatrix(world),+ world: wireMatrix(+ boundsOnly ? multiply(world, translation(bounds.x, bounds.y)) : world+ ),...(node.type === 'rectangle'? { cornerRadius: node.appearance.cornerRadius ?? 0 }: {}),diff --git a/packages/graphics/src/loro/presence.ts b/packages/graphics/src/loro/presence.tsindex debd8d9d10..d216f88f0c 100644--- a/packages/graphics/src/loro/presence.ts+++ b/packages/graphics/src/loro/presence.ts@@ -140,4 +140,8 @@ export function createGraphicsPresence(},};}-export type GraphicsPresence = ReturnType<typeof createGraphicsPresence>;+/** Rendering and pointer sampling need no dependency on a particular transport. */+export type GraphicsPresence = Pick<+ ReturnType<typeof createGraphicsPresence>,+ 'getClock' | 'getRemote' | 'subscribe' | 'setCursor'+>;diff --git a/packages/graphics/src/loro/solid/index.tsx b/packages/graphics/src/loro/solid/index.tsxindex ff14cd8d2e..f28b56ef2a 100644--- a/packages/graphics/src/loro/solid/index.tsx+++ b/packages/graphics/src/loro/solid/index.tsx@@ -22,6 +22,9 @@ import {type PresenceShape,} from '../presence-state';import { attachPresencePointer } from './pointer';++export { attachPresencePointer } from './pointer';+import { createPresenceMotion } from './presence-motion';function GhostShape(props: {