AI-native design editor. Open-source Figma alternative.
fix(cloud): split large relay messages and show when a tab stops editing live (#1338)
Danila Poyarkov6efda131469c
diff --git a/packages/cloud/AGENTS.md b/packages/cloud/AGENTS.mdindex 5dcfafce5..c33c54aec 100644--- a/packages/cloud/AGENTS.md+++ b/packages/cloud/AGENTS.md@@ -22,6 +22,7 @@ Optional, self-hostable backend; the design is in `packages/docs/development/clo- The relay hub in `src/server/collaboration/relay/` is runtime-neutral: runtimes hand it sockets through `RelaySocket` and own listening (`src/runtime/node/relay.ts`). It joins every room as the `server` peer, so it must keep answering `sync-step1` and saving the room document.- Viewers may send only the channels in `VIEWER_ACTIONS`; every other channel from them is dropped, and presence is stamped from the ticket by `stampAwareness` (`tests/server/collaboration/relay/hub.test.ts`).- Decoders must consume exactly the frame's bytes and copy payloads out, since socket buffers are pooled (`src/contract/relay.ts`, `tests/contract/relay.test.ts`).+- Send frames through `relayServerMessages` and `relayClientMessages`, which split anything past `RELAY_FRAGMENT_BYTES` into fragments, and read sockets through the matching assemblers; never send an encoded frame whole (`tests/server/collaboration/relay/hub.test.ts`).## Portaldiff --git a/packages/cloud/deploy/openpencil-cloud.example.toml b/packages/cloud/deploy/openpencil-cloud.example.tomlindex a2cf82cf5..33e42a5ef 100644--- a/packages/cloud/deploy/openpencil-cloud.example.toml+++ b/packages/cloud/deploy/openpencil-cloud.example.toml@@ -138,5 +138,6 @@ enabled = false[technical_limits]maximum_upload_bytes = 1073741824+# One WebSocket message on the relay, at least 262160. Larger edits arrive as 256 KiB fragments.maximum_collaboration_message_bytes = 1048576maximum_connections_per_room = 1000diff --git a/packages/cloud/src/contract/relay.ts b/packages/cloud/src/contract/relay.tsindex 44727c6e8..ea3ca1d8e 100644--- a/packages/cloud/src/contract/relay.ts+++ b/packages/cloud/src/contract/relay.ts@@ -98,10 +98,30 @@ export const RELAY_CLOSE = {const CLIENT_AUTH = 0const CLIENT_MESSAGE = 1+const CLIENT_FRAGMENT = 2const SERVER_WELCOME = 0const SERVER_JOIN = 1const SERVER_LEAVE = 2const SERVER_MESSAGE = 3+const SERVER_FRAGMENT = 4++/**+ * The most one WebSocket message carries. A frame past it travels as fragments of this size that+ * the receiver joins again, so a large paste or a room's first sync fits under any host's message+ * cap, such as the 32 MiB of Cloudflare Workers, and the relay can turn away a viewer's or an+ * unadmitted peer's large frame before holding it whole.+ */+export const RELAY_FRAGMENT_BYTES = 256 * 1024++/** The smallest per-message limit a relay may set: one fragment and its few bytes of framing. */+export const RELAY_MINIMUM_MESSAGE_BYTES = RELAY_FRAGMENT_BYTES + 16++/**+ * What the relay adds to a frame it forwards: the frame type, the sender's peer ID, and lengths.+ * A client reads frames this much past the relay's own limit, so a forwarded edit at that limit+ * still arrives.+ */+export const RELAY_FORWARDING_BYTES = 64 * 1024/** Frames a client sends: its ticket first, again to refresh it, then room messages. */export type RelayClientFrame =@@ -157,6 +177,122 @@ export function encodeRelayServerFrame(frame: RelayServerFrame): Uint8Array<Arra})}+/** The frame as it goes over the socket: itself, or fragments of it when it is large. */+function fragments(tag: number, frame: Uint8Array<ArrayBuffer>): Uint8Array<ArrayBuffer>[] {+ if (frame.byteLength <= RELAY_FRAGMENT_BYTES) return [frame]+ const parts: Uint8Array<ArrayBuffer>[] = []+ for (let offset = 0; offset < frame.byteLength; offset += RELAY_FRAGMENT_BYTES) {+ const end = Math.min(offset + RELAY_FRAGMENT_BYTES, frame.byteLength)+ parts.push(+ toSendable((encoder) => {+ encoding.writeVarUint(encoder, tag)+ encoding.writeVarUint(encoder, end < frame.byteLength ? 1 : 0)+ encoding.writeVarUint8Array(encoder, frame.subarray(offset, end))+ })+ )+ }+ return parts+}++/** A client frame as the socket messages that carry it, in order. */+export function relayClientMessages(frame: RelayClientFrame): Uint8Array<ArrayBuffer>[] {+ return fragments(CLIENT_FRAGMENT, encodeRelayClientFrame(frame))+}++/** A server frame as the socket messages that carry it, in order. */+export function relayServerMessages(frame: RelayServerFrame): Uint8Array<ArrayBuffer>[] {+ return fragments(SERVER_FRAGMENT, encodeRelayServerFrame(frame))+}++/** What one socket message gave: a whole frame, part of one, or a reason to close. */+export type RelayAssembly =+ | { type: 'frame'; data: Uint8Array }+ | { type: 'partial' }+ | { type: 'too-large' }+ | { type: 'malformed' }++/**+ * Joins one socket's fragments into the frames they carry. A socket sends a frame's fragments in+ * a row, so a whole frame arriving between them is malformed. `limit` caps the joined frame and is+ * read for every message, so it can follow what the sender may do.+ */+function createAssembler(tag: number, limit: () => number) {+ let parts: Uint8Array[] = []+ let size = 0+ /** Set while the rest of a refused frame arrives, so its tail never reads as a frame of its own. */+ let discarding = false+ const reset = () => {+ parts = []+ size = 0+ }+ return {+ push(data: Uint8Array): RelayAssembly {+ let decoder: decoding.Decoder+ let type: number+ try {+ decoder = decoding.createDecoder(data)+ type = decoding.readVarUint(decoder)+ } catch {+ reset()+ return { type: 'malformed' }+ }+ if (type !== tag) {+ if (parts.length > 0) {+ reset()+ return { type: 'malformed' }+ }+ return { type: 'frame', data }+ }+ let more: number+ let chunk: Uint8Array+ try {+ more = decoding.readVarUint(decoder)+ chunk = decoding.readVarUint8Array(decoder)+ } catch {+ // A fragment that cannot be read is taken as unfinished: only a sound last one ends it.+ reset()+ discarding = true+ return { type: 'malformed' }+ }+ if (decoder.pos !== data.byteLength || more > 1) {+ reset()+ discarding = more !== 0+ return { type: 'malformed' }+ }+ if (discarding) {+ discarding = more === 1+ return { type: 'partial' }+ }+ size += chunk.byteLength+ if (size > limit()) {+ reset()+ discarding = more === 1+ return { type: 'too-large' }+ }+ parts.push(chunk.slice())+ if (more === 1) return { type: 'partial' }+ const joined = new Uint8Array(size)+ let at = 0+ for (const part of parts) {+ joined.set(part, at)+ at += part.byteLength+ }+ reset()+ return { type: 'frame', data: joined }+ }+ }+}++/** Joins the fragments a client sends; the relay holds one per socket. */+export function createRelayClientAssembler(limit: () => number) {+ return createAssembler(CLIENT_FRAGMENT, limit)+}++/** Joins the fragments the relay sends; a client holds one per socket. */+export function createRelayServerAssembler(limit: () => number) {+ return createAssembler(SERVER_FRAGMENT, limit)+}+/*** lib0 reads byte arrays as views of the underlying buffer, which can run past the end of the* frame's own view, as with pooled socket buffers. A frame is valid only when decoding consumeddiff --git a/packages/cloud/src/server/collaboration/relay/hub.ts b/packages/cloud/src/server/collaboration/relay/hub.tsindex e41588cac..2c535297f 100644--- a/packages/cloud/src/server/collaboration/relay/hub.ts+++ b/packages/cloud/src/server/collaboration/relay/hub.ts@@ -1,12 +1,13 @@import {COLLAB_ACTIONS,+ createRelayClientAssembler,encodeSyncReply,decodeRelayClientFrame,decodeRoomUpdate,- encodeRelayServerFrame,MAX_COLLAB_MESSAGE_BYTES,RELAY_CLOSE,RELAY_SERVER_PEER,+ relayServerMessages,type RelayServerFrame} from '#cloud/contract'import * as Y from 'yjs'@@ -30,6 +31,10 @@ export type RelayConnection = {export type CollaborationRelayOptions = {authSecret: stringstore: CollaborationStateStore+ /**+ * The most one socket message may carry. An editor's larger frames arrive as fragments joined+ * up to `MAX_COLLAB_MESSAGE_BYTES`; anyone else's frame must fit in one message.+ */maximumMessageBytes: numbermaximumConnectionsPerRoom: number/** The participant limit policy sets for a document, or null for none. */@@ -87,7 +92,12 @@ export function createCollaborationRelay(options: CollaborationRelayOptions) {const report = options.onError ?? ((message, error) => console.error(`[Cloud] ${message}`, error))function send(socket: RelaySocket, frame: RelayServerFrame) {- socket.send(encodeRelayServerFrame(frame))+ for (const message of relayServerMessages(frame)) socket.send(message)+ }++ function sendAll(sockets: Iterable<RelaySocket>, frame: RelayServerFrame) {+ const messages = relayServerMessages(frame)+ for (const socket of sockets) for (const message of messages) socket.send(message)}async function openRoom(authorization: RelayAuthorization): Promise<Room> {@@ -170,12 +180,14 @@ export function createCollaborationRelay(options: CollaborationRelayOptions) {target: string | null,payload: Uint8Array) {- const frame = encodeRelayServerFrame({ type: 'message', namespace, from: from.id, payload })- if (target) {- room.peers.get(target)?.socket.send(frame)- return- }- for (const peer of room.peers.values()) if (peer !== from) peer.socket.send(frame)+ const frame: RelayServerFrame = { type: 'message', namespace, from: from.id, payload }+ const recipients = target+ ? [room.peers.get(target)]+ : [...room.peers.values()].filter((peer) => peer !== from)+ sendAll(+ recipients.flatMap((peer) => (peer ? [peer.socket] : [])),+ frame+ )}function handleServerMessage(room: Room, peer: Peer, namespace: string, payload: Uint8Array) {@@ -334,6 +346,13 @@ export function createCollaborationRelay(options: CollaborationRelayOptions) {const isClosed = () => state.closedconst queued: Uint8Array[] = []let queuedBytes = 0+ // Only an editor's writes can be large: a viewer's frames, and a peer's before it is+ // admitted, fit in one message, so nobody else can make the relay hold more.+ const assembler = createRelayClientAssembler(() =>+ peer?.authorization.permission === 'edit'+ ? MAX_COLLAB_MESSAGE_BYTES+ : options.maximumMessageBytes+ )const authTimer = setTimeout(() => socket.close(RELAY_CLOSE.unauthorized, 'Expected a collaboration ticket'),authTimeoutMs@@ -375,7 +394,13 @@ export function createCollaborationRelay(options: CollaborationRelayOptions) {socket.close(RELAY_CLOSE.messageTooLarge, 'Collaboration message is too large')return}- const frame = decodeRelayClientFrame(data)+ const assembled = assembler.push(data)+ if (assembled.type === 'partial') return+ if (assembled.type === 'too-large') {+ socket.close(RELAY_CLOSE.messageTooLarge, 'Collaboration message is too large')+ return+ }+ const frame = assembled.type === 'frame' ? decodeRelayClientFrame(assembled.data) : nullif (!frame) {socket.close(RELAY_CLOSE.protocol, 'Malformed collaboration frame')return@@ -456,16 +481,18 @@ export function createCollaborationRelay(options: CollaborationRelayOptions) {/** Tells everyone in a document's rooms that its version history changed. */announceVersions(documentId: string) {- const frame = encodeRelayServerFrame({+ const frame: RelayServerFrame = {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)}+ sendAll(+ [...rooms.values()]+ .filter((room) => room.identity.documentId === documentId)+ .flatMap((room) => [...room.peers.values()].map((peer) => peer.socket)),+ frame+ )},/** Saves every open room and closes its sockets, as the runtime shuts down. */diff --git a/packages/cloud/src/server/config/schema.ts b/packages/cloud/src/server/config/schema.tsindex ab87a9e43..cf852a10f 100644--- a/packages/cloud/src/server/config/schema.ts+++ b/packages/cloud/src/server/config/schema.ts@@ -1,4 +1,8 @@-import { CLOUD_PROTOCOL_MAX_UPLOAD_BYTES, cloudEditorVersionSchema } from '#cloud/contract'+import {+ CLOUD_PROTOCOL_MAX_UPLOAD_BYTES,+ cloudEditorVersionSchema,+ RELAY_MINIMUM_MESSAGE_BYTES+} from '#cloud/contract'import { staticEntitlementsSchema } from '#cloud/server/policy/static'import * as v from 'valibot'@@ -40,7 +44,7 @@ const rawCloudServerConfigSchema = v.object({CLOUD_PROTOCOL_MAX_UPLOAD_BYTES),maximumCollaborationMessageBytes: v.optional(- v.pipe(v.number(), v.integer(), v.minValue(1024)),+ v.pipe(v.number(), v.integer(), v.minValue(RELAY_MINIMUM_MESSAGE_BYTES)),CLOUD_DEFAULT_MAX_COLLABORATION_MESSAGE_BYTES),maximumConnectionsPerRoom: v.optional(diff --git a/packages/cloud/tests/contract/relay.test.ts b/packages/cloud/tests/contract/relay.test.tsindex 9c7d7f960..ce9966222 100644--- a/packages/cloud/tests/contract/relay.test.ts+++ b/packages/cloud/tests/contract/relay.test.ts@@ -1,10 +1,16 @@import { describe, expect, test } from 'bun:test'import {+ createRelayClientAssembler,+ createRelayServerAssembler,decodeRelayClientFrame,decodeRelayServerFrame,encodeRelayClientFrame,encodeRelayServerFrame,+ RELAY_FRAGMENT_BYTES,+ RELAY_MINIMUM_MESSAGE_BYTES,+ relayClientMessages,+ relayServerMessages,type RelayClientFrame,type RelayServerFrame} from '#cloud/contract'@@ -44,4 +50,93 @@ describe('relay frames', () => {expect(decodeRelayClientFrame(new Uint8Array([7]))).toBeNull()expect(decodeRelayServerFrame(new Uint8Array([7]))).toBeNull()})++ test('split large frames into messages that join back into the frame', () => {+ const payload = crypto.getRandomValues(new Uint8Array(RELAY_FRAGMENT_BYTES * 2 + 100))+ const client: RelayClientFrame = {+ type: 'message',+ namespace: 'yjs-update',+ target: null,+ payload+ }+ const server: RelayServerFrame = {+ type: 'message',+ namespace: 'yjs-update',+ from: 'a',+ payload+ }+ for (const [messages, assembler, decode, frame] of [+ [+ relayClientMessages(client),+ createRelayClientAssembler(() => Infinity),+ decodeRelayClientFrame,+ client+ ],+ [+ relayServerMessages(server),+ createRelayServerAssembler(() => Infinity),+ decodeRelayServerFrame,+ server+ ]+ ] as const) {+ expect(messages).toHaveLength(3)+ for (const message of messages)+ expect(message.byteLength).toBeLessThanOrEqual(RELAY_MINIMUM_MESSAGE_BYTES)+ const results = messages.map((message) => assembler.push(message))+ expect(results.slice(0, -1).map((result) => result.type)).toEqual(['partial', 'partial'])+ const last = results.at(-1)+ expect(last?.type === 'frame' ? decode(last.data) : null).toEqual(frame)+ }+ })++ test('send small frames whole and refuse joined frames past the limit', () => {+ const small: RelayClientFrame = { type: 'auth', token: 'ticket' }+ expect(relayClientMessages(small)).toEqual([encodeRelayClientFrame(small)])+ const assembler = createRelayClientAssembler(() => RELAY_FRAGMENT_BYTES)+ const [first, second] = relayClientMessages({+ type: 'message',+ namespace: 'yjs-update',+ target: null,+ payload: new Uint8Array(RELAY_FRAGMENT_BYTES * 2)+ })+ if (!first || !second) throw new Error('Expected two fragments')+ expect(assembler.push(first).type).toBe('partial')+ expect(assembler.push(second).type).toBe('too-large')+ // The assembler starts over after refusing.+ expect(assembler.push(encodeRelayClientFrame(small)).type).toBe('frame')+ })++ test('discard the rest of a refused frame instead of reading its tail as a frame', () => {+ const assembler = createRelayClientAssembler(() => RELAY_FRAGMENT_BYTES)+ const messages = relayClientMessages({+ type: 'message',+ namespace: 'yjs-update',+ target: null,+ payload: new Uint8Array(RELAY_FRAGMENT_BYTES * 4)+ })+ const results = messages.map((message) => assembler.push(message).type)+ expect(results).toEqual(['partial', 'too-large', 'partial', 'partial', 'partial'])+ const small: RelayClientFrame = { type: 'auth', token: 'ticket' }+ expect(assembler.push(encodeRelayClientFrame(small)).type).toBe('frame')+ })++ test('discard what follows a fragment whose flag cannot be trusted', () => {+ const assembler = createRelayClientAssembler(() => Infinity)+ const messages = relayClientMessages({+ type: 'message',+ namespace: 'yjs-update',+ target: null,+ payload: new Uint8Array(RELAY_FRAGMENT_BYTES * 3)+ })+ const [first, ...rest] = messages+ if (!first) throw new Error('Expected a fragment')+ // The first fragment with its flag rewritten to 2, which is neither "more" nor "last".+ const garbled = Uint8Array.from(first)+ garbled[1] = 2+ expect(assembler.push(garbled).type).toBe('malformed')+ expect(rest.map((message) => assembler.push(message).type)).toEqual(rest.map(() => 'partial'))+ expect(assembler.push(encodeRelayClientFrame({ type: 'auth', token: 'ticket' })).type).toBe(+ 'frame'+ )+ })})diff --git a/packages/cloud/tests/helpers/relay.ts b/packages/cloud/tests/helpers/relay.tsindex 05868384d..c48e0c385 100644--- a/packages/cloud/tests/helpers/relay.ts+++ b/packages/cloud/tests/helpers/relay.ts@@ -1,18 +1,26 @@import {+ createRelayServerAssembler,decodeRelayServerFrame,+ decodeRoomUpdate,encodeRelayClientFrame,+ MAX_COLLAB_MESSAGE_BYTES,+ relayClientMessages,type CollaborationPrincipal,type DocumentPermission,type RelayClientFrame,type RelayServerFrame} from '#cloud/contract'-import type {- CollaborationRoomIdentity,- CollaborationStateStore,- RelayConnection,- RelaySocket+import {+ createCollaborationRelay,+ type CollaborationRelay,+ type CollaborationRelayOptions,+ type CollaborationRoomIdentity,+ type CollaborationStateStore,+ type RelayConnection,+ type RelaySocket} from '#cloud/server'import { SignJWT } from 'jose'+import * as Y from 'yjs'export const relaySecret = 'relay-test-secret-at-least-32-characters'@@ -55,7 +63,12 @@ export type TestRelayClient = {frames: RelayServerFrame[]closed: { code: number; reason: string } | nullconnection: RelayConnection+ /** Sends the frame in one message, as a peer that never splits frames would. */send(frame: RelayClientFrame): void+ /** Sends the frame as the editor does: in fragments once it is large. */+ sendFragmented(frame: RelayClientFrame): void+ /** How many socket messages the relay sent. */+ received: number/** The peer ID from the relay's welcome. */peerId(): string | undefinedmessages(namespace: string): Extract<RelayServerFrame, { type: 'message' }>[]@@ -65,9 +78,13 @@ export function connectTestClient(connect: (socket: RelaySocket) => RelayConnectconst client: Omit<TestRelayClient, 'connection'> = {frames: [],closed: null,+ received: 0,send(frame) {connection.receive(encodeRelayClientFrame(frame))},+ sendFragmented(frame) {+ for (const message of relayClientMessages(frame)) connection.receive(message)+ },peerId() {const welcome = client.frames.find((frame) => frame.type === 'welcome')return welcome?.type === 'welcome' ? welcome.peerId : undefined@@ -78,9 +95,12 @@ export function connectTestClient(connect: (socket: RelaySocket) => RelayConnect)}}+ const assembler = createRelayServerAssembler(() => MAX_COLLAB_MESSAGE_BYTES)const connection = connect({send(data) {- const frame = decodeRelayServerFrame(data)+ client.received+++ const assembled = assembler.push(data)+ const frame = assembled.type === 'frame' ? decodeRelayServerFrame(assembled.data) : nullif (frame) client.frames.push(frame)},close(code, reason) {@@ -116,3 +136,53 @@ export function memoryStateStore() {}return { store, states }}++/** A relay over an in-memory store that saves at once, with whatever a test changes. */+export function startTestRelay(options: Partial<CollaborationRelayOptions> = {}) {+ const state = memoryStateStore()+ const instance = createCollaborationRelay({+ authSecret: relaySecret,+ store: state.store,+ maximumMessageBytes: 1_048_576,+ maximumConnectionsPerRoom: 100,+ persistDelayMs: 0,+ onError: () => undefined,+ ...options+ })+ return { relay: instance, ...state }+}++/** A peer in the room of `documentId`, an editor unless the ticket says otherwise. */+export async function joinTestRelay(+ hub: CollaborationRelay,+ documentId: string,+ ticket: Partial<RelayTicketOptions> = {}+) {+ const client = connectTestClient((socket) => hub.connect(socket))+ client.send({+ type: 'auth',+ token: await relayTicket({+ documentId,+ permission: 'edit',+ principal: user(crypto.randomUUID()),+ ...ticket+ })+ })+ await until(() => client.peerId() !== undefined || client.closed !== null)+ return client+}++/** A V2 update that writes `text` into a document's `t` text. */+export function textUpdate(text: string) {+ const document = new Y.Doc()+ document.getText('t').insert(0, text)+ return Y.encodeStateAsUpdateV2(document)+}++/** The text a sync reply carries, which travels as a compressed V2 update. */+export function textOfSyncReply(reply: Uint8Array) {+ const document = new Y.Doc()+ const update = decodeRoomUpdate(reply, { limit: MAX_COLLAB_MESSAGE_BYTES, compressed: true })+ if (update) Y.applyUpdateV2(document, update)+ return document.getText('t').toString()+}diff --git a/packages/cloud/tests/server/collaboration/relay/fragments.test.ts b/packages/cloud/tests/server/collaboration/relay/fragments.test.tsnew file mode 100644index 000000000..73fd6213e--- /dev/null+++ b/packages/cloud/tests/server/collaboration/relay/fragments.test.ts@@ -0,0 +1,97 @@+import { describe, expect, test } from 'bun:test'++import {+ joinTestRelay,+ startTestRelay,+ textOfSyncReply,+ textUpdate,+ until+} from '#cloud-tests/helpers/relay'+import {+ COLLAB_ACTIONS,+ RELAY_CLOSE,+ RELAY_FRAGMENT_BYTES,+ RELAY_SERVER_PEER,+ relayClientMessages+} from '#cloud/contract'+import * as Y from 'yjs'++const documentId = crypto.randomUUID()++/** Text that does not compress, so frames carrying it stay as large as it is. */+function noise(length: number) {+ const bytes = crypto.getRandomValues(new Uint8Array(length / 2))+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')+}++/** The socket messages an editor sends for an update of `size` bytes. */+function relayFragments(size: number) {+ return relayClientMessages({+ type: 'message',+ namespace: COLLAB_ACTIONS.yjsUpdate,+ target: null,+ payload: new Uint8Array(size)+ })+}++describe('collaboration relay fragments', () => {+ test("joins an editor's large edit from fragments and passes it on in fragments", async () => {+ const { relay: hub, states } = startTestRelay()+ const alice = await joinTestRelay(hub, documentId)+ const bob = await joinTestRelay(hub, documentId)+ const text = noise(2 * 1024 * 1024)+ alice.sendFragmented({+ type: 'message',+ namespace: COLLAB_ACTIONS.yjsUpdate,+ target: null,+ payload: textUpdate(text)+ })+ await until(() => bob.messages(COLLAB_ACTIONS.yjsUpdate).length > 0)+ expect(alice.closed).toBeNull()+ const [update] = bob.messages(COLLAB_ACTIONS.yjsUpdate)+ if (!update) throw new Error('Expected the forwarded update')+ const document = new Y.Doc()+ Y.applyUpdateV2(document, update.payload)+ expect(document.getText('t').toString()).toBe(text)+ expect(bob.received).toBeGreaterThan(bob.frames.length)++ // A newcomer gets the whole room, compressed and still larger than one fragment.+ const carol = await joinTestRelay(hub, documentId)+ carol.sendFragmented({+ type: 'message',+ namespace: COLLAB_ACTIONS.syncStep1,+ target: RELAY_SERVER_PEER,+ payload: Y.encodeStateVector(new Y.Doc())+ })+ await until(() => carol.messages(COLLAB_ACTIONS.syncReply).length > 0)+ const [reply] = carol.messages(COLLAB_ACTIONS.syncReply)+ if (!reply) throw new Error('Expected the sync reply')+ expect(reply.payload.byteLength).toBeGreaterThan(RELAY_FRAGMENT_BYTES)+ expect(textOfSyncReply(reply.payload)).toBe(text)+ await until(() => states.size > 0)+ })++ test('holds a viewer, and a frame between fragments, to one message', async () => {+ const { relay: hub } = startTestRelay({ maximumMessageBytes: 300_000 })+ const viewer = await joinTestRelay(hub, documentId, { permission: 'view' })+ viewer.sendFragmented({+ type: 'message',+ namespace: COLLAB_ACTIONS.awareness,+ target: null,+ payload: new Uint8Array(400_000)+ })+ expect(viewer.closed?.code).toBe(RELAY_CLOSE.messageTooLarge)++ const editor = await joinTestRelay(hub, documentId)+ const [first] = relayFragments(400_000)+ if (!first) throw new Error('Expected a fragment')+ editor.connection.receive(first)+ editor.send({+ type: 'message',+ namespace: COLLAB_ACTIONS.awareness,+ target: null,+ payload: new Uint8Array(1)+ })+ expect(editor.closed?.code).toBe(RELAY_CLOSE.protocol)+ })+})diff --git a/packages/cloud/tests/server/collaboration/relay/hub.test.ts b/packages/cloud/tests/server/collaboration/relay/hub.test.tsindex 1e2ea7e07..849cce9f3 100644--- a/packages/cloud/tests/server/collaboration/relay/hub.test.ts+++ b/packages/cloud/tests/server/collaboration/relay/hub.test.ts@@ -3,64 +3,29 @@ import { describe, expect, test } from 'bun:test'import {connectTestClient,guest,+ joinTestRelay,memoryStateStore,relaySecret,relayTicket,+ startTestRelay,+ textOfSyncReply,+ textUpdate,until,user,type RelayTicketOptions} from '#cloud-tests/helpers/relay'-import {- COLLAB_ACTIONS,- decodeRoomUpdate,- encodeSyncReply,- MAX_COLLAB_MESSAGE_BYTES,- RELAY_CLOSE,- RELAY_SERVER_PEER-} from '#cloud/contract'-import { createCollaborationRelay, type CollaborationRelayOptions } from '#cloud/server'+import { COLLAB_ACTIONS, encodeSyncReply, RELAY_CLOSE, RELAY_SERVER_PEER } from '#cloud/contract'+import { createCollaborationRelay, type CollaborationRelay } from '#cloud/server'import * as awarenessProtocol from 'y-protocols/awareness'import * as Y from 'yjs'const documentId = crypto.randomUUID()-function relay(options: Partial<CollaborationRelayOptions> = {}) {- const state = memoryStateStore()- const instance = createCollaborationRelay({- authSecret: relaySecret,- store: state.store,- maximumMessageBytes: 1_048_576,- maximumConnectionsPerRoom: 100,- persistDelayMs: 0,- onError: () => undefined,- ...options- })- return { relay: instance, ...state }-}--async function join(- hub: ReturnType<typeof relay>['relay'],- ticket: Partial<RelayTicketOptions> = {}-) {- const client = connectTestClient((socket) => hub.connect(socket))- client.send({- type: 'auth',- token: await relayTicket({- documentId,- permission: 'edit',- principal: user(crypto.randomUUID()),- ...ticket- })- })- await until(() => client.peerId() !== undefined || client.closed !== null)- return client-}--function edit(text: string) {- const document = new Y.Doc()- document.getText('t').insert(0, text)- return Y.encodeStateAsUpdateV2(document)-}+const relay = startTestRelay+const join = (hub: CollaborationRelay, ticket: Partial<RelayTicketOptions> = {}) =>+ joinTestRelay(hub, documentId, ticket)+const edit = textUpdate+const textOf = textOfSyncReply/** What an editor holding `text` answers a sync request from an empty peer with. */function syncReply(text: string) {@@ -69,14 +34,6 @@ function syncReply(text: string) {return encodeSyncReply(document, Y.encodeStateVector(new Y.Doc()))}-/** The text a sync reply carries, which travels as a compressed V2 update. */-function textOf(reply: Uint8Array) {- const document = new Y.Doc()- const update = decodeRoomUpdate(reply, { limit: MAX_COLLAB_MESSAGE_BYTES, compressed: true })- if (update) Y.applyUpdateV2(document, update)- return document.getText('t').toString()-}-describe('collaboration relay', () => {test('welcomes peers with everyone in the room and announces arrivals and departures', async () => {const { relay: hub } = relay()diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.mdindex b8b6c6f83..6ac710dc8 100644--- a/packages/docs/development/cloud.md+++ b/packages/docs/development/cloud.md@@ -149,6 +149,15 @@ PostgreSQL by document and collaboration epoch, so a newcomer gets the documentelse is online. Tickets are short-lived signed JWTs; the client presents a fresh one before thecurrent one expires, and the relay closes a socket whose ticket lapsed or changed identity.+A socket message carries at most 256 KiB of a frame, under the deployment's per-message limit,+which may not be lower. A larger frame, such as a big paste, the first editor's copy of a large+document, or a newcomer's sync reply, travels as fragments in a row that the receiver joins again.+The relay joins an editor's fragments up to 256 MiB and holds viewers and peers not yet admitted to+one message, so only an editor can make it buffer more. A peer the relay turns away for good, for+a ticket, a full room, or a frame past those limits, leaves the room: the document's status says it+is not editing live and offers to rejoin, a viewer stays read-only, and an editor saves on its own,+since a tab that was not the room's saver had its edits counted as saved by the room.+The relay enforces what the ticket allows: a viewer's document updates and sync replies never leaveit, and presence updates are rewritten so others see the ticket's name and a `cloud` field with theverified identity and permission. A peer cannot claim presence clients another peer owns. Voice isdiff --git a/packages/vue/src/i18n/locales/de/cloud/editor.json b/packages/vue/src/i18n/locales/de/cloud/editor.jsonindex f63747600..173311edb 100644--- a/packages/vue/src/i18n/locales/de/cloud/editor.json+++ b/packages/vue/src/i18n/locales/de/cloud/editor.json@@ -134,6 +134,9 @@"conflictYouOnThisDevice": "Du, auf diesem Gerät","conflictResolveFailed": "Der Konflikt konnte nicht gelöst werden. Deine Änderungen sind weiterhin auf diesem Gerät.","statusViewOnlyDetail": "Du kannst dich umsehen und anderen folgen; deine Änderungen erreichen niemanden.",+ "statusNotLive": "Nicht live",+ "statusNotLiveDetail": "Der Server hat die Live-Sitzung dieses Tabs beendet, daher gehen Änderungen nicht mehr zwischen ihm und anderen hin und her. Tritt erneut bei, um die neueste Version zu sehen.",+ "statusRejoin": "Erneut beitreten","statusSavedTo": "In {workspace} gespeichert","statusSavedAgo": "Gespeichert {time}","statusUpToDate": "Aktuell",diff --git a/packages/vue/src/i18n/locales/es/cloud/editor.json b/packages/vue/src/i18n/locales/es/cloud/editor.jsonindex 7c917d9db..6c465fafa 100644--- a/packages/vue/src/i18n/locales/es/cloud/editor.json+++ b/packages/vue/src/i18n/locales/es/cloud/editor.json@@ -134,6 +134,9 @@"conflictYouOnThisDevice": "Tú, en este dispositivo","conflictResolveFailed": "No se pudo resolver el conflicto. Tus cambios siguen en este dispositivo.","statusViewOnlyDetail": "Puedes explorar y seguir a otros; tus cambios no llegarán a nadie.",+ "statusNotLive": "Sin edición en vivo",+ "statusNotLiveDetail": "El servidor terminó la sesión en vivo de esta pestaña, así que los cambios ya no pasan entre ella y los demás. Vuelve a unirte para ver la versión más reciente.",+ "statusRejoin": "Volver a unirse","statusSavedTo": "Guardado en {workspace}","statusSavedAgo": "Guardado {time}","statusUpToDate": "Actualizado",diff --git a/packages/vue/src/i18n/locales/fr/cloud/editor.json b/packages/vue/src/i18n/locales/fr/cloud/editor.jsonindex 9128f8e62..6314ebc5e 100644--- a/packages/vue/src/i18n/locales/fr/cloud/editor.json+++ b/packages/vue/src/i18n/locales/fr/cloud/editor.json@@ -134,6 +134,9 @@"conflictYouOnThisDevice": "Vous, sur cet appareil","conflictResolveFailed": "Impossible de résoudre le conflit. Vos modifications sont toujours sur cet appareil.","statusViewOnlyDetail": "Vous pouvez explorer et suivre les autres ; vos modifications n’atteindront personne.",+ "statusNotLive": "Plus en direct",+ "statusNotLiveDetail": "Le serveur a mis fin à la session en direct de cet onglet : les modifications ne passent plus entre lui et les autres. Rejoignez-la pour voir la dernière version.",+ "statusRejoin": "Rejoindre","statusSavedTo": "Enregistré dans {workspace}","statusSavedAgo": "Enregistré {time}","statusUpToDate": "À jour",diff --git a/packages/vue/src/i18n/locales/it/cloud/editor.json b/packages/vue/src/i18n/locales/it/cloud/editor.jsonindex 6c97ba86b..467266107 100644--- a/packages/vue/src/i18n/locales/it/cloud/editor.json+++ b/packages/vue/src/i18n/locales/it/cloud/editor.json@@ -134,6 +134,9 @@"conflictYouOnThisDevice": "Tu, su questo dispositivo","conflictResolveFailed": "Impossibile risolvere il conflitto. Le tue modifiche sono ancora su questo dispositivo.","statusViewOnlyDetail": "Puoi esplorare e seguire gli altri; le tue modifiche non arriveranno a nessuno.",+ "statusNotLive": "Non in diretta",+ "statusNotLiveDetail": "Il server ha chiuso la sessione in diretta di questa scheda, quindi le modifiche non passano più tra essa e gli altri. Rientra per vedere la versione più recente.",+ "statusRejoin": "Rientra","statusSavedTo": "Salvato in {workspace}","statusSavedAgo": "Salvato {time}","statusUpToDate": "Aggiornato",diff --git a/packages/vue/src/i18n/locales/ja/cloud/editor.json b/packages/vue/src/i18n/locales/ja/cloud/editor.jsonindex 464f2a7e9..7be0e2d9d 100644--- a/packages/vue/src/i18n/locales/ja/cloud/editor.json+++ b/packages/vue/src/i18n/locales/ja/cloud/editor.json@@ -133,6 +133,9 @@"conflictYouOnThisDevice": "このデバイスのあなた","conflictResolveFailed": "競合を解決できませんでした。変更はこのデバイスに残っています。","statusViewOnlyDetail": "閲覧や他の人のフォローはできますが、変更は誰にも届きません。",+ "statusNotLive": "ライブ編集が停止中",+ "statusNotLiveDetail": "サーバーがこのタブのライブセッションを終了したため、他の人との間で編集が共有されなくなりました。再参加すると最新のバージョンが表示されます。",+ "statusRejoin": "再参加","statusSavedTo": "{workspace} に保存済み","statusSavedAgo": "{time}に保存","statusUpToDate": "最新の状態",diff --git a/packages/vue/src/i18n/locales/pl/cloud/editor.json b/packages/vue/src/i18n/locales/pl/cloud/editor.jsonindex 878141a19..65a037192 100644--- a/packages/vue/src/i18n/locales/pl/cloud/editor.json+++ b/packages/vue/src/i18n/locales/pl/cloud/editor.json@@ -135,6 +135,9 @@"conflictYouOnThisDevice": "Ty, na tym urządzeniu","conflictResolveFailed": "Nie udało się rozwiązać konfliktu. Twoje zmiany nadal są na tym urządzeniu.","statusViewOnlyDetail": "Możesz przeglądać i obserwować innych; Twoje zmiany do nikogo nie dotrą.",+ "statusNotLive": "Edycja na żywo wyłączona",+ "statusNotLiveDetail": "Serwer zakończył sesję na żywo tej karty, więc zmiany nie przechodzą już między nią a innymi. Dołącz ponownie, aby zobaczyć najnowszą wersję.",+ "statusRejoin": "Dołącz ponownie","statusSavedTo": "Zapisano w {workspace}","statusSavedAgo": "Zapisano {time}","statusUpToDate": "Aktualne",diff --git a/packages/vue/src/i18n/locales/ru/cloud/editor.json b/packages/vue/src/i18n/locales/ru/cloud/editor.jsonindex 9debbda31..a70c44944 100644--- a/packages/vue/src/i18n/locales/ru/cloud/editor.json+++ b/packages/vue/src/i18n/locales/ru/cloud/editor.json@@ -135,6 +135,9 @@"conflictYouOnThisDevice": "Вы, на этом устройстве","conflictResolveFailed": "Не удалось разрешить конфликт. Ваши изменения по-прежнему на этом устройстве.","statusViewOnlyDetail": "Можно осматриваться и следить за другими, но ваши изменения никто не увидит.",+ "statusNotLive": "Не в реальном времени",+ "statusNotLiveDetail": "Сервер завершил совместную сессию этой вкладки, поэтому правки больше не передаются между ней и другими. Подключитесь снова, чтобы увидеть последнюю версию.",+ "statusRejoin": "Подключиться снова","statusSavedTo": "Сохранено в {workspace}","statusSavedAgo": "Сохранено {time}","statusUpToDate": "Актуальная версия",diff --git a/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json b/packages/vue/src/i18n/locales/zh-cn/cloud/editor.jsonindex 8b0fd1f8c..86d2df94b 100644--- a/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json+++ b/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json@@ -133,6 +133,9 @@"conflictYouOnThisDevice": "你,在此设备上","conflictResolveFailed": "无法解决冲突。你的更改仍保存在此设备上。","statusViewOnlyDetail": "你可以浏览并跟随他人,但你的更改不会传给任何人。",+ "statusNotLive": "未在实时编辑",+ "statusNotLiveDetail": "服务器已结束此标签页的实时会话,编辑不再与他人同步。重新加入以查看最新版本。",+ "statusRejoin": "重新加入","statusSavedTo": "已保存到 {workspace}","statusSavedAgo": "保存于 {time}","statusUpToDate": "已是最新",diff --git a/packages/vue/src/i18n/messages/cloud/editor.ts b/packages/vue/src/i18n/messages/cloud/editor.tsindex 400b0e3d1..0c1d025e6 100644--- a/packages/vue/src/i18n/messages/cloud/editor.ts+++ b/packages/vue/src/i18n/messages/cloud/editor.ts@@ -182,6 +182,10 @@ export const cloudMessageDefaults = {// StatusstatusViewOnlyDetail: 'You can look around and follow others; your changes won’t reach anyone.',+ statusNotLive: 'Not editing live',+ statusNotLiveDetail:+ 'The server ended this tab’s live session, so edits no longer pass between it and others. Rejoin to see the latest version.',+ statusRejoin: 'Rejoin',statusSavedTo: params('Saved to {workspace}'),statusSavedAgo: params('Saved {time}'),statusUpToDate: 'Up to date',diff --git a/src/app/cloud/rooms/live.ts b/src/app/cloud/rooms/live.tsindex 40b3de832..8d5a3f6b5 100644--- a/src/app/cloud/rooms/live.ts+++ b/src/app/cloud/rooms/live.ts@@ -28,6 +28,8 @@ import { onceOnServer, shareRoomUploads, uploadStoredDocument } from './upload'/** Each Cloud tab's permission in its room, for the status beside the name. */export const cloudRoomPermissions = shallowRef<ReadonlyMap<EditorStore, 'edit' | 'view'>>(new Map())+/** Tabs the relay turned away for good, for the status beside the name; they do not rejoin on their own. */+export const cloudRoomsRefused = shallowRef<ReadonlySet<EditorStore>>(new Set())const starting = new WeakSet<EditorStore>()function setPermission(store: EditorStore, permission: 'edit' | 'view' | null) {@@ -241,7 +243,7 @@ export function cloudRelayTransport(url: string,first: CollaborationTicket,next: () => Promise<CollaborationTicket>,- onRestored?: () => void+ events: { onRestored?: () => void; onRefused?: () => void } = {}): JoinCollabRoom {let unused: CollaborationTicket | null = firstreturn createCloudRelayJoin({@@ -253,7 +255,8 @@ export function cloudRelayTransport(if (ticket.roomId !== first.roomId) return nullreturn { token: ticket.token, expiresAt: ticket.expiresAt }},- onRestored+ onRestored: events.onRestored,+ onRefused: events.onRefused})}@@ -267,6 +270,59 @@ const liveRooms = new Map<EditorStore, { room: LiveRoom; stopWatching: () => voi/** The server and account each tab joined its room as, so a change of account joins again. */const joinedAs = new WeakMap<EditorStore, { serverId: string; accountId: string | null }>()+/** Each refused tab's watch for its closing, which forgets the refusal with the tab. */+const refusalWatches = new Map<EditorStore, () => void>()++function setRefused(store: EditorStore, refused: boolean) {+ refusalWatches.get(store)?.()+ refusalWatches.delete(store)+ const next = new Set(cloudRoomsRefused.value)+ if (refused) {+ next.add(store)+ refusalWatches.set(+ store,+ watch(allTabs, () => {+ if (!getTabForStore(store)) setRefused(store, false)+ })+ )+ } else next.delete(store)+ cloudRoomsRefused.value = next+}++/**+ * The relay turned the tab away for good, so it leaves the room and nothing waits on it. A viewer+ * stays read-only. An editor that can save takes its saving back: a tab that was not the room's+ * saver had its edits counted as saved by the room, so it uploads the document as it stands, and+ * a newer save from someone else comes back as a conflict to resolve rather than being lost.+ */+export function leaveRefusedRoom(+ store: EditorStore,+ room: { permission: 'edit' | 'view'; canSave: boolean }+): void {+ setRefused(store, true)+ leaveCloudRoom(store)+ if (room.permission === 'view') {+ store.setReadOnly(true)+ return+ }+ if (!room.canSave || !store.getStorageBinding()) return+ store.state.autosaveEnabled = true+ void store.saveFigFile().catch(() => undefined)+}++/**+ * Joins a refused tab's room again, showing the document as the server holds it. A rejoin that+ * fails, or ends without a room, leaves the tab refused, so it can try again.+ */+export async function rejoinRefusedRoom(store: EditorStore): Promise<void> {+ setRefused(store, false)+ try {+ await restartCloudRoom(store)+ } finally {+ if (!roomForStore(store) && getTabForStore(store)) setRefused(store, true)+ }+}+/** Leaves the room's saving and status behind once its tab closes. */export function stopWithTab(store: EditorStore, room: LiveRoom): void {liveRooms.get(store)?.stopWatching()@@ -288,7 +344,15 @@ export function stopWithTab(store: EditorStore, room: LiveRoom): void {*/export async function startCloudRoom(store: EditorStore): Promise<void> {const binding = store.getStorageBinding()- if (!binding || !isCloudBinding(binding) || roomForStore(store) || starting.has(store)) return+ if (+ !binding ||+ !isCloudBinding(binding) ||+ roomForStore(store) ||+ starting.has(store) ||+ cloudRoomsRefused.value.has(store)+ ) {+ return+ }const target = cloudShareTarget(binding)if (!target?.discovery.capabilities.collaboration) returnstarting.add(store)@@ -317,7 +381,10 @@ export async function startCloudRoom(store: EditorStore): Promise<void> {? accountRoomIdentity(() => cloudConnection(target.server.id).account ?? account): undefined,roomId: first.roomId,- transport: cloudRelayTransport(first.serverURL, first, nextTicket, restart),+ transport: cloudRelayTransport(first.serverURL, first, nextTicket, {+ onRestored: restart,+ onRefused: () => leaveRefusedRoom(store, { permission: first.permission, canSave: true })+ }),permission: first.permission,roomIsCurrent: async () => (await nextTicket()).roomId === first.roomId,onRestored: restartdiff --git a/src/app/cloud/sharing/link.ts b/src/app/cloud/sharing/link.tsindex 8066a2c05..fc838c0f5 100644--- a/src/app/cloud/sharing/link.ts+++ b/src/app/cloud/sharing/link.ts@@ -10,7 +10,12 @@ import { storageFetch } from '@/app/integrations/storage/s3/fetch'import { getTabForStore, openFileInNewTab } from '@/app/tabs'import { IS_BROWSER } from '@/constants'-import { cloudRelayTransport, openCloudDocumentRoom, stopWithTab } from '../rooms/live'+import {+ cloudRelayTransport,+ leaveRefusedRoom,+ openCloudDocumentRoom,+ stopWithTab+} from '../rooms/live'import { normalizeCloudServerURL } from '../servers/address'import { cloudFetch, discoverCloudServer } from '../sessions/connection'@@ -48,8 +53,12 @@ export async function openCloudShareLink(link: CloudShareLink): Promise<void> {if (first.provider !== 'relay' || !first.serverURL || !getTabForStore(store)) returnconst room = openCloudDocumentRoom(store, {roomId: first.roomId,- transport: cloudRelayTransport(first.serverURL, first, () =>- client.getSharedCollaborationTicket(link.shareId, input)+ transport: cloudRelayTransport(+ first.serverURL,+ first,+ () => client.getSharedCollaborationTicket(link.shareId, input),+ // A guest has no account to save with, so leaving is all a refusal changes.+ { onRefused: () => leaveRefusedRoom(store, { permission: first.permission, canSave: false }) }),permission: first.permission,guest: truediff --git a/src/app/collab/transport/cloud.ts b/src/app/collab/transport/cloud.tsindex 250878705..35fa36e38 100644--- a/src/app/collab/transport/cloud.ts+++ b/src/app/collab/transport/cloud.ts@@ -1,7 +1,10 @@import {+ createRelayServerAssembler,decodeRelayServerFrame,- encodeRelayClientFrame,+ MAX_COLLAB_MESSAGE_BYTES,RELAY_CLOSE,+ RELAY_FORWARDING_BYTES,+ relayClientMessages,type RelayClientFrame} from '@open-pencil/cloud/contract'@@ -28,6 +31,11 @@ export type CloudRelayOptions = {ticket: (roomId: string) => Promise<CloudRelayTicket | null>/** The document was restored to a version and its room started over; this one is done. */onRestored?: () => void+ /**+ * The relay turned this peer away for good, and reconnecting cannot help: its ticket or the+ * room refused it, or it sent what the relay will not take.+ */+ onRefused?: () => voidcreateSocket?: (url: string) => WebSocket/** How long to wait before reconnection attempt `attempt`, counting from zero. */reconnectDelayMs?: (attempt: number) => number@@ -77,7 +85,10 @@ function joinCloudRelayRoom(roomId: string, options: CloudRelayOptions): CollabRlet reconnectTimer: ReturnType<typeof setTimeout> | undefinedfunction send(frame: RelayClientFrame) {- if (socket?.readyState === WebSocket.OPEN) socket.send(encodeRelayClientFrame(frame))+ const current = socket+ if (current?.readyState !== WebSocket.OPEN) return+ // A large frame goes as fragments in a row, which the relay joins before reading it.+ for (const message of relayClientMessages(frame)) current.send(message)}async function refresh() {@@ -122,8 +133,8 @@ function joinCloudRelayRoom(roomId: string, options: CloudRelayOptions): CollabRjoinHandler?.(peerId)}- function handleFrame(data: ArrayBuffer) {- const frame = decodeRelayServerFrame(new Uint8Array(data))+ function handleFrame(data: Uint8Array) {+ const frame = decodeRelayServerFrame(data)if (!frame) returnswitch (frame.type) {case 'welcome':@@ -186,8 +197,19 @@ function joinCloudRelayRoom(roomId: string, options: CloudRelayOptions): CollabRsend({ type: 'auth', token: issued.token })scheduleRefresh(issued)})+ const assembler = createRelayServerAssembler(+ () => MAX_COLLAB_MESSAGE_BYTES + RELAY_FORWARDING_BYTES+ )next.addEventListener('message', (event: MessageEvent<ArrayBuffer>) => {- if (socket === next) handleFrame(event.data)+ if (socket !== next) return+ const assembled = assembler.push(new Uint8Array(event.data))+ if (assembled.type === 'frame') handleFrame(assembled.data)+ else if (assembled.type !== 'partial') {+ // A frame this peer could not read leaves it behind the room, so it connects again and+ // syncs what it missed.+ report('The collaboration relay sent a frame this peer cannot read:', assembled.type)+ next.close(1000, 'Unreadable collaboration frame')+ }})next.addEventListener('close', (event) => {if (socket !== next) return@@ -200,6 +222,7 @@ function joinCloudRelayRoom(roomId: string, options: CloudRelayOptions): CollabR}if (FINAL_CLOSE_CODES.has(event.code)) {report('The collaboration relay refused this peer:', event.reason || event.code)+ options.onRefused?.()return}reconnect()diff --git a/src/components/cloud/status/CloudDocumentStatus.stories.ts b/src/components/cloud/status/CloudDocumentStatus.stories.tsindex ab11f2f8e..782752d07 100644--- a/src/components/cloud/status/CloudDocumentStatus.stories.ts+++ b/src/components/cloud/status/CloudDocumentStatus.stories.ts@@ -7,12 +7,24 @@ import IconButton from '@/components/ui/button/IconButton.vue'import CloudDocumentStatus from './CloudDocumentStatus.vue'-type Args = { state: CloudSyncState; viewOnly: boolean; savedAgo: string | null }+type Args = {+ state: CloudSyncState+ viewOnly: boolean+ savedAgo: string | null+ notLive: boolean+ canRejoin: boolean+}const meta = {title: 'App/Cloud/Document Status',tags: ['autodocs'],- args: { state: 'synced', viewOnly: false, savedAgo: 'just now' },+ args: {+ state: 'synced',+ viewOnly: false,+ savedAgo: 'just now',+ notLive: false,+ canRejoin: false+ },render: (args) => ({components: { CloudDocumentStatus, IconButton, IconSettings },setup: () => ({ args }),@@ -21,7 +33,7 @@ const meta = {<div class="flex w-64 items-center gap-1 border-b border-border bg-panel px-2 py-2"><span class="flex size-6 items-center justify-center rounded bg-accent text-[11px] font-bold text-on-accent">P</span><span class="min-w-0 flex-1 truncate px-1 text-xs text-surface">Homepage redesign</span>- <CloudDocumentStatus :state="args.state" :view-only="args.viewOnly" :saved-ago="args.savedAgo" workspace="Design team" host="cloud.openpencil.dev" />+ <CloudDocumentStatus :state="args.state" :view-only="args.viewOnly" :not-live="args.notLive" :can-rejoin="args.canRejoin" :saved-ago="args.savedAgo" workspace="Design team" host="cloud.openpencil.dev" /><IconButton label="Settings"><IconSettings class="size-3.5" /></IconButton></div></div>`@@ -42,3 +54,4 @@ export const Offline: Story = { args: { state: 'offline' } }export const NeedsAChoice: Story = { args: { state: 'conflict' } }export const CouldNotSave: Story = { args: { state: 'error' } }export const ViewOnly: Story = { args: { viewOnly: true } }+export const NotLive: Story = { args: { notLive: true, canRejoin: true } }diff --git a/src/components/cloud/status/CloudDocumentStatus.vue b/src/components/cloud/status/CloudDocumentStatus.vueindex df313981d..21786c47f 100644--- a/src/components/cloud/status/CloudDocumentStatus.vue+++ b/src/components/cloud/status/CloudDocumentStatus.vue@@ -19,13 +19,19 @@ const {workspace,host,savedAgo = null,- viewOnly = false+ viewOnly = false,+ notLive = false,+ canRejoin = false} = defineProps<{state: CloudSyncStateworkspace: stringhost: stringsavedAgo?: string | nullviewOnly?: boolean+ /** The server ended this tab's live session; a conflict or failed save still shows first. */+ notLive?: boolean+ /** Whether rejoining loses nothing, which holds once the tab's changes are saved. */+ canRejoin?: boolean}>()const emit = defineEmits<{@@ -33,22 +39,30 @@ const emit = defineEmits<{openWorkspace: []resolve: []retry: []+ rejoin: []}>()const ui = cloudStatus()const popoverOpen = ref(false)/** Every action leads somewhere else, so the popover closes first. */-function act(action: 'share' | 'openWorkspace' | 'resolve' | 'retry') {+function act(action: 'share' | 'openWorkspace' | 'resolve' | 'retry' | 'rejoin') {popoverOpen.value = falseif (action === 'share') emit('share')else if (action === 'openWorkspace') emit('openWorkspace')else if (action === 'resolve') emit('resolve')+ else if (action === 'rejoin') emit('rejoin')else emit('retry')}+const showsNotLive = computed(() => notLive && state !== 'conflict' && state !== 'error')+const syncAttribute = computed(() => {+ if (showsNotLive.value) return 'not-live'+ return viewOnly ? 'view' : state+})const popover = usePopoverUI({ content: 'w-72 p-3' })const t = useCloudMessages()const summary = computed(() => {const m = t.value+ if (showsNotLive.value) return { label: m.statusNotLive, detail: m.statusNotLiveDetail }if (viewOnly) return { label: m.viewOnly, detail: m.statusViewOnlyDetail }const summaries: Record<CloudSyncState, { label: string; detail: string }> = {synced: {@@ -70,10 +84,11 @@ const summary = computed(() => {<Tip :label="summary.label" as-child><PopoverTrigger:class="ui.trigger()"- :data-state-sync="viewOnly ? 'view' : state"+ :data-state-sync="syncAttribute":aria-label="summary.label">- <icon-lucide-eye v-if="viewOnly" class="size-3.5" />+ <icon-lucide-unplug v-if="showsNotLive" class="size-3.5" />+ <icon-lucide-eye v-else-if="viewOnly" class="size-3.5" /><icon-lucide-cloud-check v-else-if="state === 'synced'" class="size-3.5" /><icon-lucide-loader-circlev-else-if="state === 'uploading'"@@ -83,7 +98,8 @@ const summary = computed(() => {<icon-lucide-cloud-upload v-else-if="state === 'pending'" class="size-3.5" /><icon-lucide-git-compare-arrows v-else-if="state === 'conflict'" class="size-3.5" /><icon-lucide-circle-alert v-else class="size-3.5" />- <span v-if="viewOnly || state === 'conflict'" :class="ui.triggerLabel()">+ <span v-if="showsNotLive" :class="ui.triggerLabel()">{{ t.statusNotLive }}</span>+ <span v-else-if="viewOnly || state === 'conflict'" :class="ui.triggerLabel()">{{ viewOnly ? t.viewOnly : t.statusResolve }}</span></PopoverTrigger>@@ -91,8 +107,9 @@ const summary = computed(() => {<PopoverPortal><PopoverContent side="bottom" align="start" :side-offset="6" :class="popover.content"><div :class="ui.header()">- <span :class="ui.headerIcon()" :data-state-sync="viewOnly ? 'view' : state">- <icon-lucide-eye v-if="viewOnly" class="size-4" />+ <span :class="ui.headerIcon()" :data-state-sync="syncAttribute">+ <icon-lucide-unplug v-if="showsNotLive" class="size-4" />+ <icon-lucide-eye v-else-if="viewOnly" class="size-4" /><icon-lucide-git-compare-arrows v-else-if="state === 'conflict'" class="size-4" /><icon-lucide-circle-alert v-else-if="state === 'error'" class="size-4" /><icon-lucide-cloud-off v-else-if="state === 'offline'" class="size-4" />@@ -123,6 +140,15 @@ const summary = computed(() => {>{{ t.statusChooseVersion }}</AppButton>+ <AppButton+ v-else-if="showsNotLive && canRejoin"+ size="sm"+ color="primary"+ variant="solid"+ @click="act('rejoin')"+ >+ {{ t.statusRejoin }}+ </AppButton><AppButtonv-else-if="state === 'error' && !viewOnly"size="sm"diff --git a/src/components/cloud/status/CloudDocumentStatusHost.vue b/src/components/cloud/status/CloudDocumentStatusHost.vueindex 996af0acb..11402c937 100644--- a/src/components/cloud/status/CloudDocumentStatusHost.vue+++ b/src/components/cloud/status/CloudDocumentStatusHost.vue@@ -8,7 +8,7 @@ import { useCloudMessages } from '@open-pencil/vue'import { openCloudConnect } from '@/app/cloud/connect/flow'import { resolveCloudConflict, type CloudConflictChoice } from '@/app/cloud/documents/conflict'import { useCloudDocumentStatus } from '@/app/cloud/documents/status'-import { cloudRoomPermissions } from '@/app/cloud/rooms/live'+import { cloudRoomPermissions, cloudRoomsRefused, rejoinRefusedRoom } from '@/app/cloud/rooms/live'import { showCloudServerOnHome } from '@/app/cloud/servers/store'import { cloudConnection } from '@/app/cloud/sessions/connection'import { cloudShareOpen } from '@/app/cloud/sharing/dialog'@@ -33,6 +33,9 @@ const { state, location, meta } = useCloudDocumentStatus(() => store.getStorageBconst ago = (iso: string | null | undefined) => (iso ? dates.relative(iso) : '')const savedAgo = computed(() => ago(meta.value?.lastSyncedAt) || null)const viewOnly = computed(() => cloudRoomPermissions.value.get(store) === 'view')+const notLive = computed(() => cloudRoomsRefused.value.has(store))+/** Rejoining shows the document as the server holds it, so it waits for this tab's edits. */+const canRejoin = computed(() => state.value === 'synced' && !store.hasUnsavedChanges())/*** Saving and saved need nothing from the person, and the tab's dot already shows unsaved edits,* so the status shows only for what does: being offline, a failed save, a conflict, view only.@@ -40,6 +43,7 @@ const viewOnly = computed(() => cloudRoomPermissions.value.get(store) === 'view'const needsAttention = computed(() =>viewOnly.value ||+ notLive.value ||state.value === 'offline' ||state.value === 'error' ||state.value === 'conflict'@@ -104,7 +108,10 @@ function retry() {:host="location.host":saved-ago="savedAgo":view-only="viewOnly"+ :not-live="notLive"+ :can-rejoin="canRejoin"@resolve="openConflict"+ @rejoin="rejoinRefusedRoom(store)"@share="cloudShareOpen = true"@retry="retry"@open-workspace="openWorkspace"diff --git a/src/theme/cloud/status.ts b/src/theme/cloud/status.tsindex cee5fb40c..37d8394d8 100644--- a/src/theme/cloud/status.ts+++ b/src/theme/cloud/status.ts@@ -3,11 +3,11 @@ import { tv } from 'tailwind-variants'export const cloudStatus = tv({slots: {trigger:- 'flex h-6 shrink-0 items-center gap-1 rounded px-1 text-muted outline-none hover:bg-hover hover:text-surface focus-visible:ring-2 focus-visible:ring-accent/50 data-[state=open]:bg-hover data-[state-sync=conflict]:bg-warning-bg data-[state-sync=conflict]:text-warning data-[state-sync=error]:text-error data-[state-sync=view]:bg-panel-field data-[state-sync=view]:text-surface',+ 'flex h-6 shrink-0 items-center gap-1 rounded px-1 text-muted outline-none hover:bg-hover hover:text-surface focus-visible:ring-2 focus-visible:ring-accent/50 data-[state=open]:bg-hover data-[state-sync=conflict]:bg-warning-bg data-[state-sync=conflict]:text-warning data-[state-sync=error]:text-error data-[state-sync=view]:bg-panel-field data-[state-sync=view]:text-surface data-[state-sync=not-live]:bg-warning-bg data-[state-sync=not-live]:text-warning',triggerLabel: 'text-[11px] font-medium',header: 'flex items-start gap-2.5',headerIcon:- 'flex size-8 shrink-0 items-center justify-center rounded-md bg-panel-field text-muted data-[state-sync=synced]:text-primary data-[state-sync=conflict]:bg-warning-bg data-[state-sync=conflict]:text-warning data-[state-sync=error]:bg-error-bg data-[state-sync=error]:text-error',+ 'flex size-8 shrink-0 items-center justify-center rounded-md bg-panel-field text-muted data-[state-sync=synced]:text-primary data-[state-sync=conflict]:bg-warning-bg data-[state-sync=conflict]:text-warning data-[state-sync=error]:bg-error-bg data-[state-sync=error]:text-error data-[state-sync=not-live]:bg-warning-bg data-[state-sync=not-live]:text-warning',title: 'text-xs font-medium text-surface',detail: 'mt-0.5 text-[11px] leading-relaxed text-muted',facts: 'mt-3 flex flex-col gap-1 rounded-md bg-panel-field px-2.5 py-2 text-[11px]',diff --git a/tests/app/cloud/rooms/refused.test.ts b/tests/app/cloud/rooms/refused.test.tsnew file mode 100644index 000000000..f33600491--- /dev/null+++ b/tests/app/cloud/rooms/refused.test.ts@@ -0,0 +1,147 @@+import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test'++import { nextTick } from 'vue'++import {+ cloudRoomsRefused,+ leaveRefusedRoom,+ rejoinRefusedRoom,+ startCloudRoom+} from '@/app/cloud/rooms/live'+import { addCloudServer, cloudServers, removeCloudServer } from '@/app/cloud/servers/store'+import { refreshCloudConnection } from '@/app/cloud/sessions/connection'+import { CLOUD_STORAGE_PROVIDER_ID } from '@/app/cloud/sessions/token'+import type { EditorStore } from '@/app/editor/session'+import { closeTab, createTab } from '@/app/tabs'++import { cloudDiscoveryFixture } from '#tests/helpers/cloud/discovery'+import { asDouble } from '#tests/helpers/doubles'+import { fetchStub } from '#tests/helpers/fetch'++/** A Cloud tab's store, recording what leaving its room did to it. */+function tab(options: { stored?: boolean } = {}) {+ const calls = { saves: 0, readOnly: [] as boolean[] }+ const store = asDouble<EditorStore>({+ state: { autosaveEnabled: false },+ getStorageBinding: () =>+ options.stored === false ? null : { providerId: 'cloud', documentId: 'document' },+ setReadOnly: (readOnly: boolean) => calls.readOnly.push(readOnly),+ saveFigFile: async () => {+ calls.saves+++ }+ })+ return { store, calls }+}++describe('a tab the relay refused', () => {+ test('shows it, and an editor saves on its own what the room no longer carries', () => {+ const { store, calls } = tab()+ leaveRefusedRoom(store, { permission: 'edit', canSave: true })+ expect(cloudRoomsRefused.value.has(store)).toBe(true)+ expect(store.state.autosaveEnabled).toBe(true)+ expect(calls.saves).toBe(1)+ })++ test('keeps a viewer read-only, and a guest without an account unsaved', () => {+ const viewer = tab()+ leaveRefusedRoom(viewer.store, { permission: 'view', canSave: false })+ expect(cloudRoomsRefused.value.has(viewer.store)).toBe(true)+ expect(viewer.calls.readOnly.at(-1)).toBe(true)+ expect(viewer.calls.saves).toBe(0)++ const guest = tab({ stored: false })+ leaveRefusedRoom(guest.store, { permission: 'edit', canSave: false })+ expect(guest.calls.saves).toBe(0)+ expect(guest.store.state.autosaveEnabled).toBe(false)+ })++ test('forgets the refusal on rejoining, and a second refusal records it once', async () => {+ const { store } = tab({ stored: false })+ leaveRefusedRoom(store, { permission: 'edit', canSave: true })+ leaveRefusedRoom(store, { permission: 'edit', canSave: true })+ expect([...cloudRoomsRefused.value].filter((refused) => refused === store)).toHaveLength(1)+ await rejoinRefusedRoom(store)+ expect(cloudRoomsRefused.value.has(store)).toBe(false)+ })+})++describe('a refused tab over time', () => {+ const ORIGIN = 'https://refused.example.com'+ const DOCUMENT = '5a0c4d2e-8f1b-4c3d-9e2a-7b6c5d4e3f21'+ let ticketRequests = 0++ beforeEach(() => {+ ticketRequests = 0+ spyOn(globalThis, 'fetch').mockImplementation(+ fetchStub(async (input) => {+ const url = new URL(input instanceof Request ? input.url : String(input))+ if (url.pathname === '/.well-known/openpencil') {+ return Response.json(cloudDiscoveryFixture(ORIGIN))+ }+ if (url.pathname === '/api/account/status') {+ return Response.json({+ user: { userId: 'user-1', email: '[email protected]', name: 'Ben' },+ state: 'active'+ })+ }+ if (url.pathname === '/api/workspaces') return Response.json({ workspaces: [] })+ if (url.pathname === `/api/documents/${DOCUMENT}/collaboration-ticket`) {+ ticketRequests+++ // A refusal ends the start at once; a 404 would wait for the document's first upload.+ return Response.json({ error: { code: 'forbidden' } }, { status: 403 })+ }+ return Response.json({ error: { code: 'not_found' } }, { status: 404 })+ })+ )+ })++ afterEach(() => {+ for (const server of cloudServers.value) removeCloudServer(server.id)+ })++ /** A tab showing a Cloud document of a signed-in server. */+ async function cloudTab() {+ const server = await addCloudServer({ kind: 'self-hosted', url: ORIGIN })+ await refreshCloudConnection(server)+ return asDouble<EditorStore>({+ state: { autosaveEnabled: false },+ getStorageBinding: () => ({+ providerId: CLOUD_STORAGE_PROVIDER_ID,+ profileId: server.id,+ containerId: 'workspace',+ documentId: DOCUMENT+ }),+ setReadOnly: () => undefined,+ saveFigFile: async () => undefined+ })+ }++ test('does not join its room again on its own, as another tab of the server does', async () => {+ const refused = await cloudTab()+ leaveRefusedRoom(refused, { permission: 'view', canSave: false })+ await startCloudRoom(refused)+ expect(ticketRequests).toBe(0)++ const other = await cloudTab()+ await startCloudRoom(other).catch(() => undefined)+ expect(ticketRequests).toBe(1)+ })++ test('stays refused when rejoining ends without a room', async () => {+ const opened = createTab()+ leaveRefusedRoom(opened.store, { permission: 'view', canSave: false })+ // The tab has no Cloud document, so the restart finds no room to join.+ await rejoinRefusedRoom(opened.store)+ expect(cloudRoomsRefused.value.has(opened.store)).toBe(true)+ await closeTab(opened.id, 'discard')+ })++ test('forgets the refusal once its tab closes', async () => {+ const opened = createTab()+ leaveRefusedRoom(opened.store, { permission: 'view', canSave: false })+ expect(cloudRoomsRefused.value.has(opened.store)).toBe(true)+ await closeTab(opened.id, 'discard')+ await nextTick()+ expect(cloudRoomsRefused.value.has(opened.store)).toBe(false)+ })+})diff --git a/tests/app/collab/transport/cloud.test.ts b/tests/app/collab/transport/cloud.test.tsindex 3034cfab9..0e30b2ba2 100644--- a/tests/app/collab/transport/cloud.test.ts+++ b/tests/app/collab/transport/cloud.test.ts@@ -1,9 +1,11 @@import { describe, expect, jest, test } from 'bun:test'import {+ createRelayClientAssembler,decodeRelayClientFrame,- encodeRelayServerFrame,RELAY_CLOSE,+ RELAY_FRAGMENT_BYTES,+ relayServerMessages,type RelayClientFrame,type RelayServerFrame} from '@open-pencil/cloud/contract'@@ -17,9 +19,14 @@ class FakeSocket extends EventTarget {readyState: number = WebSocket.CONNECTINGbinaryType = 'blob'readonly sent: RelayClientFrame[] = []+ /** Socket messages sent, which outnumber frames once a frame travels in fragments. */+ messages = 0+ private readonly assembler = createRelayClientAssembler(() => Infinity)send(data: Uint8Array) {- const frame = decodeRelayClientFrame(data)+ this.messages+++ const assembled = this.assembler.push(data)+ const frame = assembled.type === 'frame' ? decodeRelayClientFrame(assembled.data) : nullif (frame) this.sent.push(frame)}@@ -29,7 +36,13 @@ class FakeSocket extends EventTarget {}receive(frame: RelayServerFrame) {- const data = encodeRelayServerFrame(frame)+ for (const data of relayServerMessages(frame)) {+ this.dispatchEvent(new MessageEvent('message', { data: data.slice().buffer }))+ }+ }++ /** Delivers bytes as one socket message, whatever they hold. */+ receiveMessage(data: Uint8Array) {this.dispatchEvent(new MessageEvent('message', { data: data.slice().buffer }))}@@ -138,6 +151,48 @@ describe('Cloud relay transport', () => {await transport.leave()})+ test('sends and receives frames larger than one message in fragments', async () => {+ const { transport, sockets } = room()+ const [send, receive] = transport.makeAction('yjs-update')+ const received: Uint8Array[] = []+ receive((data) => received.push(data))+ await settle()+ const socket = sockets[0]+ if (!socket) throw new Error('Expected a socket')+ socket.open()+ socket.receive({ type: 'welcome', peerId: 'me', peers: ['server'] })+ const payload = crypto.getRandomValues(new Uint8Array(RELAY_FRAGMENT_BYTES * 3))+ const before = socket.messages+ send(payload)+ expect(socket.messages - before).toBeGreaterThan(1)+ expect(socket.sent.at(-1)).toEqual({+ type: 'message',+ namespace: 'yjs-update',+ target: null,+ payload+ })+ socket.receive({ type: 'message', namespace: 'yjs-update', from: 'alice', payload })+ expect(received).toEqual([payload])+ })++ test('connects again after a frame it cannot read, to sync what it missed', async () => {+ const { sockets, errors } = room()+ await settle()+ const socket = sockets[0]+ if (!socket) throw new Error('Expected a socket')+ socket.open()+ socket.receive({ type: 'welcome', peerId: 'me', peers: ['server'] })+ // A fragment that says more follows, then a whole frame in the middle of it.+ socket.receiveMessage(new Uint8Array([4, 1, 1, 0]))+ socket.receive({ type: 'join', peerId: 'alice' })+ expect(errors).toHaveLength(1)+ await new Promise((resolve) => {+ setTimeout(resolve, 0)+ })+ await settle()+ expect(sockets).toHaveLength(2)+ })+test('reconnects with a fresh ticket after losing the relay, saying its peers left', async () => {const { transport, sockets, left, tickets } = room()await settle()