AI-native design editor. Open-source Figma alternative.
fix: show members of a Cloud document under their account name and one color (#1302)
Danila Poyarkov0ff2a7a5fff5
diff --git a/src/app/cloud/rooms/identity.ts b/src/app/cloud/rooms/identity.tsnew file mode 100644index 000000000..a106ea157--- /dev/null+++ b/src/app/cloud/rooms/identity.ts@@ -0,0 +1,24 @@+import { shallowRef } from 'vue'++import type { RoomIdentity } from '@/app/collab/session'+import { PEER_COLORS } from '@/constants'++import type { CloudAccount } from '../servers/store'++/** The same index for the same id on every device, so a person keeps one color. */+function colorIndex(id: string): number {+ let hash = 0+ for (const character of id) hash = (hash * 31 + (character.codePointAt(0) ?? 0)) >>> 0+ return hash % PEER_COLORS.length+}++/**+ * Who a signed-in member is in their documents' rooms: their account's name, as the relay shows+ * them to everyone else, on one color for every tab they have open.+ */+export function accountRoomIdentity(account: Pick<CloudAccount, 'id' | 'name'>): RoomIdentity {+ return {+ name: shallowRef(account.name),+ color: PEER_COLORS[colorIndex(account.id)] ?? PEER_COLORS[0]+ }+}diff --git a/src/app/cloud/rooms/live.ts b/src/app/cloud/rooms/live.tsindex 5a993cd4c..681f95af0 100644--- a/src/app/cloud/rooms/live.ts+++ b/src/app/cloud/rooms/live.ts@@ -3,7 +3,7 @@ import { shallowRef, watch } from 'vue'import { RELAY_SERVER_PEER, type CollaborationTicket } from '@open-pencil/cloud/contract'import { leaveRoom, openDocumentRoom, roomForStore } from '@/app/collab/rooms'-import type { RoomSession } from '@/app/collab/session'+import type { RoomIdentity, RoomSession } from '@/app/collab/session'import type { JoinCollabRoom } from '@/app/collab/transport'import { createCloudRelayJoin } from '@/app/collab/transport/cloud'import type { EditorStore } from '@/app/editor/session'@@ -19,9 +19,10 @@ import { onStorageWorkspaceEvent } from '@/app/storage/workspace/events'import { allTabs, getTabForStore, getTabsSnapshot, reloadStorageDocumentInTab } from '@/app/tabs'import { isCloudBinding } from '../documents/status'-import { cloudConnections } from '../sessions/connection'+import { cloudConnection, cloudConnections } from '../sessions/connection'import { cloudShareTarget } from '../sharing/document'import { versionListRevision } from '../versions/history'+import { accountRoomIdentity } from './identity'import { shareRoomUploads, uploadStoredDocument } from './upload'/** Each Cloud tab's permission in its room, for the status beside the name. */@@ -150,11 +151,13 @@ export function openCloudDocumentRoom(onRestored?: () => void/** How the saver gets the document onto the server; the tab's own upload unless a test stands in. */uploadNow?: () => Promise<boolean>+ /** Who the tab is in the room; the device's own identity unless an account names it. */+ identity?: RoomIdentity}) {const canEdit = options.permission === 'edit'const canSave = canEdit && !options.guest- const session = openDocumentRoom(store, options.roomId, options.transport)+ const session = openDocumentRoom(store, options.roomId, options.transport, options.identity)setPermission(store, options.permission)// A viewer sees the room's edits and makes none, as Figma's view-only files do.store.setReadOnly(!canEdit)@@ -259,7 +262,9 @@ export async function startCloudRoom(store: EditorStore): Promise<void> {if (first.provider !== 'relay' || !first.serverURL || !current) returnconst nextTicket = () => target.client.getCollaborationTicket(binding.documentId)const restart = () => void restartCloudRoom(store)+ const account = cloudConnection(target.server.id).accountconst room = openCloudDocumentRoom(store, {+ identity: account ? accountRoomIdentity(account) : undefined,roomId: first.roomId,transport: cloudRelayTransport(first.serverURL, first, nextTicket, restart),permission: first.permission,diff --git a/src/app/collab/rooms.ts b/src/app/collab/rooms.tsindex ed2cfb828..e6f4f3a48 100644--- a/src/app/collab/rooms.ts+++ b/src/app/collab/rooms.ts@@ -2,7 +2,7 @@ import { computed, shallowRef, watch } from 'vue'import { generateRoomId } from '@/app/collab/awareness'import { isRoomId } from '@/app/collab/room/id'-import { openRoomSession, type RoomSession } from '@/app/collab/session'+import { openRoomSession, type RoomIdentity, type RoomSession } from '@/app/collab/session'import type { JoinCollabRoom } from '@/app/collab/transport'import type { EditorStore } from '@/app/editor/active-store'import { activeTab, allTabs, closeTab, createTab, getTabForStore, switchTab } from '@/app/tabs'@@ -57,12 +57,14 @@ export function shareDocument(store: EditorStore, roomId = generateRoomId()): Ro/*** Puts a tab's stored document into its server's room. The tab stays that document; what the room- * already holds arrives through the connection, and an empty room is seeded by whoever asks.+ * already holds arrives through the connection, and an empty room is seeded by whoever asks. The+ * tab is the device's own identity there unless the server names it.*/export function openDocumentRoom(store: EditorStore,roomId: string,- transport: JoinCollabRoom+ transport: JoinCollabRoom,+ identity?: RoomIdentity): RoomSession {const existing = roomForStore(store)if (existing) return existing@@ -71,7 +73,8 @@ export function openDocumentRoom(store,origin: 'shared',joinRoom: transport,- holdsDocument: true+ holdsDocument: true,+ identity})addSession(session)return sessiondiff --git a/src/app/collab/session.ts b/src/app/collab/session.tsindex b0dc5d12e..601ae0685 100644--- a/src/app/collab/session.ts+++ b/src/app/collab/session.ts@@ -4,6 +4,8 @@ import { IndexeddbPersistence } from 'y-indexeddb'import * as awarenessProtocol from 'y-protocols/awareness'import * as Y from 'yjs'+import type { Color } from '@open-pencil/scene-graph/primitives'+import { shareAgentPreviews } from '@/app/collab/agent-preview'import { buildRemotePeers } from '@/app/collab/awareness'import { useCollabIdentity } from '@/app/collab/identity'@@ -34,6 +36,9 @@ import { ROOM_STATUS_TICK_MS, ROOM_UNREACHABLE_MS } from '@/constants'/** How a tab came to be in a room: by sharing its own document, or by joining someone's. */export type RoomOrigin = 'shared' | 'joined'+/** Who this tab is in a room: the name and color everyone sees, this tab included. */+export type RoomIdentity = { name: Readonly<Ref<string>>; color: Color }+/** One room, live in one tab: its document, presence, connection, and saved copy. */export interface RoomSession {readonly roomId: string@@ -44,6 +49,8 @@ export interface RoomSession {/** Whether the room's document has reached this tab, from a peer or the saved copy. */readonly hasDocument: Readonly<Ref<boolean>>readonly voice: RoomVoice+ /** Who this tab is in the room. */+ readonly identity: RoomIdentityupdateCursor(x: number, y: number, pageId: string): voidupdateSelection(ids: string[]): void/** Writes the tab's whole document into the room and makes its root the room's. */@@ -78,7 +85,7 @@ export interface RoomSessionOptions {origin: RoomOriginjoinRoom?: JoinCollabRoom/** Who this tab is in the room; the device's own identity unless a host stands in for one. */- identity?: Pick<ReturnType<typeof useCollabIdentity>, 'name' | 'color'>+ identity?: RoomIdentityopenSavedCopy?: (roomId: string, ydoc: Y.Doc) => RoomSavedCopy/** How long the tab tries to reach the service that introduces peers before saying it cannot. */unreachableMs?: number@@ -256,6 +263,7 @@ export function openRoomSession({status,hasDocument,voice,+ identity,updateCursor(x, y, pageId) {awareness.setLocalStateField('cursor', { x, y, pageId, zoom: store.state.zoom })},diff --git a/src/app/collab/use.ts b/src/app/collab/use.tsindex 5c201a739..4173d7250 100644--- a/src/app/collab/use.ts+++ b/src/app/collab/use.ts@@ -34,8 +34,9 @@ export function useCollab() {roomId: room?.roomId ?? null,status: room?.status.value ?? null,peers: room?.peers.value ?? [],- localName: identity.name.value,- localColor: identity.color,+ // A room may know this tab by another name, such as a Cloud account's.+ localName: room?.identity.name.value ?? identity.name.value,+ localColor: room?.identity.color ?? identity.color,hasChosenName: identity.hasChosenName.value}})diff --git a/tests/app/cloud/rooms/identity.test.ts b/tests/app/cloud/rooms/identity.test.tsnew file mode 100644index 000000000..186b5fcfd--- /dev/null+++ b/tests/app/cloud/rooms/identity.test.ts@@ -0,0 +1,19 @@+import { describe, expect, test } from 'bun:test'++import { accountRoomIdentity } from '@/app/cloud/rooms/identity'++describe('a member’s identity in rooms', () => {+ test('is their account’s name, on the same color in every tab', () => {+ const account = { id: '5f0c8a6e-6b0e-4a43-9a5e-2f7c1d3b9e10', name: 'Alice' }+ const first = accountRoomIdentity(account)+ const second = accountRoomIdentity(account)+ expect(first.name.value).toBe('Alice')+ expect(second.color).toEqual(first.color)+ })++ test('picks its color from the account, so people tell each other apart', () => {+ const alice = accountRoomIdentity({ id: 'alice', name: 'Alice' })+ const carol = accountRoomIdentity({ id: 'carol', name: 'Carol' })+ expect(alice.color).not.toEqual(carol.color)+ })+})diff --git a/tests/helpers/collab/relay-server.ts b/tests/helpers/collab/relay-server.tsindex c8f3be9b6..aa85e5aaf 100644--- a/tests/helpers/collab/relay-server.ts+++ b/tests/helpers/collab/relay-server.ts@@ -50,7 +50,12 @@ export async function startTestRelay() {) {const principal =kind === 'user'- ? { kind, userId: crypto.randomUUID(), name, email: `${name.toLowerCase()}@example.com` }+ ? {+ kind,+ userId: crypto.randomUUID(),+ name,+ email: `${name.toLowerCase().replaceAll(' ', '.')}@example.com`+ }: { kind, guestId: crypto.randomUUID(), name }return createCloudRelayJoin({url,diff --git a/tests/integration/collab/cloud-relay.test.ts b/tests/integration/collab/cloud-relay.test.tsindex 15b13303e..3f1ca2d65 100644--- a/tests/integration/collab/cloud-relay.test.ts+++ b/tests/integration/collab/cloud-relay.test.ts@@ -9,8 +9,10 @@ import type { DocumentPermission } from '@open-pencil/cloud/contract'import { exportFigFile, initCodec, parseFigFile } from '@open-pencil/core'import { SceneGraph } from '@open-pencil/scene-graph'+import { accountRoomIdentity } from '@/app/cloud/rooms/identity'import { openCloudDocumentRoom } from '@/app/cloud/rooms/live'import { versionListRevision } from '@/app/cloud/versions/history'+import { useCollabIdentity } from '@/app/collab/identity'import { connectCollabRoom } from '@/app/collab/room/connection'import { createEditorStore } from '@/app/editor/session'@@ -126,6 +128,43 @@ describe('collaboration through the Cloud relay', () => {})})+describe('Cloud document rooms, identity', () => {+ test('a member is their account in the room, in every tab', async () => {+ const relay = await startRelay()+ const documentId = crypto.randomUUID()+ const [grace, again] = await openedTwice()+ // The account's name differs from this device's, so the assertions show which one a tab took.+ useCollabIdentity().setName('This device')+ cleanups.push(() => useCollabIdentity().setName(''))+ const account = { id: crypto.randomUUID(), name: 'Grace Hopper' }+ const open = (store: typeof grace) => {+ const room = openCloudDocumentRoom(store, {+ roomId: `cloud:${documentId}:0`,+ transport: relay.join(documentId, 'Grace Hopper', 'edit', 'user'),+ permission: 'edit',+ identity: accountRoomIdentity(account)+ })+ cleanups.push(() => {+ room.stop()+ room.session.dispose()+ })+ return room+ }+ const first = open(grace)+ const second = open(again)+ await until(() => first.session.peers.value.length > 0 && second.session.peers.value.length > 0)+ const own = (room: typeof first) => room.session.presence().get(room.session.clientId)?.user+ expect(own(first)).toMatchObject({ name: 'Grace Hopper' })+ expect(own(second)).toEqual(own(first))+ // Each tab sees the other as it presents itself; the name comes from the ticket, which the+ // server takes from the same account.+ const seen = (room: typeof first) =>+ room.session.peers.value.map((peer) => ({ name: peer.name, color: peer.color }))+ expect([own(second)]).toEqual(seen(first))+ expect([own(first)]).toEqual(seen(second))+ })+})+describe('Cloud document rooms, reopening', () => {test('a tab that opens the stored file shows the room’s layers, not the file’s copies', async () => {const relay = await startRelay()