fix(files): 批量删除走到一半换了会话就停下来,不再收拾上一个项目

切换会话时把「正在删除」标志归零了(原问题是新项目里删除按钮被卡住),但上一批的
循环还在跑:用户可以立刻在新项目发起第二批,两批重叠,而旧循环收尾时的 pruneTree 与
clearSelection 会把新项目刚选中的行清掉。

加一个代际计数(跟读目录那条用的是同一套做法):切换时递增,循环每次 await 回来先确认
自己没过期 —— 过期就整批放弃,既不接着删、也不再往界面上写。删除调用本身带着自己的
scope,所以停在哪里都是安全的。

守护用例:file-tree-session-scope 新增一条,用延迟 promise 把第一次删除停住,切成新会话
并在新会话里选中一行,再放行旧循环 —— 去掉修复后实测新会话的选择会被清掉。另把该 spec
的 afterEach 由 mockClear 换成 mockReset,免得挂起的实现漏给下一个用例。
This commit is contained in:
unsc9 committed 2026-10-05 11:31:54 +08:00
1 parent 018cffec35
commit 44d9e7f408
2 files changed
+68 -4

No files matched your search

+20 -3
View File
@@ -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()
})()
+48 -1
View File
@@ -92,6 +92,13 @@ function selectionBar(): HTMLElement | null {
return container.querySelector<HTMLElement>('[class*="explorerSelectionBar"]')
}
function barAction(label: string): HTMLElement {
const button = [...(selectionBar()?.querySelectorAll<HTMLElement>('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<HTMLElement>('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)
})
})