Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router';
import { GitBranch, Plus, Minus, FileText, RefreshCw, Download, Rocket, Upload, ArrowUpDown, Check, Trash2, GitMerge, Globe, RotateCcw, Terminal, Loader2 } from 'lucide-react';
import toast from '../../ui/Toast';
import Modal from '../../ui/Modal';
import BrailleSpinner from '../../BrailleSpinner';
import ListLoadError from '../../ui/ListLoadError';
import * as api from '../../../services/api';
import { formatDateNumeric } from '../../../utils/formatters';
import RepositorySourcePanel from './RepositorySourcePanel';
function buildReleasePrompt({ repoPath, appName, comparison, baseBranch, devBranch, hasChangelog }) {
const commitList = comparison.commits
.map(c => `- ${c.hash} ${c.message}`)
.join('\n');
const changelogStep = hasChangelog ? `
2. **Changelog management**:
- Read version from package.json to determine the minor version series (e.g., 0.12.x)
- Check if \`.changelog/v{major}.{minor}.x.md\` exists
- If not, create it using the structure from an existing changelog file as template
- Update it with entries for the commits being released, categorized by type (Features, Fixes, Improvements)
- Keep the version as literal "x" — the release workflow substitutes the actual version
- Commit the changelog: \`git add .changelog/ && git commit -m "docs: update changelog for release"\`
- Push: \`git pull --rebase --autostash && git push\`
` : '';
const prStep = hasChangelog ? 3 : 2;
const reviewStep = prStep + 1;
const feedbackStep = reviewStep + 1;
const reRequestStep = feedbackStep + 1;
const iterateStep = reRequestStep + 1;
const ciStep = iterateStep + 1;
const mergeStep = ciStep + 1;
return `You are performing a release workflow for ${appName}. The repo is at: ${repoPath}
## Commits to release (${comparison.ahead} commits ahead of ${baseBranch}):
${commitList}
## Steps
1. **Ensure clean state**:
- Check for uncommitted changes. If any, stage, commit with a descriptive message, then run \`git pull --rebase --autostash && git push\`
- If no uncommitted changes, still run \`git pull --rebase --autostash && git push\` to ensure we're up to date
${changelogStep}
${prStep}. **Create PR**:
- Check for existing PR: \`gh pr list --base ${baseBranch} --head ${devBranch} --state open\`
- If no existing PR, create one: \`gh pr create --base ${baseBranch} --head ${devBranch} --title "Release vX.Y.Z" --body "Release notes..."\`
- Include a summary of changes in the PR body
${reviewStep}. **Wait for Copilot review**:
- Poll \`gh pr view --json reviews\` every 30 seconds
- Timeout after 2 minutes if no review appears
${feedbackStep}. **Address review feedback** (if any):
- Fetch unresolved threads via GraphQL:
\`\`\`
gh api graphql -f query='query($owner: String!, $repo: String!, $pr: Int!) { repository(owner: $owner, name: $repo) { pullRequest(number: $pr) { reviewThreads(first: 100) { nodes { id isResolved comments(first: 10) { nodes { body path line author { login } } } } } } } }'
\`\`\`
- Make requested changes, commit, push (\`git pull --rebase --autostash && git push\`)
- Resolve addressed threads via GraphQL mutation
${reRequestStep}. **Re-request review**:
- Get repo info: \`gh repo view --json owner,name\`
- Get PR number from \`gh pr view --json number\`
- Try API: \`gh api repos/{owner}/{repo}/pulls/{pr}/requested_reviewers -f '{"reviewers":["copilot-pull-request-reviewer"]}' --method POST\`
- If that fails, use browser MCP to navigate to the PR page and click the re-request review button (the sync icon button with \`name="re_request_reviewer_id"\`)
${iterateStep}. **Iterate**: Repeat steps ${reviewStep}-${reRequestStep} up to 3 times max
${ciStep}. **Verify CI**: Run \`gh pr checks\` and fix any failures
${mergeStep}. **Merge**: Once approved and CI passes, merge with \`gh pr merge --merge\`
## Important rules:
- Always \`git pull --rebase --autostash\` before pushing
- No co-author info in commits${hasChangelog ? '\n- Keep changelog version as literal "x" (the release workflow substitutes the actual version number)' : ''}
- Max 3 review iterations to prevent infinite loops
- Report clearly if something fails
- Parse repo owner/name from \`gh repo view --json owner,name\``;
}
const iconBtnCls = 'p-1.5 min-h-[40px] min-w-[40px] flex items-center justify-center';
const touchBtnCls = 'min-h-[40px]';
/**
* The confirm-dialog chrome this tab uses for its consequential actions — the
* release PR and the reset-to-origin. Extracted at the third copy of the same
* `Modal` props + header/body/footer markup, because the parts that drift when
* it is pasted again are the accessibility ones (`aria-labelledby` wiring, the
* 44px close target) rather than anything visible.
*
* `tone` picks the confirm button's colour: 'accent' for a normal action,
* 'error' for one that destroys work.
*/
function ConfirmModal({ open, onClose, titleId, icon, title, tone = 'accent', confirmLabel, onConfirm, busy = false, children }) {
const confirmCls = tone === 'error'
? 'bg-port-error hover:bg-port-error/80'
: 'bg-port-accent hover:bg-port-accent/80';
return (
<Modal
open={open}
onClose={onClose}
size="md"
align="none"
backdropClassName="bg-black/50"
panelClassName="bg-port-card border border-port-border rounded-xl overflow-hidden"
ariaLabelledBy={titleId}
>
<div className="flex items-center justify-between p-4 border-b border-port-border">
<h3 id={titleId} className="font-medium text-white flex items-center gap-2">
{icon}
{title}
</h3>
<button onClick={onClose} aria-label="Close" className="text-gray-400 hover:text-white min-h-[44px] min-w-[44px] flex items-center justify-center">×</button>
</div>
<div className="p-4 space-y-3">{children}</div>
<div className="flex justify-end gap-3 p-4 border-t border-port-border">
<button onClick={onClose} className="px-4 py-2 text-sm text-gray-400 hover:text-white">
Cancel
</button>
<button
onClick={onConfirm}
disabled={busy}
className={`flex items-center gap-2 px-4 py-2 ${confirmCls} text-white rounded-lg text-sm disabled:opacity-50`}
>
{icon}
{confirmLabel}
</button>
</div>
</Modal>
);
}
export default function GitTab({ appId, appName, repoPath }) {
const navigate = useNavigate();
const [gitInfo, setGitInfo] = useState(null);
const [diff, setDiff] = useState('');
const [showDiff, setShowDiff] = useState(false);
const [loading, setLoading] = useState(false);
const [commitMessage, setCommitMessage] = useState('');
const [committing, setCommitting] = useState(false);
const [branchComparison, setBranchComparison] = useState(null);
const [updating, setUpdating] = useState(false);
const [releasing, setReleasing] = useState(false);
const [showReleaseConfirm, setShowReleaseConfirm] = useState(false);
const [branches, setBranches] = useState([]);
// A failed branch read is kept apart from a repo that has no branches; a
// refresh failure keeps the last good list on screen beside the error row.
const [branchesError, setBranchesError] = useState(null);
const [checkingOut, setCheckingOut] = useState(null);
const [pushing, setPushing] = useState(null);
const [syncing, setSyncing] = useState(null);
const [pushingAll, setPushingAll] = useState(false);
const [rebasingAndPushing, setRebasingAndPushing] = useState(false);
const [openingPullRequest, setOpeningPullRequest] = useState(false);
const [reconciling, setReconciling] = useState(false);
const [remoteBranches, setRemoteBranches] = useState([]);
const [_defaultBranch, setDefaultBranch] = useState('main');
const [loadingRemote, setLoadingRemote] = useState(false);
const [deleting, setDeleting] = useState(null);
const [deleteConfirm, setDeleteConfirm] = useState(null);
const [merging, setMerging] = useState(null);
const [mergeConfirm, setMergeConfirm] = useState(null);
const [checkingOutRemote, setCheckingOutRemote] = useState(null);
const [cleaningUp, setCleaningUp] = useState(false);
const [cleanupConfirm, setCleanupConfirm] = useState(false);
const [resetting, setResetting] = useState(false);
const [resetConfirm, setResetConfirm] = useState(false);
const [sourceRefreshKey, setSourceRefreshKey] = useState(0);
const loadGitData = useCallback(async (opts = {}) => {
if (!repoPath) return;
const { includeRemote = true } = opts;
setLoading(true);
if (includeRemote) setLoadingRemote(true);
const promises = [
api.getGitInfo(repoPath).catch(() => null),
api.getBranches(repoPath, { silent: true }).catch((error) => ({ error }))
];
if (includeRemote) {
promises.push(api.getRemoteBranches(repoPath).catch(() => null));
}
const [info, branchesResult, remoteResult] = await Promise.all(promises);
let comparison = null;
if (info?.baseBranch && info?.devBranch) {
comparison = await api.getBranchComparison(repoPath, info.baseBranch, info.devBranch).catch(() => null);
}
setGitInfo(info);
if (branchesResult?.error) {
setBranchesError(branchesResult.error);
} else {
setBranchesError(null);
setBranches(branchesResult?.branches || []);
}
setBranchComparison(comparison);
setLoading(false);
if (includeRemote) {
if (remoteResult) {
setRemoteBranches(remoteResult.branches || []);
setDefaultBranch(remoteResult.defaultBranch || 'main');
}
setLoadingRemote(false);
}
}, [repoPath]);
// Local git mutations (push/sync/commit) change ahead/behind counts, so the
// Repository sources card must re-fetch too.
const loadGitInfo = useCallback(async () => {
await loadGitData({ includeRemote: false });
setSourceRefreshKey((key) => key + 1);
}, [loadGitData]);
const loadRemoteBranches = useCallback(async (opts = {}) => {
if (!repoPath) return;
setLoadingRemote(true);
const result = await api.getRemoteBranches(repoPath, opts).catch(() => null);
if (result) {
setRemoteBranches(result.branches || []);
setDefaultBranch(result.defaultBranch || 'main');
}
setLoadingRemote(false);
}, [repoPath]);
useEffect(() => {
loadGitData({ includeRemote: true });
}, [loadGitData]);
const loadDiff = async () => {
if (!repoPath) return;
const result = await api.getGitDiff(repoPath).catch(() => ({ diff: '' }));
setDiff(result.diff || '');
setShowDiff(true);
};
const handleStage = async (file) => {
await api.stageFiles(repoPath, [file]);
await loadGitInfo();
};
const handleUnstage = async (file) => {
await api.unstageFiles(repoPath, [file]);
await loadGitInfo();
};
const handleCommit = async () => {
if (!commitMessage.trim()) return;
setCommitting(true);
await api.createCommit(repoPath, commitMessage).catch(() => null);
setCommitMessage('');
setCommitting(false);
await loadGitInfo();
};
const handleUpdateBranches = async () => {
if (!repoPath) return;
setUpdating(true);
const result = await api.updateBranches(repoPath).catch(() => null);
setUpdating(false);
if (result) {
const parts = [];
for (const [key, val] of Object.entries(result)) {
if (key !== 'currentBranch' && val) {
parts.push(`${key}: ${val}`);
}
}
toast.success(`Branches updated — ${parts.join(', ')}`);
}
await loadGitData({ includeRemote: true });
setSourceRefreshKey((key) => key + 1);
};
const handleOpenTerminal = () => {
if (!repoPath) return;
navigate(`/shell?cwd=${encodeURIComponent(repoPath)}`);
};
const handleReleasePR = async () => {
if (!branchComparison || branchComparison.ahead === 0) return;
setShowReleaseConfirm(false);
setReleasing(true);
const prompt = buildReleasePrompt({
repoPath,
appName,
comparison: branchComparison,
baseBranch: gitInfo?.baseBranch || 'main',
devBranch: gitInfo?.devBranch || 'dev',
hasChangelog: gitInfo?.hasChangelog || false
});
const result = await api.addCosTask({
description: prompt,
context: `Release PR for ${appName}`,
priority: 'high',
autoApprove: true
}).catch(() => null);
setReleasing(false);
if (result) {
toast.success(`Release task queued for ${appName} — check CoS Agents tab`);
await api.forceCosEvaluate().catch(() => null);
}
};
const handleCheckout = async (branchName) => {
if (!repoPath || checkingOut) return;
setCheckingOut(branchName);
const result = await api.checkoutBranch(repoPath, branchName).catch(() => null);
setCheckingOut(null);
if (result?.success) {
toast.success(`Switched to ${branchName}`);
await loadGitInfo();
}
};
const handlePush = async (branchName) => {
if (!repoPath || pushing) return;
setPushing(branchName);
const result = await api.pushBranch(repoPath, branchName).catch(() => null);
setPushing(null);
if (result?.success) {
toast.success(`Pushed ${branchName}`);
await loadGitInfo();
}
};
const handleSync = async (branchName) => {
if (!repoPath || syncing) return;
setSyncing(branchName);
const result = await api.syncBranch(repoPath, branchName).catch(() => null);
setSyncing(null);
if (result?.success) {
toast.success(`Synced ${branchName}`);
await loadGitInfo();
} else if (result?.error) {
toast.error(`Sync failed: ${result.error}`);
}
};
const handlePushAll = async () => {
if (!repoPath || pushingAll) return;
setPushingAll(true);
const result = await api.pushAllBranches(repoPath).catch(() => null);
setPushingAll(false);
if (result?.success) {
toast.success(`Pushed ${result.pushed} branch${result.pushed === 1 ? '' : 'es'}`);
} else if (result) {
const failedNames = Object.entries(result.results || {})
.filter(([, v]) => !v.success)
.map(([name]) => name);
toast.error(`Push failed for: ${failedNames.join(', ')}`);
}
await loadGitInfo();
};
const handleRebaseAndPush = async () => {
if (!repoPath || rebasingAndPushing) return;
setRebasingAndPushing(true);
const result = await api.rebaseAndPushDefaultBranch(repoPath, { silent: true }).catch(error => {
toast.error(error.message || 'Rebase & push failed');
return null;
});
if (result?.success) toast.success(`Rebased and pushed ${result.branch}`);
else if (result?.error) toast.error(result.error);
await loadGitInfo();
setRebasingAndPushing(false);
};
const handleOpenPullRequest = async () => {
if (!appId || !repoPath || openingPullRequest) return;
setOpeningPullRequest(true);
const result = await api.createSlashdoTask('push', appId, {
prCompletion: 'review-then-merge',
overrideContext: `Work on the managed app repository at ${repoPath}. Reconcile all current work before delivery: include uncommitted changes, local commits not merged into the default branch, and commits not yet pushed. Preserve the app's existing intent, create or update a pull request against the default branch, then run the configured review process and merge it when review and CI are green. Do not discard work or push directly to the protected default branch.`,
}, { silent: true }).catch((err) => {
toast.error(`Could not queue pull request agent: ${err.message}`);
return null;
});
setOpeningPullRequest(false);
if (result) {
toast.success(`Pull request agent queued for ${appName} — check CoS Agents`);
await api.forceCosEvaluate().catch(() => null);
}
};
const handleReconcileBranches = async () => {
if (!appId || reconciling) return;
setReconciling(true);
const result = await api.triggerCosOnDemandTask('branch-reconcile', appId, { silent: true }).catch((err) => {
toast.error(`Could not queue branch reconcile: ${err.message}`);
return null;
});
setReconciling(false);
if (result) {
toast.success(`Branch reconcile queued for ${appName} — check CoS Agents`);
await api.forceCosEvaluate().catch(() => null);
}
};
const handleDeleteBranch = async (branchName, { local, remote }) => {
if (!repoPath || deleting) return;
setDeleting(branchName);
setDeleteConfirm(null);
const result = await api.deleteBranch(repoPath, branchName, { local, remote }, { silent: true }).catch((err) => {
toast.error(`Delete failed: ${err.message}`);
return null;
});
setDeleting(null);
if (result) {
const results = result.results || {};
const parts = Object.entries(results).map(([k, v]) => `${k}: ${v}`);
toast.success(`Branch ${branchName} — ${parts.join(', ')}`);
const localDeleted = local && results.local === 'deleted';
const remoteDeleted = remote && results.remote === 'deleted';
if (localDeleted) {
setBranches(prev => prev.filter(b => b.name !== branchName));
}
if (remoteDeleted) {
setRemoteBranches(prev => prev.filter(b => b.name !== branchName));
}
if (localDeleted && !remoteDeleted) {
setRemoteBranches(prev => prev.map(b =>
b.name === branchName ? { ...b, hasLocal: false } : b
));
}
if (remoteDeleted && !localDeleted) {
setBranches(prev => prev.map(b =>
b.name === branchName
? { ...b, tracking: null, ahead: 0, behind: 0, hasRemote: false }
: b
));
}
}
};
const handleMerge = async (branchName) => {
if (!repoPath || merging) return;
setMerging(branchName);
setMergeConfirm(null);
const result = await api.mergeBranch(repoPath, branchName, { silent: true }).catch((err) => {
toast.error(`Merge failed: ${err.message}`);
return null;
});
setMerging(null);
if (result?.success) {
toast.success(`Merged ${branchName} into current branch`);
await loadGitInfo();
}
};
const handleCheckoutRemote = async (branchName) => {
if (!repoPath || checkingOutRemote) return;
setCheckingOutRemote(branchName);
const result = await api.checkoutRemoteBranch(repoPath, branchName, { silent: true }).catch((err) => {
toast.error(`Checkout failed: ${err.message}`);
return null;
});
setCheckingOutRemote(null);
if (result?.success) {
toast.success(`Checked out ${branchName}`);
setRemoteBranches(prev => prev.map(b =>
b.name === branchName ? { ...b, hasLocal: true } : b
));
await loadGitInfo();
}
};
const mergedBranchCount = remoteBranches.filter(rb => rb.merged && !rb.isDefault).length;
// Keep the action visible for every merged local branch so a worktree-held
// branch does not make the cleanup affordance disappear. Cleanup now tears the
// worktree down too, so a merged branch sitting in one is an ordinary target
// rather than a permanent leftover — a worktree survives only when it still
// holds uncommitted or unmerged work, or something (a running agent, a claim,
// a lock) is still using it. The server names which, per branch, in `skipped`.
const localMergedCount = branches.filter(b => b.merged).length;
const localWorktreeMergedCount = branches.filter(b => b.merged && b.worktree).length;
const localCleanupTitle = localWorktreeMergedCount > 0
? `Deletes merged branches locally and on the remote, removing the ${localWorktreeMergedCount} worktree${localWorktreeMergedCount === 1 ? '' : 's'} holding one — unless it still has uncommitted or unmerged work, or is in use`
: 'Deletes merged branches both locally and on the remote';
const handleCleanupMerged = async () => {
if (!repoPath || cleaningUp) return;
setCleaningUp(true);
setCleanupConfirm(false);
const result = await api.cleanupMergedBranches(repoPath, { silent: true }).catch((err) => {
toast.error(`Cleanup failed: ${err.message}`);
return null;
});
setCleaningUp(false);
if (result) {
const deleted = Array.isArray(result.deleted) ? result.deleted : [];
const skipped = Array.isArray(result.skipped) ? result.skipped : [];
const count = deleted.length;
const removedWorktrees = deleted.filter(d => d.worktree === 'removed').length;
// Each entry already reads "<branch> (local: <why it survived>)" — the
// answer to "why is this branch still here?", which a bare count isn't.
const preserved = `${skipped.slice(0, 2).join('; ')}${skipped.length > 2 ? ` (+${skipped.length - 2} more)` : ''}`;
if (count === 0) {
toast(
skipped.length > 0 ? `No branches deleted — preserved ${preserved}` : 'No merged branches to clean up',
{ icon: skipped.length > 0 ? '⚠️' : 'ℹ️' }
);
} else {
const worktreeSuffix = removedWorktrees > 0
? ` and ${removedWorktrees} worktree${removedWorktrees === 1 ? '' : 's'}`
: '';
toast.success(`Cleaned up ${count} merged branch${count === 1 ? '' : 'es'}${worktreeSuffix}`);
const deletedRemotes = new Set(deleted.filter(d => d.remote === 'deleted').map(d => d.name));
setRemoteBranches(prev => prev.filter(b => !deletedRemotes.has(b.name)));
// A reap also clears the `worktree` flag on whatever survived, so re-read
// the branches instead of filtering the stale list. Only the branch list
// can have changed — no need for the full loadGitInfo fan-out.
if (removedWorktrees > 0) {
const refreshed = await api.getBranches(repoPath).catch(() => null);
if (refreshed) setBranches(refreshed.branches || []);
} else {
const deletedLocals = new Set(deleted.filter(d => d.local === 'deleted').map(d => d.name));
setBranches(prev => prev.filter(b => !deletedLocals.has(b.name)));
}
}
if (count > 0 && skipped.length > 0) {
toast(`Preserved ${preserved}`, { icon: '⚠️' });
}
}
};
// Destructive: throws away tracked edits and local commits on the default
// branch. The pre-reset sha comes back in the result and is surfaced in the
// toast, so a mistake is still recoverable with `git reset --hard <sha>`.
const handleResetToDefault = async () => {
if (!repoPath || resetting) return;
setResetting(true);
setResetConfirm(false);
const result = await api.resetToDefaultBranch(repoPath, { silent: true }).catch((err) => {
toast.error(`Reset failed: ${err.message}`);
return null;
});
setResetting(false);
if (result?.success) {
// The server's counts, not the pre-click snapshot the dialog previewed.
const from = result.previousBranch && result.previousBranch !== result.branch
? ` from ${result.previousBranch}`
: '';
toast.success(`Reset to origin/${result.branch}${from} — discarded ${result.discardedFiles} file change${result.discardedFiles === 1 ? '' : 's'}`);
if (result.clearedOperations?.length) {
toast(`Also cleared an in-progress ${result.clearedOperations.join(' and ')}`, { icon: '🧹' });
}
if (result.previousHead) {
toast(`Previous state was ${result.previousHead.slice(0, 7)} — git reset --hard ${result.previousHead.slice(0, 7)} to undo`, { icon: '↩️' });
}
if (!result.fetched) {
toast('Could not reach origin — reset to the last fetched state', { icon: '⚠️' });
}
await loadGitData({ includeRemote: true });
}
};
// Untracked files are the ones a reset KEEPS, so they must not be counted in
// what it says it will discard — the dialog claims both things two rows apart.
const dirtyCount = gitInfo?.status?.files?.filter(f => f.status !== 'untracked').length || 0;
const getStatusIcon = (file) => {
if (file.added) return <Plus size={14} className="text-port-success" />;
if (file.deleted) return <Minus size={14} className="text-port-error" />;
return <FileText size={14} className="text-port-warning" />;
};
if (!repoPath) {
return (
<div className="bg-port-card border border-port-border rounded-xl p-8 text-center text-gray-500">
No repository path configured for this app
</div>
);
}
return (
<fieldset disabled={rebasingAndPushing} className="min-w-0 space-y-6">
<RepositorySourcePanel
appId={appId}
appName={appName}
refreshKey={sourceRefreshKey}
hasLocalChanges={Boolean(gitInfo?.status?.files?.length)}
onUpdated={() => loadGitData({ includeRemote: true })}
/>
{/* Wraps rather than overflows: three actions no longer fit one phone row. */}
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="text-lg font-semibold text-white">Git Status</h2>
<div className="flex flex-wrap items-center gap-2">
<button
onClick={handleRebaseAndPush}
disabled={rebasingAndPushing || loading || updating || pushingAll || Boolean(syncing || pushing || checkingOut || merging || checkingOutRemote) || committing || resetting
|| !gitInfo?.status?.clean || gitInfo?.branch !== gitInfo?.baseBranch || !(gitInfo?.originComparison?.ahead > 0)}
title="Rebase local default-branch commits onto origin, then push; requires a clean checkout ahead of origin"
className="flex min-h-[40px] items-center gap-1.5 px-3 py-2 bg-port-card border border-port-border rounded-lg text-sm text-gray-300 hover:text-white hover:border-port-accent disabled:opacity-50"
>
{rebasingAndPushing ? <Loader2 size={16} className="animate-spin" /> : <ArrowUpDown size={16} />}
{rebasingAndPushing ? 'Rebasing & pushing...' : 'Rebase & push'}
</button>
{branches.some(b => b.tracking && b.ahead > 0) && (
<button
onClick={handlePushAll}
disabled={pushingAll}
className="flex items-center gap-1.5 px-3 py-2 bg-port-card border border-port-border rounded-lg text-sm text-gray-300 hover:text-white hover:border-port-success disabled:opacity-50"
>
{pushingAll ? <Loader2 size={16} className="animate-spin" /> : <Upload size={16} />}
{pushingAll ? 'Pushing...' : 'Push'}
</button>
)}
<button
onClick={handleOpenPullRequest}
disabled={openingPullRequest || !gitInfo?.isRepo}
title="Have an agent commit, push, review, and merge the current repository work through a pull request"
className="flex items-center gap-1.5 px-3 py-2 bg-port-accent/20 border border-port-accent/40 rounded-lg text-sm text-port-accent hover:bg-port-accent/30 disabled:opacity-50"
>
{openingPullRequest ? <Loader2 size={16} className="animate-spin" /> : <Rocket size={16} />}
{openingPullRequest ? 'Queuing PR agent...' : 'Open PR with agent'}
</button>
<button
onClick={handleUpdateBranches}
disabled={updating}
className="flex items-center gap-1.5 px-3 py-2 bg-port-card border border-port-border rounded-lg text-sm text-gray-300 hover:text-white hover:border-port-accent disabled:opacity-50"
>
{updating ? <Loader2 size={16} className="animate-spin" /> : <Download size={16} />}
{updating ? 'Fetching...' : 'Fetch branches'}
</button>
<button
onClick={handleOpenTerminal}
disabled={!repoPath}
title="Open shell terminal in this app directory"
className="flex items-center gap-1.5 px-3 py-2 bg-port-card border border-port-border rounded-lg text-sm text-gray-300 hover:text-white hover:border-port-accent disabled:opacity-50"
>
<Terminal size={16} />
Open terminal
</button>
<button
onClick={() => {
setResetConfirm(true);
// The dialog names how many files it is about to destroy, so it
// reads fresh state rather than whatever the last poll left.
loadGitInfo();
}}
disabled={resetting}
title="Discard local changes and match origin's default branch"
className="flex items-center gap-1.5 px-3 py-2 bg-port-card border border-port-border rounded-lg text-sm text-gray-300 hover:text-white hover:border-port-error disabled:opacity-50"
>
<RotateCcw size={16} className={resetting ? 'animate-spin' : ''} />
{resetting ? 'Resetting...' : 'Reset to origin'}
</button>
</div>
</div>
{loading ? (
<div className="text-center py-8"><BrailleSpinner text="Loading git info" /></div>
) : gitInfo && gitInfo.isRepo ? (
<div className="space-y-6">
{/* Branch Comparison / Release Status */}
{branchComparison && branchComparison.ahead > 0 && (
<div className="bg-port-card border border-port-border rounded-xl p-4">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-3">
<h3 className="text-sm font-medium text-gray-400">Release Status</h3>
<span className="text-xs font-medium text-port-accent px-2 py-0.5 bg-port-accent/20 rounded">
{branchComparison.ahead} ahead of {gitInfo?.baseBranch || 'main'}
</span>
</div>
<div className="flex items-center gap-3 text-xs text-gray-400">
<span className="text-port-success">+{branchComparison.stats.insertions}</span>
<span className="text-port-error">-{branchComparison.stats.deletions}</span>
<span>{branchComparison.stats.files} files</span>
</div>
</div>
<div className="space-y-1.5 max-h-48 overflow-auto mb-4">
{branchComparison.commits.map((commit, i) => (
<div key={i} className="flex items-center gap-2 text-sm">
<code className="text-xs text-port-accent shrink-0">{commit.hash}</code>
<span className="text-gray-300 truncate">{commit.message}</span>
</div>
))}
</div>
{gitInfo.devBranch && gitInfo.branch === gitInfo.devBranch && (
<button
onClick={() => setShowReleaseConfirm(true)}
disabled={releasing}
className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg text-sm disabled:opacity-50"
>
<Rocket size={16} />
{releasing ? 'Creating Release Task...' : 'Create Release PR'}
</button>
)}
</div>
)}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Status Panel */}
<div className="space-y-4">
{/* Branch Info */}
<div className="bg-port-card border border-port-border rounded-xl p-4">
<div className="flex items-center gap-2 mb-3">
<GitBranch size={18} className="text-port-accent" />
<span className="font-medium text-white">{gitInfo.branch}</span>
{gitInfo.status?.clean && (
<span className="text-xs text-port-success px-2 py-0.5 bg-port-success/20 rounded">Clean</span>
)}
</div>
<div className="flex gap-4 text-sm">
<div className="text-gray-400">
<span className="text-port-success">+{gitInfo.diffStats?.insertions || 0}</span>
<span className="mx-1">/</span>
<span className="text-port-error">-{gitInfo.diffStats?.deletions || 0}</span>
</div>
<div className="text-gray-500">
{gitInfo.diffStats?.files || 0} files changed
</div>
</div>
</div>
{/* Changed Files */}
<div className="bg-port-card border border-port-border rounded-xl p-4">
<div className="flex items-center justify-between mb-3">
<h3 className="text-sm font-medium text-gray-400">Changed Files</h3>
<button
onClick={loadDiff}
className="text-xs text-port-accent hover:underline"
>
View Diff
</button>
</div>
<div className="space-y-1 max-h-64 overflow-auto">
{gitInfo.status?.files?.map((file, i) => (
<div key={i} className="flex items-center gap-2 text-sm py-1 group">
{getStatusIcon(file)}
<span className={`flex-1 font-mono text-xs ${file.staged ? 'text-port-success' : 'text-gray-300'}`}>
{file.path}
</span>
<span className="text-xs text-gray-500">{file.status}</span>
{file.staged ? (
<button
onClick={() => handleUnstage(file.path)}
className="opacity-100 sm:opacity-0 sm:group-hover:opacity-100 focus-visible:opacity-100 text-xs text-gray-400 hover:text-white"
>
Unstage
</button>
) : (
<button
onClick={() => handleStage(file.path)}
className="opacity-100 sm:opacity-0 sm:group-hover:opacity-100 focus-visible:opacity-100 text-xs text-gray-400 hover:text-white"
>
Stage
</button>
)}
</div>
))}
{(!gitInfo.status?.files || gitInfo.status.files.length === 0) && (
<div className="text-gray-500 text-sm">No changes</div>
)}
</div>
</div>
{/* Quick Commit */}
{gitInfo.status?.staged > 0 && (
<div className="bg-port-card border border-port-border rounded-xl p-4">
<h3 className="text-sm font-medium text-gray-400 mb-2">Quick Commit</h3>
<div className="flex gap-2">
<input
type="text"
value={commitMessage}
onChange={(e) => setCommitMessage(e.target.value)}
placeholder="Commit message..."
aria-label="Commit message"
className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
/>
<button
onClick={handleCommit}
disabled={committing || !commitMessage.trim()}
className="px-4 py-2 bg-port-success hover:bg-port-success/80 text-white rounded-lg text-sm disabled:opacity-50"
>
Commit
</button>
</div>
</div>
)}
</div>
{/* Recent Commits */}
<div className="space-y-4">
<div className="bg-port-card border border-port-border rounded-xl p-4">
<h3 className="text-sm font-medium text-gray-400 mb-3">Recent Commits</h3>
<div className="space-y-2">
{gitInfo.recentCommits?.map((commit, i) => (
<div key={i} className="py-2 border-b border-port-border last:border-0">
<div className="flex items-center gap-2">
<code className="text-xs text-port-accent">{commit.hash}</code>
<span className="text-sm text-white truncate">{commit.message}</span>
</div>
<div className="text-xs text-gray-500 mt-1">
{commit.author} • {formatDateNumeric(commit.date)}
</div>
</div>
))}
{(!gitInfo.recentCommits || gitInfo.recentCommits.length === 0) && (
<div className="text-gray-500 text-sm">No commits</div>
)}
</div>
</div>
{/* Local Branches */}
<div className="bg-port-card border border-port-border rounded-xl p-4">
<div className="flex flex-wrap items-center justify-between gap-2 mb-3">
<h3 className="text-sm font-medium text-gray-400">Local Branches</h3>
<div className="flex flex-wrap items-center gap-2">
{appId && (
<button
onClick={handleReconcileBranches}
disabled={reconciling}
title="Queue a branch-reconcile agent to merge, push, or retire this app's leftover branches"
className={`flex items-center gap-1 text-xs ${touchBtnCls} text-port-accent hover:text-white disabled:opacity-50`}
>
<GitMerge size={12} />
{reconciling ? 'Queuing...' : 'Reconcile'}
</button>
)}
{localMergedCount > 0 && !cleanupConfirm && (
<button
onClick={() => setCleanupConfirm('local')}
disabled={cleaningUp}
title={localCleanupTitle}
className={`flex items-center gap-1 text-xs ${touchBtnCls} text-port-warning hover:text-port-error disabled:opacity-50`}
>
<Trash2 size={12} />
{cleaningUp ? 'Cleaning...' : `Clean ${localMergedCount} merged`}
</button>
)}
{localWorktreeMergedCount > 0 && !cleanupConfirm && (
<span className="text-xs text-gray-500" role="status">
{localWorktreeMergedCount} worktree{localWorktreeMergedCount === 1 ? '' : 's'} removed too, except any still in use or holding uncommitted work
</span>
)}
{cleanupConfirm === 'local' && (
<div className="flex flex-wrap items-center gap-1">
<button
onClick={handleCleanupMerged}
disabled={cleaningUp}
title={localCleanupTitle}
className={`px-2 py-1 ${touchBtnCls} text-xs bg-port-error/20 text-port-error rounded hover:bg-port-error/30 disabled:opacity-50`}
>
{cleaningUp
? 'Deleting...'
: localWorktreeMergedCount > 0
? 'Delete all merged (local + remote + worktrees)'
: 'Delete all merged (local + remote)'}
</button>
<button
onClick={() => setCleanupConfirm(false)}
className={`px-2 py-1 ${touchBtnCls} text-xs text-gray-400 hover:text-white`}
>
Cancel
</button>
</div>
)}
</div>
</div>
<div className="space-y-2 max-h-64 overflow-auto">
{branches.map((branch) => (
<div
key={branch.name}
className={`flex flex-wrap items-center justify-between gap-y-1 py-2 px-2 rounded-lg ${branch.current ? 'bg-port-accent/10 border border-port-accent/30' : 'hover:bg-port-bg'}`}
>
<div className="flex items-center gap-2 min-w-0 flex-1">
{branch.current ? (
<Check size={14} className="text-port-accent shrink-0" />
) : (
<GitBranch size={14} className="text-gray-500 shrink-0" />
)}
<span className={`text-sm truncate ${branch.current ? 'text-port-accent font-medium' : 'text-gray-300'}`}>
{branch.name}
</span>
{branch.merged && (
<span className="flex items-center gap-1 text-xs text-port-success px-1.5 py-0.5 bg-port-success/10 rounded shrink-0">
<GitMerge size={10} />
merged
</span>
)}
{branch.worktree && (
<span
className="flex items-center gap-1 text-xs text-gray-400 px-1.5 py-0.5 bg-gray-500/10 rounded shrink-0"
title="Checked out in a worktree — can't be deleted until the worktree is removed"
>
<GitBranch size={10} />
worktree
</span>
)}
{branch.tracking && (
<span className="text-xs text-gray-500 shrink-0">
{branch.ahead > 0 && <span className="text-port-success">+{branch.ahead}</span>}
{branch.ahead > 0 && branch.behind > 0 && ' / '}
{branch.behind > 0 && <span className="text-port-warning">-{branch.behind}</span>}
</span>
)}
</div>
<div className="flex items-center gap-1 shrink-0">
{!branch.current && (
<button
onClick={() => handleCheckout(branch.name)}
disabled={checkingOut === branch.name}
className={`${iconBtnCls} text-gray-400 hover:text-white hover:bg-port-bg rounded disabled:opacity-50`}
title="Checkout"
>
{checkingOut === branch.name ? (
<RefreshCw size={14} className="animate-spin" />
) : (
<Check size={14} />
)}
</button>
)}
{branch.tracking && branch.ahead > 0 && (
<button
onClick={() => handlePush(branch.name)}
disabled={pushing === branch.name}
className={`${iconBtnCls} text-gray-400 hover:text-port-success hover:bg-port-bg rounded disabled:opacity-50`}
title="Push"
>
{pushing === branch.name ? (
<RefreshCw size={14} className="animate-spin" />
) : (
<Upload size={14} />
)}
</button>
)}
{branch.tracking && (
<button
onClick={() => handleSync(branch.name)}
disabled={syncing === branch.name}
className={`${iconBtnCls} text-gray-400 hover:text-port-accent hover:bg-port-bg rounded disabled:opacity-50`}
title="Sync (pull & push)"
>
{syncing === branch.name ? (
<RefreshCw size={14} className="animate-spin" />
) : (
<ArrowUpDown size={14} />
)}
</button>
)}
{!branch.current && (
mergeConfirm === branch.name ? (
<div className="flex flex-wrap items-center gap-1">
<button
onClick={() => handleMerge(branch.name)}
disabled={merging === branch.name}
className={`px-2 py-1 ${touchBtnCls} text-xs bg-port-accent/20 text-port-accent rounded hover:bg-port-accent/30 disabled:opacity-50 inline-flex items-center gap-1`}
>
{merging === branch.name ? <Loader2 size={12} className="animate-spin" /> : null}
{merging === branch.name ? 'Merging...' : 'Confirm'}
</button>
<button
onClick={() => setMergeConfirm(null)}
className={`px-2 py-1 ${touchBtnCls} text-xs text-gray-400 hover:text-white`}
>
Cancel
</button>
</div>
) : (
<button
onClick={() => setMergeConfirm(branch.name)}
className={`${iconBtnCls} text-gray-400 hover:text-port-accent hover:bg-port-bg rounded`}
title={`Merge ${branch.name} into current branch`} aria-label={`Merge ${branch.name} into current branch`}
>
<GitMerge size={14} />
</button>
)
)}
</div>
</div>
))}
{branchesError && (
<ListLoadError what="branches" error={branchesError} onRetry={() => loadGitData({ includeRemote: false })} retrying={loading} />
)}
{!branchesError && branches.length === 0 && (
<div className="text-gray-500 text-sm">No branches found</div>
)}
</div>
</div>
</div>
</div>
{/* Remote Branches */}
<div className="bg-port-card border border-port-border rounded-xl p-4">
<div className="flex flex-wrap items-center justify-between gap-2 mb-3">
<div className="flex items-center gap-2">
<Globe size={16} className="text-gray-400" />
<h3 className="text-sm font-medium text-gray-400">Remote Branches</h3>
{remoteBranches.length > 0 && (
<span className="text-xs text-gray-500">({remoteBranches.length})</span>
)}
</div>
<div className="flex flex-wrap items-center gap-2">
{mergedBranchCount > 0 && !cleanupConfirm && (
<button
onClick={() => setCleanupConfirm('remote')}
disabled={cleaningUp}
className={`flex items-center gap-1 text-xs ${touchBtnCls} text-port-warning hover:text-port-error disabled:opacity-50`}
>
<Trash2 size={12} />
{cleaningUp ? 'Cleaning...' : `Clean ${mergedBranchCount} merged`}
</button>
)}
{cleanupConfirm === 'remote' && (
<div className="flex flex-wrap items-center gap-1">
<button
onClick={handleCleanupMerged}
disabled={cleaningUp}
title="Deletes merged branches both locally and on the remote"
className={`px-2 py-1 ${touchBtnCls} text-xs bg-port-error/20 text-port-error rounded hover:bg-port-error/30 disabled:opacity-50`}
>
{cleaningUp ? 'Deleting...' : 'Delete all merged (local + remote)'}
</button>
<button
onClick={() => setCleanupConfirm(false)}
className={`px-2 py-1 ${touchBtnCls} text-xs text-gray-400 hover:text-white`}
>
Cancel
</button>
</div>
)}
<button
onClick={() => loadRemoteBranches({ force: true })}
disabled={loadingRemote}
className={`text-xs ${touchBtnCls} text-port-accent hover:underline disabled:opacity-50`}
>
{loadingRemote ? 'Refreshing...' : 'Refresh'}
</button>
</div>
</div>
{loadingRemote && remoteBranches.length === 0 ? (
<div className="text-center py-4"><BrailleSpinner text="Loading remote branches" /></div>
) : (
<div className="space-y-1.5 max-h-80 overflow-auto">
{remoteBranches.map((rb) => (
<div
key={rb.fullRef}
className={`py-2 px-2 rounded-lg hover:bg-port-bg ${rb.isDefault ? 'bg-port-accent/5' : ''}`}
>
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2 min-w-0 flex-1">
<GitBranch size={14} className={rb.isDefault ? 'text-port-accent shrink-0' : 'text-gray-500 shrink-0'} />
<span className={`text-sm truncate ${rb.isDefault ? 'text-port-accent font-medium' : 'text-gray-300'}`}>
{rb.name}
</span>
{rb.merged && !rb.isDefault && (
<span className="flex items-center gap-1 text-xs text-port-success px-1.5 py-0.5 bg-port-success/10 rounded shrink-0">
<GitMerge size={10} />
merged
</span>
)}
{rb.hasLocal && (
<span className="text-xs text-gray-500 shrink-0">local</span>
)}
</div>
<div className="flex items-center gap-2 shrink-0">
{rb.lastCommitDate && (
<span className="text-xs text-gray-500 hidden sm:inline">
{formatDateNumeric(rb.lastCommitDate)}
</span>
)}
{!rb.hasLocal && (
<button
onClick={() => handleCheckoutRemote(rb.name)}
disabled={checkingOutRemote === rb.name}
className={`${iconBtnCls} text-gray-400 hover:text-port-success hover:bg-port-bg rounded disabled:opacity-50`}
title="Checkout locally"
>
{checkingOutRemote === rb.name ? (
<RefreshCw size={14} className="animate-spin" />
) : (
<Download size={14} />
)}
</button>
)}
{!rb.isDefault && deleteConfirm !== rb.name && (
<button
onClick={() => setDeleteConfirm(rb.name)}
className={`${iconBtnCls} text-gray-500 hover:text-port-error hover:bg-port-bg rounded`}
title="Delete branch" aria-label="Delete branch"
>
<Trash2 size={14} />
</button>
)}
</div>
</div>
{!rb.isDefault && deleteConfirm === rb.name && (
<div className="flex flex-wrap items-center gap-1 mt-2 pl-6">
<button
onClick={() => handleDeleteBranch(rb.name, { local: rb.hasLocal, remote: true })}
disabled={deleting === rb.name}
className={`px-2 py-1 ${touchBtnCls} text-xs bg-port-error/20 text-port-error rounded hover:bg-port-error/30 disabled:opacity-50`}
>
{deleting === rb.name ? 'Deleting...' : rb.hasLocal ? 'Delete both' : 'Delete remote'}
</button>
{rb.hasLocal && (
<button
onClick={() => handleDeleteBranch(rb.name, { local: false, remote: true })}
disabled={deleting === rb.name}
className={`px-2 py-1 ${touchBtnCls} text-xs bg-port-warning/20 text-port-warning rounded hover:bg-port-warning/30 disabled:opacity-50`}
>
Remote only
</button>
)}
<button
onClick={() => setDeleteConfirm(null)}
className={`px-2 py-1 ${touchBtnCls} text-xs text-gray-400 hover:text-white`}
>
Cancel
</button>
</div>
)}
</div>
))}
{remoteBranches.length === 0 && !loadingRemote && (
<div className="text-gray-500 text-sm">No remote branches found</div>
)}
</div>
)}
</div>
</div>
) : (
<div className="bg-port-card border border-port-border rounded-xl p-8 text-center text-gray-500">
{gitInfo ? 'Not a git repository' : 'Unable to load git status'}
</div>
)}
{/* Diff Modal */}
<Modal
open={showDiff}
onClose={() => setShowDiff(false)}
size="none"
align="none"
backdropClassName="bg-black/50"
panelClassName="bg-port-card border border-port-border rounded-xl w-3/4 overflow-hidden"
ariaLabelledBy="git-diff-modal-title"
>
<div className="flex items-center justify-between p-4 border-b border-port-border">
<h3 id="git-diff-modal-title" className="font-medium text-white">Git Diff</h3>
<button onClick={() => setShowDiff(false)} aria-label="Close" className="text-gray-400 hover:text-white min-h-[44px] min-w-[44px] flex items-center justify-center">×</button>
</div>
<pre className="p-4 overflow-auto max-h-[70vh] text-sm font-mono">
{diff.split('\n').map((line, i) => {
let color = 'text-gray-300';
if (line.startsWith('+') && !line.startsWith('+++')) color = 'text-port-success';
if (line.startsWith('-') && !line.startsWith('---')) color = 'text-port-error';
if (line.startsWith('@@')) color = 'text-port-accent';
return <div key={i} className={color}>{line}</div>;
})}
{!diff && <span className="text-gray-500">No changes to display</span>}
</pre>
</Modal>
<ConfirmModal
open={showReleaseConfirm}
onClose={() => setShowReleaseConfirm(false)}
titleId="git-release-modal-title"
icon={<Rocket size={18} className="text-port-accent" />}
title={`Create Release PR for ${appName}`}
confirmLabel="Start Release"
onConfirm={handleReleasePR}
>
<p className="text-sm text-gray-300">
This will create a CoS agent task to automate the full release workflow:
</p>
<ul className="text-sm text-gray-400 space-y-1.5 ml-4 list-disc">
<li>Push local commits to origin/{gitInfo?.devBranch || 'dev'}</li>
{gitInfo?.hasChangelog && <li>Check and update the changelog</li>}
<li>Create PR from {gitInfo?.devBranch || 'dev'} to {gitInfo?.baseBranch || 'main'}</li>
<li>Wait for Copilot review and address feedback</li>
<li>Merge when approved and CI passes</li>
</ul>
<p className="text-xs text-gray-500">
{branchComparison?.ahead || 0} commits will be included in this release.
</p>
</ConfirmModal>
{/* Destructive, so it spells out what goes and what survives rather than
asking "are you sure?". */}
<ConfirmModal
open={resetConfirm}
onClose={() => setResetConfirm(false)}
titleId="git-reset-modal-title"
icon={<RotateCcw size={18} className="text-port-error" />}
title={`Reset ${appName} to origin/${gitInfo?.baseBranch || 'main'}`}
tone="error"
confirmLabel={resetting ? 'Resetting...' : 'Discard and reset'}
onConfirm={handleResetToDefault}
busy={resetting}
>
<p className="text-sm text-gray-300">
Fetches origin, switches to the default branch, and hard-resets it to the remote.
</p>
<ul className="text-sm text-gray-400 space-y-1.5 ml-4 list-disc">
<li>Discards {dirtyCount} uncommitted file change{dirtyCount === 1 ? '' : 's'}</li>
<li>Discards any local commits on {gitInfo?.baseBranch || 'main'} that origin does not have</li>
<li>Keeps untracked files and every other local branch</li>
</ul>
<p className="text-xs text-gray-500">
The commit you are on now is reported after the reset, so <code>git reset --hard <sha></code> can undo this.
</p>
</ConfirmModal>
</fieldset>
);
}