/** * Git status as a bar above the input editor, with a dark-gray outline. * * ╭──────────────────────────────────────────────╮ * │ pixd main vs main +12 -3 │ * ╰──────────────────────────────────────────────╯ * * Uses `ctx.ui.setWidget()` with the default `aboveEditor` placement. Only the * box outline is dark gray; the labels use the active theme's colors. * * Configure with `/git-bar`: * /git-bar hide | show | toggle bar visibility * /git-bar metric lines | files show line counts or changed-file count * /git-bar base head | staged | session | main | upstream * what the diff is measured against * /git-bar poll 5 | 10 | 15 external-change poll interval, in seconds * /git-bar refresh re-read git now * * Defaults come from settings.json, overridden per session by the command: * { "gitBar": { "pollSeconds": 15, "base": "head", "metric": "lines", "hidden": false } } */ import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent"; import { type Color, type TUI, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui"; const WIDGET_KEY = "pixd-bar"; const SETTINGS_KEY = "gitBar"; // Refresh right after tools that can change the working tree; poll for everything // else (e.g. commits or edits made outside pi, like a manual `git init`). const MUTATING_TOOLS = new Set(["bash", "edit", "write"]); type DiffBase = "head" | "staged" | "session" | "main" | "upstream"; type DiffMetric = "lines" | "files"; const BASES: DiffBase[] = ["head", "staged", "session", "main", "upstream"]; const METRICS: DiffMetric[] = ["lines", "files"]; const POLL_CHOICES = ["5", "10", "15"]; const BASE_LABELS: Record = { head: "", staged: "staged", session: "session start", main: "main", upstream: "upstream", }; interface BarConfig { pollSeconds: number; base: DiffBase; metric: DiffMetric; hidden: boolean; } const DEFAULTS: BarConfig = { pollSeconds: 15, base: "head", metric: "lines", hidden: false }; // Dark gray for the outline, concrete so it does not vary with the theme. const BORDER: Color = { kind: "rgb", r: 90, g: 90, b: 90 }; export default function (pi: ExtensionAPI) { let repo = ""; let branch = ""; let added = 0; let removed = 0; let files = 0; let isRepo = false; let baseMissing = false; // HEAD at session start, for the "session" base. let sessionBaseline: string | undefined; // Session overrides set by /git-bar; layered over settings and defaults. const overrides: Partial = {}; let requestRender: (() => void) | undefined; let pollTimer: ReturnType | undefined; function settingsConfig(): Partial { const settings = pi.getSettings() as Record; const section = settings[SETTINGS_KEY]; if (typeof section !== "object" || section === null) return {}; const raw = section as Record; const result: Partial = {}; if (typeof raw.pollSeconds === "number" && Number.isFinite(raw.pollSeconds)) result.pollSeconds = raw.pollSeconds; if (BASES.includes(raw.base as DiffBase)) result.base = raw.base as DiffBase; if (METRICS.includes(raw.metric as DiffMetric)) result.metric = raw.metric as DiffMetric; if (typeof raw.hidden === "boolean") result.hidden = raw.hidden; return result; } function config(): BarConfig { return { ...DEFAULTS, ...settingsConfig(), ...overrides }; } async function headNumstat(cwd: string): Promise<{ text: string; ok: boolean }> { const diff = await pi.exec("git", ["diff", "HEAD", "--numstat"], { cwd, timeout: 3000 }); if (diff.code === 0) return { text: diff.stdout, ok: true }; // Before the first commit HEAD does not exist: combine worktree and index. const unstaged = await pi.exec("git", ["diff", "--numstat"], { cwd, timeout: 3000 }); const staged = await pi.exec("git", ["diff", "--cached", "--numstat"], { cwd, timeout: 3000 }); return { text: `${unstaged.stdout}\n${staged.stdout}`, ok: true }; } async function diffNumstat(cwd: string, base: DiffBase): Promise<{ text: string; ok: boolean }> { switch (base) { case "staged": { const r = await pi.exec("git", ["diff", "--cached", "--numstat"], { cwd, timeout: 3000 }); return { text: r.stdout, ok: r.code === 0 }; } case "session": { if (!sessionBaseline) return headNumstat(cwd); const r = await pi.exec("git", ["diff", sessionBaseline, "--numstat"], { cwd, timeout: 3000 }); return { text: r.stdout, ok: r.code === 0 }; } case "main": { const r = await pi.exec("git", ["diff", "main", "--numstat"], { cwd, timeout: 3000 }); return { text: r.stdout, ok: r.code === 0 }; } case "upstream": { const r = await pi.exec("git", ["diff", "@{upstream}", "--numstat"], { cwd, timeout: 3000 }); return { text: r.stdout, ok: r.code === 0 }; } case "head": default: return headNumstat(cwd); } } async function readGit(cwd: string) { const root = await pi.exec("git", ["rev-parse", "--show-toplevel"], { cwd, timeout: 3000 }); if (root.code !== 0) { isRepo = false; repo = cwd.split("/").filter(Boolean).pop() ?? cwd; branch = ""; added = removed = files = 0; baseMissing = false; return; } isRepo = true; const rootName = root.stdout.trim().split("/").filter(Boolean).pop() ?? root.stdout.trim(); // Show the repo plus the path inside it, since projects can be subdirs. const prefix = await pi.exec("git", ["rev-parse", "--show-prefix"], { cwd, timeout: 3000 }); const subdir = prefix.stdout.trim().replace(/\/+$/, ""); repo = subdir ? `${rootName}/${subdir}` : rootName; const head = await pi.exec("git", ["symbolic-ref", "--short", "-q", "HEAD"], { cwd, timeout: 3000 }); branch = head.stdout.trim() || "(detached)"; const result = await diffNumstat(cwd, config().base); baseMissing = !result.ok; added = removed = files = 0; for (const line of result.text.split("\n")) { if (!line.trim()) continue; const [add, del] = line.split("\t"); if (/^\d+$/.test(add ?? "") && /^\d+$/.test(del ?? "")) { added += Number(add); removed += Number(del); } files++; // binary changes print "-\t-\tpath" and still count as a file } } // Coalesce refresh bursts (e.g. parallel tool calls) into one git read. let refreshing = false; let pendingRefresh = false; async function refresh(ctx: ExtensionContext) { if (refreshing) { pendingRefresh = true; return; } refreshing = true; try { await readGit(ctx.cwd); requestRender?.(); } catch { // Leave the last known values; git may be missing or the cwd may be gone. } finally { refreshing = false; if (pendingRefresh) { pendingRefresh = false; void refresh(ctx); } } } function stopPolling() { if (pollTimer !== undefined) { clearInterval(pollTimer); pollTimer = undefined; } } function startPolling(ctx: ExtensionContext) { stopPolling(); const { hidden, pollSeconds } = config(); if (hidden || pollSeconds <= 0) return; pollTimer = setInterval(() => void refresh(ctx), pollSeconds * 1000); } function rightLabel(theme: Theme, metric: DiffMetric): string { if (!isRepo) return " "; if (baseMissing) return theme.fg("dim", " n/a "); if (metric === "files") { if (files === 0) return theme.fg("dim", " clean "); return theme.fg("accent", ` ${files} ${files === 1 ? "file" : "files"} `); } if (added === 0 && removed === 0) return theme.fg("dim", " clean "); return theme.fg("success", ` +${added} `) + theme.fg("error", `-${removed} `); } /** Widget factory, kept at this scope so hide/show can (re)install it. */ function widgetFactory(tui: TUI, theme: Theme) { requestRender = () => tui.requestRender(); const border = (text: string) => theme.style(text, { fg: BORDER }); return { dispose() { requestRender = undefined; }, invalidate() { // Nothing cached: colors are computed fresh on each render. }, render(width: number): string[] { const inner = width - 2; if (inner < 1) return [truncateToWidth(border("─".repeat(width)), width)]; const top = border("╭" + "─".repeat(inner) + "╮"); const bottom = border("╰" + "─".repeat(inner) + "╯"); const { base, metric } = config(); const baseTag = BASE_LABELS[base] ? theme.fg("dim", ` vs ${BASE_LABELS[base]}`) : ""; const left = theme.fg("accent", ` ${repo || "…"}`) + (isRepo ? theme.fg("text", ` ${branch}`) : theme.fg("dim", " not a git repo")) + baseTag + " "; const right = rightLabel(theme, metric); const gap = " ".repeat(Math.max(0, inner - visibleWidth(left) - visibleWidth(right))); const content = truncateToWidth(left + gap + right, inner); const pad = " ".repeat(Math.max(0, inner - visibleWidth(content))); const middle = border("│") + content + pad + border("│"); return [top, middle, bottom]; }, }; } function showWidget(ctx: ExtensionContext) { if (!ctx.hasUI) return; ctx.ui.setWidget(WIDGET_KEY, widgetFactory, { placement: "aboveEditor" }); } function hideWidget(ctx: ExtensionContext) { if (!ctx.hasUI) return; ctx.ui.setWidget(WIDGET_KEY, undefined); } /** Apply the current visibility, starting or stopping the poll to match. */ function applyVisibility(ctx: ExtensionContext) { if (config().hidden) { hideWidget(ctx); stopPolling(); return; } showWidget(ctx); void refresh(ctx); startPolling(ctx); } pi.on("session_start", async (_event, ctx) => { if (!ctx.hasUI) return; // Baseline for the "session" base: whatever HEAD is when this session starts. const head = await pi.exec("git", ["rev-parse", "HEAD"], { cwd: ctx.cwd, timeout: 3000 }); sessionBaseline = head.code === 0 ? head.stdout.trim() : undefined; applyVisibility(ctx); }); // Fast path: a command, edit, or write in pi usually changed the tree. pi.on("tool_execution_end", (event, ctx) => { if (MUTATING_TOOLS.has(event.toolName)) void refresh(ctx); }); // Backstop for any other tool-mediated change before the turn settles. pi.on("turn_end", (_event, ctx) => void refresh(ctx)); pi.on("session_shutdown", (_event, ctx) => { stopPolling(); requestRender = undefined; hideWidget(ctx); }); pi.registerCommand("git-bar", { description: "Git bar: hide/show, metric, base, poll, refresh", getArgumentCompletions: (prefix) => { const subs = ["hide", "show", "toggle", "metric", "base", "poll", "refresh"]; if (!prefix.includes(" ")) { const matches = subs.filter((value) => value.startsWith(prefix)); return matches.length > 0 ? matches.map((value) => ({ value, label: value })) : null; } const [sub, partial = ""] = prefix.split(/\s+/); const options: Record = { metric: METRICS, base: BASES, poll: POLL_CHOICES, }; const list = options[sub]; if (!list) return null; const matches = list.filter((value) => value.startsWith(partial)); return matches.length > 0 ? matches.map((value) => ({ value: `${sub} ${value}`, label: value })) : null; }, handler: async (args, ctx) => { const [sub, value] = args.trim().split(/\s+/); switch (sub) { case "hide": case "show": case "toggle": { const hidden = sub === "toggle" ? !config().hidden : sub === "hide"; overrides.hidden = hidden; applyVisibility(ctx); ctx.ui.notify(hidden ? "git bar hidden" : "git bar shown", "info"); return; } case "metric": { if (!METRICS.includes(value as DiffMetric)) { ctx.ui.notify("Usage: /git-bar metric lines|files", "info"); return; } overrides.metric = value as DiffMetric; requestRender?.(); ctx.ui.notify(`git bar metric: ${value}`, "info"); return; } case "base": { if (!BASES.includes(value as DiffBase)) { ctx.ui.notify(`Usage: /git-bar base ${BASES.join("|")}`, "info"); return; } overrides.base = value as DiffBase; await refresh(ctx); ctx.ui.notify(`git bar base: ${value}`, "info"); return; } case "poll": { if (value === undefined || value === "") { const seconds = config().pollSeconds; ctx.ui.notify(seconds > 0 ? `git bar polls every ${seconds}s` : "git bar polling disabled", "info"); return; } const seconds = Number(value); if (!Number.isFinite(seconds) || seconds < 0) { ctx.ui.notify(`Invalid interval: ${value}`, "error"); return; } overrides.pollSeconds = seconds; startPolling(ctx); ctx.ui.notify(seconds > 0 ? `git bar polls every ${seconds}s` : "git bar polling disabled", "info"); return; } case "refresh": { await refresh(ctx); ctx.ui.notify("git bar refreshed", "info"); return; } default: ctx.ui.notify( "Usage: /git-bar hide|show|toggle|refresh · metric lines|files · base head|staged|session|main|upstream · poll 5|10|15", "info", ); } }, }); }