Skip to content

AI-native design editor. Open-source Figma alternative.

fix(storage): reconnect to IndexedDB once the browser closes the connection (#1081)

Danila Poyarkovaa739bde5eb6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 14ba41dd0..32579344e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -181,6 +181,7 @@
### Fixed
+- Crash recovery, chat history, diagnostics, local files, libraries, saved credentials, and the sync outbox keep saving after Safari suspends the tab. Safari closes their IndexedDB connections without telling the page, and every later write failed with "The database connection is closing" until the page was reloaded.
- HTML, Tailwind JSX, and Vue and React exports keep a text's character styles as spans, its lists as nested lists with Figma's markers, its paragraph spacing and first-line indent, and its decoration style, colour, thickness, offset, and skip ink, where they wrote the whole text in one style. Importing HTML reads them back: inline formatting and box-less paragraphs, headings, and lists join into one text layer.
- Underlines and strikethroughs are drawn where and as Figma draws them, from the font's own metrics: underlines break around descenders, dotted ones are round dots, and a set offset or thickness is kept, in reopened `.fig` files too, which drew no strikethroughs and misplaced the other styles. Text saved to `.fig` or copied to Figma keeps its decorations there, where Figma showed underlined text without them and underlined text over several lines not at all.
- Text that mixes font sizes keeps its auto line height when a `.fig` file OpenPencil saved is reopened. Every line took the height of the first, which pushed later lines down and cut them off.
diff --git a/src/app/ai/chat/history/idb.ts b/src/app/ai/chat/history/idb.ts
index d8a93e14e..e99c426cb 100644
--- a/src/app/ai/chat/history/idb.ts
+++ b/src/app/ai/chat/history/idb.ts
@@ -1,6 +1,6 @@
import type { DBSchema } from 'idb'
-import { APP_DATABASE_NAMES, defineAppDatabase, openAppDatabase } from '@/app/storage/idb'
+import { APP_DATABASE_NAMES, defineAppDatabase, connectAppDatabase } from '@/app/storage/idb'
import { fromStorableBlobs, toStorableBlobs } from './blobs'
import type { Conversation, ConversationMeta, ConversationStore } from './types'
@@ -34,8 +34,8 @@ const definition = defineAppDatabase<ChatDatabase>({
/** Transcript snapshots and Blob previews are committed atomically with their list metadata. */
export function createConversationStore(): ConversationStore {
- let database: ReturnType<typeof openAppDatabase<ChatDatabase>> | undefined
- const getDatabase = () => (database ??= openAppDatabase(definition))
+ const database = connectAppDatabase(definition)
+ const getDatabase = () => database.open()
return {
async list(documentId) {
const db = await getDatabase()
diff --git a/src/app/diagnostics/idb.ts b/src/app/diagnostics/idb.ts
index 5019d16cb..ef4a890e7 100644
--- a/src/app/diagnostics/idb.ts
+++ b/src/app/diagnostics/idb.ts
@@ -1,6 +1,6 @@
import type { DBSchema } from 'idb'
-import { APP_DATABASE_NAMES, defineAppDatabase, openAppDatabase } from '@/app/storage/idb'
+import { APP_DATABASE_NAMES, defineAppDatabase, connectAppDatabase } from '@/app/storage/idb'
import { getDiagnosticsRetention, type DiagnosticsRetention } from './settings'
import type { DiagnosticCategory, DiagnosticEvent } from './types'
@@ -37,10 +37,10 @@ export type DiagnosticsStore = {
}
export function createIDBDiagnosticsStore(): DiagnosticsStore {
- const database = openAppDatabase(diagnosticsDatabase)
+ const database = connectAppDatabase(diagnosticsDatabase)
async function prune(retention: DiagnosticsRetention): Promise<void> {
- const db = await database
+ const db = await database.open()
const transaction = db.transaction('events', 'readwrite')
const keys = await transaction.store.index('by-timestamp').getAllKeys()
for (const key of keys.slice(0, Math.max(0, keys.length - retention))) {
@@ -51,18 +51,18 @@ export function createIDBDiagnosticsStore(): DiagnosticsStore {
return {
async record(event) {
- const db = await database
+ const db = await database.open()
const transaction = db.transaction('events', 'readwrite')
await transaction.store.put(event)
await transaction.done
await prune(getDiagnosticsRetention())
},
async list() {
- return (await (await database).getAllFromIndex('events', 'by-timestamp')).reverse()
+ return (await (await database.open()).getAllFromIndex('events', 'by-timestamp')).reverse()
},
prune,
async clear() {
- await (await database).clear('events')
+ await (await database.open()).clear('events')
}
}
}
diff --git a/src/app/document/recovery/idb.ts b/src/app/document/recovery/idb.ts
index ac4b9364e..b9529f07e 100644
--- a/src/app/document/recovery/idb.ts
+++ b/src/app/document/recovery/idb.ts
@@ -10,7 +10,7 @@ import {
APP_DATABASE_NAMES,
binaryStorage,
defineAppDatabase,
- openAppDatabase,
+ connectAppDatabase,
readStoredBinary,
type StoredBinary
} from '@/app/storage/idb'
@@ -39,16 +39,16 @@ interface RecoveryDatabase extends DBSchema {
}
export function createIdbRecoveryStore(): RecoveryStore {
- const database = openAppDatabase(recoveryDatabase)
+ const database = connectAppDatabase(recoveryDatabase)
return {
async list() {
- const rows = await (await database).getAll('meta')
+ const rows = await (await database.open()).getAll('meta')
return rows.toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt))
},
async read(id: string) {
- const db = await database
+ const db = await database.open()
const transaction = db.transaction(['meta', 'fig'])
const [metadata, stored] = await Promise.all([
transaction.objectStore('meta').get(id),
@@ -60,7 +60,7 @@ export function createIdbRecoveryStore(): RecoveryStore {
},
async write(input: RecoverySnapshotInput) {
- const db = await database
+ const db = await database.open()
const storeBinary = await binaryStorage()
const transaction = db.transaction(['meta', 'fig'], 'readwrite')
const metadata: RecoverySnapshotMeta = {
@@ -79,7 +79,7 @@ export function createIdbRecoveryStore(): RecoveryStore {
},
async remove(id: string) {
- const db = await database
+ const db = await database.open()
const transaction = db.transaction(['meta', 'fig'], 'readwrite')
await Promise.all([
transaction.objectStore('meta').delete(id),
@@ -89,7 +89,7 @@ export function createIdbRecoveryStore(): RecoveryStore {
},
async clear() {
- const db = await database
+ const db = await database.open()
const transaction = db.transaction(['meta', 'fig'], 'readwrite')
await Promise.all([
transaction.objectStore('meta').clear(),
diff --git a/src/app/libraries/catalog/local.ts b/src/app/libraries/catalog/local.ts
index 76e78b642..8daf3dfb6 100644
--- a/src/app/libraries/catalog/local.ts
+++ b/src/app/libraries/catalog/local.ts
@@ -1,4 +1,4 @@
-import type { DBSchema, IDBPDatabase } from 'idb'
+import type { DBSchema } from 'idb'
import type {
ComponentLibraryRevision,
@@ -13,7 +13,12 @@ import {
serializeLibraryRevision
} from '@open-pencil/core/library'
-import { APP_DATABASE_NAMES, defineAppDatabase, openAppDatabase } from '@/app/storage/idb'
+import {
+ APP_DATABASE_NAMES,
+ connectAppDatabase,
+ defineAppDatabase,
+ type AppDatabase
+} from '@/app/storage/idb'
const DATABASE_NAME = APP_DATABASE_NAMES.libraries
@@ -54,18 +59,18 @@ interface LocalLibraryDatabase extends DBSchema {
}
export class LocalLibraryCatalog implements LibraryCatalog {
- readonly #database: Promise<IDBPDatabase<LocalLibraryDatabase>>
+ readonly #database: AppDatabase<LocalLibraryDatabase>
constructor(databaseName = DATABASE_NAME) {
- this.#database = openAppDatabase({ ...libraryDatabase, name: databaseName })
+ this.#database = connectAppDatabase({ ...libraryDatabase, name: databaseName })
}
async listLibraries(): Promise<LibrarySummary[]> {
- return (await this.#database).getAll('latest')
+ return (await this.#database.open()).getAll('latest')
}
async getRevision(libraryId: string, revisionId?: string): Promise<ComponentLibraryRevision> {
- const database = await this.#database
+ const database = await this.#database.open()
const resolvedRevisionId =
revisionId ?? (await database.get('latest', libraryId))?.latestRevisionId
const stored = resolvedRevisionId
@@ -77,7 +82,7 @@ export class LocalLibraryCatalog implements LibraryCatalog {
}
async cacheRevision(revision: ComponentLibraryRevision, updateLatest = true): Promise<void> {
- const database = await this.#database
+ const database = await this.#database.open()
const transaction = database.transaction(['latest', 'revisions'], 'readwrite')
const manifest = revision.manifest
await transaction.objectStore('revisions').put({
@@ -103,7 +108,7 @@ export class LocalLibraryCatalog implements LibraryCatalog {
async publishRevision(input: PublishLibraryInput): Promise<ComponentLibraryRevision> {
const revision = await createLibraryRevision(input)
const serializedRevision = serializeLibraryRevision(revision)
- const database = await this.#database
+ const database = await this.#database.open()
const transaction = database.transaction(['latest', 'revisions'], 'readwrite')
const latest = await transaction.objectStore('latest').get(input.libraryId)
if ((input.previousRevisionId ?? null) !== (latest?.latestRevisionId ?? null)) {
diff --git a/src/app/settings/credentials/browser.ts b/src/app/settings/credentials/browser.ts
index bfc45f086..47dcb8ad0 100644
--- a/src/app/settings/credentials/browser.ts
+++ b/src/app/settings/credentials/browser.ts
@@ -8,7 +8,12 @@ import type {
CredentialStoreAvailability
} from '@/app/settings/credentials/types'
import { CredentialStoreError } from '@/app/settings/credentials/types'
-import { APP_DATABASE_NAMES, defineAppDatabase, openAppDatabase } from '@/app/storage/idb'
+import {
+ APP_DATABASE_NAMES,
+ connectAppDatabase,
+ defineAppDatabase,
+ type AppDatabase
+} from '@/app/storage/idb'
const credentialDatabase = defineAppDatabase<CredentialDatabase>({
name: APP_DATABASE_NAMES.credentials,
@@ -52,16 +57,16 @@ interface CredentialDatabase extends DBSchema {
export class BrowserCredentialStore implements CredentialStore {
readonly backend = 'browser' as const
- readonly #database: Promise<IDBPDatabase<CredentialDatabase>>
+ readonly #database: AppDatabase<CredentialDatabase>
#masterKeyPromise?: Promise<CryptoKey>
constructor() {
- this.#database = openAppDatabase(credentialDatabase)
+ this.#database = connectAppDatabase(credentialDatabase)
}
async availability(): Promise<CredentialStoreAvailability> {
try {
- await this.#database
+ await this.#database.open()
return 'available'
} catch {
return 'unavailable'
@@ -75,7 +80,7 @@ export class BrowserCredentialStore implements CredentialStore {
async read(reference: CredentialRef): Promise<string | null> {
const key = credentialKey(reference)
try {
- const database = await this.#database
+ const database = await this.#database.open()
const record = await database.get('credentials', key)
if (!record) return null
@@ -95,7 +100,7 @@ export class BrowserCredentialStore implements CredentialStore {
validateCredentialValue(value)
const key = credentialKey(reference)
try {
- const database = await this.#database
+ const database = await this.#database.open()
const masterKey = await this.#masterKey(database)
const iv = ownedBuffer(crypto.getRandomValues(new Uint8Array(IV_LENGTH)))
const ciphertext = await crypto.subtle.encrypt(
@@ -111,7 +116,7 @@ export class BrowserCredentialStore implements CredentialStore {
async remove(reference: CredentialRef): Promise<void> {
try {
- const database = await this.#database
+ const database = await this.#database.open()
await database.delete('credentials', credentialKey(reference))
} catch (error) {
throw this.#normalizeError(error)
diff --git a/src/app/storage/idb/client.ts b/src/app/storage/idb/client.ts
index d4a754aa6..471299a5f 100644
--- a/src/app/storage/idb/client.ts
+++ b/src/app/storage/idb/client.ts
@@ -13,9 +13,61 @@ export function defineAppDatabase<Database extends DBSchema>(
return definition
}
-/** Open a typed app database through the shared IndexedDB boundary. */
-export function openAppDatabase<Database extends DBSchema>(
+/** A typed app database whose connection is opened again once the browser closes it. */
+export interface AppDatabase<Database extends DBSchema> {
+ /** An open connection: the one in use while it still takes transactions, or a new one. */
+ open(): Promise<IDBPDatabase<Database>>
+}
+
+/**
+ * Whether a connection still takes transactions. A browser can close one without telling the
+ * page, as WebKit does when it suspends a page; every transaction then throws InvalidStateError
+ * ("The database connection is closing").
+ */
+function takesTransactions<Database extends DBSchema>(database: IDBPDatabase<Database>): boolean {
+ const [store] = database.objectStoreNames
+ if (!store) return true
+ try {
+ database.transaction(store)
+ return true
+ } catch (error) {
+ if (error instanceof DOMException && error.name === 'InvalidStateError') return false
+ throw error
+ }
+}
+
+/**
+ * Connect to a typed app database through the shared IndexedDB boundary. The connection opens on
+ * first use and is kept until it stops taking transactions because the browser closed it; the
+ * next `open` then connects again. It stays open when another tab needs a newer version: this
+ * tab's code cannot reconnect at its older one.
+ */
+export function connectAppDatabase<Database extends DBSchema>(
definition: AppDatabaseDefinition<Database>
-): Promise<IDBPDatabase<Database>> {
- return openDB(definition.name, definition.version, definition.callbacks)
+): AppDatabase<Database> {
+ let connection: Promise<IDBPDatabase<Database>> | undefined
+ const drop = (closed: Promise<IDBPDatabase<Database>>) => {
+ if (connection === closed) connection = undefined
+ }
+ const connect = (): Promise<IDBPDatabase<Database>> => {
+ const opening: Promise<IDBPDatabase<Database>> = openDB(definition.name, definition.version, {
+ ...definition.callbacks,
+ terminated() {
+ drop(opening)
+ definition.callbacks.terminated?.()
+ }
+ })
+ connection = opening
+ opening.catch(() => drop(opening))
+ return opening
+ }
+ return {
+ async open() {
+ const current = connection ?? connect()
+ const database = await current
+ if (takesTransactions(database)) return database
+ drop(current)
+ return connection ?? connect()
+ }
+ }
}
diff --git a/src/app/storage/idb/index.ts b/src/app/storage/idb/index.ts
index 9f5df4c6c..8d1cae3a8 100644
--- a/src/app/storage/idb/index.ts
+++ b/src/app/storage/idb/index.ts
@@ -1,5 +1,5 @@
export { APP_DATABASE_NAMES } from './database-names'
-export { defineAppDatabase, openAppDatabase } from './client'
-export type { AppDatabaseDefinition } from './client'
+export { connectAppDatabase, defineAppDatabase } from './client'
+export type { AppDatabase, 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.ts
index 5c0633db0..dd520ce86 100644
--- a/src/app/storage/local-store/idb.ts
+++ b/src/app/storage/local-store/idb.ts
@@ -1,10 +1,11 @@
-import type { DBSchema, IDBPDatabase } from 'idb'
+import type { DBSchema } from 'idb'
import {
APP_DATABASE_NAMES,
binaryStorage,
+ connectAppDatabase,
defineAppDatabase,
- openAppDatabase,
+ type AppDatabase,
readStoredBinary,
type StoredBinary
} from '@/app/storage/idb'
@@ -41,25 +42,25 @@ interface LocalCanvasDatabase extends DBSchema {
}
}
-function openDatabase(): Promise<IDBPDatabase<LocalCanvasDatabase>> {
- return openAppDatabase(localCanvasDatabase)
+function connectDatabase(): AppDatabase<LocalCanvasDatabase> {
+ return connectAppDatabase(localCanvasDatabase)
}
/** IndexedDB-backed local canvas store (meta + fig/thumb blobs). */
export function createIdbLocalCanvasStore(): LocalCanvasStore {
- const database = openDatabase()
+ const database = connectDatabase()
async function readBinary(storeName: 'fig' | 'thumb', id: string): Promise<Uint8Array | null> {
- return readStoredBinary(await (await database).get(storeName, id))
+ return readStoredBinary(await (await database.open()).get(storeName, id))
}
return {
async listMetas(includeTombstones = false) {
- return sortAndFilterMetas(await (await database).getAll('meta'), includeTombstones)
+ return sortAndFilterMetas(await (await database.open()).getAll('meta'), includeTombstones)
},
async getMeta(id: string) {
- return (await (await database).get('meta', id)) ?? null
+ return (await (await database.open()).get('meta', id)) ?? null
},
async readFig(id: string) {
@@ -72,7 +73,7 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {
async writeCanvas(input: LocalCanvasWriteInput) {
const storeBinary = await binaryStorage()
- const transaction = (await database).transaction(['meta', 'fig', 'thumb'], 'readwrite')
+ const transaction = (await database.open()).transaction(['meta', 'fig', 'thumb'], 'readwrite')
const figStore = transaction.objectStore('fig')
const thumbStore = transaction.objectStore('thumb')
const metaStore = transaction.objectStore('meta')
@@ -98,7 +99,7 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {
},
async upsertIndexMeta(input) {
- const transaction = (await database).transaction('meta', 'readwrite')
+ const transaction = (await database.open()).transaction('meta', 'readwrite')
const store = transaction.objectStore('meta')
const existing = (await store.get(input.id)) ?? null
const meta = buildIndexMeta(input, existing)
@@ -109,7 +110,7 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {
async writeThumb(id: string, thumbBytes: Uint8Array) {
const storeBinary = await binaryStorage()
- const transaction = (await database).transaction(['meta', 'thumb'], 'readwrite')
+ const transaction = (await database.open()).transaction(['meta', 'thumb'], 'readwrite')
const metaStore = transaction.objectStore('meta')
const existing = await metaStore.get(id)
if (!existing) {
@@ -126,7 +127,7 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {
},
async updateMeta(id: string, patch: Partial<LocalCanvasMeta>, options) {
- const transaction = (await database).transaction('meta', 'readwrite')
+ const transaction = (await database.open()).transaction('meta', 'readwrite')
const store = transaction.objectStore('meta')
const existing = await store.get(id)
if (
@@ -151,7 +152,7 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {
},
async clearFig(id: string) {
- const transaction = (await database).transaction(['meta', 'fig'], 'readwrite')
+ const transaction = (await database.open()).transaction(['meta', 'fig'], 'readwrite')
const metaStore = transaction.objectStore('meta')
const existing = await metaStore.get(id)
if (!existing) {
@@ -166,7 +167,7 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {
},
async remove(id: string) {
- const transaction = (await database).transaction(['meta', 'fig', 'thumb'], 'readwrite')
+ const transaction = (await database.open()).transaction(['meta', 'fig', 'thumb'], 'readwrite')
await Promise.all([
transaction.objectStore('meta').delete(id),
transaction.objectStore('fig').delete(id),
@@ -176,7 +177,7 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {
},
async clearAll() {
- const transaction = (await database).transaction(['meta', 'fig', 'thumb'], 'readwrite')
+ const transaction = (await database.open()).transaction(['meta', 'fig', 'thumb'], 'readwrite')
await Promise.all([
transaction.objectStore('meta').clear(),
transaction.objectStore('fig').clear(),
diff --git a/src/app/storage/sync/outbox.ts b/src/app/storage/sync/outbox.ts
index 87623ba0f..59b11080e 100644
--- a/src/app/storage/sync/outbox.ts
+++ b/src/app/storage/sync/outbox.ts
@@ -1,6 +1,6 @@
import type { DBSchema } from 'idb'
-import { APP_DATABASE_NAMES, defineAppDatabase, openAppDatabase } from '@/app/storage/idb'
+import { APP_DATABASE_NAMES, defineAppDatabase, connectAppDatabase } from '@/app/storage/idb'
import { makeJobId, supersedePutCanvasJobs, type OutboxJob } from '@/app/storage/sync/types'
const STORE = 'jobs'
@@ -41,8 +41,8 @@ export type Outbox = {
clear(): Promise<void>
}
-function openDatabase() {
- return openAppDatabase(outboxDatabase)
+function connectDatabase() {
+ return connectAppDatabase(outboxDatabase)
}
function buildJob(partial: OutboxEnqueueInput): OutboxJob {
@@ -98,11 +98,11 @@ export function createMemoryOutbox(): Outbox {
}
export function createIdbOutbox(): Outbox {
- const database = openDatabase()
+ const database = connectDatabase()
return {
async list() {
- const all = await (await database).getAll(STORE)
+ const all = await (await database.open()).getAll(STORE)
return all.sort((left, right) => left.createdAt - right.createdAt)
},
@@ -110,7 +110,7 @@ export function createIdbOutbox(): Outbox {
const job = buildJob(partial)
// Read and write in ONE transaction so concurrent enqueues can't compute
// supersession from the same stale snapshot (duplicate/stale jobs).
- const transaction = (await database).transaction(STORE, 'readwrite')
+ const transaction = (await database.open()).transaction(STORE, 'readwrite')
const store = transaction.objectStore(STORE)
const existing = await store.getAll()
const next = withJobQueued(existing, job)
@@ -125,15 +125,15 @@ export function createIdbOutbox(): Outbox {
},
async update(job) {
- await (await database).put(STORE, job)
+ await (await database.open()).put(STORE, job)
},
async remove(id) {
- await (await database).delete(STORE, id)
+ await (await database.open()).delete(STORE, id)
},
async clear() {
- await (await database).clear(STORE)
+ await (await database.open()).clear(STORE)
}
}
}
diff --git a/tests/app/storage/idb/client.test.ts b/tests/app/storage/idb/client.test.ts
new file mode 100644
index 000000000..1ff9c6f87
--- /dev/null
+++ b/tests/app/storage/idb/client.test.ts
@@ -0,0 +1,44 @@
+import 'fake-indexeddb/auto'
+import { expect, test } from 'bun:test'
+
+import type { DBSchema } from 'idb'
+
+import { connectAppDatabase, defineAppDatabase } from '@/app/storage/idb'
+
+interface NotesDatabase extends DBSchema {
+ notes: { key: string; value: string }
+}
+
+function notesDatabase(name: string) {
+ return defineAppDatabase<NotesDatabase>({
+ name,
+ version: 1,
+ callbacks: {
+ upgrade(database) {
+ database.createObjectStore('notes')
+ }
+ }
+ })
+}
+
+test('the same connection serves every use while it is open', async () => {
+ const database = connectAppDatabase(notesDatabase('reuse'))
+ expect(await database.open()).toBe(await database.open())
+})
+
+test('a connection the browser closed is replaced on the next use', async () => {
+ const database = connectAppDatabase(notesDatabase('reconnect'))
+ const first = await database.open()
+ await first.put('notes', 'kept', 'a')
+ // As WebKit does when it suspends a page: the page is not told, every transaction is refused.
+ first.close()
+ expect(() => first.transaction('notes')).toThrow(
+ expect.objectContaining({ name: 'InvalidStateError' })
+ )
+
+ const second = await database.open()
+ expect(second).not.toBe(first)
+ expect(await second.get('notes', 'a')).toBe('kept')
+ await second.put('notes', 'written', 'b')
+ expect(await second.get('notes', 'b')).toBe('written')
+})