Skip to content

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

feat: list unsaved work on Home and ask at start only after a crash (#1668)

Danila Poyarkov05bd7c6b0329
diff --git a/changes/1668/added.md b/changes/1668/added.md
new file mode 100644
index 000000000..b82a90d94
--- /dev/null
+++ b/changes/1668/added.md
@@ -0,0 +1 @@
+- Home lists unsaved work kept from documents closed without saving or open when OpenPencil quit, with a preview of each, in place of the recovery prompt at start.
diff --git a/packages/vue/src/i18n/locales/de/recovery.json b/packages/vue/src/i18n/locales/de/recovery.json
index 56a89c928..827c6f3be 100644
--- a/packages/vue/src/i18n/locales/de/recovery.json
+++ b/packages/vue/src/i18n/locales/de/recovery.json
@@ -1,11 +1,12 @@
{
"preserveUnsavedWork": "Ungespeicherte Arbeit automatisch sichern",
"preserveUnsavedWorkDescription": "Lokale Wiederherstellungskopien speichern, um Dokumente nach einem unerwarteten Beenden wiederherzustellen.",
- "dialogTitle": "Nicht gespeicherte Arbeit wiederherstellen",
- "dialogDescription": "OpenPencil hat Dokumente aus einer vorherigen Sitzung gefunden.",
+ "sectionTitle": "Ungespeicherte Arbeit",
+ "sectionDescription": "Ungespeicherte Änderungen aus Dokumenten, die ohne Speichern geschlossen wurden oder beim Beenden von OpenPencil geöffnet waren. Öffne eines, um weiterzuarbeiten.",
+ "crashNote": "Nach einem Absturz behalten",
"restoreFailed": "Dieses Dokument konnte nicht wiederhergestellt werden.",
+ "discardFailed": "Diese Kopie konnte nicht verworfen werden.",
"settingsTitle": "Wiederherstellung",
"settingsDescription": "Lokale Wiederherstellungskopien für ungespeicherte Dokumente verwalten.",
- "restore": "Wiederherstellen",
"discard": "Verwerfen"
}
diff --git a/packages/vue/src/i18n/locales/es/recovery.json b/packages/vue/src/i18n/locales/es/recovery.json
index 52a9412a0..e70549700 100644
--- a/packages/vue/src/i18n/locales/es/recovery.json
+++ b/packages/vue/src/i18n/locales/es/recovery.json
@@ -1,11 +1,12 @@
{
"preserveUnsavedWork": "Conservar automáticamente el trabajo no guardado",
"preserveUnsavedWorkDescription": "Guarda copias locales para restaurar documentos después de un cierre inesperado.",
- "dialogTitle": "Recuperar trabajo no guardado",
- "dialogDescription": "OpenPencil encontró documentos de una sesión anterior.",
+ "sectionTitle": "Trabajo sin guardar",
+ "sectionDescription": "Cambios sin guardar de documentos cerrados sin guardar o abiertos cuando OpenPencil se cerró. Abre uno para seguir trabajando.",
+ "crashNote": "Conservado tras un cierre inesperado",
"restoreFailed": "No se pudo restaurar este documento.",
+ "discardFailed": "No se pudo descartar esta copia.",
"settingsTitle": "Recuperación",
"settingsDescription": "Controla las copias locales de recuperación de documentos no guardados.",
- "restore": "Restaurar",
"discard": "Descartar"
}
diff --git a/packages/vue/src/i18n/locales/fr/recovery.json b/packages/vue/src/i18n/locales/fr/recovery.json
index cae9d3d6a..5a09b168e 100644
--- a/packages/vue/src/i18n/locales/fr/recovery.json
+++ b/packages/vue/src/i18n/locales/fr/recovery.json
@@ -1,11 +1,12 @@
{
"preserveUnsavedWork": "Conserver automatiquement le travail non enregistré",
"preserveUnsavedWorkDescription": "Stockez des copies locales afin de restaurer les documents après un arrêt inattendu.",
- "dialogTitle": "Récupérer le travail non enregistré",
- "dialogDescription": "OpenPencil a trouvé des documents d’une session précédente.",
+ "sectionTitle": "Travail non enregistré",
+ "sectionDescription": "Modifications non enregistrées de documents fermés sans enregistrer ou ouverts à la fermeture d’OpenPencil. Ouvrez-en un pour continuer à travailler.",
+ "crashNote": "Conservé après un plantage",
"restoreFailed": "Impossible de restaurer ce document.",
+ "discardFailed": "Impossible de supprimer cette copie.",
"settingsTitle": "Récupération",
"settingsDescription": "Gérez les copies locales de récupération des documents non enregistrés.",
- "restore": "Restaurer",
"discard": "Supprimer"
}
diff --git a/packages/vue/src/i18n/locales/it/recovery.json b/packages/vue/src/i18n/locales/it/recovery.json
index a5154c063..3860dca3c 100644
--- a/packages/vue/src/i18n/locales/it/recovery.json
+++ b/packages/vue/src/i18n/locales/it/recovery.json
@@ -1,11 +1,12 @@
{
"preserveUnsavedWork": "Conserva automaticamente il lavoro non salvato",
"preserveUnsavedWorkDescription": "Salva copie locali per ripristinare i documenti dopo una chiusura imprevista.",
- "dialogTitle": "Recupera il lavoro non salvato",
- "dialogDescription": "OpenPencil ha trovato documenti di una sessione precedente.",
+ "sectionTitle": "Lavoro non salvato",
+ "sectionDescription": "Modifiche non salvate di documenti chiusi senza salvare o aperti alla chiusura di OpenPencil. Aprine uno per continuare a lavorare.",
+ "crashNote": "Conservato dopo un arresto anomalo",
"restoreFailed": "Impossibile ripristinare questo documento.",
+ "discardFailed": "Impossibile eliminare questa copia.",
"settingsTitle": "Ripristino",
"settingsDescription": "Gestisci le copie locali di ripristino dei documenti non salvati.",
- "restore": "Ripristina",
"discard": "Scarta"
}
diff --git a/packages/vue/src/i18n/locales/ja/recovery.json b/packages/vue/src/i18n/locales/ja/recovery.json
index 3825f7efc..0eb3d31f9 100644
--- a/packages/vue/src/i18n/locales/ja/recovery.json
+++ b/packages/vue/src/i18n/locales/ja/recovery.json
@@ -1,11 +1,12 @@
{
"preserveUnsavedWork": "未保存の作業を自動的に保持",
"preserveUnsavedWorkDescription": "予期しない終了後にドキュメントを復元できるよう、ローカルコピーを保存します。",
- "dialogTitle": "未保存の作業を復元",
- "dialogDescription": "OpenPencil が前回のセッションのドキュメントを見つけました。",
+ "sectionTitle": "未保存の作業",
+ "sectionDescription": "保存せずに閉じたドキュメントや、OpenPencil の終了時に開いていたドキュメントの未保存の変更です。開くと作業を続けられます。",
+ "crashNote": "クラッシュ後に保持",
"restoreFailed": "このドキュメントを復元できませんでした。",
+ "discardFailed": "このコピーを破棄できませんでした。",
"settingsTitle": "復元",
"settingsDescription": "未保存ドキュメントのローカル復元コピーを管理します。",
- "restore": "復元",
"discard": "破棄"
}
diff --git a/packages/vue/src/i18n/locales/pl/recovery.json b/packages/vue/src/i18n/locales/pl/recovery.json
index 569782c64..edb4cafbc 100644
--- a/packages/vue/src/i18n/locales/pl/recovery.json
+++ b/packages/vue/src/i18n/locales/pl/recovery.json
@@ -1,11 +1,12 @@
{
"preserveUnsavedWork": "Automatycznie zachowuj niezapisaną pracę",
"preserveUnsavedWorkDescription": "Przechowuj lokalne kopie, aby odtworzyć dokumenty po nieoczekiwanym zamknięciu.",
- "dialogTitle": "Odzyskaj niezapisaną pracę",
- "dialogDescription": "OpenPencil znalazł dokumenty z poprzedniej sesji.",
+ "sectionTitle": "Niezapisana praca",
+ "sectionDescription": "Niezapisane zmiany z dokumentów zamkniętych bez zapisywania lub otwartych w chwili zamknięcia OpenPencil. Otwórz jeden, aby kontynuować pracę.",
+ "crashNote": "Zachowano po awarii",
"restoreFailed": "Nie udało się przywrócić tego dokumentu.",
+ "discardFailed": "Nie udało się odrzucić tej kopii.",
"settingsTitle": "Odzyskiwanie",
"settingsDescription": "Zarządzaj lokalnymi kopiami odzyskiwania niezapisanych dokumentów.",
- "restore": "Przywróć",
"discard": "Odrzuć"
}
diff --git a/packages/vue/src/i18n/locales/ru/recovery.json b/packages/vue/src/i18n/locales/ru/recovery.json
index f50d33582..56505e012 100644
--- a/packages/vue/src/i18n/locales/ru/recovery.json
+++ b/packages/vue/src/i18n/locales/ru/recovery.json
@@ -1,11 +1,12 @@
{
"preserveUnsavedWork": "Автоматически сохранять несохранённую работу",
"preserveUnsavedWorkDescription": "Храните локальные копии, чтобы восстановить документы после неожиданного завершения работы.",
- "dialogTitle": "Восстановить несохранённую работу",
- "dialogDescription": "OpenPencil обнаружил документы из предыдущего сеанса.",
+ "sectionTitle": "Несохранённая работа",
+ "sectionDescription": "Несохранённые изменения документов, закрытых без сохранения или открытых в момент завершения OpenPencil. Откройте документ, чтобы продолжить работу.",
+ "crashNote": "Сохранено после сбоя",
"restoreFailed": "Не удалось восстановить этот документ.",
+ "discardFailed": "Не удалось удалить эту копию.",
"settingsTitle": "Восстановление",
"settingsDescription": "Управляйте локальными резервными копиями несохранённых документов.",
- "restore": "Восстановить",
"discard": "Удалить"
}
diff --git a/packages/vue/src/i18n/locales/zh-cn/recovery.json b/packages/vue/src/i18n/locales/zh-cn/recovery.json
index 6f3cabb9c..d937d6a3a 100644
--- a/packages/vue/src/i18n/locales/zh-cn/recovery.json
+++ b/packages/vue/src/i18n/locales/zh-cn/recovery.json
@@ -1,11 +1,12 @@
{
"preserveUnsavedWork": "自动保留未保存的工作",
"preserveUnsavedWorkDescription": "存储本地恢复副本,以便在意外关闭后恢复文档。",
- "dialogTitle": "恢复未保存的工作",
- "dialogDescription": "OpenPencil 找到了上次会话中的文档。",
+ "sectionTitle": "未保存的工作",
+ "sectionDescription": "未保存就关闭的文档,或 OpenPencil 退出时仍打开的文档中未保存的更改。打开一个即可继续工作。",
+ "crashNote": "崩溃后保留",
"restoreFailed": "无法恢复此文档。",
+ "discardFailed": "无法丢弃此副本。",
"settingsTitle": "恢复",
"settingsDescription": "管理未保存文档的本地恢复副本。",
- "restore": "恢复",
"discard": "丢弃"
}
diff --git a/packages/vue/src/i18n/messages/recovery.ts b/packages/vue/src/i18n/messages/recovery.ts
index 00276bb02..f3ad75d52 100644
--- a/packages/vue/src/i18n/messages/recovery.ts
+++ b/packages/vue/src/i18n/messages/recovery.ts
@@ -1,15 +1,17 @@
import { i18n } from '#vue/i18n/create'
export const recoveryMessageDefaults = {
- dialogTitle: 'Recover unsaved work',
- dialogDescription: 'OpenPencil found documents from a previous session.',
+ sectionTitle: 'Unsaved work',
+ sectionDescription:
+ 'Unsaved changes kept from documents closed without saving or open when OpenPencil quit. Open one to keep working on it.',
+ crashNote: 'Kept after a crash',
restoreFailed: 'Could not restore this document.',
+ discardFailed: 'Could not discard this copy.',
settingsTitle: 'Recovery',
settingsDescription: 'Control local crash-recovery copies for unsaved documents.',
preserveUnsavedWork: 'Automatically preserve unsaved work',
preserveUnsavedWorkDescription:
'Store local recovery copies so documents can be restored after an unexpected shutdown.',
- restore: 'Restore',
discard: 'Discard'
} as const
diff --git a/src/App.vue b/src/App.vue
index 600cf4466..11ce2724b 100644
--- a/src/App.vue
+++ b/src/App.vue
@@ -11,6 +11,7 @@ import { useI18n } from '@open-pencil/vue/i18n'
import { startCloud } from '@/app/cloud/integration'
import { useDocumentCloseProtection } from '@/app/document/close/use'
+import { endRecoverySession, startRecoverySession } from '@/app/document/recovery/session'
import { useFollowingEditorStore } from '@/app/editor/active-store'
import { animationsEnabled } from '@/app/shell/motion'
import { useAppTheme } from '@/app/shell/theme'
@@ -23,7 +24,6 @@ import { CloudHosts } from '@/components/cloud/integration'
import UnsavedChangesDialog from '@/components/document/UnsavedChangesDialog.vue'
import PublishLibraryDialog from '@/components/libraries/PublishLibraryDialog.vue'
import LibraryUpdateReviewDialog from '@/components/libraries/review/LibraryUpdateReviewDialog.vue'
-import RecoveryDialog from '@/components/recovery/RecoveryDialog.vue'
import SaveToHost from '@/components/save-to/SaveToHost.vue'
import AISetupDialog from '@/components/settings/ai-setup/AISetupDialog.vue'
import SettingsDialog from '@/components/settings/SettingsDialog.vue'
@@ -47,8 +47,14 @@ provideEditor(useFollowingEditorStore())
useAppTheme()
useDocumentCloseProtection()
useRestartApprovals()
+startRecoverySession()
useEventListener(window, 'pagehide', () => {
void prepareForReload()
+ endRecoverySession()
+})
+// A page restored from the back/forward cache runs on in the session it had.
+useEventListener(window, 'pageshow', (event) => {
+ if (event.persisted) startRecoverySession()
})
onMounted(() => {
@@ -71,7 +77,6 @@ onMounted(() => {
<AISetupDialog />
<SaveToHost />
<CloudHosts />
- <RecoveryDialog />
<UnsavedChangesDialog />
<PublishLibraryDialog />
<LibraryUpdateReviewDialog />
diff --git a/src/app/document/io/source/actions.ts b/src/app/document/io/source/actions.ts
index 54e293830..eca6901df 100644
--- a/src/app/document/io/source/actions.ts
+++ b/src/app/document/io/source/actions.ts
@@ -19,7 +19,7 @@ import { createDocumentRecovery } from '@/app/document/recovery'
import { recoveryEnabled } from '@/app/document/recovery/preferences'
import { storageLocationOf } from '@/app/integrations/storage/location'
import type { StorageDocumentBinding, StorageLocation } from '@/app/integrations/storage/types'
-import { cacheRecentFileCover } from '@/app/recent-files'
+import { cacheRecentFileCover, drawHomeCardCover } from '@/app/recent-files'
import { createCanvasId } from '@/app/storage/id'
import { isTauri } from '@/app/tauri/env'
import { trackDocumentFormat } from '@/app/telemetry'
@@ -105,6 +105,10 @@ export function createDocumentSourceActions({
version: changes.capture,
isEnabled: () => recoveryEnabled.value,
buildFigFile: buildRecoveryFigFile,
+ buildCover: () => {
+ const renderer = getRenderer()
+ return renderer ? drawHomeCardCover(editor.graph, renderer) : null
+ },
hasWritableSource
})
diff --git a/src/app/document/recovery/controller.ts b/src/app/document/recovery/controller.ts
index 7b9129d77..062443a55 100644
--- a/src/app/document/recovery/controller.ts
+++ b/src/app/document/recovery/controller.ts
@@ -1,6 +1,7 @@
import { watchDebounced } from '@vueuse/core'
import { watch, type WatchHandle } from 'vue'
+import { recoverySessionId } from '@/app/document/recovery/session'
import { getRecoveryStore } from '@/app/document/recovery/store'
import type { RecoveryStore } from '@/app/document/recovery/types'
import { createCanvasId } from '@/app/storage/id'
@@ -10,6 +11,8 @@ interface DocumentRecoveryOptions {
/** The document's content revision; rendering and layout do not advance it. */
version: () => number
buildFigFile: () => Promise<Uint8Array> | Uint8Array
+ /** The copy's Home card cover, drawn with the document as `buildFigFile` writes it. */
+ buildCover?: () => Uint8Array | null
hasWritableSource: () => boolean
isEnabled?: () => boolean
store?: RecoveryStore
@@ -29,6 +32,7 @@ export function createDocumentRecovery({
state,
version: currentVersion,
buildFigFile,
+ buildCover,
hasWritableSource,
isEnabled = () => true,
store = getRecoveryStore(),
@@ -43,16 +47,29 @@ export function createDocumentRecovery({
let cleanup: Promise<void> = Promise.resolve()
let disposed = false
+ /** A copy without a cover still keeps the work, so a failed drawing never stops the write. */
+ function drawCover(): Uint8Array | null {
+ try {
+ return buildCover?.() ?? null
+ } catch (error) {
+ console.warn('[Recovery] Could not draw the cover:', error)
+ return null
+ }
+ }
+
async function runWrites(generation: number): Promise<void> {
if (disposed || generation !== lifecycleGeneration || !isEnabled()) return
if (hasWritableSource() || requestedVersion === protectedVersion) return
const version = requestedVersion
+ const cover = drawCover()
const bytes = await buildFigFile()
if (generation !== lifecycleGeneration || hasWritableSource() || !isEnabled()) return
await store.write({
id,
+ sessionId: recoverySessionId,
documentName: state.documentName,
- figBytes: bytes
+ figBytes: bytes,
+ cover
})
persistedVersion = version
if (generation !== lifecycleGeneration) return
diff --git a/src/app/document/recovery/idb.ts b/src/app/document/recovery/idb.ts
index b9529f07e..c4c69e6a1 100644
--- a/src/app/document/recovery/idb.ts
+++ b/src/app/document/recovery/idb.ts
@@ -17,12 +17,13 @@ import {
const recoveryDatabase = defineAppDatabase<RecoveryDatabase>({
name: APP_DATABASE_NAMES.recovery,
- version: 1,
+ version: 2,
callbacks: {
upgrade(database) {
if (!database.objectStoreNames.contains('meta'))
database.createObjectStore('meta', { keyPath: 'id' })
if (!database.objectStoreNames.contains('fig')) database.createObjectStore('fig')
+ if (!database.objectStoreNames.contains('cover')) database.createObjectStore('cover')
}
}
})
@@ -36,6 +37,10 @@ interface RecoveryDatabase extends DBSchema {
key: string
value: StoredBinary
}
+ cover: {
+ key: string
+ value: StoredBinary
+ }
}
export function createIdbRecoveryStore(): RecoveryStore {
@@ -59,12 +64,17 @@ export function createIdbRecoveryStore(): RecoveryStore {
return metadata && figBytes ? ({ ...metadata, figBytes } satisfies RecoverySnapshot) : null
},
+ async readCover(id: string) {
+ return readStoredBinary(await (await database.open()).get('cover', id))
+ },
+
async write(input: RecoverySnapshotInput) {
const db = await database.open()
const storeBinary = await binaryStorage()
- const transaction = db.transaction(['meta', 'fig'], 'readwrite')
+ const transaction = db.transaction(['meta', 'fig', 'cover'], 'readwrite')
const metadata: RecoverySnapshotMeta = {
id: input.id,
+ sessionId: input.sessionId,
documentName: input.documentName || 'Untitled',
updatedAt: new Date().toISOString(),
byteLength: input.figBytes.byteLength,
@@ -73,6 +83,9 @@ export function createIdbRecoveryStore(): RecoveryStore {
await Promise.all([
transaction.objectStore('meta').put(metadata),
transaction.objectStore('fig').put(storeBinary(input.figBytes), input.id),
+ input.cover
+ ? transaction.objectStore('cover').put(storeBinary(input.cover), input.id)
+ : transaction.objectStore('cover').delete(input.id),
transaction.done
])
return metadata
@@ -80,20 +93,30 @@ export function createIdbRecoveryStore(): RecoveryStore {
async remove(id: string) {
const db = await database.open()
- const transaction = db.transaction(['meta', 'fig'], 'readwrite')
+ const transaction = db.transaction(['meta', 'fig', 'cover'], 'readwrite')
await Promise.all([
transaction.objectStore('meta').delete(id),
transaction.objectStore('fig').delete(id),
+ transaction.objectStore('cover').delete(id),
transaction.done
])
},
+ async claim(id: string, sessionId: string) {
+ const db = await database.open()
+ const transaction = db.transaction('meta', 'readwrite')
+ const metadata = await transaction.store.get(id)
+ if (metadata) await transaction.store.put({ ...metadata, sessionId })
+ await transaction.done
+ },
+
async clear() {
const db = await database.open()
- const transaction = db.transaction(['meta', 'fig'], 'readwrite')
+ const transaction = db.transaction(['meta', 'fig', 'cover'], 'readwrite')
await Promise.all([
transaction.objectStore('meta').clear(),
transaction.objectStore('fig').clear(),
+ transaction.objectStore('cover').clear(),
transaction.done
])
}
diff --git a/src/app/document/recovery/memory.ts b/src/app/document/recovery/memory.ts
index 56e34ed21..672ce7f08 100644
--- a/src/app/document/recovery/memory.ts
+++ b/src/app/document/recovery/memory.ts
@@ -7,6 +7,7 @@ import type {
export function createMemoryRecoveryStore(): RecoveryStore {
const snapshots = new Map<string, RecoverySnapshot>()
+ const covers = new Map<string, Uint8Array>()
return {
async list() {
@@ -18,9 +19,14 @@ export function createMemoryRecoveryStore(): RecoveryStore {
const snapshot = snapshots.get(id)
return snapshot ? structuredClone(snapshot) : null
},
+ async readCover(id: string) {
+ const cover = covers.get(id)
+ return cover ? new Uint8Array(cover) : null
+ },
async write(input: RecoverySnapshotInput) {
const metadata: RecoverySnapshotMeta = {
id: input.id,
+ sessionId: input.sessionId,
documentName: input.documentName || 'Untitled',
updatedAt: new Date().toISOString(),
byteLength: input.figBytes.byteLength,
@@ -30,13 +36,21 @@ export function createMemoryRecoveryStore(): RecoveryStore {
...metadata,
figBytes: new Uint8Array(input.figBytes)
})
+ if (input.cover) covers.set(input.id, new Uint8Array(input.cover))
+ else covers.delete(input.id)
return structuredClone(metadata)
},
async remove(id: string) {
snapshots.delete(id)
+ covers.delete(id)
+ },
+ async claim(id: string, sessionId: string) {
+ const snapshot = snapshots.get(id)
+ if (snapshot) snapshots.set(id, { ...snapshot, sessionId })
},
async clear() {
snapshots.clear()
+ covers.clear()
}
}
}
diff --git a/src/app/document/recovery/session/index.ts b/src/app/document/recovery/session/index.ts
new file mode 100644
index 000000000..1d727a572
--- /dev/null
+++ b/src/app/document/recovery/session/index.ts
@@ -0,0 +1,92 @@
+import { markSessionStarted, startedSessionIds } from '@/app/document/recovery/session/storage'
+import { createCanvasId } from '@/app/storage/id'
+
+/** This window's app session; the recovery copies it writes carry this id. */
+export const recoverySessionId = createCanvasId()
+
+const SESSION_LOCK_PREFIX = 'open-pencil:recovery-session:'
+
+type SessionLocks = Pick<LockManager, 'query' | 'request'>
+
+function sessionLocks(): SessionLocks | undefined {
+ return typeof navigator === 'undefined' ? undefined : navigator.locks
+}
+
+/** Bumped when the session ends, so a lock granted after that is let go at once. */
+let sessionGeneration = 0
+let lockRequested = false
+let releaseSessionLock: (() => void) | null = null
+
+/**
+ * Marks this session running until the window closes, which `endRecoverySession` records. With
+ * Web Locks it is marked once its lock is held, so no window ever sees it started but unlocked.
+ */
+export function startRecoverySession(locks = sessionLocks()): void {
+ if (!locks) {
+ markSessionStarted(recoverySessionId, true)
+ return
+ }
+ if (lockRequested) return
+ lockRequested = true
+ const generation = sessionGeneration
+ void locks.request(SESSION_LOCK_PREFIX + recoverySessionId, () => {
+ if (generation !== sessionGeneration) return undefined
+ markSessionStarted(recoverySessionId, true)
+ return new Promise<void>((resolve) => {
+ releaseSessionLock = resolve
+ })
+ })
+}
+
+/** The window closed or reloaded on purpose, so the copies it leaves were kept, not lost to a crash. */
+export function endRecoverySession(): void {
+ sessionGeneration++
+ markSessionStarted(recoverySessionId, false)
+ releaseSessionLock?.()
+ releaseSessionLock = null
+ lockRequested = false
+}
+
+export interface RecoverySessionStates {
+ /** Sessions still running in some window, this one included; their copies are theirs. */
+ live: ReadonlySet<string>
+ /** Sessions that ended without closing their window. */
+ crashed: ReadonlySet<string>
+}
+
+/**
+ * Which sessions are running and which crashed, from the sessions `started` and the ones whose
+ * locks are `held`. Without Web Locks (`held` null) a crash cannot be told from another running
+ * window, so none counts as crashed and only this window's session as running: Home lists the
+ * others' copies without asking at start.
+ */
+export function sessionStates(
+ started: readonly string[],
+ held: readonly string[] | null
+): RecoverySessionStates {
+ if (!held) return { live: new Set([recoverySessionId]), crashed: new Set() }
+ const live = new Set([recoverySessionId, ...held])
+ return { live, crashed: new Set(started.filter((id) => !live.has(id))) }
+}
+
+export async function recoverySessionStates(
+ locks = sessionLocks()
+): Promise<RecoverySessionStates> {
+ if (!locks) return sessionStates(startedSessionIds(), null)
+ const before = startedSessionIds()
+ const { held = [] } = await locks.query()
+ const sessions = held.flatMap(({ name }) =>
+ name?.startsWith(SESSION_LOCK_PREFIX) ? [name.slice(SESSION_LOCK_PREFIX.length)] : []
+ )
+ // Started both before and after the query: one that began or ended meanwhile is not a crash.
+ const after = new Set(startedSessionIds())
+ return sessionStates(
+ before.filter((id) => after.has(id)),
+ sessions
+ )
+}
+
+/** Forgets crashed sessions, once no copy they wrote is left to mark as a crash's. */
+export function forgetCrashedSessions(crashed: ReadonlySet<string>): void {
+ for (const id of crashed) markSessionStarted(id, false)
+}
diff --git a/src/app/document/recovery/session/storage.ts b/src/app/document/recovery/session/storage.ts
new file mode 100644
index 000000000..1ed570b3b
--- /dev/null
+++ b/src/app/document/recovery/session/storage.ts
@@ -0,0 +1,45 @@
+/**
+ * One local storage key per started recovery session, so windows starting together never
+ * overwrite each other's entry. A running session also holds its lock, so a started session
+ * without its lock ended without closing its window: the app crashed or was killed.
+ */
+const STARTED_SESSION_PREFIX = 'open-pencil:recovery-started:'
+
+type SessionRegistry = Pick<Storage, 'getItem' | 'setItem' | 'removeItem' | 'key' | 'length'>
+
+let override: SessionRegistry | null | undefined
+
+/** Local storage, absent or throwing in private windows and with site data blocked. */
+function registry(): SessionRegistry | null {
+ if (override !== undefined) return override
+ try {
+ return typeof localStorage === 'undefined' ? null : localStorage
+ } catch {
+ return null
+ }
+}
+
+export function markSessionStarted(id: string, started: boolean): void {
+ try {
+ if (started) registry()?.setItem(STARTED_SESSION_PREFIX + id, '1')
+ else registry()?.removeItem(STARTED_SESSION_PREFIX + id)
+ } catch (error) {
+ console.warn('[Recovery] Could not record the session:', error)
+ }
+}
+
+export function startedSessionIds(): string[] {
+ const store = registry()
+ if (!store) return []
+ const ids: string[] = []
+ for (let index = 0; index < store.length; index++) {
+ const key = store.key(index)
+ if (key?.startsWith(STARTED_SESSION_PREFIX)) ids.push(key.slice(STARTED_SESSION_PREFIX.length))
+ }
+ return ids
+}
+
+/** Tests keep sessions in `store`; `undefined` goes back to local storage. */
+export function setSessionRegistryForTests(store: SessionRegistry | null | undefined): void {
+ override = store
+}
diff --git a/src/app/document/recovery/store.ts b/src/app/document/recovery/store.ts
index 3ce7e318b..64da17432 100644
--- a/src/app/document/recovery/store.ts
+++ b/src/app/document/recovery/store.ts
@@ -16,6 +16,16 @@ function warnMemoryFallback(error?: unknown): void {
memoryFallback = true
}
+/** A cover is only a preview: one that cannot be read is left out, and the copy still counts. */
+async function readCoverOrNone(store: RecoveryStore, id: string): Promise<Uint8Array | null> {
+ try {
+ return await store.readCover(id)
+ } catch (error) {
+ console.warn('[Recovery] Could not read the cover:', error)
+ return null
+ }
+}
+
function createResilientRecoveryStore(primary: RecoveryStore): RecoveryStore {
let current = primary
let queue = Promise.resolve()
@@ -37,7 +47,8 @@ function createResilientRecoveryStore(primary: RecoveryStore): RecoveryStore {
const snapshots = await primary.list()
for (const metadata of snapshots) {
const snapshot = await primary.read(metadata.id)
- if (snapshot) await memory.write(snapshot)
+ if (snapshot)
+ await memory.write({ ...snapshot, cover: await readCoverOrNone(primary, metadata.id) })
}
} catch (migrationError) {
console.warn('[Recovery] Failed to migrate IndexedDB snapshots to memory:', migrationError)
@@ -64,6 +75,20 @@ function createResilientRecoveryStore(primary: RecoveryStore): RecoveryStore {
})
}
+ /**
+ * Claims the durable copy, so other windows stop listing it. A failed claim fails the restore
+ * rather than falling back, but once IndexedDB has failed the durable claim is only attempted.
+ */
+ function claimInAll(id: string, sessionId: string): Promise<void> {
+ return serialized(async () => {
+ if (current === primary) return primary.claim(id, sessionId)
+ await current.claim(id, sessionId)
+ await primary.claim(id, sessionId).catch((error: unknown) => {
+ console.warn('[Recovery] Failed to claim the IndexedDB snapshot:', error)
+ })
+ })
+ }
+
function clearAll(): Promise<void> {
return serialized(async () => {
await primary.clear()
@@ -74,9 +99,12 @@ function createResilientRecoveryStore(primary: RecoveryStore): RecoveryStore {
return {
list: () => run((store) => store.list()),
read: (id: string): Promise<RecoverySnapshot | null> => run((store) => store.read(id)),
+ // A failed preview never moves the copies to memory.
+ readCover: (id: string) => serialized(() => readCoverOrNone(current, id)),
write: (input: RecoverySnapshotInput): Promise<RecoverySnapshotMeta> =>
run((store) => store.write(input)),
remove: removeFromAll,
+ claim: claimInAll,
clear: clearAll
}
}
diff --git a/src/app/document/recovery/types.ts b/src/app/document/recovery/types.ts
index c2b96bd5d..824a75605 100644
--- a/src/app/document/recovery/types.ts
+++ b/src/app/document/recovery/types.ts
@@ -1,5 +1,7 @@
export interface RecoverySnapshotMeta {
id: string
+ /** The app session that wrote the copy; a copy no running session holds is left to recover. */
+ sessionId: string
documentName: string
updatedAt: string
byteLength: number
@@ -12,14 +14,21 @@ export interface RecoverySnapshot extends RecoverySnapshotMeta {
export interface RecoverySnapshotInput {
id: string
+ sessionId: string
documentName: string
figBytes: Uint8Array
+ /** The PNG its Home card shows; a write without one leaves the copy without a cover. */
+ cover?: Uint8Array | null
}
export interface RecoveryStore {
list(): Promise<RecoverySnapshotMeta[]>
read(id: string): Promise<RecoverySnapshot | null>
+ /** The cover stored with the copy, or null when it has none or is gone. */
+ readCover(id: string): Promise<Uint8Array | null>
write(input: RecoverySnapshotInput): Promise<RecoverySnapshotMeta>
remove(id: string): Promise<void>
+ /** Hands a stored copy to `sessionId` without touching its bytes; nothing when it is gone. */
+ claim(id: string, sessionId: string): Promise<void>
clear(): Promise<void>
}
diff --git a/src/app/recent-files/index.ts b/src/app/recent-files/index.ts
index 20924bb94..fa9e93015 100644
--- a/src/app/recent-files/index.ts
+++ b/src/app/recent-files/index.ts
@@ -21,6 +21,7 @@ export {
export { rememberDocumentView, rememberedDocumentView } from './view'
export {
cacheRecentFileCover,
+ drawHomeCardCover,
cacheRecentFileThumbnail,
loadCachedRecentFileThumbnail,
loadRecentFileThumbnail
diff --git a/src/app/recent-files/thumbnails.ts b/src/app/recent-files/thumbnails.ts
index 39ea20728..9476d8534 100644
--- a/src/app/recent-files/thumbnails.ts
+++ b/src/app/recent-files/thumbnails.ts
@@ -78,6 +78,17 @@ export async function cacheRecentFileThumbnail(path: string, bytes: Uint8Array):
*/
const RECENT_FILE_COVER = { width: 800, height: 450 }
+/** Draws `graph`'s cover page as a Home card shows it; null when there is no page to draw. */
+export function drawHomeCardCover(
+ graph: SceneGraph,
+ renderer: NonNullable<Editor['renderer']>
+): Uint8Array | null {
+ const pageId = figThumbnailPageId(graph.getPages())
+ if (!pageId) return null
+ const { width, height } = RECENT_FILE_COVER
+ return renderThumbnail(renderer.ck, renderer, graph, pageId, width, height, 'letterbox')
+}
+
/** Cover writes still running, by file, so each file's covers are cached in the order drawn. */
const coverWrites = new Map<string, Promise<void>>()
@@ -93,10 +104,7 @@ export async function cacheRecentFileCover(
renderer: NonNullable<Editor['renderer']>
): Promise<boolean> {
if (!isTauri()) return false
- const pageId = figThumbnailPageId(graph.getPages())
- if (!pageId) return false
- const { width, height } = RECENT_FILE_COVER
- const bytes = renderThumbnail(renderer.ck, renderer, graph, pageId, width, height, 'letterbox')
+ const bytes = drawHomeCardCover(graph, renderer)
if (!bytes) return false
// Read now, for the file this cover was drawn from, but queued at once, so covers keep the
// order they were drawn in however their reads finish.
diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.ts
index 579b30953..11ab2cfa9 100644
--- a/src/app/tabs/index.ts
+++ b/src/app/tabs/index.ts
@@ -20,6 +20,7 @@ import { applyImportedDocument } from '@/app/document/io/imported-document'
import { isFigArchiveName } from '@/app/document/io/names'
import type { DocumentSourceIdentity } from '@/app/document/io/types'
import { getRecoveryStore, type RecoverySnapshotMeta } from '@/app/document/recovery'
+import { recoverySessionId } from '@/app/document/recovery/session'
import { setActiveEditorStore } from '@/app/editor/active-store'
import { appIcons } from '@/app/editor/icons/provider'
import type { EditorPreparationHandle as DocumentLoadSession } from '@/app/editor/preparation/types'
@@ -650,6 +651,13 @@ export async function listRecoverySnapshots(): Promise<RecoverySnapshotMeta[]> {
return getRecoveryStore().list()
}
+/** The recovery copies of the documents open in tabs, which belong to those tabs while open. */
+export function openRecoveryIds(): Set<string> {
+ return new Set(
+ tabsRef.value.filter((tab) => tab.kind === 'document').map((tab) => tab.store.getRecoveryId())
+ )
+}
+
export async function discardRecoverySnapshot(id: string): Promise<void> {
await getRecoveryStore().remove(id)
}
@@ -680,6 +688,8 @@ export async function restoreRecoverySnapshot(id: string): Promise<void> {
async () => {
store.state.documentName = snapshot.documentName
await store.adoptRecoverySnapshot(id)
+ // The copy is this window's now, so no other window lists it while it is open here.
+ await getRecoveryStore().claim(id, recoverySessionId)
},
load
)
diff --git a/src/app/tabs/recovery.ts b/src/app/tabs/recovery.ts
new file mode 100644
index 000000000..1d8f466a5
--- /dev/null
+++ b/src/app/tabs/recovery.ts
@@ -0,0 +1,103 @@
+import { shallowReadonly, shallowRef, watch } from 'vue'
+
+import { useDocumentWorkspace } from '@open-pencil/vue/document/workspace'
+
+import type { RecoverySnapshotMeta } from '@/app/document/recovery'
+import { recoveryEnabled } from '@/app/document/recovery/preferences'
+import {
+ forgetCrashedSessions,
+ recoverySessionStates,
+ type RecoverySessionStates
+} from '@/app/document/recovery/session'
+import { getRecoveryStore } from '@/app/document/recovery/store'
+import {
+ discardRecoverySnapshot,
+ listRecoverySnapshots,
+ openRecoveryIds,
+ restoreRecoverySnapshot
+} from '@/app/tabs'
+
+export interface RecoverableSnapshot extends RecoverySnapshotMeta {
+ /** Its session crashed, rather than closing or reloading its window with the copy kept. */
+ crashed: boolean
+}
+
+/**
+ * The copies left to recover: none a running session writes or a tab has open. A copy written
+ * before copies named their session belongs to none, so it is left to recover and not a crash.
+ */
+export function recoverableSnapshots(
+ snapshots: readonly RecoverySnapshotMeta[],
+ sessions: RecoverySessionStates,
+ open: ReadonlySet<string>
+): RecoverableSnapshot[] {
+ return snapshots
+ .filter((snapshot) => !sessions.live.has(snapshot.sessionId) && !open.has(snapshot.id))
+ .map((snapshot) => ({ ...snapshot, crashed: sessions.crashed.has(snapshot.sessionId) }))
+}
+
+const listed = shallowRef<readonly RecoverableSnapshot[]>([])
+/** Bumped by each refresh and each restore or discard, so an older refresh never lands last. */
+let listGeneration = 0
+
+/** The copies Home lists, as of the last `refreshRecoverableSnapshots`. */
+export const recoverable = shallowReadonly(listed)
+
+/** A crashed session is remembered while copies it wrote are left, so their cards keep saying so. */
+export function crashedSessionsWithoutCopies(
+ snapshots: readonly RecoverySnapshotMeta[],
+ sessions: RecoverySessionStates
+): Set<string> {
+ const written = new Set(snapshots.map((snapshot) => snapshot.sessionId))
+ return new Set([...sessions.crashed].filter((id) => !written.has(id)))
+}
+
+/** Lists the copies left to recover. */
+export async function refreshRecoverableSnapshots(): Promise<readonly RecoverableSnapshot[]> {
+ const generation = ++listGeneration
+ if (!recoveryEnabled.value) {
+ listed.value = []
+ return listed.value
+ }
+ const [snapshots, sessions] = await Promise.all([
+ listRecoverySnapshots(),
+ recoverySessionStates()
+ ])
+ const found = recoverableSnapshots(snapshots, sessions, openRecoveryIds())
+ forgetCrashedSessions(crashedSessionsWithoutCopies(snapshots, sessions))
+ if (generation === listGeneration) listed.value = found
+ return found
+}
+
+function drop(id: string): void {
+ listGeneration++
+ listed.value = listed.value.filter((snapshot) => snapshot.id !== id)
+}
+
+export async function restoreRecoverable(id: string): Promise<void> {
+ await restoreRecoverySnapshot(id)
+ drop(id)
+}
+
+export async function discardRecoverable(id: string): Promise<void> {
+ await discardRecoverySnapshot(id)
+ drop(id)
+}
+
+/** The listed copies with their covers, as Home's cards show them. */
+export function useRecoverableWorkspace() {
+ const workspace = useDocumentWorkspace({
+ source: {
+ async refresh() {
+ return recoverable.value.map((snapshot) => ({ ...snapshot, name: snapshot.documentName }))
+ },
+ loadPreview: (id) => getRecoveryStore().readCover(id)
+ },
+ refreshOnFocus: false,
+ refreshOnReconnect: false,
+ previewConcurrency: 2,
+ onPreviewError: (id, error) => console.warn(`[Recovery] No cover for ${id}:`, error)
+ })
+ watch(recoverable, () => void workspace.invalidate())
+ return workspace
+}
diff --git a/src/components/home/HomeWorkspace.vue b/src/components/home/HomeWorkspace.vue
index 971d0cc15..4b952e72a 100644
--- a/src/components/home/HomeWorkspace.vue
+++ b/src/components/home/HomeWorkspace.vue
@@ -28,12 +28,14 @@ import { openSettingsDialog } from '@/app/settings/dialog'
import { createStoredDocument } from '@/app/storage/workspace/create'
import { activeStorageLocation, createStorageWorkspaceSource } from '@/app/storage/workspace/source'
import { openStorageDocumentInNewTab } from '@/app/tabs'
+import { recoverable } from '@/app/tabs/recovery'
import { CloudSharedSection, CloudWorkspaceSection } from '@/components/cloud/integration'
import DocumentDeleteDialog from '@/components/home/document/DocumentDeleteDialog.vue'
import DocumentEntry from '@/components/home/document/DocumentEntry.vue'
import { ofKind, type DocumentKindFilter } from '@/components/home/document/filter'
import HomeLayout from '@/components/home/HomeLayout.vue'
import RecentFilesSection from '@/components/home/recent/RecentFilesSection.vue'
+import RecoverySection from '@/components/home/recovery/RecoverySection.vue'
import HomeSearchActions from '@/components/home/search/HomeSearchActions.vue'
import HomeLocationMenu from '@/components/home/sidebar/HomeLocationMenu.vue'
import HomeSidebar from '@/components/home/sidebar/HomeSidebar.vue'
@@ -164,10 +166,15 @@ const filteredStorageDocuments = computed(() =>
document.name.toLocaleLowerCase(locale.value).includes(normalizedQuery.value)
)
)
+const filteredRecoverable = computed(() =>
+ recoverable.value.filter((snapshot) =>
+ snapshot.documentName.toLocaleLowerCase(locale.value).includes(normalizedQuery.value)
+ )
+)
// Recent files counts matches before its kind filter, so its kind control stays to switch kinds;
-// storage has none to count while its first listing loads.
+// storage has none to count while its first listing loads. Unsaved work shows in every place.
const noSearchMatches = computed(() => {
- if (!normalizedQuery.value) return false
+ if (!normalizedQuery.value || filteredRecoverable.value.length > 0) return false
if (places.location.value.kind !== 'storage') return searchedRecentFiles.value.length === 0
return (
filteredStorageDocuments.value.length === 0 &&
@@ -239,6 +246,8 @@ function formattedDate(updatedAt: string): string {
/>
<p v-if="openError" class="mb-4 text-xs text-error" role="alert">{{ openError }}</p>
+ <!-- Unsaved work is this device's, so it shows in every place. -->
+ <RecoverySection :view="view" :snapshots="filteredRecoverable" />
<!-- Nothing until Cloud says which workspace Home opens on. -->
<template v-if="places.settling.value" />
<CloudWorkspaceSection
diff --git a/src/components/home/recovery/RecoverySection.vue b/src/components/home/recovery/RecoverySection.vue
new file mode 100644
index 000000000..4d3300e8e
--- /dev/null
+++ b/src/components/home/recovery/RecoverySection.vue
@@ -0,0 +1,106 @@
+<script setup lang="ts">
+import { useWindowFocus, watchImmediate } from '@vueuse/core'
+
+import { useI18n } from '@open-pencil/vue/i18n'
+
+import { useDateFormat } from '@/app/i18n/date'
+import { useNotificationMessages } from '@/app/i18n/notifications'
+import { toast } from '@/app/shell/ui'
+import { formatStorageBytes } from '@/app/storage/format-bytes'
+import { allTabs } from '@/app/tabs'
+import {
+ discardRecoverable,
+ refreshRecoverableSnapshots,
+ restoreRecoverable,
+ useRecoverableWorkspace,
+ type RecoverableSnapshot
+} from '@/app/tabs/recovery'
+import DocumentEntry from '@/components/home/document/DocumentEntry.vue'
+
+/** Recovery copies of documents closed without saving, until each is restored or discarded. */
+const { view, snapshots } = defineProps<{
+ view: 'grid' | 'list'
+ /** The copies to list, filtered by Home's search. */
+ snapshots: readonly RecoverableSnapshot[]
+}>()
+const { recovery, files } = useI18n()
+const notifications = useNotificationMessages()
+const dates = useDateFormat()
+const focused = useWindowFocus()
+const workspace = useRecoverableWorkspace()
+const previewURL = workspace.previewURL
+const vWorkspacePreview = workspace.previewDirective
+
+// A closed tab or another window that went away can leave a copy behind.
+watchImmediate([() => allTabs.value.length, focused], () => {
+ void refreshRecoverableSnapshots().catch((error: unknown) => {
+ console.warn('[Recovery] Failed to list snapshots:', error)
+ })
+})
+
+/** When and how big; a crash's copy says so first, as the start no longer asks about it. */
+function metadata(snapshot: RecoverableSnapshot): string {
+ const details = `${dates.format(snapshot.updatedAt, 'dateTime')} · ${formatStorageBytes(snapshot.byteLength)}`
+ return snapshot.crashed ? `${recovery.value.crashNote} · ${details}` : details
+}
+
+function menu(snapshot: RecoverableSnapshot) {
+ return {
+ actions: files.value.documentActions({ name: snapshot.documentName }),
+ delete: recovery.value.discard
+ }
+}
+
+async function restore(snapshot: RecoverableSnapshot): Promise<void> {
+ try {
+ await restoreRecoverable(snapshot.id)
+ } catch (error) {
+ toast.error(
+ notifications.value.operationFailed({
+ error: error instanceof Error ? error.message : recovery.value.restoreFailed
+ })
+ )
+ }
+}
+
+async function discard(snapshot: RecoverableSnapshot): Promise<void> {
+ try {
+ await discardRecoverable(snapshot.id)
+ } catch (error) {
+ toast.error(
+ notifications.value.operationFailed({
+ error: error instanceof Error ? error.message : recovery.value.discardFailed
+ })
+ )
+ }
+}
+</script>
+
+<template>
+ <section v-if="snapshots.length" class="mb-8" data-test-id="home-recovery">
+ <div class="mb-3 min-w-0">
+ <h2 class="text-base font-semibold">{{ recovery.sectionTitle }}</h2>
+ <p class="mt-0.5 text-pretty text-xs text-muted">{{ recovery.sectionDescription }}</p>
+ </div>
+ <div
+ :class="
+ view === 'grid'
+ ? 'grid grid-cols-1 gap-x-5 gap-y-6 sm:grid-cols-[repeat(auto-fill,minmax(200px,1fr))]'
+ : 'overflow-hidden rounded-lg border border-border'
+ "
+ >
+ <DocumentEntry
+ v-for="snapshot in snapshots"
+ :key="snapshot.id"
+ v-workspace-preview="snapshot.id"
+ :view="view"
+ :name="snapshot.documentName"
+ :metadata="metadata(snapshot)"
+ :previewURL="previewURL(snapshot.id)"
+ :menu="menu(snapshot)"
+ @open="restore(snapshot)"
+ @delete="discard(snapshot)"
+ />
+ </div>
+ </section>
+</template>
diff --git a/src/components/recovery/RecoveryDialog.vue b/src/components/recovery/RecoveryDialog.vue
deleted file mode 100644
index dbac9a6ec..000000000
--- a/src/components/recovery/RecoveryDialog.vue
+++ /dev/null
@@ -1,123 +0,0 @@
-<script setup lang="ts">
-import { AlertDialogCancel, AlertDialogDescription, AlertDialogTitle } from 'reka-ui'
-import { onMounted, ref } from 'vue'
-import { useRoute } from 'vue-router'
-
-import { useI18n } from '@open-pencil/vue/i18n'
-
-import type { RecoverySnapshotMeta } from '@/app/document/recovery'
-import { recoveryEnabled } from '@/app/document/recovery/preferences'
-import { useDateFormat } from '@/app/i18n/date'
-import { useNotificationMessages } from '@/app/i18n/notifications'
-import { toast } from '@/app/shell/ui'
-import { formatStorageBytes } from '@/app/storage/format-bytes'
-import { discardRecoverySnapshot, listRecoverySnapshots, restoreRecoverySnapshot } from '@/app/tabs'
-import AppButton from '@/components/ui/button/AppButton.vue'
-
-const { recovery, common } = useI18n()
-const notifications = useNotificationMessages()
-const route = useRoute()
-const snapshots = ref<RecoverySnapshotMeta[]>([])
-const busyId = ref<string | null>(null)
-const open = ref(false)
-
-const dates = useDateFormat()
-const updatedLabel = (snapshot: RecoverySnapshotMeta) =>
- dates.format(snapshot.updatedAt, 'dateTime')
-
-/** Drops a handled snapshot; the last one stays listed while the dialog animates closed. */
-function settle(snapshot: RecoverySnapshotMeta): void {
- const remaining = snapshots.value.filter((candidate) => candidate.id !== snapshot.id)
- if (remaining.length === 0) open.value = false
- else snapshots.value = remaining
-}
-
-async function restore(snapshot: RecoverySnapshotMeta): Promise<void> {
- busyId.value = snapshot.id
- try {
- await restoreRecoverySnapshot(snapshot.id)
- settle(snapshot)
- } catch (error) {
- toast.error(
- notifications.value.operationFailed({
- error: error instanceof Error ? error.message : recovery.value.restoreFailed
- })
- )
- } finally {
- busyId.value = null
- }
-}
-
-async function discard(snapshot: RecoverySnapshotMeta): Promise<void> {
- busyId.value = snapshot.id
- try {
- await discardRecoverySnapshot(snapshot.id)
- settle(snapshot)
- } finally {
- busyId.value = null
- }
-}
-
-onMounted(async () => {
- if (route.path !== '/' || !recoveryEnabled.value) return
- try {
- snapshots.value = await listRecoverySnapshots()
- open.value = snapshots.value.length > 0
- } catch (error) {
- console.warn('[Recovery] Failed to list snapshots:', error)
- }
-})
-</script>
-
-<template>
- <AppAlertDialogRoot v-model:open="open" size="md" data-test-id="recovery-dialog">
- <div class="border-b border-border px-4 py-3">
- <AlertDialogTitle class="text-sm font-semibold text-surface">
- {{ recovery.dialogTitle }}
- </AlertDialogTitle>
- </div>
- <AppDialogBody class="space-y-3">
- <AlertDialogDescription class="text-xs text-muted">
- {{ recovery.dialogDescription }}
- </AlertDialogDescription>
- <div class="max-h-72 space-y-2 overflow-y-auto">
- <div
- v-for="snapshot in snapshots"
- :key="snapshot.id"
- class="flex items-center gap-3 rounded border border-border p-3"
- >
- <icon-lucide-file-clock class="size-4 shrink-0 text-muted" />
- <div class="min-w-0 flex-1">
- <p class="truncate text-xs font-medium text-surface">{{ snapshot.documentName }}</p>
- <p class="text-[11px] text-muted">
- {{ updatedLabel(snapshot) }} · {{ formatStorageBytes(snapshot.byteLength) }}
- </p>
- </div>
- <AppButton
- color="error"
- variant="ghost"
- size="xs"
- :disabled="busyId !== null"
- @click="discard(snapshot)"
- >
- {{ recovery.discard }}
- </AppButton>
- <AppButton
- color="primary"
- variant="solid"
- size="xs"
- :disabled="busyId !== null"
- @click="restore(snapshot)"
- >
- {{ recovery.restore }}
- </AppButton>
- </div>
- </div>
- </AppDialogBody>
- <AppDialogFooter>
- <AlertDialogCancel as-child>
- <AppButton color="neutral" variant="ghost">{{ common.close }}</AppButton>
- </AlertDialogCancel>
- </AppDialogFooter>
- </AppAlertDialogRoot>
-</template>
diff --git a/tests/app/document/recovery/session.test.ts b/tests/app/document/recovery/session.test.ts
new file mode 100644
index 000000000..3efedc615
--- /dev/null
+++ b/tests/app/document/recovery/session.test.ts
@@ -0,0 +1,65 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
+
+import {
+ endRecoverySession,
+ recoverySessionId,
+ sessionStates,
+ startRecoverySession
+} from '@/app/document/recovery/session'
+import {
+ setSessionRegistryForTests,
+ startedSessionIds
+} from '@/app/document/recovery/session/storage'
+
+/** The session registry as local storage keeps it; Bun has no local storage. */
+function memoryRegistry() {
+ const items = new Map<string, string>()
+ return {
+ get length() {
+ return items.size
+ },
+ getItem: (key: string) => items.get(key) ?? null,
+ key: (index: number) => [...items.keys()][index] ?? null,
+ removeItem: (key: string) => void items.delete(key),
+ setItem: (key: string, value: string) => void items.set(key, value)
+ }
+}
+
+describe('recovery sessions', () => {
+ beforeAll(() => setSessionRegistryForTests(memoryRegistry()))
+ afterAll(() => setSessionRegistryForTests(undefined))
+
+ test('a started session whose lock is gone crashed', () => {
+ const states = sessionStates(['crashed', 'other-window'], ['other-window'])
+ expect([...states.crashed]).toEqual(['crashed'])
+ expect(states.live).toEqual(new Set([recoverySessionId, 'other-window']))
+ })
+
+ test('a session that ended on purpose is no longer started, so it is not a crash', () => {
+ expect(sessionStates([], []).crashed.size).toBe(0)
+ })
+
+ test('without Web Locks no session crashed and only this one runs', () => {
+ const states = sessionStates(['other-or-crashed'], null)
+ expect(states.crashed.size).toBe(0)
+ expect(states.live).toEqual(new Set([recoverySessionId]))
+ })
+
+ test('a session counts as started only once its lock is held, until it ends', () => {
+ const pending: { grant?: () => unknown } = {}
+ const locks = {
+ query: async () => ({ held: [], pending: [] }),
+ request: ((_name: string, callback: () => unknown) => {
+ pending.grant = callback
+ return Promise.resolve()
+ }) as LockManager['request']
+ }
+ startRecoverySession(locks)
+ // Before the grant no window could tell it from a crashed one, so it is not listed yet.
+ expect(startedSessionIds()).toEqual([])
+ void pending.grant?.()
+ expect(startedSessionIds()).toEqual([recoverySessionId])
+ endRecoverySession()
+ expect(startedSessionIds()).toEqual([])
+ })
+})
diff --git a/tests/app/document/recovery/store.test.ts b/tests/app/document/recovery/store.test.ts
new file mode 100644
index 000000000..a7a02e851
--- /dev/null
+++ b/tests/app/document/recovery/store.test.ts
@@ -0,0 +1,80 @@
+import 'fake-indexeddb/auto'
+import { afterAll, afterEach, describe, expect, test } from 'bun:test'
+
+import { IDBFactory } from 'fake-indexeddb'
+
+import { createIdbRecoveryStore } from '@/app/document/recovery/idb'
+import { createMemoryRecoveryStore } from '@/app/document/recovery/memory'
+import {
+ getRecoveryStore,
+ isRecoveryStoreMemoryFallback,
+ resetRecoveryStoreForTests
+} from '@/app/document/recovery/store'
+
+/** An IndexedDB that exists but fails every open, as in some private windows. */
+class BrokenFactory extends IDBFactory {
+ override open(): IDBOpenDBRequest {
+ throw new DOMException('IndexedDB is broken', 'UnknownError')
+ }
+}
+
+describe('recovery store fallback', () => {
+ const sharedFactory = globalThis.indexedDB
+
+ afterEach(() => resetRecoveryStoreForTests())
+ afterAll(() => {
+ globalThis.indexedDB = sharedFactory
+ })
+
+ test('a cover that cannot be read leaves the store on IndexedDB', async () => {
+ globalThis.indexedDB = new BrokenFactory()
+ resetRecoveryStoreForTests()
+ expect(await getRecoveryStore().readCover('copy')).toBeNull()
+ expect(isRecoveryStoreMemoryFallback()).toBe(false)
+ })
+
+ test('a restored copy is claimed in memory once IndexedDB has failed', async () => {
+ globalThis.indexedDB = new BrokenFactory()
+ resetRecoveryStoreForTests()
+ const store = getRecoveryStore()
+ await store.write({
+ id: 'copy',
+ sessionId: 'crashed',
+ documentName: 'Draft',
+ figBytes: new Uint8Array([1, 2, 3])
+ })
+ expect(isRecoveryStoreMemoryFallback()).toBe(true)
+
+ await store.claim('copy', 'restoring')
+
+ expect((await store.list()).map((snapshot) => snapshot.sessionId)).toEqual(['restoring'])
+ })
+})
+
+describe('recovery covers', () => {
+ const sharedFactory = globalThis.indexedDB
+ const cover = new Uint8Array([137, 80, 78, 71])
+ const figBytes = new Uint8Array([1, 2, 3])
+
+ afterAll(() => {
+ globalThis.indexedDB = sharedFactory
+ })
+
+ test.each([
+ ['IndexedDB', createIdbRecoveryStore],
+ ['memory', createMemoryRecoveryStore]
+ ])('a %s store keeps the cover of the last write until the copy goes', async (_, create) => {
+ globalThis.indexedDB = new IDBFactory()
+ const store = create()
+ const copy = { id: 'copy', sessionId: 'one', documentName: 'Draft', figBytes }
+ await store.write({ ...copy, cover })
+ expect(await store.readCover('copy')).toEqual(cover)
+
+ await store.write(copy)
+ expect(await store.readCover('copy')).toBeNull()
+
+ await store.write({ ...copy, cover })
+ await store.remove('copy')
+ expect(await store.readCover('copy')).toBeNull()
+ })
+})
diff --git a/tests/app/tabs/recovery.test.ts b/tests/app/tabs/recovery.test.ts
new file mode 100644
index 000000000..21d696ca7
--- /dev/null
+++ b/tests/app/tabs/recovery.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, test } from 'bun:test'
+
+import type { RecoverySnapshotMeta } from '@/app/document/recovery'
+import { crashedSessionsWithoutCopies, recoverableSnapshots } from '@/app/tabs/recovery'
+
+function snapshot(id: string, sessionId: string): RecoverySnapshotMeta {
+ return {
+ id,
+ sessionId,
+ documentName: id,
+ updatedAt: '2026-11-01T12:00:00.000Z',
+ byteLength: 1,
+ formatVersion: 1
+ }
+}
+
+describe('recoverable snapshots', () => {
+ const sessions = { live: new Set(['running']), crashed: new Set(['crashed']) }
+
+ test('lists copies no running session holds, marking those of a crashed one', () => {
+ const listed = recoverableSnapshots(
+ [snapshot('lost', 'crashed'), snapshot('kept', 'closed'), snapshot('editing', 'running')],
+ sessions,
+ new Set()
+ )
+ expect(listed.map(({ id, crashed }) => [id, crashed])).toEqual([
+ ['lost', true],
+ ['kept', false]
+ ])
+ })
+
+ test('forgets a crashed session only once no copy it wrote is left', () => {
+ const crashed = { live: new Set<string>(), crashed: new Set(['restored', 'still-lost']) }
+ expect([...crashedSessionsWithoutCopies([snapshot('lost', 'still-lost')], crashed)]).toEqual([
+ 'restored'
+ ])
+ })
+
+ test('leaves out a copy a tab has open again', () => {
+ expect(
+ recoverableSnapshots([snapshot('lost', 'crashed')], sessions, new Set(['lost']))
+ ).toEqual([])
+ })
+})
diff --git a/tests/e2e/recovery.spec.ts b/tests/e2e/recovery.spec.ts
index 09d4d4e17..0a95a2762 100644
--- a/tests/e2e/recovery.spec.ts
+++ b/tests/e2e/recovery.spec.ts
@@ -45,11 +45,51 @@ test('keeps recovery independent from cancelling an unsaved-document close', asy
)
.toBe(1)
+ // A reload leaves the copy on purpose, so Home lists it without calling it a crash's.
page.once('dialog', (dialog) => dialog.accept())
- await page.reload()
- await expect(page.getByRole('alertdialog', { name: 'Recover unsaved work' })).toBeVisible()
- await page.getByRole('button', { name: 'Restore' }).click()
+ await page.goto('/?recent-files')
+ const kept = page.getByTestId('home-recovery').locator('[data-slot="document-entry"]')
+ await expect(kept).toHaveCount(1)
+ await expect(kept).not.toContainText('Kept after a crash')
+ await kept.locator('[data-slot="trigger"]').click()
await expect(page.getByText('Retained recovery rectangle')).toBeVisible()
+ await expect(page.getByTestId('home-recovery')).toHaveCount(0)
+
+ await context.close()
+})
+
+test('lists the unsaved work of a window that crashed on Home', async ({ browser, baseURL }) => {
+ const context = await browser.newContext({ baseURL })
+ const crashing = await context.newPage()
+ await crashing.goto('/?test')
+ await new CanvasHelper(crashing).waitForInit()
+ await crashing.evaluate(async () => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const id = store.createShape('RECTANGLE', 120, 120, 240, 140)
+ store.updateNode(id, { name: 'Crashed recovery rectangle' })
+ await store.persistRecoveryNow()
+ })
+ // The renderer goes away without unloading the page, as in a crash.
+ const cdp = await context.newCDPSession(crashing)
+ const crashed = crashing.waitForEvent('crash')
+ // Chromium never answers this command: the page it would answer from is gone.
+ void cdp.send('Page.crash').catch(() => undefined)
+ await crashed
+
+ const page = await context.newPage()
+ await page.goto('/?recent-files')
+ const lost = page.getByTestId('home-recovery').locator('[data-slot="document-entry"]')
+ await expect(lost).toHaveCount(1)
+ await expect(lost).toContainText('Kept after a crash')
+ // The cover stored with the copy decodes to an image on the card.
+ await expect(lost.locator('img')).toHaveAttribute('src', /^blob:/)
+ await expect
+ .poll(() => lost.locator('img').evaluate((image: HTMLImageElement) => image.naturalWidth))
+ .toBeGreaterThan(0)
+ await expect(page.getByRole('alertdialog')).toHaveCount(0)
+ await lost.locator('[data-slot="trigger"]').click()
+ await expect(page.getByText('Crashed recovery rectangle')).toBeVisible()
await context.close()
})
diff --git a/tests/engine/app/document/recovery/store.test.ts b/tests/engine/app/document/recovery/store.test.ts
index b3f3e8ddd..039549e0b 100644
--- a/tests/engine/app/document/recovery/store.test.ts
+++ b/tests/engine/app/document/recovery/store.test.ts
@@ -28,12 +28,14 @@ describe('document recovery store', () => {
const store = createIdbRecoveryStore()
const metadata = await store.write({
id: 'recovery-1',
+ sessionId: 'session-1',
documentName: 'Agent draft',
figBytes: bytes
})
expect(metadata).toMatchObject({
id: 'recovery-1',
+ sessionId: 'session-1',
documentName: 'Agent draft',
byteLength: 4,
formatVersion: 1
@@ -51,6 +53,7 @@ describe('document recovery store', () => {
const buffer = new Uint8Array([9, 9, 1, 2, 3, 9])
await store.write({
id: 'recovery-1',
+ sessionId: 'session-1',
documentName: 'Agent draft',
figBytes: buffer.subarray(2, 5)
})
@@ -62,7 +65,7 @@ describe('document recovery store', () => {
test('memory store owns input and output bytes', async () => {
const store = createMemoryRecoveryStore()
const input = new Uint8Array(bytes)
- await store.write({ id: 'one', documentName: 'Draft', figBytes: input })
+ await store.write({ id: 'one', sessionId: 'session-1', documentName: 'Draft', figBytes: input })
input[0] = 99
const first = await store.read('one')
@@ -70,4 +73,19 @@ describe('document recovery store', () => {
if (first) first.figBytes[0] = 88
expect((await store.read('one'))?.figBytes[0]).toBe(1)
})
+
+ test.each([
+ ['IndexedDB', createIdbRecoveryStore],
+ ['memory', createMemoryRecoveryStore]
+ ])('a %s store hands a copy to another session and keeps its bytes', async (_, create) => {
+ const store = create()
+ await store.write({ id: 'one', sessionId: 'crashed', documentName: 'Draft', figBytes: bytes })
+ await store.claim('one', 'restoring')
+ await store.claim('gone', 'restoring')
+
+ expect((await store.list()).map(({ id, sessionId }) => [id, sessionId])).toEqual([
+ ['one', 'restoring']
+ ])
+ expect((await store.read('one'))?.figBytes).toEqual(bytes)
+ })
})
diff --git a/tests/engine/app/tabs/open-file-dedup.test.ts b/tests/engine/app/tabs/open-file-dedup.test.ts
index 0b9627821..459a929d5 100644
--- a/tests/engine/app/tabs/open-file-dedup.test.ts
+++ b/tests/engine/app/tabs/open-file-dedup.test.ts
@@ -220,6 +220,7 @@ describe('openFileInNewTab deduplication', () => {
resetRecoveryStoreForTests(createMemoryRecoveryStore())
await getRecoveryStore().write({
id: 'broken',
+ sessionId: 'crashed-session',
documentName: 'Broken',
figBytes: new Uint8Array([1])
})
diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txt
index 26a02d1dd..e5709e10d 100644
--- a/tools/checks/i18n/mixed-script-baseline.txt
+++ b/tools/checks/i18n/mixed-script-baseline.txt
@@ -205,7 +205,7 @@ ja:panels.yAxis
ja:panels.shaderPreset
ja:panels.invalidShaderPreset
ja:panels.shaderNeedsWebGPU
-ja:recovery.dialogDescription
+ja:recovery.sectionDescription
ja:settings.baseURLHint
ja:settings.invalidURL
ja:settings.modelIDHint
@@ -423,7 +423,7 @@ zh-cn:panels.sizingFillFr
zh-cn:panels.sizingFixedPx
zh-cn:panels.xAxis
zh-cn:panels.yAxis
-zh-cn:recovery.dialogDescription
+zh-cn:recovery.sectionDescription
zh-cn:settings.baseURLHint
zh-cn:settings.invalidURL
zh-cn:settings.temporaryDisableSnappingHint
diff --git a/tools/checks/lint/src/rules/runtime.ts b/tools/checks/lint/src/rules/runtime.ts
index 4a6a38c0b..65bbe8ad1 100644
--- a/tools/checks/lint/src/rules/runtime.ts
+++ b/tools/checks/lint/src/rules/runtime.ts
@@ -23,6 +23,7 @@ const noDirectStorageAccess = {
const allowedFiles = [
'/src/app/ai/chat/storage.ts',
'/src/app/cache/index.ts',
+ '/src/app/document/recovery/session/storage.ts',
'/src/app/settings/credentials/storage.ts',
'/src/app/settings/theme.ts',
'/src/app/shell/layout-storage.ts',