Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(desktop): avoid duplicate GFS upload names

M5eb0bf4e8884
diff --git a/desktop-app/ui/src/gfs/__tests__/resourceName.test.ts b/desktop-app/ui/src/gfs/__tests__/resourceName.test.ts
index 9b21ffb69..984845209 100644
--- a/desktop-app/ui/src/gfs/__tests__/resourceName.test.ts
+++ b/desktop-app/ui/src/gfs/__tests__/resourceName.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest'
import { createHash } from 'node:crypto'
-import { GFS_RESOURCE_NAME_MAX_LENGTH, normalizeGfsResourceName } from '../resourceName'
+import {
+ GFS_RESOURCE_NAME_MAX_LENGTH,
+ nextAvailableGfsResourceName,
+ normalizeGfsResourceName,
+} from '../resourceName'
const HASH_LENGTH = 12
const EXTENSION_MAX_LENGTH = 48
@@ -53,3 +57,23 @@ describe('normalizeGfsResourceName', () => {
}
)
})
+
+describe('nextAvailableGfsResourceName', () => {
+ it('adds the first available numbered suffix before the extension', () => {
+ expect(
+ nextAvailableGfsResourceName('report.txt', ['report.txt', 'report (1).txt', 'report (3).txt'])
+ ).toBe('report (2).txt')
+ })
+
+ it('adds a suffix to names without an extension', () => {
+ expect(nextAvailableGfsResourceName('README', ['README'])).toBe('README (1)')
+ })
+
+ it('keeps numbered names within the GFS name limit', () => {
+ const name = `${'a'.repeat(GFS_RESOURCE_NAME_MAX_LENGTH - '.txt'.length)}.txt`
+ const candidate = nextAvailableGfsResourceName(name, [name])
+
+ expect(candidate).toBe(`${'a'.repeat(247)} (1).txt`)
+ expect(candidate).toHaveLength(GFS_RESOURCE_NAME_MAX_LENGTH)
+ })
+})
diff --git a/desktop-app/ui/src/gfs/resourceName.ts b/desktop-app/ui/src/gfs/resourceName.ts
index dba4e2d46..779382b14 100644
--- a/desktop-app/ui/src/gfs/resourceName.ts
+++ b/desktop-app/ui/src/gfs/resourceName.ts
@@ -14,6 +14,37 @@ function extensionOf(name: string): string {
return extension.length <= GFS_RESOURCE_EXTENSION_MAX_LENGTH ? extension : ''
}
+function truncatedBaseForSuffix(base: string, suffix: string): string {
+ const maxBaseLength = GFS_RESOURCE_NAME_MAX_LENGTH - suffix.length
+ if (maxBaseLength <= 0) throw new Error('Could not create a unique GFS resource name.')
+ const truncatedBase = base.slice(0, maxBaseLength).replace(/[\s._-]+$/g, '')
+ return truncatedBase || base.slice(0, maxBaseLength)
+}
+
+/**
+ * Returns the first available sibling name using the familiar `(1)`, `(2)`
+ * suffix convention. The extension stays at the end and the result remains
+ * within the same limit as normalizeGfsResourceName.
+ */
+export function nextAvailableGfsResourceName(
+ name: string,
+ occupiedNames: Iterable<string>
+): string {
+ const normalized = name.normalize('NFC')
+ const occupied = new Set(Array.from(occupiedNames, value => value.normalize('NFC')))
+ if (!occupied.has(normalized)) return normalized
+
+ const extension = extensionOf(normalized)
+ const base = extension ? normalized.slice(0, -extension.length) : normalized
+ for (let index = 1; index <= 10_000; index += 1) {
+ const suffix = ` (${index})${extension}`
+ const candidate = `${truncatedBaseForSuffix(base, suffix)}${suffix}`
+ if (!occupied.has(candidate)) return candidate
+ }
+
+ throw new Error('Could not create a unique GFS resource name.')
+}
+
export async function normalizeGfsResourceName(name: string): Promise<string> {
const normalized = name.normalize('NFC')
if (normalized === '.' || normalized === '..' || /[\/\\\u0000-\u001f\u007f]/.test(normalized)) {
@@ -25,9 +56,7 @@ export async function normalizeGfsResourceName(name: string): Promise<string> {
const base = extension ? normalized.slice(0, -extension.length) : normalized
const hash = (await sha256Hex(normalized)).slice(0, GFS_RESOURCE_NAME_HASH_LENGTH)
const suffix = `-${hash}${extension}`
- const maxBaseLength = GFS_RESOURCE_NAME_MAX_LENGTH - suffix.length
- const truncatedBase = base.slice(0, maxBaseLength).replace(/[\s._-]+$/g, '')
- const safeBase = truncatedBase || base.slice(0, maxBaseLength)
+ const safeBase = truncatedBaseForSuffix(base, suffix)
return `${safeBase}${suffix}`
}
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index 70521f720..6597dff4e 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -40,7 +40,7 @@ import {
} from '@/gfs/delegation'
import { GfsFilePicker } from '@/gfs/filePicker'
import { GfsMoveDialog } from '@/gfs/moveDialog'
-import { normalizeGfsResourceName } from '@/gfs/resourceName'
+import { nextAvailableGfsResourceName, normalizeGfsResourceName } from '@/gfs/resourceName'
import type { TeamDirectoryResult } from '../../../src/types'
import type {
FilesPageProps,
@@ -112,6 +112,37 @@ function mergeErrorMessages(...errors: unknown[]): string | null {
return messages.length > 0 ? messages.join(' · ') : null
}
+function isGfsNameConflict(error: unknown): boolean {
+ const details =
+ error && typeof error === 'object'
+ ? (error as {
+ status?: unknown
+ bodyText?: unknown
+ message?: unknown
+ response?: { status?: unknown }
+ })
+ : null
+ const status = details?.status ?? details?.response?.status
+ if (status === 409 || status === '409') return true
+
+ const messageParts = details
+ ? [details.message, details.bodyText].filter(value => value != null).map(String)
+ : []
+ const message =
+ error instanceof Error
+ ? error.message
+ : messageParts.length > 0
+ ? messageParts.join(' ')
+ : String(error)
+ return (
+ /\b409\b[\s\S]*\bconflict\b/i.test(message) ||
+ /\bconflict\b[\s\S]*\b409\b/i.test(message) ||
+ /\b(?:already exists|duplicate|name[_ ]?conflict|resource[_ ]?exists)\b/i.test(message)
+ )
+}
+
+const GFS_UPLOAD_NAME_RETRY_LIMIT = 100
+
/** Any row/header action target — a listing row (GfsDriveResource) or the
* current breadcrumb (GfsCrumb); both carry the identity fields the delete /
* rename / move calls need (kind also powers dialog titles + the move cycle
@@ -136,6 +167,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
const [dragActive, setDragActive] = useState(false)
const [droppedUploadCount, setDroppedUploadCount] = useState(0)
const replaceInputRef = useRef<HTMLInputElement | null>(null)
+ const uploadNameReservationsRef = useRef(new Map<string, Set<string>>())
const queryClient = useQueryClient()
const ctrl = useGfsBrowserController({ grantsListEnabled: manageOpen })
const {
@@ -447,19 +479,47 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
const handleUploadFile = async (
file: File | null | undefined,
- parentResourceId = current?.resourceId
+ parentResourceId = current?.resourceId,
+ occupiedNames = new Set(items.map(item => item.name))
) => {
if (!file || !parentResourceId) return
+ const attemptedNames = new Set<string>()
try {
assertGfsFileUploadSize(file.size)
- const name = await normalizeGfsResourceName(file.name)
+ const normalizedName = await normalizeGfsResourceName(file.name)
const filePath = window.clerum.gfs.getPathForFile(file)
if (!filePath) throw new Error('Could not resolve the selected local file')
- await ctrl.createFileFromPath(parentResourceId, name, filePath)
- pushToast?.(`Uploaded ${name}`, 'success')
+
+ for (let attempt = 0; attempt < GFS_UPLOAD_NAME_RETRY_LIMIT; attempt += 1) {
+ const reservations =
+ uploadNameReservationsRef.current.get(parentResourceId) ?? new Set<string>()
+ uploadNameReservationsRef.current.set(parentResourceId, reservations)
+ const name = nextAvailableGfsResourceName(normalizedName, [
+ ...occupiedNames,
+ ...reservations,
+ ])
+ reservations.add(name)
+ attemptedNames.add(name)
+
+ try {
+ await ctrl.createFileFromPath(parentResourceId, name, filePath)
+ occupiedNames.add(name)
+ pushToast?.(`Uploaded ${name}`, 'success')
+ return
+ } catch (uploadError) {
+ if (!isGfsNameConflict(uploadError)) throw uploadError
+ occupiedNames.add(name)
+ }
+ }
+
+ throw new Error('Could not create a unique GFS resource name.')
} catch (uploadError) {
if (failClosedOnAuthorizationError(uploadError)) return
pushToast?.(uploadError instanceof Error ? uploadError.message : String(uploadError), 'error')
+ } finally {
+ const reservations = uploadNameReservationsRef.current.get(parentResourceId)
+ for (const name of attemptedNames) reservations?.delete(name)
+ if (reservations?.size === 0) uploadNameReservationsRef.current.delete(parentResourceId)
}
}
@@ -503,9 +563,10 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
}
setDroppedUploadCount(droppedFiles.length)
+ const occupiedNames = new Set(items.map(item => item.name))
try {
for (const file of droppedFiles) {
- await handleUploadFile(file, destinationResourceId)
+ await handleUploadFile(file, destinationResourceId, occupiedNames)
}
} finally {
setDroppedUploadCount(0)
diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index 4a39a7d0b..2d3d0c12c 100644
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@ -479,6 +479,158 @@ describe('FilesPage', () => {
expect(pushToast).toHaveBeenCalledWith('Uploaded clip.mov', 'success')
})
+ it('adds numbered suffixes for duplicate names in one dropped batch', async () => {
+ const createFileFromPath = vi.fn(async () => undefined)
+ const pushToast = vi.fn()
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ current: {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder-1',
+ name: 'Team folder',
+ kind: 'directory',
+ version: 7,
+ },
+ items: [
+ {
+ resourceId: 'file-1',
+ rid: 'file-1',
+ gfsUri: 'gfs://main/file-1',
+ drive: 'main',
+ parentResourceId: 'folder-1',
+ name: 'report.txt',
+ kind: 'file',
+ path: '/report.txt',
+ version: 1,
+ bytes: 12,
+ },
+ ],
+ affordances: {
+ held: ['read', 'write'],
+ canDelegate: false,
+ grantableBits: [],
+ canCreateShare: false,
+ },
+ createFileFromPath,
+ })
+
+ renderFilesPage(pushToast)
+ fireEvent.drop(screen.getByRole('region', { name: 'Global File System browser' }), {
+ dataTransfer: {
+ dropEffect: 'none',
+ files: [
+ new File(['first'], 'report.txt', { type: 'text/plain' }),
+ new File(['second'], 'report.txt', { type: 'text/plain' }),
+ ],
+ types: ['Files'],
+ },
+ })
+
+ await waitFor(() => expect(createFileFromPath).toHaveBeenCalledTimes(2))
+ expect(createFileFromPath.mock.calls.map(call => call[1])).toEqual([
+ 'report (1).txt',
+ 'report (2).txt',
+ ])
+ expect(pushToast).toHaveBeenCalledWith('Uploaded report (1).txt', 'success')
+ expect(pushToast).toHaveBeenCalledWith('Uploaded report (2).txt', 'success')
+ })
+
+ it('adds a numbered suffix when a duplicate is selected with the upload picker', async () => {
+ const createFileFromPath = vi.fn(async () => undefined)
+ const pushToast = vi.fn()
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ current: {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder-1',
+ name: 'Team folder',
+ kind: 'directory',
+ version: 7,
+ },
+ items: [
+ {
+ resourceId: 'file-1',
+ rid: 'file-1',
+ gfsUri: 'gfs://main/file-1',
+ drive: 'main',
+ parentResourceId: 'folder-1',
+ name: 'report.txt',
+ kind: 'file',
+ path: '/report.txt',
+ version: 1,
+ bytes: 12,
+ },
+ ],
+ affordances: {
+ held: ['read', 'write'],
+ canDelegate: false,
+ grantableBits: [],
+ canCreateShare: false,
+ },
+ createFileFromPath,
+ })
+
+ renderFilesPage(pushToast)
+ fireEvent.change(screen.getByLabelText('Upload file'), {
+ target: { files: [new File(['report'], 'report.txt', { type: 'text/plain' })] },
+ })
+
+ await waitFor(() =>
+ expect(createFileFromPath).toHaveBeenCalledWith(
+ 'folder-1',
+ 'report (1).txt',
+ '/tmp/report.txt'
+ )
+ )
+ expect(pushToast).toHaveBeenCalledWith('Uploaded report (1).txt', 'success')
+ })
+
+ it('retries a stale duplicate conflict with the next available name', async () => {
+ const createFileFromPath = vi
+ .fn()
+ .mockRejectedValueOnce(
+ new Error(
+ "Error invoking remote method 'gfs:createFileFromPath': Error: 409 Conflict: [object Object]"
+ )
+ )
+ .mockResolvedValueOnce(undefined)
+ const pushToast = vi.fn()
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ current: {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder-1',
+ name: 'Team folder',
+ kind: 'directory',
+ version: 7,
+ },
+ affordances: {
+ held: ['read', 'write'],
+ canDelegate: false,
+ grantableBits: [],
+ canCreateShare: false,
+ },
+ createFileFromPath,
+ })
+
+ renderFilesPage(pushToast)
+ fireEvent.drop(screen.getByRole('region', { name: 'Global File System browser' }), {
+ dataTransfer: {
+ dropEffect: 'none',
+ files: [new File(['report'], 'report.txt', { type: 'text/plain' })],
+ types: ['Files'],
+ },
+ })
+
+ await waitFor(() => expect(createFileFromPath).toHaveBeenCalledTimes(2))
+ expect(createFileFromPath.mock.calls.map(call => call[1])).toEqual([
+ 'report.txt',
+ 'report (1).txt',
+ ])
+ expect(pushToast).toHaveBeenCalledWith('Uploaded report (1).txt', 'success')
+ expect(pushToast).not.toHaveBeenCalledWith(expect.stringContaining('409 Conflict'), 'error')
+ })
+
it('allows a Markdown drop to retry immediately after an upload failure', async () => {
const createFileFromPath = vi
.fn()