diff --git a/docs/external-plugin-guide.md b/docs/external-plugin-guide.md index ac15d199..38f68590 100644 --- a/docs/external-plugin-guide.md +++ b/docs/external-plugin-guide.md @@ -454,7 +454,7 @@ ctx.effect(() => { | id | order | single | hidden | 用途 | |---|---|---|---|---| | `editor` | 10 | 否(按 path 去重) | 否 | 唯一「文件窗口」(编辑/预览 + 资源管理)。chrome 恒合并形态:路径输入框 + 编辑器控件 + 可开关内嵌文件树(全局搜索 `fs.search`;状态存 `tab.meta.treeOpen/treeWidth`)。`editorExplorer`:关(默认)= 按 path 新开,无路径窗口 = 纯资源管理器;开 = 树点击/Enter 经 `updateTab` 原地切换(id/meta 不变),无路径窗口 = 带 chrome 空窗口。树右键「在新 Tab 中打开」「在侧边打开」(pane 右侧 split)。新会话 seed 空文件窗口(`title:'Files'`);旧 `explorer` tab 经 `sanitizeState` 迁移。树 listing 与文件名搜索应用 `explorerExclude` 排除模式(editor 卡片齿轮弹窗可编辑;host 侧过滤,匹配条目彻底移除且永不阻塞折叠);单目录链折叠为 `a/b/c` 面包屑行(POSIX 隐藏与排除条目不计入唯一子项判定) | -| `git` | 20 | 是 | 是(本轮文件操作数) | 「文件变动」统一 tab(id 保留 `git` 以兼容持久化布局):**Git 视角**(Source Control:独立折叠的 Changes / Graph;Changes 内为多行 Message + 仅填草稿的 Generate、Merge Changes → Staged Changes → Changes;真实 parent hashes 泳道图;常驻底栏为可点击分支 + `*`/`+`/`!` 标记、upstream 的 behind↓ / ahead↑ 及安全 Pull-then-Push 同步;Push/Pull 与 worktree·子仓库选择移入 More Actions;提交只消费已暂存项,冲突/空消息/无暂存时禁止,草稿按会话·仓库·worktree 隔离)+ **本轮文件视角**(原 file-trace:模型读/写/编辑实时折叠,按文件分组、类型筛选);会话事件经插件自有宿主路由 `changes.ops` 供给(live 日志优先、冷会话回放持久化记录,`afterSeq` 增量),badge 读 tab 轮询写入的同步缓存。两视角共用底部可拖拽预览面板(`tab.meta.lens/previewH` 持久化),diff 渲染统一走 `src/client/diff/`(`DiffRows`/`DiffFiles`:mod 配对 + 行内高亮 + 语法着色 + 上下文折叠);Git 目标可展开为独立 diff tab(落进工作台的 diff 分栏) | +| `git` | 20 | 是 | 是(本轮文件操作数) | 「文件变动」统一 tab(id 保留 `git` 以兼容持久化布局):**Git 视角**(Source Control:独立折叠的 Changes / Graph;Changes 内为多行 Message + 仅填草稿的 Generate、Merge Changes → Staged Changes → Changes(资源组也独立折叠,计数常驻标题最右,文件行整行 hover);Git 刷新仅留在 Changes 标题,外层本轮文件刷新保留;真实 parent hashes 泳道图;常驻底栏为可点击分支 + `*`/`+`/`!` 标记、upstream 的 behind↓ / ahead↑ 及安全 Pull-then-Push 同步;Push/Pull 与 worktree·子仓库选择移入 More Actions;提交只消费已暂存项,冲突/空消息/无暂存时禁止,草稿按会话·仓库·worktree 隔离)+ **本轮文件视角**(原 file-trace:模型读/写/编辑实时折叠,按文件分组、类型筛选);会话事件经插件自有宿主路由 `changes.ops` 供给(live 日志优先、冷会话回放持久化记录,`afterSeq` 增量),badge 读 tab 轮询写入的同步缓存。两视角共用底部可拖拽预览面板(`tab.meta.lens/previewH` 持久化),diff 渲染统一走 `src/client/diff/`(`DiffRows`/`DiffFiles`:mod 配对 + 行内高亮 + 语法着色 + 上下文折叠);Git 目标可展开为独立 diff tab(落进工作台的 diff 分栏) | | `subagent` | 30 | 是 | 否 | 任务管理(工作流图/树、团队任务板、后台任务抽屉) | | `sidechat` | 35 | 否(`sidechat:`,按 `meta.threadId` 去重) | 否 | 侧边对话(每对话一 Tab):打开即建空线程(首条消息赢得标签并同步标题);线程 = 插件自建子会话(种子继承父会话上下文,进行中回合以 `interrupted` 闭合;种子带合法 `subagent/descriptor`,SubagentView 按 `Side: ` 前缀过滤),`origin:'subagent'` 隐藏于主列表;走 `/sidebar/api/sidechat.*` 路由;头部菜单切换/重开(`parkSidechatReopen` + 确定性 id),关 Tab 释放 live agent;重开经 `collectOwnEvents` 回源到种子边界;「保存为新会话」= `session.fork`(`this` 敏感)。[设计文档](plans/2026-08-20-sidechat-tab-design.md) | | `diff` | -1 | 否(按 id 去重) | 是 | 差异查看(changes tab 的预览面板「展开为独立页签」触发,同一渲染栈) | diff --git a/src/client/changes/ChangesTab.tsx b/src/client/changes/ChangesTab.tsx index 48c369c0..788cc13f 100644 --- a/src/client/changes/ChangesTab.tsx +++ b/src/client/changes/ChangesTab.tsx @@ -2,8 +2,8 @@ * The unified changes tab: one tab, two lenses on "what changed?" — Git * (repository truth: staged/unstaged files, commit box, history) and the * session round (agent truth: every file the model read, wrote, or edited). - * A 36px header carries the host {@link SegmentedControl} and the current - * lens's refresh action; both lenses preview their selections in a shared + * A 36px header carries the host {@link SegmentedControl} and the session + * lens's refresh action (Git refresh lives in Changes); both lenses share a * resizable bottom pane ({@link DiffPane}), and git targets expand into the * dedicated diff tab docked in the workbench's diff pane. The active lens and * the pane height persist in the tab's meta, so the tab reopens exactly where @@ -72,8 +72,6 @@ export function ChangesTab({ ctx, store, scope, tab, visible, onOpenFile, onOpen const [paneHeight, setPaneHeight] = useState(() => clampPaneHeight( typeof meta.previewH === 'number' ? meta.previewH : PANE_HEIGHT_DEFAULT, )) - /** The header refresh action for the Git lens (the lens owns its own queue). */ - const [gitRefresh, setGitRefresh] = useState(0) // ── Session-event accumulation: one catch-up pull when the tab becomes // visible, then a 2.5s delta poll while the SESSION lens is on screen. @@ -171,14 +169,6 @@ export function ChangesTab({ ctx, store, scope, tab, visible, onOpenFile, onOpen patchMeta({ lens: next }) } - /** The header's refresh action: the Git lens reloads through its own queue - * (a click while a refresh is in flight is queued, not dropped), the - * session lens re-pulls its event delta. */ - const refreshCurrent = (): void => { - if (lens === 'git') setGitRefresh(value => value + 1) - else void pull() - } - /** Preview one git change (worktree file or commit) from the Git lens. */ const previewGit = (ref: SidebarDiffRef): void => { setSelection({ kind: 'git', ref }) @@ -215,12 +205,12 @@ export function ChangesTab({ ctx, store, scope, tab, visible, onOpenFile, onOpen onChange={chooseLens} label={t('changes')} /> - } label={t('refresh')} - onClick={refreshCurrent} - /> + onClick={() => { void pull() }} + />} {lens === 'git' ? ( @@ -229,7 +219,6 @@ export function ChangesTab({ ctx, store, scope, tab, visible, onOpenFile, onOpen scope={scope} store={store} visible={visible} - refreshTick={gitRefresh} onOpenFile={onOpenFile ?? (() => { /* no-op */ })} onPreview={previewGit} selectedRef={previewTarget !== null && previewTarget.kind === 'git' ? previewTarget.ref : null} diff --git a/src/client/changes/GitLens.tsx b/src/client/changes/GitLens.tsx index 116ec57b..f37bd00d 100644 --- a/src/client/changes/GitLens.tsx +++ b/src/client/changes/GitLens.tsx @@ -24,7 +24,7 @@ import { isZh, t } from '../locales.ts' import { GitGraph } from './GitGraph.tsx' import type { SidebarDiffRef, SidebarStore } from '../state.ts' import { - ConfirmDialog, IconButton, Notice, SectionHeader, StatusBadge, invalidateGitStatus, statusOfXY, + ConfirmDialog, IconButton, Notice, StatusBadge, invalidateGitStatus, statusOfXY, useGitStatus, type GitFileStatus, type GitTone, type StatusTone, } from '../ui/index.ts' import { buildChangeTree, sumLineCounts, type ChangeDir, type ChangeFile, type ChangeNode } from './change-tree.ts' @@ -93,16 +93,19 @@ const LOG_BATCH = 20 * within ~30s, without a second git process per status tick. */ const WORKTREE_POLL_MS = 30_000 -/** Commit-box growth contract: one line is 18px with 6px of padding above and - * below (mirrored by `changes.module.css`), and it scrolls past six lines. */ -const COMMIT_BOX_LINE_HEIGHT = 18 -const COMMIT_BOX_PADDING_Y = 6 +/** Desktop's official Input typography, with a six-line SCM cap. */ +const COMMIT_BOX_LINE_HEIGHT = 22 const COMMIT_BOX_MAX_ROWS = 6 /** A stable empty entry list: the tree memo must not rebuild on every render * just because `snapshot?.entries ?? []` minted a new array. */ const NO_ENTRIES: readonly GitStatusEntry[] = [] +// The horizontal half of the host's Plus artwork (no public Minus icon). +const MINUS_ICON = + /** * A CONTENT key for one status answer. The shared store mints a brand-new * entries array for every poll — idle polls with byte-identical content @@ -176,6 +179,7 @@ function worktreeRefOf( * specs use — an idle poll must not resolve a single icon. */ const FileRow = memo(function FileRow(props: { row: ChangeFile + depth: number glyph: (path: string) => ReactNode staged: boolean busy: boolean @@ -187,7 +191,7 @@ const FileRow = memo(function FileRow(props: { const { row: node, staged, busy, selected } = props const action = staged ? t('unstage') : t('stage') return ( -
+
@@ -219,24 +223,25 @@ const FileRow = memo(function FileRow(props: { /** One directory row: the disclosure chevron + folder artwork + the label * (a compressed chain reads as one 'a/b/c' line) + how much changed below, * plus the SAME trailing action a file row carries — applied to the whole - * subtree (`git add -A -- ` / `git reset -q -- `, both of which - * take a directory pathspec). The action is a sibling of the disclosure - * button, so a click can never fold the row; it stops propagation anyway so + * subtree (only this group's paths when conflicts exist). The action is a + * sibling of the disclosure button, so a click can never fold the row; it stops propagation anyway so * the intent survives a future nesting change. Memoized like {@link FileRow}. */ const DirRow = memo(function DirRow(props: { row: ChangeDir + depth: number folderGlyph: (path: string, open: boolean) => ReactNode staged: boolean open: boolean busy: boolean + merge: boolean onToggle: (key: string) => void - onToggleStage: (path: string, staged: boolean) => void + onToggleStage: (path: string, staged: boolean, merge?: boolean) => void }): ReactNode { - const { row: node, staged, open, busy } = props - const key = `${staged ? 's' : 'u'}:${node.path}` + const { row: node, staged, open, busy, merge } = props + const key = `${merge ? 'm' : staged ? 's' : 'u'}:${node.path}` const action = staged ? t('unstageAll') : t('stageAll') return ( -
+
: } + icon={MINUS_ICON} onClick={(event) => { event.stopPropagation() - props.onToggleStage(node.path, staged) + props.onToggleStage(node.path, staged, merge) }} />
@@ -279,15 +283,13 @@ export interface GitLensProps { selectedRef: SidebarDiffRef | null /** Poll the inventory only while the tab is actually visible. */ visible: boolean - /** Bumped by the tab header's refresh action (0 = never asked). */ - refreshTick?: number /** The tab's context, for the registered file/folder icon chain (absent → * the host's built-in artwork, exactly like the file tree falls back). */ ctx?: Context } export function GitLens(props: GitLensProps) { - const { scope, onOpenFile, onPreview, selectedRef, visible, refreshTick = 0, ctx } = props + const { scope, onOpenFile, onPreview, selectedRef, visible, ctx } = props const service = ctx?.get('betterSidebar') /** The file row's artwork: a registered icon wins, else the host's own @@ -349,7 +351,7 @@ export function GitLens(props: GitLensProps) { const box = commitBoxRef.current // A layout-less environment (tests) reports 0: leave the CSS height alone. if (box === null || box.scrollHeight === 0) return - const max = COMMIT_BOX_LINE_HEIGHT * COMMIT_BOX_MAX_ROWS + COMMIT_BOX_PADDING_Y * 2 + const max = COMMIT_BOX_LINE_HEIGHT * COMMIT_BOX_MAX_ROWS // Reset first: a scrollHeight measured against the current height can only // ever grow, so a deleted line would leave the box too tall. box.style.height = 'auto' @@ -518,8 +520,10 @@ export function GitLens(props: GitLensProps) { } const targetChanged = target !== chosenPathRef.current if (targetChanged) { + const checkoutChanged = chosenPathRef.current !== undefined || target !== current?.path selectWorktree(target) - clearDerived() + // First inventory merely names the already-active primary checkout. + if (checkoutChanged) clearDerived() } // A silent tick only keeps the inventory (and its change counts) fresh. if (silent && !targetChanged) return @@ -594,16 +598,6 @@ export function GitLens(props: GitLensProps) { // eslint-disable-next-line react-hooks/exhaustive-deps }, [visible]) - // The header's refresh action: re-read the inventory and derived surfaces, - // and force the SHARED status of this session (the file tree's colors too). - useEffect(() => { - if (refreshTick === 0) return - void refresh(false) - invalidateGitStatus(scope.sessionId) - // Only the tick drives this effect. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [refreshTick]) - /** The inventory poll: a linked checkout created mid-session shows up * without a manual refresh (the status poll itself belongs to the store). */ const pollInventory = useCallback((signal: AbortSignal): Promise => refresh(true, signal), [refresh]) @@ -624,7 +618,7 @@ export function GitLens(props: GitLensProps) { setActionError(null) try { await action() - onSuccess?.() + if (generation === scopeGen.current) onSuccess?.() } catch (reason) { if (generation === scopeGen.current) setActionError(failure(reason)) } finally { @@ -646,25 +640,25 @@ export function GitLens(props: GitLensProps) { const pushError = (reason: unknown): string => `${t('pushError')}: ${errorMessage(reason)}` const pullError = (reason: unknown): string => `${t('pullError')}: ${errorMessage(reason)}` - const stageEntry = (path: string, staged: boolean): void => { - void runAction( - () => (staged ? api.gitUnstage(gitScopeNow(), path, selectedWorktree) : api.gitStage(gitScopeNow(), path, selectedWorktree)), - stageError, - ) - } - - const stageAll = (staged: boolean, merge = false): void => { + const stageEntry = (path: string | undefined, staged: boolean, merge = false): void => { const gitScope = gitScopeNow() const target = selectedWorktree + // With conflicts, directory/all actions must only touch their own group: + // git add/reset on the whole directory would silently resolve/reset Merge. + const rows = staged ? stagedEntries : merge || mergeEntries.some(entry => entry.path === path) ? mergeEntries : unstagedEntries + const paths = mergeEntries.length === 0 ? [path] : rows + .filter(entry => path === undefined || entry.path === path || entry.path.startsWith(`${path}/`)) + .map(entry => entry.path) void runAction(async () => { - if (!staged && mergeEntries.length > 0) { - // Separate Merge/Changes groups must not stage each other's files. - for (const entry of merge ? mergeEntries : unstagedEntries) await api.gitStage(gitScope, entry.path, target) - } else if (staged) await api.gitUnstage(gitScope, undefined, target) - else await api.gitStage(gitScope, undefined, target) + for (const selectedPath of paths) { + if (staged) await api.gitUnstage(gitScope, selectedPath, target) + else await api.gitStage(gitScope, selectedPath, target) + } }, stageError) } + const stageAll = (staged: boolean, merge = false): void => { stageEntry(undefined, staged, merge) } + const commit = (): void => { const message = commitMsg.trim() if (!canCommit || actionLock.current) return @@ -727,8 +721,8 @@ export function GitLens(props: GitLensProps) { const gitScope = gitScopeNow() const target = selectedWorktree void runAction(async () => { - try { await api.gitPull(gitScope, target) } catch (reason) { throw new Error(pullError(reason)) } - try { await api.gitPush(gitScope, target) } catch (reason) { throw new Error(pushError(reason)) } + try { await api.gitPull(gitScope, target) } catch (reason) { throw new Error(pullError(reason), { cause: reason }) } + try { await api.gitPush(gitScope, target) } catch (reason) { throw new Error(pushError(reason), { cause: reason }) } }) } @@ -906,14 +900,14 @@ export function GitLens(props: GitLensProps) { * current closures through the ref instead of closing over them. */ const rowActions = useRef({ preview: (_node: ChangeFile, _staged: boolean): void => { /* replaced below */ }, - stage: (_path: string, _staged: boolean): void => { /* replaced below */ }, + stage: (_path: string, _staged: boolean, _merge?: boolean): void => { /* replaced below */ }, }) useEffect(() => { rowActions.current = { preview: (node, staged) => { onPreview(worktreeRefOf(node.path, isUntrackedStatus(node.status), staged, chosenPathRef.current, repoRootRef.current)) }, - stage: (path, staged) => { stageEntry(path, staged) }, + stage: (path, staged, merge) => { stageEntry(path, staged, merge) }, } }) @@ -921,8 +915,8 @@ export function GitLens(props: GitLensProps) { const previewFile = useCallback((node: ChangeFile, staged: boolean): void => { rowActions.current.preview(node, staged) }, []) - const stagePath = useCallback((path: string, staged: boolean): void => { - rowActions.current.stage(path, staged) + const stagePath = useCallback((path: string, staged: boolean, merge = false): void => { + rowActions.current.stage(path, staged, merge) }, []) const openRowMenu = useCallback((event: MouseEvent, node: ChangeFile, staged: boolean): void => { event.preventDefault() @@ -930,11 +924,12 @@ export function GitLens(props: GitLensProps) { setFileMenu({ path: node.path, staged, untracked: isUntrackedStatus(node.status), x: event.clientX, y: event.clientY }) }, []) - /** One file row of a group's tree (the single file-row renderer). */ - const renderFile = (node: ChangeFile, staged: boolean): ReactNode => ( + /** Indent the content, not its container: hover and selection stay full-width. */ + const renderFile = (node: ChangeFile, staged: boolean, depth = 0): ReactNode => ( ) - /** One directory row plus its (default-expanded) subtree. */ - const renderDir = (node: ChangeDir, staged: boolean): ReactNode => { - const key = `${staged ? 's' : 'u'}:${node.path}` + const renderDir = (node: ChangeDir, staged: boolean, merge: boolean, depth = 0): ReactNode => { + const key = `${merge ? 'm' : staged ? 's' : 'u'}:${node.path}` const open = !collapsed.has(key) return (
- - {open && ( -
- {node.children.map(child => (child.kind === 'dir' ? renderDir(child, staged) : renderFile(child, staged)))} -
- )} + + {open && node.children.map(child => child.kind === 'dir' + ? renderDir(child, staged, merge, depth + 1) : renderFile(child, staged, depth + 1))}
) } - /** One group's whole tree. */ - const renderTree = (nodes: readonly ChangeNode[], staged: boolean): ReactNode => ( + const renderTree = (nodes: readonly ChangeNode[], staged: boolean, merge = false): ReactNode => (
- {nodes.map(node => (node.kind === 'dir' ? renderDir(node, staged) : renderFile(node, staged)))} + {nodes.map(node => (node.kind === 'dir' ? renderDir(node, staged, merge) : renderFile(node, staged)))}
) + const renderGroup = (id: string, label: string, rows: readonly GitStatusEntry[], nodes: readonly ChangeNode[], staged: boolean, merge = false): ReactNode => { + if (rows.length === 0) return null + const key = `group:${id}` + const open = !collapsed.has(key) + const totals = staged ? stagedTotal : merge ? undefined : unstagedTotal + return ( +
+
+ + } + onClick={() => { stageAll(staged, merge) }} /> + {rows.length} +
+ {open && renderTree(nodes, staged, merge)} +
+ ) + } + return (
{/* Changes and Graph scroll together; only the branch/sync footer docks. */} @@ -1006,8 +1013,8 @@ export function GitLens(props: GitLensProps) { anchor={} label={t('gitMoreActions')} active={moreOpen} onClick={() => { setMoreOpen(open => !open) }} />} items={[ - { id: 'push', label: t('push'), disabled: busy || suggesting || snapshot?.detached === true }, { id: 'pull', label: t('pull'), disabled: busy || suggesting || snapshot?.detached === true }, + { id: 'push', label: t('push'), disabled: busy || suggesting || snapshot?.detached === true }, ...(repoChoices.length > 1 ? [{ id: 'repos', label: t('gitRepository'), submenu: repoChoices.map(root => ({ id: `repo:${root}`, label: baseName(root), disabled: busy || suggesting })), }] : []), @@ -1053,32 +1060,9 @@ export function GitLens(props: GitLensProps) {
{clean && {t('changesClean')}} - {mergeEntries.length > 0 &&
- } onClick={() => { stageAll(false, true) }} />}> - {mergeEntries.length} - - {renderTree(mergeTree, false)} -
} - {stagedEntries.length > 0 &&
- } onClick={() => { stageAll(true) }} />}> - {stagedEntries.length} - {stagedTotal.files > 0 && } - - {renderTree(stagedTree, true)} -
} - {unstagedEntries.length > 0 &&
- } onClick={() => { stageAll(false) }} />}> - {unstagedEntries.length} - {unstagedTotal.files > 0 && } - - {renderTree(unstagedTree, false)} -
} + {renderGroup('merge', t('gitMergeChanges'), mergeEntries, mergeTree, false, true)} + {renderGroup('staged', t('gitStagedChanges'), stagedEntries, stagedTree, true)} + {renderGroup('unstaged', t('gitChanges'), unstagedEntries, unstagedTree, false)}
} )} @@ -1126,7 +1110,7 @@ export function GitLens(props: GitLensProps) { onSelect={name => { setBranchOpen(false); void checkout(name) }} /> diff --git a/src/client/changes/changes.module.css b/src/client/changes/changes.module.css index e822133f..513c9bf1 100644 --- a/src/client/changes/changes.module.css +++ b/src/client/changes/changes.module.css @@ -25,6 +25,7 @@ min-width: 0; display: flex; flex-direction: column; + padding-top: 6px; } /* The inner scroll body: the change groups + the history. It owns both scroll @@ -67,24 +68,25 @@ class keeps the opaque fill above the kit's transparent band no matter which sheet lands first in the bundle. */ .group .groupHeader { + gap: 4px; position: sticky; top: 0; z-index: 2; background: var(--dsw-alias-bg-base); } -/* The group's change count, as a small capsule on the label's baseline. */ +/* Group counts match the action height; directory rows need no badge. */ .countPill { flex: none; - min-width: 16px; - height: 16px; - padding: 0 5px; - border-radius: 999px; + width: 20px; + height: 20px; + border-radius: 50%; background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-secondary); font: var(--dsw-font-xxxs-strong-11); - line-height: 16px; + line-height: 20px; text-align: center; + font-size: 10px; font-variant-numeric: tabular-nums; } @@ -98,17 +100,8 @@ .group .headerAction { opacity: 1; } } -/* The tree body: rows are flush bands, the gutter lives here. */ -.tree { display: flex; flex-direction: column; padding: 0 6px; } - -/* One nesting level: 12px of indent, with the guide line drawn at its edge so - the depth stays readable without a second colour. */ -.treeChildren { - display: flex; - flex-direction: column; - margin-left: 11px; - border-left: 1px solid var(--dsw-alias-border-l1); -} +/* Indent row contents only; hover bands span the full panel. */ +.tree { display: flex; flex-direction: column; } /* A directory row's disclosure button. It shares the `.row` band with a file row (the band owns the hover/selected fill and the trailing action), so this @@ -142,8 +135,7 @@ gap: 6px; position: relative; min-height: 28px; - padding: 0 2px; - border-radius: 4px; + padding: 0 6px; animation: dsh-row-in 150ms var(--ds-ease-in-out); } .row:hover { background: var(--dsw-alias-interactive-bg-hover); } @@ -215,6 +207,9 @@ white-space: nowrap; } +/* Match both glyphs and keep their hover boxes smaller than the 28px row. */ +.row .rowAction, .group .headerAction { width: 20px; height: 20px; } + /* The row action is invisible until its row is hovered or holds focus (a keyboard tab lands on it and reveals it). The three-class form outranks the kit's own disabled rule, which would otherwise pin every button to a dim but @@ -228,42 +223,39 @@ .messageBox { display: flex; padding: 4px 8px 8px; } -/* The commit-message box and its busy overlay: the input keeps its own - flex sizing through a wrapper so the overlay can sit exactly on top of it - while the host generates or commits. */ +/* Desktop's official Input frame, with a growing textarea instead of input. */ .commitInputWrap { position: relative; display: flex; + align-items: center; + gap: 6px; flex: 1; min-width: 0; + min-height: 32px; + box-sizing: border-box; + padding: 0 4px 0 8px; + border: 0.5px solid var(--dsw-alias-border-l4); + border-radius: var(--dsw-radius-md); + background: var(--dsw-alias-bg-layer-1); } +.commitInputWrap:focus-within { border-color: var(--dsw-alias-state-business-primary); } -/* The multiline commit box: a native textarea styled to match the primitives - Input (layer fill, hairline border, brand focus ring). Flex sizing keeps it - inside the row — `width: 100%` would overflow its own padding/border. */ .commitInput { flex: 1; min-width: 0; - box-sizing: border-box; - /* One line by default; GitLens grows it with the text (18px per line, - 6px vertical padding, six lines before it scrolls). The bounds here are - the stylesheet's half of that contract. */ - min-height: 30px; - max-height: 120px; - padding: 6px 32px 6px 8px; - border: 0.5px solid var(--dsw-alias-border-l4); - border-radius: 3px; - background: var(--dsw-alias-bg-layer-1); + height: 22px; + min-height: 22px; + max-height: 132px; + padding: 0; + margin: 4px 0; + border: none; + background: transparent; color: var(--dsw-alias-label-primary); - font: var(--dsw-font-s-13); - line-height: 18px; + font: var(--dsw-font-s-14); + line-height: 22px; resize: none; overflow-y: hidden; -} - -.commitInput:focus { outline: none; - border-color: var(--dsw-alias-brand-primary); } .commitInput::placeholder { @@ -280,13 +272,14 @@ is cleared while busy, so the two never overlap. */ .commitBusyText { position: absolute; - inset: 0; + inset: 0 38px 0 0; display: flex; align-items: center; - /* Matches the textarea's own padding so the label sits where the text would. */ - padding: 6px 8px; + /* Match the frame's inset while keeping the generate button unobscured. */ + padding: 0 8px; pointer-events: none; - font: var(--dsw-font-xxs-12); + font: var(--dsw-font-s-14); + line-height: 22px; background-image: linear-gradient( 90deg, var(--dsw-alias-label-tertiary) 0%, @@ -311,20 +304,19 @@ /* Generate fills the draft only. Inline on the input's right edge. */ .suggestButton { - position: absolute; - top: 2px; - right: 2px; flex: none; + align-self: flex-start; + margin-top: 3px; display: inline-flex; align-items: center; justify-content: center; - width: 26px; - height: 26px; + width: 24px; + height: 24px; padding: 0; border: none; - border-radius: 3px; + border-radius: 8px; background: transparent; - color: var(--dsw-alias-label-secondary); + color: var(--dsw-alias-label-tertiary); cursor: pointer; } diff --git a/tests/changes-tab.spec.tsx b/tests/changes-tab.spec.tsx index d8cef920..9115b241 100644 --- a/tests/changes-tab.spec.tsx +++ b/tests/changes-tab.spec.tsx @@ -238,8 +238,9 @@ describe('ChangesTab', () => { expect(container.textContent).toContain('src/a.ts') const chips = [...container.querySelectorAll('button[aria-pressed]')] expect(chips.some(chip => /写入\s*2|Write\s*2/.test(chip.textContent ?? ''))).toBe(true) - // The git lens (its branch picker) is unmounted by the switch. - expect(container.querySelector('select')).toBeNull() + // The Git lens (including its footer branch menu) is unmounted by the switch. + expect(container.querySelector('[data-git-root]')).toBeNull() + expect(container.querySelector('[data-git-footer]')).toBeNull() } finally { act(() => { root.unmount() }) container.remove() @@ -314,7 +315,8 @@ describe('ChangesTab', () => { const empties = [...container.querySelectorAll('[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. + // No resource group or tree row is rendered when nothing changed. + expect(container.querySelectorAll('[data-group]')).toHaveLength(0) expect(container.querySelectorAll('[data-path]')).toHaveLength(0) } finally { act(() => { root.unmount() }) @@ -322,7 +324,7 @@ describe('ChangesTab', () => { } }) - it('reports a failed stage action in the commit bar and catches it (no unhandled rejection)', async () => { + it('reports a failed stage action in the footer and catches it (no unhandled rejection)', async () => { mockGit([{ path: 'src/a.ts', xy: ' M' }]) vi.spyOn(api, 'gitStage').mockRejectedValue(new Error('index.lock exists')) @@ -334,26 +336,30 @@ describe('ChangesTab', () => { await flushEffects() const stage = container.querySelector(`button[aria-label="${t('stage')}"]`) - expect(stage).toBeDefined() + expect(stage).not.toBeNull() await act(async () => { stage!.click() }) await flushEffects() - const alert = [...container.querySelectorAll('[role="alert"]')] - .find(node => (node.textContent ?? '').includes(t('changesStageFailed', { message: 'index.lock exists' }))) + const alerts = [...container.querySelectorAll('[role="alert"]')] + const alert = alerts.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(`textarea[placeholder="${t('commitPlaceholder')}"]`) + expect(alerts).toHaveLength(1) + // The ONE action status line stays visible with the checkout/sync footer. + const footer = container.querySelector('[data-git-footer]') + const input = container.querySelector('[data-message-box] textarea') expect(input).not.toBeNull() - expect(alert!.previousElementSibling?.contains(input)).toBe(true) + expect(alert!.parentElement).toBe(footer) + expect(alert!.nextElementSibling).toBe(footer!.querySelector('[data-footer-row]')) + expect(container.querySelector('[data-git-scroll]')!.contains(alert!)).toBe(false) } finally { act(() => { root.unmount() }) container.remove() } }) - it('re-derives the previewed op from the latest fold when it settles', async () => { + it('keeps Git refresh in Changes and re-derives the session preview on manual refresh', async () => { mockGit([]) - vi.spyOn(api, 'changesOps') + const ops = 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' }) } }], @@ -372,6 +378,12 @@ describe('ChangesTab', () => { try { mount(root) await flushEffects() + const refreshSelector = `button[aria-label="${t('refresh')}"]` + const head = container.querySelector('[role="tablist"]')!.parentElement! + // Git has one refresh, inside Changes rather than beside the lens tabs. + expect(head.querySelector(refreshSelector)).toBeNull() + expect(container.querySelectorAll(refreshSelector)).toHaveLength(1) + expect(container.querySelector(`[data-scm-section="changes"] ${refreshSelector}`)).not.toBeNull() const sessionTab = lensTab(container, t('changesSessionLens')) await act(async () => { sessionTab!.click() }) @@ -384,10 +396,13 @@ describe('ChangesTab', () => { // 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(`button[aria-label="${t('refresh')}"]`) + const refresh = head.querySelector(refreshSelector) expect(refresh).not.toBeNull() + expect(container.querySelectorAll(refreshSelector)).toHaveLength(1) + expect(ops).toHaveBeenCalledTimes(1) await act(async () => { refresh!.click() }) await flushEffects() + expect(ops).toHaveBeenLastCalledWith({ sessionId: 'session', cwd: MAIN }, 1, undefined) expect(container.textContent).toContain('settled-body') } finally { act(() => { root.unmount() }) @@ -495,16 +510,16 @@ describe('ChangesTab', () => { }) /** - * Issue #194: the branch band and the commit box must not scroll away with - * the list. The lens root is therefore a FIXED frame whose only scrollable - * child is the list body holding the change groups and the history — the two - * chrome bands are its siblings, not its contents. + * Issue #194's single-scroller frame survives #941: Message, groups and Graph + * now scroll together, while the checkout/sync footer stays docked outside. + * The old selector band and bottom commit bar are intentionally gone. */ - it('keeps the branch band and the commit bar outside the one scroll body (#194)', async () => { + it('scrolls Message, change groups and Graph together with the footer outside (#194, #941)', async () => { mockGit([{ path: 'src/a.ts', xy: ' M' }]) vi.spyOn(api, 'gitLog').mockResolvedValue([{ hash: 'abcdef0', hashFull: 'abcdef0abcdef0abcdef0abcdef0abcdef0abcd', + parents: [], subject: 'history row', author: 'Test', date: '2026-08-20 00:00:00 +0800', @@ -520,63 +535,59 @@ describe('ChangesTab', () => { const frame = container.querySelector('[data-git-root]') const scroller = container.querySelector('[data-git-scroll]') - const head = container.querySelector('[data-git-head]') - const bar = container.querySelector('[data-commit-bar]') + const footer = container.querySelector('[data-git-footer]') expect(frame).not.toBeNull() expect(scroller).not.toBeNull() - expect(head).not.toBeNull() - expect(bar).not.toBeNull() - // The frame is NOT the scroller: the root must never carry the scroll body. + expect(footer).not.toBeNull() expect(frame!.hasAttribute('data-git-scroll')).toBe(false) + expect(container.querySelectorAll('[data-git-scroll]')).toHaveLength(1) + expect(scroller!.parentElement).toBe(frame) + expect(footer!.parentElement).toBe(frame) + expect(scroller!.contains(footer!)).toBe(false) + expect(scroller!.compareDocumentPosition(footer!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + expect(footer!.querySelector('[data-footer-row] button[aria-haspopup="menu"]')).not.toBeNull() + expect(container.querySelector('[data-git-head]')).toBeNull() + expect(container.querySelector('[data-commit-bar]')).toBeNull() + expect(container.querySelector('select')).toBeNull() - // The branch band and the commit bar are the frame's own children, so - // neither can be carried out of the viewport by the list scrolling. - expect(head!.parentElement).toBe(frame) - expect(bar!.parentElement).toBe(frame) - expect(scroller!.contains(head!)).toBe(false) - expect(scroller!.contains(bar!)).toBe(false) - - // The list body is what actually holds the change list and the history. - expect(scroller!.querySelector('[data-group="unstaged"] [data-path="src/a.ts"]')).not.toBeNull() - const historyRow = scroller!.querySelector('[role="button"]') + const changes = scroller!.querySelector('[data-scm-section="changes"]') + const graph = scroller!.querySelector('[data-scm-section="graph"]') + const message = changes!.querySelector('[data-message-box]') + const unstaged = changes!.querySelector('[data-group="unstaged"]') + expect(message!.querySelector('textarea')).not.toBeNull() + expect(unstaged!.querySelector('[data-path="src/a.ts"]')).not.toBeNull() + expect(changes!.querySelector('[data-group="staged"]')).toBeNull() + expect(message!.compareDocumentPosition(unstaged!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + expect(changes!.compareDocumentPosition(graph!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + const historyRow = graph!.querySelector('[data-graph-row]') expect(historyRow).not.toBeNull() expect(historyRow!.textContent).toContain('history row') - - // The commit box is inside its bar, and the bar sits BELOW the scroller. - const input = container.querySelector('textarea') - expect(input).not.toBeNull() - expect(scroller!.contains(input!)).toBe(false) - expect(bar!.contains(input!)).toBe(true) - expect(scroller!.compareDocumentPosition(bar!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + expect(footer!.querySelector('textarea')).toBeNull() } finally { act(() => { root.unmount() }) container.remove() } }) - it('scrolls the inner body only and no longer pins the commit bar with position: sticky (#194)', () => { - // jsdom has no layout engine, so the sheet itself is the evidence for the - // docking mechanic (the same pattern the explorer's batch bar uses). + it('keeps one inner scroller and docks the footer without sticky positioning (#194, #941)', () => { + // jsdom has no layout engine, so the sheet itself is the docking evidence. const sheet = readFileSync('src/client/changes/changes.module.css', 'utf8') const rule = (selector: string): string => { - const block = sheet.match(new RegExp(`\\n\\${selector} \\{([\\s\\S]*?)\\n\\}`))?.[1] + const block = sheet.match(new RegExp(`\\n\\${selector} \\{([^}]+)\\}`))?.[1] expect(block, `the ${selector} rule must exist in changes.module.css`).toBeDefined() return block! } - // The lens root is the fixed frame: it owns no scroll axis at all. expect(rule('.git')).not.toContain('overflow') expect(rule('.git')).toContain('display: flex') - // The inner body is the ONE vertical scroller (and clips the width). expect(rule('.gitScroll')).toContain('overflow-y: auto') expect(rule('.gitScroll')).toContain('overflow-x: hidden') expect(rule('.gitScroll')).toContain('flex: 1') - // The commit bar is now a plain flex sibling — no sticky bottom, no - // stacking order over the (still sticky) group headers. - expect(rule('.commitBar')).not.toContain('position') - expect(rule('.commitBar')).not.toContain('sticky') - expect(rule('.commitBar')).not.toContain('z-index') - // The group headers still park on the inner body's top edge. + expect(rule('.gitFooter')).toContain('flex: none') + expect(rule('.gitFooter')).not.toMatch(/position|sticky|z-index|overflow/) + expect(rule('.messageBox')).not.toMatch(/position|sticky|overflow/) + expect(sheet).not.toMatch(/\.(?:selectors|select|branchLabel|commitBar|commitRow)\s*\{/) + // The retained group headers still park on the inner body's top edge. const groupHeader = rule('.group .groupHeader') expect(groupHeader).toContain('position: sticky') expect(groupHeader).toContain('top: 0') diff --git a/tests/git-remote-actions-ui.spec.tsx b/tests/git-remote-actions-ui.spec.tsx index d9d201d5..a22ddec2 100644 --- a/tests/git-remote-actions-ui.spec.tsx +++ b/tests/git-remote-actions-ui.spec.tsx @@ -1,11 +1,10 @@ /** - * The commit bar's Push / Pull affordances (the AI commit-message suggestion - * that landed in the same upstream PR is pinned by `git-suggest.spec.tsx`, - * which keeps the implementation merged from `port/pr-642`). + * The More Actions menu's Push / Pull affordances (the AI commit-message + * suggestion is pinned by `git-suggest.spec.tsx`). * * These pin the WIRING the host routes cannot see — which args each action - * sends (scope, selected checkout) and that its failure lands on the bar's ONE - * status line, the same channel commit / stage failures use + * sends (scope, selected checkout) and that its failure lands on the footer's + * ONE status line, the same channel commit / stage failures use * (`changes-tab.spec.tsx` pins that placement). * * The copy assertions go through `t()`, so they follow the active locale @@ -45,7 +44,6 @@ function mountGit(root: Root): void { onPreview: () => {}, selectedRef: null, visible: true, - refreshTick: 0, })) }) } @@ -62,15 +60,20 @@ function makeRoot(): { container: HTMLDivElement; root: Root } { return { container, root: createRoot(container) } } -/** One text button of the commit bar, by its label. */ -function textButton(container: HTMLElement, label: string): HTMLButtonElement { - const button = [...container.querySelectorAll('button')] +/** Push/Pull live in the native, portaled More Actions menu. */ +async function selectRemoteAction(container: HTMLElement, label: string): Promise { + const trigger = container.querySelector(`button[aria-label="${t('gitMoreActions')}"]`) + if (trigger === null) throw new Error('More Actions button not found') + act(() => { trigger.click() }) + const item = [...document.querySelectorAll('button[role="menuitem"]')] .find(candidate => candidate.textContent === label) - if (button === undefined) throw new Error(`no commit-bar button labelled "${label}"`) - return button + if (item === undefined) throw new Error(`remote menu action not found: ${label}`) + expect(container.contains(item)).toBe(false) + await act(async () => { item.click() }) + await flushEffects() } -/** One rendered error line of the commit bar. */ +/** One rendered error line of the footer. */ function errorLine(container: HTMLElement, text: string): HTMLElement | undefined { return [...container.querySelectorAll('[role="alert"]')] .find(node => (node.textContent ?? '').includes(text)) @@ -85,7 +88,7 @@ afterEach(() => { document.body.innerHTML = '' }) -describe('GitLens commit bar: remote actions', () => { +describe('GitLens More Actions menu: remote actions', () => { it('pushes and pulls the selected checkout, reporting failures on the same status line', async () => { mockGit([{ path: 'src/a.ts', xy: ' M' }]) const push = vi.spyOn(api, 'gitPush').mockResolvedValue({ ok: true }) @@ -96,14 +99,15 @@ describe('GitLens commit bar: remote actions', () => { mountGit(root) await flushEffects() - await act(async () => { textButton(container, t('push')).click() }) - await flushEffects() + await selectRemoteAction(container, t('push')) expect(push).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'session' }), MAIN) - await act(async () => { textButton(container, t('pull')).click() }) - await flushEffects() + await selectRemoteAction(container, t('pull')) expect(pull).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'session' }), MAIN) - expect(errorLine(container, `${t('pullError')}: Not possible to fast-forward`)).toBeDefined() + const error = errorLine(container, `${t('pullError')}: Not possible to fast-forward`) + expect(error).toBeDefined() + expect(container.querySelectorAll('[role="alert"]')).toHaveLength(1) + expect(error!.parentElement).toBe(container.querySelector('[data-git-footer]')) } finally { act(() => { root.unmount() }) container.remove() diff --git a/tests/git-scm.spec.tsx b/tests/git-scm.spec.tsx index 71c9ca7c..59959c8e 100644 --- a/tests/git-scm.spec.tsx +++ b/tests/git-scm.spec.tsx @@ -52,6 +52,27 @@ it('orders distinct conflict/index/worktree groups, folds independently, and kee expect([...container.querySelectorAll('[data-group] > header [data-count], [data-group] > div:first-child [data-count]')].map(el => el.textContent)).toEqual(['1', '1', '2']) expect(container.querySelector('[data-group="staged"] [data-path="src/partial.ts"] [data-tone]')!.textContent).toBe('M') expect(container.querySelector('[data-group="unstaged"] [data-path="src/partial.ts"] [data-tone]')!.textContent).toBe('D') + const group = (name: string): HTMLElement => container.querySelector(`[data-group="${name}"]`)! + const disclosure = (name: string): HTMLButtonElement => group(name).querySelector(':scope > div:first-child > button[aria-expanded]')! + for (const [name, count] of [['merge', '1'], ['staged', '1'], ['unstaged', '2']] as const) { + expect(group(name).firstElementChild!.lastElementChild!.getAttribute('data-count')).toBe(count) + expect(disclosure(name).getAttribute('aria-label')).toContain(count) + } + await click(disclosure('staged')) + expect(disclosure('staged').getAttribute('aria-expanded')).toBe('false') + expect(group('staged').querySelector('[data-path]')).toBeNull() + expect(group('staged').firstElementChild!.lastElementChild!.getAttribute('data-count')).toBe('1') + expect(group('unstaged').querySelector('[data-path="src/partial.ts"]')).not.toBeNull() + await click(disclosure('unstaged')) + expect(disclosure('unstaged').getAttribute('aria-expanded')).toBe('false') + expect(group('unstaged').querySelector('[data-path]')).toBeNull() + expect(group('merge').querySelector('[data-path="conflict.ts"]')).not.toBeNull() + await click(disclosure('staged')) + expect(disclosure('staged').getAttribute('aria-expanded')).toBe('true') + expect(group('staged').querySelector('[data-path="src/partial.ts"]')).not.toBeNull() + expect(disclosure('unstaged').getAttribute('aria-expanded')).toBe('false') + await click(disclosure('unstaged')) + expect(disclosure('unstaged').getAttribute('aria-expanded')).toBe('true') const footer = container.querySelector('[data-git-footer]')! expect(footer.textContent).toContain('main*+!') expect(container.querySelector('[data-git-scroll]')!.contains(footer)).toBe(false) @@ -69,6 +90,75 @@ it('orders distinct conflict/index/worktree groups, folds independently, and kee await click(container.querySelector(`[data-group="unstaged"] button[aria-label="${t('stageAll')}"]`)!) expect(stage.mock.calls.map(call => call[1])).toEqual(['src/partial.ts', 'new.ts']) expect(changes.getAttribute('aria-expanded')).toBe('true') + expect(disclosure('unstaged').getAttribute('aria-expanded')).toBe('true') + expect(group('unstaged').querySelector('[data-path="src/partial.ts"]')).not.toBeNull() + } finally { view.unmount() } +}) + +it('keeps directory/all actions inside their group, including Merge directory folding', async () => { + const snapshot = { ...tracked(), entries: [ + { path: 'src/conflict.ts', xy: 'UU' }, { path: 'src/partial.ts', xy: 'MM' }, { path: 'new.ts', xy: '??' }, + ] } + const stage = vi.spyOn(api, 'gitStage').mockResolvedValue({ ok: true }) + const unstage = vi.spyOn(api, 'gitUnstage').mockResolvedValue({ ok: true }) + const view = await mount(() => snapshot) + const group = (name: string): HTMLElement => view.container.querySelector(`[data-group="${name}"]`)! + const dir = (name: string): HTMLButtonElement => group(name).querySelector('[data-dir="src"]')! + const dirAction = (name: string): HTMLButtonElement => dir(name).parentElement!.querySelector(`button[aria-label="${t('stageAll')}"]`)! + try { + const rows = [...view.container.querySelectorAll('[data-row]')] + expect(rows).toHaveLength(7) + for (const directory of view.container.querySelectorAll('[data-dir]')) expect(directory.closest('[data-row]')!.querySelector('[data-count]')).toBeNull() + for (const row of rows) { + const action = row.querySelector(':scope > button[aria-label]')! + expect(row.lastElementChild).toBe(action) + expect(action.querySelector('svg')!.getAttribute('width')).toBe('12') + expect(action.querySelector('svg')!.getAttribute('height')).toBe('12') + expect(action.querySelector('svg path')!.getAttribute('d')).toBe('M2 8H14') + } + for (const name of ['merge', 'staged', 'unstaged']) { + const headerAction = group(name).firstElementChild!.querySelector(`button[aria-label="${t(name === 'staged' ? 'unstageAll' : 'stageAll')}"]`)! + expect(headerAction.querySelector('svg')!.getAttribute('width')).toBe('12') + expect(headerAction.querySelector('svg')!.getAttribute('height')).toBe('12') + expect([...headerAction.querySelectorAll('svg path')].map(path => path.getAttribute('d'))) + .toEqual(name === 'staged' ? ['M2 8H14'] : ['M8 2V14', 'M2 8H14']) + } + await click(dir('merge')) + expect(dir('merge').getAttribute('aria-expanded')).toBe('false') + expect(group('merge').querySelector('[data-path="src/conflict.ts"]')).toBeNull() + expect(group('unstaged').querySelector('[data-path="src/partial.ts"]')).not.toBeNull() + await click(dirAction('unstaged')) + expect(stage.mock.calls.map(call => call[1])).toEqual(['src/partial.ts']) + expect(dir('unstaged').getAttribute('aria-expanded')).toBe('true') + expect(group('unstaged').querySelector('[data-path="src/partial.ts"]')).not.toBeNull() + await click(dirAction('merge')) + expect(stage.mock.calls.map(call => call[1])).toEqual(['src/partial.ts', 'src/conflict.ts']) + expect(dir('merge').getAttribute('aria-expanded')).toBe('false') + expect(group('merge').querySelector('[data-path="src/conflict.ts"]')).toBeNull() + await click(group('staged').querySelector(`button[aria-label="${t('unstageAll')}"]`)!) + expect(unstage.mock.calls.map(call => call[1])).toEqual(['src/partial.ts']) + expect(group('staged').querySelector('button[aria-expanded]')!.getAttribute('aria-expanded')).toBe('true') + expect(dir('staged').getAttribute('aria-expanded')).toBe('true') + expect(group('staged').querySelector('[data-path="src/partial.ts"]')).not.toBeNull() + await click(group('staged').querySelector(`[data-row="src/partial.ts"] > button[aria-label="${t('unstage')}"]`)!) + expect(unstage.mock.calls.map(call => call[1])).toEqual(['src/partial.ts', 'src/partial.ts']) + expect(dir('staged').getAttribute('aria-expanded')).toBe('true') + expect(group('staged').querySelector('button[aria-expanded]')!.getAttribute('aria-expanded')).toBe('true') + } finally { view.unmount() } +}) + +it('does not erase a newer draft when an old commit finishes after a scope round trip', async () => { + let done!: (value: { ok: true }) => void + vi.spyOn(api, 'gitCommit').mockReturnValueOnce(new Promise(resolve => { done = resolve })) + const view = await mount(() => tracked()) + try { + await write(input(view.container), 'old A') + await enter(input(view.container)) + await view.switchTo('scm-B') + await view.switchTo('scm-A') + await write(input(view.container), 'new A') + await act(async () => { done({ ok: true }); await Promise.resolve() }) + expect(input(view.container).value).toBe('new A') } finally { view.unmount() } }) diff --git a/tests/git-suggest.spec.tsx b/tests/git-suggest.spec.tsx index 0b30f2fb..746ea3ea 100644 --- a/tests/git-suggest.spec.tsx +++ b/tests/git-suggest.spec.tsx @@ -5,7 +5,7 @@ * (`git-suggest-empty`) so the panel can say "nothing to summarize" instead * of a generic generation failure. * - * The commit bar only exists once the git status says the directory is a + * The message box only exists once the git status says the directory is a * repository, and the shared status store subscribes only while the lens is * VISIBLE — so the harness mounts a visible lens and waits for that first * answer (the model tooltip rides the same mount, its route read fires on @@ -33,7 +33,7 @@ function deferred(): { promise: Promise; resolve: (value: T) => void } { } function pendingStatus(): GitStatusResult { - return { isRepo: true, branch: 'main', entries: [{ path: 'src/app.ts', xy: ' M' }] } + return { isRepo: true, branch: 'main', entries: [{ path: 'src/app.ts', xy: 'M ' }] } } async function mount(options: { @@ -79,7 +79,7 @@ function suggestButton(container: HTMLElement): HTMLButtonElement { } function commitInput(container: HTMLElement): HTMLTextAreaElement { - const input = container.querySelector('textarea') + const input = container.querySelector('[data-message-box] textarea') if (input === null) throw new Error('the commit input is missing') return input } diff --git a/tests/git-view-worktree.spec.tsx b/tests/git-view-worktree.spec.tsx index 6fad842e..492740fb 100644 --- a/tests/git-view-worktree.spec.tsx +++ b/tests/git-view-worktree.spec.tsx @@ -48,6 +48,7 @@ function logFor(target?: string, index = 0): GitLogEntry[] { return [{ hash: `${digit.repeat(6)}${suffix.slice(-1)}`, hashFull: `${digit.repeat(32)}${suffix}`, + parents: [], subject: agent ? `Agent checkout commit ${index}` : `Main checkout commit ${index}`, author: 'Test', date: '2026-08-20 00:00:00 +0800', @@ -74,7 +75,6 @@ function mountGit( root: Root, options: { scope?: { sessionId: string; cwd?: string } - refreshTick?: number visible?: boolean ctx?: Context } = {}, @@ -87,7 +87,6 @@ function mountGit( onPreview: () => {}, selectedRef: null, visible: options.visible ?? true, - refreshTick: options.refreshTick ?? 0, ...(options.ctx === undefined ? {} : { ctx: options.ctx }), })) }) @@ -100,6 +99,37 @@ function makeRoot(): { container: HTMLDivElement; root: Root } { return { container, root: createRoot(container) } } +/** Menu surfaces are portaled to document.body, not into the lens container. */ +function menuItem(label: string): HTMLButtonElement { + const item = [...document.querySelectorAll('button[role="menuitem"]')] + .find(button => button.textContent?.trim() === label) + if (item === undefined) throw new Error(`menu item not found: ${label}`) + return item +} + +function openMoreSubmenu(container: HTMLElement, label: string): HTMLButtonElement[] { + const trigger = container.querySelector(`button[aria-label="${t('gitMoreActions')}"]`) + if (trigger === null) throw new Error('More Actions button not found') + act(() => { trigger.click() }) + const parent = menuItem(label) + expect(parent.getAttribute('aria-haspopup')).toBe('menu') + act(() => { parent.click() }) + return [...document.querySelectorAll('[role="menu"] [role="menu"] button[role="menuitem"]')] +} + +async function chooseMoreOption(container: HTMLElement, submenu: string, label: string): Promise { + const item = openMoreSubmenu(container, submenu).find(button => button.textContent?.trim() === label) + if (item === undefined) throw new Error(`submenu option not found: ${label}`) + await act(async () => { item.click() }) + await flushEffects() +} + +function branchButton(container: HTMLElement): HTMLButtonElement { + const button = container.querySelector('[data-git-footer] button[aria-haspopup="menu"]') + if (button === null) throw new Error('footer branch button not found') + return button +} + afterEach(() => { vi.restoreAllMocks() }) describe('GitLens (changes tab, git lens) linked-worktree consistency', () => { @@ -119,24 +149,21 @@ describe('GitLens (changes tab, git lens) linked-worktree consistency', () => { mountGit(root) await flushEffects() - const selects = container.querySelectorAll('select') - const worktreeSelect = selects[0]! // A clean primary + exactly one dirty linked checkout auto-selects the // linked checkout and loads every target-derived surface from it. - expect(worktreeSelect.value).toBe(AGENT) + expect(branchButton(container).textContent).toBe('agent*') expect(container.textContent).toContain('agent-change.ts') expect(container.textContent).toContain('Agent checkout commit') expect(container.textContent).not.toContain('Main checkout commit') expect(branch).toHaveBeenCalledWith(expect.anything(), AGENT) expect(log).toHaveBeenCalledWith(expect.anything(), 20, 0, AGENT) - - await act(async () => { - Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value')!.set!.call(worktreeSelect, MAIN) - worktreeSelect.dispatchEvent(new Event('change', { bubbles: true })) - }) + expect(container.querySelector('select')).toBeNull() + const options = openMoreSubmenu(container, t('worktree')) + expect(options.map(button => button.textContent)).toEqual(['main · main (0)', 'agent · agent (1)']) + await act(async () => { options[0]!.click() }) await flushEffects() - expect(worktreeSelect.value).toBe(MAIN) + expect(branchButton(container).textContent).toBe('main*') expect(container.textContent).toContain('main-change.ts') expect(container.textContent).toContain('Main checkout commit') expect(container.textContent).not.toContain('Agent checkout commit') @@ -169,17 +196,12 @@ describe('GitLens (changes tab, git lens) linked-worktree consistency', () => { mountGit(root) await flushEffects() - const worktreeSelect = container.querySelectorAll('select')[0]! - const loadMore = [...container.querySelectorAll('button')] - .find(button => /Load more|加载更多/.test(button.textContent ?? '')) + const loadMore = [...container.querySelectorAll('[data-scm-section="graph"] button')] + .find(button => button.textContent === t('loadMore')) expect(loadMore).not.toBeUndefined() await act(async () => { loadMore!.click() }) - await act(async () => { - Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value')!.set!.call(worktreeSelect, MAIN) - worktreeSelect.dispatchEvent(new Event('change', { bubbles: true })) - }) - await flushEffects() + await chooseMoreOption(container, t('worktree'), 'main · main (0)') expect(container.textContent).toContain('Main checkout commit 0') lateAgentPage.resolve(logFor(AGENT, 99)) @@ -209,7 +231,7 @@ describe('GitLens (changes tab, git lens) linked-worktree consistency', () => { ? { isRepo: true, branch: 'b-main', entries: [{ path: 'b-change.ts', xy: ' M' }], root: REPO_B, repositories: [REPO_B] } : { isRepo: true, branch: 'a-main', entries: [{ path: 'a-change.ts', xy: ' M' }], root: REPO_A, repositories: [REPO_A, REPO_B] } )) - vi.spyOn(api, 'gitBranch').mockImplementation(async (scope) => ( + const branch = vi.spyOn(api, 'gitBranch').mockImplementation(async (scope) => ( scope.repoRoot === REPO_B ? { current: 'b-main', names: ['b-main'] } : { current: 'a-main', names: ['a-main'] } )) vi.spyOn(api, 'gitLog').mockResolvedValue([]) @@ -221,15 +243,12 @@ describe('GitLens (changes tab, git lens) linked-worktree consistency', () => { mountGit(root, { scope: { sessionId: 'session', cwd: WS } }) await flushEffects() - // The workspace container's two child repositories are the repo choices. - const repoSelect = container.querySelectorAll('select')[0]! - expect([...repoSelect.options].map(option => option.textContent)).toEqual(['a', 'b']) + // The workspace container's child repositories retain their basename labels. + const repoOptions = openMoreSubmenu(container, t('gitRepository')) + expect(repoOptions.map(button => button.textContent)).toEqual(['a', 'b']) const listingsBefore = worktrees.mock.calls.length - await act(async () => { - Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value')!.set!.call(repoSelect, REPO_B) - repoSelect.dispatchEvent(new Event('change', { bubbles: true })) - }) + await act(async () => { repoOptions[1]!.click() }) await flushEffects() // The listing carries the selected repoRoot — a container's own listing @@ -240,18 +259,18 @@ describe('GitLens (changes tab, git lens) linked-worktree consistency', () => { expect(worktrees.mock.calls.length).toBe(listingsBefore + 1) // The shared status follows the same selection. expect(status.mock.calls.at(-1)![0]).toMatchObject({ sessionId: 'session', cwd: WS, repoRoot: REPO_B }) - expect(container.querySelector(`[title="${t('branch')}: b-main"]`)).not.toBeNull() + expect(branchButton(container).title).toBe(`${t('branch')}: b-main*`) expect(container.querySelector('[data-path="b-change.ts"]')).not.toBeNull() expect(container.querySelector('[data-path="a-change.ts"]')).toBeNull() - const worktreeSelect = container.querySelectorAll('select')[1]! - expect(worktreeSelect.value).toBe(REPO_B) + // Explicit repo selection keeps that repo's PRIMARY checkout, even with + // one dirty linked checkout available; every derived call targets it. + expect(branch).toHaveBeenLastCalledWith(expect.objectContaining({ repoRoot: REPO_B }), REPO_B) + expect(openMoreSubmenu(container, t('worktree')).map(button => button.textContent)) + .toEqual(['b-main · b (0)', 'b-agent · b-agent (2)']) + act(() => { document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })) }) - await act(async () => { - repoSelect.value = REPO_A - repoSelect.dispatchEvent(new Event('change', { bubbles: true })) - }) - await flushEffects() - expect(container.querySelector(`[title="${t('branch')}: a-main"]`)).not.toBeNull() + await chooseMoreOption(container, t('gitRepository'), 'a') + expect(branchButton(container).title).toBe(`${t('branch')}: a-main*`) expect(container.querySelector('[data-path="a-change.ts"]')).not.toBeNull() expect(container.querySelector('[data-path="b-change.ts"]')).toBeNull() } finally { @@ -266,7 +285,7 @@ describe('GitLens (changes tab, git lens) linked-worktree consistency', () => { { path: AGENT, branch: 'agent', current: false, changes: 0 }, { path: AGENT_2, branch: 'agent-2', current: false, changes: 5 }, ] - vi.spyOn(api, 'gitWorktrees') + const worktrees = vi.spyOn(api, 'gitWorktrees') .mockResolvedValueOnce(inventories) .mockResolvedValue(LATER) vi.spyOn(api, 'gitStatus').mockImplementation(async (_scope, target) => statusFor(target)) @@ -282,15 +301,17 @@ describe('GitLens (changes tab, git lens) linked-worktree consistency', () => { try { mountGit(root) await flushEffects() - const worktreeSelect = container.querySelectorAll('select')[0]! - expect(worktreeSelect.value).toBe(AGENT) + expect(branchButton(container).textContent).toBe('agent*') // A later inventory pass prefers the brand-new dirty checkout; the user // never chose a checkout, but the ONE automatic pass already ran. - mountGit(root, { refreshTick: 1 }) + const refresh = container.querySelector(`[data-scm-section="changes"] button[aria-label="${t('refresh')}"]`) + expect(refresh).not.toBeNull() + await act(async () => { refresh!.click() }) await flushEffects() + expect(worktrees).toHaveBeenCalledTimes(2) - expect(worktreeSelect.value).toBe(AGENT) + expect(branchButton(container).textContent).toBe('agent*') expect(container.textContent).toContain('agent-change.ts') expect(container.textContent).not.toContain('agent-2-change.ts') } finally { @@ -319,8 +340,12 @@ describe('GitLens (changes tab, git lens) linked-worktree consistency', () => { await flushEffects() expect(worktrees).toHaveBeenCalledTimes(1) - // The header's refresh action lands while the mount pass is in flight. - mountGit(root, { refreshTick: 1 }) + // Changes refresh lands while the mount's inventory pass is in flight. + // Shared status already knows this is a repo, so the action is available. + const refresh = container.querySelector(`[data-scm-section="changes"] button[aria-label="${t('refresh')}"]`) + expect(refresh).not.toBeNull() + expect(refresh!.disabled).toBe(false) + await act(async () => { refresh!.click() }) await flushEffects() // Queued, not dropped and not started in parallel. expect(worktrees).toHaveBeenCalledTimes(1) @@ -410,7 +435,7 @@ describe('GitLens (changes tab, git lens) linked-worktree consistency', () => { } }) - it('keeps branch switch and history failures out of the commit bar', async () => { + it('keeps branch switch and history failures in the view banner, not the footer action status', async () => { vi.spyOn(api, 'gitWorktrees').mockResolvedValue([ { path: MAIN, branch: 'main', current: true, changes: 1 }, ]) @@ -428,20 +453,22 @@ describe('GitLens (changes tab, git lens) linked-worktree consistency', () => { mountGit(root) await flushEffects() - const branchSelect = container.querySelectorAll('select')[0]! - await act(async () => { - Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value')!.set!.call(branchSelect, 'feature') - branchSelect.dispatchEvent(new Event('change', { bubbles: true })) - }) + // The entire footer branch button opens a menu of PLAIN branch names; + // the dirty marker belongs only to the footer label, never its options. + expect(branchButton(container).textContent).toBe('main*') + act(() => { branchButton(container).click() }) + expect([...document.querySelectorAll('[role="menuitem"]')].map(item => item.textContent)).toEqual(['main', 'feature']) + await act(async () => { menuItem('feature').click() }) await flushEffects() const banner = [...container.querySelectorAll('[role="alert"]')] .find(node => (node.textContent ?? '').includes(`${t('checkoutError')}: dirty worktree`)) expect(banner).toBeDefined() - const input = container.querySelector(`textarea[placeholder="${t('commitPlaceholder')}"]`) + const input = container.querySelector('[data-message-box] textarea') expect(input).not.toBeNull() - // The commit bar owns only its own status line: the branch failure is - // rendered ABOVE it, never under the commit input. + // Branch/history failures are view-level, not the shared action channel. + expect(banner!.parentElement).toBe(container.querySelector('[data-git-scroll]')) + expect(container.querySelector('[data-git-footer] [role="alert"]')).toBeNull() expect(banner!.compareDocumentPosition(input!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() } finally { act(() => { root.unmount() }) @@ -474,24 +501,24 @@ describe('GitLens (changes tab, git lens) change tree', () => { { path: 'src/b.ts', xy: 'M ' }, // staged side ]) - const dirs = () => [...container.querySelectorAll('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() + const dir = (group: string): HTMLButtonElement => + container.querySelector(`[data-group="${group}"] button[data-dir="src"]`)! + // One 'src' row per group, independent of the sections' display order. + expect(container.querySelectorAll('button[data-dir="src"]')).toHaveLength(2) + expect(dir('unstaged').getAttribute('aria-expanded')).toBe('true') + expect(dir('unstaged').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() }) + await act(async () => { dir('unstaged').click() }) // Folded: the unstaged subtree is gone... - expect(dirs()[0]!.getAttribute('aria-expanded')).toBe('false') + expect(dir('unstaged').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(dir('staged').getAttribute('aria-expanded')).toBe('true') expect(container.querySelector('button[data-path="src/b.ts"]')).not.toBeNull() - await act(async () => { dirs()[0]!.click() }) + await act(async () => { dir('unstaged').click() }) expect(container.querySelector('button[data-path="src/a.ts"]')).not.toBeNull() } finally { act(() => { root.unmount() }) @@ -515,7 +542,8 @@ describe('GitLens (changes tab, git lens) change tree', () => { // 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. + // Nothing on the staged side: no empty group and no tree rows. + expect(container.querySelector('[data-group="staged"]')).toBeNull() expect(container.querySelectorAll('[data-group="staged"] [data-path]')).toHaveLength(0) } finally { act(() => { root.unmount() }) @@ -556,7 +584,8 @@ describe('GitLens (changes tab, git lens) change tree', () => { const unstaged = container.querySelector('[data-group="unstaged"]')! const staged = container.querySelector('[data-group="staged"]')! - expect(unstaged.textContent).toContain(t('unstaged')) + expect(unstaged.textContent).toContain(t('gitChanges')) + expect(staged.textContent).toContain(t('gitStagedChanges')) expect(unstaged.querySelector('[data-count]')?.textContent).toBe('2') expect(staged.querySelector('[data-count]')?.textContent).toBe('1') @@ -873,7 +902,7 @@ describe('GitLens (changes tab, git lens) scope swap', () => { // Re-queried on every use: a re-render may hand back a different node, and // a detached one keeps whatever its last render set. const box = (): HTMLTextAreaElement | null => - container.querySelector(`textarea[placeholder="${t('commitPlaceholder')}"]`) + container.querySelector('[data-message-box] textarea') const typeInto = async (text: string): Promise => { await act(async () => { const node = box()