The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): storage versioning - archived UI (#51476)
Francesco Sansalvadorecb4307f15b99
diff --git a/apps/studio/components/interfaces/Storage/BucketVersioningPill.tsx b/apps/studio/components/interfaces/Storage/BucketVersioningPill.tsxnew file mode 100644index 00000000000..dca1a44b77b--- /dev/null+++ b/apps/studio/components/interfaces/Storage/BucketVersioningPill.tsx@@ -0,0 +1,49 @@+import { FileStack } from 'lucide-react'+import { Badge, Tooltip, TooltipContent, TooltipTrigger } from 'ui'++import { getBucketVersioningState } from './StorageVersioning.constants'+import { useIsStorageVersioningEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'+import type { Bucket } from '@/data/storage/buckets-query'++const COPY = {+ enabled: {+ variant: 'success' as const,+ state: 'Enabled',+ tooltip: 'Overwriting or archiving a file keeps a recoverable copy.',+ },+ suspended: {+ variant: 'warning' as const,+ state: 'Suspended',+ tooltip: 'Existing versions stay retained, but new writes are not versioned.',+ },+}++interface BucketVersioningPillProps {+ bucket?: Bucket+ showPrefix?: boolean+}++export const BucketVersioningPill = ({ bucket, showPrefix = true }: BucketVersioningPillProps) => {+ const isStorageVersioningEnabled = useIsStorageVersioningEnabled()+ const versioningState = getBucketVersioningState(bucket)++ if (!isStorageVersioningEnabled || versioningState === 'disabled') return null++ const { variant, state, tooltip } = COPY[versioningState]++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <span tabIndex={0} className="shrink-0">+ <Badge variant={variant}>+ <FileStack size={12} aria-hidden />+ {showPrefix ? `Versioning ${state.toLowerCase()}` : state}+ </Badge>+ </span>+ </TooltipTrigger>+ <TooltipContent side="bottom" className="max-w-64">+ {tooltip}+ </TooltipContent>+ </Tooltip>+ )+}diff --git a/apps/studio/components/interfaces/Storage/FilesBuckets/BucketTable.tsx b/apps/studio/components/interfaces/Storage/FilesBuckets/BucketTable.tsxindex b569965dcbd..e2ac8c2ac1c 100644--- a/apps/studio/components/interfaces/Storage/FilesBuckets/BucketTable.tsx+++ b/apps/studio/components/interfaces/Storage/FilesBuckets/BucketTable.tsx@@ -12,7 +12,10 @@ import {TooltipTrigger,} from 'ui'+import { useIsStorageVersioningEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'+import { BucketVersioningPill } from '@/components/interfaces/Storage/BucketVersioningPill'import { PUBLIC_BUCKET_TOOLTIP } from '@/components/interfaces/Storage/Storage.constants'+import { getBucketVersioningState } from '@/components/interfaces/Storage/StorageVersioning.constants'import { useBucketPolicyCount } from '@/components/interfaces/Storage/useBucketPolicyCount'import { TableRowNoResults } from '@/components/ui/TableRowNoResults'import {@@ -27,12 +30,21 @@ import { createNavigationHandler } from '@/lib/navigation'type BucketTableMode = 'standard' | 'virtualized'+export const useVersioningColumnSpan = () => (useIsStorageVersioningEnabled() ? 1 : 0)++const BucketVersioningCell = ({ bucket }: { bucket: Bucket }) => {+ if (getBucketVersioningState(bucket) === 'disabled')+ return <span className="text-foreground-muted">-</span>+ return <BucketVersioningPill bucket={bucket} showPrefix={false} />+}+type BucketTableHeaderProps = {mode: BucketTableModehasBuckets?: boolean}export const BucketTableHeader = ({ mode, hasBuckets = true }: BucketTableHeaderProps) => {+ const isStorageVersioningEnabled = useIsStorageVersioningEnabled()const BucketTableHeader = mode === 'standard' ? TableHeader : VirtualizedTableHeaderconst BucketTableRow = mode === 'standard' ? TableRow : VirtualizedTableRowconst BucketTableHead = mode === 'standard' ? TableHead : VirtualizedTableHead@@ -51,6 +63,9 @@ export const BucketTableHeader = ({ mode, hasBuckets = true }: BucketTableHeader<BucketTableHead className={stickyClasses}>Policies</BucketTableHead><BucketTableHead className={stickyClasses}>File size limit</BucketTableHead><BucketTableHead className={stickyClasses}>Allowed MIME types</BucketTableHead>+ {isStorageVersioningEnabled && (+ <BucketTableHead className={stickyClasses}>Versioning</BucketTableHead>+ )}<BucketTableHead className={stickyClasses}><span className="sr-only">Actions</span></BucketTableHead>@@ -65,22 +80,28 @@ type BucketTableEmptyStateProps = {}export const BucketTableEmptyState = ({ mode, filterString }: BucketTableEmptyStateProps) => {+ const versioningColumnSpan = useVersioningColumnSpan()+if (mode === 'standard') {return (- <TableRowNoResults className="[&>td]:hover:bg-inherit" colSpan={5} search={filterString} />- )- } else {- return (- <VirtualizedTableRow className="[&>td]:hover:bg-inherit">- <VirtualizedTableCell colSpan={5}>- <p className="text-sm text-foreground">No results found</p>- <p className="text-sm text-foreground-lighter">- Your search for “{filterString}” did not return any results- </p>- </VirtualizedTableCell>- </VirtualizedTableRow>+ <TableRowNoResults+ className="[&>td]:hover:bg-inherit"+ colSpan={5 + versioningColumnSpan}+ search={filterString}+ />)}++ return (+ <VirtualizedTableRow className="[&>td]:hover:bg-inherit">+ <VirtualizedTableCell colSpan={5 + versioningColumnSpan}>+ <p className="text-sm text-foreground">No results found</p>+ <p className="text-sm text-foreground-lighter">+ Your search for “{filterString}” did not return any results+ </p>+ </VirtualizedTableCell>+ </VirtualizedTableRow>+ )}type BucketTableRowProps = {@@ -98,6 +119,7 @@ export const BucketTableRow = ({}: BucketTableRowProps) => {const router = useRouter()const { getPolicyCount } = useBucketPolicyCount()+ const isStorageVersioningEnabled = useIsStorageVersioningEnabled()const BucketTableRow = mode === 'standard' ? TableRow : VirtualizedTableRowconst BucketTableCell = mode === 'standard' ? TableCell : VirtualizedTableCell@@ -158,6 +180,12 @@ export const BucketTableRow = ({</p></BucketTableCell>+ {isStorageVersioningEnabled && (+ <BucketTableCell>+ <BucketVersioningCell bucket={bucket} />+ </BucketTableCell>+ )}+<BucketTableCell><div className="flex justify-end items-center h-full"><ChevronRight aria-hidden={true} size={14} className="text-foreground-muted/60" />diff --git a/apps/studio/components/interfaces/Storage/FilesBuckets/BucketVersioningFields/BucketVersioningFields.tsx b/apps/studio/components/interfaces/Storage/FilesBuckets/BucketVersioningFields/BucketVersioningFields.tsxindex 93dd4cd1456..544ce50c1a1 100644--- a/apps/studio/components/interfaces/Storage/FilesBuckets/BucketVersioningFields/BucketVersioningFields.tsx+++ b/apps/studio/components/interfaces/Storage/FilesBuckets/BucketVersioningFields/BucketVersioningFields.tsx@@ -48,6 +48,9 @@ export const BucketVersioningFields = ({// Turning the switch off suspends rather than disables, so this is a heads-up.const isSuspending = !isVersioningEnabled && initialVersioningState !== 'disabled'+ // A suspended bucket keeps expiring the versions it still holds, so the policy stays editable.+ const canEditLifecycle = isVersioningEnabled || initialVersioningState === 'suspended'+// A bound nobody has read, or that the fields only partly represent, can't be compared against.const hasKnownBounds = !isLoadingPolicy && !isUnsupportedPolicy && !policyError@@ -86,7 +89,6 @@ export const BucketVersioningFields = ({><FormControl><Switch- // Matches the field name, which is what the layout's label points at.id="enable_versioning"aria-label="Object versioning"size="large"@@ -139,7 +141,7 @@ export const BucketVersioningFields = ({</FormSectionCollapse>)}- {isVersioningEnabled && (+ {canEditLifecycle && (<FormSectionCollapse key="lifecycle-policy"><LifecyclePolicySectionform={form}diff --git a/apps/studio/components/interfaces/Storage/FilesBuckets/BucketsTable.tsx b/apps/studio/components/interfaces/Storage/FilesBuckets/BucketsTable.tsxindex be21a3782a5..abeb6d738ba 100644--- a/apps/studio/components/interfaces/Storage/FilesBuckets/BucketsTable.tsx+++ b/apps/studio/components/interfaces/Storage/FilesBuckets/BucketsTable.tsx@@ -3,8 +3,12 @@ import { Table, TableBody } from 'ui'import { LoadMoreRow } from './BucketsTable.LoadMoreRow'import type { BucketsTablePaginationProps } from './BucketsTable.types'-import { BucketTableHeader, BucketTableRow } from './BucketTable'-import { TableRowNoResults } from '@/components/ui/TableRowNoResults'+import {+ BucketTableEmptyState,+ BucketTableHeader,+ BucketTableRow,+ useVersioningColumnSpan,+} from './BucketTable'import { VirtualizedTable, VirtualizedTableBody } from '@/components/ui/VirtualizedTable'import { Bucket } from '@/data/storage/buckets-query'@@ -41,6 +45,7 @@ const BucketsTableUnvirtualized = ({pagination: { hasMore = false, isLoadingMore = false, onLoadMore },}: BucketsTableProps) => {const showSearchEmptyState = buckets.length === 0 && filterString.length > 0+ const versioningColumnSpan = useVersioningColumnSpan()return (<Table@@ -52,11 +57,7 @@ const BucketsTableUnvirtualized = ({<BucketTableHeader mode="standard" hasBuckets={buckets.length > 0} /><TableBody>{showSearchEmptyState ? (- <TableRowNoResults- className="[&>td]:hover:bg-inherit"- colSpan={5}- search={filterString}- />+ <BucketTableEmptyState mode="standard" filterString={filterString} />) : (buckets.map((bucket) => (<BucketTableRow@@ -70,7 +71,7 @@ const BucketsTableUnvirtualized = ({)}<LoadMoreRowmode="standard"- colSpan={6}+ colSpan={6 + versioningColumnSpan}hasMore={hasMore}isLoadingMore={isLoadingMore}onLoadMore={onLoadMore}@@ -88,6 +89,7 @@ const BucketsTableVirtualized = ({pagination: { hasMore = false, isLoadingMore = false, onLoadMore },}: BucketsTableProps) => {const showSearchEmptyState = buckets.length === 0 && filterString.length > 0+ const versioningColumnSpan = useVersioningColumnSpan()const scrollContainerRef = useRef<HTMLDivElement>(null)return (@@ -99,20 +101,16 @@ const BucketsTableVirtualized = ({><BucketTableHeader mode="virtualized" hasBuckets={buckets.length > 0} /><VirtualizedTableBody<Bucket>- paddingColSpan={5}+ paddingColSpan={5 + versioningColumnSpan}emptyContent={showSearchEmptyState ? (- <TableRowNoResults- className="[&>td]:hover:bg-inherit"- colSpan={5}- search={filterString}- />+ <BucketTableEmptyState mode="virtualized" filterString={filterString} />) : undefined}trailingContent={<LoadMoreRowmode="virtualized"- colSpan={6}+ colSpan={6 + versioningColumnSpan}hasMore={hasMore}isLoadingMore={isLoadingMore}onLoadMore={onLoadMore}diff --git a/apps/studio/components/interfaces/Storage/FilesBuckets/DeleteBucketModal.tsx b/apps/studio/components/interfaces/Storage/FilesBuckets/DeleteBucketModal.tsxindex 7d2acf649f1..5587852749c 100644--- a/apps/studio/components/interfaces/Storage/FilesBuckets/DeleteBucketModal.tsx+++ b/apps/studio/components/interfaces/Storage/FilesBuckets/DeleteBucketModal.tsx@@ -3,6 +3,7 @@ import { useRouter } from 'next/router'import { toast } from 'sonner'import { extractBucketNameFromDefinition } from '@/components/interfaces/Storage/Storage.utils'+import { hasVersioningHistory } from '@/components/interfaces/Storage/StorageVersioning.constants'import { TextConfirmModal } from '@/components/ui/TextConfirmModalWrapper'import { useDatabasePoliciesQuery } from '@/data/database-policies/database-policies-query'import { useDatabasePolicyDeleteMutation } from '@/data/database-policies/database-policy-delete-mutation'@@ -74,6 +75,10 @@ export const DeleteBucketModal = ({ visible, bucket, onClose }: DeleteBucketModadeleteBucket({ projectRef, id: bucket.id })}+ // Not gated on the feature preview: the retained data is destroyed either way, so the+ // warning has to reflect the bucket rather than what the dashboard happens to be showing.+ const isRetainingVersions = hasVersioningHistory(bucket)+return (<TextConfirmModalvisible={visible}@@ -94,6 +99,8 @@ export const DeleteBucketModal = ({ visible, bucket, onClose }: DeleteBucketModa<p className="text-sm">Your bucket <span className="font-bold text-foreground">{bucket.id}</span> and all of itscontents will be permanently deleted.+ {isRetainingVersions &&+ ' That includes every archived file and every retained version, which cannot be restored afterwards.'}</p></TextConfirmModal>)diff --git a/apps/studio/components/interfaces/Storage/FilesBuckets/EmptyBucketModal.tsx b/apps/studio/components/interfaces/Storage/FilesBuckets/EmptyBucketModal.tsxindex 4a9b669c43c..f62e8663159 100644--- a/apps/studio/components/interfaces/Storage/FilesBuckets/EmptyBucketModal.tsx+++ b/apps/studio/components/interfaces/Storage/FilesBuckets/EmptyBucketModal.tsx@@ -12,6 +12,7 @@ import {} from 'ui'import { Admonition } from 'ui-patterns/Admonition'+import { hasVersioningHistory } from '@/components/interfaces/Storage/StorageVersioning.constants'import { useBucketEmptyMutation } from '@/data/storage/bucket-empty-mutation'import type { Bucket } from '@/data/storage/buckets-query'import { useStorageExplorerStateSnapshot } from '@/state/storage-explorer'@@ -25,6 +26,9 @@ export interface EmptyBucketModalProps {export const EmptyBucketModal = ({ visible, bucket, onClose }: EmptyBucketModalProps) => {const { ref: projectRef } = useParams()const { fetchFolderContents } = useStorageExplorerStateSnapshot()+ // Not gated on the feature preview: the retained data is destroyed either way, so the+ // warning has to reflect the bucket rather than what the dashboard happens to be showing.+ const isRetainingVersions = hasVersioningHistory(bucket)const { mutate: emptyBucket, isPending } = useBucketEmptyMutation({onSuccess: async () => {@@ -62,7 +66,11 @@ export const EmptyBucketModal = ({ visible, bucket, onClose }: EmptyBucketModalPtype="destructive"className="rounded-none border-x-0 border-t-0"title="This action cannot be undone"- description="The contents of your bucket cannot be recovered once deleted."+ description={+ isRetainingVersions+ ? 'Every live object, archived file and retained version in this bucket is permanently deleted and cannot be recovered.'+ : 'The contents of your bucket cannot be recovered once deleted.'+ }/><DialogSection><p className="text-sm">diff --git a/apps/studio/components/interfaces/Storage/Storage.types.ts b/apps/studio/components/interfaces/Storage/Storage.types.tsindex a738cdf60d6..48a97fb05bf 100644--- a/apps/studio/components/interfaces/Storage/Storage.types.ts+++ b/apps/studio/components/interfaces/Storage/Storage.types.ts@@ -37,10 +37,10 @@ export interface StorageItem {created_at: string | nullupdated_at: string | nulllast_accessed_at: string | null+ is_versioned?: boolean | null// UI specific properties, not from APIisCorrupted: booleanpath?: string- /** Set on a row synthesized from the archived list; absent on a synthesized folder. */archived?: { archivedObjectId?: string }}diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/ArchivedFilePreviewPane.test.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/ArchivedFilePreviewPane.test.tsxnew file mode 100644index 00000000000..f8f33b086c2--- /dev/null+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/ArchivedFilePreviewPane.test.tsx@@ -0,0 +1,146 @@+import { screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { ArchivedFilePreviewPane } from '@/components/interfaces/Storage/StorageExplorer/ArchivedFilePreviewPane'+import type { ArchivedVersionRow } from '@/components/interfaces/Storage/StorageExplorer/archivedVersions.utils'+import type { ArchivedObject } from '@/data/storage/versioning/archived-objects-query'+import { customRender as render } from '@/tests/lib/custom-render'+import { addAPIMock } from '@/tests/lib/msw'++const refetchAllOpenedFolders = vi.fn().mockResolvedValue(undefined)+const clearArchivedSelection = vi.fn()++const ARCHIVED_OBJECT: ArchivedObject = {+ id: 'delete-marker-1',+ path: 'images/gone.png',+ archivedAt: '2024-01-02T00:00:00Z',+ currentVersion: {+ versionId: 'v-current',+ size: 100,+ createdAt: '2024-01-01T00:00:00Z',+ action: 'initial upload',+ mimeType: 'image/png',+ },+ noncurrentVersions: [+ {+ versionId: 'v-older',+ size: 80,+ createdAt: '2023-12-01T00:00:00Z',+ action: 'initial upload',+ mimeType: 'image/png',+ },+ ],+}++let selectedArchivedVersion: ArchivedVersionRow | undefined++vi.mock('@/state/storage-explorer', () => ({+ useStorageExplorerStateSnapshot: () => ({+ projectRef: 'abcdef',+ selectedBucket: { id: 'my-bucket', name: 'my-bucket', public: false },+ refetchAllOpenedFolders,+ }),+}))+vi.mock('@/components/interfaces/Storage/StorageExplorer/ArchivedFilesContext', () => ({+ useArchivedFilesContext: () => ({+ selectedArchivedObject: ARCHIVED_OBJECT,+ selectedArchivedVersion,+ setSelectedArchivedVersion: vi.fn(),+ clearArchivedSelection,+ }),+}))+vi.mock('@/hooks/misc/useCheckPermissions', () => ({+ useAsyncCheckPermissions: () => ({ can: true }),+}))++describe('ArchivedFilePreviewPane', () => {+ // The pane previews the archived file, so every test makes this request.+ let signed: unknown[] = []+ beforeEach(() => {+ signed = []+ selectedArchivedVersion = undefined+ addAPIMock({+ method: 'post',+ path: '/platform/storage/:ref/buckets/:id/objects/sign',+ response: async ({ request }) => {+ signed.push(await request.json())+ return Response.json({ signedUrl: 'https://example.com/gone.png' })+ },+ })+ })++ it('signs the archived version, since the path itself resolves to the delete marker', async () => {+ render(<ArchivedFilePreviewPane />)++ await waitFor(() =>+ expect(signed).toContainEqual(+ expect.objectContaining({+ path: 'images/gone.png',+ options: expect.objectContaining({ versionId: 'v-current' }),+ })+ )+ )+ })++ it('refreshes the live listing after a restore, so the file reappears', async () => {+ addAPIMock({+ method: 'delete',+ path: '/platform/storage/:ref/buckets/:id/objects',+ response: () => Response.json({}),+ })++ render(<ArchivedFilePreviewPane />)++ await userEvent.click(screen.getByRole('button', { name: /restore/i }))++ // Without this the archived row goes but the restored file stays invisible:+ // the live listing is the explorer's own state, not a React Query cache.+ await waitFor(() => expect(refetchAllOpenedFolders).toHaveBeenCalled())+ expect(clearArchivedSelection).toHaveBeenCalled()+ })++ it('promotes the selected version after unarchiving, not just the one under the marker', async () => {+ selectedArchivedVersion = {+ versionId: 'v-older',+ size: 80,+ createdAt: '2023-12-01T00:00:00Z',+ action: 'initial upload',+ mimeType: 'image/png',+ wasCurrentAtArchive: false,+ }++ const unarchived: unknown[] = []+ const moved: unknown[] = []+ addAPIMock({+ method: 'delete',+ path: '/platform/storage/:ref/buckets/:id/objects',+ response: async ({ request }) => {+ unarchived.push(await request.json())+ return Response.json({})+ },+ })+ addAPIMock({+ method: 'post',+ path: '/platform/storage/:ref/buckets/:id/objects/move',+ response: async ({ request }) => {+ moved.push(await request.json())+ return Response.json({})+ },+ })++ render(<ArchivedFilePreviewPane />)++ await userEvent.click(screen.getByRole('button', { name: /restore as current version/i }))++ // Removing the delete marker only promotes the version that was current at archive time.+ await waitFor(() => expect(unarchived).toHaveLength(1))+ await waitFor(() => expect(moved).toHaveLength(1))+ expect(moved[0]).toMatchObject({+ from: 'images/gone.png',+ to: 'images/gone.png',+ sourceVersionId: 'v-older',+ })+ expect(clearArchivedSelection).toHaveBeenCalled()+ })+})diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/ArchivedFilePreviewPane.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/ArchivedFilePreviewPane.tsxnew file mode 100644index 00000000000..1f4e8e99a41--- /dev/null+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/ArchivedFilePreviewPane.tsx@@ -0,0 +1,322 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'+import dayjs from 'dayjs'+import { RotateCcw, Trash2, X } from 'lucide-react'+import { useState } from 'react'+import { toast } from 'sonner'+import { Badge, Button } from 'ui'+import { ConfirmationModal } from 'ui-patterns/Dialogs/ConfirmationModal'++import { useArchivedFilesContext } from './ArchivedFilesContext'+import { ArchivedVersionRestoreWidget } from './ArchivedVersionRestoreWidget'+import { ArchivedVersionRow as ArchivedVersionListRow } from './ArchivedVersionRow'+import { getMergedArchivedVersions, type ArchivedVersionRow } from './archivedVersions.utils'+import { FilePreview } from './FilePreview'+import { PreviewSection } from './PreviewSection'+import { shortVersion } from './VersionHistory'+import { ButtonTooltip } from '@/components/ui/ButtonTooltip'+import { useArchivedObjectPurgeMutation } from '@/data/storage/versioning/archived-object-purge-mutation'+import { useArchivedObjectRestoreMutation } from '@/data/storage/versioning/archived-object-restore-mutation'+import { useArchivedObjectVersionDeleteMutation } from '@/data/storage/versioning/archived-object-version-delete-mutation'+import { useObjectVersionRestoreMutation } from '@/data/storage/versioning/object-version-restore-mutation'+import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'+import { formatBytes } from '@/lib/helpers'+import { useStorageExplorerStateSnapshot } from '@/state/storage-explorer'++const PANEL_WIDTH = 450++const ArchivedFileDetail = ({ label, value }: { label: string; value: string }) => (+ <div>+ <label className="mb-1 text-xs text-foreground-lighter">{label}</label>+ <p className="break-all text-sm text-foreground-light">{value}</p>+ </div>+)++/** Replaces `PreviewPane` while an archived row is selected. */+export const ArchivedFilePreviewPane = () => {+ const { projectRef, selectedBucket, refetchAllOpenedFolders } = useStorageExplorerStateSnapshot()+ const {+ selectedArchivedObject: object,+ selectedArchivedVersion: previewedVersion,+ setSelectedArchivedVersion,+ clearArchivedSelection,+ } = useArchivedFilesContext()+ const { can: canUpdateFiles } = useAsyncCheckPermissions(PermissionAction.STORAGE_WRITE, '*')++ const [isPurgeConfirmVisible, setIsPurgeConfirmVisible] = useState(false)+ const [versionToDelete, setVersionToDelete] = useState<ArchivedVersionRow>()++ // Unarchiving promotes whichever version was current when the file was archived, so restoring+ // an older one takes a second step.+ const { mutateAsync: restoreObject, isPending: isUnarchiving } =+ useArchivedObjectRestoreMutation()+ const { mutateAsync: restoreVersion, isPending: isPromotingVersion } =+ useObjectVersionRestoreMutation()+ const isRestoring = isUnarchiving || isPromotingVersion++ const { mutate: purgeObject, isPending: isPurging } = useArchivedObjectPurgeMutation({+ onSuccess: () => {+ toast.success('File permanently deleted')+ setIsPurgeConfirmVisible(false)+ clearArchivedSelection()+ },+ })++ const { mutate: deleteVersion, isPending: isDeletingVersion } =+ useArchivedObjectVersionDeleteMutation({+ onSuccess: () => {+ toast.success('Version permanently deleted')+ setVersionToDelete(undefined)+ },+ })++ if (object === undefined) return null++ const mergedVersions = getMergedArchivedVersions(object)+ const hasOlderVersions = object.noncurrentVersions.length > 0++ const handleRestore = async (version?: ArchivedVersionRow) => {+ if (!projectRef || !selectedBucket?.id) return+ const bucketId = selectedBucket.id+ const isOlderVersion = version !== undefined && !version.wasCurrentAtArchive++ try {+ await restoreObject({+ projectRef,+ bucketId,+ archivedObjectId: object.id,+ path: object.path,+ })+ if (isOlderVersion) {+ await restoreVersion({+ projectRef,+ bucketId,+ path: object.path,+ versionId: version.versionId,+ })+ }++ toast.success(+ isOlderVersion+ ? `File restored — version ${shortVersion(version.versionId)} is now current`+ : 'File restored'+ )+ clearArchivedSelection()+ // The file is live again, and the live listing is the explorer's own state.+ await refetchAllOpenedFolders()+ } catch {+ // Both mutations report their own failures.+ }+ }++ const handleDeleteVersion = () => {+ if (!projectRef || !selectedBucket?.id || versionToDelete === undefined) return+ deleteVersion({+ projectRef,+ bucketId: selectedBucket.id,+ archivedObjectId: object.id,+ path: object.path,+ versionId: versionToDelete.versionId,+ wasCurrentAtArchive: versionToDelete.wasCurrentAtArchive,+ })+ }++ // A plain restore already produces the version that was current at archive time.+ const handleSelectVersion = (version: ArchivedVersionRow) =>+ setSelectedArchivedVersion(version.wasCurrentAtArchive ? undefined : version)++ const getVersionDeleteCopy = () => {+ if (versionToDelete === undefined) return null+ if (!versionToDelete.wasCurrentAtArchive) {+ return (+ <>+ Version{' '}+ <span className="font-mono text-foreground">+ {shortVersion(versionToDelete.versionId)}+ </span>{' '}+ of {object.path} will be deleted permanently. This cannot be undone.+ </>+ )+ }+ return (+ <>+ The version of {object.path} that was current when it was archived will be deleted+ permanently+ {hasOlderVersions+ ? ' — its next most recent version becomes the one shown here'+ : ', leaving nothing left to restore'}+ . This cannot be undone.+ </>+ )+ }++ return (+ <>+ <div+ key={object.id}+ className="flex h-full flex-col border-l border-overlay bg-surface-100"+ style={{ width: PANEL_WIDTH }}+ >+ <div className="flex items-center gap-x-2 border-b border-overlay px-4 py-2.5">+ <p className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">+ Archived file+ </p>+ <Button+ variant="text"+ className="h-7 w-7 shrink-0 p-0"+ onClick={clearArchivedSelection}+ aria-label="Close preview"+ >+ <X size={14} />+ </Button>+ </div>++ <div className="min-h-0 flex-1 overflow-y-auto">+ {previewedVersion !== undefined ? (+ <ArchivedVersionRestoreWidget+ version={previewedVersion}+ path={object.path}+ canUpdateFiles={canUpdateFiles}+ isRestoring={isRestoring}+ onRestore={() => handleRestore(previewedVersion)}+ onDismiss={() => setSelectedArchivedVersion(undefined)}+ />+ ) : (+ <div className="border-b border-overlay p-3">+ <div+ className="flex items-center justify-center overflow-hidden rounded-md border border-overlay bg-surface-200"+ style={{ height: 'clamp(120px, calc((100vh - 144px) * 0.4), 180px)' }}+ >+ <FilePreview+ path={object.path}+ mimeType={object.currentVersion.mimeType}+ size={object.currentVersion.size}+ versionId={object.currentVersion.versionId}+ />+ </div>++ <div className="mt-2 flex flex-col">+ <p className="truncate text-sm font-medium text-foreground" title={object.path}>+ {object.path}+ </p>+ <div className="mt-0.5 flex flex-wrap items-center gap-x-1.5 truncate text-xs text-foreground-light">+ {formatBytes(object.currentVersion.size)}+ <Badge variant="warning" className="-my-1">+ Archived+ </Badge>+ </div>++ <div className="mt-3 flex shrink-0 items-center gap-x-1">+ <ButtonTooltip+ variant="outline"+ size="tiny"+ icon={<RotateCcw size={14} />}+ loading={isRestoring}+ disabled={!canUpdateFiles}+ onClick={() => handleRestore()}+ tooltip={{+ content: {+ side: 'top',+ text: canUpdateFiles+ ? undefined+ : 'You need additional permissions to restore files',+ },+ }}+ >+ Restore file+ </ButtonTooltip>+ <ButtonTooltip+ variant="outline"+ size="tiny"+ icon={<Trash2 size={14} />}+ disabled={!canUpdateFiles}+ onClick={() => setIsPurgeConfirmVisible(true)}+ tooltip={{+ content: {+ side: 'top',+ text: canUpdateFiles+ ? undefined+ : 'You need additional permissions to delete files',+ },+ }}+ >+ Delete permanently+ </ButtonTooltip>+ </div>+ </div>+ </div>+ )}++ <div className="space-y-3 px-4 pt-3">+ {previewedVersion === undefined && (+ <div className="space-y-2">+ <ArchivedFileDetail label="Original location" value={object.path} />+ <ArchivedFileDetail+ label="Archived"+ value={dayjs(object.archivedAt).format('MMM D, YYYY · HH:mm')}+ />+ </div>+ )}++ <PreviewSection title="Versions" count={mergedVersions.length} defaultOpen>+ <ol className="flex flex-col gap-y-0.5">+ {mergedVersions.map((version) => (+ <ArchivedVersionListRow+ key={version.versionId}+ version={version}+ path={object.path}+ isSelected={previewedVersion?.versionId === version.versionId}+ canUpdateFiles={canUpdateFiles}+ isRestoring={isRestoring}+ isDeleting={isDeletingVersion}+ onSelect={() => handleSelectVersion(version)}+ onRestore={() => handleRestore(version)}+ onDelete={() => setVersionToDelete(version)}+ />+ ))}+ </ol>+ </PreviewSection>+ </div>+ </div>+ </div>++ <ConfirmationModal+ variant="destructive"+ visible={isPurgeConfirmVisible}+ title={<span className="wrap-break-word">Permanently delete {object.path}?</span>}+ confirmLabel="Delete permanently"+ confirmLabelLoading="Deleting..."+ loading={isPurging}+ onCancel={() => setIsPurgeConfirmVisible(false)}+ onConfirm={() => {+ if (!projectRef || !selectedBucket?.id) return+ purgeObject({+ projectRef,+ bucketId: selectedBucket.id,+ archivedObjectId: object.id,+ path: object.path,+ })+ }}+ alert={{+ base: { variant: 'destructive' },+ title: 'This cannot be undone',+ description: `Deletes the file and all ${mergedVersions.length} retained version${+ mergedVersions.length === 1 ? '' : 's'+ }. None of them can be restored afterwards.`,+ }}+ />++ <ConfirmationModal+ variant="destructive"+ visible={versionToDelete !== undefined}+ title="Permanently delete this version?"+ confirmLabel="Delete version"+ confirmLabelLoading="Deleting..."+ loading={isDeletingVersion}+ onCancel={() => setVersionToDelete(undefined)}+ onConfirm={handleDeleteVersion}+ >+ <p className="text-sm text-foreground-light">{getVersionDeleteCopy()}</p>+ </ConfirmationModal>+ </>+ )+}diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/ArchivedFilesContext.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/ArchivedFilesContext.tsxnew file mode 100644index 00000000000..755c2143f75--- /dev/null+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/ArchivedFilesContext.tsx@@ -0,0 +1,120 @@+import { useQuery } from '@tanstack/react-query'+import {+ createContext,+ useCallback,+ useContext,+ useMemo,+ useState,+ type PropsWithChildren,+} from 'react'++import { getMergedArchivedVersions, type ArchivedVersionRow } from './archivedVersions.utils'+import { useStoragePreference } from './useStoragePreference'+import { useIsStorageVersioningEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'+import {+ archivedObjectsQueryOptions,+ type ArchivedObject,+} from '@/data/storage/versioning/archived-objects-query'+import { useStorageExplorerStateSnapshot } from '@/state/storage-explorer'++interface ArchivedFilesContextValue {+ isOverlayEnabled: boolean+ archivedObjects: ArchivedObject[]+ /** The bucket holds more rows than one listing run can carry, so `archivedObjects` is a subset. */+ isListingTruncated: boolean+ selectedArchivedObject: ArchivedObject | undefined+ selectedArchivedVersion: ArchivedVersionRow | undefined+ setSelectedArchivedVersion: (version?: ArchivedVersionRow) => void+ selectArchivedObject: (archivedObjectId: string) => void+ clearArchivedSelection: () => void+}++const ArchivedFilesContext = createContext<ArchivedFilesContextValue>({+ isOverlayEnabled: false,+ archivedObjects: [],+ isListingTruncated: false,+ selectedArchivedObject: undefined,+ selectedArchivedVersion: undefined,+ setSelectedArchivedVersion: () => {},+ selectArchivedObject: () => {},+ clearArchivedSelection: () => {},+})++export const useArchivedFilesContext = () => useContext(ArchivedFilesContext)++/** Stable identity so an unanswered query doesn't re-render every overlay consumer. */+const NO_ARCHIVED_OBJECTS: ArchivedObject[] = []++/** Not gated on the bucket's versioning state: a suspended bucket can still be retaining files. */+export const ArchivedFilesProvider = ({ children }: PropsWithChildren) => {+ const { projectRef, selectedBucket } = useStorageExplorerStateSnapshot()+ const { showArchivedInline } = useStoragePreference(projectRef)+ const isStorageVersioningEnabled = useIsStorageVersioningEnabled()++ const [selectedArchivedObjectId, setSelectedArchivedObjectId] = useState<string>()+ const [selectedVersionId, setSelectedVersionId] = useState<string>()++ const bucketId = selectedBucket?.id+ const isOverlayEnabled = isStorageVersioningEnabled && showArchivedInline++ const { data: listing } = useQuery({+ ...archivedObjectsQueryOptions({ projectRef, bucketId }),+ enabled: isOverlayEnabled && !!projectRef && !!bucketId,+ })++ const archivedObjects = listing?.objects ?? NO_ARCHIVED_OBJECTS+ const isListingTruncated = listing?.isTruncated ?? false++ // Held by id and resolved against the listing rather than snapshotted: a snapshot outlives+ // the listing it came from, so a purged version stays on show and a restored file — or one+ // belonging to the bucket the user just left — keeps its pane open over nothing.+ const selectedArchivedObject = archivedObjects.find(+ (object) => object.id === selectedArchivedObjectId+ )++ const selectedArchivedVersion = useMemo(() => {+ if (selectedArchivedObject === undefined || selectedVersionId === undefined) return undefined+ return getMergedArchivedVersions(selectedArchivedObject).find(+ (version) => version.versionId === selectedVersionId+ )+ }, [selectedArchivedObject, selectedVersionId])++ const selectArchivedObject = useCallback((archivedObjectId: string) => {+ setSelectedVersionId(undefined)+ setSelectedArchivedObjectId(archivedObjectId)+ }, [])++ const setSelectedArchivedVersion = useCallback((version?: ArchivedVersionRow) => {+ setSelectedVersionId(version?.versionId)+ }, [])++ const clearArchivedSelection = useCallback(() => {+ setSelectedArchivedObjectId(undefined)+ setSelectedVersionId(undefined)+ }, [])++ const value = useMemo(+ () => ({+ isOverlayEnabled,+ archivedObjects,+ isListingTruncated,+ selectedArchivedObject,+ selectedArchivedVersion,+ setSelectedArchivedVersion,+ selectArchivedObject,+ clearArchivedSelection,+ }),+ [+ isOverlayEnabled,+ archivedObjects,+ isListingTruncated,+ selectedArchivedObject,+ selectedArchivedVersion,+ setSelectedArchivedVersion,+ selectArchivedObject,+ clearArchivedSelection,+ ]+ )++ return <ArchivedFilesContext.Provider value={value}>{children}</ArchivedFilesContext.Provider>+}diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/ArchivedVersionRestoreWidget.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/ArchivedVersionRestoreWidget.tsxnew file mode 100644index 00000000000..eec85638e0f--- /dev/null+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/ArchivedVersionRestoreWidget.tsx@@ -0,0 +1,82 @@+import dayjs from 'dayjs'+import { RotateCcw, X } from 'lucide-react'++import type { ArchivedVersionRow } from './archivedVersions.utils'+import { FilePreview } from './FilePreview'+import { shortVersion } from './VersionHistory'+import { ButtonTooltip } from '@/components/ui/ButtonTooltip'+import { formatBytes } from '@/lib/helpers'++interface ArchivedVersionRestoreWidgetProps {+ version: ArchivedVersionRow+ /** Full path within the bucket, which is what the version endpoints address. */+ path: string+ canUpdateFiles: boolean+ isRestoring: boolean+ onRestore: () => void+ onDismiss: () => void+}++// No side-by-side comparison: the whole file is archived, so nothing is current.+export const ArchivedVersionRestoreWidget = ({+ version,+ path,+ canUpdateFiles,+ isRestoring,+ onRestore,+ onDismiss,+}: ArchivedVersionRestoreWidgetProps) => (+ <div className="space-y-3 border-b border-overlay bg-brand-200/30 p-3">+ <div className="flex items-center gap-x-1.5">+ <RotateCcw size={13} className="shrink-0 text-brand" />+ <p className="truncate text-sm font-medium text-foreground">+ Restore version {shortVersion(version.versionId)}?+ </p>+ <button+ type="button"+ tabIndex={0}+ className="ml-auto shrink-0 text-foreground-lighter transition-colors hover:text-foreground"+ onClick={onDismiss}+ aria-label="Cancel restore"+ >+ <X size={13} />+ </button>+ </div>++ <div className="space-y-1.5">+ <div className="flex h-24 items-center justify-center overflow-hidden rounded-md border border-brand-400 bg-surface-200">+ <FilePreview+ path={path}+ mimeType={version.mimeType}+ size={version.size}+ versionId={version.versionId}+ />+ </div>+ <p className="truncate text-center font-mono text-[11px] text-foreground-light">+ {dayjs(version.createdAt).format('MMM D, YYYY · HH:mm')} · {formatBytes(version.size)}+ </p>+ </div>++ <ButtonTooltip+ variant="primary"+ block+ icon={<RotateCcw size={14} />}+ loading={isRestoring}+ disabled={!canUpdateFiles}+ onClick={onRestore}+ tooltip={{+ content: {+ side: 'bottom',+ text: canUpdateFiles ? undefined : 'You need additional permissions to restore files',+ },+ }}+ >+ Restore as current version+ </ButtonTooltip>++ <p className="text-xs leading-relaxed text-foreground-lighter">+ The file leaves the archive and this becomes its current version. Every other retained version+ stays in its history.+ </p>+ </div>+)diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/ArchivedVersionRow.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/ArchivedVersionRow.tsxnew file mode 100644index 00000000000..aaebc460578--- /dev/null+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/ArchivedVersionRow.tsx@@ -0,0 +1,112 @@+import dayjs from 'dayjs'+import { MoreVertical, RotateCcw, Trash2 } from 'lucide-react'+import {+ Badge,+ Button,+ cn,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from 'ui'++import type { ArchivedVersionRow as ArchivedVersion } from './archivedVersions.utils'+import { shortVersion } from './VersionHistory'+import { VersionThumbnail } from './VersionThumbnail'+import { formatBytes } from '@/lib/helpers'++interface ArchivedVersionRowProps {+ version: ArchivedVersion+ /** Full path within the bucket, which is what the version endpoints address. */+ path: string+ isSelected: boolean+ canUpdateFiles: boolean+ isRestoring: boolean+ isDeleting: boolean+ onSelect: () => void+ onRestore: () => void+ onDelete: () => void+}++export const ArchivedVersionRow = ({+ version,+ path,+ isSelected,+ canUpdateFiles,+ isRestoring,+ isDeleting,+ onSelect,+ onRestore,+ onDelete,+}: ArchivedVersionRowProps) => (+ <li+ className={cn(+ 'group -mx-2 flex items-center gap-x-2.5 rounded-md border border-transparent px-2 py-1.5',+ isSelected ? 'border-brand-500 bg-brand-200' : 'hover:bg-surface-200'+ )}+ >+ {/* A real button, so the actions menu isn't nested inside another control. */}+ <button+ type="button"+ tabIndex={0}+ className="flex min-w-0 flex-1 items-center gap-x-2.5 text-left"+ onClick={onSelect}+ >+ <VersionThumbnail+ isCurrent={false}+ path={path}+ versionId={version.versionId}+ mimeType={version.mimeType}+ byteSize={version.size}+ />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm text-foreground group-hover:underline">+ {dayjs(version.createdAt).format('MMM D, HH:mm')}+ </span>+ <span className="block truncate font-mono text-xs text-foreground-lighter">+ {formatBytes(version.size)}+ </span>+ </span>+ </button>++ {version.wasCurrentAtArchive ? (+ <Badge variant="warning">Was current</Badge>+ ) : (+ <span className="shrink-0 font-mono text-xs text-foreground-lighter">+ {shortVersion(version.versionId)}+ </span>+ )}++ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="text"+ size="tiny"+ className="px-1.5"+ icon={<MoreVertical size={14} />}+ aria-label={`Actions for version ${shortVersion(version.versionId)}`}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ className="gap-x-2"+ disabled={!canUpdateFiles || isRestoring}+ onClick={onRestore}+ >+ <RotateCcw size={14} />+ Restore as current+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={onDelete}+ disabled={!canUpdateFiles || isDeleting}+ className="gap-x-2 text-destructive focus:text-destructive"+ >+ <Trash2 size={14} />+ Delete permanently+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </li>+)diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/ConfirmDeleteModal.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/ConfirmDeleteModal.tsxindex f5c6dd9ab05..ce68b112bce 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/ConfirmDeleteModal.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/ConfirmDeleteModal.tsx@@ -2,7 +2,7 @@ import { useEffect, useState } from 'react'import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'import { STORAGE_ROW_TYPES } from '../Storage.constants'-import { getBucketVersioningState } from '../StorageVersioning.constants'+import { getBucketVersioningState, isVersioningActive } from '../StorageVersioning.constants'import { useIsStorageVersioningEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'import { useStorageExplorerStateSnapshot } from '@/state/storage-explorer'@@ -17,8 +17,11 @@ export const ConfirmDeleteModal = () => {} = useStorageExplorerStateSnapshot()const isStorageVersioningEnabled = useIsStorageVersioningEnabled()- const isVersionedBucket =- isStorageVersioningEnabled && getBucketVersioningState(selectedBucket) !== 'disabled'+ // Only an enabled bucket soft-deletes. A suspended bucket still writes a delete marker,+ // but the content deleted, so it reads as a plain delete.+ const canArchive = isStorageVersioningEnabled && isVersioningActive(selectedBucket)+ const isSuspended =+ isStorageVersioningEnabled && getBucketVersioningState(selectedBucket) === 'suspended'const visible = selectedItemsToDelete.length > 0const multipleFiles = selectedItemsToDelete.length > 1@@ -26,11 +29,11 @@ export const ConfirmDeleteModal = () => {const getTitle = () => {if (multipleFiles) {- const verb = isVersionedBucket ? 'Archive' : 'Delete'+ const verb = canArchive ? 'Archive' : 'Delete'return `${verb} ${selectedItemsToDelete.length} items?`}if (firstItem === undefined) return ''- return isVersionedBucket ? `Archive ${firstItem.name}?` : `Delete ${firstItem.name}?`+ return canArchive ? `Archive ${firstItem.name}?` : `Delete ${firstItem.name}?`}const getSubject = () => {@@ -39,17 +42,29 @@ export const ConfirmDeleteModal = () => {return `the selected ${firstItem.type.toLowerCase()}`}- const alert = isVersionedBucket- ? {+ const getAlert = () => {+ if (canArchive) {+ return {base: { variant: 'warning' as const },title: 'Versions are retained',description: `Archiving ${getSubject()} hides it from the bucket. Its noncurrent versions stay retained until you delete them individually or a lifecycle policy expires them.`,}- : {+ }+ if (isSuspended) {+ return {base: { variant: 'destructive' as const },- title: 'This action cannot be undone',- description: `Are you sure you want to delete ${getSubject()}?`,+ title: 'Only retained versions survive',+ description: `Versioning is suspended, so deleting ${getSubject()} permanently removes its current content. Versions retained from before stay under Show archived until you delete them or a lifecycle policy expires them.`,}+ }+ return {+ base: { variant: 'destructive' as const },+ title: 'This action cannot be undone',+ description: `Are you sure you want to delete ${getSubject()}?`,+ }+ }++ const alert = getAlert()const onDeleteSelectedFiles = async () => {try {@@ -58,9 +73,9 @@ export const ConfirmDeleteModal = () => {selectedItemsToDelete.length === 1 &&selectedItemsToDelete[0].type === STORAGE_ROW_TYPES.FOLDER) {- await deleteFolder(selectedItemsToDelete[0])+ await deleteFolder(selectedItemsToDelete[0], { isArchive: canArchive })} else {- await deleteFiles({ files: selectedItemsToDelete })+ await deleteFiles({ files: selectedItemsToDelete, isArchive: canArchive })}} catch (err) {} finally {@@ -77,11 +92,11 @@ export const ConfirmDeleteModal = () => {size="medium"visible={visible}title={<span className="wrap-break-word">{getTitle()}</span>}- confirmLabel={isVersionedBucket ? 'Archive' : 'Delete'}+ confirmLabel={canArchive ? 'Archive' : 'Delete'}loading={deleting}onCancel={() => setSelectedItemsToDelete([])}onConfirm={onDeleteSelectedFiles}- variant={isVersionedBucket ? 'warning' : 'destructive'}+ variant={canArchive ? 'warning' : 'destructive'}alert={alert}/>)diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/ConfirmPurgeModal.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/ConfirmPurgeModal.tsxindex 047b0d2055f..e90005247f8 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/ConfirmPurgeModal.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/ConfirmPurgeModal.tsx@@ -1,11 +1,20 @@+import { useQueryClient } from '@tanstack/react-query'+import { useState } from 'react'import { toast } from 'sonner'import { ConfirmationModal } from 'ui-patterns/Dialogs/ConfirmationModal'+import { STORAGE_ROW_TYPES } from '../Storage.constants'+import { getArchivedObjectsUnderFolder } from './archivedOverlay.utils'import { getStorageItemPath } from './StorageExplorer.utils'import { useStorageExplorerNavigation } from './StorageExplorerNavigation'+import { useArchivedObjectPurgeMutation } from '@/data/storage/versioning/archived-object-purge-mutation'+import { archivedObjectsQueryOptions } from '@/data/storage/versioning/archived-objects-query'import { useObjectPurgeMutation } from '@/data/storage/versioning/object-purge-mutation'import { useStorageExplorerStateSnapshot } from '@/state/storage-explorer'+/** Thrown once the user has already been told, so the catch below stays quiet for it. */+const TRUNCATED_LISTING = new Error('Archived listing truncated')+/** Mounted once by the explorer. Confirmed separately from `ConfirmDeleteModal`, which archives. */export const ConfirmPurgeModal = () => {const {@@ -16,28 +25,96 @@ export const ConfirmPurgeModal = () => {setItemToPurge,selectedFilePreview,refetchAllOpenedFolders,+ getAllItemsAlongFolder,} = useStorageExplorerStateSnapshot()const { clearPreviewedFile } = useStorageExplorerNavigation()+ const queryClient = useQueryClient()- const { mutate: purgeObject, isPending: isPurging } = useObjectPurgeMutation({- onSuccess: async () => {- 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)- await refetchAllOpenedFolders()- },- })+ const [isPurging, setIsPurging] = useState(false)++ const { mutateAsync: purgeObject } = useObjectPurgeMutation()+ const { mutateAsync: purgeArchivedObject } = useArchivedObjectPurgeMutation()++ const isFolder = itemToPurge?.type === STORAGE_ROW_TYPES.FOLDER+ const isArchivedFolder = isFolder && itemToPurge.archived !== undefined++ /** 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>,+ path: string+ ) => {+ const liveItems = isArchivedFolder ? [] : await getAllItemsAlongFolder(folder)++ // Not the overlay's copy: it is empty whenever "Show archived" is off, which would leave+ // every archived descendant behind while the purge reported success.+ const listing = await queryClient.fetchQuery({+ ...archivedObjectsQueryOptions({ projectRef, bucketId }),+ staleTime: 0,+ })+ if (listing.isTruncated) {+ toast.error(+ 'This bucket holds more archived files than can be listed at once. Delete them one by one instead.'+ )+ throw TRUNCATED_LISTING+ }- const onConfirm = () => {+ const archivedUnder = getArchivedObjectsUnderFolder({+ folderSegments: path.split('/'),+ archivedObjects: listing.objects,+ })++ const results = await Promise.allSettled([+ ...liveItems.map((item) =>+ purgeObject({ projectRef, bucketId, path: `${item.prefix}/${item.name}` })+ ),+ ...archivedUnder.map((object) =>+ purgeArchivedObject({+ projectRef,+ bucketId,+ archivedObjectId: object.id,+ path: object.path,+ })+ ),+ ])++ return results.filter((result) => result.status === 'rejected').length+ }++ const onConfirm = async () => {if (!projectRef || !selectedBucket?.id || itemToPurge === undefined) return- // The endpoint addresses an object by full path; a row only knows its leaf name.+ // 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; rows synthesized without one still need the rebuild.+ // that may have moved on; synthesized archived folders carry none, so they fall back.const path = itemToPurge.path ?? getStorageItemPath({ openedFolders }, itemToPurge)+ setIsPurging(true)+ try {+ const failureCount = isFolder+ ? await purgeFolder(projectRef, selectedBucket.id, itemToPurge, path)+ : await purgeObject({ projectRef, bucketId: selectedBucket.id, path }).then(() => 0)- purgeObject({ projectRef, bucketId: selectedBucket.id, path })+ 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}`)+ }+ } finally {+ // Whatever did go through has already changed the listing.+ await refetchAllOpenedFolders()+ setIsPurging(false)+ }}return (@@ -54,8 +131,9 @@ export const ConfirmPurgeModal = () => {alert={{base: { variant: 'destructive' },title: 'This cannot be undone',- description:- 'Deletes the file and every version of it, bypassing versioning. Nothing is left to restore.',+ 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.',}}/>)diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorer.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorer.tsxindex 247ebf6c923..94ffcc58833 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorer.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorer.tsx@@ -1,13 +1,47 @@import { noop } from 'lodash'-import { useEffect, useRef } from 'react'+import { useEffect, useMemo, useRef } from 'react'import { cn } from 'ui'-import { STORAGE_ROW_STATUS, STORAGE_VIEWS } from '../Storage.constants'-import type { StorageColumn, StorageItemWithColumn } from '../Storage.types'+import {+ STORAGE_ROW_STATUS,+ STORAGE_SORT_BY,+ STORAGE_SORT_BY_ORDER,+ STORAGE_VIEWS,+} from '../Storage.constants'+import type { StorageColumn, StorageItem, StorageItemWithColumn } from '../Storage.types'+import { useArchivedFilesContext } from './ArchivedFilesContext'+import { getArchivedOverlayItems } from './archivedOverlay.utils'import { FileExplorerColumn } from './FileExplorerColumn'import { useStoragePreference } from './useStoragePreference'import { useStorageExplorerStateSnapshot } from '@/state/storage-explorer'+/** Archived rows fall back to the archive timestamp so they don't all sink. */+const getSortValue = (item: StorageItem, sortBy: STORAGE_SORT_BY): string | number | null => {+ switch (sortBy) {+ case STORAGE_SORT_BY.NAME:+ return item.name.toLowerCase()+ case STORAGE_SORT_BY.CREATED_AT:+ return item.created_at ?? (item.archived ? item.updated_at : null)+ case STORAGE_SORT_BY.UPDATED_AT:+ return item.updated_at+ case STORAGE_SORT_BY.LAST_ACCESSED_AT:+ return item.last_accessed_at ?? (item.archived ? item.updated_at : null)+ }+}++const compareItems =+ (sortBy: STORAGE_SORT_BY, order: STORAGE_SORT_BY_ORDER) => (a: StorageItem, b: StorageItem) => {+ const aValue = getSortValue(a, sortBy)+ const bValue = getSortValue(b, sortBy)+ // Nulls last either way, matching the server-side sort on the live items.+ if (aValue === null && bValue === null) return 0+ if (aValue === null) return 1+ if (bValue === null) return -1+ if (aValue < bValue) return order === STORAGE_SORT_BY_ORDER.ASC ? -1 : 1+ if (aValue > bValue) return order === STORAGE_SORT_BY_ORDER.ASC ? 1 : -1+ return 0+ }+export interface FileExplorerProps {columns: StorageColumn[]selectedItems: StorageItemWithColumn[]@@ -31,8 +65,27 @@ export const FileExplorer = ({}: FileExplorerProps) => {const fileExplorerRef = useRef<HTMLDivElement>(null)const snap = useStorageExplorerStateSnapshot()- const { view } = useStoragePreference(snap.projectRef)+ const { view, sortBy, sortByOrder } = useStoragePreference(snap.projectRef)const isPreviewOpen = !!snap.selectedFilePreview+ const { isOverlayEnabled, archivedObjects } = useArchivedFilesContext()++ const overlaidColumns = useMemo(() => {+ if (!isOverlayEnabled || archivedObjects.length === 0) return columns+ const compare = compareItems(sortBy, sortByOrder)++ return columns.map((column) => {+ const folderSegments = column.path.split('/').filter((segment) => segment !== '')+ const archivedItems = getArchivedOverlayItems({+ folderSegments,+ archivedObjects,+ existingItemNames: new Set(column.items.map((item) => item.name)),+ })+ if (archivedItems.length === 0) return column++ // The server-side sort never saw the archived rows.+ return { ...column, items: [...column.items, ...archivedItems].sort(compare) }+ })+ }, [columns, archivedObjects, isOverlayEnabled, sortBy, sortByOrder])// Keep the deepest column in view. Also re-runs when the preview pane opens, since it// takes 450px off the container and would otherwise hide the column it belongs to.@@ -40,7 +93,7 @@ export const FileExplorer = ({const container = fileExplorerRef.currentif (!container || view !== STORAGE_VIEWS.COLUMNS) returncontainer.scrollLeft = container.scrollWidth - container.clientWidth- }, [columns.length, view, isPreviewOpen])+ }, [overlaidColumns.length, view, isPreviewOpen])return (<div@@ -56,7 +109,7 @@ export const FileExplorer = ({/>) : view === STORAGE_VIEWS.COLUMNS ? (<div className="flex">- {columns.map((column, index) => (+ {overlaidColumns.map((column, index) => (<FileExplorerColumnkey={`column-${index}`}index={index}@@ -72,11 +125,11 @@ export const FileExplorer = ({</div>) : view === STORAGE_VIEWS.LIST ? (<>- {columns.length > 0 && (+ {overlaidColumns.length > 0 && (<FileExplorerColumnfullWidth- index={columns.length - 1}- column={columns[columns.length - 1]}+ index={overlaidColumns.length - 1}+ column={overlaidColumns[overlaidColumns.length - 1]}selectedItems={selectedItems}itemSearchString={itemSearchString}onFilesUpload={onFilesUpload}diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeader.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeader.tsxindex de95158b572..d51b9a15d6c 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeader.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeader.tsx@@ -43,10 +43,12 @@ import {import { Input } from 'ui-patterns/DataInputs/Input'import { STORAGE_SORT_BY, STORAGE_SORT_BY_ORDER, STORAGE_VIEWS } from '../Storage.constants'+import { hasVersioningHistory } from '../StorageVersioning.constants'import { pageChromeRowClassName } from './storageExplorerChrome'import { useStorageExplorerNavigation } from './StorageExplorerNavigation'import { useFileExplorerHeaderShortcuts } from './useFileExplorerHeaderShortcuts'import { useStoragePreference } from './useStoragePreference'+import { useIsStorageVersioningEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'import { ButtonTooltip } from '@/components/ui/ButtonTooltip'import { ShortcutTooltip } from '@/components/ui/ShortcutTooltip'import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'@@ -153,6 +155,7 @@ export const FileExplorerHeader = ({const {projectRef,+ selectedBucket,columns,refetchAllOpenedFolders,refreshAll,@@ -168,7 +171,11 @@ export const FileExplorerHeader = ({setSortBy: setPreferenceSortBy,sortByOrder,setSortByOrder: setPreferenceSortByOrder,+ showArchivedInline,+ setShowArchivedInline,} = useStoragePreference(projectRef)+ const isStorageVersioningEnabled = useIsStorageVersioningEnabled()+ const canShowArchivedToggle = isStorageVersioningEnabled && hasVersioningHistory(selectedBucket)const breadcrumbs = columns.map((column) => column.name)const isListView = view === STORAGE_VIEWS.LIST@@ -396,6 +403,17 @@ export const FileExplorerHeader = ({))}</DropdownMenuSubContent></DropdownMenuSub>+ {canShowArchivedToggle && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={() => setShowArchivedInline(!showArchivedInline)}>+ <div className="flex items-center justify-between w-full">+ <p>Show archived</p>+ {showArchivedInline && <Check size={16} className="text-brand" />}+ </div>+ </DropdownMenuItem>+ </>+ )}</DropdownMenuContent></DropdownMenu></div>diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.tsxindex 6f985065298..a331aa614f1 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerHeaderSelection.tsx@@ -1,8 +1,10 @@import { PermissionAction } from '@supabase/shared-types/out/constants'-import { Download, Move, Trash2, X } from 'lucide-react'+import { Archive, Download, Move, Trash2, X } from 'lucide-react'import { Button } from 'ui'+import { isVersioningActive } from '../StorageVersioning.constants'import { bulkActionBarClassName } from './storageExplorerChrome'+import { useIsStorageVersioningEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'import { ButtonTooltip } from '@/components/ui/ButtonTooltip'import { ShortcutTooltip } from '@/components/ui/ShortcutTooltip'import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'@@ -13,6 +15,7 @@ export const FileExplorerHeaderSelection = () => {const { can: canUpdateFiles } = useAsyncCheckPermissions(PermissionAction.STORAGE_WRITE, '*')const {+ selectedBucket,selectedItems,downloadFile,downloadSelectedFiles,@@ -21,6 +24,9 @@ export const FileExplorerHeaderSelection = () => {setSelectedItemsToMove,} = useStorageExplorerStateSnapshot()+ const isStorageVersioningEnabled = useIsStorageVersioningEnabled()+ const canArchive = isStorageVersioningEnabled && isVersioningActive(selectedBucket)+const count = selectedItems.lengthreturn (@@ -53,7 +59,7 @@ export const FileExplorerHeaderSelection = () => {><ButtonTooltipsize="tiny"- icon={<Trash2 size={12} />}+ icon={canArchive ? <Archive size={12} /> : <Trash2 size={12} />}disabled={!canUpdateFiles}onClick={() => setSelectedItemsToDelete(selectedItems)}tooltip={{@@ -65,7 +71,7 @@ export const FileExplorerHeaderSelection = () => {},}}>- Delete+ {canArchive ? 'Archive' : 'Delete'}</ButtonTooltip></ShortcutTooltip>diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.test.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.test.tsxindex 891821c075d..11e5e247c24 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.test.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.test.tsx@@ -1,19 +1,38 @@import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { describe, expect, it, vi } from 'vitest'+import { beforeEach, describe, expect, it, vi } from 'vitest'import {STORAGE_ROW_STATUS,STORAGE_ROW_TYPES,STORAGE_VIEWS,} from '@/components/interfaces/Storage/Storage.constants'+import type {+ StorageItem,+ StorageItemMetadata,+} from '@/components/interfaces/Storage/Storage.types'import { FileExplorerRow } from '@/components/interfaces/Storage/StorageExplorer/FileExplorerRow'import { customRender as render } from '@/tests/lib/custom-render'+const { versioningEnabled, selectedBucket } = vi.hoisted(() => ({+ versioningEnabled: { current: false },+ selectedBucket: {+ current: { id: 'my-bucket', name: 'my-bucket', public: false } as Record<string, unknown>,+ },+}))++vi.mock(+ '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext',+ async (importOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>()+ return { ...actual, useIsStorageVersioningEnabled: () => versioningEnabled.current }+ }+)+vi.mock('@/state/storage-explorer', () => ({useStorageExplorerStateSnapshot: () => ({projectRef: 'abcdef',- selectedBucket: { id: 'my-bucket', name: 'my-bucket', public: false },+ selectedBucket: selectedBucket.current,selectedFilePreview: undefined,openedFolders: [],setSelectedFileCustomExpiry: vi.fn(),@@ -24,6 +43,7 @@ vi.mock('@/state/storage-explorer', () => ({setSelectedItemsToMove: vi.fn(),downloadFolder: vi.fn(),selectRangeItems: vi.fn(),+ setItemToPurge: vi.fn(),}),}))vi.mock('@/components/interfaces/Storage/StorageExplorer/StorageExplorerNavigation', () => ({@@ -41,21 +61,40 @@ vi.mock('@/components/interfaces/Storage/StorageExplorer/useCopyUrl', () => ({useCopyUrl: () => ({ onCopyUrl: vi.fn() }),}))-const base = {+const METADATA: StorageItemMetadata = {+ cacheControl: 'max-age=3600',+ contentLength: 10,+ size: 10,+ httpStatusCode: 200,+ eTag: 'etag',+ lastModified: '2024-01-01T00:00:00Z',+ mimetype: 'image/png',+}++const item = (overrides: Partial<StorageItem>): StorageItem => ({+ id: null,+ name: 'photo.png',+ type: STORAGE_ROW_TYPES.FILE,status: STORAGE_ROW_STATUS.READY,- metadata: { size: 10, mimetype: 'image/png' },+ metadata: METADATA,isCorrupted: false,created_at: null,updated_at: null,last_accessed_at: null,path: 'photo.png',-}+ ...overrides,+})++beforeEach(() => {+ versioningEnabled.current = false+ selectedBucket.current = { id: 'my-bucket', name: 'my-bucket', public: false }+})describe('FileExplorerRow', () => {it('offers both the relative path and the dashboard URL for a file', async () => {render(<FileExplorerRow- item={{ ...base, id: 'f1', name: 'photo.png', type: STORAGE_ROW_TYPES.FILE } as any}+ item={item({ id: 'f1' })}index={0}view={STORAGE_VIEWS.COLUMNS}columnIndex={0}@@ -70,15 +109,7 @@ describe('FileExplorerRow', () => {it('offers both the relative path and the dashboard URL for a folder', async () => {render(<FileExplorerRow- item={- {- ...base,- id: null,- name: 'avatars',- type: STORAGE_ROW_TYPES.FOLDER,- metadata: null,- } as any- }+ item={item({ name: 'avatars', type: STORAGE_ROW_TYPES.FOLDER, metadata: null })}index={0}view={STORAGE_VIEWS.COLUMNS}columnIndex={0}@@ -90,4 +121,178 @@ describe('FileExplorerRow', () => {expect(screen.getByText('Copy link')).toBeInTheDocument()expect(screen.queryByText('Copy path to folder')).not.toBeInTheDocument()})++ it('marks an archived file with an icon in the leading slot rather than a text badge', async () => {+ const { container } = render(+ <FileExplorerRow+ item={item({ id: 'f2', name: 'gone.png', archived: { archivedObjectId: 'a1' } })}+ index={0}+ view={STORAGE_VIEWS.COLUMNS}+ columnIndex={0}+ selectedItems={[]}+ />+ )++ // The icon reads as a button, not the word "Archived", and sits where the file icon would.+ const archivedIcon = screen.getByRole('button', { name: 'View archived file gone.png' })+ expect(screen.queryByText('Archived')).not.toBeInTheDocument()+ expect(container.querySelector('.w-\\[30px\\]')).toContainElement(archivedIcon)++ // Only the actions an archived file can actually take.+ await userEvent.click(screen.getByRole('button', { name: 'gone.png actions' }))+ expect(await screen.findByText('Restore')).toBeInTheDocument()+ expect(screen.getByText('Delete permanently')).toBeInTheDocument()+ expect(screen.queryByText('Download')).not.toBeInTheDocument()+ expect(screen.queryByText('Rename')).not.toBeInTheDocument()+ expect(screen.queryByText('Move')).not.toBeInTheDocument()+ await userEvent.keyboard('{Escape}')++ // The archive icon replaces the file icon outright, so there is nothing left to+ // hide on hover and no checkbox to swap in.+ expect(screen.queryByRole('checkbox')).not.toBeInTheDocument()+ expect(container.querySelector('.absolute')).toBeNull()+ })++ it('gives an archived folder the same actions, since its contents are what they act on', async () => {+ render(+ <FileExplorerRow+ item={item({+ name: 'matches',+ type: STORAGE_ROW_TYPES.FOLDER,+ metadata: null,+ archived: {},+ })}+ index={0}+ view={STORAGE_VIEWS.COLUMNS}+ columnIndex={0}+ selectedItems={[]}+ />+ )++ await userEvent.click(screen.getByRole('button', { name: 'matches actions' }))+ expect(await screen.findByText('Restore')).toBeInTheDocument()+ expect(screen.getByText('Delete permanently')).toBeInTheDocument()+ // The live folder actions have no archived equivalent.+ expect(screen.queryByText('Download')).not.toBeInTheDocument()+ expect(screen.queryByText('Rename')).not.toBeInTheDocument()+ })++ describe('versioning state', () => {+ const openFileMenu = async (fileItem: Partial<StorageItem> = {}) => {+ render(+ <FileExplorerRow+ item={item({ id: 'f4', ...fileItem })}+ index={0}+ view={STORAGE_VIEWS.COLUMNS}+ columnIndex={0}+ selectedItems={[]}+ />+ )+ await userEvent.click(screen.getByRole('button', { name: 'photo.png actions' }))+ // Waiting on one entry keeps the rest of the assertions off a racing menu.+ await screen.findByText('Download')+ }++ it('archives and offers a purge on an enabled bucket', async () => {+ versioningEnabled.current = true+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'ENABLED' }++ await openFileMenu()++ expect(screen.getByText('Upload new version')).toBeInTheDocument()+ expect(screen.getByText('Archive')).toBeInTheDocument()+ expect(screen.getByText('Delete permanently')).toBeInTheDocument()+ })++ it('deletes rather than archives on a suspended bucket', async () => {+ versioningEnabled.current = true+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }++ await openFileMenu({ is_versioned: false })++ // Suspended can't archive, so there is no soft delete and nothing to purge from here.+ expect(screen.getByText('Delete')).toBeInTheDocument()+ expect(screen.queryByText('Archive')).not.toBeInTheDocument()+ expect(screen.queryByText('Delete permanently')).not.toBeInTheDocument()+ // The write overwrites in place, so it is not a new version.+ expect(screen.getByText('Replace file')).toBeInTheDocument()+ expect(screen.queryByText('Upload new version')).not.toBeInTheDocument()+ })++ it('still reads "Replace file" for a file that predates the suspension', async () => {+ versioningEnabled.current = true+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }++ await openFileMenu({ is_versioned: true })++ // This write does retain one last version, but the label names the action taken,+ // not the retention behind it. The version history is where that gets explained.+ expect(screen.getByText('Replace file')).toBeInTheDocument()+ expect(screen.queryByText('Upload new version')).not.toBeInTheDocument()+ expect(screen.getByText('Delete')).toBeInTheDocument()+ expect(screen.queryByText('Archive')).not.toBeInTheDocument()+ })++ it('ignores is_versioned on a disabled bucket', async () => {+ versioningEnabled.current = true+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'DISABLED' }++ await openFileMenu({ is_versioned: true })++ expect(screen.getByText('Replace file')).toBeInTheDocument()+ expect(screen.getByText('Delete')).toBeInTheDocument()+ expect(screen.queryByText('Delete permanently')).not.toBeInTheDocument()+ })++ it('archives a folder on an enabled bucket, and plainly deletes it on a suspended one', async () => {+ versioningEnabled.current = true+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'ENABLED' }++ const folder = item({ name: 'avatars', type: STORAGE_ROW_TYPES.FOLDER, metadata: null })+ const { unmount } = render(+ <FileExplorerRow+ item={folder}+ index={0}+ view={STORAGE_VIEWS.COLUMNS}+ columnIndex={0}+ selectedItems={[]}+ />+ )+ await userEvent.click(screen.getByRole('button', { name: 'avatars actions' }))+ expect(await screen.findByText('Archive')).toBeInTheDocument()+ expect(screen.getByText('Delete permanently')).toBeInTheDocument()+ await userEvent.keyboard('{Escape}')+ unmount()++ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }+ render(+ <FileExplorerRow+ item={folder}+ index={0}+ view={STORAGE_VIEWS.COLUMNS}+ columnIndex={0}+ selectedItems={[]}+ />+ )+ await userEvent.click(screen.getByRole('button', { name: 'avatars actions' }))+ expect(await screen.findByText('Delete')).toBeInTheDocument()+ expect(screen.queryByText('Archive')).not.toBeInTheDocument()+ expect(screen.queryByText('Delete permanently')).not.toBeInTheDocument()+ })+ })++ it('keeps hiding the icon on hover for a live file, which does swap in a checkbox', () => {+ const { container } = render(+ <FileExplorerRow+ item={item({ id: 'f3', name: 'live.png' })}+ index={0}+ view={STORAGE_VIEWS.COLUMNS}+ columnIndex={0}+ selectedItems={[]}+ />+ )++ expect(screen.getByRole('checkbox')).toBeInTheDocument()+ expect(container.querySelector('.absolute')?.className).toContain('group-hover:hidden')+ })})diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.tsxindex 56b71d7690d..3f5c36548cd 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/FileExplorerRow.tsx@@ -10,9 +10,12 @@ import {LoaderCircle,MoreVertical,Move,+ RotateCcw,Trash2,+ Upload,} from 'lucide-react'import type { CSSProperties, ReactNode } from 'react'+import { toast } from 'sonner'import {Checkbox,cn,@@ -37,19 +40,105 @@ import {URL_EXPIRY_DURATION,} from '../Storage.constants'import { StorageItemWithColumn, type StorageItem } from '../Storage.types'-import { StorageRowIcon } from '../StorageRowIcon'-import { getBucketVersioningState } from '../StorageVersioning.constants'+import { ICON_STROKE_WIDTH, StorageRowIcon } from '../StorageRowIcon'+import { isVersioningActive } from '../StorageVersioning.constants'+import { useArchivedFilesContext } from './ArchivedFilesContext'+import { getArchivedObjectsUnderFolder } from './archivedOverlay.utils'import { useFileExplorerContextMenu } from './FileExplorerRowContextMenu'import { FileExplorerRowEditing } from './FileExplorerRowEditing'-import { copyStorageExplorerUrl, copyStoragePath } from './StorageExplorer.utils'+import { pickFile } from './pickFile'+import {+ copyStorageExplorerUrl,+ copyStoragePath,+ getStoragePathForItem,+} from './StorageExplorer.utils'import { useStorageExplorerNavigation } from './StorageExplorerNavigation'import { useCopyUrl } from './useCopyUrl'import { useIsStorageVersioningEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'+import { useArchivedObjectRestoreMutation } from '@/data/storage/versioning/archived-object-restore-mutation'import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'import { formatBytes } from '@/lib/helpers'import { useStorageExplorerStateSnapshot } from '@/state/storage-explorer'+/** Built from `currentColor` so the stripes track the row's text color. */+const ARCHIVED_STRIPES_STYLE: CSSProperties = {+ backgroundImage:+ 'repeating-linear-gradient(-45deg, color-mix(in srgb, currentColor 8%, transparent) 0 1px, transparent 1px 7px)',+}++const ARCHIVED_ICON_CLASS = 'flex h-4 w-4 items-center justify-center text-foreground-lighter'++/** Takes the file icon's slot, and is an archived row's only keyboard focus target. */+const ArchivedRowIcon = ({ name, onOpen }: { name: string; onOpen?: () => void }) => (+ <Tooltip>+ <TooltipTrigger asChild>+ {onOpen ? (+ <button+ type="button"+ tabIndex={0}+ aria-label={`View archived file ${name}`}+ onClick={(event) => {+ event.stopPropagation()+ onOpen()+ }}+ className={cn(ARCHIVED_ICON_CLASS, 'focus-ring rounded-sm')}+ >+ <Archive size={16} strokeWidth={ICON_STROKE_WIDTH} aria-hidden />+ </button>+ ) : (+ <span className={ARCHIVED_ICON_CLASS}>+ <Archive size={16} strokeWidth={ICON_STROKE_WIDTH} aria-hidden />+ <span className="sr-only">Archived</span>+ </span>+ )}+ </TooltipTrigger>+ <TooltipContent side="bottom">Archived</TooltipContent>+ </Tooltip>+)++const RowActionsMenu = ({ name, options }: { name: string; options: RowOption[] }) => (+ <DropdownMenu>+ <DropdownMenuTrigger className="focus-ring rounded-sm">+ <div className="storage-row-menu opacity-0">+ <MoreVertical size={16} />+ <span className="sr-only">{name} actions</span>+ </div>+ </DropdownMenuTrigger>+ <DropdownMenuContent side="bottom" align="end">+ {options.map((option) => {+ if ((option?.children ?? []).length > 0) {+ return (+ <DropdownMenuSub key={option.name}>+ <DropdownMenuSubTrigger className="space-x-2">+ {option.icon || <></>}+ <p>{option.name}</p>+ </DropdownMenuSubTrigger>+ <DropdownMenuPortal>+ <DropdownMenuSubContent>+ {(option?.children ?? [])?.map((child) => (+ <DropdownMenuItem key={child.name} onClick={child.onClick}>+ <p>{child.name}</p>+ </DropdownMenuItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuPortal>+ </DropdownMenuSub>+ )+ }+ if (option.name === 'Separator') return <DropdownMenuSeparator key={option.name} />+ return (+ <DropdownMenuItem className="space-x-2" key={option.name} onClick={option.onClick}>+ {option.icon || <></>}+ <p>{option.name}</p>+ </DropdownMenuItem>+ )+ })}+ </DropdownMenuContent>+ </DropdownMenu>+)+interface FileExplorerRowProps {+ /** Part of the virtual list's row contract; the row addresses itself by `item.id`. */index: numberitem: StorageItemview: STORAGE_VIEWS@@ -66,7 +155,6 @@ type RowOption = {}export const FileExplorerRow = ({- index: itemIndex,item,view = STORAGE_VIEWS.COLUMNS,columnIndex = 0,@@ -82,31 +170,60 @@ export const FileExplorerRow = ({setSelectedItems,setSelectedItemsToDelete,setItemToPurge,+ refetchAllOpenedFolders,+ replaceFile,downloadFile,setSelectedItemToRename,setSelectedItemsToMove,downloadFolder,selectRangeItems,} = useStorageExplorerStateSnapshot()- const { openFolderAtIndex, setPreviewedFile, clearPreviewedFile } = useStorageExplorerNavigation()+ const { openFolderAtIndex, setPreviewedFile, clearPreviewedFile, truncateToColumn } =+ useStorageExplorerNavigation()const { onCopyUrl } = useCopyUrl()const ctx = useFileExplorerContextMenu()+ const { archivedObjects, selectedArchivedObject, selectArchivedObject, clearArchivedSelection } =+ useArchivedFilesContext()+ const isArchived = item.archived !== undefined+ const archivedObjectId = item.archived?.archivedObjectId+ const isArchivedFile = archivedObjectId !== undefined && item.type === STORAGE_ROW_TYPES.FILE+ const isArchivedFolder = isArchived && item.type === STORAGE_ROW_TYPES.FOLDER+const isPublic = selectedBucket.publicconst itemWithColumnIndex = { ...item, columnIndex }const isSelected = !!selectedItems.find((i) => i.id === item.id)const isOpened =openedFolders.length > columnIndex ? openedFolders[columnIndex].name === item.name : false- const isPreviewed = !isEmpty(selectedFilePreview) && isEqual(selectedFilePreview?.id, item.id)+ const isPreviewed =+ (!isEmpty(selectedFilePreview) && isEqual(selectedFilePreview?.id, item.id)) ||+ (isArchivedFile && selectedArchivedObject?.id === archivedObjectId)const { can: canUpdateFiles } = useAsyncCheckPermissions(PermissionAction.STORAGE_WRITE, '*')const isStorageVersioningEnabled = useIsStorageVersioningEnabled()- const isVersionedBucket =- isStorageVersioningEnabled && getBucketVersioningState(selectedBucket) !== 'disabled'+ // Names the action being taken, not the retention behind it: a suspended bucket reads+ // "Replace file" and "Delete" even for a file that still has one retained version coming.+ const isActivelyVersioning = isStorageVersioningEnabled && isVersioningActive(selectedBucket)++ const onSelectFile = (columnIndex: number) => {+ if (isArchivedFile) {+ // No live object to preview, so let the archived pane take over.+ truncateToColumn(columnIndex)+ selectArchivedObject(archivedObjectId)+ return+ }+ clearArchivedSelection()+ setPreviewedFile(itemWithColumnIndex)+ }++ const onReplaceFile = async () => {+ const file = await pickFile()+ if (file !== undefined) await replaceFile({ file, item: itemWithColumnIndex })+ }const onCheckItem = (isShiftKeyHeld: boolean) => {// Select a range if shift is held downif (isShiftKeyHeld && selectedItems.length !== 0) {- selectRangeItems(columnIndex, itemIndex)+ selectRangeItems(columnIndex, item.id)return}if (find(selectedItems, (item) => itemWithColumnIndex.id === item.id) !== undefined) {@@ -160,10 +277,25 @@ export const FileExplorerRow = ({? [{ name: 'Separator', icon: undefined, onClick: undefined },{- name: 'Delete',- icon: <Trash2 size={12} className="text-foreground-light" />,+ // Deleting a folder deletes everything under it, so on a versioned+ // bucket the whole prefix is archived rather than removed.+ name: isActivelyVersioning ? 'Archive' : 'Delete',+ icon: isActivelyVersioning ? (+ <Archive size={12} className="text-foreground-light" />+ ) : (+ <Trash2 size={12} className="text-foreground-light" />+ ),onClick: () => setSelectedItemsToDelete([itemWithColumnIndex]),},+ ...(isActivelyVersioning+ ? [+ {+ name: 'Delete permanently',+ icon: <Trash2 size={12} className="text-destructive" />,+ onClick: () => setItemToPurge(itemWithColumnIndex),+ },+ ]+ : []),]: []),]@@ -225,6 +357,11 @@ export const FileExplorerRow = ({icon: <Move size={12} className="text-foreground-light" />,onClick: () => setSelectedItemsToMove([itemWithColumnIndex]),},+ {+ name: isActivelyVersioning ? 'Upload new version' : 'Replace file',+ icon: <Upload size={12} className="text-foreground-light" />,+ onClick: onReplaceFile,+ },{ name: 'Separator', icon: undefined, onClick: undefined },]: []),@@ -234,15 +371,15 @@ export const FileExplorerRow = ({? [{// On a versioned bucket this is a soft delete, so it reads as Archive.- name: isVersionedBucket ? 'Archive' : 'Delete',- icon: isVersionedBucket ? (+ name: isActivelyVersioning ? 'Archive' : 'Delete',+ icon: isActivelyVersioning ? (<Archive size={12} className="text-foreground-light" />) : (<Trash2 size={12} className="text-foreground-light" />),onClick: () => setSelectedItemsToDelete([itemWithColumnIndex]),},- ...(isVersionedBucket+ ...(isActivelyVersioning? [{name: 'Delete permanently',@@ -255,6 +392,66 @@ export const FileExplorerRow = ({: []),]+ const { mutateAsync: restoreArchivedObject } = useArchivedObjectRestoreMutation()++ // A folder is only a prefix, so restoring one means restoring everything archived under it.+ const archivedFolderObjects = isArchivedFolder+ ? getArchivedObjectsUnderFolder({+ folderSegments: getStoragePathForItem(openedFolders, itemWithColumnIndex).split('/'),+ archivedObjects,+ })+ : []++ const handleRestoreArchived = async () => {+ if (!projectRef || !selectedBucket?.id) return++ const targets = isArchivedFolder+ ? archivedFolderObjects.map((object) => ({ archivedObjectId: object.id, path: object.path }))+ : [{ archivedObjectId, path: item.path }]++ const results = await Promise.allSettled(+ targets.map(({ archivedObjectId, path }) =>+ archivedObjectId && path+ ? restoreArchivedObject({+ projectRef,+ bucketId: selectedBucket.id,+ archivedObjectId,+ path,+ })+ : Promise.resolve()+ )+ )++ const failureCount = results.filter((result) => result.status === 'rejected').length+ if (failureCount > 0) {+ // The mutation reports each failure; this is what the batch as a whole did.+ toast.error(`Could not restore ${failureCount} file${failureCount === 1 ? '' : 's'}`)+ } else {+ toast.success(`Restored ${item.name}`)+ }++ // Whatever did restore is already live again.+ await refetchAllOpenedFolders()+ }++ // An archived file has no live object, so downloading, copying a URL, renaming and+ // moving all have nothing to act on. Only these two do.+ const archivedRowOptions: RowOption[] = !canUpdateFiles+ ? []+ : [+ {+ name: 'Restore',+ icon: <RotateCcw size={12} className="text-foreground-light" />,+ onClick: handleRestoreArchived,+ },+ { name: 'Separator', icon: undefined, onClick: undefined },+ {+ name: 'Delete permanently',+ icon: <Trash2 size={12} className="text-destructive" />,+ onClick: () => setItemToPurge(itemWithColumnIndex),+ },+ ]+const size = item.metadata ? formatBytes(item.metadata.size) : '-'const mimeType = item.metadata ? item.metadata.mimetype : '-'const createdAt = item.created_at ? new Date(item.created_at).toLocaleString() : '-'@@ -281,9 +478,13 @@ export const FileExplorerRow = ({<divstyle={style}className="h-full border-b border-default"- onContextMenu={(e) => ctx?.onRowContextMenu(e, rowOptions)}+ onContextMenu={(e) => {+ if (isArchived) return ctx?.onRowContextMenu(e, archivedRowOptions)+ return ctx?.onRowContextMenu(e, rowOptions)+ }}><div+ style={isArchived ? ARCHIVED_STRIPES_STYLE : undefined}className={cn('storage-row group flex h-full items-center px-2.5 rounded-sm','hover:bg-panel-footer-light in-data-[theme*=dark]:hover:bg-panel-footer-dark',@@ -291,6 +492,7 @@ export const FileExplorerRow = ({isSelected && 'bg-selection',isPreviewed && 'bg-selection hover:bg-selection',item.status !== STORAGE_ROW_STATUS.LOADING && 'cursor-pointer',+ isArchived && 'text-foreground-lighter [&_p]:text-foreground-lighter',// Keyboard focus on the checkbox: ring the whole row'has-[:focus-visible]:outline-solid has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-[-2px] has-[:focus-visible]:outline-[var(--ring)]')}@@ -298,9 +500,12 @@ export const FileExplorerRow = ({event.stopPropagation()event.preventDefault()if (item.status !== STORAGE_ROW_STATUS.LOADING && !isOpened && !isPreviewed) {- item.type === STORAGE_ROW_TYPES.FOLDER- ? openFolderAtIndex(columnIndex, item)- : setPreviewedFile(itemWithColumnIndex)+ if (item.type === STORAGE_ROW_TYPES.FOLDER) {+ clearArchivedSelection()+ openFolderAtIndex(columnIndex, item)+ } else {+ onSelectFile(columnIndex)+ }}}}>@@ -311,42 +516,51 @@ export const FileExplorerRow = ({)}><div className="relative flex h-4 w-[30px] shrink-0 items-center">- {showRowIcon && (- <div- className={cn(- 'absolute',- // Swap icon → checkbox on hover / keyboard focus (files only)- isFile && 'group-hover:hidden group-focus-within:hidden'- )}- style={{ top: '2px' }}- >- <StorageRowIcon- view={view}- status={item.status}- fileType={item.type}- isOpened={isOpened}- mimeType={item.metadata?.mimetype}- />- </div>- )}- {isFile ? (- <Checkbox- className={- isSelected- ? 'opacity-100'- : 'opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100'- }- checked={isSelected}- // use onClick instead of onCheckedChange to handle shift-key selection- onClick={(event) => {- event.stopPropagation()- onCheckItem(event.nativeEvent.shiftKey)- }}- aria-label="Check to select this item"+ {isArchived ? (+ <ArchivedRowIcon+ name={item.name}+ onOpen={isArchivedFile ? () => onSelectFile(columnIndex) : undefined}/>) : (- // Reserve the same slot as the file checkbox without a focusable control- <span aria-hidden className="h-4 w-4 shrink-0" />+ <>+ {showRowIcon && (+ <div+ className={cn(+ 'absolute',+ isFile && 'group-hover:hidden group-focus-within:hidden'+ )}+ style={{ top: '2px' }}+ >+ <StorageRowIcon+ view={view}+ status={item.status}+ fileType={item.type}+ isOpened={isOpened}+ mimeType={item.metadata?.mimetype}+ />+ </div>+ )}+ {/* An archived row has no live object, so none of the bulk actions apply to it. */}+ {isFile && !isArchived ? (+ <Checkbox+ className={+ isSelected+ ? 'opacity-100'+ : 'opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100'+ }+ checked={isSelected}+ // use onClick instead of onCheckedChange to handle shift-key selection+ onClick={(event) => {+ event.stopPropagation()+ onCheckItem(event.nativeEvent.shiftKey)+ }}+ aria-label="Check to select this item"+ />+ ) : (+ // Reserve the same slot as the file checkbox without a focusable control+ <span aria-hidden className="h-4 w-4 shrink-0" />+ )}+ </>)}</div><p title={item.name} className="truncate text-sm" style={{ width: nameWidth }}>@@ -387,53 +601,12 @@ export const FileExplorerRow = ({className={`animate-spin text-foreground-lighter ${view === STORAGE_VIEWS.LIST ? 'invisible' : ''}`}size={14}/>+ ) : isArchived ? (+ archivedRowOptions.length > 0 && (+ <RowActionsMenu name={item.name} options={archivedRowOptions} />+ )) : (- <DropdownMenu>- <DropdownMenuTrigger className="focus-ring rounded-sm">- <div className="storage-row-menu opacity-0">- <MoreVertical size={16} />- <span className="sr-only">{item.name} actions</span>- </div>- </DropdownMenuTrigger>- <DropdownMenuContent side="bottom" align="end">- {rowOptions.map((option) => {- if ((option?.children ?? []).length > 0) {- return (- <DropdownMenuSub key={option.name}>- <DropdownMenuSubTrigger className="space-x-2">- {option.icon || <></>}- <p>{option.name}</p>- </DropdownMenuSubTrigger>- <DropdownMenuPortal>- <DropdownMenuSubContent>- {(option?.children ?? [])?.map((child) => {- return (- <DropdownMenuItem key={child.name} onClick={child.onClick}>- <p>{child.name}</p>- </DropdownMenuItem>- )- })}- </DropdownMenuSubContent>- </DropdownMenuPortal>- </DropdownMenuSub>- )- } else if (option.name === 'Separator') {- return <DropdownMenuSeparator key={option.name} />- } else {- return (- <DropdownMenuItem- className="space-x-2"- key={option.name}- onClick={option.onClick}- >- {option.icon || <></>}- <p>{option.name}</p>- </DropdownMenuItem>- )- }- })}- </DropdownMenuContent>- </DropdownMenu>+ <RowActionsMenu name={item.name} options={rowOptions} />)}</div></div>diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.test.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.test.tsxnew file mode 100644index 00000000000..15010d61b70--- /dev/null+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.test.tsx@@ -0,0 +1,241 @@+import { screen } from '@testing-library/react'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import {+ STORAGE_ROW_STATUS,+ STORAGE_ROW_TYPES,+} from '@/components/interfaces/Storage/Storage.constants'+import type { StorageItem } from '@/components/interfaces/Storage/Storage.types'+import { PreviewPane } from '@/components/interfaces/Storage/StorageExplorer/PreviewPane'+import { customRender as render } from '@/tests/lib/custom-render'+import { addAPIMock } from '@/tests/lib/msw'++const { versioningEnabled, selectedBucket, selectedFilePreview } = vi.hoisted(() => ({+ versioningEnabled: { current: true },+ selectedBucket: {+ current: { id: 'my-bucket', name: 'my-bucket', public: false } as Record<string, unknown>,+ },+ selectedFilePreview: { current: undefined as Record<string, unknown> | undefined },+}))++vi.mock(+ '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext',+ async (importOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>()+ return { ...actual, useIsStorageVersioningEnabled: () => versioningEnabled.current }+ }+)++vi.mock('@/state/storage-explorer', () => ({+ useStorageExplorerStateSnapshot: () => ({+ projectRef: 'abcdef',+ selectedBucket: selectedBucket.current,+ selectedFilePreview: selectedFilePreview.current,+ openedFolders: [],+ setSelectedItemsToDelete: vi.fn(),+ setItemToPurge: vi.fn(),+ refetchAllOpenedFolders: vi.fn().mockResolvedValue(undefined),+ replaceFile: vi.fn(),+ setSelectedFileCustomExpiry: vi.fn(),+ downloadFile: vi.fn(),+ }),+}))+vi.mock('@/components/interfaces/Storage/StorageExplorer/StorageExplorerNavigation', () => ({+ useStorageExplorerNavigation: () => ({ clearPreviewedFile: vi.fn() }),+}))+vi.mock('@/hooks/misc/useCheckPermissions', () => ({+ useAsyncCheckPermissions: () => ({ can: true }),+}))+vi.mock('@/components/interfaces/Storage/StorageExplorer/useCopyUrl', () => ({+ useCopyUrl: () => ({ onCopyUrl: vi.fn() }),+}))++const FILE: StorageItem = {+ id: 'f1',+ name: 'photo.png',+ type: STORAGE_ROW_TYPES.FILE,+ status: STORAGE_ROW_STATUS.READY,+ metadata: {+ cacheControl: 'max-age=3600',+ contentLength: 10,+ size: 10,+ httpStatusCode: 200,+ eTag: 'etag',+ lastModified: '2024-01-01T00:00:00Z',+ mimetype: 'image/png',+ },+ isCorrupted: false,+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ last_accessed_at: null,+ path: 'photo.png',+}++const VERSIONS = [+ {+ id: 'f1',+ name: 'photo.png',+ version: 'v-current',+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ last_accessed_at: null,+ archived_at: null,+ is_delete_marker: false,+ metadata: { size: 10, mimetype: 'image/png' },+ },+]++/**+ * Ferhat's A/B/C case: B was written while suspended so it carries no version id and the+ * listing drops it, but A stays behind it as a restorable noncurrent version.+ */+const NONCURRENT_UNDER_UNVERSIONED_CURRENT = [+ {+ id: 'f1',+ name: 'photo.png',+ version: null,+ created_at: '2024-02-01T00:00:00Z',+ updated_at: '2024-02-01T00:00:00Z',+ last_accessed_at: null,+ archived_at: null,+ is_delete_marker: false,+ metadata: { size: 12, mimetype: 'image/png' },+ },+ {+ id: 'f1',+ name: 'photo.png',+ version: 'v-a',+ created_at: '2024-01-01T00:00:00Z',+ updated_at: '2024-01-01T00:00:00Z',+ last_accessed_at: null,+ archived_at: '2024-02-01T00:00:00Z',+ is_delete_marker: false,+ metadata: { size: 10, mimetype: 'image/png' },+ },+]++const mockVersionListing = (objects: unknown[]) =>+ addAPIMock({+ method: 'post',+ path: '/platform/storage/:ref/buckets/:id/objects/list',+ response: () => Response.json(objects),+ })++const renderPane = (file: Partial<StorageItem> = {}) => {+ selectedFilePreview.current = { ...FILE, ...file }+ return render(<PreviewPane />)+}++describe('PreviewPane', () => {+ beforeEach(() => {+ versioningEnabled.current = true+ selectedBucket.current = { id: 'my-bucket', name: 'my-bucket', public: false }++ mockVersionListing(VERSIONS)+ addAPIMock({+ method: 'post',+ path: '/platform/storage/:ref/buckets/:id/objects/sign',+ response: () => Response.json({ signedUrl: '/storage/v1/object/sign/photo.png' }),+ })+ addAPIMock({+ method: 'get',+ path: '/platform/storage/:ref/buckets/:id/lifecycle',+ response: () => Response.json({ rules: [] }),+ })+ })++ it('offers Archive and a purge on an enabled bucket', async () => {+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'ENABLED' }+ renderPane()++ expect(await screen.findByRole('button', { name: 'Archive' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'More delete options' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Delete file' })).not.toBeInTheDocument()+ })++ it('offers a single Delete on a suspended bucket', async () => {+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }+ renderPane({ is_versioned: false })++ // Suspended can't soft-delete, so there is no Archive and no purge split button.+ expect(await screen.findByRole('button', { name: 'Delete file' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Archive' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'More delete options' })).not.toBeInTheDocument()+ })++ describe('replace action label', () => {+ it('reads "Upload new version" on an enabled bucket', async () => {+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'ENABLED' }+ renderPane({ is_versioned: true })++ expect(await screen.findByRole('button', { name: 'Upload new version' })).toBeInTheDocument()+ })++ it('reads "Replace file" on a suspended bucket, even for a file that still retains one', async () => {+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }+ renderPane({ is_versioned: true })++ // The label names the action, not the retention. The Versions section explains that.+ expect(await screen.findByRole('button', { name: 'Replace file' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Upload new version' })).not.toBeInTheDocument()+ })++ it('reads "Replace file" on a disabled bucket', async () => {+ mockVersionListing([])+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'DISABLED' }+ renderPane({ is_versioned: false })++ expect(await screen.findByRole('button', { name: 'Replace file' })).toBeInTheDocument()+ })+ })++ describe('version history visibility', () => {+ it('shows it for a versioned file on a suspended bucket', async () => {+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }+ renderPane({ is_versioned: true })++ expect(await screen.findByText('Versions')).toBeInTheDocument()+ expect(+ await screen.findByText(/retains the current version one last time/)+ ).toBeInTheDocument()+ })++ it('hides it for a file written while versioning was suspended', async () => {+ // The listing drops unversioned rows, so a file with no history comes back empty.+ mockVersionListing([])+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }+ renderPane({ is_versioned: false })++ expect(await screen.findByRole('button', { name: 'Delete file' })).toBeInTheDocument()+ expect(screen.queryByText('Versions')).not.toBeInTheDocument()+ })++ it('still shows it when a retained version sits under an unversioned current', async () => {+ // Hiding here would strand a version the user can still restore.+ mockVersionListing(NONCURRENT_UNDER_UNVERSIONED_CURRENT)+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'SUSPENDED' }+ renderPane({ is_versioned: false })++ expect(await screen.findByText('Versions')).toBeInTheDocument()+ expect(await screen.findByText(/overwrites it in place/)).toBeInTheDocument()+ })++ it('hides it on a disabled bucket', async () => {+ mockVersionListing([])+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'DISABLED' }+ renderPane({ is_versioned: false })++ expect(await screen.findByRole('button', { name: 'Delete file' })).toBeInTheDocument()+ expect(screen.queryByText('Versions')).not.toBeInTheDocument()+ })++ it('shows it for every file on an enabled bucket, even one written before versioning', async () => {+ mockVersionListing([])+ selectedBucket.current = { ...selectedBucket.current, versioning_status: 'ENABLED' }+ renderPane({ is_versioned: false })++ // The next write will version it, so the history has to be on offer.+ expect(await screen.findByText('Versions')).toBeInTheDocument()+ })+ })+})diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.tsxindex 8255fb6d34e..1e042e6d09c 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/PreviewPane.tsx@@ -16,7 +16,12 @@ import {import { fromLifecycleRules } from '../FilesBuckets/BucketVersioningFields/BucketVersioningFields.lifecycle'import { URL_EXPIRY_DURATION } from '../Storage.constants'import { StorageItem } from '../Storage.types'-import { getBucketVersioningState } from '../StorageVersioning.constants'+import {+ getBucketVersioningState,+ hasVersioningHistory,+ isVersioningActive,+ willRetainVersionOnWrite,+} from '../StorageVersioning.constants'import { FilePreview } from './FilePreview'import { pickFile } from './pickFile'import { PreviewSection } from './PreviewSection'@@ -60,15 +65,13 @@ const FileDetails = ({ createdAt, updatedAt }: FileDetailsProps) => (interface CurrentFilePreviewProps {file: StorageItem- /** Full path within the bucket, which is what the URL endpoints address. */path: stringmimeType?: stringsize: string | nullisPublicBucket: boolean- isVersionedBucket: boolean- /** Sits beside Download. Omitted when replacing a file isn't on offer. */+ hasVersions: boolean+ canArchive: booleanreplacementAction?: ReactNode- /** Pins the preview to the current version, so a new one busts the cached URL. */currentVersionId?: stringhasCurrentVersion: booleancanUpdateFiles: boolean@@ -85,7 +88,8 @@ const CurrentFilePreview = ({mimeType,size,isPublicBucket,- isVersionedBucket,+ hasVersions,+ canArchive,replacementAction,currentVersionId,hasCurrentVersion,@@ -114,15 +118,15 @@ const CurrentFilePreview = ({{/* No `title`: the explorer rows use it as their handle, and a secondelement carrying the same one makes `getByTitle` ambiguous. */}<p className="truncate text-sm font-medium text-foreground">{file.name}</p>- <p className="mt-0.5 flex flex-wrap items-center gap-x-1.5 truncate text-xs text-foreground-light">+ <div className="mt-0.5 flex flex-wrap items-center gap-x-1.5 truncate text-xs text-foreground-light">{mimeType}{size && <>, {size}</>}- {isVersionedBucket && hasCurrentVersion && (+ {hasVersions && hasCurrentVersion && (<Badge variant="success" className="-my-1">Current</Badge>)}- </p>+ </div>{file.isCorrupted && (<div className="mt-1 flex items-center gap-x-1.5"><AlertCircle size={12} className="shrink-0 text-foreground-light" />@@ -183,7 +187,7 @@ const CurrentFilePreview = ({)}{/* A delete in a versioned bucket is a soft delete/archive, unless specified explicitly */}- {canUpdateFiles && isVersionedBucket && (+ {canUpdateFiles && canArchive && (<div className="flex"><Buttonvariant="outline"@@ -222,7 +226,7 @@ const CurrentFilePreview = ({</div>)}- {canUpdateFiles && !isVersionedBucket && (+ {canUpdateFiles && !canArchive && (<ButtonTooltipvariant="outline"size="tiny"@@ -307,7 +311,19 @@ export const PreviewPane = () => {const updatedAt = file.updated_at ? new Date(file.updated_at).toLocaleString() : 'Unknown'const currentVersion = versions?.find((version) => version.isCurrent)- const isVersionedBucket = isStorageVersioningEnabled && versioningState !== 'disabled'+ const hasVersions = isStorageVersioningEnabled && hasVersioningHistory(selectedBucket)+ const isActivelyVersioning = isStorageVersioningEnabled && isVersioningActive(selectedBucket)+ // The label names the action being taken, not the retention behind it: a suspended bucket+ // reads "Replace file" even for a file that still has one retained version coming.+ const replaceLabel = isActivelyVersioning ? 'Upload new version' : 'Replace file'+ // A suspended bucket only retains a copy when this particular file predates the suspension.+ const willRetainVersion =+ isStorageVersioningEnabled &&+ willRetainVersionOnWrite({ versioningState, isObjectVersioned: file.is_versioned })++ const hasRetainedVersions = (versions?.length ?? 0) > 0+ const showVersionHistory = hasVersions && (willRetainVersion || hasRetainedVersions)+const isComparing = previewedVersion !== undefined && !previewedVersion.isCurrentconst handleRestore = () => {@@ -325,7 +341,6 @@ export const PreviewPane = () => {if (newFile !== undefined) await replaceFile({ file: newFile, item: file })}- // The compare widget replaces the top of the panel, so scroll up to show it.const handlePreviewVersion = (version: ObjectVersion) => {setPreviewedVersion(version)scrollContainerRef.current?.scrollTo({ top: 0, behavior: 'smooth' })@@ -367,7 +382,8 @@ export const PreviewPane = () => {mimeType={mimeType}size={size}isPublicBucket={!!selectedBucket?.public}- isVersionedBucket={isVersionedBucket}+ hasVersions={hasVersions}+ canArchive={isActivelyVersioning}replacementAction={canUpdateFiles && isStorageVersioningEnabled ? (<ButtonTooltip@@ -375,12 +391,8 @@ export const PreviewPane = () => {className="px-2"icon={<Upload size={14} />}onClick={onReplaceFile}- tooltip={{- content: {- side: 'top',- text: isVersionedBucket ? 'Upload new version' : 'Replace file',- },- }}+ aria-label={replaceLabel}+ tooltip={{ content: { side: 'top', text: replaceLabel } }}/>) : undefined}@@ -398,7 +410,7 @@ export const PreviewPane = () => {<div className="space-y-3 px-4 pt-3"><FileDetails createdAt={createdAt} updatedAt={updatedAt} />- {isStorageVersioningEnabled && (+ {showVersionHistory && (<PreviewSection title="Versions" count={versions?.length} defaultOpen><VersionHistoryprojectRef={projectRef}@@ -406,6 +418,7 @@ export const PreviewPane = () => {objectName={file.name}path={filePath ?? file.name}versioningState={versioningState}+ willRetainVersionOnWrite={willRetainVersion}lifecyclePolicy={lifecyclePolicy}expirationMode={storedPolicy.expirationMode}mimeType={mimeType}diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsxindex 310cd7ccf8e..e1ff0bca12d 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorer.tsx@@ -1,6 +1,7 @@import { useParams } from 'common'import { useSelectedBucket } from '../FilesBuckets/useSelectedBucket'+import { ArchivedFilesProvider } from './ArchivedFilesContext'import { StorageExplorerContent } from './StorageExplorerContent'import { StorageExplorerNavigationProvider } from './StorageExplorerNavigation'import { useProjectStorageConfigQuery } from '@/data/config/project-storage-config-query'@@ -20,24 +21,24 @@ export const StorageExplorer = () => {// Deliberately not in the URL, so a shared link points at a folder, not someone's filter.return (- <div className="bg-studio flex h-full w-full flex-col">- {/* The skeleton swap is silent, and a live region must be mounted before it changes.- `aria-live` rather than `role="status"`: that role is how toasts announce- themselves here, and tests wait on it to tell when an upload has finished. */}- <span aria-live="polite" aria-atomic="true" className="sr-only">- {isBucketReady ? 'Bucket contents loaded' : 'Loading bucket contents'}- </span>- <StorageExplorerNavigationProvider- isBucketReady={isBucketReady}- searchString={debouncedSearchString}- >- <StorageExplorerContent- itemSearchString={itemSearchString}- setItemSearchString={setItemSearchString}- isLoading={!isBucketReady}- />- </StorageExplorerNavigationProvider>- </div>+ <ArchivedFilesProvider>+ <div className="bg-studio flex h-full w-full flex-col">+ {/* `aria-live` rather than `role="status"`, which is how toasts announce here. */}+ <span aria-live="polite" aria-atomic="true" className="sr-only">+ {isBucketReady ? 'Bucket contents loaded' : 'Loading bucket contents'}+ </span>+ <StorageExplorerNavigationProvider+ isBucketReady={isBucketReady}+ searchString={debouncedSearchString}+ >+ <StorageExplorerContent+ itemSearchString={itemSearchString}+ setItemSearchString={setItemSearchString}+ isLoading={!isBucketReady}+ />+ </StorageExplorerNavigationProvider>+ </div>+ </ArchivedFilesProvider>)}diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorerContent.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorerContent.tsxindex 3a6218a834b..cab69b0a0f5 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorerContent.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/StorageExplorerContent.tsx@@ -1,7 +1,10 @@import { compact, get, isEmpty, uniqBy } from 'lodash'import { useCallback } from 'react'+import { Admonition } from 'ui-patterns/Admonition'import { STORAGE_ROW_TYPES } from '../Storage.constants'+import { ArchivedFilePreviewPane } from './ArchivedFilePreviewPane'+import { useArchivedFilesContext } from './ArchivedFilesContext'import { ConfirmDeleteModal } from './ConfirmDeleteModal'import { ConfirmPurgeModal } from './ConfirmPurgeModal'import { CustomExpiryModal } from './CustomExpiryModal'@@ -40,6 +43,7 @@ export const StorageExplorerContent = ({setIsSearching,} = useStorageExplorerStateSnapshot()const { truncateToColumn } = useStorageExplorerNavigation()+ const { isOverlayEnabled, isListingTruncated, selectedArchivedObject } = useArchivedFilesContext()const handleClearSearch = useCallback(() => {setIsSearching(false)@@ -53,7 +57,8 @@ export const StorageExplorerContent = ({const onSelectAllItemsInColumn = (columnIndex: number) => {const columnFiles = columns[columnIndex].items- .filter((item) => item.type === STORAGE_ROW_TYPES.FILE)+ // An archived row has no live object, so the bulk actions have nothing to act on.+ .filter((item) => item.type === STORAGE_ROW_TYPES.FILE && item.archived === undefined).map((item) => {return { ...item, columnIndex }})@@ -100,6 +105,14 @@ export const StorageExplorerContent = ({) : (<FileExplorerHeaderSelection />)}+ {isOverlayEnabled && isListingTruncated && (+ <Admonition+ type="warning"+ className="mb-0 rounded-none border-x-0 border-t-0"+ title="Showing only some of this bucket's archived files"+ description="The bucket holds more rows than one listing can carry. Archived files past that point aren't shown here and can't be restored or deleted from this view."+ />+ )}<div className="flex flex-1 min-h-0"><FileExplorercolumns={columns}@@ -113,7 +126,7 @@ export const StorageExplorerContent = ({fetchMoreFolderContents({ index, column, searchString: itemSearchString })}/>- <PreviewPane />+ {selectedArchivedObject !== undefined ? <ArchivedFilePreviewPane /> : <PreviewPane />}</div><ConfirmDeleteModal />diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.test.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.test.tsxindex 46cc3a0b003..8a2638b882c 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.test.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.test.tsx@@ -1,5 +1,6 @@import { screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import type { ComponentProps } from 'react'import { describe, expect, it, vi } from 'vitest'import { VersionHistory } from '@/components/interfaces/Storage/StorageExplorer/VersionHistory'@@ -48,7 +49,7 @@ const VERSIONS = [},]-const renderHistory = () =>+const renderHistory = (props: Partial<ComponentProps<typeof VersionHistory>> = {}) =>render(<VersionHistoryprojectRef="abcdef"@@ -56,10 +57,12 @@ const renderHistory = () =>objectName="photo.png"path="images/photo.png"versioningState="enabled"+ willRetainVersionOnWritelifecyclePolicy={{ expiryDays: null, maxVersions: null }}expirationMode="and"clearPreview={vi.fn()}onEditBucket={vi.fn()}+ {...props}/>)@@ -90,4 +93,71 @@ describe('VersionHistory', () => {// showing them lives in the explorer's state rather than a React Query cache.await waitFor(() => expect(refetchAllOpenedFolders).toHaveBeenCalled())})++ describe('empty state', () => {+ const mockEmptyListing = () =>+ addAPIMock({+ method: 'post',+ path: '/platform/storage/:ref/buckets/:id/objects/list',+ response: () => Response.json([]),+ })++ it('promises retention on an enabled bucket', async () => {+ mockEmptyListing()+ renderHistory()++ expect(+ await screen.findByText(/Overwriting this file will retain a recoverable copy/)+ ).toBeInTheDocument()+ })++ it('promises retention on a suspended bucket when the file predates the suspension', async () => {+ mockEmptyListing()+ renderHistory({ versioningState: 'suspended', willRetainVersionOnWrite: true })++ expect(+ await screen.findByText(/Overwriting this file will retain a recoverable copy/)+ ).toBeInTheDocument()+ })+ })++ describe('suspended notice', () => {+ it('promises one last retained version for a file that predates the suspension', async () => {+ addAPIMock({+ method: 'post',+ path: '/platform/storage/:ref/buckets/:id/objects/list',+ response: () => Response.json(VERSIONS),+ })+ renderHistory({ versioningState: 'suspended', willRetainVersionOnWrite: true })++ expect(+ await screen.findByText(/retains the current version one last time/)+ ).toBeInTheDocument()+ })++ it('says the file is overwritten in place once the one-shot retention is spent', async () => {+ addAPIMock({+ method: 'post',+ path: '/platform/storage/:ref/buckets/:id/objects/list',+ response: () => Response.json(VERSIONS),+ })+ renderHistory({ versioningState: 'suspended', willRetainVersionOnWrite: false })++ // The versions already listed are still restorable, so the notice has to say so.+ expect(await screen.findByText(/overwrites it in place/)).toBeInTheDocument()+ expect(screen.getByText(/stay retained/)).toBeInTheDocument()+ })++ it('stays out of the way on an enabled bucket', async () => {+ addAPIMock({+ method: 'post',+ path: '/platform/storage/:ref/buckets/:id/objects/list',+ response: () => Response.json(VERSIONS),+ })+ renderHistory({ versioningState: 'enabled' })++ await screen.findByRole('button', { name: /Actions for version/ })+ expect(screen.queryByText(/Versioning is suspended/)).not.toBeInTheDocument()+ })+ })})diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.tsx b/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.tsxindex 72b5ec59673..a38512d0806 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.tsx+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.tsx@@ -141,9 +141,9 @@ interface VersionHistoryProps {projectRef?: stringbucketId?: stringobjectName: string- /** Full path within the bucket, which is what the version endpoints address. */path: stringversioningState: BucketVersioningState+ willRetainVersionOnWrite: booleanlifecyclePolicy: LifecyclePolicyexpirationMode: ExpirationModemimeType?: string@@ -159,6 +159,7 @@ export const VersionHistory = ({objectName,path,versioningState,+ willRetainVersionOnWrite,lifecyclePolicy,expirationMode,mimeType,@@ -218,10 +219,11 @@ export const VersionHistory = ({expiryDays,cap,mode: expirationMode,+ willRetainVersionOnWrite,}),]))- }, [versions, expiryDays, cap, expirationMode])+ }, [versions, expiryDays, cap, expirationMode, willRetainVersionOnWrite])const handleRestore = (version: ObjectVersion) => {if (!projectRef || !bucketId) return@@ -242,22 +244,23 @@ export const VersionHistory = ({/>)}- {versioningState === 'suspended' && (+ {versioningState === 'suspended' && willRetainVersionOnWrite && (<Admonitiontype="default"title="Versioning is suspended on this bucket"- description="New noncurrent versions are no longer created. Everything already retained here stays as it is until you delete it or a lifecycle policy expires it."+ description="Replacing this file retains the current version one last time. Anything uploaded after that overwrites it in place."/>)}- {isSuccess && versions.length === 0 && versioningState === 'disabled' && (- <p className="text-sm text-foreground-light">- Versioning is off for this bucket, so previous versions aren't retained. Turn it on- in the bucket settings to start keeping them.- </p>+ {versioningState === 'suspended' && !willRetainVersionOnWrite && (+ <Admonition+ type="default"+ title="Versioning is suspended on this bucket"+ description="Replacing this file overwrites it in place. The versions below stay retained until you delete them or a lifecycle policy expires them."+ />)}- {isSuccess && versions.length === 0 && versioningState !== 'disabled' && (+ {isSuccess && versions.length === 0 && (<p className="text-sm text-foreground-light">No previous versions yet. Overwriting this file will retain a recoverable copy here.</p>diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.utils.test.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.utils.test.tsindex c8cef66e836..8194c02af8a 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.utils.test.ts+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.utils.test.ts@@ -12,6 +12,7 @@ describe('computeVersionFate', () => {expiryDays: null,cap: null,mode: 'and',+ willRetainVersionOnWrite: true,})).toEqual({ type: 'retained' })})@@ -26,6 +27,7 @@ describe('computeVersionFate', () => {expiryDays: 0,cap: 0,mode: 'or',+ willRetainVersionOnWrite: true,})).toEqual({ type: 'retained' })})@@ -37,6 +39,7 @@ describe('computeVersionFate', () => {expiryDays: 30,cap: null,mode: 'and' as const,+ willRetainVersionOnWrite: true,}it('gives every version a determined countdown', () => {@@ -51,7 +54,7 @@ describe('computeVersionFate', () => {it('ignores a cap that has no expiration age alongside it', () => {// Not a reachable policy: S3 requires NoncurrentDays on any expiration rule.- const base = { expiryDays: null, cap: 3, mode: 'and' as const }+ const base = { expiryDays: null, cap: 3, mode: 'and' as const, willRetainVersionOnWrite: true }expect(computeVersionFate({ ...base, daysOld: 3, chronoIndex: 2, noncurrentCount: 3 })).toEqual({@@ -65,7 +68,7 @@ describe('computeVersionFate', () => {})describe('both — AND', () => {- const base = { expiryDays: 30, cap: 3, mode: 'and' as const }+ const base = { expiryDays: 30, cap: 3, mode: 'and' as const, willRetainVersionOnWrite: true }it('retains every version under the cap regardless of age', () => {expect(@@ -94,7 +97,7 @@ describe('computeVersionFate', () => {})describe('either — OR', () => {- const base = { expiryDays: 30, cap: 3, mode: 'or' as const }+ const base = { expiryDays: 30, cap: 3, mode: 'or' as const, willRetainVersionOnWrite: true }it('lets age alone trigger removal, even well under the cap', () => {expect(@@ -132,4 +135,25 @@ describe('computeVersionFate', () => {).toEqual({ type: 'expiry-due' })})})++ describe('when no further write will retain a version', () => {+ // A suspended bucket overwrites in place, so nothing will ever push the version+ // sitting at the cap boundary over it.+ const base = { expiryDays: 30, cap: 3, mode: 'or' as const, willRetainVersionOnWrite: false }++ it('falls back to the age countdown at the cap boundary', () => {+ expect(+ computeVersionFate({ ...base, daysOld: 6, chronoIndex: 1, noncurrentCount: 4 })+ ).toEqual({ type: 'expires-in', days: 24 })+ })++ it('leaves every other fate untouched', () => {+ expect(+ computeVersionFate({ ...base, daysOld: 3, chronoIndex: 2, noncurrentCount: 4 })+ ).toEqual({ type: 'expires-in', days: 27 })+ expect(+ computeVersionFate({ ...base, daysOld: 9, chronoIndex: 0, noncurrentCount: 4 })+ ).toEqual({ type: 'expiry-due' })+ })+ })})diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.utils.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.utils.tsindex 3b9a599471f..430e50a584f 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.utils.ts+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/VersionHistory.utils.ts@@ -14,6 +14,7 @@ export interface ComputeVersionFateOptions {expiryDays: number | nullcap: number | nullmode: ExpirationMode+ willRetainVersionOnWrite: boolean}const toActiveBound = (value: number | null) => (value !== null && value > 0 ? value : null)@@ -26,6 +27,7 @@ export const computeVersionFate = ({expiryDays,cap,mode,+ willRetainVersionOnWrite,}: ComputeVersionFateOptions): VersionFate => {const activeExpiryDays = toActiveBound(expiryDays)const activeCap = toActiveBound(cap)@@ -56,6 +58,8 @@ export const computeVersionFate = ({? { type: 'expiry-due' }: { type: 'expires-in', days: MIN_NONCURRENT_DAYS - daysOld }}- if (isAtCapBoundary) return { type: 'expires-on-next-upload', daysRemaining }+ if (isAtCapBoundary && willRetainVersionOnWrite) {+ return { type: 'expires-on-next-upload', daysRemaining }+ }return { type: 'expires-in', days: daysRemaining }}diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/archivedOverlay.utils.test.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/archivedOverlay.utils.test.tsindex f53e336eede..4e4102f5be7 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/archivedOverlay.utils.test.ts+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/archivedOverlay.utils.test.ts@@ -1,7 +1,11 @@import { describe, expect, it } from 'vitest'import { STORAGE_ROW_TYPES } from '../Storage.constants'-import { getArchivedOverlayItems, getArchivedSegments } from './archivedOverlay.utils'+import {+ getArchivedObjectsUnderFolder,+ getArchivedOverlayItems,+ getArchivedSegments,+} from './archivedOverlay.utils'import type { ArchivedObject } from '@/data/storage/versioning/archived-objects-query'const archived = (path: string, overrides: Partial<ArchivedObject> = {}): ArchivedObject => ({@@ -13,6 +17,7 @@ const archived = (path: string, overrides: Partial<ArchivedObject> = {}): Archivsize: 1024,createdAt: '2026-07-01T00:00:00Z',action: 'overwrite',+ mimeType: 'image/png',},noncurrentVersions: [],...overrides,@@ -87,6 +92,8 @@ describe('getArchivedOverlayItems', () => {expect(rows).toHaveLength(1)expect(rows[0].name).toBe('final.png')expect(rows[0].type).toBe(STORAGE_ROW_TYPES.FILE)+ // Carried through so the row icon and the preview both know what this is.+ expect(rows[0].metadata?.mimetype).toBe('image/png')})it('coalesces several objects under one subfolder into a single row', () => {@@ -134,3 +141,39 @@ describe('getArchivedOverlayItems', () => {expect(overlay(['a'], [archived('a/b/c/d.png')]).map((r) => r.name)).toEqual(['b'])})})++describe('getArchivedObjectsUnderFolder', () => {+ const objects = [+ archived('logo.svg'),+ archived('matches/final.png'),+ archived('matches/round-3/a.png'),+ archived('matches-2026/other.png'),+ ]++ it('collects everything under the folder at any depth', () => {+ const under = getArchivedObjectsUnderFolder({+ folderSegments: ['matches'],+ archivedObjects: objects,+ })+ expect(under.map((object) => object.path)).toEqual([+ 'matches/final.png',+ 'matches/round-3/a.png',+ ])+ })++ it('does not match a sibling folder sharing the name as a prefix', () => {+ const under = getArchivedObjectsUnderFolder({+ folderSegments: ['matches'],+ archivedObjects: [archived('matches-2026/other.png')],+ })+ expect(under).toEqual([])+ })++ it('includes the placeholder, so an empty archived folder is still actionable', () => {+ const under = getArchivedObjectsUnderFolder({+ folderSegments: ['matches'],+ archivedObjects: [archived('matches/.emptyFolderPlaceholder')],+ })+ expect(under.map((object) => object.path)).toEqual(['matches/.emptyFolderPlaceholder'])+ })+})diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/archivedOverlay.utils.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/archivedOverlay.utils.tsindex 0592b5a1535..a4e660e572f 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/archivedOverlay.utils.ts+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/archivedOverlay.utils.ts@@ -13,6 +13,16 @@ const isUnderFolder = (folderSegments: string[], objectSegments: string[]): boolreturn folderSegments.every((segment, index) => segment === objectSegments[index])}+/** Every archived object inside a folder, at any depth. A folder is only a prefix. */+export const getArchivedObjectsUnderFolder = ({+ folderSegments,+ archivedObjects,+}: {+ folderSegments: string[]+ archivedObjects: ArchivedObject[]+}): ArchivedObject[] =>+ archivedObjects.filter((object) => isUnderFolder(folderSegments, getArchivedSegments(object)))+export interface ArchivedOverlayInput {folderSegments: string[]archivedObjects: ArchivedObject[]@@ -54,7 +64,7 @@ export const getArchivedOverlayItems = ({status: STORAGE_ROW_STATUS.READY,metadata: {size: object.currentVersion.size,- mimetype: '',+ mimetype: object.currentVersion.mimeType ?? '',cacheControl: '',contentLength: object.currentVersion.size,httpStatusCode: 0,diff --git a/apps/studio/components/interfaces/Storage/StorageExplorer/useStoragePreference.ts b/apps/studio/components/interfaces/Storage/StorageExplorer/useStoragePreference.tsindex 9e484b50bfe..a2ba41d0aeb 100644--- a/apps/studio/components/interfaces/Storage/StorageExplorer/useStoragePreference.ts+++ b/apps/studio/components/interfaces/Storage/StorageExplorer/useStoragePreference.ts@@ -14,6 +14,7 @@ interface StoragePreference {sortBy: STORAGE_SORT_BYsortByOrder: STORAGE_SORT_BY_ORDERsortBucket: STORAGE_BUCKET_SORT+ showArchivedInline: boolean}const DEFAULT_PREFERENCES: StoragePreference = {@@ -21,6 +22,7 @@ const DEFAULT_PREFERENCES: StoragePreference = {sortBy: STORAGE_SORT_BY.NAME,sortByOrder: STORAGE_SORT_BY_ORDER.ASC,sortBucket: STORAGE_BUCKET_SORT.CREATED_AT,+ showArchivedInline: false,}/**@@ -64,6 +66,13 @@ export function useStoragePreference(projectRef: string) {[setPreference])+ const setShowArchivedInline = useCallback(+ (showArchivedInline: boolean) => {+ setPreference((prev) => ({ ...prev, showArchivedInline }))+ },+ [setPreference]+ )+const setSortBucket = useCallback((sortBucket: STORAGE_BUCKET_SORT) => {setPreference((prev) => ({ ...prev, sortBucket }))@@ -76,9 +85,11 @@ export function useStoragePreference(projectRef: string) {sortBy: preference.sortBy,sortByOrder: preference.sortByOrder,sortBucket: preference.sortBucket,+ showArchivedInline: preference.showArchivedInline,setView,setSortBy,setSortByOrder,setSortBucket,+ setShowArchivedInline,}}diff --git a/apps/studio/components/interfaces/Storage/StorageRowIcon.tsx b/apps/studio/components/interfaces/Storage/StorageRowIcon.tsxindex 814a3b259c2..72e0392bfd9 100644--- a/apps/studio/components/interfaces/Storage/StorageRowIcon.tsx+++ b/apps/studio/components/interfaces/Storage/StorageRowIcon.tsx@@ -3,7 +3,7 @@ import { File, Film, FolderOpen, Image as ImageIcon, LoaderCircle, Music } fromimport { STORAGE_ROW_STATUS, STORAGE_ROW_TYPES, STORAGE_VIEWS } from './Storage.constants'-const ICON_STROKE_WIDTH = 1.5+export const ICON_STROKE_WIDTH = 1.5interface StorageRowIconProps {view: STORAGE_VIEWSdiff --git a/apps/studio/components/interfaces/Storage/StorageVersioning.constants.test.ts b/apps/studio/components/interfaces/Storage/StorageVersioning.constants.test.tsnew file mode 100644index 00000000000..79df7b4f8ed--- /dev/null+++ b/apps/studio/components/interfaces/Storage/StorageVersioning.constants.test.ts@@ -0,0 +1,85 @@+import { describe, expect, it } from 'vitest'++import {+ getBucketVersioningState,+ hasVersioningHistory,+ isVersioningActive,+ willRetainVersionOnWrite,+} from './StorageVersioning.constants'+import type { Bucket } from '@/data/storage/buckets-query'++const bucket = (versioning_status?: Bucket['versioning_status']) =>+ ({ id: 'bucket', name: 'bucket', versioning_status }) as Bucket++describe('getBucketVersioningState', () => {+ it('maps the API statuses', () => {+ expect(getBucketVersioningState(bucket('ENABLED'))).toBe('enabled')+ expect(getBucketVersioningState(bucket('SUSPENDED'))).toBe('suspended')+ expect(getBucketVersioningState(bucket('DISABLED'))).toBe('disabled')+ })++ it('treats a bucket that never reported a status as disabled', () => {+ expect(getBucketVersioningState(bucket(undefined))).toBe('disabled')+ expect(getBucketVersioningState(undefined)).toBe('disabled')+ })+})++describe('isVersioningActive', () => {+ it('only lets an enabled bucket soft-delete', () => {+ expect(isVersioningActive(bucket('ENABLED'))).toBe(true)+ expect(isVersioningActive(bucket('SUSPENDED'))).toBe(false)+ expect(isVersioningActive(bucket('DISABLED'))).toBe(false)+ expect(isVersioningActive(undefined)).toBe(false)+ })+})++describe('hasVersioningHistory', () => {+ it('keeps a suspended bucket in, since it can still be retaining versions', () => {+ expect(hasVersioningHistory(bucket('ENABLED'))).toBe(true)+ expect(hasVersioningHistory(bucket('SUSPENDED'))).toBe(true)+ expect(hasVersioningHistory(bucket('DISABLED'))).toBe(false)+ expect(hasVersioningHistory(undefined)).toBe(false)+ })+})++describe('willRetainVersionOnWrite', () => {+ it('always retains on an enabled bucket, whatever the object reports', () => {+ expect(willRetainVersionOnWrite({ versioningState: 'enabled', isObjectVersioned: true })).toBe(+ true+ )+ expect(willRetainVersionOnWrite({ versioningState: 'enabled', isObjectVersioned: false })).toBe(+ true+ )+ expect(+ willRetainVersionOnWrite({ versioningState: 'enabled', isObjectVersioned: undefined })+ ).toBe(true)+ })++ it('retains on a suspended bucket only for an object that predates the suspension', () => {+ expect(+ willRetainVersionOnWrite({ versioningState: 'suspended', isObjectVersioned: true })+ ).toBe(true)+ expect(+ willRetainVersionOnWrite({ versioningState: 'suspended', isObjectVersioned: false })+ ).toBe(false)+ })++ it('falls back to no retention when the listing omits the field', () => {+ // An older storage build may not send `is_versioned`; "replace in place" is the safe read.+ expect(+ willRetainVersionOnWrite({ versioningState: 'suspended', isObjectVersioned: undefined })+ ).toBe(false)+ expect(+ willRetainVersionOnWrite({ versioningState: 'suspended', isObjectVersioned: null })+ ).toBe(false)+ })++ it('never retains on a disabled bucket', () => {+ expect(willRetainVersionOnWrite({ versioningState: 'disabled', isObjectVersioned: true })).toBe(+ false+ )+ expect(+ willRetainVersionOnWrite({ versioningState: 'disabled', isObjectVersioned: false })+ ).toBe(false)+ })+})diff --git a/apps/studio/components/interfaces/Storage/StorageVersioning.constants.ts b/apps/studio/components/interfaces/Storage/StorageVersioning.constants.tsindex c9c998be1f3..489347c3d47 100644--- a/apps/studio/components/interfaces/Storage/StorageVersioning.constants.ts+++ b/apps/studio/components/interfaces/Storage/StorageVersioning.constants.ts@@ -19,8 +19,28 @@ export const getBucketVersioningState = (bucket?: Bucket): BucketVersioningState}}-export const isBucketVersioned = (bucket?: Bucket) => getBucketVersioningState(bucket) === 'enabled'+/**+ * The bucket versions writes right now: a delete becomes a recoverable archive and an+ * overwrite becomes a new version. Drives what the actions are called.+ */+export const isVersioningActive = (bucket?: Bucket) =>+ getBucketVersioningState(bucket) === 'enabled'/** A suspended bucket can still be retaining versions. */export const hasVersioningHistory = (bucket?: Bucket) =>getBucketVersioningState(bucket) !== 'disabled'++/**+ * A suspended bucket retains a copy when the object it replaces+ * was itself written while versioning was enabled.+ */+export const willRetainVersionOnWrite = ({+ versioningState,+ isObjectVersioned,+}: {+ versioningState: BucketVersioningState+ isObjectVersioned?: boolean | null+}) => {+ if (versioningState === 'enabled') return true+ return versioningState === 'suspended' && !!isObjectVersioned+}diff --git a/apps/studio/pages/project/[ref]/storage/files/buckets/[bucketId].tsx b/apps/studio/pages/project/[ref]/storage/files/buckets/[bucketId].tsxindex 7b1ad863a03..ea8ee17f105 100644--- a/apps/studio/pages/project/[ref]/storage/files/buckets/[bucketId].tsx+++ b/apps/studio/pages/project/[ref]/storage/files/buckets/[bucketId].tsx@@ -25,6 +25,7 @@ import {import { PageBreadcrumbs, PageBreadcrumbsActions } from 'ui-patterns/PageBreadcrumbs'import { PageContainer } from 'ui-patterns/PageContainer'+import { BucketVersioningPill } from '@/components/interfaces/Storage/BucketVersioningPill'import { DeleteBucketModal } from '@/components/interfaces/Storage/FilesBuckets/DeleteBucketModal'import { EditBucketModal } from '@/components/interfaces/Storage/FilesBuckets/EditBucketModal'import { EmptyBucketModal } from '@/components/interfaces/Storage/FilesBuckets/EmptyBucketModal'@@ -78,6 +79,7 @@ const BucketPage: NextPageWithLayout = () => {<PageBreadcrumbsactions={<PageBreadcrumbsActions>+ <BucketVersioningPill bucket={bucket} /><ButtonasChildvariant="outline"diff --git a/apps/studio/state/storage-explorer.test.ts b/apps/studio/state/storage-explorer.test.tsindex 00536fc4c4e..2c19ee41192 100644--- a/apps/studio/state/storage-explorer.test.ts+++ b/apps/studio/state/storage-explorer.test.ts@@ -2,8 +2,15 @@ import { HttpResponse } from 'msw'import { beforeEach, describe, expect, it } from 'vitest'import { createStorageExplorerState } from './storage-explorer'+import {+ STORAGE_ROW_STATUS,+ STORAGE_ROW_TYPES,+} from '@/components/interfaces/Storage/Storage.constants'+import type { StorageItem } from '@/components/interfaces/Storage/Storage.types'+import { getQueryClient } from '@/data/query-client'import type { StorageObject } from '@/data/storage/bucket-objects-list-mutation'import type { Bucket } from '@/data/storage/buckets-query'+import { storageKeys } from '@/data/storage/keys'import { addAPIMock } from '@/tests/lib/msw'function makeBucket(id: string): Bucket {@@ -107,3 +114,69 @@ describe('fetchFoldersByPath', () => {expect(state.openedFolders.map((folder) => folder.name)).toEqual(['shared'])})})++describe('refetchAllOpenedFolders', () => {+ it('marks the archived list stale, so an archive or restore shows without a refresh', async () => {+ addAPIMock({+ method: 'post',+ path: '/platform/storage/:ref/buckets/:id/objects/list',+ response: BUCKET_A_LISTING,+ })++ const queryClient = getQueryClient()+ const key = storageKeys.archivedObjects('test-ref', 'bucket-a')+ queryClient.setQueryData(key, [])+ expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false)++ const state = createState(makeBucket('bucket-a'))+ await state.refetchAllOpenedFolders()++ expect(queryClient.getQueryState(key)?.isInvalidated).toBe(true)+ })+})++describe('selectRangeItems', () => {+ function makeFile(id: string): StorageItem {+ return {+ id,+ name: `${id}.png`,+ type: STORAGE_ROW_TYPES.FILE,+ status: STORAGE_ROW_STATUS.READY,+ metadata: null,+ created_at: null,+ updated_at: null,+ last_accessed_at: null,+ isCorrupted: false,+ }+ }++ function createStateWithColumn(items: StorageItem[]) {+ const state = createState(makeBucket('bucket-a'))+ state.columns = [+ { id: null, name: 'bucket-a', path: '', status: STORAGE_ROW_STATUS.READY, items },+ ]+ return state+ }++ it('resolves the range from the item id, not a rendered row position', () => {+ const items = [makeFile('a'), makeFile('b'), makeFile('c')]+ const state = createStateWithColumn(items)+ state.setSelectedItems([{ ...items[0], columnIndex: 0 }])++ // The rendered column interleaves archived rows, so 'c' sits at a higher index there+ // than it does here. Addressing it by id is what keeps the two in agreement.+ state.selectRangeItems(0, 'c')++ expect(state.selectedItems.map((item) => item.id)).toEqual(['a', 'b', 'c'])+ })++ it('ignores an id the column does not hold', () => {+ const items = [makeFile('a'), makeFile('b')]+ const state = createStateWithColumn(items)+ state.setSelectedItems([{ ...items[0], columnIndex: 0 }])++ state.selectRangeItems(0, 'archived-only')++ expect(state.selectedItems.map((item) => item.id)).toEqual(['a'])+ })+})diff --git a/apps/studio/state/storage-explorer.tsx b/apps/studio/state/storage-explorer.tsxindex dfa65399781..8c47f033121 100644--- a/apps/studio/state/storage-explorer.tsx+++ b/apps/studio/state/storage-explorer.tsx@@ -45,6 +45,7 @@ import {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 { InlineLink } from '@/components/ui/InlineLink'import { getOrRefreshTemporaryApiKey } from '@/data/api-keys/temp-api-keys-utils'import { configKeys } from '@/data/config/keys'@@ -445,6 +446,12 @@ export function createStorageExplorerState({} else {await state.fetchFoldersByPath({ paths })}++ // The archived overlay is part of what the explorer shows, and an archive or a+ // restore moves an object across that boundary, so both halves refresh together.+ await getQueryClient().invalidateQueries({+ queryKey: storageKeys.archivedObjects(state.projectRef, state.selectedBucket?.id),+ })},refreshAll: async () => {@@ -589,7 +596,10 @@ export function createStorageExplorerState({} catch (error) {}},- deleteFolder: async (folder: StorageItemWithColumn) => {+ deleteFolder: async (+ folder: StorageItemWithColumn,+ { isArchive = false }: { isArchive?: boolean } = {}+ ) => {try {const isDeleteFolder = trueconst files = await state.getAllItemsAlongFolder(folder)@@ -603,7 +613,7 @@ export function createStorageExplorerState({prefix: folder.path,})} else {- await state.deleteFiles({ files: files as any[], isDeleteFolder })+ await state.deleteFiles({ files: files as any[], isDeleteFolder, isArchive })}state.popColumnAtIndex(folder.columnIndex)@@ -620,9 +630,15 @@ export function createStorageExplorerState({await state.refetchAllOpenedFolders()state.setSelectedItemsToDelete([])- toast.success(`Successfully deleted ${folder.name}`)+ toast.success(+ isArchive ? `Successfully archived ${folder.name}` : `Successfully deleted ${folder.name}`+ )} catch (error: any) {- toast.error(`Failed to delete folder: ${error.message}`)+ toast.error(+ isArchive+ ? `Failed to archive folder: ${error.message}`+ : `Failed to delete folder: ${error.message}`+ )}},@@ -1512,7 +1528,15 @@ export function createStorageExplorerState({*/replaceFile: async ({ file, item }: { file: File; item: StorageItemWithColumn }) => {const path = getStorageItemPath(state, item)- const toastId = toast.loading(`Uploading a new version of ${item.name}...`)+ // Mirrors the action label the user clicked, which follows the bucket rather than+ // whether this particular write happens to retain a version.+ const copy = isVersioningActive(state.selectedBucket)+ ? {+ loading: `Uploading a new version of ${item.name}...`,+ success: `Uploaded a new version of ${item.name}`,+ }+ : { loading: `Replacing ${item.name}...`, success: `Replaced ${item.name}` }+ const toastId = toast.loading(copy.loading)state.updateRowStatus({name: item.name,@@ -1548,7 +1572,7 @@ export function createStorageExplorerState({upload.start()})- toast.success(`Uploaded a new version of ${item.name}`, { id: toastId })+ toast.success(copy.success, { id: toastId })await state.refetchAllOpenedFolders()await Promise.all([getQueryClient().invalidateQueries({@@ -1585,9 +1609,12 @@ export function createStorageExplorerState({deleteFiles: async ({files,isDeleteFolder = false,+ isArchive = false,}: {files: (StorageItemWithColumn & { prefix?: string })[]isDeleteFolder?: boolean+ /** On a versioned bucket the object survives behind a delete marker, so the copy says archive. */+ isArchive?: boolean}) => {state.setSelectedFilePreview(undefined)@@ -1607,7 +1634,19 @@ export function createStorageExplorerState({state.clearSelectedItems()- const toastId = toast.loading(`Deleting ${prefixes.length} file(s)...`)+ const copy = isArchive+ ? {+ loading: `Archiving ${prefixes.length} file(s)...`,+ success: `Successfully archived ${prefixes.length} file(s)`,+ error: `Failed to archive ${prefixes.length} file(s)`,+ }+ : {+ loading: `Deleting ${prefixes.length} file(s)...`,+ success: `Successfully deleted ${prefixes.length} file(s)`,+ error: `Failed to delete ${prefixes.length} file(s)`,+ }++ const toastId = toast.loading(copy.loading)try {await deleteBucketObject({@@ -1628,7 +1667,7 @@ export function createStorageExplorerState({parentFolderPrefixes.map((prefix) => state.validateParentFolderEmpty(prefix)))- toast.success(`Successfully deleted ${prefixes.length} file(s)`, {+ toast.success(copy.success, {id: toastId,closeButton: true,duration: SONNER_DEFAULT_DURATION,@@ -1641,7 +1680,7 @@ export function createStorageExplorerState({}} catch (err) {if (!isDeleteFolder) {- toast.error(`Failed to delete ${prefixes.length} file(s)`, {+ toast.error(copy.error, {id: toastId,closeButton: true,duration: SONNER_DEFAULT_DURATION,@@ -1849,8 +1888,12 @@ export function createStorageExplorerState({// ======== UI Helper functions ========- selectRangeItems: (columnIndex: number, toItemIndex: number) => {+ selectRangeItems: (columnIndex: number, toItemId: string | null) => {const columnItems = state.columns[columnIndex].items+ // Addressed by id, not by the row's own position: the rendered column can carry+ // archived rows this list has never held, which shifts every index below them.+ const toItemIndex = toItemId === null ? -1 : findIndex(columnItems, { id: toItemId })+ if (toItemIndex === -1) returnconst toItem = columnItems[toItemIndex]const selectedItemIds = state.selectedItems.map((item) => item.id)const lastSelectedItemId = selectedItemIds[selectedItemIds.length - 1]@@ -1863,6 +1906,8 @@ export function createStorageExplorerState({// Get the range to select and reverse the order if necessaryconst rangeToSelect = columnItems.slice(start, end + 1)+ // An archived row has no live object, so the bulk actions have nothing to act on.+ .filter((item) => item.archived === undefined)// we need `columnIndex` in all item of `selectedItems`.map((item) => ({ ...item, columnIndex }))if (toItemIndex < lastSelectedItemIndex) {diff --git a/knip.jsonc b/knip.jsoncindex d7c60d89b6a..7a79952a7e0 100644--- a/knip.jsonc+++ b/knip.jsonc@@ -71,11 +71,6 @@// alongside the rest of the Warehouse work so the values stay in one// place until the project-creation surface that consumes them lands."components/interfaces/ProjectCreation/WarehouseFdwCustomImage.constants.ts": ["files"],- // Storage object versioning: the archived explorer rows are the first- // consumer of these two, and that PR drops the entry.- "data/storage/versioning/archived-object-{purge,restore}-mutation.ts": ["files"],- // Consumed by the archived file preview pane, one PR further up.- "data/storage/versioning/archived-object-version-delete-mutation.ts": ["files"],},// `vercel` is a globally installed CLI used by the `deploy:staging` script"ignoreBinaries": ["vercel"],