Skip to content

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

feat: update open version histories live when the document's history changes (#1301)

Danila Poyarkov32ae94175da6
diff --git a/packages/cloud/src/contract/relay.ts b/packages/cloud/src/contract/relay.ts
index c4050a4e7..ea10437f6 100644
--- a/packages/cloud/src/contract/relay.ts
+++ b/packages/cloud/src/contract/relay.ts
@@ -15,7 +15,9 @@ export const COLLAB_ACTIONS = {
syncStep1: 'sync-step1',
syncReply: 'sync-reply',
awareness: 'awareness',
- agentPreview: 'agent-preview'
+ agentPreview: 'agent-preview',
+ /** From the server only: the document's version history changed, so open lists load it again. */
+ versions: 'versions'
} as const
/**
diff --git a/packages/cloud/src/runtime/node/server.ts b/packages/cloud/src/runtime/node/server.ts
index a59850108..74e8fc462 100644
--- a/packages/cloud/src/runtime/node/server.ts
+++ b/packages/cloud/src/runtime/node/server.ts
@@ -107,7 +107,8 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})
transactionalEmail: email,
enrollment,
relayURL: config.relayURL ?? defaultRelayURL(config.publicURL),
- onDocumentRestored: (documentId) => relay.startOver(documentId)
+ onDocumentRestored: (documentId) => relay.startOver(documentId),
+ onDocumentVersionsChanged: (documentId) => relay.announceVersions(documentId)
})
const emailWorker = emailTransport
? startTransactionalEmailWorker(email, {
diff --git a/packages/cloud/src/server/app.ts b/packages/cloud/src/server/app.ts
index 116f40ca4..0aaadb213 100644
--- a/packages/cloud/src/server/app.ts
+++ b/packages/cloud/src/server/app.ts
@@ -70,6 +70,8 @@ export type CloudServices = {
relayURL?: string
/** Ends a restored document's live rooms, on the relay this runtime runs, if any. */
onDocumentRestored?: (documentId: string) => void
+ /** Tells a document's live rooms its version history changed, on the relay this runtime runs. */
+ onDocumentVersionsChanged?: (documentId: string) => void
}
type CloudEnvironment = CloudAPIEnvironment
@@ -199,12 +201,14 @@ export function createCloudApp(services: CloudServices) {
createDefaultCloudPolicy(new EntitlementOpenFeatureProvider(entitlementSource))
const documents = createDocumentService(services.database, services.objects, {
policy,
- technicalMaximumUploadBytes: services.config.technicalLimits.maximumUploadBytes
+ technicalMaximumUploadBytes: services.config.technicalLimits.maximumUploadBytes,
+ onVersionsChanged: services.onDocumentVersionsChanged
})
const versions = createDocumentVersionService(services.database, services.objects, {
policy,
deploymentMode: services.config.deployment,
- onRestored: services.onDocumentRestored
+ onRestored: services.onDocumentRestored,
+ onVersionsChanged: services.onDocumentVersionsChanged
})
const entitlements = createEntitlementService(
services.database,
diff --git a/packages/cloud/src/server/collaboration/relay/hub.ts b/packages/cloud/src/server/collaboration/relay/hub.ts
index e68f9ab1f..e41588cac 100644
--- a/packages/cloud/src/server/collaboration/relay/hub.ts
+++ b/packages/cloud/src/server/collaboration/relay/hub.ts
@@ -207,6 +207,8 @@ export function createCollaborationRelay(options: CollaborationRelayOptions) {
) {
const readOnly = peer.authorization.permission === 'view'
if (readOnly && !VIEWER_ACTIONS.has(namespace)) return
+ // Only the server says the history changed.
+ if (namespace === COLLAB_ACTIONS.versions) return
let forwarded = payload
if (namespace === COLLAB_ACTIONS.awareness) {
@@ -452,6 +454,20 @@ export function createCollaborationRelay(options: CollaborationRelayOptions) {
}
},
+ /** Tells everyone in a document's rooms that its version history changed. */
+ announceVersions(documentId: string) {
+ const frame = encodeRelayServerFrame({
+ type: 'message',
+ namespace: COLLAB_ACTIONS.versions,
+ from: RELAY_SERVER_PEER,
+ payload: new Uint8Array()
+ })
+ for (const room of rooms.values()) {
+ if (room.identity.documentId !== documentId) continue
+ for (const peer of room.peers.values()) peer.socket.send(frame)
+ }
+ },
+
/** Saves every open room and closes its sockets, as the runtime shuts down. */
async close() {
shuttingDown = true
diff --git a/packages/cloud/src/server/documents/service.ts b/packages/cloud/src/server/documents/service.ts
index ed34f97a0..5cc9adf0c 100644
--- a/packages/cloud/src/server/documents/service.ts
+++ b/packages/cloud/src/server/documents/service.ts
@@ -22,12 +22,12 @@ import {
} from '#cloud/server/documents/repository'
import { documentSummary, getDocumentSummaryRow } from '#cloud/server/documents/summary'
import type { CreateDocumentUploadResult } from '#cloud/server/documents/types'
-import { recordCheckpoint } from '#cloud/server/documents/versions/checkpoint'
+import { announceVersions, recordCheckpoint } from '#cloud/server/documents/versions/checkpoint'
import type { ObjectStore } from '#cloud/server/objects'
import { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'
import type { CloudPolicy } from '#cloud/server/policy/policy'
import { createStorageQuotaService } from '#cloud/server/quota'
-import type { Kysely } from 'kysely'
+import type { Kysely, Transaction } from 'kysely'
const DOWNLOAD_LIFETIME_MS = 5 * 60 * 1000
const UPLOAD_LIFETIME_MS = 15 * 60 * 1000
@@ -49,6 +49,20 @@ export class UploadInvalidError extends Error {
export type DocumentServiceOptions = {
policy?: CloudPolicy
technicalMaximumUploadBytes?: number
+ /** Called once a save adds a checkpoint to the document's history. */
+ onVersionsChanged?: (documentId: string) => void
+}
+
+/** Whether the stored object is the file the upload declared, which the commit names again. */
+function matchesUpload(
+ stored: { checksum: string; byteSize: number; contentType: string },
+ upload: { checksum: string; byteSize: number | string | bigint; contentType: string }
+): boolean {
+ return (
+ stored.checksum === upload.checksum &&
+ stored.byteSize === Number(upload.byteSize) &&
+ stored.contentType === upload.contentType
+ )
}
export function createDocumentService(
@@ -59,6 +73,89 @@ export function createDocumentService(
const cleanup = createUploadCleanupService(database, objects)
const quota = createStorageQuotaService(database)
+ /**
+ * Makes a committed upload the document's current revision, unless it already was, and records
+ * the checkpoint the save adds, if any. Whether the history gained one.
+ */
+ async function landRevision(
+ transaction: Transaction<CloudDatabase>,
+ {
+ userId,
+ uploadId,
+ upload,
+ stored,
+ revisionId,
+ storageObjectId
+ }: {
+ userId: string
+ uploadId: string
+ upload: { documentId: string; baseRevisionId: string | null; objectKey: string }
+ stored: { checksum: string; byteSize: number; contentType: string }
+ revisionId: string
+ storageObjectId: string
+ }
+ ): Promise<boolean> {
+ const lockedUpload = await transaction
+ .selectFrom('upload')
+ .select('status')
+ .where('id', '=', uploadId)
+ .forUpdate()
+ .executeTakeFirstOrThrow()
+ if (lockedUpload.status === 'committed') return false
+ if (lockedUpload.status !== 'finalizing') throw new UploadInvalidError()
+ const document = await transaction
+ .selectFrom('document')
+ .select(['currentRevisionId'])
+ .where('id', '=', upload.documentId)
+ .forUpdate()
+ .executeTakeFirstOrThrow()
+ if (document.currentRevisionId !== upload.baseRevisionId) {
+ throw new DocumentConflictError()
+ }
+ await transaction
+ .insertInto('storageObject')
+ .values({
+ id: storageObjectId,
+ objectKey: upload.objectKey,
+ checksum: stored.checksum,
+ byteSize: stored.byteSize,
+ contentType: stored.contentType
+ })
+ .execute()
+ await transaction
+ .insertInto('documentRevision')
+ .values({
+ id: revisionId,
+ documentId: upload.documentId,
+ parentRevisionId: upload.baseRevisionId,
+ storageObjectId,
+ createdBy: userId
+ })
+ .execute()
+ await transaction
+ .updateTable('document')
+ .set({
+ currentRevisionId: revisionId,
+ version: (expression) => expression('version', '+', 1)
+ })
+ .where('id', '=', upload.documentId)
+ .execute()
+ const checkpointed = await recordCheckpoint(transaction, {
+ documentId: upload.documentId,
+ previousRevisionId: document.currentRevisionId,
+ revisionId,
+ userId,
+ now: new Date()
+ })
+ await transaction
+ .updateTable('upload')
+ .set({ status: 'committed', finalizationStartedAt: null })
+ .where('id', '=', uploadId)
+ .execute()
+ await quota.commitInTransaction(transaction, uploadId)
+ return checkpointed
+ }
+
async function createDownload(documentId: string): Promise<DocumentDownload> {
const row = await getDocumentSummaryRow(database, documentId)
if (!row?.currentRevisionId) throw new DocumentNotFoundError()
@@ -319,6 +416,7 @@ export function createDocumentService(
.returning('id')
.executeTakeFirst()
if (!claimed) throw new UploadInvalidError()
+ let checkpointed = false
try {
if (input.multipart) {
if (
@@ -334,78 +432,20 @@ export function createDocumentService(
})
}
const stored = await objects.head(upload.objectKey)
- if (
- !stored ||
- stored.checksum !== input.checksum ||
- stored.checksum !== upload.checksum ||
- stored.byteSize !== Number(upload.byteSize) ||
- stored.contentType !== upload.contentType
- ) {
- throw new UploadInvalidError()
- }
+ if (!stored || !matchesUpload(stored, upload)) throw new UploadInvalidError()
const revisionId = crypto.randomUUID()
const storageObjectId = crypto.randomUUID()
- await database.transaction().execute(async (transaction) => {
- const lockedUpload = await transaction
- .selectFrom('upload')
- .select('status')
- .where('id', '=', uploadId)
- .forUpdate()
- .executeTakeFirstOrThrow()
- if (lockedUpload.status === 'committed') return
- if (lockedUpload.status !== 'finalizing') throw new UploadInvalidError()
- const document = await transaction
- .selectFrom('document')
- .select(['currentRevisionId'])
- .where('id', '=', upload.documentId)
- .forUpdate()
- .executeTakeFirstOrThrow()
- if (document.currentRevisionId !== upload.baseRevisionId) {
- throw new DocumentConflictError()
- }
- await transaction
- .insertInto('storageObject')
- .values({
- id: storageObjectId,
- objectKey: upload.objectKey,
- checksum: stored.checksum,
- byteSize: stored.byteSize,
- contentType: stored.contentType
- })
- .execute()
- await transaction
- .insertInto('documentRevision')
- .values({
- id: revisionId,
- documentId: upload.documentId,
- parentRevisionId: upload.baseRevisionId,
- storageObjectId,
- createdBy: userId
- })
- .execute()
- await transaction
- .updateTable('document')
- .set({
- currentRevisionId: revisionId,
- version: (expression) => expression('version', '+', 1)
- })
- .where('id', '=', upload.documentId)
- .execute()
- await recordCheckpoint(transaction, {
- documentId: upload.documentId,
- previousRevisionId: document.currentRevisionId,
- revisionId,
+ checkpointed = await database.transaction().execute((transaction) =>
+ landRevision(transaction, {
userId,
- now: new Date()
+ uploadId,
+ upload,
+ stored,
+ revisionId,
+ storageObjectId
})
- await transaction
- .updateTable('upload')
- .set({ status: 'committed', finalizationStartedAt: null })
- .where('id', '=', uploadId)
- .execute()
- await quota.commitInTransaction(transaction, uploadId)
- })
+ )
} catch (error) {
await database
.updateTable('upload')
@@ -415,6 +455,7 @@ export function createDocumentService(
.execute()
throw error
}
+ if (checkpointed) announceVersions(options.onVersionsChanged, upload.documentId)
const document = await findDocument(database, userId, upload.documentId)
if (!document) throw new DocumentNotFoundError()
return document
diff --git a/packages/cloud/src/server/documents/versions/checkpoint.ts b/packages/cloud/src/server/documents/versions/checkpoint.ts
index 2add3234d..225e664cb 100644
--- a/packages/cloud/src/server/documents/versions/checkpoint.ts
+++ b/packages/cloud/src/server/documents/versions/checkpoint.ts
@@ -36,7 +36,7 @@ export async function keepRevision(
* Records the history's checkpoints as a save lands: the document's first save, and the state a
* save replaces once the newest version is half an hour old. Each stretch of editing, and how the
* document was left at the end of every session, stays in the history; the saves between them are
- * compacted later.
+ * compacted later. Whether the history gained a checkpoint.
*/
export async function recordCheckpoint(
transaction: Transaction<CloudDatabase>,
@@ -47,7 +47,7 @@ export async function recordCheckpoint(
userId: string
now: Date
}
-): Promise<void> {
+): Promise<boolean> {
if (!input.previousRevisionId) {
await keepRevision(transaction, {
documentId: input.documentId,
@@ -55,7 +55,7 @@ export async function recordCheckpoint(
createdBy: input.userId,
createdAt: input.now
})
- return
+ return true
}
const newest = await transaction
.selectFrom('documentVersion')
@@ -64,17 +64,35 @@ export async function recordCheckpoint(
.orderBy('createdAt', 'desc')
.limit(1)
.executeTakeFirst()
- if (newest && newest.createdAt.getTime() > input.now.getTime() - CHECKPOINT_INTERVAL_MS) return
+ if (newest && newest.createdAt.getTime() > input.now.getTime() - CHECKPOINT_INTERVAL_MS) {
+ return false
+ }
const previous = await transaction
.selectFrom('documentRevision')
.select(['createdBy', 'createdAt'])
.where('id', '=', input.previousRevisionId)
.executeTakeFirst()
- if (!previous) return
+ if (!previous) return false
await keepRevision(transaction, {
documentId: input.documentId,
revisionId: input.previousRevisionId,
createdBy: previous.createdBy,
createdAt: previous.createdAt
})
+ return true
+}
+
+/**
+ * Tells the document's live rooms that its history changed. The change stands whatever the hook
+ * does; an open list that misses it loads the history again when it is next opened.
+ */
+export function announceVersions(
+ onVersionsChanged: ((documentId: string) => void) | undefined,
+ documentId: string
+): void {
+ try {
+ onVersionsChanged?.(documentId)
+ } catch (error) {
+ console.error('[Cloud] Announcing a version history change failed:', error)
+ }
}
diff --git a/packages/cloud/src/server/documents/versions/service.ts b/packages/cloud/src/server/documents/versions/service.ts
index 542be76d6..630116993 100644
--- a/packages/cloud/src/server/documents/versions/service.ts
+++ b/packages/cloud/src/server/documents/versions/service.ts
@@ -17,7 +17,7 @@ import type { CloudPolicyContext } from '#cloud/server/policy/keys'
import type { CloudPolicy } from '#cloud/server/policy/policy'
import type { Kysely, Transaction } from 'kysely'
-import { keepRevision } from './checkpoint'
+import { announceVersions, keepRevision } from './checkpoint'
import { historyStart } from './history'
const DOWNLOAD_LIFETIME_MS = 5 * 60 * 1000
@@ -63,6 +63,8 @@ export function createDocumentVersionService(
deploymentMode?: CloudPolicyContext['deploymentMode']
/** Called once a restore lands, so the document's live room starts over. */
onRestored?: (documentId: string) => void
+ /** Called once the history changes: a version named, renamed, or turned back into an autosave. */
+ onVersionsChanged?: (documentId: string) => void
} = {}
) {
const deploymentMode = options.deploymentMode ?? 'self-hosted'
@@ -197,6 +199,7 @@ export function createDocumentVersionService(
.doUpdateSet({ kind: 'named', name: input.name, description })
)
.execute()
+ announceVersions(options.onVersionsChanged, documentId)
const row = await versions()
.where('documentVersion.revisionId', '=', revisionId)
.executeTakeFirstOrThrow()
@@ -221,6 +224,7 @@ export function createDocumentVersionService(
)
.where('id', '=', versionId)
.execute()
+ announceVersions(options.onVersionsChanged, documentId)
return versionOf(await findVersion(documentId, versionId, start), document.currentRevisionId)
},
diff --git a/packages/cloud/tests/integration/server/documents/versions.test.ts b/packages/cloud/tests/integration/server/documents/versions.test.ts
index 465dd9a61..b1c246fb7 100644
--- a/packages/cloud/tests/integration/server/documents/versions.test.ts
+++ b/packages/cloud/tests/integration/server/documents/versions.test.ts
@@ -62,6 +62,8 @@ async function testApp(options: { fullHistory?: boolean } = {}) {
)
: undefined
const restoredDocuments: string[] = []
+ /** Each time the server told the document's rooms its history changed. */
+ const announcements: string[] = []
const app = createCloudApp({
config,
database: runtime.database,
@@ -69,7 +71,8 @@ async function testApp(options: { fullHistory?: boolean } = {}) {
objects: objects.store,
policy,
resolveSession: async () => alice,
- onDocumentRestored: (documentId) => restoredDocuments.push(documentId)
+ onDocumentRestored: (documentId) => restoredDocuments.push(documentId),
+ onDocumentVersionsChanged: (documentId) => announcements.push(documentId)
})
const request = (path: string, init: { method?: string; json?: unknown } = {}) =>
app.request(`/api${path}`, {
@@ -149,6 +152,7 @@ async function testApp(options: { fullHistory?: boolean } = {}) {
return {
runtime,
restoredDocuments,
+ announcements,
objects,
policy,
request,
@@ -171,10 +175,13 @@ describe('Cloud version history', () => {
expect((await context.history()).versions.map((version) => version.revisionId)).toEqual([
first
])
+ // Only saves that add a checkpoint change the history open lists show.
+ expect(context.announcements).toEqual([context.documentId])
// Half an hour on, the next save keeps the state it replaces.
await context.age(31 * 60_000)
const latest = await context.save()
+ expect(context.announcements).toHaveLength(2)
const { versions } = await context.history()
expect(versions.map((version) => version.revisionId)).toEqual([ended, first])
expect(versions.every((version) => version.kind === 'checkpoint')).toBe(true)
@@ -215,6 +222,8 @@ describe('Cloud version history', () => {
)
expect(cleared.version).toMatchObject({ kind: 'checkpoint', name: null, description: null })
expect((await context.history()).versions).toHaveLength(2)
+ // The first save's checkpoint, the name, and taking it away.
+ expect(context.announcements).toHaveLength(3)
const empty = await context.request(`/documents/${context.documentId}/versions`, {
method: 'POST',
diff --git a/packages/cloud/tests/server/collaboration/relay/hub.test.ts b/packages/cloud/tests/server/collaboration/relay/hub.test.ts
index 3d6df888e..1e2ea7e07 100644
--- a/packages/cloud/tests/server/collaboration/relay/hub.test.ts
+++ b/packages/cloud/tests/server/collaboration/relay/hub.test.ts
@@ -189,6 +189,32 @@ describe('collaboration relay', () => {
expect(carol.messages(COLLAB_ACTIONS.agentPreview)).toHaveLength(1)
})
+ test('tells everyone in a document’s room, viewers too, that its history changed', async () => {
+ const { relay: hub } = relay()
+ const alice = await join(hub)
+ const bob = await join(hub, { permission: 'view' })
+ const elsewhere = await join(hub, { documentId: crypto.randomUUID() })
+ // A peer cannot say it; only the server can.
+ alice.send({
+ type: 'message',
+ namespace: COLLAB_ACTIONS.versions,
+ target: null,
+ payload: new Uint8Array()
+ })
+ hub.announceVersions(documentId)
+
+ const announced = {
+ type: 'message' as const,
+ namespace: COLLAB_ACTIONS.versions,
+ from: RELAY_SERVER_PEER,
+ payload: new Uint8Array()
+ }
+ await until(() => bob.messages(COLLAB_ACTIONS.versions).length > 0)
+ expect(alice.messages(COLLAB_ACTIONS.versions)).toEqual([announced])
+ expect(bob.messages(COLLAB_ACTIONS.versions)).toEqual([announced])
+ expect(elsewhere.messages(COLLAB_ACTIONS.versions)).toEqual([])
+ })
+
test('drops document writes from viewers', async () => {
const { relay: hub } = relay()
const editor = await join(hub)
diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.md
index 231033e25..152f01a76 100644
--- a/packages/docs/development/cloud.md
+++ b/packages/docs/development/cloud.md
@@ -68,7 +68,9 @@ keeps on its own, and versions someone named (`document_version`, one per revisi
- In the editor, File → Show version history makes the document read-only and lists its versions in
the right sidebar, as Figma does. Choosing a version shows it in a read-only editor of its own in
place of the document, whose room keeps syncing underneath; Save to version history (⌥⌘S) names
- the document once the saver's edits are uploaded.
+ the document once the saver's edits are uploaded. When a version is named, renamed, or turned
+ back into an autosave, or a save adds a checkpoint, the server sends `versions` to the
+ document's rooms and every open history loads it again; peers cannot send it.
- A document's address is `/cloud/documents/:id?server=…`, with `&version=…` for a version; the
editor keeps the address bar on the active tab's document and the version it shows, and a
version's Copy link builds the address on the server's advertised editor URL. The address carries
diff --git a/src/app/cloud/rooms/live.ts b/src/app/cloud/rooms/live.ts
index 44b52f027..39c7439c9 100644
--- a/src/app/cloud/rooms/live.ts
+++ b/src/app/cloud/rooms/live.ts
@@ -21,6 +21,7 @@ import { allTabs, getTabForStore, getTabsSnapshot, reloadStorageDocumentInTab }
import { isCloudBinding } from '../documents/status'
import { cloudConnections } from '../sessions/connection'
import { cloudShareTarget } from '../sharing/document'
+import { versionListRevision } from '../versions/history'
/** Each Cloud tab's permission in its room, for the status beside the name. */
export const cloudRoomPermissions = shallowRef<ReadonlyMap<EditorStore, 'edit' | 'view'>>(new Map())
@@ -152,6 +153,10 @@ export function openCloudDocumentRoom(
// A viewer sees the room's edits and makes none, as Figma's view-only files do.
store.setReadOnly(!canEdit)
if (!canSave) store.state.autosaveEnabled = false
+ // Someone named, renamed, or saved a checkpoint anywhere: an open history loads it again.
+ const stopVersions = session.onVersionsChanged(() => {
+ versionListRevision.value++
+ })
const stopSynced = session.onSynced((peerId) => {
if (peerId !== RELAY_SERVER_PEER) return
stopSynced()
@@ -166,6 +171,7 @@ export function openCloudDocumentRoom(
return {
session,
stop() {
+ stopVersions()
stopSynced()
stopSaver()
setPermission(store, null)
@@ -262,6 +268,8 @@ export async function restartCloudRoom(store: EditorStore): Promise<void> {
if (session) leaveRoom(session)
// The tab shows what it downloaded: another tab of the document may still write the local copy.
await reloadStorageDocumentInTab(store, await adoptStoredVersion(binding.documentId))
+ // The restore is in the history now; the old room closed before it could say so.
+ versionListRevision.value++
await startCloudRoom(store)
} finally {
restarting.delete(store)
diff --git a/src/app/cloud/versions/history.ts b/src/app/cloud/versions/history.ts
index f988f3482..a339c633e 100644
--- a/src/app/cloud/versions/history.ts
+++ b/src/app/cloud/versions/history.ts
@@ -33,7 +33,7 @@ const histories = shallowRef<ReadonlyMap<EditorStore, VersionHistory>>(new Map()
export type VersionDialog = { store: EditorStore; version: DocumentVersion | null }
export const versionDialog = shallowRef<VersionDialog | null>(null)
-/** Bumped when this window changes the history, so an open list loads it again. */
+/** Bumped when the history changes, here or anywhere the server says, so open lists load it again. */
export const versionListRevision = shallowRef(0)
/** Each tab's preview download in flight, keyed by its document. */
const previewLoads = new Map<EditorStore, AbortController>()
diff --git a/src/app/collab/room/connection.ts b/src/app/collab/room/connection.ts
index ce97c1bf6..ea866dbc2 100644
--- a/src/app/collab/room/connection.ts
+++ b/src/app/collab/room/connection.ts
@@ -6,7 +6,8 @@ import {
COLLAB_ACTIONS,
encodeSyncReply,
decodeRoomUpdate,
- MAX_COLLAB_MESSAGE_BYTES
+ MAX_COLLAB_MESSAGE_BYTES,
+ RELAY_SERVER_PEER
} from '@open-pencil/cloud/contract'
import { joinCollabRoom, type JoinCollabRoom } from '@/app/collab/transport'
@@ -35,6 +36,8 @@ export type CollabRoomConnection = {
peerForClient: (clientId: number) => string | undefined
/** Follow peers answering this tab's state with theirs; returns the unsubscribe. */
onSynced: (handler: (peerId: string) => void) => () => void
+ /** Follow the server saying the document's version history changed; returns the unsubscribe. */
+ onVersionsChanged: (handler: () => void) => () => void
}
type AwarenessEntry = { clientId: number; removed: boolean }
@@ -93,9 +96,11 @@ export function connectCollabRoom({
const [sendSyncStep1, getSyncStep1] = room.makeAction(COLLAB_ACTIONS.syncStep1)
const [sendSyncReply, getSyncReply] = room.makeAction(COLLAB_ACTIONS.syncReply)
const agentPreview = room.makeAction(COLLAB_ACTIONS.agentPreview)
+ const [, getVersions] = room.makeAction(COLLAB_ACTIONS.versions)
// A transport keeps one leave handler, so the connection shares it with its users.
const leaveHandlers = new Set<(peerId: string) => void>()
const syncedHandlers = new Set<(peerId: string) => void>()
+ const versionsHandlers = new Set<() => void>()
const awarenessClientsByPeer = new Map<string, Set<number>>()
@@ -114,6 +119,11 @@ export function connectCollabRoom({
awarenessProtocol.applyAwarenessUpdate(awareness, data, 'remote')
})
+ getVersions((_data, peerId) => {
+ if (peerId !== RELAY_SERVER_PEER) return
+ for (const handler of versionsHandlers) handler()
+ })
+
getSyncStep1((stateVector, peerId) => {
sendSyncReply(encodeSyncReply(ydoc, stateVector), peerId)
})
@@ -168,6 +178,10 @@ export function connectCollabRoom({
syncedHandlers.add(handler)
return () => syncedHandlers.delete(handler)
},
+ onVersionsChanged(handler) {
+ versionsHandlers.add(handler)
+ return () => versionsHandlers.delete(handler)
+ },
peerForClient(clientId) {
for (const [peerId, clients] of awarenessClientsByPeer) {
if (clients.has(clientId)) return peerId
diff --git a/src/app/collab/session.ts b/src/app/collab/session.ts
index 0ac7daa4e..a60bd7977 100644
--- a/src/app/collab/session.ts
+++ b/src/app/collab/session.ts
@@ -51,6 +51,8 @@ export interface RoomSession {
roomHasDocument(): boolean
/** Follow peers answering this tab's state with theirs; returns the unsubscribe. */
onSynced(handler: (peerId: string) => void): () => void
+ /** Follow the server saying the document's version history changed; returns the unsubscribe. */
+ onVersionsChanged(handler: () => void): () => void
/** The awareness states of everyone in the room, this tab included. */
presence(): ReadonlyMap<number, Record<string, unknown>>
/** This tab's awareness client. */
@@ -251,6 +253,7 @@ export function openRoomSession({
},
roomHasDocument: () => readRoot(meta) !== undefined,
onSynced: (handler) => connection.onSynced(handler),
+ onVersionsChanged: (handler) => connection.onVersionsChanged(handler),
presence: () => awareness.getStates() as Map<number, Record<string, unknown>>,
clientId: awareness.clientID,
dispose() {
diff --git a/tests/helpers/collab/relay-server.ts b/tests/helpers/collab/relay-server.ts
index 567cc17c0..c8f3be9b6 100644
--- a/tests/helpers/collab/relay-server.ts
+++ b/tests/helpers/collab/relay-server.ts
@@ -39,6 +39,8 @@ export async function startTestRelay() {
return {
url,
states,
+ /** Tells a document's rooms its version history changed, as the server does. */
+ announceVersions: (documentId: string) => relay.announceVersions(documentId),
/** Joins a document's room with the given permission, as a guest or a signed-in user. */
join(
documentId: string,
diff --git a/tests/integration/collab/cloud-relay.test.ts b/tests/integration/collab/cloud-relay.test.ts
index e5684e832..4dffa6e19 100644
--- a/tests/integration/collab/cloud-relay.test.ts
+++ b/tests/integration/collab/cloud-relay.test.ts
@@ -10,6 +10,7 @@ import { exportFigFile, initCodec, parseFigFile } from '@open-pencil/core'
import { SceneGraph } from '@open-pencil/scene-graph'
import { openCloudDocumentRoom } from '@/app/cloud/rooms/live'
+import { versionListRevision } from '@/app/cloud/versions/history'
import { connectCollabRoom } from '@/app/collab/room/connection'
import { createEditorStore } from '@/app/editor/session'
@@ -125,6 +126,31 @@ describe('collaboration through the Cloud relay', () => {
})
})
+describe('Cloud document rooms, version history', () => {
+ test('a tab reloads its history when the server says it changed', async () => {
+ const relay = await startRelay()
+ const documentId = crypto.randomUUID()
+ const [grace] = await openedTwice()
+ const room = openCloudDocumentRoom(grace, {
+ roomId: `cloud:${documentId}:0`,
+ transport: relay.join(documentId, 'Grace', 'view', 'user'),
+ permission: 'view'
+ })
+ cleanups.push(() => {
+ room.stop()
+ room.session.dispose()
+ })
+ let joined = false
+ room.session.onSynced(() => {
+ joined = true
+ })
+ await until(() => joined)
+ const before = versionListRevision.value
+ relay.announceVersions(documentId)
+ await until(() => versionListRevision.value > before)
+ })
+})
+
/** Tabs that each opened the same stored file, which gives each its own root. */
async function openedTwice() {
await initCodec()