/** * Source Control inside the unchanged changes-tab shell: independent Changes * and Graph disclosures, a draft above the resource groups, and a sticky * checkout/sync footer. Status still comes from the one shared Git poller; * mutations, worktree inventory and history reuse the existing host routes. * * UI semantics reference: VS Code 76f9f309edc0682f4ef9465be8d12af754b87236, * extensions/git and src/vs/workbench/contrib/scm (not a runtime dependency). */ import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent, type ReactNode } from 'react' import { IconBranchOutlineRegular, IconCheckOutlineRegular, IconChevronRightOutlineRegular, IconCloseFillRegular, IconCodeOutlineRegular, IconCopyOutlineRegular, IconEllipsisOutlineRegular, IconPlusOutlineRegular, IconRefreshOutlineRegular, IconSparkleRegular, IconTrashOutlineRegular, writeClipboard, } from '@deepseek-ai/dsh-client-ui-primitives' import type { Context } from '../../context-types.ts' import type { GitLineCounts, GitLogEntry, GitStatusEntry, GitStatusResult, GitWorktree, SessionScope } from '../api.ts' import { api, SidebarApiError } from '../api.ts' import { builtinFileIcon, builtinFolderIcon } from '../file-icons.tsx' import { usePolling } from '../use-polling.ts' import { baseName, relativeTo } from '../paths.ts' import { resolveSidebarPath } from '../paths.ts' import { isZh, t } from '../locales.ts' import { GitGraphSection, type GraphDetailsSelection } from './GitGraphSection.tsx' import type { SidebarDiffRef } from '../state.ts' import { buildRepositoryLabels } from './repo-labels.ts' import { RepoSwitcher } from './RepoSwitcher.tsx' import { ActionButton, ConfirmDialog, IconButton, Menu, Notice, StatusBadge, TextArea, WorkbenchSection, WorkbenchStack, 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' import diffCss from '../diff/diff.module.css' import css from './changes.module.css' /** Whether the entry carries STAGED (index) changes — the X letter is set. */ function isStagedEntry(entry: GitStatusEntry): boolean { return statusOfXY(entry.xy)?.staged === true } /** Whether the entry carries UNSTAGED (worktree) changes — the Y letter is set * (untracked `??` counts as unstaged: it is a worktree-only change). A file * with both letters set ('MM') lands in BOTH sections. */ function isUnstagedEntry(entry: GitStatusEntry): boolean { return statusOfXY(entry.xy)?.unstaged === true } /** Whether a row is untracked (`??`): git diff never includes it, so the * preview and the discard action must know. */ function isUntrackedStatus(status: GitFileStatus): boolean { return status.tone === 'untracked' } /** The porcelain tone → the kit badge tone (a copy reads as a rename). */ const BADGE_TONE: Record = { modified: 'modified', added: 'added', deleted: 'deleted', untracked: 'untracked', renamed: 'renamed', copied: 'renamed', conflict: 'conflict', } /** One thrown value as display text (every error line here normalizes through * this so non-Error rejections never render as '[object Object]'). */ function errorMessage(reason: unknown): string { return reason instanceof Error ? reason.message : String(reason) } /** Existing Host fact used only to disambiguate ambiguous path spellings (a * leading `//` is either POSIX or Windows UNC). Read through the guarded * face; never rendered and never requested. */ function hostHomeOf(ctx: Context | undefined): string | undefined { try { const remote = ctx?.get('remote') as { $host?: { home?: unknown } } | undefined return typeof remote?.$host?.home === 'string' ? remote.$host.home : undefined } catch { // A composition without the Remote service must not take the lens down. return undefined } } /** 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. * * Case folds only for Windows spellings. POSIX keeps case: a container * workspace can legally hold `Foo` and `foo` as two different checkouts, and * folding would light up both chips. */ function rootKey(value: string | undefined): string { const key = (value ?? '').replaceAll('\\', '/').replace(/\/+$/, '') return /^[a-zA-Z]:\//.test(key) ? key.toLowerCase() : key } /** 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 * poll; a field-by-field compare is what lets an unchanged silent tick stay * silent (see `runOnce`). */ function sameWorktrees(left: readonly GitWorktree[], right: readonly GitWorktree[]): boolean { if (left === right) return true if (left.length !== right.length) return false return left.every((entry, index) => { const other = right[index]! return entry.path === other.path && entry.branch === other.branch && entry.current === other.current && entry.changes === other.changes }) } /** * How many scopes' commit drafts are remembered. The lens is a kept-mounted tab * body, so this record lives for the page: without a bound, a session that * walked through many projects would pin one message per project forever. */ export const COMMIT_DRAFT_CAP = 32 /** * Write one scope's draft into the record, remembering at most * {@link COMMIT_DRAFT_CAP} scopes. Re-writing a key moves it to the back, so * the draft evicted past the cap is the scope typed into longest ago — a typed * message for another project is never what a commit here submits (the record * is keyed by scope, and `commit()` reads only its own key). * * @param prev - the current record (never mutated). * @param key - the scope key (session + cwd). * @param text - the draft (`''` = cleared; the key stays, so it reads back as * an empty box rather than as a missing one). * @returns the next record. */ export function withCommitDraft( prev: Record, key: string, text: string, ): Record { const next: Record = { ...prev } delete next[key] next[key] = text const keys = Object.keys(next) for (const stale of keys.slice(0, Math.max(0, keys.length - COMMIT_DRAFT_CAP))) delete next[stale] return next } /** The pending destructive action (discard / revert / cherry-pick), gated by a confirm dialog. */ interface ConfirmState { title: string description: string confirmLabel: string onConfirm: () => Promise } /** One open file-row context menu (cursor position for the portaled Menu). */ interface FileMenuState { path: string staged: boolean untracked: boolean x: number y: number } /** History batch size: the log loads lazily in pages so a long history never * floods the panel at once (the end of the log is reached by paging). */ /** Cadence of the background worktree re-list: the shared status store already * polls the selected checkout's status, so the inventory (a different call) * only needs to notice a linked checkout the agent created mid-session — * within ~30s, without a second git process per status tick. */ const WORKTREE_POLL_MS = 30_000 /** 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): the // unstage affordance. The stage side reuses the host's own Plus, so the two // directions never read as the same action (VS Code's `$(remove)` / `$(add)`). const MINUS_ICON = /** The tree's indent guides: one hairline per level ABOVE the row (the group's * own column carries no line), drawn in the same 12px column the old nested * tree used to draw at — 17px for the first level, +12 per level — so a deep * path reads as deep as it did before the SCM rewrite. The lines are absolutely * placed (no part in the flex row's metrics) and span the whole 28px band, so * they stay continuous across every sibling and every hover/selected fill. */ function IndentGuides(props: { depth: number }): ReactNode { return <>{Array.from({ length: props.depth }, (_, index) => (