Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(gfs): rp-003 seed the numbered-name ladder with the destination's known children
M41d7e4fb0b82
diff --git a/control-ui/components/GfsBrowser.tsx b/control-ui/components/GfsBrowser.tsxindex 8ba96e071..7b7fcc36c 100644--- a/control-ui/components/GfsBrowser.tsx+++ b/control-ui/components/GfsBrowser.tsx@@ -3,9 +3,9 @@import React, { useCallback, useEffect, useRef, useState } from 'react'import { SingleValueEditDialog } from '@clerum/frontend-components'import {+ GFS_MOVE_MAX_NETWORK_ATTEMPTS,GFS_UPLOAD_NAME_EXHAUSTED_MESSAGE,GFS_UPLOAD_NAME_RETRY_LIMIT,- GFS_MOVE_MAX_NETWORK_ATTEMPTS,createGfsUploadNameReservationBook,decideDragPathStructure,gfsUploadNameRetryDecision,@@ -1360,7 +1360,12 @@ export function GfsBrowser(): React.JSX.Element {movingResourceRef.current = source.resourceIdsetMovingResourceId(source.resourceId)try {- const occupiedNames = new Set<string>()+ // Seed the ladder with the destination's known children (the same cache+ // the confirmation suggestion came from) so the first 409 skips every+ // already-taken numbered name instead of guessing it blind.+ const occupiedNames = new Set<string>(+ (childCacheRef.current.get(destination.resourceId)?.items ?? []).map(item => item.name)+ )let moveName = source.namelet moved = falselet moveResult: unknown@@ -1579,7 +1584,9 @@ export function GfsBrowser(): React.JSX.Element {}}- function structureDenialMessage(reason: 'self' | 'descendant' | 'same-parent' | 'root-source' | 'cross-drive'): string {+ function structureDenialMessage(+ reason: 'self' | 'descendant' | 'same-parent' | 'root-source' | 'cross-drive'+ ): string {switch (reason) {case 'same-parent':return 'This item is already in this folder.'diff --git a/control-ui/components/__tests__/GfsBrowser.test.tsx b/control-ui/components/__tests__/GfsBrowser.test.tsxindex e3de82ffa..c83fb842f 100644--- a/control-ui/components/__tests__/GfsBrowser.test.tsx+++ b/control-ui/components/__tests__/GfsBrowser.test.tsx@@ -3843,7 +3843,7 @@ describe('GfsBrowser — folder drag-and-drop', () => {mockApiSend.mockReset()})- function folderPage() {+ function folderPage(archiveChildren: ReturnType<typeof child>[] = []) {const archive = child('archive', 'directory', 1)const projects = child('projects', 'directory', 2)mockApiGet.mockImplementation(async (path: string) => {@@ -3857,6 +3857,9 @@ describe('GfsBrowser — folder drag-and-drop', () => {nextCursor: null,}}+ if (path === '/api/v1/gfs/resources/id-1/children') {+ return { items: archiveChildren, nextCursor: null }+ }return { items: [], nextCursor: null }})return { archive, projects }@@ -4047,4 +4050,61 @@ describe('GfsBrowser — folder drag-and-drop', () => {)expect(await screen.findByText('Moved "projects" to "archive" as "projects (2)".')).toBeTruthy()})++ it('a cached destination seeds the ladder so the first 409 jumps to the first free numbered name', async () => {+ // RP-003: archive is prefetched holding projects, projects (1) and+ // projects (2). The blind ladder burned all three attempts on taken+ // names and ended on "The destination changed". Seeded from the same+ // cache the suggestion came from, attempt two lands on projects (3).+ folderPage([+ child('projects', 'directory', 3),+ child('projects (1)', 'directory', 4),+ child('projects (2)', 'directory', 5),+ ])+ const actualApi = await vi.importActual<typeof import('@lib/api')>('@lib/api')+ const conflict = () => {+ const text = JSON.stringify({+ error: { code: 'already_exists', message: 'a resource with this name already exists' },+ })+ return actualApi.formatApiError(+ new Response(text, { status: 409, statusText: 'Conflict' }),+ text+ )+ }+ mockApiSend.mockRejectedValueOnce(conflict()).mockResolvedValueOnce({+ ok: true,+ data: { resourceId: 'id-2', version: 1 },+ })+ renderBrowser()++ await waitFor(() => expect(screen.queryByRole('status', { name: 'Loading files' })).toBeNull())+ // Wait until the archive prefetch has landed in the children cache.+ await waitFor(() =>+ expect(mockApiGet).toHaveBeenCalledWith('/api/v1/gfs/resources/id-1/children', {+ drive: 'main',+ })+ )+ const list = screen.getByRole('list', { name: 'Current folder resources' })+ const projectsRow = within(list).getByText('projects').closest('li')!+ const archiveRow = within(list).getByText('archive').closest('li')!++ dragAndDrop(projectsRow, archiveRow)+ const dialog = await screen.findByRole('dialog', {+ name: 'Move folder projects to archive',+ })+ // The suggestion is derived from the same cached names.+ expect(within(dialog).getByText(/projects \(3\)/)).toBeTruthy()+ fireEvent.click(within(dialog).getByRole('checkbox'))+ fireEvent.click(within(dialog).getByRole('button', { name: 'Move', exact: true }))++ await waitFor(() => expect(mockApiSend).toHaveBeenCalledTimes(2))+ expect(mockApiSend).toHaveBeenNthCalledWith(+ 2,+ 'PATCH',+ '/api/v1/gfs/resources/id-2',+ { drive: 'main', newParentId: 'id-1', ifMatch: 0, newName: 'projects (3)' },+ { drive: 'main' }+ )+ expect(await screen.findByText('Moved "projects" to "archive" as "projects (3)".')).toBeTruthy()+ })})diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 7496c0a55..39cfaf1b9 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.738",+ "version": "0.1.739","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.738",+ "version": "0.1.739","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/frontend-components": "file:../packages/frontend-components",diff --git a/control-ui/package.json b/control-ui/package.jsonindex 7cd3923b6..cf97cc7a7 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.738",+ "version": "0.1.739","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",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.tsxindex d0fd8f1aa..c6d2ab4de 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@@ -859,6 +859,97 @@ describe('FileExplorerTree — drag-and-drop moves', () => {await screen.findByRole('dialog', { name: 'Move folder A to B' })})+ it('seeds the numbered-name ladder from the destination’s cached children (RP-003)', async () => {+ // B is expanded and its children — A, A (1), A (2) — are in the shared+ // children cache. The blind ladder burned all three attempts on taken+ // names and ended on "The destination changed". Seeded from the cache,+ // the first 409 jumps straight to A (3), and the confirmation suggests+ // that same name.+ const moveResource = vi.fn(+ async (+ _resourceId: string,+ _destinationId: string,+ _drive?: string,+ _ifMatch?: number,+ newName?: string+ ) => {+ if (+ newName === undefined ||+ newName === 'A' ||+ newName === 'A (1)' ||+ newName === 'A (2)'+ ) {+ throw new Error('409 Conflict: a resource with this name already exists httpStatus=409')+ }+ return { 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'+ return {+ drive: 'main',+ resourceId: id === 'grand' ? 'grand' : id,+ 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'),+ ])+ ),+ listChildren: vi.fn(async (resourceId: string) => {+ if (resourceId === 'folderb') {+ return listChildrenPage([+ childView('a-dup', 'A', 'directory'),+ childView('a-1', 'A (1)', 'directory'),+ childView('a-2', 'A (2)', 'directory'),+ ])+ }+ return listChildrenPage([])+ }),+ affordances,+ resolve,+ moveResource,+ })+ const { pushToast } = renderTreeWithSession()++ const rowA = await screen.findByRole('button', { name: 'A' })+ const rowB = await screen.findByRole('button', { name: 'B' })+ // Expand B so its children load into the shared children cache — the+ // production path that makes the destination's names known.+ fireEvent.click(screen.getByRole('button', { name: 'Expand B' }))+ await screen.findByRole('button', { name: 'A (1)' })++ const dataTransfer = dragTypes()+ const aRow = rowA.closest('[role="treeitem"]')!.querySelector('.da-file-explorer__row')!+ const bRow = rowB.closest('[role="treeitem"]')!.querySelector('.da-file-explorer__row')!+ fireEvent.dragStart(rowA, { dataTransfer })+ fireEvent.dragOver(bRow, { dataTransfer })+ fireEvent.drop(bRow, { dataTransfer })+ fireEvent.dragEnd(aRow, { dataTransfer })++ const dialog = await screen.findByRole('dialog', { name: 'Move folder A to B' })+ // The suggestion comes from the cached destination names.+ expect(within(dialog).getByText(/A \(3\)/)).toBeTruthy()+ fireEvent.click(within(dialog).getByRole('checkbox'))+ fireEvent.click(within(dialog).getByRole('button', { name: 'Move' }))++ await waitFor(() => expect(moveResource).toHaveBeenCalledTimes(2))+ expect(moveResource).toHaveBeenNthCalledWith(2, 'foldera', 'folderb', 'main', 4, 'A (3)')+ await waitFor(() => expect(pushToast).toHaveBeenCalledWith('Moved A to B as A (3)', 'success'))+ })+it('a new gesture after a lost dragend commits the dragged folder, not the stale one', async () => {// R1-H2: the browser can lose dragend (e.g. the source row is replaced by// a listing refresh mid-drag and dragend fires on a detached node). Thediff --git a/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/index.tsx b/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/index.tsxindex 045ad4b37..20bc67151 100644--- a/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/index.tsx+++ b/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/index.tsx@@ -20,7 +20,12 @@ import { isGfsChildrenDenied, purgeDeniedGfsChildren } from '@/gfs/deniedChildreimport { useGfsDragAdjudication } from '@/gfs/dragAdjudication'import type { GfsDragSource } from '@/gfs/dragSession'import { useGfsDragSession } from '@/gfs/dragSession'-import { commitGfsMove, moveDenialMessage, toastMoveOutcome } from '@/gfs/moveCommit'+import {+ commitGfsMove,+ moveDenialMessage,+ suggestNumberedMoveName,+ toastMoveOutcome,+} from '@/gfs/moveCommit'import { GfsMoveConfirmDialog } from '@/gfs/moveConfirmDialog'import { GfsMoveDialog } from '@/gfs/moveDialog'import { IconChevronRight, IconContexts } from '../icons'@@ -430,6 +435,7 @@ export function FileExplorerTree({pushToast,}: FileExplorerTreeProps) {const ctrl = useGfsBrowserController()+ const queryClient = useQueryClient()const dragSession = useGfsDragSession()const adjudication = useGfsDragAdjudication({scope: ctrl.sessionScope,@@ -493,6 +499,24 @@ export function FileExplorerTree({const roots = useMemo(() => sortTreeItems(ctrl.accessibleResources), [ctrl.accessibleResources])+ /** Cached destination names for the numbered-name ladder and suggestion —+ * the same shared children cache the Files page seeds its commit from. */+ const cachedDestinationNames = useCallback(+ (destinationId: string): Set<string> => {+ const cached = queryClient.getQueryData<{ pages?: Array<{ items?: GfsBrowserChild[] }> }>(+ desktopQueryKeys.gfsChildren(+ ctrl.sessionScope ?? 'anonymous',+ destinationId,+ GFS_DRIVE_MAIN+ )+ )+ return new Set(+ (cached?.pages ?? []).flatMap(page => page.items?.map(item => item.name) ?? [])+ )+ },+ [ctrl.sessionScope, queryClient]+ )+const handleToggle = useCallback((resourceId: string) => {setExpandedIds(previous => {const next = new Set(previous)@@ -715,6 +739,7 @@ export function FileExplorerTree({},destination,allowNumberedRename,+ occupiedDestinationNames: cachedDestinationNames(destination.resourceId),})toastMoveOutcome(pushToast, outcome, source.name, destination.name, source.kind)@@ -724,7 +749,7 @@ export function FileExplorerTree({setMovingResourceId(null)}},- [ctrl, pushToast]+ [cachedDestinationNames, ctrl, pushToast])const handleNodeDrop = useCallback(@@ -755,12 +780,15 @@ export function FileExplorerTree({return}if (source.kind === 'directory') {+ const occupied = cachedDestinationNames(node.resourceId)+ const suggested = suggestNumberedMoveName(source.name, occupied)setPendingFolderMove({source,gestureGeneration: epoch,sessionGeneration,destination: { resourceId: node.resourceId, name: node.name },allowNumberedRename: decision.allowNumberedRename,+ ...(suggested !== undefined ? { suggestedName: suggested } : {}),})return}@@ -775,6 +803,7 @@ export function FileExplorerTree({},[adjudication,+ cachedDestinationNames,finishNodeDropCleanup,commitMove,dragSession,diff --git a/desktop-app/ui/src/gfs/__tests__/moveCommit.test.ts b/desktop-app/ui/src/gfs/__tests__/moveCommit.test.tsindex 481c028dc..e3efb288d 100644--- a/desktop-app/ui/src/gfs/__tests__/moveCommit.test.ts+++ b/desktop-app/ui/src/gfs/__tests__/moveCommit.test.ts@@ -102,16 +102,47 @@ describe('commitGfsMove — conflict policy (rev-2 §5)', () => {})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 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('seeds the ladder from plan.occupiedDestinationNames so known-taken names are skipped', async () => {+ // RP-003: with the destination already holding report.md, report (1).md+ // and report (2).md, a blind ladder burns all three attempts on taken+ // names. Seeded from the plan, the first 409 jumps straight past them.+ const moveResource = vi+ .fn()+ .mockImplementation(async (_id: string, _dest: string, _v: number, newName?: string) => {+ if (+ newName === undefined ||+ newName === 'report.md' ||+ newName === 'report (1).md' ||+ newName === 'report (2).md'+ ) {+ throw conflictError()+ }+ return { resourceId: 'r-1', version: 10 }+ })+ const outcome = await commitGfsMove(+ deps({ moveResource }),+ plan({+ allowNumberedRename: true,+ occupiedDestinationNames: new Set(['report.md', 'report (1).md', 'report (2).md']),+ })+ )+ expect(outcome).toEqual({ status: 'committed', version: 10, renamedTo: 'report (3).md' })+ expect(moveResource).toHaveBeenCalledTimes(2)+ expect(moveResource).toHaveBeenLastCalledWith('r-1', 'dest-1', 7, 'report (3).md')+ })+it('a concurrent-name storm stops after the attempt cap with the destination-changed copy', async () => {const moveResource = vi.fn(async () => {throw conflictError()@@ -191,8 +222,8 @@ 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')+ expect(suggestNumberedMoveName('report.md', new Set(['report.md', 'report (1).md']))).toBe(+ 'report (2).md'+ )})})