Skip to content

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

TypeScript

refactor(gfs): centralize upload collision policy

M3a504e6e326c
diff --git a/.github/workflows/build-publish.yml b/.github/workflows/build-publish.yml
index 974febe62..85b8d6409 100644
--- a/.github/workflows/build-publish.yml
+++ b/.github/workflows/build-publish.yml
@@ -130,6 +130,7 @@ jobs:
- 'packages/workflow-recipe-capability-policy/**'
- 'packages/display-field/**'
- 'packages/frontend-components/**'
+ - 'packages/gfs-interaction-policy/**'
external-rest-api:
- 'external-rest-api/**'
host-context-controller:
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.yml
index 293ca3c97..9d757e444 100644
--- a/.github/workflows/ci-public.yml
+++ b/.github/workflows/ci-public.yml
@@ -64,6 +64,7 @@ jobs:
- desktop-app
- mcp-servers
- packages/desktop-app-links
+ - packages/gfs-interaction-policy
- packages/workflow-runtime-core
- packages/workflow-sdk
- packages/network-policy-core
@@ -134,14 +135,15 @@ jobs:
# project and just prints its help text. Adding a strict root tsconfig surfaces
# ~10 pre-existing type errors in its __tests__ — worth fixing, but as its own
# change rather than smuggled into a CI-coverage PR.
- # network-policy-core is a hand-authored .cjs + .d.ts with no tsconfig, so
- # `tsc --noEmit` resolves no project (like mcp-servers). Its .d.ts is kept
- # aligned with the runtime by the "runtime exports stay aligned" node:test.
+ # network-policy-core and gfs-interaction-policy are hand-authored .cjs +
+ # .d.ts packages with no tsconfig, so
+ # `tsc --noEmit` resolves no project (like mcp-servers). Their declarations
+ # are kept aligned with runtime by "runtime exports stay aligned" node:tests.
# llm-provider-attempt-contract and codex-catalog-projection are the same
# shape: hand-authored .cjs + .d.ts, no tsconfig; node --test keeps the
# types aligned with the runtime.
- name: Typecheck (tsc --noEmit)
- if: matrix.service != 'mcp-servers' && matrix.service != 'packages/desktop-app-links' && matrix.service != 'packages/network-policy-core' && matrix.service != 'packages/llm-provider-attempt-contract' && matrix.service != 'packages/codex-catalog-projection'
+ if: matrix.service != 'mcp-servers' && matrix.service != 'packages/desktop-app-links' && matrix.service != 'packages/gfs-interaction-policy' && matrix.service != 'packages/network-policy-core' && matrix.service != 'packages/llm-provider-attempt-contract' && matrix.service != 'packages/codex-catalog-projection'
working-directory: ${{ matrix.service }}
run: npx tsc --noEmit
diff --git a/Makefile b/Makefile
index 4eea8240c..a3fb829c8 100644
--- a/Makefile
+++ b/Makefile
@@ -47,6 +47,7 @@ SERVICES := \
profile-ui \
mcp-servers \
packages/desktop-app-links \
+ packages/gfs-interaction-policy \
packages/workflow-runtime-core \
packages/workflow-sdk \
packages/llm-provider-attempt-contract
@@ -69,6 +70,7 @@ TEST_SERVICES := \
desktop-app \
mcp-servers \
packages/desktop-app-links \
+ packages/gfs-interaction-policy \
packages/workflow-runtime-core \
packages/workflow-sdk \
packages/network-policy-core \
diff --git a/control-ui/Dockerfile b/control-ui/Dockerfile
index 45fb8f9e4..4a817202b 100644
--- a/control-ui/Dockerfile
+++ b/control-ui/Dockerfile
@@ -9,6 +9,7 @@ ENV NEXT_PUBLIC_CLERUM_ENABLE_LOCAL_TEMPLATES=${NEXT_PUBLIC_CLERUM_ENABLE_LOCAL_
COPY packages/workflow-recipe-capability-policy ./packages/workflow-recipe-capability-policy
COPY packages/display-field ./packages/display-field
COPY packages/frontend-components ./packages/frontend-components
+COPY packages/gfs-interaction-policy ./packages/gfs-interaction-policy
COPY packages/llm-providers ./packages/llm-providers
COPY control-ui/package*.json ./control-ui/
WORKDIR /app/control-ui
@@ -24,7 +25,9 @@ RUN npm ci \
&& rm -rf node_modules/@clerum/display-field \
&& cp -R ../packages/display-field node_modules/@clerum/display-field \
&& rm -rf node_modules/@clerum/frontend-components \
- && cp -R ../packages/frontend-components node_modules/@clerum/frontend-components
+ && cp -R ../packages/frontend-components node_modules/@clerum/frontend-components \
+ && rm -rf node_modules/@clerum/gfs-interaction-policy \
+ && cp -R ../packages/gfs-interaction-policy node_modules/@clerum/gfs-interaction-policy
# Next type-checks the Playwright config, which imports this shared loader.
COPY scripts/qa-recorder /app/scripts/qa-recorder
diff --git a/control-ui/Dockerfile.dockerignore b/control-ui/Dockerfile.dockerignore
index 1c9d0ce35..22b974be2 100644
--- a/control-ui/Dockerfile.dockerignore
+++ b/control-ui/Dockerfile.dockerignore
@@ -10,6 +10,9 @@
!packages/frontend-components/src/index.tsx
!packages/frontend-components/styles.css
packages/frontend-components/node_modules/
+!packages/gfs-interaction-policy/
+!packages/gfs-interaction-policy/**
+packages/gfs-interaction-policy/node_modules/
!packages/llm-providers/
!packages/llm-providers/**
!scripts/
diff --git a/control-ui/app/globals.css b/control-ui/app/globals.css
index cc27cad8d..405c5c01a 100644
--- a/control-ui/app/globals.css
+++ b/control-ui/app/globals.css
@@ -13157,9 +13157,9 @@ button.cu-gfs-tree__button:focus-visible,
overflow: hidden;
margin: 0;
color: var(--cu-text);
- font-size: 1.25rem;
- font-weight: 600;
- line-height: 1.25;
+ font-size: var(--cu-font-size-2xl);
+ font-weight: var(--cu-font-weight-semibold);
+ line-height: var(--cu-line-height-tight);
text-overflow: ellipsis;
white-space: nowrap;
}
@@ -13192,7 +13192,7 @@ button.cu-gfs-tree__button:focus-visible,
gap: var(--cu-space-2);
padding: 0 var(--cu-space-5) var(--cu-space-3);
color: var(--cu-text-soft);
- font-size: 0.8125rem;
+ font-size: var(--cu-font-size-sm);
}
.cu-gfs-move-dialog__location-pill {
@@ -13217,7 +13217,7 @@ button.cu-gfs-tree__button:focus-visible,
.cu-gfs-move-dialog__location-pill strong {
min-width: 0;
overflow: hidden;
- font-weight: 500;
+ font-weight: var(--cu-font-weight-medium);
text-overflow: ellipsis;
white-space: nowrap;
}
@@ -13234,8 +13234,8 @@ button.cu-gfs-tree__button:focus-visible,
border-top: 1px solid var(--cu-border-subtle);
border-bottom: 1px solid var(--cu-border-subtle);
color: var(--cu-text);
- font-size: 0.8125rem;
- font-weight: 600;
+ font-size: var(--cu-font-size-sm);
+ font-weight: var(--cu-font-weight-semibold);
}
.cu-gfs-move-dialog__tree {
@@ -13344,8 +13344,8 @@ button.cu-gfs-tree__button:focus-visible,
min-width: 0;
flex: 1 1 auto;
overflow: hidden;
- font-size: 0.8125rem;
- font-weight: 500;
+ font-size: var(--cu-font-size-sm);
+ font-weight: var(--cu-font-weight-medium);
text-overflow: ellipsis;
white-space: nowrap;
}
@@ -13373,7 +13373,7 @@ button.cu-gfs-tree__button:focus-visible,
.cu-gfs-move-dialog__notice {
margin: var(--cu-space-2);
color: var(--cu-text-soft);
- font-size: 0.8125rem;
+ font-size: var(--cu-font-size-sm);
}
.cu-gfs-move-dialog__load-more.cu-btn {
@@ -13396,14 +13396,14 @@ button.cu-gfs-tree__button:focus-visible,
flex: 1 1 auto;
overflow: hidden;
color: var(--cu-text-soft);
- font-size: 0.8125rem;
+ font-size: var(--cu-font-size-sm);
text-overflow: ellipsis;
white-space: nowrap;
}
.cu-gfs-move-dialog__selection strong {
color: var(--cu-text);
- font-weight: 600;
+ font-weight: var(--cu-font-weight-semibold);
}
.cu-gfs-move-dialog__actions {
diff --git a/control-ui/components/GfsBrowser.tsx b/control-ui/components/GfsBrowser.tsx
index bf50de102..ed4dbaa6c 100644
--- a/control-ui/components/GfsBrowser.tsx
+++ b/control-ui/components/GfsBrowser.tsx
@@ -1,6 +1,13 @@
'use client'
import React, { useCallback, useEffect, useRef, useState } from 'react'
+import {
+ GFS_UPLOAD_NAME_EXHAUSTED_MESSAGE,
+ GFS_UPLOAD_NAME_RETRY_LIMIT,
+ createGfsUploadNameReservationBook,
+ gfsUploadNameRetryDecision,
+ normalizeGfsResourceName,
+} from '@clerum/gfs-interaction-policy'
import { FileUploadModal } from '@components/FileUploadModal'
import { GfsImagePreview } from '@components/GfsImagePreview'
import { GfsMarkdownPreview } from '@components/GfsMarkdownPreview'
@@ -37,7 +44,6 @@ import {
} from '@lib/gfsFileUpload'
import { gfsImagePreviewMimeType } from '@lib/gfsImagePreview'
import { isGfsMarkdownPreviewFile } from '@lib/gfsMarkdownPreview'
-import { nextAvailableGfsResourceName, normalizeGfsResourceName } from '@lib/gfsResourceName'
import { isGfsVideoFile } from '@lib/gfsVideoFile'
import { gfsVideoPreviewMimeType } from '@lib/gfsVideoPreview'
import { GfsGrantPanel } from './GfsGrantPanel'
@@ -195,38 +201,6 @@ function isEventFromNestedInteractive(
)
}
-function isGfsNameConflict(error: unknown): boolean {
- const details =
- error && typeof error === 'object'
- ? (error as {
- status?: unknown
- bodyText?: unknown
- message?: unknown
- code?: 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, details.code].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
-
export function GfsBrowser(): React.JSX.Element {
const { showToast } = useToast()
const [crumbs, setCrumbs] = useState<Crumb[]>([{ id: null, rid: null, name: '/' }])
@@ -250,7 +224,7 @@ export function GfsBrowser(): React.JSX.Element {
const [uploadCandidate, setUploadCandidate] = useState<File | null>(null)
const [uploading, setUploading] = useState(false)
const uploadJobRef = useRef<GfsUploadJob | null>(null)
- const uploadNameReservationsRef = useRef(new Map<string, Set<string>>())
+ const uploadNameReservationsRef = useRef(createGfsUploadNameReservationBook())
const [uploadSnapshot, setUploadSnapshot] = useState<GfsUploadJobSnapshot | null>(null)
const [dragActive, setDragActive] = useState(false)
const [droppedUploadCount, setDroppedUploadCount] = useState(0)
@@ -777,7 +751,6 @@ export function GfsBrowser(): React.JSX.Element {
const rid = current?.rid ?? (current?.id ? ridOfResourceId(current.id) : null)
if (!rid || !file) return
setUploading(true)
- const attemptedNames = new Set<string>()
let resumeUploadId: string | undefined
let legacyFallbackAnnounced = false
try {
@@ -785,105 +758,107 @@ export function GfsBrowser(): React.JSX.Element {
const normalizedName = await normalizeGfsResourceName(file.name)
const target = { operation: 'create' as const, parentRid: rid }
resumeUploadId = matchingPendingResumeUploadId(file, target, normalizedName)
+ const nameReservation = uploadNameReservationsRef.current.begin(
+ rid,
+ normalizedName,
+ occupiedNames
+ )
+ try {
+ for (let attempt = 0; attempt < GFS_UPLOAD_NAME_RETRY_LIMIT; attempt += 1) {
+ const resumeUploadIdForAttempt = attempt === 0 ? resumeUploadId : undefined
+ const name = nameReservation.reserveNext({ exact: Boolean(resumeUploadIdForAttempt) })
- for (let attempt = 0; attempt < GFS_UPLOAD_NAME_RETRY_LIMIT; attempt += 1) {
- const reservations = uploadNameReservationsRef.current.get(rid) ?? new Set<string>()
- uploadNameReservationsRef.current.set(rid, reservations)
- const name = resumeUploadId
- ? normalizedName
- : nextAvailableGfsResourceName(normalizedName, [...occupiedNames, ...reservations])
- reservations.add(name)
- attemptedNames.add(name)
- const resumeUploadIdForAttempt = attempt === 0 ? resumeUploadId : undefined
-
- try {
try {
- const job = createGfsUploadJob({
- file,
- name,
- target,
- resumeUploadId: resumeUploadIdForAttempt,
- onPersistPending: record => {
- persistPendingGfsUpload({
- idempotencyKey: record.idempotencyKey,
- fileName: record.fileName,
- fileSize: record.fileSize,
- lastModified: record.lastModified,
- target: record.target,
- name: record.name,
- })
- },
- onProgress: progress => mergeUploadProgress(progress.uploadedBytes),
- onState: snapshot => mergeUploadSnapshot(snapshot),
- onPersist: record => {
- persistPendingGfsUpload({
- uploadId: record.uploadId,
- fileName: record.fileName,
- fileSize: record.fileSize,
- lastModified: record.lastModified,
- target: record.target,
- name: record.name,
- })
- },
- onClearPersisted: uploadId => clearPendingGfsUpload(uploadId),
- })
- uploadJobRef.current = job
- const receipt = await job.start()
- if (receipt.state === 'paused') {
- setUploading(false)
- return
- }
- } catch (err) {
- if (!(err instanceof GfsUploadCapabilityError) || !err.allowLegacyFallback) throw err
- if (resumeUploadIdForAttempt) {
- throw new GfsUploadCapabilityError(
- 'The persisted resumable session cannot be resumed while GFS Upload v2 is unavailable.',
- { cause: err }
- )
- }
- if (!legacyFallbackAnnounced) {
- showToast('Resumable upload is unavailable; using the legacy 16 MiB path.', {
- tone: 'info',
+ try {
+ const job = createGfsUploadJob({
+ file,
+ name,
+ target,
+ resumeUploadId: resumeUploadIdForAttempt,
+ onPersistPending: record => {
+ persistPendingGfsUpload({
+ idempotencyKey: record.idempotencyKey,
+ fileName: record.fileName,
+ fileSize: record.fileSize,
+ lastModified: record.lastModified,
+ target: record.target,
+ name: record.name,
+ })
+ },
+ onProgress: progress => mergeUploadProgress(progress.uploadedBytes),
+ onState: snapshot => mergeUploadSnapshot(snapshot),
+ onPersist: record => {
+ persistPendingGfsUpload({
+ uploadId: record.uploadId,
+ fileName: record.fileName,
+ fileSize: record.fileSize,
+ lastModified: record.lastModified,
+ target: record.target,
+ name: record.name,
+ })
+ },
+ onClearPersisted: uploadId => clearPendingGfsUpload(uploadId),
})
- legacyFallbackAnnounced = true
+ uploadJobRef.current = job
+ const receipt = await job.start()
+ if (receipt.state === 'paused') {
+ setUploading(false)
+ return
+ }
+ } catch (err) {
+ if (!(err instanceof GfsUploadCapabilityError) || !err.allowLegacyFallback) throw err
+ if (resumeUploadIdForAttempt) {
+ throw new GfsUploadCapabilityError(
+ 'The persisted resumable session cannot be resumed while GFS Upload v2 is unavailable.',
+ { cause: err }
+ )
+ }
+ if (!legacyFallbackAnnounced) {
+ showToast('Resumable upload is unavailable; using the legacy 16 MiB path.', {
+ tone: 'info',
+ })
+ legacyFallbackAnnounced = true
+ }
+ await uploadGfsFileLegacy({ file, name, target })
+ clearPendingGfsUpload()
+ setUploadCandidate(null)
+ setUploadOpen(false)
+ setUploadSnapshot(null)
+ uploadJobRef.current = null
}
- await uploadGfsFileLegacy({ file, name, target })
- clearPendingGfsUpload()
+
+ nameReservation.markSuccess(name)
+ showToast('File uploaded.', { tone: 'success' })
setUploadCandidate(null)
setUploadOpen(false)
setUploadSnapshot(null)
uploadJobRef.current = null
- }
+ await refreshCurrent()
+ return
+ } catch (err) {
+ if (uploadJobRef.current?.snapshot().state === 'aborted') return
+ const decision = gfsUploadNameRetryDecision(err, {
+ attempt,
+ resuming: Boolean(resumeUploadIdForAttempt),
+ })
+ if (decision === 'terminal') throw err
- occupiedNames.add(name)
- showToast('File uploaded.', { tone: 'success' })
- setUploadCandidate(null)
- setUploadOpen(false)
- setUploadSnapshot(null)
- uploadJobRef.current = null
- await refreshCurrent()
- return
- } catch (err) {
- if (uploadJobRef.current?.snapshot().state === 'aborted') return
- if (!resumeUploadIdForAttempt && isGfsNameConflict(err)) {
- occupiedNames.add(name)
+ nameReservation.markConflict(name)
clearPendingGfsUpload()
uploadJobRef.current = null
setUploadSnapshot(null)
- continue
+ if (decision === 'exhausted') throw new Error(GFS_UPLOAD_NAME_EXHAUSTED_MESSAGE)
}
- throw err
}
- }
- throw new Error('Could not create a unique GFS resource name.')
+ throw new Error(GFS_UPLOAD_NAME_EXHAUSTED_MESSAGE)
+ } finally {
+ nameReservation.release()
+ }
} catch (err) {
if (uploadJobRef.current?.snapshot().state === 'aborted') return
showToast(err instanceof Error ? err.message : 'Could not upload file.', { tone: 'error' })
} finally {
- const reservations = uploadNameReservationsRef.current.get(rid)
- for (const name of attemptedNames) reservations?.delete(name)
- if (reservations?.size === 0) uploadNameReservationsRef.current.delete(rid)
setUploading(false)
}
}
diff --git a/control-ui/components/GfsMoveDialog/index.tsx b/control-ui/components/GfsMoveDialog/index.tsx
index 4f7b1f456..a10d77091 100644
--- a/control-ui/components/GfsMoveDialog/index.tsx
+++ b/control-ui/components/GfsMoveDialog/index.tsx
@@ -5,38 +5,17 @@ import { IconFolder } from '@components/Sidebar/icons'
import { IconCheck, IconChevronRight, IconX } from '@components/icons'
import { Button } from '@components/ui'
import { apiGet } from '@lib/api'
+import type {
+ GfsMoveDialogProps,
+ MoveFolder,
+ MoveTreeFolderProps,
+ MoveTreePage,
+ SelectedMoveDestination,
+} from './types'
-const DRIVE = 'main'
-
-type MoveFolder = {
- resourceId: string
- name: string
- kind: string
- /** Present on browser rows — used to refuse a no-op move into the folder
- * that already contains the target. */
- parentResourceId?: string | null
-}
-
-type MoveCrumb = {
- id: string | null
- name: string
-}
-
-type TreePage = {
- rootResourceId?: string
- items: MoveFolder[]
- nextCursor: string | null
-}
-
-type SelectedDestination = Pick<MoveFolder, 'resourceId' | 'name'>
+export type { GfsMoveDialogProps } from './types'
-export type GfsMoveDialogProps = {
- target: MoveFolder
- initialCrumbs: MoveCrumb[]
- busy?: boolean
- onClose: () => void
- onMove: (destinationId: string, destinationName: string) => Promise<void>
-}
+const DRIVE = 'main'
function foldersOnly(items: MoveFolder[], excludedIds: ReadonlySet<string>): MoveFolder[] {
return items
@@ -48,17 +27,6 @@ function messageOf(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
-type TreeFolderProps = {
- ancestors: ReadonlySet<string>
- expandedIds: ReadonlySet<string>
- folder: MoveFolder
- level: number
- selected: SelectedDestination | null
- targetId: string
- onSelect: (folder: MoveFolder) => void
- onToggle: (folderId: string) => void
-}
-
function TreeFolder({
ancestors,
expandedIds,
@@ -68,7 +36,7 @@ function TreeFolder({
targetId,
onSelect,
onToggle,
-}: TreeFolderProps) {
+}: MoveTreeFolderProps) {
const expanded = expandedIds.has(folder.resourceId)
const [children, setChildren] = useState<MoveFolder[]>([])
const [nextCursor, setNextCursor] = useState<string | null>(null)
@@ -95,7 +63,7 @@ function TreeFolder({
const page = (await apiGet(
`/api/v1/gfs/resources/${encodeURIComponent(folder.resourceId)}/children`,
query
- )) as TreePage
+ )) as MoveTreePage
setChildren(previous => (cursor ? [...previous, ...page.items] : page.items))
setNextCursor(page.nextCursor)
setLoaded(true)
@@ -217,7 +185,7 @@ export function GfsMoveDialog({
? DRIVE
: currentParent.name
: null
- const [selected, setSelected] = useState<SelectedDestination | null>(null)
+ const [selected, setSelected] = useState<SelectedMoveDestination | null>(null)
const [expandedIds, setExpandedIds] = useState<Set<string>>(
() => new Set(initialCrumbs.flatMap(crumb => (crumb.id ? [crumb.id] : [])))
)
@@ -234,7 +202,7 @@ export function GfsMoveDialog({
try {
const query: Record<string, string> = { drive: DRIVE }
if (cursor) query.cursor = cursor
- const page = (await apiGet('/api/v1/gfs/tree', query)) as TreePage
+ const page = (await apiGet('/api/v1/gfs/tree', query)) as MoveTreePage
setRootFolders(previous => (cursor ? [...previous, ...page.items] : page.items))
if (page.rootResourceId) setRootResourceId(page.rootResourceId)
setNextCursor(page.nextCursor)
diff --git a/control-ui/components/GfsMoveDialog/types.ts b/control-ui/components/GfsMoveDialog/types.ts
new file mode 100644
index 000000000..3828da484
--- /dev/null
+++ b/control-ui/components/GfsMoveDialog/types.ts
@@ -0,0 +1,39 @@
+export type MoveFolder = {
+ resourceId: string
+ name: string
+ kind: string
+ /** Present on browser rows so a no-op move to the current parent is refused. */
+ parentResourceId?: string | null
+}
+
+export type MoveCrumb = {
+ id: string | null
+ name: string
+}
+
+export type MoveTreePage = {
+ rootResourceId?: string
+ items: MoveFolder[]
+ nextCursor: string | null
+}
+
+export type SelectedMoveDestination = Pick<MoveFolder, 'resourceId' | 'name'>
+
+export type GfsMoveDialogProps = {
+ target: MoveFolder
+ initialCrumbs: MoveCrumb[]
+ busy?: boolean
+ onClose: () => void
+ onMove: (destinationId: string, destinationName: string) => Promise<void>
+}
+
+export type MoveTreeFolderProps = {
+ ancestors: ReadonlySet<string>
+ expandedIds: ReadonlySet<string>
+ folder: MoveFolder
+ level: number
+ selected: SelectedMoveDestination | null
+ targetId: string
+ onSelect: (folder: MoveFolder) => void
+ onToggle: (folderId: string) => void
+}
diff --git a/control-ui/components/__tests__/GfsBrowser.test.tsx b/control-ui/components/__tests__/GfsBrowser.test.tsx
index 8c0a4055e..0831f569c 100644
--- a/control-ui/components/__tests__/GfsBrowser.test.tsx
+++ b/control-ui/components/__tests__/GfsBrowser.test.tsx
@@ -1,5 +1,6 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import { normalizeGfsResourceName } from '@clerum/gfs-interaction-policy'
import { GFS_FILE_UPLOAD_PROTOCOL_MAX_BYTES } from '@constants/gfsFileUpload'
import { GFS_IMAGE_PREVIEW_MAX_BYTES } from '@constants/gfsImagePreview'
import { GFS_MARKDOWN_PREVIEW_MAX_BYTES } from '@constants/gfsMarkdownPreview'
@@ -22,7 +23,6 @@ import {
normalizeUploadProductMaxBytes,
uploadGfsFile,
} from '@lib/gfsFileUpload'
-import { normalizeGfsResourceName } from '@lib/gfsResourceName'
import { GfsBrowser } from '../GfsBrowser'
import { ToastProvider } from '../Toast'
@@ -139,7 +139,24 @@ describe('GfsBrowser', () => {
mockPutGfsGrant.mockReset()
mockGfsDownload.mockReset()
mockGfsFetchFileBlob.mockReset()
- mockCreateGfsUploadJob.mockClear()
+ mockCreateGfsUploadJob.mockReset()
+ mockCreateGfsUploadJob.mockImplementation(
+ (input: { file: File; onState?: (snapshot: unknown) => void }) => ({
+ start: vi.fn(async () => {
+ input.onState?.({
+ state: 'completed',
+ session: { uploadId: 'test-upload', state: 'completed' },
+ uploadedBytes: input.file.size,
+ totalBytes: input.file.size,
+ })
+ return { state: 'completed', uploadId: 'test-upload' }
+ }),
+ pause: vi.fn(),
+ resume: vi.fn(),
+ cancel: vi.fn(),
+ snapshot: vi.fn(() => ({ state: 'failed' })),
+ })
+ )
mockUploadGfsFile.mockReset()
window.localStorage.clear()
mockUploadGfsFile.mockImplementation(async ({ file }: { file: File }) => {
@@ -182,6 +199,10 @@ describe('GfsBrowser', () => {
mockGetGfsShares.mockResolvedValue({ items: [] })
})
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ })
+
it('loads the root tree and renders directories + files', async () => {
mockApiGet.mockResolvedValueOnce({
items: [child('org', 'directory', 1), child('readme.md', 'file', 2)],
@@ -525,11 +546,119 @@ describe('GfsBrowser', () => {
})
})
- it('retries a stale duplicate conflict with the next available name', async () => {
+ it('retries the real Upload v2 409 producer error with the next available name', async () => {
const rootId = '11111111-1111-1111-1111-111111111111'
const rootRid = '11111111111111111111111111111111'
mockApiGet.mockResolvedValue({ rootResourceId: rootId, items: [], nextCursor: null })
- const failedJob = {
+ const actualUpload =
+ await vi.importActual<typeof import('@lib/gfsFileUpload')>('@lib/gfsFileUpload')
+ const producerErrors: unknown[] = []
+ const uploadNames: string[] = []
+ const session = {
+ uploadId: 'producer-upload',
+ drive: 'main',
+ operation: 'create' as const,
+ expectedBytes: 0,
+ partBytes: 1,
+ partCount: 0,
+ state: 'initiated',
+ committedBytes: 0,
+ committedPartCount: 0,
+ activePartCount: 0,
+ }
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input)
+ const method = init?.method ?? 'GET'
+ if (url.endsWith('/api/v1/gfs/proxy/v1/capabilities')) {
+ return new Response(
+ JSON.stringify({
+ upload: {
+ resumableV2: {
+ enabled: true,
+ maxFileBytes: GFS_FILE_UPLOAD_PROTOCOL_MAX_BYTES,
+ preferredChunkBytes: 1,
+ maxChunkBytes: 1,
+ },
+ },
+ }),
+ { status: 200 }
+ )
+ }
+ if (method === 'POST' && url.endsWith('/api/v1/gfs/proxy/v1/uploads')) {
+ const body = JSON.parse(String(init?.body)) as { name: string }
+ uploadNames.push(body.name)
+ if (uploadNames.length === 1) {
+ return new Response(
+ JSON.stringify({
+ ok: false,
+ error: { code: 'conflict', message: 'resource already exists' },
+ }),
+ { status: 409, statusText: 'Conflict' }
+ )
+ }
+ return new Response(JSON.stringify({ ok: true, data: session }), { status: 201 })
+ }
+ if (
+ method === 'POST' &&
+ url.endsWith(`/api/v1/gfs/proxy/v1/uploads/${session.uploadId}/complete`)
+ ) {
+ return new Response(
+ JSON.stringify({ ok: true, data: { ...session, state: 'completed' } }),
+ { status: 200 }
+ )
+ }
+ throw new Error(`Unexpected producer request: ${method} ${url}`)
+ })
+ vi.stubGlobal('fetch', fetchMock)
+ mockCreateGfsUploadJob.mockImplementation(input => {
+ const job = actualUpload.createGfsUploadJob(input)
+ return {
+ start: async () => {
+ try {
+ return await job.start()
+ } catch (error) {
+ producerErrors.push(error)
+ throw error
+ }
+ },
+ pause: job.pause.bind(job),
+ resume: job.resume.bind(job),
+ cancel: job.cancel.bind(job),
+ snapshot: job.snapshot.bind(job),
+ }
+ })
+ renderBrowser()
+ await screen.findByText('No resources are visible in this folder.')
+
+ fireEvent.click(screen.getByRole('button', { name: /upload file/i }))
+ const uploadDialog = await screen.findByRole('dialog', { name: 'Upload file' })
+ fireEvent.change(within(uploadDialog).getByLabelText('Choose file to upload'), {
+ target: { files: [new File([], 'report.txt', { type: 'text/plain' })] },
+ })
+ fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Upload' }))
+
+ await waitFor(() => {
+ expect(uploadNames).toEqual(['report.txt', 'report (1).txt'])
+ })
+ const conflict = producerErrors[0] as Error & { status?: number; code?: string }
+ expect(conflict).toBeInstanceOf(Error)
+ expect(conflict.message).toBe('409 resource already exists')
+ expect(conflict.status).toBe(409)
+ expect(conflict.code).toBe('conflict')
+ expect(mockCreateGfsUploadJob).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ name: 'report (1).txt',
+ target: { operation: 'create', parentRid: rootRid },
+ })
+ )
+ await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Upload file' })).toBeNull())
+ })
+
+ it('keeps the legacy Electron conflict string as a separate compatibility path', async () => {
+ const rootId = '11111111-1111-1111-1111-111111111111'
+ mockApiGet.mockResolvedValue({ rootResourceId: rootId, items: [], nextCursor: null })
+ mockCreateGfsUploadJob.mockImplementationOnce(() => ({
start: vi
.fn()
.mockRejectedValue(
@@ -541,8 +670,7 @@ describe('GfsBrowser', () => {
resume: vi.fn(),
cancel: vi.fn(),
snapshot: vi.fn(() => ({ state: 'failed' })),
- }
- mockCreateGfsUploadJob.mockImplementationOnce(() => failedJob)
+ }))
renderBrowser()
await screen.findByText('No resources are visible in this folder.')
@@ -554,20 +682,11 @@ describe('GfsBrowser', () => {
fireEvent.click(within(uploadDialog).getByRole('button', { name: 'Upload' }))
await waitFor(() => {
- expect(mockCreateGfsUploadJob).toHaveBeenCalledTimes(2)
- expect(mockCreateGfsUploadJob).toHaveBeenNthCalledWith(
- 1,
- expect.objectContaining({ name: 'report.txt' })
- )
expect(mockCreateGfsUploadJob).toHaveBeenNthCalledWith(
2,
- expect.objectContaining({
- name: 'report (1).txt',
- target: { operation: 'create', parentRid: rootRid },
- })
+ expect.objectContaining({ name: 'report (1).txt' })
)
})
- await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Upload file' })).toBeNull())
})
it('moves a dragged file into a visible folder without treating it as an upload', async () => {
diff --git a/control-ui/e2e/support/gfs-resource-crud-journey.test.ts b/control-ui/e2e/support/gfs-resource-crud-journey.test.ts
index 079920978..18828ba8a 100644
--- a/control-ui/e2e/support/gfs-resource-crud-journey.test.ts
+++ b/control-ui/e2e/support/gfs-resource-crud-journey.test.ts
@@ -1,6 +1,9 @@
import { type Locator, type Page, expect, test } from '@playwright/test'
+import {
+ GFS_RESOURCE_NAME_MAX_LENGTH,
+ normalizeGfsResourceName,
+} from '@clerum/gfs-interaction-policy'
import { getGfsChildResourceSummary, uniqueGfsFixtureName } from '../../../tests/e2e/gfsUiFixtures'
-import { GFS_RESOURCE_NAME_MAX_LENGTH, normalizeGfsResourceName } from '../../lib/gfsResourceName'
type GfsCrudFixture = {
childName: string
diff --git a/control-ui/lib/__tests__/gfsResourceName.test.ts b/control-ui/lib/__tests__/gfsResourceName.test.ts
index e87b85c5b..90b575f94 100644
--- a/control-ui/lib/__tests__/gfsResourceName.test.ts
+++ b/control-ui/lib/__tests__/gfsResourceName.test.ts
@@ -4,7 +4,7 @@ import {
GFS_RESOURCE_NAME_MAX_LENGTH,
nextAvailableGfsResourceName,
normalizeGfsResourceName,
-} from '../gfsResourceName'
+} from '@clerum/gfs-interaction-policy'
const HASH_LENGTH = 12
const EXTENSION_MAX_LENGTH = 48
diff --git a/control-ui/lib/gfsResourceName.ts b/control-ui/lib/gfsResourceName.ts
deleted file mode 100644
index e4897b3c3..000000000
--- a/control-ui/lib/gfsResourceName.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-export const GFS_RESOURCE_NAME_MAX_LENGTH = 255
-const GFS_RESOURCE_NAME_HASH_LENGTH = 12
-const GFS_RESOURCE_EXTENSION_MAX_LENGTH = 48
-
-async function sha256Hex(value: string): Promise<string> {
- const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value))
- return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('')
-}
-
-function extensionOf(name: string): string {
- const lastDot = name.lastIndexOf('.')
- if (lastDot <= 0 || lastDot === name.length - 1) return ''
- const extension = name.slice(lastDot)
- 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.
- * Precondition: `name` has already passed through 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)) {
- throw new Error('File and folder names cannot contain path separators or control characters.')
- }
- if (normalized.length <= GFS_RESOURCE_NAME_MAX_LENGTH) return normalized
-
- const extension = extensionOf(normalized)
- 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 safeBase = truncatedBaseForSuffix(base, suffix)
-
- return `${safeBase}${suffix}`
-}
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 72a2f6ee1..278b18084 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,15 +1,16 @@
{
"name": "clerum-control-ui",
- "version": "0.1.565",
+ "version": "0.1.566",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.565",
+ "version": "0.1.566",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/frontend-components": "file:../packages/frontend-components",
+ "@clerum/gfs-interaction-policy": "file:../packages/gfs-interaction-policy",
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",
"@uiw/react-md-editor": "^4.1.0",
@@ -46,6 +47,11 @@
"react-dom": "^18.3.1"
}
},
+ "../packages/gfs-interaction-policy": {
+ "name": "@clerum/gfs-interaction-policy",
+ "version": "0.1.0",
+ "license": "MIT"
+ },
"../packages/llm-providers": {
"name": "@clerum/llm-providers",
"version": "0.1.0",
@@ -175,6 +181,10 @@
"resolved": "../packages/frontend-components",
"link": true
},
+ "node_modules/@clerum/gfs-interaction-policy": {
+ "resolved": "../packages/gfs-interaction-policy",
+ "link": true
+ },
"node_modules/@clerum/llm-providers": {
"resolved": "../packages/llm-providers",
"link": true
diff --git a/control-ui/package.json b/control-ui/package.json
index 82f1c7427..88d785988 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.565",
+ "version": "0.1.566",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
@@ -64,6 +64,7 @@
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/frontend-components": "file:../packages/frontend-components",
+ "@clerum/gfs-interaction-policy": "file:../packages/gfs-interaction-policy",
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",
"@uiw/react-md-editor": "^4.1.0",
diff --git a/deploy/images.json b/deploy/images.json
index 3063bccd3..3286b1a23 100644
--- a/deploy/images.json
+++ b/deploy/images.json
@@ -37,7 +37,8 @@
"control-ui/**",
"packages/workflow-recipe-capability-policy/**",
"packages/display-field/**",
- "packages/frontend-components/**"
+ "packages/frontend-components/**",
+ "packages/gfs-interaction-policy/**"
],
"published": true,
"deployed_to_minikube": true
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index a4b05946a..2f618f0fa 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -10,6 +10,7 @@
"license": "MPL-2.0",
"dependencies": {
"@clerum/desktop-app-links": "file:../packages/desktop-app-links",
+ "@clerum/gfs-interaction-policy": "file:../packages/gfs-interaction-policy",
"@tanstack/react-query": "5.100.10",
"hast-util-to-jsx-runtime": "^2.3.6",
"js-yaml": "^4.1.1",
@@ -59,6 +60,11 @@
"fast-check": "^4.9.0"
}
},
+ "../packages/gfs-interaction-policy": {
+ "name": "@clerum/gfs-interaction-policy",
+ "version": "0.1.0",
+ "license": "MIT"
+ },
"node_modules/@adobe/css-tools": {
"version": "4.4.4",
"resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.4.tgz",
@@ -414,6 +420,10 @@
"resolved": "../packages/desktop-app-links",
"link": true
},
+ "node_modules/@clerum/gfs-interaction-policy": {
+ "resolved": "../packages/gfs-interaction-policy",
+ "link": true
+ },
"node_modules/@csstools/color-helpers": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.0.2.tgz",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index 93bb96dfd..5f8a4fa8b 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -46,6 +46,7 @@
},
"dependencies": {
"@clerum/desktop-app-links": "file:../packages/desktop-app-links",
+ "@clerum/gfs-interaction-policy": "file:../packages/gfs-interaction-policy",
"@tanstack/react-query": "5.100.10",
"hast-util-to-jsx-runtime": "^2.3.6",
"js-yaml": "^4.1.1",
diff --git a/desktop-app/ui/src/gfs/__tests__/resourceName.test.ts b/desktop-app/ui/src/gfs/__tests__/resourceName.test.ts
index 984845209..4f810938d 100644
--- a/desktop-app/ui/src/gfs/__tests__/resourceName.test.ts
+++ b/desktop-app/ui/src/gfs/__tests__/resourceName.test.ts
@@ -4,7 +4,7 @@ import {
GFS_RESOURCE_NAME_MAX_LENGTH,
nextAvailableGfsResourceName,
normalizeGfsResourceName,
-} from '../resourceName'
+} from '@clerum/gfs-interaction-policy'
const HASH_LENGTH = 12
const EXTENSION_MAX_LENGTH = 48
diff --git a/desktop-app/ui/src/gfs/resourceName.ts b/desktop-app/ui/src/gfs/resourceName.ts
deleted file mode 100644
index e4897b3c3..000000000
--- a/desktop-app/ui/src/gfs/resourceName.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-export const GFS_RESOURCE_NAME_MAX_LENGTH = 255
-const GFS_RESOURCE_NAME_HASH_LENGTH = 12
-const GFS_RESOURCE_EXTENSION_MAX_LENGTH = 48
-
-async function sha256Hex(value: string): Promise<string> {
- const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value))
- return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('')
-}
-
-function extensionOf(name: string): string {
- const lastDot = name.lastIndexOf('.')
- if (lastDot <= 0 || lastDot === name.length - 1) return ''
- const extension = name.slice(lastDot)
- 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.
- * Precondition: `name` has already passed through 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)) {
- throw new Error('File and folder names cannot contain path separators or control characters.')
- }
- if (normalized.length <= GFS_RESOURCE_NAME_MAX_LENGTH) return normalized
-
- const extension = extensionOf(normalized)
- 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 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 90cc3181b..7b8c38569 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -8,6 +8,13 @@ import {
useState,
} from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
+import {
+ GFS_UPLOAD_NAME_EXHAUSTED_MESSAGE,
+ GFS_UPLOAD_NAME_RETRY_LIMIT,
+ createGfsUploadNameReservationBook,
+ gfsUploadNameRetryDecision,
+ normalizeGfsResourceName,
+} from '@clerum/gfs-interaction-policy'
import { Badge, Button, EmptyState, IconButton, StatusBanner, TextInput } from '@components/Common'
import { ConfirmDialog } from '@components/ConfirmDialog'
import { GfsFileIcon } from '@components/GfsFileIcon'
@@ -46,7 +53,6 @@ import {
} from '@/gfs/delegation'
import { GfsFilePicker } from '@/gfs/filePicker'
import { GfsMoveDialog } from '@/gfs/moveDialog'
-import { nextAvailableGfsResourceName, normalizeGfsResourceName } from '@/gfs/resourceName'
import type { TeamDirectoryResult } from '../../../src/types'
import type {
FilesPageProps,
@@ -126,37 +132,6 @@ 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
@@ -262,7 +237,7 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
const dragSessionRef = useRef(0)
const manageReturnCrumbsRef = useRef<GfsCrumb[] | null>(null)
const uploadInputRef = useRef<HTMLInputElement | null>(null)
- const uploadNameReservationsRef = useRef(new Map<string, Set<string>>())
+ const uploadNameReservationsRef = useRef(createGfsUploadNameReservationBook())
const createFolderTitleId = useId()
const createFolderDescriptionId = useId()
const createFolderInputId = useId()
@@ -652,43 +627,41 @@ export function FilesPage({ pushToast, pendingGfsUri, onPendingGfsUriHandled }:
occupiedNames = new Set(items.map(item => item.name))
) => {
if (!file || !parentResourceId) return
- const attemptedNames = new Set<string>()
try {
assertGfsFileUploadSize(file.size)
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')
-
- 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)
+ const nameReservation = uploadNameReservationsRef.current.begin(
+ parentResourceId,
+ normalizedName,
+ occupiedNames
+ )
+ try {
+ for (let attempt = 0; attempt < GFS_UPLOAD_NAME_RETRY_LIMIT; attempt += 1) {
+ const name = nameReservation.reserveNext()
+
+ try {
+ await ctrl.createFileFromPath(parentResourceId, name, filePath)
+ nameReservation.markSuccess(name)
+ pushToast?.(`Uploaded ${name}`, 'success')
+ return
+ } catch (uploadError) {
+ const decision = gfsUploadNameRetryDecision(uploadError, { attempt })
+ if (decision === 'terminal') throw uploadError
+
+ nameReservation.markConflict(name)
+ if (decision === 'exhausted') throw new Error(GFS_UPLOAD_NAME_EXHAUSTED_MESSAGE)
+ }
}
- }
- throw new Error('Could not create a unique GFS resource name.')
+ throw new Error(GFS_UPLOAD_NAME_EXHAUSTED_MESSAGE)
+ } finally {
+ nameReservation.release()
+ }
} 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)
}
}
diff --git a/packages/gfs-interaction-policy/index.cjs b/packages/gfs-interaction-policy/index.cjs
new file mode 100644
index 000000000..b206858c0
--- /dev/null
+++ b/packages/gfs-interaction-policy/index.cjs
@@ -0,0 +1,190 @@
+'use strict'
+
+/**
+ * Pure, browser-safe GFS interaction policy shared by Control UI and Desktop.
+ * This module owns product decisions only: transports and presentation remain
+ * inside each application.
+ */
+
+const GFS_RESOURCE_NAME_MAX_LENGTH = 255
+const GFS_RESOURCE_NAME_HASH_LENGTH = 12
+const GFS_RESOURCE_EXTENSION_MAX_LENGTH = 48
+const GFS_UPLOAD_NAME_RETRY_LIMIT = 100
+const GFS_UPLOAD_NAME_EXHAUSTED_MESSAGE = 'Could not create a unique GFS resource name.'
+
+function extensionOf(name) {
+ const lastDot = name.lastIndexOf('.')
+ if (lastDot <= 0 || lastDot === name.length - 1) return ''
+ const extension = name.slice(lastDot)
+ return extension.length <= GFS_RESOURCE_EXTENSION_MAX_LENGTH ? extension : ''
+}
+
+function truncatedBaseForSuffix(base, suffix) {
+ const maxBaseLength = GFS_RESOURCE_NAME_MAX_LENGTH - suffix.length
+ if (maxBaseLength <= 0) throw new Error(GFS_UPLOAD_NAME_EXHAUSTED_MESSAGE)
+ const truncatedBase = base.slice(0, maxBaseLength).replace(/[\s._-]+$/g, '')
+ return truncatedBase || base.slice(0, maxBaseLength)
+}
+
+async function sha256Hex(value) {
+ const cryptoApi = globalThis.crypto
+ if (!cryptoApi || !cryptoApi.subtle) {
+ throw new Error('Web Crypto is required to normalize long GFS resource names.')
+ }
+ const digest = await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(value))
+ return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('')
+}
+
+async function normalizeGfsResourceName(name) {
+ const normalized = name.normalize('NFC')
+ // eslint-disable-next-line no-control-regex
+ if (normalized === '.' || normalized === '..' || /[\/\\\u0000-\u001f\u007f]/.test(normalized)) {
+ throw new Error('File and folder names cannot contain path separators or control characters.')
+ }
+ if (normalized.length <= GFS_RESOURCE_NAME_MAX_LENGTH) return normalized
+
+ const extension = extensionOf(normalized)
+ 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}`
+ return `${truncatedBaseForSuffix(base, suffix)}${suffix}`
+}
+
+/**
+ * Precondition: name has already passed through normalizeGfsResourceName.
+ */
+function nextAvailableGfsResourceName(name, occupiedNames) {
+ 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(GFS_UPLOAD_NAME_EXHAUSTED_MESSAGE)
+}
+
+function isObject(value) {
+ return value !== null && typeof value === 'object'
+}
+
+function is409(value) {
+ return value === 409 || value === '409'
+}
+
+function isGfsNameConflict(error) {
+ const details = isObject(error) ? error : null
+ const structuredStatus = details?.status ?? details?.response?.status
+ // A structured non-409 response is authoritative. Do not reinterpret a 4xx
+ // permission or validation failure as a collision because its text happens
+ // to contain a compatibility keyword.
+ if (structuredStatus !== undefined) return is409(structuredStatus)
+
+ const code = typeof details?.code === 'string' ? details.code : ''
+ if (/^(?:conflict|already_exists|duplicate|name_conflict|resource_exists)$/i.test(code)) {
+ return true
+ }
+
+ const parts = [
+ error instanceof Error ? error.message : error,
+ details?.message,
+ details?.bodyText,
+ ].filter(value => value !== undefined && value !== null)
+ const message = parts.map(String).join(' ')
+ 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)
+ )
+}
+
+function gfsUploadNameRetryDecision(error, options) {
+ const attempt = options?.attempt
+ const retryLimit = options?.retryLimit ?? GFS_UPLOAD_NAME_RETRY_LIMIT
+ if (!Number.isSafeInteger(attempt) || attempt < 0) {
+ throw new Error('GFS upload name retry attempt must be a non-negative integer.')
+ }
+ if (!Number.isSafeInteger(retryLimit) || retryLimit < 1) {
+ throw new Error('GFS upload name retry limit must be a positive integer.')
+ }
+ if (!isGfsNameConflict(error) || options?.resuming === true) return 'terminal'
+ return attempt + 1 < retryLimit ? 'retry' : 'exhausted'
+}
+
+function createGfsUploadNameReservationBook() {
+ const byParent = new Map()
+
+ function reservationCounts(parentKey) {
+ let counts = byParent.get(parentKey)
+ if (!counts) {
+ counts = new Map()
+ byParent.set(parentKey, counts)
+ }
+ return counts
+ }
+
+ function acquire(parentKey, name) {
+ const counts = reservationCounts(parentKey)
+ counts.set(name, (counts.get(name) ?? 0) + 1)
+ }
+
+ function release(parentKey, names) {
+ const counts = byParent.get(parentKey)
+ if (!counts) return
+ for (const name of names) {
+ const count = counts.get(name) ?? 0
+ if (count <= 1) counts.delete(name)
+ else counts.set(name, count - 1)
+ }
+ if (counts.size === 0) byParent.delete(parentKey)
+ }
+
+ return {
+ begin(parentKey, normalizedName, occupiedNames) {
+ const attempts = []
+ let settled = false
+ return {
+ reserveNext(options = {}) {
+ if (settled) throw new Error('GFS upload name reservation is already settled.')
+ const reserved = byParent.get(parentKey)?.keys() ?? []
+ const name = options.exact
+ ? normalizedName.normalize('NFC')
+ : nextAvailableGfsResourceName(normalizedName, [...occupiedNames, ...reserved])
+ acquire(parentKey, name)
+ attempts.push(name)
+ return name
+ },
+ markConflict(name) {
+ occupiedNames.add(name)
+ },
+ markSuccess(name) {
+ occupiedNames.add(name)
+ },
+ release() {
+ if (settled) return
+ settled = true
+ release(parentKey, attempts)
+ },
+ }
+ },
+ reservedNames(parentKey) {
+ return [...(byParent.get(parentKey)?.keys() ?? [])]
+ },
+ }
+}
+
+module.exports = {
+ GFS_RESOURCE_NAME_MAX_LENGTH,
+ GFS_UPLOAD_NAME_EXHAUSTED_MESSAGE,
+ GFS_UPLOAD_NAME_RETRY_LIMIT,
+ createGfsUploadNameReservationBook,
+ gfsUploadNameRetryDecision,
+ isGfsNameConflict,
+ nextAvailableGfsResourceName,
+ normalizeGfsResourceName,
+}
diff --git a/packages/gfs-interaction-policy/index.d.ts b/packages/gfs-interaction-policy/index.d.ts
new file mode 100644
index 000000000..860d94cc6
--- /dev/null
+++ b/packages/gfs-interaction-policy/index.d.ts
@@ -0,0 +1,42 @@
+export declare const GFS_RESOURCE_NAME_MAX_LENGTH: number
+export declare const GFS_UPLOAD_NAME_RETRY_LIMIT: number
+export declare const GFS_UPLOAD_NAME_EXHAUSTED_MESSAGE: string
+
+export declare function normalizeGfsResourceName(name: string): Promise<string>
+
+/** Precondition: name has already passed through normalizeGfsResourceName. */
+export declare function nextAvailableGfsResourceName(
+ name: string,
+ occupiedNames: Iterable<string>
+): string
+
+export declare function isGfsNameConflict(error: unknown): boolean
+
+export type GfsUploadNameRetryDecision = 'retry' | 'exhausted' | 'terminal'
+
+export declare function gfsUploadNameRetryDecision(
+ error: unknown,
+ options: {
+ attempt: number
+ retryLimit?: number
+ resuming?: boolean
+ }
+): GfsUploadNameRetryDecision
+
+export interface GfsUploadNameReservation {
+ reserveNext(options?: { exact?: boolean }): string
+ markConflict(name: string): void
+ markSuccess(name: string): void
+ release(): void
+}
+
+export interface GfsUploadNameReservationBook {
+ begin(
+ parentKey: string,
+ normalizedName: string,
+ occupiedNames: Set<string>
+ ): GfsUploadNameReservation
+ reservedNames(parentKey: string): string[]
+}
+
+export declare function createGfsUploadNameReservationBook(): GfsUploadNameReservationBook
diff --git a/packages/gfs-interaction-policy/index.test.cjs b/packages/gfs-interaction-policy/index.test.cjs
new file mode 100644
index 000000000..b714aebf4
--- /dev/null
+++ b/packages/gfs-interaction-policy/index.test.cjs
@@ -0,0 +1,134 @@
+'use strict'
+
+const assert = require('node:assert/strict')
+const fs = require('node:fs')
+const path = require('node:path')
+const { describe, it } = require('node:test')
+const policy = require('./index.cjs')
+const {
+ GFS_RESOURCE_NAME_MAX_LENGTH,
+ createGfsUploadNameReservationBook,
+ gfsUploadNameRetryDecision,
+ isGfsNameConflict,
+ nextAvailableGfsResourceName,
+ normalizeGfsResourceName,
+} = policy
+
+it('keeps runtime exports aligned with the declaration file', () => {
+ const declarations = fs.readFileSync(path.join(__dirname, 'index.d.ts'), 'utf8')
+ const declared = Array.from(
+ declarations.matchAll(/export declare (?:const|function)\s+([A-Za-z0-9_]+)/g),
+ match => match[1]
+ ).sort()
+ assert.deepEqual(Object.keys(policy).sort(), declared)
+})
+
+describe('GFS collision classification and retry policy', () => {
+ it('classifies the structured error emitted by the Control UI Upload v2 producer', () => {
+ const error = Object.assign(new Error('409 resource already exists'), {
+ status: 409,
+ code: 'conflict',
+ })
+ assert.equal(isGfsNameConflict(error), true)
+ assert.equal(gfsUploadNameRetryDecision(error, { attempt: 0 }), 'retry')
+ })
+
+ it('keeps the legacy Electron conflict string as an explicit compatibility case', () => {
+ const error = new Error(
+ "Error invoking remote method 'gfs:createFileFromPath': Error: 409 Conflict: [object Object]"
+ )
+ assert.equal(isGfsNameConflict(error), true)
+ })
+
+ it('refuses name retries for unrelated errors, resume sessions, and exhaustion', () => {
+ const conflict = Object.assign(new Error('409 resource already exists'), { status: 409 })
+ assert.equal(
+ gfsUploadNameRetryDecision(new Error('network failed'), { attempt: 0 }),
+ 'terminal'
+ )
+ assert.equal(gfsUploadNameRetryDecision(conflict, { attempt: 0, resuming: true }), 'terminal')
+ assert.equal(gfsUploadNameRetryDecision(conflict, { attempt: 1, retryLimit: 2 }), 'exhausted')
+ })
+
+ it('does not let compatibility text override an authoritative non-409 status', () => {
+ const error = Object.assign(new Error('403 resource already exists outside your access'), {
+ status: 403,
+ code: 'forbidden',
+ })
+ assert.equal(isGfsNameConflict(error), false)
+ })
+})
+
+describe('GFS resource naming', () => {
+ it('selects the first numbered gap while preserving the extension', () => {
+ assert.equal(
+ nextAvailableGfsResourceName('report.txt', [
+ 'report.txt',
+ 'report (1).txt',
+ 'report (3).txt',
+ ]),
+ 'report (2).txt'
+ )
+ })
+
+ it('normalizes long names deterministically within the 255-character limit', async () => {
+ const name = `${'a'.repeat(280)}.txt`
+ const normalized = await normalizeGfsResourceName(name)
+ assert.equal(normalized.length, GFS_RESOURCE_NAME_MAX_LENGTH)
+ assert.match(normalized, /-[0-9a-f]{12}\.txt$/)
+ })
+
+ it('rejects path separators and control characters before allocation', async () => {
+ await assert.rejects(() => normalizeGfsResourceName('../report.txt'), /path separators/)
+ await assert.rejects(() => normalizeGfsResourceName('report\n.txt'), /control characters/)
+ })
+})
+
+describe('GFS upload name reservations', () => {
+ it('allocates distinct concurrent names in one parent and isolates other parents', () => {
+ const book = createGfsUploadNameReservationBook()
+ const occupied = new Set()
+ const first = book.begin('parent-a', 'report.txt', occupied)
+ const second = book.begin('parent-a', 'report.txt', occupied)
+ const otherParent = book.begin('parent-b', 'report.txt', new Set())
+
+ assert.equal(first.reserveNext(), 'report.txt')
+ assert.equal(second.reserveNext(), 'report (1).txt')
+ assert.equal(otherParent.reserveNext(), 'report.txt')
+ assert.deepEqual(book.reservedNames('parent-a'), ['report.txt', 'report (1).txt'])
+
+ first.release()
+ second.release()
+ otherParent.release()
+ assert.deepEqual(book.reservedNames('parent-a'), [])
+ assert.deepEqual(book.reservedNames('parent-b'), [])
+ })
+
+ it('retains retry candidates until settlement and releases all after success', () => {
+ const book = createGfsUploadNameReservationBook()
+ const occupied = new Set()
+ const operation = book.begin('parent', 'report.txt', occupied)
+ const first = operation.reserveNext()
+ operation.markConflict(first)
+ const second = operation.reserveNext()
+ operation.markSuccess(second)
+
+ assert.equal(second, 'report (1).txt')
+ assert.deepEqual(book.reservedNames('parent'), ['report.txt', 'report (1).txt'])
+ operation.release()
+ assert.deepEqual(book.reservedNames('parent'), [])
+ })
+
+ it('releases failure reservations without dropping another operation reference', () => {
+ const book = createGfsUploadNameReservationBook()
+ const first = book.begin('parent', 'report.txt', new Set())
+ const resume = book.begin('parent', 'report.txt', new Set())
+ first.reserveNext({ exact: true })
+ resume.reserveNext({ exact: true })
+
+ first.release()
+ assert.deepEqual(book.reservedNames('parent'), ['report.txt'])
+ resume.release()
+ assert.deepEqual(book.reservedNames('parent'), [])
+ })
+})
diff --git a/packages/gfs-interaction-policy/package-lock.json b/packages/gfs-interaction-policy/package-lock.json
new file mode 100644
index 000000000..7466a3586
--- /dev/null
+++ b/packages/gfs-interaction-policy/package-lock.json
@@ -0,0 +1,13 @@
+{
+ "name": "@clerum/gfs-interaction-policy",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@clerum/gfs-interaction-policy",
+ "version": "0.1.0",
+ "license": "MIT"
+ }
+ }
+}
diff --git a/packages/gfs-interaction-policy/package.json b/packages/gfs-interaction-policy/package.json
new file mode 100644
index 000000000..51d7feb8e
--- /dev/null
+++ b/packages/gfs-interaction-policy/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@clerum/gfs-interaction-policy",
+ "version": "0.1.0",
+ "private": true,
+ "description": "Shared browser-safe GFS upload collision, naming, retry, and reservation policy",
+ "main": "index.cjs",
+ "types": "index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./index.d.ts",
+ "require": "./index.cjs",
+ "default": "./index.cjs"
+ }
+ },
+ "scripts": {
+ "build": "node --check index.cjs",
+ "test": "node --test index.test.cjs"
+ },
+ "license": "MIT"
+}
diff --git a/scripts/minikube/pre-gate-incremental.sh b/scripts/minikube/pre-gate-incremental.sh
index ed388b44a..4acfd07a1 100755
--- a/scripts/minikube/pre-gate-incremental.sh
+++ b/scripts/minikube/pre-gate-incremental.sh
@@ -193,6 +193,7 @@ incremental_classify_path() {
channel-reader/*) incremental_add_target channel-reader channels channel-reader-chatllm ;;
mcp-proxy/*) incremental_add_target mcp-proxy mcp-server mcp-proxy ;;
control-ui/*) incremental_add_target control-ui control-plane control-ui ;;
+ packages/gfs-interaction-policy/*) incremental_add_target control-ui control-plane control-ui ;;
packages/display-field/*)
# display-field is consumed ONLY by the control-api and control-ui images
# (their Dockerfiles COPY it and their field validation runs off it), so a
diff --git a/scripts/prettier/paths.mjs b/scripts/prettier/paths.mjs
index 3944d8f41..49dfc613e 100644
--- a/scripts/prettier/paths.mjs
+++ b/scripts/prettier/paths.mjs
@@ -9,6 +9,7 @@ export const projectRoots = [
'mcp-proxy',
'mcp-servers',
'packages/desktop-app-links',
+ 'packages/gfs-interaction-policy',
'packages/workflow-sdk',
'profile-ui',
'rpc-proxy',
diff --git a/scripts/tests/test-dockerfile-local-packages.sh b/scripts/tests/test-dockerfile-local-packages.sh
index 67cd60b44..4cb097107 100755
--- a/scripts/tests/test-dockerfile-local-packages.sh
+++ b/scripts/tests/test-dockerfile-local-packages.sh
@@ -185,7 +185,7 @@ assert_dockerignore_mutations_rejected() {
assert_copy_before_every_ci control-api/Dockerfile \
display-field image-policy llm-providers workflow-recipe-capability-policy workflow-runtime-core
assert_copy_before_every_ci control-ui/Dockerfile \
- display-field frontend-components llm-providers workflow-recipe-capability-policy
+ display-field frontend-components gfs-interaction-policy llm-providers workflow-recipe-capability-policy
assert_copy_before_every_ci profile-ui/Dockerfile desktop-app-links frontend-components
assert_copy_before_every_ci host-context-controller/Dockerfile \
image-policy llm-providers network-policy-core workflow-recipe-capability-policy
@@ -206,6 +206,7 @@ assert_copy_before_last_ci workflow-recipes/Dockerfile.coordinator image-policy
assert_materialized control-ui/Dockerfile display-field
assert_materialized control-ui/Dockerfile frontend-components
+assert_materialized control-ui/Dockerfile gfs-interaction-policy
assert_materialized control-ui/Dockerfile llm-providers
assert_materialized control-ui/Dockerfile workflow-recipe-capability-policy
assert_materialized profile-ui/Dockerfile desktop-app-links
@@ -214,7 +215,10 @@ assert_materialized profile-ui/Dockerfile frontend-components
assert_dockerignore_allows control-api/Dockerfile.dockerignore display-field
assert_dockerignore_allows control-api/Dockerfile.dockerignore llm-providers
assert_dockerignore_allows control-ui/Dockerfile.dockerignore display-field
+assert_dockerignore_allows control-ui/Dockerfile.dockerignore gfs-interaction-policy
assert_dockerignore_allows control-ui/Dockerfile.dockerignore llm-providers
+assert_dockerignore_excludes_generated_dependencies \
+ control-ui/Dockerfile.dockerignore gfs-interaction-policy
assert_dockerignore_narrow_package control-ui/Dockerfile.dockerignore frontend-components
assert_dockerignore_excludes_generated_dependencies \
control-ui/Dockerfile.dockerignore frontend-components
diff --git a/scripts/tests/test-minikube-pre-gate-sync-state.sh b/scripts/tests/test-minikube-pre-gate-sync-state.sh
index 3e6b7a063..a73e43e9c 100755
--- a/scripts/tests/test-minikube-pre-gate-sync-state.sh
+++ b/scripts/tests/test-minikube-pre-gate-sync-state.sh
@@ -105,6 +105,7 @@ if incremental_contains 'control-api/*) incremental_add_target control-api contr
incremental_contains 'rpc-proxy/*) incremental_add_target rpc-proxy rpc-proxy rpc-proxy' &&
incremental_contains 'host-context-controller/*) incremental_add_target host-context-controller control-plane host-context-controller' &&
incremental_contains 'control-ui/*) incremental_add_target control-ui control-plane control-ui' &&
+ incremental_contains 'packages/gfs-interaction-policy/*) incremental_add_target control-ui control-plane control-ui' &&
incremental_contains 'tests/e2e/fixtures/workflow-plugin-sdk-e2e/*)' &&
incremental_contains 'incremental_add_target workflow-plugin-sdk-e2e sandbox-recipes workflow-plugin-sdk-e2e'; then
pass "incremental sync maps known runtime paths to their own images and deployments"
diff --git a/work-tracker/specs/01-gfs-upload-collision-policy.md b/work-tracker/specs/01-gfs-upload-collision-policy.md
new file mode 100644
index 000000000..9fc868dcb
--- /dev/null
+++ b/work-tracker/specs/01-gfs-upload-collision-policy.md
@@ -0,0 +1,114 @@
+# GFS upload collision and naming policy
+
+Status: accepted for PR #595
+Date: 2026-09-09
+
+## 1. Problem and scope
+
+Control UI and Desktop currently make the same product decisions in separate
+page components: how to recognize a create-name collision, how to select a
+numbered sibling name, when to retry, and how concurrent uploads reserve and
+release candidate names. The duplicate implementations have already drifted:
+the Control UI regression test used an Electron-shaped error even though its
+real Upload v2 producer creates a structured fetch error.
+
+This redesign establishes one pure behavioral authority. It does not share
+React components, transport clients, upload execution, notifications, or
+presentation between the applications.
+
+## 2. Supported boundary and PR decision
+
+The live repository boundaries were inspected before choosing a location:
+
+| Existing boundary | Intended ownership | Decision |
+| ------------------------------------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
+| `packages/frontend-components` | React 18 visual and semantic primitives for Control UI and Profile UI | Reject. Desktop intentionally uses React 19 and its own renderer primitives; collision policy is not visual. |
+| `packages/desktop-app-links` | Desktop/profile link and packaging behavior | Reject. GFS upload naming is unrelated to link interpretation. |
+| `packages/display-field` | Control API/Control UI validation of admin display fields | Reject. Extending it would blur a deliberately narrow validation contract. |
+| Dependency-free domain packages under `packages/` | Pure policy shared across otherwise separate consumers | Use this established pattern for `packages/gfs-interaction-policy`. |
+
+`packages/gfs-interaction-policy` will be a browser-safe leaf with no React,
+Node, transport, storage, or environment dependency. It will expose CommonJS
+runtime code plus declarations, matching the repository's existing pure policy
+packages. Both applications will depend on that same authority.
+
+The redesign remains in PR #595. It is a bounded correction to collision
+behavior already introduced by this PR, and splitting it would either leave
+one client on duplicated policy or make this PR depend on an unmerged
+prerequisite. Any backend protocol change, shared visual component, or broader
+upload architecture change must be split into a separate proposal.
+
+## 3. Decision table
+
+| Situation | Classification | Candidate/operation decision | Reservation decision |
+| ------------------------------------------------------------------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
+| Preferred normalized name is absent from both the observed siblings and active reservations for the same parent | Available | Attempt the preferred name | Reserve it before starting transport. |
+| Preferred name is occupied or reserved | Local collision | Select the first available ` (n)` suffix while preserving the extension and 255-character limit | Reserve the selected candidate atomically within the synchronous policy call. |
+| Upload v2 create responds with real HTTP 409; producer exposes `status`, optional parsed `code`, and parsed message | Remote collision | For a fresh create with retry budget remaining, mark the attempted name occupied and retry with the next candidate | Retain attempt reservations until the operation settles so concurrent uploads cannot reuse an in-flight candidate. |
+| Legacy Electron error contains the established 409/conflict or already-exists text but has no structured status | Compatibility collision | Apply the same bounded fresh-create retry | Cover separately; it is not the primary Control UI fixture. |
+| Conflict occurs while resuming a persisted Upload v2 session | Terminal for this operation | Do not rename; a persisted session is bound to its original identity | Release all reservations when the operation exits. |
+| Error is not classified as a name collision | Terminal error | Surface through the owning application's existing error path | Release all reservations when the operation exits. |
+| Collision retry budget is exhausted | Terminal uniqueness error | Surface `Could not create a unique GFS resource name.` | Release all reservations when the operation exits. |
+| Two uploads choose a name concurrently in one parent | Concurrent local collision | First gets the preferred name; later reservations receive increasing numbered names | Reservations are isolated by parent and shared across concurrent operations in that client. |
+| Equivalent names are uploaded to different parents | Available in each parent | Each parent may use the same preferred name | Reservation sets never leak across parent keys. |
+| Upload succeeds, fails, is canceled, or returns early | Settled | Application performs its existing UI/state work | A `finally` path releases every name reserved by that operation and removes empty parent buckets. |
+
+## 4. Behavioral invariants
+
+1. Callers normalize and validate a source name before asking the policy to
+ reserve or suffix it; the policy owns deterministic NFC comparison and
+ numbered-name selection after that precondition.
+2. The extension remains last, suffixes start at ` (1)`, and every candidate
+ stays within 255 characters using the existing deterministic truncation
+ rule.
+3. One exported classifier owns structured 409 and legacy compatibility
+ recognition. Neither client may duplicate status/message regular
+ expressions.
+4. The real Control UI Upload v2 fetch producer is the primary regression
+ contract: its numeric `status`, optional parsed `code`, and parsed message
+ must reach the shared classifier unchanged.
+5. Name retries are create-only, bounded, and never rename a persisted resume
+ session.
+6. A reservation is acquired before transport begins. Reservations are scoped
+ to a parent, distinguish concurrent operations, and are all released on
+ success, failure, cancellation, early return, or retry exhaustion.
+7. A remote collision is added to the operation's observed occupied names
+ before choosing the next candidate, even when the initial directory listing
+ was stale.
+8. Control UI and Desktop produce the same collision decision and candidate
+ sequence for equivalent inputs.
+9. App-specific transport, React state, abort/session handling, notifications,
+ and rendering remain in their current application boundaries.
+
+## 5. Required proof
+
+- Package-level decision-table tests cover structured Upload v2 errors,
+ separately labeled legacy errors, numbering/truncation, parent isolation,
+ concurrent reservations, bounded retry decisions, and complete cleanup.
+- Control UI drives `GfsBrowser` through the real fetch-based Upload v2
+ producer: first create returns 409, the produced error shape is asserted,
+ and the observable second upload uses `report (1).txt` and completes.
+- Desktop and Control UI tests prove both consumers import the same package
+ authority and produce equivalent candidates for equivalent inputs.
+- T3 regression evidence runs the producer-backed assertion against the
+ relevant pre-fix commit in an isolated checkout and records that it fails
+ because the previous browser path did not consume the real producer-backed
+ conflict behavior.
+- The repository strict style-rule command passes after the Move Dialog token
+ cleanup.
+
+## 6. T3 regression evidence
+
+The producer-backed browser assertion was run in an isolated local clone at
+`5eb0bf4e8884183df7bac9cb6aa5f85f0acac5ce`, the parent of the Control UI
+collision-retry implementation. The real Upload v2 producer emitted and the
+test verified `status: 409`, `code: conflict`, and the parsed message
+`409 resource already exists`. The assertion then failed for the intended
+behavioral reason:
+
+```text
+expected [ 'report.txt' ] to deeply equal [ 'report.txt', 'report (1).txt' ]
+```
+
+That head attempted the original name once, surfaced the 409, and never issued
+the numbered retry. The same producer-backed assertion passes with this design.