feat(sidebar): 文件页与文件变动页 UIUX 重构 + 全局组件抽取

文件页(FileTree/TreePanel)
- Ctrl/Cmd 多选 + Shift 按可见行序连选(Esc/点空白/右键收敛),批量条支持复制路径、批量删除(共享 ConfirmDialog + 顺序 fsRemove)
- Git 变更着色:行名按状态上色 + M/A/D/U 徽标,目录按 dirHasChanges 着色,非仓库静默降级(数据来自共享 git 状态存储)
- 新建文件夹:fs.mkdir 路由 + mkdirWorkspaceEntry + 内联输入行(Enter/Esc/blur/IME 守卫)
- 性能:FileRow/DirRow memo(含反向验证)、搜索 hidden 停车不再卸载树、level 拉取世代守卫 + AbortController、fs.tree truncated 提示、use-dir-watch 入参 memo
- 拖拽上传视觉 token 化(硬编码色清零);可见性下传后隐藏页签停止轮询
- 右键「打开方式」改为复用 DSH 自带 open-in-app(宿主探测的关联应用 + 文件管理器显示)

文件变动页(changes/diff)
- 36px 头(宿主 SegmentedControl)+ 单一 ChangeRow + SectionHeader 分组 + 吸底提交条单状态行 + 历史独立空态
- 修掉:双份空态、暂存失败 unhandled rejection、手动刷新被丢、仓库切换刷新两次、worktree 清单缺 repoRoot、工作树被自动切走、预览持旧快照、恢复高度未 clamp、session ops 无谓轮询
- DiffPane/DiffTab 共用 use-git-diff;修掉 DiffPane 的 untracked 预览从不渲染

全局组件与宿主接入
- 新增 src/client/ui(IconButton/Chip/SectionHeader/Notice/ConfirmDialog/StatusBadge + 共享 git 状态存储)
- 新增 src/client/open-in-app.ts(宿主 open-in-app 客户端适配),删除自研 open-with 全链路与 open.external 路由
- 客户端 inject 补 remote / remote.session:缺声明时 ctx.get('remote').session 会抛出并把整个面板打成错误条(真实挂载 lane 抓到)
- 词典:+25 键 / -20 openWith* / -noChanges,20 份同步

验证:typecheck / lint / test(126 文件 1322 通过)/ build 全绿;
DSH_CMD='npx -y --package @deepseek-ai/dsh@0.1.7-rc.1 dsh' pnpm test:mount 7/7 通过(含 tab sweep 与 perf lane)
This commit is contained in:
Menghuan1918 committed 2026-09-28 00:27:31 +08:00
1 parent 606339f81e
commit 36fbc5ac7e
76 files changed
+6961 -3944

No files matched your search

+259 -23
View File
@@ -1,18 +1,23 @@
/**
* The unified changes tab shell: the lens switcher swaps the Git lens for
* the session lens, a Git-lens file row opens the shared preview pane
* (loaded through the mocked git API, rendered by the shared DiffFiles
* stack), and the session ops ride the mocked `changes.ops` poll — the
* event poll, the op fold and the badge cache all live in the tab.
* The unified changes tab shell: the 36px header's lens switcher swaps the
* Git lens for the session lens, a Git-lens file row opens the shared preview
* pane (loaded through the mocked git API, rendered by the shared DiffFiles
* stack), and the session ops ride the mocked `changes.ops` poll — the event
* poll, the op fold and the badge cache all live in the tab.
*
* The copy assertions below pin the zh strings (the test environment's
* navigator may be a real Node one with an en locale), so a bare substring
* check cannot accidentally pass on a different message.
*/
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { afterEach, 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 { ChangesTab, opCountOf } from '../src/client/changes/ChangesTab.tsx'
import { createSidebarStore } from '../src/client/state.ts'
import { api, type GitStatusResult, type GitWorktree } from '../src/client/api.ts'
import { t } from '../src/client/locales.ts'
import type { Context } from '../src/context-types.ts'
import type { SidebarTab } from '../src/client/state.ts'
@@ -42,7 +47,7 @@ function mount(root: Root, tab: SidebarTab = { id: 'git', type: 'git', title: 'C
store: createSidebarStore(),
scope: { sessionId: 'session', cwd: MAIN },
tab,
visible: false,
visible: true,
onOpenFile: () => {},
onOpenDiff: () => {},
}))
@@ -60,11 +65,21 @@ function mockGit(entries: Array<{ path: string; xy: string }>): void {
vi.spyOn(api, 'gitLog').mockResolvedValue([])
}
/** One lens tab of the header's segmented control. */
function lensTab(container: HTMLElement, label: string): HTMLButtonElement | undefined {
return [...container.querySelectorAll<HTMLButtonElement>('[role="tab"]')]
.find(tab => tab.textContent === label)
}
async function flushEffects(): Promise<void> {
await act(async () => { await Promise.resolve() })
await act(async () => { await Promise.resolve() })
}
beforeEach(() => {
Object.defineProperty(globalThis.navigator, 'language', { value: 'zh-CN', configurable: true })
})
afterEach(() => {
vi.restoreAllMocks()
document.body.innerHTML = ''
@@ -91,10 +106,11 @@ describe('ChangesTab', () => {
mount(root)
await flushEffects()
// Git lens: the file row from the mocked status (badge letter + path).
const row = [...container.querySelectorAll<HTMLButtonElement>('button')]
.find(button => button.textContent?.includes('src/a.ts'))
// Git lens: the changed-file row (badge letter + split name/directory).
const row = container.querySelector<HTMLButtonElement>('button[data-path="src/a.ts"]')
expect(row).toBeDefined()
expect(row!.textContent).toContain('a.ts')
expect(row!.textContent).toContain('src')
// Clicking the row previews inline (no diff tab minted): the shared
// renderer draws the added row.
@@ -103,11 +119,9 @@ describe('ChangesTab', () => {
expect(container.textContent).toContain('new')
// The preview survives a lens switch (it is a dock, not lens state).
const group = container.querySelector('[role="group"]')
const sessionButton = [...group!.querySelectorAll<HTMLButtonElement>('button')]
.find(button => button.getAttribute('aria-pressed') === 'false')
expect(sessionButton).toBeDefined()
await act(async () => { sessionButton!.click() })
const sessionTab = lensTab(container, t('changesSessionLens'))
expect(sessionTab).toBeDefined()
await act(async () => { sessionTab!.click() })
expect(container.textContent).toContain('src/a.ts')
} finally {
act(() => { root.unmount() })
@@ -127,13 +141,13 @@ describe('ChangesTab', () => {
mount(root)
await flushEffects()
// The tab pulled once on mount and published the op count.
// Opening the tab pulls once and publishes the op count (the tab-strip
// badge reads this cache).
expect(ops).toHaveBeenCalled()
expect(opCountOf('session')).toBe(2)
const group = container.querySelector('[role="group"]')
const buttons = [...group!.querySelectorAll<HTMLButtonElement>('button')]
await act(async () => { buttons[1]!.click() })
const sessionTab = lensTab(container, t('changesSessionLens'))
await act(async () => { sessionTab!.click() })
// Two files grouped, newest first; the write chip carries its count.
expect(container.textContent).toContain('src/b.ts')
expect(container.textContent).toContain('src/a.ts')
@@ -168,10 +182,8 @@ describe('ChangesTab', () => {
await flushEffects()
// Session lens: open the read op's preview.
const group = container.querySelector('[role="group"]')
const sessionButton = [...group!.querySelectorAll<HTMLButtonElement>('button')]
.find(button => button.getAttribute('aria-pressed') === 'false')
await act(async () => { sessionButton!.click() })
const sessionTab = lensTab(container, t('changesSessionLens'))
await act(async () => { sessionTab!.click() })
const row = container.querySelector<HTMLButtonElement>('button[data-op-kind="read"]')
expect(row).toBeDefined()
expect(container.textContent).toContain('notes.md')
@@ -201,4 +213,228 @@ describe('ChangesTab', () => {
container.remove()
}
})
it('renders exactly one clean empty state, and the history has its own', async () => {
mockGit([])
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
try {
mount(root)
await flushEffects()
// A clean repository says it ONCE: both sections (unstaged/staged) used
// to print their own "no changes" line under the same message.
const empties = [...container.querySelectorAll<HTMLElement>('[data-kind="empty"]')]
.map(node => node.textContent)
expect(empties).toEqual([t('changesClean'), t('changesNoHistory')])
// The two section bands are not rendered at all when nothing changed.
expect(container.querySelectorAll('[data-path]')).toHaveLength(0)
} finally {
act(() => { root.unmount() })
container.remove()
}
})
it('reports a failed stage action in the commit bar and catches it (no unhandled rejection)', async () => {
mockGit([{ path: 'src/a.ts', xy: ' M' }])
vi.spyOn(api, 'gitStage').mockRejectedValue(new Error('index.lock exists'))
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
try {
mount(root)
await flushEffects()
const stage = container.querySelector<HTMLButtonElement>(`button[aria-label="${t('stage')}"]`)
expect(stage).toBeDefined()
await act(async () => { stage!.click() })
await flushEffects()
const alert = [...container.querySelectorAll<HTMLElement>('[role="alert"]')]
.find(node => (node.textContent ?? '').includes(t('changesStageFailed', { message: 'index.lock exists' })))
expect(alert).toBeDefined()
// The ONE status line sits in the commit bar, directly under its input row.
const input = container.querySelector(`input[placeholder="${t('commitPlaceholder')}"]`)
expect(input).not.toBeNull()
expect(alert!.previousElementSibling?.contains(input)).toBe(true)
} finally {
act(() => { root.unmount() })
container.remove()
}
})
it('re-derives the previewed op from the latest fold when it settles', async () => {
mockGit([])
vi.spyOn(api, 'changesOps')
// The call starts running: no result yet, so the write has no payload.
.mockResolvedValueOnce({
events: [{ type: 'tool/call', seq: 1, time: 1, data: { name: 'write', callId: 'w1', arguments: JSON.stringify({ file_path: 'notes.txt' }) } }],
lastSeq: 1,
})
// The result lands in a later delta and settles the same callId.
.mockResolvedValueOnce({
events: [{ type: 'tool/result', seq: 2, time: 2, data: { message: { source: { kind: 'tool', callId: 'w1' }, content: [{ type: 'tool-result', content: [{ type: 'text', text: 'settled-body' }] }] } } }],
lastSeq: 2,
})
.mockResolvedValue({ events: [], lastSeq: 2 })
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
try {
mount(root)
await flushEffects()
const sessionTab = lensTab(container, t('changesSessionLens'))
await act(async () => { sessionTab!.click() })
const row = container.querySelector<HTMLButtonElement>('button[data-op-kind="write"]')
expect(row).toBeDefined()
await act(async () => { row!.click() })
await flushEffects()
expect(container.textContent).toContain(t('changesPriorUnknown'))
expect(container.textContent).not.toContain('settled-body')
// The header's refresh pulls the delta; the SAME preview must pick the
// settled payload up without the user re-clicking the row.
const refresh = container.querySelector<HTMLButtonElement>(`button[aria-label="${t('refresh')}"]`)
expect(refresh).not.toBeNull()
await act(async () => { refresh!.click() })
await flushEffects()
expect(container.textContent).toContain('settled-body')
} finally {
act(() => { root.unmount() })
container.remove()
}
})
it('shows a history failure instead of claiming there are no commits', async () => {
mockGit([])
vi.spyOn(api, 'gitLog').mockRejectedValue(new Error('bad object'))
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
try {
mount(root)
await flushEffects()
expect(container.textContent).toContain(t('historyLoadError'))
expect(container.textContent).not.toContain(t('changesNoHistory'))
} finally {
act(() => { root.unmount() })
container.remove()
}
})
it('keeps the preview redaction toggle working (a secret file masks by default)', async () => {
mockGit([])
localStorage.removeItem('dsh-sidebar:v1:redaction')
vi.spyOn(api, 'changesOps').mockResolvedValue({
events: [
{ type: 'tool/call', seq: 1, time: 1, data: { name: 'read', callId: 'r1', arguments: JSON.stringify({ file_path: 'C:/repo/main/.env' }) } },
{ type: 'tool/result', seq: 2, time: 2, data: { message: { source: { kind: 'tool', callId: 'r1' }, content: [{ type: 'tool-result', content: [{ type: 'text', text: '<content>1: OPENAI_API_KEY=sk-abcdefghijklmnop</content>' }] }] } } },
],
lastSeq: 2,
})
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
try {
mount(root)
await flushEffects()
const sessionTab = lensTab(container, t('changesSessionLens'))
await act(async () => { sessionTab!.click() })
const row = container.querySelector<HTMLButtonElement>('button[data-op-kind="read"]')
await act(async () => { row!.click() })
await flushEffects()
// Redaction is on by default: the secret never reaches the DOM.
expect(container.textContent).toContain('[REDACTED]')
expect(container.textContent).not.toContain('sk-abcdefghijklmnop')
// The kit toggle (a Chip) turns it off, and only then does the raw value
// render; toggling back masks it again.
const byLabel = (label: string): HTMLButtonElement | undefined =>
[...container.querySelectorAll<HTMLButtonElement>('button')]
.find(button => (button.textContent ?? '') === label)
const on = byLabel(t('changesRedactOnLabel'))
expect(on).toBeDefined()
await act(async () => { on!.click() })
await flushEffects()
expect(container.textContent).toContain('sk-abcdefghijklmnop')
const off = byLabel(t('changesRedactOffLabel'))
expect(off).toBeDefined()
await act(async () => { off!.click() })
await flushEffects()
expect(container.textContent).not.toContain('sk-abcdefghijklmnop')
} finally {
act(() => { root.unmount() })
container.remove()
localStorage.removeItem('dsh-sidebar:v1:redaction')
}
})
it('clamps the restored preview height to the pane bounds', async () => {
mockGit([{ path: 'src/a.ts', xy: ' M' }])
vi.spyOn(api, 'gitDiff').mockResolvedValue({
diff: 'diff --git a/src/a.ts b/src/a.ts\n--- a/src/a.ts\n+++ b/src/a.ts\n@@ -1 +1 @@\n-old\n+new\n',
})
/** Open the pane with one persisted height and read back the rendered one. */
const paneHeightFor = async (previewH: number): Promise<string | undefined> => {
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
try {
mount(root, { id: 'git', type: 'git', title: 'Changes', meta: { previewH } })
await flushEffects()
const row = container.querySelector<HTMLButtonElement>('button[data-path="src/a.ts"]')
expect(row).not.toBeNull()
await act(async () => { row!.click() })
await flushEffects()
return container.querySelector<HTMLElement>('[role="separator"]')?.parentElement?.style.height
} finally {
act(() => { root.unmount() })
container.remove()
}
}
// A height saved under a taller window cannot open past the pane's cap...
expect(await paneHeightFor(5000)).toBe(`${String(Math.round(window.innerHeight * 0.7))}px`)
// ...and an unusably small one is raised to the content minimum.
expect(await paneHeightFor(50)).toBe('140px')
})
it('polls the session events only while the session lens is on screen', async () => {
vi.useFakeTimers()
mockGit([])
const ops = vi.spyOn(api, 'changesOps').mockResolvedValue({ events: [], lastSeq: 0 })
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
try {
mount(root)
await flushEffects()
// Opening the tab is one catch-up pull (the badge count follows it).
expect(ops).toHaveBeenCalledTimes(1)
await act(async () => { await vi.advanceTimersByTimeAsync(10_000) })
// The git lens has no use for the session event log: no cadence at all.
expect(ops).toHaveBeenCalledTimes(1)
const sessionTab = lensTab(container, t('changesSessionLens'))
await act(async () => { sessionTab!.click() })
await act(async () => { await vi.advanceTimersByTimeAsync(5_000) })
// On screen: the 2.5s delta cadence runs.
expect(ops.mock.calls.length).toBeGreaterThan(1)
} finally {
act(() => { root.unmount() })
container.remove()
vi.useRealTimers()
}
})
})