Skip to content

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

TypeScript

feat(desktop): folder and file drag moves across Files page and sidebar explorer

M3454973a997a
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index 26210533d..fa6e23ba7 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -9,6 +9,7 @@ import {
NotificationsContext,
WorkspaceActionsProvider,
} from '@contexts/index'
+import { GfsDragSessionProvider } from '@/gfs/dragSession'
import { AppHeader } from '@components/AppHeader'
import { BootSplash } from '@components/BootSplash'
import { ChatDrawer } from '@components/ChatDrawer'
@@ -2812,6 +2813,7 @@ export function App() {
>
<McpRuntimeProvider value={mcpRuntimeValue}>
<DesktopStateProvider value={desktopStateValue}>
+ <GfsDragSessionProvider>
<main className="app-shell">
<SidebarNav
navItem={vm.navItem}
@@ -3076,6 +3078,7 @@ export function App() {
onClose={closePluginGfsPreview}
/>
) : null}
+ </GfsDragSessionProvider>
</DesktopStateProvider>
</McpRuntimeProvider>
</AgentChatProviders>
diff --git a/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/__tests__/FileExplorerTree.test.tsx b/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/__tests__/FileExplorerTree.test.tsx
index 88ef11e53..bb5834611 100644
--- a/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/__tests__/FileExplorerTree.test.tsx
+++ b/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/__tests__/FileExplorerTree.test.tsx
@@ -726,3 +726,266 @@ describe('FileExplorerTree — download-path authority wiring (R1-H8)', () => {
expect(pushToast).not.toHaveBeenCalledWith('401 Unauthorized', 'error')
})
})
+
+// ── drag-and-drop (rev-2 D1) ─────────────────────────────────────────────────
+
+import { GfsDragSessionProvider } from '@/gfs/dragSession'
+
+type DndProducers = Producers & {
+ affordances?: (resourceId: string, drive?: string) => Promise<unknown>
+ resolve?: (uri: string) => Promise<unknown>
+ moveResource?: (
+ resourceId: string,
+ destinationId: string,
+ drive?: string,
+ ifMatch?: number,
+ newName?: string
+ ) => Promise<unknown>
+}
+
+function installDndClerum(producers: DndProducers) {
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ gfs: {
+ listAccessible: producers.listAccessible ?? vi.fn(async () => listAccessiblePage([])),
+ listChildren: producers.listChildren ?? vi.fn(async () => listChildrenPage([])),
+ download:
+ producers.download ??
+ vi.fn(async () => downloadResult(resolvedFile('fallback', 'fallback.bin'))),
+ affordances: producers.affordances ?? vi.fn(async () => ({ held: ['read'] })),
+ resolve: producers.resolve ?? vi.fn(async () => { throw new Error('resolve not stubbed') }),
+ moveResource: producers.moveResource ?? vi.fn(async () => ({ resourceId: 'x', version: 2 })),
+ },
+ },
+ })
+}
+
+function dragTypes() {
+ return {
+ types: ['application/x-evenfire-gfs-resource'],
+ files: [],
+ effectAllowed: 'move',
+ dropEffect: 'none',
+ setData: vi.fn(),
+ }
+}
+
+function renderTreeWithSession(props: Partial<Parameters<typeof FileExplorerTree>[0]> = {}) {
+ const onOpenFolder = props.onOpenFolder ?? vi.fn()
+ const onOpenPreview = props.onOpenPreview ?? vi.fn()
+ const pushToast = props.pushToast ?? vi.fn()
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ render(
+ <QueryClientProvider client={queryClient}>
+ <GfsDragSessionProvider>
+ <FileExplorerTree
+ onOpenFolder={onOpenFolder}
+ onOpenPreview={onOpenPreview}
+ pushToast={pushToast}
+ />
+ </GfsDragSessionProvider>
+ </QueryClientProvider>
+ )
+ return { onOpenFolder, onOpenPreview, pushToast }
+}
+
+describe('FileExplorerTree — drag-and-drop moves', () => {
+ it('moves a dragged folder into an unrelated folder through the one confirmation', async () => {
+ // Two directly-shared folders under one unshared common parent 'grand':
+ // the drop must walk B's (bounded) ancestry, find the common anchor via
+ // the root, and admit the move on exact bits.
+ const moveResource = vi.fn(async () => ({ resourceId: 'foldera', version: 9 }))
+ const affordances = vi.fn(async (resourceId: string) => {
+ if (resourceId === 'folderb') return { held: ['read', 'write'] }
+ return { held: ['read', 'write', 'delete'] }
+ })
+ const resolve = vi.fn(async (uri: string) => {
+ const id = uri.split('/').pop()
+ const parent = id === 'grand' ? null : 'grand'
+ const name = id === 'foldera' ? 'A' : id === 'folderb' ? 'B' : 'Grand'
+ const resourceId = id === 'grand' ? 'grand' : id
+ return {
+ drive: 'main',
+ resourceId,
+ parentResourceId: parent,
+ name,
+ kind: 'directory',
+ version: id === 'foldera' ? 4 : 1,
+ }
+ })
+ installDndClerum({
+ listAccessible: vi.fn(async () =>
+ listAccessiblePage([
+ accessibleResource('foldera', 'A', 'directory', { version: 4 }),
+ accessibleResource('folderb', 'B', 'directory'),
+ ])
+ ),
+ affordances,
+ resolve,
+ moveResource,
+ })
+ const { pushToast } = renderTreeWithSession()
+
+ const rowA = await screen.findByRole('button', { name: 'A' })
+ const rowB = await screen.findByRole('button', { name: 'B' })
+ const dataTransfer = dragTypes()
+
+ fireEvent.dragStart(rowA, { dataTransfer })
+ const bTreeItem = rowB.closest('[role="treeitem"]')!.querySelector('.da-file-explorer__row')!
+ fireEvent.dragEnter(bTreeItem, { dataTransfer })
+
+ // Root-level folder sources resolve ancestry on DROP (bounded), not on
+ // hover; hover shows checking until cached bits decide structure-free
+ // facts. Drop performs the priority check.
+ fireEvent.dragOver(bTreeItem, { dataTransfer })
+ fireEvent.drop(bTreeItem, { dataTransfer })
+
+ const dialog = await screen.findByRole('dialog', { name: 'Move folder A to B' })
+ expect(
+ within(dialog).getByText(/Inherited access to this folder and its contents follows the new location/)
+ ).toBeTruthy()
+ await act(async () => {
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Move' }))
+ })
+
+ await waitFor(() => {
+ expect(moveResource).toHaveBeenCalledWith('foldera', 'folderb', 'main', 4, undefined)
+ })
+ await waitFor(() =>
+ expect(pushToast).toHaveBeenCalledWith('Moved A to B', 'success')
+ )
+ // Folder-impact info accompanies the success toast (rev-2 §1/§8).
+ expect(pushToast).toHaveBeenCalledWith(
+ 'Moving a folder changes who can access its contents — access now follows the new location.',
+ 'info'
+ )
+ expect(screen.queryByRole('dialog')).toBeNull()
+ })
+
+ it('refuses a same-parent drop before any request or confirmation', async () => {
+ const moveResource = vi.fn()
+ const affordances = vi.fn(async () => ({ held: ['read', 'write', 'delete'] }))
+ installDndClerum({
+ listAccessible: vi.fn(async () =>
+ listAccessiblePage([accessibleResource('parent-1', 'P', 'directory')])
+ ),
+ listChildren: vi.fn(async () =>
+ listChildrenPage([childView('folder-a', 'A', 'directory', { parentResourceId: 'parent-1' })])
+ ),
+ affordances,
+ moveResource,
+ })
+ const { pushToast } = renderTreeWithSession()
+
+ await screen.findByRole('button', { name: 'P' })
+ // Expand P (single-click, deferred) to reveal A.
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'P' }))
+ })
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'A' })).toBeTruthy()
+ })
+
+ const rowA = screen.getByRole('button', { name: 'A' })
+ const rowP = screen.getByRole('button', { name: 'P' })
+ const dataTransfer = dragTypes()
+ fireEvent.dragStart(rowA, { dataTransfer })
+ const pRow = rowP.closest('[role="treeitem"]')!.querySelector('.da-file-explorer__row')!
+ fireEvent.dragOver(pRow, { dataTransfer })
+ fireEvent.drop(pRow, { dataTransfer })
+
+ await waitFor(() => {
+ expect(pushToast).toHaveBeenCalledWith('This item is already in this folder.', 'error')
+ })
+ expect(moveResource).not.toHaveBeenCalled()
+ expect(screen.queryByRole('dialog')).toBeNull()
+ })
+
+ it('refuses a drop into the source folder’s own loaded descendant', async () => {
+ const moveResource = vi.fn()
+ installDndClerum({
+ listAccessible: vi.fn(async () =>
+ listAccessiblePage([accessibleResource('folder-a', 'A', 'directory')])
+ ),
+ listChildren: vi.fn(async () =>
+ listChildrenPage([childView('child-c', 'C', 'directory', { parentResourceId: 'folder-a' })])
+ ),
+ affordances: vi.fn(async () => ({ held: ['read', 'write', 'delete'] })),
+ moveResource,
+ })
+ const { pushToast } = renderTreeWithSession()
+
+ await act(async () => {
+ fireEvent.click(await screen.findByRole('button', { name: 'A' }))
+ })
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'C' })).toBeTruthy()
+ })
+
+ const rowA = screen.getByRole('button', { name: 'A' })
+ const rowC = screen.getByRole('button', { name: 'C' })
+ const dataTransfer = dragTypes()
+ fireEvent.dragStart(rowA, { dataTransfer })
+ const cRow = rowC.closest('[role="treeitem"]')!.querySelector('.da-file-explorer__row')!
+ fireEvent.dragOver(cRow, { dataTransfer })
+ expect(cRow.getAttribute('data-drop-state')).toBe('denied')
+ fireEvent.drop(cRow, { dataTransfer })
+
+ await waitFor(() => {
+ expect(pushToast).toHaveBeenCalledWith(
+ 'A folder cannot be moved into itself or one of its subfolders.',
+ 'error'
+ )
+ })
+ expect(moveResource).not.toHaveBeenCalled()
+ })
+
+ it('dragstart cancels the deferred folder toggle (no expansion after a drag)', async () => {
+ installDndClerum({
+ listAccessible: vi.fn(async () =>
+ listAccessiblePage([accessibleResource('folder-a', 'A', 'directory')])
+ ),
+ })
+ renderTreeWithSession()
+
+ const rowA = await screen.findByRole('button', { name: 'A' })
+ const dataTransfer = dragTypes()
+ fireEvent.click(rowA) // schedules the deferred toggle
+ fireEvent.dragStart(rowA, { dataTransfer }) // drag cancels the timer
+ fireEvent.dragEnd(rowA, { dataTransfer })
+ // Within the 250ms window the folder would have expanded without the
+ // cancellation; advance and assert it did not.
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 320))
+ })
+ const treeItem = rowA.closest('[role="treeitem"]')!
+ expect(treeItem.getAttribute('aria-expanded')).toBe('false')
+ })
+
+ it('row Move action and Shift+F10 open the existing Move dialog', async () => {
+ installDndClerum({
+ listAccessible: vi.fn(async () =>
+ listAccessiblePage([accessibleResource('folder-a', 'A', 'directory')])
+ ),
+ })
+ renderTreeWithSession()
+
+ await act(async () => {
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Move A to another folder' })
+ )
+ })
+ expect(await screen.findByRole('dialog', { name: 'Move folder A' })).toBeTruthy()
+ fireEvent.click(screen.getByRole('button', { name: 'Close move dialog' }))
+
+ // Shift+F10 on the row label opens the same dialog.
+ await act(async () => {
+ fireEvent.keyDown(await screen.findByRole('button', { name: 'A' }), {
+ key: 'F10',
+ shiftKey: true,
+ })
+ })
+ expect(await screen.findByRole('dialog', { name: 'Move folder A' })).toBeTruthy()
+ })
+})
diff --git a/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/index.tsx b/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/index.tsx
index 56afcf16a..4c05ce72d 100644
--- a/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/index.tsx
+++ b/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/index.tsx
@@ -2,18 +2,33 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query'
import { Badge, Button, IconButton, StatusBanner } from '@components/Common'
import { GfsFileIcon } from '@components/GfsFileIcon'
-import { GFS_DRIVE_MAIN } from '@constants/gfsBrowser'
+import {
+ FOLDER_HOVER_EXPAND_DELAY_MS,
+ GFS_DRIVE_MAIN,
+ GFS_RESOURCE_DRAG_TYPE,
+} from '@constants/gfsBrowser'
import { desktopQueryKeys } from '@hooks/domain/queryKeys'
import {
type GfsBrowserChild,
+ type GfsCrumb,
useGfsBrowserController,
} from '@hooks/domain/useGfsBrowserController'
import { saveGfsFileToDisk } from '@lib/gfsDownload'
import { resolveGfsPreview } from '@lib/gfsPreview'
import { sanitizeAppTabTitle } from '@lib/sanitizeAppTabTitle'
import { isGfsChildrenDenied, purgeDeniedGfsChildren } from '@/gfs/deniedChildren'
-import { IconChevronRight, IconContexts } from '../icons'
-import type { FileExplorerNodeProps, FileExplorerTreeProps } from './types'
+import { useGfsDragAdjudication } from '@/gfs/dragAdjudication'
+import type { GfsDragSource } from '@/gfs/dragSession'
+import { useGfsDragSession } from '@/gfs/dragSession'
+import { GfsMoveConfirmDialog } from '@/gfs/moveConfirmDialog'
+import { commitGfsMove, moveDenialMessage, toastMoveOutcome } from '@/gfs/moveCommit'
+import { GfsMoveDialog } from '@/gfs/moveDialog'
+import { IconChevronRight, IconContexts, IconMoreHorizontal } from '../icons'
+import type {
+ FileExplorerDropState,
+ FileExplorerNodeProps,
+ FileExplorerTreeProps,
+} from './types'
// A folder's single-click (toggle) must not act before we know a double-click
// (open its files tab) is not coming, so it is deferred by this window to let a
@@ -52,6 +67,8 @@ function sortTreeItems(items: GfsBrowserChild[]): GfsBrowserChild[] {
* Gestures differ by kind: a file activates on single-click (open its preview,
* or download when it is not previewable); a folder toggles expand/collapse on
* single-click and opens its files tab on double-click. Enter activates either.
+ * Files AND folders are draggable (rev-2 D1); directory rows are move targets,
+ * and a hover-dwelling collapsed folder expands through its existing loader.
*/
function FileExplorerNode({
node,
@@ -60,10 +77,21 @@ function FileExplorerNode({
accessActive,
expandedIds,
selectedId,
+ movingResourceId,
+ ancestorIds,
+ ancestorCrumbs,
+ dropState,
+ dropStatesByResourceId,
onToggle,
onActivateFolder,
onActivateFile,
onAuthorityFailure,
+ onNodeDragStart,
+ onNodeDragEnd,
+ onNodeDragOver,
+ onNodeDragLeave,
+ onNodeDrop,
+ onRequestMove,
}: FileExplorerNodeProps) {
const queryClient = useQueryClient()
const isDirectory = node.kind === 'directory'
@@ -153,19 +181,123 @@ function FileExplorerNode({
const handleRowKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLButtonElement>) => {
- if (event.key !== 'Enter') return
- // Stop the native button click Enter would otherwise fire (which would run
- // the row's single-click handler — a folder's deferred toggle); Enter
- // activates instead, matching the folder double-click / file single-click.
- event.preventDefault()
+ if (event.key === 'Enter') {
+ // Stop the native button click Enter would otherwise fire (which would run
+ // the row's single-click handler — a folder's deferred toggle); Enter
+ // activates instead, matching the folder double-click / file single-click.
+ event.preventDefault()
+ clearClickTimer()
+ runActivate()
+ return
+ }
+ // Shift+F10 opens the row's Move action contextually, matching the
+ // row-action discoverability of the Files page.
+ if (event.shiftKey && event.key === 'F10') {
+ event.preventDefault()
+ clearClickTimer()
+ onRequestMove(node, ancestorCrumbs)
+ }
+ },
+ [ancestorCrumbs, clearClickTimer, node, onRequestMove, runActivate]
+ )
+
+ const handleDragStart = useCallback(
+ (event: React.DragEvent<HTMLElement>) => {
+ // A drag must not fire the deferred folder toggle after release.
clearClickTimer()
- runActivate()
+ onNodeDragStart(node, event, ancestorIds)
},
- [clearClickTimer, runActivate]
+ [ancestorIds, clearClickTimer, node, onNodeDragStart]
+ )
+
+ const isDirectoryRow = isDirectory
+ const canDrag = isUnreadable !== true && movingResourceId == null
+
+ const handleRowDragOver = useCallback(
+ (event: React.DragEvent<HTMLDivElement>) => {
+ // Nested rows live in the sibling `.da-file-explorer__group`, so a child
+ // drop cannot bubble through an ancestor ROW — verify the closest marked
+ // row still matches before adjudicating (rev-2 §4.1).
+ if (event.target instanceof Element) {
+ const closestRow = event.target.closest('.da-file-explorer__row')
+ if (closestRow !== null && closestRow !== event.currentTarget) return
+ }
+ onNodeDragOver(node, event, ancestorIds)
+ },
+ [ancestorIds, node, onNodeDragOver]
+ )
+
+ const handleRowDrop = useCallback(
+ (event: React.DragEvent<HTMLDivElement>) => {
+ if (event.target instanceof Element) {
+ const closestRow = event.target.closest('.da-file-explorer__row')
+ if (closestRow !== null && closestRow !== event.currentTarget) return
+ }
+ onNodeDrop(node, event, ancestorIds)
+ },
+ [ancestorIds, node, onNodeDrop]
+ )
+
+ // Hover a collapsed directory for FOLDER_HOVER_EXPAND_DELAY_MS to expand it
+ // through its existing loader (rev-2 §4.1). The timer is owned here so a
+ // leave/drop/drag-end in this row cancels exactly its own expansion.
+ const hoverExpandTimerRef = useRef<number | null>(null)
+ const clearHoverExpand = useCallback(() => {
+ if (hoverExpandTimerRef.current !== null) {
+ clearTimeout(hoverExpandTimerRef.current)
+ hoverExpandTimerRef.current = null
+ }
+ }, [])
+ useEffect(() => clearHoverExpand, [clearHoverExpand])
+
+ const handleRowDragEnterOrOver = useCallback(
+ (event: React.DragEvent<HTMLDivElement>) => {
+ handleRowDragOver(event)
+ if (
+ isDirectoryRow &&
+ !isExpanded &&
+ (dropState === undefined || dropState === 'allowed' || dropState === 'checking')
+ ) {
+ if (hoverExpandTimerRef.current === null) {
+ hoverExpandTimerRef.current = window.setTimeout(() => {
+ hoverExpandTimerRef.current = null
+ onToggle(node.resourceId)
+ }, FOLDER_HOVER_EXPAND_DELAY_MS)
+ }
+ }
+ },
+ [dropState, handleRowDragOver, isDirectoryRow, isExpanded, node.resourceId, onToggle]
+ )
+
+ const handleRowDragLeave = useCallback(
+ (event: React.DragEvent<HTMLDivElement>) => {
+ if (event.currentTarget.contains(event.relatedTarget as Node | null)) return
+ clearHoverExpand()
+ onNodeDragLeave(node, event)
+ },
+ [clearHoverExpand, node, onNodeDragLeave]
)
const loadingChildren = Boolean(isExpanded && childQuery.isFetching && !childQuery.data)
const hasMoreChildren = Boolean(childQuery.hasNextPage)
+ const nextAncestorIds = useMemo(
+ () => [node.resourceId, ...ancestorIds],
+ [ancestorIds, node.resourceId]
+ )
+ const nextAncestorCrumbs = useMemo<GfsCrumb[]>(
+ () => [
+ ...ancestorCrumbs,
+ {
+ resourceId: node.resourceId,
+ gfsUri: node.gfsUri,
+ name: node.name,
+ kind: 'directory',
+ version: node.version,
+ bytes: node.bytes,
+ },
+ ],
+ [ancestorCrumbs, node]
+ )
return (
<div
@@ -175,7 +307,14 @@ function FileExplorerNode({
className="da-file-explorer__item"
role="treeitem"
>
- <div className="da-file-explorer__row">
+ <div
+ className={`da-file-explorer__row${dropState ? ` is-drop-${dropState}` : ''}`}
+ data-drop-state={isDirectory ? dropState : undefined}
+ onDragEnter={isDirectory ? handleRowDragEnterOrOver : undefined}
+ onDragOver={isDirectory ? handleRowDragEnterOrOver : undefined}
+ onDragLeave={isDirectory ? handleRowDragLeave : undefined}
+ onDrop={isDirectory ? handleRowDrop : undefined}
+ >
{isDirectory ? (
<IconButton
aria-expanded={isExpanded}
@@ -197,9 +336,13 @@ function FileExplorerNode({
isUnreadable ? ' da-file-explorer__label--no-access' : ''
}`}
color="neutral"
+ draggable={canDrag}
onClick={handleRowClick}
onDoubleClick={handleRowDoubleClick}
+ onDragStart={canDrag ? handleDragStart : undefined}
+ onDragEnd={canDrag ? onNodeDragEnd : undefined}
onKeyDown={handleRowKeyDown}
+ title={canDrag ? `Drag ${label} into a folder to move it` : undefined}
variant="text"
>
<span className="da-file-explorer__icon" aria-hidden="true">
@@ -214,6 +357,18 @@ function FileExplorerNode({
</Badge>
) : null}
</Button>
+ <IconButton
+ className="da-file-explorer__move-action"
+ label={`Move ${label} to another folder`}
+ onClick={() => {
+ clearClickTimer()
+ onRequestMove(node, ancestorCrumbs)
+ }}
+ size="sm"
+ variant="ghost"
+ >
+ <IconMoreHorizontal />
+ </IconButton>
</div>
{isExpanded ? (
<div className="da-file-explorer__group" role="group">
@@ -226,13 +381,24 @@ function FileExplorerNode({
{childItems.map(child => (
<FileExplorerNode
accessActive={accessActive}
+ ancestorCrumbs={nextAncestorCrumbs}
+ ancestorIds={nextAncestorIds}
+ dropState={dropStatesByResourceId[child.resourceId]}
+ dropStatesByResourceId={dropStatesByResourceId}
expandedIds={expandedIds}
key={child.resourceId}
level={level + 1}
+ movingResourceId={movingResourceId}
node={child}
onActivateFile={onActivateFile}
onActivateFolder={onActivateFolder}
onAuthorityFailure={onAuthorityFailure}
+ onNodeDragEnd={onNodeDragEnd}
+ onNodeDragLeave={onNodeDragLeave}
+ onNodeDragOver={onNodeDragOver}
+ onNodeDragStart={onNodeDragStart}
+ onNodeDrop={onNodeDrop}
+ onRequestMove={onRequestMove}
onToggle={onToggle}
scope={scope}
selectedId={selectedId}
@@ -267,6 +433,12 @@ function FileExplorerNode({
* instance shares the Files page's TanStack cache by query key, so folders the
* page already warmed render instantly and the discovery authority/fail-closed
* boundary is reused.
+ *
+ * Drag-and-drop (rev-2 D1): files AND folders drag from the tree; directory
+ * rows are move targets adjudicated by the shared drag session + policy
+ * (cross-surface drags from/to the Files page share one active source); a
+ * folder drop stops at ONE confirmation; commits run through the same shared
+ * move dispatch as the Files page.
*/
export function FileExplorerTree({
onOpenFolder,
@@ -274,8 +446,31 @@ export function FileExplorerTree({
pushToast,
}: FileExplorerTreeProps) {
const ctrl = useGfsBrowserController()
+ const dragSession = useGfsDragSession()
+ const adjudication = useGfsDragAdjudication({
+ scope: ctrl.sessionScope,
+ drive: GFS_DRIVE_MAIN,
+ resolve: (uri: string) => window.clerum.gfs.resolve(uri),
+ })
const [expandedIds, setExpandedIds] = useState<Set<string>>(() => new Set())
const [selectedId, setSelectedId] = useState<string | null>(null)
+ const [dropStatesByResourceId, setDropStatesByResourceId] = useState<
+ Record<string, FileExplorerDropState>
+ >({})
+ const [movingResourceId, setMovingResourceId] = useState<string | null>(null)
+ const movingResourceIdRef = useRef<string | null>(null)
+ const draggingSourceRef = useRef<GfsDragSource | null>(null)
+ const dragSessionEpochRef = useRef(0)
+ const [pendingFolderMove, setPendingFolderMove] = useState<{
+ source: GfsDragSource
+ destination: { resourceId: string; name: string }
+ allowNumberedRename: boolean
+ suggestedName?: string
+ } | null>(null)
+ const [moveDialogTarget, setMoveDialogTarget] = useState<{
+ node: GfsBrowserChild
+ initialCrumbs: GfsCrumb[]
+ } | null>(null)
const roots = useMemo(() => sortTreeItems(ctrl.accessibleResources), [ctrl.accessibleResources])
@@ -288,6 +483,251 @@ export function FileExplorerTree({
})
}, [])
+ const clearDragState = useCallback(() => {
+ dragSessionEpochRef.current += 1
+ draggingSourceRef.current = null
+ dragSession?.endDrag()
+ adjudication.endDragSession()
+ setDropStatesByResourceId({})
+ }, [adjudication, dragSession])
+
+ const treeDragSourceFrom = useCallback(
+ (
+ node: GfsBrowserChild,
+ ancestorIds: readonly (string | null)[]
+ ): Omit<GfsDragSource, 'generation'> => {
+ // Nested rows observe their loaded parent (nearest ancestor); forest
+ // roots only know the parent the accessible payload carried — unknown is
+ // never an invented root fact.
+ const parentKnown = ancestorIds.length > 0 || node.parentResourceId != null
+ const parentResourceId =
+ ancestorIds.length > 0 ? (ancestorIds[0] ?? null) : (node.parentResourceId ?? null)
+ return {
+ resourceId: node.resourceId,
+ gfsUri: node.gfsUri,
+ drive: node.drive || GFS_DRIVE_MAIN,
+ kind: node.kind === 'directory' ? 'directory' : 'file',
+ name: node.name,
+ ...(Number.isSafeInteger(node.version) ? { version: node.version } : {}),
+ parentKnown,
+ parentResourceId,
+ knownAncestorIds: ancestorIds.filter((id): id is string => id !== null),
+ origin: 'sidebar',
+ scope: ctrl.sessionScope ?? 'anonymous',
+ }
+ },
+ [ctrl.sessionScope]
+ )
+
+ const handleNodeDragStart = useCallback(
+ (
+ node: GfsBrowserChild,
+ event: React.DragEvent<HTMLElement>,
+ ancestorIds: readonly (string | null)[]
+ ) => {
+ if (node.readable === false || movingResourceIdRef.current) {
+ event.preventDefault()
+ return
+ }
+ dragSessionEpochRef.current += 1
+ const source: GfsDragSource = {
+ ...treeDragSourceFrom(node, ancestorIds),
+ generation: dragSessionEpochRef.current,
+ }
+ const { generation: _generation, ...sourceForStore } = source
+ dragSession?.beginDrag(sourceForStore)
+ adjudication.beginDragSession()
+ event.dataTransfer.effectAllowed = 'move'
+ event.dataTransfer.setData(GFS_RESOURCE_DRAG_TYPE, node.resourceId)
+ event.dataTransfer.setData('text/plain', node.name)
+ draggingSourceRef.current = source
+ },
+ [adjudication, dragSession, treeDragSourceFrom]
+ )
+
+ const resolveActiveSource = useCallback((): GfsDragSource | null => {
+ const fromSession = dragSession?.activeSource()
+ if (
+ fromSession &&
+ dragSession?.matchesScope(ctrl.sessionScope ?? 'anonymous') &&
+ fromSession.drive === GFS_DRIVE_MAIN
+ ) {
+ return fromSession
+ }
+ return draggingSourceRef.current
+ }, [ctrl.sessionScope, dragSession])
+
+ const handleNodeDragOver = useCallback(
+ (
+ node: GfsBrowserChild,
+ event: React.DragEvent<HTMLElement>,
+ ancestorIds: readonly (string | null)[]
+ ) => {
+ if (!Array.from(event.dataTransfer.types || []).includes(GFS_RESOURCE_DRAG_TYPE)) return
+ const source = resolveActiveSource()
+ if (!source || node.kind !== 'directory' || source.resourceId === node.resourceId) return
+ event.preventDefault()
+ event.stopPropagation()
+ const verdict = adjudication.hoverVerdict(source, {
+ resourceId: node.resourceId,
+ name: node.name,
+ kind: node.kind,
+ ancestorIds,
+ })
+ setDropStatesByResourceId(previous =>
+ previous[node.resourceId] === verdict.state
+ ? previous
+ : { ...previous, [node.resourceId]: verdict.state }
+ )
+ event.dataTransfer.dropEffect = verdict.state === 'allowed' ? 'move' : 'none'
+ if (verdict.state === 'checking') {
+ adjudication.scheduleColdCheck(
+ { resourceId: node.resourceId, name: node.name, kind: node.kind, ancestorIds },
+ source.parentKnown ? source.parentResourceId : null,
+ () => {
+ setDropStatesByResourceId(previous => {
+ const fresh = adjudication.hoverVerdict(source, {
+ resourceId: node.resourceId,
+ name: node.name,
+ kind: node.kind,
+ ancestorIds,
+ })
+ return previous[node.resourceId] === fresh.state
+ ? previous
+ : { ...previous, [node.resourceId]: fresh.state }
+ })
+ }
+ )
+ }
+ },
+ [adjudication, resolveActiveSource]
+ )
+
+ const handleNodeDragLeave = useCallback(
+ (node: GfsBrowserChild, event: React.DragEvent<HTMLElement>) => {
+ if (!Array.from(event.dataTransfer.types || []).includes(GFS_RESOURCE_DRAG_TYPE)) return
+ event.preventDefault()
+ event.stopPropagation()
+ setDropStatesByResourceId(previous => {
+ if (!(node.resourceId in previous)) return previous
+ const next = { ...previous }
+ delete next[node.resourceId]
+ return next
+ })
+ },
+ []
+ )
+
+ const commitMove = useCallback(
+ async (
+ source: GfsDragSource,
+ destination: { resourceId: string; name: string },
+ allowNumberedRename: boolean
+ ) => {
+ movingResourceIdRef.current = source.resourceId
+ setMovingResourceId(source.resourceId)
+ try {
+ const outcome = await commitGfsMove(
+ {
+ resolveSource: async gfsUri => {
+ const resolved = await window.clerum.gfs.resolve(gfsUri)
+ return {
+ resourceId: resolved.resourceId,
+ gfsUri,
+ kind: resolved.kind === 'directory' ? 'directory' : 'file',
+ name: resolved.name,
+ version: resolved.version,
+ parentResourceId: resolved.parentResourceId,
+ }
+ },
+ moveResource: (resourceId, destinationId, ifMatch, newName) =>
+ ctrl.moveResource(
+ resourceId,
+ destinationId,
+ ifMatch,
+ newName,
+ source.parentKnown ? source.parentResourceId : null
+ ),
+ isSessionAuthorityFailure: error =>
+ ctrl.handleAuthorityFailure(
+ error instanceof Error ? error.message : String(error),
+ 'operation'
+ ),
+ },
+ {
+ source: {
+ resourceId: source.resourceId,
+ gfsUri: source.gfsUri,
+ kind: source.kind,
+ name: source.name,
+ },
+ destination,
+ allowNumberedRename,
+ }
+ )
+ toastMoveOutcome(pushToast, outcome, source.name, destination.name, source.kind)
+ return outcome
+ } finally {
+ movingResourceIdRef.current = null
+ setMovingResourceId(null)
+ }
+ },
+ [ctrl, pushToast]
+ )
+
+ const handleNodeDrop = useCallback(
+ async (
+ node: GfsBrowserChild,
+ event: React.DragEvent<HTMLElement>,
+ ancestorIds: readonly (string | null)[]
+ ) => {
+ if (!Array.from(event.dataTransfer.types || []).includes(GFS_RESOURCE_DRAG_TYPE)) return
+ event.preventDefault()
+ event.stopPropagation()
+ setDropStatesByResourceId({})
+ const source = resolveActiveSource()
+ if (!source || node.kind !== 'directory' || movingResourceIdRef.current) return
+ const epoch = dragSessionEpochRef.current
+ try {
+ const decision = await adjudication.adjudicateDrop(source, {
+ resourceId: node.resourceId,
+ name: node.name,
+ kind: node.kind,
+ ancestorIds,
+ })
+ if (epoch !== dragSessionEpochRef.current) return
+ if (!decision.allowed) {
+ const message = moveDenialMessage(decision, node.name)
+ if (message) pushToast(message, 'error')
+ return
+ }
+ if (source.kind === 'directory') {
+ setPendingFolderMove({
+ source,
+ destination: { resourceId: node.resourceId, name: node.name },
+ allowNumberedRename: decision.allowNumberedRename,
+ })
+ return
+ }
+ await commitMove(
+ source,
+ { resourceId: node.resourceId, name: node.name },
+ decision.allowNumberedRename
+ )
+ } finally {
+ clearDragState()
+ }
+ },
+ [adjudication, clearDragState, commitMove, dragSessionEpochRef, pushToast, resolveActiveSource]
+ )
+
+ const handleRequestMove = useCallback(
+ (node: GfsBrowserChild, ancestorCrumbs: readonly GfsCrumb[]) => {
+ setMoveDialogTarget({ node, initialCrumbs: [...ancestorCrumbs] })
+ },
+ []
+ )
+
const handleActivateFolder = useCallback(
(node: GfsBrowserChild) => {
// A folder grant without inheritance lists the folder but denies its
@@ -384,15 +824,25 @@ export function FileExplorerTree({
{roots.map(node => (
<FileExplorerNode
accessActive={ctrl.accessState === 'active'}
+ ancestorCrumbs={[]}
+ ancestorIds={node.parentResourceId != null ? [node.parentResourceId] : []}
+ dropStatesByResourceId={dropStatesByResourceId}
expandedIds={expandedIds}
key={node.resourceId}
level={1}
+ movingResourceId={movingResourceId}
node={node}
onActivateFile={handleActivateFile}
onActivateFolder={handleActivateFolder}
onAuthorityFailure={handleAuthorityFailure}
+ onNodeDragEnd={clearDragState}
+ onNodeDragLeave={handleNodeDragLeave}
+ onNodeDragOver={handleNodeDragOver}
+ onNodeDragStart={handleNodeDragStart}
+ onNodeDrop={handleNodeDrop}
+ onRequestMove={handleRequestMove}
onToggle={handleToggle}
- scope={ctrl.sessionScope}
+ scope={ctrl.sessionScope ?? 'anonymous'}
selectedId={selectedId}
/>
))}
@@ -410,6 +860,82 @@ export function FileExplorerTree({
) : null}
</div>
)}
+
+ {pendingFolderMove ? (
+ <GfsMoveConfirmDialog
+ busy={movingResourceId === pendingFolderMove.source.resourceId}
+ request={{
+ sourceName: displayName(pendingFolderMove.source.name),
+ destinationName: displayName(pendingFolderMove.destination.name),
+ canRename: pendingFolderMove.allowNumberedRename,
+ ...(pendingFolderMove.suggestedName !== undefined
+ ? { suggestedName: pendingFolderMove.suggestedName }
+ : {}),
+ }}
+ onCancel={() => setPendingFolderMove(null)}
+ onConfirm={({ allowNumberedRename }) => {
+ const pending = pendingFolderMove
+ setPendingFolderMove(null)
+ if (pending) {
+ void commitMove(pending.source, pending.destination, allowNumberedRename)
+ }
+ }}
+ />
+ ) : null}
+
+ {moveDialogTarget ? (
+ <GfsMoveDialog
+ busy={ctrl.mutating}
+ initialCrumbs={moveDialogTarget.initialCrumbs}
+ onClose={() => setMoveDialogTarget(null)}
+ onMove={async (destinationId, destinationName) => {
+ const target = moveDialogTarget
+ const allowNumberedRename = await adjudication.probeSourceWrite(
+ target.node.resourceId
+ )
+ const source: GfsDragSource = {
+ resourceId: target.node.resourceId,
+ gfsUri: target.node.gfsUri,
+ drive: target.node.drive || GFS_DRIVE_MAIN,
+ kind: target.node.kind === 'directory' ? 'directory' : 'file',
+ name: target.node.name,
+ ...(Number.isSafeInteger(target.node.version)
+ ? { version: target.node.version }
+ : {}),
+ parentKnown: target.node.parentResourceId != null,
+ parentResourceId: target.node.parentResourceId ?? null,
+ knownAncestorIds: [],
+ origin: 'sidebar',
+ scope: ctrl.sessionScope ?? 'anonymous',
+ generation: dragSessionEpochRef.current,
+ }
+ const outcome = await commitMove(
+ source,
+ { resourceId: destinationId, name: destinationName },
+ allowNumberedRename
+ )
+ if (outcome.status === 'session-lost') {
+ setMoveDialogTarget(null)
+ return
+ }
+ if (outcome.status !== 'committed' && outcome.status !== 'no-op') {
+ throw new Error(outcome.message)
+ }
+ setMoveDialogTarget(null)
+ }}
+ onAuthorityFailure={message => {
+ handleAuthorityFailure(message)
+ return false
+ }}
+ sessionScope={ctrl.sessionScope}
+ target={{
+ resourceId: moveDialogTarget.node.resourceId,
+ name: moveDialogTarget.node.name,
+ kind: moveDialogTarget.node.kind === 'directory' ? 'directory' : 'file',
+ parentResourceId: moveDialogTarget.node.parentResourceId ?? null,
+ }}
+ />
+ ) : null}
</div>
)
}
diff --git a/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/types.ts b/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/types.ts
index 56f84a3d4..5ddd5dcd4 100644
--- a/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/types.ts
+++ b/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/types.ts
@@ -1,4 +1,5 @@
-import type { GfsBrowserChild } from '@hooks/domain/useGfsBrowserController'
+import type { DragEvent as ReactDragEvent } from 'react'
+import type { GfsBrowserChild, GfsCrumb } from '@hooks/domain/useGfsBrowserController'
import type { GfsPreviewResource } from '@lib/gfsPreview'
import type { Tone } from '@/uiTypes'
@@ -16,6 +17,8 @@ export interface FileExplorerTreeProps {
pushToast: (message: string, tone: Tone) => void
}
+export type FileExplorerDropState = 'checking' | 'allowed' | 'denied' | 'unavailable'
+
export interface FileExplorerNodeProps {
node: GfsBrowserChild
/** 1-based ARIA depth (`aria-level`). */
@@ -23,13 +26,44 @@ export interface FileExplorerNodeProps {
/** Cache-scope key shared with the Files page's TanStack queries. */
scope: string
/** Session access is live: gates the per-node children fetch the same way the
- * controller gates its own children query — a revoked session fetches nothing. */
+ * controller gates its own children query — a revoked session fetches nothing. */
accessActive: boolean
expandedIds: ReadonlySet<string>
selectedId: string | null
+ /** Resource id currently being moved (freezes drag starts), when a move the
+ * tree itself initiated is in flight. */
+ movingResourceId?: string | null
+ /** Loaded ancestors of this node, NEAREST-FIRST; drives the drag structure
+ * facts (common-anchor / descendant observations). */
+ ancestorIds: readonly (string | null)[]
+ /** Same ancestors as crumbs, ROOT-FIRST, for the Move dialog's initial path. */
+ ancestorCrumbs: readonly GfsCrumb[]
+ /** Live hover verdict for directory nodes (drop feedback). */
+ dropState?: FileExplorerDropState
+ /** Verdict map shared with descendant nodes (render feedback only). */
+ dropStatesByResourceId: Readonly<Record<string, FileExplorerDropState>>
onToggle: (resourceId: string) => void
onActivateFolder: (node: GfsBrowserChild) => void
onActivateFile: (node: GfsBrowserChild) => void
/** Fail-closed hook: a listing authority error revokes the session. */
onAuthorityFailure: (message: string) => void
+ onNodeDragStart: (
+ node: GfsBrowserChild,
+ event: ReactDragEvent<HTMLElement>,
+ ancestorIds: readonly (string | null)[]
+ ) => void
+ onNodeDragEnd: () => void
+ onNodeDragOver: (
+ node: GfsBrowserChild,
+ event: ReactDragEvent<HTMLElement>,
+ ancestorIds: readonly (string | null)[]
+ ) => void
+ onNodeDragLeave: (node: GfsBrowserChild, event: ReactDragEvent<HTMLElement>) => void
+ onNodeDrop: (
+ node: GfsBrowserChild,
+ event: ReactDragEvent<HTMLElement>,
+ ancestorIds: readonly (string | null)[]
+ ) => void
+ /** Open the existing Move dialog for this node (row action / Shift+F10). */
+ onRequestMove: (node: GfsBrowserChild, ancestorCrumbs: readonly GfsCrumb[]) => void
}
diff --git a/desktop-app/ui/src/gfs/__tests__/dragSession.test.tsx b/desktop-app/ui/src/gfs/__tests__/dragSession.test.tsx
new file mode 100644
index 000000000..336d37dcd
--- /dev/null
+++ b/desktop-app/ui/src/gfs/__tests__/dragSession.test.tsx
@@ -0,0 +1,121 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { cleanup, render, waitFor } from '@testing-library/react'
+import { desktopQueryKeys } from '@hooks/domain/queryKeys'
+import { GfsDragSessionProvider, GfsDragSessionStore, useGfsDragSession } from '../dragSession'
+import type { GfsDragSource } from '../dragSession.types'
+
+vi.mock('@contexts/AuthContext', () => ({
+ useAuthContext: () => authState,
+}))
+
+let authState = {
+ isAuthenticated: true,
+ me: { id: 'user-1', teamId: 'team-1' },
+ runtimeConfigState: { envKey: 'test' },
+}
+
+function source(overrides: Partial<Omit<GfsDragSource, 'generation'>> = {}) {
+ return {
+ resourceId: 'r-1',
+ gfsUri: 'gfs://main/r1',
+ drive: 'main',
+ kind: 'file' as const,
+ name: 'a.txt',
+ version: 2,
+ parentKnown: true,
+ parentResourceId: 'p-1',
+ knownAncestorIds: ['p-1'],
+ origin: 'sidebar' as const,
+ scope: 'test:user-1:team-1',
+ ...overrides,
+ }
+}
+
+beforeEach(() => {
+ authState = {
+ isAuthenticated: true,
+ me: { id: 'user-1', teamId: 'team-1' },
+ runtimeConfigState: { envKey: 'test' },
+ }
+})
+
+afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+})
+
+describe('GfsDragSessionStore — one active source per session', () => {
+ it('begins one drag, refuses a second, and clears on endDrag', () => {
+ const store = new GfsDragSessionStore()
+ expect(store.beginDrag(source())).toBe(true)
+ expect(store.beginDrag(source({ resourceId: 'r-2' }))).toBe(false)
+ expect(store.activeSource()?.resourceId).toBe('r-1')
+ store.endDrag()
+ expect(store.activeSource()).toBeNull()
+ // After clearing, a new drag can start with a fresh generation.
+ expect(store.beginDrag(source({ resourceId: 'r-2' }))).toBe(true)
+ expect(store.activeSource()?.generation).toBeGreaterThan(1)
+ })
+
+ it('matches scope only while the same session drag is active', () => {
+ const store = new GfsDragSessionStore()
+ expect(store.matchesScope('test:user-1:team-1')).toBe(false)
+ store.beginDrag(source())
+ expect(store.matchesScope('test:user-1:team-1')).toBe(true)
+ expect(store.matchesScope('other:user-1:team-1')).toBe(false)
+ expect(store.matchesScope(null)).toBe(false)
+ })
+
+ it('invalidate clears the source and bumps the generation (race discard)', () => {
+ const store = new GfsDragSessionStore()
+ store.beginDrag(source())
+ const generation = store.activeSource()!.generation
+ store.invalidate('authority')
+ expect(store.activeSource()).toBeNull()
+ expect(store.currentGeneration()).toBeGreaterThan(generation)
+ })
+})
+
+function Probe({ onApi }: { onApi: (api: ReturnType<typeof useGfsDragSession>) => void }) {
+ const api = useGfsDragSession()
+ onApi(api)
+ return null
+}
+
+describe('GfsDragSessionProvider — lifecycle binding', () => {
+ it('exposes begin/active/end through context and clears on revoked access state', async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ let api: ReturnType<typeof useGfsDragSession> | null = null
+ render(
+ <QueryClientProvider client={queryClient}>
+ <GfsDragSessionProvider>
+ <Probe onApi={captured => (api = captured)} />
+ </GfsDragSessionProvider>
+ </QueryClientProvider>
+ )
+ expect(api).not.toBeNull()
+ expect(api!.beginDrag(source())).toBe(true)
+ expect(api!.activeSource()?.resourceId).toBe('r-1')
+
+ // The shared fail-closed boundary writes 'revoked' via setQueryData; the
+ // provider subscription must clear the active drag in the same turn.
+ queryClient.setQueryData(desktopQueryKeys.gfsAccessState('test:user-1:team-1'), 'revoked')
+ await waitFor(() => expect(api!.activeSource()).toBeNull())
+ })
+
+ it('refuses to begin a drag for a foreign scope', () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ let api: ReturnType<typeof useGfsDragSession> | null = null
+ render(
+ <QueryClientProvider client={queryClient}>
+ <GfsDragSessionProvider>
+ <Probe onApi={captured => (api = captured)} />
+ </GfsDragSessionProvider>
+ </QueryClientProvider>
+ )
+ expect(api!.beginDrag(source({ scope: 'other:user-9:' }))).toBe(false)
+ expect(api!.activeSource()).toBeNull()
+ })
+})
diff --git a/desktop-app/ui/src/gfs/__tests__/moveCommit.test.ts b/desktop-app/ui/src/gfs/__tests__/moveCommit.test.ts
new file mode 100644
index 000000000..481c028dc
--- /dev/null
+++ b/desktop-app/ui/src/gfs/__tests__/moveCommit.test.ts
@@ -0,0 +1,198 @@
+import { describe, expect, it, vi } from 'vitest'
+import { commitGfsMove, suggestNumberedMoveName } from '../moveCommit'
+import type { MoveCommitSourceSnapshot } from '../moveCommit'
+import type { MoveCommitDeps, MoveCommitPlan } from '../moveCommit'
+
+function resolved(overrides: Partial<MoveCommitSourceSnapshot> = {}): MoveCommitSourceSnapshot {
+ return {
+ resourceId: 'r-1',
+ gfsUri: 'gfs://main/r1',
+ kind: 'file',
+ name: 'report.md',
+ version: 7,
+ parentResourceId: 'old-parent',
+ ...overrides,
+ }
+}
+
+function deps(overrides: Partial<MoveCommitDeps> = {}): MoveCommitDeps {
+ return {
+ resolveSource: vi.fn(async (_gfsUri: string) => resolved()),
+ moveResource: vi.fn(async () => ({ resourceId: 'r-1', version: 8 })),
+ isSessionAuthorityFailure: vi.fn(() => false),
+ ...overrides,
+ }
+}
+
+function plan(overrides: Partial<MoveCommitPlan> = {}): MoveCommitPlan {
+ return {
+ source: { resourceId: 'r-1', gfsUri: 'gfs://main/r1', kind: 'file', name: 'report.md' },
+ destination: { resourceId: 'dest-1', name: 'Dest' },
+ allowNumberedRename: false,
+ ...overrides,
+ }
+}
+
+describe('commitGfsMove — commit-time source refresh', () => {
+ it('resolves the source and sends exactly one PATCH with the fresh version and ifMatch', async () => {
+ const moveResource = vi.fn(async () => ({ resourceId: 'r-1', version: 8 }))
+ const outcome = await commitGfsMove(deps({ moveResource }), plan())
+ expect(outcome).toEqual({ status: 'committed', version: 8 })
+ expect(moveResource).toHaveBeenCalledTimes(1)
+ expect(moveResource).toHaveBeenCalledWith('r-1', 'dest-1', 7, undefined)
+ })
+
+ it('refuses without a request when the fresh parent already IS the destination (no-op)', async () => {
+ const moveResource = vi.fn()
+ const outcome = await commitGfsMove(
+ deps({
+ resolveSource: vi.fn(async () => resolved({ parentResourceId: 'dest-1' })),
+ moveResource,
+ }),
+ plan()
+ )
+ expect(outcome.status).toBe('no-op')
+ expect(moveResource).not.toHaveBeenCalled()
+ })
+
+ it('a missing source (404 on resolve) stops as source-unavailable', async () => {
+ const outcome = await commitGfsMove(
+ deps({
+ resolveSource: vi.fn(async () => {
+ throw new Error('404 Not Found: httpStatus=404')
+ }),
+ }),
+ plan()
+ )
+ expect(outcome.status).toBe('source-unavailable')
+ })
+
+ it('a session-authority failure on resolve fails closed', async () => {
+ const outcome = await commitGfsMove(
+ deps({
+ resolveSource: vi.fn(async () => {
+ throw new Error('401')
+ }),
+ isSessionAuthorityFailure: error => String(error) === 'Error: 401',
+ }),
+ plan()
+ )
+ expect(outcome.status).toBe('session-lost')
+ })
+})
+
+describe('commitGfsMove — conflict policy (rev-2 §5)', () => {
+ function conflictError(): Error {
+ const error = new Error(
+ 'Error invoking remote method: Error: 409 Conflict: a resource with this name already exists httpStatus=409'
+ )
+ return error
+ }
+
+ it('without a pre-approved policy a 409 stops with alternatives copy and no retry', async () => {
+ const moveResource = vi.fn(async () => {
+ throw conflictError()
+ })
+ const outcome = await commitGfsMove(deps({ moveResource }), plan())
+ expect(outcome.status).toBe('conflict-stopped')
+ if (outcome.status === 'conflict-stopped') {
+ expect(outcome.message).toContain('Choose another folder')
+ }
+ expect(moveResource).toHaveBeenCalledTimes(1)
+ })
+
+ it('with an approved policy it retries numbered names, whole-resource, capped at 3 attempts', async () => {
+ const moveResource = vi.fn().mockImplementation(async (_id: string, _dest: string, _v: number, newName?: string) => {
+ if (newName === undefined || newName === 'report.md') throw conflictError()
+ return { resourceId: 'r-1', version: 9 }
+ })
+ const outcome = await commitGfsMove(deps({ moveResource }), plan({ allowNumberedRename: true }))
+ expect(outcome).toEqual({ status: 'committed', version: 9, renamedTo: 'report (1).md' })
+ expect(moveResource).toHaveBeenCalledTimes(2)
+ expect(moveResource).toHaveBeenLastCalledWith('r-1', 'dest-1', 7, 'report (1).md')
+ })
+
+ it('a concurrent-name storm stops after the attempt cap with the destination-changed copy', async () => {
+ const moveResource = vi.fn(async () => {
+ throw conflictError()
+ })
+ const outcome = await commitGfsMove(deps({ moveResource }), plan({ allowNumberedRename: true }))
+ expect(outcome.status).toBe('conflict-stopped')
+ if (outcome.status === 'conflict-stopped') {
+ expect(outcome.message).toContain('The destination changed')
+ // Never claim all numbered names were used.
+ expect(outcome.message).not.toContain('all numbered names')
+ }
+ expect(moveResource).toHaveBeenCalledTimes(3)
+ })
+})
+
+describe('commitGfsMove — server verdicts', () => {
+ it('412 surfaces as changed and never auto re-PATCHes', async () => {
+ const moveResource = vi.fn(async () => {
+ throw new Error('412 Precondition Failed: httpStatus=412')
+ })
+ const outcome = await commitGfsMove(deps({ moveResource }), plan())
+ expect(outcome.status).toBe('changed')
+ expect(moveResource).toHaveBeenCalledTimes(1)
+ })
+
+ it('404 maps to target-unavailable', async () => {
+ const outcome = await commitGfsMove(
+ deps({
+ moveResource: vi.fn(async () => {
+ throw new Error('404 Not Found: httpStatus=404')
+ }),
+ }),
+ plan()
+ )
+ expect(outcome.status).toBe('target-unavailable')
+ })
+
+ it('429 maps to rate-limited with the parsed window', async () => {
+ const outcome = await commitGfsMove(
+ deps({
+ moveResource: vi.fn(async () => {
+ throw new Error('429 Too Many Requests: httpStatus=429 retryAfterSeconds=7')
+ }),
+ }),
+ plan()
+ )
+ expect(outcome.status).toBe('rate-limited')
+ if (outcome.status === 'rate-limited') expect(outcome.retryAfterSeconds).toBe(7)
+ })
+
+ it('transport loss after dispatch verifies by resolve and never repeats the PATCH', async () => {
+ const moveResource = vi.fn(async () => {
+ throw new Error('network error')
+ })
+ const resolveSource = vi
+ .fn()
+ // Pre-dispatch refresh: still in the old parent.
+ .mockResolvedValueOnce(resolved())
+ // Post-loss verification: the move actually landed.
+ .mockResolvedValueOnce(resolved({ parentResourceId: 'dest-1', version: 11 }))
+ const outcome = await commitGfsMove(deps({ moveResource, resolveSource }), plan())
+ expect(outcome).toEqual({ status: 'committed', version: 11 })
+ expect(moveResource).toHaveBeenCalledTimes(1)
+ })
+
+ it('an unverifiable transport loss stays unconfirmed', async () => {
+ const moveResource = vi.fn(async () => {
+ throw new Error('network error')
+ })
+ const outcome = await commitGfsMove(deps({ moveResource }), plan())
+ expect(outcome.status).toBe('unconfirmed')
+ expect(moveResource).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('suggestNumberedMoveName', () => {
+ it('proposes the first free numbered name only when the plain name is taken', () => {
+ expect(suggestNumberedMoveName('report.md', new Set(['other.md']))).toBeUndefined()
+ expect(suggestNumberedMoveName('report.md', new Set(['report.md']))).toBe('report (1).md')
+ expect(
+ suggestNumberedMoveName('report.md', new Set(['report.md', 'report (1).md']))
+ ).toBe('report (2).md')
+ })
+})
diff --git a/desktop-app/ui/src/gfs/dragAdjudication.ts b/desktop-app/ui/src/gfs/dragAdjudication.ts
new file mode 100644
index 000000000..39a97ccdc
--- /dev/null
+++ b/desktop-app/ui/src/gfs/dragAdjudication.ts
@@ -0,0 +1,368 @@
+import { useCallback, useRef } from 'react'
+import { useQueryClient } from '@tanstack/react-query'
+import { decideDragAuthority, decideDragStructure } from '@clerum/gfs-interaction-policy'
+import { DRAG_COLD_CHECK_BUDGET, DRAG_COLD_CHECK_DEBOUNCE_MS } from '@constants/gfsBrowser'
+import { desktopQueryKeys } from '@hooks/domain/queryKeys'
+import { describeGfsReadError, parseHttpStatus } from '@lib/gfsGrantErrors'
+import type {
+ GfsDragSource,
+ GfsDropDecision,
+ GfsDropRejection,
+ GfsDropTargetFact,
+ GfsDropVerdict,
+} from './dragSession.types'
+
+/** At most two ancestor resolves on drop when cached structure cannot decide. */
+const MAX_DROP_ANCESTOR_RESOLVES = 2
+/** Mutation-intent affordance freshness (rev-2 cache decisions). */
+const AFFORDANCES_HOVER_STALE_MS = 60_000
+const AFFORDANCES_MUTATION_STALE_MS = 5_000
+
+interface ResolvedLike {
+ resourceId: string
+ parentResourceId: string | null
+ name: string
+ version: number
+}
+
+export interface GfsDragAdjudicationDeps {
+ scope: string | null
+ drive: string
+ /** Resolve by stable URI (read plane; 403/404/429 throw). */
+ resolve: (gfsUri: string) => Promise<ResolvedLike>
+}
+
+interface HeldAffordances {
+ held: string[]
+}
+
+type AffordancesProbe = { ok: true; held: string[] } | { ok: false; error: unknown }
+
+/** Map a failed probe to a drop decision, or null when it should not decide. */
+function unavailableDecision(error: unknown): GfsDropRejection | null {
+ const status = parseHttpStatus(error instanceof Error ? error.message : String(error))
+ if (status === 401) return { allowed: false, reason: 'session-lost' }
+ if (status === 429) {
+ return {
+ allowed: false,
+ reason: 'unavailable',
+ message: describeGfsReadError(error).message,
+ }
+ }
+ if (status === 404) {
+ return {
+ allowed: false,
+ reason: 'target-unavailable',
+ message: 'This folder is no longer available.',
+ }
+ }
+ return null
+}
+
+/**
+ * Hover/drop adjudication shared by the Files page and the sidebar explorer
+ * (rev-2 §3, §4.1). Structure comes from loaded observations first (common
+ * anchor / breadcrumb chains); authority comes from the SHARED TanStack
+ * affordances keys — warm hover reads cache only, a cold target is debounced
+ * and budgeted (≤ DRAG_COLD_CHECK_BUDGET per drag), and over-budget targets
+ * stay "checking" and get a priority check on drop instead of a false deny.
+ */
+export function useGfsDragAdjudication(deps: GfsDragAdjudicationDeps) {
+ const queryClient = useQueryClient()
+ const coldChecksRef = useRef(0)
+ const debounceTimerRef = useRef<number | null>(null)
+ const inFlightRef = useRef(0)
+
+ const readCachedAffordances = useCallback(
+ (resourceId: string): HeldAffordances | null => {
+ if (!deps.scope) return null
+ return (
+ queryClient.getQueryData<HeldAffordances>(
+ desktopQueryKeys.gfsAffordances(deps.scope, resourceId, deps.drive)
+ ) ?? null
+ )
+ },
+ [deps.drive, deps.scope, queryClient]
+ )
+
+ const fetchAffordances = useCallback(
+ async (resourceId: string, staleTime: number): Promise<AffordancesProbe> => {
+ if (!deps.scope) return { ok: false, error: new Error('No active session scope') }
+ try {
+ const held = await queryClient.fetchQuery({
+ queryKey: desktopQueryKeys.gfsAffordances(deps.scope, resourceId, deps.drive),
+ queryFn: () => window.clerum.gfs.affordances(resourceId, deps.drive),
+ staleTime,
+ })
+ return { ok: true, held: held.held }
+ } catch (error) {
+ return { ok: false, error }
+ }
+ },
+ [deps.drive, deps.scope, queryClient]
+ )
+
+ /** Warm hover verdict: cached structure + cached bits; ZERO network reads. */
+ const hoverVerdict = useCallback(
+ (source: GfsDragSource, target: GfsDropTargetFact): GfsDropVerdict => {
+ if (target.kind !== 'directory') return { state: 'denied', reason: 'self' }
+ const structure = decideDragStructure({
+ source: {
+ resourceId: source.resourceId,
+ drive: source.drive,
+ kind: source.kind,
+ parentKnown: source.parentKnown,
+ parentResourceId: source.parentResourceId,
+ },
+ target: { resourceId: target.resourceId, drive: source.drive },
+ targetAncestorIds: target.ancestorIds,
+ knownSourceAncestorIds: new Set(source.knownAncestorIds),
+ })
+ if (structure.kind === 'deny') {
+ return { state: 'denied', reason: structure.reason }
+ }
+ const destinationHeld = readCachedAffordances(target.resourceId)
+ const sourceParentHeld = source.parentKnown
+ ? source.parentResourceId !== null
+ ? readCachedAffordances(source.parentResourceId)
+ : null
+ : null
+ if (destinationHeld === null || (source.parentKnown && sourceParentHeld === null)) {
+ return { state: 'checking' }
+ }
+ const authority = decideDragAuthority({
+ sourceParentHeld: sourceParentHeld?.held ?? null,
+ destinationHeld: destinationHeld.held,
+ })
+ if (authority.kind === 'deny') return { state: 'denied', reason: authority.reason }
+ if (authority.kind === 'observed-allowed' && structure.kind === 'observed-safe') {
+ return { state: 'allowed' }
+ }
+ return { state: 'checking' }
+ },
+ [readCachedAffordances]
+ )
+
+ /**
+ * Schedule one budgeted cold check for a hovered target: at most two
+ * feature requests (destination + known source parent) run concurrently
+ * after the dwell debounce; over-budget stays silent (drop performs the
+ * priority check). No network resolves happen on hover.
+ */
+ const scheduleColdCheck = useCallback(
+ (
+ target: GfsDropTargetFact,
+ sourceParentId: string | null,
+ onComplete: () => void
+ ) => {
+ if (inFlightRef.current >= 2) return
+ if (coldChecksRef.current >= DRAG_COLD_CHECK_BUDGET) return
+ coldChecksRef.current += 1
+ inFlightRef.current += 1
+ if (debounceTimerRef.current !== null) window.clearTimeout(debounceTimerRef.current)
+ debounceTimerRef.current = window.setTimeout(() => {
+ debounceTimerRef.current = null
+ void (async () => {
+ try {
+ if (readCachedAffordances(target.resourceId) === null) {
+ await fetchAffordances(target.resourceId, AFFORDANCES_HOVER_STALE_MS)
+ }
+ if (
+ sourceParentId !== null &&
+ readCachedAffordances(sourceParentId) === null
+ ) {
+ await fetchAffordances(sourceParentId, AFFORDANCES_HOVER_STALE_MS)
+ }
+ onComplete()
+ } finally {
+ inFlightRef.current -= 1
+ }
+ })()
+ }, DRAG_COLD_CHECK_DEBOUNCE_MS)
+ },
+ [fetchAffordances, readCachedAffordances]
+ )
+
+ /** Reset the per-drag budget (new dragstart). */
+ const beginDragSession = useCallback(() => {
+ coldChecksRef.current = 0
+ inFlightRef.current = 0
+ if (debounceTimerRef.current !== null) {
+ window.clearTimeout(debounceTimerRef.current)
+ debounceTimerRef.current = null
+ }
+ }, [])
+
+ const endDragSession = useCallback(() => {
+ if (debounceTimerRef.current !== null) {
+ window.clearTimeout(debounceTimerRef.current)
+ debounceTimerRef.current = null
+ }
+ }, [])
+
+ /**
+ * Bounded upward continuation of the target's ancestor chain (rev-2 §3.1):
+ * start from the oldest LOADED ancestor (or the target itself), resolve at
+ * most MAX_DROP_ANCESTOR_RESOLVES parents upward, stop on the physical root
+ * (null sentinel), a repetition, or a read 403/404 visibility boundary —
+ * never treat an unreadable ancestor as missing move rights.
+ */
+ const resolveAncestorsUpTo = useCallback(
+ async (source: GfsDragSource, target: GfsDropTargetFact): Promise<(string | null)[]> => {
+ const chain: (string | null)[] = [...target.ancestorIds]
+ const oldest = chain.length > 0 ? chain[chain.length - 1] : null
+ if (oldest === null && chain.length > 0) return chain // already at root
+ let nextIdToResolve: string = oldest ?? target.resourceId
+ for (let step = 0; step < MAX_DROP_ANCESTOR_RESOLVES; step += 1) {
+ const uri = `gfs://${source.drive}/${nextIdToResolve.replace(/-/g, '').toLowerCase()}`
+ let parent: string | null
+ try {
+ const resolved = await deps.resolve(uri)
+ parent = resolved.parentResourceId
+ } catch (error) {
+ const status = parseHttpStatus(error instanceof Error ? error.message : String(error))
+ if (status === 403 || status === 404) return chain
+ throw error
+ }
+ if (parent === null) {
+ chain.push(null)
+ return chain
+ }
+ if (chain.includes(parent)) return chain
+ chain.push(parent)
+ nextIdToResolve = parent
+ }
+ return chain
+ },
+ [deps]
+ )
+
+ /**
+ * Priority drop admission (rev-2 §3): immutable facts → structure (loaded,
+ * then ≤2 ancestor resolves for folders) → exact authority via fresh (5 s)
+ * affordances → rename capability via source-resource write. Never denies on
+ * an unproved structure; the atomic server PATCH is the backstop.
+ */
+ const adjudicateDrop = useCallback(
+ async (source: GfsDragSource, target: GfsDropTargetFact): Promise<GfsDropDecision> => {
+ if (target.kind !== 'directory') {
+ return { allowed: false, reason: 'self', message: 'A folder destination is required.' }
+ }
+ const structureFacts = {
+ source: {
+ resourceId: source.resourceId,
+ drive: source.drive,
+ kind: source.kind,
+ parentKnown: source.parentKnown,
+ parentResourceId: source.parentResourceId,
+ } as const,
+ target: { resourceId: target.resourceId, drive: source.drive } as const,
+ }
+ let structure = decideDragStructure({
+ ...structureFacts,
+ targetAncestorIds: target.ancestorIds,
+ knownSourceAncestorIds: new Set(source.knownAncestorIds),
+ })
+ if (structure.kind === 'server-check-required' && source.kind === 'directory') {
+ try {
+ const chain = await resolveAncestorsUpTo(source, target)
+ structure = decideDragStructure({
+ ...structureFacts,
+ targetAncestorIds: chain,
+ knownSourceAncestorIds: new Set(source.knownAncestorIds),
+ })
+ } catch {
+ // Unreadable ancestry stays server-check-required; proceed below —
+ // a read failure upward is a visibility boundary, not a denial.
+ }
+ }
+
+ if (structure.kind === 'deny') {
+ return { allowed: false, reason: structure.reason }
+ }
+
+ // Exact authority: destination write + source-parent write & delete.
+ let sourceParentForProbe: string | null = source.parentKnown
+ ? source.parentResourceId
+ : null
+ if (sourceParentForProbe === null) {
+ try {
+ const resolved = await deps.resolve(source.gfsUri)
+ sourceParentForProbe = resolved.parentResourceId
+ } catch (error) {
+ const status = parseHttpStatus(error instanceof Error ? error.message : String(error))
+ if (status === 401) return { allowed: false, reason: 'session-lost' }
+ if (status === 404) {
+ return {
+ allowed: false,
+ reason: 'source-location-unknown',
+ message: 'EvenDrive cannot verify this item’s current location. Refresh and try again.',
+ }
+ }
+ return {
+ allowed: false,
+ reason: 'unavailable',
+ message: describeGfsReadError(error).message,
+ }
+ }
+ }
+ if (sourceParentForProbe === null) {
+ // Physical root source.
+ return { allowed: false, reason: 'root-source' }
+ }
+
+ const destinationProbe = await fetchAffordances(target.resourceId, AFFORDANCES_MUTATION_STALE_MS)
+ if (!destinationProbe.ok) {
+ const decision = unavailableDecision(destinationProbe.error)
+ if (decision) return decision
+ }
+ const sourceParentProbe = await fetchAffordances(
+ sourceParentForProbe,
+ AFFORDANCES_MUTATION_STALE_MS
+ )
+ if (!sourceParentProbe.ok) {
+ const decision = unavailableDecision(sourceParentProbe.error)
+ if (decision) return decision
+ }
+ const authority = decideDragAuthority({
+ destinationHeld: destinationProbe.ok ? destinationProbe.held : null,
+ sourceParentHeld: sourceParentProbe.ok ? sourceParentProbe.held : null,
+ })
+ if (authority.kind === 'deny') return { allowed: false, reason: authority.reason }
+
+ // Rename capability (not user consent): source-resource write proves a
+ // combined rename+move; the folder confirmation records the opt-in.
+ const sourceProbe = await fetchAffordances(source.resourceId, AFFORDANCES_MUTATION_STALE_MS)
+ const canRename = sourceProbe.ok && sourceProbe.held.includes('write')
+
+ return {
+ allowed: true,
+ allowNumberedRename: canRename,
+ structure,
+ authority: { kind: 'observed-allowed', checkedAt: Date.now() },
+ }
+ },
+ [deps, fetchAffordances, resolveAncestorsUpTo]
+ )
+
+ /** Fresh (5 s) source-resource write probe for the rename policy. */
+ const probeSourceWrite = useCallback(
+ async (resourceId: string): Promise<boolean> => {
+ const cached = readCachedAffordances(resourceId)
+ if (cached?.held.includes('write')) return true
+ const fresh = await fetchAffordances(resourceId, AFFORDANCES_MUTATION_STALE_MS)
+ return fresh.ok && fresh.held.includes('write')
+ },
+ [fetchAffordances, readCachedAffordances]
+ )
+
+ return {
+ hoverVerdict,
+ scheduleColdCheck,
+ beginDragSession,
+ endDragSession,
+ adjudicateDrop,
+ probeSourceWrite,
+ readCachedAffordances,
+ }
+}
diff --git a/desktop-app/ui/src/gfs/dragSession.tsx b/desktop-app/ui/src/gfs/dragSession.tsx
index 198315317..63a84d40c 100644
--- a/desktop-app/ui/src/gfs/dragSession.tsx
+++ b/desktop-app/ui/src/gfs/dragSession.tsx
@@ -4,6 +4,8 @@ import { useAuthContext } from '@contexts/AuthContext'
import { desktopQueryKeys } from '@hooks/domain/queryKeys'
import type { GfsDragSessionApi, GfsDragSource } from './dragSession.types'
+type GfsAccessState = 'active' | 'revoked'
+
/**
* Per-session drag coordinator (rev-2 §4): exactly one active in-window
* source, held in refs (dragover never re-renders the tree). The store is
@@ -37,7 +39,7 @@ export class GfsDragSessionStore implements GfsDragSessionApi {
return this.active !== null && scope !== null && this.boundScope === scope
}
- invalidate(): void {
+ invalidate(_reason?: 'authority' | 'scope-change'): void {
this.active = null
// Bump so in-flight callbacks captured against an older generation are
// discarded by their owners (`source.generation !== activeSource()`).
@@ -49,6 +51,13 @@ export class GfsDragSessionStore implements GfsDragSessionApi {
}
}
+export type {
+ GfsDragSource,
+ GfsDropDecision,
+ GfsDropRejection,
+ GfsDropVerdict,
+} from './dragSession.types'
+
const GfsDragSessionContext = createContext<GfsDragSessionApi | null>(null)
function sessionScopeOf(auth: {
@@ -80,13 +89,13 @@ export function GfsDragSessionProvider({ children }: { children: React.ReactNode
// a revocation, and 'active' is the safe default while nothing wrote yet).
const accessStateQuery = useQuery({
queryKey: desktopQueryKeys.gfsAccessState(scope ?? 'anonymous'),
- queryFn: () => 'active' as const,
+ queryFn: (): GfsAccessState => 'active',
enabled: false,
- initialData: 'active' as const,
+ initialData: 'active' as GfsAccessState,
gcTime: Infinity,
staleTime: Infinity,
})
- const accessState = accessStateQuery.data ?? 'active'
+ const accessState: GfsAccessState = accessStateQuery.data ?? 'active'
useEffect(() => {
if (scope === null || accessState === 'revoked') store.invalidate('authority')
@@ -98,6 +107,9 @@ export function GfsDragSessionProvider({ children }: { children: React.ReactNode
() => ({
beginDrag: source => {
if (scope === null || accessState !== 'active') return false
+ // A drag started under another env/user/team never crosses into this
+ // session (foreign/other-window drags stay inert).
+ if (source.scope !== scope) return false
return store.beginDrag(source)
},
endDrag: () => store.endDrag(),
diff --git a/desktop-app/ui/src/gfs/dragSession.types.ts b/desktop-app/ui/src/gfs/dragSession.types.ts
index 674a79125..8093f6823 100644
--- a/desktop-app/ui/src/gfs/dragSession.types.ts
+++ b/desktop-app/ui/src/gfs/dragSession.types.ts
@@ -49,8 +49,9 @@ export interface GfsDropTargetFact {
resourceId: string
name: string
kind: 'file' | 'directory'
- /** Loaded ancestors of the target, nearest-first (observation only). */
- ancestorIds: readonly string[]
+ /** Loaded ancestors of the target, nearest-first; trailing null = observed
+ * to the physical root (observation only). */
+ ancestorIds: readonly (string | null)[]
}
export type GfsDropVerdict =
diff --git a/desktop-app/ui/src/gfs/moveCommit.ts b/desktop-app/ui/src/gfs/moveCommit.ts
new file mode 100644
index 000000000..c77ca3633
--- /dev/null
+++ b/desktop-app/ui/src/gfs/moveCommit.ts
@@ -0,0 +1,274 @@
+import {
+ GFS_MOVE_MAX_NETWORK_ATTEMPTS,
+ isGfsNameConflict,
+ nextAvailableGfsResourceName,
+} from '@clerum/gfs-interaction-policy'
+import { parseHttpStatus, parseRetryAfterSeconds } from '@lib/gfsGrantErrors'
+import type { GfsDropRejection } from './dragSession.types'
+
+/** Server truth from a commit-time resolve of the source. */
+export interface MoveCommitSourceSnapshot {
+ resourceId: string
+ gfsUri: string
+ kind: 'file' | 'directory'
+ /** Server-observed name/version/parent right before dispatch. */
+ name: string
+ version: number
+ parentResourceId: string | null
+}
+
+export interface MoveCommitPlan {
+ source: { resourceId: string; gfsUri: string; kind: 'file' | 'directory'; name: string }
+ destination: { resourceId: string; name: string }
+ /** Pre-approved numbered-name conflict policy (rev-2 §5). */
+ allowNumberedRename: boolean
+ /** Names already known to be taken in the destination, when cached. */
+ occupiedDestinationNames?: ReadonlySet<string>
+}
+
+export type MoveCommitOutcome =
+ | { status: 'committed'; version: number; renamedTo?: string }
+ | { status: 'no-op'; message: string }
+ | { status: 'conflict-stopped'; message: string }
+ | { status: 'changed'; message: string }
+ | { status: 'source-unavailable'; message: string }
+ | { status: 'target-unavailable'; message: string }
+ | { status: 'rate-limited'; message: string; retryAfterSeconds?: number }
+ | { status: 'unconfirmed'; message: string }
+ | { status: 'session-lost' }
+
+export interface MoveCommitDeps {
+ /** Resolve by stable URI; throws on 403/404/transport like the read plane. */
+ resolveSource: (gfsUri: string) => Promise<MoveCommitSourceSnapshot>
+ /** One move PATCH attempt; ifMatch is mandatory client policy. */
+ moveResource: (
+ resourceId: string,
+ destinationId: string,
+ ifMatch: number,
+ newName?: string
+ ) => Promise<{ resourceId: string; version: number }>
+ /** Central fail-closed classifier; returns true when the session died. */
+ isSessionAuthorityFailure: (error: unknown) => boolean
+}
+
+function messageOf(error: unknown): string {
+ return error instanceof Error ? error.message : String(error)
+}
+
+/**
+ * Shared move dispatch (rev-2 §5): one service called by the Files page,
+ * the sidebar explorer and the Move-dialog adapters. Every attempt is ONE
+ * PATCH with newParentId (+ optional newName for the whole-resource rename);
+ * never a separate rename-then-move. The source is re-resolved immediately
+ * before dispatch — its fresh version is the ifMatch, its fresh parent
+ * re-checks the no-op guard, and a missing source stops the gesture.
+ */
+export async function commitGfsMove(
+ deps: MoveCommitDeps,
+ plan: MoveCommitPlan
+): Promise<MoveCommitOutcome> {
+ let snapshot: MoveCommitSourceSnapshot
+ try {
+ const resolved = await deps.resolveSource(plan.source.gfsUri)
+ snapshot = {
+ resourceId: resolved.resourceId,
+ gfsUri: plan.source.gfsUri,
+ kind: resolved.kind === 'directory' ? 'directory' : 'file',
+ name: resolved.name,
+ version: resolved.version,
+ parentResourceId: resolved.parentResourceId,
+ }
+ } catch (error) {
+ if (deps.isSessionAuthorityFailure(error)) return { status: 'session-lost' }
+ const status = parseHttpStatus(messageOf(error))
+ if (status === 404) {
+ return {
+ status: 'source-unavailable',
+ message: 'EvenDrive cannot verify this item’s current location. Refresh and try again.',
+ }
+ }
+ return { status: 'unconfirmed', message: messageOf(error) }
+ }
+
+ // Fresh-parent no-op guard before any request (a concurrent move may have
+ // already relocated the item into the chosen destination).
+ if (snapshot.parentResourceId === plan.destination.resourceId) {
+ return { status: 'no-op', message: 'This item is already in this folder.' }
+ }
+
+ const occupied = new Set<string>(plan.occupiedDestinationNames ?? [])
+ let moveName = snapshot.name
+
+ for (let attempt = 0; attempt < GFS_MOVE_MAX_NETWORK_ATTEMPTS; attempt += 1) {
+ let error: unknown
+ try {
+ const receipt = await deps.moveResource(
+ snapshot.resourceId,
+ plan.destination.resourceId,
+ snapshot.version,
+ moveName === snapshot.name ? undefined : moveName
+ )
+ return {
+ status: 'committed',
+ version: receipt.version,
+ ...(moveName !== snapshot.name ? { renamedTo: moveName } : {}),
+ }
+ } catch (attemptError) {
+ error = attemptError
+ }
+ if (deps.isSessionAuthorityFailure(error)) return { status: 'session-lost' }
+
+ const message = messageOf(error)
+ const status = parseHttpStatus(message)
+ if (status === 412) {
+ // No automatic re-PATCH: the item changed; require a new gesture.
+ return {
+ status: 'changed',
+ message: 'This item changed while you were moving it. Review its current location and try again.',
+ }
+ }
+ if (status === 404) {
+ return { status: 'target-unavailable', message: 'This folder is no longer available.' }
+ }
+ if (status === 403) {
+ // Generic unless a successful permission recheck proves the missing bit;
+ // the pre-commit probes own the exact-reason copy.
+ return { status: 'unconfirmed', message }
+ }
+ if (status === 429 || (!status && /too many/i.test(message))) {
+ return {
+ status: 'rate-limited',
+ message: 'Too many file requests — try again shortly.',
+ ...(parseRetryAfterSeconds(message) !== null
+ ? { retryAfterSeconds: parseRetryAfterSeconds(message) ?? undefined }
+ : {}),
+ }
+ }
+ if (status !== 409 && !isGfsNameConflict(error)) {
+ // Transport loss after dispatch: verify the outcome by identity; never
+ // repeat a possibly committed move.
+ const verified = await verifyOutcomeByResolve(deps, plan, snapshot)
+ if (verified) return verified
+ return {
+ status: 'unconfirmed',
+ message: 'Couldn’t confirm the move. Refresh before trying again.',
+ }
+ }
+
+ // 409 name conflict.
+ if (!plan.allowNumberedRename) {
+ return {
+ status: 'conflict-stopped',
+ message:
+ 'An item with this name already exists. Choose another folder, or use Move to change its name if you have rename access.',
+ }
+ }
+ occupied.add(moveName)
+ if (attempt + 1 >= GFS_MOVE_MAX_NETWORK_ATTEMPTS) break
+ moveName = nextAvailableGfsResourceName(snapshot.name, occupied)
+ }
+ // Bounded attempts exhausted under an approved rename policy: a concurrent
+ // naming storm, not "all numbered names used".
+ return {
+ status: 'conflict-stopped',
+ message: 'The destination changed. Refresh it or choose another folder.',
+ }
+}
+
+/**
+ * Post-transport-loss verification (rev-2 §5): resolve the source by its
+ * stable URI and compare parent/version — only if that read is authorized.
+ * Returns null when the outcome stays unknown.
+ */
+async function verifyOutcomeByResolve(
+ deps: MoveCommitDeps,
+ plan: MoveCommitPlan,
+ before: MoveCommitSourceSnapshot
+): Promise<MoveCommitOutcome | null> {
+ try {
+ const resolved = await deps.resolveSource(plan.source.gfsUri)
+ if (resolved.parentResourceId === plan.destination.resourceId) {
+ return {
+ status: 'committed',
+ version: resolved.version,
+ ...(resolved.name !== before.name ? { renamedTo: resolved.name } : {}),
+ }
+ }
+ return null
+ } catch {
+ return null
+ }
+}
+
+/** Suggested rename candidate for confirmation UI (never dispatched alone). */
+export function suggestNumberedMoveName(
+ sourceName: string,
+ occupiedDestinationNames: ReadonlySet<string>
+): string | undefined {
+ if (!occupiedDestinationNames.has(sourceName)) return undefined
+ return nextAvailableGfsResourceName(sourceName, occupiedDestinationNames)
+}
+
+
+export type MoveToast = (message: string, tone: 'success' | 'error' | 'info') => void
+
+/** Presented outcome toasts (rev-2 §8 UX matrix) shared by every surface. */
+export function toastMoveOutcome(
+ pushToast: MoveToast | undefined,
+ outcome: MoveCommitOutcome,
+ sourceName: string,
+ destinationName: string,
+ sourceKind: 'file' | 'directory'
+): void {
+ switch (outcome.status) {
+ case 'committed':
+ pushToast?.(
+ outcome.renamedTo
+ ? `Moved ${sourceName} to ${destinationName} as ${outcome.renamedTo}`
+ : `Moved ${sourceName} to ${destinationName}`,
+ 'success'
+ )
+ if (sourceKind === 'directory') {
+ pushToast?.(
+ 'Moving a folder changes who can access its contents — access now follows the new location.',
+ 'info'
+ )
+ }
+ break
+ case 'no-op':
+ pushToast?.(outcome.message, 'info')
+ break
+ case 'session-lost':
+ break
+ default:
+ pushToast?.(outcome.message, 'error')
+ }
+}
+
+/** Exact-reason denial copy (rev-2 §8). Null = stay silent (session-lost). */
+export function moveDenialMessage(
+ rejection: GfsDropRejection,
+ destinationName: string
+): string | null {
+ switch (rejection.reason) {
+ case 'destination-write':
+ return `You can’t move files to ${destinationName} because you don’t have write permission for this folder.`
+ case 'source-write':
+ return 'You cannot move this item out of its current folder without write access there.'
+ case 'source-delete':
+ return 'You do not have permission to remove this item from its current folder.'
+ case 'same-parent':
+ return 'This item is already in this folder.'
+ case 'self':
+ case 'descendant':
+ return 'A folder cannot be moved into itself or one of its subfolders.'
+ case 'root-source':
+ return 'The top-level folder cannot be moved.'
+ case 'cross-drive':
+ return 'Items can’t be moved between drives.'
+ case 'session-lost':
+ return null
+ default:
+ return rejection.message ?? 'This move is not available right now. Try again in a moment.'
+ }
+}
diff --git a/desktop-app/ui/src/gfs/moveConfirmDialog.tsx b/desktop-app/ui/src/gfs/moveConfirmDialog.tsx
new file mode 100644
index 000000000..ad907970a
--- /dev/null
+++ b/desktop-app/ui/src/gfs/moveConfirmDialog.tsx
@@ -0,0 +1,111 @@
+import { useEffect, useRef, useState } from 'react'
+import { Button } from '@components/Common'
+import { IconContexts } from '@components/SidebarNav/icons'
+
+export interface GfsMoveConfirmRequest {
+ /** Sanitizable display facts of the moving folder. */
+ sourceName: string
+ destinationName: string
+ /** Suggested numbered-name candidate, when destination names are known. */
+ suggestedName?: string
+ /** Numbered renaming is allowed (source-resource write proved). */
+ canRename: boolean
+}
+
+export interface GfsMoveConfirmDialogProps {
+ request: GfsMoveConfirmRequest
+ busy?: boolean
+ onConfirm: (options: { allowNumberedRename: boolean }) => void
+ onCancel: () => void
+}
+
+/**
+ * The ONE confirmation for folder moves (rev-2 §1): explains the
+ * inherited-access impact and records the conflict naming policy in the same
+ * dialog, so no second automatic prompt follows the drop. Files move without
+ * confirmation. Escape/Cancel end the admission before dispatch; once the
+ * PATCH is dispatched it cannot be recalled.
+ */
+export function GfsMoveConfirmDialog({
+ request,
+ busy = false,
+ onConfirm,
+ onCancel,
+}: GfsMoveConfirmDialogProps) {
+ const [allowNumberedRename, setAllowNumberedRename] = useState(false)
+ const cancelButtonRef = useRef<HTMLButtonElement | null>(null)
+
+ useEffect(() => {
+ cancelButtonRef.current?.focus()
+ }, [])
+
+ useEffect(() => {
+ if (busy) return
+ function handleKeyDown(event: KeyboardEvent) {
+ if (event.key === 'Escape') onCancel()
+ }
+ window.addEventListener('keydown', handleKeyDown)
+ return () => window.removeEventListener('keydown', handleKeyDown)
+ }, [busy, onCancel])
+
+ return (
+ <div
+ className="da-gfs-manage-modal"
+ role="presentation"
+ onMouseDown={event => {
+ if (!busy && event.target === event.currentTarget) onCancel()
+ }}
+ >
+ <section
+ aria-label={`Move folder ${request.sourceName} to ${request.destinationName}`}
+ aria-modal="true"
+ className="da-gfs-manage-dialog da-gfs-move-confirm-dialog"
+ role="dialog"
+ >
+ <header className="da-gfs-manage-dialog__header">
+ <span className="da-gfs-manage-dialog__icon" aria-hidden="true">
+ <IconContexts />
+ </span>
+ <span className="da-gfs-manage-dialog__heading">
+ <h3>
+ Move “{request.sourceName}” to “{request.destinationName}”?
+ </h3>
+ </span>
+ </header>
+ <div className="da-gfs-manage-dialog__body">
+ <p className="da-gfs-move-confirm-dialog__impact">
+ Inherited access to this folder and its contents follows the new location. Direct
+ sharing entries stay with their items, and you may lose access.
+ </p>
+ {request.canRename ? (
+ <label className="da-gfs-move-confirm-dialog__rename-toggle">
+ <input
+ checked={allowNumberedRename}
+ disabled={busy}
+ onChange={event => setAllowNumberedRename(event.target.checked)}
+ type="checkbox"
+ />
+ <span>
+ {request.suggestedName
+ ? `Use a numbered name if needed (e.g. “${request.suggestedName}”)`
+ : 'Use a numbered name if needed'}
+ </span>
+ </label>
+ ) : null}
+ </div>
+ <footer className="da-gfs-move-confirm-dialog__actions">
+ <Button disabled={busy} onClick={onCancel} ref={cancelButtonRef} variant="ghost">
+ Cancel
+ </Button>
+ <Button
+ disabled={busy}
+ onClick={() => onConfirm({ allowNumberedRename })}
+ variant="solid"
+ >
+ {busy ? 'Moving…' : 'Move'}
+ </Button>
+ </footer>
+ </section>
+ </div>
+ )
+}
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
index 7bbdc4527..410ad28a7 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useGfsBrowserController.test.tsx
@@ -2082,7 +2082,7 @@ describe('useGfsBrowserController', () => {
screen.getByRole('button', { name: 'move current' }).click()
})
await waitFor(() =>
- expect(moveResource).toHaveBeenCalledWith(docsId, 'destination-1', 'main', 3)
+ expect(moveResource).toHaveBeenCalledWith(docsId, 'destination-1', 'main', 3, undefined)
)
// Navigation reconciles to the new location and consumes the new version.
await waitFor(() =>
diff --git a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
index 749fac91f..63c77c4eb 100644
--- a/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
+++ b/desktop-app/ui/src/hooks/domain/useGfsBrowserController.ts
@@ -17,6 +17,7 @@ import {
} from '@lib/gfsGrantErrors'
import type { GfsGrantListItem, GfsShareListItem } from '@/gfs/delegation.types'
import { deriveGfsInheritedAccess } from '@/gfs/inheritedAccess'
+import { applyMoveConvergence } from '@lib/gfsEntityChangeState'
import { desktopQueryKeys } from './queryKeys'
/**
@@ -1109,25 +1110,53 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
[current?.gfsUri, openUri]
)
- // Move refreshes the old parent's children, the destination's children,
- // and the accessible roots in one shot via refreshGfs. The moved resource's
- // id does not change, but its version does, and when the OPEN folder (or
- // file) itself moved, its breadcrumb trail is stale: the ancestors above it
+ // Move refreshes through the shared convergence planner (rev-2 §6): the
+ // receipt selectively invalidates the old/new parent children listings and
+ // accessible roots, and marks the moved resource plus its KNOWN cached
+ // descendants' permission data stale-on-entry. The moved resource's id does
+ // not change, but its version does, and when the OPEN folder (or file)
+ // itself moved, its breadcrumb trail is stale: the ancestors above it
// belong to the old location. Consume the returned version immediately and
// reconcile navigation to the new location (resolve + ancestor walk) so a
// follow-up Rename/Delete/Move runs with the post-move version, not the
// pre-move one (which would 409 on ifMatch).
const moveResourceMutation = useMutation({
- mutationFn: (input: { resourceId: string; destinationId: string; ifMatch?: number }) =>
- window.clerum.gfs.moveResource(input.resourceId, input.destinationId, DRIVE, input.ifMatch),
+ mutationFn: (input: {
+ resourceId: string
+ destinationId: string
+ ifMatch?: number
+ newName?: string
+ oldParentId?: string | null
+ }) =>
+ window.clerum.gfs.moveResource(
+ input.resourceId,
+ input.destinationId,
+ DRIVE,
+ input.ifMatch,
+ input.newName
+ ),
onSuccess: async (receipt, input) => {
const movedCrumb = crumbs.find(crumb => crumb.resourceId === input.resourceId)
setCrumbs(prev =>
prev.map(crumb =>
- crumb.resourceId === input.resourceId ? { ...crumb, version: receipt.version } : crumb
+ crumb.resourceId === input.resourceId
+ ? {
+ ...crumb,
+ version: receipt.version,
+ ...(input.newName !== undefined ? { name: input.newName } : {}),
+ }
+ : crumb
)
)
- await refreshGfs()
+ if (sessionScope) {
+ applyMoveConvergence(queryClient, sessionScope, DRIVE, {
+ resourceId: input.resourceId,
+ oldParentId: input.oldParentId ?? null,
+ newParentId: input.destinationId,
+ })
+ } else {
+ await refreshGfs()
+ }
if (movedCrumb) await openUri(movedCrumb.gfsUri)
},
onError: failClosedOnMutationError,
@@ -1360,8 +1389,14 @@ export function useGfsBrowserController(options: GfsBrowserControllerOptions = {
replaceFileFromPathMutation.mutateAsync({ resourceId, filePath, ifMatch }),
renameResource: (resourceId: string, name: string, ifMatch?: number) =>
renameResourceMutation.mutateAsync({ resourceId, name, ifMatch }),
- moveResource: (resourceId: string, destinationId: string, ifMatch?: number) =>
- moveResourceMutation.mutateAsync({ resourceId, destinationId, ifMatch }),
+ moveResource: (
+ resourceId: string,
+ destinationId: string,
+ ifMatch?: number,
+ newName?: string,
+ oldParentId?: string | null
+ ) =>
+ moveResourceMutation.mutateAsync({ resourceId, destinationId, ifMatch, newName, oldParentId }),
deleteResource: (resourceId: string, ifMatch?: number) =>
deleteResourceMutation.mutateAsync({ resourceId, ifMatch }),
mutating:
diff --git a/desktop-app/ui/src/lib/__tests__/gfsEntityChangeState.test.ts b/desktop-app/ui/src/lib/__tests__/gfsEntityChangeState.test.ts
index 165898641..539ed820e 100644
--- a/desktop-app/ui/src/lib/__tests__/gfsEntityChangeState.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/gfsEntityChangeState.test.ts
@@ -30,3 +30,97 @@ describe('plugin preview unavailable reconciliation', () => {
expect(markPluginGfsPreviewUnavailable(null, 'gfs://main/visible.png')).toBeNull()
})
})
+
+// ── selective move convergence (rev-2 drag-and-drop §6) ─────────────────────
+
+import { QueryClient } from '@tanstack/react-query'
+import { applyMoveConvergence, collectKnownChildParents } from '../gfsEntityChangeState'
+import { desktopQueryKeys } from '@hooks/domain/queryKeys'
+
+const SCOPE = 'test:user-1:team-1'
+const DRIVE = 'main'
+
+function seedChildren(
+ queryClient: QueryClient,
+ parentId: string,
+ items: Array<{ resourceId: string; name?: string }>
+) {
+ queryClient.setQueryData(desktopQueryKeys.gfsChildren(SCOPE, parentId, DRIVE), {
+ pages: [{ items: items.map(item => ({ ...item, name: item.name ?? item.resourceId })) }],
+ })
+}
+
+describe('collectKnownChildParents', () => {
+ it('derives child→parent links from cached children listings only', () => {
+ const queryClient = new QueryClient()
+ seedChildren(queryClient, 'A', [{ resourceId: 'x' }, { resourceId: 'M' }])
+ seedChildren(queryClient, 'M', [{ resourceId: 'c1' }])
+ expect(collectKnownChildParents(queryClient, SCOPE, DRIVE)).toEqual(
+ new Map([
+ ['x', 'A'],
+ ['M', 'A'],
+ ['c1', 'M'],
+ ])
+ )
+ })
+
+ it('ignores other scopes, drives and key families', () => {
+ const queryClient = new QueryClient()
+ seedChildren(queryClient, 'A', [{ resourceId: 'x' }])
+ queryClient.setQueryData(desktopQueryKeys.gfsChildren('other-scope', 'A', DRIVE), {
+ pages: [{ items: [{ resourceId: 'foreign' }] }],
+ })
+ queryClient.setQueryData(desktopQueryKeys.gfsAffordances(SCOPE, 'x', DRIVE), {
+ held: ['read'],
+ })
+ const links = collectKnownChildParents(queryClient, SCOPE, DRIVE)
+ expect(links.has('x')).toBe(true)
+ expect(links.has('foreign')).toBe(false)
+ })
+})
+
+describe('applyMoveConvergence', () => {
+ it('invalidates old/new parent children and accessible, and marks known descendants stale without refetch', async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ seedChildren(queryClient, 'A', [{ resourceId: 'M' }])
+ seedChildren(queryClient, 'M', [
+ { resourceId: 'c1' },
+ { resourceId: 'c2', name: 'nested' },
+ ])
+ seedChildren(queryClient, 'c1', [{ resourceId: 'c3' }])
+ seedChildren(queryClient, 'B', [{ resourceId: 'unrelated' }])
+ queryClient.setQueryData(desktopQueryKeys.gfsAccessible(SCOPE, DRIVE), {
+ pages: [{ items: [] }],
+ })
+ for (const id of ['M', 'c1', 'c3', 'B']) {
+ queryClient.setQueryData(desktopQueryKeys.gfsAffordances(SCOPE, id, DRIVE), {
+ held: ['read'],
+ })
+ }
+
+ applyMoveConvergence(queryClient, SCOPE, DRIVE, {
+ resourceId: 'M',
+ oldParentId: 'A',
+ newParentId: 'B',
+ })
+
+ // Let microtasks settle (invalidations are fire-and-forget promises).
+ await Promise.resolve()
+
+ // Old + new parent children and accessible were invalidated: their cached
+ // data is now marked stale (isInvalidated true).
+ const stale = (key: readonly unknown[]) =>
+ queryClient.getQueryCache().find({ queryKey: key })?.state.isInvalidated === true
+ expect(stale(desktopQueryKeys.gfsChildren(SCOPE, 'A', DRIVE))).toBe(true)
+ expect(stale(desktopQueryKeys.gfsChildren(SCOPE, 'B', DRIVE))).toBe(true)
+ expect(stale(desktopQueryKeys.gfsAccessible(SCOPE, DRIVE))).toBe(true)
+ // The moved resource and its KNOWN descendants' permission data were
+ // invalidated with refetchType none — stale, not eagerly refetched.
+ expect(stale(desktopQueryKeys.gfsAffordances(SCOPE, 'M', DRIVE))).toBe(true)
+ expect(stale(desktopQueryKeys.gfsAffordances(SCOPE, 'c1', DRIVE))).toBe(true)
+ expect(stale(desktopQueryKeys.gfsAffordances(SCOPE, 'c3', DRIVE))).toBe(true)
+ // Unknown-descendant guarantee: nothing outside the known subtree was touched.
+ expect(stale(desktopQueryKeys.gfsChildren(SCOPE, 'M', DRIVE))).toBe(false)
+ expect(stale(desktopQueryKeys.gfsAffordances(SCOPE, 'B', DRIVE))).toBe(false)
+ })
+})
diff --git a/desktop-app/ui/src/lib/gfsEntityChangeState.ts b/desktop-app/ui/src/lib/gfsEntityChangeState.ts
index 1258185af..dee789c98 100644
--- a/desktop-app/ui/src/lib/gfsEntityChangeState.ts
+++ b/desktop-app/ui/src/lib/gfsEntityChangeState.ts
@@ -1,3 +1,6 @@
+import type { QueryClient } from '@tanstack/react-query'
+import { planMoveConvergence } from '@clerum/gfs-interaction-policy'
+import { desktopQueryKeys } from '@hooks/domain/queryKeys'
import { parseHttpStatus } from './gfsGrantErrors'
import { refreshPreviewTab } from './workspaceTabs'
import type { WorkspaceTabsState } from './workspaceTabs.types'
@@ -39,3 +42,103 @@ export function markPluginGfsPreviewUnavailable<
if (!current || current.gfsUri !== gfsUri || current.unavailable) return current
return { ...current, unavailable: true, reloadVersion: current.reloadVersion + 1 }
}
+
+// ── selective move convergence (rev-2 drag-and-drop §6) ──────────────────────
+
+interface ChildrenPageLike {
+ items?: Array<{ resourceId: string }>
+}
+
+type ChildrenCacheEntry = { pages?: ChildrenPageLike[] }
+
+export interface GfsMoveReceiptInput {
+ resourceId: string
+ oldParentId: string | null
+ newParentId: string | null
+}
+
+/**
+ * Collect the child→parent links currently present in cached children
+ * listings (an observation of what this session has loaded — never a claim
+ * that it covers the physical subtree). Children keys are
+ * ['desktop-app','gfs',scope,'children',drive,parentId].
+ */
+export function collectKnownChildParents(
+ queryClient: QueryClient,
+ scope: string,
+ drive: string
+): Map<string, string | null> {
+ const links = new Map<string, string | null>()
+ for (const query of queryClient.getQueryCache().getAll()) {
+ const key = query.queryKey
+ if (!Array.isArray(key) || key.length !== 6) continue
+ if (
+ key[0] === 'desktop-app' &&
+ key[1] === 'gfs' &&
+ key[2] === scope &&
+ key[3] === 'children' &&
+ key[4] === drive &&
+ typeof key[5] === 'string'
+ ) {
+ const parentId = key[5] as string
+ const data = query.state.data as ChildrenCacheEntry | undefined
+ const items = data?.pages?.flatMap(page => page.items ?? []) ?? []
+ for (const item of items) links.set(item.resourceId, parentId)
+ }
+ }
+ return links
+}
+
+/**
+ * Selective move convergence: apply the pure plan from
+ * gfs-interaction-policy to the SHARED query cache — refetch the old/new
+ * parent children listings and the accessible roots (active surfaces only),
+ * and mark the moved resource plus its KNOWN cached descendants stale
+ * (affordances, grants, shares, inherited access) without eager refetches.
+ * Local receipts and remote hints converge through the same cache; there is
+ * deliberately no echo matching (user hint frames carry no operation ids).
+ */
+export function applyMoveConvergence(
+ queryClient: QueryClient,
+ scope: string,
+ drive: string,
+ receipt: GfsMoveReceiptInput
+): void {
+ const known = { childParentByResourceId: collectKnownChildParents(queryClient, scope, drive) }
+ const plan = planMoveConvergence(receipt, known)
+
+ for (const parentId of plan.refetchChildIds) {
+ void queryClient.invalidateQueries({
+ exact: true,
+ queryKey: desktopQueryKeys.gfsChildren(scope, parentId, drive),
+ })
+ }
+ void queryClient.invalidateQueries({
+ exact: true,
+ queryKey: desktopQueryKeys.gfsAccessible(scope, drive),
+ })
+ for (const resourceId of plan.staleResourceIds) {
+ // Stale-on-entry: inactive permission caches re-read when next observed,
+ // not eagerly here (bounded feature traffic).
+ void queryClient.invalidateQueries({
+ exact: true,
+ queryKey: desktopQueryKeys.gfsAffordances(scope, resourceId, drive),
+ refetchType: 'none',
+ })
+ void queryClient.invalidateQueries({
+ exact: true,
+ queryKey: desktopQueryKeys.gfsGrants(scope, resourceId, drive),
+ refetchType: 'none',
+ })
+ void queryClient.invalidateQueries({
+ exact: true,
+ queryKey: desktopQueryKeys.gfsShares(scope, resourceId, drive),
+ refetchType: 'none',
+ })
+ void queryClient.invalidateQueries({
+ exact: true,
+ queryKey: desktopQueryKeys.gfsInheritedAccess(scope, resourceId, drive),
+ refetchType: 'none',
+ })
+ }
+}
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index 8f7785559..e4cbafef8 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -32,7 +32,11 @@ import {
IconShare,
IconUpload,
} from '@components/SidebarNav/icons'
-import { GFS_DRIVE_MAIN } from '@constants/gfsBrowser'
+import {
+ FOLDER_HOVER_EXPAND_DELAY_MS,
+ GFS_DRIVE_MAIN,
+ GFS_RESOURCE_DRAG_TYPE,
+} from '@constants/gfsBrowser'
import { desktopQueryKeys } from '@hooks/domain/queryKeys'
import {
GFS_UNAVAILABLE_LOCATION_MESSAGE,
@@ -51,6 +55,9 @@ import {
} from '@lib/gfsGrantErrors'
import { isGfsPreviewFile, resolveGfsPreview } from '@lib/gfsPreview'
import { formatSharedFileSize } from '@lib/sharedFiles'
+import { useGfsDragAdjudication } from '@/gfs/dragAdjudication'
+import type { GfsDragSource, GfsDropRejection, GfsDropVerdict } from '@/gfs/dragSession'
+import { useGfsDragSession } from '@/gfs/dragSession'
import { GfsGrantList } from '@/gfs/GfsGrantList'
import type { GfsAccessRole } from '@/gfs/GfsGrantList'
import type { GfsMergedAccessRow } from '@/gfs/GfsGrantList/types'
@@ -65,6 +72,9 @@ import {
import type { GfsInheritedAccessSource } from '@/gfs/delegation.types'
import { GfsFilePicker } from '@/gfs/filePicker'
import { planInheritedRoleChange } from '@/gfs/inheritedAccess'
+import { GfsMoveConfirmDialog } from '@/gfs/moveConfirmDialog'
+import { commitGfsMove, suggestNumberedMoveName } from '@/gfs/moveCommit'
+import type { MoveCommitOutcome } from '@/gfs/moveCommit'
import { GfsMoveDialog } from '@/gfs/moveDialog'
import type { TeamDirectoryResult } from '../../../src/types'
import type { FilesPageProps, GfsDriveResource, MyAgentEntry } from './FilesPage.types'
@@ -94,16 +104,12 @@ function hasDraggedFiles(event: ReactDragEvent<HTMLElement>): boolean {
return Array.from(event.dataTransfer.types || []).includes('Files')
}
-const GFS_RESOURCE_DRAG_TYPE = 'application/x-evenfire-gfs-resource'
-
-const INHERITED_DERIVATION_NOTICE =
- 'Inherited access could not be loaded. Members with access from a parent folder may be missing.'
-
function hasDraggedGfsResource(event: ReactDragEvent<HTMLElement>): boolean {
return Array.from(event.dataTransfer.types || []).includes(GFS_RESOURCE_DRAG_TYPE)
}
-type FolderDropAccessResult = { allowed: boolean; error?: unknown }
+const INHERITED_DERIVATION_NOTICE =
+ 'Inherited access could not be loaded. Members with access from a parent folder may be missing.'
function delegationSubjectOptions(
directory: TeamDirectoryResult | undefined
@@ -279,11 +285,19 @@ export function FilesPage({
const [draggingResourceId, setDraggingResourceId] = useState<string | null>(null)
const [dragOverFolderId, setDragOverFolderId] = useState<string | null>(null)
const [movingResourceId, setMovingResourceId] = useState<string | null>(null)
+ const [dropStatesById, setDropStatesById] = useState<Record<string, GfsDropVerdict['state']>>({})
+ // Folder drops stop at ONE confirmation (impact + naming policy) before the
+ // shared dispatch; files commit directly on an allowed admission.
+ const [pendingFolderMove, setPendingFolderMove] = useState<{
+ source: GfsDragSource
+ destination: { resourceId: string; name: string }
+ allowNumberedRename: boolean
+ suggestedName?: string
+ } | null>(null)
const draggingResourceRef = useRef<GfsDriveResource | null>(null)
+ const draggingSourceRef = useRef<GfsDragSource | null>(null)
const movingResourceRef = useRef<string | null>(null)
const hoveredFolderRef = useRef<string | null>(null)
- const folderDropAccessRef = useRef(new Map<string, FolderDropAccessResult>())
- const folderDropChecksRef = useRef(new Map<string, Promise<FolderDropAccessResult>>())
const dragSessionRef = useRef(0)
const manageReturnCrumbsRef = useRef<GfsCrumb[] | null>(null)
const uploadInputRef = useRef<HTMLInputElement | null>(null)
@@ -312,6 +326,18 @@ export function FilesPage({
refreshAffordances,
} = ctrl
+ // Cross-surface drag coordinator (null outside the provider — e.g. unit
+ // tests — where the local per-surface ref drives same-surface drags).
+ const dragSession = useGfsDragSession()
+ const adjudication = useGfsDragAdjudication({
+ scope: sessionScope,
+ drive: GFS_DRIVE_MAIN,
+ resolve: useCallback(
+ (uri: string) => window.clerum.gfs.resolve(uri),
+ []
+ ),
+ })
+
const lastRemoteGfsChangeEpochRef = useRef(remoteGfsChangeEpoch)
useEffect(() => {
if (remoteGfsChangeEpoch === undefined) return
@@ -532,7 +558,7 @@ export function FilesPage({
}
useEffect(() => {
- if (!manageOpen && !openLinkOpen && !moveTarget && !renameTarget) return
+ if (!manageOpen && !openLinkOpen && !moveTarget && !renameTarget && !pendingFolderMove) return
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Escape') return
// The parent-folder confirmation is the top-most dialog: Escape cancels
@@ -541,6 +567,10 @@ export function FilesPage({
setParentUpdate(null)
return
}
+ if (pendingFolderMove) {
+ setPendingFolderMove(null)
+ return
+ }
closeManage()
setOpenLinkOpen(false)
setMoveTarget(null)
@@ -548,7 +578,15 @@ export function FilesPage({
}
window.addEventListener('keydown', handleKeyDown)
return () => window.removeEventListener('keydown', handleKeyDown)
- }, [closeManage, manageOpen, openLinkOpen, moveTarget, parentUpdate, renameTarget])
+ }, [
+ closeManage,
+ manageOpen,
+ openLinkOpen,
+ moveTarget,
+ parentUpdate,
+ pendingFolderMove,
+ renameTarget,
+ ])
// One atomic bulk grant for every selected subject — the server grants all or
// none (a `subjects_invalid` rejects the whole request), so there is no
@@ -935,61 +973,95 @@ export function FilesPage({
const clearResourceDrag = () => {
dragSessionRef.current += 1
draggingResourceRef.current = null
+ draggingSourceRef.current = null
hoveredFolderRef.current = null
- folderDropAccessRef.current.clear()
- folderDropChecksRef.current.clear()
+ dragSession?.endDrag()
+ adjudication.endDragSession()
setDraggingResourceId(null)
setDragOverFolderId(null)
+ setDropStatesById({})
}
- const resolveFolderDropAccess = (folder: GfsDriveResource): Promise<FolderDropAccessResult> => {
- const cached = folderDropAccessRef.current.get(folder.resourceId)
- if (cached) return Promise.resolve(cached)
- const pending = folderDropChecksRef.current.get(folder.resourceId)
- if (pending) return pending
-
- const dragSession = dragSessionRef.current
- const check = Promise.resolve()
- .then(() => window.clerum.gfs.affordances(folder.resourceId, 'main'))
- .then(result => ({ allowed: result.held.includes('write') }))
- .catch((permissionError: unknown) => {
- const failedClosed = failClosedOnAuthorizationError(permissionError)
- return { allowed: false, error: failedClosed ? undefined : permissionError }
- })
- .then(result => {
- if (dragSession === dragSessionRef.current) {
- folderDropAccessRef.current.set(folder.resourceId, result)
- if (result.allowed && hoveredFolderRef.current === folder.resourceId) {
- setDragOverFolderId(folder.resourceId)
- }
- }
- return result
- })
- .finally(() => {
- if (dragSession === dragSessionRef.current) {
- folderDropChecksRef.current.delete(folder.resourceId)
- }
- })
+ /** Ancestor chain of rows in the current listing, nearest-first: the open
+ * folder and its breadcrumb ancestors (an observation, never a guess). */
+ const rowTargetAncestorIds = (): (string | null)[] =>
+ currentIsFolder && current
+ ? [...crumbs].map(crumb => crumb.resourceId).reverse()
+ : []
+
+ /** Build the cross-surface drag descriptor for a row of this surface. */
+ const dragSourceFrom = (resource: GfsDriveResource): Omit<GfsDragSource, 'generation'> => {
+ const parentKnown = currentIsFolder && current ? true : resource.parentResourceId != null
+ const parentResourceId =
+ currentIsFolder && current ? current.resourceId : (resource.parentResourceId ?? null)
+ return {
+ resourceId: resource.resourceId,
+ gfsUri: resource.gfsUri,
+ drive: resource.drive || GFS_DRIVE_MAIN,
+ kind: resource.kind === 'directory' ? 'directory' : 'file',
+ name: resource.name,
+ ...(Number.isSafeInteger(resource.version) ? { version: resource.version } : {}),
+ parentKnown,
+ parentResourceId,
+ knownAncestorIds: currentIsFolder && current
+ ? [...crumbs].map(crumb => crumb.resourceId).reverse()
+ : [],
+ origin: 'files',
+ scope: sessionScope ?? 'anonymous',
+ }
+ }
- folderDropChecksRef.current.set(folder.resourceId, check)
- return check
+ /** The active source is the session descriptor when its scope matches
+ * (cross-surface drags), else this surface's local ref. */
+ const resolveActiveSource = (): GfsDragSource | null => {
+ const fromSession = dragSession?.activeSource()
+ if (
+ fromSession &&
+ dragSession?.matchesScope(sessionScope ?? 'anonymous') &&
+ fromSession.drive === GFS_DRIVE_MAIN
+ ) {
+ return fromSession
+ }
+ return draggingSourceRef.current
+ }
+
+ const applyHoverVerdict = (folderId: string, verdict: GfsDropVerdict): GfsDropVerdict => {
+ if (verdict.state === 'allowed') {
+ setDragOverFolderId(folderId)
+ } else if (hoveredFolderRef.current === folderId) {
+ setDragOverFolderId(null)
+ }
+ setDropStatesById(previous =>
+ previous[folderId] === verdict.state
+ ? previous
+ : { ...previous, [folderId]: verdict.state }
+ )
+ return verdict
}
const handleResourceDragStart = (
event: ReactDragEvent<HTMLElement>,
resource: GfsDriveResource
) => {
- if (resource.kind === 'directory' || movingResourceRef.current) {
+ // Files AND folders drag; unreadable rows, in-flight moves and any pending
+ // controller mutation stay frozen.
+ if (resource.readable === false || movingResourceRef.current || ctrl.mutating) {
event.preventDefault()
return
}
dragSessionRef.current += 1
- folderDropAccessRef.current.clear()
- folderDropChecksRef.current.clear()
+ const source: GfsDragSource = {
+ ...dragSourceFrom(resource),
+ generation: dragSessionRef.current,
+ }
+ const { generation: _generation, ...sourceForStore } = source
+ dragSession?.beginDrag(sourceForStore)
+ adjudication.beginDragSession()
event.dataTransfer.effectAllowed = 'move'
event.dataTransfer.setData(GFS_RESOURCE_DRAG_TYPE, resource.resourceId)
event.dataTransfer.setData('text/plain', resource.name)
draggingResourceRef.current = resource
+ draggingSourceRef.current = source
setDraggingResourceId(resource.resourceId)
}
@@ -999,22 +1071,33 @@ export function FilesPage({
const handleFolderDragOver = (event: ReactDragEvent<HTMLElement>, folder: GfsDriveResource) => {
if (!hasDraggedGfsResource(event)) return
- const source = draggingResourceRef.current
+ const source = resolveActiveSource()
if (!source || folder.kind !== 'directory' || source.resourceId === folder.resourceId) return
event.preventDefault()
event.stopPropagation()
hoveredFolderRef.current = folder.resourceId
- const access = folderDropAccessRef.current.get(folder.resourceId)
- if (access?.allowed) {
- event.dataTransfer.dropEffect = 'move'
- setDragOverFolderId(folder.resourceId)
- return
+ const target = {
+ resourceId: folder.resourceId,
+ name: folder.name,
+ kind: folder.kind,
+ ancestorIds: rowTargetAncestorIds(),
+ } as const
+ const verdict = applyHoverVerdict(
+ folder.resourceId,
+ adjudication.hoverVerdict(source, target)
+ )
+ event.dataTransfer.dropEffect = verdict.state === 'allowed' ? 'move' : 'none'
+ if (verdict.state === 'checking') {
+ adjudication.scheduleColdCheck(
+ target,
+ source.parentKnown ? source.parentResourceId : null,
+ () => {
+ if (hoveredFolderRef.current !== folder.resourceId) return
+ const fresh = adjudication.hoverVerdict(source, target)
+ applyHoverVerdict(folder.resourceId, fresh)
+ })
}
-
- event.dataTransfer.dropEffect = 'none'
- setDragOverFolderId(null)
- if (!access) void resolveFolderDropAccess(folder)
}
const handleFolderDragLeave = (event: ReactDragEvent<HTMLElement>) => {
@@ -1027,6 +1110,116 @@ export function FilesPage({
}
}
+ /** Cached destination names for the suggested numbered-name candidate. */
+ const cachedDestinationNames = (destinationId: string): Set<string> => {
+ const cached = queryClient.getQueryData<{ pages?: Array<{ items?: GfsDriveResource[] }> }>(
+ desktopQueryKeys.gfsChildren(sessionScope ?? 'anonymous', destinationId, GFS_DRIVE_MAIN)
+ )
+ return new Set((cached?.pages ?? []).flatMap(page => page.items?.map(item => item.name) ?? []))
+ }
+
+ const dropDenialMessage = (
+ rejection: GfsDropRejection,
+ destinationName: string
+ ): string | null => {
+ switch (rejection.reason) {
+ case 'destination-write':
+ return `You can’t move files to ${destinationName} because you don’t have write permission for this folder.`
+ case 'source-write':
+ return 'You cannot move this item out of its current folder without write access there.'
+ case 'source-delete':
+ return 'You do not have permission to remove this item from its current folder.'
+ case 'same-parent':
+ return 'This item is already in this folder.'
+ case 'self':
+ case 'descendant':
+ return 'A folder cannot be moved into itself or one of its subfolders.'
+ case 'root-source':
+ return 'The top-level folder cannot be moved.'
+ case 'cross-drive':
+ return 'Items can’t be moved between drives.'
+ case 'session-lost':
+ return null
+ default:
+ return rejection.message ?? 'This move is not available right now. Try again in a moment.'
+ }
+ }
+
+ /** Shared move dispatch (rev-2 §5) used by the drag path, the folder
+ * confirmation and the Move dialog — one service, one code path. */
+ const runMoveCommit = async (
+ source: GfsDragSource,
+ destination: { resourceId: string; name: string },
+ allowNumberedRename: boolean
+ ): Promise<MoveCommitOutcome> => {
+ movingResourceRef.current = source.resourceId
+ setMovingResourceId(source.resourceId)
+ try {
+ const outcome = await commitGfsMove(
+ {
+ resolveSource: async gfsUri => {
+ const resolved = await window.clerum.gfs.resolve(gfsUri)
+ return {
+ resourceId: resolved.resourceId,
+ gfsUri,
+ kind: resolved.kind === 'directory' ? 'directory' : 'file',
+ name: resolved.name,
+ version: resolved.version,
+ parentResourceId: resolved.parentResourceId,
+ }
+ },
+ moveResource: (resourceId, destinationId, ifMatch, newName) =>
+ ctrl.moveResource(
+ resourceId,
+ destinationId,
+ ifMatch,
+ newName,
+ source.parentKnown ? source.parentResourceId : null
+ ),
+ isSessionAuthorityFailure: error => failClosedOnAuthorizationError(error),
+ },
+ {
+ source: {
+ resourceId: source.resourceId,
+ gfsUri: source.gfsUri,
+ kind: source.kind,
+ name: source.name,
+ },
+ destination,
+ allowNumberedRename,
+ occupiedDestinationNames: cachedDestinationNames(destination.resourceId),
+ }
+ )
+ switch (outcome.status) {
+ case 'committed':
+ pushToast?.(
+ outcome.renamedTo
+ ? `Moved ${source.name} to ${destination.name} as ${outcome.renamedTo}`
+ : `Moved ${source.name} to ${destination.name}`,
+ 'success'
+ )
+ if (source.kind === 'directory') {
+ pushToast?.(
+ 'Moving a folder changes who can access its contents — access now follows the new location.',
+ 'info'
+ )
+ }
+ break
+ case 'no-op':
+ pushToast?.(outcome.message, 'info')
+ break
+ case 'session-lost':
+ break
+ default:
+ pushToast?.(outcome.message, 'error')
+ }
+ return outcome
+ } finally {
+ movingResourceRef.current = null
+ setMovingResourceId(null)
+ }
+ }
+
const handleFolderDrop = async (
event: ReactDragEvent<HTMLElement>,
destination: GfsDriveResource
@@ -1036,37 +1229,42 @@ export function FilesPage({
event.stopPropagation()
hoveredFolderRef.current = null
setDragOverFolderId(null)
- const source = draggingResourceRef.current
+ setDropStatesById({})
+ const source = resolveActiveSource()
if (!source || destination.kind !== 'directory' || movingResourceRef.current) return
+ const dragGeneration = dragSessionRef.current
try {
- const access = await resolveFolderDropAccess(destination)
- if (!access.allowed) {
- // Through the read-plane presenter, like `handleDownload`. The
- // affordances check is one of the methods `surfaceGfsGrantError`
- // wraps, so its rejection carries the IPC wrapper and the vetted
- // markers; raw, this toast read "… httpStatus=403". A 403 or 429 here
- // is a policy verdict, not an authority failure, so it does not fail
- // closed and this really is the path the user sees.
- const message = access.error
- ? describeGfsReadError(access.error).message
- : `You can’t move files to ${destination.name} because you don’t have write permission for this folder.`
- pushToast?.(message, 'error')
+ const decision = await adjudication.adjudicateDrop(source, {
+ resourceId: destination.resourceId,
+ name: destination.name,
+ kind: destination.kind,
+ ancestorIds: rowTargetAncestorIds(),
+ })
+ if (dragGeneration !== dragSessionRef.current) return
+ if (!decision.allowed) {
+ const message = dropDenialMessage(decision, destination.name)
+ if (message) pushToast?.(message, 'error')
return
}
-
- movingResourceRef.current = source.resourceId
- setMovingResourceId(source.resourceId)
- try {
- await ctrl.moveResource(source.resourceId, destination.resourceId, source.version)
- pushToast?.(`Moved ${source.name} to ${destination.name}`, 'success')
- } catch (moveError) {
- if (failClosedOnAuthorizationError(moveError)) return
- pushToast?.(moveError instanceof Error ? moveError.message : String(moveError), 'error')
- } finally {
- movingResourceRef.current = null
- setMovingResourceId(null)
+ if (source.kind === 'directory') {
+ // The ONE folder confirmation (rev-2 §1): impact + naming policy in a
+ // single dialog; dispatch happens on explicit Move.
+ const occupied = cachedDestinationNames(destination.resourceId)
+ const suggested = suggestNumberedMoveName(source.name, occupied)
+ setPendingFolderMove({
+ source,
+ destination: { resourceId: destination.resourceId, name: destination.name },
+ allowNumberedRename: decision.allowNumberedRename,
+ ...(suggested !== undefined ? { suggestedName: suggested } : {}),
+ })
+ return
}
+ await runMoveCommit(
+ source,
+ { resourceId: destination.resourceId, name: destination.name },
+ decision.allowNumberedRename
+ )
} finally {
clearResourceDrag()
}
@@ -1222,24 +1420,42 @@ export function FilesPage({
return Boolean(resource.permissions?.includes('manage_acl'))
}
- /** Move commits bubble their failure back to the dialog (in-place banner);
- * success toasts and closes it. An authority rejection instead fails the
- * session closed and closes the dialog — the revoked state takes over.
- * ifMatch pins the resource version. */
+ /** Move-dialog commit through the shared dispatch: success toasts and
+ * closes; failure throws the presented verdict so the dialog shows it
+ * in place; an authority rejection fails the session closed instead. */
const handleMoveTarget = async (destinationId: string, destinationName: string) => {
if (!moveTarget) return
const target = moveTarget
- try {
- await ctrl.moveResource(target.resourceId, destinationId, target.version)
- } catch (moveError) {
- if (failClosedOnAuthorizationError(moveError)) {
- setMoveTarget(null)
- return
- }
- throw moveError
+ const source: GfsDragSource = {
+ resourceId: target.resourceId,
+ gfsUri: `gfs://${GFS_DRIVE_MAIN}/${target.resourceId.replace(/-/g, '').toLowerCase()}`,
+ drive: GFS_DRIVE_MAIN,
+ kind: target.kind,
+ name: target.name,
+ ...(Number.isSafeInteger(target.version) ? { version: target.version } : {}),
+ parentKnown: target.parentResourceId != null,
+ parentResourceId: target.parentResourceId ?? null,
+ knownAncestorIds: [],
+ origin: 'files',
+ scope: sessionScope ?? 'anonymous',
+ generation: dragSessionRef.current,
+ }
+ // Files and explicit dialog moves may use numbered names when the source
+ // resource is writable (rev-2 §5).
+ const allowNumberedRename = await adjudication.probeSourceWrite(target.resourceId)
+ const outcome = await runMoveCommit(
+ source,
+ { resourceId: destinationId, name: destinationName },
+ allowNumberedRename
+ )
+ if (outcome.status === 'session-lost') {
+ setMoveTarget(null)
+ return
+ }
+ if (outcome.status !== 'committed' && outcome.status !== 'no-op') {
+ throw new Error(outcome.message)
}
setMoveTarget(null)
- pushToast?.(`Moved ${target.name} to ${destinationName}`, 'success')
}
const requestMoveCurrent = () => {
@@ -1703,24 +1919,26 @@ export function FilesPage({
const isDragging =
draggingResourceId === resource.resourceId ||
movingResourceId === resource.resourceId
- const isDropTarget = dragOverFolderId === resource.resourceId
- const canDragResource =
- resource.kind === 'file' &&
- resource.readable !== false &&
- movingResourceId === null &&
- !ctrl.mutating
- return (
- <div
- className="da-grid__row da-grid__row--clickable da-grid__row--compact"
- key={resource.resourceId}
- draggable={canDragResource}
- title={
- canDragResource
- ? `Drag ${resource.name} into a folder to move it`
- : undefined
- }
- data-dragging={isDragging ? 'true' : undefined}
- data-drop-target={isDropTarget ? 'true' : undefined}
+ const isDropTarget = dragOverFolderId === resource.resourceId
+ const dropState =
+ resource.kind === 'directory' ? dropStatesById[resource.resourceId] : undefined
+ const canDragResource =
+ resource.readable !== false &&
+ movingResourceId === null &&
+ !ctrl.mutating
+ return (
+ <div
+ className="da-grid__row da-grid__row--clickable da-grid__row--compact"
+ key={resource.resourceId}
+ draggable={canDragResource}
+ title={
+ canDragResource
+ ? `Drag ${resource.name} into a folder to move it`
+ : undefined
+ }
+ data-dragging={isDragging ? 'true' : undefined}
+ data-drop-target={isDropTarget ? 'true' : undefined}
+ data-drop-state={dropState}
role="button"
tabIndex={0}
aria-label={
@@ -2225,6 +2443,28 @@ export function FilesPage({
target={moveTarget}
/>
) : null}
+
+ {pendingFolderMove ? (
+ <GfsMoveConfirmDialog
+ busy={movingResourceId === pendingFolderMove.source.resourceId}
+ request={{
+ sourceName: pendingFolderMove.source.name,
+ destinationName: pendingFolderMove.destination.name,
+ canRename: pendingFolderMove.allowNumberedRename,
+ ...(pendingFolderMove.suggestedName !== undefined
+ ? { suggestedName: pendingFolderMove.suggestedName }
+ : {}),
+ }}
+ onCancel={() => setPendingFolderMove(null)}
+ onConfirm={({ allowNumberedRename }) => {
+ const pending = pendingFolderMove
+ setPendingFolderMove(null)
+ if (pending) {
+ void runMoveCommit(pending.source, pending.destination, allowNumberedRename)
+ }
+ }}
+ />
+ ) : null}
</section>
)
}
diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index b41ffeed8..7d0646dd1 100644
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@ -3451,9 +3451,30 @@ describe('FilesPage', () => {
],
nextCursor: null,
}))
+ // rev-2 shared dispatch: the dialog commit re-resolves the source before
+ // the PATCH (fresh ifMatch) and probes source-resource write for the
+ // numbered-name policy.
+ const resolve = vi.fn(async () => ({
+ drive: 'main',
+ resourceId: 'child-1',
+ parentResourceId: 'folder-1',
+ rid: 'child-1',
+ gfsUri: 'gfs://main/child-1',
+ name: 'notes.txt',
+ kind: 'file',
+ pathCache: '/Product/notes.txt',
+ version: 3,
+ bytes: 12,
+ }))
+ const affordances = vi.fn(async () => ({
+ held: ['read', 'write'],
+ canDelegate: false,
+ grantableBits: [],
+ canCreateShare: false,
+ }))
Object.defineProperty(window, 'clerum', {
configurable: true,
- value: { gfs: { listChildren } },
+ value: { gfs: { listChildren, resolve, affordances } },
})
const child = {
resourceId: 'child-1',
@@ -3525,7 +3546,7 @@ describe('FilesPage', () => {
fireEvent.click(within(dialog).getByRole('button', { name: 'Move here (Subfolder)' }))
})
- expect(moveResource).toHaveBeenCalledWith('child-1', 'sub-1', 3)
+ expect(moveResource).toHaveBeenCalledWith('child-1', 'sub-1', 3, undefined, 'folder-1')
expect(moveResource).toHaveBeenCalledTimes(1)
expect(pushToast).toHaveBeenCalledWith('Moved notes.txt to Subfolder', 'success')
})
@@ -3533,15 +3554,39 @@ describe('FilesPage', () => {
it('moves a dragged file onto a folder only after confirming destination write access', async () => {
const pushToast = vi.fn()
const moveResource = vi.fn(async () => ({}))
- const affordances = vi.fn(async () => ({
- held: ['read', 'write'],
- canDelegate: false,
- grantableBits: [],
- canCreateShare: false,
+ // rev-2 exact-bit authority: the source parent needs write+delete, the
+ // destination write, and the source resource write unlocks numbered names.
+ const affordances = vi.fn(async (resourceId: string) => {
+ if (resourceId === 'folder-1') {
+ return {
+ held: ['read', 'write', 'delete'],
+ canDelegate: false,
+ grantableBits: [],
+ canCreateShare: false,
+ }
+ }
+ return {
+ held: ['read', 'write'],
+ canDelegate: false,
+ grantableBits: [],
+ canCreateShare: false,
+ }
+ })
+ const resolve = vi.fn(async () => ({
+ drive: 'main',
+ resourceId: 'file-1',
+ parentResourceId: 'folder-1',
+ rid: 'file-1',
+ gfsUri: 'gfs://main/file-1',
+ name: 'notes.txt',
+ kind: 'file',
+ pathCache: '/Product/notes.txt',
+ version: 3,
+ bytes: 12,
}))
Object.defineProperty(window, 'clerum', {
configurable: true,
- value: { gfs: { affordances } },
+ value: { gfs: { affordances, resolve } },
})
hookMock.useGfsBrowserController.mockReturnValue({
...baseController(),
@@ -3605,7 +3650,7 @@ describe('FilesPage', () => {
fireEvent.drop(destinationRow, { dataTransfer })
await waitFor(() => {
- expect(moveResource).toHaveBeenCalledWith('file-1', 'archive-1', 3)
+ expect(moveResource).toHaveBeenCalledWith('file-1', 'archive-1', 3, undefined, 'folder-1')
expect(pushToast).toHaveBeenCalledWith('Moved notes.txt to Archive', 'success')
})
})
@@ -3613,12 +3658,22 @@ describe('FilesPage', () => {
it('rejects a file drop when the destination folder lacks write access', async () => {
const pushToast = vi.fn()
const moveResource = vi.fn(async () => ({}))
- const affordances = vi.fn(async () => ({
- held: ['read'],
- canDelegate: false,
- grantableBits: [],
- canCreateShare: false,
- }))
+ const affordances = vi.fn(async (resourceId: string) => {
+ if (resourceId === 'folder-1') {
+ return {
+ held: ['read', 'write', 'delete'],
+ canDelegate: false,
+ grantableBits: [],
+ canCreateShare: false,
+ }
+ }
+ return {
+ held: ['read'],
+ canDelegate: false,
+ grantableBits: [],
+ canCreateShare: false,
+ }
+ })
Object.defineProperty(window, 'clerum', {
configurable: true,
value: { gfs: { affordances } },
@@ -5043,3 +5098,314 @@ describe('FilesPage', () => {
expect(screen.getByText(/Too many file requests — try again in 7s\./)).toBeTruthy()
})
})
+
+// ── folder drag moves + conflict parity (rev-2 D1) ───────────────────────────
+
+describe('FilesPage — folder drag-and-drop', () => {
+ // The file's shared afterEach(cleanup) lives inside the sibling
+ // describe('FilesPage') block; this block needs its own unmount.
+ afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+ })
+
+ function folderDragHarness(options: {
+ destinationHeld?: string[]
+ sourceParentHeld?: string[]
+ sourceResourceHeld?: string[]
+ resolveParent?: string | null
+ resolveVersion?: number
+ moveResult?: () => Promise<{ resourceId: string; version: number }>
+ conflictOnce?: boolean
+ } = {}) {
+ const pushToast = vi.fn()
+ const moveResource = vi.fn(
+ options.moveResult ??
+ (async () => ({ resourceId: 'folder-src', version: 5 }))
+ )
+ if (options.conflictOnce) {
+ let conflicted = false
+ moveResource.mockImplementation(async () => {
+ if (!conflicted) {
+ conflicted = true
+ throw new Error(
+ '409 Conflict: a resource with this name already exists httpStatus=409'
+ )
+ }
+ return { resourceId: 'folder-src', version: 5 }
+ })
+ }
+ const affordances = vi.fn(async (resourceId: string) => {
+ if (resourceId === 'folder-1') {
+ return { held: options.sourceParentHeld ?? ['read', 'write', 'delete'] }
+ }
+ if (resourceId === 'folder-src') {
+ return { held: options.sourceResourceHeld ?? ['read', 'write'] }
+ }
+ return { held: options.destinationHeld ?? ['read', 'write'] }
+ })
+ const resolve = vi.fn(async () => ({
+ drive: 'main',
+ resourceId: 'folder-src',
+ parentResourceId: options.resolveParent ?? 'folder-1',
+ rid: 'foldersrc',
+ gfsUri: 'gfs://main/foldersrc',
+ name: 'Projects',
+ kind: 'directory',
+ pathCache: '/Product/Projects',
+ version: options.resolveVersion ?? 4,
+ }))
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { gfs: { affordances, resolve } },
+ })
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ current: {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder-1',
+ name: 'Product',
+ kind: 'directory',
+ version: 1,
+ },
+ crumbs: [
+ {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder-1',
+ name: 'Product',
+ kind: 'directory',
+ version: 1,
+ bytes: 0,
+ },
+ ],
+ items: [
+ {
+ resourceId: 'folder-src',
+ rid: 'folder-src',
+ gfsUri: 'gfs://main/folder-src',
+ drive: 'main',
+ parentResourceId: 'folder-1',
+ name: 'Projects',
+ kind: 'directory',
+ path: '/Product/Projects',
+ version: 4,
+ bytes: 0,
+ },
+ {
+ resourceId: 'archive-1',
+ rid: 'archive-1',
+ gfsUri: 'gfs://main/archive-1',
+ drive: 'main',
+ parentResourceId: 'folder-1',
+ name: 'Archive',
+ kind: 'directory',
+ path: '/Product/Archive',
+ version: 2,
+ bytes: 0,
+ },
+ ],
+ moveResource,
+ })
+ renderFilesPage(pushToast)
+ return { pushToast, moveResource }
+ }
+
+ it('stops a folder drop at the one confirmation and commits on Move', async () => {
+ const { pushToast, moveResource } = folderDragHarness()
+ const sourceRow = screen.getByRole('button', { name: 'Open Projects' })
+ const destinationRow = screen.getByRole('button', { name: 'Open Archive' })
+ const dataTransfer = {
+ types: ['application/x-evenfire-gfs-resource'],
+ files: [],
+ effectAllowed: 'none',
+ dropEffect: 'none',
+ setData: vi.fn(),
+ }
+
+ fireEvent.dragStart(sourceRow, { dataTransfer })
+ fireEvent.dragEnter(destinationRow, { dataTransfer })
+ fireEvent.dragOver(destinationRow, { dataTransfer })
+ fireEvent.drop(destinationRow, { dataTransfer })
+
+ const dialog = await screen.findByRole('dialog', { name: 'Move folder Projects to Archive' })
+ expect(
+ within(dialog).getByText(/Inherited access to this folder and its contents follows the new location/)
+ ).toBeTruthy()
+ expect(moveResource).not.toHaveBeenCalled()
+
+ await act(async () => {
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Move' }))
+ })
+ await waitFor(() => {
+ expect(moveResource).toHaveBeenCalledWith('folder-src', 'archive-1', 4, undefined, 'folder-1')
+ })
+ await waitFor(() =>
+ expect(pushToast).toHaveBeenCalledWith('Moved Projects to Archive', 'success')
+ )
+ expect(pushToast).toHaveBeenCalledWith(
+ 'Moving a folder changes who can access its contents — access now follows the new location.',
+ 'info'
+ )
+ expect(screen.queryByRole('dialog')).toBeNull()
+ })
+
+ it('cancelling the folder confirmation sends nothing and never claims a move', async () => {
+ const { pushToast, moveResource } = folderDragHarness()
+ const sourceRow = screen.getByRole('button', { name: 'Open Projects' })
+ const destinationRow = screen.getByRole('button', { name: 'Open Archive' })
+ const dataTransfer = {
+ types: ['application/x-evenfire-gfs-resource'],
+ files: [],
+ effectAllowed: 'none',
+ dropEffect: 'none',
+ setData: vi.fn(),
+ }
+ fireEvent.dragStart(sourceRow, { dataTransfer })
+ fireEvent.dragEnter(destinationRow, { dataTransfer })
+ fireEvent.drop(destinationRow, { dataTransfer })
+
+ const dialog = await screen.findByRole('dialog', { name: 'Move folder Projects to Archive' })
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))
+ expect(moveResource).not.toHaveBeenCalled()
+ expect(pushToast).not.toHaveBeenCalledWith(
+ expect.stringContaining('Moved'),
+ expect.anything()
+ )
+ expect(screen.queryByRole('dialog')).toBeNull()
+ })
+
+ it('a folder conflict without the numbered-name opt-in stops with alternatives', async () => {
+ const { pushToast, moveResource } = folderDragHarness({ conflictOnce: true })
+ const sourceRow = screen.getByRole('button', { name: 'Open Projects' })
+ const destinationRow = screen.getByRole('button', { name: 'Open Archive' })
+ const dataTransfer = {
+ types: ['application/x-evenfire-gfs-resource'],
+ files: [],
+ effectAllowed: 'none',
+ dropEffect: 'none',
+ setData: vi.fn(),
+ }
+ fireEvent.dragStart(sourceRow, { dataTransfer })
+ fireEvent.dragEnter(destinationRow, { dataTransfer })
+ fireEvent.drop(destinationRow, { dataTransfer })
+
+ const dialog = await screen.findByRole('dialog', { name: 'Move folder Projects to Archive' })
+ await act(async () => {
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Move' }))
+ })
+ await waitFor(() => {
+ expect(pushToast).toHaveBeenCalledWith(
+ expect.stringContaining('An item with this name already exists'),
+ 'error'
+ )
+ })
+ expect(moveResource).toHaveBeenCalledTimes(1)
+ })
+
+ it('a file conflict resolves with a numbered whole-resource rename (CU parity)', async () => {
+ const pushToast = vi.fn()
+ let conflicted = false
+ const moveResource = vi.fn(async (_id: string, _dest: string, _v: number, newName?: string) => {
+ if (newName === undefined && !conflicted) {
+ conflicted = true
+ throw new Error(
+ '409 Conflict: a resource with this name already exists httpStatus=409'
+ )
+ }
+ return { resourceId: 'file-1', version: 6 }
+ })
+ const affordances = vi.fn(async (resourceId: string) => {
+ if (resourceId === 'folder-1') return { held: ['read', 'write', 'delete'] }
+ return { held: ['read', 'write'] }
+ })
+ const resolve = vi.fn(async () => ({
+ drive: 'main',
+ resourceId: 'file-1',
+ parentResourceId: 'folder-1',
+ rid: 'file-1',
+ gfsUri: 'gfs://main/file-1',
+ name: 'notes.txt',
+ kind: 'file',
+ pathCache: '/Product/notes.txt',
+ version: 3,
+ }))
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { gfs: { affordances, resolve } },
+ })
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ current: {
+ resourceId: 'folder-1',
+ gfsUri: 'gfs://main/folder-1',
+ name: 'Product',
+ kind: 'directory',
+ version: 1,
+ },
+ items: [
+ {
+ resourceId: 'file-1',
+ rid: 'file-1',
+ gfsUri: 'gfs://main/file-1',
+ drive: 'main',
+ parentResourceId: 'folder-1',
+ name: 'notes.txt',
+ kind: 'file',
+ path: '/Product/notes.txt',
+ version: 3,
+ bytes: 12,
+ },
+ {
+ resourceId: 'archive-1',
+ rid: 'archive-1',
+ gfsUri: 'gfs://main/archive-1',
+ drive: 'main',
+ parentResourceId: 'folder-1',
+ name: 'Archive',
+ kind: 'directory',
+ path: '/Product/Archive',
+ version: 2,
+ bytes: 0,
+ },
+ ],
+ moveResource,
+ })
+ renderFilesPage(pushToast)
+
+ const sourceRow = screen.getByRole('button', { name: 'Open notes.txt' })
+ const destinationRow = screen.getByRole('button', { name: 'Open Archive' })
+ const dataTransfer = {
+ types: ['application/x-evenfire-gfs-resource'],
+ files: [],
+ effectAllowed: 'none',
+ dropEffect: 'none',
+ setData: vi.fn(),
+ }
+ fireEvent.dragStart(sourceRow, { dataTransfer })
+ fireEvent.dragEnter(destinationRow, { dataTransfer })
+ fireEvent.drop(destinationRow, { dataTransfer })
+
+ await waitFor(() => {
+ expect(pushToast).toHaveBeenCalledWith(
+ 'Moved notes.txt to Archive as notes (1).txt',
+ 'success'
+ )
+ })
+ expect(moveResource).toHaveBeenLastCalledWith(
+ 'file-1',
+ 'archive-1',
+ 3,
+ 'notes (1).txt',
+ 'folder-1'
+ )
+ })
+
+ it('folder rows are draggable sources (title hint present)', () => {
+ folderDragHarness()
+ const folderRow = screen
+ .getByRole('button', { name: 'Open Projects' })
+ .closest('.da-grid__row') as HTMLElement
+ expect(folderRow.getAttribute('draggable')).toBe('true')
+ expect(folderRow.getAttribute('title')).toBe('Drag Projects into a folder to move it')
+ })
+})
diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.css
index 12c0f1069..c9426d10f 100644
--- a/desktop-app/ui/src/styles.css
+++ b/desktop-app/ui/src/styles.css
@@ -1978,6 +1978,65 @@ h3 {
flex: 0 0 auto;
}
+/* ── Drag-and-drop states (rev-2 D1) ──────────────────────────────────────
+ Existing tokens only; no motion. `checking` reads as neutral-active so the
+ row is visibly being adjudicated without implying a verdict; `allowed`
+ reuses the selected-row accent; `denied` keeps the error border tone. The
+ row-level attribute also styles Files-page rows which reuse the same
+ attribute names on their grid rows. */
+.da-file-explorer__row[data-drop-state='checking'] {
+ background: rgba(var(--accent-rgb), 0.06);
+}
+
+.da-file-explorer__row[data-drop-state='allowed'] {
+ background: rgba(var(--accent-rgb), 0.12);
+}
+
+.da-file-explorer__row[data-drop-state='allowed'] .da-file-explorer__label.ui-button {
+ background: transparent;
+}
+
+.da-file-explorer__row[data-drop-state='denied'] .da-file-explorer__label.ui-button,
+.da-file-explorer__row[data-drop-state='unavailable'] .da-file-explorer__label.ui-button {
+ color: var(--text-dim);
+}
+
+/* Files-page grid rows use the same attribute vocabulary. */
+.da-grid__row--compact[data-drop-state='checking'] {
+ background: rgba(var(--accent-rgb), 0.06);
+}
+
+.da-grid__row--compact[data-drop-state='allowed'] {
+ background: rgba(var(--accent-rgb), 0.12);
+}
+
+/* The per-row Move action is revealed on hover/focus-within so the compact
+ chrome is unchanged at rest (keyboard users reach it via Tab). */
+.da-file-explorer__move-action {
+ flex: 0 0 auto;
+ opacity: 0;
+}
+
+.da-file-explorer__row:hover .da-file-explorer__move-action,
+.da-file-explorer__row:focus-within .da-file-explorer__move-action {
+ opacity: 1;
+}
+
+@media (prefers-reduced-motion: no-preference) {
+ .da-file-explorer__move-action {
+ transition: opacity var(--motion-fast, 120ms) ease;
+ }
+}
+
+/* Draggable tree labels and grid rows show the grab affordance. */
+.da-file-explorer__label.ui-button[draggable='true'] {
+ cursor: grab;
+}
+
+.da-grid__row--compact[draggable='true'] {
+ cursor: grab;
+}
+
.da-file-explorer__icon {
display: inline-flex;
flex: 0 0 auto;
diff --git a/packages/gfs-interaction-policy/dragPolicy.cjs b/packages/gfs-interaction-policy/dragPolicy.cjs
index 66453220f..256236857 100644
--- a/packages/gfs-interaction-policy/dragPolicy.cjs
+++ b/packages/gfs-interaction-policy/dragPolicy.cjs
@@ -148,9 +148,11 @@ function decideDragAuthority(input) {
const sourceBits = sourceParentHeld instanceof Set ? sourceParentHeld : new Set(sourceParentHeld)
const destinationBits =
destinationHeld instanceof Set ? destinationHeld : new Set(destinationHeld)
+ // Destination first (the surface the user is acting on), then the two
+ // independent source-parent bits in UX-matrix order.
+ if (!destinationBits.has('write')) return { kind: 'deny', reason: 'destination-write' }
if (!sourceBits.has('write')) return { kind: 'deny', reason: 'source-write' }
if (!sourceBits.has('delete')) return { kind: 'deny', reason: 'source-delete' }
- if (!destinationBits.has('write')) return { kind: 'deny', reason: 'destination-write' }
return { kind: 'observed-allowed', checkedAt: input.checkedAt ?? 0 }
}
diff --git a/packages/gfs-interaction-policy/dragPolicy.d.ts b/packages/gfs-interaction-policy/dragPolicy.d.ts
index 7e9d73702..b255a0ccd 100644
--- a/packages/gfs-interaction-policy/dragPolicy.d.ts
+++ b/packages/gfs-interaction-policy/dragPolicy.d.ts
@@ -42,8 +42,9 @@ export interface GfsDragStructureTargetFact {
export interface GfsDragStructureInput {
source: GfsDragStructureSourceFact
target: GfsDragStructureTargetFact
- /** Ancestors of the target from a currently loaded chain, nearest-first. */
- targetAncestorIds?: readonly string[]
+ /** Ancestors of the target from a currently loaded chain, nearest-first; a
+ * trailing `null` marks a chain observed to the physical root. */
+ targetAncestorIds?: readonly (string | null)[]
/** Currently known ancestors of the source (physical parent and above). */
knownSourceAncestorIds?: ReadonlySet<string>
}
diff --git a/packages/gfs-interaction-policy/dragPolicy.test.cjs b/packages/gfs-interaction-policy/dragPolicy.test.cjs
index ae8b4d4c2..5ee9e072e 100644
--- a/packages/gfs-interaction-policy/dragPolicy.test.cjs
+++ b/packages/gfs-interaction-policy/dragPolicy.test.cjs
@@ -315,7 +315,11 @@ describe('dragPolicy: decideDragAuthority', () => {
}
})
- it('evaluate source-write before source-delete (message order matches the UX matrix)', () => {
+ it('destination is evaluated first, then source-write before source-delete', () => {
+ assert.deepEqual(
+ decideDragAuthority({ sourceParentHeld: [], destinationHeld: [] }),
+ { kind: 'deny', reason: 'destination-write' }
+ )
assert.deepEqual(
decideDragAuthority({ sourceParentHeld: [], destinationHeld: ['write'] }),
{ kind: 'deny', reason: 'source-write' }