From f49bad2279dec003936b47df497176a745480b9d Mon Sep 17 00:00:00 2001 From: Zabo Date: Wed, 4 Nov 2026 16:55:51 +0800 Subject: [PATCH] feat(git): show every child repository in the Git panel with a visible switcher A container workspace (a project directory that is not itself a repository) can hold several independent repositories. Discovery and `git.status` already report all of them; the panel listed them only in the "more actions -> repository" submenu, so nothing on screen said the others existed and the body silently rendered repositories[0]. Render one chip per discovered root above the Changes section, mark the root the panel is pinned to, and switch through the existing chooseRepo so reads, mutations and the commit graph follow the selection. A single repository workspace renders no row; the menu entry stays. --- CHANGELOG.md | 2 + CHANGELOG_EN.md | 2 + src/client/changes/GitLens.tsx | 33 ++++++++ src/client/changes/changes.module.css | 42 ++++++++++ tests/git-repo-switcher.spec.tsx | 106 ++++++++++++++++++++++++++ 5 files changed, 185 insertions(+) create mode 100644 tests/git-repo-switcher.spec.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index a98b5542..3fc34c41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ ### 未发布 +- 🗂 **容器工作区里能直接看到并切换每个子仓库**:`git.status` 早就把发现到的全部根放在 `repositories` 里,但 Git 面板只在「⋯(更多操作)→ 仓库」二级菜单中列出它们——面板顶部既没有仓库名也没有数量,正文默认渲染 `repositories[0]`,于是有三个项目的工作区看起来只有一个。现在发现多个根时,「更改」区块上方渲染一行仓库胶囊(`data-scm-repos`,每个根一个 `[data-scm-repo]`),当前检出以 `[data-active="true"]` 高亮;点击走既有的 `chooseRepo`,读数、写操作与提交图继续被钉在选中的根上。单一仓库工作区不渲染这一行,原菜单入口保留。 + - 🧪 `tests/git-repo-switcher.spec.tsx` 新增 3 例:多仓库逐个列出并可切换、同一检出的反斜杠/尾斜杠/大小写写法只算一个、单仓库不渲染切换行。 - ⚡ **大 Markdown 的 Mermaid 预览不再卡死渲染器(chunk 内测量隔离到沙箱 iframe)**:Mermaid 用 `SVGElement.getBBox()` 量文字,测量节点挂在 `document.body` 上 → 每次测量都刷新整个 DSH 文档布局。真机实测一次 `getBBox` **59–75 ms**(15,418 节点),空 iframe 里只要 **1 ms**;31 张图因此阻塞主线程 >20 s,触发桌面壳看门狗杀渲染器,恢复标签页后循环卡死。现在图表改在隐藏的 `sandbox="allow-scripts"` iframe(blob: 自包含 mermaid UMD + 协议)里渲染,父侧只做 postMessage 收发与 SVG 清洗:**单图 1,500–7,300 ms → 30–104 ms,31 图约 5 s 内完成**,客户端 mermaid chunk 同时从 **7.04 MB → 3.69 MB**。另加共享渲染队列(可见/近视口优先,其余 `requestIdleCallback` 逐张补齐,两次之间让出 16 ms 主线程;**所有图最终都会渲染成图,不再退化为代码块**)与按围栏行数预留高度的占位骨架。设计与实测见 [docs/plans/2026-10-23-mermaid-iframe-isolation.md](docs/plans/2026-10-23-mermaid-iframe-isolation.md)。 - ⚡ **大文档滚动流畅性:渲染让位于滚动、隐藏页签不空转、摘掉全量 DOM 扫描**:图表渲染队列在滚动期间暂停(停止滚动 350 ms 后恢复),并且只服务当前可见的预览——隐藏页签里的图表保持占位、切回时才渲染;`Markdown` 变更触发的两次全量扫描(内联 HTML pass、标题锚点 pass)由「每次 mutation 跑一遍」(实测 8–15 ms/次)改为 80 ms 合并一次;打开文档时的近视口判断改为先批量读 rect、再统一写入,去掉每张图一次强制布局;`.mermaidWrap` 增加 `content-visibility: auto` + `contain-intrinsic-size` + `contain: layout paint style`,视口外的图表不再参与布局与绘制。滚动时不再有后台渲染、全量扫描与视口外 SVG 重绘抢主线程;图表仍会在滚动停止后或进入视口时补齐,不退化为代码块。 - 🐞 **图表渲染失败时直接显示 mermaid 的解析错误**:之前只显示通用「Mermaid 渲染失败」+ 源码块(完整错误只在 hover title 里)。现在错误条下方直接给出 mermaid 报错的首两行(如 `Parse error on line 10 ... Expecting 'SEMI', ... got 'UNICODE_TEXT'`),配合下方源码可快速定位坏围栏;错误信息仍完整保留在 title 中。 diff --git a/CHANGELOG_EN.md b/CHANGELOG_EN.md index fd180998..eea6f9b5 100644 --- a/CHANGELOG_EN.md +++ b/CHANGELOG_EN.md @@ -6,6 +6,8 @@ ### Unreleased +- 🗂 **A container workspace now shows and switches every child repository**: `git.status` has always reported every discovered root in `repositories`, but the Git panel only listed them in the "More actions → Repository" submenu — no name and no count at the top of the panel, and the body rendered `repositories[0]`, so a workspace holding three projects looked like it had one. When more than one root is discovered, a chip row (`data-scm-repos`, one `[data-scm-repo]` per root) now renders above the Changes section with the current checkout marked `[data-active="true"]`; clicking a chip goes through the existing `chooseRepo`, so reads, mutations and the commit graph stay pinned to the chosen root. A single-repository workspace renders no row, and the existing menu entry stays. + - 🧪 `tests/git-repo-switcher.spec.tsx` adds three cases: every root listed and switchable, backslash/trailing-slash/case spellings folded to one checkout, and no row for a single-repository workspace. - 🪟 **Windows + WSL workspaces: a UNC path is no longer folded into a drive-relative one.** Re-spelling paths on a Windows base folded every run of separators into one `\`, which also folded the UNC prefix of `\\wsl.localhost\\...` into `\wsl.localhost\...`; the host's `path.resolve()` then anchored that on its own process drive (`C:\wsl.localhost\...`), so every file opened from a WSL workspace failed with ENOENT. The UNC prefix now survives and only the rest is folded (drive paths are unchanged). - 🧪 `tests/worktree-address.spec.ts` adds one case: UNC absolute, workspace-relative, and forward-slash spellings all keep the two leading separators. - 🗂 **A session cwd that is a Git repository subdirectory is no longer lifted to the repository top** ([#1024](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1024), [#1080](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1080); contributor PR [#1070](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1070) @hy5424): the sidebar root was replaced with `git rev-parse --show-toplevel`, so a relative file link in chat resolved to `/` instead of `//` (ENOENT) and file search used the wrong root. The session cwd is now the root as it stands; only linked-worktree evidence from the session's own tool calls replaces it. The cwd is canonicalized first, so symlinked spellings (`/var` vs `/private/var`) cannot make a nested worktree look outside the workspace (#952). diff --git a/src/client/changes/GitLens.tsx b/src/client/changes/GitLens.tsx index 48c0bf60..d62defec 100644 --- a/src/client/changes/GitLens.tsx +++ b/src/client/changes/GitLens.tsx @@ -68,6 +68,18 @@ function errorMessage(reason: unknown): string { return reason instanceof Error ? reason.message : String(reason) } +/** One checkout root in the form comparisons use: `git rev-parse` reports + * forward slashes, React state may carry the shell's backslashes, Windows + * folds case, and a trailing separator means the same directory. */ +function rootKey(value: string | undefined): string { + return (value ?? '').replaceAll('\\', '/').replace(/\/+$/, '').toLowerCase() +} + +/** Whether two spellings name the SAME checkout root. */ +function sameRepoRoot(left: string | undefined, right: string | undefined): boolean { + return rootKey(left) === rootKey(right) +} + /** * Whether two inventory listings say the same thing. Every listing pass answers * with a fresh array of fresh rows, so identity alone would republish on each @@ -1088,6 +1100,27 @@ export function GitLens(props: GitLensProps) { {snapshot !== null && !isRepo && {t('notRepo')}} {snapshot?.truncated === true && {t('statusTruncated')}} + {/* A container workspace can hold several independent repositories, and + every view below is pinned to ONE of them — without this row the + panel silently shows the first root, so nothing on screen says the + others exist. The switcher is not a second source of truth: + `repoChoices` comes from the status snapshot, `chooseRepo` re-pins + the scope (reads, writes, graph) to the clicked root. */} + {isRepo && repoChoices.length > 1 && ( +
+ {repoChoices.map(root => { + const isActive = sameRepoRoot(root, repoRoot ?? snapshot?.root) + return ( + + ) + })} +
+ )} + {isRepo && (
diff --git a/src/client/changes/changes.module.css b/src/client/changes/changes.module.css index b45d2b37..70e2ae7a 100644 --- a/src/client/changes/changes.module.css +++ b/src/client/changes/changes.module.css @@ -60,6 +60,48 @@ .scmHeader:hover .scmActions, .scmHeader:focus-within .scmActions { opacity: 1; } @media (hover: none) { .scmActions { opacity: 1; } } +/* Child repositories of a workspace container: every view in this panel is + pinned to ONE root, so the switcher is the only surface that says the others + exist. One band above the sections, one chip per discovered root; it scrolls + sideways rather than wrapping so a deep root list cannot push the changes + away from the top of the pane. */ +.repoSwitcher { + flex: none; + display: flex; + align-items: center; + gap: 4px; + min-width: 0; + padding: 0 6px 2px; + overflow-x: auto; + overflow-y: hidden; + scrollbar-width: none; +} +.repoSwitcher::-webkit-scrollbar { display: none; } +.repoChip { + flex: none; + max-width: 160px; + min-height: 22px; + padding: 2px 8px; + border: 1px solid var(--dsw-alias-border-l1); + border-radius: 3px; + background: transparent; + color: var(--dsw-alias-label-secondary); + font: var(--dsw-font-xxxs-11); + text-align: left; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + cursor: pointer; +} +.repoChip:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); } +.repoChip[data-active='true'] { + border-color: var(--dsw-alias-border-l2); + background: var(--dsw-alias-interactive-bg-hover-accent); + color: var(--dsw-alias-label-primary); +} +.repoChip:disabled { opacity: 0.45; cursor: default; } +.repoChip:focus-visible { outline: 2px solid var(--dsw-alias-interactive-bg-hover-accent); outline-offset: -2px; } + /* Docked by the flex column above (a sibling of `.gitScroll`), plus sticky so it also survives the case where the host tab body itself scrolls the whole tab — the branch control must never leave the bottom of the pane. diff --git a/tests/git-repo-switcher.spec.tsx b/tests/git-repo-switcher.spec.tsx new file mode 100644 index 00000000..df8387ef --- /dev/null +++ b/tests/git-repo-switcher.spec.tsx @@ -0,0 +1,106 @@ +/** + * Multi-repository switcher in the Git lens (a workspace CONTAINER, i.e. a + * project directory that is not itself a repository but holds several). + * + * Contract: + * - `git.status` reports `repositories` (every discovered root). When it holds + * more than one, the lens renders one chip per root above the Changes + * section: label = `baseName(root)`, `[data-scm-repo]` = the absolute root. + * - Exactly one chip is marked `[data-active="true"]`: the root the panel is + * currently pinned to (`repoRoot`, or the resolved `status.root` before the + * user picks one). Both spellings of one checkout are the same root — + * forward/back slashes, a trailing separator and Windows case all fold. + * - Clicking another chip re-pins the scope through the same `chooseRepo` the + * ⋯ → 仓库 submenu uses, so the next status read carries that root and the + * switcher survives the following read (a selected child still reports the + * full `repositories` list). + * - A single-repository workspace renders NO switcher: the row must not steal + * vertical space from the ordinary case. + */ +// @vitest-environment jsdom +import { act } from 'react-dom/test-utils' +import { afterEach, expect, it, vi } from 'vitest' +import { api, type GitStatusResult, type SessionScope } from '../src/client/api.ts' +import { GitLens } from '../src/client/changes/GitLens.tsx' +import { createSidebarStore } from '../src/client/state.ts' +import { renderRoot, setupReactAct } from './test-utils.ts' + +setupReactAct() +afterEach(() => { vi.restoreAllMocks() }) + +const CWD = 'C:/work' +const ADMIN = 'C:/work-admin' +const DOCS = 'C:/work-docs' +const flush = async (): Promise => { await act(async () => { await Promise.resolve() }) } +const click = async (button: HTMLButtonElement): Promise => { await act(async () => { button.click() }) } +const chips = (container: HTMLElement): HTMLButtonElement[] => + [...container.querySelectorAll('[data-scm-repo]')] + +/** One container-workspace snapshot: the resolved root plus every discovered root. */ +const snapshot = (root: string, repositories: string[]): GitStatusResult => + ({ isRepo: true, branch: 'main', root, entries: [], repositories }) + +/** Mount the lens over a mocked host; `scopes` records every status request. */ +async function mount(options: { sessionId: string; repositories?: string[] }) { + const scopes: SessionScope[] = [] + const repositories = options.repositories ?? [CWD, ADMIN, DOCS] + vi.spyOn(api, 'gitStatus').mockImplementation(async scope => { + scopes.push(scope) + return snapshot(scope.repoRoot ?? CWD, repositories) + }) + vi.spyOn(api, 'gitWorktrees').mockResolvedValue([{ path: CWD, branch: 'main', current: true, changes: 0 }]) + vi.spyOn(api, 'gitBranch').mockResolvedValue({ current: 'main', names: ['main'] }) + vi.spyOn(api, 'gitCommitModel').mockResolvedValue({ pinned: false }) + vi.spyOn(api, 'gitGraph').mockResolvedValue({ + isRepo: true, root: CWD, entries: [], branches: [], hasMore: false, snapshot: 'one', + }) + const view = renderRoot( + {}} onPreview={() => {}} />, + ) + await flush() + await flush() + return { ...view, scopes } +} + +it('lists every discovered repository and re-pins the scope to the clicked chip', async () => { + const view = await mount({ sessionId: 'scm-repos-multi' }) + const { container } = view + const row = container.querySelector('[data-scm-repos]')! + expect(row).not.toBeNull() + + const buttons = chips(container) + expect(buttons.map(button => button.dataset.scmRepo)).toEqual([CWD, ADMIN, DOCS]) + expect(buttons.map(button => button.textContent)).toEqual(['work', 'work-admin', 'work-docs']) + expect(buttons.map(button => button.getAttribute('data-active'))).toEqual(['true', null, null]) + expect(buttons[0]!.getAttribute('aria-pressed')).toBe('true') + + await click(buttons[1]!) + await flush() + await flush() + + // The click went through `chooseRepo`: the next status read targets that root... + expect(view.scopes.at(-1)?.repoRoot).toBe(ADMIN) + // ...and the switcher survived the following snapshot, still listing all roots. + const after = chips(container) + expect(after.map(button => button.dataset.scmRepo)).toEqual([CWD, ADMIN, DOCS]) + expect(after.map(button => button.getAttribute('data-active'))).toEqual([null, 'true', null]) +}) + +it('folds separator, trailing slash and case when marking the current checkout', async () => { + // The status snapshot reports the git spelling (`C:/work`); the root rendered + // into a chip may arrive as `C:\WORK\`. Both name the same checkout, so + // exactly one chip is active — a naive string compare would mark none. + const view = await mount({ sessionId: 'scm-repos-spelling', repositories: ['C:\\WORK\\', ADMIN] }) + const buttons = chips(view.container) + expect(buttons.map(button => button.dataset.scmRepo)).toEqual(['C:\\WORK\\', ADMIN]) + expect(buttons.map(button => button.getAttribute('data-active'))).toEqual(['true', null]) +}) + +it('renders no switcher for a single-repository workspace', async () => { + const view = await mount({ sessionId: 'scm-repos-single', repositories: [CWD] }) + expect(view.container.querySelector('[data-scm-repos]')).toBeNull() + expect(chips(view.container)).toEqual([]) + // The ordinary panel is intact: the Changes section is still there. + expect(view.container.querySelector('[data-scm-section="changes"]')).not.toBeNull() +})