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, useMemo } from 'react';
import { Link } from 'react-router';
import toast from '../ui/Toast';
import {
getGitHubRepos,
getGitHubStatus,
syncGitHubRepos,
updateGitHubRepo,
getGitHubSecrets,
setGitHubSecret,
syncGitHubSecret,
archiveGitHubRepo,
unarchiveGitHubRepo
} from '../../services/api';
import { timeAgo } from '../../utils/formatters';
import PageSkeleton from '../ui/PageSkeleton';
import Modal from '../ui/Modal';
import { FormField } from '../ui/FormField';
import LoadFailedState from '../ui/LoadFailedState';
const FILTERS = ['all', 'npm', 'secrets', 'archived'];
const GITHUB_LOGIN_COMMAND = 'gh auth login --hostname github.com --web --clipboard';
const GITHUB_SWITCH_COMMAND = 'gh auth switch --hostname github.com';
const UNAVAILABLE_AUTH_STATUS = Object.freeze({
authenticated: false,
status: 'unavailable',
login: null,
remedy: 'PortOS could not check GitHub authentication. Retry before syncing or changing repositories.',
githubUser: null,
});
export default function GitHubReposTab() {
const [repos, setRepos] = useState({});
const [secrets, setSecrets] = useState({});
const [loading, setLoading] = useState(true);
const [reposFailed, setReposFailed] = useState(false);
const [syncing, setSyncing] = useState(false);
const [lastSync, setLastSync] = useState(null);
const [repoListTruncated, setRepoListTruncated] = useState(false);
const [authStatus, setAuthStatus] = useState(null);
const [search, setSearch] = useState('');
const [filter, setFilter] = useState('all');
const [sort, setSort] = useState('recent'); // 'recent' | 'alpha'
const [syncingSecret, setSyncingSecret] = useState(null);
// Add secret form
const [newSecretName, setNewSecretName] = useState('');
const [newSecretValue, setNewSecretValue] = useState('');
const [savingSecret, setSavingSecret] = useState(false);
const [archiveConfirm, setArchiveConfirm] = useState(null); // { fullName, action: 'archive'|'unarchive' }
const [archiving, setArchiving] = useState(null);
useEffect(() => {
loadData();
}, []);
const loadData = async () => {
setLoading(true);
const [reposResult, secretsResult, statusResult] = await Promise.allSettled([
getGitHubRepos({ silent: true }),
getGitHubSecrets({ silent: true }),
getGitHubStatus({ silent: true })
]);
setReposFailed(reposResult.status === 'rejected');
if (reposResult.status === 'fulfilled') setRepos(reposResult.value || {});
if (secretsResult.status === 'fulfilled') setSecrets(secretsResult.value || {});
const statusData = statusResult.status === 'fulfilled' ? statusResult.value : UNAVAILABLE_AUTH_STATUS;
setAuthStatus(statusData);
setLastSync(statusData?.lastRepoSync || null);
setRepoListTruncated(statusData?.lastRepoSyncTruncated === true);
setLoading(false);
};
const handleSync = async () => {
setSyncing(true);
const result = await syncGitHubRepos({ silent: true }).catch((err) => {
toast.error(`Sync failed: ${err.message}`);
return null;
});
if (result) {
setRepos(result.repos || {});
setLastSync(result.lastRepoSync);
setRepoListTruncated(result.truncated === true);
if (result.truncated) {
toast.warning('GitHub returned its repository listing limit. Some repositories may be missing; cached entries were preserved.');
} else {
toast.success(`Synced ${Object.keys(result.repos || {}).length} repos`);
}
}
// Re-derive auth status from the server regardless of outcome — a sync
// is the freshest signal about which account is actually authenticated.
// Patching only `githubUser` in place left `login` stale (inverting the
// account-mismatch banner after a legitimate account switch), and a
// failed sync's 401/409 was otherwise dropped, leaving a stale
// `authenticated: true` state that kept every mutating control enabled.
const statusData = await getGitHubStatus({ silent: true }).catch(() => null);
if (statusData) setAuthStatus(statusData);
setSyncing(false);
};
const handleToggleNpm = async (fullName, currentValue) => {
const updated = await updateGitHubRepo(fullName, {
flags: { npmProject: !currentValue }
}, { silent: true }).catch((err) => {
toast.error(`Update failed: ${err.message}`);
return null;
});
if (updated) {
setRepos(prev => ({ ...prev, [fullName]: updated }));
}
};
const handleSaveSecret = async () => {
if (!newSecretName.trim() || !newSecretValue) return;
setSavingSecret(true);
const result = await setGitHubSecret(newSecretName.trim(), newSecretValue, { silent: true }).catch((err) => {
toast.error(`Failed to save secret: ${err.message}`);
return null;
});
if (result) {
toast.success(`Secret ${newSecretName} saved. Synced to ${result.synced} repos${result.failed ? `, ${result.failed} failed` : ''}`);
setNewSecretName('');
setNewSecretValue('');
// Reload secrets metadata
const secretsData = await getGitHubSecrets().catch(() => ({}));
setSecrets(secretsData || {});
}
setSavingSecret(false);
};
const handleSyncSecret = async (name) => {
setSyncingSecret(name);
const result = await syncGitHubSecret(name, { silent: true }).catch((err) => {
toast.error(`Sync failed: ${err.message}`);
return null;
});
if (result) {
toast.success(`${name} synced to ${result.synced} repos${result.failed ? `, ${result.failed} failed` : ''}`);
}
setSyncingSecret(null);
};
const handleArchiveClick = (fullName, isArchived) => {
setArchiveConfirm({ fullName, action: isArchived ? 'unarchive' : 'archive' });
};
const handleArchiveConfirm = async () => {
const { fullName, action } = archiveConfirm;
setArchiveConfirm(null);
setArchiving(fullName);
const fn = action === 'archive' ? archiveGitHubRepo : unarchiveGitHubRepo;
const updated = await fn(fullName, { silent: true }).catch((err) => {
toast.error(`Failed to ${action}: ${err.message}`);
return null;
});
if (updated) {
setRepos(prev => ({ ...prev, [fullName]: updated }));
toast.success(`${action === 'archive' ? 'Archived' : 'Unarchived'} ${fullName}`);
}
setArchiving(null);
};
const repoList = useMemo(() => {
let list = Object.values(repos);
// Apply search
if (search) {
const q = search.toLowerCase();
list = list.filter(r =>
r.name.toLowerCase().includes(q) ||
r.description?.toLowerCase().includes(q)
);
}
// Apply filter
if (filter === 'npm') {
list = list.filter(r => r.flags?.npmProject);
} else if (filter === 'secrets') {
list = list.filter(r => r.managedSecrets?.length > 0);
} else if (filter === 'archived') {
list = list.filter(r => r.isArchived);
}
// Sort: active first, then by selected sort
list.sort((a, b) => {
if (a.isArchived !== b.isArchived) return a.isArchived ? 1 : -1;
if (sort === 'alpha') return a.name.localeCompare(b.name);
return new Date(b.pushedAt || 0) - new Date(a.pushedAt || 0);
});
return list;
}, [repos, search, filter, sort]);
const secretEntries = Object.entries(secrets);
const authStatusUnavailable = ['unavailable', 'unreachable', 'error'].includes(authStatus?.status);
const authStatusNotInstalled = authStatus?.status === 'not-installed';
const environmentCredential = authStatus?.credentialSource === 'env';
const cachedAccountMatches = authStatus?.authenticated === true
&& typeof authStatus.login === 'string'
&& typeof authStatus.githubUser === 'string'
&& authStatus.login.toLowerCase() === authStatus.githubUser.toLowerCase();
const authHeading = authStatusUnavailable
? 'GitHub status unavailable'
: authStatusNotInstalled
? 'GitHub CLI required'
: environmentCredential
? 'GitHub environment credential rejected'
: 'GitHub sign-in required';
if (loading) {
return <PageSkeleton label="Loading GitHub repos" titleWidthClass="w-44" showAction={false} cards={3} />;
}
return (
<div className="min-w-0">
{!authStatus?.authenticated && (
<section className="mb-6 rounded-lg border border-port-warning/30 bg-port-warning/10 p-4" aria-label="GitHub account">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h2 className="font-semibold text-white">{authHeading}</h2>
{!authStatusUnavailable && !authStatusNotInstalled && !environmentCredential && (
<p className="mt-1 text-sm text-gray-300">
Sign in through PortOS Shell, complete GitHub's browser prompt, then return here and reload.
</p>
)}
{authStatus?.remedy && (
<p className="mt-1 text-xs text-gray-500">{authStatus.remedy}</p>
)}
{authStatus?.githubUser && !cachedAccountMatches && (
<p className="mt-2 text-xs text-port-warning">
The repositories below are cached from @{authStatus.githubUser}. Sign in and sync to replace them; repository actions stay disabled.
</p>
)}
</div>
{!authStatusUnavailable && !environmentCredential && authStatus?.status !== 'not-installed' && (
<Link
to={`/shell?cmd=${encodeURIComponent(GITHUB_LOGIN_COMMAND)}`}
className="inline-flex min-h-[44px] shrink-0 items-center justify-center rounded bg-port-accent px-4 py-2 text-sm font-medium text-white hover:bg-port-accent/80 sm:min-h-0"
>
Sign in with GitHub
</Link>
)}
{authStatusUnavailable && (
<button
type="button"
onClick={loadData}
className="inline-flex min-h-[44px] shrink-0 items-center justify-center rounded bg-port-accent px-4 py-2 text-sm font-medium text-white hover:bg-port-accent/80 sm:min-h-0"
>
Retry
</button>
)}
</div>
</section>
)}
{/* Archive Confirmation Modal */}
<Modal
open={!!archiveConfirm}
onClose={() => setArchiveConfirm(null)}
size="sm"
backdropClassName="bg-black/50"
ariaLabelledBy="github-archive-title"
>
<div className="bg-gray-800 rounded-lg p-4 sm:p-6">
<h3 id="github-archive-title" className="text-lg font-bold text-white mb-4">
{archiveConfirm?.action === 'archive' ? 'Archive' : 'Unarchive'} Repository?
</h3>
<p className="text-gray-300 mb-6 text-sm break-words">
{archiveConfirm?.action === 'archive'
? `Archiving "${archiveConfirm?.fullName}" will make it read-only on GitHub.`
: `Unarchiving "${archiveConfirm?.fullName}" will restore it to active status on GitHub.`
}
</p>
<div className="flex flex-col-reverse sm:flex-row gap-2 sm:justify-end">
<button
onClick={() => setArchiveConfirm(null)}
className="w-full sm:w-auto px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded"
>
Cancel
</button>
<button
onClick={handleArchiveConfirm}
className={`w-full sm:w-auto px-4 py-2 text-white rounded ${
archiveConfirm?.action === 'archive'
? 'bg-port-warning hover:bg-port-warning/80'
: 'bg-port-success hover:bg-port-success/80'
}`}
>
{archiveConfirm?.action === 'archive' ? 'Archive' : 'Unarchive'}
</button>
</div>
</div>
</Modal>
<div className="grid grid-cols-1 @5xl/page:grid-cols-[minmax(0,1fr)_360px] gap-6 items-start">
{/* Repo List */}
<div className="bg-port-card rounded-lg border border-port-border @container/repos p-4 sm:p-6 min-w-0">
<div className="flex flex-wrap gap-3 mb-4 items-center justify-between">
<div className="flex flex-wrap items-center gap-3">
<h2 className="text-lg font-bold text-white">Repositories</h2>
{lastSync && (
<span className="text-xs text-gray-500">Last sync: {timeAgo(lastSync)}</span>
)}
</div>
<div className="flex flex-wrap items-center gap-2">
{authStatus?.authenticated && environmentCredential && (
<span className="inline-flex min-h-[36px] min-w-0 max-w-full items-center gap-2 rounded border border-port-border bg-port-bg px-3 text-xs text-gray-300">
<span className="h-2 w-2 rounded-full bg-port-success" aria-hidden="true" />
<span className="max-w-28 truncate font-mono text-white sm:max-w-40" title={`@${authStatus.login}`}>
@{authStatus.login}
</span>
<span className="hidden text-gray-500 sm:inline">via environment</span>
</span>
)}
{authStatus?.authenticated && !environmentCredential && (
<details className="relative min-w-0 max-w-full">
<summary
aria-label={`GitHub account @${authStatus.login}`}
className="inline-flex min-h-[36px] min-w-0 max-w-full cursor-pointer list-none items-center gap-2 rounded border border-port-border bg-port-bg px-3 text-xs text-gray-300 hover:text-white [&::-webkit-details-marker]:hidden"
>
<span className="h-2 w-2 rounded-full bg-port-success" aria-hidden="true" />
<span className="max-w-28 truncate font-mono text-white sm:max-w-40" title={`@${authStatus.login}`}>
@{authStatus.login}
</span>
<span aria-hidden="true">▾</span>
</summary>
<div className="absolute left-0 z-20 mt-2 w-52 rounded-lg border border-port-border bg-port-card p-1 shadow-xl sm:left-auto sm:right-0">
<Link
to={`/shell?cmd=${encodeURIComponent(GITHUB_LOGIN_COMMAND)}`}
className="flex min-h-[44px] items-center rounded px-3 py-2 text-sm text-gray-300 hover:bg-port-border/50 hover:text-white"
>
Add GitHub account
</Link>
<Link
to={`/shell?cmd=${encodeURIComponent(GITHUB_SWITCH_COMMAND)}`}
className="flex min-h-[44px] items-center rounded px-3 py-2 text-sm text-gray-300 hover:bg-port-border/50 hover:text-white"
>
Switch GitHub account
</Link>
</div>
</details>
)}
<button
onClick={handleSync}
disabled={syncing || authStatus?.authenticated !== true}
className="rounded bg-port-accent px-4 py-2 text-sm text-white hover:bg-port-accent/80 disabled:opacity-50"
>
{syncing ? 'Syncing...' : 'Sync Repos'}
</button>
</div>
</div>
{authStatus?.authenticated && environmentCredential && (
<p className="mb-4 text-xs text-gray-500">
Environment credentials override stored gh accounts. Update or remove GH_TOKEN/GITHUB_TOKEN to change accounts.
</p>
)}
{authStatus?.authenticated && authStatus?.githubUser && !cachedAccountMatches && (
<p className="mb-4 text-xs text-port-warning">
The repositories below are cached from @{authStatus.githubUser}. Their actions are disabled until you sync @{authStatus.login}.
</p>
)}
{/* Search + Filter */}
<div className="flex flex-wrap gap-2 mb-4">
<input
type="text"
aria-label="Search repositories"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search repos..."
className="min-w-0 w-full flex-auto px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
/>
<div className="flex flex-wrap gap-1">
{FILTERS.map(f => (
<button
key={f}
onClick={() => setFilter(f)}
className={`px-3 py-2 text-sm rounded capitalize ${
filter === f
? 'bg-port-accent text-white'
: 'bg-port-bg text-gray-400 hover:text-white border border-port-border'
}`}
>
{f === 'npm' ? 'NPM Projects' : f === 'secrets' ? 'Has Secrets' : f === 'archived' ? 'Archived' : 'All'}
</button>
))}
<button
onClick={() => setSort(s => s === 'recent' ? 'alpha' : 'recent')}
className="px-3 py-2 text-sm rounded bg-port-bg text-gray-400 hover:text-white border border-port-border"
title={`Sort by ${sort === 'recent' ? 'name' : 'recent activity'}`}
>
{sort === 'recent' ? 'A-Z' : 'Recent'}
</button>
</div>
</div>
{/* Repo count */}
<p className="text-xs text-gray-500 mb-3">
{repoList.length} repo{repoList.length !== 1 ? 's' : ''}
{filter !== 'all' ? ` (filtered)` : ''}
</p>
{repoListTruncated && (
<p className="mb-3 text-xs text-port-warning" role="status">
GitHub returned the 200-repository limit. This list may be incomplete; cached entries were preserved.
</p>
)}
{reposFailed ? (
<LoadFailedState title="Could not load GitHub repositories." hint="Retry the local repository read." onRetry={loadData} />
) : Object.keys(repos).length === 0 ? (
<div className="text-center py-8">
<p className="text-gray-400">No repos loaded yet.</p>
<p className="text-gray-500 text-sm mt-1">Click "Sync Repos" to fetch from GitHub.</p>
</div>
) : repoList.length === 0 ? (
<div className="text-center py-8">
<p className="text-gray-400">No repos match your filter.</p>
</div>
) : (
<div className="space-y-1">
{repoList.map(repo => (
<div
key={repo.fullName}
className={`flex flex-col @xl/repos:flex-row @xl/repos:items-center gap-2 p-3 rounded border border-port-border ${
repo.isArchived ? 'opacity-50 bg-port-bg/50' : 'bg-port-bg'
}`}
>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<a
href={`https://github.com/${repo.fullName}`}
target="_blank"
rel="noopener noreferrer"
className="text-white text-sm font-medium hover:text-port-accent truncate"
>
{repo.name}
</a>
{repo.isPrivate && (
<span className="text-xs px-1.5 py-0.5 rounded bg-purple-900/50 text-purple-400 border border-purple-800">private</span>
)}
{repo.isFork && (
<a
href={`https://github.com/${repo.forkSource}`}
target="_blank"
rel="noopener noreferrer"
className="text-xs px-1.5 py-0.5 rounded bg-cyan-900/50 text-cyan-400 border border-cyan-800 hover:bg-cyan-900/70"
title={`Forked from ${repo.forkSource}`}
>
fork: {repo.forkSource}
</a>
)}
{repo.isArchived && (
<span className="text-xs px-1.5 py-0.5 rounded bg-gray-700 text-gray-400">archived</span>
)}
{repo.flags?.npmProject && (
<span className="text-xs px-1.5 py-0.5 rounded bg-red-900/50 text-red-400 border border-red-800">npm</span>
)}
{repo.managedSecrets?.map(s => (
<span key={s} className="max-w-full [overflow-wrap:anywhere] text-xs px-1.5 py-0.5 rounded bg-port-accent/10 text-port-accent border border-port-accent/30">
{s}
</span>
))}
</div>
{repo.description && (
<p className="text-xs text-gray-500 mt-0.5 truncate">{repo.description}</p>
)}
</div>
<div className="flex flex-wrap items-center gap-3 shrink-0">
<span className="text-xs text-gray-500">{timeAgo(repo.pushedAt)}</span>
{!repo.isArchived && (
<label className="flex items-center gap-1.5 cursor-pointer">
<input
type="checkbox"
checked={!!repo.flags?.npmProject}
onChange={() => handleToggleNpm(repo.fullName, repo.flags?.npmProject)}
disabled={!cachedAccountMatches}
className="w-4 h-4 rounded border-gray-600 bg-port-bg text-port-accent focus:ring-port-accent"
/>
<span className="text-xs text-gray-400">NPM</span>
</label>
)}
<button
onClick={() => handleArchiveClick(repo.fullName, repo.isArchived)}
disabled={archiving === repo.fullName || !cachedAccountMatches}
className={`px-2 py-1 text-xs rounded ${
repo.isArchived
? 'bg-port-success/20 text-port-success hover:bg-port-success/30 border border-port-success/30'
: 'bg-port-warning/20 text-port-warning hover:bg-port-warning/30 border border-port-warning/30'
} disabled:opacity-50`}
>
{archiving === repo.fullName ? '...' : repo.isArchived ? 'Unarchive' : 'Archive'}
</button>
</div>
</div>
))}
</div>
)}
</div>
<div className="min-w-0 space-y-6 [overflow-wrap:anywhere]">
{/* Secrets Management */}
<div className="bg-port-card rounded-lg border border-port-border p-4 sm:p-6">
<h2 className="text-lg font-bold text-white mb-4">Secrets Management</h2>
{secretEntries.length > 0 && (
<div className="space-y-2 mb-4">
{secretEntries.map(([name, meta]) => (
<div key={name} className="flex flex-col gap-2 p-3 bg-port-bg rounded border border-port-border">
<div>
<span className="text-white font-mono text-sm">{name}</span>
<span className={`ml-2 text-xs ${meta.hasValue ? 'text-port-success' : 'text-port-warning'}`}>
{meta.hasValue ? 'configured' : 'no value'}
</span>
{meta.updatedAt && (
<span className="ml-2 text-xs text-gray-500">
updated {timeAgo(meta.updatedAt)}
</span>
)}
</div>
<button
onClick={() => handleSyncSecret(name)}
disabled={syncingSecret === name || !meta.hasValue || !cachedAccountMatches}
className="self-start px-3 py-1 text-sm bg-port-accent hover:bg-port-accent/80 text-white rounded disabled:opacity-50"
>
{syncingSecret === name ? 'Syncing...' : 'Sync to Repos'}
</button>
</div>
))}
</div>
)}
<div className="flex flex-col gap-2">
<FormField label="Secret name">
<input
type="text"
value={newSecretName}
onChange={(e) => setNewSecretName(e.target.value.toUpperCase().replace(/[^A-Z0-9_]/g, ''))}
placeholder="SECRET_NAME"
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white font-mono text-sm"
/>
</FormField>
<FormField label="Secret value">
<input
type="password"
value={newSecretValue}
onChange={(e) => setNewSecretValue(e.target.value)}
placeholder="Secret value"
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
/>
</FormField>
<button
onClick={handleSaveSecret}
disabled={savingSecret || !newSecretName.trim() || !newSecretValue || !cachedAccountMatches}
className="px-4 py-2 bg-port-success hover:bg-port-success/80 text-white rounded text-sm disabled:opacity-50"
>
{savingSecret ? 'Saving...' : 'Save Secret'}
</button>
</div>
<p className="text-xs text-gray-500 mt-2">
Secrets are stored locally and pushed to repos via <code>gh secret set</code>. Stored values are never returned from the server.
</p>
</div>
{/* Info */}
<div className="bg-port-card rounded-lg border border-port-border p-4 sm:p-6">
<h2 className="text-base font-bold text-white mb-3">How it works</h2>
<div className="space-y-2 text-xs sm:text-sm text-gray-300">
<p>1. Sign in above, then click "Sync Repos" to fetch repositories owned by the active GitHub account</p>
<p>2. Toggle "NPM" on repos that publish to npm — this auto-adds NPM_TOKEN to their managed secrets</p>
<p>3. Add secrets (like NPM_TOKEN) with their values — values are stored locally, never in the browser</p>
<p>4. Click "Sync to Repos" to push secrets to all flagged repos via <code>gh secret set</code></p>
<p className="text-gray-500 mt-2">
Uses the account authenticated in the <code>gh</code> CLI. Repository access is required to sync private repos and secrets.
</p>
</div>
</div>
</div>
</div>
</div>
);
}