File size: 15,763 Bytes
2b2ba56 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 | import { useStore } from '@nanostores/react'
import { memo, useEffect } from 'react'
import { PrTag } from '@/app/chat/pr-tag'
import { StatusRow } from '@/components/chat/status-row'
import {
type ActionItemSpec,
ActionsContextMenu,
ActionsMenu,
type MenuKit,
renderActionItem
} from '@/components/ui/actions-menu'
import { Button } from '@/components/ui/button'
import { Codicon } from '@/components/ui/codicon'
import { CopyButton } from '@/components/ui/copy-button'
import { DiffCount } from '@/components/ui/diff-count'
import type { HermesGitBranch } from '@/global'
import { useI18n } from '@/i18n'
import { displayPath } from '@/lib/display-path'
import { openWorktreeDialog, registerRepoStatusCwd, repoStatusForCwd, repoWorktreesForCwd } from '@/store/coding-status'
import { notifyError } from '@/store/notifications'
import { $pullRequestsByBranch, branchPrKey, refreshPullRequests } from '@/store/pull-requests'
// Tiny uppercase section header, matching the composer "+" menu's labels.
const MENU_SECTION = 'text-[0.625rem] font-semibold uppercase tracking-wider text-(--ui-text-tertiary)'
interface CodingStatusRowProps {
/** Branch the current draft off into a fresh worktree + session, based on
* `base` (a branch name; omitted = current HEAD). The composer owns the
* draft, so it supplies the orchestration; the row just collects the new
* branch name + base. Omitted (e.g. remote backend) hides the affordance. */
onBranchOff?: (branch: string, base?: string) => Promise<void>
/** Check an existing branch out into a fresh worktree + session (no new
* branch). Drives the dialog's "convert a branch" picker. */
onConvertBranch?: (branch: string, path?: null | string, isDefault?: boolean) => Promise<void>
/** List the repo's local branches for the "convert a branch" picker. */
onListBranches?: () => Promise<HermesGitBranch[]>
/** Open the review pane (changed files + diffs). */
onOpen?: () => void
/** Jump into an existing worktree (open a fresh session anchored there). */
onOpenWorktree?: (path: string) => void
/** Switch the current repo checkout to another branch. */
onSwitchBranch?: (branch: string) => Promise<void>
/** Repo root path for the worktree dialog. */
repoPath?: null | string
}
/**
* The always-on coding-context row, the BASE of the composer status stack:
* current branch, dirty summary (+/-), and ahead/behind. A touch more prominent
* than the per-turn rows above it (larger branch label, accent glyph), and the
* entry point to the review pane. Hidden when the active session isn't in a
* local git repo (the probe returns null).
*/
export const CodingStatusRow = memo(function CodingStatusRow({
onBranchOff,
onConvertBranch,
onListBranches,
onOpen,
onOpenWorktree,
onSwitchBranch,
repoPath
}: CodingStatusRowProps) {
const { t } = useI18n()
const s = t.statusStack.coding
const p = t.sidebar.projects
const fileMenu = t.fileMenu
const resolvedRepoPath = repoPath?.trim() || undefined
// This surface's OWN worktree, always β never the primary's. The row used to
// fall back to the global `$repoStatus` for a blank repoPath, which painted
// the main pane's branch/Β± onto a tile whose cwd hadn't resolved yet. That
// fallback bought nothing (the primary's computed is keyed to `$currentCwd`,
// which is blank in exactly the same case) and cost a wrong-tree rail.
const status = useStore(repoStatusForCwd(resolvedRepoPath))
const worktrees = useStore(repoWorktreesForCwd(resolvedRepoPath))
// While mounted, keep this worktree in the coding-status refresh set so the
// turn-settle / tool-complete / focus edges re-probe it too (tiles otherwise
// only refreshed when the MAIN cwd probe happened to cover them).
useEffect(() => registerRepoStatusCwd(resolvedRepoPath), [resolvedRepoPath])
// The branch's PR, so the rail links to it instead of leaving you to go find
// it. One `gh` lookup for this one branch, TTL-cached in the store and shared
// with the sidebar's badges.
const prBranch = status?.detached ? null : status?.branch || null
useEffect(() => {
if (resolvedRepoPath && prBranch) {
void refreshPullRequests({ [resolvedRepoPath]: [prBranch] })
}
}, [resolvedRepoPath, prBranch])
const pr =
useStore($pullRequestsByBranch)[resolvedRepoPath && prBranch ? branchPrKey(resolvedRepoPath, prBranch) : '']
const switchToBranch = async (branch: string) => {
if (!onSwitchBranch) {
return
}
try {
await onSwitchBranch(branch)
} catch (err) {
notifyError(err, s.switchFailed(branch))
}
}
// useKeybinds now handles the ββ§B hotkey globally, through
// openWorktreeDialog. One dialog is mounted in the sidebar, so N mounted
// rails can no longer each open their own copy. The menu items below only
// publish the intent. They pin the repo of THIS rail, so the kebab of a tile
// targets the worktree of that tile.
const startBranch = (base: string | undefined) => {
void openWorktreeDialog({ base, repoPath: resolvedRepoPath })
}
if (!status) {
return null
}
const branchLabel = status.detached ? s.detached : status.branch || s.noBranch
// The kebab offers branching off the trunk and/or the current branch. The
// worktree-add bases the new branch on `base` (a branch name; undefined =
// current HEAD). We dedupe so "on main" shows a single trunk entry, and fall
// back to a plain off-HEAD branch when no trunk is detected.
const current = status.detached ? null : status.branch
const branchTargets: { base: string | undefined; label: string }[] = []
// Current branch first (the 99% "branch off where I am"), then the trunk just
// below it ("New branch from main"), deduped when they're the same.
if (current) {
branchTargets.push({ base: current, label: s.branchOffFrom(current) })
}
if (status.defaultBranch && status.defaultBranch !== current) {
branchTargets.push({ base: status.defaultBranch, label: s.branchOffFrom(status.defaultBranch) })
}
if (branchTargets.length === 0) {
branchTargets.push({ base: undefined, label: s.newBranch })
}
const switchTarget =
onSwitchBranch && current && status.defaultBranch && status.defaultBranch !== current ? status.defaultBranch : null
// Other worktrees to jump into β everything except the one we're already in
// (matched by its checked-out branch) and the bare/main placeholder entry.
const otherWorktrees = onOpenWorktree
? worktrees.filter(w => w.path && !w.detached && w.branch && w.branch !== current)
: []
const hasLineDelta = status.added > 0 || status.removed > 0
// Untracked files carry no line delta vs HEAD, so surface them as a count when
// they're the only change (otherwise +/- tells the story).
const untrackedOnly = !hasLineDelta && status.untracked > 0
// The branch actions, rendered identically by the kebab dropdown and the
// row's right-click menu so the two never drift. `onBranchOff` gates the
// whole menu (omitted = remote backend), matching the kebab.
const renderBranchItems = (kit: MenuKit) => {
const branchItems: ActionItemSpec[] = branchTargets.map(target => ({
key: target.base ?? '__head__',
label: <span className="truncate">{target.label}</span>,
onSelect: () => startBranch(target.base)
}))
const worktreeItems: ActionItemSpec[] = otherWorktrees.map(worktree => ({
key: worktree.path,
label: <span className="truncate">{worktree.branch}</span>,
onSelect: () => onOpenWorktree?.(worktree.path)
}))
return (
<>
<kit.Label className={MENU_SECTION}>{s.newBranch}</kit.Label>
{branchItems.map(item => renderActionItem(kit, item))}
{switchTarget &&
renderActionItem(kit, {
key: '__switch__',
label: <span className="truncate">{s.switchTo(switchTarget)}</span>,
onSelect: () => void switchToBranch(switchTarget)
})}
<kit.Separator />
<kit.Label className={MENU_SECTION}>{s.worktrees}</kit.Label>
{worktreeItems.map(item => renderActionItem(kit, item))}
{/* Create a fresh worktree off the current HEAD (the generic "spin up a
worktree here", mirroring the sidebar's + button). */}
{renderActionItem(kit, {
key: '__start__',
label: <span className="truncate">{p.startWork}</span>,
onSelect: () => startBranch(undefined)
})}
{onConvertBranch &&
renderActionItem(kit, {
key: '__convert__',
label: <span className="truncate">{p.convertBranch}</span>,
onSelect: () => startBranch(undefined)
})}
</>
)
}
return (
<>
<ActionsContextMenu contentClassName="w-60" disabled={!onBranchOff} items={renderBranchItems}>
<StatusRow
// The base "where am I working" strip is part of the composer surface
// itself, so it inherits the composer's width and clipped top radius.
className="coding-status-bar min-h-7 rounded-t-[inherit] rounded-b-none border-b border-(--ui-stroke-tertiary) px-3.5 py-1.5 hover:bg-transparent"
// Static branch glyph β never the loading spinner. This row only renders
// once `status` exists, so a spinner here only ever fired on *refreshes*
// of an already-loaded repo (window focus, turn settle), reading as an
// annoying icon "blip" with no first-load value. Refreshes are silent.
// It's a button (not the whole row) so the glyph opens the review pane
// while the strip around it stays inert; size-3.5 fills the slot exactly.
leading={
<button className="flex size-3.5 items-center justify-center" onClick={onOpen} type="button">
<Codicon className="text-(--ui-green)" name="git-branch" size="0.8rem" />
</button>
}
>
<div className="flex min-w-0 flex-1 items-center gap-1">
{/* PR number first, right against the leading git glyph β the chip
borrows that icon instead of carrying a second one of its own
(`showIcon={false}`), so the row reads glyph β #number β branch. */}
{pr && <PrTag pr={pr} showIcon={false} />}
{/* Branch name β the other half of the review-pane target. `contents`
so the button lays out nothing of its own: the label stays the
same flex child it always was, and the hit area is the text. */}
<button className="contents" onClick={onOpen} type="button">
<span className="min-w-0 truncate text-xs font-normal text-muted-foreground/92" title={branchLabel}>
{branchLabel}
</span>
</button>
{/* Worktree path + copy β plain muted text, not a chip. Always in the
flex so hover doesn't reflow the row; opacity alone reveals the
pair. The path sizes to its content (the `flex-1` lives on the
wrapper) so the glyph sits against the end of the text instead of
drifting to the far edge of the row. `displayPath` collapses
home β ~; the copy still takes the real absolute path, and it's
the shared `CopyButton` so it confirms with the same inline
checkmark as every other copy in the app. */}
{resolvedRepoPath && (
<div className="flex min-w-0 flex-1 items-center gap-0.5 opacity-0 transition-opacity group-hover/status-row:opacity-100 group-focus-within/status-row:opacity-100">
<span
className="min-w-0 truncate font-mono text-[0.62rem] leading-4 text-muted-foreground/50"
data-slot="coding-status-cwd"
>
{displayPath(resolvedRepoPath)}
</span>
<CopyButton
appearance="icon"
buttonSize="icon-xs"
className="pointer-events-none size-4 shrink-0 text-muted-foreground/50 hover:text-foreground group-hover/status-row:pointer-events-auto group-focus-within/status-row:pointer-events-auto"
iconClassName="size-3"
label={fileMenu.copyPath}
side="top"
stopPropagation
text={resolvedRepoPath}
/>
</div>
)}
{/* Branch actions kebab β same pattern as the session/worktree rows.
ALWAYS laid out; only its opacity flips on hover/focus/open, so
revealing it never reflows the row (no layout shift). pointer-events
follow opacity so the invisible trigger isn't clickable at rest. */}
{onBranchOff && (
<ActionsMenu
align="end"
contentClassName="w-60"
// The row sits at the bottom of the screen (above the composer),
// so the menu opens upward.
items={renderBranchItems}
side="top"
>
<Button
aria-label={s.newBranch}
className="pointer-events-none size-4 shrink-0 text-muted-foreground/60 opacity-0 transition hover:text-foreground group-hover/status-row:pointer-events-auto group-hover/status-row:opacity-100 group-focus-within/status-row:pointer-events-auto group-focus-within/status-row:opacity-100 data-[state=open]:pointer-events-auto data-[state=open]:opacity-100"
size="icon-xs"
variant="ghost"
>
<Codicon name="kebab-vertical" size="0.8rem" />
</Button>
</ActionsMenu>
)}
</div>
{/* The counts describe what's in the review pane, so clicking them
opens it. `contents` again: the two spans stay direct flex children
of the row, keeping their gap and `ml-auto` behaviour untouched. */}
{(status.ahead > 0 || status.behind > 0 || hasLineDelta || untrackedOnly) && (
<button className="contents" onClick={onOpen} type="button">
{(status.ahead > 0 || status.behind > 0) && (
<span className="ml-auto flex shrink-0 items-center gap-1.5 text-[0.68rem] leading-4 text-muted-foreground/75 tabular-nums">
{status.ahead > 0 && (
<span className="flex items-center gap-0.5" title={s.ahead(status.ahead)}>
<span aria-hidden>β</span>
{status.ahead}
</span>
)}
{status.behind > 0 && (
<span className="flex items-center gap-0.5" title={s.behind(status.behind)}>
<span aria-hidden>β</span>
{status.behind}
</span>
)}
</span>
)}
{hasLineDelta ? (
<DiffCount
added={status.added}
className={`text-[0.72rem] leading-4 ${status.ahead === 0 && status.behind === 0 ? 'ml-auto' : ''}`}
removed={status.removed}
/>
) : untrackedOnly ? (
<span
className={`shrink-0 text-[0.72rem] leading-4 text-amber-500/90 ${status.ahead === 0 && status.behind === 0 ? 'ml-auto' : ''}`}
>
{s.changed(status.untracked)}
</span>
) : null}
</button>
)}
</StatusRow>
</ActionsContextMenu>
</>
)
})
|