Skip to content

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

feat: delete stored documents from Home (#1592)

Danila Poyarkovabb7281f9d42
diff --git a/changes/1592/added.md b/changes/1592/added.md
new file mode 100644
index 000000000..ac747b9a0
--- /dev/null
+++ b/changes/1592/added.md
@@ -0,0 +1 @@
+- Home deletes storage and Cloud workspace documents from an entry's ⋯ menu or its right-click menu, after a confirmation (#1533).
diff --git a/changes/1592/fixed.md b/changes/1592/fixed.md
new file mode 100644
index 000000000..a7348d0c0
--- /dev/null
+++ b/changes/1592/fixed.md
@@ -0,0 +1 @@
+- Home stops listing storage documents deleted from another device or through the Cloud API (#1533).
diff --git a/packages/vue/src/i18n/locales/de/files.json b/packages/vue/src/i18n/locales/de/files.json
index 6a4053e7f..0c15764fa 100644
--- a/packages/vue/src/i18n/locales/de/files.json
+++ b/packages/vue/src/i18n/locales/de/files.json
@@ -26,6 +26,11 @@
"searchRecentAndStorageFiles": "Zuletzt verwendete und gespeicherte Dateien suchen…",
"newDesign": "Neues Design",
"noMatchingFiles": "Keine Dateien entsprechen „{query}“.",
+ "documentActions": "Aktionen für {name}",
+ "deleteDocument": "Löschen",
+ "deleteDocumentConfirmation": "„{name}“ löschen?",
+ "deleteDocumentDescription": "Das Dokument wird für alle gelöscht, die es öffnen können. Das lässt sich nicht rückgängig machen.",
+ "deleteDocumentFailed": "„{name}“ konnte nicht gelöscht werden. Versuche es erneut.",
"saveAsPrompt": "Speichern unter:",
"browserFileAPINotSupported": "Dein Browser unterstützt die lokale Datei-API nicht. Dateien werden heruntergeladen, statt direkt gespeichert zu werden.",
"newDesignIn": "Neues Design in {place}"
diff --git a/packages/vue/src/i18n/locales/es/files.json b/packages/vue/src/i18n/locales/es/files.json
index 2f999d9f2..60ae0106a 100644
--- a/packages/vue/src/i18n/locales/es/files.json
+++ b/packages/vue/src/i18n/locales/es/files.json
@@ -26,6 +26,11 @@
"searchRecentAndStorageFiles": "Buscar en archivos recientes y almacenados…",
"newDesign": "Nuevo diseño",
"noMatchingFiles": "Ningún archivo coincide con «{query}».",
+ "documentActions": "Acciones de {name}",
+ "deleteDocument": "Eliminar",
+ "deleteDocumentConfirmation": "¿Eliminar «{name}»?",
+ "deleteDocumentDescription": "El documento se elimina para todas las personas que pueden abrirlo. No se puede deshacer.",
+ "deleteDocumentFailed": "No se pudo eliminar «{name}». Inténtalo de nuevo.",
"saveAsPrompt": "Guardar como:",
"browserFileAPINotSupported": "Tu navegador no admite la API de archivos locales. Los archivos se descargarán en lugar de guardarse en el mismo lugar.",
"newDesignIn": "Nuevo diseño en {place}"
diff --git a/packages/vue/src/i18n/locales/fr/files.json b/packages/vue/src/i18n/locales/fr/files.json
index 70a9bf1ef..cf5ed5d8d 100644
--- a/packages/vue/src/i18n/locales/fr/files.json
+++ b/packages/vue/src/i18n/locales/fr/files.json
@@ -26,6 +26,11 @@
"searchRecentAndStorageFiles": "Rechercher dans les fichiers récents et stockés…",
"newDesign": "Nouveau design",
"noMatchingFiles": "Aucun fichier ne correspond à « {query} ».",
+ "documentActions": "Actions pour {name}",
+ "deleteDocument": "Supprimer",
+ "deleteDocumentConfirmation": "Supprimer « {name} » ?",
+ "deleteDocumentDescription": "Le document est supprimé pour toutes les personnes qui peuvent l’ouvrir. Cette action est irréversible.",
+ "deleteDocumentFailed": "Impossible de supprimer « {name} ». Réessayez.",
"saveAsPrompt": "Enregistrer sous :",
"browserFileAPINotSupported": "Votre navigateur ne prend pas en charge l’API de fichiers locaux. Les fichiers seront téléchargés au lieu d’être enregistrés sur place.",
"newDesignIn": "Nouveau design dans {place}"
diff --git a/packages/vue/src/i18n/locales/it/files.json b/packages/vue/src/i18n/locales/it/files.json
index 79fc6428f..bbf74eb3e 100644
--- a/packages/vue/src/i18n/locales/it/files.json
+++ b/packages/vue/src/i18n/locales/it/files.json
@@ -26,6 +26,11 @@
"searchRecentAndStorageFiles": "Cerca nei file recenti e archiviati…",
"newDesign": "Nuovo design",
"noMatchingFiles": "Nessun file corrisponde a «{query}».",
+ "documentActions": "Azioni per {name}",
+ "deleteDocument": "Elimina",
+ "deleteDocumentConfirmation": "Eliminare «{name}»?",
+ "deleteDocumentDescription": "Il documento viene eliminato per tutti coloro che possono aprirlo. L’operazione non può essere annullata.",
+ "deleteDocumentFailed": "Impossibile eliminare «{name}». Riprova.",
"saveAsPrompt": "Salva con nome:",
"browserFileAPINotSupported": "Il browser non supporta l’API dei file locali. I file verranno scaricati anziché salvati nella posizione corrente.",
"newDesignIn": "Nuovo design in {place}"
diff --git a/packages/vue/src/i18n/locales/ja/files.json b/packages/vue/src/i18n/locales/ja/files.json
index 58c2691e9..cfd233945 100644
--- a/packages/vue/src/i18n/locales/ja/files.json
+++ b/packages/vue/src/i18n/locales/ja/files.json
@@ -26,6 +26,11 @@
"searchRecentAndStorageFiles": "最近使用したファイルとストレージを検索…",
"newDesign": "新しいデザイン",
"noMatchingFiles": "「{query}」に一致するファイルはありません。",
+ "documentActions": "{name} の操作",
+ "deleteDocument": "削除",
+ "deleteDocumentConfirmation": "「{name}」を削除しますか?",
+ "deleteDocumentDescription": "このドキュメントは開けるすべての人に対して削除されます。この操作は元に戻せません。",
+ "deleteDocumentFailed": "「{name}」を削除できませんでした。もう一度お試しください。",
"saveAsPrompt": "名前を付けて保存:",
"browserFileAPINotSupported": "このブラウザはローカルファイルAPIに対応していません。ファイルは同じ場所に保存されず、ダウンロードされます。",
"newDesignIn": "{place} に新規デザイン"
diff --git a/packages/vue/src/i18n/locales/pl/files.json b/packages/vue/src/i18n/locales/pl/files.json
index 61debe500..6de4307f4 100644
--- a/packages/vue/src/i18n/locales/pl/files.json
+++ b/packages/vue/src/i18n/locales/pl/files.json
@@ -26,6 +26,11 @@
"searchRecentAndStorageFiles": "Szukaj w ostatnich i zapisanych plikach…",
"newDesign": "Nowy projekt",
"noMatchingFiles": "Brak plików pasujących do „{query}”.",
+ "documentActions": "Działania dla {name}",
+ "deleteDocument": "Usuń",
+ "deleteDocumentConfirmation": "Usunąć „{name}”?",
+ "deleteDocumentDescription": "Dokument zostanie usunięty dla wszystkich, którzy mogą go otworzyć. Tej operacji nie można cofnąć.",
+ "deleteDocumentFailed": "Nie udało się usunąć „{name}”. Spróbuj ponownie.",
"saveAsPrompt": "Zapisz jako:",
"browserFileAPINotSupported": "Twoja przeglądarka nie obsługuje interfejsu API plików lokalnych. Pliki będą pobierane zamiast zapisywane w bieżącym miejscu.",
"newDesignIn": "Nowy projekt w {place}"
diff --git a/packages/vue/src/i18n/locales/ru/files.json b/packages/vue/src/i18n/locales/ru/files.json
index 1817d120b..0a3bc1777 100644
--- a/packages/vue/src/i18n/locales/ru/files.json
+++ b/packages/vue/src/i18n/locales/ru/files.json
@@ -26,6 +26,11 @@
"searchRecentAndStorageFiles": "Поиск в недавних файлах и хранилище…",
"newDesign": "Новый дизайн",
"noMatchingFiles": "Нет файлов по запросу «{query}».",
+ "documentActions": "Действия с {name}",
+ "deleteDocument": "Удалить",
+ "deleteDocumentConfirmation": "Удалить «{name}»?",
+ "deleteDocumentDescription": "Документ будет удалён для всех, кто может его открыть. Это действие нельзя отменить.",
+ "deleteDocumentFailed": "Не удалось удалить «{name}». Попробуйте ещё раз.",
"saveAsPrompt": "Сохранить как:",
"browserFileAPINotSupported": "Ваш браузер не поддерживает API локальных файлов. Вместо сохранения на месте файлы будут скачиваться.",
"newDesignIn": "Новый дизайн в {place}"
diff --git a/packages/vue/src/i18n/locales/zh-cn/files.json b/packages/vue/src/i18n/locales/zh-cn/files.json
index 9b3ba7892..2c1934d6f 100644
--- a/packages/vue/src/i18n/locales/zh-cn/files.json
+++ b/packages/vue/src/i18n/locales/zh-cn/files.json
@@ -26,6 +26,11 @@
"searchRecentAndStorageFiles": "搜索最近使用和存储的文件…",
"newDesign": "新建设计",
"noMatchingFiles": "没有与“{query}”匹配的文件。",
+ "documentActions": "{name} 的操作",
+ "deleteDocument": "删除",
+ "deleteDocumentConfirmation": "删除“{name}”?",
+ "deleteDocumentDescription": "该文档将对所有可以打开它的人删除。此操作无法撤销。",
+ "deleteDocumentFailed": "无法删除“{name}”。请重试。",
"saveAsPrompt": "另存为:",
"browserFileAPINotSupported": "你的浏览器不支持本地文件 API。文件将被下载,而不是保存在原位置。",
"newDesignIn": "在 {place} 中新建设计"
diff --git a/packages/vue/src/i18n/messages/files.ts b/packages/vue/src/i18n/messages/files.ts
index 1500d2361..f3c432fbd 100644
--- a/packages/vue/src/i18n/messages/files.ts
+++ b/packages/vue/src/i18n/messages/files.ts
@@ -37,6 +37,12 @@ export const filesMessageDefaults = {
newDesign: 'New design',
newDesignIn: params('New design in {place}'),
noMatchingFiles: params('No files match “{query}”.'),
+ documentActions: params('Actions for {name}'),
+ deleteDocument: 'Delete',
+ deleteDocumentConfirmation: params('Delete “{name}”?'),
+ deleteDocumentDescription:
+ 'The document is deleted for everyone who can open it. This can’t be undone.',
+ deleteDocumentFailed: params('Couldn’t delete “{name}”. Try again.'),
saveAsPrompt: 'Save as:',
browserFileAPINotSupported:
"Your browser doesn't support the local file API. Files will be downloaded instead of saved in place."
diff --git a/src/app/integrations/storage/cloud/adapter.ts b/src/app/integrations/storage/cloud/adapter.ts
index dfd0bcc41..d7b179281 100644
--- a/src/app/integrations/storage/cloud/adapter.ts
+++ b/src/app/integrations/storage/cloud/adapter.ts
@@ -178,7 +178,10 @@ export function createCloudStorageAdapter(
},
async deleteDocument(id) {
- await (await client()).deleteDocument(id)
+ // Already gone, deleted by someone else or by a try whose answer was lost, is deleted.
+ await (await client()).deleteDocument(id).catch((error: unknown) => {
+ if (!(error instanceof CloudAPIError && error.code === 'not_found')) throw error
+ })
},
async getDocumentMetadata(id) {
diff --git a/src/app/recent-files/index.ts b/src/app/recent-files/index.ts
index 620794def..5552936d8 100644
--- a/src/app/recent-files/index.ts
+++ b/src/app/recent-files/index.ts
@@ -2,6 +2,7 @@ export {
clearRecentFiles,
forgetRecentDocument,
forgetRecentFile,
+ forgetRecentStorageDocument,
recentDocuments,
recentFiles,
recentLocalFileAt,
diff --git a/src/app/recent-files/store.ts b/src/app/recent-files/store.ts
index a2c2dbc5d..63738a023 100644
--- a/src/app/recent-files/store.ts
+++ b/src/app/recent-files/store.ts
@@ -102,6 +102,10 @@ export function forgetRecentFile(path: string): void {
forgetRecentDocument(localDocumentId(path))
}
+export function forgetRecentStorageDocument(binding: StorageDocumentBinding): void {
+ forgetRecentDocument(storageDocumentId(binding))
+}
+
export async function clearRecentFiles(): Promise<void> {
recentDocuments.value = []
await clearRecentFileThumbnails()
diff --git a/src/app/storage/local-store/idb.ts b/src/app/storage/local-store/idb.ts
index dd520ce86..50f8f8a87 100644
--- a/src/app/storage/local-store/idb.ts
+++ b/src/app/storage/local-store/idb.ts
@@ -9,7 +9,12 @@ import {
readStoredBinary,
type StoredBinary
} from '@/app/storage/idb'
-import { buildIndexMeta, buildWriteMeta, sortAndFilterMetas } from '@/app/storage/local-store/meta'
+import {
+ buildIndexMeta,
+ buildWriteMeta,
+ sameLocalCanvasState,
+ sortAndFilterMetas
+} from '@/app/storage/local-store/meta'
import type { LocalCanvasStore } from '@/app/storage/local-store/store'
import type { LocalCanvasMeta, LocalCanvasWriteInput } from '@/app/storage/local-store/types'
@@ -166,14 +171,23 @@ export function createIdbLocalCanvasStore(): LocalCanvasStore {
return meta
},
- async remove(id: string) {
+ async remove(id: string, options) {
const transaction = (await database.open()).transaction(['meta', 'fig', 'thumb'], 'readwrite')
+ const expected = options?.unchangedFrom
+ if (expected) {
+ const existing = await transaction.objectStore('meta').get(id)
+ if (!existing || !sameLocalCanvasState(existing, expected)) {
+ await transaction.done
+ return false
+ }
+ }
await Promise.all([
transaction.objectStore('meta').delete(id),
transaction.objectStore('fig').delete(id),
transaction.objectStore('thumb').delete(id)
])
await transaction.done
+ return true
},
async clearAll() {
diff --git a/src/app/storage/local-store/memory.ts b/src/app/storage/local-store/memory.ts
index c2d22c7ee..ec8d8e663 100644
--- a/src/app/storage/local-store/memory.ts
+++ b/src/app/storage/local-store/memory.ts
@@ -1,4 +1,9 @@
-import { buildIndexMeta, buildWriteMeta, sortAndFilterMetas } from '@/app/storage/local-store/meta'
+import {
+ buildIndexMeta,
+ buildWriteMeta,
+ sameLocalCanvasState,
+ sortAndFilterMetas
+} from '@/app/storage/local-store/meta'
import type { LocalCanvasStore } from '@/app/storage/local-store/store'
import type { LocalCanvasMeta, LocalCanvasWriteInput } from '@/app/storage/local-store/types'
@@ -102,10 +107,14 @@ export function createMemoryLocalCanvasStore(): LocalCanvasStore {
return meta
},
- async remove(id: string) {
+ async remove(id: string, options) {
+ const expected = options?.unchangedFrom
+ const existing = metas.get(id)
+ if (expected && (!existing || !sameLocalCanvasState(existing, expected))) return false
metas.delete(id)
figs.delete(id)
thumbs.delete(id)
+ return true
},
async clearAll() {
diff --git a/src/app/storage/local-store/meta.ts b/src/app/storage/local-store/meta.ts
index 8cbc6b78b..c07e33b15 100644
--- a/src/app/storage/local-store/meta.ts
+++ b/src/app/storage/local-store/meta.ts
@@ -1,6 +1,7 @@
import type {
LocalCanvasIndexInput,
LocalCanvasMeta,
+ LocalCanvasState,
LocalCanvasWriteInput
} from '@/app/storage/local-store/types'
@@ -88,3 +89,12 @@ export function buildIndexMeta(
conflictRevision: existing?.conflictRevision ?? null
}
}
+
+/** Whether a row is still in the state a caller read it in. */
+export function sameLocalCanvasState(row: LocalCanvasMeta, state: LocalCanvasState): boolean {
+ return (
+ row.revision === state.revision &&
+ row.syncStatus === state.syncStatus &&
+ row.tombstoned === state.tombstoned
+ )
+}
diff --git a/src/app/storage/local-store/store.ts b/src/app/storage/local-store/store.ts
index 8b3d74740..94dbd5dfe 100644
--- a/src/app/storage/local-store/store.ts
+++ b/src/app/storage/local-store/store.ts
@@ -3,6 +3,7 @@ import { createMemoryLocalCanvasStore } from '@/app/storage/local-store/memory'
import type {
LocalCanvasIndexInput,
LocalCanvasMeta,
+ LocalCanvasState,
LocalCanvasWriteInput
} from '@/app/storage/local-store/types'
@@ -11,6 +12,11 @@ export type UpdateLocalCanvasMetaOptions = {
expectedRevision?: number
}
+export type RemoveLocalCanvasOptions = {
+ /** Remove only if the row is still in this state, checked in the same transaction. */
+ unchangedFrom?: LocalCanvasState
+}
+
export type LocalCanvasStore = {
listMetas(includeTombstones?: boolean): Promise<LocalCanvasMeta[]>
getMeta(id: string): Promise<LocalCanvasMeta | null>
@@ -28,7 +34,8 @@ export type LocalCanvasStore = {
tombstone(id: string): Promise<LocalCanvasMeta | null>
/** Drop only the cached fig blob (eviction) — meta and thumb stay. */
clearFig(id: string): Promise<LocalCanvasMeta | null>
- remove(id: string): Promise<void>
+ /** Removes the copy, and says whether it did; a changed row stays under `unchangedFrom`. */
+ remove(id: string, options?: RemoveLocalCanvasOptions): Promise<boolean>
clearAll(): Promise<void>
}
diff --git a/src/app/storage/local-store/types.ts b/src/app/storage/local-store/types.ts
index f0a0df5ca..b4ac18797 100644
--- a/src/app/storage/local-store/types.ts
+++ b/src/app/storage/local-store/types.ts
@@ -56,3 +56,6 @@ export type LocalCanvasWriteInput = LocalCanvasLocation & {
/** Replaces the base revision, as when the bytes come straight from the provider. */
remoteRevision?: string | null
}
+
+/** The state a copy must still be in for a conditional removal to go ahead. */
+export type LocalCanvasState = Pick<LocalCanvasMeta, 'revision' | 'syncStatus' | 'tombstoned'>
diff --git a/src/app/storage/reconcile.ts b/src/app/storage/reconcile.ts
index 162f3e04f..26f05ac9f 100644
--- a/src/app/storage/reconcile.ts
+++ b/src/app/storage/reconcile.ts
@@ -23,8 +23,12 @@ export function reconcileStorageDocuments(
.map((document) => [document.id, document])
)
+ // A synced copy the provider no longer lists was deleted there, by another device or person.
+ const deletedRemotely = (metadata: LocalCanvasMeta) =>
+ metadata.syncStatus === 'synced' && !remoteIds.has(metadata.id)
+
for (const metadata of local) {
- if (metadata.tombstoned) continue
+ if (metadata.tombstoned || deletedRemotely(metadata)) continue
if (metadata.syncStatus === 'synced' && merged.has(metadata.id)) continue
merged.set(metadata.id, {
id: metadata.id,
@@ -41,7 +45,10 @@ export function reconcileStorageDocuments(
),
remoteDocumentsToSeed: remote.filter((document) => !localById.has(document.id)),
localIdsToPurge: local
- .filter((metadata) => metadata.tombstoned && !remoteIds.has(metadata.id))
+ .filter(
+ (metadata) =>
+ (metadata.tombstoned && !remoteIds.has(metadata.id)) || deletedRemotely(metadata)
+ )
.map((metadata) => metadata.id)
}
}
diff --git a/src/app/storage/workspace/delete.ts b/src/app/storage/workspace/delete.ts
new file mode 100644
index 000000000..0982e35fe
--- /dev/null
+++ b/src/app/storage/workspace/delete.ts
@@ -0,0 +1,75 @@
+import {
+ sameStorageDocument,
+ sameStorageLocation,
+ storageLocationOf,
+ type StorageDocument,
+ type StorageDocumentBinding,
+ type StorageLocation
+} from '@/app/integrations/storage'
+import { forgetRecentStorageDocument } from '@/app/recent-files'
+import { getLocalCanvasStore } from '@/app/storage/local-store'
+import { enqueueDeleteCanvas } from '@/app/storage/sync'
+import { emitStorageWorkspaceEvent } from '@/app/storage/workspace/events'
+import { closeTab, getTabsSnapshot } from '@/app/tabs'
+
+/**
+ * Deletes a stored document for everyone, once the person has confirmed it. Home stops listing it at
+ * once and the provider deletes it when the sync engine reaches the job, so a deletion made offline
+ * or refused for now is kept until it goes through. The document's tabs in this window close last,
+ * without asking, so a deletion that could not be recorded leaves their edits as they were.
+ */
+export async function deleteStoredDocument(
+ document: StorageDocument,
+ location: StorageLocation
+): Promise<void> {
+ const binding: StorageDocumentBinding = {
+ ...storageLocationOf(location),
+ documentId: document.id
+ }
+ const store = getLocalCanvasStore()
+ // The sync engine finds the provider through the device's copy, which home seeds as it lists.
+ const copy =
+ (await store.getMeta(document.id)) ??
+ (await store.upsertIndexMeta({
+ id: document.id,
+ ...storageLocationOf(location),
+ name: document.name,
+ updatedAt: document.updatedAt,
+ syncStatus: 'synced',
+ lastSyncedAt: document.updatedAt,
+ lastSyncError: null,
+ remoteRevision: document.revision ?? null
+ }))
+ // The job deletes wherever the copy lives, so a copy of another location is not this document.
+ if (!sameStorageLocation(storageLocationOf(copy), location)) {
+ throw new Error(`Document ${document.id} is stored in another location`)
+ }
+ await store.tombstone(document.id)
+ try {
+ await enqueueDeleteCanvas(document.id)
+ } catch (error) {
+ // Without its job the tombstone would hide a document that stays in storage. The sync state
+ // goes back only if nothing was saved meanwhile, since a newer save has its own upload to make.
+ await store.updateMeta(document.id, { tombstoned: copy.tombstoned })
+ await store.updateMeta(
+ document.id,
+ { syncStatus: copy.syncStatus, updatedAt: copy.updatedAt },
+ { expectedRevision: copy.revision }
+ )
+ throw error
+ }
+ forgetRecentStorageDocument(binding)
+ emitStorageWorkspaceEvent({
+ ...storageLocationOf(location),
+ documentId: document.id,
+ kind: 'changed'
+ })
+ // The deletion is recorded by now, so a tab that fails to close does not undo it.
+ for (const tab of getTabsSnapshot()) {
+ const open = tab.store.getStorageBinding()
+ if (!open || !sameStorageDocument(open, binding)) continue
+ await closeTab(tab.id, 'discard').catch((error: unknown) => {
+ console.error('[Storage] Closing a deleted document’s tab failed:', error)
+ })
+ }
+}
diff --git a/src/app/storage/workspace/source.ts b/src/app/storage/workspace/source.ts
index ba9a974c6..206c612e8 100644
--- a/src/app/storage/workspace/source.ts
+++ b/src/app/storage/workspace/source.ts
@@ -6,7 +6,11 @@ import {
sameStorageLocation,
storageLocationOf
} from '@/app/integrations/storage'
-import { getLocalCanvasStore } from '@/app/storage/local-store'
+import {
+ getLocalCanvasStore,
+ type LocalCanvasMeta,
+ type LocalCanvasStore
+} from '@/app/storage/local-store'
import { reconcileStorageDocuments } from '@/app/storage/reconcile'
import { onStorageWorkspaceEvent } from '@/app/storage/workspace/events'
@@ -15,6 +19,22 @@ export type StorageWorkspaceSnapshot = {
configured: boolean
}
+/**
+ * Removes this device's copies that reconciliation found deleted, each only if it is as it was when
+ * read: listing the provider takes a while, and an edit saved meanwhile makes it unsent work again.
+ */
+export async function purgeUnchangedCopies(
+ store: LocalCanvasStore,
+ read: LocalCanvasMeta[],
+ ids: string[]
+): Promise<void> {
+ const before = new Map(read.map((metadata) => [metadata.id, metadata]))
+ for (const id of ids) {
+ const unchangedFrom = before.get(id)
+ if (unchangedFrom) await store.remove(id, { unchangedFrom })
+ }
+}
+
/** The configured storage bucket, the location home lists when no other is chosen. */
export function activeStorageLocation(): StorageLocation {
return { providerId: activeStorageProviderID.value }
@@ -70,7 +90,7 @@ export function createStorageWorkspaceSource(
throw error
}
const reconciliation = reconcileStorageDocuments(local, remote)
- for (const id of reconciliation.localIdsToPurge) await localStore.remove(id)
+ await purgeUnchangedCopies(localStore, local, reconciliation.localIdsToPurge)
for (const document of reconciliation.remoteDocumentsToSeed) {
await localStore.upsertIndexMeta({
id: document.id,
diff --git a/src/components/home/HomeWorkspace.vue b/src/components/home/HomeWorkspace.vue
index b60260196..00976735e 100644
--- a/src/components/home/HomeWorkspace.vue
+++ b/src/components/home/HomeWorkspace.vue
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { useLocalStorage } from '@vueuse/core'
-import { computed, ref } from 'vue'
+import { computed, ref, shallowRef } from 'vue'
import { useDocumentWorkspace } from '@open-pencil/vue/document/workspace'
import { useI18n } from '@open-pencil/vue/i18n'
@@ -25,9 +25,10 @@ import {
import { useCredentialSettings } from '@/app/settings/credentials/preferences/use'
import { openSettingsDialog } from '@/app/settings/dialog'
import { createStoredDocument } from '@/app/storage/workspace/create'
-import { createStorageWorkspaceSource } from '@/app/storage/workspace/source'
+import { activeStorageLocation, createStorageWorkspaceSource } from '@/app/storage/workspace/source'
import { openStorageDocumentInNewTab } from '@/app/tabs'
import { CloudSharedSection, CloudWorkspaceSection } from '@/components/cloud/integration'
+import DocumentDeleteDialog from '@/components/home/document/DocumentDeleteDialog.vue'
import DocumentEntry from '@/components/home/document/DocumentEntry.vue'
import HomeLayout from '@/components/home/HomeLayout.vue'
import RecentFilesSection from '@/components/home/recent/RecentFilesSection.vue'
@@ -64,6 +65,14 @@ const storageWorkspace = useDocumentWorkspace<StorageDocument>({
previewConcurrency: 6
})
const storageDocuments = storageWorkspace.documents
+const storageLocation = computed(() => activeStorageLocation())
+const deletingStorageDocument = shallowRef<StorageDocument | null>(null)
+function documentMenu(document: StorageDocument) {
+ return {
+ actions: files.value.documentActions({ name: document.name }),
+ delete: files.value.deleteDocument
+ }
+}
const storageLoading = storageWorkspace.loading
// Paused credential access has its own fix, so the card offers it instead of the raw native error.
const credentialAccess = useCredentialSettings()
@@ -323,7 +332,9 @@ function formattedDate(updatedAt: string): string {
:name="document.name"
:metadata="formattedDate(document.updatedAt)"
:previewURL="storagePreviewURL(document.id)"
+ :menu="documentMenu(document)"
@open="openStorageDocument(document)"
+ @delete="deletingStorageDocument = document"
/>
</div>
@@ -337,7 +348,9 @@ function formattedDate(updatedAt: string): string {
view="list"
:name="document.name"
:metadata="formattedDate(document.updatedAt)"
+ :menu="documentMenu(document)"
@open="openStorageDocument(document)"
+ @delete="deletingStorageDocument = document"
/>
</div>
@@ -357,6 +370,10 @@ function formattedDate(updatedAt: string): string {
>
{{ storage.emptyStorageWorkspace }}
</div>
+ <DocumentDeleteDialog
+ v-model:document="deletingStorageDocument"
+ :location="storageLocation"
+ />
</section>
</template>
</HomeLayout>
diff --git a/src/components/home/cloud/CloudWorkspaceSection.vue b/src/components/home/cloud/CloudWorkspaceSection.vue
index 3dab479d2..deb25ae56 100644
--- a/src/components/home/cloud/CloudWorkspaceSection.vue
+++ b/src/components/home/cloud/CloudWorkspaceSection.vue
@@ -22,6 +22,7 @@ import { pendingSyncCount, syncUIState, uploadProgressByCanvas } from '@/app/sto
import { createStoredDocument } from '@/app/storage/workspace/create'
import { createStorageWorkspaceSource } from '@/app/storage/workspace/source'
import { openStorageDocumentInNewTab } from '@/app/tabs'
+import DocumentDeleteDialog from '@/components/home/document/DocumentDeleteDialog.vue'
import CloudWorkspaceView from './CloudWorkspaceView.vue'
import type { CloudDocumentRow } from './types'
@@ -139,6 +140,11 @@ function reviewConflicts() {
if (conflicted) open(conflicted)
}
+const deleting = shallowRef<StorageDocument | null>(null)
+function requestDelete(row: CloudDocumentRow) {
+ deleting.value = listed.value.find((candidate) => candidate.id === row.id) ?? null
+}
+
function open(row: CloudDocumentRow) {
const document = listed.value.find((candidate) => candidate.id === row.id)
if (!document) return
@@ -156,10 +162,13 @@ function open(row: CloudDocumentRow) {
:state="state"
:usage="usage"
:can-create="workspace.role !== 'viewer'"
+ :can-delete="workspace.role !== 'viewer'"
@open="open"
+ @delete="requestDelete"
@members="openWorkspaceMembers(serverId, workspace.id)"
@refresh="files.refresh"
@new-design="createStoredDocument(location)"
@review-conflicts="reviewConflicts"
/>
+ <DocumentDeleteDialog v-model:document="deleting" :location="location" />
</template>
diff --git a/src/components/home/cloud/CloudWorkspaceView.vue b/src/components/home/cloud/CloudWorkspaceView.vue
index 4ab9d2e71..2286eef78 100644
--- a/src/components/home/cloud/CloudWorkspaceView.vue
+++ b/src/components/home/cloud/CloudWorkspaceView.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed } from 'vue'
-import { useCloudMessages, useCommonMessages } from '@open-pencil/vue/i18n'
+import { useCloudMessages, useCommonMessages, useFileMessages } from '@open-pencil/vue/i18n'
import { formatStorageBytes } from '@/app/storage/format-bytes'
import DocumentEntry from '@/components/home/document/DocumentEntry.vue'
@@ -28,7 +28,8 @@ const {
documents,
usage = null,
state = 'ready',
- canCreate = false
+ canCreate = false,
+ canDelete = false
} = defineProps<{
heading: string
subtitle?: string
@@ -39,11 +40,14 @@ const {
state?: 'loading' | 'ready' | 'offline' | 'error'
/** The person may create designs here. */
canCreate?: boolean
+ /** The person may delete the designs listed here. */
+ canDelete?: boolean
}>()
const view = defineModel<'grid' | 'list'>('view', { default: 'grid' })
const emit = defineEmits<{
open: [document: CloudDocumentRow]
+ delete: [document: CloudDocumentRow]
newDesign: []
members: []
refresh: []
@@ -52,6 +56,14 @@ const emit = defineEmits<{
const t = useCloudMessages()
const common = useCommonMessages()
+const files = useFileMessages()
+const menu = (document: CloudDocumentRow) =>
+ canDelete
+ ? {
+ actions: files.value.documentActions({ name: document.name }),
+ delete: files.value.deleteDocument
+ }
+ : undefined
const conflicts = computed(() => documents.filter((document) => document.sync === 'conflict'))
const usageLabel = computed(() => {
if (!usage) return null
@@ -191,7 +203,9 @@ const metadata = (document: CloudDocumentRow) =>
:name="document.name"
:metadata="metadata(document)"
:previewURL="document.previewURL"
+ :menu="menu(document)"
@open="emit('open', document)"
+ @delete="emit('delete', document)"
>
<template #status>
<Tip v-if="document.permission === 'view'" :label="t.homeViewOnlyTip">
diff --git a/src/components/home/document/DocumentDeleteDialog.vue b/src/components/home/document/DocumentDeleteDialog.vue
new file mode 100644
index 000000000..dcc91d2eb
--- /dev/null
+++ b/src/components/home/document/DocumentDeleteDialog.vue
@@ -0,0 +1,55 @@
+<script setup lang="ts">
+import { ref, shallowRef, watch } from 'vue'
+
+import { useCommonMessages, useFileMessages } from '@open-pencil/vue/i18n'
+
+import type { StorageDocument, StorageLocation } from '@/app/integrations/storage'
+import { toast } from '@/app/shell/ui'
+import { deleteStoredDocument } from '@/app/storage/workspace/delete'
+import { AppConfirmationDialog } from '@/components/ui/dialog'
+
+/** Asks before a stored document is deleted for everyone who can open it. */
+const { location } = defineProps<{ location: StorageLocation }>()
+/** The document to ask about; set it to ask, and it is cleared once the dialog closes. */
+const document = defineModel<StorageDocument | null>('document', { default: null })
+const files = useFileMessages()
+const common = useCommonMessages()
+
+// The dialog closes itself before it confirms, and keeps its heading while it animates closed,
+// so it holds the document it was asked about apart from the model.
+const open = ref(false)
+const target = shallowRef<StorageDocument | null>(null)
+watch(
+ document,
+ (next) => {
+ if (!next) return
+ target.value = next
+ open.value = true
+ },
+ { immediate: true }
+)
+watch(open, (value) => {
+ if (!value) document.value = null
+})
+
+function confirm() {
+ const deleting = target.value
+ if (!deleting) return
+ void deleteStoredDocument(deleting, location).catch((error: unknown) => {
+ console.error('[Storage] Deleting a document failed:', error)
+ toast.error(files.value.deleteDocumentFailed({ name: deleting.name }))
+ })
+}
+</script>
+
+<template>
+ <AppConfirmationDialog
+ v-model:open="open"
+ :heading="files.deleteDocumentConfirmation({ name: target?.name ?? '' })"
+ :description="files.deleteDocumentDescription"
+ :cancel-label="common.cancel"
+ :confirm-label="files.deleteDocument"
+ tone="danger"
+ @confirm="confirm"
+ />
+</template>
diff --git a/src/components/home/document/DocumentEntry.stories.ts b/src/components/home/document/DocumentEntry.stories.ts
index 501826759..eded2b41a 100644
--- a/src/components/home/document/DocumentEntry.stories.ts
+++ b/src/components/home/document/DocumentEntry.stories.ts
@@ -12,7 +12,13 @@ const meta = {
template:
'<div class="max-w-sm bg-panel p-4 text-surface"><DocumentEntry v-bind="args" /></div>'
})
-} satisfies Meta<{ name: string; metadata: string; view: 'grid' | 'list'; disabled?: boolean }>
+} satisfies Meta<{
+ name: string
+ metadata: string
+ view: 'grid' | 'list'
+ disabled?: boolean
+ menu?: { actions: string; delete: string }
+}>
export default meta
type Story = StoryObj<typeof meta>
@@ -22,3 +28,6 @@ export const LongName: Story = {
args: { name: 'A deliberately long document name that must stay inside the document card' }
}
export const Disabled: Story = { args: { disabled: true } }
+const menu = { actions: 'Actions for Design system', delete: 'Delete' }
+export const WithMenu: Story = { args: { menu } }
+export const ListWithMenu: Story = { args: { view: 'list', menu } }
diff --git a/src/components/home/document/DocumentEntry.vue b/src/components/home/document/DocumentEntry.vue
index 193c6e337..945a8716d 100644
--- a/src/components/home/document/DocumentEntry.vue
+++ b/src/components/home/document/DocumentEntry.vue
@@ -1,10 +1,26 @@
<script setup lang="ts">
+import {
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuPortal,
+ ContextMenuRoot,
+ ContextMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuPortal,
+ DropdownMenuRoot,
+ DropdownMenuTrigger
+} from 'reka-ui'
import { tv } from 'tailwind-variants'
import { computed, normalizeClass, type HTMLAttributes } from 'vue'
+import { useMenuUI } from '@/components/ui/menu/menu'
+import MenuScrollArea from '@/components/ui/menu/MenuScrollArea.vue'
+import iconButtonTheme from '@/theme/button/icon-button'
import documentEntryTheme from '@/theme/home/document-entry'
const documentEntry = tv(documentEntryTheme)
+const iconButton = tv(iconButtonTheme)
const {
name,
@@ -12,6 +28,7 @@ const {
previewURL,
view = 'grid',
disabled = false,
+ menu,
class: className
} = defineProps<{
name: string
@@ -19,39 +36,79 @@ const {
previewURL?: string | null
view?: 'grid' | 'list'
disabled?: boolean
+ /** Labels of the entry's menu, opened from its ⋯ button or by right-clicking; none without them. */
+ menu?: { actions: string; delete: string }
class?: HTMLAttributes['class']
}>()
-const emit = defineEmits<{ open: [] }>()
+const emit = defineEmits<{ open: []; delete: [] }>()
const styles = computed(() => documentEntry({ view }))
+const menuUI = useMenuUI({ content: 'min-w-40', item: 'justify-start gap-2 text-error' })
</script>
<template>
- <div data-slot="document-entry" :class="styles.root({ class: normalizeClass(className) })">
- <button
- type="button"
- :disabled="disabled"
- data-slot="trigger"
- :class="styles.trigger()"
- @click="emit('open')"
- >
- <span v-if="view === 'grid'" data-slot="preview" :class="styles.preview()">
- <img v-if="previewURL" :src="previewURL" alt="" :class="styles.image()" />
- <icon-lucide-file-image v-else :class="styles.fallback()" />
- </span>
- <icon-lucide-file-image v-else :class="styles.icon()" />
- <span data-slot="body" :class="styles.body()">
- <span data-slot="title" :class="styles.title()">
- <span data-slot="name" :class="styles.name()">{{ name }}</span>
- <span v-if="$slots.status" data-slot="status" :class="styles.status()">
- <slot name="status" />
+ <ContextMenuRoot :disabled="!menu">
+ <ContextMenuTrigger as-child>
+ <div data-slot="document-entry" :class="styles.root({ class: normalizeClass(className) })">
+ <button
+ type="button"
+ :disabled="disabled"
+ data-slot="trigger"
+ :class="styles.trigger()"
+ @click="emit('open')"
+ >
+ <span v-if="view === 'grid'" data-slot="preview" :class="styles.preview()">
+ <img v-if="previewURL" :src="previewURL" alt="" :class="styles.image()" />
+ <icon-lucide-file-image v-else :class="styles.fallback()" />
</span>
- </span>
- <span data-slot="metadata" :class="styles.metadata()">{{ metadata }}</span>
- </span>
- <span v-if="view === 'list'" :class="styles.trailingMetadata()">{{ metadata }}</span>
- </button>
- <div v-if="$slots.actions" data-slot="actions" :class="styles.actions()">
- <slot name="actions" />
- </div>
- </div>
+ <icon-lucide-file-image v-else :class="styles.icon()" />
+ <span data-slot="body" :class="styles.body()">
+ <span data-slot="title" :class="styles.title()">
+ <span data-slot="name" :class="styles.name()">{{ name }}</span>
+ <span v-if="$slots.status" data-slot="status" :class="styles.status()">
+ <slot name="status" />
+ </span>
+ </span>
+ <span data-slot="metadata" :class="styles.metadata()">{{ metadata }}</span>
+ </span>
+ <span v-if="view === 'list'" :class="styles.trailingMetadata()">{{ metadata }}</span>
+ </button>
+ <div v-if="$slots.actions" data-slot="actions" :class="styles.actions()">
+ <slot name="actions" />
+ </div>
+ <DropdownMenuRoot v-if="menu">
+ <DropdownMenuTrigger
+ :aria-label="menu.actions"
+ data-test-id="home-document-actions"
+ :class="iconButton({ size: 'xs', class: styles.menuTrigger() })"
+ >
+ <icon-lucide-ellipsis class="size-3.5" />
+ </DropdownMenuTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuContent align="end" :side-offset="4" :class="menuUI.content">
+ <MenuScrollArea>
+ <DropdownMenuItem
+ :class="menuUI.item"
+ data-test-id="home-document-delete"
+ @select="emit('delete')"
+ >
+ <icon-lucide-trash-2 :class="menuUI.icon" />
+ {{ menu.delete }}
+ </DropdownMenuItem>
+ </MenuScrollArea>
+ </DropdownMenuContent>
+ </DropdownMenuPortal>
+ </DropdownMenuRoot>
+ </div>
+ </ContextMenuTrigger>
+ <ContextMenuPortal v-if="menu">
+ <ContextMenuContent :class="menuUI.content">
+ <MenuScrollArea>
+ <ContextMenuItem :class="menuUI.item" @select="emit('delete')">
+ <icon-lucide-trash-2 :class="menuUI.icon" />
+ {{ menu.delete }}
+ </ContextMenuItem>
+ </MenuScrollArea>
+ </ContextMenuContent>
+ </ContextMenuPortal>
+ </ContextMenuRoot>
</template>
diff --git a/src/theme/home/document-entry.ts b/src/theme/home/document-entry.ts
index 10d91229a..0068a7654 100644
--- a/src/theme/home/document-entry.ts
+++ b/src/theme/home/document-entry.ts
@@ -1,6 +1,6 @@
export default {
slots: {
- root: 'group min-w-0',
+ root: 'group relative min-w-0',
trigger:
'min-w-0 w-full text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50 disabled:opacity-50',
preview:
@@ -14,15 +14,23 @@ export default {
status: 'flex shrink-0 items-center gap-1 text-muted',
metadata: 'mt-0.5 block truncate text-[10px] text-muted',
trailingMetadata: 'hidden shrink-0 text-[10px] text-muted sm:inline',
- actions: 'flex shrink-0 items-center gap-1'
+ actions: 'flex shrink-0 items-center gap-1',
+ // Over an icon button: shown on hover, focus, and while open; always on touch screens.
+ menuTrigger:
+ 'shrink-0 opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100 data-[state=open]:opacity-100 pointer-coarse:opacity-100'
},
variants: {
view: {
- grid: { body: 'mt-2 block', trailingMetadata: 'hidden sm:hidden' },
+ grid: {
+ body: 'mt-2 block',
+ trailingMetadata: 'hidden sm:hidden',
+ menuTrigger: 'absolute top-2 right-2 bg-panel/90 shadow-sm'
+ },
list: {
root: 'flex items-center border-b border-border last:border-b-0 hover:bg-hover',
trigger: 'flex min-h-14 items-center gap-3 px-3 py-2 sm:min-h-0 sm:px-4 sm:py-3',
- metadata: 'sm:hidden'
+ metadata: 'sm:hidden',
+ menuTrigger: 'mr-2 sm:mr-3'
}
}
},
diff --git a/tests/app/integrations/storage/cloud/adapter.test.ts b/tests/app/integrations/storage/cloud/adapter.test.ts
index 92a1c6096..17464b833 100644
--- a/tests/app/integrations/storage/cloud/adapter.test.ts
+++ b/tests/app/integrations/storage/cloud/adapter.test.ts
@@ -10,6 +10,8 @@ import { StorageRevisionConflictError } from '@/app/integrations/storage'
import { createCloudStorageAdapter } from '@/app/integrations/storage/cloud/adapter'
const WORKSPACE = '0b5a4e0a-2d1c-4d6e-9f1a-6b2c3d4e5f60'
+/** A document the signed-in person may not delete. */
+const FORBIDDEN = '5f1c2a3b-4d5e-4f60-8a7b-9c0d1e2f3a4b'
async function sha256(bytes: Uint8Array): Promise<string> {
return fromUint8Array(
@@ -158,6 +160,16 @@ function cloudServer() {
return json({ document: summary(upload.documentId, doc) })
}
],
+ [
+ 'DELETE',
+ /^\/documents\/([^/]+)$/,
+ ([, id = '']) => {
+ if (id === FORBIDDEN) return json({ error: { code: 'forbidden' } }, 403)
+ return documents.delete(id)
+ ? new Response(null, { status: 204 })
+ : json({ error: { code: 'not_found' } }, 404)
+ }
+ ],
[
'GET',
/^\/documents\/([^/]+)$/,
@@ -288,6 +300,23 @@ function adapter(server: ReturnType<typeof cloudServer>) {
}
describe('Cloud storage adapter', () => {
+ test('deletes a document, and counts one already gone as deleted', async () => {
+ const storage = adapter(cloudServer())
+ const id = crypto.randomUUID()
+ await storage.putDocument(id, new TextEncoder().encode('design'), {
+ name: 'Old',
+ updatedAt: ''
+ })
+ await storage.deleteDocument(id)
+ await storage.deleteDocument(id)
+ expect(await storage.listDocuments()).toEqual([])
+ })
+
+ test('reports a deletion Cloud refuses', async () => {
+ const storage = adapter(cloudServer())
+ await expect(storage.deleteDocument(FORBIDDEN)).rejects.toMatchObject({ code: 'forbidden' })
+ })
+
test('saves an edited title with an existing document revision', async () => {
const storage = adapter(cloudServer())
const id = crypto.randomUUID()
diff --git a/tests/engine/app/storage/reconcile.test.ts b/tests/app/storage/reconcile.test.ts
similarity index 81%
rename from tests/engine/app/storage/reconcile.test.ts
rename to tests/app/storage/reconcile.test.ts
index 7363899f1..034ecead3 100644
--- a/tests/engine/app/storage/reconcile.test.ts
+++ b/tests/app/storage/reconcile.test.ts
@@ -60,4 +60,12 @@ describe('storage workspace reconciliation', () => {
const confirmed = reconcileStorageDocuments([localMeta('deleted', 'synced', true)], [])
expect(confirmed.localIdsToPurge).toEqual(['deleted'])
})
+ test('drops a synced copy the provider no longer lists, and keeps unsent work', () => {
+ const result = reconcileStorageDocuments(
+ [localMeta('deleted', 'synced'), localMeta('unsent', 'pending'), localMeta('kept', 'synced')],
+ [remoteDocument('kept')]
+ )
+ expect(result.documents.map((document) => document.id).sort()).toEqual(['kept', 'unsent'])
+ expect(result.localIdsToPurge).toEqual(['deleted'])
+ })
})
diff --git a/tests/app/storage/workspace/delete.test.ts b/tests/app/storage/workspace/delete.test.ts
new file mode 100644
index 000000000..41121467a
--- /dev/null
+++ b/tests/app/storage/workspace/delete.test.ts
@@ -0,0 +1,132 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
+
+import { recentDocuments, rememberRecentStorageDocument } from '@/app/recent-files'
+import { createMemoryLocalCanvasStore, type LocalCanvasStore } from '@/app/storage/local-store'
+import { resetLocalCanvasStoreForTests } from '@/app/storage/local-store/store'
+import { createMemoryOutbox, getOutbox, resetOutboxForTests } from '@/app/storage/sync'
+import { deleteStoredDocument } from '@/app/storage/workspace/delete'
+import { onStorageWorkspaceEvent } from '@/app/storage/workspace/events'
+import { closeTab, createTab, getTabsSnapshot } from '@/app/tabs'
+
+const BUCKET = { providerId: 's3-compatible' }
+const CLOUD = { providerId: 'cloud', profileId: 'server', containerId: 'workspace' }
+const POSTER = { id: 'poster', name: 'Poster', updatedAt: '2026-10-01T00:00:00.000Z' }
+
+let store: LocalCanvasStore
+let recentBefore: typeof recentDocuments.value
+
+const recentPoster = () =>
+ recentDocuments.value.some(
+ (document) => document.kind === 'storage' && document.documentId === POSTER.id
+ )
+
+beforeEach(() => {
+ // Recent files live in shared storage; each test starts from none and leaves them as it found them.
+ recentBefore = recentDocuments.value
+ recentDocuments.value = []
+ store = createMemoryLocalCanvasStore()
+ resetLocalCanvasStoreForTests(store)
+ resetOutboxForTests(createMemoryOutbox())
+})
+
+afterEach(() => {
+ recentDocuments.value = recentBefore
+ resetLocalCanvasStoreForTests()
+ resetOutboxForTests()
+})
+
+describe('deleting a stored document', () => {
+ test('hides it, queues its deletion, and drops it from recent files', async () => {
+ await store.writeCanvas({
+ id: POSTER.id,
+ ...BUCKET,
+ name: POSTER.name,
+ figBytes: new Uint8Array([1]),
+ syncStatus: 'synced'
+ })
+ rememberRecentStorageDocument({ ...BUCKET, documentId: POSTER.id }, POSTER.name)
+ rememberRecentStorageDocument({ ...BUCKET, documentId: 'flyer' }, 'Flyer')
+ expect(recentPoster()).toBe(true)
+ const events: string[] = []
+ const stop = onStorageWorkspaceEvent((event) =>
+ events.push(`${event.kind}:${event.documentId}`)
+ )
+
+ await deleteStoredDocument(POSTER, BUCKET)
+ stop()
+
+ expect(await store.listMetas()).toEqual([])
+ expect(await getOutbox().list()).toMatchObject([{ canvasId: POSTER.id, type: 'deleteCanvas' }])
+ expect(recentPoster()).toBe(false)
+ expect(recentDocuments.value.map((document) => document.name)).toEqual(['Flyer'])
+ expect(events).toContain(`changed:${POSTER.id}`)
+ })
+
+ test('remembers where a document without a local copy lives, so its deletion reaches it', async () => {
+ await deleteStoredDocument(POSTER, CLOUD)
+
+ expect(await store.getMeta(POSTER.id)).toMatchObject({ ...CLOUD, tombstoned: true })
+ expect(await getOutbox().list()).toMatchObject([{ canvasId: POSTER.id, type: 'deleteCanvas' }])
+ })
+ test('refuses a copy of the same ID that lives in another location', async () => {
+ await store.writeCanvas({
+ id: POSTER.id,
+ ...BUCKET,
+ name: POSTER.name,
+ figBytes: new Uint8Array([1]),
+ syncStatus: 'synced'
+ })
+
+ await expect(deleteStoredDocument(POSTER, CLOUD)).rejects.toThrow('another location')
+ expect(await store.getMeta(POSTER.id)).toMatchObject({ ...BUCKET, tombstoned: false })
+ expect(await getOutbox().list()).toEqual([])
+ })
+
+ test('shows the document again when its deletion cannot be queued', async () => {
+ await store.writeCanvas({
+ id: POSTER.id,
+ ...BUCKET,
+ name: POSTER.name,
+ figBytes: new Uint8Array([1]),
+ syncStatus: 'synced'
+ })
+ const outbox = createMemoryOutbox()
+ resetOutboxForTests({
+ ...outbox,
+ enqueue: () => Promise.reject(new Error('quota exceeded'))
+ })
+
+ await expect(deleteStoredDocument(POSTER, BUCKET)).rejects.toThrow('quota exceeded')
+ expect(await store.listMetas()).toMatchObject([{ id: POSTER.id, syncStatus: 'synced' }])
+ })
+ test('keeps an earlier deletion hidden when a repeated one cannot be queued', async () => {
+ await store.writeCanvas({
+ id: POSTER.id,
+ ...BUCKET,
+ name: POSTER.name,
+ figBytes: new Uint8Array([1]),
+ syncStatus: 'synced'
+ })
+ await store.tombstone(POSTER.id)
+ resetOutboxForTests({
+ ...createMemoryOutbox(),
+ enqueue: () => Promise.reject(new Error('quota exceeded'))
+ })
+
+ await expect(deleteStoredDocument(POSTER, BUCKET)).rejects.toThrow('quota exceeded')
+ expect(await store.getMeta(POSTER.id)).toMatchObject({ tombstoned: true })
+ })
+ test("closes this document's tabs and leaves other tabs open", async () => {
+ const deleted = createTab()
+ deleted.store.setStorageDocumentSource({ ...BUCKET, documentId: POSTER.id }, POSTER.name)
+ const other = createTab()
+ other.store.setStorageDocumentSource({ ...BUCKET, documentId: 'flyer' }, 'Flyer')
+
+ await deleteStoredDocument(POSTER, BUCKET)
+
+ const open = getTabsSnapshot().map((tab) => tab.id)
+ expect(open).not.toContain(deleted.id)
+ expect(open).toContain(other.id)
+ await closeTab(other.id, 'discard')
+ })
+})
diff --git a/tests/app/storage/workspace/source.test.ts b/tests/app/storage/workspace/source.test.ts
new file mode 100644
index 000000000..0e38c18f8
--- /dev/null
+++ b/tests/app/storage/workspace/source.test.ts
@@ -0,0 +1,52 @@
+import 'fake-indexeddb/auto'
+import { describe, expect, test } from 'bun:test'
+
+import { createMemoryLocalCanvasStore, type LocalCanvasStore } from '@/app/storage/local-store'
+import { createIdbLocalCanvasStore } from '@/app/storage/local-store/idb'
+import { purgeUnchangedCopies } from '@/app/storage/workspace/source'
+
+function write(store: LocalCanvasStore, id: string, syncStatus: 'synced' | 'pending') {
+ return store.writeCanvas({
+ id,
+ providerId: 's3-compatible',
+ name: id,
+ figBytes: new Uint8Array([1]),
+ syncStatus
+ })
+}
+
+for (const [kind, create] of [
+ ['memory', createMemoryLocalCanvasStore],
+ ['IndexedDB', createIdbLocalCanvasStore]
+] as const) {
+ describe(`purging copies deleted from storage (${kind})`, () => {
+ test('removes a copy that stayed as it was read', async () => {
+ const store = create()
+ const id = crypto.randomUUID()
+ await write(store, id, 'synced')
+ await purgeUnchangedCopies(store, await store.listMetas(true), [id])
+ expect(await store.getMeta(id)).toBeNull()
+ expect(await store.readFig(id)).toBeNull()
+ })
+
+ test('keeps a copy edited while the provider was listed', async () => {
+ const store = create()
+ const id = crypto.randomUUID()
+ await write(store, id, 'synced')
+ const read = await store.listMetas(true)
+ await write(store, id, 'pending')
+ await purgeUnchangedCopies(store, read, [id])
+ expect(await store.getMeta(id)).toMatchObject({ syncStatus: 'pending', revision: 2 })
+ })
+
+ test('keeps a copy replaced by a newer synced one while the provider was listed', async () => {
+ const store = create()
+ const id = crypto.randomUUID()
+ await write(store, id, 'synced')
+ const read = await store.listMetas(true)
+ await write(store, id, 'synced')
+ await purgeUnchangedCopies(store, read, [id])
+ expect(await store.getMeta(id)).toMatchObject({ syncStatus: 'synced', revision: 2 })
+ })
+ })
+}
diff --git a/tests/e2e/storage/workspace.spec.ts b/tests/e2e/storage/workspace.spec.ts
index c7854b299..885cdd037 100644
--- a/tests/e2e/storage/workspace.spec.ts
+++ b/tests/e2e/storage/workspace.spec.ts
@@ -1,10 +1,55 @@
import { readFileSync } from 'node:fs'
-import { expect, test } from '@playwright/test'
+import { expect, test, type Page } from '@playwright/test'
import { CanvasHelper } from '#tests/helpers/canvas'
import { openAppMenu } from '#tests/helpers/menu'
+/** An S3 bucket held in memory that lists, stores, reads, and deletes objects. */
+async function memoryBucket(page: Page): Promise<Map<string, Buffer>> {
+ const objects = new Map<string, Buffer>()
+ await page.route('https://s3.example.com/**', async (route) => {
+ const request = route.request()
+ const url = new URL(request.url())
+ const key = decodeURIComponent(url.pathname.replace(/^\/designs\/?/, ''))
+ const prefix = url.searchParams.get('prefix')
+ if (url.searchParams.get('list-type') === '2' && prefix !== null) {
+ const contents = [...objects]
+ .filter(([name]) => name.startsWith(prefix))
+ .map(
+ ([name, body]) =>
+ `<Contents><Key>${name}</Key><LastModified>2026-01-02T03:04:05.000Z</LastModified><Size>${body.byteLength}</Size></Contents>`
+ )
+ await route.fulfill({
+ contentType: 'application/xml',
+ body: `<ListBucketResult><IsTruncated>false</IsTruncated>${contents.join('')}</ListBucketResult>`
+ })
+ return
+ }
+ if (request.method() === 'DELETE') {
+ objects.delete(key)
+ await route.fulfill({ status: 204 })
+ return
+ }
+ if (request.method() === 'PUT') {
+ objects.set(key, request.postDataBuffer() ?? Buffer.alloc(0))
+ await route.fulfill({ status: 200, headers: { ETag: '"etag"' } })
+ return
+ }
+ const body = objects.get(key)
+ if (!body) {
+ await route.fulfill({ status: 404 })
+ return
+ }
+ await route.fulfill({
+ status: 200,
+ headers: { 'Content-Length': String(body.byteLength) },
+ body: request.method() === 'HEAD' ? undefined : body
+ })
+ })
+ return objects
+}
+
test('configured storage lists previews through ranges before opening the document', async ({
page
}) => {
@@ -129,41 +174,7 @@ test('storage workspace directs unconfigured users to Settings', async ({ page }
test('Save to storage uploads the open document and lists it in the workspace', async ({
page
}) => {
- const objects = new Map<string, Buffer>()
- await page.route('https://s3.example.com/**', async (route) => {
- const request = route.request()
- const url = new URL(request.url())
- const key = decodeURIComponent(url.pathname.replace(/^\/designs\/?/, ''))
- const prefix = url.searchParams.get('prefix')
- if (url.searchParams.get('list-type') === '2' && prefix !== null) {
- const contents = [...objects]
- .filter(([name]) => name.startsWith(prefix))
- .map(
- ([name, body]) =>
- `<Contents><Key>${name}</Key><LastModified>2026-01-02T03:04:05.000Z</LastModified><Size>${body.byteLength}</Size></Contents>`
- )
- await route.fulfill({
- contentType: 'application/xml',
- body: `<ListBucketResult><IsTruncated>false</IsTruncated>${contents.join('')}</ListBucketResult>`
- })
- return
- }
- if (request.method() === 'PUT') {
- objects.set(key, request.postDataBuffer() ?? Buffer.alloc(0))
- await route.fulfill({ status: 200, headers: { ETag: '"etag"' } })
- return
- }
- const body = objects.get(key)
- if (!body) {
- await route.fulfill({ status: 404 })
- return
- }
- await route.fulfill({
- status: 200,
- headers: { 'Content-Length': String(body.byteLength) },
- body: request.method() === 'HEAD' ? undefined : body
- })
- })
+ const objects = await memoryBucket(page)
await page.goto('/?test')
const canvas = new CanvasHelper(page)
@@ -199,3 +210,52 @@ test('Save to storage uploads the open document and lists it in the workspace',
await expect(page.getByTestId('recent-files-home')).toBeVisible()
await expect(page.getByRole('button', { name: /^Untitled/ }).first()).toBeVisible()
})
+
+test('Delete removes a stored document from the bucket, and a document deleted elsewhere drops out', async ({
+ page
+}) => {
+ const objects = await memoryBucket(page)
+ for (const [id, name] of [
+ ['poster', 'Poster'],
+ ['flyer', 'Flyer']
+ ]) {
+ objects.set(
+ `open_pencil_storage/canvases/${id}.fig`,
+ readFileSync('tests/fixtures/gold-preview.fig')
+ )
+ objects.set(
+ `open_pencil_storage/canvases/${id}.meta.json`,
+ Buffer.from(JSON.stringify({ name, updatedAt: '2026-01-02T03:04:05.000Z' }))
+ )
+ }
+
+ await page.goto('/?recent-files')
+ await expect(page.getByTestId('recent-files-home')).toBeVisible()
+ await page.getByRole('button', { name: 'Settings' }).last().click()
+ await page.getByTestId('settings-section-storage').click()
+ const panel = page.getByTestId('settings-storage-panel')
+ await panel.getByRole('button', { name: /S3 storage/ }).click()
+ await panel.getByLabel('Endpoint').fill('https://s3.example.com')
+ await panel.getByLabel('Bucket').fill('designs')
+ await panel.getByLabel('Access key ID').fill('access-key')
+ await panel.getByLabel('Secret access key').fill('secret-key')
+ await page.getByRole('button', { name: 'Save', exact: true }).click()
+ await page.getByTestId('settings-storage-open-workspace').click()
+
+ const poster = page.getByRole('button', { name: /^Poster/ })
+ await expect(poster).toBeVisible()
+ await poster.hover()
+ await page.getByRole('button', { name: 'Actions for Poster' }).click()
+ await page.getByRole('menuitem', { name: 'Delete' }).click()
+ const dialog = page.getByRole('alertdialog', { name: 'Delete “Poster”?' })
+ await dialog.getByRole('button', { name: 'Delete' }).click()
+ await expect(poster).toBeHidden()
+ await expect.poll(() => [...objects.keys()].filter((key) => key.includes('/poster.'))).toEqual([])
+
+ objects.delete('open_pencil_storage/canvases/flyer.fig')
+ objects.delete('open_pencil_storage/canvases/flyer.meta.json')
+ await page.goto('/?recent-files')
+ await page.getByRole('button', { name: /^designs/ }).click()
+ await expect(page.getByText('No stored documents yet.')).toBeVisible()
+ await expect(page.getByRole('button', { name: /^Poster|^Flyer/ })).toHaveCount(0)
+})
diff --git a/tools/checks/test-homes/engine-baseline.txt b/tools/checks/test-homes/engine-baseline.txt
index b0857bf3a..ed118eedb 100644
--- a/tools/checks/test-homes/engine-baseline.txt
+++ b/tools/checks/test-homes/engine-baseline.txt
@@ -93,7 +93,6 @@ tests/engine/app/storage/cache-eviction.test.ts
tests/engine/app/storage/format-bytes.test.ts
tests/engine/app/storage/local-store.test.ts
tests/engine/app/storage/persist.test.ts
-tests/engine/app/storage/reconcile.test.ts
tests/engine/app/storage/sync-outbox.test.ts
tests/engine/app/storage/unique-name.test.ts
tests/engine/app/tabs/open-file-dedup.test.ts