an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions
HTML agent-harnessagent-orchestrationagentsai-agentsautonomous-agentsclaude-codecodexcoding-agentsdesktop-appdeveloper-toolselectrongemini-cliharnessharness-engineeringlocal-firstmemorymulti-agentopencodeorchestrationtypescript
feat(git): history + compare + guarded checkout — the commit graph goes live
Chaitanya Giri7797d205e6b1
diff --git a/src/main/git.ts b/src/main/git.tsindex fd967203..38297dba 100644--- a/src/main/git.ts+++ b/src/main/git.ts@@ -327,3 +327,163 @@ export async function worktreeIsGcSafe(// Either there are real un-integrated commits, or a query failed → keep.return { gc: false, detail: `clean but content not yet in ${baseBranch}` };}++// ─── v0.3.4: history / compare / checkout plumbing (git visualization) ───────++/** Renderer-supplied revs/refs are untrusted strings. Allow the conservative+ * charset git refs actually use, refuse leading '-' (option injection), and+ * always pass '--' before any path arguments at call sites. */+export function isSafeRev(rev: string): boolean {+ return rev.length > 0 && rev.length <= 256 && !rev.startsWith('-') && /^[0-9A-Za-z._/^~@{}-]+$/.test(rev);+}++/** Full-history DAG page for the commit graph. Same record shape as getLog but+ * topologically ordered (the graph layout assumes it) and pageable. Run this+ * against mainRepoRoot(cwd) so every agent worktree branch appears. */+export async function getLogGraph(cwd: string, n: number, skip = 0): Promise<GitCommit[] | { error: string }> {+ const sep = '\x1e';+ const fsep = '\x1f';+ const fmt = ['%H', '%P', '%s', '%an', '%at', '%D'].join(fsep) + sep;+ const res = await runGit(cwd, [+ 'log', '--all', '--topo-order', `--max-count=${n}`, ...(skip > 0 ? [`--skip=${skip}`] : []),+ `--pretty=format:${fmt}`+ ], 15000);+ if (!res.ok) return { error: res.error };+ const out: GitCommit[] = [];+ for (const rec of res.stdout.split(sep)) {+ if (!rec.trim()) continue;+ const [sha, parents, subject, author, atime, refs] = rec.split(fsep);+ if (!sha) continue;+ out.push({+ sha: sha.trim(),+ shortSha: sha.trim().slice(0, 7),+ parents: (parents ?? '').split(' ').filter(Boolean),+ subject: subject ?? '',+ author: author ?? '',+ time: parseInt(atime, 10) || 0,+ refs: (refs ?? '').split(', ').map(s => s.trim()).filter(Boolean)+ });+ }+ return out;+}++export interface GitCommitFile {+ path: string;+ status: string; // A/M/D/R/C/T…+ oldPath?: string; // for renames/copies+}++/** Parse `-z --name-status` output shared by diff-tree and diff. Records are+ * STATUS\0path\0 — with renames/copies STATUS<score>\0old\0new\0. */+function parseNameStatusZ(stdout: string): GitCommitFile[] {+ const tokens = stdout.split('\0').filter((t) => t.length > 0);+ const files: GitCommitFile[] = [];+ for (let i = 0; i < tokens.length; i++) {+ const status = tokens[i];+ if (!/^[A-Z]/.test(status)) continue; // skip stray commit ids+ const kind = status[0];+ if (kind === 'R' || kind === 'C') {+ const oldPath = tokens[i + 1];+ const path = tokens[i + 2];+ i += 2;+ if (path) files.push({ path, status: kind, oldPath });+ } else {+ const path = tokens[i + 1];+ i += 1;+ if (path) files.push({ path, status: kind });+ }+ }+ return files;+}++/** Files touched by one commit (rename-aware). */+export async function getCommitFiles(cwd: string, sha: string): Promise<GitCommitFile[] | { error: string }> {+ if (!isSafeRev(sha)) return { error: 'invalid revision' };+ const res = await runGit(cwd, ['diff-tree', '--no-commit-id', '-r', '--root', '-z', '-M', '--name-status', sha, '--']);+ if (!res.ok) return { error: res.error };+ return parseNameStatusZ(res.stdout);+}++const MAX_SHOW_BYTES = 2 * 1024 * 1024; // match getDiff's cap++/** One side of a rev-pinned diff: the file's content at `rev` ('' + exists:false+ * when the path doesn't exist there — e.g. an added file's parent side). */+export async function getFileAtRev(cwd: string, rev: string, relPath: string): Promise<+ { ok: true; exists: boolean; isBinary: boolean; content: string } | { ok: false; error: string }+> {+ if (!isSafeRev(rev)) return { ok: false, error: 'invalid revision' };+ if (!safeJoin(cwd, relPath)) return { ok: false, error: 'path escapes repository root' };+ const size = await runGit(cwd, ['cat-file', '-s', `${rev}:${relPath}`]);+ if (!size.ok) return { ok: true, exists: false, isBinary: false, content: '' };+ if ((parseInt(size.stdout.trim(), 10) || 0) > MAX_SHOW_BYTES) {+ return { ok: false, error: 'file too large to diff (>2 MB)' };+ }+ const res = await runGit(cwd, ['show', `${rev}:${relPath}`]);+ if (!res.ok) return { ok: true, exists: false, isBinary: false, content: '' };+ if (res.stdout.includes('\0')) return { ok: true, exists: true, isBinary: true, content: '' };+ return { ok: true, exists: true, isBinary: false, content: res.stdout };+}++export interface GitCompare {+ ahead: number; // commits in head, not base+ behind: number; // commits in base, not head+ mergeBase: string | null;+ files: GitCommitFile[];+}++/** Compare two refs. mode 'three' (default, PR-style): what head adds since the+ * merge base. mode 'two': the literal state difference base→head. */+export async function compareRefs(cwd: string, base: string, head: string, mode: 'two' | 'three'): Promise<GitCompare | { error: string }> {+ if (!isSafeRev(base) || !isSafeRev(head)) return { error: 'invalid revision' };+ const counts = await runGit(cwd, ['rev-list', '--left-right', '--count', `${base}...${head}`]);+ if (!counts.ok) return { error: counts.error };+ const [behind, ahead] = counts.stdout.trim().split('\t').map((x) => parseInt(x, 10) || 0);+ const mb = await runGit(cwd, ['merge-base', base, head]);+ const mergeBase = mb.ok ? mb.stdout.trim() : null;+ const diffArgs = mode === 'three'+ ? ['diff', '-z', '-M', '--name-status', `${base}...${head}`, '--']+ : ['diff', '-z', '-M', '--name-status', base, head, '--'];+ const res = await runGit(cwd, diffArgs, 15000);+ if (!res.ok) return { error: res.error };+ return { ahead, behind, mergeBase, files: parseNameStatusZ(res.stdout) };+}++export interface GitWorktreeInfo { path: string; head: string; branch: string | null }++export async function listWorktrees(cwd: string): Promise<GitWorktreeInfo[] | { error: string }> {+ const res = await runGit(cwd, ['worktree', 'list', '--porcelain']);+ if (!res.ok) return { error: res.error };+ const out: GitWorktreeInfo[] = [];+ let cur: Partial<GitWorktreeInfo> = {};+ for (const line of res.stdout.split('\n')) {+ if (line.startsWith('worktree ')) { if (cur.path) out.push(cur as GitWorktreeInfo); cur = { path: line.slice(9), head: '', branch: null }; }+ else if (line.startsWith('HEAD ')) cur.head = line.slice(5);+ else if (line.startsWith('branch ')) cur.branch = line.slice(7).replace(/^refs\/heads\//, '');+ }+ if (cur.path) out.push(cur as GitWorktreeInfo);+ return out;+}++/** Guarded checkout (v0.3.4). FAIL-SAFE philosophy like worktreeHasUnintegratedWork:+ * any doubt → refuse. Guards here cover the repo itself; the IPC layer adds the+ * "no agent actively working in this tree" guard (it owns the pty registry). */+export async function checkoutRef(cwd: string, ref: string, detach: boolean): Promise<{ ok: true; detached: boolean } | { ok: false; error: string }> {+ if (!isSafeRev(ref)) return { ok: false, error: 'invalid revision' };+ const st = await getStatus(cwd);+ if ('error' in st) return { ok: false, error: `could not verify a clean tree: ${st.error}` };+ const dirty = st.staged.length + st.unstaged.length;+ if (dirty > 0) {+ return { ok: false, error: `working tree has ${dirty} uncommitted change${dirty === 1 ? '' : 's'} — commit or stash first` };+ }+ const res = await runGit(cwd, detach ? ['switch', '--detach', ref] : ['switch', ref], 15000);+ if (!res.ok) {+ // A branch held by another worktree: name the holder instead of raw stderr.+ if (/already checked out|already used by worktree/i.test(res.error)) {+ const wts = await listWorktrees(cwd);+ const holder = Array.isArray(wts) ? wts.find((w) => w.branch === ref.replace(/^refs\/heads\//, '')) : undefined;+ return { ok: false, error: holder ? `'${ref}' is checked out in another worktree: ${holder.path}` : res.error };+ }+ return { ok: false, error: res.error };+ }+ return { ok: true, detached: detach };+}diff --git a/src/main/index.ts b/src/main/index.tsindex 88b2cea1..85b21a7c 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -18,7 +18,8 @@ import {import { listDir, readFileText, writeFileText, statAbs } from './fs';import {getBranch, getStatus, getLog, getBranches, getAheadBehind, isRepo, getDiff, mainRepoRoot,- addWorktree, removeWorktree, worktreeHasUnintegratedWork, worktreeIsGcSafe+ addWorktree, removeWorktree, worktreeHasUnintegratedWork, worktreeIsGcSafe,+ getLogGraph, getCommitFiles, getFileAtRev, compareRefs, listWorktrees, checkoutRef} from './git';import { HiveManager, type AgentMeta, type HiveMessage, type HiveTask } from './hive';import { HookServer } from './hooks';@@ -2613,6 +2614,49 @@ ipcMain.handle('git:diff', (_evt, cwd: unknown, relPath: unknown) => {}return getDiff(cwd, relPath);});+// ─── v0.3.4: history / compare / checkout (git visualization) ───────────────+ipcMain.handle('git:logGraph', (_evt, cwd: unknown, n: unknown, skip: unknown) => {+ if (typeof cwd !== 'string') return { error: 'invalid args' };+ const count = Math.min(500, Math.max(1, typeof n === 'number' ? n : 200));+ const off = Math.max(0, typeof skip === 'number' ? skip : 0);+ return getLogGraph(cwd, count, off);+});+ipcMain.handle('git:commitFiles', (_evt, cwd: unknown, sha: unknown) => {+ if (typeof cwd !== 'string' || typeof sha !== 'string') return { error: 'invalid args' };+ return getCommitFiles(cwd, sha);+});+ipcMain.handle('git:showFile', (_evt, cwd: unknown, rev: unknown, relPath: unknown) => {+ if (typeof cwd !== 'string' || typeof rev !== 'string' || typeof relPath !== 'string') {+ return { ok: false, error: 'invalid args' };+ }+ return getFileAtRev(cwd, rev, relPath);+});+ipcMain.handle('git:compareRefs', (_evt, cwd: unknown, base: unknown, head: unknown, mode: unknown) => {+ if (typeof cwd !== 'string' || typeof base !== 'string' || typeof head !== 'string') {+ return { error: 'invalid args' };+ }+ return compareRefs(cwd, base, head, mode === 'two' ? 'two' : 'three');+});+ipcMain.handle('git:worktrees', (_evt, cwd: unknown) => {+ if (typeof cwd !== 'string') return { error: 'invalid args' };+ return listWorktrees(cwd);+});+ipcMain.handle('git:checkout', async (_evt, cwd: unknown, ref: unknown, detach: unknown) => {+ if (typeof cwd !== 'string' || typeof ref !== 'string') return { ok: false, error: 'invalid args' };+ // Guard: never swap files under an actively-working agent. Objective signal+ // owned by main — any live pty whose cwd sits in this tree and emitted output+ // in the last 10s is treated as mid-run. (Idle-but-open terminals are fine:+ // checkoutRef additionally requires a clean tree, and TUIs redraw on fs+ // changes gracefully.)+ const busy = ptyManager.list().find((p) =>+ (p.cwd === cwd || p.cwd.startsWith(cwd.endsWith('/') ? cwd : `${cwd}/`)) &&+ Date.now() - p.lastOutputAt < 10_000+ );+ if (busy) {+ return { ok: false, error: `an agent is actively working in this repo (${busy.id}) — try again when it goes quiet` };+ }+ return checkoutRef(cwd, ref, detach === true);+});// ─── IPC: roster mirror (shared between dev and a packaged build) ───────────// The renderer's store is built synchronously at module load, before any asyncdiff --git a/src/preload/index.ts b/src/preload/index.tsindex 375200da..c3d79d7e 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -389,6 +389,22 @@ export interface GitDiff {isBinary: boolean;}+/** v0.3.4 git visualization — mirrors src/main/git.ts GitCommit / GitCommitFile. */+export interface GitCommitRow {+ sha: string;+ shortSha: string;+ parents: string[];+ subject: string;+ author: string;+ time: number;+ refs: string[];+}+export interface GitFileChange {+ path: string;+ status: string;+ oldPath?: string;+}+/** Real token usage + estimated USD cost summed from an agent's Claude Code* transcripts under ~/.claude/projects. Reconciler/fallback path — now priced* PER MODEL (not Sonnet-for-everyone). The live path uses AgentUsageSample. */@@ -639,6 +655,27 @@ const api = {* text sides. Backs the IDE's git-diff (Monaco DiffEditor) view. */gitDiff: (cwd: string, relPath: string) =>ipcRenderer.invoke('git:diff', cwd, relPath) as Promise<GitDiff | { ok: false; error: string }>,+ // ── v0.3.4: history / compare / checkout (git visualization) ──+ gitLogGraph: (cwd: string, n: number, skip?: number) =>+ ipcRenderer.invoke('git:logGraph', cwd, n, skip ?? 0) as Promise<GitCommitRow[] | { error: string }>,+ gitCommitFiles: (cwd: string, sha: string) =>+ ipcRenderer.invoke('git:commitFiles', cwd, sha) as Promise<GitFileChange[] | { error: string }>,+ gitShowFile: (cwd: string, rev: string, relPath: string) =>+ ipcRenderer.invoke('git:showFile', cwd, rev, relPath) as Promise<+ { ok: true; exists: boolean; isBinary: boolean; content: string } | { ok: false; error: string }+ >,+ gitCompareRefs: (cwd: string, base: string, head: string, mode?: 'two' | 'three') =>+ ipcRenderer.invoke('git:compareRefs', cwd, base, head, mode ?? 'three') as Promise<+ { ahead: number; behind: number; mergeBase: string | null; files: GitFileChange[] } | { error: string }+ >,+ gitWorktrees: (cwd: string) =>+ ipcRenderer.invoke('git:worktrees', cwd) as Promise<+ Array<{ path: string; head: string; branch: string | null }> | { error: string }+ >,+ gitCheckout: (cwd: string, ref: string, detach?: boolean) =>+ ipcRenderer.invoke('git:checkout', cwd, ref, detach === true) as Promise<+ { ok: true; detached: boolean } | { ok: false; error: string }+ >,// ─── Hive (multi-agent coordination) ─────────────────────────────────────hiveRegistry: (): Promise<HiveRegistry> => ipcRenderer.invoke('hive:registry'),diff --git a/src/renderer/src/components/AgentDetailPanel.tsx b/src/renderer/src/components/AgentDetailPanel.tsxindex 09a5f6fa..b1b73ed8 100644--- a/src/renderer/src/components/AgentDetailPanel.tsx+++ b/src/renderer/src/components/AgentDetailPanel.tsx@@ -12,6 +12,7 @@ import { SidebarTabs } from './SidebarTabs';import { ThreadsPanel } from './ThreadsPanel';import { ToolWaterfall } from './ToolWaterfall';import { AgentControlStrip } from './AgentControlStrip';+import { GitTab } from './GitTab';import { Icon } from './Icon';import { useStore, type Agent } from '@/store/store';import { usePtyParser } from '@/hooks/usePtyParser';@@ -188,6 +189,10 @@ export function AgentDetailPanel({ agent }: AgentDetailPanelProps) {))}+ {sidebarTab === 'git' && (+ <GitTab cwd={agent.cwd} />+ )}+{sidebarTab === 'messages' && (<ThreadsPanel agentId={agent.id} />)}diff --git a/src/renderer/src/components/SidebarTabs.tsx b/src/renderer/src/components/SidebarTabs.tsxindex 38ffebf7..ad867bcf 100644--- a/src/renderer/src/components/SidebarTabs.tsx+++ b/src/renderer/src/components/SidebarTabs.tsx@@ -6,6 +6,7 @@ import { Icon, type IconName } from './Icon';// full Monaco editor + file tree, which superseded the read-only browser.const TABS: { key: SidebarTab; label: string; icon: IconName }[] = [{ key: 'terminal', label: 'terminal', icon: 'terminal' },+ { key: 'git', label: 'git', icon: 'code' },{ key: 'messages', label: 'messages', icon: 'bell' },{ key: 'traces', label: 'traces', icon: 'web' }];diff --git a/src/renderer/src/components/git/CommitGraph.tsx b/src/renderer/src/components/git/CommitGraph.tsxindex ba78e598..de68e54c 100644--- a/src/renderer/src/components/git/CommitGraph.tsx+++ b/src/renderer/src/components/git/CommitGraph.tsx@@ -15,16 +15,19 @@ export interface CommitGraphProps {commits: CommitLite[];/** Name of the currently checked-out branch, for highlighting. */currentBranch?: string | null;+ /** v0.3.4: commit click → per-commit file list / diff in the IDE HISTORY pane. */+ onCommitClick?: (sha: string) => void;}// CTH palette → branch lane colors (commit-graph renders raw colors into SVG).+// v0.3.4 recalibration: the muted set, matching tokens.css.const BRANCH_COLORS = [- '#4ECDC4', // sky- '#FFD93D', // lemon- '#6BCF7F', // mint- '#FF6B6B', // coral- '#B197FC', // lilac- '#FFA07A' // peach+ '#4F9FAF', // sky+ '#DCAB3C', // lemon/amber+ '#5CA97A', // mint/sage+ '#D96A62', // coral+ '#9482D3', // lilac+ '#D99168' // peach];const GRAPH_STYLE = {@@ -44,7 +47,7 @@ function relTime(d: string | number | Date): string {return `${Math.round(delta / (86400 * 30))}mo`;}-export function CommitGraph({ commits, currentBranch }: CommitGraphProps) {+export function CommitGraph({ commits, currentBranch, onCommitClick }: CommitGraphProps) {// Adapt our flat git-log rows into the GitHub-style shape commit-graph expects.const libCommits: Commit[] = useMemo(() => commits.map(c => ({sha: c.sha,@@ -84,6 +87,7 @@ export function CommitGraph({ commits, currentBranch }: CommitGraphProps) {graphStyle={GRAPH_STYLE}currentBranch={currentBranch ?? undefined}dateFormatFn={relTime}+ onCommitClick={onCommitClick ? (c) => onCommitClick(c.hash) : undefined}/></div>);diff --git a/src/renderer/src/ide/GitPanes.tsx b/src/renderer/src/ide/GitPanes.tsxnew file mode 100644index 00000000..1670de6a--- /dev/null+++ b/src/renderer/src/ide/GitPanes.tsx@@ -0,0 +1,248 @@+/**+ * v0.3.4 git visualization — the HISTORY and COMPARE panes of the IDE's left+ * rail. Both operate at the repository's MAIN root (mainRepoRoot), so every+ * agent worktree branch appears in one graph. All git access stays in the main+ * process; these panes only render what the IPC returns.+ */+import { useCallback, useEffect, useState } from 'react';+import { CommitGraph } from '@/components/git/CommitGraph';+import { Icon } from '@/components/Icon';++// Local mirrors of the main-side git shapes (renderer-local by convention —+// importing the preload module would drag electron into the bundle).+interface GitCommitRow {+ sha: string; shortSha: string; parents: string[];+ subject: string; author: string; time: number; refs: string[];+}+interface GitFileChange { path: string; status: string; oldPath?: string }++function statusColor(code: string): string {+ if (code === 'M') return 'var(--cth-lemon)';+ if (code === 'A') return 'var(--cth-mint)';+ if (code === 'D') return 'var(--cth-coral)';+ if (code === 'R' || code === 'C') return 'var(--cth-lilac)';+ return 'var(--cth-ink-500)';+}++const rowStyle: React.CSSProperties = {+ display: 'flex', alignItems: 'center', gap: 6, padding: '2px 12px',+ cursor: 'pointer', fontSize: 12, color: 'var(--cth-ink-900)'+};+const noteStyle: React.CSSProperties = {+ padding: '6px 12px', fontSize: 12, color: 'var(--cth-ink-500)'+};+const smallBtn: React.CSSProperties = {+ padding: '0 6px', height: 20, fontFamily: 'var(--cth-font-ui)', fontSize: 11,+ color: 'var(--cth-ink-900)', background: 'var(--cth-cream-100)', border: 'none',+ boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)', cursor: 'pointer',+ display: 'inline-flex', alignItems: 'center', gap: 3, flexShrink: 0+};++function FileRow({ f, onClick }: { f: GitFileChange; onClick: () => void }) {+ return (+ <div onClick={onClick} title={f.oldPath ? `${f.oldPath} → ${f.path}` : f.path} style={rowStyle}>+ <span style={{+ width: 12, textAlign: 'center', fontFamily: 'var(--cth-font-mono)',+ fontWeight: 'bold' as const, color: statusColor(f.status)+ }}>{f.status}</span>+ <span style={{+ flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',+ fontFamily: 'var(--cth-font-mono)', direction: 'rtl', textAlign: 'left'+ }}>{f.path}</span>+ </div>+ );+}++// ─── HISTORY ─────────────────────────────────────────────────────────────────++export function HistoryPane({ gitRoot, onOpenRevDiff }: {+ gitRoot: string;+ /** Open a Monaco diff of `path` between `revA` (parent/base) and `revB`. */+ onOpenRevDiff: (revA: string, revB: string, path: string, label: string) => void;+}) {+ const [commits, setCommits] = useState<GitCommitRow[]>([]);+ const [branch, setBranch] = useState<string | null>(null);+ const [loading, setLoading] = useState(true);+ const [selected, setSelected] = useState<GitCommitRow | null>(null);+ const [files, setFiles] = useState<GitFileChange[] | null>(null);+ const [note, setNote] = useState('');+ const [page, setPage] = useState(1);++ const load = useCallback(async (pages: number) => {+ setLoading(true);+ const [log, br] = await Promise.all([+ window.cth.gitLogGraph(gitRoot, pages * 200),+ window.cth.gitBranch(gitRoot)+ ]);+ if (Array.isArray(log)) setCommits(log);+ if (!('error' in br)) setBranch(br.current);+ setLoading(false);+ }, [gitRoot]);++ useEffect(() => { void load(page); }, [load, page]);++ const pick = useCallback(async (sha: string) => {+ const c = commits.find((x) => x.sha === sha) ?? null;+ setSelected(c);+ setFiles(null);+ setNote('');+ if (!c) return;+ const res = await window.cth.gitCommitFiles(gitRoot, sha);+ if (Array.isArray(res)) setFiles(res);+ else setNote(res.error);+ }, [commits, gitRoot]);++ const jump = async (c: GitCommitRow) => {+ if (!window.confirm(`Jump the repo to ${c.shortSha} ("${c.subject.slice(0, 60)}")?\n\nThis detaches HEAD. Blocked automatically if the tree is dirty or an agent is mid-run.`)) return;+ const res = await window.cth.gitCheckout(gitRoot, c.sha, true);+ setNote(res.ok ? `now at ${c.shortSha} (detached HEAD)` : res.error);+ if (res.ok) void load(page);+ };++ return (+ <div style={{ display: 'flex', flexDirection: 'column', minHeight: 0, flex: 1 }}>+ <div style={{ flex: 1, minHeight: 0, overflow: 'auto' }}>+ {loading && commits.length === 0 && <div style={noteStyle}>loading history…</div>}+ {!loading && commits.length === 0 && <div style={noteStyle}>no commits</div>}+ <CommitGraph commits={commits} currentBranch={branch} onCommitClick={(sha) => { void pick(sha); }} />+ {commits.length >= page * 200 && (+ <div style={{ padding: '4px 12px' }}>+ <button style={smallBtn} onClick={() => setPage((p) => p + 1)}>load older…</button>+ </div>+ )}+ </div>+ {selected && (+ <div style={{+ flexShrink: 0, maxHeight: '45%', display: 'flex', flexDirection: 'column', minHeight: 0,+ borderTop: '1px solid var(--cth-ink-300)', background: 'var(--cth-cream-50)'+ }}>+ <div style={{+ display: 'flex', alignItems: 'center', gap: 6, padding: '5px 12px 3px',+ fontSize: 12, color: 'var(--cth-ink-700)'+ }}>+ <span style={{ fontFamily: 'var(--cth-font-mono)', color: 'var(--cth-ink-900)' }}>{selected.shortSha}</span>+ <span style={{+ flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'+ }} title={selected.subject}>{selected.subject}</span>+ <button style={smallBtn} onClick={() => void jump(selected)} title="Check out this commit (detached HEAD)">+ <Icon name="arrow-right" /> jump here+ </button>+ <button style={{ ...smallBtn, width: 20, justifyContent: 'center' }} onClick={() => setSelected(null)} title="Close">✕</button>+ </div>+ <div style={{ overflow: 'auto', minHeight: 0 }}>+ {!files && !note && <div style={noteStyle}>loading files…</div>}+ {note && <div style={{ ...noteStyle, color: 'var(--cth-ink-700)' }}>{note}</div>}+ {files && files.length === 0 && <div style={noteStyle}>no file changes (merge?)</div>}+ {files?.map((f) => (+ <FileRow+ key={f.path}+ f={f}+ onClick={() => onOpenRevDiff(`${selected.sha}^`, selected.sha, f.path, selected.shortSha)}+ />+ ))}+ </div>+ </div>+ )}+ </div>+ );+}++// ─── COMPARE ─────────────────────────────────────────────────────────────────++export function ComparePane({ gitRoot, onOpenRevDiff }: {+ gitRoot: string;+ onOpenRevDiff: (revA: string, revB: string, path: string, label: string) => void;+}) {+ const [branches, setBranches] = useState<string[]>([]);+ const [base, setBase] = useState('');+ const [head, setHead] = useState('');+ const [mode, setMode] = useState<'two' | 'three'>('three');+ const [result, setResult] = useState<{ ahead: number; behind: number; mergeBase: string | null; files: GitFileChange[] } | null>(null);+ const [note, setNote] = useState('');++ useEffect(() => {+ void window.cth.gitBranches(gitRoot).then((res) => {+ if ('error' in res) { setNote(res.error); return; }+ const all = [...res.local, ...res.remote];+ setBranches(all);+ if (res.current) setHead((h) => h || res.current!);+ const guess = res.local.find((b) => b === 'main' || b === 'master') ?? res.local[0];+ if (guess) setBase((b) => b || guess);+ });+ }, [gitRoot]);++ useEffect(() => {+ if (!base || !head) { setResult(null); return; }+ let alive = true;+ setNote('comparing…');+ void window.cth.gitCompareRefs(gitRoot, base, head, mode).then((res) => {+ if (!alive) return;+ if ('error' in res) { setNote(res.error); setResult(null); return; }+ setNote('');+ setResult(res);+ });+ return () => { alive = false; };+ }, [gitRoot, base, head, mode]);++ const switchTo = async () => {+ if (!head) return;+ if (!window.confirm(`Switch this repo to '${head}'?\n\nBlocked automatically if the tree is dirty or an agent is mid-run.`)) return;+ const res = await window.cth.gitCheckout(gitRoot, head.replace(/^origin\//, ''), false);+ setNote(res.ok ? `switched to ${head}` : res.error);+ };++ const sel: React.CSSProperties = {+ flex: 1, minWidth: 0, height: 22, fontFamily: 'var(--cth-font-mono)', fontSize: 11,+ background: 'var(--cth-paper-100)', color: 'var(--cth-ink-900)',+ border: 'none', boxShadow: 'inset 0 0 0 1px var(--cth-ink-100)'+ };++ return (+ <div style={{ display: 'flex', flexDirection: 'column', minHeight: 0, flex: 1 }}>+ <div style={{ display: 'flex', flexDirection: 'column', gap: 4, padding: '6px 12px', flexShrink: 0 }}>+ <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>+ <select value={base} onChange={(e) => setBase(e.target.value)} style={sel} title="Base — the branch you're comparing against">+ {branches.map((b) => <option key={b} value={b}>{b}</option>)}+ </select>+ <button style={{ ...smallBtn, width: 22, justifyContent: 'center' }} title="Swap base ↔ compare"+ onClick={() => { setBase(head); setHead(base); }}>⇄</button>+ <select value={head} onChange={(e) => setHead(e.target.value)} style={sel} title="Compare — the branch whose changes you're viewing">+ {branches.map((b) => <option key={b} value={b}>{b}</option>)}+ </select>+ </div>+ <div style={{ display: 'flex', gap: 6, alignItems: 'center', fontSize: 11, color: 'var(--cth-ink-500)' }}>+ {result && (+ <span title={`'${head}' is ${result.ahead} ahead and ${result.behind} behind '${base}'`}>+ ↑{result.ahead} ↓{result.behind}+ </span>+ )}+ <button+ style={{ ...smallBtn, background: mode === 'three' ? 'var(--cth-sky-light)' : 'var(--cth-cream-100)' }}+ onClick={() => setMode((m) => (m === 'three' ? 'two' : 'three'))}+ title={mode === 'three'+ ? 'Showing what the compare branch ADDS since the common ancestor (PR-style). Click for the literal two-dot difference.'+ : 'Showing the literal difference between the two branch states. Click for PR-style (what compare adds).'}+ >{mode === 'three' ? 'since common ancestor' : 'literal difference'}</button>+ <span style={{ flex: 1 }} />+ <button style={smallBtn} onClick={() => void switchTo()} title={`Check out '${head}'`}>+ <Icon name="arrow-right" /> switch to {head.split('/').pop()}+ </button>+ </div>+ </div>+ <div style={{ flex: 1, minHeight: 0, overflow: 'auto', borderTop: '1px solid var(--cth-ink-100)' }}>+ {note && <div style={noteStyle}>{note}</div>}+ {result && result.files.length === 0 && !note && <div style={noteStyle}>no differences</div>}+ {result?.files.map((f) => (+ <FileRow+ key={f.path}+ f={f}+ onClick={() => onOpenRevDiff(+ mode === 'three' ? (result.mergeBase ?? base) : base,+ head, f.path, `${base}…${head}`+ )}+ />+ ))}+ </div>+ </div>+ );+}diff --git a/src/renderer/src/ide/IdePanel.tsx b/src/renderer/src/ide/IdePanel.tsxindex a56d0843..473df24e 100644--- a/src/renderer/src/ide/IdePanel.tsx+++ b/src/renderer/src/ide/IdePanel.tsx@@ -5,6 +5,7 @@ import { Icon } from '@/components/Icon';import { MonacoEditor } from './MonacoEditor';import { MonacoDiff } from './MonacoDiff';import { MarkdownPreview } from '@/markdown/MarkdownPreview';+import { HistoryPane, ComparePane } from './GitPanes';// v0.3.4 markdown preview: per-md-tab view mode, defaulted from the last choice.type MdView = 'code' | 'split' | 'preview';@@ -22,8 +23,12 @@ function defaultMdView(): MdView {interface GitStatusEntry { path: string; index: string; worktree: string }interface GitStatusT { staged: GitStatusEntry[]; unstaged: GitStatusEntry[]; untracked: string[] }-type TabMode = 'edit' | 'diff';-interface Tab { key: string; rel: string; mode: TabMode }+type TabMode = 'edit' | 'diff' | 'revdiff';+interface Tab {+ key: string; rel: string; mode: TabMode;+ /** revdiff only: the two sides + a short human label ("a1b2c3d" / "main…feat"). */+ revA?: string; revB?: string; revLabel?: string;+}interface EditBuffer {content: string;@@ -72,6 +77,16 @@ export function IdePanel() {const [isRepo, setIsRepo] = useState<boolean | null>(null);const [status, setStatus] = useState<GitStatusT | null>(null);const [treeWidth, setTreeWidth] = useState(300);+ // v0.3.4 git visualization: which rail pane is showing, and the repo's MAIN+ // root (a worktree's history/compare must run against the shared repo).+ const [railTab, setRailTab] = useState<'changes' | 'history' | 'compare'>('changes');+ const [gitRoot, setGitRoot] = useState<string | null>(null);+ useEffect(() => {+ if (!root) return;+ let alive = true;+ void window.cth.gitMainRepo(root).then((r) => { if (alive) setGitRoot(r ?? root); });+ return () => { alive = false; };+ }, [root]);// Per-markdown-tab view mode (code | split | preview); changing it also// updates the sticky default for the next markdown file.const [mdViews, setMdViews] = useState<Record<string, MdView>>({});@@ -131,6 +146,35 @@ export function IdePanel() {const openEdit = useCallback((rel: string) => { ensureEdit(rel); openTab('edit', rel); }, [ensureEdit, openTab]);+ // v0.3.4: rev-pinned diff tabs (per-commit files + branch compare). Both+ // sides load through the metadata-guarded git:showFile IPC at the MAIN root.+ const openRevDiff = useCallback((revA: string, revB: string, rel: string, revLabel: string) => {+ const repo = gitRoot ?? root;+ if (!repo) return;+ const key = `rev::${revA}::${revB}::${rel}`;+ setTabs((prev) => (prev.some((t) => t.key === key)+ ? prev+ : [...prev, { key, rel, mode: 'revdiff', revA, revB, revLabel }]));+ setActiveKey(key);+ if (diffDataRef.current[key] && diffDataRef.current[key].status !== 'error') return;+ setDiffData((p) => ({ ...p, [key]: { status: 'loading', head: '', working: '' } }));+ void Promise.all([+ window.cth.gitShowFile(repo, revA, rel),+ window.cth.gitShowFile(repo, revB, rel)+ ]).then(([a, b]) => {+ if (!a.ok || !b.ok) {+ const error = (!a.ok ? a.error : !b.ok ? (b as { error: string }).error : 'diff failed');+ setDiffData((p) => ({ ...p, [key]: { status: 'error', head: '', working: '', error } }));+ return;+ }+ if (a.isBinary || b.isBinary) {+ setDiffData((p) => ({ ...p, [key]: { status: 'binary', head: '', working: '' } }));+ return;+ }+ setDiffData((p) => ({ ...p, [key]: { status: 'ready', head: a.content, working: b.content } }));+ });+ }, [gitRoot, root]);+// Entry point from elsewhere in the app ("open in IDE" on the file overlay):// consume the queued absolute path once the root is known, open it (preview// for markdown), then clear the queue slot so a later IDE open starts fresh.@@ -307,13 +351,34 @@ export function IdePanel() {display: 'flex', flexDirection: 'column',borderRight: '1px solid var(--cth-ink-700)', background: 'var(--cth-cream-50)'}}>- {/* CHANGES */}- <div style={{ flexShrink: 0, maxHeight: '45%', display: 'flex', flexDirection: 'column', minHeight: 0 }}>- <SectionHeader title="changes" right={+ {/* Git rail: CHANGES · HISTORY · COMPARE (v0.3.4). History/compare+ run at the repo's MAIN root so worktree branches all appear. */}+ <div style={{+ flexShrink: 0, display: 'flex', gap: 2, padding: '6px 10px 4px',+ background: 'var(--cth-cream-50)', borderBottom: '1px solid var(--cth-ink-100)'+ }}>+ {(['changes', 'history', 'compare'] as const).map((k) => (+ <button+ key={k}+ onClick={() => setRailTab(k)}+ style={{+ padding: '1px 8px', border: 'none', cursor: 'pointer',+ fontFamily: 'var(--cth-font-display)', fontSize: 8, lineHeight: '14px',+ textTransform: 'uppercase', color: 'var(--cth-ink-700)',+ background: railTab === k ? 'var(--cth-sky-light)' : 'transparent',+ boxShadow: railTab === k ? 'inset 0 0 0 1px var(--cth-ink-300)' : 'none'+ }}+ >{k}</button>+ ))}+ <span style={{ flex: 1 }} />+ {railTab === 'changes' && (<button onClick={() => refreshStatus()} title="Refresh" style={iconBtn}><Icon name="web" /></button>- } />+ )}+ </div>+ {railTab === 'changes' && (+ <div style={{ flexShrink: 0, maxHeight: '45%', display: 'flex', flexDirection: 'column', minHeight: 0 }}><div style={{ overflow: 'auto', minHeight: 0 }}>{isRepo === false && (<div style={{ padding: '6px 12px', fontSize: 12, color: 'var(--cth-ink-500)' }}>not a git repo</div>@@ -347,6 +412,13 @@ export function IdePanel() {})}</div></div>+ )}+ {railTab === 'history' && gitRoot && (+ <HistoryPane key={gitRoot} gitRoot={gitRoot} onOpenRevDiff={openRevDiff} />+ )}+ {railTab === 'compare' && gitRoot && (+ <ComparePane key={gitRoot} gitRoot={gitRoot} onOpenRevDiff={openRevDiff} />+ )}{/* FILES */}<div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', borderTop: '1px solid var(--cth-ink-300)' }}><SectionHeader title="files" />@@ -384,11 +456,12 @@ export function IdePanel() {fontFamily: 'var(--cth-font-ui)', fontSize: 12, color: 'var(--cth-ink-900)'}}>- {t.mode === 'diff' && (+ {t.mode !== 'edit' && (<span style={{fontFamily: 'var(--cth-font-display)', fontSize: 7, padding: '1px 3px',- background: 'var(--cth-sky-light)', color: 'var(--cth-ink-900)'- }}>DIFF</span>+ background: t.mode === 'revdiff' ? 'var(--cth-lilac-light)' : 'var(--cth-sky-light)',+ color: 'var(--cth-ink-900)'+ }}>{t.mode === 'revdiff' ? (t.revLabel ?? 'REV') : 'DIFF'}</span>)}<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{basename(t.rel)}{dirty ? ' •' : ''}@@ -468,6 +541,33 @@ export function IdePanel() {);})()}+ {activeTab?.mode === 'revdiff' && (() => {+ const d = diffData[activeTab.key];+ if (!d || d.status === 'loading') return <Centered>loading diff…</Centered>;+ if (d.status === 'error') return <Centered tone="error">{d.error}</Centered>;+ if (d.status === 'binary') return <Centered>binary file — no text diff</Centered>;+ return (+ <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>+ <div style={{+ display: 'flex', alignItems: 'center', gap: 8, padding: '3px 8px',+ background: 'var(--cth-cream-200)', borderBottom: '1px solid var(--cth-ink-700)',+ fontFamily: 'var(--cth-font-ui)', fontSize: 12, color: 'var(--cth-ink-700)'+ }}>+ <span style={{ fontFamily: 'var(--cth-font-mono)', color: 'var(--cth-ink-500)' }}>+ {activeTab.revLabel ?? `${activeTab.revA} → ${activeTab.revB}`}+ </span>+ <span style={{+ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',+ fontFamily: 'var(--cth-font-mono)', textAlign: 'right'+ }} title={activeTab.rel}>{activeTab.rel}</span>+ </div>+ <div style={{ flex: 1, minHeight: 0 }}>+ <MonacoDiff path={activeTab.rel} original={d.head} modified={d.working} />+ </div>+ </div>+ );+ })()}+{activeTab?.mode === 'diff' && (() => {const d = diffData[activeTab.rel];if (!d || d.status === 'loading') return <Centered>loading diff…</Centered>;diff --git a/src/renderer/src/store/store.ts b/src/renderer/src/store/store.tsindex a500f4a4..4c2694f1 100644--- a/src/renderer/src/store/store.ts+++ b/src/renderer/src/store/store.ts@@ -116,8 +116,9 @@ export interface QueuedMessage {}// 'files' retired in v0.3.4 (the per-agent IDE button superseded it) — a-// persisted 'files' selection falls back to 'terminal' on load.-export type SidebarTab = 'terminal' | 'messages' | 'traces';+// persisted 'files' selection falls back to 'terminal' on load. 'git' added in+// v0.3.4: at-a-glance branch/status/log without opening the IDE.+export type SidebarTab = 'terminal' | 'messages' | 'traces' | 'git';/** Lifecycle of the god agent ("Michael") bootstrap on launch.* 'booting' until his PTY is confirmed live, then 'ready' (or 'failed' if the@@ -500,7 +501,7 @@ const initialSidebarWidth = (() => {const initialSidebarTab: SidebarTab = (() => {try {const v = window.localStorage.getItem(LS_SIDEBAR_TAB);- if (v === 'terminal' || v === 'messages' || v === 'traces') return v;+ if (v === 'terminal' || v === 'messages' || v === 'traces' || v === 'git') return v;} catch { /* noop */ }return 'terminal';})();