Skip to content

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

TypeScript

fix(desktop): r1-m4 enforce admitted drag ownership across surfaces

M763b881bb33e
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 7e3325c5a..d0fd8f1aa 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
@@ -986,11 +986,11 @@ describe('FileExplorerTree — drag-and-drop moves', () => {
await screen.findByRole('dialog', { name: 'Move folder B to C' })
})
- it('a stale drop’s cleanup releases only its own shared-store gesture', async () => {
+ it('a stale cross-surface drop cannot open a dialog or release the newer shared gesture', async () => {
// R1-M4 cross-surface: A’s drop is pending in the tree when another
// surface begins gesture B (here driven through the session api). A’s
- // surface epoch is unchanged, so A’s own dialog legitimately opens — but
- // its cleanup must not endDrag the shared store now owned by B.
+ // surface epoch is unchanged; the shared generation must still reject A
+ // and preserve the store now owned by B.
const moveResource = vi.fn(async () => ({ resourceId: 'foldera', version: 9 }))
type Affordances = { held: string[] }
let releaseA!: (value: Affordances) => void
@@ -1073,12 +1073,12 @@ describe('FileExplorerTree — drag-and-drop moves', () => {
})
).toBe(true)
- // A resolves late: its surface epoch is unchanged, so A’s own
- // confirmation legitimately opens.
+ // A resolves late: the shared generation rejects its stale admission.
await act(async () => {
releaseA({ held: ['read', 'write'] })
})
- await screen.findByRole('dialog', { name: 'Move folder A to C' })
+ expect(screen.queryByRole('dialog', { name: 'Move folder A to C' })).toBeNull()
+ expect(moveResource).not.toHaveBeenCalled()
// A’s cleanup must not have ended the shared store’s newer gesture.
expect(sessionApi!.activeSource()?.resourceId).toBe('file-external')
diff --git a/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/index.tsx b/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/index.tsx
index c6c75e28c..045ad4b37 100644
--- a/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/index.tsx
+++ b/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/index.tsx
@@ -444,9 +444,12 @@ export function FileExplorerTree({
const [movingResourceId, setMovingResourceId] = useState<string | null>(null)
const movingResourceIdRef = useRef<string | null>(null)
const draggingSourceRef = useRef<GfsDragSource | null>(null)
+ const hoverOwnerRef = useRef<GfsDragSource | null>(null)
const dragSessionEpochRef = useRef(0)
const [pendingFolderMove, setPendingFolderMove] = useState<{
source: GfsDragSource
+ gestureGeneration: number
+ sessionGeneration: number | null
destination: { resourceId: string; name: string }
allowNumberedRename: boolean
suggestedName?: string
@@ -456,6 +459,38 @@ export function FileExplorerTree({
initialCrumbs: GfsCrumb[]
} | null>(null)
+ useEffect(
+ () => () => {
+ dragSessionEpochRef.current += 1
+ hoverOwnerRef.current = null
+ adjudication.endDragSession()
+ },
+ [adjudication.endDragSession]
+ )
+
+ const liveDragScope = ctrl.accessState === 'revoked' ? null : (ctrl.sessionScope ?? 'anonymous')
+ const liveDragScopeRef = useRef(liveDragScope)
+ liveDragScopeRef.current = liveDragScope
+ const previousDragScopeRef = useRef(liveDragScope)
+ useEffect(() => {
+ if (previousDragScopeRef.current === liveDragScope) return
+ previousDragScopeRef.current = liveDragScope
+ dragSessionEpochRef.current += 1
+ draggingSourceRef.current = null
+ hoverOwnerRef.current = null
+ adjudication.endDragSession()
+ setPendingFolderMove(null)
+ setDropStatesByResourceId({})
+ }, [adjudication.endDragSession, liveDragScope])
+
+ const ownsDrop = useCallback(
+ (source: GfsDragSource, epoch: number, sharedGeneration: number | null) =>
+ source.scope === liveDragScopeRef.current &&
+ epoch === dragSessionEpochRef.current &&
+ (!dragSession || dragSession.currentGeneration() === sharedGeneration),
+ [dragSession]
+ )
+
const roots = useMemo(() => sortTreeItems(ctrl.accessibleResources), [ctrl.accessibleResources])
const handleToggle = useCallback((resourceId: string) => {
@@ -476,30 +511,27 @@ export function FileExplorerTree({
// folder confirmation never appeared). A new dragstart still invalidates
// in-flight decisions.
draggingSourceRef.current = null
+ hoverOwnerRef.current = null
dragSession?.endDrag()
adjudication.endDragSession()
setDropStatesByResourceId({})
}, [adjudication, dragSession])
- /** Drop-path cleanup owned by the gesture that started the drop: a newer
- * gesture on THIS surface (epoch advanced) owns every local ref and timer,
- * and a newer gesture on ANY surface (shared generation advanced) owns the
- * session store. The unconditional native-dragend clear above stays. */
+ /** Release only the source and hover work owned by the admitted gesture. */
const finishNodeDropCleanup = useCallback(
- (epoch: number, sessionGeneration: number | null) => {
+ (source: GfsDragSource, epoch: number, sessionGeneration: number | null) => {
if (epoch !== dragSessionEpochRef.current) return
draggingSourceRef.current = null
- setDropStatesByResourceId({})
- if (
- dragSession &&
- sessionGeneration !== null &&
- dragSession.currentGeneration() === sessionGeneration
- ) {
+ if (hoverOwnerRef.current === null || hoverOwnerRef.current === source) {
+ hoverOwnerRef.current = null
+ setDropStatesByResourceId({})
+ adjudication.endDragSession()
+ }
+ if (dragSession && dragSession.currentGeneration() === sessionGeneration) {
dragSession.endDrag()
}
- adjudication.endDragSession()
},
- [adjudication, dragSession, dragSessionEpochRef]
+ [adjudication, dragSession]
)
const treeDragSourceFrom = useCallback(
@@ -562,15 +594,13 @@ export function FileExplorerTree({
)
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
+ if (!dragSession) return draggingSourceRef.current
+ const source = dragSession.activeSource()
+ return source &&
+ dragSession.matchesScope(ctrl.sessionScope ?? 'anonymous') &&
+ source.drive === GFS_DRIVE_MAIN
+ ? source
+ : null
}, [ctrl.sessionScope, dragSession])
const handleNodeDragOver = useCallback(
@@ -584,6 +614,7 @@ export function FileExplorerTree({
if (!source || node.kind !== 'directory' || source.resourceId === node.resourceId) return
event.preventDefault()
event.stopPropagation()
+ hoverOwnerRef.current = source
const verdict = adjudication.hoverVerdict(source, {
resourceId: node.resourceId,
name: node.name,
@@ -605,6 +636,7 @@ export function FileExplorerTree({
{ resourceId: node.resourceId, name: node.name, kind: node.kind, ancestorIds },
source.parentKnown ? source.parentResourceId : null,
() => {
+ if (hoverOwnerRef.current !== source) return
setDropStatesByResourceId(previous => {
const fresh = adjudication.hoverVerdict(source, {
resourceId: node.resourceId,
@@ -716,7 +748,7 @@ export function FileExplorerTree({
kind: node.kind,
ancestorIds,
})
- if (epoch !== dragSessionEpochRef.current) return
+ if (!ownsDrop(source, epoch, sessionGeneration)) return
if (!decision.allowed) {
const message = moveDenialMessage(decision, node.name)
if (message) pushToast(message, 'error')
@@ -725,6 +757,8 @@ export function FileExplorerTree({
if (source.kind === 'directory') {
setPendingFolderMove({
source,
+ gestureGeneration: epoch,
+ sessionGeneration,
destination: { resourceId: node.resourceId, name: node.name },
allowNumberedRename: decision.allowNumberedRename,
})
@@ -736,14 +770,15 @@ export function FileExplorerTree({
decision.allowNumberedRename
)
} finally {
- finishNodeDropCleanup(epoch, sessionGeneration)
+ finishNodeDropCleanup(source, epoch, sessionGeneration)
}
},
[
adjudication,
finishNodeDropCleanup,
commitMove,
- dragSessionEpochRef,
+ dragSession,
+ ownsDrop,
pushToast,
resolveActiveSource,
]
@@ -904,7 +939,10 @@ export function FileExplorerTree({
onConfirm={({ allowNumberedRename }) => {
const pending = pendingFolderMove
setPendingFolderMove(null)
- if (pending) {
+ if (
+ pending &&
+ ownsDrop(pending.source, pending.gestureGeneration, pending.sessionGeneration)
+ ) {
void commitMove(pending.source, pending.destination, allowNumberedRename)
}
}}
diff --git a/desktop-app/ui/src/gfs/__tests__/dragOwnership.test.tsx b/desktop-app/ui/src/gfs/__tests__/dragOwnership.test.tsx
new file mode 100644
index 000000000..7dccff4b9
--- /dev/null
+++ b/desktop-app/ui/src/gfs/__tests__/dragOwnership.test.tsx
@@ -0,0 +1,431 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import { FileExplorerTree } from '@components/SidebarNav/FileExplorerTree'
+import { FilesPage } from '@/pages/FilesPage'
+import {
+ accessibleResource,
+ affordancesResult,
+ childView,
+ heldAffordances,
+ listAccessiblePage,
+ listChildrenPage,
+ resolveResource,
+ resolvedDirectory,
+ resolvedFile,
+} from '../__fixtures__/gfsProducerFixtures'
+import { GfsDragSessionProvider, useGfsDragSession } from '../dragSession'
+import type { GfsDragSessionApi } from '../dragSession.types'
+
+const mocks = vi.hoisted(() => ({
+ controller: vi.fn(),
+ auth: {
+ isAuthenticated: true,
+ me: { id: 'user-1', teamId: 'team-1' },
+ runtimeConfigState: { envKey: 'env-1' },
+ },
+}))
+vi.mock('@hooks/domain/useGfsBrowserController', () => ({
+ useGfsBrowserController: mocks.controller,
+ GFS_UNAVAILABLE_LOCATION_MESSAGE: 'This folder or file is no longer available.',
+}))
+vi.mock('@contexts/AuthContext', () => ({ useAuthContext: () => mocks.auth }))
+
+function baseController() {
+ return {
+ current: null,
+ crumbs: [],
+ sessionScope: 'env-1:user-1:team-1',
+ accessibleResources: [],
+ items: [],
+ affordances: null,
+ affordancesError: null,
+ loadingAffordances: false,
+ rowAffordancesResourceId: null,
+ setRowAffordancesResourceId: vi.fn(),
+ rowAffordancesByResourceId: {},
+ rowAffordances: null,
+ rowAffordancesError: null,
+ loadingAccessible: false,
+ loading: false,
+ accessibleError: null,
+ accessibleNotice: null,
+ error: null,
+ openError: null,
+ resolving: false,
+ hasMoreAccessible: false,
+ isFetchingMoreAccessible: false,
+ hasMore: false,
+ isFetchingMore: false,
+ loadMoreAccessible: vi.fn(),
+ loadMore: vi.fn(),
+ openUri: vi.fn(),
+ openResource: vi.fn(),
+ openChild: vi.fn(),
+ goToCrumb: vi.fn(),
+ restoreCrumbs: vi.fn(),
+ grant: vi.fn(),
+ grants: [],
+ grantsError: null,
+ loadingGrants: false,
+ refreshGrants: vi.fn(),
+ inheritedAccess: [],
+ loadingInheritedAccess: false,
+ refreshInheritedAccess: vi.fn(),
+ revokeGrant: vi.fn(),
+ revoking: false,
+ shares: [],
+ sharesError: null,
+ loadingShares: false,
+ refreshShares: vi.fn(),
+ revokeShare: vi.fn(),
+ revokingShare: false,
+ accessState: 'active',
+ retryAccess: vi.fn(),
+ handleAuthorityFailure: vi.fn(() => false),
+ createShare: vi.fn(),
+ createFolder: vi.fn(),
+ createFile: vi.fn(),
+ createFileFromPath: vi.fn(),
+ replaceFile: vi.fn(),
+ replaceFileFromPath: vi.fn(),
+ renameResource: vi.fn(),
+ moveResource: vi.fn(),
+ deleteResource: vi.fn(),
+ mutating: false,
+ reset: vi.fn(),
+ refreshAffordances: vi.fn(),
+ discoveryFailure: null,
+ retryDiscovery: vi.fn(),
+ authorityPending: false,
+ errorUpdatedAt: 0,
+ retryChildren: vi.fn(),
+ }
+}
+
+// Controller values model local UI state; wire values pass through the real
+// GfsClient and structured-clone fixture producers.
+function SessionProbe({ onApi }: { onApi: (api: GfsDragSessionApi) => void }) {
+ const api = useGfsDragSession()
+ if (api) onApi(api)
+ return null
+}
+function transfer() {
+ return {
+ types: ['application/x-evenfire-gfs-resource'],
+ files: [],
+ effectAllowed: 'move',
+ dropEffect: 'none',
+ setData: vi.fn(),
+ }
+}
+function externalSource() {
+ return {
+ resourceId: 'external',
+ gfsUri: 'gfs://main/external',
+ drive: 'main',
+ kind: 'file' as const,
+ name: 'external.txt',
+ parentKnown: true,
+ parentResourceId: 'grand',
+ knownAncestorIds: ['grand'],
+ origin: 'files' as const,
+ scope: 'env-1:user-1:team-1',
+ }
+}
+afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+})
+beforeEach(() => {
+ mocks.auth.me = { id: 'user-1', teamId: 'team-1' }
+})
+
+for (const surface of ['sidebar', 'files'] as const) {
+ describe(`${surface} drop ownership (R1-M4)`, () => {
+ async function setup(
+ sourceKind: 'file' | 'directory' = 'directory',
+ delayed = false,
+ denyTarget = false
+ ) {
+ const bits = await affordancesResult(heldAffordances(['read', 'write', 'delete']))
+ let release!: () => void
+ const gate = new Promise<void>(resolve => {
+ release = resolve
+ })
+ let parked = delayed
+ const affordances = vi.fn(async (id: string, _drive: string) => {
+ if (parked && id === 'target') {
+ parked = false
+ await gate
+ }
+ return denyTarget && id === 'target' ? affordancesResult(heldAffordances(['read'])) : bits
+ })
+ const moveResource = vi.fn(async (_id: string, _destination: string) => ({}))
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ gfs: {
+ listChildren: vi.fn(async () =>
+ listChildrenPage([
+ childView('source', 'Source', sourceKind, { parentResourceId: 'grand' }),
+ childView('target', 'Target', 'directory', { parentResourceId: 'grand' }),
+ childView('hover', 'Hover', 'directory', { parentResourceId: 'grand' }),
+ ])
+ ),
+ affordances,
+ resolve: vi.fn(async (uri: string) => {
+ const id = uri.split('/').pop()!
+ return resolveResource(
+ id === 'external' || (id === 'source' && sourceKind === 'file')
+ ? resolvedFile(id, id === 'external' ? 'external.txt' : 'Source', {
+ parentResourceId: 'grand',
+ })
+ : resolvedDirectory(id, id === 'source' ? 'Source' : id, {
+ parentResourceId: id === 'grand' ? null : 'grand',
+ })
+ )
+ }),
+ },
+ },
+ })
+ const { items } = await listAccessiblePage([
+ accessibleResource('source', 'Source', sourceKind, { parentResourceId: 'grand' }),
+ accessibleResource('target', 'Target', 'directory', { parentResourceId: 'grand' }),
+ accessibleResource('hover', 'Hover', 'directory', { parentResourceId: 'grand' }),
+ ])
+ const ctrl = {
+ ...baseController(),
+ accessibleResources:
+ surface === 'sidebar'
+ ? (await listAccessiblePage([accessibleResource('grand', 'Grand', 'directory')])).items
+ : items,
+ items,
+ moveResource,
+ }
+ mocks.controller.mockReturnValue(ctrl)
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ let api!: GfsDragSessionApi
+ const toast = vi.fn()
+ let mounted = true
+ const view = () => (
+ <QueryClientProvider client={queryClient}>
+ <GfsDragSessionProvider>
+ {!mounted ? null : surface === 'sidebar' ? (
+ <FileExplorerTree onOpenFolder={vi.fn()} onOpenPreview={vi.fn()} pushToast={toast} />
+ ) : (
+ <FilesPage pushToast={toast} />
+ )}
+ <SessionProbe
+ onApi={value => {
+ api = value
+ }}
+ />
+ </GfsDragSessionProvider>
+ </QueryClientProvider>
+ )
+ const rendered = render(view())
+ if (surface === 'sidebar') {
+ fireEvent.click(screen.getByRole('button', { name: 'Expand Grand' }))
+ await screen.findByRole('button', { name: 'Source' })
+ }
+ const row = (name: string) => {
+ const button = screen.getByRole('button', {
+ name: surface === 'sidebar' ? name : `Open ${name}`,
+ })
+ return surface === 'sidebar'
+ ? button.closest('[role="treeitem"]')!.querySelector('.da-file-explorer__row')!
+ : button
+ }
+ const dataTransfer = transfer()
+ const sourceElement = () =>
+ screen.getByRole('button', { name: surface === 'sidebar' ? 'Source' : 'Open Source' })
+ const start = () => fireEvent.dragStart(sourceElement(), { dataTransfer })
+ const drop = () => fireEvent.drop(row('Target'), { dataTransfer })
+ const dropState = (name: string) => row(name).getAttribute('data-drop-state')
+ return {
+ dropState,
+ sourceElement,
+ ctrl,
+ api: () => api,
+ row,
+ start,
+ drop,
+ dataTransfer,
+ release,
+ moveResource,
+ affordances,
+ toast,
+ rerender: () => rendered.rerender(view()),
+ unmountSurface: () => {
+ mounted = false
+ rendered.rerender(view())
+ },
+ }
+ }
+
+ it.each(['file', 'directory'] as const)(
+ 'rejects late %s admission and preserves the newer cross-surface hover check',
+ async kind => {
+ const h = await setup(kind, true)
+ h.start()
+ h.drop()
+ await waitFor(() => expect(h.affordances).toHaveBeenCalledWith('target', 'main'))
+ expect(h.api().beginDrag(externalSource())).toBe(true)
+ fireEvent.dragOver(h.row('Hover'), { dataTransfer: h.dataTransfer })
+ expect(h.dropState('Hover')).toBe('checking')
+ await act(async () => {
+ h.release()
+ })
+ expect(screen.queryByRole('dialog', { name: 'Move folder Source to Target' })).toBeNull()
+ expect(h.moveResource).not.toHaveBeenCalled()
+ expect(h.toast).not.toHaveBeenCalled()
+ expect(h.dropState('Hover')).toBe('checking')
+ expect(h.api().activeSource()?.resourceId).toBe('external')
+ await waitFor(() => expect(h.affordances).toHaveBeenCalledWith('hover', 'main'))
+ fireEvent.drop(h.row('Hover'), { dataTransfer: h.dataTransfer })
+ await waitFor(() => expect(h.moveResource).toHaveBeenCalled())
+ expect(h.moveResource.mock.calls[0]![0]).toBe('external')
+ expect(h.moveResource.mock.calls[0]![1]).toBe('hover')
+ }
+ )
+
+ it('does not dispatch a pending admission after its destination surface unmounts', async () => {
+ const h = await setup('file', true)
+ h.start()
+ h.drop()
+ await waitFor(() => expect(h.affordances).toHaveBeenCalledWith('target', 'main'))
+ h.unmountSurface()
+ await act(async () => {
+ h.release()
+ })
+ expect(h.moveResource).not.toHaveBeenCalled()
+ expect(h.toast).not.toHaveBeenCalled()
+ })
+
+ it('suppresses a stale denial without clearing the newer source', async () => {
+ const h = await setup('file', true, true)
+ h.start()
+ h.drop()
+ await waitFor(() => expect(h.affordances).toHaveBeenCalledWith('target', 'main'))
+ h.api().beginDrag(externalSource())
+ await act(async () => {
+ h.release()
+ })
+ expect(h.toast).not.toHaveBeenCalled()
+ expect(h.moveResource).not.toHaveBeenCalled()
+ expect(h.api().activeSource()?.resourceId).toBe('external')
+ })
+
+ it('reports an already dispatched move without clearing newer hover work', async () => {
+ const h = await setup('file')
+ let finish!: () => void
+ const mutation = new Promise<void>(resolve => {
+ finish = resolve
+ })
+ h.moveResource.mockImplementationOnce(async () => {
+ await mutation
+ return {}
+ })
+ h.start()
+ h.drop()
+ await waitFor(() => expect(h.moveResource).toHaveBeenCalled())
+ h.api().beginDrag(externalSource())
+ fireEvent.dragOver(h.row('Hover'), { dataTransfer: h.dataTransfer })
+ await act(async () => {
+ finish()
+ })
+ expect(h.toast).toHaveBeenCalledWith('Moved Source to Target', 'success')
+ expect(h.api().activeSource()?.resourceId).toBe('external')
+ expect(h.dropState('Hover')).toBe('checking')
+ await waitFor(() => expect(h.affordances).toHaveBeenCalledWith('hover', 'main'))
+ })
+
+ it.each(['scope', 'revoked'] as const)(
+ 'rejects pending adjudication after native end and %s change',
+ async change => {
+ const h = await setup('directory', true)
+ h.start()
+ h.drop()
+ await waitFor(() => expect(h.affordances).toHaveBeenCalledWith('target', 'main'))
+ fireEvent.dragEnd(h.sourceElement(), { dataTransfer: h.dataTransfer })
+ if (change === 'scope') {
+ mocks.auth.me = { id: 'user-1', teamId: 'team-2' }
+ h.ctrl.sessionScope = 'env-1:user-1:team-2'
+ } else h.ctrl.accessState = 'revoked'
+ h.rerender()
+ await act(async () => {
+ h.release()
+ })
+ expect(screen.queryByRole('dialog')).toBeNull()
+ expect(h.moveResource).not.toHaveBeenCalled()
+ expect(h.toast).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each(['end', 'invalidate'] as const)(
+ 'never resurrects the local descriptor after shared %s',
+ async action => {
+ const h = await setup()
+ h.start()
+ if (action === 'end') h.api().endDrag()
+ else h.api().invalidate('authority')
+ fireEvent.dragOver(h.row('Target'), { dataTransfer: h.dataTransfer })
+ await act(async () => {
+ h.drop()
+ })
+ expect(h.affordances).not.toHaveBeenCalled()
+ expect(screen.queryByRole('dialog')).toBeNull()
+ expect(h.moveResource).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each(['scope', 'revoked'] as const)(
+ 'dismisses a pending folder confirmation on %s change',
+ async change => {
+ const h = await setup()
+ h.start()
+ h.drop()
+ await screen.findByRole('dialog', { name: 'Move folder Source to Target' })
+ fireEvent.dragEnd(h.sourceElement(), { dataTransfer: h.dataTransfer })
+ if (change === 'scope') {
+ mocks.auth.me = { id: 'user-1', teamId: 'team-2' }
+ h.ctrl.sessionScope = 'env-1:user-1:team-2'
+ } else h.ctrl.accessState = 'revoked'
+ h.rerender()
+ expect(screen.queryByRole('dialog', { name: 'Move folder Source to Target' })).toBeNull()
+ expect(h.moveResource).not.toHaveBeenCalled()
+ }
+ )
+
+ it('refuses a confirmation superseded by another surface gesture', async () => {
+ const h = await setup()
+ h.start()
+ h.drop()
+ const dialog = await screen.findByRole('dialog', { name: 'Move folder Source to Target' })
+ expect(h.api().beginDrag(externalSource())).toBe(true)
+ await act(async () => {
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Move' }))
+ })
+ expect(h.moveResource).not.toHaveBeenCalled()
+ expect(h.api().activeSource()?.resourceId).toBe('external')
+ })
+
+ it('preserves a valid admitted confirmation across ordinary native end', async () => {
+ const h = await setup('directory', true)
+ h.start()
+ h.drop()
+ await waitFor(() => expect(h.affordances).toHaveBeenCalledWith('target', 'main'))
+ fireEvent.dragEnd(h.sourceElement(), { dataTransfer: h.dataTransfer })
+ await act(async () => {
+ h.release()
+ })
+ const dialog = await screen.findByRole('dialog', { name: 'Move folder Source to Target' })
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Move' }))
+ await waitFor(() => expect(h.moveResource).toHaveBeenCalled())
+ expect(h.moveResource.mock.calls[0]![0]).toBe('source')
+ expect(h.moveResource.mock.calls[0]![1]).toBe('target')
+ })
+ })
+}
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index 947a20ee8..ed7324f5b 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -301,6 +301,8 @@ export function FilesPage({
// shared dispatch; files commit directly on an allowed admission.
const [pendingFolderMove, setPendingFolderMove] = useState<{
source: GfsDragSource
+ gestureGeneration: number
+ sessionGeneration: number | null
destination: { resourceId: string; name: string }
allowNumberedRename: boolean
suggestedName?: string
@@ -309,6 +311,7 @@ export function FilesPage({
const draggingSourceRef = useRef<GfsDragSource | null>(null)
const movingResourceRef = useRef<string | null>(null)
const hoveredFolderRef = useRef<string | null>(null)
+ const hoverOwnerRef = useRef<GfsDragSource | null>(null)
const dragSessionRef = useRef(0)
const manageReturnCrumbsRef = useRef<GfsCrumb[] | null>(null)
const uploadInputRef = useRef<HTMLInputElement | null>(null)
@@ -346,6 +349,39 @@ export function FilesPage({
resolve: useCallback((uri: string) => window.clerum.gfs.resolve(uri), []),
})
+ useEffect(
+ () => () => {
+ dragSessionRef.current += 1
+ hoverOwnerRef.current = null
+ adjudication.endDragSession()
+ },
+ [adjudication.endDragSession]
+ )
+
+ const liveDragScope = ctrl.accessState === 'revoked' ? null : (sessionScope ?? 'anonymous')
+ const liveDragScopeRef = useRef(liveDragScope)
+ liveDragScopeRef.current = liveDragScope
+ const previousDragScopeRef = useRef(liveDragScope)
+ useEffect(() => {
+ if (previousDragScopeRef.current === liveDragScope) return
+ previousDragScopeRef.current = liveDragScope
+ dragSessionRef.current += 1
+ draggingResourceRef.current = null
+ draggingSourceRef.current = null
+ hoveredFolderRef.current = null
+ hoverOwnerRef.current = null
+ adjudication.endDragSession()
+ setPendingFolderMove(null)
+ setDraggingResourceId(null)
+ setDragOverFolderId(null)
+ setDropStatesById({})
+ }, [adjudication.endDragSession, liveDragScope])
+
+ const ownsDrop = (source: GfsDragSource, epoch: number, sharedGeneration: number | null) =>
+ source.scope === liveDragScopeRef.current &&
+ epoch === dragSessionRef.current &&
+ (!dragSession || dragSession.currentGeneration() === sharedGeneration)
+
const lastRemoteGfsChangeEpochRef = useRef(remoteGfsChangeEpoch)
useEffect(() => {
if (remoteGfsChangeEpoch === undefined) return
@@ -1083,6 +1119,7 @@ export function FilesPage({
draggingResourceRef.current = null
draggingSourceRef.current = null
hoveredFolderRef.current = null
+ hoverOwnerRef.current = null
dragSession?.endDrag()
adjudication.endDragSession()
setDraggingResourceId(null)
@@ -1090,26 +1127,26 @@ export function FilesPage({
setDropStatesById({})
}
- /** Drop-path cleanup owned by the gesture that started the drop: a newer
- * gesture on THIS surface (epoch advanced) owns every local ref and timer,
- * and a newer gesture on ANY surface (shared generation advanced) owns the
- * session store. The unconditional native-dragend clear above stays. */
- const finishDropCleanup = (gestureGeneration: number, sessionGeneration: number | null) => {
+ /** Release only the source and hover work owned by the admitted gesture. */
+ const finishDropCleanup = (
+ source: GfsDragSource,
+ gestureGeneration: number,
+ sessionGeneration: number | null
+ ) => {
if (gestureGeneration !== dragSessionRef.current) return
draggingResourceRef.current = null
draggingSourceRef.current = null
- hoveredFolderRef.current = null
setDraggingResourceId(null)
- setDragOverFolderId(null)
- setDropStatesById({})
- if (
- dragSession &&
- sessionGeneration !== null &&
- dragSession.currentGeneration() === sessionGeneration
- ) {
+ if (hoverOwnerRef.current === null || hoverOwnerRef.current === source) {
+ hoverOwnerRef.current = null
+ hoveredFolderRef.current = null
+ setDragOverFolderId(null)
+ setDropStatesById({})
+ adjudication.endDragSession()
+ }
+ if (dragSession && dragSession.currentGeneration() === sessionGeneration) {
dragSession.endDrag()
}
- adjudication.endDragSession()
}
/** Ancestor chain of rows in the current listing, nearest-first: the open
@@ -1138,18 +1175,15 @@ export function FilesPage({
}
}
- /** The active source is the session descriptor when its scope matches
- * (cross-surface drags), else this surface's local ref. */
+ /** A provider owns transport identity; local refs are only a provider-absent fallback. */
const resolveActiveSource = (): GfsDragSource | null => {
- const fromSession = dragSession?.activeSource()
- if (
- fromSession &&
- dragSession?.matchesScope(sessionScope ?? 'anonymous') &&
- fromSession.drive === GFS_DRIVE_MAIN
- ) {
- return fromSession
- }
- return draggingSourceRef.current
+ if (!dragSession) return draggingSourceRef.current
+ const source = dragSession.activeSource()
+ return source &&
+ dragSession.matchesScope(sessionScope ?? 'anonymous') &&
+ source.drive === GFS_DRIVE_MAIN
+ ? source
+ : null
}
const applyHoverVerdict = (folderId: string, verdict: GfsDropVerdict): GfsDropVerdict => {
@@ -1207,6 +1241,7 @@ export function FilesPage({
event.preventDefault()
event.stopPropagation()
hoveredFolderRef.current = folder.resourceId
+ hoverOwnerRef.current = source
const target = {
resourceId: folder.resourceId,
name: folder.name,
@@ -1225,7 +1260,8 @@ export function FilesPage({
target,
source.parentKnown ? source.parentResourceId : null,
() => {
- if (hoveredFolderRef.current !== folder.resourceId) return
+ if (hoverOwnerRef.current !== source || hoveredFolderRef.current !== folder.resourceId)
+ return
const fresh = adjudication.hoverVerdict(source, target)
applyHoverVerdict(folder.resourceId, fresh)
}
@@ -1375,7 +1411,7 @@ export function FilesPage({
kind: destination.kind,
ancestorIds: rowTargetAncestorIds(),
})
- if (dragGeneration !== dragSessionRef.current) return
+ if (!ownsDrop(source, dragGeneration, sessionGeneration)) return
if (!decision.allowed) {
const message = dropDenialMessage(decision, destination.name)
if (message) pushToast?.(message, 'error')
@@ -1388,6 +1424,8 @@ export function FilesPage({
const suggested = suggestNumberedMoveName(source.name, occupied)
setPendingFolderMove({
source,
+ gestureGeneration: dragGeneration,
+ sessionGeneration,
destination: { resourceId: destination.resourceId, name: destination.name },
allowNumberedRename: decision.allowNumberedRename,
...(suggested !== undefined ? { suggestedName: suggested } : {}),
@@ -1400,7 +1438,7 @@ export function FilesPage({
decision.allowNumberedRename
)
} finally {
- finishDropCleanup(dragGeneration, sessionGeneration)
+ finishDropCleanup(source, dragGeneration, sessionGeneration)
}
}
@@ -2593,7 +2631,10 @@ export function FilesPage({
onConfirm={({ allowNumberedRename }) => {
const pending = pendingFolderMove
setPendingFolderMove(null)
- if (pending) {
+ if (
+ pending &&
+ ownsDrop(pending.source, pending.gestureGeneration, pending.sessionGeneration)
+ ) {
void runMoveCommit(pending.source, pending.destination, allowNumberedRename)
}
}}