/** * GitPanel – Source Control panel for Coding Mode. * * Features: * • Current branch + branch switcher (dropdown) * • Changed-files list with stage/unstage checkboxes * • Per-file diff viewer (unified diff text) * • Commit message input + Commit button * • Recent commits log */ import { useCallback, useEffect, useRef, useState } from "react"; import { Button, Input, message, Modal, Popconfirm, Select, Tabs, Tag, Tooltip, } from "antd"; import { GitBranch, GitCommit, GitMerge, RefreshCw, Plus, Minus, FileDiff, RotateCcw, Undo2, } from "lucide-react"; import { gitApi } from "../../api/modules/git"; import type { GitStatus, BranchInfo, CommitInfo, GitChangedFile, } from "../../api/modules/git"; import styles from "./GitPanel.module.less"; const STATUS_LABELS: Record = { M: { label: "M", color: "#f0ad4e" }, A: { label: "A", color: "#5cb85c" }, D: { label: "D", color: "#d9534f" }, R: { label: "R", color: "#5bc0de" }, "?": { label: "U", color: "#aaa" }, }; function StatusBadge({ status }: { status: string }) { const info = STATUS_LABELS[status] ?? { label: status, color: "#aaa" }; return ( {info.label} ); } // --------------------------------------------------------------------------- export default function GitPanel({ chatId }: { chatId?: string }) { const [loading, setLoading] = useState(false); const [status, setStatus] = useState(null); const [branches, setBranches] = useState([]); const [log, setLog] = useState([]); const [commitMsg, setCommitMsg] = useState(""); const [committing, setCommitting] = useState(false); const [diffFile, setDiffFile] = useState<{ path: string; staged: boolean; diff: string; title?: string; } | null>(null); const [newBranchModal, setNewBranchModal] = useState(false); const [newBranchName, setNewBranchName] = useState(""); const [msgApi, contextHolder] = message.useMessage(); const pollingRef = useRef | null>(null); /** Show full list when > FILE_LIMIT items */ const [showAllUnstaged, setShowAllUnstaged] = useState(false); const [showAllStaged, setShowAllStaged] = useState(false); const FILE_LIMIT = 50; const refresh = useCallback(async () => { try { const [s, b] = await Promise.all([ gitApi.status(chatId), gitApi.branches(chatId), ]); setStatus(s); setBranches(b); } catch { // Not a git repo or git not available – silently hide setStatus(null); } }, [chatId]); const refreshLog = useCallback(async () => { try { setLog(await gitApi.log(50, chatId)); } catch { setLog([]); } }, [chatId]); // Re-fetch when the active chat changes because it may override project_dir. useEffect(() => { setStatus(null); setLog([]); void refresh(); void refreshLog(); }, [chatId, refresh, refreshLog]); useEffect(() => { // Poll every 10 s — reduced from 5 s to cut API load pollingRef.current = setInterval(() => void refresh(), 10000); return () => { if (pollingRef.current) clearInterval(pollingRef.current); }; }, [refresh]); // ---- Branch actions ------------------------------------------------------- const handleCheckout = useCallback( async (branch: string) => { try { await gitApi.checkout(branch, false, chatId); await refresh(); void msgApi.success(`Switched to ${branch}`); } catch (e: unknown) { void msgApi.error(String(e)); } }, [chatId, refresh, msgApi], ); const handleCreateBranch = useCallback(async () => { if (!newBranchName.trim()) return; try { await gitApi.checkout(newBranchName.trim(), true, chatId); setNewBranchModal(false); setNewBranchName(""); await refresh(); void msgApi.success(`Created & switched to ${newBranchName.trim()}`); } catch (e: unknown) { void msgApi.error(String(e)); } }, [chatId, newBranchName, refresh, msgApi]); // ---- Stage / unstage ------------------------------------------------------ const handleStage = useCallback( async (file: GitChangedFile) => { await gitApi.stage([file.path], chatId); await refresh(); }, [chatId, refresh], ); const handleUnstage = useCallback( async (file: GitChangedFile) => { await gitApi.unstage([file.path], chatId); await refresh(); }, [chatId, refresh], ); const handleStageAll = useCallback(async () => { await gitApi.stage([], chatId); await refresh(); }, [chatId, refresh]); // ---- Discard -------------------------------------------------------------- const handleDiscard = useCallback( async (file: GitChangedFile) => { try { await gitApi.discard([file.path], chatId); await refresh(); void msgApi.success(`Discarded changes in ${file.path}`); } catch (e: unknown) { void msgApi.error(String(e)); } }, [chatId, refresh, msgApi], ); // ---- Diff ----------------------------------------------------------------- const handleShowDiff = useCallback( async (file: GitChangedFile) => { try { const isUntracked = file.status === "?"; const res = await gitApi.diff( file.path, file.staged, isUntracked, chatId, ); setDiffFile({ path: file.path, staged: file.staged, diff: res.diff, title: `${file.path}${file.staged ? " (staged)" : ""}`, }); } catch { // ignore } }, [chatId], ); const handleShowCommitDiff = useCallback( async (commit: CommitInfo) => { try { const res = await gitApi.commitDiff(commit.hash, chatId); setDiffFile({ path: commit.hash, staged: false, diff: res.diff, title: `${commit.hash} · ${commit.message}`, }); } catch { // ignore } }, [chatId], ); // ---- Revert --------------------------------------------------------------- const handleRevert = useCallback( async (commit: CommitInfo) => { try { await gitApi.revert(commit.hash, chatId); await refresh(); await refreshLog(); void msgApi.success(`Reverted commit ${commit.hash}`); } catch (e: unknown) { void msgApi.error(String(e)); } }, [chatId, refresh, refreshLog, msgApi], ); // ---- Commit --------------------------------------------------------------- const handleCommit = useCallback(async () => { if (!commitMsg.trim()) { void msgApi.warning("Please enter a commit message"); return; } const hasStaged = status?.changes.some((f) => f.staged); if (!hasStaged) { void msgApi.warning("No staged files. Stage changes before committing."); return; } setCommitting(true); try { await gitApi.commit(commitMsg.trim(), chatId); setCommitMsg(""); await refresh(); await refreshLog(); void msgApi.success("Committed successfully"); } catch (e: unknown) { const raw = e instanceof Error ? e.message : String(e); if (raw.includes("nothing to commit")) { void msgApi.warning("Nothing to commit"); } else if (raw.includes("nothing added to commit")) { void msgApi.warning( "No staged files. Stage changes before committing.", ); } else { void msgApi.error(raw); } } finally { setCommitting(false); } }, [chatId, commitMsg, status, refresh, refreshLog, msgApi]); // ---- Render --------------------------------------------------------------- if (status === null) return null; // not a git repo const staged = status.changes.filter((f) => f.staged); const unstaged = status.changes.filter((f) => !f.staged); const localBranches = branches.filter((b) => !b.remote); const visibleStaged = showAllStaged ? staged : staged.slice(0, FILE_LIMIT); const visibleUnstaged = showAllUnstaged ? unstaged : unstaged.slice(0, FILE_LIMIT); return (
{contextHolder} {/* Branch bar */}
setNewBranchName(e.target.value)} onPressEnter={handleCreateBranch} autoFocus />
); } // --------------------------------------------------------------------------- // File row // --------------------------------------------------------------------------- interface FileRowProps { file: GitChangedFile; onStage: () => void; onDiff: () => void; onDiscard?: () => void; actionIcon: React.ReactNode; actionTip: string; } function FileRow({ file, onStage, onDiff, onDiscard, actionIcon, actionTip, }: FileRowProps) { const name = file.path.split("/").pop() ?? file.path; return (
{name}
{onDiscard && ( )}
); } // --------------------------------------------------------------------------- // Unified diff viewer // --------------------------------------------------------------------------- function UnifiedDiffView({ diff }: { diff: string }) { if (!diff.trim()) { return
No diff available.
; } const lines = diff.split("\n"); return (
      {lines.map((line, i) => {
        let cls = styles.diffCtx;
        if (line.startsWith("+++") || line.startsWith("---")) {
          cls = styles.diffMeta;
        } else if (line.startsWith("@@")) {
          cls = styles.diffHunk;
        } else if (line.startsWith("+")) {
          cls = styles.diffAdd;
        } else if (line.startsWith("-")) {
          cls = styles.diffDel;
        } else if (line.startsWith("diff ") || line.startsWith("index ")) {
          cls = styles.diffMeta;
        }
        return (
          
{line || " "}
); })}
); }