fix(safety): 会话切换不再把上一项目的删除动作带进新项目

工作台每个 tab 一个常驻组件实例(tab id 按会话重新计数),会话/cwd 切换只换
props 不重挂,于是「指向某一行」的危险状态跨会话存活,执行时却用新会话的 scope:

- 文件树:选中集不清 → 批量删除用新 scope + 旧会话绝对路径(宿主按原样执行,
  工作区包含检查已刻意移除)→ 删掉别的项目的文件。现在切换即清空全部 path 型
  状态、批删进行标志与在轮询的打包任务。
- 变更页:右键菜单与待确认的「放弃更改 / 还原 / 拣选」不清 → onConfirm 闭包带
  旧行路径,而 gitScopeNow() 已在点击时读到新 scope → 在新项目里丢未提交改动。
- 任务窗口:两步删除的 armed 状态不清 → 切任务后第一次点击就是删除。

同时修掉工作区根守卫:原来比较两个字符串,同一目录的大小写变体、\\?\ 前缀、
8.3 短名、映射盘都能绕过,rm -r 真的递归删光整个项目。改为按 dev+ino 比较身份
(stat 跟随链接,指向根的链接也拒绝;拿不到 inode 或 stat 失败时退回归一化拼写)。

守护用例:file-tree-session-scope / task-window-delete-arm / GitLens scope swap
三条在未修复代码上均精确变红;fs-operations 增补 Windows 拼写变体与 symlink→根。
This commit is contained in:
unsc9 committed 2026-10-05 11:31:54 +08:00
1 parent d51a46075d
commit 74461c9954
8 files changed
+531 -6

No files matched your search

+40
View File
@@ -980,6 +980,38 @@ export function FileTree(props: {
setSelection(new Set())
}, [setSelection])
/**
* A session/cwd swap REUSES this component: the workbench keeps one mounted
* instance per tab id, and tab ids restart per session. Every path-shaped
* piece of state here therefore outlives the project it was picked in — and
* the selection is the dangerous one, because "delete selected" sends THIS
* session's scope with the PREVIOUS session's absolute paths, which the host
* applies verbatim (containment was removed on purpose): it deleted another
* project's files. The rest is the same leak in harmless clothing — a menu,
* an inline editor, an armed confirmation aimed at a row that is no longer
* on screen.
*/
useEffect(() => {
setSelection(new Set())
kindRef.current.clear()
anchorRef.current = null
setRowMenu(null)
setApps(null)
setCopiedPath(null)
setRenaming(null)
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.
setDeletingSelected(false)
setActionError(null)
setLoadError(null)
pendingUploadDir.current = undefined
resetDrop()
}, [sessionId, cwd, resetDrop, setSelection])
const copySelectedPaths = useCallback((): void => {
void writeClipboard([...selectedRef.current].join('\n'))
}, [])
@@ -1446,6 +1478,14 @@ export function FileTree(props: {
setArchiveProgress(null)
}, [])
// A session/cwd swap abandons the archive job with it: the poller would keep
// asking with the NEW scope for the PREVIOUS session's job (the host refuses
// that), and the strip would report a zip failure in a project that never
// asked for one.
useEffect(() => {
settleArchive()
}, [sessionId, cwd, settleArchive])
const failArchive = useCallback((message: string): void => {
setActionError(t('zipFailed', { message }))
settleArchive()
+4
View File
@@ -248,6 +248,10 @@ export function TaskWindow(props: TaskWindowProps): ReactNode {
setDescription(seed.description)
setSubjectTouched(false)
setEditing(seed.creating)
// An armed "confirm delete" is the first half of a two-step aimed at THIS
// task. Carried into the next one it makes that reader's first click the
// delete itself.
setArmedDelete(false)
}, [task?.id])
const teammates = members.filter(member => member.role === 'teammate')
+9
View File
@@ -520,6 +520,15 @@ export function GitLens(props: GitLensProps) {
setRepoChoices([])
clearDerived()
setViewError(null)
// The three destructive entry points are aimed at a ROW of the previous
// scope: the menus carry that row's path and `confirmPending` executes a
// closure over it, while `gitScopeNow()` already reads the NEW scope — so
// a discard/revert/cherry-pick confirmed here would land in the project
// that took over the pane (same class as the file tree's cross-session
// delete).
setFileMenu(null)
setHistoryMenu(null)
setConfirm(null)
if (visible) void refresh(false)
// Granular scope fields: the refresh identity is stable, only a real
// session/cwd change restarts the chain.
+43 -6
View File
@@ -130,10 +130,47 @@ export interface WorkspaceRenameInput {
async function resolveEntry(
cwd: string,
target: string,
): Promise<{ absolute: string; real: string; realCwd: string }> {
): Promise<{ absolute: string; realCwd: string }> {
const absolute = resolveTarget(cwd, target)
const realCwd = requireAbsolute(cwd)
return { absolute, real: absolute, realCwd }
return { absolute, realCwd }
}
/**
* Whether `target` IS the workspace root. Comparing the two SPELLINGS is not
* enough: the resolution above is deliberately lexical (a symlink row must
* keep addressing the LINK, not its target), and one directory has many
* spellings — a case variant, a `\\?\` prefix, an 8.3 short name, a mapped
* drive. Each of them walked straight past this guard and turned "delete this
* row" into a recursive delete of the whole project. `dev`+`ino` is the
* identity the filesystem itself uses, and it does not care how the path is
* spelled. `stat` (not `lstat`) is deliberate: a symlink aimed AT the root is
* refused too — no link is worth the project behind it. A target that cannot
* be stat'ed (it may legitimately be gone) falls back to the spelling.
*/
/**
* Compare two spellings the way Windows itself does: the extended-length
* prefix is not part of the name and case is free. Only reached when the
* volume cannot answer with an inode (FAT/exFAT, some network shares) — weaker
* than an identity, but never weaker than the plain string compare it
* replaced.
*/
function sameSpelling(a: string, b: string): boolean {
const strip = (value: string): string => value.replace(/^\\\\\?\\/, '')
const left = strip(a)
const right = strip(b)
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right
}
async function isWorkspaceRoot(target: string, root: string): Promise<boolean> {
try {
const [entry, base] = await Promise.all([stat(target), stat(root)])
// No inode = no identity: fall back to the spelling.
if (entry.ino === 0 || base.ino === 0) return sameSpelling(target, root)
return entry.dev === base.dev && entry.ino === base.ino
} catch {
return sameSpelling(target, root)
}
}
/** Whether a path exists (ENOENT → false; other failures propagate). */
@@ -163,8 +200,8 @@ export async function renameWorkspaceEntry(input: WorkspaceRenameInput): Promise
if (name === '' || name === '.' || name === '..' || name.includes('/') || name.includes('\\')) {
throw new SidebarError('bad-request', 'name must be a single path segment', 400)
}
const { absolute, real, realCwd } = await resolveEntry(cwd, path)
if (real === realCwd) {
const { absolute, realCwd } = await resolveEntry(cwd, path)
if (await isWorkspaceRoot(absolute, realCwd)) {
throw new SidebarError('fs-error', 'cannot rename the workspace root', 400)
}
if (basename(absolute) === name) return { path: absolute }
@@ -243,8 +280,8 @@ export interface WorkspaceRemoveInput {
*/
export async function removeWorkspaceEntry(input: WorkspaceRemoveInput): Promise<{ path: string }> {
const { cwd, path } = input
const { absolute, real, realCwd } = await resolveEntry(cwd, path)
if (real === realCwd) {
const { absolute, realCwd } = await resolveEntry(cwd, path)
if (await isWorkspaceRoot(absolute, realCwd)) {
throw new SidebarError('fs-error', 'cannot remove the workspace root', 400)
}
try {
+156
View File
@@ -0,0 +1,156 @@
/**
* FileTree session scope: the workbench keeps ONE mounted tree instance per
* tab id, and tab ids restart per session, so a session (or cwd) swap
* re-renders this component in place instead of mounting a fresh one. Nothing
* picked in the previous project may survive that swap — a leftover selection
* made "delete selected" send the NEW session's scope with the OLD project's
* absolute paths, and the host applies those verbatim (containment was removed
* on purpose): it deleted another project's files. Confirmations and inline
* editors aimed at a row that is no longer on screen are the same leak.
*
* What must NOT change: an ordinary re-render of the SAME session keeps every
* bit of that state (the workbench relies on the instance staying alive).
*/
// @vitest-environment jsdom
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { FileTree } from '../src/client/FileTree.tsx'
import { setupReactAct } from './test-utils.ts'
setupReactAct()
// vitest follows the OS locale; pin en-US so the copy asserted below is English.
beforeAll(() => {
Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true })
})
const { fsRemove, fsTrees } = vi.hoisted(() => ({
fsRemove: vi.fn(async (_scope: unknown, path: string) => ({ path })),
// Every requested level answers with the same two rows under THAT level's
// path, so each row's absolute path names the project it belongs to.
fsTrees: vi.fn(async (_scope: unknown, paths: readonly string[]) => ({
levels: paths.map(path => ({
path,
entries: [
{ name: 'a.ts', path: `${path}/a.ts`, isDir: false },
{ name: 'b.ts', path: `${path}/b.ts`, isDir: false },
],
truncated: false,
})),
})),
}))
vi.mock('../src/client/api.ts', () => ({
api: {
fsTrees,
fsRemove,
// The tree reads the shared git-status store; a non-repo answer keeps every
// row plain (this spec is about state ownership).
gitStatus: async () => ({ isRepo: false, entries: [] }),
},
downloadUrl: () => '/sidebar/file',
isOutsideWorkspaceMessage: () => false,
}))
let container: HTMLDivElement
let root: Root
/** Render — or RE-render in place — the one mounted tree, exactly as the
* workbench's reused tab instance does on a session swap. */
async function render(sessionId: string, cwd: string): Promise<void> {
await act(async () => {
root.render(createElement(FileTree, {
sessionId,
cwd,
expanded: [],
revealed: [],
onToggle: () => {},
onOpenFile: () => {},
onReferenceFile: () => {},
refreshTick: 0,
onUploadRequest: () => {},
busy: false,
}))
})
}
function click(el: Element, init: MouseEventInit = {}): void {
act(() => { el.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, ...init })) })
}
function rowByName(name: string): HTMLElement {
const row = [...container.querySelectorAll<HTMLElement>('[role="button"]')]
.find(el => el.querySelector('[class*="explorerName"]')?.textContent === name)
if (row === undefined) throw new Error(`row not found: ${name}`)
return row
}
/** The batch bar (the kit's section band carries the page class). */
function selectionBar(): HTMLElement | null {
return container.querySelector<HTMLElement>('[class*="explorerSelectionBar"]')
}
function openMenu(name: string): void {
const event = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 20, clientY: 30 })
act(() => { rowByName(name).dispatchEvent(event) })
}
function clickMenuitem(label: string): void {
const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(el => el.textContent === label)
if (item === undefined) throw new Error(`menuitem "${label}" not found`)
act(() => { item.click() })
}
afterEach(() => {
act(() => { root.unmount() })
container.remove()
document.body.innerHTML = ''
fsRemove.mockClear()
})
function mount(): void {
container = document.createElement('div')
document.body.append(container)
root = createRoot(container)
}
describe('FileTree session scope', () => {
it('drops the previous project\'s selection instead of deleting its files', async () => {
mount()
await render('s1', '/projects/alpha')
click(rowByName('a.ts'), { ctrlKey: true })
expect(selectionBar()?.textContent).toContain('1 selected')
// The same mounted instance, now showing session B's project.
await render('s2', '/projects/beta')
expect(selectionBar()).toBeNull()
expect(fsRemove).not.toHaveBeenCalled()
})
it('keeps the selection when the SAME session re-renders', async () => {
mount()
await render('s1', '/projects/alpha')
click(rowByName('a.ts'), { ctrlKey: true })
// A refresh tick, a new store revision, a parent re-render: still s1.
await render('s1', '/projects/alpha')
expect(selectionBar()?.textContent).toContain('1 selected')
})
it('closes a delete confirmation opened in the previous session', async () => {
mount()
await render('s1', '/projects/alpha')
openMenu('a.ts')
clickMenuitem('Delete')
expect(document.querySelector('[role="dialog"]')).not.toBeNull()
await render('s2', '/projects/beta')
expect(document.querySelector('[role="dialog"]')).toBeNull()
expect(fsRemove).not.toHaveBeenCalled()
})
})
+91
View File
@@ -261,6 +261,24 @@ describe('removeWorkspaceEntry', () => {
await expect(removeWorkspaceEntry({ cwd: root, path: join(root, 'no-such.txt') }))
.rejects.toMatchObject({ code: 'fs-error' })
})
it.runIf(canSymlink)('refuses a symlink aimed AT the root', async () => {
// The guard resolves the target's identity on purpose: this link stands
// for the project itself, so it is refused instead of unlinked.
const ws = mkdtempSync(join(tmpdir(), 'dsh-sidebar-rootlink-'))
const inner = join(ws, 'Proj')
mkdirSync(join(inner, 'src'), { recursive: true })
writeFileSync(join(inner, 'src', 'keep.ts'), 'x')
symlinkSync(inner, join(ws, 'link-to-proj'))
try {
await expect(removeWorkspaceEntry({ cwd: inner, path: join(ws, 'link-to-proj') }))
.rejects.toMatchObject({ code: 'fs-error' })
expect(existsSync(join(inner, 'src', 'keep.ts'))).toBe(true)
expect(existsSync(join(ws, 'link-to-proj'))).toBe(true)
} finally {
rmSync(ws, { recursive: true, force: true })
}
})
})
describe('session-relative targets (the shared resolution contract, #646)', () => {
@@ -318,3 +336,76 @@ describe('session-relative targets (the shared resolution contract, #646)', () =
}
})
})
/**
* One directory has many SPELLINGS — a case variant, a `\\?\` prefix, an 8.3
* short name, a mapped drive. The root guard compared the two strings, so any
* of them walked past it and "delete this row" became a recursive delete of
* the whole project. The guard compares what the filesystem itself compares
* (`dev`+`ino`), which does not care how a path is spelled.
*
* Windows-only: on Linux the variant is a different directory, not a spelling
* of this one, and a case variant of a real path does not exist.
*/
describe.runIf(process.platform === 'win32')('workspace-root guard across path spellings', () => {
/** A project directory whose name carries letters, so a lowercase variant is
* a real spelling of the same directory. */
function makeProject(): { ws: string; inner: string } {
const ws = mkdtempSync(join(tmpdir(), 'dsh-sidebar-root-'))
const inner = join(ws, 'ProjDir')
mkdirSync(join(inner, 'src'), { recursive: true })
writeFileSync(join(inner, 'src', 'keep.ts'), 'x')
return { ws, inner }
}
it('refuses a case variant of the root', async () => {
const { ws, inner } = makeProject()
try {
const variant = inner.toLowerCase()
// `ProjDir` carries capitals, so the lowercase spelling always differs —
// this does not depend on how the temp directory itself is spelled.
expect(variant).not.toBe(inner)
await expect(removeWorkspaceEntry({ cwd: inner, path: variant }))
.rejects.toMatchObject({ code: 'fs-error' })
expect(existsSync(join(inner, 'src', 'keep.ts'))).toBe(true)
} finally {
rmSync(ws, { recursive: true, force: true })
}
})
it('refuses the extended-length spelling of the root', async () => {
const { ws, inner } = makeProject()
try {
await expect(removeWorkspaceEntry({ cwd: inner, path: `\\\\?\\${inner}` }))
.rejects.toMatchObject({ code: 'fs-error' })
expect(existsSync(join(inner, 'src', 'keep.ts'))).toBe(true)
} finally {
rmSync(ws, { recursive: true, force: true })
}
})
it('refuses a case variant for rename too', async () => {
const { ws, inner } = makeProject()
try {
await expect(renameWorkspaceEntry({ cwd: inner, path: inner.toLowerCase(), name: 'moved' }))
.rejects.toMatchObject({ code: 'fs-error' })
expect(existsSync(join(inner, 'src', 'keep.ts'))).toBe(true)
} finally {
rmSync(ws, { recursive: true, force: true })
}
})
it('still removes a SUBdirectory reached through a spelled-out path', async () => {
const { ws, inner } = makeProject()
try {
mkdirSync(join(inner, 'Sub'))
// A spelled-out path that is NOT the root passes the guard — and unlike a
// case variant this holds on a case-SENSITIVE volume too.
await removeWorkspaceEntry({ cwd: inner, path: `\\\\?\\${join(inner, 'Sub')}` })
expect(existsSync(join(inner, 'Sub'))).toBe(false)
expect(existsSync(inner)).toBe(true)
} finally {
rmSync(ws, { recursive: true, force: true })
}
})
})
+52
View File
@@ -685,3 +685,55 @@ describe('GitLens (changes tab, git lens) change tree', () => {
}
})
})
/**
* The lens lives in a REUSED tab instance (the workbench keeps one mounted
* component per tab id and swaps `scope`), so a destructive confirmation armed
* for a row of the previous project must not survive the swap: its `onConfirm`
* closure carries that row's path while `gitScopeNow()` already reads the new
* scope — the discard would land in the project that took over the pane.
*/
describe('GitLens (changes tab, git lens) scope swap', () => {
it('drops a pending discard confirmation when the scope changes', async () => {
// One primary checkout, so the view stays on MAIN's changed row.
const onlyMain: GitWorktree[] = [{ path: MAIN, branch: 'main', current: true, changes: 1 }]
vi.spyOn(api, 'gitWorktrees').mockResolvedValue(onlyMain)
vi.spyOn(api, 'gitStatus').mockImplementation(async (_scope, target) => statusFor(target))
vi.spyOn(api, 'gitBranch').mockImplementation(async (_scope, target) => ({
current: target === AGENT ? 'agent' : 'main',
names: target === AGENT ? ['agent'] : ['main'],
}))
vi.spyOn(api, 'gitLog').mockImplementation(async (_scope, _count, _skip, target) => logFor(target))
const discard = vi.spyOn(api, 'gitDiscard')
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
try {
mountGit(root, { scope: { sessionId: 's1', cwd: MAIN } })
await flushEffects()
const row = container.querySelector<HTMLElement>('[data-path="main-change.ts"]')
if (row === null) throw new Error('changed row not found')
act(() => {
row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 20, clientY: 30 }))
})
const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')]
.find(el => el.textContent === t('discard'))
if (item === undefined) throw new Error('discard menu item not found')
act(() => { item.click() })
expect(document.querySelector('[role="dialog"]')).not.toBeNull()
// Another session takes over the same mounted instance.
mountGit(root, { scope: { sessionId: 's2', cwd: AGENT } })
await flushEffects()
expect(document.querySelector('[role="dialog"]')).toBeNull()
expect(discard).not.toHaveBeenCalled()
} finally {
act(() => { root.unmount() })
container.remove()
document.body.innerHTML = ''
}
})
})
+136
View File
@@ -0,0 +1,136 @@
/**
* The task window's delete is a TWO-step button armed in component state: the
* first click arms it ("Confirm delete"), the second one deletes. Every task
* surface swaps the subject task through props with no `key`, so React reuses
* the instance — an armed button carried into the next task made that reader's
* FIRST click the delete itself, one click away from removing a task they
* never armed.
*
* What must NOT change: arming still works, and the second click still goes
* through with the visible task's id.
*/
// @vitest-environment jsdom
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { TaskWindow } from '../src/client/TaskWindow.tsx'
import type { SidebarTeamTaskView } from '../src/context-types.ts'
import { setupReactAct } from './test-utils.ts'
setupReactAct()
// vitest follows the OS locale; pin en-US so the button copy is English.
beforeAll(() => {
Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true })
})
const { teamsTaskUpdate } = vi.hoisted(() => ({
teamsTaskUpdate: vi.fn(async () => ({ ok: true })),
}))
vi.mock('../src/client/api.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/client/api.ts')>()
return { ...actual, api: { ...actual.api, teamsTaskUpdate } }
})
/** One board row as the projection hands it over. */
function taskView(id: string, subject: string): SidebarTeamTaskView {
return {
id,
revision: 1,
subject,
description: 'body',
status: 'in_progress',
blockedBy: [],
writeScopes: [],
ready: true,
writeScopeWarnings: [],
}
}
let container: HTMLDivElement
let root: Root
/** Render — or RE-render in place — the one window, as the caller's popover
* state does when another task is opened. */
async function render(task: SidebarTeamTaskView): Promise<void> {
await act(async () => {
root.render(createElement(TaskWindow, {
rootId: 'root-1',
task,
members: [],
onClose: () => {},
}))
})
}
/** One footer button by its copy (the window is body-portaled). */
function button(label: string): HTMLElement {
const found = [...document.querySelectorAll<HTMLElement>('button')]
.find(el => el.textContent?.trim() === label)
if (found === undefined) throw new Error(`button not found: ${label}`)
return found
}
function hasButton(label: string): boolean {
return [...document.querySelectorAll<HTMLElement>('button')]
.some(el => el.textContent?.trim() === label)
}
afterEach(() => {
act(() => { root.unmount() })
container.remove()
document.body.innerHTML = ''
teamsTaskUpdate.mockClear()
})
describe('TaskWindow two-step delete', () => {
it('disarms the delete when the window swaps to another task', async () => {
container = document.createElement('div')
document.body.append(container)
root = createRoot(container)
await render(taskView('t1', 'First'))
act(() => { button('Delete').click() })
expect(hasButton('Confirm delete')).toBe(true)
expect(hasButton('Delete')).toBe(false)
expect(teamsTaskUpdate).not.toHaveBeenCalled()
// Another task opened in the same instance (no key on the caller's side).
await render(taskView('t2', 'Second'))
expect(hasButton('Delete')).toBe(true)
expect(hasButton('Confirm delete')).toBe(false)
})
it('makes the first click on the next task an arm, never the delete', async () => {
container = document.createElement('div')
document.body.append(container)
root = createRoot(container)
await render(taskView('t1', 'First'))
act(() => { button('Delete').click() }) // armed on t1
await render(taskView('t2', 'Second'))
await act(async () => { button('Delete').click() }) // first click on t2
expect(teamsTaskUpdate).not.toHaveBeenCalled()
expect(hasButton('Confirm delete')).toBe(true)
})
it('still deletes the visible task on the second click', async () => {
container = document.createElement('div')
document.body.append(container)
root = createRoot(container)
await render(taskView('t9', 'Only'))
act(() => { button('Delete').click() })
await act(async () => { button('Confirm delete').click() })
expect(teamsTaskUpdate).toHaveBeenCalledWith('root-1', {
taskId: 't9',
expectedRevision: 1,
action: 'delete',
})
})
})