AI-native design editor. Open-source Figma alternative.
fix(ai): keep saving chat history in Safari Private Browsing (#920)
Danila Poyarkov710e1a3ac158
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b437a85ed..ce22430b3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -98,6 +98,7 @@### Fixed+- Keep saving AI chat history in Safari Private Browsing after a message with an image or a reply that changed the document. Safari cannot store image data that way in a private window, so the conversation stopped saving from that point and showed "Chat history could not be saved".- `figma.combineAsVariants` derives variant properties from components named as Figma names variants, such as `State=On, Size=Large`, as Combine as variants in the editor now does too; before, only slash-separated names gave the set any properties.- HTML and Tailwind export place layers of frames without auto layout at their coordinates instead of stacking them, leave the size of hugging auto layout frames and auto-sizing text to their content, and round ellipses.- Show the blinking caret in a new, empty text layer before the first character is typed.diff --git a/src/app/ai/chat/history/blobs.ts b/src/app/ai/chat/history/blobs.tsnew file mode 100644index 000000000..ec2e7b322--- /dev/null+++ b/src/app/ai/chat/history/blobs.ts@@ -0,0 +1,37 @@+import { isPlainObject } from 'es-toolkit/predicate'+import * as v from 'valibot'++/**+ * WebKit's IndexedDB cannot store Blobs in private contexts, such as Safari Private Browsing,+ * and aborts the whole write ("Error preparing Blob/File data to be stored in object store"),+ * so attachment previews and tool change images would stop every later save. Conversations+ * are stored with each Blob as its type and bytes instead, which every engine can store.+ */+const StoredBlob = v.object({+ storedBlob: v.literal(true),+ type: v.string(),+ bytes: v.instance(ArrayBuffer)+})++/** `value` with every Blob in it, at any depth of arrays and plain objects, as its bytes. */+export async function toStorableBlobs(value: unknown): Promise<unknown> {+ if (value instanceof Blob) {+ return { storedBlob: true, type: value.type, bytes: await value.arrayBuffer() }+ }+ if (Array.isArray(value)) return Promise.all(value.map(toStorableBlobs))+ if (!isPlainObject(value)) return value+ const entries = await Promise.all(+ Object.entries(value).map(async ([key, entry]) => [key, await toStorableBlobs(entry)] as const)+ )+ return Object.fromEntries(entries)+}++/** The inverse of `toStorableBlobs`; Blobs stored before it existed are kept as they are. */+export function fromStorableBlobs(value: unknown): unknown {+ if (v.is(StoredBlob, value)) return new Blob([value.bytes], { type: value.type })+ if (Array.isArray(value)) return value.map(fromStorableBlobs)+ if (!isPlainObject(value)) return value+ return Object.fromEntries(+ Object.entries(value).map(([key, entry]) => [key, fromStorableBlobs(entry)])+ )+}diff --git a/src/app/ai/chat/history/idb.ts b/src/app/ai/chat/history/idb.tsindex 809e4215b..d8a93e14e 100644--- a/src/app/ai/chat/history/idb.ts+++ b/src/app/ai/chat/history/idb.ts@@ -2,11 +2,13 @@ import type { DBSchema } from 'idb'import { APP_DATABASE_NAMES, defineAppDatabase, openAppDatabase } from '@/app/storage/idb'+import { fromStorableBlobs, toStorableBlobs } from './blobs'import type { Conversation, ConversationMeta, ConversationStore } from './types'interface ChatDatabase extends DBSchema {conversations: { key: string; value: ConversationMeta; indexes: { document: string } }- messages: { key: string; value: Conversation['messages'] }+ /** `Conversation['messages']` with each Blob stored as bytes (`./blobs`). */+ messages: { key: string; value: unknown }files: { key: string; value: FileSystemFileHandle }deleted: { key: string; value: true }selected: { key: string; value: string }@@ -48,10 +50,15 @@ export function createConversationStore(): ConversationStore {const meta = await transaction.objectStore('conversations').get(id)const messages = await transaction.objectStore('messages').get(id)await transaction.done- return meta ? { ...meta, messages: messages ?? [] } : null+ if (!meta) return null+ // Written only by `write` below, from `Conversation['messages']`.+ const restored = fromStorableBlobs(messages ?? []) as Conversation['messages']+ return { ...meta, messages: restored }},async write(conversation) {const { messages, ...meta } = conversation+ // Before the transaction opens: awaiting anything but its own requests would end it.+ const stored = await toStorableBlobs(messages)const transaction = (await getDatabase()).transaction(['conversations', 'messages', 'deleted'],'readwrite'@@ -71,7 +78,7 @@ export function createConversationStore(): ConversationStore {meta.titleSource = 'manual'}await transaction.objectStore('conversations').put(meta)- await transaction.objectStore('messages').put(messages, meta.id)+ await transaction.objectStore('messages').put(stored, meta.id)await transaction.done},async rename(id, title) {diff --git a/tests/app/ai/chat/history/blobs.test.ts b/tests/app/ai/chat/history/blobs.test.tsnew file mode 100644index 000000000..cb457aa18--- /dev/null+++ b/tests/app/ai/chat/history/blobs.test.ts@@ -0,0 +1,45 @@+import { describe, expect, test } from 'bun:test'++import { fromStorableBlobs, toStorableBlobs } from '@/app/ai/chat/history/blobs'++function containsBlob(value: unknown): boolean {+ if (value instanceof Blob) return true+ if (Array.isArray(value)) return value.some(containsBlob)+ if (value && typeof value === 'object') return Object.values(value).some(containsBlob)+ return false+}++const messages = () => [+ {+ message: { id: 'user', role: 'user', parts: [{ type: 'text', text: 'Hero' }] },+ attachments: [{ id: 'image', preview: new Blob(['image'], { type: 'image/png' }) }],+ toolChanges: [{ images: { before: new Blob(['before']), after: null, highlight: null } }]+ }+]++describe('conversation Blobs in storage', () => {+ test('stores no Blob at any depth, so private WebKit contexts can store it', async () => {+ const stored = await toStorableBlobs(messages())+ expect(containsBlob(stored)).toBe(false)+ })++ test('restores each Blob with its bytes and type, and leaves other values alone', async () => {+ const restored = fromStorableBlobs(await toStorableBlobs(messages()))+ expect(restored).toMatchObject([+ {+ message: { id: 'user', parts: [{ text: 'Hero' }] },+ toolChanges: [{ images: { after: null, highlight: null } }]+ }+ ])+ const [entry] = restored as ReturnType<typeof messages>+ expect(entry.attachments[0].preview.type).toBe('image/png')+ expect(await entry.attachments[0].preview.text()).toBe('image')+ expect(await entry.toolChanges[0].images.before?.text()).toBe('before')+ })++ test('keeps Blobs saved before conversion as they are', async () => {+ const blob = new Blob(['old'])+ const [restored] = fromStorableBlobs([blob]) as Blob[]+ expect(restored).toBe(blob)+ })+})diff --git a/tests/e2e/chat/history-save.webkit.spec.ts b/tests/e2e/chat/history-save.webkit.spec.tsnew file mode 100644index 000000000..904ba1da1--- /dev/null+++ b/tests/e2e/chat/history-save.webkit.spec.ts@@ -0,0 +1,35 @@+import { expect, test } from '#tests/helpers/chat/fixture'++const IMAGE = 'tests/fixtures/vectorize/pilot_avatar.png'++// Playwright's WebKit contexts are private, like Safari Private Browsing, where IndexedDB+// cannot store Blobs; a conversation with an image preview must still save.+test('a conversation with an image keeps saving in a private WebKit context', async ({+ configuredChat: chat+}) => {+ await chat.input.fill('Use this image for the hero')+ const chooser = chat.page.waitForEvent('filechooser')+ await chat.page.getByRole('button', { name: 'Attach images' }).click()+ await (await chooser).setFiles([IMAGE])+ await chat.sendButton.click()+ await expect(+ chat.userMessage().getByRole('button', { name: 'View attachment pilot_avatar.png' })+ ).toBeVisible()++ await chat.submit('And a caption below it')+ await expect(chat.assistantMessage()).toBeVisible()++ const storedTexts = () =>+ chat.page.evaluate(async () => {+ const historyPath = '/src/app/ai/chat/history/idb.ts'+ const { createConversationStore } = await import(historyPath)+ const store = createConversationStore()+ const [latest] = await store.list(undefined)+ const conversation = latest ? await store.read(latest.id) : null+ return (conversation?.messages ?? []).map(+ (entry: { displayText?: string }) => entry.displayText ?? ''+ )+ })+ await expect.poll(storedTexts).toContain('And a caption below it')+ await expect(chat.page.getByText(/Chat history could not be saved/)).toHaveCount(0)+})