AI-native design editor. Open-source Figma alternative.
fix: show Cloud document previews on Home before they are opened (#1295)
Danila Poyarkov06847b0bb393
diff --git a/packages/docs/reference/self-hosting-cloud.md b/packages/docs/reference/self-hosting-cloud.mdindex 39cdefe90..b8499abe7 100644--- a/packages/docs/reference/self-hosting-cloud.md+++ b/packages/docs/reference/self-hosting-cloud.md@@ -52,7 +52,7 @@ Either way, the desktop app connects to the server directly, and the web editor- Terminate TLS in front of the server and the object store, on stable hostnames.- Forward WebSocket upgrades for `/api/collaboration/relay`. Collaboration tickets name the relay at `public_url` with a `ws:` or `wss:` scheme; set `[collaboration] relay_url` when clients reach it elsewhere.-- The object store must accept presigned uploads from the editor's origins: allow `PUT` and `GET` from `trusted_origins` in its CORS rules.+- The object store must accept presigned uploads from the editor's origins: allow `PUT` and `GET` from `trusted_origins` in its CORS rules, with the `Range` request header, which Home uses to read a document's preview without downloading the whole file.## The first administratordiff --git a/src/app/integrations/storage/cloud/adapter.ts b/src/app/integrations/storage/cloud/adapter.tsindex 258838093..bb07fc327 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 { extractFigThumbnailFromReader } from '@open-pencil/fig'import { cloudServerHost } from '@/app/cloud/servers/address'import { findCloudServer } from '@/app/cloud/servers/store'@@ -11,7 +12,7 @@ import {import { StorageRevisionConflictError, StorageUnavailableError } from '../errors'import { storageFetch } from '../s3/fetch'import type { StorageAdapter, StorageProviderRuntime } from '../types'-import { cloudChecksum, downloadCloudRevision } from './download'+import { cloudChecksum, downloadCloudRevision, readCloudRevisionRange } from './download'import { uploadCloudObject } from './upload'function revisionConflict(error: unknown): boolean {@@ -129,6 +130,17 @@ export function createCloudStorageAdapter(}},+ async getThumbnail(id) {+ const download = await (await client()).getDocument(id)+ const objectFetch = (input: string, init: RequestInit) =>+ dependencies.objectFetch(input, init)+ return extractFigThumbnailFromReader({+ size: download.byteSize,+ read: (start, endExclusive) =>+ readCloudRevisionRange(download, objectFetch, start, endExclusive)+ })+ },+async deleteDocument(id) {await (await client()).deleteDocument(id)},diff --git a/src/app/integrations/storage/cloud/download.ts b/src/app/integrations/storage/cloud/download.tsindex b1791dbb4..5caeb9147 100644--- a/src/app/integrations/storage/cloud/download.ts+++ b/src/app/integrations/storage/cloud/download.ts@@ -31,3 +31,58 @@ export async function downloadCloudRevision(options.onProgress?.({ transferredBytes: bytes.byteLength, totalBytes: download.byteSize })return bytes}++/**+ * Reads exactly `length` bytes of a response, stopping a body that runs past them rather than+ * receiving the rest.+ */+async function readExactly(response: Response, length: number): Promise<Uint8Array> {+ const bytes = new Uint8Array(length)+ let received = 0+ const reader = response.body?.getReader()+ if (reader) {+ for (;;) {+ const { done, value } = await reader.read()+ if (done) break+ if (received + value.byteLength > length) {+ await reader.cancel()+ throw new Error(`Cloud document range read sent more than the ${length} bytes asked for`)+ }+ bytes.set(value, received)+ received += value.byteLength+ }+ }+ if (received !== length) {+ throw new Error(`Cloud document range read sent ${received} of the ${length} bytes asked for`)+ }+ return bytes+}++/**+ * Bytes `start` to `endExclusive` of a revision, for reading its preview without the rest. Only+ * a partial response of exactly that range counts: a store that ignores the range, or answers+ * another one, is stopped rather than left sending the file. `Content-Range` is checked when the+ * store's CORS rules let the browser read it.+ */+export async function readCloudRevisionRange(+ download: DocumentDownload,+ objectFetch: (input: string, init: RequestInit) => Promise<Response>,+ start: number,+ endExclusive: number+): Promise<Uint8Array> {+ const response = await objectFetch(download.download.url, {+ method: download.download.method,+ headers: { ...download.download.headers, Range: `bytes=${start}-${endExclusive - 1}` }+ })+ const range = response.headers.get('Content-Range')+ if (+ response.status !== 206 ||+ (range && !range.startsWith(`bytes ${start}-${endExclusive - 1}/`))+ ) {+ await response.body?.cancel()+ throw new Error(+ `Cloud document range read failed with HTTP ${response.status}${range ? ` (${range})` : ''}`+ )+ }+ return readExactly(response, endExclusive - start)+}diff --git a/src/app/storage/sync/persist.ts b/src/app/storage/sync/persist.tsindex 1a98ab3d1..a3617a6a0 100644--- a/src/app/storage/sync/persist.ts+++ b/src/app/storage/sync/persist.ts@@ -19,6 +19,16 @@ export type PersistStorageCanvasOptions = StorageLocation & {figBytes: Uint8Array}+/** The preview a `.fig` carries, read in place. */+function figThumbnail(figBytes: Uint8Array): Promise<Uint8Array | null> {+ return extractFigThumbnailFromReader({+ size: figBytes.byteLength,+ async read(start, endExclusive) {+ return figBytes.subarray(start, endExclusive)+ }+ })+}+/** Write locally before scheduling remote synchronization. */export async function persistStorageCanvasLocally(options: PersistStorageCanvasOptions,@@ -28,12 +38,7 @@ export async function persistStorageCanvasLocally(store: getLocalCanvasStore(),enqueueCanvas: enqueuePutCanvas}- const thumbnailBytes = await extractFigThumbnailFromReader({- size: options.figBytes.byteLength,- async read(start, endExclusive) {- return options.figBytes.subarray(start, endExclusive)- }- })+ const thumbnailBytes = await figThumbnail(options.figBytes)const metadata = await runtime.store.writeCanvas({id: options.canvasId,providerId: options.providerId,@@ -76,7 +81,8 @@ export async function seedStorageCanvasFromRemote(updatedAt: options.updatedAt,remoteRevision: options.remoteRevision ?? null,figBytes: options.figBytes,- thumbBytes: options.thumbnailBytes,+ // Home shows the preview from the local copy, so a downloaded document brings its own.+ thumbBytes: options.thumbnailBytes ?? (await figThumbnail(options.figBytes)),syncStatus: options.markSynced === false ? 'pending' : 'synced'})if (options.markSynced === false) returndiff --git a/tests/app/integrations/storage/cloud/adapter.test.ts b/tests/app/integrations/storage/cloud/adapter.test.tsindex 5e634d75b..e54a52629 100644--- a/tests/app/integrations/storage/cloud/adapter.test.ts+++ b/tests/app/integrations/storage/cloud/adapter.test.ts@@ -1,4 +1,5 @@import { describe, expect, test } from 'bun:test'+import { readFileSync } from 'node:fs'import { fromUint8Array } from 'js-base64'@@ -20,6 +21,13 @@ function cloudServer() {type Doc = { name: string; revision: string | null; version: number; checksum?: string }const documents = new Map<string, Doc>()const objects = new Map<string, Uint8Array>()+ let fullReads = 0+ let cancelledReads = 0+ /**+ * How the object store answers a range: as asked, by ignoring it, with more or fewer bytes+ * than asked and no `Content-Range` to tell, or with another range than asked.+ */+ let ranges: 'honored' | 'ignored' | 'oversized' | 'short' | 'other' = 'honored'const uploads = new Map<string, { documentId: string; base: string | null }>()const summary = (id: string, doc: Doc) => ({id,@@ -128,7 +136,46 @@ function cloudServer() {return new Response(null, { status: 200 })}const bytes = objects.get(key)- return bytes ? new Response(Uint8Array.from(bytes)) : new Response(null, { status: 404 })+ if (!bytes) return new Response(null, { status: 404 })+ const range = /^bytes=(\d+)-(\d+)$/.exec(new Headers(init.headers).get('Range') ?? '')+ if (!range) {+ fullReads += 1+ return new Response(Uint8Array.from(bytes))+ }+ const [, first = '0', last = '0'] = range+ const start = Number(first)+ const end = Number(last) + 1+ // A chunk at a time, so a reader can stop it partway.+ const streamed = (from: number, to: number) => {+ let offset = from+ return new ReadableStream<Uint8Array>({+ pull(controller) {+ controller.enqueue(bytes.slice(offset, Math.min(offset + 1024, to)))+ offset += 1024+ if (offset >= to) controller.close()+ },+ cancel() {+ cancelledReads += 1+ }+ })+ }+ if (ranges === 'ignored') {+ fullReads += 1+ return new Response(streamed(0, bytes.byteLength))+ }+ const sent = {+ honored: [start, end],+ oversized: [start, bytes.byteLength],+ short: [start, end - 1],+ other: [start + 1, end + 1]+ }[ranges]+ const [from = start, to = end] = sent+ // A store whose CORS rules hide `Content-Range` leaves only the body's length to go by.+ const headers: Record<string, string> =+ ranges === 'oversized' || ranges === 'short'+ ? {}+ : { 'Content-Range': `bytes ${from}-${to - 1}/${bytes.byteLength}` }+ return new Response(streamed(from, to), { status: 206, headers })}/** Someone else saves the document, moving its revision on. */@@ -138,7 +185,17 @@ function cloudServer() {}const client = createCloudAPIClient('https://cloud.test/api', { fetch: api })- return { client, objectFetch, saveElsewhere, objects }+ return {+ client,+ objectFetch,+ saveElsewhere,+ objects,+ fullReads: () => fullReads,+ cancelledReads: () => cancelledReads,+ answerRanges(answer: typeof ranges) {+ ranges = answer+ }+ }}function adapter(server: ReturnType<typeof cloudServer>) {@@ -215,4 +272,45 @@ describe('Cloud storage adapter', () => {server.objects.set(saved.revision ?? '', new Uint8Array([9, 9, 9]))await expect(storage.getDocument(id)).rejects.toThrow('does not match')})++ test('reads a document’s preview without downloading the whole file', async () => {+ const server = cloudServer()+ const storage = adapter(server)+ const id = crypto.randomUUID()+ const figBytes = new Uint8Array(readFileSync('tests/fixtures/gold-preview.fig'))+ await storage.putDocument(id, figBytes, { name: 'Preview', updatedAt: '' })+ const thumbnail = await storage.getThumbnail?.(id)+ expect(thumbnail?.subarray(0, 8)).toEqual(+ new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])+ )+ expect(server.fullReads()).toBe(0)+ })++ test('gives up on a preview when the object store sends the whole file', async () => {+ const server = cloudServer()+ const storage = adapter(server)+ const id = crypto.randomUUID()+ const figBytes = new Uint8Array(readFileSync('tests/fixtures/gold-preview.fig'))+ await storage.putDocument(id, figBytes, { name: 'Preview', updatedAt: '' })+ server.answerRanges('ignored')+ await expect(storage.getThumbnail?.(id) ?? Promise.resolve()).rejects.toThrow('HTTP 200')+ expect(server.cancelledReads()).toBe(1)+ })++ test('takes only the range it asked for, stopping one that runs on', async () => {+ const server = cloudServer()+ const storage = adapter(server)+ const id = crypto.randomUUID()+ const figBytes = new Uint8Array(readFileSync('tests/fixtures/gold-preview.fig'))+ await storage.putDocument(id, figBytes, { name: 'Preview', updatedAt: '' })+ const preview = () => storage.getThumbnail?.(id) ?? Promise.resolve()++ server.answerRanges('oversized')+ await expect(preview()).rejects.toThrow('more than')+ expect(server.cancelledReads()).toBeGreaterThan(0)+ server.answerRanges('short')+ await expect(preview()).rejects.toThrow('sent')+ server.answerRanges('other')+ await expect(preview()).rejects.toThrow('HTTP 206 (bytes')+ })})diff --git a/tests/engine/app/storage/persist.test.ts b/tests/engine/app/storage/persist.test.tsindex 6061844cb..2931e30ff 100644--- a/tests/engine/app/storage/persist.test.ts+++ b/tests/engine/app/storage/persist.test.ts@@ -1,8 +1,14 @@import { describe, expect, test, vi } from 'bun:test'import { readFileSync } from 'node:fs'-import { createMemoryLocalCanvasStore } from '@/app/storage/local-store'-import { persistStorageCanvasLocally } from '@/app/storage/sync/persist'+import {+ createMemoryLocalCanvasStore,+ resetLocalCanvasStoreForTests+} from '@/app/storage/local-store'+import {+ persistStorageCanvasLocally,+ seedStorageCanvasFromRemote+} from '@/app/storage/sync/persist'describe('local-first storage persistence', () => {test('writes document bytes before enqueueing remote synchronization', async () => {@@ -53,4 +59,24 @@ describe('local-first storage persistence', () => {new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))})++ test('keeps the preview of a downloaded document', async () => {+ const store = createMemoryLocalCanvasStore()+ resetLocalCanvasStoreForTests(store)+ try {+ await seedStorageCanvasFromRemote({+ providerId: 'cloud',+ canvasId: 'canvas-downloaded',+ name: 'Downloaded design',+ updatedAt: '2026-10-19T00:00:00.000Z',+ figBytes: new Uint8Array(readFileSync('tests/fixtures/gold-preview.fig'))+ })+ const thumbnail = await store.readThumb('canvas-downloaded')+ expect(thumbnail?.subarray(0, 8)).toEqual(+ new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])+ )+ } finally {+ resetLocalCanvasStoreForTests()+ }+ })})