From 44d9e7f408e8d8dabbb9335e65079bad35a18515 Mon Sep 17 00:00:00 2001 From: unsc9 <438590997@qq.com> Date: Mon, 5 Oct 2026 10:41:28 +0800 Subject: [PATCH] =?UTF-8?q?fix(files):=20=E6=89=B9=E9=87=8F=E5=88=A0?= =?UTF-8?q?=E9=99=A4=E8=B5=B0=E5=88=B0=E4=B8=80=E5=8D=8A=E6=8D=A2=E4=BA=86?= =?UTF-8?q?=E4=BC=9A=E8=AF=9D=E5=B0=B1=E5=81=9C=E4=B8=8B=E6=9D=A5=EF=BC=8C?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E6=94=B6=E6=8B=BE=E4=B8=8A=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E9=A1=B9=E7=9B=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 切换会话时把「正在删除」标志归零了(原问题是新项目里删除按钮被卡住),但上一批的 循环还在跑:用户可以立刻在新项目发起第二批,两批重叠,而旧循环收尾时的 pruneTree 与 clearSelection 会把新项目刚选中的行清掉。 加一个代际计数(跟读目录那条用的是同一套做法):切换时递增,循环每次 await 回来先确认 自己没过期 —— 过期就整批放弃,既不接着删、也不再往界面上写。删除调用本身带着自己的 scope,所以停在哪里都是安全的。 守护用例:file-tree-session-scope 新增一条,用延迟 promise 把第一次删除停住,切成新会话 并在新会话里选中一行,再放行旧循环 —— 去掉修复后实测新会话的选择会被清掉。另把该 spec 的 afterEach 由 mockClear 换成 mockReset,免得挂起的实现漏给下一个用例。 --- src/client/FileTree.tsx | 23 ++++++++++-- tests/file-tree-session-scope.spec.tsx | 49 +++++++++++++++++++++++++- 2 files changed, 68 insertions(+), 4 deletions(-) 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) + }) })