Skip to content

AI-native design editor. Open-source Figma alternative.

fix(cloud): save a room's document only when the room holds unsaved edits (#1352)

Danila Poyarkov8d26bd195a37
diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.md
index a8191978f..969ee17f0 100644
--- a/packages/docs/development/cloud.md
+++ b/packages/docs/development/cloud.md
@@ -187,6 +187,13 @@ layers new IDs. One signed-in editor, the one with the lowest presence client, s
the others drop their queued uploads and count their edits as saved. Guests who open a link join
the room with the link's permission and never save.
+The room says what is unsaved, not the tab. Each peer counts its own edits to the room's document
+under its Yjs client in the `edits` map, and the saver copies the counts its upload held into
+`saved` once the server has that upload. What a tab takes from the room, including the replay when
+it opens the stored file, is no edit of its own. The saver saves whenever any client has more edits
+than `saved` records, so a tab that becomes the saver also saves edits an earlier saver left, and
+opening a document nobody edited uploads nothing.
+
## Configuration
Operators author one schema-versioned TOML file. It owns URLs, trusted origins and proxies,
@@ -279,6 +286,12 @@ needs a headless `.fig` writer on the server, which is a later step.
IDs, so two tabs that read the same file cannot merge their Yjs states. The first editor seeds an
empty room only after the relay answers, and later tabs adopt the room root.
+**2026-10 · The room records what its revisions hold.** A tab compared with its own copy saw the
+room's values as edits wherever a `.fig` round trip changes them, such as defaults it writes, so
+every open uploaded a revision. Matching the round trip field by field breaks again with each new
+field. Per-client edit counts in the room are what Yjs already merges, so no server change is
+needed.
+
**2026-10 · Redirect sign-in only on the server's own editor address.** There the session cookie is
first-party and the server can send the person back to the same tab. The desktop app and editors on
other origins approve a device code instead of relying on third-party cookies or custom URL
diff --git a/src/app/cloud/rooms/live.ts b/src/app/cloud/rooms/live.ts
index f79ee3fe3..751a005e0 100644
--- a/src/app/cloud/rooms/live.ts
+++ b/src/app/cloud/rooms/live.ts
@@ -1,3 +1,4 @@
+import { isEqual } from 'es-toolkit'
import { effectScope, onScopeDispose, shallowRef, watch } from 'vue'
import { RELAY_SERVER_PEER, type CollaborationTicket } from '@open-pencil/cloud/contract'
@@ -71,8 +72,9 @@ async function catchUpWithServer(store: EditorStore): Promise<void> {
* Keeps this tab saving only while it is the room's saver, for as long as the current effect
* scope runs. A tab that stops drops its queued uploads, since the room holds those edits; the
* saver overwrites a revision it conflicts with, since the room's document already has every edit
- * in it, unless that revision is a restore, which moves the room on instead. Returns whether this
- * tab saves now.
+ * in it, unless that revision is a restore, which moves the room on instead. The saver saves
+ * whatever edits the room holds unsaved, its own or anyone's, and once the server has them tells
+ * the room so. Returns whether this tab saves now.
*/
function followSaver(
store: EditorStore,
@@ -89,6 +91,8 @@ function followSaver(
if (next === saving) return
saving = next
store.state.autosaveEnabled = next
+ // Edits an earlier saver left without uploading, or made where nobody saved, are this tab's now.
+ if (next && session.saves.unsaved()) store.markDocumentChanged()
const id = documentId()
if (!id) return
if (!next) {
@@ -101,6 +105,18 @@ function followSaver(
if (store.getStorageBinding() && store.hasUnsavedChanges()) await store.saveFigFile()
}
+ /** Tells the room its edits are saved once this tab's upload of all of them is on the server. */
+ async function markUploaded(id: string) {
+ const clean = () => saving === true && !store.hasUnsavedChanges()
+ if (!clean() || !session.saves.unsaved()) return
+ const counts = session.saves.counts()
+ const meta = await getLocalCanvasStore().getMeta(id)
+ // An edit that arrived meanwhile is in a later save, and so is not saved yet.
+ if (meta?.syncStatus !== 'synced' || !clean() || !isEqual(counts, session.saves.counts()))
+ return
+ session.saves.markSaved(counts)
+ }
+
async function settleConflict(id: string) {
if (!saving) return
const meta = await getLocalCanvasStore().getMeta(id)
@@ -116,12 +132,25 @@ function followSaver(
() => store.hasUnsavedChanges(),
(dirty) => {
if (dirty && saving === false) store.markDocumentSaved()
+ const id = documentId()
+ if (!dirty && id) void markUploaded(id)
}
)
+ // What the tab takes from the room is no edit of its own; the room says what is unsaved. It
+ // says so after the task, once a tab that seeded the room has called its document saved.
+ onScopeDispose(
+ session.saves.onChange(() =>
+ queueMicrotask(() => {
+ if (saving === true && session.saves.unsaved()) store.markDocumentChanged()
+ })
+ )
+ )
onScopeDispose(
onStorageWorkspaceEvent((event) => {
const id = documentId()
- if (id && event.documentId === id) void settleConflict(id)
+ if (!id || event.documentId !== id) return
+ void settleConflict(id)
+ void markUploaded(id)
})
)
return () => saving === true
@@ -170,7 +199,10 @@ export function openCloudDocumentRoom(
const stopSynced = session.onSynced((peerId) => {
if (peerId !== RELAY_SERVER_PEER) return
stopSynced()
- if (canEdit && !session.roomHasDocument()) session.shareDocument()
+ if (!canEdit || session.roomHasDocument()) return
+ session.shareDocument()
+ // The tab's document is the stored revision unless it was edited first.
+ if (!store.hasUnsavedChanges()) session.saves.markSaved(session.saves.counts())
})
onScopeDispose(stopSynced)
// Unsure whether the document moved on, the saver waits rather than overwrite a restore.
diff --git a/src/app/collab/room/saves.ts b/src/app/collab/room/saves.ts
new file mode 100644
index 000000000..4135aeae0
--- /dev/null
+++ b/src/app/collab/room/saves.ts
@@ -0,0 +1,79 @@
+import type * as Y from 'yjs'
+
+import { readCounter } from '@/app/collab/shared-tree/fields'
+
+/** How many edits each peer's client has made to a room's document. */
+export type EditCounts = ReadonlyMap<string, number>
+
+const EDITS_KEY = 'edits'
+const SAVED_KEY = 'saved'
+
+function readCounts(map: Y.Map<unknown>): Map<string, number> {
+ const counts = new Map<string, number>()
+ for (const [client, value] of map.entries()) {
+ const count = readCounter(value)
+ if (count !== undefined) counts.set(client, count)
+ }
+ return counts
+}
+
+/** Whether `counts` holds an edit that `saved` does not. */
+function hasEditsBeyond(counts: EditCounts, saved: EditCounts): boolean {
+ return [...counts].some(([client, count]) => count > (saved.get(client) ?? 0))
+}
+
+/**
+ * What of a room's document its stored revisions hold, so a tab that opens the stored document
+ * can tell the room's copy from an edit. Each peer counts its own edits to the document's content
+ * under its client in `edits`; whoever saves copies the counts its upload held into `saved`. The
+ * room has unsaved edits while any client has more edits than `saved` records.
+ */
+export function trackRoomSaves(ydoc: Y.Doc, content: readonly object[]) {
+ const edits = ydoc.getMap<unknown>(EDITS_KEY)
+ const saved = ydoc.getMap<unknown>(SAVED_KEY)
+ const client = String(ydoc.clientID)
+ const handlers = new Set<() => void>()
+
+ // A count written here is a transaction of its own, which Yjs runs right after this one.
+ const countEdit = (transaction: Y.Transaction) => {
+ if (!transaction.local) return
+ const changed: ReadonlyMap<object, unknown> = transaction.changedParentTypes
+ if (!content.some((type) => changed.has(type))) return
+ edits.set(client, (readCounter(edits.get(client)) ?? 0) + 1)
+ }
+ const notify = () => {
+ for (const handler of handlers) handler()
+ }
+ ydoc.on('afterTransaction', countEdit)
+ edits.observe(notify)
+ saved.observe(notify)
+
+ return {
+ counts: (): EditCounts => readCounts(edits),
+ /** Whether the room holds edits no stored revision has. */
+ unsaved: () => hasEditsBeyond(readCounts(edits), readCounts(saved)),
+ /** Records that a stored revision now holds the edits `counts` counted. */
+ markSaved(counts: EditCounts) {
+ const current = readCounts(saved)
+ if (!hasEditsBeyond(counts, current)) return
+ ydoc.transact(() => {
+ for (const [client, count] of counts) {
+ if (count > (current.get(client) ?? 0)) saved.set(client, count)
+ }
+ })
+ },
+ /** Follows edits and saves from anyone; returns the unsubscribe. */
+ onChange(handler: () => void): () => void {
+ handlers.add(handler)
+ return () => handlers.delete(handler)
+ },
+ dispose() {
+ ydoc.off('afterTransaction', countEdit)
+ edits.unobserve(notify)
+ saved.unobserve(notify)
+ handlers.clear()
+ }
+ }
+}
+
+export type RoomSaves = Omit<ReturnType<typeof trackRoomSaves>, 'dispose'>
diff --git a/src/app/collab/session.ts b/src/app/collab/session.ts
index cbbb25895..015ee809a 100644
--- a/src/app/collab/session.ts
+++ b/src/app/collab/session.ts
@@ -11,6 +11,7 @@ import { buildRemotePeers } from '@/app/collab/awareness'
import { useCollabIdentity } from '@/app/collab/identity'
import { publishLocalAgents } from '@/app/collab/local-awareness'
import { connectCollabRoom } from '@/app/collab/room/connection'
+import { trackRoomSaves, type RoomSaves } from '@/app/collab/room/saves'
import { deriveRoomStatus, type RoomStatus } from '@/app/collab/room/status'
import {
readRoomName,
@@ -53,6 +54,8 @@ export interface RoomSession {
readonly identity: RoomIdentity
/** Whether the person may leave; a stored document's room stays open while its tab does. */
readonly leavable: boolean
+ /** What of the room's document its stored revisions hold. */
+ readonly saves: RoomSaves
updateCursor(x: number, y: number, pageId: string): void
updateSelection(ids: string[]): void
/** Writes the tab's whole document into the room and makes its root the room's. */
@@ -95,7 +98,8 @@ export interface RoomSessionOptions {
tickMs?: number
/**
* The tab already shows the room's document, as a stored document opened before its room was:
- * it counts as having the document until the room says it holds another.
+ * it counts as having the document until the room says it holds another, and what it takes
+ * from the room is no edit of its own, since the room says what is unsaved.
*/
holdsDocument?: boolean
/** False for a room the tab's document lives in, which the person never leaves by hand. */
@@ -128,9 +132,12 @@ export function openRoomSession({
const yvariables: YRecords = ydoc.getMap('variables')
const ycollections: YRecords = ydoc.getMap('collections')
const persistence = openSavedCopy(roomId, ydoc)
+ const saves = trackRoomSaves(ydoc, [ynodes, yimages, yvariables, ycollections])
+ const adopt = (apply: () => void) => (holdsDocument ? store.adoptChanges(apply) : apply())
const peers = shallowRef<RemotePeer[]>([])
- const hasDocument = ref(false)
+ // A tab that holds the document shows it from the start; the room's screen would replace it.
+ const hasDocument = ref(holdsDocument)
const savedCopyLoaded = ref(false)
const openedAt = Date.now()
const now = ref(openedAt)
@@ -174,7 +181,9 @@ export function openRoomSession({
followsRoom = true
suppressGraphSync = true
try {
- sync.dropLayersOutsideRoom()
+ // What the person drew while the room loaded is theirs; the rest is the file's copy.
+ sync.syncHeldBackEdits()
+ adopt(sync.dropLayersOutsideRoom)
} finally {
suppressGraphSync = false
}
@@ -210,7 +219,7 @@ export function openRoomSession({
suppressGraphSync = value
},
applyYjsToGraph: (events) => {
- sync.applyYjsToGraph(events)
+ adopt(() => sync.applyYjsToGraph(events))
refreshDocument()
}
})
@@ -270,6 +279,7 @@ export function openRoomSession({
voice,
identity,
leavable,
+ saves,
updateCursor(x, y, pageId) {
awareness.setLocalStateField('cursor', { x, y, pageId, zoom: store.state.zoom })
},
@@ -303,6 +313,7 @@ export function openRoomSession({
voice.dispose()
meta.unobserve(refreshDocument)
unregisterYjsObservers()
+ saves.dispose()
// Destroying the awareness can emit a last change; nothing here should react to it.
awareness.off('change', updatePeers)
void connection.room.leave()
diff --git a/src/app/collab/shared-tree/sync.ts b/src/app/collab/shared-tree/sync.ts
index e04baf213..4f6b9e001 100644
--- a/src/app/collab/shared-tree/sync.ts
+++ b/src/app/collab/shared-tree/sync.ts
@@ -44,6 +44,13 @@ export function createLocalEdit(): LocalEdit {
}
}
+/** Adds what `edit` changed to `into`. */
+export function mergeLocalEdit(into: LocalEdit, edit: LocalEdit): void {
+ for (const key of Object.keys(into) as (keyof LocalEdit)[]) {
+ for (const id of edit[key]) into[key].add(id)
+ }
+}
+
export function isLocalEditEmpty(edit: LocalEdit): boolean {
return Object.values(edit).every((ids: Set<string>) => ids.size === 0)
}
diff --git a/src/app/collab/yjs-sync.ts b/src/app/collab/yjs-sync.ts
index 62824e835..0d2a83923 100644
--- a/src/app/collab/yjs-sync.ts
+++ b/src/app/collab/yjs-sync.ts
@@ -8,6 +8,7 @@ import { decodeNodeFromYjs, syncEncodedNodeToYMap } from '@/app/collab/node-code
import {
claimRoot,
markTreeFormat,
+ readRoot,
writeOrderKey,
writePage,
writeParentEntry,
@@ -21,6 +22,7 @@ import {
createSharedTree,
isLocalEditEmpty,
keepSharedLayers,
+ mergeLocalEdit,
pageOf,
recordLocalLayers,
writeLocalPlacement,
@@ -181,6 +183,8 @@ export function createYjsGraphSync({
}: YjsGraphSyncOptions) {
let pendingPageSwitch: { store: EditorStore; pageId: string } | undefined
let shared: SharedTree | null = null
+ /** Edits made before this peer knew the room's root, which the room did not take. */
+ let heldBack = createLocalEdit()
function sharedTreeOf(ydoc: Y.Doc): SharedTree {
if (shared?.ydoc !== ydoc) {
@@ -216,6 +220,7 @@ export function createYjsGraphSync({
const ynodes = getYnodes()
if (!ydoc || !ynodes) return
const tree = sharedTreeOf(ydoc)
+ if (tree.rootId === null) mergeLocalEdit(heldBack, edit)
setSuppressYjsEvents(true)
try {
ydoc.transact(() => {
@@ -278,6 +283,7 @@ export function createYjsGraphSync({
claimRoot(ydoc.getMap('meta'), graph.rootId)
markTreeFormat(ydoc.getMap('meta'))
})
+ heldBack = createLocalEdit()
recordLocalLayers(sharedTreeOf(ydoc), ynodes, ydoc.getMap('meta'), ynodes.keys())
} catch (error) {
logCollabSyncError('Failed to sync document', error)
@@ -355,6 +361,21 @@ export function createYjsGraphSync({
})
}
+ /**
+ * Writes the edits made before the room's root was known, once this peer's document follows
+ * that root, as a stored document's tab does: what was drawn while the room loaded joins it.
+ */
+ function syncHeldBackEdits() {
+ const ydoc = getYdoc()
+ const rootId = ydoc ? readRoot(ydoc.getMap('meta')) : undefined
+ if (!ydoc || rootId === undefined || isLocalEditEmpty(heldBack)) return
+ const tree = sharedTreeOf(ydoc)
+ if (tree.rootId === null) tree.setRoot(rootId)
+ const edit = heldBack
+ heldBack = createLocalEdit()
+ syncLocalEdit(edit)
+ }
+
/**
* Removes the layers under the document's root that the room does not hold. A stored document
* opened in several tabs numbers its layers afresh each time, so its copies of layers the room
@@ -382,6 +403,7 @@ export function createYjsGraphSync({
syncLocalEdit,
syncAllNodesToYjs,
applyYjsToGraph,
+ syncHeldBackEdits,
dropLayersOutsideRoom
}
}
diff --git a/src/app/document/io/changes.ts b/src/app/document/io/changes.ts
index f1ea3616a..65a99c89a 100644
--- a/src/app/document/io/changes.ts
+++ b/src/app/document/io/changes.ts
@@ -28,6 +28,8 @@ export function createDocumentChanges(editor: Editor) {
let savedHistory: UndoEntry | undefined = editor.undo.peekUndo()
/** The history at each captured revision, for a save that finishes after later edits. */
const capturedHistory = new Map<number, UndoEntry | undefined>()
+ /** How many changes the document already had elsewhere are being applied. */
+ let adopting = 0
const dirty = computed(() => {
if (revision.value === savedRevision.value) return false
@@ -42,7 +44,7 @@ export function createDocumentChanges(editor: Editor) {
outsideRevision = revision.value
}
const contentChanged = () => {
- if (editor.graph.isApplyingImportedState) return
+ if (editor.graph.isApplyingImportedState || adopting > 0) return
revision.value++
contentRevision = revision.value
const at = contentRevision
@@ -88,6 +90,15 @@ export function createDocumentChanges(editor: Editor) {
savedRevision.value = version
},
markChanged: changed,
+ /** Applies changes the document already has elsewhere, such as its room's, as no edit. */
+ adopt: <T>(apply: () => T): T => {
+ adopting++
+ try {
+ return apply()
+ } finally {
+ adopting--
+ }
+ },
dispose: () => {
for (const unsubscribe of unsubscribers) unsubscribe()
}
diff --git a/src/app/document/io/create.ts b/src/app/document/io/create.ts
index 18fb1e16e..93e4f6463 100644
--- a/src/app/document/io/create.ts
+++ b/src/app/document/io/create.ts
@@ -94,6 +94,8 @@ export function createDocumentIOActions(
importDOMText,
hasUnsavedChanges: sourceActions.hasUnsavedChanges,
markDocumentSaved: () => sourceActions.markDocumentSaved(),
+ markDocumentChanged: sourceActions.markDocumentChanged,
+ adoptChanges: sourceActions.adoptChanges,
saveFigFile: sourceActions.saveFigFile,
saveFigFileAs: sourceActions.saveFigFileAs
}
diff --git a/src/app/document/io/source/actions.ts b/src/app/document/io/source/actions.ts
index 4281e3925..2bc73d2eb 100644
--- a/src/app/document/io/source/actions.ts
+++ b/src/app/document/io/source/actions.ts
@@ -269,6 +269,8 @@ export function createDocumentSourceActions({
saveFigFileAs: () => saveAndTrack(saveFigFileAs),
hasUnsavedChanges: changes.hasUnsavedChanges,
markDocumentSaved,
+ markDocumentChanged: changes.markChanged,
+ adoptChanges: changes.adopt,
getStorageBinding,
getRecoveryId: () => recovery.getRecoveryId(),
adoptRecoverySnapshot: (id: string) => {
diff --git a/src/app/editor/session/modules.ts b/src/app/editor/session/modules.ts
index 131e55adb..d442e6efc 100644
--- a/src/app/editor/session/modules.ts
+++ b/src/app/editor/session/modules.ts
@@ -86,6 +86,10 @@ export function createEditorStoreModules(
hasUnsavedChanges: documentIO.hasUnsavedChanges,
/** Takes the document as it is now as its saved state, so closing it asks nothing. */
markDocumentSaved: documentIO.markDocumentSaved,
+ /** Counts the document changed by something outside its history, so it gets saved. */
+ markDocumentChanged: documentIO.markDocumentChanged,
+ /** Applies changes the document already has elsewhere, such as its room's, as no edit. */
+ adoptChanges: documentIO.adoptChanges,
saveFigFile: documentIO.saveFigFile,
saveFigFileAs: documentIO.saveFigFileAs,
getDocumentFilePath: documentIO.getDocumentFilePath,
diff --git a/tests/app/collab/room/saves.test.ts b/tests/app/collab/room/saves.test.ts
new file mode 100644
index 000000000..bc56af30d
--- /dev/null
+++ b/tests/app/collab/room/saves.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, test } from 'bun:test'
+
+import * as Y from 'yjs'
+
+import { trackRoomSaves } from '@/app/collab/room/saves'
+
+function peer() {
+ const ydoc = new Y.Doc()
+ const nodes = ydoc.getMap<unknown>('nodes')
+ const saves = trackRoomSaves(ydoc, [nodes])
+ return { ydoc, nodes, saves }
+}
+
+function exchange(from: Y.Doc, to: Y.Doc) {
+ Y.applyUpdate(to, Y.encodeStateAsUpdate(from, Y.encodeStateVector(to)))
+}
+
+describe('room saves', () => {
+ test('a peer’s own edits to the content are unsaved until a save holds them', () => {
+ const { nodes, saves, ydoc } = peer()
+ ydoc.getMap('meta').set('clock', 1)
+ expect(saves.unsaved()).toBe(false)
+
+ nodes.set('1:2', new Y.Map())
+ expect(saves.unsaved()).toBe(true)
+ saves.markSaved(saves.counts())
+ expect(saves.unsaved()).toBe(false)
+ })
+
+ test('edits that arrive from another peer are theirs, and unsaved for everyone', () => {
+ const ada = peer()
+ const grace = peer()
+ ada.nodes.set('1:2', new Y.Map())
+ exchange(ada.ydoc, grace.ydoc)
+
+ expect(grace.saves.counts()).toEqual(new Map([[String(ada.ydoc.clientID), 1]]))
+ expect(grace.saves.unsaved()).toBe(true)
+ grace.saves.markSaved(grace.saves.counts())
+ exchange(grace.ydoc, ada.ydoc)
+ expect(ada.saves.unsaved()).toBe(false)
+ })
+
+ test('a save that held fewer edits leaves the later ones unsaved', () => {
+ const { nodes, saves } = peer()
+ nodes.set('1:2', new Y.Map())
+ const held = saves.counts()
+ nodes.set('1:3', new Y.Map())
+
+ saves.markSaved(held)
+ expect(saves.unsaved()).toBe(true)
+ saves.markSaved(saves.counts())
+ saves.markSaved(held)
+ expect(saves.unsaved()).toBe(false)
+ })
+})
diff --git a/tests/app/collab/session.test.ts b/tests/app/collab/session.test.ts
index 0feb8eb7a..c2142679b 100644
--- a/tests/app/collab/session.test.ts
+++ b/tests/app/collab/session.test.ts
@@ -143,6 +143,25 @@ describe('room sessions', () => {
})
})
+ test('a tab that holds the room’s document keeps showing it while its saved copy loads', async () => {
+ await withRooms(async (open) => {
+ let loaded: () => void = () => undefined
+ const whenSynced = new Promise<void>((resolve) => {
+ loaded = resolve
+ })
+ const session = open({
+ roomId: ROOM_A,
+ store: newStore('Poster'),
+ origin: 'shared',
+ holdsDocument: true,
+ openSavedCopy: () => ({ whenSynced, destroy: () => undefined })
+ })
+ expect(session.hasDocument.value).toBe(true)
+ expect(session.status.value).toBe('alone')
+ loaded()
+ })
+ })
+
test('a room someone shared or joined can be left', async () => {
await withRooms(async (open) => {
const shared = open({ roomId: ROOM_A, store: newStore('Poster'), origin: 'shared' })
diff --git a/tests/integration/collab/cloud-relay.test.ts b/tests/integration/collab/cloud-relay.test.ts
index 769cbceea..d17941276 100644
--- a/tests/integration/collab/cloud-relay.test.ts
+++ b/tests/integration/collab/cloud-relay.test.ts
@@ -1,5 +1,5 @@
import 'fake-indexeddb/auto'
-import { afterEach, describe, expect, test } from 'bun:test'
+import { afterEach, describe, expect, spyOn, test } from 'bun:test'
import { compact } from 'es-toolkit'
import * as awarenessProtocol from 'y-protocols/awareness'
@@ -15,7 +15,10 @@ import { versionListRevision } from '@/app/cloud/versions/history'
import { useCollabIdentity } from '@/app/collab/identity'
import { connectCollabRoom } from '@/app/collab/room/connection'
import { openDocumentRoom, roomById, roomForStore } from '@/app/collab/rooms'
-import { createEditorStore } from '@/app/editor/session'
+import { createEditorStore, type EditorStore } from '@/app/editor/session'
+import { createMemoryLocalCanvasStore } from '@/app/storage/local-store'
+import { resetLocalCanvasStoreForTests } from '@/app/storage/local-store/store'
+import { emitStorageWorkspaceEvent } from '@/app/storage/workspace/events'
import { startTestRelay } from '#tests/helpers/collab/relay-server'
@@ -485,6 +488,12 @@ describe('Cloud document rooms, live order', () => {
transport: relay.join(documentId, 'Ada', 'edit', 'user'),
permission: 'edit'
})
+ let synced = false
+ cleanups.push(
+ second.session.onSynced(() => {
+ synced = true
+ })
+ )
cleanups.push(() => {
second.stop()
second.session.dispose()
@@ -496,7 +505,7 @@ describe('Cloud document rooms, live order', () => {
node.type === 'RECTANGLE' &&
store.graph.closest(node.id, (ancestor) => ancestor.id === store.graph.rootId)
).length
- await until(() => second.session.hasDocument.value && rectangles(ada) === 1)
+ await until(() => synced && rectangles(ada) === 1)
// Ada's updates arrive in order, so a copy pushed into the room would land before this marker.
const adaPage = ada.graph.getPages()[0]
if (!adaPage) throw new Error('Expected a page')
@@ -508,6 +517,40 @@ describe('Cloud document rooms, live order', () => {
})
describe('Cloud document rooms, drawing early', () => {
+ test('a shape a joining tab draws before the relay answers reaches the room', async () => {
+ const relay = await startRelay()
+ const documentId = crypto.randomUUID()
+ const roomId = `cloud:${documentId}:0`
+ const [grace, ada] = await openedTwice()
+ const first = openCloudDocumentRoom(grace, {
+ roomId,
+ transport: relay.join(documentId, 'Grace', 'edit', 'user'),
+ permission: 'edit'
+ })
+ cleanups.push(() => {
+ first.stop()
+ first.session.dispose()
+ })
+ await until(() => first.session.roomHasDocument())
+ await until(() => ada.state.preparation === null)
+ const second = openCloudDocumentRoom(ada, {
+ roomId,
+ transport: relay.join(documentId, 'Ada', 'edit', 'user'),
+ permission: 'edit'
+ })
+ cleanups.push(() => {
+ second.stop()
+ second.session.dispose()
+ })
+ // The tab shows its stored document at once, so the person may draw before the room arrives.
+ const page = ada.graph.getPages()[0]
+ if (!page) throw new Error('Expected a page')
+ ada.graph.createNode('ELLIPSE', page.id, { id: 'early:ada', name: 'Early' })
+
+ await until(() => grace.graph.getNode('early:ada') !== undefined)
+ expect(ada.graph.getNode('early:ada')?.parentId).toBe(page.id)
+ })
+
test('a shape drawn before the relay answers is in the room once it is seeded', async () => {
const relay = await startRelay()
const documentId = crypto.randomUUID()
@@ -543,3 +586,107 @@ describe('Cloud document rooms, drawing early', () => {
await until(() => watcher.graph.getNode('early:card') !== undefined)
})
})
+
+describe('Cloud document rooms, unsaved edits', () => {
+ /** Grace's tab seeds the room and leaves, after `edit`, so Ada's tab opens it alone and saves. */
+ async function reopenAfter(edit: (grace: EditorStore) => void) {
+ const relay = await startRelay()
+ const documentId = crypto.randomUUID()
+ const roomId = `cloud:${documentId}:0`
+ const [grace, ada] = await openedTwice()
+ // Opening a stored document marks it saved, so the room takes it as the stored revision.
+ await until(() => grace.state.preparation === null)
+ grace.markDocumentSaved()
+ const first = openCloudDocumentRoom(grace, {
+ roomId,
+ transport: relay.join(documentId, 'Grace', 'edit', 'user'),
+ permission: 'edit'
+ })
+ await until(() => first.session.roomHasDocument())
+ edit(grace)
+ first.stop()
+ first.session.dispose()
+
+ await until(() => ada.state.preparation === null)
+ // The file read back differs from the room's copy, as a value the round trip changes would.
+ const card = ada.graph.getPages()[0]?.childIds[0]
+ if (!card) throw new Error('Expected a layer')
+ ada.graph.updateNode(card, { name: 'Read back' })
+ ada.markDocumentSaved()
+ let synced = false
+ const second = openCloudDocumentRoom(ada, {
+ roomId,
+ transport: relay.join(documentId, 'Ada', 'edit', 'user'),
+ permission: 'edit'
+ })
+ cleanups.push(
+ second.session.onSynced(() => {
+ synced = true
+ })
+ )
+ cleanups.push(() => {
+ second.stop()
+ second.session.dispose()
+ })
+ await until(() => synced && ada.state.autosaveEnabled)
+ return { ada, card, session: second.session }
+ }
+
+ test('a tab that takes in the room’s copy of its document has nothing to save', async () => {
+ const { ada, card, session } = await reopenAfter(() => undefined)
+
+ expect(ada.graph.getNode(card)?.name).toBe('Card')
+ expect(session.saves.unsaved()).toBe(false)
+ expect(ada.hasUnsavedChanges()).toBe(false)
+ })
+
+ test('the tab that saves next saves edits the room holds unsaved', async () => {
+ const { ada, session } = await reopenAfter((grace) => {
+ const page = grace.graph.getPages()[0]
+ if (!page) throw new Error('Expected a page')
+ grace.graph.createNode('ELLIPSE', page.id, { id: 'left:unsaved', name: 'Dot' })
+ })
+
+ expect(ada.graph.getNode('left:unsaved')).toBeDefined()
+ expect(session.saves.unsaved()).toBe(true)
+ expect(ada.hasUnsavedChanges()).toBe(true)
+ })
+
+ test('the room’s edits are saved once the saver’s upload of them is on the server', async () => {
+ const { ada, session } = await reopenAfter((grace) => {
+ const page = grace.graph.getPages()[0]
+ if (!page) throw new Error('Expected a page')
+ grace.graph.createNode('ELLIPSE', page.id, { name: 'Dot' })
+ })
+ const local = createMemoryLocalCanvasStore()
+ resetLocalCanvasStoreForTests(local)
+ cleanups.push(() => resetLocalCanvasStoreForTests())
+ const binding = { providerId: 'cloud', documentId: crypto.randomUUID() } as const
+ await local.writeCanvas({
+ id: binding.documentId,
+ providerId: 'cloud',
+ name: 'Poster',
+ figBytes: new Uint8Array([1]),
+ syncStatus: 'pending'
+ })
+ const bound = spyOn(ada, 'getStorageBinding').mockReturnValue(binding)
+ cleanups.push(() => bound.mockRestore())
+ // The saver reads whether its upload is on the server; the room hears only after that.
+ let reads = 0
+ const getMeta = local.getMeta.bind(local)
+ const read = spyOn(local, 'getMeta').mockImplementation(async (id) => {
+ const meta = await getMeta(id)
+ reads++
+ return meta
+ })
+ cleanups.push(() => read.mockRestore())
+ // The tab's save landed locally, as autosave leaves it, and is still on its way.
+ ada.markDocumentSaved()
+ await until(() => reads > 0)
+ expect(session.saves.unsaved()).toBe(true)
+
+ await local.updateMeta(binding.documentId, { syncStatus: 'synced' })
+ emitStorageWorkspaceEvent({ ...binding, kind: 'changed' })
+ await until(() => !session.saves.unsaved())
+ })
+})