Skip to content

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

TypeScript

feat(control-ui): improve GFS resource workflows

M6d185ebfbb50
diff --git a/control-ui/app/globals.css b/control-ui/app/globals.css
index 4c5c2b37d..43d9557f1 100644
--- a/control-ui/app/globals.css
+++ b/control-ui/app/globals.css
@@ -12444,10 +12444,32 @@ button.cu-gfs-tree__button:focus-visible,
background: rgba(var(--cu-accent-rgb), 0.06);
}
+.cu-gfs-list__row[data-dragging='true'] {
+ opacity: 0.55;
+}
+
+.cu-gfs-list__row[data-drop-target='true'] {
+ outline: 2px solid rgba(var(--cu-accent-rgb), 0.72);
+ outline-offset: -2px;
+ background: rgba(var(--cu-accent-rgb), 0.14);
+}
+
+.cu-gfs-list__row[data-drop-target='true']:hover {
+ background: rgba(var(--cu-accent-rgb), 0.18);
+}
+
.cu-gfs-list__row--clickable {
cursor: pointer;
}
+.cu-gfs-list__row[draggable='true'] {
+ cursor: grab;
+}
+
+.cu-gfs-list__row[draggable='true']:active {
+ cursor: grabbing;
+}
+
.cu-gfs-list__row--clickable:focus-visible {
outline: 2px solid rgba(var(--cu-focus-rgb), 0.8);
outline-offset: -2px;
diff --git a/control-ui/components/GfsBrowser.tsx b/control-ui/components/GfsBrowser.tsx
index 95e2dd629..a8d2659ef 100644
--- a/control-ui/components/GfsBrowser.tsx
+++ b/control-ui/components/GfsBrowser.tsx
@@ -28,11 +28,10 @@ import {
} from '@lib/gfsFileUpload'
import { gfsImagePreviewMimeType } from '@lib/gfsImagePreview'
import { isGfsMarkdownPreviewFile } from '@lib/gfsMarkdownPreview'
-import { normalizeGfsResourceName } from '@lib/gfsResourceName'
+import { nextAvailableGfsResourceName, normalizeGfsResourceName } from '@lib/gfsResourceName'
import { isGfsVideoFile } from '@lib/gfsVideoFile'
import { gfsVideoPreviewMimeType } from '@lib/gfsVideoPreview'
import { GfsGrantPanel } from './GfsGrantPanel'
-import type { GfsCreateShareActionChange } from './GfsGrantPanel.types'
import { GfsResourceMenu } from './GfsResourceMenu'
import { NewFolderModal } from './NewFolderModal'
import { TablePanelHeader } from './TablePanelHeader'
@@ -64,6 +63,7 @@ interface Crumb {
const DRIVE = 'main'
const PENDING_GFS_UPLOAD_KEY = 'evenfire:gfs-upload-v2:pending'
+const GFS_RESOURCE_DRAG_TYPE = 'application/x-evenfire-gfs-resource'
interface PendingGfsUpload {
uploadId?: string
@@ -162,6 +162,10 @@ function hasDraggedFiles(event: React.DragEvent<HTMLElement>): boolean {
return Array.from(event.dataTransfer.types || []).includes('Files')
}
+function hasDraggedGfsResource(event: React.DragEvent<HTMLElement>): boolean {
+ return Array.from(event.dataTransfer.types || []).includes(GFS_RESOURCE_DRAG_TYPE)
+}
+
function isGfsPreviewFile(fileName: string): boolean {
return (
gfsImagePreviewMimeType(fileName) !== null ||
@@ -181,6 +185,38 @@ 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: '/' }])
@@ -189,20 +225,11 @@ export function GfsBrowser(): React.JSX.Element {
const [loading, setLoading] = useState(true)
const [loadingMore, setLoadingMore] = useState(false)
const [error, setError] = useState('')
- // Operator selects a resource to delegate access on (grant/share panel).
+ // Operator selects a resource to delegate access on (grant panel).
const [selected, setSelected] = useState<GfsChild | null>(null)
const [renameOpen, setRenameOpen] = useState(false)
const [renameName, setRenameName] = useState('')
const [deleteOpen, setDeleteOpen] = useState(false)
- const createShareActionRef = useRef<(() => void) | null>(null)
- const [createShareDisabled, setCreateShareDisabled] = useState(true)
- const handleCreateShareActionChange = useCallback<GfsCreateShareActionChange>(
- (action, disabled) => {
- createShareActionRef.current = action
- setCreateShareDisabled(disabled)
- },
- []
- )
// New-folder dialog (replaces the native window.prompt flow).
const [newFolderOpen, setNewFolderOpen] = useState(false)
const [creatingFolder, setCreatingFolder] = useState(false)
@@ -211,9 +238,15 @@ 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 [uploadSnapshot, setUploadSnapshot] = useState<GfsUploadJobSnapshot | null>(null)
const [dragActive, setDragActive] = useState(false)
const [droppedUploadCount, setDroppedUploadCount] = useState(0)
+ const [draggingResourceId, setDraggingResourceId] = useState<string | null>(null)
+ const [dragOverFolderId, setDragOverFolderId] = useState<string | null>(null)
+ const [movingResourceId, setMovingResourceId] = useState<string | null>(null)
+ const draggingResourceRef = useRef<GfsChild | null>(null)
+ const movingResourceRef = useRef<string | null>(null)
const [imagePreview, setImagePreview] = useState<{
byteLength: number
fileName: string
@@ -514,6 +547,118 @@ export function GfsBrowser(): React.JSX.Element {
await load(current)
}
+ function handleResourceDragStart(
+ event: React.DragEvent<HTMLLIElement>,
+ child: GfsChild
+ ): void {
+ if (child.kind === 'directory' || movingResourceRef.current) {
+ event.preventDefault()
+ return
+ }
+ event.dataTransfer.effectAllowed = 'move'
+ event.dataTransfer.setData(GFS_RESOURCE_DRAG_TYPE, child.resourceId)
+ event.dataTransfer.setData('text/plain', child.name)
+ draggingResourceRef.current = child
+ setDraggingResourceId(child.resourceId)
+ }
+
+ function handleResourceDragEnd(): void {
+ draggingResourceRef.current = null
+ setDraggingResourceId(null)
+ setDragOverFolderId(null)
+ }
+
+ function handleFolderDragOver(
+ event: React.DragEvent<HTMLLIElement>,
+ folder: GfsChild
+ ): void {
+ if (!hasDraggedGfsResource(event)) return
+ const source = draggingResourceRef.current
+ if (
+ !source ||
+ source.resourceId === folder.resourceId ||
+ folder.kind !== 'directory'
+ )
+ return
+ event.preventDefault()
+ event.stopPropagation()
+ event.dataTransfer.dropEffect = 'move'
+ setDragOverFolderId(folder.resourceId)
+ }
+
+ function handleFolderDragEnter(
+ event: React.DragEvent<HTMLLIElement>,
+ folder: GfsChild
+ ): void {
+ handleFolderDragOver(event, folder)
+ }
+
+ function handleFolderDragLeave(event: React.DragEvent<HTMLLIElement>): void {
+ if (!hasDraggedGfsResource(event)) return
+ event.preventDefault()
+ event.stopPropagation()
+ if (!event.currentTarget.contains(event.relatedTarget as Node | null)) {
+ setDragOverFolderId(null)
+ }
+ }
+
+ async function moveResource(
+ source: GfsChild,
+ destination: GfsChild
+ ): Promise<void> {
+ if (
+ source.kind === 'directory' ||
+ destination.kind !== 'directory' ||
+ source.resourceId === destination.resourceId ||
+ movingResourceRef.current
+ ) {
+ return
+ }
+
+ movingResourceRef.current = source.resourceId
+ setMovingResourceId(source.resourceId)
+ try {
+ await apiSend(
+ 'PATCH',
+ `/api/v1/gfs/resources/${encodeURIComponent(source.resourceId)}`,
+ {
+ drive: DRIVE,
+ newParentId: destination.resourceId,
+ ifMatch: source.version,
+ },
+ { drive: DRIVE }
+ )
+ // The destination may have been prefetched while it was visible. Its
+ // cached listing is stale after a move and must be revalidated before it
+ // is opened.
+ childCacheRef.current.delete(destination.resourceId)
+ showToast(`Moved "${source.name}" to "${destination.name}".`, {
+ tone: 'success',
+ })
+ await refreshCurrent()
+ } catch (err) {
+ showToast(err instanceof Error ? err.message : 'Could not move resource.', {
+ tone: 'error',
+ })
+ } finally {
+ movingResourceRef.current = null
+ setMovingResourceId(null)
+ }
+ }
+
+ async function handleFolderDrop(
+ event: React.DragEvent<HTMLLIElement>,
+ folder: GfsChild
+ ): Promise<void> {
+ if (!hasDraggedGfsResource(event)) return
+ event.preventDefault()
+ event.stopPropagation()
+ setDragOverFolderId(null)
+ const source = draggingResourceRef.current
+ if (!source) return
+ await moveResource(source, folder)
+ }
+
async function uploadWithCompatibility(
input: GfsUploadJobInput
): Promise<'completed' | 'paused'> {
@@ -620,74 +765,92 @@ export function GfsBrowser(): React.JSX.Element {
}
}
- async function uploadFile(file: File | null | undefined): Promise<void> {
+ async function uploadFile(
+ file: File | null | undefined,
+ occupiedNames = new Set(items.map(item => item.name))
+ ): Promise<void> {
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 {
assertGfsFileUploadSize(file.size)
- const name = await normalizeGfsResourceName(file.name)
+ const normalizedName = await normalizeGfsResourceName(file.name)
const target = { operation: 'create' as const, parentRid: rid }
- resumeUploadId = matchingPendingResumeUploadId(file, target, name)
- const job = createGfsUploadJob({
- file,
- name,
- target,
- resumeUploadId,
- 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
- }
- showToast('File uploaded.', { tone: 'success' })
- setUploadCandidate(null)
- setUploadOpen(false)
- setUploadSnapshot(null)
- uploadJobRef.current = null
- await refreshCurrent()
- } catch (err) {
- if (uploadJobRef.current?.snapshot().state === 'aborted') return
- if (err instanceof GfsUploadCapabilityError && err.allowLegacyFallback) {
- if (resumeUploadId) {
- showToast(
- 'The persisted resumable session cannot be resumed while GFS Upload v2 is unavailable.',
- { tone: 'error' }
- )
- return
- }
- showToast('Resumable upload is unavailable; using the legacy 16 MiB path.', {
- tone: 'info',
- })
+ resumeUploadId = matchingPendingResumeUploadId(file, target, normalizedName)
+
+ 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 {
- const name = await normalizeGfsResourceName(file.name)
- await uploadGfsFileLegacy({ file, name, target: { operation: 'create', parentRid: rid } })
- clearPendingGfsUpload()
+ 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',
+ })
+ legacyFallbackAnnounced = true
+ }
+ await uploadGfsFileLegacy({ file, name, target })
+ clearPendingGfsUpload()
+ setUploadCandidate(null)
+ setUploadOpen(false)
+ setUploadSnapshot(null)
+ uploadJobRef.current = null
+ }
+
+ occupiedNames.add(name)
showToast('File uploaded.', { tone: 'success' })
setUploadCandidate(null)
setUploadOpen(false)
@@ -695,26 +858,47 @@ export function GfsBrowser(): React.JSX.Element {
uploadJobRef.current = null
await refreshCurrent()
return
- } catch (legacyError) {
- showToast(legacyError instanceof Error ? legacyError.message : 'Could not upload file.', {
- tone: 'error',
- })
- return
+ } catch (err) {
+ if (uploadJobRef.current?.snapshot().state === 'aborted') return
+ if (!resumeUploadIdForAttempt && isGfsNameConflict(err)) {
+ occupiedNames.add(name)
+ clearPendingGfsUpload()
+ uploadJobRef.current = null
+ setUploadSnapshot(null)
+ continue
+ }
+ throw err
}
}
+
+ throw new Error('Could not create a unique GFS resource name.')
+ } 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)
}
}
function handleGfsDragEnter(event: React.DragEvent<HTMLElement>): void {
+ if (hasDraggedGfsResource(event)) {
+ event.preventDefault()
+ return
+ }
if (!hasDraggedFiles(event)) return
event.preventDefault()
setDragActive(true)
}
function handleGfsDragOver(event: React.DragEvent<HTMLElement>): void {
+ if (hasDraggedGfsResource(event)) {
+ event.preventDefault()
+ event.dataTransfer.dropEffect = 'none'
+ return
+ }
if (!hasDraggedFiles(event)) return
event.preventDefault()
event.dataTransfer.dropEffect = current?.id ? 'copy' : 'none'
@@ -722,11 +906,16 @@ export function GfsBrowser(): React.JSX.Element {
}
function handleGfsDragLeave(event: React.DragEvent<HTMLElement>): void {
+ if (hasDraggedGfsResource(event)) return
if (event.currentTarget.contains(event.relatedTarget as Node | null)) return
setDragActive(false)
}
async function handleGfsDrop(event: React.DragEvent<HTMLElement>): Promise<void> {
+ if (hasDraggedGfsResource(event)) {
+ event.preventDefault()
+ return
+ }
if (!hasDraggedFiles(event)) return
event.preventDefault()
setDragActive(false)
@@ -745,9 +934,10 @@ export function GfsBrowser(): React.JSX.Element {
}
setDroppedUploadCount(droppedFiles.length)
+ const occupiedNames = new Set(items.map(item => item.name))
try {
for (const file of droppedFiles) {
- await uploadFile(file)
+ await uploadFile(file, occupiedNames)
}
} finally {
setDroppedUploadCount(0)
@@ -906,7 +1096,7 @@ export function GfsBrowser(): React.JSX.Element {
<section
className="cu-gfs"
aria-label="Global File System browser"
- aria-busy={loading || droppedUploadCount > 0}
+ aria-busy={loading || droppedUploadCount > 0 || movingResourceId !== null}
>
<div
className="cu-card cu-card--viewport-fill cu-gfs-card"
@@ -1017,6 +1207,10 @@ export function GfsBrowser(): React.JSX.Element {
<ul className="cu-gfs-list" aria-label="Current folder resources">
{items.map(child => {
const rowOpenable = child.kind === 'directory' || isGfsPreviewFile(child.name)
+ const isDragging = draggingResourceId === child.resourceId
+ const isDropTarget = dragOverFolderId === child.resourceId
+ const canDragResource =
+ child.kind !== 'directory' && movingResourceId === null
const openRow = () => {
if (child.kind === 'directory') openDirectory(child)
else openFilePreview(child)
@@ -1025,6 +1219,38 @@ export function GfsBrowser(): React.JSX.Element {
<li
className={`cu-gfs-list__row${rowOpenable ? ' cu-gfs-list__row--clickable' : ''}`}
key={child.resourceId}
+ draggable={canDragResource}
+ title={
+ canDragResource
+ ? `Drag ${child.name} into a folder to move it`
+ : undefined
+ }
+ onDragStart={
+ canDragResource
+ ? event => handleResourceDragStart(event, child)
+ : undefined
+ }
+ onDragEnd={canDragResource ? handleResourceDragEnd : undefined}
+ onDragEnter={
+ child.kind === 'directory'
+ ? event => handleFolderDragEnter(event, child)
+ : undefined
+ }
+ onDragOver={
+ child.kind === 'directory'
+ ? event => handleFolderDragOver(event, child)
+ : undefined
+ }
+ onDragLeave={
+ child.kind === 'directory' ? handleFolderDragLeave : undefined
+ }
+ onDrop={
+ child.kind === 'directory'
+ ? event => void handleFolderDrop(event, child)
+ : undefined
+ }
+ data-dragging={isDragging ? 'true' : undefined}
+ data-drop-target={isDropTarget ? 'true' : undefined}
role={rowOpenable ? 'button' : undefined}
tabIndex={rowOpenable ? 0 : undefined}
aria-label={rowOpenable ? `Open ${child.name}` : undefined}
@@ -1209,7 +1435,6 @@ export function GfsBrowser(): React.JSX.Element {
<span className="cu-gfs-manage-dialog__title-row">
<h3>{selected.name}</h3>
<GfsResourceMenu
- createShareDisabled={createShareDisabled}
resourceName={selected.name}
resourceUri={selected.gfsUri}
downloading={downloadingIds.has(selected.resourceId)}
@@ -1224,7 +1449,6 @@ export function GfsBrowser(): React.JSX.Element {
: undefined
}
onCopyLink={() => void copyGfsUri(selected.gfsUri)}
- onCreateShare={() => createShareActionRef.current?.()}
onRename={() => {
setRenameName(selected.name)
setRenameOpen(true)
@@ -1269,7 +1493,6 @@ export function GfsBrowser(): React.JSX.Element {
gfsUri: selected.gfsUri,
kind: selected.kind,
}}
- onCreateShareActionChange={handleCreateShareActionChange}
/>
</section>
</div>
diff --git a/control-ui/components/GfsGrantPanel.tsx b/control-ui/components/GfsGrantPanel.tsx
index a18729195..a35cbb029 100644
--- a/control-ui/components/GfsGrantPanel.tsx
+++ b/control-ui/components/GfsGrantPanel.tsx
@@ -12,7 +12,6 @@ import { Button, CheckboxField } from '@components/ui'
import { GFS_MAX_BULK_SUBJECTS } from '@constants/gfsGrantSubjects'
import {
type AdminUser,
- type GfsBulkShareSubjectInput,
type GfsGrantError,
type HostResource,
type TeamListItem,
@@ -25,7 +24,6 @@ import {
getGfsShares,
getHosts,
getRecipes,
- postGfsShare,
putGfsGrant,
} from '@lib/api'
import type { GfsExistingAccessItem, GfsGrantPanelProps } from './GfsGrantPanel.types'
@@ -33,10 +31,12 @@ import { buildGfsBulkSubjectOptions, toGfsBulkSubjectInputs } from './gfsGrantSu
/**
* P4-S07 — Operator delegation panel for the Global File System. The operator
- * (Control UI / Admin-JWT plane) seeds Layer-1/2 grants and creates URI shares
- * on a selected resource. Bulk actions accept users, teams, and canonical host
- * subjects; the intrinsic operator remains a singular request. The existing
- * server-side authority and no-escalation policies remain authoritative.
+ * (Control UI / Admin-JWT plane) seeds Layer-1/2 grants on a selected resource.
+ * Bulk actions accept users, teams, and canonical host subjects; the intrinsic
+ * operator remains a singular request. Existing URI shares remain visible and
+ * revocable, while share creation is intentionally unavailable in this UI.
+ * The existing server-side authority and no-escalation policies remain
+ * authoritative.
*/
const PERMISSION_BITS = ['read', 'write', 'delete', 'manage_acl', 'share'] as const
@@ -53,7 +53,6 @@ const OPERATOR_OPTION: SelectionDropdownOption = {
export function GfsGrantPanel({
resource,
- onCreateShareActionChange,
}: GfsGrantPanelProps): React.JSX.Element {
const { showToast } = useToast()
const { confirm, confirmDialog } = useConfirmDialog()
@@ -75,7 +74,6 @@ export function GfsGrantPanel({
const [existingAccessError, setExistingAccessError] = useState('')
const existingAccessRequest = useRef(0)
const existingAccessController = useRef<AbortController | null>(null)
- const submitShareRef = useRef<() => void>(() => undefined)
const canIncludeDescendants = resource.kind === 'directory'
const loadExistingAccess = useCallback(async () => {
@@ -186,8 +184,6 @@ export function GfsGrantPanel({
const hasHost = selectedSubjects.some(subject => subject.type === 'host')
const visiblePermissionBits = hasHost ? HOST_PERMISSION_BITS : PERMISSION_BITS
const subjectValid = operatorSelected || selectedSubjects.length > 0
- const canCreateShare =
- operatorSelected || selectedSubjects.every(subject => subject.type !== 'host')
const actionPending = busy || confirming
const canSubmit = subjectValid && bits.length > 0 && !actionPending
@@ -217,7 +213,7 @@ export function GfsGrantPanel({
setSelectedValues(bulkValues)
}
- async function submit(kind: 'grant' | 'share') {
+ async function submit() {
setError('')
if (!subjectValid || bits.length === 0) {
setError('subject_and_permissions_required')
@@ -243,9 +239,9 @@ export function GfsGrantPanel({
setConfirming(true)
const confirmed = await confirm({
- title: kind === 'grant' ? 'Grant access?' : 'Create share?',
- message: `${kind === 'grant' ? 'Grant access' : 'Create a share'} for ${recipientSummary} on "${resource.name}". Permissions: ${bits.join(', ')}. Scope: ${scope}.`,
- confirmLabel: kind === 'grant' ? 'Grant access' : 'Create share',
+ title: 'Grant access?',
+ message: `Grant access for ${recipientSummary} on "${resource.name}". Permissions: ${bits.join(', ')}. Scope: ${scope}.`,
+ confirmLabel: 'Grant access',
})
setConfirming(false)
if (!confirmed) return
@@ -259,8 +255,7 @@ export function GfsGrantPanel({
subject: { type: 'operator' as const },
permissions: bits,
}
- if (kind === 'grant') await putGfsGrant({ ...body, inherit: includeDescendants })
- else await postGfsShare({ ...body, includeDescendants })
+ await putGfsGrant({ ...body, inherit: includeDescendants })
} else {
const body = {
drive: DRIVE,
@@ -268,17 +263,9 @@ export function GfsGrantPanel({
subjects: selectedSubjects,
permissions: bits,
}
- if (kind === 'grant') {
- await putGfsGrant({ ...body, inherit: includeDescendants })
- } else {
- const shareSubjects = selectedSubjects.filter(
- (subject): subject is GfsBulkShareSubjectInput => subject.type !== 'host'
- )
- if (shareSubjects.length !== selectedSubjects.length) throw new Error('subjects_invalid')
- await postGfsShare({ ...body, subjects: shareSubjects, includeDescendants })
- }
+ await putGfsGrant({ ...body, inherit: includeDescendants })
}
- showToast(kind === 'grant' ? 'Grant saved.' : 'Share created.', { tone: 'success' })
+ showToast('Grant saved.', { tone: 'success' })
await loadExistingAccess()
setBits([])
setSelectedValues([])
@@ -304,16 +291,6 @@ export function GfsGrantPanel({
}
}
- submitShareRef.current = () => {
- void submit('share')
- }
-
- useEffect(() => {
- if (!onCreateShareActionChange) return
- onCreateShareActionChange(() => submitShareRef.current(), !canSubmit || !canCreateShare)
- return () => onCreateShareActionChange(null, true)
- }, [canCreateShare, canSubmit, onCreateShareActionChange])
-
function subjectLabel(item: GfsExistingAccessItem): string {
if (item.subject.type === 'operator') return 'Operator'
const option = bulkSubjectOptions.find(
@@ -404,7 +381,7 @@ export function GfsGrantPanel({
/>
) : null}
<div className="cu-gfs-grant__actions">
- <Button variant="primary" disabled={!canSubmit} onClick={() => submit('grant')}>
+ <Button variant="primary" disabled={!canSubmit} onClick={() => submit()}>
Grant access
</Button>
</div>
@@ -417,7 +394,7 @@ export function GfsGrantPanel({
<section className="cu-gfs-existing-access" aria-label="Who has access">
<div className="cu-gfs-existing-access__header">
<h4>Who has access</h4>
- <p>Existing grants on this resource. Revoking is immediate.</p>
+ <p>Existing grants and shares on this resource. Revoking is immediate.</p>
</div>
{existingAccessLoading ? (
<p className="cu-gfs-existing-access__empty" role="status">
diff --git a/control-ui/components/GfsGrantPanel.types.ts b/control-ui/components/GfsGrantPanel.types.ts
index 9291f8b48..1e5a69b00 100644
--- a/control-ui/components/GfsGrantPanel.types.ts
+++ b/control-ui/components/GfsGrantPanel.types.ts
@@ -27,11 +27,8 @@ export type GfsGrantResource = {
kind?: string
}
-export type GfsCreateShareActionChange = (action: (() => void) | null, disabled: boolean) => void
-
export interface GfsGrantPanelProps {
resource: GfsGrantResource
- onCreateShareActionChange?: GfsCreateShareActionChange
}
export type GfsExistingAccessItem =
diff --git a/control-ui/components/GfsResourceMenu/index.tsx b/control-ui/components/GfsResourceMenu/index.tsx
index d138ca2ad..add97230c 100644
--- a/control-ui/components/GfsResourceMenu/index.tsx
+++ b/control-ui/components/GfsResourceMenu/index.tsx
@@ -6,10 +6,8 @@ import { IconMoreHorizontal } from '@components/icons'
import type { GfsResourceMenuProps } from './types'
export function GfsResourceMenu({
- createShareDisabled = false,
downloading = false,
onCopyLink,
- onCreateShare,
onDelete,
onDownload,
onManage,
@@ -90,17 +88,6 @@ export function GfsResourceMenu({
Manage access
</button>
) : null}
- {onCreateShare ? (
- <button
- type="button"
- role="menuitem"
- className="cu-kebab__item"
- disabled={createShareDisabled}
- onClick={() => run(onCreateShare)}
- >
- Create share
- </button>
- ) : null}
{onPreview ? (
<button
type="button"
diff --git a/control-ui/components/GfsResourceMenu/types.ts b/control-ui/components/GfsResourceMenu/types.ts
index b443c9ee5..b8928d646 100644
--- a/control-ui/components/GfsResourceMenu/types.ts
+++ b/control-ui/components/GfsResourceMenu/types.ts
@@ -1,8 +1,6 @@
export interface GfsResourceMenuProps {
- createShareDisabled?: boolean
downloading?: boolean
onCopyLink: () => void
- onCreateShare?: () => void
onDelete: () => void
onDownload?: () => void
onManage?: () => void
diff --git a/control-ui/components/__tests__/GfsBrowser.test.tsx b/control-ui/components/__tests__/GfsBrowser.test.tsx
index 70fd77d67..f3eefdf8c 100644
--- a/control-ui/components/__tests__/GfsBrowser.test.tsx
+++ b/control-ui/components/__tests__/GfsBrowser.test.tsx
@@ -14,7 +14,6 @@ import {
getRecipes,
gfsDownload,
gfsFetchFileBlob,
- postGfsShare,
putGfsGrant,
} from '@lib/api'
import {
@@ -40,7 +39,6 @@ vi.mock('@lib/api', () => ({
gfsDownload: vi.fn(),
gfsFetchFileBlob: vi.fn(),
isSilentApiError: () => false,
- postGfsShare: vi.fn(),
putGfsGrant: vi.fn(),
}))
@@ -75,7 +73,6 @@ const mockGetRecipes = vi.mocked(getRecipes)
const mockPutGfsGrant = putGfsGrant as unknown as ReturnType<typeof vi.fn>
const mockGfsDownload = gfsDownload as unknown as ReturnType<typeof vi.fn>
const mockGfsFetchFileBlob = gfsFetchFileBlob as unknown as ReturnType<typeof vi.fn>
-const mockPostGfsShare = vi.mocked(postGfsShare)
const mockUploadGfsFile = uploadGfsFile as unknown as ReturnType<typeof vi.fn>
const mockCreateGfsUploadJob = createGfsUploadJob as unknown as ReturnType<typeof vi.fn>
const mockCreateObjectUrl = vi.fn((_blob: Blob) => 'blob:gfs-image-preview')
@@ -142,7 +139,6 @@ describe('GfsBrowser', () => {
mockPutGfsGrant.mockReset()
mockGfsDownload.mockReset()
mockGfsFetchFileBlob.mockReset()
- mockPostGfsShare.mockReset()
mockCreateGfsUploadJob.mockClear()
mockUploadGfsFile.mockReset()
window.localStorage.clear()
@@ -488,6 +484,138 @@ describe('GfsBrowser', () => {
})
})
+ it('adds numbered suffixes for duplicate names in one dropped batch', async () => {
+ const rootId = '11111111-1111-1111-1111-111111111111'
+ const rootRid = '11111111111111111111111111111111'
+ mockApiGet.mockResolvedValue({
+ rootResourceId: rootId,
+ items: [child('report.txt', 'file', 2)],
+ nextCursor: null,
+ })
+ renderBrowser()
+ await screen.findByText('report.txt')
+
+ const browser = screen.getByRole('region', { name: 'Global File System browser' })
+ fireEvent.drop(browser.querySelector('.cu-gfs-card')!, {
+ 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(mockCreateGfsUploadJob).toHaveBeenCalledTimes(2)
+ expect(mockCreateGfsUploadJob).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ name: 'report (1).txt',
+ target: { operation: 'create', parentRid: rootRid },
+ })
+ )
+ expect(mockCreateGfsUploadJob).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ name: 'report (2).txt',
+ target: { operation: 'create', parentRid: rootRid },
+ })
+ )
+ })
+ })
+
+ it('retries a stale duplicate conflict 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 = {
+ start: vi
+ .fn()
+ .mockRejectedValue(
+ new Error(
+ "Error invoking remote method 'gfs:createFileFromPath': Error: 409 Conflict: [object Object]"
+ )
+ ),
+ pause: vi.fn(),
+ 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.')
+
+ 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'], 'report.txt', { type: 'text/plain' })] },
+ })
+ 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 },
+ })
+ )
+ })
+ 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 () => {
+ const folder = child('archive', 'directory', 1)
+ const file = child('report.md', 'file', 2)
+ mockApiGet
+ .mockResolvedValueOnce({ items: [folder, file], nextCursor: null })
+ .mockResolvedValueOnce({ items: [], nextCursor: null })
+ .mockResolvedValueOnce({ items: [folder], nextCursor: null })
+ mockApiSend.mockResolvedValueOnce({ ok: true })
+ renderBrowser()
+
+ const resources = await screen.findByRole('list', { name: 'Current folder resources' })
+ const fileRow = within(resources).getByText('report.md').closest('li')
+ const folderRow = within(resources).getByText('archive').closest('li')
+ expect(fileRow).not.toBeNull()
+ expect(folderRow).not.toBeNull()
+ expect(fileRow).toHaveAttribute('draggable', 'true')
+ expect(folderRow).toHaveAttribute('draggable', 'false')
+
+ const dataTransfer = {
+ dropEffect: 'none',
+ effectAllowed: 'uninitialized',
+ files: [],
+ types: ['application/x-evenfire-gfs-resource'],
+ setData: vi.fn(),
+ getData: vi.fn(),
+ }
+ fireEvent.dragStart(fileRow!, { dataTransfer })
+ fireEvent.dragEnter(folderRow!, { dataTransfer })
+ expect(folderRow).toHaveAttribute('data-drop-target', 'true')
+ fireEvent.dragOver(folderRow!, { dataTransfer })
+ fireEvent.drop(folderRow!, { dataTransfer })
+
+ await waitFor(() =>
+ expect(mockApiSend).toHaveBeenCalledWith(
+ 'PATCH',
+ '/api/v1/gfs/resources/id-2',
+ { drive: 'main', newParentId: 'id-1', ifMatch: 0 },
+ { drive: 'main' }
+ )
+ )
+ expect(mockCreateGfsUploadJob).not.toHaveBeenCalled()
+ expect(await screen.findByText('Moved "report.md" to "archive".')).toBeTruthy()
+ await waitFor(() => expect(screen.queryByText('report.md')).toBeNull())
+ })
+
it('keeps a persisted drag-and-drop session when resumable capabilities are unavailable', async () => {
const rootId = '11111111-1111-1111-1111-111111111111'
const rootRid = '11111111111111111111111111111111'
@@ -1318,14 +1446,17 @@ describe('GfsBrowser', () => {
expect(screen.getByRole('button', { name: 'Grant access' })).not.toBeDisabled()
})
- it('includes descendants for directory shares from the resource menu', async () => {
+ it('does not expose share creation from a directory resource menu', async () => {
mockApiGet.mockResolvedValueOnce({
items: [child('team-folder', 'directory', 2)],
nextCursor: null,
})
renderBrowser()
- await openManage('team-folder')
+ await openResourceMenu('team-folder')
+ const rowMenu = screen.getByRole('menu')
+ expect(within(rowMenu).queryByRole('menuitem', { name: 'Create share' })).toBeNull()
+ fireEvent.click(within(rowMenu).getByRole('menuitem', { name: 'Manage access' }))
expect(screen.queryByText('Manage folder')).toBeNull()
await waitFor(() => expect(mockGetAdminUsers).toHaveBeenCalledWith(''))
expect(
@@ -1337,28 +1468,14 @@ describe('GfsBrowser', () => {
})
expect(within(manageDialog).queryByRole('button', { name: 'Upload file' })).toBeNull()
fireEvent.click(manageMenuTrigger)
- expect(within(manageDialog).getByRole('menuitem', { name: 'Create share' })).toBeDisabled()
+ expect(
+ within(manageDialog).queryByRole('menuitem', { name: 'Create share' })
+ ).toBeNull()
fireEvent.click(manageMenuTrigger)
await openSubjectPicker()
fireEvent.click(await screen.findByRole('option', { name: 'Ada Lovelace' }))
selectPermission('Read')
- fireEvent.click(manageMenuTrigger)
- const createShareItem = within(manageDialog).getByRole('menuitem', { name: 'Create share' })
- expect(createShareItem).toBeEnabled()
- fireEvent.click(createShareItem)
- const shareDialog = await screen.findByRole('alertdialog', { name: 'Create share?' })
- fireEvent.click(within(shareDialog).getByRole('button', { name: 'Create share' }))
-
- await waitFor(() =>
- expect(mockPostGfsShare).toHaveBeenCalledWith(
- expect.objectContaining({
- resourceId: 'id-2',
- subjects: [{ type: 'user', id: '11111111-1111-1111-1111-111111111111' }],
- permissions: ['read'],
- includeDescendants: true,
- })
- )
- )
+ expect(screen.getByRole('button', { name: 'Grant access' })).toBeEnabled()
})
it('lets an operator select team and operator subjects without typing UUIDs', async () => {
diff --git a/control-ui/components/__tests__/GfsGrantPanel.bulk.test.tsx b/control-ui/components/__tests__/GfsGrantPanel.bulk.test.tsx
index 2bef23b65..16e8e76db 100644
--- a/control-ui/components/__tests__/GfsGrantPanel.bulk.test.tsx
+++ b/control-ui/components/__tests__/GfsGrantPanel.bulk.test.tsx
@@ -11,7 +11,6 @@ import {
getGfsShares,
getHosts,
getRecipes,
- postGfsShare,
putGfsGrant,
} from '@lib/api'
import { GfsGrantPanel } from '../GfsGrantPanel'
@@ -26,7 +25,6 @@ vi.mock('@lib/api', () => ({
getGfsShares: vi.fn(),
deleteGfsGrant: vi.fn(),
deleteGfsShare: vi.fn(),
- postGfsShare: vi.fn(),
putGfsGrant: vi.fn(),
}))
@@ -38,7 +36,6 @@ const mockGetGfsGrants = vi.mocked(getGfsGrants)
const mockGetGfsShares = vi.mocked(getGfsShares)
const mockDeleteGfsGrant = vi.mocked(deleteGfsGrant)
const mockDeleteGfsShare = vi.mocked(deleteGfsShare)
-const mockPostGfsShare = vi.mocked(postGfsShare)
const mockPutGfsGrant = vi.mocked(putGfsGrant)
const resource = {
@@ -58,9 +55,6 @@ const workflowHostSubject = {
} as const
const operatorSubject = { type: 'operator' } as const
-let createShareAction: (() => void) | null = null
-let createShareDisabled = true
-
function successfulMutation(...updated: GfsSubjectInput[]): GfsMutationResponse {
return { ok: true, resourceId: resource.resourceId, updated, count: updated.length }
}
@@ -68,13 +62,7 @@ function successfulMutation(...updated: GfsSubjectInput[]): GfsMutationResponse
function renderPanel(target = resource) {
return render(
<ToastProvider>
- <GfsGrantPanel
- resource={target}
- onCreateShareActionChange={(action, disabled) => {
- createShareAction = action
- createShareDisabled = disabled
- }}
- />
+ <GfsGrantPanel resource={target} />
</ToastProvider>
)
}
@@ -110,16 +98,8 @@ function selectPermission(name: string) {
fireEvent.click(within(openPermissionMenu()).getByRole('menuitemcheckbox', { name }))
}
-async function submit(action: 'Grant access' | 'Create share') {
- if (action === 'Create share') {
- await waitFor(() => {
- expect(createShareAction).not.toBeNull()
- expect(createShareDisabled).toBe(false)
- })
- createShareAction?.()
- } else {
- fireEvent.click(screen.getByRole('button', { name: action }))
- }
+async function submit(action: 'Grant access') {
+ fireEvent.click(screen.getByRole('button', { name: action }))
const dialog = await screen.findByRole('alertdialog')
fireEvent.click(within(dialog).getByRole('button', { name: action }))
}
@@ -127,8 +107,6 @@ async function submit(action: 'Grant access' | 'Create share') {
describe('GfsGrantPanel bulk access', () => {
beforeEach(() => {
vi.clearAllMocks()
- createShareAction = null
- createShareDisabled = true
mockGetAdminUsers.mockResolvedValue({
items: [
{
@@ -358,8 +336,6 @@ describe('GfsGrantPanel bulk access', () => {
expect(within(permissions).getByRole('menuitemcheckbox', { name: 'Write' })).not.toBeChecked()
expect(within(permissions).queryByRole('menuitemcheckbox', { name: 'Delete' })).toBeNull()
expect(within(permissions).queryByRole('menuitemcheckbox', { name: 'Share' })).toBeNull()
- expect(createShareDisabled).toBe(true)
-
await submit('Grant access')
await waitFor(() =>
@@ -380,27 +356,6 @@ describe('GfsGrantPanel bulk access', () => {
await waitFor(() => expect(mockGetGfsGrants).toHaveBeenCalledTimes(2))
})
- it('creates one bulk share for user and team subjects', async () => {
- mockPostGfsShare.mockResolvedValue(successfulMutation(userSubject, teamSubject))
- renderPanel()
- await chooseSubjects('Ada Lovelace', 'Research')
- selectPermission('Read')
- await submit('Create share')
-
- await waitFor(() =>
- expect(mockPostGfsShare).toHaveBeenCalledWith({
- drive: 'main',
- resourceId: resource.resourceId,
- subjects: [
- { type: 'user', id: '11111111-1111-1111-1111-111111111111' },
- { type: 'team', id: '22222222-2222-2222-2222-222222222222' },
- ],
- permissions: ['read'],
- includeDescendants: false,
- })
- )
- })
-
it('requires an explicit scope review before creating access', async () => {
const directory = { ...resource, name: 'reports', kind: 'directory' as const }
renderPanel(directory)
@@ -414,8 +369,6 @@ describe('GfsGrantPanel bulk access', () => {
expect(dialog).toHaveTextContent('"reports"')
expect(dialog).toHaveTextContent('Permissions: read, write')
expect(dialog).toHaveTextContent('Scope: this resource and all descendants')
- expect(createShareDisabled).toBe(true)
-
fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))
await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull())
expect(mockPutGfsGrant).not.toHaveBeenCalled()
@@ -506,7 +459,6 @@ describe('GfsGrantPanel bulk access', () => {
within(openPermissionMenu()).getByRole('menuitemcheckbox', { name: 'Delete' })
).not.toBeChecked()
selectPermission('Read')
- await waitFor(() => expect(createShareDisabled).toBe(false))
})
it('caps the UI selection at 100 subjects', async () => {
diff --git a/control-ui/e2e/support/gfs-bulk-operator-journey.test.ts b/control-ui/e2e/support/gfs-bulk-operator-journey.test.ts
index 008a8acd7..5c1be0006 100644
--- a/control-ui/e2e/support/gfs-bulk-operator-journey.test.ts
+++ b/control-ui/e2e/support/gfs-bulk-operator-journey.test.ts
@@ -16,7 +16,6 @@ import {
uniqueGfsFixtureName,
} from '../../../tests/e2e/gfsUiFixtures'
import { E2E_TEST_EMAIL, E2E_TEST_NAME } from '../../../tests/e2e/testUser'
-import { exerciseGfsBulkShareJourney } from './gfs-bulk-share-journey.test'
import {
CONTROL_UI_BASE_URL,
loginControlUi,
@@ -111,8 +110,6 @@ export async function exerciseGfsBulkOperatorJourney(page: Page): Promise<void>
).toHaveCount(0)
await expect(permissionMenu.getByRole('menuitemcheckbox', { name: 'Share' })).toHaveCount(0)
await expect(permissionMenu.getByRole('menuitemcheckbox', { name: 'Delete' })).toHaveCount(0)
- await expect(panel.getByRole('button', { name: 'Create share', exact: true })).toBeDisabled()
-
await chooseGrantSubject(panel, workflowRecipe.name, workflowRecipe.name)
await expect(selectedSubjects).toContainText(workflowRecipe.name)
await expect(selectedSubjects.getByRole('button', { name: /^Remove / })).toHaveCount(5)
@@ -242,14 +239,6 @@ export async function exerciseGfsBulkOperatorJourney(page: Page): Promise<void>
page,
unchangedHostSubjectIds: ['1st:mcp-host/chatllm-stateless', workflowRecipe.subjectId],
})
- await exerciseGfsBulkShareJourney({
- fixture,
- page,
- targetTeam,
- targetUserEmail: E2E_TEST_EMAIL,
- targetUserId,
- })
-
await test.step('operator remains a distinct singular grant target', async () => {
const panel = grantPanel()
await chooseGrantSubject(panel, 'Operator', 'Operator')
diff --git a/control-ui/e2e/support/gfs-bulk-share-journey.test.ts b/control-ui/e2e/support/gfs-bulk-share-journey.test.ts
deleted file mode 100644
index a4afb3018..000000000
--- a/control-ui/e2e/support/gfs-bulk-share-journey.test.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { type Page, expect, test } from '@playwright/test'
-import { getGfsShareSummary } from '../../../tests/e2e/gfsUiFixtures'
-
-type BulkShareJourneyInput = {
- fixture: { name: string; resourceId: string }
- page: Page
- targetTeam: { id: string; name: string }
- targetUserEmail: string
- targetUserId: string
-}
-
-export async function exerciseGfsBulkShareJourney({
- fixture,
- page,
- targetTeam,
- targetUserEmail,
- targetUserId,
-}: BulkShareJourneyInput): Promise<void> {
- await test.step('operator creates one persisted user/team bulk share through the visible UI', async () => {
- const panel = page.getByRole('dialog', {
- name: `Manage folder ${fixture.name}`,
- exact: true,
- })
- const subjectSearch = panel.getByRole('combobox', {
- name: 'Add people, teams, agents, or workflows',
- })
- await expect(subjectSearch).toBeVisible()
- await subjectSearch.fill(targetUserEmail)
- await panel.getByRole('option').filter({ hasText: targetUserEmail }).first().click()
- await subjectSearch.fill(targetTeam.name)
- await panel.getByRole('option', { name: targetTeam.name, exact: true }).click()
-
- await panel.getByRole('button', { name: 'Permissions', exact: true }).click()
- await panel.getByRole('menuitemcheckbox', { name: 'Read', exact: true }).click()
- const shareResponsePromise = page.waitForResponse(
- response =>
- response.request().method() === 'POST' &&
- response.url().includes('/control-api/api/v1/gfs/shares')
- )
- await panel.getByRole('button', { name: 'Create share', exact: true }).click()
- const confirmation = page.getByRole('alertdialog')
- await expect(confirmation).toContainText('Create share?')
- await expect(confirmation).toContainText(/2 subjects/i)
- await expect(confirmation).toContainText(/read/)
- await confirmation.getByRole('button', { name: 'Create share' }).click()
-
- const shareResponse = await shareResponsePromise
- expect(shareResponse.status(), `${shareResponse.url()} ${await shareResponse.text()}`).toBe(200)
- const submittedBody = shareResponse.request().postDataJSON() as {
- subject?: unknown
- subjects?: Array<{ type: string; id?: string }>
- permissions?: string[]
- }
- expect(submittedBody.subject).toBeUndefined()
- expect(submittedBody.subjects).toEqual([
- { type: 'user', id: targetUserId },
- { type: 'team', id: targetTeam.id },
- ])
- expect(submittedBody.permissions).toEqual(['read'])
- await expect(page.getByText('Share created.').last()).toBeVisible({ timeout: 15_000 })
-
- for (const subject of [
- { type: 'user' as const, id: targetUserId },
- { type: 'team' as const, id: targetTeam.id },
- ]) {
- await expect
- .poll(
- () =>
- getGfsShareSummary({
- resourceId: fixture.resourceId,
- subjectType: subject.type,
- subjectId: subject.id,
- }),
- { timeout: 15_000, intervals: [250, 500, 1_000] }
- )
- .toMatchObject({ permissions: ['read'], includeDescendants: true, createdBy: 'operator:' })
- }
- })
-}
diff --git a/control-ui/lib/__tests__/gfsResourceName.test.ts b/control-ui/lib/__tests__/gfsResourceName.test.ts
index d0e3d4903..e87b85c5b 100644
--- a/control-ui/lib/__tests__/gfsResourceName.test.ts
+++ b/control-ui/lib/__tests__/gfsResourceName.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 '../gfsResourceName'
+import {
+ GFS_RESOURCE_NAME_MAX_LENGTH,
+ nextAvailableGfsResourceName,
+ normalizeGfsResourceName,
+} from '../gfsResourceName'
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/control-ui/lib/gfsResourceName.ts b/control-ui/lib/gfsResourceName.ts
index dba4e2d46..779382b14 100644
--- a/control-ui/lib/gfsResourceName.ts
+++ b/control-ui/lib/gfsResourceName.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}`
}