Skip to content

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

Add GitHub accounts with trust levels to the GitHub page

Claudef83e18a1fefa
diff --git a/client/src/App.jsx b/client/src/App.jsx
index d0b1c52e7a..91d11be91f 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -300,6 +300,7 @@ export default function App() {
<Route path="devtools/datadog" element={<DataDog />} />
<Route path="devtools/flows" element={<FlowsDoc />} />
<Route path="devtools/github" element={<GitHub />} />
+ <Route path="devtools/github/:tab" element={<GitHub />} />
<Route path="devtools/history" element={<HistoryPage />} />
<Route path="devtools/image-clean" element={<ImageClean />} />
<Route path="devtools/quota-burn" element={<QuotaBurn />} />
diff --git a/client/src/components/github/GitHubAccountsTab.jsx b/client/src/components/github/GitHubAccountsTab.jsx
new file mode 100644
index 0000000000..b7512172ad
--- /dev/null
+++ b/client/src/components/github/GitHubAccountsTab.jsx
@@ -0,0 +1,259 @@
+import { useCallback, useEffect, useState } from 'react';
+import { Link } from 'react-router';
+import { Plus, RefreshCw } from 'lucide-react';
+import toast from '../ui/Toast';
+import Pill from '../ui/Pill';
+import InlineConfirmRow from '../ui/InlineConfirmRow';
+import LoadFailedState from '../ui/LoadFailedState';
+import PageSkeleton from '../ui/PageSkeleton';
+import { FormField } from '../ui/FormField';
+import {
+ getGitHubAccounts,
+ createGitHubAccount,
+ updateGitHubAccount,
+ deleteGitHubAccount,
+ getGitHubAccountStatus,
+} from '../../services/api';
+
+const GITHUB_DOT_COM = 'github.com';
+const TRUST_OPTIONS = [
+ { value: 'public', label: 'Public', hint: 'Anyone can mention you; outside content is always screened' },
+ { value: 'private', label: 'Private', hint: 'Enterprise: org members trusted; content stays on allowed AI providers' },
+];
+const MODE_LABELS = { observe: 'Observe', assist: 'Assist', autopilot: 'Autopilot' };
+const STATUS_VIEW = {
+ ok: { tone: 'success', label: 'Signed in' },
+ 'wrong-account': { tone: 'warning', label: 'Other login active' },
+ 'not-authenticated': { tone: 'warning', label: 'Signed out' },
+ 'not-installed': { tone: 'error', label: 'gh missing' },
+ unreachable: { tone: 'error', label: 'Unreachable' },
+ error: { tone: 'error', label: 'Check failed' },
+};
+
+const defaultTrustForHost = (host) => (host.trim().toLowerCase() === GITHUB_DOT_COM ? 'public' : 'private');
+const emptyForm = () => ({ host: GITHUB_DOT_COM, login: '', label: '', trust: 'public', trustTouched: false });
+const formFromAccount = (account) => ({
+ host: account.host,
+ login: account.login || '',
+ label: account.label || '',
+ trust: account.trust,
+ trustTouched: true,
+});
+const payloadFromForm = (form) => ({
+ host: form.host.trim(),
+ login: form.login.trim() || null,
+ label: form.label.trim(),
+ trust: form.trust,
+});
+
+function AccountForm({ form, setForm, onSubmit, onCancel, saving, submitLabel }) {
+ const setField = (field) => (event) => {
+ const value = event.target.value;
+ setForm((prev) => {
+ const next = { ...prev, [field]: value };
+ if (field === 'host' && !prev.trustTouched) next.trust = defaultTrustForHost(value);
+ if (field === 'trust') next.trustTouched = true;
+ return next;
+ });
+ };
+ const inputClass = 'w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm';
+ return (
+ <form
+ className="space-y-3"
+ onSubmit={(event) => { event.preventDefault(); onSubmit(); }}
+ >
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
+ <FormField label="Host" hint="github.com or your Enterprise hostname">
+ <input type="text" value={form.host} onChange={setField('host')} autoCapitalize="none" autoCorrect="off" spellCheck={false} className={`${inputClass} font-mono`} required />
+ </FormField>
+ <FormField label="Login" hint="Leave empty to use whoever gh has signed in">
+ <input type="text" value={form.login} onChange={setField('login')} autoCapitalize="none" autoCorrect="off" spellCheck={false} placeholder="octocat" className={`${inputClass} font-mono`} />
+ </FormField>
+ <FormField label="Name">
+ <input type="text" value={form.label} onChange={setField('label')} placeholder="Shown on the account card" maxLength={80} className={inputClass} />
+ </FormField>
+ <FormField label="Trust" hint={TRUST_OPTIONS.find((option) => option.value === form.trust)?.hint}>
+ <select value={form.trust} onChange={setField('trust')} className={inputClass}>
+ {TRUST_OPTIONS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
+ </select>
+ </FormField>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <button type="submit" disabled={saving || !form.host.trim()} className="px-4 py-2 rounded bg-port-accent text-white text-sm disabled:opacity-50">
+ {saving ? 'Saving…' : submitLabel}
+ </button>
+ <button type="button" onClick={onCancel} disabled={saving} className="px-4 py-2 rounded border border-port-border text-gray-300 text-sm">
+ Cancel
+ </button>
+ </div>
+ </form>
+ );
+}
+
+function AccountStatus({ status, onRecheck }) {
+ if (!status) return <p className="text-xs text-gray-500">Checking sign-in…</p>;
+ const view = STATUS_VIEW[status.status] || STATUS_VIEW.error;
+ return (
+ <div className="space-y-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <Pill tone={view.tone}>{view.label}</Pill>
+ {status.login && <span className="min-w-0 truncate font-mono text-xs text-gray-300">@{status.login}</span>}
+ <button type="button" onClick={onRecheck} className="ml-auto inline-flex items-center gap-1 rounded px-2 py-1 text-xs text-gray-400 hover:text-white" aria-label="Recheck sign-in">
+ <RefreshCw size={12} aria-hidden="true" /> Recheck
+ </button>
+ </div>
+ {status.remedy && <p className="text-xs text-gray-400 break-words">{status.remedy}</p>}
+ {status.command && (
+ <Link to={`/shell?cmd=${encodeURIComponent(status.command)}`} className="inline-block rounded bg-port-accent px-3 py-1.5 text-xs text-white">
+ Sign in on {status.host}
+ </Link>
+ )}
+ </div>
+ );
+}
+
+export default function GitHubAccountsTab() {
+ const [accounts, setAccounts] = useState(null);
+ const [loadFailed, setLoadFailed] = useState(false);
+ const [statuses, setStatuses] = useState({});
+ const [adding, setAdding] = useState(false);
+ const [editingId, setEditingId] = useState(null);
+ const [form, setForm] = useState(emptyForm);
+ const [saving, setSaving] = useState(false);
+ const [confirmingDelete, setConfirmingDelete] = useState(null);
+
+ const checkStatus = useCallback((id) => {
+ setStatuses((prev) => ({ ...prev, [id]: null }));
+ getGitHubAccountStatus(id, { silent: true })
+ .then((status) => setStatuses((prev) => ({ ...prev, [id]: status })))
+ .catch((err) => setStatuses((prev) => ({ ...prev, [id]: { id, status: 'error', remedy: err.message } })));
+ }, []);
+
+ const load = useCallback(async () => {
+ setLoadFailed(false);
+ const list = await getGitHubAccounts({ silent: true }).catch(() => null);
+ if (!list) {
+ setLoadFailed(true);
+ return;
+ }
+ setAccounts(list);
+ list.forEach((account) => checkStatus(account.id));
+ }, [checkStatus]);
+
+ useEffect(() => { load(); }, [load]);
+
+ const closeForm = () => {
+ setAdding(false);
+ setEditingId(null);
+ setForm(emptyForm());
+ };
+
+ const handleCreate = async () => {
+ setSaving(true);
+ const created = await createGitHubAccount(payloadFromForm(form)).catch(() => null);
+ setSaving(false);
+ if (!created) return;
+ setAccounts((prev) => [...(prev || []), created]);
+ checkStatus(created.id);
+ closeForm();
+ toast.success(`Added ${created.label}`);
+ };
+
+ const handleUpdate = async () => {
+ setSaving(true);
+ const updated = await updateGitHubAccount(editingId, payloadFromForm(form)).catch(() => null);
+ setSaving(false);
+ if (!updated) return;
+ setAccounts((prev) => prev.map((account) => (account.id === updated.id ? updated : account)));
+ checkStatus(updated.id);
+ closeForm();
+ };
+
+ const handleDelete = async (id) => {
+ const removed = await deleteGitHubAccount(id).catch(() => null);
+ setConfirmingDelete(null);
+ if (!removed) return;
+ setAccounts((prev) => prev.filter((account) => account.id !== id));
+ };
+
+ if (loadFailed) return <LoadFailedState title="Could not load GitHub accounts." hint="Retry the local account read." onRetry={load} />;
+ if (!accounts) return <PageSkeleton label="Loading GitHub accounts" titleWidthClass="w-40" showAction={false} cards={2} />;
+
+ return (
+ <div className="min-w-0 space-y-4">
+ <div className="flex items-center justify-between gap-3">
+ <p className="text-sm text-gray-400">Each account is one login on one GitHub host.</p>
+ {!adding && !editingId && (
+ <button
+ type="button"
+ onClick={() => { setForm(emptyForm()); setAdding(true); }}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded bg-port-accent px-3 py-2 text-sm text-white"
+ >
+ <Plus size={14} aria-hidden="true" /> Add account
+ </button>
+ )}
+ </div>
+
+ {adding && (
+ <section className="rounded-lg border border-port-border bg-port-card p-4" aria-label="Add GitHub account">
+ <h2 className="mb-3 font-semibold text-white">Add account</h2>
+ <AccountForm form={form} setForm={setForm} onSubmit={handleCreate} onCancel={closeForm} saving={saving} submitLabel="Add account" />
+ </section>
+ )}
+
+ {accounts.length === 0 && !adding && (
+ <p className="rounded-lg border border-port-border bg-port-card p-4 text-sm text-gray-400">No GitHub accounts yet.</p>
+ )}
+
+ <ul className="grid grid-cols-1 gap-3 @3xl/page:grid-cols-2">
+ {accounts.map((account) => (
+ <li key={account.id} className="min-w-0 rounded-lg border border-port-border bg-port-card p-4">
+ {editingId === account.id ? (
+ <AccountForm form={form} setForm={setForm} onSubmit={handleUpdate} onCancel={closeForm} saving={saving} submitLabel="Save" />
+ ) : (
+ <div className="space-y-3">
+ <div className="flex flex-wrap items-start gap-2">
+ <div className="min-w-0 flex-1">
+ <h2 className="truncate font-semibold text-white">{account.label}</h2>
+ <p className="truncate font-mono text-xs text-gray-400">
+ {account.host}{account.login ? ` · @${account.login}` : ' · active gh login'}
+ </p>
+ </div>
+ <Pill tone={account.trust === 'private' ? 'accent' : 'muted'}>{account.trust === 'private' ? 'Private' : 'Public'}</Pill>
+ <Pill tone="muted">{MODE_LABELS[account.mode] || account.mode}</Pill>
+ </div>
+ <AccountStatus status={statuses[account.id]} onRecheck={() => checkStatus(account.id)} />
+ {confirmingDelete === account.id ? (
+ <InlineConfirmRow
+ question={`Remove ${account.label}? gh keeps its sign-in.`}
+ confirmText="Remove"
+ onConfirm={() => handleDelete(account.id)}
+ onCancel={() => setConfirmingDelete(null)}
+ />
+ ) : (
+ <div className="flex flex-wrap gap-2">
+ <button
+ type="button"
+ onClick={() => { setAdding(false); setForm(formFromAccount(account)); setEditingId(account.id); }}
+ disabled={adding || Boolean(editingId)}
+ className="rounded border border-port-border px-3 py-1.5 text-xs text-gray-300 disabled:opacity-50"
+ >
+ Edit
+ </button>
+ <button
+ type="button"
+ onClick={() => setConfirmingDelete(account.id)}
+ className="rounded border border-port-border px-3 py-1.5 text-xs text-gray-300"
+ >
+ Remove
+ </button>
+ </div>
+ )}
+ </div>
+ )}
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
diff --git a/client/src/components/github/GitHubReposTab.jsx b/client/src/components/github/GitHubReposTab.jsx
new file mode 100644
index 0000000000..e977d6048c
--- /dev/null
+++ b/client/src/components/github/GitHubReposTab.jsx
@@ -0,0 +1,582 @@
+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">&#9662;</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 &mdash; this auto-adds NPM_TOKEN to their managed secrets</p>
+ <p>3. Add secrets (like NPM_TOKEN) with their values &mdash; 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>
+ );
+}
diff --git a/client/src/pages/GitHub.jsx b/client/src/pages/GitHub.jsx
index 92028f9f23..447647137a 100644
--- a/client/src/pages/GitHub.jsx
+++ b/client/src/pages/GitHub.jsx
@@ -1,584 +1,25 @@
-import { useState, useEffect, useMemo } from 'react';
-import { Link } from 'react-router';
-import toast from '../components/ui/Toast';
-import {
- getGitHubRepos,
- getGitHubStatus,
- syncGitHubRepos,
- updateGitHubRepo,
- getGitHubSecrets,
- setGitHubSecret,
- syncGitHubSecret,
- archiveGitHubRepo,
- unarchiveGitHubRepo
-} from '../services/api';
-import { timeAgo } from '../utils/formatters';
-import PageSkeleton from '../components/ui/PageSkeleton';
-import Modal from '../components/ui/Modal';
-import { FormField } from '../components/ui/FormField';
-import LoadFailedState from '../components/ui/LoadFailedState';
+import { useParams } from 'react-router';
+import RouteTabsHeader from '../components/ui/RouteTabsHeader';
+import GitHubAccountsTab from '../components/github/GitHubAccountsTab';
+import GitHubReposTab from '../components/github/GitHubReposTab';
-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,
-});
+// Inbox, Automations and Audit join as their phases ship (#12870–#12874).
+export const GITHUB_PAGE_TABS = Object.freeze([
+ { id: 'repos', label: 'Repos', to: '/devtools/github/repos' },
+ { id: 'accounts', label: 'Accounts', to: '/devtools/github/accounts' },
+]);
export default function GitHub() {
- 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" padded titleWidthClass="w-44" showAction={false} cards={3} />;
- }
+ const { tab } = useParams();
+ const activeTab = GITHUB_PAGE_TABS.some((entry) => entry.id === tab) ? tab : 'repos';
return (
<div className="@container/page min-w-0 p-4 sm:p-6">
- <h1 className="text-xl sm:text-2xl font-bold text-white mb-6">GitHub Repos</h1>
-
- {!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">&#9662;</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 &mdash; this auto-adds NPM_TOKEN to their managed secrets</p>
- <p>3. Add secrets (like NPM_TOKEN) with their values &mdash; 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 className="mb-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <h1 className="text-xl sm:text-2xl font-bold text-white">GitHub</h1>
+ <RouteTabsHeader tabs={GITHUB_PAGE_TABS} activeTab={activeTab} ariaLabel="GitHub views" />
</div>
+ {activeTab === 'accounts' ? <GitHubAccountsTab /> : <GitHubReposTab />}
</div>
);
}
diff --git a/client/src/pages/GitHub.test.jsx b/client/src/pages/GitHub.test.jsx
index 910c52b76c..85be811366 100644
--- a/client/src/pages/GitHub.test.jsx
+++ b/client/src/pages/GitHub.test.jsx
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
-import { MemoryRouter } from 'react-router';
+import { MemoryRouter, Route, Routes } from 'react-router';
const mock = vi.hoisted(() => ({
getGitHubRepos: vi.fn(),
@@ -12,6 +12,11 @@ const mock = vi.hoisted(() => ({
syncGitHubSecret: vi.fn(),
archiveGitHubRepo: vi.fn(),
unarchiveGitHubRepo: vi.fn(),
+ getGitHubAccounts: vi.fn(),
+ createGitHubAccount: vi.fn(),
+ updateGitHubAccount: vi.fn(),
+ deleteGitHubAccount: vi.fn(),
+ getGitHubAccountStatus: vi.fn(),
}));
vi.mock('../services/api', () => mock);
@@ -294,3 +299,63 @@ describe('GitHub account setup', () => {
expect(screen.getByRole('button', { name: 'Sync Repos' })).not.toBeDisabled();
});
});
+
+const renderAccounts = () => render(
+ <MemoryRouter initialEntries={['/devtools/github/accounts']}>
+ <Routes>
+ <Route path="/devtools/github/:tab" element={<GitHub />} />
+ </Routes>
+ </MemoryRouter>,
+);
+
+const IMPLICIT = {
+ id: 'github-com', label: 'github.com', host: 'github.com', login: null,
+ trust: 'public', allowedProviders: null, mode: 'observe', enabled: true, implicit: true,
+};
+
+describe('GitHub accounts tab', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mock.getGitHubAccounts.mockResolvedValue([IMPLICIT]);
+ mock.getGitHubAccountStatus.mockResolvedValue({ id: 'github-com', host: 'github.com', status: 'ok', login: 'octocat', remedy: null, command: null });
+ });
+
+ it('lists each account with its trust level and live sign-in state', async () => {
+ renderAccounts();
+ expect(await screen.findByText('Signed in')).toBeTruthy();
+ expect(screen.getByText('@octocat')).toBeTruthy();
+ expect(screen.getByText('Public')).toBeTruthy();
+ expect(screen.getByText('Observe')).toBeTruthy();
+ expect(mock.getGitHubRepos).not.toHaveBeenCalled();
+ });
+
+ it('adds an Enterprise account as Private by default and offers its sign-in command', async () => {
+ mock.createGitHubAccount.mockImplementation(async (body) => ({
+ ...body, id: 'acct-2', label: 'alice @ ghe.example.com', mode: 'observe', enabled: true, allowedProviders: null,
+ }));
+ mock.getGitHubAccountStatus.mockImplementation(async (id) => (id === 'acct-2'
+ ? { id, host: 'ghe.example.com', status: 'not-authenticated', login: null, remedy: 'Sign in.', command: 'gh auth login --hostname ghe.example.com --web --clipboard' }
+ : { id, host: 'github.com', status: 'ok', login: 'octocat', remedy: null, command: null }));
+ renderAccounts();
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Add account' }));
+ fireEvent.change(screen.getByLabelText('Host'), { target: { value: 'ghe.example.com' } });
+ fireEvent.change(screen.getByLabelText('Login'), { target: { value: 'alice' } });
+ expect(screen.getByLabelText('Trust').value).toBe('private');
+ fireEvent.click(screen.getAllByRole('button', { name: 'Add account' }).at(-1));
+
+ expect(mock.createGitHubAccount).toHaveBeenCalledWith({ host: 'ghe.example.com', login: 'alice', label: '', trust: 'private' });
+ const signIn = await screen.findByRole('link', { name: 'Sign in on ghe.example.com' });
+ expect(decodeURIComponent(signIn.getAttribute('href'))).toBe('/shell?cmd=gh auth login --hostname ghe.example.com --web --clipboard');
+ });
+
+ it('removes an account only after an inline confirmation', async () => {
+ mock.deleteGitHubAccount.mockResolvedValue({ id: 'github-com' });
+ renderAccounts();
+ fireEvent.click(await screen.findByRole('button', { name: 'Remove' }));
+ expect(mock.deleteGitHubAccount).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'Remove' }));
+ expect(mock.deleteGitHubAccount).toHaveBeenCalledWith('github-com');
+ expect(await screen.findByText('No GitHub accounts yet.')).toBeTruthy();
+ });
+});
diff --git a/client/src/services/apiGithub.js b/client/src/services/apiGithub.js
index 5ad46855db..9c7d2d5f4f 100644
--- a/client/src/services/apiGithub.js
+++ b/client/src/services/apiGithub.js
@@ -17,3 +17,14 @@ export const setGitHubSecret = (name, value, options = {}) =>
request(`/github/secrets/${encodeURIComponent(name)}`, { method: 'PUT', body: JSON.stringify({ value }), ...options });
export const syncGitHubSecret = (name, options = {}) =>
request(`/github/secrets/${encodeURIComponent(name)}/sync`, { method: 'POST', ...options });
+
+// GitHub accounts (github.com + Enterprise hosts) for the notifications manager.
+export const getGitHubAccounts = (options = {}) => request('/github/accounts', options);
+export const createGitHubAccount = (data, options = {}) =>
+ request('/github/accounts', { method: 'POST', body: JSON.stringify(data), ...options });
+export const updateGitHubAccount = (id, data, options = {}) =>
+ request(`/github/accounts/${encodeURIComponent(id)}`, { method: 'PUT', body: JSON.stringify(data), ...options });
+export const deleteGitHubAccount = (id, options = {}) =>
+ request(`/github/accounts/${encodeURIComponent(id)}`, { method: 'DELETE', ...options });
+export const getGitHubAccountStatus = (id, options = {}) =>
+ request(`/github/accounts/${encodeURIComponent(id)}/status`, options);
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 37ac8715eb..c3746b0b5c 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -605,6 +605,10 @@ Optional SDK environments under `data/venvs/` are machine-local, regenerable run
`data/videos/.music-video-render-cleanup.json` is machine-local, `file-primary` recovery metadata for generated video files. Version 1 holds pending retired final-render history records until their video, poster and proof bytes are removed. Cleanup writes this journal before changing the derived index or history, removes history entries before unlinking files, and retries pending entries from the journal on the next cleanup or successful final render. The Cleanup page includes pending bytes even after their media-library rows are gone. A global write queue and backup publication admission cover journal, history and file changes; normal data backups include the journal beside its videos. It has no search or cross-record query requirements and is never federated. Unknown/malformed versions fail closed. It is created only when retiring a render, needs no seed or migration, and disappears when empty. Source takes and cutting-room media are not journaled or removed.
+### GitHub accounts
+
+`data/github-accounts.json` is `file-primary`: the GitHub logins the notifications manager works with (#12869), one record per login on one host (github.com or a GitHub Enterprise Server hostname) with its operator-chosen trust level (`public` | `private`), allowed AI providers, automation mode and enabled flag. It is small machine-local configuration, like Messages accounts: no foreign keys, no cross-record queries, no search. It holds no credentials (`gh` keeps those) and is never federated, because which logins a machine is signed into is a property of that machine. With no file, the API shows one implicit github.com account so existing installs need no migration or `data.reference/` seed; the file is written on the first edit, and a stored empty list stays authoritative. Version 1; a malformed or other-version file is refused with 503 and left untouched. Rsync backups include it. Code: `server/services/githubAccounts.js`.
+
### Music Video cover lettering
`data/cover-fonts/` is `file-primary`: the typefaces a director uploads for cover lettering (`<id>.ttf|otf|woff2`) plus a small `fonts.json` index (`{ id, family, ext, width, addedAt }`, width measured at upload). Machine-local and never federated: a font is a licensed binary the director chose for this install, and whether it renders depends on this machine's font system. It is included in normal data backups (no new exclude); it relates to no other record and needs no search, so it stays out of the DB. On macOS each font is also mirrored into `~/Library/Fonts/PortOS/`, because CoreText reads only Fonts folders; other platforms register the file with fontconfig through libvips. An upload is refused unless the renderer proves it can set text in it. The per-artist saved cover design is `settings.musicVideoPublishing.artistStyles` in the file-primary `data/settings.json` (keyed by lowercased artist name), beside the machine-local `platforms` choice; settings are not synced between machines. Neither needs a migration: a cover design stored before `titleStyle`/`tagLayout` existed normalizes to the previous look unchanged. Code: `server/services/musicVideo/coverFonts.js`, `publish/artistStyles.js`; layout: `server/lib/musicVideoCoverOverlay.js`.
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index ec760a36f9..8810b7fd9c 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -219,6 +219,9 @@ const RAW_NAV_COMMANDS = [
{ id: 'nav.devtools.datadog', path: '/devtools/datadog', label: 'DataDog', section: 'Dev Tools', feature: 'datadog', previousPaths: ['/datadog'], aliases: ['datadog', 'devtools-datadog'] },
{ id: 'nav.devtools.flows', path: '/devtools/flows', label: 'Flows', section: 'Dev Tools', aliases: ['flows', 'integration-flows', 'workflows'], keywords: ['architecture', 'diagram', 'data flow', 'integrations', 'how it works'] },
{ id: 'nav.devtools.github', path: '/devtools/github', label: 'GitHub', section: 'Dev Tools', aliases: ['github', 'devtools-github'] },
+ // ⌘K / voice only — no sidebar row: tabs of the GitHub page.
+ { id: 'nav.devtools.github-accounts', path: '/devtools/github/accounts', label: 'GitHub Accounts', section: 'Dev Tools', aliases: ['github-accounts', 'github-enterprise'], keywords: ['github', 'enterprise', 'ghes', 'gh auth', 'login', 'trust', 'notifications'] },
+ { id: 'nav.devtools.github-repos', path: '/devtools/github/repos', label: 'GitHub Repos', section: 'Dev Tools', aliases: ['github-repos', 'github-secrets'], keywords: ['github', 'repositories', 'secrets', 'archive', 'npm'] },
{ id: 'nav.devtools.history', path: '/devtools/history', label: 'History', section: 'Dev Tools', aliases: ['devtools-history'] },
{ id: 'nav.devtools.image-clean', path: '/devtools/image-clean', label: 'Image Cleaner', section: 'Dev Tools', aliases: ['image-clean', 'image-cleaner'], keywords: ['metadata', 'c2pa', 'content-credentials', 'sharp', 'denoise'] },
{ id: 'nav.devtools.jira', path: '/devtools/jira', label: 'JIRA', section: 'Dev Tools', feature: 'jira', previousPaths: ['/jira'], aliases: ['jira', 'devtools-jira'] },
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 30c9cd0665..093cd0471f 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -943,6 +943,29 @@ export const githubSecretSchema = z.object({
value: z.string().min(1)
});
+// GitHub notifications manager accounts (#12869). A bare hostname (optional
+// :port) whose first character also rules out a value `gh` would parse as a flag.
+export const GITHUB_ACCOUNT_HOST_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*(?::\d{1,5})?$/;
+// github.com logins are [A-Za-z0-9-]; Enterprise Managed Users add `_shortcode`.
+export const GITHUB_ACCOUNT_LOGIN_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/;
+export const GITHUB_ACCOUNT_TRUST_LEVELS = Object.freeze(['public', 'private']);
+export const GITHUB_ACCOUNT_MODES = Object.freeze(['observe', 'assist', 'autopilot']);
+
+export const githubAccountCreateSchema = z.object({
+ label: z.string().trim().max(80).optional(),
+ host: z.string().trim().toLowerCase()
+ .transform((value) => value.replace(/^https?:\/\//, '').replace(/\/+$/, ''))
+ .pipe(z.string().min(1).max(253).regex(GITHUB_ACCOUNT_HOST_RE, 'Use a bare hostname such as github.example.com')),
+ login: z.string().trim().regex(GITHUB_ACCOUNT_LOGIN_RE, 'Not a valid GitHub login').nullable().optional(),
+ trust: z.enum(GITHUB_ACCOUNT_TRUST_LEVELS).optional(),
+ // null = the trust level's default (Private: local providers only).
+ allowedProviders: z.array(z.string().trim().min(1).max(128)).max(50).nullable().optional(),
+ mode: z.enum(GITHUB_ACCOUNT_MODES).optional(),
+ enabled: z.boolean().optional(),
+}).strict();
+
+export const githubAccountUpdateSchema = githubAccountCreateSchema.partial().strict();
+
// =============================================================================
// INSIGHTS SCHEMAS
// =============================================================================
diff --git a/server/routes/github.js b/server/routes/github.js
index f5c725386a..c5add2bd98 100644
--- a/server/routes/github.js
+++ b/server/routes/github.js
@@ -1,7 +1,8 @@
import express from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { validateRequest, githubRepoUpdateSchema, githubSecretSchema } from '../lib/validation.js';
+import { validateRequest, githubRepoUpdateSchema, githubSecretSchema, githubAccountCreateSchema, githubAccountUpdateSchema } from '../lib/validation.js';
import * as githubService from '../services/github.js';
+import * as githubAccounts from '../services/githubAccounts.js';
const router = express.Router();
@@ -95,4 +96,32 @@ router.get('/status', asyncHandler(async (req, res) => {
res.json(status);
}));
+/**
+ * GET /api/github/accounts — configured accounts (github.com + Enterprise hosts)
+ */
+router.get('/accounts', asyncHandler(async (req, res) => {
+ res.json(await githubAccounts.listAccounts());
+}));
+
+router.post('/accounts', asyncHandler(async (req, res) => {
+ const body = validateRequest(githubAccountCreateSchema, req.body);
+ res.status(201).json(await githubAccounts.createAccount(body));
+}));
+
+router.put('/accounts/:id', asyncHandler(async (req, res) => {
+ const body = validateRequest(githubAccountUpdateSchema, req.body);
+ res.json(await githubAccounts.updateAccount(req.params.id, body));
+}));
+
+router.delete('/accounts/:id', asyncHandler(async (req, res) => {
+ res.json(await githubAccounts.deleteAccount(req.params.id));
+}));
+
+/**
+ * GET /api/github/accounts/:id/status — live `gh` sign-in probe for one account
+ */
+router.get('/accounts/:id/status', asyncHandler(async (req, res) => {
+ res.json(await githubAccounts.getAccountStatus(req.params.id));
+}));
+
export default router;
diff --git a/server/services/githubAccounts.js b/server/services/githubAccounts.js
new file mode 100644
index 0000000000..4f16533c21
--- /dev/null
+++ b/server/services/githubAccounts.js
@@ -0,0 +1,233 @@
+/**
+ * GitHub accounts for the notifications manager (#12869): one login on one host
+ * (github.com or a GitHub Enterprise Server hostname) with the operator-chosen
+ * trust level and automation mode. Credentials stay in `gh`'s own store; this
+ * file holds only machine-local configuration and is never federated.
+ *
+ * Trust is a property of the ACCOUNT the operator configured, never of any
+ * notification content — later phases compute per-thread trust from it plus
+ * repo ownership and actor metadata.
+ */
+import { join } from 'path';
+import { z } from 'zod';
+import { v4 as uuidv4 } from '../lib/uuid.js';
+import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { execGh, classifyGhProbe, ghRemedy } from './github.js';
+import {
+ GITHUB_ACCOUNT_HOST_RE as HOST_RE,
+ GITHUB_ACCOUNT_LOGIN_RE as LOGIN_RE,
+ GITHUB_ACCOUNT_MODES,
+ GITHUB_ACCOUNT_TRUST_LEVELS,
+ githubAccountCreateSchema,
+ githubAccountUpdateSchema,
+ validateRequest,
+} from '../lib/validation.js';
+
+const ACCOUNTS_FILE = join(PATHS.data, 'github-accounts.json');
+const STORE_VERSION = 1;
+const STATUS_TIMEOUT_MS = 10000;
+const queueWrite = createFileWriteQueue();
+
+const GITHUB_DOT_COM = 'github.com';
+// Shown before the operator has configured anything: the github.com login `gh`
+// already uses, so an existing install sees its account without a migration.
+// Persisted only once edited.
+const IMPLICIT_ACCOUNT_ID = 'github-com';
+
+const defaultTrustForHost = (host) => (host === GITHUB_DOT_COM ? 'public' : 'private');
+
+const storedAccountSchema = z.object({
+ id: z.string().min(1),
+ label: z.string(),
+ host: z.string().regex(HOST_RE),
+ login: z.string().regex(LOGIN_RE).nullable(),
+ trust: z.enum(GITHUB_ACCOUNT_TRUST_LEVELS),
+ allowedProviders: z.array(z.string()).nullable(),
+ mode: z.enum(GITHUB_ACCOUNT_MODES),
+ enabled: z.boolean(),
+ createdAt: z.string(),
+ updatedAt: z.string(),
+}).passthrough();
+const storeSchema = z.object({ version: z.literal(STORE_VERSION), accounts: z.array(storedAccountSchema) }).passthrough();
+
+const implicitAccount = () => ({
+ id: IMPLICIT_ACCOUNT_ID,
+ label: GITHUB_DOT_COM,
+ host: GITHUB_DOT_COM,
+ login: null,
+ trust: 'public',
+ allowedProviders: null,
+ mode: 'observe',
+ enabled: true,
+ createdAt: null,
+ updatedAt: null,
+ implicit: true,
+});
+
+// null = no store yet (show the implicit account); a stored empty list means
+// the operator removed every account and stays authoritative.
+async function loadStore() {
+ await ensureDir(PATHS.data);
+ const raw = await readJSONFile(ACCOUNTS_FILE, null, { strict: true, allowArray: false });
+ if (raw === null) return null;
+ const parsed = storeSchema.safeParse(raw);
+ if (!parsed.success) {
+ throw new ServerError('GitHub accounts storage is invalid; original file preserved', {
+ status: 503, code: 'GITHUB_ACCOUNTS_UNAVAILABLE',
+ });
+ }
+ return parsed.data;
+}
+
+const saveStore = (accounts) => atomicWrite(ACCOUNTS_FILE, { version: STORE_VERSION, accounts });
+
+const currentAccounts = (store) => (store ? store.accounts : [implicitAccount()]);
+
+const materialize = (account) => {
+ if (!account.implicit) return account;
+ const now = new Date().toISOString();
+ const { implicit: _implicit, ...rest } = account;
+ return { ...rest, createdAt: now, updatedAt: now };
+};
+
+const sameIdentity = (a, b) => a.host === b.host && (a.login || '').toLowerCase() === (b.login || '').toLowerCase();
+
+function assertUniqueIdentity(accounts, candidate) {
+ const clash = accounts.find((account) => account.id !== candidate.id && sameIdentity(account, candidate));
+ if (clash) {
+ throw new ServerError(`An account for ${candidate.login ? `${candidate.login} on ` : ''}${candidate.host} already exists`, {
+ status: 409, code: 'GITHUB_ACCOUNT_EXISTS',
+ });
+ }
+}
+
+const notFound = (id) => new ServerError(`GitHub account ${id} not found`, { status: 404, code: 'GITHUB_ACCOUNT_NOT_FOUND' });
+
+export async function listAccounts() {
+ return currentAccounts(await loadStore());
+}
+
+async function getAccount(id) {
+ const account = (await listAccounts()).find((entry) => entry.id === id);
+ if (!account) throw notFound(id);
+ return account;
+}
+
+export function createAccount(input) {
+ const data = validateRequest(githubAccountCreateSchema, input);
+ return queueWrite(async () => {
+ const accounts = currentAccounts(await loadStore()).map(materialize);
+ const now = new Date().toISOString();
+ const account = {
+ id: uuidv4(),
+ label: data.label || (data.login ? `${data.login} @ ${data.host}` : data.host),
+ host: data.host,
+ login: data.login ?? null,
+ trust: data.trust || defaultTrustForHost(data.host),
+ allowedProviders: data.allowedProviders ?? null,
+ mode: data.mode || 'observe',
+ enabled: data.enabled ?? true,
+ createdAt: now,
+ updatedAt: now,
+ };
+ assertUniqueIdentity(accounts, account);
+ await saveStore([...accounts, account]);
+ console.log(`🔐 Added GitHub account for ${account.host} (${account.trust})`);
+ return account;
+ });
+}
+
+export function updateAccount(id, input) {
+ const data = validateRequest(githubAccountUpdateSchema, input);
+ return queueWrite(async () => {
+ const accounts = currentAccounts(await loadStore()).map(materialize);
+ const index = accounts.findIndex((account) => account.id === id);
+ if (index === -1) throw notFound(id);
+ const updated = { ...accounts[index], ...data, updatedAt: new Date().toISOString() };
+ if (data.label === '') updated.label = updated.login ? `${updated.login} @ ${updated.host}` : updated.host;
+ assertUniqueIdentity(accounts, updated);
+ accounts[index] = updated;
+ await saveStore(accounts);
+ return updated;
+ });
+}
+
+export function deleteAccount(id) {
+ return queueWrite(async () => {
+ const accounts = currentAccounts(await loadStore()).map(materialize);
+ const remaining = accounts.filter((account) => account.id !== id);
+ if (remaining.length === accounts.length) throw notFound(id);
+ await saveStore(remaining);
+ return { id };
+ });
+}
+
+// --- Sign-in status ---------------------------------------------------------
+
+const loginCommand = (host) => `gh auth login --hostname ${host} --web --clipboard`;
+
+/**
+ * The environment that makes `gh` act as THIS account, or `null` when `gh`
+ * holds no credential for the named login. A named login is pinned through its
+ * own token so a second login on the same host works without `gh auth switch`;
+ * an account with no login uses whichever login is active on that host.
+ */
+async function resolveGitHubAccountEnv(account, { baseEnv = process.env } = {}) {
+ const env = { ...baseEnv, GH_HOST: account.host };
+ if (!account.login) return env;
+ const token = await execGh(
+ ['auth', 'token', '--hostname', account.host, '--user', account.login],
+ STATUS_TIMEOUT_MS,
+ { env },
+ ).catch(() => null);
+ if (!token) return null;
+ return account.host === GITHUB_DOT_COM
+ ? { ...env, GH_TOKEN: token }
+ : { ...env, GH_ENTERPRISE_TOKEN: token };
+}
+
+function classifyError(error) {
+ if (error?.ghExitCode !== undefined) return classifyGhProbe({ code: error.ghExitCode, stderr: error.ghStderr });
+ if (error?.code) return classifyGhProbe({ spawnError: error });
+ return classifyGhProbe({ code: null, stderr: error?.message });
+}
+
+/**
+ * Probe `gh` for one account: is it installed, is the host reachable, and is
+ * the configured login actually the one the API answers as.
+ */
+export async function getAccountStatus(id) {
+ const account = await getAccount(id);
+ const { host, login } = account;
+ const checkedAt = new Date().toISOString();
+ const env = await resolveGitHubAccountEnv(account);
+ if (!env) {
+ return {
+ id, host, status: 'not-authenticated', login: null, checkedAt,
+ remedy: `gh has no credential for ${login} on ${host}. Run \`${loginCommand(host)}\` and sign in as ${login}.`,
+ command: loginCommand(host),
+ };
+ }
+ const attempt = await execGh(['api', 'user', '--hostname', host, '--jq', '.login'], STATUS_TIMEOUT_MS, { env })
+ .then((answer) => ({ answer, error: null }))
+ .catch((error) => ({ answer: null, error }));
+ if (attempt.answer) {
+ if (login && attempt.answer.toLowerCase() !== login.toLowerCase()) {
+ return {
+ id, host, status: 'wrong-account', login: attempt.answer, checkedAt,
+ remedy: `${host} answered as ${attempt.answer}, not ${login}. Sign in as ${login} or change this account's login.`,
+ command: loginCommand(host),
+ };
+ }
+ return { id, host, status: 'ok', login: attempt.answer, checkedAt, remedy: null, command: null };
+ }
+ const classified = classifyError(attempt.error);
+ const status = classified.status === 'ok' ? 'error' : classified.status;
+ return {
+ id, host, status, login: null, checkedAt,
+ remedy: ghRemedy(status, { hostname: host }),
+ command: status === 'not-authenticated' ? loginCommand(host) : null,
+ };
+}
diff --git a/server/services/githubAccounts.test.js b/server/services/githubAccounts.test.js
new file mode 100644
index 0000000000..bf005c4792
--- /dev/null
+++ b/server/services/githubAccounts.test.js
@@ -0,0 +1,128 @@
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import express from 'express';
+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
+import { request } from '../lib/testHelper.js';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'github-accounts-test-'));
+const ACCOUNTS_FILE = join(TEST_DATA_ROOT, 'github-accounts.json');
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) => makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));
+
+vi.mock('./github.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ execGh: vi.fn(),
+}));
+
+const { execGh } = await import('./github.js');
+const { errorMiddleware } = await import('../lib/errorHandler.js');
+const { default: githubRoutes } = await import('../routes/github.js');
+
+function makeApp() {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/github', githubRoutes);
+ app.use(errorMiddleware);
+ return app;
+}
+
+const ghError = (stderr, code = 1) => Object.assign(new Error(stderr), { ghExitCode: code, ghStderr: stderr });
+
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+describe('GitHub accounts API', () => {
+ let app;
+ beforeEach(() => {
+ rmSync(ACCOUNTS_FILE, { force: true });
+ vi.mocked(execGh).mockReset();
+ app = makeApp();
+ });
+
+ it('shows the implicit github.com account until the operator saves one, then persists it on edit', async () => {
+ const listed = await request(app).get('/api/github/accounts');
+ expect(listed.status).toBe(200);
+ expect(listed.body).toEqual([expect.objectContaining({ id: 'github-com', host: 'github.com', trust: 'public', mode: 'observe', implicit: true })]);
+
+ const updated = await request(app).put('/api/github/accounts/github-com').send({ login: 'octocat' });
+ expect(updated.status).toBe(200);
+ expect(updated.body).toEqual(expect.objectContaining({ id: 'github-com', login: 'octocat' }));
+ expect(updated.body.implicit).toBeUndefined();
+
+ const after = await request(app).get('/api/github/accounts');
+ expect(after.body).toEqual([expect.objectContaining({ id: 'github-com', login: 'octocat' })]);
+ expect(after.body[0].implicit).toBeUndefined();
+ });
+
+ it('defaults Enterprise hosts to private trust, normalizes the host, and refuses duplicates', async () => {
+ const created = await request(app).post('/api/github/accounts').send({ host: 'HTTPS://GitHub.Example.com/', login: 'alice' });
+ expect(created.status).toBe(201);
+ expect(created.body).toEqual(expect.objectContaining({ host: 'github.example.com', login: 'alice', trust: 'private', mode: 'observe', enabled: true }));
+
+ const listed = await request(app).get('/api/github/accounts');
+ expect(listed.body.map((account) => account.host)).toEqual(['github.com', 'github.example.com']);
+
+ const duplicate = await request(app).post('/api/github/accounts').send({ host: 'github.example.com', login: 'ALICE' });
+ expect(duplicate.status).toBe(409);
+ });
+
+ it('rejects hosts and logins that are not plain identifiers', async () => {
+ for (const body of [
+ { host: '--hostname=evil' },
+ { host: 'github.example.com/path' },
+ { host: 'github.example.com', login: '-x' },
+ { host: 'github.example.com', trust: 'trusted' },
+ ]) {
+ const res = await request(app).post('/api/github/accounts').send(body);
+ expect(res.status).toBe(400);
+ }
+ });
+
+ it('keeps an emptied account list authoritative instead of re-showing the implicit account', async () => {
+ expect((await request(app).delete('/api/github/accounts/github-com')).status).toBe(200);
+ expect((await request(app).get('/api/github/accounts')).body).toEqual([]);
+ expect((await request(app).delete('/api/github/accounts/github-com')).status).toBe(404);
+ });
+
+ it('refuses a corrupt store instead of overwriting it', async () => {
+ writeFileSync(ACCOUNTS_FILE, JSON.stringify({ version: 1, accounts: [{ id: 'x' }] }));
+ expect((await request(app).get('/api/github/accounts')).status).toBe(503);
+ expect((await request(app).post('/api/github/accounts').send({ host: 'github.com', login: 'bob' })).status).toBe(503);
+ });
+
+ describe('sign-in status', () => {
+ it('pins a named login through its own token and reports ok', async () => {
+ const { body: account } = await request(app).post('/api/github/accounts').send({ host: 'github.example.com', login: 'alice' });
+ vi.mocked(execGh).mockImplementation(async (args, _timeout, { env }) => {
+ if (args[0] === 'auth') return 'ghs_example';
+ expect(env.GH_ENTERPRISE_TOKEN).toBe('ghs_example');
+ expect(env.GH_HOST).toBe('github.example.com');
+ return 'alice';
+ });
+ const res = await request(app).get(`/api/github/accounts/${account.id}/status`);
+ expect(res.body).toEqual(expect.objectContaining({ status: 'ok', login: 'alice', remedy: null }));
+ });
+
+ it('names the login command when gh has no credential for the configured login', async () => {
+ const { body: account } = await request(app).post('/api/github/accounts').send({ host: 'github.example.com', login: 'alice' });
+ vi.mocked(execGh).mockRejectedValue(ghError('no oauth token found for github.example.com account alice'));
+ const res = await request(app).get(`/api/github/accounts/${account.id}/status`);
+ expect(res.body).toEqual(expect.objectContaining({ status: 'not-authenticated', command: 'gh auth login --hostname github.example.com --web --clipboard' }));
+ });
+
+ it('flags an active login that differs from the configured one', async () => {
+ await request(app).put('/api/github/accounts/github-com').send({ login: 'octocat' });
+ vi.mocked(execGh).mockImplementation(async (args) => (args[0] === 'auth' ? 'gho_example' : 'someone-else'));
+ const res = await request(app).get('/api/github/accounts/github-com/status');
+ expect(res.body).toEqual(expect.objectContaining({ status: 'wrong-account', login: 'someone-else' }));
+ });
+
+ it('classifies an unreachable Enterprise host for an account with no fixed login', async () => {
+ const { body: account } = await request(app).post('/api/github/accounts').send({ host: 'ghe.example.com' });
+ vi.mocked(execGh).mockRejectedValue(ghError('error connecting to ghe.example.com'));
+ const res = await request(app).get(`/api/github/accounts/${account.id}/status`);
+ expect(res.body.status).toBe('unreachable');
+ });
+ });
+});