AI-native design editor. Open-source Figma alternative.
fix: persist Cloud document renames with saved revisions (#1571)
GitttHomie81661eb90ac0
diff --git a/changes/1571/fixed.md b/changes/1571/fixed.mdnew file mode 100644index 000000000..f03aca544--- /dev/null+++ b/changes/1571/fixed.md@@ -0,0 +1 @@+- Cloud document renames persist across reopening and synchronize with collaborators.diff --git a/packages/cloud/src/contract/documents.ts b/packages/cloud/src/contract/documents.tsindex 26c6edfe3..0c2063dd1 100644--- a/packages/cloud/src/contract/documents.ts+++ b/packages/cloud/src/contract/documents.ts@@ -112,9 +112,11 @@ export const workspaceUsageSchema = v.object({})export type WorkspaceUsage = v.InferOutput<typeof workspaceUsageSchema>+export const CLOUD_DOCUMENT_NAME_MAX_LENGTH = 255+export const createDocumentSchema = v.object({id: v.optional(v.pipe(v.string(), v.uuid())),- name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(255))+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(CLOUD_DOCUMENT_NAME_MAX_LENGTH))})export type CreateDocumentInput = v.InferOutput<typeof createDocumentSchema>@@ -189,6 +191,8 @@ export const completedUploadPartSchema = v.object({export const commitUploadSchema = v.object({checksum: checksumSchema,+ /** The document title captured with this revision; omitted by older clients. */+ name: v.optional(createDocumentSchema.entries.name),multipart: v.optional(v.object({uploadId: v.pipe(v.string(), v.minLength(1)),diff --git a/packages/cloud/src/contract/index.ts b/packages/cloud/src/contract/index.tsindex c185d70aa..d30c9aec9 100644--- a/packages/cloud/src/contract/index.ts+++ b/packages/cloud/src/contract/index.ts@@ -65,6 +65,7 @@ export {type CloudListing} from './discovery'export {+ CLOUD_DOCUMENT_NAME_MAX_LENGTH,CLOUD_IMAGE_NAME_PATTERN,CLOUD_MAX_DOCUMENT_IMAGES,CLOUD_PROTOCOL_MAX_UPLOAD_BYTES,diff --git a/packages/cloud/src/server/documents/service.ts b/packages/cloud/src/server/documents/service.tsindex 7969c02be..e56d9f5d5 100644--- a/packages/cloud/src/server/documents/service.ts+++ b/packages/cloud/src/server/documents/service.ts@@ -92,7 +92,8 @@ export function createDocumentService(stored,revisionId,storageObjectId,- images: revisionImages+ images: revisionImages,+ name}: {userId: stringuploadId: string@@ -106,6 +107,7 @@ export function createDocumentService(revisionId: stringstorageObjectId: stringimages: CommitUploadInput['images']+ name: CommitUploadInput['name']}): Promise<boolean> {const lockedUpload = await transaction@@ -154,6 +156,7 @@ export function createDocumentService(await transaction.updateTable('document').set({+ ...(name === undefined ? {} : { name }),currentRevisionId: revisionId,version: (expression) => expression('version', '+', 1)})@@ -324,7 +327,8 @@ export function createDocumentService(stored,revisionId: crypto.randomUUID(),storageObjectId: crypto.randomUUID(),- images: input.images+ images: input.images,+ name: input.name})))diff --git a/packages/cloud/tests/integration/server/documents/routes.test.ts b/packages/cloud/tests/integration/server/documents/routes.test.tsindex 7c5adce47..b86b7471e 100644--- a/packages/cloud/tests/integration/server/documents/routes.test.ts+++ b/packages/cloud/tests/integration/server/documents/routes.test.ts@@ -162,24 +162,32 @@ describe('Cloud document routes', () => {const commit = await context.app.request(`/api/uploads/${upload.id}/commit`, {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ checksum })+ body: JSON.stringify({ checksum, name: 'Updated homepage' })})expect(commit.status).toBe(200)const committed = await responseJSON(commit,- v.object({ document: v.object({ currentRevisionId: v.string(), version: v.number() }) })+ v.object({+ document: v.object({+ currentRevisionId: v.string(),+ version: v.number(),+ name: v.string()+ })+ }))expect(committed.document.currentRevisionId).toBeString()expect(committed.document.version).toBe(1)+ expect(committed.document.name).toBe('Updated homepage')const repeatedCommit = await context.app.request(`/api/uploads/${upload.id}/commit`, {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ checksum })+ body: JSON.stringify({ checksum, name: 'Stale retry' })})expect(repeatedCommit.status).toBe(200)expect(await repeatedCommit.json()).toMatchObject({document: {+ name: 'Updated homepage',currentRevisionId: committed.document.currentRevisionId,version: 1}@@ -198,7 +206,7 @@ describe('Cloud document routes', () => {expect(downloadResponse.status).toBe(200)expect(await downloadResponse.json()).toMatchObject({document: {- document: { id: document.document.id, version: 1 },+ document: { id: document.document.id, version: 1, name: 'Updated homepage' },revisionId: committed.document.currentRevisionId,byteSize: 128,checksum,diff --git a/src/app/collab/session.ts b/src/app/collab/session.tsindex 0faa4c6d5..f51ae0c6d 100644--- a/src/app/collab/session.ts+++ b/src/app/collab/session.ts@@ -150,6 +150,7 @@ export function openRoomSession({const documentData = roomDocumentData(ydoc)const persistence = openSavedCopy(roomId, ydoc)const saves = trackRoomSaves(ydoc, [+ meta,ynodes,yimages,yvariables,@@ -224,7 +225,7 @@ export function openRoomSession({awareness.setLocalStateField('hasFile', hasDocument.value)}const name = readRoomName(meta)- if (hasDocument.value && name && origin === 'joined') store.state.documentName = name+ if (hasDocument.value && name) store.state.documentName = name}function updatePeers() {@@ -256,6 +257,21 @@ export function openRoomSession({}})meta.observe(refreshDocument)+ const stopName = watch(+ () => store.state.documentName,+ (name) => {+ if (+ disposed ||+ store.state.readOnly ||+ !hasDocument.value ||+ readRoot(meta) !== store.graph.rootId ||+ name === readRoomName(meta)+ )+ return+ writeRoomName(meta, name)+ },+ { flush: 'sync' }+ )awareness.on('change', updatePeers)const connection = connectCollabRoom({@@ -335,6 +351,7 @@ export function openRoomSession({upload: connection.upload,dispose() {if (disposed) return+ stopName()// Unbinding writes an edit still waiting to be sent, so it runs while the room is open.unbindGraphEvents()variableSync.dispose()diff --git a/src/app/document/io/create.ts b/src/app/document/io/create.tsindex b7179a389..9fe8d5b73 100644--- a/src/app/document/io/create.ts+++ b/src/app/document/io/create.ts@@ -69,6 +69,7 @@ export function createDocumentIOActions(})return {+ renameDocument: sourceActions.renameDocument,downloadBlob,setViewportSize,getViewportSize,diff --git a/src/app/document/io/source/actions.ts b/src/app/document/io/source/actions.tsindex 56004489d..5d31d1ba3 100644--- a/src/app/document/io/source/actions.ts+++ b/src/app/document/io/source/actions.ts@@ -128,6 +128,14 @@ export function createDocumentSourceActions({setSavedVersion(changes.capture())}+ function renameDocument(name: string) {+ const trimmed = name.trim()+ if (state.readOnly || !trimmed || trimmed === state.documentName) return+ state.documentName = trimmed+ // Storage keeps the name with the document; a file's name is its path, which saving leaves as is.+ if (getStorageBinding()) changes.markChanged()+ }+function setDocumentSource(fileName: string,sourceFormat: string,@@ -256,6 +264,7 @@ export function createDocumentSourceActions({}return {+ renameDocument,setDocumentSource,setStorageDocumentSource,setPlannedFilePath,diff --git a/src/app/editor/session/modules.ts b/src/app/editor/session/modules.tsindex 9f0d11359..aae142ac3 100644--- a/src/app/editor/session/modules.ts+++ b/src/app/editor/session/modules.ts@@ -84,6 +84,7 @@ export function createEditorStoreModules(getViewportSize: documentIO.getViewportSize,fitCurrentPageToViewport: documentIO.fitCurrentPageToViewport,hasUnsavedChanges: documentIO.hasUnsavedChanges,+ renameDocument: documentIO.renameDocument,/** Takes the document as it is now as its saved state, so closing it asks nothing. */markDocumentSaved: documentIO.markDocumentSaved,/** Counts the document changed by something outside its history, so it gets saved. */diff --git a/src/app/integrations/storage/cloud/adapter.ts b/src/app/integrations/storage/cloud/adapter.tsindex cfecfb262..dfd0bcc41 100644--- a/src/app/integrations/storage/cloud/adapter.ts+++ b/src/app/integrations/storage/cloud/adapter.ts@@ -1,4 +1,5 @@import { CloudAPIError, type CloudAPIClient } from '@open-pencil/cloud/client'+import { CLOUD_DOCUMENT_NAME_MAX_LENGTH } from '@open-pencil/cloud/contract'import { extractFigThumbnailFromReader } from '@open-pencil/fig'import { cloudServerHost } from '@/app/cloud/servers/address'@@ -21,6 +22,22 @@ function invalidUpload(error: unknown): boolean {return error instanceof CloudAPIError && error.code === 'invalid_upload'}+/**+ * The name as Cloud accepts it: trimmed and cut to its limit, so a long name never fails every save.+ * The cut never splits a character in two.+ */+function cloudDocumentName(name: string): string {+ const trimmed = name.trim()+ const cut =+ trimmed.length > CLOUD_DOCUMENT_NAME_MAX_LENGTH+ ? trimmed+ .slice(0, CLOUD_DOCUMENT_NAME_MAX_LENGTH)+ .replace(/[\uD800-\uDBFF]$/, '')+ .trimEnd()+ : trimmed+ return cut || 'Untitled'+}+export type CloudStorageDependencies = {/** The signed-in API client for a server, or a `StorageUnavailableError`. */client(serverId: string): Promise<CloudAPIClient>@@ -103,9 +120,10 @@ export function createCloudStorageAdapter(async putDocument(id, bytes, metadata, onProgress, options) {const cloud = await client()const baseRevision = options?.baseRevision ?? null+ const name = cloudDocumentName(metadata.name)// Without a revision this is the first save; the document may not exist on the server yet.if (!baseRevision && !(await listed(id))) {- await cloud.createDocument(workspaceId(), { id, name: metadata.name })+ await cloud.createDocument(workspaceId(), { id, name })}// The workspace keeps images once; the stored file names them and uploads only those it lacks.const { lean, images } = splitCloudDocument(bytes)@@ -128,6 +146,7 @@ export function createCloudStorageAdapter(})const committed = await cloud.commitUpload(upload.uploadId, {checksum,+ name,multipart: upload.multipart,images: named.map((image) => ({ name: image.name, checksum: image.checksum }))})diff --git a/src/app/shell/menu/document-name.ts b/src/app/shell/menu/document-name.tsindex 7e161250b..673087331 100644--- a/src/app/shell/menu/document-name.ts+++ b/src/app/shell/menu/document-name.ts@@ -8,7 +8,7 @@ const DOCUMENT_NAME_ID = 'document-name'export function useDocumentNameRename(store: EditorStore) {const rename = useInlineRename<'document-name'>((_id, name) => {- store.state.documentName = name+ store.renameDocument(name)})const editingName = computed(() => rename.editingId.value === DOCUMENT_NAME_ID)diff --git a/tests/app/collab/session.test.ts b/tests/app/collab/session.test.tsindex cf9f301f8..b6addca9f 100644--- a/tests/app/collab/session.test.ts+++ b/tests/app/collab/session.test.ts@@ -54,6 +54,32 @@ function firstPageId(store: EditorStore) {}describe('room sessions', () => {+ test('renames reach the saver and count as edits without echoing back', async () => {+ await withRooms(async (open, settle) => {+ const host = newStore('Checkout')+ const shared = open({ roomId: ROOM_A, store: host, origin: 'shared' })+ shared.shareDocument()+ const guest = newStore()+ const joined = open({ roomId: ROOM_A, store: guest, origin: 'joined' })+ await settle()+ shared.saves.markSaved(shared.saves.counts())+ await settle()+ expect(joined.saves.unsaved()).toBe(false)++ guest.renameDocument('Payment')+ await settle()+ expect(host.state.documentName).toBe('Payment')+ expect(shared.saves.unsaved()).toBe(true)+ const counts = shared.saves.counts()+ await settle()+ expect(shared.saves.counts()).toEqual(counts)++ host.renameDocument('Receipt')+ await settle()+ expect(guest.state.documentName).toBe('Receipt')+ })+ })+test("a joined tab shows the sharer's document, with its name, once it arrives", async () => {await withRooms(async (open, settle) => {const host = newStore('Checkout flow')diff --git a/tests/app/document/io/source/actions.test.ts b/tests/app/document/io/source/actions.test.tsnew file mode 100644index 000000000..2423b99f9--- /dev/null+++ b/tests/app/document/io/source/actions.test.ts@@ -0,0 +1,47 @@+import { afterEach, describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'++import { createEditorStore, type EditorStore } from '@/app/editor/session'++const CLOUD = { providerId: 'cloud', containerId: 'workspace', documentId: 'document' }++let store: EditorStore++function storedDocument() {+ store = createEditorStore(new SceneGraph())+ store.setStorageDocumentSource(CLOUD, 'Untitled')+ return store+}++afterEach(() => store.dispose())++describe('renaming a document', () => {+ test('marks a stored document changed under its new name', () => {+ storedDocument().renameDocument(' Checkout ')+ expect(store.state.documentName).toBe('Checkout')+ expect(store.hasUnsavedChanges()).toBe(true)+ })++ test('leaves the document saved when the name stays the same or is blank', () => {+ storedDocument().renameDocument(' Untitled ')+ store.renameDocument(' ')+ expect(store.state.documentName).toBe('Untitled')+ expect(store.hasUnsavedChanges()).toBe(false)+ })++ test('keeps a read-only document as it is', () => {+ storedDocument().setReadOnly(true)+ store.renameDocument('Other')+ expect(store.state.documentName).toBe('Untitled')+ expect(store.hasUnsavedChanges()).toBe(false)+ })++ test('shows a new name for a file without calling it unsaved', () => {+ store = createEditorStore(new SceneGraph())+ store.markDocumentSaved()+ store.renameDocument('Checkout')+ expect(store.state.documentName).toBe('Checkout')+ expect(store.hasUnsavedChanges()).toBe(false)+ })+})diff --git a/tests/app/integrations/storage/cloud/adapter.test.ts b/tests/app/integrations/storage/cloud/adapter.test.tsindex 1379786aa..92a1c6096 100644--- a/tests/app/integrations/storage/cloud/adapter.test.ts+++ b/tests/app/integrations/storage/cloud/adapter.test.ts@@ -149,6 +149,7 @@ function cloudServer() {const revision = crypto.randomUUID()objects.set(revision, objects.get(uploadId) ?? new Uint8Array())Object.assign(doc, {+ ...(typeof body.name === 'string' ? { name: body.name } : {}),revision,version: doc.version + 1,checksum: String(body.checksum),@@ -287,6 +288,32 @@ function adapter(server: ReturnType<typeof cloudServer>) {}describe('Cloud storage adapter', () => {+ test('saves an edited title with an existing document revision', async () => {+ const storage = adapter(cloudServer())+ const id = crypto.randomUUID()+ const bytes = new TextEncoder().encode('design')+ const first = await storage.putDocument(id, bytes, { name: 'Untitled', updatedAt: '' })+ await storage.putDocument(id, bytes, { name: 'Checkout', updatedAt: '' }, undefined, {+ baseRevision: first.revision+ })+ expect(await storage.getDocumentMetadata?.(id)).toMatchObject({ name: 'Checkout' })+ expect(await storage.listDocuments()).toMatchObject([{ id, name: 'Checkout' }])+ })++ test('saves a name Cloud accepts, whatever the editor calls the document', async () => {+ const storage = adapter(cloudServer())+ const id = crypto.randomUUID()+ const bytes = new TextEncoder().encode('design')+ const first = await storage.putDocument(id, bytes, { name: ' ', updatedAt: '' })+ expect(await storage.getDocumentMetadata?.(id)).toMatchObject({ name: 'Untitled' })+ // Cloud keeps 255 UTF-16 units; the emoji's second half would be the 256th, so it goes whole.+ const kept = 'a'.repeat(254)+ await storage.putDocument(id, bytes, { name: `${kept}😀 tail`, updatedAt: '' }, undefined, {+ baseRevision: first.revision+ })+ expect(await storage.getDocumentMetadata?.(id)).toMatchObject({ name: kept })+ })+test('creates the document on its first save and opens what it saved', async () => {const server = cloudServer()const storage = adapter(server)