feat(sidebar): 打开方式双源并存 + 多选压缩下载 + 文件变动层级树

用户追加三条需求,全部落地:

1) 打开方式 = 宿主探测应用 + 插件自研 open-with(并存)
- 逐字恢复 src/client/open-with.ts / open-with-settings.tsx / plugin-settings.ts /
  src/open-external.ts / open.external 路由 / api.openExternal / editor descriptor
  的 settings.render,以及 20 个 openWith* 词条(19 份词典从 main 取回原文)
- 恢复 menu-flip.ts + layout.css 子菜单翻转规则(子菜单回来了)
- FileTree 菜单段(无标题行):宿主行 → 分隔线 → 插件 pinned + 「在应用中打开 >」
  子菜单(图钉 / SSH 后缀原样)→ 分隔线 → 宿主 reveal;宿主可用时过滤插件
  explorer 目标,宿主不可用时插件行照旧(SSH 远端场景保持可用)
- 死键清理:菜单去掉标题行后 openInApp 词条无引用,已从 21 份词典删除

2) 文件页多选右键「压缩并打包下载」
- 新增 src/zip.ts(自研 ZIP:方法 0/8 按收益二选一、UTF-8 bit 11、目录条目、
  自实现 CRC32、无第三方依赖)+ src/archive-route.ts(名净化 + 递归收集)+
  GET /sidebar/archive(同一道 workspace fence、目录递归跳过符号链接、
  10000 条目 / 256 MiB 上限)+ api.archiveUrl
- FileTree:多选 ≥2 项或单选目录时出现;fetch → blob → objectURL 下载,
  路由错误(超限 / fence / 非 GET)以 zipFailed 显示在错误条
- 修掉真实缺陷:central directory 只写 MS-DOS 位而 version-made-by 声称 Unix,
  Info-ZIP 会把每个文件解成 mode 000;改为 Unix 语义(0o100644 * 0x10000,
  << 16 会溢出 int32)。系统 unzip 复验:mode 644/755、unzip -t 无错

3) 文件变动页层级树 + 视觉打磨
- 新增 src/client/changes/change-tree.ts:单子目录链压缩成一行、目录先于文件、
  大小写不敏感排序、文件带 GitFileStatus、目录带下级变更数
- GitLens 两组各自渲染树:折叠状态按「组+路径」独立、默认展开;分组头吸顶 +
  计数胶囊;Stage all/Unstage all 改为带 aria-label 的 IconButton;选中 =
  interactive-bg-active + 2px 内嵌强调条;12px/级缩进 + l1 参考线;
  历史行 hash 徽标 / ref 胶囊 / 作者·时间右对齐

验证:typecheck / lint / test(134 文件 1422 通过)/ build 全绿;
DSH_CMD='npx -y --package @deepseek-ai/dsh@0.1.7-rc.1 dsh' pnpm test:mount 7/7 通过;
真实宿主截图确认三条需求(多选+双源菜单+zip 项、变动页树形层级)
This commit is contained in:
Menghuan1918 committed 2026-09-28 18:08:21 +08:00
1 parent 36fbc5ac7e
commit b011be1e98
56 files changed
+4468 -194

No files matched your search

+3 -3
View File
@@ -154,9 +154,9 @@ describe('built-in tab registrations', () => {
// The workspace fence switch rides the same card as a plain boolean row.
expect(toggles[1]?.title).toBeDefined()
expect(toggles[1]?.desc).toBeDefined()
// External opening is the host's own open-in-app capability now: the
// editor card has no custom settings panel left to render.
expect(service.getTab('editor')?.settings?.render).toBeUndefined()
// The open-with configuration (SSH host + custom editors) is the custom
// panel rendered below the declarative rows.
expect(service.getTab('editor')?.settings?.render).toBeDefined()
})
it('every built-in tab carries the settings-surface icon', () => {
+108 -3
View File
@@ -1,13 +1,16 @@
/**
* Changes tab session-lens data layer: event-log folding into file
* operations, plus a sanity pass over the shared diff/highlight engines
* (their full behavior suites live in the standalone dsh-file-trace plugin).
* Changes tab data layer: event-log folding into file operations, the
* directory tree the Git lens renders its groups through, and a sanity pass
* over the shared diff/highlight engines (their full behavior suites live in
* the standalone dsh-file-trace plugin).
*/
import { describe, expect, it } from 'vitest'
import { createToolResultMessage, ToolCallId } from '@deepseek-ai/dsh-llm'
import { extractFileOps, groupByFile, knownContentBefore, parseReadContent, parseReadLines } from '../src/client/changes/ops.ts'
import { buildChangeTree, type ChangeNode } from '../src/client/changes/change-tree.ts'
import { diffLines, buildDiffSegments, coalesceInline, diffInline } from '../src/client/diff/rows.ts'
import { langOfPath, scanLine } from '../src/client/diff/highlight.ts'
import type { GitStatusEntry } from '../src/client/api.ts'
import type { SidebarSessionEvent } from '../src/context-types.ts'
/** One synthetic session event. */
@@ -157,6 +160,108 @@ describe('parseReadLines', () => {
})
})
describe('change tree (the Git lens reads its groups through it)', () => {
/** One `git status` row from a path and its porcelain code. */
const entry = (path: string, xy = ' M'): GitStatusEntry => ({ path, xy })
/** A compact, assertion-friendly projection of one tree. */
const shape = (nodes: readonly ChangeNode[]): unknown[] => nodes.map(node => node.kind === 'dir'
? { dir: node.name, path: node.path, changes: node.changes, children: shape(node.children) }
: { file: node.name, path: node.path, letter: node.status.letter, tone: node.status.tone })
it('keeps a single root-level file as one leaf', () => {
expect(shape(buildChangeTree([entry('readme.md')]))).toEqual([
{ file: 'readme.md', path: 'readme.md', letter: 'M', tone: 'modified' },
])
})
it('nests a deep path and compresses its single-child chain into one row', () => {
const tree = buildChangeTree([entry('src/client/changes/a.ts')])
expect(shape(tree)).toEqual([
{
dir: 'src/client/changes',
path: 'src/client/changes',
changes: 1,
children: [{ file: 'a.ts', path: 'src/client/changes/a.ts', letter: 'M', tone: 'modified' }],
},
])
})
it('stops compressing where the path branches or a directory holds its own file', () => {
// Two child directories: 'src' keeps its own row.
expect(shape(buildChangeTree([entry('src/a/x.ts'), entry('src/b/y.ts')]))).toEqual([
{
dir: 'src',
path: 'src',
changes: 2,
children: [
{ dir: 'a', path: 'src/a', changes: 1, children: [{ file: 'x.ts', path: 'src/a/x.ts', letter: 'M', tone: 'modified' }] },
{ dir: 'b', path: 'src/b', changes: 1, children: [{ file: 'y.ts', path: 'src/b/y.ts', letter: 'M', tone: 'modified' }] },
],
},
])
// A file AT this level: 'a' keeps its own row (and its file leads the child).
expect(shape(buildChangeTree([entry('a/x.ts'), entry('a/b/y.ts')]))).toEqual([
{
dir: 'a',
path: 'a',
changes: 2,
children: [
{ dir: 'b', path: 'a/b', changes: 1, children: [{ file: 'y.ts', path: 'a/b/y.ts', letter: 'M', tone: 'modified' }] },
{ file: 'x.ts', path: 'a/x.ts', letter: 'M', tone: 'modified' },
],
},
])
})
it('orders directories before files, each by name case-insensitively', () => {
const tree = buildChangeTree([
entry('Zed.ts'), entry('B.ts'), entry('a.ts'), entry('zdir/f.ts'), entry('Adir/f.ts'),
])
expect(shape(tree).map(node => (node as { dir?: string; file?: string }).dir ?? (node as { file: string }).file))
.toEqual(['Adir', 'zdir', 'a.ts', 'B.ts', 'Zed.ts'])
})
it('mixes root-level files with nested paths and keeps same-named files apart', () => {
expect(shape(buildChangeTree([
entry('b/index.ts'), entry('index.ts'), entry('a/index.ts'),
]))).toEqual([
{ dir: 'a', path: 'a', changes: 1, children: [{ file: 'index.ts', path: 'a/index.ts', letter: 'M', tone: 'modified' }] },
{ dir: 'b', path: 'b', changes: 1, children: [{ file: 'index.ts', path: 'b/index.ts', letter: 'M', tone: 'modified' }] },
{ file: 'index.ts', path: 'index.ts', letter: 'M', tone: 'modified' },
])
})
it('carries every file porcelain status and counts the files under each row', () => {
const tree = buildChangeTree([
entry('src/a.ts', ' M'), entry('src/new.ts', '??'), entry('src/gone.ts', ' D'), entry('src/kept.ts', ' '),
])
expect(shape(tree)).toEqual([
{
dir: 'src',
path: 'src',
changes: 3,
children: [
{ file: 'a.ts', path: 'src/a.ts', letter: 'M', tone: 'modified' },
{ file: 'gone.ts', path: 'src/gone.ts', letter: 'D', tone: 'deleted' },
{ file: 'new.ts', path: 'src/new.ts', letter: 'U', tone: 'untracked' },
],
},
])
})
it('returns no nodes for an empty or all-clean list', () => {
expect(buildChangeTree([])).toEqual([])
expect(buildChangeTree([entry('a.ts', ' '), entry('b.ts', '!!')])).toEqual([])
})
it('counts a repeated path once', () => {
expect(shape(buildChangeTree([entry('a.ts'), entry('a.ts', '??')]))).toEqual([
{ file: 'a.ts', path: 'a.ts', letter: 'M', tone: 'modified' },
])
})
})
describe('ported diff/highlight engines (sanity)', () => {
it('diffLines pairs a rewrite as mod and folds context into hunks', () => {
const rows = diffLines('hello world', 'hello dsh')
+9 -3
View File
@@ -106,11 +106,17 @@ describe('ChangesTab', () => {
mount(root)
await flushEffects()
// Git lens: the changed-file row (badge letter + split name/directory).
// Git lens: the change reads as a TREE — the directory row owns the
// path segment, the file row its own name, its porcelain letter and the
// host's file artwork.
const dir = container.querySelector<HTMLButtonElement>('button[data-dir="src"]')
expect(dir).not.toBeNull()
expect(dir!.getAttribute('aria-expanded')).toBe('true')
const row = container.querySelector<HTMLButtonElement>('button[data-path="src/a.ts"]')
expect(row).toBeDefined()
expect(row).not.toBeNull()
expect(row!.textContent).toContain('a.ts')
expect(row!.textContent).toContain('src')
expect(row!.textContent).toContain('M')
expect(row!.querySelector('svg')).not.toBeNull()
// Clicking the row previews inline (no diff tab minted): the shared
// renderer draws the added row.
+317
View File
@@ -0,0 +1,317 @@
/**
* 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()
})
})
+115 -4
View File
@@ -16,6 +16,7 @@ import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { FileTree } from '../src/client/FileTree.tsx'
import { createOpenInApp, type OpenInApp, type OpenInAppEntry } from '../src/client/open-in-app.ts'
import type { OpenWithTarget } from '../src/client/open-with.ts'
import { createSidebarStore } from '../src/client/state.ts'
import { setupReactAct } from './test-utils.ts'
@@ -83,13 +84,28 @@ function makeHandle(overrides: Partial<OpenInApp> = {}): Handle {
interface Harness {
container: HTMLDivElement
onOpenWith: ReturnType<typeof vi.fn>
onToggleOpenWithPin: ReturnType<typeof vi.fn>
unmount: () => void
}
async function mountTree(handle?: Handle): Promise<Harness> {
/** The plugin targets a caller (EditorHost) may hand FileTree alongside the
* host handle; names are distinct from FILE_APPS so assertions are exact. */
const PLUGIN_TARGETS: OpenWithTarget[] = [
{ id: 'explorer', nameKey: 'openWithExplorer', name: '', kind: 'reveal', isVscodeFamily: false, localOnly: true },
{ id: 'custom:w', name: 'Windsurf', kind: 'url', urlTemplate: 'windsurf://file/{path}', isVscodeFamily: false, localOnly: false },
]
async function mountTree(handle?: Handle, plugin: {
targets?: OpenWithTarget[]
pinned?: string[]
ssh?: boolean
} = {}): Promise<Harness> {
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
const onOpenWith = vi.fn()
const onToggleOpenWithPin = vi.fn()
await act(async () => {
root.render(createElement(FileTree, {
sessionId: 's1',
@@ -102,17 +118,26 @@ async function mountTree(handle?: Handle): Promise<Harness> {
onOpenFileNewTab: () => {},
onOpenFileSide: () => {},
...(handle !== undefined ? { openInApp: handle.openInApp } : {}),
...(plugin.targets !== undefined ? {
openWithTargets: plugin.targets,
openWithPinned: plugin.pinned ?? [],
openWithSsh: plugin.ssh ?? false,
onOpenWith,
onToggleOpenWithPin,
} : {}),
onReferenceFile: () => {},
refreshTick: 0,
onUploadRequest: () => {},
busy: false,
}))
// Settle the async app listing the row menu triggers.
// Settle the async app listing / availability probe the menu triggers.
await Promise.resolve()
await Promise.resolve()
})
return {
container,
onOpenWith,
onToggleOpenWithPin,
unmount: () => { act(() => { root.unmount() }); container.remove() },
}
}
@@ -162,8 +187,13 @@ describe('FileTree open-in-app menu', () => {
harness = await mountTree(handle)
await openMenu(harness.container, 'a.ts')
expect(handle.fileApps).toHaveBeenCalledWith('/tmp/a.ts')
// The section heading is a non-interactive label row.
expect(document.body.textContent).toContain('Open with')
// No heading row any more: the host group is read from the application
// names themselves (`openInApp` and `openWithMenu` are near-synonyms, so
// two labels in one menu read as a repeated item). A data label entry is
// a LEAF `role="presentation"` row inside the menu.
const menu = document.querySelector('[role="menuitem"]')!.closest('[role="menu"]')
expect([...(menu?.querySelectorAll('[role="presentation"]') ?? [])]
.filter(row => row.children.length === 0)).toEqual([])
expect(menuLabels()).toContain('Open with default app')
expect(menuLabels()).toContain('VS Code')
expect(menuLabels()).toContain('Reveal in File Manager')
@@ -289,3 +319,84 @@ describe('FileTree open-in-app menu', () => {
expect(calls.open).toEqual([{ path: '/tmp/a.ts' }])
})
})
describe('FileTree open-in-app + plugin open-with coexistence', () => {
let harness: Harness
afterEach(() => {
harness.unmount()
document.body.innerHTML = ''
})
/** The label rows of the single open menu, in DOM order. */
function labelsOf(items: string[]): number[] {
const labels = menuLabels()
return items.map(item => labels.indexOf(item))
}
it('stacks the host rows above the plugin rows and ends with the host reveal', async () => {
const handle = makeHandle()
harness = await mountTree(handle, { targets: PLUGIN_TARGETS, pinned: ['custom:w'] })
await openMenu(harness.container, 'a.ts')
const [hostDefault, hostApp, pinnedPlugin, submenu, reveal] = labelsOf([
'Open with default app', 'VS Code', 'Windsurf', 'Open with', 'Reveal in File Manager',
])
// Every row exists, in the frozen order: host group → plugin group →
// reveal.
expect([hostDefault, hostApp, pinnedPlugin, submenu, reveal]).not.toContain(-1)
expect(hostDefault!).toBeLessThan(hostApp!)
expect(hostApp!).toBeLessThan(pinnedPlugin!)
expect(pinnedPlugin!).toBeLessThan(submenu!)
expect(submenu!).toBeLessThan(reveal!)
// The plugin's `explorer` target is replaced by the host reveal row.
expect(menuLabels()).not.toContain('File Manager')
// Separator rows between each group.
expect(document.querySelectorAll('[role="separator"]').length).toBeGreaterThanOrEqual(2)
})
it('keeps the plugin rows — explorer included — when the host cannot open desktop paths', async () => {
const handle = makeHandle({ available: () => false })
harness = await mountTree(handle, { targets: PLUGIN_TARGETS, pinned: ['custom:w'] })
await openMenu(harness.container, 'a.ts')
// No host rows at all…
expect(menuLabels()).not.toContain('Open with default app')
expect(menuLabels()).not.toContain('Reveal in File Manager')
// …but the plugin's own reveal target survives, so reveal is never lost.
expect(menuLabels()).toContain('Windsurf')
const parent = menuItems().find(item => item.getAttribute('aria-haspopup') === 'menu')!
act(() => { parent.click() })
expect([...document.querySelectorAll<HTMLElement>('[role="menu"] [role="menu"] [role="menuitem"]')]
.map(item => item.textContent?.trim())).toEqual(['File Manager', 'Windsurf'])
})
it('keeps the plugin rows when no host handle was injected at all', async () => {
harness = await mountTree(undefined, { targets: PLUGIN_TARGETS, pinned: [] })
await openMenu(harness.container, 'a.ts')
expect(menuLabels()).not.toContain('Reveal in File Manager')
expect(menuLabels()).toContain('Open with')
})
it('hands the plugin target id and path to onOpenWith (SSH suffix intact)', async () => {
const handle = makeHandle({ available: () => false })
harness = await mountTree(handle, { targets: PLUGIN_TARGETS, pinned: [], ssh: true })
await openMenu(harness.container, 'a.ts')
const parent = menuItems().find(item => item.getAttribute('aria-haspopup') === 'menu')!
act(() => { parent.click() })
const windsurf = [...document.querySelectorAll<HTMLElement>('[role="menu"] [role="menu"] [role="menuitem"]')]
.find(item => item.textContent?.trim() === 'Windsurf (SSH)')!
act(() => { windsurf.click() })
expect(harness.onOpenWith).toHaveBeenCalledWith('custom:w', '/tmp/a.ts')
})
it('routes a pin click to onToggleOpenWithPin without selecting a row', async () => {
const handle = makeHandle({ available: () => false })
harness = await mountTree(handle, { targets: PLUGIN_TARGETS, pinned: [] })
await openMenu(harness.container, 'a.ts')
act(() => { menuItems().find(item => item.getAttribute('aria-haspopup') === 'menu')!.click() })
const pin = [...document.querySelectorAll<HTMLElement>('[role="menu"] [role="menu"] [role="menuitem"]')]
.find(item => item.textContent?.trim() === 'Windsurf')!
.querySelector<HTMLElement>('[class*="openWithPin"]')!
act(() => { pin.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })) })
expect(harness.onToggleOpenWithPin).toHaveBeenCalledWith('custom:w')
expect(harness.onOpenWith).not.toHaveBeenCalled()
})
})
+256
View File
@@ -0,0 +1,256 @@
/**
* FileTree's PLUGIN open-with menu (restored in round two, and coexisting with
* the host's open-in-app rows — the coexistence cases live in
* file-tree-open-in-app.spec.tsx). With no host handle injected, the "打开方式"
* section is the plugin's own: the pinned targets as direct rows, the
* `openWithMenu` parent row with every target as a nested submenu (per-row
* pushpins that toggle without selecting the row), SSH suffixes in remote
* mode, and the reveal target kept (nothing else can reveal without the host).
*/
// @vitest-environment jsdom
import { beforeAll, afterEach, 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 type { OpenWithTarget } from '../src/client/open-with.ts'
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 })
})
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 },
],
truncated: false,
}),
// The tree reads the shared git-status store; a non-repo answer keeps
// every row plain.
gitStatus: async () => ({ isRepo: false, entries: [] }),
},
downloadUrl: () => '/sidebar/file',
archiveUrl: () => '/sidebar/archive',
isOutsideWorkspaceMessage: () => false,
}))
/** The resolved target list a caller (EditorHost) would hand FileTree. */
const targets: OpenWithTarget[] = [
{ id: 'explorer', nameKey: 'openWithExplorer', name: '', kind: 'reveal', isVscodeFamily: false, localOnly: true },
{ id: 'vscode', nameKey: 'openWithVscode', name: '', kind: 'url', urlTemplate: 'vscode://file/{path}', isVscodeFamily: true, localOnly: false },
{ id: 'cursor', nameKey: 'openWithCursor', name: '', kind: 'url', urlTemplate: 'cursor://file/{path}', isVscodeFamily: true, localOnly: false },
{ id: 'zed', nameKey: 'openWithZed', name: '', kind: 'url', urlTemplate: 'zed://file/{path}', isVscodeFamily: false, localOnly: true },
{ id: 'custom:w', name: 'Windsurf', kind: 'url', urlTemplate: 'windsurf://file/{path}', isVscodeFamily: false, localOnly: false },
]
interface Harness {
container: HTMLDivElement
onOpenWith: ReturnType<typeof vi.fn>
onToggleOpenWithPin: ReturnType<typeof vi.fn>
unmount: () => void
}
async function mountTree(overrides: {
openWithTargets?: OpenWithTarget[]
openWithPinned?: string[]
openWithSsh?: boolean
} = {}): Promise<Harness> {
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
const onOpenWith = vi.fn()
const onToggleOpenWithPin = vi.fn()
// Property-presence semantics: an explicit `openWithTargets: undefined`
// must reach FileTree (the section hides) instead of falling back.
const has = (key: 'openWithTargets' | 'openWithPinned' | 'openWithSsh'): boolean =>
Object.prototype.hasOwnProperty.call(overrides, key)
await act(async () => {
root.render(createElement(FileTree, {
sessionId: 's1',
cwd: '/tmp',
store: createSidebarStore(),
expanded: [],
revealed: [],
onToggle: () => {},
onOpenFile: () => {},
onOpenFileNewTab: () => {},
onOpenFileSide: () => {},
openWithTargets: has('openWithTargets') ? overrides.openWithTargets : targets,
openWithPinned: has('openWithPinned') ? overrides.openWithPinned : ['vscode'],
openWithSsh: has('openWithSsh') ? overrides.openWithSsh : false,
onOpenWith,
onToggleOpenWithPin,
onReferenceFile: () => {},
refreshTick: 0,
onUploadRequest: () => {},
busy: false,
}))
await Promise.resolve()
})
return {
container,
onOpenWith,
onToggleOpenWithPin,
unmount: () => { act(() => { root.unmount() }); container.remove() },
}
}
/** The file row of the one-level tree. */
function fileRow(container: HTMLDivElement): HTMLElement {
const row = [...container.querySelectorAll<HTMLElement>('[role="button"]')]
.find(el => el.querySelector('[class*="explorerName"]')?.textContent === 'a.ts')
if (row === undefined) throw new Error('file row not found')
return row
}
/** Open the row's context menu at a fixed cursor position. */
function openMenu(container: HTMLDivElement): void {
const event = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 20, clientY: 30 })
act(() => { fileRow(container).dispatchEvent(event) })
}
function menuItems(): HTMLElement[] {
return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')]
}
function submenuRows(): HTMLElement[] {
return [...document.querySelectorAll<HTMLElement>('[role="menu"] [role="menu"] [role="menuitem"]')]
}
function submenuParent(): HTMLElement {
const parent = menuItems().find(item => item.getAttribute('aria-haspopup') === 'menu')
if (parent === undefined) throw new Error('submenu parent not found')
return parent
}
describe('FileTree plugin open-with menu', () => {
let harness: Harness
afterEach(() => {
harness.unmount()
document.body.innerHTML = ''
document.body.removeAttribute('data-dsh-sidebar-submenu')
})
it('renders the pinned direct row and the submenu parent for a file row', async () => {
harness = await mountTree()
openMenu(harness.container)
// The pinned VS Code sits at the top level (before the submenu parent).
expect(menuItems().map(item => item.textContent?.trim())).toContain('VS Code')
const parent = submenuParent()
expect(parent.textContent).toContain('Open with')
// The submenu parent carries the trailing chevron affordance (the
// primitives Menu renders no arrow of its own), right-aligned inside a
// full-width label row — the same structure the submenu children use.
expect(parent.querySelector('[class*="openWithChevron"]')).not.toBeNull()
expect(parent.querySelector('[class*="openWithLabel"]')).not.toBeNull()
})
it('opens the submenu on click and lists every target with pin toggles', async () => {
harness = await mountTree()
openMenu(harness.container)
act(() => { submenuParent().click() })
expect(submenuRows().map(item => item.textContent?.trim())).toEqual([
'File Manager', 'VS Code', 'Cursor', 'Zed', 'Windsurf',
])
expect(submenuRows().every(item => item.querySelector('[class*="openWithPin"]') !== null)).toBe(true)
// Pinned state is announced per row (and swaps the pushpin glyph).
const vscodeRow = submenuRows().find(item => item.textContent?.trim() === 'VS Code')
const cursorRow = submenuRows().find(item => item.textContent?.trim() === 'Cursor')
expect(vscodeRow?.querySelector('[aria-label="Unpin"]')).not.toBeNull()
expect(cursorRow?.querySelector('[aria-label="Pin to menu"]')).not.toBeNull()
})
it('pin click toggles without selecting the row or closing the menu', async () => {
harness = await mountTree()
openMenu(harness.container)
act(() => { submenuParent().click() })
const cursorRow = submenuRows().find(item => item.textContent?.trim() === 'Cursor')!
const pin = cursorRow.querySelector<HTMLElement>('[class*="openWithPin"]')
expect(pin).not.toBeNull()
act(() => { pin!.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })) })
expect(harness.onToggleOpenWithPin).toHaveBeenCalledWith('cursor')
expect(harness.onOpenWith).not.toHaveBeenCalled()
// The menu (and the submenu) stayed open.
expect(document.querySelector('[role="menu"] [role="menu"]')).not.toBeNull()
})
it('selecting a submenu child invokes onOpenWith with the row path and closes the menu', async () => {
harness = await mountTree()
openMenu(harness.container)
act(() => { submenuParent().click() })
const zedRow = submenuRows().find(item => item.textContent?.trim() === 'Zed')!
act(() => { zedRow.click() })
expect(harness.onOpenWith).toHaveBeenCalledWith('zed', '/tmp/a.ts')
// Selecting closes the row menu entirely.
expect(document.querySelector('[role="menu"] [role="menu"]')).toBeNull()
expect(menuItems()).toHaveLength(0)
})
it('appends the SSH hint to VSCode-family labels in remote mode', async () => {
harness = await mountTree({
openWithSsh: true,
openWithTargets: targets.filter(target => !target.localOnly),
openWithPinned: [],
})
openMenu(harness.container)
act(() => { submenuParent().click() })
expect(submenuRows().map(item => item.textContent?.trim())).toEqual([
'VS Code (SSH)', 'Cursor (SSH)', 'Windsurf (SSH)',
])
})
it('hides the plugin section when the caller wires no targets', async () => {
harness = await mountTree({ openWithTargets: undefined })
openMenu(harness.container)
expect(menuItems().some(item => item.textContent?.includes('Open with'))).toBe(false)
expect(menuItems().some(item => item.getAttribute('aria-haspopup') === 'menu')).toBe(false)
})
})
describe('FileTree plugin open-with menu flip geometry (submenu clamping)', () => {
const ATTR = 'data-dsh-sidebar-submenu'
let harness: Harness
afterEach(() => {
harness.unmount()
document.body.innerHTML = ''
document.body.removeAttribute(ATTR)
})
it('publishes "down" for a top-of-tree opening and clears on selection', async () => {
harness = await mountTree()
// openMenu() right-clicks at (20, 30) — the upper half, plenty of right
// room in jsdom's default viewport.
openMenu(harness.container)
expect(document.body.getAttribute(ATTR)).toBe('down')
act(() => { submenuParent().click() })
const zedRow = submenuRows().find(item => item.textContent?.trim() === 'Zed')!
act(() => { zedRow.click() })
expect(menuItems()).toHaveLength(0)
expect(document.body.hasAttribute(ATTR)).toBe(false)
})
it('adds "left" when the cursor sits within the right-hand submenu room', async () => {
harness = await mountTree()
const nearRight = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: window.innerWidth - 10, clientY: 30 })
act(() => { fileRow(harness.container).dispatchEvent(nearRight) })
expect(document.body.getAttribute(ATTR)).toBe('down left')
})
it('clears the attribute on unmount with the menu still open', async () => {
harness = await mountTree()
openMenu(harness.container)
expect(document.body.getAttribute(ATTR)).toBe('down')
harness.unmount()
expect(document.body.hasAttribute(ATTR)).toBe(false)
})
})
+133
View File
@@ -421,3 +421,136 @@ describe('GitLens (changes tab, git lens) linked-worktree consistency', () => {
}
})
})
describe('GitLens (changes tab, git lens) change tree', () => {
/** Mount with one changed-file inventory; every test picks its own entries. */
async function mountTree(
container: HTMLElement,
root: Root,
entries: Array<{ path: string; xy: string }>,
): Promise<void> {
const changes = entries.filter(row => row.xy !== ' ').length
vi.spyOn(api, 'gitWorktrees').mockResolvedValue([{ path: MAIN, branch: 'main', current: true, changes }])
vi.spyOn(api, 'gitStatus').mockResolvedValue({ isRepo: true, branch: 'main', entries })
vi.spyOn(api, 'gitBranch').mockResolvedValue({ current: 'main', names: ['main'] })
vi.spyOn(api, 'gitLog').mockResolvedValue([])
mountGit(root)
await flushEffects()
}
function makeRoot(): { container: HTMLDivElement; root: Root } {
const container = document.createElement('div')
document.body.append(container)
return { container, root: createRoot(container) }
}
it('folds a directory row per group, independently of the same path on the other side', async () => {
const { container, root } = makeRoot()
try {
await mountTree(container, root, [
{ path: 'src/a.ts', xy: ' M' }, // unstaged side
{ path: 'src/b.ts', xy: 'M ' }, // staged side
])
const dirs = () => [...container.querySelectorAll<HTMLButtonElement>('button[data-dir="src"]')]
// One 'src' row per group: a path with changes on both sides appears in
// both trees.
expect(dirs()).toHaveLength(2)
expect(dirs()[0]!.getAttribute('aria-expanded')).toBe('true')
expect(dirs()[0]!.querySelector('svg')).not.toBeNull()
expect(container.querySelector('button[data-path="src/a.ts"]')).not.toBeNull()
expect(container.querySelector('button[data-path="src/a.ts"]')!.querySelector('svg')).not.toBeNull()
await act(async () => { dirs()[0]!.click() })
// Folded: the unstaged subtree is gone...
expect(dirs()[0]!.getAttribute('aria-expanded')).toBe('false')
expect(container.querySelector('button[data-path="src/a.ts"]')).toBeNull()
// ...while the staged group's own 'src' row stays open and keeps its file.
expect(dirs()[1]!.getAttribute('aria-expanded')).toBe('true')
expect(container.querySelector('button[data-path="src/b.ts"]')).not.toBeNull()
await act(async () => { dirs()[0]!.click() })
expect(container.querySelector('button[data-path="src/a.ts"]')).not.toBeNull()
} finally {
act(() => { root.unmount() })
container.remove()
}
})
it('compresses a single-child directory chain into one labelled row', async () => {
const { container, root } = makeRoot()
try {
await mountTree(container, root, [
{ path: 'src/client/changes/a.ts', xy: ' M' },
{ path: 'src/client/changes/b.ts', xy: ' M' },
])
// Three levels, one child each: one row, one label, two changes.
const row = container.querySelector<HTMLButtonElement>('button[data-dir="src/client/changes"]')
expect(row).not.toBeNull()
expect(row!.textContent).toContain('src/client/changes')
expect(container.querySelector('[data-group="unstaged"] [data-count]')?.textContent).toBe('2')
// Both files hang under that one row.
expect(container.querySelector('button[data-path="src/client/changes/a.ts"]')).not.toBeNull()
expect(container.querySelector('button[data-path="src/client/changes/b.ts"]')).not.toBeNull()
// Nothing on the staged side: only the empty band, no tree rows.
expect(container.querySelectorAll('[data-group="staged"] [data-path]')).toHaveLength(0)
} finally {
act(() => { root.unmount() })
container.remove()
}
})
it('stages a file from a nested tree row and re-reads the shared status', async () => {
const { container, root } = makeRoot()
try {
await mountTree(container, root, [{ path: 'src/deep/a.ts', xy: ' M' }])
const stage = vi.spyOn(api, 'gitStage').mockResolvedValue({ ok: true })
const statusSpy = vi.mocked(api.gitStatus)
const statusCallsBefore = statusSpy.mock.calls.length
const action = container.querySelector<HTMLButtonElement>(`button[aria-label="${t('stage')}"]`)
expect(action).not.toBeNull()
await act(async () => { action!.click() })
await flushEffects()
// The auto-selected primary checkout rides along as the worktree target.
expect(stage).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'session' }), 'src/deep/a.ts', MAIN)
expect(statusSpy.mock.calls.length).toBeGreaterThan(statusCallsBefore)
} finally {
act(() => { root.unmount() })
container.remove()
}
})
it('bands each group with its count and a labelled stage-all action', async () => {
const { container, root } = makeRoot()
try {
await mountTree(container, root, [
{ path: 'src/a.ts', xy: ' M' },
{ path: 'docs/b.md', xy: ' M' },
{ path: 'src/c.ts', xy: 'M ' },
])
const unstaged = container.querySelector<HTMLElement>('[data-group="unstaged"]')!
const staged = container.querySelector<HTMLElement>('[data-group="staged"]')!
expect(unstaged.textContent).toContain(t('unstaged'))
expect(unstaged.querySelector('[data-count]')?.textContent).toBe('2')
expect(staged.querySelector('[data-count]')?.textContent).toBe('1')
const stageAll = unstaged.querySelector<HTMLButtonElement>(`button[aria-label="${t('stageAll')}"]`)
const unstageAll = staged.querySelector<HTMLButtonElement>(`button[aria-label="${t('unstageAll')}"]`)
expect(stageAll).not.toBeNull()
expect(unstageAll).not.toBeNull()
const stage = vi.spyOn(api, 'gitStage').mockResolvedValue({ ok: true })
await act(async () => { stageAll!.click() })
await flushEffects()
// "Stage all" stages the whole worktree: no path argument.
expect(stage).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'session' }), undefined, MAIN)
} finally {
act(() => { root.unmount() })
container.remove()
}
})
})
+122
View File
@@ -0,0 +1,122 @@
/**
* The context-menu submenu flip geometry: the pure token computation behind
* the body attribute layout.css consumes (see src/client/menu-flip.ts for
* the contract) plus the attribute lifecycle of the hook itself.
*/
// @vitest-environment jsdom
import { createElement, useState } from 'react'
import { readFileSync } from 'node:fs'
import { act } from 'react-dom/test-utils'
import { describe, expect, it } from 'vitest'
import { renderRoot, setupReactAct } from './test-utils.ts'
import { SUBMENU_FLIP_ATTR, submenuFlipTokens, useSubmenuFlip } from '../src/client/menu-flip.ts'
setupReactAct()
describe('layout.css contract', () => {
it('consumes the exact attribute name menu-flip.ts publishes', () => {
// The two halves of the flip mechanism can drift silently: renaming the
// attribute here would leave layout.css matching nothing (submenus revert
// to overflowing) with every test still green. Tie them together. Specs
// run from the repo root (chunk-artifact.spec.ts reads lib/ the same way).
const css = readFileSync('src/client/layout.css', 'utf8')
expect(css).toContain(`body[${SUBMENU_FLIP_ATTR}~="down"] div[role="menu"] div[role="menu"]`)
expect(css).toContain(`body[${SUBMENU_FLIP_ATTR}~="left"] div[role="menu"] div[role="menu"]`)
expect(css).toContain(`body[${SUBMENU_FLIP_ATTR}~="left"] div[role="menu"] div[role="menu"]::before`)
})
it('keeps the submenu visual tether rules (parent highlight + tight gap)', () => {
// Part 1 keeps the parent row lit while its submenu is open (the Menu
// marks it aria-expanded); part 2 tightens the card gap to 4px with the
// hover corridor narrowed to match. Losing either sends the submenu back
// to reading as an unrelated floating card.
const css = readFileSync('src/client/layout.css', 'utf8')
expect(css).toContain(`body[${SUBMENU_FLIP_ATTR}] div[role="menu"] button[aria-expanded="true"]`)
expect(css).toContain('left: calc(100% + 4px)')
expect(css).toContain('right: calc(100% + 4px)')
expect(css).toContain('width: 4px')
})
})
describe('submenuFlipTokens', () => {
// Default geometry (1024x768): the panel is docked right, so the
// interesting split is the right-hand 400px strip and the vertical half.
it('flips down for a cursor in the upper half, keeps primitive defaults below', () => {
expect(submenuFlipTokens(500, 20, 1024, 768)).toBe('down')
expect(submenuFlipTokens(500, 700, 1024, 768)).toBe('')
})
it('flips left when the right-hand room cannot fit card + submenu', () => {
// 700 + 400 > 1024 → left; the cursor is low, so no down token.
expect(submenuFlipTokens(700, 700, 1024, 768)).toBe('left')
// Both tokens compose for a top-right opening.
expect(submenuFlipTokens(700, 20, 1024, 768)).toBe('down left')
})
it('uses the exact boundary inclusively (midpoint and width-minus-room still flip)', () => {
expect(submenuFlipTokens(500, 384, 1024, 768)).toBe('')
expect(submenuFlipTokens(500, 383, 1024, 768)).toBe('down')
expect(submenuFlipTokens(624, 700, 1024, 768)).toBe('')
expect(submenuFlipTokens(625, 700, 1024, 768)).toBe('left')
})
it('flips left throughout a narrow viewport', () => {
// A 600px window: any cursor past x=200 flips; the left strip cannot
// fit a right-growing submenu beside the 218px card either way.
expect(submenuFlipTokens(300, 100, 600, 800)).toBe('down left')
expect(submenuFlipTokens(500, 700, 600, 800)).toBe('left')
})
})
describe('useSubmenuFlip', () => {
const ATTR = 'data-dsh-sidebar-submenu'
/** Mount a probe whose menu state the spec drives via the returned setter. */
function mountFlipProbe(initial: { x: number; y: number } | null): { setMenu: (next: { x: number; y: number } | null) => void, unmount: () => void } {
let applyMenu: (next: { x: number; y: number } | null) => void = () => {}
function Probe(): React.ReactElement {
const [menu, setMenu] = useState<{ x: number; y: number } | null>(initial)
applyMenu = setMenu
useSubmenuFlip(menu)
return <div />
}
const rendered = renderRoot(createElement(Probe))
return {
setMenu: (next) => { act(() => { applyMenu(next) }) },
unmount: rendered.unmount,
}
}
it('publishes tokens while the menu is open and clears on close', () => {
const probe = mountFlipProbe({ x: 700, y: 20 })
try {
expect(document.body.getAttribute(ATTR)).toBe('down left')
probe.setMenu(null)
expect(document.body.hasAttribute(ATTR)).toBe(false)
} finally {
probe.unmount()
}
})
it('tracks the position across consecutive openings', () => {
const probe = mountFlipProbe({ x: 100, y: 20 })
try {
expect(document.body.getAttribute(ATTR)).toBe('down')
// Still open, now lower-left: the attribute stays (menu lifetime) but
// carries no token, so the primitive's own geometry applies.
probe.setMenu({ x: 100, y: 700 })
expect(document.body.getAttribute(ATTR)).toBe('')
probe.setMenu({ x: 700, y: 700 })
expect(document.body.getAttribute(ATTR)).toBe('left')
} finally {
probe.unmount()
}
})
it('clears the attribute when the owner unmounts with the menu still open', () => {
const probe = mountFlipProbe({ x: 100, y: 20 })
expect(document.body.getAttribute(ATTR)).toBe('down')
probe.unmount()
expect(document.body.hasAttribute(ATTR)).toBe(false)
})
})
+98
View File
@@ -0,0 +1,98 @@
/**
* Client/host routing for the file tree's external-open action. Remote
* VSCode-family SSH URLs must launch on the browser machine, while local
* editor URLs and reveal actions keep using the DSH host opener.
*/
import { afterEach, describe, expect, it, vi } from 'vitest'
import { api } from '../src/client/api.ts'
afterEach(() => {
vi.unstubAllGlobals()
})
function hostOk(): ReturnType<typeof vi.fn> {
return vi.fn(async () => ({
ok: true,
status: 200,
json: async () => ({ ok: true, value: { started: true } }),
}))
}
describe('api.openExternal', () => {
it('launches an SSH remote-editor URL on the client without calling the host', async () => {
const assign = vi.fn()
const fetchMock = hostOk()
vi.stubGlobal('window', { location: { assign } })
vi.stubGlobal('fetch', fetchMock)
const url = 'vscode://vscode-remote/ssh-remote+dev/home/u/f.ts'
await expect(api.openExternal({ action: 'url', url })).resolves.toEqual({ started: true })
expect(assign).toHaveBeenCalledOnce()
expect(assign).toHaveBeenCalledWith(url)
expect(fetchMock).not.toHaveBeenCalled()
})
it('launches Cursor/custom VSCode-family SSH URLs on the client too', async () => {
const assign = vi.fn()
const fetchMock = hostOk()
vi.stubGlobal('window', { location: { assign } })
vi.stubGlobal('fetch', fetchMock)
await api.openExternal({
action: 'url',
url: 'cursor://vscode-remote/ssh-remote+dev/home/u/f.ts',
})
await api.openExternal({
action: 'url',
url: 'myfork://vscode-remote/ssh-remote+dev/home/u/f.ts',
})
expect(assign).toHaveBeenCalledTimes(2)
expect(fetchMock).not.toHaveBeenCalled()
})
it('keeps local editor URLs on the host opener', async () => {
const assign = vi.fn()
const fetchMock = hostOk()
vi.stubGlobal('window', { location: { assign } })
vi.stubGlobal('fetch', fetchMock)
await expect(api.openExternal({
action: 'url',
url: 'vscode://file//tmp/a.ts',
})).resolves.toEqual({ started: true })
expect(assign).not.toHaveBeenCalled()
expect(fetchMock).toHaveBeenCalledOnce()
expect(fetchMock.mock.calls[0]?.[0]).toBe('/sidebar/api/open.external')
})
it('keeps reveal actions and http(s) lookalikes on the host opener', async () => {
const assign = vi.fn()
const fetchMock = hostOk()
vi.stubGlobal('window', { location: { assign } })
vi.stubGlobal('fetch', fetchMock)
await api.openExternal({ action: 'reveal', path: '/tmp/a.ts' })
await api.openExternal({
action: 'url',
url: 'https://vscode-remote/ssh-remote+dev/home/u/f.ts',
})
expect(assign).not.toHaveBeenCalled()
expect(fetchMock).toHaveBeenCalledTimes(2)
})
it('returns a rejected promise when client navigation throws', async () => {
const error = new Error('navigation failed')
const fetchMock = hostOk()
vi.stubGlobal('window', { location: { assign: vi.fn(() => { throw error }) } })
vi.stubGlobal('fetch', fetchMock)
await expect(api.openExternal({
action: 'url',
url: 'vscode://vscode-remote/ssh-remote+dev/home/u/f.ts',
})).rejects.toBe(error)
expect(fetchMock).not.toHaveBeenCalled()
})
})
+73
View File
@@ -0,0 +1,73 @@
/**
* Host external-open helpers: per-platform opener commands (pure, injected
* platform) and the URL validation that guards the spawn route. The actual
* spawns are not exercised — the route runs in the DSH host process and the
* OS outcome is not testable here.
*/
import { describe, expect, it } from 'vitest'
import { launchExternal, revealCommand, urlCommand, validateExternalUrl } from '../src/open-external.ts'
import { SidebarError } from '../src/wire.ts'
describe('revealCommand', () => {
it('darwin: `open -R <path>` selects the file in Finder', () => {
expect(revealCommand('/a/b.txt', 'darwin')).toEqual({ command: 'open', args: ['-R', '/a/b.txt'] })
})
it('win32: passes /select,<path> as one shell-free Explorer argument', () => {
expect(revealCommand('C:\\work\\two words\\a.txt', 'win32')).toEqual({
command: 'explorer.exe',
args: ['/select,C:\\work\\two words\\a.txt'],
})
})
it('linux: `xdg-open` opens the containing directory (no common select protocol)', () => {
expect(revealCommand('/a/b.txt', 'linux')).toEqual({ command: 'xdg-open', args: ['/a'] })
expect(revealCommand('/', 'linux')).toEqual({ command: 'xdg-open', args: ['/'] })
})
})
describe('urlCommand', () => {
it('darwin: `open <url>` launches the registered protocol handler', () => {
expect(urlCommand('vscode://file/x', 'darwin')).toEqual({ command: 'open', args: ['vscode://file/x'] })
})
it('win32: rundll32 url.dll,FileProtocolHandler <url>', () => {
expect(urlCommand('cursor://file/x', 'win32')).toEqual({
command: 'rundll32.exe',
args: ['url.dll,FileProtocolHandler', 'cursor://file/x'],
})
})
it('linux: `xdg-open <url>` launches the registered protocol handler', () => {
expect(urlCommand('zed://file/x', 'linux')).toEqual({ command: 'xdg-open', args: ['zed://file/x'] })
})
})
describe('validateExternalUrl', () => {
it('accepts custom-scheme URLs (incl. the SSH-remote form)', () => {
expect(validateExternalUrl('vscode://vscode-remote/ssh-remote+dev/home/u/f.ts'))
.toBe('vscode://vscode-remote/ssh-remote+dev/home/u/f.ts')
expect(validateExternalUrl('myapp://file/{path}')).toBe('myapp://file/{path}')
})
it('rejects http/https (only custom schemes make sense here)', () => {
expect(() => validateExternalUrl('https://example.com')).toThrow(SidebarError)
expect(() => validateExternalUrl('http://example.com')).toThrow(SidebarError)
})
it('rejects non-URL / non-`scheme://` strings', () => {
expect(() => validateExternalUrl('/home/u/f.ts')).toThrow(SidebarError)
expect(() => validateExternalUrl('a:file/x')).toThrow(SidebarError)
expect(() => validateExternalUrl('')).toThrow(SidebarError)
})
})
describe('launchExternal validation (pre-spawn)', () => {
it('rejects relative reveal paths before anything is spawned', () => {
expect(() => launchExternal('reveal', 'relative/path')).toThrow(SidebarError)
})
it('rejects invalid URLs before anything is spawned', () => {
expect(() => launchExternal('url', 'https://example.com')).toThrow(SidebarError)
})
})
+112
View File
@@ -0,0 +1,112 @@
/**
* The editor's "open with" settings panel: the SSH host row and the custom
* editor list (name + URL template + VSCode-family flag, add/remove). Every
* edit commits the whole `openWith` blob through the popup's
* updatePluginSetting; removing an editor also prunes its pinned id.
*/
// @vitest-environment jsdom
import { beforeAll, afterEach, 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 { OpenWithSettings } from '../src/client/open-with-settings.tsx'
import { setupReactAct } from './test-utils.ts'
setupReactAct()
beforeAll(() => {
Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true })
})
interface Harness {
container: HTMLDivElement
update: ReturnType<typeof vi.fn>
unmount: () => void
}
function mountSettings(rawOpenWith: unknown): Harness {
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
const update = vi.fn()
act(() => {
root.render(createElement(OpenWithSettings, {
pluginSettings: { openWith: rawOpenWith },
updatePluginSetting: update,
}))
})
return {
container,
update,
unmount: () => { act(() => { root.unmount() }) },
}
}
const baseConfig = {
sshHost: 'dev',
customEditors: [
{ id: 'a', name: 'Windsurf', urlTemplate: 'windsurf://file/{path}', isVscodeFamily: false },
],
pinned: ['vscode', 'custom:a'],
}
describe('OpenWithSettings', () => {
let harness: Harness
afterEach(() => {
harness.unmount()
document.body.innerHTML = ''
})
it('seeds the SSH host input from the persisted blob and commits edits', () => {
harness = mountSettings(baseConfig)
const input = harness.container.querySelector<HTMLInputElement>('input:not([type])')
expect(input?.value).toBe('dev')
// The native value setter (React's value tracker must see the change).
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!
act(() => {
setter.call(input, 'prod')
input!.dispatchEvent(new Event('input', { bubbles: true }))
})
expect(harness.update.mock.calls[0]?.[0]).toBe('openWith')
expect(harness.update.mock.calls[0]?.[1]).toMatchObject({ sshHost: 'prod' })
})
it('adds a custom editor row and commits the extended list', () => {
harness = mountSettings(baseConfig)
const add = [...harness.container.querySelectorAll<HTMLButtonElement>('button')]
.find(button => button.textContent?.trim() === 'Add')
expect(add).toBeDefined()
act(() => { add!.click() })
const blob = harness.update.mock.calls[0]?.[1] as { customEditors: unknown[]; pinned: string[] }
expect(blob.customEditors).toHaveLength(2)
expect(blob.pinned).toEqual(['vscode', 'custom:a'])
})
it('removes an editor and prunes its pinned id', () => {
harness = mountSettings(baseConfig)
const remove = harness.container.querySelector<HTMLButtonElement>('button[aria-label="Remove"]')
expect(remove).toBeDefined()
act(() => { remove!.click() })
const blob = harness.update.mock.calls[0]?.[1] as { customEditors: unknown[]; pinned: string[] }
expect(blob.customEditors).toHaveLength(0)
expect(blob.pinned).toEqual(['vscode'])
})
it('shows the validity hint when a row is incomplete', () => {
harness = mountSettings({
sshHost: '',
customEditors: [{ id: 'x', name: 'Bad', urlTemplate: 'x://file/x', isVscodeFamily: true }],
pinned: [],
})
expect(harness.container.textContent).toContain('are not shown in the menu')
})
it('edits the VSCode-family flag of one row', () => {
harness = mountSettings(baseConfig)
const checkbox = harness.container.querySelector<HTMLInputElement>('input[type="checkbox"]')
expect(checkbox?.checked).toBe(false)
act(() => { checkbox!.click() })
const blob = harness.update.mock.calls[0]?.[1] as { customEditors: { isVscodeFamily: boolean }[] }
expect(blob.customEditors[0]?.isVscodeFamily).toBe(true)
})
})
+150
View File
@@ -0,0 +1,150 @@
/**
* The file tree "open with" pure logic: config parsing (tolerant), target
* resolution (built-ins + custom, SSH filtering), URL building (local file
* URLs and VSCode-family SSH-remote URLs) and the custom-editor validators.
*/
import { describe, expect, it } from 'vitest'
import {
isValidCustomEditor,
newCustomEditorId,
normalizeUrlPath,
openWithSshActive,
openWithUrl,
parseOpenWithConfig,
resolveOpenWithTargets,
type CustomEditor,
type OpenWithTarget,
} from '../src/client/open-with.ts'
describe('parseOpenWithConfig', () => {
it('returns the defaults for null / non-object / array values', () => {
expect(parseOpenWithConfig(null)).toEqual({ sshHost: '', customEditors: [], pinned: [] })
expect(parseOpenWithConfig('junk')).toEqual({ sshHost: '', customEditors: [], pinned: [] })
expect(parseOpenWithConfig([])).toEqual({ sshHost: '', customEditors: [], pinned: [] })
})
it('keeps structurally valid custom editors (incl. in-progress rows) and drops junk', () => {
const config = parseOpenWithConfig({
sshHost: 'dev',
customEditors: [
{ id: 'a', name: 'Windsurf', urlTemplate: 'windsurf://file/{path}', isVscodeFamily: false },
{ id: 'b', name: '', urlTemplate: 'b://file/{path}', isVscodeFamily: true },
{ id: 'c', name: 'Trae', urlTemplate: 'trae://file/{path}', isVscodeFamily: true },
'junk',
null,
42,
],
pinned: ['vscode', 'custom:a', 42, '', 'custom:c'],
})
expect(config.sshHost).toBe('dev')
expect(config.customEditors.map(editor => editor.id)).toEqual(['a', 'b', 'c'])
expect(config.pinned).toEqual(['vscode', 'custom:a', 'custom:c'])
})
})
describe('resolveOpenWithTargets', () => {
const localCustom: CustomEditor = { id: 'e1', name: 'Windsurf', urlTemplate: 'windsurf://file/{path}', isVscodeFamily: false }
const familyCustom: CustomEditor = { id: 'e2', name: 'Zed-like fork', urlTemplate: 'x-zed://file/{path}', isVscodeFamily: true }
it('lists built-ins first, then custom editors (local mode)', () => {
const targets = resolveOpenWithTargets(parseOpenWithConfig({ customEditors: [localCustom] }))
expect(targets.map(target => target.id)).toEqual(['explorer', 'vscode', 'cursor', 'zed', 'custom:e1'])
expect(targets[0]?.kind).toBe('reveal')
expect(targets[1]?.urlTemplate).toBe('vscode://file/{path}')
})
it('excludes incomplete custom-editor rows from the menu (they stay in the blob)', () => {
const targets = resolveOpenWithTargets(parseOpenWithConfig({
customEditors: [
{ id: 'e1', name: 'Windsurf', urlTemplate: 'windsurf://file/{path}', isVscodeFamily: false },
{ id: 'e2', name: '', urlTemplate: 'incomplete://file/{path}', isVscodeFamily: true },
],
}))
expect(targets.map(target => target.id)).toEqual(['explorer', 'vscode', 'cursor', 'zed', 'custom:e1'])
})
it('drops local-only targets in SSH mode (file manager, Zed, non-VSCode custom)', () => {
const config = parseOpenWithConfig({ sshHost: 'dev', customEditors: [localCustom, familyCustom] })
const targets = resolveOpenWithTargets(config)
expect(targets.map(target => target.id)).toEqual(['vscode', 'cursor', 'custom:e2'])
})
it('prunes unknown pinned ids only when resolving (the parse keeps them)', () => {
const config = parseOpenWithConfig({ pinned: ['ghost'] })
expect(config.pinned).toEqual(['ghost'])
expect(resolveOpenWithTargets(config).map(target => target.id)).toContain('vscode')
})
})
describe('openWithUrl', () => {
const targets = resolveOpenWithTargets(parseOpenWithConfig({}))
const byId = (id: string): OpenWithTarget => {
const target = targets.find(item => item.id === id)
if (target === undefined) throw new Error(`no target ${id}`)
return target
}
it('builds local file URLs with the raw path (backslashes normalized)', () => {
expect(openWithUrl(byId('vscode'), '/home/u/f.ts', parseOpenWithConfig({}))).toBe('vscode://file//home/u/f.ts')
expect(openWithUrl(byId('vscode'), 'C:\\Users\\u\\f.ts', parseOpenWithConfig({}))).toBe('vscode://file/C:/Users/u/f.ts')
expect(openWithUrl(byId('zed'), '/x/y', parseOpenWithConfig({}))).toBe('zed://file//x/y')
})
it('builds SSH-remote URLs for VSCode-family targets in SSH mode', () => {
const config = parseOpenWithConfig({ sshHost: 'dev' })
expect(openWithUrl(byId('vscode'), '/home/u/f.ts', config))
.toBe('vscode://vscode-remote/ssh-remote+dev/home/u/f.ts')
expect(openWithUrl(byId('cursor'), '/home/u/f.ts', config))
.toBe('cursor://vscode-remote/ssh-remote+dev/home/u/f.ts')
})
it('keeps the local URL form for non-VSCode-family targets even in SSH mode', () => {
// (Such targets are hidden from the SSH menu; the URL builder stays honest.)
expect(openWithUrl(byId('zed'), '/x', parseOpenWithConfig({ sshHost: 'dev' }))).toBe('zed://file//x')
})
it('returns undefined for reveal targets and malformed templates', () => {
expect(openWithUrl(byId('explorer'), '/x', parseOpenWithConfig({}))).toBeUndefined()
const noScheme: OpenWithTarget = { id: 'x', name: '', kind: 'url', urlTemplate: 'not-a-url {path}', isVscodeFamily: false, localOnly: false }
expect(openWithUrl(noScheme, '/x', parseOpenWithConfig({}))).toBeUndefined()
const noSlash: OpenWithTarget = { id: 'y', name: '', kind: 'url', urlTemplate: 'a:file/{path}', isVscodeFamily: false, localOnly: false }
expect(openWithUrl(noSlash, '/x', parseOpenWithConfig({}))).toBeUndefined()
})
it('uses the custom template scheme for SSH URLs of VSCode-family custom editors', () => {
const config = parseOpenWithConfig({
sshHost: 'dev',
customEditors: [
{ id: 'e', name: 'Fork', urlTemplate: 'myfork://file/{path}', isVscodeFamily: true },
],
})
const targets = resolveOpenWithTargets(config)
expect(openWithUrl(targets[targets.length - 1]!, '/r/f.ts', config))
.toBe('myfork://vscode-remote/ssh-remote+dev/r/f.ts')
})
})
describe('helpers', () => {
it('normalizeUrlPath converts backslashes to slashes', () => {
expect(normalizeUrlPath('a\\b\\c')).toBe('a/b/c')
})
it('openWithSshActive trims the host', () => {
expect(openWithSshActive(parseOpenWithConfig({ sshHost: ' ' }))).toBe(false)
expect(openWithSshActive(parseOpenWithConfig({ sshHost: ' dev ' }))).toBe(true)
})
it('isValidCustomEditor requires a name, a {path} placeholder and a scheme:// prefix', () => {
expect(isValidCustomEditor({ name: 'A', urlTemplate: 'a://file/{path}' })).toBe(true)
expect(isValidCustomEditor({ name: '', urlTemplate: 'a://file/{path}' })).toBe(false)
expect(isValidCustomEditor({ name: 'A', urlTemplate: 'a://file/x' })).toBe(false)
expect(isValidCustomEditor({ name: 'A', urlTemplate: 'a:file/{path}' })).toBe(false)
})
it('newCustomEditorId yields unique non-empty ids', () => {
const first = newCustomEditorId()
const second = newCustomEditorId()
expect(first).not.toBe(second)
expect(first.length).toBeGreaterThan(0)
})
})
+20
View File
@@ -84,6 +84,7 @@ describe('host plugin smoke', () => {
'/sidebar/api',
'/sidebar/upload',
'/sidebar/bundle',
'/sidebar/archive',
'/sidebar/file',
'/sidebar/html',
])
@@ -738,6 +739,25 @@ const mountWithSettings = (settings?: unknown, home?: string): SidebarWebRoute =
return routes.find(route => route.path === '/sidebar/api')!
}
describe('open.external route', () => {
it('rejects an unknown action with bad-request (before anything spawns)', async () => {
const route = mountWithSettings()
const result = await invoke(route, 'open.external', { action: 'open-ish', path: '/tmp/a.txt' })
expect(result).toMatchObject({ ok: false, error: { code: 'bad-request' } })
})
it('rejects http(s) URLs and relative reveal paths before spawning', async () => {
const route = mountWithSettings()
const https = await invoke(route, 'open.external', { action: 'url', url: 'https://example.com' })
expect(https).toMatchObject({ ok: false, error: { code: 'bad-request' } })
const relative = await invoke(route, 'open.external', { action: 'reveal', path: 'relative/path' })
expect(relative).toMatchObject({ ok: false, error: { code: 'fs-error' } })
// A missing field never reaches launchExternal either.
const empty = await invoke(route, 'open.external', { action: 'url' })
expect(empty).toMatchObject({ ok: false, error: { code: 'bad-request' } })
})
})
describe('side card settings routes', () => {
it('serves the schema defaults when the settings service is absent', async () => {
const route = mountWithSettings(undefined)
+436
View File
@@ -0,0 +1,436 @@
/**
* ZIP builder + /sidebar/archive route.
*
* Two layers, no third-party ZIP dependency in either direction:
* - `buildZip` is checked by a minimal reader written HERE (EOCD → central
* directory → local header → inflate), so the test proves the bytes on the
* wire, not the writer's own bookkeeping. `unzip -t` is an extra check when
* the binary happens to exist (CI runners do not ship it).
* - the route is mounted against a fake cordis context (the same shape
* smoke.spec.ts uses) and answers a real request over a real temp
* workspace, covering the fence, the parameter guards and a full
* directory walk.
*/
import { afterEach, describe, expect, it } from 'vitest'
import { spawnSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { inflateRawSync } from 'node:zlib'
import { apply } from '../src/index.ts'
import { archiveUrl } from '../src/client/api.ts'
import { archiveNameOf, collectZipEntries } from '../src/archive-route.ts'
import { crc32, buildZip, type ZipEntry } from '../src/zip.ts'
import { SidebarError } from '../src/wire.ts'
import type { SidebarWebRoute, SidebarWebUpgradeRoute } from '../src/context-types.ts'
/** One parsed central-directory row + its local payload. */
interface ParsedEntry {
name: string
method: number
crc: number
compressedSize: number
size: number
flags: number
externalAttributes: number
isDirectory: boolean
data: Buffer
}
/**
* Minimal ZIP reader: locate the EOCD from the tail, walk the central
* directory, then read each local header's payload. Enough to verify names
* (UTF-8), methods, CRCs, sizes and both compression branches.
*/
function readZip(archive: Buffer): ParsedEntry[] {
const eocdAt = archive.lastIndexOf(Buffer.from([0x50, 0x4B, 0x05, 0x06]))
if (eocdAt < 0) throw new Error('no EOCD')
if (eocdAt + 22 !== archive.length) throw new Error('EOCD is not the last record')
const count = archive.readUInt16LE(eocdAt + 10)
const directorySize = archive.readUInt32LE(eocdAt + 12)
const directoryAt = archive.readUInt32LE(eocdAt + 16)
if (count > 0 && archive.readUInt32LE(directoryAt) !== 0x02014B50) throw new Error('bad central directory signature')
if (directoryAt + directorySize > eocdAt) throw new Error('central directory overruns the EOCD')
const entries: ParsedEntry[] = []
let cursor = directoryAt
for (let index = 0; index < count; index += 1) {
if (archive.readUInt32LE(cursor) !== 0x02014B50) throw new Error(`bad central header ${index}`)
const flags = archive.readUInt16LE(cursor + 8)
const method = archive.readUInt16LE(cursor + 10)
const crc = archive.readUInt32LE(cursor + 16)
const compressedSize = archive.readUInt32LE(cursor + 20)
const size = archive.readUInt32LE(cursor + 24)
const nameLength = archive.readUInt16LE(cursor + 28)
const extraLength = archive.readUInt16LE(cursor + 30)
const commentLength = archive.readUInt16LE(cursor + 32)
const externalAttributes = archive.readUInt32LE(cursor + 38)
const localAt = archive.readUInt32LE(cursor + 42)
const name = archive.subarray(cursor + 46, cursor + 46 + nameLength).toString('utf8')
if (archive.readUInt32LE(localAt) !== 0x04034B50) throw new Error(`bad local header for ${name}`)
const localNameLength = archive.readUInt16LE(localAt + 26)
const localExtraLength = archive.readUInt16LE(localAt + 28)
if (archive.readUInt32LE(localAt + 14) !== crc) throw new Error(`local CRC mismatch for ${name}`)
if (archive.readUInt32LE(localAt + 18) !== compressedSize) throw new Error(`local compressed size mismatch for ${name}`)
if (archive.readUInt32LE(localAt + 22) !== size) throw new Error(`local size mismatch for ${name}`)
const payloadAt = localAt + 30 + localNameLength + localExtraLength
const payload = archive.subarray(payloadAt, payloadAt + compressedSize)
entries.push({
name,
method,
crc,
compressedSize,
size,
flags,
externalAttributes,
isDirectory: name.endsWith('/'),
data: method === 8 ? inflateRawSync(payload) : Buffer.from(payload),
})
cursor += 46 + nameLength + extraLength + commentLength
}
return entries
}
/** /sidebar/archive mounted against a fake context, as the host runs it. */
function mountArchive(): SidebarWebRoute {
const routes: SidebarWebRoute[] = []
const ctx = {
webRuntime: { trustedHosts: [] },
webServer: {
register: (route: SidebarWebRoute) => { routes.push(route); return () => {} },
registerUpgrade: (route: SidebarWebUpgradeRoute) => { void route; return () => {} },
},
sessions: { get: () => undefined },
tools: { register: () => () => {} },
effect: (fn: () => void | (() => void)) => { fn() },
inject: () => () => {},
on: () => () => {},
get: () => undefined,
}
apply(ctx as never)
const route = routes.find(candidate => candidate.path === '/sidebar/archive')
if (route === undefined) throw new Error('test setup: /sidebar/archive route not registered')
return route
}
/** One GET against a mounted route, collecting raw bytes. */
async function get(route: SidebarWebRoute, url: string): Promise<{ status: number; headers: Record<string, string>; body: Buffer }> {
const out: { status: number; headers: Record<string, string>; chunks: Buffer[] } = { status: 200, headers: {}, chunks: [] }
const req = { method: 'GET', url, headers: { host: '127.0.0.1:3080' } } as never
const res = {
writeHead: (status: number, headers: Record<string, string> = {}) => { out.status = status; out.headers = headers },
end: (chunk?: Buffer | string) => { if (chunk !== undefined) out.chunks.push(Buffer.from(chunk)) },
} as never
await route.handler(req, res)
return { status: out.status, headers: out.headers, body: Buffer.concat(out.chunks) }
}
/** A temp workspace (plus an outside sibling) removed after each test. */
const roots: string[] = []
function tempRoot(): string {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-zip-'))
roots.push(root)
return root
}
afterEach(() => {
while (roots.length > 0) rmSync(roots.pop()!, { recursive: true, force: true })
})
describe('buildZip', () => {
it('round-trips a deflated file: name, content and CRC-32', async () => {
const root = tempRoot()
const path = join(root, 'hello.txt')
const content = 'hello zip\n'.repeat(200)
writeFileSync(path, content)
const archive = await buildZip([{ path, name: 'hello.txt' }])
const entries = readZip(archive)
expect(entries).toHaveLength(1)
const entry = entries[0]!
expect(entry.name).toBe('hello.txt')
expect(entry.method).toBe(8)
expect(entry.data.toString('utf8')).toBe(content)
expect(entry.crc).toBe(crc32(Buffer.from(content)))
expect(entry.size).toBe(Buffer.byteLength(content))
expect(entry.isDirectory).toBe(false)
})
it('stores incompressible data (method 0) and marks UTF-8 names (bit 11)', async () => {
const root = tempRoot()
const path = join(root, 'random.bin')
// High-entropy bytes: deflateRaw expands them (4096 → ~4100), so the
// writer must fall back to `store`. Generated from a fixed seed so the
// case stays deterministic.
const random = Buffer.alloc(4096)
let state = 0x9E3779B9
for (let i = 0; i < random.length; i += 1) {
state = (Math.imul(state, 1664525) + 1013904223) >>> 0
random[i] = (state >>> 16) & 0xFF
}
writeFileSync(path, random)
const archive = await buildZip([{ path, name: '数据/随机.bin' }])
const entries = readZip(archive)
expect(entries).toHaveLength(1)
const entry = entries[0]!
expect(entry.method).toBe(0)
expect(entry.name).toBe('数据/随机.bin')
expect((entry.flags & 0x0800) !== 0).toBe(true)
expect(entry.data.equals(random)).toBe(true)
expect(entry.crc).toBe(crc32(random))
})
it('writes directory rows with a trailing slash, zero payload and the dir attribute', async () => {
const root = tempRoot()
mkdirSync(join(root, 'nested'))
writeFileSync(join(root, 'nested', 'a.txt'), 'a')
const archive = await buildZip([
{ path: join(root, 'nested'), name: 'nested', isDir: true },
{ path: join(root, 'nested', 'a.txt'), name: 'nested/a.txt' },
])
const entries = readZip(archive)
expect(entries.map(entry => entry.name)).toEqual(['nested/', 'nested/a.txt'])
const dir = entries[0]!
expect(dir.isDirectory).toBe(true)
expect(dir.size).toBe(0)
expect(dir.crc).toBe(0)
// The external-attributes word carries the Unix mode in the high half and
// the MS-DOS directory bit in the low half: without the mode Info-ZIP
// extracts every member as mode 000.
expect(dir.externalAttributes & 0x10).toBe(0x10)
expect(dir.externalAttributes >>> 16).toBe(0o40755)
expect(entries[1]!.externalAttributes & 0x10).toBe(0)
expect(entries[1]!.externalAttributes >>> 16).toBe(0o100644)
})
it('accepts an empty directory set and produces a valid empty archive', async () => {
const archive = await buildZip([])
expect(readZip(archive)).toEqual([])
expect(archive.readUInt32LE(archive.length - 22)).toBe(0x06054B50)
})
it('rejects an over-limit entry count before reading anything', async () => {
const root = tempRoot()
const path = join(root, 'a.txt')
writeFileSync(path, 'a')
await expect(buildZip([{ path, name: 'a.txt' }], { maxEntries: 0 })).rejects.toThrow(SidebarError)
await expect(buildZip([{ path, name: 'a.txt' }], { maxEntries: 0 })).rejects.toMatchObject({ code: 'fs-error' })
})
it('rejects an over-limit payload with fs-error', async () => {
const root = tempRoot()
const path = join(root, 'big.txt')
writeFileSync(path, 'x'.repeat(4096))
await expect(buildZip([{ path, name: 'big.txt' }], { maxBytes: 1024 }))
.rejects.toMatchObject({ code: 'fs-error' })
})
it('reports an unreadable source as fs-error and refuses traversal names', async () => {
const root = tempRoot()
await expect(buildZip([{ path: join(root, 'missing.txt'), name: 'missing.txt' }]))
.rejects.toMatchObject({ code: 'fs-error' })
await expect(buildZip([{ path: join(root, 'x'), name: '../escape.txt' }]))
.rejects.toMatchObject({ code: 'bad-request' })
})
it('passes `unzip -t` when the binary exists (skipped otherwise)', async () => {
const probe = spawnSync('unzip', ['-v'], { encoding: 'utf8' })
if (probe.error !== undefined || probe.status !== 0) return
const root = tempRoot()
const content = 'unzip parity\n'.repeat(100)
writeFileSync(join(root, 'a.txt'), content)
mkdirSync(join(root, 'dir'))
writeFileSync(join(root, 'dir', 'b.txt'), content)
const archive = await buildZip([
{ path: join(root, 'a.txt'), name: 'a.txt' },
{ path: join(root, 'dir'), name: 'dir', isDir: true },
{ path: join(root, 'dir', 'b.txt'), name: 'dir/b.txt' },
])
const file = join(root, 'out.zip')
writeFileSync(file, archive)
const result = spawnSync('unzip', ['-t', file], { encoding: 'utf8' })
expect(result.status, result.stderr).toBe(0)
expect(result.stdout).toContain('No errors detected')
// `-t` only checks CRCs; extract too, so a broken external-attributes word
// (Info-ZIP writes mode 000 files) cannot pass unnoticed.
const extracted = join(root, 'out')
const unpack = spawnSync('unzip', ['-o', file, '-d', extracted], { encoding: 'utf8' })
expect(unpack.status, unpack.stderr).toBe(0)
const inMode = statSync(join(root, 'a.txt')).mode & 0o777
const outMode = statSync(join(extracted, 'a.txt')).mode & 0o777
expect(outMode).toBe(inMode & 0o644)
expect(readFileSync(join(extracted, 'a.txt'), 'utf8')).toBe(content)
expect(readFileSync(join(extracted, 'dir', 'b.txt'), 'utf8')).toBe(content)
})
})
describe('collectZipEntries', () => {
it('walks directories depth-first in name order and bounds the row count', async () => {
const root = tempRoot()
mkdirSync(join(root, 'd'))
writeFileSync(join(root, 'a.txt'), 'a')
writeFileSync(join(root, 'd', 'b.txt'), 'b')
const entries: ZipEntry[] = []
await collectZipEntries(root, 'root', entries)
expect(entries.map(entry => entry.name)).toEqual(['root', 'root/a.txt', 'root/d', 'root/d/b.txt'])
expect(entries[0]!.isDir).toBe(true)
const bounded: ZipEntry[] = []
await expect(collectZipEntries(root, 'root', bounded, 2))
.rejects.toMatchObject({ code: 'fs-error' })
// The bound stops the walk early instead of filling the list first.
expect(bounded.length).toBeLessThanOrEqual(2)
})
it('treats an unreadable row as fs-error', async () => {
const root = tempRoot()
const entries: ZipEntry[] = []
await expect(collectZipEntries(join(root, 'missing'), 'missing', entries))
.rejects.toMatchObject({ code: 'fs-error' })
})
})
describe('archiveNameOf', () => {
it('strips separators / quotes / control chars and applies the .zip suffix once', () => {
expect(archiveNameOf(null)).toBe('archive.zip')
expect(archiveNameOf('')).toBe('archive.zip')
expect(archiveNameOf(' ')).toBe('archive.zip')
expect(archiveNameOf('docs')).toBe('docs.zip')
expect(archiveNameOf('docs.zip')).toBe('docs.zip')
expect(archiveNameOf('DOCS.ZIP')).toBe('DOCS.ZIP')
// Path separators, traversal dots and quotes never survive.
expect(archiveNameOf('../../etc/passwd')).toBe('etcpasswd.zip')
expect(archiveNameOf('a\\b".zip')).toBe('ab.zip')
expect(archiveNameOf('bad\u0000name\u001F.zip')).toBe('badname.zip')
// Length is capped, and a bare ".zip" input falls back to the default.
expect(archiveNameOf(`${'x'.repeat(300)}.zip`).length).toBe(124)
expect(archiveNameOf('.zip')).toBe('archive.zip')
})
})
describe('/sidebar/archive route', () => {
it('archiveUrl builds the GET URL the route parses (repeated path, encoded)', () => {
const url = archiveUrl({ sessionId: 's-1', cwd: '/work tree' }, ['/work tree/a b.txt', '/work tree/子目录'], 'my zip.zip')
const parsed = new URL(url, 'http://dsh.internal')
expect(parsed.pathname).toBe('/sidebar/archive')
expect(parsed.searchParams.get('sessionId')).toBe('s-1')
expect(parsed.searchParams.get('cwd')).toBe('/work tree')
expect(parsed.searchParams.get('name')).toBe('my zip.zip')
expect(parsed.searchParams.getAll('path')).toEqual(['/work tree/a b.txt', '/work tree/子目录'])
// A scope without a cwd omits the parameter entirely (same as downloadUrl).
expect(archiveUrl({ sessionId: 's-2' }, ['/a'], 'x.zip')).toBe('/sidebar/archive?sessionId=s-2&name=x.zip&path=%2Fa')
})
it('zips a selected file and a selected directory, walking it recursively', async () => {
const root = tempRoot()
const workspace = join(root, 'workspace')
mkdirSync(join(workspace, 'src', 'deep'), { recursive: true })
writeFileSync(join(workspace, 'src', 'index.ts'), 'export {}\n')
writeFileSync(join(workspace, 'src', 'deep', 'nested.ts'), 'nested\n')
writeFileSync(join(workspace, 'notes.md'), '# notes\n')
const route = mountArchive()
const url = `/sidebar/archive?sessionId=s-zip&cwd=${encodeURIComponent(workspace)}`
+ `&name=${encodeURIComponent('我的打包.zip')}`
+ `&path=${encodeURIComponent(join(workspace, 'src'))}`
+ `&path=${encodeURIComponent(join(workspace, 'notes.md'))}`
const response = await get(route, url)
expect(response.status).toBe(200)
expect(response.headers['content-type']).toBe('application/zip')
expect(response.headers['content-disposition']).toBe('attachment; filename="我的打包.zip"')
expect(Number(response.headers['content-length'])).toBe(response.body.byteLength)
const entries = readZip(response.body)
expect(entries.map(entry => entry.name)).toEqual([
'src/',
'src/deep/',
'src/deep/nested.ts',
'src/index.ts',
'notes.md',
])
const byName = new Map(entries.map(entry => [entry.name, entry]))
expect(byName.get('src/index.ts')!.data.toString('utf8')).toBe('export {}\n')
expect(byName.get('notes.md')!.data.toString('utf8')).toBe('# notes\n')
})
it('never follows a symlink out of the workspace', async () => {
const root = tempRoot()
const workspace = join(root, 'workspace')
const outside = join(root, 'outside')
mkdirSync(workspace)
mkdirSync(outside)
writeFileSync(join(outside, 'secret.txt'), 'secret')
try {
symlinkSync(outside, join(workspace, 'link'))
// A file INSIDE the workspace, so the archive itself is readable.
writeFileSync(join(workspace, 'keep.txt'), 'keep')
} catch {
return // symlink creation needs privileges on Windows
}
const route = mountArchive()
const scope = `sessionId=s-zip&cwd=${encodeURIComponent(workspace)}`
// Selecting the escaping link refuses at the workspace fence (the route
// canonicalizes before walking), so its target is never read…
const linked = await get(route, `/sidebar/archive?${scope}&path=${encodeURIComponent(join(workspace, 'link'))}`)
expect(linked.status).toBe(403)
// …and walking the containing directory reports the link as an entry-less
// row instead of descending into it.
const walked = await get(route, `/sidebar/archive?${scope}&path=${encodeURIComponent(workspace)}`)
expect(walked.status).toBe(200)
const entries = readZip(walked.body)
expect(entries.map(entry => entry.name)).toEqual(['workspace/', 'workspace/keep.txt'])
expect(entries.some(entry => entry.data.toString('utf8').includes('secret'))).toBe(false)
})
it('refuses a path outside the workspace with 403', async () => {
const root = tempRoot()
const workspace = join(root, 'workspace')
const outside = join(root, 'outside')
mkdirSync(workspace)
mkdirSync(outside)
writeFileSync(join(outside, 'secret.txt'), 'secret')
const route = mountArchive()
const url = `/sidebar/archive?sessionId=s-zip&cwd=${encodeURIComponent(workspace)}`
+ `&path=${encodeURIComponent(join(outside, 'secret.txt'))}`
const response = await get(route, url)
expect(response.status).toBe(403)
expect(JSON.parse(response.body.toString('utf8'))).toMatchObject({ ok: false, error: { code: 'forbidden' } })
})
it('rejects a missing path (and a missing sessionId) with 400', async () => {
const root = tempRoot()
const workspace = join(root, 'workspace')
mkdirSync(workspace)
const route = mountArchive()
const noPath = await get(route, `/sidebar/archive?sessionId=s-zip&cwd=${encodeURIComponent(workspace)}`)
expect(noPath.status).toBe(400)
expect(JSON.parse(noPath.body.toString('utf8'))).toMatchObject({ ok: false, error: { code: 'bad-request' } })
const noSession = await get(route, `/sidebar/archive?cwd=${encodeURIComponent(workspace)}&path=${encodeURIComponent(workspace)}`)
expect(noSession.status).toBe(400)
})
it('sanitizes the download name (separators stripped, default and suffix applied)', async () => {
const root = tempRoot()
const workspace = join(root, 'workspace')
mkdirSync(workspace)
writeFileSync(join(workspace, 'a.txt'), 'a')
const route = mountArchive()
const path = encodeURIComponent(join(workspace, 'a.txt'))
const scope = `sessionId=s-zip&cwd=${encodeURIComponent(workspace)}&path=${path}`
const traversal = await get(route, `/sidebar/archive?${scope}&name=${encodeURIComponent('../evil")b.zip')}`)
expect(traversal.headers['content-disposition']).toBe('attachment; filename="evil)b.zip"')
const bare = await get(route, `/sidebar/archive?${scope}&name=docs`)
expect(bare.headers['content-disposition']).toBe('attachment; filename="docs.zip"')
const fallback = await get(route, `/sidebar/archive?${scope}`)
expect(fallback.headers['content-disposition']).toBe('attachment; filename="archive.zip"')
})
it('rejects a non-GET method', async () => {
const route = mountArchive()
const out: { status: number; body: string } = { status: 200, body: '' }
const req = { method: 'POST', url: '/sidebar/archive?sessionId=s&path=/x', headers: { host: '127.0.0.1:3080' } } as never
const res = {
writeHead: (status: number) => { out.status = status },
end: (chunk?: string) => { out.body += String(chunk ?? '') },
} as never
await route.handler(req, res)
expect(out.status).toBe(405)
})
})