diff --git a/src/client/FileTree.tsx b/src/client/FileTree.tsx index 7150a7ba..281d9542 100644 --- a/src/client/FileTree.tsx +++ b/src/client/FileTree.tsx @@ -1006,10 +1006,12 @@ export function FileTree(props: { setNewFolder(null) setConfirmDelete(null) setConfirmDeleteSelected(false) - // A batch walk of the PREVIOUS session may still be in flight (it carries - // its own scope, so it stays safe) — but its flag must not lock the new - // session's bar if that walk died without settling. + // A batch walk of the PREVIOUS session may still be in flight. Its + // removals carry their own scope, so they stay correct — but the walk must + // not settle over THIS session (see batchGenRef), and its flag must not + // lock the new session's bar either. setDeletingSelected(false) + batchGenRef.current += 1 setActionError(null) setLoadError(null) pendingUploadDir.current = undefined @@ -1134,6 +1136,14 @@ export function FileTree(props: { } // ── Batch delete ─────────────────────────────────────────────────────── + /** + * Bumped by a session/cwd swap. The walk below carries its OWN scope, so the + * removals it issues stay correct — but everything it SETTLES (pruneTree, the + * error strip, the selection, the busy flag) is state of the project on + * screen, which may no longer be the one it started in. A walk whose + * generation is stale goes quiet instead. + */ + const batchGenRef = useRef(0) /** * Delete every selected row, ONE AT A TIME (the host refuses nothing here, * but a partial batch must be debuggable). The first failure stops the walk @@ -1146,6 +1156,7 @@ export function FileTree(props: { setConfirmDeleteSelected(false) if (paths.length === 0) return const scope = { sessionId: live.sessionId, cwd: live.cwd } + const generation = batchGenRef.current setDeletingSelected(true) void (async () => { const removed: string[] = [] @@ -1153,6 +1164,7 @@ export function FileTree(props: { try { await api.fsRemove(scope, path) } catch (error: unknown) { + if (generation !== batchGenRef.current) return setActionError(error instanceof Error ? error.message : String(error)) // Keep the rows that were NOT removed selected, so a retry is one click. const next = new Set(selectedRef.current) @@ -1161,11 +1173,16 @@ export function FileTree(props: { setDeletingSelected(false) return } + // The reader moved on mid-walk: drop the rest of the batch rather than + // settle it into the project that took over. The swap already released + // the busy flag, so nothing here needs to. + if (generation !== batchGenRef.current) return setActionError(null) pruneTree(path) live.onPathDeleted?.(path, kindRef.current.get(path) ?? false) removed.push(path) } + if (generation !== batchGenRef.current) return setDeletingSelected(false) clearSelection() })() diff --git a/tests/file-tree-session-scope.spec.tsx b/tests/file-tree-session-scope.spec.tsx index 39c7e982..b94e3b0a 100644 --- a/tests/file-tree-session-scope.spec.tsx +++ b/tests/file-tree-session-scope.spec.tsx @@ -92,6 +92,13 @@ function selectionBar(): HTMLElement | null { return container.querySelector('[class*="explorerSelectionBar"]') } +function barAction(label: string): HTMLElement { + const button = [...(selectionBar()?.querySelectorAll('button') ?? [])] + .find(el => el.textContent === label) + if (button === undefined) throw new Error(`bar action not found: ${label}`) + return button +} + function openMenu(name: string): void { const event = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 20, clientY: 30 }) act(() => { rowByName(name).dispatchEvent(event) }) @@ -107,7 +114,10 @@ afterEach(() => { act(() => { root.unmount() }) container.remove() document.body.innerHTML = '' - fsRemove.mockClear() + // Reset, not clear: a case that parks a removal on a deferred promise must + // not leak that implementation into the next one. + fsRemove.mockReset() + fsRemove.mockImplementation(async (_scope: unknown, path: string) => ({ path })) }) function mount(): void { @@ -152,4 +162,41 @@ describe('FileTree session scope', () => { expect(document.querySelector('[role="dialog"]')).toBeNull() expect(fsRemove).not.toHaveBeenCalled() }) + + it('stops a batch delete from the previous session from settling into the new one', async () => { + // The walk carries its own scope, so its removals stay correct — but it + // must not settle (pruneTree / the selection / the busy flag) into whatever + // project has taken over the instance since. + let release!: () => void + const held = new Promise<{ path: string }>((resolve) => { + release = () => { resolve({ path: '/projects/alpha/a.ts' }) } + }) + fsRemove.mockImplementationOnce(async () => held) + + await render('s1', '/projects/alpha') + click(rowByName('a.ts'), { ctrlKey: true }) + click(rowByName('b.ts'), { ctrlKey: true }) + act(() => { barAction('Delete selected').click() }) + const confirm = [...document.querySelectorAll('button')] + .find(el => el.textContent === 'Delete selected' && el.closest('[role="dialog"]') !== null) + if (confirm === undefined) throw new Error('confirm button not found') + act(() => { confirm.click() }) // the first removal is now in flight + // …and it is parked there: one removal issued, the second row untouched. + expect(fsRemove.mock.calls).toHaveLength(1) + + // Another session takes over the same mounted instance, and the reader + // makes a fresh selection there. + await render('s2', '/projects/beta') + click(rowByName('a.ts'), { ctrlKey: true }) + expect(selectionBar()?.textContent).toContain('1 selected') + + // The previous walk resumes. It must go quiet, not clear THIS selection. + await act(async () => { release() }) + // The walk's tail is a plain microtask chain, outside act's tracking: give + // it (and React's flush of whatever it wrote) a beat to land. + await act(async () => { await new Promise(resolve => { setTimeout(resolve, 0) }) }) + expect(selectionBar()?.textContent).toContain('1 selected') + // …and the stale walk stopped instead of removing the rest of its batch. + expect(fsRemove.mock.calls).toHaveLength(1) + }) })