Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

chore(studio): storage versioning override conflict (#51593)

Francesco Sansalvadore25708ed67ae2
diff --git a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx
index 58fd3f6d341..837e7159563 100644
--- a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx
+++ b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx
@@ -180,6 +180,7 @@ export const useIsStorageVersioningEnabled = () => {
const isStorageVersioningEnabled = useFlag('storageVersioningPrivateAlpha')
const { data } = useProjectStorageConfigQuery({ projectRef: ref })
const isObjectVersioningAvailable = !!data?.capabilities?.object_versioning
+
return (
isStorageVersioningEnabled &&
isObjectVersioningAvailable &&
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/ConfirmPurgeModal.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/ConfirmPurgeModal.tsx
index e90005247f8..c46d4430ec0 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/ConfirmPurgeModal.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/ConfirmPurgeModal.tsx
@@ -4,6 +4,7 @@ import { toast } from 'sonner'
import { ConfirmationModal } from 'ui-patterns/Dialogs/ConfirmationModal'
import { STORAGE_ROW_TYPES } from '../Storage.constants'
+import type { StorageItemWithColumn } from '../Storage.types'
import { getArchivedObjectsUnderFolder } from './archivedOverlay.utils'
import { getStorageItemPath } from './StorageExplorer.utils'
import { useStorageExplorerNavigation } from './StorageExplorerNavigation'
@@ -21,8 +22,10 @@ export const ConfirmPurgeModal = () => {
projectRef,
selectedBucket,
openedFolders,
- itemToPurge,
- setItemToPurge,
+ itemsToPurge,
+ setItemsToPurge,
+ selectedItems,
+ clearSelectedItems,
selectedFilePreview,
refetchAllOpenedFolders,
getAllItemsAlongFolder,
@@ -35,16 +38,18 @@ export const ConfirmPurgeModal = () => {
const { mutateAsync: purgeObject } = useObjectPurgeMutation()
const { mutateAsync: purgeArchivedObject } = useArchivedObjectPurgeMutation()
- const isFolder = itemToPurge?.type === STORAGE_ROW_TYPES.FOLDER
- const isArchivedFolder = isFolder && itemToPurge.archived !== undefined
+ const [firstItem] = itemsToPurge
+ const hasMultipleItems = itemsToPurge.length > 1
+ const hasFolder = itemsToPurge.some((item) => item.type === STORAGE_ROW_TYPES.FOLDER)
/** A folder is only a prefix, so both halves of what it holds have to go. */
const purgeFolder = async (
projectRef: string,
bucketId: string,
- folder: NonNullable<typeof itemToPurge>,
+ folder: StorageItemWithColumn,
path: string
) => {
+ const isArchivedFolder = folder.archived !== undefined
const liveItems = isArchivedFolder ? [] : await getAllItemsAlongFolder(folder)
// Not the overlay's copy: it is empty whenever "Show archived" is off, which would leave
@@ -82,33 +87,55 @@ export const ConfirmPurgeModal = () => {
return results.filter((result) => result.status === 'rejected').length
}
- const onConfirm = async () => {
- if (!projectRef || !selectedBucket?.id || itemToPurge === undefined) return
-
+ const purgeItem = async (projectRef: string, bucketId: string, item: StorageItemWithColumn) => {
// The endpoints address an object by full path; a row only knows its leaf name.
// The path captured when the row was targeted beats rebuilding it from folders
// that may have moved on; synthesized archived folders carry none, so they fall back.
- const path = itemToPurge.path ?? getStorageItemPath({ openedFolders }, itemToPurge)
+ const path = item.path ?? getStorageItemPath({ openedFolders }, item)
+
+ if (item.type === STORAGE_ROW_TYPES.FOLDER) {
+ return purgeFolder(projectRef, bucketId, item, path)
+ }
+ await purgeObject({ projectRef, bucketId, path })
+ return 0
+ }
+
+ const onConfirm = async () => {
+ if (!projectRef || !selectedBucket?.id || itemsToPurge.length === 0) return
+
+ const bucketId = selectedBucket.id
setIsPurging(true)
try {
- const failureCount = isFolder
- ? await purgeFolder(projectRef, selectedBucket.id, itemToPurge, path)
- : await purgeObject({ projectRef, bucketId: selectedBucket.id, path }).then(() => 0)
+ const results = await Promise.allSettled(
+ itemsToPurge.map((item) => purgeItem(projectRef, bucketId, item))
+ )
+
+ results.forEach((result, index) => {
+ const item = itemsToPurge[index]
+ if (result.status !== 'rejected' || result.reason === TRUNCATED_LISTING) return
+ if (item.type !== STORAGE_ROW_TYPES.FOLDER) return
+ toast.error(`Failed to delete ${item.name}: ${(result.reason as Error).message}`)
+ })
+
+ // A rejected item failed whole; a resolved one reports what of its contents stayed.
+ const failureCount = results.reduce(
+ (total, result) => total + (result.status === 'rejected' ? 1 : result.value),
+ 0
+ )
if (failureCount > 0) {
toast.error(`Could not delete ${failureCount} item${failureCount === 1 ? '' : 's'}`)
} else {
- toast.success(`Permanently deleted ${itemToPurge.name}`)
- // Purging from a row menu shouldn't close a preview of something else.
- if (selectedFilePreview?.id === itemToPurge.id) clearPreviewedFile()
- setItemToPurge(undefined)
- }
- } catch (error) {
- // The purge mutations settle rather than throw, and report their own failures. What
- // reaches here is a folder that couldn't be enumerated or whose archived listing
- // couldn't be fetched — silent until now.
- if (isFolder && error !== TRUNCATED_LISTING) {
- toast.error(`Failed to delete ${itemToPurge.name}: ${(error as Error).message}`)
+ toast.success(
+ hasMultipleItems
+ ? `Permanently deleted ${itemsToPurge.length} items`
+ : `Permanently deleted ${firstItem.name}`
+ )
+ const purgedIds = new Set(itemsToPurge.map((item) => item.id))
+ const previewedId = selectedFilePreview?.id
+ if (previewedId !== undefined && purgedIds.has(previewedId)) clearPreviewedFile()
+ if (selectedItems.some((item) => purgedIds.has(item.id))) clearSelectedItems()
+ setItemsToPurge([])
}
} finally {
// Whatever did go through has already changed the listing.
@@ -117,23 +144,37 @@ export const ConfirmPurgeModal = () => {
}
}
+ const getAlertDescription = () => {
+ if (hasMultipleItems) {
+ return 'Deletes the selected files and every version of them, bypassing versioning. Nothing is left to restore.'
+ }
+ if (hasFolder) {
+ return 'Deletes everything in this folder, archived files included, and every version of them. Nothing is left to restore.'
+ }
+ return 'Deletes the file and every version of it, bypassing versioning. Nothing is left to restore.'
+ }
+
return (
<ConfirmationModal
size="medium"
- visible={itemToPurge !== undefined}
- title={<span className="wrap-break-word">Permanently delete {itemToPurge?.name}?</span>}
+ visible={itemsToPurge.length > 0}
+ title={
+ <span className="wrap-break-word">
+ {hasMultipleItems
+ ? `Permanently delete ${itemsToPurge.length} items?`
+ : `Permanently delete ${firstItem?.name}?`}
+ </span>
+ }
confirmLabel="Delete permanently"
confirmLabelLoading="Deleting..."
loading={isPurging}
variant="destructive"
- onCancel={() => setItemToPurge(undefined)}
+ onCancel={() => setItemsToPurge([])}
onConfirm={onConfirm}
alert={{
base: { variant: 'destructive' },
title: 'This cannot be undone',
- description: isFolder
- ? 'Deletes everything in this folder, archived files included, and every version of them. Nothing is left to restore.'
- : 'Deletes the file and every version of it, bypassing versioning. Nothing is left to restore.',
+ description: getAlertDescription(),
}}
/>
)
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.test.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.test.tsx
new file mode 100644
index 00000000000..c518cf75c3e
--- /dev/null
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.test.tsx
@@ -0,0 +1,132 @@
+import { screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import {
+ STORAGE_ROW_STATUS,
+ STORAGE_ROW_TYPES,
+} from '@/components/interfaces/Storage/Storage.constants'
+import type { StorageItemWithColumn } from '@/components/interfaces/Storage/Storage.types'
+import { FileExplorerHeaderSelection } from '@/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection'
+import { customRender as render } from '@/tests/lib/custom-render'
+
+const { versioningEnabled, selectedBucket, actions } = vi.hoisted(() => ({
+ versioningEnabled: { current: true },
+ selectedBucket: {
+ current: { id: 'my-bucket', name: 'my-bucket', public: false } as Record<string, unknown>,
+ },
+ actions: {
+ setSelectedItemsToDelete: vi.fn(),
+ setItemsToPurge: vi.fn(),
+ },
+}))
+
+vi.mock(
+ '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext',
+ async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>()
+ return { ...actual, useIsStorageVersioningEnabled: () => versioningEnabled.current }
+ }
+)
+
+const SELECTED: StorageItemWithColumn[] = [
+ {
+ id: 'file-1',
+ name: 'photo.png',
+ type: STORAGE_ROW_TYPES.FILE,
+ status: STORAGE_ROW_STATUS.READY,
+ metadata: null,
+ isCorrupted: false,
+ created_at: null,
+ updated_at: null,
+ last_accessed_at: null,
+ columnIndex: 0,
+ },
+ {
+ id: 'file-2',
+ name: 'notes.txt',
+ type: STORAGE_ROW_TYPES.FILE,
+ status: STORAGE_ROW_STATUS.READY,
+ metadata: null,
+ isCorrupted: false,
+ created_at: null,
+ updated_at: null,
+ last_accessed_at: null,
+ columnIndex: 0,
+ },
+]
+
+vi.mock('@/state/storage-explorer', () => ({
+ useStorageExplorerStateSnapshot: () => ({
+ selectedBucket: selectedBucket.current,
+ selectedItems: SELECTED,
+ downloadFile: vi.fn(),
+ downloadSelectedFiles: vi.fn(),
+ clearSelectedItems: vi.fn(),
+ setSelectedItemsToMove: vi.fn(),
+ ...actions,
+ }),
+}))
+vi.mock('@/hooks/misc/useCheckPermissions', () => ({
+ useAsyncCheckPermissions: () => ({ can: true }),
+}))
+
+describe('FileExplorerHeaderSelection', () => {
+ beforeEach(() => {
+ versioningEnabled.current = true
+ selectedBucket.current = {
+ id: 'my-bucket',
+ name: 'my-bucket',
+ public: false,
+ versioning_status: 'ENABLED',
+ }
+ actions.setSelectedItemsToDelete.mockClear()
+ actions.setItemsToPurge.mockClear()
+ })
+
+ it('offers a permanent delete beside the archive, since archiving leaves versions behind', async () => {
+ render(<FileExplorerHeaderSelection />)
+
+ expect(screen.getByRole('button', { name: 'Archive' })).toBeInTheDocument()
+
+ await userEvent.click(screen.getByRole('button', { name: 'Delete permanently' }))
+
+ expect(actions.setItemsToPurge).toHaveBeenCalledWith(SELECTED)
+ expect(actions.setSelectedItemsToDelete).not.toHaveBeenCalled()
+ })
+
+ it('archives through the separate action, which keeps the versions', async () => {
+ render(<FileExplorerHeaderSelection />)
+
+ await userEvent.click(screen.getByRole('button', { name: 'Archive' }))
+
+ expect(actions.setSelectedItemsToDelete).toHaveBeenCalledWith(SELECTED)
+ expect(actions.setItemsToPurge).not.toHaveBeenCalled()
+ })
+
+ it('drops the permanent delete on a suspended bucket, where deleting is already permanent', () => {
+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }
+
+ render(<FileExplorerHeaderSelection />)
+
+ expect(screen.getByRole('button', { name: 'Delete' })).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Delete permanently' })).not.toBeInTheDocument()
+ })
+
+ it('drops it on an unversioned bucket too, so the bar never says the same thing twice', () => {
+ selectedBucket.current = { id: 'my-bucket', name: 'my-bucket', public: false }
+
+ render(<FileExplorerHeaderSelection />)
+
+ expect(screen.getByRole('button', { name: 'Delete' })).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Delete permanently' })).not.toBeInTheDocument()
+ })
+
+ it('drops it when the feature preview is off', () => {
+ versioningEnabled.current = false
+
+ render(<FileExplorerHeaderSelection />)
+
+ expect(screen.queryByRole('button', { name: 'Delete permanently' })).not.toBeInTheDocument()
+ })
+})
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.tsx
index a331aa614f1..00e07f8b7b5 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.tsx
@@ -22,6 +22,7 @@ export const FileExplorerHeaderSelection = () => {
clearSelectedItems,
setSelectedItemsToDelete,
setSelectedItemsToMove,
+ setItemsToPurge,
} = useStorageExplorerStateSnapshot()
const isStorageVersioningEnabled = useIsStorageVersioningEnabled()
@@ -74,6 +75,24 @@ export const FileExplorerHeaderSelection = () => {
{canArchive ? 'Archive' : 'Delete'}
</ButtonTooltip>
</ShortcutTooltip>
+ {canArchive && (
+ <ButtonTooltip
+ size="tiny"
+ icon={<Trash2 size={12} className={canUpdateFiles ? 'text-destructive' : undefined} />}
+ disabled={!canUpdateFiles}
+ onClick={() => setItemsToPurge(selectedItems)}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: !canUpdateFiles
+ ? 'You need additional permissions to delete files'
+ : 'Deletes every version, leaving nothing to restore',
+ },
+ }}
+ >
+ Delete permanently
+ </ButtonTooltip>
+ )}
<ShortcutTooltip
shortcutId={SHORTCUT_IDS.STORAGE_EXPLORER_MOVE_SELECTED}
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.test.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.test.tsx
index 11e5e247c24..a47b806a11d 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.test.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.test.tsx
@@ -43,7 +43,7 @@ vi.mock('@/state/storage-explorer', () => ({
setSelectedItemsToMove: vi.fn(),
downloadFolder: vi.fn(),
selectRangeItems: vi.fn(),
- setItemToPurge: vi.fn(),
+ setItemsToPurge: vi.fn(),
}),
}))
vi.mock('@/components/interfaces/Storage/StorageExplorer/StorageExplorerNavigation', () => ({
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.tsx
index 3f5c36548cd..93086b67720 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.tsx
@@ -169,7 +169,7 @@ export const FileExplorerRow = ({
setSelectedFileCustomExpiry,
setSelectedItems,
setSelectedItemsToDelete,
- setItemToPurge,
+ setItemsToPurge,
refetchAllOpenedFolders,
replaceFile,
downloadFile,
@@ -292,7 +292,7 @@ export const FileExplorerRow = ({
{
name: 'Delete permanently',
icon: <Trash2 size={12} className="text-destructive" />,
- onClick: () => setItemToPurge(itemWithColumnIndex),
+ onClick: () => setItemsToPurge([itemWithColumnIndex]),
},
]
: []),
@@ -384,7 +384,7 @@ export const FileExplorerRow = ({
{
name: 'Delete permanently',
icon: <Trash2 size={12} className="text-destructive" />,
- onClick: () => setItemToPurge(itemWithColumnIndex),
+ onClick: () => setItemsToPurge([itemWithColumnIndex]),
},
]
: []),
@@ -448,7 +448,7 @@ export const FileExplorerRow = ({
{
name: 'Delete permanently',
icon: <Trash2 size={12} className="text-destructive" />,
- onClick: () => setItemToPurge(itemWithColumnIndex),
+ onClick: () => setItemsToPurge([itemWithColumnIndex]),
},
]
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.test.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.test.tsx
index 15010d61b70..d56fd604f8a 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.test.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.test.tsx
@@ -33,7 +33,7 @@ vi.mock('@/state/storage-explorer', () => ({
selectedFilePreview: selectedFilePreview.current,
openedFolders: [],
setSelectedItemsToDelete: vi.fn(),
- setItemToPurge: vi.fn(),
+ setItemsToPurge: vi.fn(),
refetchAllOpenedFolders: vi.fn().mockResolvedValue(undefined),
replaceFile: vi.fn(),
setSelectedFileCustomExpiry: vi.fn(),
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.tsx
index 1e042e6d09c..51383dd00e2 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.tsx
@@ -249,7 +249,7 @@ export const PreviewPane = () => {
selectedFilePreview: file,
openedFolders,
setSelectedItemsToDelete,
- setItemToPurge,
+ setItemsToPurge,
refetchAllOpenedFolders,
replaceFile,
setSelectedFileCustomExpiry,
@@ -403,7 +403,7 @@ export const PreviewPane = () => {
onDownload={() => downloadFile(file)}
onCustomExpiry={() => setSelectedFileCustomExpiry(file)}
onDelete={() => setSelectedItemsToDelete([file])}
- onPurge={() => setItemToPurge(file)}
+ onPurge={() => setItemsToPurge([file])}
/>
)}
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.test.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.test.ts
index 4957abe6c66..e452401cc82 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.test.ts
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.test.ts
@@ -13,9 +13,11 @@ import {
describeUploadFailure,
getPathAlongFoldersToIndex,
getPathAlongOpenedFolders,
+ getReplaceableFileNames,
getStorageExplorerUrlForItem,
getStorageItemPath,
getStoragePathForItem,
+ getUploadNameConflicts,
parseStoragePath,
sanitizeNameForDuplicateInColumn,
serializeStoragePath,
@@ -214,6 +216,31 @@ describe('sanitizeNameForDuplicateInColumn', () => {
expect(sanitizeNameForDuplicateInColumn(state, { name: 'file.txt' })).toBe('file.txt')
})
+ describe('reservedNames', () => {
+ it('treats a reserved name as taken even though no column holds it', () => {
+ const state = makeState([[{ name: 'other.txt' }]])
+ expect(
+ sanitizeNameForDuplicateInColumn(state, {
+ name: 'file.txt',
+ autofix: true,
+ reservedNames: ['file.txt'],
+ })
+ ).toBe('file (1).txt')
+ })
+
+ it('matches a reserved name case-insensitively, like a column name', () => {
+ const state = makeState([[{ name: 'other.txt' }]])
+ expect(
+ sanitizeNameForDuplicateInColumn(state, { name: 'file.txt', reservedNames: ['FILE.TXT'] })
+ ).toBeNull()
+ })
+
+ it('leaves callers that pass none exactly as they were', () => {
+ const state = makeState([[{ name: 'file.txt' }]])
+ expect(sanitizeNameForDuplicateInColumn(state, { name: 'other.txt' })).toBe('other.txt')
+ })
+ })
+
describe('columnIndex', () => {
// Two-column state: col 0 has 'file.txt', col 1 has 'other.txt'
const state = makeState([[{ name: 'file.txt' }], [{ name: 'other.txt' }]])
@@ -275,6 +302,19 @@ describe('sanitizeNameForDuplicateInColumn', () => {
)
})
+ it('counts a reserved duplicate, so the suffix skips a name an archived file holds', () => {
+ // Without this the upload lands on `file (1).txt` and restores the archived file,
+ // which is exactly what picking "keep both" declined.
+ const state = makeState([[{ name: 'file.txt' }]])
+ expect(
+ sanitizeNameForDuplicateInColumn(state, {
+ name: 'file.txt',
+ autofix: true,
+ reservedNames: ['file (1).txt'],
+ })
+ ).toBe('file (2).txt')
+ })
+
it('treats the whole name as the extension when there is no dot (existing behaviour)', () => {
// NOTE: the function splits on '.' and always treats the last segment as the
// extension, so a dotless name produces " (1).myfile" rather than "myfile (1)".
@@ -508,3 +548,106 @@ describe('describeUploadFailure', () => {
expect(describeUploadFailure({ fallback: 'network down' })).toBe('network down')
})
})
+
+describe('getUploadNameConflicts', () => {
+ it('returns the names already taken in the destination', () => {
+ expect(
+ getUploadNameConflicts({
+ fileNames: ['photo.png', 'notes.txt'],
+ existingNames: ['photo.png', 'archive.zip'],
+ })
+ ).toEqual(['photo.png'])
+ })
+
+ it('matches case-insensitively, the way the rename fallback does', () => {
+ expect(
+ getUploadNameConflicts({ fileNames: ['Photo.PNG'], existingNames: ['photo.png'] })
+ ).toEqual(['Photo.PNG'])
+ })
+
+ it('returns nothing when every name is free', () => {
+ expect(
+ getUploadNameConflicts({ fileNames: ['photo.png'], existingNames: ['notes.txt'] })
+ ).toEqual([])
+ expect(getUploadNameConflicts({ fileNames: [], existingNames: ['photo.png'] })).toEqual([])
+ })
+
+ it('reports a name once even when it is uploaded twice', () => {
+ expect(
+ getUploadNameConflicts({
+ fileNames: ['photo.png', 'photo.png'],
+ existingNames: ['photo.png'],
+ })
+ ).toEqual(['photo.png'])
+ })
+})
+
+describe('getReplaceableFileNames', () => {
+ const file = (overrides: Partial<StorageItem>): StorageItem => ({
+ id: 'file-id',
+ name: 'file.txt',
+ type: STORAGE_ROW_TYPES.FILE,
+ status: STORAGE_ROW_STATUS.READY,
+ metadata: null,
+ isCorrupted: false,
+ created_at: null,
+ updated_at: null,
+ last_accessed_at: null,
+ ...overrides,
+ })
+
+ it('offers every file on an enabled bucket, where any replace keeps what it lands on', () => {
+ expect(
+ getReplaceableFileNames({
+ items: [file({ name: 'a.txt', is_versioned: true }), file({ name: 'b.txt' })],
+ versioningState: 'enabled',
+ })
+ ).toEqual(['a.txt', 'b.txt'])
+ })
+
+ it('offers only a pre-suspension file once the bucket is suspended', () => {
+ // Its replacement is unversioned, so the write after it retains nothing — which is why
+ // `b.txt`, written while suspended, is not worth asking about.
+ expect(
+ getReplaceableFileNames({
+ items: [
+ file({ name: 'a.txt', is_versioned: true }),
+ file({ name: 'b.txt', is_versioned: false }),
+ ],
+ versioningState: 'suspended',
+ })
+ ).toEqual(['a.txt'])
+ })
+
+ it('offers nothing on a suspended bucket when the flag is absent', () => {
+ // Nothing is promised that the write might not deliver; the upload renames instead.
+ expect(
+ getReplaceableFileNames({
+ items: [file({ name: 'a.txt' }), file({ name: 'b.txt', is_versioned: null })],
+ versioningState: 'suspended',
+ })
+ ).toEqual([])
+ })
+
+ it('offers nothing on a disabled bucket', () => {
+ expect(
+ getReplaceableFileNames({
+ items: [file({ name: 'a.txt', is_versioned: true })],
+ versioningState: 'disabled',
+ })
+ ).toEqual([])
+ })
+
+ it('skips folders and rows being renamed', () => {
+ expect(
+ getReplaceableFileNames({
+ items: [
+ file({ name: 'folder', type: STORAGE_ROW_TYPES.FOLDER, id: null }),
+ file({ name: 'editing.txt', status: STORAGE_ROW_STATUS.EDITING }),
+ file({ name: 'a.txt' }),
+ ],
+ versioningState: 'enabled',
+ })
+ ).toEqual(['a.txt'])
+ })
+})
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.tsx
index f8b58f4925a..89e875271d1 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils.tsx
@@ -4,6 +4,10 @@ import { copyToClipboard } from 'ui'
import { STORAGE_ROW_STATUS, STORAGE_ROW_TYPES } from '../Storage.constants'
import { StorageItem, StorageItemMetadata } from '../Storage.types'
import { inverseValidObjectKeyRegex, validObjectKeyRegex } from '../Storage.utils'
+import {
+ willRetainVersionOnWrite,
+ type BucketVersioningState,
+} from '../StorageVersioning.constants'
import type { StorageObject } from '@/data/storage/bucket-objects-list-mutation'
import { BASE_PATH } from '@/lib/constants'
import type { StorageExplorerState } from '@/state/storage-explorer'
@@ -98,10 +102,16 @@ export function sanitizeNameForDuplicateInColumn(
name,
columnIndex,
autofix = false,
+ reservedNames = [],
}: {
name: string
columnIndex?: number
autofix?: boolean
+ /**
+ * Names that are taken in the destination but absent from `state.columns` — archived
+ * objects, which only exist in the rendered overlay.
+ */
+ reservedNames?: string[]
}
): string | null {
const columnIndex_ = columnIndex !== undefined ? columnIndex : state.columns.length - 1
@@ -109,12 +119,15 @@ export function sanitizeNameForDuplicateInColumn(
const currentColumnItems = currentColumn.items.filter(
(item) => item.status !== STORAGE_ROW_STATUS.EDITING
)
+ // One list, so the suffix counter sees everything the clash check does. Counting only
+ // column items would hand back a ` (1)` that an archived object already holds.
+ const takenNames = currentColumnItems.map((item) => item.name).concat(reservedNames)
// [Joshen] JFYI storage does support folders of the same name with different casing
// but its an issue with the List V1 endpoint that's causing an issue with fetching contents
// for folders of the same name with different casing
// We should remove this check once all projects are on the List V2 endpoint
const hasSameNameInColumn =
- currentColumnItems.filter((item) => item.name.toLowerCase() === name.toLowerCase()).length > 0
+ takenNames.filter((takenName) => takenName.toLowerCase() === name.toLowerCase()).length > 0
if (hasSameNameInColumn) {
if (autofix) {
@@ -123,11 +136,9 @@ export function sanitizeNameForDuplicateInColumn(
const fileExt = fileNameSegments[fileNameSegments.length - 1]
const dupeNameRegex = new RegExp(`${fileName} \\([-0-9]+\\)${fileExt ? '.' + fileExt : ''}$`)
- const itemsWithSameNameInColumn = currentColumnItems.filter((item) =>
- item.name.match(dupeNameRegex)
- )
+ const namesWithSuffix = takenNames.filter((takenName) => takenName.match(dupeNameRegex))
- const updatedFileName = fileName + ` (${itemsWithSameNameInColumn.length + 1})`
+ const updatedFileName = fileName + ` (${namesWithSuffix.length + 1})`
return fileExt ? `${updatedFileName}.${fileExt}` : updatedFileName
} else {
toast.error(
@@ -140,6 +151,41 @@ export function sanitizeNameForDuplicateInColumn(
return name
}
+export type UploadConflictResolution = 'replace' | 'keep-both' | 'cancel'
+
+export type UploadConflicts = {
+ liveNames: string[]
+ archivedNames: string[]
+ isVersioningSuspended: boolean
+}
+
+export function getUploadNameConflicts({
+ fileNames,
+ existingNames,
+}: {
+ fileNames: string[]
+ existingNames: string[]
+}): string[] {
+ const takenNames = new Set(existingNames.map((name) => name.toLowerCase()))
+ return Array.from(new Set(fileNames.filter((name) => takenNames.has(name.toLowerCase()))))
+}
+
+export const getReplaceableFileNames = ({
+ items,
+ versioningState,
+}: {
+ items: readonly StorageItem[]
+ versioningState: BucketVersioningState
+}): string[] =>
+ items
+ .filter(
+ (item) =>
+ item.type === STORAGE_ROW_TYPES.FILE &&
+ item.status !== STORAGE_ROW_STATUS.EDITING &&
+ willRetainVersionOnWrite({ versioningState, isObjectVersioned: item.is_versioned })
+ )
+ .map((item) => item.name)
+
/** Bucket-relative path to an item */
export function getStoragePathForItem(
openedFolders: readonly StorageItem[],
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorerContent.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorerContent.tsx
index cab69b0a0f5..91b15f85f0b 100644
--- a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorerContent.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorerContent.tsx
@@ -14,7 +14,10 @@ import { FileExplorerHeaderSelection } from './FileExplorerHeaderSelection'
import { MoveItemsModal } from './MoveItemsModal'
import { PreviewPane } from './PreviewPane'
import { useStorageExplorerNavigation } from './StorageExplorerNavigation'
+import { UploadConflictModal } from './UploadConflictModal'
import { useStorageExplorerShortcuts } from './useStorageExplorerShortcuts'
+import { useUploadConflictPrompt } from './useUploadConflictPrompt'
+import { useIsStorageVersioningEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { useStorageExplorerStateSnapshot } from '@/state/storage-explorer'
interface StorageExplorerContentProps {
@@ -44,6 +47,8 @@ export const StorageExplorerContent = ({
} = useStorageExplorerStateSnapshot()
const { truncateToColumn } = useStorageExplorerNavigation()
const { isOverlayEnabled, isListingTruncated, selectedArchivedObject } = useArchivedFilesContext()
+ const isStorageVersioningEnabled = useIsStorageVersioningEnabled()
+ const { conflicts, promptForConflicts, resolveConflicts } = useUploadConflictPrompt()
const handleClearSearch = useCallback(() => {
setIsSearching(false)
@@ -86,7 +91,14 @@ export const StorageExplorerContent = ({
event.persist()
const items = event.target.files || event.dataTransfer.items
const isDrop = !isEmpty(get(event, ['dataTransfer', 'items'], []))
- await uploadFiles({ files: items, columnIndex, isDrop })
+ await uploadFiles({
+ files: items,
+ columnIndex,
+ isDrop,
+ // Whether a clash is worth asking about depends on the bucket's versioning state,
+ // which `uploadFiles` reads for itself. The preview gate is the part only a hook knows.
+ onConflict: isStorageVersioningEnabled ? promptForConflicts : undefined,
+ })
event.target.value = ''
}
@@ -129,6 +141,12 @@ export const StorageExplorerContent = ({
{selectedArchivedObject !== undefined ? <ArchivedFilePreviewPane /> : <PreviewPane />}
</div>
+ <UploadConflictModal
+ conflicts={conflicts}
+ onCancel={() => resolveConflicts('cancel')}
+ onConfirm={(choice) => resolveConflicts(choice)}
+ />
+
<ConfirmDeleteModal />
<ConfirmPurgeModal />
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/UploadConflictModal.test.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/UploadConflictModal.test.tsx
new file mode 100644
index 00000000000..6b907c3de83
--- /dev/null
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/UploadConflictModal.test.tsx
@@ -0,0 +1,115 @@
+import { screen, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it, vi } from 'vitest'
+
+import type { UploadConflicts } from './StorageExplorer.utils'
+import { UploadConflictModal } from './UploadConflictModal'
+import { customRender } from '@/tests/lib/custom-render'
+
+const renderModal = (conflicts: Partial<UploadConflicts>) => {
+ const onCancel = vi.fn()
+ const onConfirm = vi.fn()
+ customRender(
+ <UploadConflictModal
+ conflicts={{
+ liveNames: [],
+ archivedNames: [],
+ isVersioningSuspended: false,
+ ...conflicts,
+ }}
+ onCancel={onCancel}
+ onConfirm={onConfirm}
+ />
+ )
+ return { onCancel, onConfirm }
+}
+
+describe('UploadConflictModal', () => {
+ it('stays closed when nothing clashes', () => {
+ renderModal({})
+
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ })
+
+ it('names the file that is already there', () => {
+ renderModal({ liveNames: ['photo.png'] })
+
+ expect(screen.getByText('photo.png already exists here')).toBeInTheDocument()
+ expect(screen.getByText('Replace existing file')).toBeInTheDocument()
+ expect(screen.getByText('Keep both files')).toBeInTheDocument()
+ })
+
+ it('counts and lists the files when several clash', () => {
+ renderModal({ liveNames: ['photo.png', 'notes.txt'] })
+
+ expect(screen.getByText('2 files already exist here')).toBeInTheDocument()
+ expect(screen.getByText('Replace existing files')).toBeInTheDocument()
+ const list = screen.getByRole('list')
+ expect(within(list).getByText('photo.png')).toBeInTheDocument()
+ expect(within(list).getByText('notes.txt')).toBeInTheDocument()
+ })
+
+ it('replaces by default, since that is what versioning retains', async () => {
+ const { onConfirm } = renderModal({ liveNames: ['photo.png'] })
+
+ await userEvent.click(screen.getByRole('button', { name: 'Upload' }))
+
+ expect(onConfirm).toHaveBeenCalledWith('replace')
+ })
+
+ it('keeps both files when the user picks that instead', async () => {
+ const { onConfirm } = renderModal({ liveNames: ['photo.png'] })
+
+ await userEvent.click(screen.getByRole('radio', { name: /Keep both files/ }))
+ await userEvent.click(screen.getByRole('button', { name: 'Upload' }))
+
+ expect(onConfirm).toHaveBeenCalledWith('keep-both')
+ })
+
+ it('cancels the upload rather than guessing', async () => {
+ const { onCancel, onConfirm } = renderModal({ liveNames: ['photo.png'] })
+
+ await userEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+
+ expect(onCancel).toHaveBeenCalled()
+ expect(onConfirm).not.toHaveBeenCalled()
+ })
+
+ it('says the retention only holds once when versioning is suspended', () => {
+ renderModal({ liveNames: ['photo.png'], isVersioningSuspended: true })
+
+ expect(screen.getByText('Replace existing file')).toBeInTheDocument()
+ expect(screen.getByText(/one last time/)).toBeInTheDocument()
+ })
+
+ describe('archived conflicts', () => {
+ it('offers a restore rather than a replace', () => {
+ renderModal({ archivedNames: ['icon-1.svg'] })
+
+ expect(screen.getByText('icon-1.svg already exists and is archived')).toBeInTheDocument()
+ expect(screen.getByText('Restore and add a new version')).toBeInTheDocument()
+ expect(screen.queryByText('Replace existing file')).not.toBeInTheDocument()
+ })
+
+ it('still reports the choice as a replace, which is what the upload does', async () => {
+ const { onConfirm } = renderModal({ archivedNames: ['icon-1.svg'] })
+
+ await userEvent.click(screen.getByRole('button', { name: 'Upload' }))
+
+ expect(onConfirm).toHaveBeenCalledWith('replace')
+ })
+
+ it('marks which of the listed names are archived', () => {
+ renderModal({ liveNames: ['photo.png'], archivedNames: ['icon-1.svg'] })
+
+ expect(screen.getByText('2 files already exist here')).toBeInTheDocument()
+ expect(screen.getByText('Replace and restore')).toBeInTheDocument()
+
+ const archivedRow = screen.getByText('icon-1.svg').closest('li')
+ expect(within(archivedRow!).getByText('Archived')).toBeInTheDocument()
+ expect(
+ within(screen.getByText('photo.png').closest('li')!).queryByText('Archived')
+ ).toBeNull()
+ })
+ })
+})
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/UploadConflictModal.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/UploadConflictModal.tsx
new file mode 100644
index 00000000000..09fbb8750e0
--- /dev/null
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/UploadConflictModal.tsx
@@ -0,0 +1,96 @@
+import { useState } from 'react'
+import { RadioGroupStacked, RadioGroupStackedItem, ScrollArea } from 'ui'
+import { ConfirmationModal } from 'ui-patterns/Dialogs/ConfirmationModal'
+
+import type { UploadConflictResolution, UploadConflicts } from './StorageExplorer.utils'
+import { getUploadConflictCopy } from './UploadConflictModal.utils'
+
+/** Cancelling is reported through `onCancel` instead, so the radio never carries it. */
+export type UploadConflictChoice = Exclude<UploadConflictResolution, 'cancel'>
+
+interface UploadConflictModalProps {
+ /** Names the upload would land on. Empty keeps the modal closed. */
+ conflicts: UploadConflicts
+ onCancel: () => void
+ onConfirm: (choice: UploadConflictChoice) => void
+}
+
+/**
+ * Asked before an upload overwrites something, including something only the archived view
+ * can see. Mounted for a bucket that retains versions — elsewhere the explorer renames
+ * instead of offering a choice that would lose the existing file.
+ */
+export const UploadConflictModal = ({
+ conflicts,
+ onCancel,
+ onConfirm,
+}: UploadConflictModalProps) => {
+ const [choice, setChoice] = useState<UploadConflictChoice>('replace')
+
+ const { liveNames, archivedNames } = conflicts
+ const conflictCount = liveNames.length + archivedNames.length
+ const hasMultipleConflicts = conflictCount > 1
+ const copy = getUploadConflictCopy(conflicts)
+
+ const handleCancel = () => {
+ setChoice('replace')
+ onCancel()
+ }
+
+ const handleConfirm = () => {
+ setChoice('replace')
+ onConfirm(choice)
+ }
+
+ return (
+ <ConfirmationModal
+ size="medium"
+ visible={conflictCount > 0}
+ loading={false}
+ title={<span className="wrap-break-word">{copy.title}</span>}
+ description={copy.description}
+ confirmLabel="Upload"
+ onCancel={handleCancel}
+ onConfirm={handleConfirm}
+ >
+ <RadioGroupStacked
+ value={choice}
+ onValueChange={(value) => setChoice(value as UploadConflictChoice)}
+ >
+ <RadioGroupStackedItem
+ value="replace"
+ label={copy.replaceLabel}
+ className="[&_p]:text-pretty!"
+ description={copy.replaceDescription}
+ />
+ <RadioGroupStackedItem
+ value="keep-both"
+ label={copy.keepBothLabel}
+ className="[&_p]:text-pretty!"
+ description={copy.keepBothDescription}
+ />
+ </RadioGroupStacked>
+
+ {hasMultipleConflicts && (
+ <ScrollArea className="mt-3 rounded-md border">
+ <ul className="px-4 py-2 max-h-32 overflow-y-auto bg-surface-200 dark:bg-surface-100/50 text-xs text-foreground-light divide-y divide-border">
+ {liveNames.map((name) => (
+ <li key={name} className="text-sm py-1 wrap-break-word">
+ {name}
+ </li>
+ ))}
+ {archivedNames.map((name) => (
+ <li
+ key={name}
+ className="text-sm py-1 flex items-center justify-between gap-x-2 wrap-break-word"
+ >
+ {name}
+ <span className="text-xs text-foreground-lighter shrink-0">Archived</span>
+ </li>
+ ))}
+ </ul>
+ </ScrollArea>
+ )}
+ </ConfirmationModal>
+ )
+}
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/UploadConflictModal.utils.test.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/UploadConflictModal.utils.test.ts
new file mode 100644
index 00000000000..f07ccf9a7eb
--- /dev/null
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/UploadConflictModal.utils.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it } from 'vitest'
+
+import type { UploadConflicts } from './StorageExplorer.utils'
+import { getUploadConflictCopy } from './UploadConflictModal.utils'
+
+const copyFor = (conflicts: Partial<UploadConflicts>) =>
+ getUploadConflictCopy({
+ liveNames: [],
+ archivedNames: [],
+ isVersioningSuspended: false,
+ ...conflicts,
+ })
+
+describe('getUploadConflictCopy', () => {
+ it('names the single live file and offers a replace', () => {
+ const copy = copyFor({ liveNames: ['photo.png'] })
+
+ expect(copy.title).toBe('photo.png already exists here')
+ expect(copy.replaceLabel).toBe('Replace existing file')
+ expect(copy.keepBothLabel).toBe('Keep both files')
+ })
+
+ it('counts several live files instead of naming them', () => {
+ const copy = copyFor({
+ liveNames: ['photo.png', 'notes.txt'],
+ })
+
+ expect(copy.title).toBe('2 files already exist here')
+ expect(copy.replaceLabel).toBe('Replace existing files')
+ expect(copy.keepBothLabel).toBe('Keep all files')
+ })
+
+ it('calls a single archived clash a restore, not a replace', () => {
+ const copy = copyFor({ archivedNames: ['icon-1.svg'] })
+
+ expect(copy.title).toBe('icon-1.svg already exists and is archived')
+ expect(copy.replaceLabel).toBe('Restore and add a new version')
+ expect(copy.keepBothDescription).toContain('Leaves the file archived')
+ })
+
+ it('counts several archived clashes', () => {
+ const copy = copyFor({
+ archivedNames: ['icon-1.svg', 'icon-2.svg'],
+ })
+
+ expect(copy.title).toBe('2 files already exist and are archived')
+ expect(copy.replaceLabel).toBe('Restore and add new versions')
+ })
+
+ describe('suspended versioning', () => {
+ it('promises the retention once, then an overwrite', () => {
+ const copy = copyFor({ liveNames: ['photo.png'], isVersioningSuspended: true })
+
+ expect(copy.replaceLabel).toBe('Replace existing file')
+ expect(copy.replaceDescription).toContain('kept as a noncurrent version one last time')
+ expect(copy.replaceDescription).toContain('overwrites it in place')
+ })
+
+ it('says the same for several files', () => {
+ const copy = copyFor({
+ liveNames: ['photo.png', 'notes.txt'],
+ isVersioningSuspended: true,
+ })
+
+ expect(copy.replaceDescription).toContain('Each file you replace is kept')
+ expect(copy.replaceDescription).toContain('one last time')
+ })
+
+ it('keeps the restore wording for an archived clash, which suspension does not change', () => {
+ const copy = copyFor({ archivedNames: ['icon-1.svg'], isVersioningSuspended: true })
+
+ expect(copy.replaceLabel).toBe('Restore and add a new version')
+ })
+
+ it('keeps the one-shot qualifier in the mixed case', () => {
+ const copy = copyFor({
+ liveNames: ['photo.png'],
+ archivedNames: ['icon-1.svg'],
+ isVersioningSuspended: true,
+ })
+
+ expect(copy.replaceDescription).toContain('archived files are restored')
+ expect(copy.replaceDescription).toContain('one last time')
+ })
+ })
+
+ it('covers both effects when the clash is mixed', () => {
+ const copy = copyFor({
+ liveNames: ['photo.png'],
+ archivedNames: ['icon-1.svg'],
+ })
+
+ expect(copy.title).toBe('2 files already exist here')
+ expect(copy.description).toContain('Some of them are archived')
+ expect(copy.replaceLabel).toBe('Replace and restore')
+ expect(copy.replaceDescription).toContain('noncurrent versions')
+ expect(copy.replaceDescription).toContain('restored')
+ })
+})
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/UploadConflictModal.utils.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/UploadConflictModal.utils.ts
new file mode 100644
index 00000000000..fa7fa104799
--- /dev/null
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/UploadConflictModal.utils.ts
@@ -0,0 +1,97 @@
+import type { UploadConflicts } from './StorageExplorer.utils'
+
+export interface UploadConflictCopy {
+ title: string
+ description: string
+ replaceLabel: string
+ replaceDescription: string
+ keepBothLabel: string
+ keepBothDescription: string
+}
+
+const getLiveReplaceDescription = (isVersioningSuspended: boolean, isPlural: boolean) => {
+ if (isVersioningSuspended && isPlural) {
+ return 'Each file you replace is kept as a noncurrent version one last time, and anything uploaded after that overwrites it in place'
+ }
+ if (isVersioningSuspended) {
+ return 'The file you replace is kept as a noncurrent version one last time, and anything uploaded after that overwrites it in place'
+ }
+ if (isPlural) {
+ return 'Each file you replace becomes a noncurrent version you can restore from its version history'
+ }
+ return 'The file you replace becomes a noncurrent version you can restore from its version history'
+}
+
+/**
+ * What the two choices mean depends on what is sitting at the name. A live file is replaced
+ * and kept as a noncurrent version; an archived one has no visible occupant at all, so the
+ * upload restores it. There is no singular mixed case — a mix needs at least two names.
+ */
+export const getUploadConflictCopy = ({
+ liveNames,
+ archivedNames,
+ isVersioningSuspended,
+}: UploadConflicts): UploadConflictCopy => {
+ const totalCount = liveNames.length + archivedNames.length
+
+ if (archivedNames.length === 0 && liveNames.length === 1) {
+ return {
+ title: `${liveNames[0]} already exists here`,
+ description: 'Choose what happens to the existing file.',
+ replaceLabel: 'Replace existing file',
+ replaceDescription: getLiveReplaceDescription(isVersioningSuspended, false),
+ keepBothLabel: 'Keep both files',
+ keepBothDescription: 'Keeps the existing file and appends an incremental number to the name',
+ }
+ }
+
+ if (archivedNames.length === 0) {
+ return {
+ title: `${totalCount} files already exist here`,
+ description: 'Choose what happens to the existing files.',
+ replaceLabel: 'Replace existing files',
+ replaceDescription: getLiveReplaceDescription(isVersioningSuspended, true),
+ keepBothLabel: 'Keep all files',
+ keepBothDescription:
+ 'Keeps the existing files and appends an incremental number to the names',
+ }
+ }
+
+ if (liveNames.length === 0 && archivedNames.length === 1) {
+ return {
+ title: `${archivedNames[0]} already exists and is archived`,
+ description: 'Choose what happens to the archived file.',
+ replaceLabel: 'Restore and add a new version',
+ replaceDescription:
+ 'Your upload becomes the current version, and the archived versions stay in its version history',
+ keepBothLabel: 'Keep both files',
+ keepBothDescription:
+ 'Leaves the file archived and appends an incremental number to the name you upload',
+ }
+ }
+
+ if (liveNames.length === 0) {
+ return {
+ title: `${totalCount} files already exist and are archived`,
+ description: 'Choose what happens to the archived files.',
+ replaceLabel: 'Restore and add new versions',
+ replaceDescription:
+ 'Each upload becomes the current version, and the archived versions stay in its version history',
+ keepBothLabel: 'Keep all files',
+ keepBothDescription:
+ 'Leaves the files archived and appends an incremental number to the names you upload',
+ }
+ }
+
+ return {
+ title: `${totalCount} files already exist here`,
+ description: 'Some of them are archived. Choose what happens to all of them.',
+ replaceLabel: 'Replace and restore',
+ replaceDescription: isVersioningSuspended
+ ? 'Existing files are kept as noncurrent versions one last time, and archived files are restored with your upload as the current version'
+ : 'Existing files become noncurrent versions, and archived files are restored with your upload as the current version',
+ keepBothLabel: 'Keep all files',
+ keepBothDescription:
+ 'Leaves the existing and archived files as they are, and appends an incremental number to the names you upload',
+ }
+}
diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/useUploadConflictPrompt.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/useUploadConflictPrompt.ts
new file mode 100644
index 00000000000..323a0b7d045
--- /dev/null
+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/useUploadConflictPrompt.ts
@@ -0,0 +1,39 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+
+import type { UploadConflictResolution, UploadConflicts } from './StorageExplorer.utils'
+
+const NO_CONFLICTS: UploadConflicts = {
+ liveNames: [],
+ archivedNames: [],
+ isVersioningSuspended: false,
+}
+
+/**
+ * Turns the upload's name clash into a question the user answers in a modal. The upload is
+ * already in flight by then, so it awaits the returned promise rather than being restarted.
+ */
+export const useUploadConflictPrompt = () => {
+ const [conflicts, setConflicts] = useState<UploadConflicts>(NO_CONFLICTS)
+ const resolveRef = useRef<((resolution: UploadConflictResolution) => void) | undefined>(undefined)
+
+ // An unmount mid-prompt would otherwise leave the upload waiting on a modal nobody can see.
+ useEffect(() => () => resolveRef.current?.('cancel'), [])
+
+ const promptForConflicts = useCallback((nextConflicts: UploadConflicts) => {
+ // Two uploads can be in flight at once, and only one modal can be on screen. Without
+ // this the earlier upload would wait on a promise nothing resolves, silently forever.
+ resolveRef.current?.('cancel')
+ setConflicts(nextConflicts)
+ return new Promise<UploadConflictResolution>((resolve) => {
+ resolveRef.current = resolve
+ })
+ }, [])
+
+ const resolveConflicts = useCallback((resolution: UploadConflictResolution) => {
+ setConflicts(NO_CONFLICTS)
+ resolveRef.current?.(resolution)
+ resolveRef.current = undefined
+ }, [])
+
+ return { conflicts, promptForConflicts, resolveConflicts }
+}
diff --git a/apps/studio/data/storage/keys.ts b/apps/studio/data/storage/keys.ts
index 13257248024..1c84d8e2c14 100644
--- a/apps/studio/data/storage/keys.ts
+++ b/apps/studio/data/storage/keys.ts
@@ -99,6 +99,11 @@ export const storageKeys = {
] as const,
archivedObjects: (projectRef: string | undefined, bucketId: string | undefined) =>
['projects', projectRef, 'buckets', bucketId, 'archived-objects'] as const,
+ archivedObjectNames: (
+ projectRef: string | undefined,
+ bucketId: string | undefined,
+ path: string
+ ) => ['projects', projectRef, 'buckets', bucketId, 'archived-object-names', path] as const,
icebergNamespaces: ({ projectRef, warehouse }: { projectRef?: string; warehouse?: string }) =>
[projectRef, 'warehouse', warehouse, 'namespaces'] as const,
icebergNamespace: ({
diff --git a/apps/studio/data/storage/versioning/archived-object-names-query.test.ts b/apps/studio/data/storage/versioning/archived-object-names-query.test.ts
new file mode 100644
index 00000000000..c2bfaaea0bc
--- /dev/null
+++ b/apps/studio/data/storage/versioning/archived-object-names-query.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it } from 'vitest'
+
+import { toArchivedFileNames } from './archived-object-names-query'
+import type { components } from '@/data/api'
+
+type StorageObjectV2 = components['schemas']['StorageListResponseV2_Output']['objects'][number]
+
+const makeRow = (
+ name: string,
+ {
+ version,
+ createdAt,
+ archivedAt,
+ isDeleteMarker = false,
+ }: {
+ version: string
+ createdAt: string
+ archivedAt?: string
+ isDeleteMarker?: boolean
+ }
+): StorageObjectV2 => ({
+ id: `id-${name}-${version}`,
+ name,
+ version,
+ created_at: createdAt,
+ updated_at: createdAt,
+ last_accessed_at: createdAt,
+ archived_at: archivedAt ?? null,
+ is_delete_marker: isDeleteMarker,
+ metadata: isDeleteMarker ? null : { size: 10, mimetype: 'image/svg+xml' },
+})
+
+/** A delete marker on top of the version it hid: what archiving a file leaves behind. */
+const archivedRows = (name: string) => [
+ makeRow(name, { version: 'v-marker', createdAt: '2024-02-01T00:00:00Z', isDeleteMarker: true }),
+ makeRow(name, {
+ version: 'v1',
+ createdAt: '2024-01-01T00:00:00Z',
+ archivedAt: '2024-02-01T00:00:00Z',
+ }),
+]
+
+describe('toArchivedFileNames', () => {
+ it('takes the leaf, since v2 returns the full key from the bucket root', () => {
+ expect(toArchivedFileNames(archivedRows('folder/nested/icon-1.svg'))).toEqual(['icon-1.svg'])
+ })
+
+ it('leaves a root-level name alone', () => {
+ expect(toArchivedFileNames(archivedRows('icon-1.svg'))).toEqual(['icon-1.svg'])
+ })
+
+ it('ignores a live file, which has no delete marker on top', () => {
+ expect(
+ toArchivedFileNames([
+ makeRow('photo.png', { version: 'v1', createdAt: '2024-01-01T00:00:00Z' }),
+ ])
+ ).toEqual([])
+ })
+
+ it('ignores a delete marker left behind by a permanent delete', () => {
+ // Nothing is retained underneath, so there is nothing to restore and the explorer does
+ // not list it either. Prompting here would name a file the user cannot find anywhere.
+ expect(
+ toArchivedFileNames([
+ makeRow('app icon-1.svg', {
+ version: 'v-marker',
+ createdAt: '2024-02-01T00:00:00Z',
+ isDeleteMarker: true,
+ }),
+ ])
+ ).toEqual([])
+ })
+
+ it('drops the empty folder placeholder, which is not a file anyone uploads onto', () => {
+ expect(toArchivedFileNames(archivedRows('folder/.emptyFolderPlaceholder'))).toEqual([])
+ })
+
+ it('reports a leaf once even when two folders both hold it archived', () => {
+ expect(
+ toArchivedFileNames([...archivedRows('a/icon.svg'), ...archivedRows('b/icon.svg')])
+ ).toEqual(['icon.svg'])
+ })
+
+ it('discards the trailing path when the page was cut short', () => {
+ // Its rows are a fragment, and a fragment classifies wrongly either way.
+ const rows = [...archivedRows('a/first.svg'), ...archivedRows('b/second.svg')]
+ expect(toArchivedFileNames(rows, true)).toEqual(['first.svg'])
+ expect(toArchivedFileNames(rows, false)).toEqual(['first.svg', 'second.svg'])
+ })
+
+ it('handles an absent list', () => {
+ expect(toArchivedFileNames()).toEqual([])
+ expect(toArchivedFileNames([])).toEqual([])
+ })
+})
diff --git a/apps/studio/data/storage/versioning/archived-object-names-query.ts b/apps/studio/data/storage/versioning/archived-object-names-query.ts
new file mode 100644
index 00000000000..ca5fff976b8
--- /dev/null
+++ b/apps/studio/data/storage/versioning/archived-object-names-query.ts
@@ -0,0 +1,84 @@
+import { queryOptions } from '@tanstack/react-query'
+import { components } from 'api-types'
+
+import { listBucketObjectsV2 } from '../bucket-objects-list-mutation'
+import { storageKeys } from '../keys'
+import { dropPartialTrailingPath, toArchivedObjects } from './archived-objects-query'
+import { EMPTY_FOLDER_PLACEHOLDER_FILE_NAME } from '@/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils'
+import { IS_PLATFORM } from '@/lib/constants'
+import type { ResponseError } from '@/types'
+
+type StorageObjectV2 = components['schemas']['StorageListResponseV2_Output']['objects'][number]
+
+export type ArchivedObjectNamesVariables = {
+ projectRef?: string
+ bucketId?: string
+ /** Bucket-relative folder path, empty at the root. */
+ path: string
+}
+
+export type ArchivedObjectNamesError = ResponseError
+
+/**
+ * One page only. A folder holding more versioned rows than this just goes unchecked, which
+ * is the behavior from before the prompt existed.
+ */
+const PAGE_SIZE = 1000
+
+/**
+ * Classified exactly the way the explorer's archived view classifies, so the prompt can never
+ * claim something is archived that the user cannot find. `deleteMarkers: 'only'` is not enough
+ * on its own: a purge can leave a delete marker with nothing retained underneath, and that
+ * tombstone is not an archived file — there is nothing behind it to restore.
+ *
+ * v2 also returns `name` as the full key from the bucket root rather than a leaf, so a raw
+ * comparison against an uploaded file's name matches nothing below the root.
+ */
+export const toArchivedFileNames = (objects: StorageObjectV2[] = [], hasNext = false): string[] => {
+ // A page cap can cut one path's rows in half, and a fragment misclassifies either way.
+ const rows = hasNext ? dropPartialTrailingPath(objects) : objects
+ const names = toArchivedObjects(rows)
+ .map((object) => object.path.split('/').pop() ?? '')
+ .filter((name) => name.length > 0 && name !== EMPTY_FOLDER_PLACEHOLDER_FILE_NAME)
+ return Array.from(new Set(names))
+}
+
+/** Names in one folder that the explorer would show under "Show archived". */
+async function getArchivedObjectNames(
+ { projectRef, bucketId, path }: ArchivedObjectNamesVariables,
+ signal?: AbortSignal
+): Promise<string[]> {
+ if (!projectRef) throw new Error('projectRef is required')
+ if (!bucketId) throw new Error('bucketId is required')
+
+ // Without the trailing slash v2 reads "docs" as a partial name match against siblings
+ // like "docs-old" rather than descending into the folder.
+ const prefix = path.length > 0 ? `${path}/` : ''
+
+ const data = await listBucketObjectsV2(
+ {
+ projectRef,
+ bucketId,
+ prefix,
+ // Whole history per path: deciding whether a path is archived takes the rows under the
+ // current one, not just the markers.
+ options: { limit: PAGE_SIZE, deleteMarkers: 'include', noncurrentVersions: 'include' },
+ },
+ signal
+ )
+
+ return toArchivedFileNames(data?.objects, data?.hasNext)
+}
+
+export type ArchivedObjectNamesData = Awaited<ReturnType<typeof getArchivedObjectNames>>
+
+export const archivedObjectNamesQueryOptions = ({
+ projectRef,
+ bucketId,
+ path,
+}: ArchivedObjectNamesVariables) =>
+ queryOptions({
+ queryKey: storageKeys.archivedObjectNames(projectRef, bucketId, path),
+ queryFn: ({ signal }) => getArchivedObjectNames({ projectRef, bucketId, path }, signal),
+ enabled: IS_PLATFORM && typeof projectRef !== 'undefined' && typeof bucketId !== 'undefined',
+ })
diff --git a/apps/studio/state/storage-explorer.tsx b/apps/studio/state/storage-explorer.tsx
index 8c47f033121..c44c1e100ba 100644
--- a/apps/studio/state/storage-explorer.tsx
+++ b/apps/studio/state/storage-explorer.tsx
@@ -38,14 +38,22 @@ import {
formatTime,
getFilesDataTransferItems,
getPathAlongFoldersToIndex,
+ getReplaceableFileNames,
getStorageItemPath,
+ getUploadNameConflicts,
sanitizeNameForDuplicateInColumn,
validateFolderName,
+ type UploadConflictResolution,
+ type UploadConflicts,
} from '@/components/interfaces/Storage/StorageExplorer/StorageExplorer.utils'
import { fetchFileUrl } from '@/components/interfaces/Storage/StorageExplorer/useFetchFileUrlQuery'
import { getStoragePreference } from '@/components/interfaces/Storage/StorageExplorer/useStoragePreference'
import { convertFromBytes } from '@/components/interfaces/Storage/StorageSettings/StorageSettings.utils'
-import { isVersioningActive } from '@/components/interfaces/Storage/StorageVersioning.constants'
+import {
+ getBucketVersioningState,
+ hasVersioningHistory,
+ isVersioningActive,
+} from '@/components/interfaces/Storage/StorageVersioning.constants'
import { InlineLink } from '@/components/ui/InlineLink'
import { getOrRefreshTemporaryApiKey } from '@/data/api-keys/temp-api-keys-utils'
import { configKeys } from '@/data/config/keys'
@@ -59,6 +67,7 @@ import { deleteBucketPrefix } from '@/data/storage/bucket-prefix-delete-mutation
import type { Bucket } from '@/data/storage/buckets-query'
import { storageKeys } from '@/data/storage/keys'
import { moveStorageObject } from '@/data/storage/object-move-mutation'
+import { archivedObjectNamesQueryOptions } from '@/data/storage/versioning/archived-object-names-query'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { PROJECT_STATUS } from '@/lib/constants'
import { lookupMime } from '@/lib/mime'
@@ -174,9 +183,9 @@ export function createStorageExplorerState({
},
// Separate from `selectedItemsToDelete`, which only archives on a versioned bucket.
- itemToPurge: undefined as StorageItemWithColumn | undefined,
- setItemToPurge: (item?: StorageItemWithColumn) => {
- state.itemToPurge = item
+ itemsToPurge: [] as StorageItemWithColumn[],
+ setItemsToPurge: (items: StorageItemWithColumn[]) => {
+ state.itemsToPurge = items
},
selectedItemsToMove: [] as StorageItemWithColumn[],
@@ -1062,10 +1071,17 @@ export function createStorageExplorerState({
files,
columnIndex,
isDrop = false,
+ onConflict,
}: {
files: FileList | DataTransferItemList
columnIndex: number
isDrop?: boolean
+ /**
+ * Offered the names an upload would land on, when the bucket's versioning state makes
+ * the choice meaningful. Without it — or on a bucket where it isn't offered — the
+ * upload falls back to renaming, which is what every caller did before the prompt.
+ */
+ onConflict?: (conflicts: UploadConflicts) => Promise<UploadConflictResolution>
}) => {
const queryClient = getQueryClient()
const storageConfiguration = queryClient
@@ -1078,13 +1094,35 @@ export function createStorageExplorerState({
const t1 = new Date()
const autofix = true
+ // Resolved before the awaits below so the destination can be checked for drift
+ // afterwards: the user is free to navigate while a drop is being read and prompted on.
+ const derivedColumnIndex = columnIndex === -1 ? state.getLatestColumnIndex() : columnIndex
+ const bucketIdAtStart = state.selectedBucket.id
+ const destinationPath = state.columns?.[derivedColumnIndex]?.path ?? ''
+
+ const canPromptOnConflict =
+ onConflict !== undefined && hasVersioningHistory(state.selectedBucket)
+ const archivedNamesRequest = canPromptOnConflict
+ ? queryClient
+ .fetchQuery({
+ ...archivedObjectNamesQueryOptions({
+ projectRef: state.projectRef,
+ bucketId: bucketIdAtStart,
+ path: destinationPath,
+ }),
+ staleTime: 0,
+ })
+ // An auxiliary check never blocks an upload; without it the clash just goes
+ // unannounced, which is the behavior that shipped before.
+ .catch(() => [] as string[])
+ : Promise.resolve([] as string[])
+
// We filter out any folders which are just '#' until we can properly encode such characters in the URL
const filesToUpload: (File & { path?: string })[] = isDrop
? (await getFilesDataTransferItems(files as DataTransferItemList)).filter(
(file) => !file.path.includes('#/')
)
: Array.from(files as FileList)
- const derivedColumnIndex = columnIndex === -1 ? state.getLatestColumnIndex() : columnIndex
const filesWithinUploadLimit =
fileSizeLimit !== undefined
@@ -1159,6 +1197,77 @@ export function createStorageExplorerState({
return file
})
+ // Asked before anything is written, because the answer changes where the bytes land: a
+ // replace overwrites the object in place, which on a versioned bucket turns the file it
+ // lands on into a previous version. Only the top level of a drop can clash — a folder
+ // upload merges into its destination — and only against files, since a name that belongs
+ // to a folder has nothing to overwrite.
+ const topLevelFileNames = formattedFilesToUpload
+ .filter((file) => (file.path ?? '').split('/').length <= 1)
+ .map((file) => file.name)
+ const existingFileNames = (state.columns?.[derivedColumnIndex]?.items ?? [])
+ .filter(
+ (item) =>
+ item.type === STORAGE_ROW_TYPES.FILE && item.status !== STORAGE_ROW_STATUS.EDITING
+ )
+ .map((item) => item.name)
+
+ const versioningState = getBucketVersioningState(state.selectedBucket)
+ const replaceableNames = getReplaceableFileNames({
+ items: state.columns?.[derivedColumnIndex]?.items ?? [],
+ versioningState,
+ })
+ const liveNames = getUploadNameConflicts({
+ fileNames: topLevelFileNames,
+ existingNames: replaceableNames,
+ })
+ // A delete marker can outlive the delete it recorded, so anything the archived listing
+ // reports that is also live belongs to the live half, where replacing is what it says.
+ const takenLiveNames = new Set(existingFileNames.map((name) => name.toLowerCase()))
+ const archivedFolderNames = (await archivedNamesRequest).filter(
+ (name) => !takenLiveNames.has(name.toLowerCase())
+ )
+ const archivedNames = getUploadNameConflicts({
+ fileNames: topLevelFileNames,
+ existingNames: archivedFolderNames,
+ })
+
+ const existingNameByLowercase = new Map(
+ [...replaceableNames, ...archivedFolderNames].map((name) => [name.toLowerCase(), name])
+ )
+
+ const conflicts: UploadConflicts = {
+ liveNames: canPromptOnConflict ? liveNames : [],
+ archivedNames: canPromptOnConflict ? archivedNames : [],
+ isVersioningSuspended: versioningState === 'suspended',
+ }
+
+ let shouldReplaceConflicts = false
+ if (
+ onConflict !== undefined &&
+ conflicts.liveNames.length + conflicts.archivedNames.length > 0
+ ) {
+ const resolution = await onConflict(conflicts)
+ if (resolution === 'cancel') return
+ shouldReplaceConflicts = resolution === 'replace'
+ }
+
+ const destinationColumn = state.columns?.[derivedColumnIndex]
+ if (
+ destinationColumn === undefined ||
+ destinationColumn.path !== destinationPath ||
+ state.selectedBucket.id !== bucketIdAtStart
+ ) {
+ toast.error('Upload cancelled: the folder you dropped into is no longer open')
+ return
+ }
+
+ const conflictingNames = [...conflicts.liveNames, ...conflicts.archivedNames]
+ const archivedConflictNames = new Set(conflicts.archivedNames)
+
+ /** Overwritten paths, whose cached preview bytes and version list go stale. */
+ const replacedPaths: string[] = []
+
state.uploadProgresses = new Array(formattedFilesToUpload.length).fill({
percentage: 0,
elapsed: 0,
@@ -1188,9 +1297,23 @@ export function createStorageExplorerState({
const fileOptions = { cacheControl: '3600', contentType: metadata.mimetype }
const isWithinFolder = (file?.path ?? '').split('/').length > 1
- const fileName = !isWithinFolder
- ? sanitizeNameForDuplicateInColumn(state, { name: file.name, autofix })
- : file.name
+ const isReplacingExisting =
+ shouldReplaceConflicts && !isWithinFolder && conflictingNames.includes(file.name)
+ const isReplacingArchived = isReplacingExisting && archivedConflictNames.has(file.name)
+
+ const getUploadName = () => {
+ if (isWithinFolder) return file.name
+ if (isReplacingExisting) {
+ return existingNameByLowercase.get(file.name.toLowerCase()) ?? file.name
+ }
+ return sanitizeNameForDuplicateInColumn(state, {
+ name: file.name,
+ autofix,
+ columnIndex: derivedColumnIndex,
+ reservedNames: archivedFolderNames,
+ })
+ }
+ const fileName = getUploadName()
const unsanitizedFormattedFileName =
has(file, ['path']) && isWithinFolder ? file.path : fileName
/**
@@ -1220,7 +1343,19 @@ export function createStorageExplorerState({
})
uploadedTopLevelFolders.push(topLevelFolder)
}
+ } else if (isReplacingExisting && !isReplacingArchived) {
+ replacedPaths.push(formattedPathToFile)
+ // The row is already in the column, so a temp row would duplicate it until the refetch.
+ state.updateRowStatus({
+ name: fileName!,
+ status: STORAGE_ROW_STATUS.LOADING,
+ columnIndex: derivedColumnIndex,
+ })
} else {
+ // An archived row lives in the rendered overlay rather than the column, so it needs
+ // a temp row like any new file — which also hides the overlay's copy of it, since
+ // the overlay skips names the column already holds.
+ if (isReplacingArchived) replacedPaths.push(formattedPathToFile)
state.addTempRow({
type: STORAGE_ROW_TYPES.FILE,
name: fileName!,
@@ -1261,9 +1396,10 @@ export function createStorageExplorerState({
const upload = new tus.Upload(file, {
endpoint: state.resumableUploadUrl,
retryDelays: [0, 200, 500, 1500, 3000, 5000],
- headers: {
- 'x-source': 'supabase-dashboard',
- },
+ // Without upsert the write is rejected as a conflict, since the path exists.
+ headers: isReplacingExisting
+ ? { 'x-source': 'supabase-dashboard', 'x-upsert': 'true' }
+ : { 'x-source': 'supabase-dashboard' },
uploadDataDuringCreation: uploadDataDuringCreation,
removeFingerprintOnSuccess: true,
metadata: {
@@ -1421,6 +1557,24 @@ export function createStorageExplorerState({
await state.refetchAllOpenedFolders()
+ // The preview URL is cached against the path for a week, so without this the panel
+ // keeps rendering the bytes from before the replace, and the version list stays short.
+ await Promise.all(
+ replacedPaths.flatMap((path) => [
+ queryClient.invalidateQueries({
+ queryKey: storageKeys.objectVersions(state.projectRef, state.selectedBucket.id, path),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: storageKeys.fileUrl({
+ projectRef: state.projectRef,
+ isBucketPublic: state.selectedBucket.public,
+ bucketId: state.selectedBucket.id,
+ path,
+ }),
+ }),
+ ])
+ )
+
if (
numberOfFilesToUpload === 0 ||
(numberOfFilesUploadedSuccess === 0 && numberOfFilesUploadedFail === 0)