@laoyuehanni/dsh-git-worktree 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","names":["error","useRef","useState","useMemo","useCallback","css","IconChevronRightOutline14","IconCheckOutline16","IconChevronDownOutline14","createPortal","IconGoalOutline16","IconChevronUpOutline14","useState","useCallback","useRef","createPortal","css","useMemo","IconBranchOutline16","Toast","useState","css","IconChevronDownOutline14"],"sources":["../src/normalize.ts","../src/wire.ts","../src/client/api.ts","../src/client/BranchMenu.tsx","../src/client/BranchChip.tsx","../src/client/card-form.ts","../src/client/GitWorktreeCard.tsx","../src/client/locales.ts","../src/client/index.ts"],"sourcesContent":["/**\n * Pure branch/path name normalization for worktree directory placement.\n * Windows-forbidden characters are the governing constraint: a worktree\n * folder name must survive on every platform the host runs on.\n */\n\n/**\n * Turn a branch display name into a single safe directory segment.\n * `feat/auth-login` → `feat-auth-login`; every Windows-forbidden character\n * (`<>:\"|?*`, control chars) and `/` become `-`; runs of separators (`-`,\n * `.`, whitespace — so a `//` or a git-illegal `..` collapses too) merge to\n * one `-`; a single interior `.` survives (`v1.2.3` stays readable); trailing\n * dots and spaces (Windows-forbidden suffixes) are stripped; the result is\n * clamped to 64 characters and never empty or dash-only.\n * @param branch - branch display name (local or `remote/name` form).\n * @returns a safe single path segment.\n */\nexport function sanitizeBranchDir(branch: string): string {\n const replaced = branch.replace(/[<>:\"/\\\\|?*\\u0000-\\u001f\\s]/g, '-')\n const merged = replaced.replace(/[-.]{2,}/g, '-')\n const trimmed = merged.replace(/[.\\s-]+$/, '')\n const clamped = trimmed.slice(0, 64).replace(/[.\\s-]+$/, '')\n return clamped === '' || clamped.replaceAll('-', '') === '' ? 'branch' : clamped\n}\n\n/**\n * Local branch name for a display name: strip the leading `<remote>/` segment\n * when one is present (`origin/feat/x` → `feat/x`). A local branch whose own\n * name contains `/` (like `feat/x`) passes through unchanged — callers that\n * need certainty compare against the authoritative branch list instead.\n * @param branch - branch display name.\n * @returns the candidate local branch name.\n */\nexport function localBranchName(branch: string): string {\n const at = branch.indexOf('/')\n return at <= 0 ? branch : branch.slice(at + 1)\n}\n\n/**\n * Split a `<remote>/<name>` display name when it plausibly names a remote\n * branch: the first `/`-separated segment is treated as the remote.\n * @param branch - branch display name.\n * @returns the remote part and the local-twin name, or undefined when the\n * name has no `/` (a local branch or a bare word).\n */\nexport function splitRemoteBranch(branch: string): { remote: string; name: string } | undefined {\n const at = branch.indexOf('/')\n if (at <= 0) return undefined\n return { remote: branch.slice(0, at), name: branch.slice(at + 1) }\n}\n\n/**\n * Validate a user-configured worktree storage root: an absolute path on any\n * platform (POSIX `/…`, Windows drive `C:\\…`/`C:/…`, or UNC `\\\\…`).\n * @param value - raw settings string.\n * @returns true when the value names an absolute path.\n */\nexport function isAbsoluteConfigPath(value: string): boolean {\n if (value === '') return false\n if (value.startsWith('/') || value.startsWith('\\\\')) return true\n return /^[a-zA-Z]:[\\\\/]/.test(value)\n}\n","/**\n * Shared wire contract between the host half (HTTP routes under\n * `/plugin/git-worktree`) and the browser half (chip + plugin settings card).\n * Zero runtime dependencies: constants and types only, imported by both\n * builds.\n */\n\n/** Absolute pathname prefix every route of this plugin lives under. */\nexport const ROUTE_PREFIX = '/plugin/git-worktree'\n\n/** GET ROUTE_PREFIX/status?path=<absolute dir> */\nexport const ROUTE_STATUS = `${ROUTE_PREFIX}/status`\n\n/** POST ROUTE_PREFIX/worktree — create-or-reuse a worktree for a branch. */\nexport const ROUTE_WORKTREE = `${ROUTE_PREFIX}/worktree`\n\n/** POST ROUTE_PREFIX/switch — in-place branch switch of the main checkout. */\nexport const ROUTE_SWITCH = `${ROUTE_PREFIX}/switch`\n\n/** One selectable branch row. */\nexport interface BranchEntry {\n /** Display name: a bare local name (`main`) or `<remote>/<name>`. */\n name: string\n kind: 'local' | 'remote'\n}\n\n/** One existing worktree of the repository. */\nexport interface WorktreeEntry {\n /** Absolute path of the worktree directory. */\n path: string\n /** Checked-out local branch name; absent for a detached or bare worktree. */\n branch: string | undefined\n /** True for the main worktree (the one holding `.git`). */\n main: boolean\n}\n\n/** Response of GET status — `repo: false` for a directory outside any git repository. */\nexport type RepoStatus =\n | { repo: false }\n | {\n repo: true\n /** Main repository directory basename — the root folder of `<rootDir>/<repoName>/`. */\n repoName: string\n /** Absolute path of the main worktree directory. */\n repoRoot: string\n /** Branch checked out by the directory the client asked about. */\n currentBranch: string\n /** Local branches plus remote branches without a same-named local one. */\n branches: BranchEntry[]\n /** Every worktree of the repository, main first (git order). */\n worktrees: WorktreeEntry[]\n /** Resolved worktree storage root (absolute) — what the settings say today. */\n rootDir: string\n }\n\n/** POST worktree request body. */\nexport interface CreateWorktreeBody {\n /** Any directory inside the repository (workspace cwd). */\n repoPath: string\n /** Chosen branch display name: local (`feat-x`) or remote (`origin/feat-x`). */\n branch: string\n /** True: cut a NEW branch out of `branch` (the current checkout's\n * branch — occupied by the main worktree) and isolate it in a fresh\n * worktree. The storage folder is named after the new branch. */\n cutout?: boolean\n}\n\n/** POST worktree response body. */\nexport interface CreateWorktreeResult {\n /** The worktree directory (created or reused). */\n path: string\n /** False when an existing worktree for the branch was reused. */\n created: boolean\n}\n\n/** POST switch request body. */\nexport interface SwitchBody {\n /** Any directory inside the main worktree. */\n repoPath: string\n /** Target branch display name (local, or remote whose local twin is created by dwim). */\n branch: string\n}\n\n/** POST switch response body. */\nexport interface SwitchResult {\n /** The branch actually checked out after the switch. */\n branch: string\n}\n\n/** Error envelope every non-2xx response carries. */\nexport interface RouteError {\n error: string\n}\n","/**\n * Browser-side fetch client for the plugin's host routes. Plain fetch against\n * same-origin paths; every failure resolves to `{ error }` so callers can\n * branch without try/catch.\n */\n\nimport type {\n CreateWorktreeResult, RepoStatus, RouteError, SwitchResult,\n} from '../wire.ts'\nimport { ROUTE_STATUS, ROUTE_SWITCH, ROUTE_WORKTREE } from '../wire.ts'\n\n/** One route call outcome: the parsed body, or the error envelope text. */\ntype Call<T> = (T & { ok: true }) | { ok: false; error: string }\n\n/** POST one JSON body and parse the uniform envelope. */\nasync function post<T>(url: string, body: unknown): Promise<Call<T>> {\n return send<T>('POST', url, body)\n}\n\n/** Send one JSON body with any method and parse the uniform envelope. */\nasync function send<T>(method: string, url: string, body: unknown): Promise<Call<T>> {\n try {\n const response = await fetch(url, {\n method,\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n })\n const payload: unknown = await response.json()\n if (!response.ok) {\n const error = payload as RouteError\n return { ok: false, error: error.error ?? `HTTP ${String(response.status)}` }\n }\n return { ...(payload as T), ok: true }\n } catch (cause) {\n return { ok: false, error: cause instanceof Error ? cause.message : String(cause) }\n }\n}\n\n/**\n * Repository status for one directory.\n * @param path - absolute workspace directory.\n */\nexport async function fetchStatus(path: string): Promise<Call<RepoStatus>> {\n try {\n const response = await fetch(`${ROUTE_STATUS}?path=${encodeURIComponent(path)}`, { cache: 'no-store' })\n if (!response.ok) return { ok: false, error: `HTTP ${String(response.status)}` }\n return { ...(await response.json() as RepoStatus), ok: true }\n } catch (cause) {\n return { ok: false, error: cause instanceof Error ? cause.message : String(cause) }\n }\n}\n\n/**\n * Create or reuse the worktree for a branch.\n * @param repoPath - absolute directory inside the repository.\n * @param branch - branch display name.\n */\nexport function requestWorktree(repoPath: string, branch: string): Promise<Call<CreateWorktreeResult>> {\n return post<CreateWorktreeResult>(ROUTE_WORKTREE, { repoPath, branch })\n}\n\n/**\n * Cut a NEW branch out of the current checkout and isolate it in a fresh\n * worktree (the current branch itself is occupied by the main worktree).\n * @param repoPath - absolute directory inside the repository.\n * @param branch - the current checkout's branch (or `HEAD` when detached).\n */\nexport function requestWorktreeCutout(repoPath: string, branch: string): Promise<Call<CreateWorktreeResult>> {\n return post<CreateWorktreeResult>(ROUTE_WORKTREE, { repoPath, branch, cutout: true })\n}\n\n/**\n * Switch the main checkout in place.\n * @param repoPath - absolute directory inside the main worktree.\n * @param branch - branch display name.\n */\nexport function requestSwitch(repoPath: string, branch: string): Promise<Call<SwitchResult>> {\n return post<SwitchResult>(ROUTE_SWITCH, { repoPath, branch })\n}\n","/**\n * BranchMenu: the branch picker popup anchored to the composer branch chip.\n * The base Menu primitive exposes neither a height cap nor a search field,\n * so with many branches its portal list fills the viewport — this popup\n * replaces it with an owner-styled card: Menu's card chrome (r12, inverted\n * hairline, shadow-lv3, --dsw-specific-menu, see .menuCard) on a\n * portal-fixed posture, with owner requirements baked in:\n *\n * 1. the card is capped at min(420px, 60vh) and only the branch rows\n * scroll (heading, search, and the toolbar stay pinned);\n * 2. a search field is pinned at the card's bottom edge — the row list\n * scrolls above it — filtering rows by case-insensitive substring\n * while KEEPING the matching branches' ancestor folders (IDEA-style\n * prune) and highlighting the hit substring;\n * 3. the card opens entirely above the chip: the CSS `bottom` pins its\n * bottom edge ~6px above the chip's top, so it grows upward and can\n * never cover the composer, whatever the branch count.\n *\n * Layout (IDEA branch-panel posture at popup scale): a narrow tool strip\n * on the left (locate-current + expand/collapse-all), then a main column\n * of heading / tree / search. Selection model borrowed from IDEA: a\n * single click SELECTS a row (blue); double-click or Enter then OPENS the\n * right-side confirm flyout for that row — the switch itself always goes\n * through the confirmation step, never straight away. While the confirm\n * flyout is open, clicking another row re-anchors it (the old one-click\n * pick flow).\n *\n * The confirm step is a second-level flyout opening to the RIGHT of the\n * branch card (the base Menu's submenu posture): the chip sits in the\n * bottom composer, so the old below-the-chip bubble landed off-viewport.\n * The flyout is a separate portal (not clipped by the card's\n * overflow:hidden), horizontally anchored to the card's right edge — it\n * can never overlap the branch list — and vertically centered on the\n * picked row. Its width is content-driven, capped in CSS, wrapping.\n *\n * Close semantics: outside pointerdown (card, flyout, and chip excluded)\n * cancels the confirm and closes the menu; Escape unwinds tier by tier —\n * confirm, then search text, then selection, then the menu; Enter in the\n * search field commits the first enabled visible row.\n *\n * Long names and many branches: a clipped label shows the full name on\n * hover via the native title (gated to actually-clipped rows only). When\n * the list grows past TREE_MIN_ROWS it renders as a full-depth '/' prefix\n * tree instead: folder-header rows (chevron + count) toggle; under an\n * expanded folder, child rows show only their own segment (indentation\n * carries the hierarchy — no repeated path, no color distinction); linear\n * chains compress into one row; the checked-out branch's chain opens by\n * default (centering still lands it mid-viewport).\n */\n\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'\nimport { createPortal } from 'react-dom'\nimport {\n IconCheckOutline16,\n IconChevronDownOutline14,\n IconChevronRightOutline14,\n IconChevronUpOutline14,\n IconGoalOutline16,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'\nimport css from './BranchChip.module.css'\n\n/** One selectable branch row (disabled = checked out by a live worktree). */\nexport interface BranchRow {\n name: string\n disabled: boolean\n}\n\n/** The confirm flyout bundle, owned and localized by the caller. */\nexport interface BranchConfirmFly {\n /** Ask line (already localized). */\n ask: string\n /** Confirm-button label (progress text while busy). */\n confirmLabel: string\n /** Cancel-button label. */\n cancelLabel: string\n /** True while the action runs: both buttons disable. */\n busy: boolean\n /** Run the confirmed action. */\n onConfirm: () => void\n /** Dismiss the flyout without acting (stays on the open menu). */\n onCancel: () => void\n}\n\n/** Full props: anchor + data + confirm bundle + callbacks + locale seat. */\nexport interface BranchMenuProps {\n /** Whether the popup shows. */\n open: boolean\n /** The chip element — the popup's bottom edge pins just above its top. */\n anchorRef: React.RefObject<HTMLElement | null>\n /** Every local branch as a row (occupancy-disabled rows included). */\n rows: readonly BranchRow[]\n /** The branch currently checked out (trailing check, HEAD tint). */\n currentBranch: string\n /** Non-null while a picked branch awaits confirmation. */\n confirm: BranchConfirmFly | null\n /** Stage a pick (starts the confirm flyout beside that row). Current\n * branch re-select closes the menu unless the owner stages otherwise. */\n onSelect: (branch: string) => void\n /** Dismiss the menu (outside click, Escape with nothing open). */\n onClose: () => void\n /** Bound locale translate (placeholder, empty state, heading, toolbar). */\n t: PropsLocale<'git-worktree'>['t']\n}\n\n/** Viewport edge clearance, mirroring the base Menu portal margin. */\nconst MARGIN = 12\n/** Gap kept between the chip's top edge and the card's bottom edge. */\nconst GAP = 6\n/** Design card width — the CSS width's px arm; used for horizontal clamping. */\nconst CARD_WIDTH = 360\n/** Design flyout width cap — matches .popCard's max-width arm. */\nconst FLY_MAX_WIDTH = 400\n/** After a folder toggle, clicks arriving within this window are swallowed\n * (double-click misfire guard — see shiftGuardUntil in the component). */\nconst CLICK_GUARD_MS = 250\n/** Unplaced flyout: hidden but laid out at a fixed origin so offsetWidth/\n * offsetHeight are real for the measure-then-place pass (base Menu trick). */\nconst FLY_MEASURE: Partial<CSSStyleDeclaration> = { left: '-9999px', top: '0px', visibility: 'hidden' }\n\n/** Below this many rows the picker stays a flat list: in small repos a\n * tree would hide real branches behind one-entry folders, buying nothing. */\nconst TREE_MIN_ROWS = 8\n\n/** One node of the '/' prefix tree built from the row list: every segment\n * boundary is a folder level, so `feature/x/y` nests under `feature` and\n * `x`, and the leaves (rows) sit at the terminal nodes. */\ninterface TreeNode {\n /** This node's own segment (the label text). */\n segment: string\n /** Full path: segments joined by '/'. Empty only at the root list. */\n path: string\n /** Depth from the root (root children are depth 0). */\n depth: number\n /** The branch named exactly `path`, if any — may coexist with children\n * (`feature` plus `feature/x` are both legal git branch names). */\n leaf: BranchRow | null\n /** Children, sorted folders-first then by segment. */\n children: TreeNode[]\n /** Leaf branches under this node, including its own leaf. */\n total: number\n}\n\nconst segCmp = (a: string, b: string): number =>\n a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })\n\n/** Build the prefix tree of the rows (see TreeNode). */\nfunction buildTree(rows: readonly BranchRow[]): TreeNode[] {\n /** Mutable builder node — same shape as TreeNode but built incrementally\n * (find-by-segment walks), sorted and totalled at the end. */\n interface M {\n segment: string\n path: string\n depth: number\n leaf: BranchRow | null\n children: M[]\n total: number\n }\n const root: M[] = []\n const find = (level: M[], segment: string): M | undefined =>\n level.find(n => n.segment === segment)\n for (const row of rows) {\n const segs = row.name.split('/').filter(s => s !== '')\n let level = root\n let path = ''\n for (let i = 0; i < segs.length; i += 1) {\n path = path === '' ? segs[i] : `${path}/${segs[i]}`\n let node = find(level, segs[i])\n if (node === undefined) {\n node = { segment: segs[i], path, depth: i, leaf: null, children: [], total: 0 }\n level.push(node)\n }\n if (i === segs.length - 1) node.leaf = row\n level = node.children\n }\n }\n const finish = (nodes: M[]): void => {\n for (const node of nodes) finish(node.children)\n nodes.sort((a, b) => {\n const af = a.children.length > 0 ? 0 : 1\n const bf = b.children.length > 0 ? 0 : 1\n return af !== bf ? af - bf : segCmp(a.segment, b.segment)\n })\n }\n finish(root)\n const count = (nodes: M[]): void => {\n for (const node of nodes) {\n count(node.children)\n node.total = (node.leaf === null ? 0 : 1)\n + node.children.reduce((sum, c) => sum + c.total, 0)\n }\n }\n count(root)\n return root as unknown as TreeNode[]\n}\n\n/** The folders that must start expanded so the checked-out branch is\n * immediately visible in the tree: every proper ancestor of its path. */\nfunction chainExpanded(branch: string): Set<string> {\n const segs = branch.split('/').filter(s => s !== '')\n const set = new Set<string>()\n let path = ''\n for (let i = 0; i < segs.length - 1; i += 1) {\n path = path === '' ? segs[i] : `${path}/${segs[i]}`\n set.add(path)\n }\n return set\n}\n\n/** Hover tooltip: set the native `title` ONLY when the label is actually\n * clipped (scrollWidth > clientWidth) — fitted names show no tooltip, and\n * long ones expose their full path without a custom bubble. The target is\n * the label span (first span child), the clipped element. */\nconst gateTooltip = (button: HTMLButtonElement, name: string): void => {\n const label = button.querySelector<HTMLElement>(':scope > span')\n if (label !== null) label.title = label.scrollWidth > label.clientWidth ? name : ''\n}\n\n/** Leaving a row drops its tooltip so a recycled DOM node (search refilter)\n * can never show a stale title for another branch. */\nconst clearTooltip = (button: HTMLButtonElement): void => {\n const label = button.querySelector<HTMLElement>(':scope > span')\n if (label !== null) label.title = ''\n}\n\n/**\n * Render the upward branch picker with its right-side confirm flyout.\n * @param props - anchor, rows, confirm bundle, callbacks, and the class sheet.\n * @returns null while closed or unplaced; otherwise the portaled card (+flyout).\n */\nexport function BranchMenu({\n open, anchorRef, rows, currentBranch, confirm, onSelect, onClose, t,\n}: BranchMenuProps) {\n const cardRef = useRef<HTMLDivElement>(null)\n const inputRef = useRef<HTMLInputElement | null>(null)\n /**\n * Search-field ref callback: focus the field the moment it mounts. The\n * card mounts in two stages (open flips, then pos resolves a render\n * later), so an [open]-keyed passive effect fires while the input is\n * still unmounted — its focus() no-ops against a null ref. Focusing at\n * mount time is immune to that race by construction.\n */\n const holdSearchFocus = (el: HTMLInputElement | null): void => {\n inputRef.current = el\n if (el !== null) el.focus()\n }\n const flyRef = useRef<HTMLDivElement>(null)\n const flyConfirmRef = useRef<HTMLButtonElement | null>(null)\n /** The row whose pick is awaiting confirmation (anchoring element). */\n const pendingRef = useRef<{ name: string; el: HTMLElement } | null>(null)\n /** Pending row's name — the placement-effect trigger: picking another\n * row while the flyout is open must re-anchor it (confirmOpen alone\n * stays true, so a ref mutation re-renders nothing). */\n const [pendingName, setPendingName] = useState<string | null>(null)\n const [pos, setPos] = useState<{ left: number; bottom: number } | null>(null)\n const [flyPos, setFlyPos] = useState<{ left: number; top: number } | null>(null)\n const [query, setQuery] = useState('')\n /** Expanded folder set, keyed by node path. Re-seeded on every open so\n * the current branch's chain is visible without re-expanding by hand. */\n const [expanded, setExpanded] = useState<ReadonlySet<string>>(new Set())\n /** IDEA-style selection: clicked row (blue). Zero or one at a time. */\n const [selected, setSelected] = useState<string | null>(null)\n\n // Latest values for stable-effect listeners (the parent rebuilds the\n // confirm object each render; refs keep the document-level keydown and\n // outside-click handlers from going stale on the closure they captured).\n const confirmRef = useRef(confirm)\n confirmRef.current = confirm\n const queryRef = useRef(query)\n queryRef.current = query\n const selectedRef = useRef(selected)\n selectedRef.current = selected\n /** Always-fresh pick for the stale-safe document keydown listener. */\n const pickRef = useRef<(el: HTMLElement | null, name: string) => void>(() => {})\n const confirmOpen = confirm !== null\n\n /**\n * Double-click misfire guard: toggling a folder shifts the layout — the\n * second click of a double-click can land on a row that slid under the\n * cursor (a branch!), which would select it or pop the switch flyout.\n * After a folder toggle, every click swallowed for CLICK_GUARD_MS, so a\n * double-click on a folder expands it exactly once and never bleeds into\n * a branch click. Branch-row clicks do not arm the guard (selecting does\n * not move anything), so row double-clicks keep working instantly.\n */\n const shiftGuardUntil = useRef(0)\n const guardActive = (): boolean => Date.now() < shiftGuardUntil.current\n const armShiftGuard = (): void => { shiftGuardUntil.current = Date.now() + CLICK_GUARD_MS }\n\n /** Stage a pick: remember the row element (the flyout anchors beside\n * it), then hand the branch to the owner. All pick paths — search Enter,\n * keyboard Enter on a selected row — funnel through here. */\n const pick = (el: HTMLElement | null, name: string): void => {\n if (el !== null) pendingRef.current = { name, el }\n setPendingName(name)\n onSelect(name)\n }\n pickRef.current = pick\n\n /** Prefix tree when the list is big enough to need one; null (flat list)\n * below TREE_MIN_ROWS. Built once per rows change. */\n const tree = useMemo(\n () => (rows.length > TREE_MIN_ROWS ? buildTree(rows) : null),\n [rows],\n )\n\n /** Every folder path that renders a header — the expand/collapse-all\n * button's scope. */\n const folderPaths = useMemo(() => {\n const out: string[] = []\n const walk = (nodes: TreeNode[]): void => {\n for (const node of nodes) {\n if (node.children.length > 0) out.push(node.path)\n walk(node.children)\n }\n }\n if (tree !== null) walk(tree)\n return out\n }, [tree])\n const allExpanded = folderPaths.length > 0 && folderPaths.every(p => expanded.has(p))\n const toggleAll = (): void => {\n setExpanded(allExpanded ? new Set() : new Set(folderPaths))\n }\n const locateCurrent = (): void => {\n // Locate, don't restructure: only ADD the current branch's ancestor\n // folders if they happen to be closed (the row must exist to scroll\n // to it) — folders the user expanded/collapsed stay untouched. Then\n // center the row one frame later, once the re-render has committed.\n setExpanded(prev => {\n const next = new Set(prev)\n for (const p of chainExpanded(currentBranch)) next.add(p)\n return next\n })\n requestAnimationFrame(() => {\n if (rowsRef.current !== null) centerCurrentRow(rowsRef.current)\n })\n }\n\n // Every open starts from a clean filter, selection, and tree — only the\n // current branch's folder chain open.\n useEffect(() => {\n if (!open) return\n setQuery('')\n setSelected(null)\n setExpanded(chainExpanded(currentBranch))\n }, [open, currentBranch])\n\n // A selection that no longer exists in the rows (worktree toggle, refresh)\n // must not linger as a phantom Enter target.\n useEffect(() => {\n if (selected !== null && !rows.some(r => r.name === selected)) setSelected(null)\n }, [rows, selected])\n\n /** Toggle one folder header. */\n const toggle = (path: string): void => {\n setExpanded(prev => {\n const next = new Set(prev)\n if (next.has(path)) next.delete(path)\n else next.add(path)\n return next\n })\n }\n\n // Pin above the chip on open and on viewport movement while open. CSS\n // `bottom` pinning means the card grows upward from that edge without\n // measuring its own height; the width is fixed by CSS, so the horizontal\n // clamp is deterministic.\n useLayoutEffect(() => {\n if (!open) {\n setPos(null)\n return\n }\n const place = (): void => {\n const anchor = anchorRef.current\n if (anchor === null) return\n const rect = anchor.getBoundingClientRect()\n const vw = window.innerWidth\n const vh = window.innerHeight\n const left = Math.min(Math.max(rect.left, MARGIN), Math.max(MARGIN, vw - CARD_WIDTH - MARGIN))\n setPos({ left, bottom: vh - rect.top + GAP })\n }\n place()\n window.addEventListener('resize', place)\n window.addEventListener('scroll', place, true)\n return () => {\n window.removeEventListener('resize', place)\n window.removeEventListener('scroll', place, true)\n }\n }, [open, anchorRef])\n\n // Land the current-branch row mid-viewport when the list shows. With\n // dozens of branches the row otherwise drowns off-screen and \"where am\n // I?\" becomes a scroll hunt. Two trigger paths, both required:\n //\n // - rows MOUNT: the card mounts in two stages (open flips, pos\n // resolves a render later), so an [open]-keyed effect runs while\n // nothing is mounted and never re-fires once rows appear — the\n // stable mount-signal ref below fires exactly at mount instead;\n // - filter CLEARS back to the full list: the rows container is\n // long-mounted by then, so a plain [query] effect reaches it.\n //\n // Manual scrollTo on the rows container — scrollIntoView would also drag\n // scrollable ancestors. Re-renders must NOT re-center (it would yank the\n // user's scroll during picks), hence the stable useCallback identity.\n const rowsRef = useRef<HTMLElement | null>(null)\n const centerCurrentRow = useCallback((viewport: HTMLElement): void => {\n const row = [...viewport.querySelectorAll<HTMLButtonElement>('button[role=\"menuitem\"][data-branch]')]\n .find(b => (b.dataset.branch ?? '') === currentBranch)\n if (row === undefined) return\n const rowRect = row.getBoundingClientRect()\n const vpRect = viewport.getBoundingClientRect()\n const target = viewport.scrollTop + (rowRect.top - vpRect.top) - (viewport.clientHeight - rowRect.height) / 2\n viewport.scrollTo({ top: Math.max(0, target) })\n }, [currentBranch])\n const holdRowsCenter = useCallback((el: HTMLElement | null): void => {\n rowsRef.current = el\n if (el !== null) centerCurrentRow(el)\n }, [centerCurrentRow])\n useEffect(() => {\n if (!open || query.trim() !== '') return\n if (rowsRef.current !== null) centerCurrentRow(rowsRef.current)\n }, [open, query, centerCurrentRow])\n\n // After an open re-seeds the folder chain (see the reset effect above),\n // its re-render commits one render AFTER the rows mount — centering in\n // that window would no-op because the current row's folder is still\n // closed. One frame later the chain is committed and the row exists, so\n // run the centering again then. User folder toggles never re-center:\n // this effect fires only on open / branch change.\n useEffect(() => {\n if (!open) return\n const raf = requestAnimationFrame(() => {\n if (rowsRef.current !== null) centerCurrentRow(rowsRef.current)\n })\n return () => { cancelAnimationFrame(raf) }\n }, [open, centerCurrentRow])\n\n // Flyout lifecycle: horizontally anchored to the card's right edge (so\n // it never overlaps the branch list), vertically centered on the picked\n // row, clamped into the viewport. Width is content-driven: place()\n // clamps the flyout's inline max-width to the room right of the card\n // (CSS caps the design width), then measures the laid-out hidden flyout\n // and pins it. Re-runs when the pending ROW changes — confirmOpen alone\n // stays true across re-picks, which used to leave the flyout stranded\n // at the first row. Scroll/resize re-fit while open.\n useLayoutEffect(() => {\n if (!confirmOpen || pendingName === null) {\n setFlyPos(null)\n return\n }\n const place = (): void => {\n const pending = pendingRef.current\n const fly = flyRef.current\n const card = cardRef.current\n if (pending === null || fly === null || card === null) return\n const row = pending.el.getBoundingClientRect()\n const cr = card.getBoundingClientRect()\n const vw = window.innerWidth\n const vh = window.innerHeight\n const left = cr.right + GAP\n // Fit the right side: content width first, clamped by the room left\n // of the viewport margin (floor keeps the buttons usable on very\n // narrow windows, at the cost of spilling past the margin).\n const room = Math.min(FLY_MAX_WIDTH, Math.max(200, vw - MARGIN - left))\n fly.style.maxWidth = `${room}px`\n const fw = fly.offsetWidth\n const fh = fly.offsetHeight\n // The picked row's center rides the flyout's vertical center.\n const top = Math.min(\n Math.max(row.top + row.height / 2 - fh / 2, MARGIN),\n Math.max(MARGIN, vh - fh - MARGIN),\n )\n setFlyPos({ left: Math.min(left, vw - MARGIN - fw), top })\n }\n place()\n window.addEventListener('resize', place)\n window.addEventListener('scroll', place, true)\n return () => {\n window.removeEventListener('resize', place)\n window.removeEventListener('scroll', place, true)\n }\n }, [confirmOpen, pendingName])\n\n // Confirm opens (or re-anchors to another row) → focus the confirm\n // button (Enter commits, Escape cancels); confirm closes → forget the\n // pending row anchor. The focus rides a rAF: the flyout mounts in the\n // hidden measure-then-place posture, and focus() on a visibility:hidden\n // element is a no-op — one frame later the placed card is visible and\n // the focus lands.\n useEffect(() => {\n if (confirmOpen && pendingName !== null) {\n const raf = requestAnimationFrame(() => { flyConfirmRef.current?.focus() })\n return () => { cancelAnimationFrame(raf) }\n }\n if (!confirmOpen) {\n pendingRef.current = null\n setPendingName(null)\n }\n }, [confirmOpen, pendingName])\n\n // Outside pointer / keyboard dismiss. Outside clicks cancel the confirm\n // and close the menu in one go. Escape unwinds tier by tier — confirm,\n // then search text, then selection, then the menu. Arrow keys move the\n // selection over the visible leaf rows and Enter stages the confirm,\n // but only while focus sits on a card button: the search input keeps\n // its own caret handling and Enter-commit.\n useEffect(() => {\n if (!open) return\n const onPointerDown = (event: PointerEvent): void => {\n if (cardRef.current?.contains(event.target as Node) === true) return\n if (flyRef.current?.contains(event.target as Node) === true) return\n if (anchorRef.current?.contains(event.target as Node) === true) return\n confirmRef.current?.onCancel()\n onClose()\n }\n const onKeyDown = (event: KeyboardEvent): void => {\n const key = event.key\n if (key === 'Escape') {\n if (confirmRef.current !== null) { confirmRef.current.onCancel(); return }\n if (queryRef.current.trim() !== '') { setQuery(''); return }\n if (selectedRef.current !== null) { setSelected(null); return }\n onClose()\n return\n }\n const card = cardRef.current\n const active = document.activeElement\n if (card === null || active === null || !card.contains(active)) return\n const input = card.querySelector('input')\n if (active === input) return\n const leaves = [...card.querySelectorAll<HTMLButtonElement>('button[role=\"menuitem\"][data-branch]')]\n if (key === 'ArrowDown' || key === 'ArrowUp') {\n event.preventDefault()\n if (leaves.length === 0) return\n const idx = leaves.findIndex(b => (b.dataset.branch ?? '') === selectedRef.current)\n let next = idx\n if (key === 'ArrowDown') next = idx < 0 ? 0 : Math.min(leaves.length - 1, idx + 1)\n else next = idx <= 0 ? leaves.length - 1 : idx - 1\n const target = leaves[next]\n const name = target.dataset.branch ?? null\n if (name !== null) setSelected(name)\n target.focus()\n target.scrollIntoView({ block: 'nearest' })\n } else if (key === 'Enter' && selectedRef.current !== null) {\n event.preventDefault()\n const el = leaves.find(b => (b.dataset.branch ?? '') === selectedRef.current) ?? null\n pickRef.current(el, selectedRef.current)\n }\n }\n document.addEventListener('pointerdown', onPointerDown, true)\n document.addEventListener('keydown', onKeyDown)\n return () => {\n document.removeEventListener('pointerdown', onPointerDown, true)\n document.removeEventListener('keydown', onKeyDown)\n }\n }, [open, onClose, anchorRef])\n\n if (!open || pos === null) return null\n\n const needle = query.trim().toLowerCase()\n const visible = needle === ''\n ? rows\n : rows.filter(row => row.name.toLowerCase().includes(needle))\n\n /** Enter in the search field: commit the first enabled visible row\n * (its rendered button is the anchor — found by its data-branch key; the\n * label text alone can't identify a row inside a tree). */\n const commitFirst = (): void => {\n const first = visible.find(row => !row.disabled)\n if (first === undefined) return\n const card = cardRef.current\n if (card === null) return\n const el = card.querySelector<HTMLButtonElement>(`button[data-branch=\"${CSS.escape(first.name)}\"]`)\n pick(el, first.name)\n }\n\n /** Row class composition: base + HEAD tint + selection (selection wins). */\n const rowClass = (name: string): string => {\n let cls = css.menuRow\n if (name === currentBranch) cls += ` ${css.menuRowSelected}`\n if (name === selected) cls += ` ${css.menuRowPicked}`\n return cls\n }\n\n /** A row's click behavior: with the confirm flyout open, clicking a row\n * re-picks it (the old one-click flow — the flyout re-anchors); without\n * one it just selects (IDEA model — double-click or Enter opens the\n * confirm flyout for the selected row). */\n const rowClick = (el: HTMLButtonElement, name: string): void => {\n if (confirmOpen) pick(el, name)\n else setSelected(name)\n }\n\n /** Wrap every case-insensitive occurrence of `needle` in `text` with the\n * search-mark span (IDEA-style hit highlight). */\n const renderLabel = (text: string): React.ReactNode => {\n if (needle === '') return text\n const out: React.ReactNode[] = []\n let rest = text\n let key = 0\n for (;;) {\n const idx = rest.toLowerCase().indexOf(needle)\n if (idx === -1) { out.push(rest); break }\n if (idx > 0) out.push(rest.slice(0, idx))\n out.push(<span key={key} className={css.menuSearchMark}>{rest.slice(idx, idx + needle.length)}</span>)\n key += 1\n rest = rest.slice(idx + needle.length)\n }\n return out\n }\n\n /** Does any leaf under these nodes match the needle? */\n const subtreeMatches = (nodes: TreeNode[]): boolean => {\n for (const node of nodes) {\n if (node.leaf !== null && node.leaf.name.toLowerCase().includes(needle)) return true\n if (subtreeMatches(node.children)) return true\n }\n return false\n }\n\n /** One tree group-header row: its own segment (a compressed chain's\n * walked segments join the label), a count badge, and a chevron that\n * turns for expansion. Clicking toggles. One color throughout — the\n * folder path is not color-distinguished from the name. */\n const renderHeader = (node: TreeNode, label: string, depth: number): React.ReactNode => {\n const isOpen = expanded.has(node.path)\n return (\n <button\n key={`group:${node.path}`}\n type=\"button\"\n className={css.menuGroup}\n data-group={node.path}\n style={{ paddingLeft: 8 + depth * 12 }}\n aria-expanded={isOpen}\n onClick={() => {\n if (guardActive()) return\n toggle(node.path)\n armShiftGuard()\n }}\n >\n <IconChevronRightOutline14\n size={12}\n className={isOpen ? `${css.menuGroupChevron} ${css.menuGroupChevronOpen}` : css.menuGroupChevron}\n />\n <span className={css.menuGroupLabel}>{label}</span>\n <span className={css.menuGroupCount}>({node.total})</span>\n </button>\n )\n }\n\n /** One tree leaf row: under an expanded folder it shows only its own\n * segment (indentation carries the hierarchy — no repeated full path);\n * a compressed linear chain keeps its walked segments in the label so\n * the context survives without a pointless one-entry folder. */\n const renderLeaf = (node: TreeNode, label: string, depth: number): React.ReactNode => (\n <button\n key={node.path}\n type=\"button\"\n role=\"menuitem\"\n data-branch={node.path}\n className={rowClass(node.path)}\n disabled={node.leaf?.disabled ?? false}\n style={{ paddingLeft: 8 + depth * 12 }}\n onClick={() => { if (guardActive()) return; rowClick(buttonOf(node.path), node.path) }}\n onDoubleClick={(event) => { if (guardActive()) return; pick(event.currentTarget, node.path) }}\n onMouseEnter={(event) => { gateTooltip(event.currentTarget, node.path) }}\n onMouseLeave={(event) => { clearTooltip(event.currentTarget) }}\n >\n <span className={css.menuRowLabel}>{label}</span>\n {node.path === currentBranch && <IconCheckOutline16 size={14} />}\n </button>\n )\n\n /** Recursive tree renderer. Linear chains — nodes that are neither a\n * branch nor a real fork — compress into the next row's label, so\n * `feature/优化` stays a single flat row instead of a pointless one-entry\n * folder, while a real fork (`a/deep/tree` holding leaf1+leaf2) gets a\n * header whose children show only their own segments. */\n const renderTree = (nodes: TreeNode[], depth: number): React.ReactNode[] => {\n const out: React.ReactNode[] = []\n for (const node of nodes) {\n let cur = node\n const parts: string[] = []\n while (cur.leaf === null && cur.children.length === 1) {\n parts.push(cur.segment)\n cur = cur.children[0]\n }\n const label = parts.length === 0 ? cur.segment : `${parts.join('/')}/${cur.segment}`\n if (cur.leaf !== null) {\n out.push(renderLeaf(cur, label, depth))\n // A branch that is also a folder path (`feature` next to\n // `feature/x`): keep the pickable row and fold the children under\n // a second, toggle-only header of the same name (rare coexistence).\n if (cur.children.length > 0) {\n out.push(renderHeader(cur, label, depth))\n if (expanded.has(cur.path)) out.push(...renderTree(cur.children, depth + 1))\n }\n } else {\n out.push(renderHeader(cur, label, depth))\n if (expanded.has(cur.path)) out.push(...renderTree(cur.children, depth + 1))\n }\n }\n return out\n }\n\n /** Search view: keep matching leaves AND their ancestor folders (IDEA's\n * filter keeps the path), hide non-matching siblings, force every kept\n * folder open, and highlight the hit substring. No chain compression —\n * the full ancestor path is exactly the context the search is for. */\n const renderSearch = (nodes: TreeNode[], depth: number): React.ReactNode[] => {\n const out: React.ReactNode[] = []\n for (const node of nodes) {\n const leafHit = node.leaf !== null && node.leaf.name.toLowerCase().includes(needle)\n const childHit = subtreeMatches(node.children)\n if (leafHit) {\n out.push(\n <button\n key={node.path}\n type=\"button\"\n role=\"menuitem\"\n data-branch={node.path}\n className={rowClass(node.path)}\n disabled={node.leaf?.disabled ?? false}\n style={{ paddingLeft: 8 + depth * 12 }}\n onClick={() => { if (guardActive()) return; rowClick(buttonOf(node.path), node.path) }}\n onDoubleClick={(event) => { if (guardActive()) return; pick(event.currentTarget, node.path) }}\n onMouseEnter={(event) => { gateTooltip(event.currentTarget, node.path) }}\n onMouseLeave={(event) => { clearTooltip(event.currentTarget) }}\n >\n <span className={css.menuRowLabel}>{renderLabel(node.segment)}</span>\n {node.path === currentBranch && <IconCheckOutline16 size={14} />}\n </button>,\n )\n }\n if (childHit) {\n out.push(\n <div\n key={`search:${node.path}`}\n role=\"presentation\"\n className={css.menuGroup}\n data-group={node.path}\n style={{ paddingLeft: 8 + depth * 12 }}\n >\n <IconChevronDownOutline14 size={12} className={css.menuGroupChevron} />\n <span className={css.menuGroupLabel}>{renderLabel(node.segment)}</span>\n <span className={css.menuGroupCount}>({node.total})</span>\n </div>,\n )\n out.push(...renderSearch(node.children, depth + 1))\n }\n }\n return out\n }\n\n /** The rendered button for a branch name (flyout anchor on click-select\n * paths, where the handler only has the name at hand). */\n const buttonOf = (name: string): HTMLButtonElement | null =>\n cardRef.current?.querySelector<HTMLButtonElement>(`button[data-branch=\"${CSS.escape(name)}\"]`) ?? null\n\n /** One flat row (small repos, and search results there). */\n const renderRow = (row: BranchRow, highlight: boolean): React.ReactNode => (\n <button\n key={row.name}\n type=\"button\"\n role=\"menuitem\"\n data-branch={row.name}\n className={rowClass(row.name)}\n disabled={row.disabled}\n onClick={() => { if (guardActive()) return; rowClick(buttonOf(row.name), row.name) }}\n onDoubleClick={(event) => { if (guardActive()) return; pick(event.currentTarget, row.name) }}\n onMouseEnter={(event) => { gateTooltip(event.currentTarget, row.name) }}\n onMouseLeave={(event) => { clearTooltip(event.currentTarget) }}\n >\n <span className={css.menuRowLabel}>{highlight ? renderLabel(row.name) : row.name}</span>\n {row.name === currentBranch && <IconCheckOutline16 size={14} />}\n </button>\n )\n\n return (\n <>\n {createPortal(\n <div\n ref={cardRef}\n className={css.menuCard}\n style={{ left: pos.left, bottom: pos.bottom }}\n role=\"menu\"\n aria-label={t('menuLocalBranches')}\n >\n <div className={css.menuToolbar} role=\"toolbar\" aria-label={t('menuLocalBranches')}>\n <button\n type=\"button\"\n className={css.menuToolButton}\n title={t('menuLocate')}\n aria-label={t('menuLocate')}\n onClick={locateCurrent}\n >\n <IconGoalOutline16 size={16} />\n </button>\n <button\n type=\"button\"\n className={css.menuToolButton}\n title={allExpanded ? t('menuCollapseAll') : t('menuExpandAll')}\n aria-label={allExpanded ? t('menuCollapseAll') : t('menuExpandAll')}\n disabled={tree === null || folderPaths.length === 0}\n onClick={toggleAll}\n >\n {allExpanded ? <IconChevronUpOutline14 size={14} /> : <IconChevronDownOutline14 size={14} />}\n </button>\n </div>\n <div className={css.menuMain}>\n <div className={css.menuHeading}>{t('menuLocalBranches')}</div>\n <div className={css.menuRows} role=\"presentation\" ref={holdRowsCenter}>\n {tree === null\n ? (needle === '' ? rows : visible).map(row => renderRow(row, needle !== ''))\n : (needle === '' ? renderTree(tree, 0) : renderSearch(tree, 0))}\n {visible.length === 0 && <div className={css.menuEmpty}>{t('menuNoMatches')}</div>}\n </div>\n <div className={css.menuSearchWrap}>\n <input\n ref={holdSearchFocus}\n className={css.menuSearch}\n type=\"text\"\n value={query}\n placeholder={t('menuSearchPlaceholder')}\n aria-label={t('menuSearchPlaceholder')}\n spellCheck={false}\n onChange={event => { setQuery(event.target.value) }}\n onKeyDown={event => {\n if (event.key === 'Enter') {\n event.preventDefault()\n commitFirst()\n }\n }}\n />\n </div>\n </div>\n </div>,\n document.body,\n )}\n {confirm !== null && createPortal(\n <div\n ref={flyRef}\n className={css.popCard}\n style={flyPos ?? FLY_MEASURE}\n role=\"dialog\"\n aria-label={confirm.ask}\n >\n <p className={css.popAsk}>{confirm.ask}</p>\n <div className={css.popActions}>\n <button type=\"button\" disabled={confirm.busy} onClick={confirm.onCancel}>\n {confirm.cancelLabel}\n </button>\n <button ref={flyConfirmRef} type=\"button\" disabled={confirm.busy} onClick={confirm.onConfirm}>\n {confirm.confirmLabel}\n </button>\n </div>\n </div>,\n document.body,\n )}\n </>\n )\n}","/**\n * BranchChipDock: the composer tool-row entry (conversation.input.left, right\n * of the mode chips) for sessions inside a git repository. Blank sessions\n * get the full segmented control — branch picker plus the worktree\n * isolation toggle — because that is the moment to choose the environment\n * for the conversation. Once the session starts, the worktree toggle is\n * withdrawn: a started session may still switch branches in place (a\n * switch inside a linked worktree checks out within that worktree —\n * probeRepo roots at the session directory's toplevel, never the main\n * checkout), but its directory is fixed. Non-git directories and load\n * failures render nothing. The confirm dialogs and the error toast live\n * here too.\n *\n * Checking the worktree toggle pops the cutout confirm dialog right away:\n * confirming it cuts a NEW branch (`<current>-wt`, suffixes past taken\n * names) out of the current checkout into a fresh isolated worktree — the\n * current branch itself is occupied by the main worktree, so git refuses a\n * second worktree on it. The dialog stands alone above the chip (the\n * branch menu stays closed); the chip still opens the menu, where picking\n * another branch keeps the plain create-or-reuse flow and re-picking the\n * current branch stages the same cutout confirm. Dismissing the dialog and\n * sending the message anyway means the user knowingly stays in the current\n * directory — no separate notice fires on send.\n */\n\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'\nimport { createPortal } from 'react-dom'\nimport {\n Button, IconBranchOutline16, Toast,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\nimport { localBranchName } from '../normalize.ts'\nimport type { BranchEntry, RepoStatus, WorktreeEntry } from '../wire.ts'\nimport { fetchStatus, requestSwitch, requestWorktree, requestWorktreeCutout } from './api.ts'\nimport { BranchMenu, type BranchRow } from './BranchMenu.tsx'\nimport type { BranchChipInjected } from './slots.ts'\nimport css from './BranchChip.module.css'\n\n/**\n * Heavier check glyph for the worktree toggle. The base's IconCheckOutline16\n * is a fill path (fixed visual weight); we need a visibly bolder stroke to\n * read inside the 14×14 bluish fill — local to this module so the heavier\n * weight doesn't leak into the rest of the composer chrome.\n */\nfunction WorktreeCheck({ size = 12 }: { size?: number }) {\n return (\n <svg width={size} height={size} viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\">\n <path\n d=\"M3.2 8.4 L6.6 11.8 L12.8 4.4\"\n stroke=\"currentColor\"\n strokeWidth=\"3.2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n )\n}\n\n/** Full props: owner share + standard kit + injected adopt verb + locale seat. */\nexport type BranchChipDockProps =\n PropsRuntime<'conversation.input.left'>\n & BranchChipInjected\n & PropsLocale<'git-worktree'>\n\n/** Status fetch lifecycle: `null` facts until ready; failures park unloaded. */\ninterface StatusState {\n facts: (RepoStatus & { repo: true }) | null\n}\n\n/** One pending confirm dialog. */\ninterface ConfirmState {\n kind: 'switch' | 'worktree' | 'worktree-cutout'\n branch: string\n}\n\n/**\n * Read the repository status for a directory; refetch on demand.\n * @param cwd - absolute session directory.\n * @returns the state holder and a refetch verb.\n */\nfunction useRepoStatus(cwd: string | undefined): readonly [StatusState, () => Promise<void>] {\n const [state, setState] = useState<StatusState>({ facts: null })\n const load = useCallback(async (): Promise<void> => {\n if (cwd === undefined) {\n setState({ facts: null })\n return\n }\n const result = await fetchStatus(cwd)\n setState({ facts: result.ok && result.repo ? result : null })\n }, [cwd])\n useEffect(() => {\n let live = true\n setState({ facts: null })\n if (cwd !== undefined) {\n void fetchStatus(cwd).then(result => {\n if (live) setState({ facts: result.ok && result.repo ? result : null })\n })\n }\n return () => { live = false }\n }, [cwd])\n return [state, load]\n}\n\n/** Longest branch name shown on the chip before ellipsizing (chars, … included). */\nconst BRANCH_DISPLAY_MAX = 25\n\n/** Viewport edge clearance and chip gap, mirroring BranchMenu's posture. */\nconst POP_MARGIN = 12\nconst POP_GAP = 6\n/** Unplaced dialog: hidden but laid out at a fixed origin so offsetWidth is\n * real for the measure-then-place pass (BranchMenu's flyout trick). */\nconst POP_MEASURE: Partial<CSSStyleDeclaration> = { left: '-9999px', bottom: '0px', visibility: 'hidden' }\n\n/**\n * Clamp a branch name for chip display: names up to 25 chars pass through;\n * longer ones show the first 24 chars plus an ellipsis.\n * @param branch - full branch name.\n */\nfunction displayBranch(branch: string): string {\n return branch.length <= BRANCH_DISPLAY_MAX ? branch : `${branch.slice(0, BRANCH_DISPLAY_MAX - 1)}…`\n}\n\n/**\n * Build the branch rows for the picker: local branches only (remote\n * branches are not offered). A branch already checked out by a live\n * worktree is disabled while the worktree toggle is off (git refuses such\n * a switch); with the toggle on it is the reuse path, so it stays\n * selectable. The selected row's trailing check is BranchMenu's own\n * affordance — no leading icon.\n */\nfunction buildBranchRows(\n branches: readonly BranchEntry[],\n worktrees: readonly WorktreeEntry[],\n currentBranch: string,\n worktreeMode: boolean,\n): BranchRow[] {\n const occupied = new Set(worktrees.flatMap(w => w.branch === undefined ? [] : [w.branch]))\n return branches\n .filter(b => b.kind === 'local')\n .map(branch => ({\n name: branch.name,\n disabled: branch.name !== currentBranch && !worktreeMode && occupied.has(localBranchName(branch.name)),\n }))\n}\n\n/** The standalone confirm dialog shown while the branch menu is closed. */\ninterface ChipConfirmProps {\n /** The chip element — the dialog's bottom edge pins just above its top. */\n anchorRef: React.RefObject<HTMLElement | null>\n /** Ask line (already localized). */\n ask: string\n /** Confirm-button label (progress text while busy). */\n confirmLabel: string\n /** Cancel-button label. */\n cancelLabel: string\n /** True while the action runs: both buttons disable. */\n busy: boolean\n /** Run the confirmed action. */\n onConfirm: () => void\n /** Dismiss the dialog without acting. */\n onCancel: () => void\n}\n\n/**\n * The check-time confirm dialog, rendered while the branch menu is closed:\n * the same popCard chrome as BranchMenu's flyout, but bottom-pinned above\n * the chip in the menu card's posture — the flyout's right-of-card anchor\n * has no card to sit beside here. Outside pointerdown and Escape cancel;\n * the confirm button takes focus so Enter commits.\n */\nfunction ChipConfirm({ anchorRef, ask, confirmLabel, cancelLabel, busy, onConfirm, onCancel }: ChipConfirmProps) {\n const popRef = useRef<HTMLDivElement>(null)\n const confirmRef = useRef<HTMLButtonElement | null>(null)\n const [pos, setPos] = useState<{ left: number; bottom: number } | null>(null)\n\n // Bottom-pin above the chip and clamp horizontally against the measured,\n // content-driven width (popCard is max-content under an 80vw cap).\n useLayoutEffect(() => {\n const place = (): void => {\n const anchor = anchorRef.current\n const pop = popRef.current\n if (anchor === null || pop === null) return\n const rect = anchor.getBoundingClientRect()\n const vw = window.innerWidth\n const vh = window.innerHeight\n const left = Math.min(Math.max(rect.left, POP_MARGIN), Math.max(POP_MARGIN, vw - POP_MARGIN - pop.offsetWidth))\n setPos({ left, bottom: vh - rect.top + POP_GAP })\n }\n place()\n window.addEventListener('resize', place)\n window.addEventListener('scroll', place, true)\n return () => {\n window.removeEventListener('resize', place)\n window.removeEventListener('scroll', place, true)\n }\n }, [anchorRef])\n\n // Focus rides a rAF: the first frame lays the dialog out in the hidden\n // measure-then-place posture, and focus() on a visibility:hidden node\n // no-ops — one frame later the placed dialog is visible and the focus\n // lands.\n useEffect(() => {\n const raf = requestAnimationFrame(() => { confirmRef.current?.focus() })\n return () => { cancelAnimationFrame(raf) }\n }, [])\n\n // Outside pointerdown cancels (the dialog and the chip excluded — the\n // chip click runs its own toggle); Escape unwinds the dialog.\n useEffect(() => {\n const onPointerDown = (event: PointerEvent): void => {\n if (popRef.current?.contains(event.target as Node) === true) return\n if (anchorRef.current?.contains(event.target as Node) === true) return\n onCancel()\n }\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') onCancel()\n }\n document.addEventListener('pointerdown', onPointerDown, true)\n document.addEventListener('keydown', onKeyDown)\n return () => {\n document.removeEventListener('pointerdown', onPointerDown, true)\n document.removeEventListener('keydown', onKeyDown)\n }\n }, [onCancel, anchorRef])\n\n return createPortal(\n <div ref={popRef} className={css.popCard} style={pos ?? POP_MEASURE} role=\"dialog\" aria-label={ask}>\n <p className={css.popAsk}>{ask}</p>\n <div className={css.popActions}>\n <button type=\"button\" disabled={busy} onClick={onCancel}>\n {cancelLabel}\n </button>\n <button ref={confirmRef} type=\"button\" disabled={busy} onClick={onConfirm}>\n {confirmLabel}\n </button>\n </div>\n </div>,\n document.body,\n )\n}\n\n/** The tool-row entry registered into conversation.input.left. */\nexport function BranchChipDock({ session, sessionId, useSessions, adoptWorktree, t }: BranchChipDockProps) {\n const summary = useSessions(state => state.byId[sessionId])\n const cwd = summary?.cwd\n const [repo, refresh] = useRepoStatus(cwd)\n const [menuOpen, setMenuOpen] = useState(false)\n const [worktreeMode, setWorktreeMode] = useState(false)\n const [confirm, setConfirm] = useState<ConfirmState | null>(null)\n const [busy, setBusy] = useState(false)\n const [toast, setToast] = useState<{ seq: number; text: string } | null>(null)\n const chipRef = useRef<HTMLButtonElement | null>(null)\n const busyRef = useRef(false)\n\n useEffect(() => {\n // A moved session directory means a new repository context: the staged\n // toggle and any half-open dialog belong to the old one.\n setWorktreeMode(false)\n setConfirm(null)\n setMenuOpen(false)\n }, [cwd])\n\n useEffect(() => {\n // The session started: the environment is fixed now, so a toggle staged\n // during the blank phase must not survive into branch switching — nor\n // its confirm: a keyboard-only send (no outside pointerdown to dismiss\n // it) can start the session while the cutout dialog still floats over a\n // withdrawn toggle. Switch confirms stay: in-place branch switching is\n // a started-session feature.\n if (!session.blank) {\n setWorktreeMode(false)\n setConfirm(current => current !== null && current.kind !== 'switch' ? null : current)\n }\n }, [session.blank])\n\n // External branch changes (terminal, other tools) never reach this chip\n // on their own — the status fetch runs on mount, on cwd change, and after\n // our own switches. Two cheap pull points cover the real workflow:\n // regaining window focus (the user returns from the terminal where the\n // branches moved; refreshes the chip label) and opening the menu (fresh\n // rows exactly at decision time, see the chip's onClick). A push channel\n // (host-side fs.watch on .git/refs + SSE) was considered and skipped:\n // these pulls hide all but the menu-open-while-branches-change race, at\n // none of that complexity.\n useEffect(() => {\n const refreshIfIdle = (): void => {\n if (busyRef.current) return\n void refresh()\n }\n const onVisibility = (): void => {\n if (document.visibilityState === 'visible') refreshIfIdle()\n }\n window.addEventListener('focus', refreshIfIdle)\n document.addEventListener('visibilitychange', onVisibility)\n return () => {\n window.removeEventListener('focus', refreshIfIdle)\n document.removeEventListener('visibilitychange', onVisibility)\n }\n }, [refresh])\n\n const showError = useCallback((message: string) => {\n setToast({ seq: Date.now(), text: t('errorGeneric', { message }) })\n }, [t])\n\n /** Run one guarded confirm action: single-flight, toast on failure, close on success. */\n const runGuarded = useCallback(async (action: () => Promise<string | undefined>): Promise<void> => {\n if (busyRef.current) return\n busyRef.current = true\n setBusy(true)\n const failure = await action()\n busyRef.current = false\n setBusy(false)\n if (failure !== undefined) {\n showError(failure)\n return\n }\n setConfirm(null)\n setMenuOpen(false)\n }, [showError])\n\n /** In-place switch flow: POST /switch, then refetch the status. */\n const doSwitch = useCallback((branch: string) => runGuarded(async () => {\n if (cwd === undefined) return 'no session directory'\n const result = await requestSwitch(cwd, branch)\n if (!result.ok) return result.error\n await refresh()\n return undefined\n }), [cwd, refresh, runGuarded])\n\n /** Worktree flow: POST /worktree (create-or-reuse, or cut out a new\n * branch), register the directory, hop sessions. */\n const doWorktree = useCallback((branch: string, cutout: boolean) => runGuarded(async () => {\n if (cwd === undefined) return 'no session directory'\n const result = cutout\n ? await requestWorktreeCutout(cwd, branch)\n : await requestWorktree(cwd, branch)\n if (!result.ok) return result.error\n try {\n await adoptWorktree(result.path)\n } catch (cause) {\n return cause instanceof Error ? cause.message : String(cause)\n }\n return undefined\n }), [adoptWorktree, cwd, runGuarded])\n\n const facts = repo.facts\n const rows = useMemo(\n () => facts === null ? [] : buildBranchRows(facts.branches, facts.worktrees, facts.currentBranch, worktreeMode),\n [facts, worktreeMode],\n )\n\n // Non-repo and still-loading directories render nothing at all.\n if (facts === null) return null\n\n const confirmLocalName = confirm === null ? '' : localBranchName(confirm.branch)\n // Reuse applies only to the plain create flow: a cutout always cuts a\n // fresh branch, so the current-branch confirm can never reuse.\n const existingWorktree = confirm === null || confirm.kind !== 'worktree'\n ? undefined\n : facts.worktrees.find(w => w.branch === confirmLocalName)\n\n /** One confirm bundle shared by the menu flyout and the standalone\n * dialog (whichever is showing). */\n const confirmBundle = confirm === null ? null : {\n ask: confirm.kind === 'worktree-cutout'\n ? t('worktreeAskCutOut', { branch: confirmLocalName })\n : confirm.kind === 'worktree'\n ? t(existingWorktree !== undefined ? 'worktreeAskReuse' : 'worktreeAskNew', { branch: confirmLocalName })\n : t('switchAsk', { branch: confirm.branch }),\n confirmLabel: busy\n ? (confirm.kind === 'worktree' || confirm.kind === 'worktree-cutout' ? t('worktreeBusy') : t('switchBusy'))\n : t('actionConfirm'),\n cancelLabel: t('actionCancel'),\n busy,\n onConfirm: () => {\n if (confirm.kind === 'worktree' || confirm.kind === 'worktree-cutout') {\n void doWorktree(confirm.branch, confirm.kind === 'worktree-cutout')\n } else {\n void doSwitch(confirm.branch)\n }\n },\n onCancel: () => { if (!busy) setConfirm(null) },\n }\n\n return (\n <>\n <span className={css.dock}>\n <button\n ref={chipRef}\n type=\"button\"\n className={css.chip}\n title={facts.currentBranch}\n onClick={() => {\n // Toggling always unwinds any half-open confirm first.\n setConfirm(null)\n const opening = !menuOpen\n setMenuOpen(opening)\n // Fresh rows at decision time: branches may have moved outside\n // (terminal, other tools) since the last fetch. Non-blocking —\n // the menu opens on current data and re-renders when it lands.\n if (opening && !busyRef.current) void refresh()\n }}\n >\n <IconBranchOutline16 size={12} />\n <span className={css.branch}>{displayBranch(facts.currentBranch)}</span>\n </button>\n {/* The worktree toggle exists only for blank sessions: the started\n * session's directory is fixed, so its chip degrades to the plain\n * branch picker (the dock's only child then rounds all corners). */}\n {session.blank && (\n <>\n <span className={css.divider} aria-hidden=\"true\" />\n <button\n type=\"button\"\n className={worktreeMode ? css.checkOn : css.check}\n onClick={() => {\n // Checking stages the cutout confirm for the current branch\n // right away — the guidance IS the dialog, not a branch\n // list to explore. Unchecking clears it (and any menu)\n // again.\n const next = !worktreeMode\n setWorktreeMode(next)\n setMenuOpen(false)\n if (next) {\n setConfirm({ kind: 'worktree-cutout', branch: facts.currentBranch })\n if (!busyRef.current) void refresh()\n } else {\n setConfirm(null)\n }\n }}\n title={t('worktreeToggle')}\n >\n <span className={css.box}>{worktreeMode ? <WorktreeCheck size={10} /> : null}</span>\n <span className={css.checkLabel}>{t('chipWorktree')}</span>\n </button>\n </>\n )}\n </span>\n <BranchMenu\n open={menuOpen}\n anchorRef={chipRef}\n rows={rows}\n currentBranch={facts.currentBranch}\n confirm={confirmBundle}\n onSelect={(branch) => {\n // In worktree mode re-selecting the CURRENT branch stages the\n // cut-out confirm; without the mode it is a plain close. Any\n // other pick stages the regular confirm flyout beside that row\n // (menu stays open).\n if (branch === facts.currentBranch) {\n if (worktreeMode) setConfirm({ kind: 'worktree-cutout', branch })\n else setMenuOpen(false)\n return\n }\n setConfirm({ kind: worktreeMode ? 'worktree' : 'switch', branch })\n }}\n onClose={() => { setMenuOpen(false) }}\n t={t}\n />\n {confirmBundle !== null && !menuOpen && (\n <ChipConfirm anchorRef={chipRef} {...confirmBundle} />\n )}\n {toast !== null && <Toast key={toast.seq} text={toast.text} onDone={() => { setToast(null) }} />}\n </>\n )\n}\n","/**\n * Staged form over the `git-worktree` settings namespace's single field: the\n * worktree storage root.\n *\n * A settings write is a durable, revision-fenced document mutation, so the\n * control stages what the user picks and commits it only on save: what is on\n * screen is exactly what a save would store. The field shows its effective\n * value (user layer over composition layer over schema default) and whether\n * the user layer carries it — key presence, not a value comparison, marks an\n * override. The namespace has no secret fields, so there is no write-only\n * control here.\n *\n * Self-contained on purpose: the client bundle-purity rule forbids value\n * imports across plugins, so this package stages and fences its own form\n * (and its own snapshot store) rather than importing another plugin's model.\n *\n * @module git-worktree/client/card-form\n */\n\nimport type { SettingsScope } from '@deepseek-ai/dsh-client-runtime/client'\n\n/** The field this card edits. */\nexport const ROOT_FIELD = 'rootDir'\n\n/** The resolved user-facing section this card edits. */\nexport interface SectionValue {\n /** Worktree storage root; absent selects `$DSH_HOME/gitworktree`. */\n rootDir?: string\n}\n\n/**\n * Minimal observable snapshot source: the stable-reference discipline the\n * shell's stores follow (same snapshot object until the fact moves), with\n * nothing the single-field form does not use.\n */\nexport interface CardStore {\n /** @returns the current snapshot (stable reference until the next change). */\n getSnapshot(): CardState\n /** @param listener - invoked after each snapshot change. @returns the disposer. */\n subscribe(listener: () => void): () => void\n /** @param next - the new snapshot; replaces the reference only on a real change. */\n set(next: CardState): void\n}\n\n/** What the git-worktree settings card renders. */\nexport interface CardState {\n /** False while the namespace is not served to this client; the card renders nothing. */\n available: boolean\n /** Whether the Host document accepts writes. */\n writable: boolean\n /** Draft text ('' marks the inherited/default location). */\n rootDir: string\n /** Whether saving the field would leave a user-layer entry. */\n overridden: boolean\n /** Whether the form holds an edit that a save would write. */\n dirty: boolean\n /** Whether a save is crossing the wire. */\n saving: boolean\n /** Whether the last save did not land as staged; cleared by the next edit or save. */\n failed: boolean\n}\n\n/** The form actions the card's slot entry injects. */\nexport interface CardActions {\n /** Stage draft text for the root field. */\n editRoot: (text: string) => void\n /** Stage a clear, so saving lets the field re-inherit the default location. */\n clearRoot: () => void\n /** Write the staged edit, then re-seed from what the Host accepted. */\n save: () => void\n /** Drop the staged edit. */\n discard: () => void\n}\n\n/**\n * Stages the settings edit over the `git-worktree` scope.\n *\n * The form publishes through a snapshot store because the slot component\n * reads through a snapshot selector while both the scope and the local draft\n * change underneath; every projection is rebuilt from the two together. The\n * field is staged only when the user touched it, so a save writes a sparse\n * patch and never restates fields it did not see.\n */\nexport class CardForm {\n private snapshotValue: CardState\n private readonly listeners = new Set<() => void>()\n private draft: string | undefined\n private saving = false\n private failed = false\n\n /**\n * @param scope - the bound settings scope for the `git-worktree` namespace.\n */\n constructor(private readonly scope: SettingsScope<SectionValue>) {\n this.snapshotValue = this.project()\n scope.subscribe(() => { this.publish() })\n }\n\n /** @returns the store the card's component reads through its bound selector. */\n bind(): CardStore {\n return {\n getSnapshot: () => this.snapshotValue,\n subscribe: (listener) => {\n this.listeners.add(listener)\n return () => { this.listeners.delete(listener) }\n },\n set: (next) => { this.store(next) },\n }\n }\n\n /** @returns the edit, clear, save, and discard actions bound to this form. */\n actions(): CardActions {\n return {\n editRoot: (text) => {\n this.draft = text\n this.failed = false\n this.publish()\n },\n clearRoot: () => {\n this.draft = ''\n this.failed = false\n this.publish()\n },\n // Returns the save's promise (assignable to the void action slot) so\n // callers that care — tests — can await settlement.\n save: () => this.save(),\n discard: () => {\n if (this.draft === undefined && !this.failed) return\n this.draft = undefined\n this.failed = false\n this.publish()\n },\n }\n }\n\n /**\n * Write the staged edit, then re-seed from what the Host accepted.\n *\n * The Host is the only authority on acceptance — an empty draft clears the\n * field, anything else stores the trimmed text (so blanking the control and\n * saving is the same gesture as clearing it). A save that did not land\n * keeps its draft so the user can correct it instead of retyping.\n */\n private async save(): Promise<void> {\n if (this.draft === undefined || this.saving) return\n // Snapshot the intended write: a keystroke mid-await must not change what\n // this save commits.\n const intended = this.draft.trim()\n this.saving = true\n this.failed = false\n this.publish()\n let landed = true\n try {\n if (intended === '') await this.scope.unset(ROOT_FIELD)\n else await this.scope.set(ROOT_FIELD, intended)\n // Read back: the Host's validator owns the constraints no schema\n // expresses, so acceptance is judged from the stored layers.\n if (intended === '' ? this.storedRoot() : this.storedRootValue() !== intended) {\n landed = false\n }\n } catch (_settingsWriteFailure) {\n landed = false\n }\n if (landed) this.draft = undefined\n this.saving = false\n this.failed = !landed\n this.publish()\n }\n\n /** The raw user layer narrowed to a record; the wire answer is `unknown`. */\n private userLayer(): Record<string, unknown> | undefined {\n const user = this.scope.getSnapshot().user\n return typeof user === 'object' && user !== null ? user as Record<string, unknown> : undefined\n }\n\n /** Whether the user layer carries the root field. */\n private storedRoot(): boolean {\n const user = this.userLayer()\n return user !== undefined && Object.hasOwn(user, ROOT_FIELD)\n }\n\n /** The raw user-layer value of the root field. */\n private storedRootValue(): unknown {\n return this.userLayer()?.[ROOT_FIELD]\n }\n\n /** The resolved (draft-free) text of the field; '' means inherited. */\n private effectiveRoot(): string {\n const value = this.scope.getSnapshot().value?.[ROOT_FIELD]\n return typeof value === 'string' ? value : ''\n }\n\n private project(): CardState {\n const snapshot = this.scope.getSnapshot()\n const draft = this.draft ?? this.effectiveRoot()\n return {\n available: snapshot.status === 'ready',\n writable: snapshot.writable,\n rootDir: draft,\n // A staged edit answers for itself, so the override badge previews the\n // save rather than reporting a state the pending edit contradicts.\n overridden: this.draft !== undefined ? this.draft.trim() !== '' : this.storedRoot(),\n dirty: this.draft !== undefined && this.draft !== this.effectiveRoot(),\n saving: this.saving,\n failed: this.failed,\n }\n }\n\n /** Replace the snapshot reference and notify, only when the fact moved. */\n private store(next: CardState): void {\n if (next === this.snapshotValue) return\n this.snapshotValue = next\n for (const listener of this.listeners) listener()\n }\n\n private publish(): void {\n this.store(this.project())\n }\n}\n","/**\n * The git-worktree card on the Plugins configuration tab: a collapsible row\n * whose header names the plugin over a one-line description of what its\n * settings govern, disclosing the storage-root control when open. The card\n * owns everything inside it — chrome, controls, and copy — per the keyed-slot\n * contract; the tab only dispatches it under the `git-worktree` namespace\n * key.\n *\n * Renders nothing while the namespace is unavailable: a deployment that did\n * not compose the host half shows no trace of the card. A stored root edit\n * takes effect live (the Host routes read the section source per request);\n * no data moves — worktrees already created stay where they are, and git\n * itself still lists and reuses them.\n *\n * @module git-worktree/client/GitWorktreeCard\n */\n\nimport { useState } from 'react'\nimport { IconChevronDownOutline14 } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { CardActions, CardStore } from './card-form.ts'\nimport css from './GitWorktreeCard.module.css'\n\n/** Props the renderer binds for the git-worktree settings card. */\nexport type GitWorktreeCardProps =\n PropsRuntime<'settings.plugin.item'>\n & PropsLocale<'git-worktree'>\n & InjectFace<GitWorktreeCardFace>\n\n/** The registration-side face this card's slot entry injects. */\nexport interface GitWorktreeCardFace extends CardActions {\n hooks: {\n /** Card snapshot bound by the renderer as useGitWorktreeCard. */\n gitWorktreeCard: CardStore\n }\n /**\n * The shell's native directory picker (the workspace flows' chooser):\n * resolves the chosen absolute path, or null when the user dismisses the\n * dialog.\n */\n pickDirectory: () => Promise<string | null>\n}\n\n/**\n * Render the git-worktree settings card.\n * @param props - locale copy, the card snapshot, and its form actions.\n * @returns the card, or nothing when the namespace is unavailable.\n */\nexport function GitWorktreeCard(props: GitWorktreeCardProps) {\n const [open, setOpen] = useState(false)\n const [picking, setPicking] = useState(false)\n const { t } = props\n const state = props.useGitWorktreeCard(snapshot => snapshot)\n if (!state.available) return null\n const lockInput = !state.writable\n const lockActions = !state.dirty || state.saving\n\n /**\n * Open the shell's native folder dialog and stage the chosen path — the\n * same picker the workspace flows use, driven through the injected\n * workspace service. A dismissal leaves the staged draft exactly as it\n * was; the text input stays the fallback either way.\n */\n const browse = async (): Promise<void> => {\n if (picking || lockInput) return\n setPicking(true)\n try {\n const picked = await props.pickDirectory()\n if (picked !== null && picked !== '') props.editRoot(picked)\n } catch (_pickFailure) {\n // Leave the draft untouched; typing the path remains available.\n } finally {\n setPicking(false)\n }\n }\n\n return (\n <li className={open ? `${css.card} ${css.cardOpen}` : css.card}>\n <button\n type=\"button\"\n className={css.header}\n aria-expanded={open}\n aria-label={`${t(open ? 'cardCollapse' : 'cardExpand')}: ${t('cardTitle')}`}\n onClick={() => { setOpen(!open) }}\n >\n <span className={css.headText}>\n <span className={css.name}>{t('cardTitle')}</span>\n <span className={css.description}>{t('cardDescription')}</span>\n </span>\n {state.dirty ? <span className={css.pending}>{t('cardUnsaved')}</span> : null}\n <IconChevronDownOutline14 className={open ? `${css.chevron} ${css.chevronOpen}` : css.chevron} />\n </button>\n {open\n ? (\n <div className={css.body}>\n {!state.writable ? <p className={css.note} role=\"status\">{t('cardReadOnly')}</p> : null}\n <label className={css.field} htmlFor=\"git-worktree-card-root-dir\">\n <span className={css.fieldLabel}>{t('cardRootDirLabel')}</span>\n <span className={css.inputRow}>\n <input\n id=\"git-worktree-card-root-dir\"\n className={css.input}\n type=\"text\"\n spellCheck={false}\n value={state.rootDir}\n disabled={lockInput}\n onChange={event => { props.editRoot(event.target.value) }}\n />\n <button\n type=\"button\"\n className={css.browse}\n disabled={lockInput || picking}\n onClick={() => { void browse() }}\n >\n {t(picking ? 'cardPicking' : 'cardBrowse')}\n </button>\n </span>\n </label>\n <p className={css.hint}>\n {t('cardRootDirHint')}\n {state.overridden ? ` ${t('cardOverridden')}` : ''}\n </p>\n <div className={css.footer}>\n {state.failed\n ? <p className={css.failed} role=\"status\">{t('cardSaveFailed')}</p>\n : null}\n <button\n type=\"button\"\n className={css.discard}\n disabled={lockActions}\n onClick={props.discard}\n >\n {t('cardDiscard')}\n </button>\n <button\n type=\"button\"\n className={css.save}\n disabled={lockActions}\n onClick={props.save}\n >\n {t(state.saving ? 'cardSaving' : 'cardSave')}\n </button>\n </div>\n </div>\n )\n : null}\n </li>\n )\n}\n","/**\n * Locale dictionaries for the git-worktree plugin. zh is the key source; en\n * is `Record<GitWorktreeKey, string>`, so a missing translation fails the\n * build instead of surfacing a raw key.\n */\n\n/** Every copy key the plugin surfaces (chip, dialogs, settings card). */\nexport type GitWorktreeKey =\n | 'chipWorktree'\n | 'worktreeToggle'\n | 'menuLocalBranches'\n | 'menuSearchPlaceholder'\n | 'menuNoMatches'\n | 'menuLocate'\n | 'menuExpandAll'\n | 'menuCollapseAll'\n | 'switchAsk'\n | 'switchBusy'\n | 'worktreeAskNew'\n | 'worktreeAskReuse'\n | 'worktreeAskCutOut'\n | 'worktreeBusy'\n | 'actionCancel'\n | 'actionConfirm'\n | 'errorGeneric'\n | 'cardTitle'\n | 'cardDescription'\n | 'cardUnsaved'\n | 'cardExpand'\n | 'cardCollapse'\n | 'cardReadOnly'\n | 'cardRootDirLabel'\n | 'cardBrowse'\n | 'cardPicking'\n | 'cardRootDirHint'\n | 'cardOverridden'\n | 'cardSaveFailed'\n | 'cardDiscard'\n | 'cardSave'\n | 'cardSaving'\n\n/** English dictionary — complete by construction. */\nexport const en: Record<GitWorktreeKey, string> = {\n chipWorktree: 'Worktree',\n worktreeToggle: 'Create an isolated worktree',\n menuLocalBranches: 'Local branches',\n menuSearchPlaceholder: 'Search branches',\n menuNoMatches: 'No matching branches',\n menuLocate: 'Locate current branch',\n menuExpandAll: 'Expand all',\n menuCollapseAll: 'Collapse all',\n switchAsk: 'Switch to {branch}?',\n switchBusy: 'Switching…',\n worktreeAskNew: 'Create a worktree from {branch}?',\n worktreeAskReuse: 'Switch to the {branch} worktree?',\n worktreeAskCutOut: 'Cut a worktree out of the current branch {branch}?',\n worktreeBusy: 'Creating…',\n actionCancel: 'Cancel',\n actionConfirm: 'Confirm',\n errorGeneric: 'Git worktree: {message}',\n cardTitle: 'Git Worktree',\n cardDescription: 'Where isolated worktree folders for new sessions are stored.',\n cardUnsaved: 'Unsaved',\n cardExpand: 'Expand',\n cardCollapse: 'Collapse',\n cardReadOnly: 'The settings document is read-only; edits cannot be saved.',\n cardRootDirLabel: 'Worktree storage folder',\n cardBrowse: 'Browse…',\n cardPicking: 'Choosing…',\n cardRootDirHint: 'Absolute path. Empty uses the default $DSH_HOME/gitworktree (~/.dsh/gitworktree).',\n cardOverridden: '(custom location)',\n cardSaveFailed: 'The change did not save. Check the path is absolute and try again.',\n cardDiscard: 'Discard',\n cardSave: 'Save',\n cardSaving: 'Saving…',\n}\n\n/** 中文词典。 */\nexport const zh: Record<GitWorktreeKey, string> = {\n chipWorktree: '工作树',\n worktreeToggle: '创建隔离工作树',\n menuLocalBranches: '本地分支',\n menuSearchPlaceholder: '搜索分支',\n menuNoMatches: '没有匹配的分支',\n menuLocate: '定位当前分支',\n menuExpandAll: '全部展开',\n menuCollapseAll: '全部折叠',\n switchAsk: '是否切到 {branch}?',\n switchBusy: '切换中…',\n worktreeAskNew: '是否从 {branch} 新建工作树?',\n worktreeAskReuse: '是否切到 {branch} 工作树?',\n worktreeAskCutOut: '是否从当前分支 {branch} 切出工作树?',\n worktreeBusy: '创建中…',\n actionCancel: '取消',\n actionConfirm: '确认',\n errorGeneric: 'Git 工作树:{message}',\n cardTitle: 'Git 工作树',\n cardDescription: '新会话的隔离工作树文件夹存放位置。',\n cardUnsaved: '未保存',\n cardExpand: '展开',\n cardCollapse: '折叠',\n cardReadOnly: '设置文档为只读,修改无法保存。',\n cardRootDirLabel: '工作树存放目录',\n cardBrowse: '浏览…',\n cardPicking: '选择中…',\n cardRootDirHint: '绝对路径。留空使用默认 $DSH_HOME/gitworktree(~/.dsh/gitworktree)。',\n cardOverridden: '(已自定义位置)',\n cardSaveFailed: '保存未生效,请检查路径是否为绝对路径后重试。',\n cardDiscard: '放弃',\n cardSave: '保存',\n cardSaving: '保存中…',\n}\n","/**\n * dsh-git-worktree browser half: the composer branch chip + worktree toggle\n * (conversation.input.left) for blank sessions, and the plugin configuration\n * card on the Plugins tab (the `git-worktree` settings namespace — the\n * worktree storage root — edited through the settings scope). Repo facts and\n * worktree creation flow through the host half's own routes; session hopping\n * uses the framework's workspaces service; the card's browse button rides the\n * same service's native directory picker (`ctx.workspaces.pickDirectory`).\n */\n\nimport type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'\n// Type-only: pulls the ui-conversation SlotMap merge (input region entries).\nimport type {} from '@deepseek-ai/dsh-client-ui-conversation/client'\n// Type-only: pulls the ui-settings SlotMap merge ('settings.section') and the\n// settingsScope service declaration into this program.\nimport type {} from '@deepseek-ai/dsh-client-ui-settings/client'\n// Type-only: pulls the ui-settings-plugins keyed-slot declaration\n// ('settings.plugin.item') into this program. The value face stays\n// uncompromised: cross-plugin collaboration goes through the slot system.\nimport type {} from '@deepseek-ai/dsh-client-ui-settings-plugins/client'\n// Type-only: pulls the locale plugin's Context merge (ctx.locale).\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\nimport { BranchChipDock } from './BranchChip.tsx'\nimport { CardForm, type SectionValue } from './card-form.ts'\nimport { GitWorktreeCard } from './GitWorktreeCard.tsx'\nimport { en, zh, type GitWorktreeKey } from './locales.ts'\nimport type { BranchChipInjected } from './slots.ts'\n\nexport type { BranchChipInjected } from './slots.ts'\nexport type { GitWorktreeKey } from './locales.ts'\n\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\n interface LocaleNamespaceMap {\n /** The git-worktree chip, dialogs, and settings card copy. */\n 'git-worktree': GitWorktreeKey\n }\n}\n\n/** Dictionary namespace owned by this plugin. */\nconst NS = 'git-worktree'\n\n/**\n * Namespace of the git-worktree settings section. Spelled here rather than\n * imported: a client package must not depend on a Host package.\n */\nconst GIT_WORKTREE_NS = 'git-worktree'\n\n/** Required services: the slot ledger, session/workspace runtime, copy, and\n * the settings scope backing the plugin configuration card. */\nexport const inject = ['slots', 'sessions', 'workspaces', 'locale', 'connection', 'remote', 'settingsScope']\n\nexport function apply(ctx: ClientContext): void {\n ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'git-worktree: dictionaries')\n\n const chipInjected = (): BranchChipInjected => ({\n adoptWorktree: async (path) => {\n const workspace = await ctx.workspaces.create({ path })\n ctx.workspaces.startSession(workspace.workspaceId)\n },\n })\n\n ctx.slots.inject('conversation.input.left', () => ctx.slots.register({\n name: 'conversation.input.left',\n id: 'git-worktree',\n order: 5,\n locale: NS,\n inject: chipInjected,\n }, BranchChipDock))\n\n // The Plugins configuration tab dispatches keyed cards for the namespaces\n // the Host serves; the git-worktree host half registers this key, so the\n // storage-root card pairs with it without any upstream change.\n const form = new CardForm(ctx.settingsScope.bind<SectionValue>({ namespace: GIT_WORKTREE_NS }))\n const store = form.bind()\n ctx.slots.inject('settings.plugin.item', () => ctx.slots.register({\n name: 'settings.plugin.item',\n key: GIT_WORKTREE_NS,\n locale: NS,\n inject: () => ({\n hooks: { gitWorktreeCard: store },\n ...form.actions(),\n // The shell's own directory picker (the workspace flows' chooser):\n // resolves the chosen absolute path, or null when the user dismisses.\n pickDirectory: () => ctx.workspaces.pickDirectory(),\n }),\n }, GitWorktreeCard))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;EAiCA,SAAgB,gBAAgB,QAAwB;GACtD,MAAM,KAAK,OAAO,QAAQ,GAAG;GAC7B,OAAO,MAAM,IAAI,SAAS,OAAO,MAAM,KAAK,CAAC;EAC/C;;;;;;;;;;EC5BA,MAAa,eAAe;;EAG5B,MAAa,eAAe,GAAG,aAAa;;EAG5C,MAAa,iBAAiB,GAAG,aAAa;;EAG9C,MAAa,eAAe,GAAG,aAAa;;;;ECF5C,eAAe,KAAQ,KAAa,MAAiC;GACnE,OAAO,KAAQ,QAAQ,KAAK,IAAI;EAClC;;EAGA,eAAe,KAAQ,QAAgB,KAAa,MAAiC;GACnF,IAAI;IACF,MAAM,WAAW,MAAM,MAAM,KAAK;KAChC;KACA,SAAS,EAAE,gBAAgB,mBAAmB;KAC9C,MAAM,KAAK,UAAU,IAAI;IAC3B,CAAC;IACD,MAAM,UAAmB,MAAM,SAAS,KAAK;IAC7C,IAAI,CAAC,SAAS,IAEZ,OAAO;KAAE,IAAI;KAAO,OAAOA,QAAM,SAAS,QAAQ,OAAO,SAAS,MAAM;IAAI;IAE9E,OAAO;KAAE,GAAI;KAAe,IAAI;IAAK;GACvC,SAAS,OAAO;IACd,OAAO;KAAE,IAAI;KAAO,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IAAE;GACpF;EACF;;;;;EAMA,eAAsB,YAAY,MAAyC;GACzE,IAAI;IACF,MAAM,WAAW,MAAM,MAAM,GAAG,aAAa,QAAQ,mBAAmB,IAAI,KAAK,EAAE,OAAO,WAAW,CAAC;IACtG,IAAI,CAAC,SAAS,IAAI,OAAO;KAAE,IAAI;KAAO,OAAO,Q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xEA,MAAM,KAAK;;;;;EAMX,MAAM,kBAAkB;;;EAIxB,MAAa,SAAS;GAAC;GAAS;GAAY;GAAc;GAAU;GAAc;GAAU;EAAe;EAE3G,SAAgB,MAAM,KAA0B;GAC9C,IAAI,aAAa,IAAI,OAAO,SAAS,IAAI;IAAE;IAAI;GAAG,CAAC,GAAG,4BAA4B;GAElF,MAAM,sBAA0C,EAC9C,eAAe,OAAO,SAAS;IAC7B,MAAM,YAAY,MAAM,IAAI,WAAW,OAAO,EAAE,KAAK,CAAC;IACtD,IAAI,WAAW,aAAa,UAAU,WAAW;GACnD,EACF;GAEA,IAAI,MAAM,OAAO,iCAAiC,IAAI,MAAM,SAAS;IACnE,MAAM;IACN,IAAI;IACJ,OAAO;IACP,QAAQ;IACR,QAAQ;GACV,GAAG,cAAc,CAAC;GAKlB,MAAM,OAAO,IAAI,SAAS,IAAI,cAAc,KAAmB,EAAE,WAAW,gBAAgB,CAAC,CAAC;GAC9F,MAAM,QAAQ,KAAK,KAAK;GACxB,IAAI,MAAM,OAAO,8BAA8B,IAAI,MAAM,SAAS;IAChE,MAAM;IACN,KAAK;IACL,QAAQ;IACR,eAAe;KACb,OAAO,EAAE,iBAAiB,MAAM;KAChC,GAAG,KAAK,QAAQ;KAGhB,qBAAqB,IAAI,WAAW,cAAc;IACpD;GACF,GAAG,eAAe,CAAC;EACrB"}
package/lib/git.d.ts ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Git command wrapper for the host half. All git access goes through one
3
+ * injectable `exec` seam (tests substitute it); every method is plain
4
+ * argument assembly plus porcelain parsing, no ambient state.
5
+ */
6
+ import type { BranchEntry, WorktreeEntry } from './wire.js';
7
+ /** One process result as the seam reports it. */
8
+ export interface ExecResult {
9
+ code: number;
10
+ stdout: string;
11
+ stderr: string;
12
+ }
13
+ /**
14
+ * Process executor seam. Runs `file args` with cwd set, captures output as
15
+ * UTF-8 text, and never throws — a non-zero exit is a normal result.
16
+ */
17
+ export type Exec = (file: string, args: readonly string[], options: {
18
+ cwd: string;
19
+ }) => Promise<ExecResult>;
20
+ /** Failure of one git invocation: non-zero exit with the stderr text. */
21
+ export declare class GitError extends Error {
22
+ readonly args: readonly string[];
23
+ readonly code: number;
24
+ readonly stderr: string;
25
+ constructor(args: readonly string[], code: number, stderr: string);
26
+ }
27
+ /** Facts the status route assembles: branches, worktrees, repo identity. */
28
+ export interface RepoFacts {
29
+ /** Absolute main worktree path (`rev-parse --show-toplevel` of the main dir). */
30
+ repoRoot: string;
31
+ /** Main repository directory basename. */
32
+ repoName: string;
33
+ /** Branch checked out by the queried directory. */
34
+ currentBranch: string;
35
+ branches: BranchEntry[];
36
+ worktrees: WorktreeEntry[];
37
+ }
38
+ /** Real executor over node:child_process with a hard timeout. */
39
+ export declare function childProcessExec(file: string, args: readonly string[], options: {
40
+ cwd: string;
41
+ }): Promise<ExecResult>;
42
+ /** Directory-existence seam over the parsed worktree registrations. */
43
+ export type DirExists = (path: string) => boolean;
44
+ /** Real existence check. */
45
+ export declare const fsDirExists: DirExists;
46
+ /**
47
+ * Resolve a directory to repository facts, or undefined outside any git
48
+ * repository (including the `git` binary missing: ENOENT surfaces as a
49
+ * non-zero exit through the seam).
50
+ * @param exec - executor seam.
51
+ * @param path - absolute directory the workspace reports.
52
+ * @param dirExists - existence seam for stale-registration filtering.
53
+ */
54
+ export declare function probeRepo(exec: Exec, path: string, dirExists?: DirExists): Promise<RepoFacts | undefined>;
55
+ /**
56
+ * Create (or reuse) the worktree for one branch.
57
+ *
58
+ * Idempotence: git allows one worktree per checked-out branch, so an existing
59
+ * worktree already on `branch` (compared by local name) is returned unreused.
60
+ * A local branch gets `git worktree add <path> <name>`; a remote-only branch
61
+ * gets a new local twin via `git worktree add <path> -b <name> <remoteRef>`.
62
+ * @param exec - executor seam.
63
+ * @param repoRoot - main worktree directory.
64
+ * @param branch - branch display name.
65
+ * @param targetPath - absolute directory to create.
66
+ * @returns the worktree path and whether this call created it.
67
+ */
68
+ export declare function addWorktree(exec: Exec, repoRoot: string, branch: string, targetPath: string, dirExists?: DirExists): Promise<{
69
+ path: string;
70
+ created: boolean;
71
+ }>;
72
+ /**
73
+ * Plan a new branch name to cut out of `base`: `<base>-wt`, or the first
74
+ * `-wt<N>` suffix not already taken (`main` → `main-wt`; if that exists,
75
+ * `main-wt2`, …). One `for-each-ref` pass decides; the worktree folder
76
+ * name derives from the returned name, so the caller should resolve it
77
+ * BEFORE computing the target path. With `folderTaken` given, a name is
78
+ * only free when its storage folder is free too: a leftover folder of a
79
+ * since-deleted branch would otherwise fail `worktree add` with a bare
80
+ * "already exists" — the suffix walk skips it the same way.
81
+ * @param exec - executor seam.
82
+ * @param repoRoot - main worktree directory.
83
+ * @param base - base branch local name (or `HEAD` when detached).
84
+ * @param folderTaken - storage-folder occupancy probe (branch name → taken).
85
+ * @returns the free cutout branch name.
86
+ */
87
+ export declare function cutoutBranchName(exec: Exec, repoRoot: string, base: string, folderTaken?: (branch: string) => boolean): Promise<string>;
88
+ /**
89
+ * Create a worktree on a brand-new branch cut out of `base`: the base is
90
+ * checked out by the main worktree (git forbids a second worktree on it),
91
+ * so the new branch is created from it and checked out in the fresh
92
+ * worktree instead.
93
+ * @param exec - executor seam.
94
+ * @param repoRoot - main worktree directory.
95
+ * @param base - base branch local name (`main` or `HEAD`).
96
+ * @param newBranch - the cutout branch name (see {@link cutoutBranchName}).
97
+ * @param targetPath - absolute directory to create.
98
+ */
99
+ export declare function addWorktreeCutout(exec: Exec, repoRoot: string, base: string, newBranch: string, targetPath: string): Promise<void>;
100
+ /**
101
+ * In-place branch switch of the main checkout. A remote display name relies
102
+ * on git's dwim: `git switch <local>` creates the tracking branch when
103
+ * exactly one remote has it.
104
+ * @param exec - executor seam.
105
+ * @param repoRoot - main worktree directory.
106
+ * @param branch - branch display name.
107
+ * @returns the local branch name now checked out.
108
+ */
109
+ export declare function switchBranch(exec: Exec, repoRoot: string, branch: string): Promise<string>;
110
+ /** Guard for route inputs: a non-empty absolute directory path. */
111
+ export declare function isAbsoluteDir(value: string): boolean;