verifier 二轮报告(F1–F9)全部修复,每条都有「临时回退即变红」的判别性验证: - F1【高】中文等非 latin1 下载名 → 真实宿主 500:content-disposition 改用 RFC 5987(ASCII 回退 + filename*=UTF-8'');补真 node:http 用例与根因对照断言 - F2【中】多选同名文件归档重名(解压互相覆盖):冲突项逐级上溯父目录消歧 - F3【中低】maxBytes 在读完之后才判定;budget<=0 的 0 字节 FIFO 会永久阻塞: 改为先 stat、读取前拒绝(FIFO 探针验证) - F4【中低】SSH 模式 + 宿主不可用时 reveal 整条消失:保留 kind==='reveal' 目标 - F5【低】图钉嵌套交互语义非法且键盘不可达:改为诚实的鼠标热区,键盘入口归设置面板 - F6【低】变更树空闲 tick 全量重渲染:行 memo + 恒定 props + 内容键派生 + 共享 store 的 sameStatus 保住快照身份 - F7【低】排序随运行时 locale 漂移:显式 'en' collation + 码点兜底 - F8【低】POSIX 文件名的反斜杠被当成层级:不再替换 - F9【低】打包中重复点击静默、无反馈:busy 行(role=status)+ in-flight 守卫 - 新增:目录行「暂存/取消暂存该目录」(git pathspec 语义,不触发折叠) 验证:typecheck / lint / test(134 文件 1441 通过)/ build 全绿; DSH_CMD='npx -y --package @deepseek-ai/dsh@0.1.7-rc.1 dsh' pnpm test:mount 7/7 通过
358 lines
14 KiB
TypeScript
358 lines
14 KiB
TypeScript
/**
|
|
* FileTree "zip and download": the context menu offers an archive row for a
|
|
* multi-selection (≥2 rows) and for a LONE directory (a lone file is skipped —
|
|
* the plain download row already covers it).
|
|
*
|
|
* The row is NOT a bare anchor any more: the bytes are fetched through
|
|
* `archiveUrl(scope, paths, name)`, because the archive route reports its caps
|
|
* and refusals as the plugin's JSON error envelope — an anchor would save that
|
|
* envelope as a broken `.zip`. So these cases pin:
|
|
* - the URL parameters (scope / paths / name) and the appearance gates;
|
|
* - success: the response body becomes an object URL, saved through a hidden
|
|
* `<a download={name}>`, revoked on the next task;
|
|
* - failure: a non-2xx JSON envelope (`{error:{message}}`), a non-JSON body
|
|
* (`HTTP <status>`) and a network rejection all land in the error strip
|
|
* with the `zipFailed` copy;
|
|
* - a click while one request is in flight does not package twice.
|
|
*/
|
|
// @vitest-environment jsdom
|
|
import { afterEach, beforeAll, beforeEach, 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 { createSidebarStore } from '../src/client/state.ts'
|
|
|
|
import { setupReactAct } from './test-utils.ts'
|
|
setupReactAct()
|
|
|
|
// vitest 4.1.11+ follows the OS locale; pin en-US so menu copy is English.
|
|
beforeAll(() => {
|
|
Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true })
|
|
})
|
|
|
|
const { archiveUrl, fetchMock } = vi.hoisted(() => ({
|
|
archiveUrl: vi.fn((_scope: unknown, _paths: readonly string[], name: string) => `/sidebar/archive?name=${encodeURIComponent(name)}`),
|
|
fetchMock: vi.fn(),
|
|
}))
|
|
|
|
vi.mock('../src/client/api.ts', () => ({
|
|
api: {
|
|
fsTree: async () => ({
|
|
path: '/tmp',
|
|
entries: [
|
|
{ name: 'sub', path: '/tmp/sub', isDir: true },
|
|
{ name: 'a.ts', path: '/tmp/a.ts', isDir: false },
|
|
{ name: 'b.ts', path: '/tmp/b.ts', isDir: false },
|
|
],
|
|
truncated: false,
|
|
}),
|
|
// The tree reads the shared git-status store; a non-repo answer keeps
|
|
// every row plain (this spec is about the archive row).
|
|
gitStatus: async () => ({ isRepo: false, entries: [] }),
|
|
},
|
|
downloadUrl: () => '/sidebar/file',
|
|
archiveUrl,
|
|
isOutsideWorkspaceMessage: () => false,
|
|
}))
|
|
|
|
/** jsdom implements neither object-URL helper; these ARE the download probe. */
|
|
const createdUrls: Blob[] = []
|
|
const revokedUrls: string[] = []
|
|
beforeAll(() => {
|
|
Object.defineProperty(URL, 'createObjectURL', {
|
|
configurable: true,
|
|
writable: true,
|
|
value: (blob: Blob) => {
|
|
createdUrls.push(blob)
|
|
return `blob:mock-${createdUrls.length}`
|
|
},
|
|
})
|
|
Object.defineProperty(URL, 'revokeObjectURL', {
|
|
configurable: true,
|
|
writable: true,
|
|
value: (url: string) => { revokedUrls.push(url) },
|
|
})
|
|
})
|
|
|
|
interface Harness {
|
|
container: HTMLDivElement
|
|
unmount: () => void
|
|
}
|
|
|
|
async function mountTree(): Promise<Harness> {
|
|
const container = document.createElement('div')
|
|
document.body.append(container)
|
|
const root: Root = createRoot(container)
|
|
await act(async () => {
|
|
root.render(createElement(FileTree, {
|
|
sessionId: 's1',
|
|
cwd: '/tmp',
|
|
store: createSidebarStore(),
|
|
expanded: [],
|
|
revealed: [],
|
|
onToggle: () => {},
|
|
onOpenFile: () => {},
|
|
onReferenceFile: () => {},
|
|
refreshTick: 0,
|
|
onUploadRequest: () => {},
|
|
busy: false,
|
|
}))
|
|
await Promise.resolve()
|
|
})
|
|
return {
|
|
container,
|
|
unmount: () => { act(() => { root.unmount() }); container.remove() },
|
|
}
|
|
}
|
|
|
|
/** One tree row by its displayed name (the root row included). */
|
|
function rowByName(container: HTMLElement, name: string): HTMLElement {
|
|
const row = [...container.querySelectorAll<HTMLElement>('[class*="explorerRow"]')]
|
|
.find(el => el.querySelector('[class*="explorerName"]')?.textContent === name)
|
|
if (row === undefined) throw new Error(`row not found: ${name}`)
|
|
return row
|
|
}
|
|
|
|
function click(el: Element, init: MouseEventInit = {}): void {
|
|
act(() => { el.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, ...init })) })
|
|
}
|
|
|
|
function rightClick(el: Element): void {
|
|
act(() => {
|
|
el.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 20, clientY: 30 }))
|
|
})
|
|
}
|
|
|
|
function menuLabels(): string[] {
|
|
return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].map(item => item.textContent ?? '')
|
|
}
|
|
|
|
function clickMenuitem(label: string): void {
|
|
const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')]
|
|
.find(el => el.textContent === label)
|
|
if (item === undefined) throw new Error(`menuitem not found: ${label}`)
|
|
act(() => { item.click() })
|
|
}
|
|
|
|
/**
|
|
* Flush the fetch → blob → anchor chain. The chain crosses several async
|
|
* function boundaries (fetch promise → `await response.blob()` → object URL →
|
|
* revoke), so a single microtask/timer pair is not enough on a loaded machine:
|
|
* three macrotask ticks let every hop land, including the revoke `setTimeout`.
|
|
*/
|
|
async function settleDownload(): Promise<void> {
|
|
await act(async () => {
|
|
for (let tick = 0; tick < 3; tick += 1) {
|
|
await Promise.resolve()
|
|
await new Promise<void>(resolve => { window.setTimeout(resolve, 0) })
|
|
}
|
|
})
|
|
}
|
|
|
|
/** A 200 answer carrying ZIP bytes. */
|
|
function okResponse(bytes = 'zip-bytes'): Response {
|
|
return {
|
|
ok: true,
|
|
status: 200,
|
|
blob: async () => new Blob([bytes], { type: 'application/zip' }),
|
|
} as unknown as Response
|
|
}
|
|
|
|
/** A refused answer carrying the plugin's JSON envelope (or a non-JSON body). */
|
|
function errorResponse(status: number, body?: unknown): Response {
|
|
return {
|
|
ok: false,
|
|
status,
|
|
json: async () => {
|
|
if (body === undefined) throw new Error('not json')
|
|
return body
|
|
},
|
|
} as unknown as Response
|
|
}
|
|
|
|
let harness: Harness
|
|
/** The anchors whose click() ran, as `href|download`. */
|
|
const downloads: string[] = []
|
|
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement): void {
|
|
downloads.push(`${this.getAttribute('href') ?? ''}|${this.download}`)
|
|
})
|
|
|
|
beforeEach(() => {
|
|
vi.stubGlobal('fetch', fetchMock)
|
|
fetchMock.mockReset()
|
|
fetchMock.mockResolvedValue(okResponse())
|
|
archiveUrl.mockClear()
|
|
archiveUrl.mockImplementation((_scope: unknown, _paths: readonly string[], name: string) =>
|
|
`/sidebar/archive?name=${encodeURIComponent(name)}`)
|
|
})
|
|
|
|
afterEach(() => {
|
|
harness.unmount()
|
|
document.body.innerHTML = ''
|
|
downloads.length = 0
|
|
createdUrls.length = 0
|
|
revokedUrls.length = 0
|
|
clickSpy.mockClear()
|
|
vi.unstubAllGlobals()
|
|
})
|
|
|
|
describe('FileTree zip and download', () => {
|
|
it('archives a multi-selection through one fetched row', async () => {
|
|
harness = await mountTree()
|
|
click(rowByName(harness.container, 'a.ts'), { ctrlKey: true })
|
|
click(rowByName(harness.container, 'b.ts'), { ctrlKey: true })
|
|
// Right-clicking a row INSIDE the selection keeps the batch.
|
|
rightClick(rowByName(harness.container, 'b.ts'))
|
|
expect(menuLabels()).toContain('Zip and download (2 items)')
|
|
clickMenuitem('Zip and download (2 items)')
|
|
await settleDownload()
|
|
expect(archiveUrl).toHaveBeenCalledWith({ sessionId: 's1', cwd: '/tmp' }, ['/tmp/a.ts', '/tmp/b.ts'], 'archive.zip')
|
|
expect(fetchMock).toHaveBeenCalledWith('/sidebar/archive?name=archive.zip')
|
|
// The body became an object URL saved through a hidden anchor…
|
|
expect(createdUrls).toHaveLength(1)
|
|
expect(downloads).toEqual(['blob:mock-1|archive.zip'])
|
|
// …and the object URL is released on the next task.
|
|
expect(revokedUrls).toEqual(['blob:mock-1'])
|
|
})
|
|
|
|
it('archives a lone directory under its own name', async () => {
|
|
harness = await mountTree()
|
|
rightClick(rowByName(harness.container, 'sub'))
|
|
expect(menuLabels()).toContain('Zip and download')
|
|
clickMenuitem('Zip and download')
|
|
await settleDownload()
|
|
expect(archiveUrl).toHaveBeenCalledWith({ sessionId: 's1', cwd: '/tmp' }, ['/tmp/sub'], 'sub.zip')
|
|
expect(fetchMock).toHaveBeenCalledWith('/sidebar/archive?name=sub.zip')
|
|
expect(downloads).toEqual(['blob:mock-1|sub.zip'])
|
|
})
|
|
|
|
it('archives the workspace root row (a lone directory too)', async () => {
|
|
harness = await mountTree()
|
|
rightClick(rowByName(harness.container, 'tmp'))
|
|
clickMenuitem('Zip and download')
|
|
await settleDownload()
|
|
expect(archiveUrl).toHaveBeenCalledWith({ sessionId: 's1', cwd: '/tmp' }, ['/tmp'], 'tmp.zip')
|
|
})
|
|
|
|
it('offers nothing for a lone FILE (the download row already covers it)', async () => {
|
|
harness = await mountTree()
|
|
rightClick(rowByName(harness.container, 'a.ts'))
|
|
expect(menuLabels()).toContain('Download')
|
|
expect(menuLabels().some(label => label.startsWith('Zip and download'))).toBe(false)
|
|
expect(archiveUrl).not.toHaveBeenCalled()
|
|
expect(fetchMock).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('reports a route refusal with the envelope message (caps, fence, bad request)', async () => {
|
|
fetchMock.mockResolvedValue(errorResponse(413, { ok: false, error: { code: 'bad-request', message: 'archive would exceed 64 MB' } }))
|
|
harness = await mountTree()
|
|
rightClick(rowByName(harness.container, 'sub'))
|
|
clickMenuitem('Zip and download')
|
|
await settleDownload()
|
|
expect(harness.container.querySelector('[role="alert"]')?.textContent)
|
|
.toContain('Archive failed: archive would exceed 64 MB')
|
|
// Nothing was downloaded, and no object URL leaked.
|
|
expect(downloads).toEqual([])
|
|
expect(createdUrls).toEqual([])
|
|
})
|
|
|
|
it('falls back to the status when the refusal carries no JSON body', async () => {
|
|
fetchMock.mockResolvedValue(errorResponse(500))
|
|
harness = await mountTree()
|
|
rightClick(rowByName(harness.container, 'sub'))
|
|
clickMenuitem('Zip and download')
|
|
await settleDownload()
|
|
expect(harness.container.querySelector('[role="alert"]')?.textContent)
|
|
.toContain('Archive failed: HTTP 500')
|
|
expect(downloads).toEqual([])
|
|
})
|
|
|
|
it('reports a network failure in the error strip', async () => {
|
|
fetchMock.mockRejectedValue(new Error('network down'))
|
|
harness = await mountTree()
|
|
rightClick(rowByName(harness.container, 'sub'))
|
|
clickMenuitem('Zip and download')
|
|
await settleDownload()
|
|
expect(harness.container.querySelector('[role="alert"]')?.textContent)
|
|
.toContain('Archive failed: network down')
|
|
expect(downloads).toEqual([])
|
|
})
|
|
|
|
it('reports a ZIP whose URL cannot be built without fetching', async () => {
|
|
archiveUrl.mockImplementation(() => { throw new Error('boom: too large') })
|
|
harness = await mountTree()
|
|
rightClick(rowByName(harness.container, 'sub'))
|
|
clickMenuitem('Zip and download')
|
|
await settleDownload()
|
|
expect(harness.container.querySelector('[role="alert"]')?.textContent)
|
|
.toContain('Archive failed: boom: too large')
|
|
expect(fetchMock).not.toHaveBeenCalled()
|
|
expect(downloads).toEqual([])
|
|
})
|
|
|
|
it('packages once while a request is in flight (double click guard)', async () => {
|
|
let release: (response: Response) => void = () => {}
|
|
fetchMock.mockImplementation(async () => await new Promise<Response>(resolve => { release = resolve }))
|
|
harness = await mountTree()
|
|
const pick = (): void => {
|
|
rightClick(rowByName(harness.container, 'sub'))
|
|
clickMenuitem('Zip and download')
|
|
}
|
|
pick()
|
|
expect(fetchMock).toHaveBeenCalledTimes(1)
|
|
// The row is still reachable (the menu closed on selection) and a second
|
|
// pick must not start a second archive.
|
|
pick()
|
|
expect(fetchMock).toHaveBeenCalledTimes(1)
|
|
await act(async () => { release(okResponse()) })
|
|
await settleDownload()
|
|
expect(downloads).toEqual(['blob:mock-1|sub.zip'])
|
|
// The guard releases once the request settled: another pick fetches again.
|
|
fetchMock.mockResolvedValue(okResponse())
|
|
pick()
|
|
expect(fetchMock).toHaveBeenCalledTimes(2)
|
|
await settleDownload()
|
|
})
|
|
|
|
it('shows a loading line while the archive is being built, and hides it after', async () => {
|
|
let release: (response: Response) => void = () => {}
|
|
fetchMock.mockImplementation(async () => await new Promise<Response>(resolve => { release = resolve }))
|
|
harness = await mountTree()
|
|
const busyLine = (): HTMLElement | null => harness.container.querySelector<HTMLElement>('[data-kind="loading"]')
|
|
// Nothing is shown before the request starts…
|
|
expect(busyLine()).toBeNull()
|
|
rightClick(rowByName(harness.container, 'sub'))
|
|
clickMenuitem('Zip and download')
|
|
// …the in-flight request keeps one visible, announced line…
|
|
const line = busyLine()
|
|
expect(line).not.toBeNull()
|
|
expect(line?.textContent).toBe('Loading…')
|
|
expect(line?.getAttribute('role')).toBe('status')
|
|
// …a repeated pick is still guarded (no second fetch) AND still not silent.
|
|
rightClick(rowByName(harness.container, 'sub'))
|
|
clickMenuitem('Zip and download')
|
|
expect(fetchMock).toHaveBeenCalledTimes(1)
|
|
expect(busyLine()).not.toBeNull()
|
|
await act(async () => { release(okResponse()) })
|
|
await settleDownload()
|
|
expect(busyLine()).toBeNull()
|
|
expect(downloads).toEqual(['blob:mock-1|sub.zip'])
|
|
})
|
|
|
|
it('hides the loading line when the archive fails too', async () => {
|
|
let release: (response: Response) => void = () => {}
|
|
fetchMock.mockImplementation(async () => await new Promise<Response>(resolve => { release = resolve }))
|
|
harness = await mountTree()
|
|
rightClick(rowByName(harness.container, 'sub'))
|
|
clickMenuitem('Zip and download')
|
|
expect(harness.container.querySelector('[data-kind="loading"]')).not.toBeNull()
|
|
await act(async () => { release(errorResponse(413, { ok: false, error: { message: 'too big' } })) })
|
|
await settleDownload()
|
|
expect(harness.container.querySelector('[data-kind="loading"]')).toBeNull()
|
|
// The busy line yields to the error strip: both never race for the slot.
|
|
expect(harness.container.querySelector('[role="alert"]')?.textContent)
|
|
.toContain('Archive failed: too big')
|
|
})
|
|
})
|