AI-native design editor. Open-source Figma alternative.
fix(storage): store binary IndexedDB values in a form each browser keeps (#996)
Danila Poyarkovbb01da4aa457
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c63391157..b914baeaf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -141,7 +141,8 @@- Undo a change to a property that drives several layers of an instance on all of them, and show an instance's value on a layer linked to that property after the instance was made.- Open S3 storage documents and show their previews on servers that answer a byte-range read with `200` instead of `206`, such as `rclone serve s3`. Previews failed to load, and the browser cached the partial reply as the whole document, so opening it failed with "Invalid fig-kiwi container". Storage requests now skip the browser cache, and a `200` whose `Content-Range` matches the request is accepted.- Keep a layer's `.fig` ID the same across saves (#890). Layers created in OpenPencil were numbered in tree order on each save until the file was reopened, so inserting a layer shifted the IDs of the layers after it; variable collections and modes could also be renumbered.-- Store crash recovery snapshots of any size. Snapshots of documents over 127 MiB failed to save to IndexedDB and stayed in memory for the rest of the session.+- Store crash recovery snapshots of documents over 127 MiB, and in Safari Private Browsing. Those snapshots failed to save to IndexedDB and stayed in memory for the rest of the session.+- Keep browser-stored documents over 127 MiB: Chromium refused to save them to IndexedDB. Binary data is stored as Blobs where the browser allows it, and as plain bytes in Safari Private Browsing, where IndexedDB cannot store Blobs.- Keep an opened `.fig` file saved until it is edited. Laying out its first page, which recomputes auto-layout sizes and positions, and showing another page for the first time, which loads its layers from the file, marked it unsaved, so closing it asked to save changes nobody made.- Save variable edits to an opened `.fig` file. After changing only variables, variable collections, or the document's color profile or libraries, saving wrote the original file unchanged.- Run crash recovery and autosave after edits, not whenever the canvas redraws. Opening a document, laying out a page, or loading a font started a recovery snapshot or an autosave, which encoded the whole document again once another page had loaded. In Safari, where every opened file gets recovery snapshots, a large page froze the browser for minutes after it first appeared.diff --git a/src/AGENTS.md b/src/AGENTS.mdindex 7e4f72ead..0b613beda 100644--- a/src/AGENTS.md+++ b/src/AGENTS.md@@ -17,6 +17,7 @@ Root Tauri/Vite app. Services and state live under `src/app/**`, views under `sr- Credential persistence lives under `src/app/settings/credentials/`. Settings components receive `CredentialManager` and may inspect status, replace, or clear; runtime adapters receive `CredentialResolver` and resolve secrets at operation time. Components must not read saved secrets or keep them in long-lived reactive refs; keep newly entered secrets short-lived. Non-secret provider preferences stay in normal settings storage.- Tauri stores secrets in the system credential store through `desktop/src/credentials.rs`; browsers default to WebCrypto-encrypted IndexedDB and may explicitly opt out to session-only memory. Native failures must never silently fall back to browser or plaintext storage. New integration credentials use stable `CredentialRef` values and join the unified Settings surface rather than feature-local key forms.- Storage-provider schemas and runtime adapters live under `src/app/integrations/storage/`; non-secret preferences and credential references stay separate. Local-first document caching and outbox synchronization live under `src/app/storage/`. A remote storage binding augments document source state and must not replace local file identity.+- IndexedDB binary rows are written in the form `binaryStorage()` returns, taken before the transaction opens, and read with `readStoredBinary()`. Chromium caps a single byte array at 127 MiB, and WebKit cannot store Blobs in private contexts (`tests/e2e/storage/binary.webkit.spec.ts`).## AI, ACP, automation, collaborationdiff --git a/src/app/document/recovery/idb.ts b/src/app/document/recovery/idb.tsindex 1e074b5b4..ac4b9364e 100644--- a/src/app/document/recovery/idb.ts+++ b/src/app/document/recovery/idb.ts@@ -6,7 +6,14 @@ import type {RecoverySnapshotMeta,RecoveryStore} from '@/app/document/recovery/types'-import { APP_DATABASE_NAMES, defineAppDatabase, openAppDatabase } from '@/app/storage/idb'+import {+ APP_DATABASE_NAMES,+ binaryStorage,+ defineAppDatabase,+ openAppDatabase,+ readStoredBinary,+ type StoredBinary+} from '@/app/storage/idb'const recoveryDatabase = defineAppDatabase<RecoveryDatabase>({name: APP_DATABASE_NAMES.recovery,@@ -27,30 +34,10 @@ interface RecoveryDatabase extends DBSchema {}fig: {key: string- value: StoredFig+ value: StoredBinary}}-/**- * A snapshot as IndexedDB stores it. Chromium refuses a single value over 127 MiB, which a- * document's archive passes easily, but keeps a Blob as a file at any size, and faster.- * Snapshots from earlier versions are byte arrays.- */-type StoredFig = Blob | Uint8Array--/** A Blob of the snapshot without copying it; bytes over a shared buffer are copied first. */-function figBlob(bytes: Uint8Array): Blob {- const plain =- bytes.buffer instanceof ArrayBuffer- ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)- : bytes.slice()- return new Blob([plain])-}--async function figBytesOf(stored: StoredFig): Promise<Uint8Array> {- return stored instanceof Blob ? new Uint8Array(await stored.arrayBuffer()) : stored-}-export function createIdbRecoveryStore(): RecoveryStore {const database = openAppDatabase(recoveryDatabase)@@ -68,13 +55,13 @@ export function createIdbRecoveryStore(): RecoveryStore {transaction.objectStore('fig').get(id)])await transaction.done- return metadata && stored- ? ({ ...metadata, figBytes: await figBytesOf(stored) } satisfies RecoverySnapshot)- : null+ const figBytes = await readStoredBinary(stored)+ return metadata && figBytes ? ({ ...metadata, figBytes } satisfies RecoverySnapshot) : null},async write(input: RecoverySnapshotInput) {const db = await database+ const storeBinary = await binaryStorage()const transaction = db.transaction(['meta', 'fig'], 'readwrite')const metadata: RecoverySnapshotMeta = {id: input.id,@@ -85,7 +72,7 @@ export function createIdbRecoveryStore(): RecoveryStore {}await Promise.all([transaction.objectStore('meta').put(metadata),- transaction.objectStore('fig').put(figBlob(input.figBytes), input.id),+ transaction.objectStore('fig').put(storeBinary(input.figBytes), input.id),transaction.done])return metadatadiff --git a/src/app/storage/idb/binary.ts b/src/app/storage/idb/binary.tsnew file mode 100644index 000000000..2bc561747--- /dev/null+++ b/src/app/storage/idb/binary.ts@@ -0,0 +1,73 @@+import { deleteDB, openDB, type IDBPDatabase } from 'idb'++import { APP_DATABASE_NAMES } from './database-names'++/**+ * Binary values as IndexedDB stores them. Neither form fits every engine: Chromium refuses a+ * single value over 127 MiB but keeps a Blob as a file at any size, and WebKit cannot store a+ * Blob in a private context such as Safari Private Browsing. Writes store Blobs where the engine+ * takes them and byte arrays elsewhere. Rows from earlier versions may be either, or an+ * ArrayBuffer.+ */+export type StoredBinary = Blob | Uint8Array | ArrayBuffer++/** Turns bytes into the value a write stores. */+export type StoreBinary = (bytes: Uint8Array) => StoredBinary++/** The bytes as a view IndexedDB can store; bytes over a shared buffer are copied first. */+function plainBytes(bytes: Uint8Array): Uint8Array<ArrayBuffer> {+ return bytes.buffer instanceof ArrayBuffer+ ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)+ : bytes.slice()+}++const asBlob: StoreBinary = (bytes) => new Blob([plainBytes(bytes)])++/**+ * Whether the engine stores Blobs, found by storing one in a database of its own. WebKit fails a+ * Blob write in a private context with "Error preparing Blob/File data to be stored in object+ * store", and when the transaction holds another pending request it never aborts, blocking+ * every later write to those stores, so an app write cannot try a Blob and fall back. Any failed+ * Blob write means byte arrays; a probe database that cannot open or be removed says nothing+ * about Blobs.+ */+async function probeBlobs(): Promise<boolean> {+ const name = APP_DATABASE_NAMES.blobProbe+ let database: IDBPDatabase+ try {+ database = await openDB(name, 1, {+ upgrade: (upgrading) => upgrading.createObjectStore('probe')+ })+ } catch {+ return true+ }+ try {+ await database.put('probe', new Blob([new Uint8Array(1)]), 'probe')+ return true+ } catch {+ return false+ } finally {+ database.close()+ await deleteDB(name).catch(() => undefined)+ }+}++let blobsStored: Promise<boolean> | undefined++/**+ * The form this engine stores binary values in. Take it before opening the transaction that+ * writes them: waiting on it inside one would let the transaction commit.+ */+export async function binaryStorage(): Promise<StoreBinary> {+ blobsStored ??= probeBlobs()+ return (await blobsStored) ? asBlob : plainBytes+}++/** The bytes of a stored binary value, in any form a version of the app stored. */+export async function readStoredBinary(+ stored: StoredBinary | undefined+): Promise<Uint8Array | null> {+ if (!stored) return null+ if (stored instanceof Blob) return new Uint8Array(await stored.arrayBuffer())+ return stored instanceof ArrayBuffer ? new Uint8Array(stored) : stored+}diff --git a/src/app/storage/idb/database-names.ts b/src/app/storage/idb/database-names.tsindex 5e015157f..bb7e86442 100644--- a/src/app/storage/idb/database-names.ts+++ b/src/app/storage/idb/database-names.ts@@ -6,5 +6,7 @@ export const APP_DATABASE_NAMES = {localCanvas: 'open-pencil-cloud-local',outbox: 'open-pencil-cloud-outbox',recovery: 'open-pencil-recovery',- diagnostics: 'open-pencil-diagnostics'+ diagnostics: 'open-pencil-diagnostics',+ /** Written and deleted once per page, to learn whether the engine stores Blobs. */+ blobProbe: 'open-pencil-blob-probe'} as constdiff --git a/src/app/storage/idb/index.ts b/src/app/storage/idb/index.tsindex 58e93ed53..9f5df4c6c 100644--- a/src/app/storage/idb/index.ts+++ b/src/app/storage/idb/index.ts@@ -1,3 +1,5 @@export { APP_DATABASE_NAMES } from './database-names'export { defineAppDatabase, openAppDatabase } from './client'export type { AppDatabaseDefinition } from './client'+export { binaryStorage, readStoredBinary } from './binary'+export type { StoreBinary, StoredBinary } from './binary'diff --git a/src/app/storage/local-store/idb.ts b/src/app/storage/local-store/idb.tsindex 5e04e8b69..5c0633db0 100644--- a/src/app/storage/local-store/idb.ts+++ b/src/app/storage/local-store/idb.ts@@ -1,6 +1,13 @@import type { DBSchema, IDBPDatabase } from 'idb'-import { APP_DATABASE_NAMES, defineAppDatabase, openAppDatabase } from '@/app/storage/idb'+import {+ APP_DATABASE_NAMES,+ binaryStorage,+ defineAppDatabase,+ openAppDatabase,+ readStoredBinary,+ type StoredBinary+} from '@/app/storage/idb'import { buildIndexMeta, buildWriteMeta, sortAndFilterMetas } from '@/app/storage/local-store/meta'import type { LocalCanvasStore } from '@/app/storage/local-store/store'import type { LocalCanvasMeta, LocalCanvasWriteInput } from '@/app/storage/local-store/types'@@ -19,8 +26,6 @@ const localCanvasDatabase = defineAppDatabase<LocalCanvasDatabase>({}})-type StoredBinary = ArrayBuffer | Uint8Array | Blob-interface LocalCanvasDatabase extends DBSchema {meta: {key: string@@ -36,14 +41,6 @@ interface LocalCanvasDatabase extends DBSchema {}}-/** Stored rows may use older ArrayBuffer/Blob representations. */-async function storedBinaryToBytes(row: StoredBinary | undefined): Promise<Uint8Array | null> {- if (!row) return null- if (row instanceof ArrayBuffer) return new Uint8Array(row)- if (row instanceof Uint8Array) return Uint8Array.from(row)- return new Uint8Array(await row.arrayBuffer())-}-function openDatabase(): Promise<IDBPDatabase<LocalCanvasDatabase>> {return openAppDatabase(localCanvasDatabase)}@@ -53,7 +50,7 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {const database = openDatabase()async function readBinary(storeName: 'fig' | 'thumb', id: string): Promise<Uint8Array | null> {- return storedBinaryToBytes(await (await database).get(storeName, id))+ return readStoredBinary(await (await database).get(storeName, id))}return {@@ -74,6 +71,7 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {},async writeCanvas(input: LocalCanvasWriteInput) {+ const storeBinary = await binaryStorage()const transaction = (await database).transaction(['meta', 'fig', 'thumb'], 'readwrite')const figStore = transaction.objectStore('fig')const thumbStore = transaction.objectStore('thumb')@@ -81,11 +79,11 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {const existing = (await metaStore.get(input.id)) ?? nulllet hasThumb = existing?.hasThumb ?? false- await figStore.put(Uint8Array.from(input.figBytes), input.id)+ await figStore.put(storeBinary(input.figBytes), input.id)if (input.thumbBytes != null) {if (input.thumbBytes.byteLength > 0) {- await thumbStore.put(Uint8Array.from(input.thumbBytes), input.id)+ await thumbStore.put(storeBinary(input.thumbBytes), input.id)hasThumb = true} else {await thumbStore.delete(input.id)@@ -110,6 +108,7 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {},async writeThumb(id: string, thumbBytes: Uint8Array) {+ const storeBinary = await binaryStorage()const transaction = (await database).transaction(['meta', 'thumb'], 'readwrite')const metaStore = transaction.objectStore('meta')const existing = await metaStore.get(id)@@ -117,7 +116,7 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {await transaction.donereturn null}- await transaction.objectStore('thumb').put(Uint8Array.from(thumbBytes), id)+ await transaction.objectStore('thumb').put(storeBinary(thumbBytes), id)// Thumb freshness is tracked by its own outbox job — never demote the// document's syncStatus here (it orphaned rows as 'pending' forever).const meta: LocalCanvasMeta = { ...existing, hasThumb: true }diff --git a/tests/app/storage/idb/binary.test.ts b/tests/app/storage/idb/binary.test.tsnew file mode 100644index 000000000..db4a58e50--- /dev/null+++ b/tests/app/storage/idb/binary.test.ts@@ -0,0 +1,27 @@+import 'fake-indexeddb/auto'+import { describe, expect, test } from 'bun:test'++import { binaryStorage, readStoredBinary } from '@/app/storage/idb'++const bytes = new Uint8Array([1, 2, 3, 4])++describe('IndexedDB binary values', () => {+ test('are stored as Blobs where the engine stores them', async () => {+ const stored = (await binaryStorage())(bytes)+ expect(stored).toBeInstanceOf(Blob)+ expect(await readStoredBinary(stored)).toEqual(bytes)+ })++ test('are stored from bytes over a shared buffer', async () => {+ const shared = new Uint8Array(new SharedArrayBuffer(4))+ shared.set(bytes)+ expect(await readStoredBinary((await binaryStorage())(shared))).toEqual(bytes)+ })++ test('are read in every form earlier versions stored', async () => {+ expect(await readStoredBinary(new Blob([bytes]))).toEqual(bytes)+ expect(await readStoredBinary(bytes)).toEqual(bytes)+ expect(await readStoredBinary(bytes.slice().buffer)).toEqual(bytes)+ expect(await readStoredBinary(undefined)).toBeNull()+ })+})diff --git a/tests/e2e/storage/binary.webkit.spec.ts b/tests/e2e/storage/binary.webkit.spec.tsnew file mode 100644index 000000000..66c3a7d1f--- /dev/null+++ b/tests/e2e/storage/binary.webkit.spec.ts@@ -0,0 +1,58 @@+import { expect, test } from '#tests/e2e/fixtures'++// Playwright's WebKit contexts are private, like Safari Private Browsing, where IndexedDB cannot+// store Blobs; Chromium refuses a single value over 127 MiB unless it is a Blob. Recovery+// snapshots and local documents must store in both.++test('keeps recovery snapshots and local documents in IndexedDB', async ({ page }) => {+ await page.goto('/?test')+ const stored = await page.evaluate(async () => {+ const recoveryPath = '/src/app/document/recovery/idb.ts'+ const localPath = '/src/app/storage/local-store/idb.ts'+ const { createIdbRecoveryStore } = await import(recoveryPath)+ const { createIdbLocalCanvasStore } = await import(localPath)+ const bytes = new Uint8Array([1, 2, 3, 4])++ const recovery = createIdbRecoveryStore()+ await recovery.write({ id: 'binary-probe', documentName: 'Probe', figBytes: bytes })+ const snapshot = await recovery.read('binary-probe')+ await recovery.remove('binary-probe')++ const local = createIdbLocalCanvasStore()+ await local.writeCanvas({+ id: 'binary-probe',+ providerId: 'local',+ name: 'Probe',+ figBytes: bytes,+ thumbBytes: bytes+ })+ await local.writeThumb('binary-probe', new Uint8Array([5, 6]))+ const fig = await local.readFig('binary-probe')+ const thumb = await local.readThumb('binary-probe')+ await local.remove('binary-probe')++ return {+ snapshot: snapshot ? [...snapshot.figBytes] : null,+ fig: fig ? [...fig] : null,+ thumb: thumb ? [...thumb] : null+ }+ })+ expect(stored).toEqual({ snapshot: [1, 2, 3, 4], fig: [1, 2, 3, 4], thumb: [5, 6] })+})++test('keeps a local document over 127 MiB in IndexedDB', async ({ page }) => {+ await page.goto('/?test')+ const stored = await page.evaluate(async () => {+ const localPath = '/src/app/storage/local-store/idb.ts'+ const { createIdbLocalCanvasStore } = await import(localPath)+ const figBytes = new Uint8Array(140 * 1024 * 1024)+ figBytes[figBytes.length - 1] = 7++ const local = createIdbLocalCanvasStore()+ await local.writeCanvas({ id: 'large-probe', providerId: 'local', name: 'Large', figBytes })+ const fig: Uint8Array | null = await local.readFig('large-probe')+ await local.remove('large-probe')+ return fig ? { length: fig.length, last: fig[fig.length - 1] } : null+ })+ expect(stored).toEqual({ length: 140 * 1024 * 1024, last: 7 })+})