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 a GitHub notifications inbox

Claude4d5829b4fe39
diff --git a/client/src/components/github/GitHubInboxTab.jsx b/client/src/components/github/GitHubInboxTab.jsx
new file mode 100644
index 0000000000..1dc2b4c9d8
--- /dev/null
+++ b/client/src/components/github/GitHubInboxTab.jsx
@@ -0,0 +1,232 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { ExternalLink, RefreshCw } from 'lucide-react';
+import Pill from '../ui/Pill';
+import LoadFailedState from '../ui/LoadFailedState';
+import PageSkeleton from '../ui/PageSkeleton';
+import CollapsibleListItem from '../ui/CollapsibleListItem';
+import { timeAgo } from '../../utils/formatters';
+import {
+ getGitHubAccounts,
+ getGitHubNotifications,
+ syncGitHubNotifications,
+ applyGitHubNotificationAction,
+} from '../../services/api';
+
+const VIEWS = [
+ { id: 'needs-you', label: 'Needs you' },
+ { id: 'handled', label: 'Handled' },
+ { id: 'all', label: 'All' },
+];
+
+// GitHub's `reason` vocabulary, phrased for a glance.
+const REASON_LABELS = {
+ assign: 'Assigned',
+ author: 'You opened',
+ ci_activity: 'CI',
+ comment: 'Comment',
+ invitation: 'Invitation',
+ manual: 'Subscribed',
+ mention: 'Mention',
+ review_requested: 'Review requested',
+ security_alert: 'Security alert',
+ state_change: 'State change',
+ subscribed: 'Watching',
+ team_mention: 'Team mention',
+};
+
+const STATE_LABELS = { done: 'Done', muted: 'Muted', unsubscribed: 'Unsubscribed' };
+
+const OPEN_ACTIONS = [
+ { action: 'done', label: 'Done' },
+ { action: 'mute', label: 'Mute' },
+ { action: 'unsubscribe', label: 'Unsubscribe' },
+];
+
+const chipClass = (active) => `shrink-0 rounded-full border px-3 py-1.5 text-xs ${active
+ ? 'border-port-accent/40 bg-port-accent/20 text-port-accent'
+ : 'border-port-border bg-port-bg text-gray-400'}`;
+
+// Whether a row still belongs in the view after an action moved it.
+const belongsInView = (row, view) => view === 'all' || (view === 'needs-you') === (row.state === 'open');
+
+function NotificationCard({ notification, accountLabel, busy, onAction }) {
+ const handled = notification.state !== 'open';
+ return (
+ <article className="min-w-0 rounded-lg border border-port-border bg-port-card p-3">
+ <div className="flex flex-wrap items-center gap-2 text-xs text-gray-400">
+ {notification.unread && <span className="h-2 w-2 shrink-0 rounded-full bg-port-accent" aria-label="Unread" />}
+ <span className="font-medium text-gray-300">{REASON_LABELS[notification.reason] || notification.reason}</span>
+ <span className="min-w-0 truncate font-mono">{notification.repoFullName}</span>
+ {notification.yourRepo && <Pill tone="accent">Your repo</Pill>}
+ {notification.repoPrivate && <Pill tone="muted">Private</Pill>}
+ {handled && <Pill tone="muted">{STATE_LABELS[notification.state] || notification.state}</Pill>}
+ <span className="ml-auto shrink-0">{timeAgo(notification.updatedAt)}</span>
+ </div>
+ <p className="mt-1.5 break-words text-sm text-white">{notification.title}</p>
+ {accountLabel && <p className="mt-0.5 text-xs text-gray-500">{accountLabel}</p>}
+ <div className="mt-2 flex flex-wrap gap-2">
+ {notification.htmlUrl && (
+ <a
+ href={notification.htmlUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex items-center gap-1 rounded border border-port-border px-3 py-1.5 text-xs text-gray-300"
+ >
+ <ExternalLink size={12} aria-hidden="true" /> Open
+ </a>
+ )}
+ {(handled ? [{ action: 'resubscribe', label: 'Back to inbox' }] : OPEN_ACTIONS).map(({ action, label }) => (
+ <button
+ key={action}
+ type="button"
+ disabled={busy}
+ onClick={() => onAction(notification, action)}
+ className="rounded border border-port-border px-3 py-1.5 text-xs text-gray-300 disabled:opacity-50"
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ </article>
+ );
+}
+
+export default function GitHubInboxTab() {
+ const [accounts, setAccounts] = useState(null);
+ const [accountId, setAccountId] = useState(null);
+ const [view, setView] = useState('needs-you');
+ const [data, setData] = useState(null);
+ const [loadFailed, setLoadFailed] = useState(false);
+ const [syncing, setSyncing] = useState(false);
+ const [busyKey, setBusyKey] = useState(null);
+ const [removing, setRemoving] = useState(() => new Set());
+ const [syncTick, setSyncTick] = useState(0);
+ const requestRef = useRef(0);
+
+ const keyOf = (row) => `${row.accountId}/${row.threadId}`;
+
+ const loadList = useCallback(async () => {
+ const requestId = ++requestRef.current;
+ const result = await getGitHubNotifications({ accountId, view }, { silent: true }).catch(() => null);
+ if (requestId !== requestRef.current) return;
+ if (!result) {
+ setLoadFailed(true);
+ return;
+ }
+ setLoadFailed(false);
+ setRemoving(new Set());
+ setData(result);
+ }, [accountId, view]);
+
+ const refresh = useCallback(async () => {
+ setSyncing(true);
+ // Per-account failures come back in the results and are shown from the
+ // stored sync state, so this never toasts.
+ await syncGitHubNotifications(accountId, { silent: true }).catch(() => null);
+ setSyncing(false);
+ setSyncTick((tick) => tick + 1);
+ }, [accountId]);
+
+ useEffect(() => {
+ // Accounts only label rows and add a filter; without them the inbox still works.
+ getGitHubAccounts({ silent: true }).then(setAccounts).catch(() => {});
+ }, []);
+
+ // Stored rows show at once; each finished sync re-reads them.
+ useEffect(() => { loadList(); }, [loadList, syncTick]);
+ useEffect(() => { refresh(); }, [refresh]);
+
+ const handleAction = async (row, action) => {
+ const key = keyOf(row);
+ setBusyKey(key);
+ const updated = await applyGitHubNotificationAction(row.accountId, row.threadId, action).catch(() => null);
+ setBusyKey(null);
+ if (!updated) return;
+ if (belongsInView(updated, view)) {
+ setData((prev) => ({ ...prev, notifications: prev.notifications.map((entry) => (keyOf(entry) === key ? updated : entry)) }));
+ } else {
+ setRemoving((prev) => new Set(prev).add(key));
+ }
+ };
+
+ const dropRow = (key) => {
+ setData((prev) => ({ ...prev, notifications: prev.notifications.filter((entry) => keyOf(entry) !== key) }));
+ setRemoving((prev) => {
+ const next = new Set(prev);
+ next.delete(key);
+ return next;
+ });
+ };
+
+ const enabledAccounts = (accounts || []).filter((account) => account.enabled);
+ const labelFor = (id) => (enabledAccounts.length > 1 ? accounts.find((account) => account.id === id)?.label : null);
+ const syncErrors = Object.entries(data?.sync || {}).filter(([id, state]) => state.lastError && (!accountId || id === accountId));
+ const lastSyncAt = Object.values(data?.sync || {}).map((state) => state.lastSyncAt).filter(Boolean).sort().at(-1);
+
+ if (loadFailed && !data) return <LoadFailedState title="Could not load GitHub notifications." hint="Retry the local inbox read." onRetry={loadList} />;
+ if (!data) return <PageSkeleton label="Loading GitHub notifications" titleWidthClass="w-40" showAction={false} cards={3} />;
+
+ return (
+ <div className="min-w-0 space-y-3">
+ <div className="flex items-center gap-2">
+ <div className="flex min-w-0 flex-1 gap-2 overflow-x-auto" role="group" aria-label="Inbox view">
+ {VIEWS.map((entry) => (
+ <button key={entry.id} type="button" aria-pressed={view === entry.id} onClick={() => setView(entry.id)} className={chipClass(view === entry.id)}>
+ {entry.label}
+ </button>
+ ))}
+ </div>
+ <button
+ type="button"
+ onClick={refresh}
+ disabled={syncing}
+ className="inline-flex shrink-0 items-center gap-1.5 rounded border border-port-border px-3 py-1.5 text-xs text-gray-300 disabled:opacity-60"
+ >
+ <RefreshCw size={12} className={syncing ? 'animate-spin' : ''} aria-hidden="true" />
+ {syncing ? 'Checking…' : 'Refresh'}
+ </button>
+ </div>
+
+ {enabledAccounts.length > 1 && (
+ <div className="flex gap-2 overflow-x-auto" role="group" aria-label="Account">
+ <button type="button" aria-pressed={!accountId} onClick={() => setAccountId(null)} className={chipClass(!accountId)}>All accounts</button>
+ {enabledAccounts.map((account) => (
+ <button key={account.id} type="button" aria-pressed={accountId === account.id} onClick={() => setAccountId(account.id)} className={chipClass(accountId === account.id)}>
+ {account.label}
+ </button>
+ ))}
+ </div>
+ )}
+
+ {syncErrors.map(([id, state]) => (
+ <p key={id} role="alert" className="rounded border border-port-error/40 bg-port-error/10 p-2 text-xs text-port-error break-words">
+ {accounts?.find((account) => account.id === id)?.label || id}: {state.lastError}
+ </p>
+ ))}
+
+ {data.notifications.length === 0 ? (
+ <p className="rounded-lg border border-port-border bg-port-card p-4 text-sm text-gray-400">
+ {view === 'needs-you' ? 'Nothing needs you right now.' : 'No notifications here.'}
+ </p>
+ ) : (
+ <div className="min-w-0">
+ {data.notifications.map((notification) => {
+ const key = keyOf(notification);
+ return (
+ <CollapsibleListItem key={key} removing={removing.has(key)} onExited={() => dropRow(key)}>
+ <NotificationCard
+ notification={notification}
+ accountLabel={labelFor(notification.accountId)}
+ busy={busyKey === key || removing.has(key)}
+ onAction={handleAction}
+ />
+ </CollapsibleListItem>
+ );
+ })}
+ </div>
+ )}
+
+ {lastSyncAt && <p className="text-xs text-gray-500">Checked {timeAgo(lastSyncAt)}</p>}
+ </div>
+ );
+}
diff --git a/client/src/pages/GitHub.jsx b/client/src/pages/GitHub.jsx
index 447647137a..44d10e6843 100644
--- a/client/src/pages/GitHub.jsx
+++ b/client/src/pages/GitHub.jsx
@@ -1,17 +1,19 @@
import { useParams } from 'react-router';
import RouteTabsHeader from '../components/ui/RouteTabsHeader';
import GitHubAccountsTab from '../components/github/GitHubAccountsTab';
+import GitHubInboxTab from '../components/github/GitHubInboxTab';
import GitHubReposTab from '../components/github/GitHubReposTab';
-// Inbox, Automations and Audit join as their phases ship (#12870–#12874).
+// Automations and Audit join as their phases ship (#12871–#12874).
export const GITHUB_PAGE_TABS = Object.freeze([
+ { id: 'inbox', label: 'Inbox', to: '/devtools/github/inbox' },
{ id: 'repos', label: 'Repos', to: '/devtools/github/repos' },
{ id: 'accounts', label: 'Accounts', to: '/devtools/github/accounts' },
]);
export default function GitHub() {
const { tab } = useParams();
- const activeTab = GITHUB_PAGE_TABS.some((entry) => entry.id === tab) ? tab : 'repos';
+ const activeTab = GITHUB_PAGE_TABS.some((entry) => entry.id === tab) ? tab : 'inbox';
return (
<div className="@container/page min-w-0 p-4 sm:p-6">
@@ -19,7 +21,9 @@ export default function GitHub() {
<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 />}
+ {activeTab === 'inbox' && <GitHubInboxTab />}
+ {activeTab === 'repos' && <GitHubReposTab />}
+ {activeTab === 'accounts' && <GitHubAccountsTab />}
</div>
);
}
diff --git a/client/src/pages/GitHub.test.jsx b/client/src/pages/GitHub.test.jsx
index 85be811366..c2751eabfb 100644
--- a/client/src/pages/GitHub.test.jsx
+++ b/client/src/pages/GitHub.test.jsx
@@ -17,12 +17,24 @@ const mock = vi.hoisted(() => ({
updateGitHubAccount: vi.fn(),
deleteGitHubAccount: vi.fn(),
getGitHubAccountStatus: vi.fn(),
+ getGitHubNotifications: vi.fn(),
+ syncGitHubNotifications: vi.fn(),
+ applyGitHubNotificationAction: vi.fn(),
}));
vi.mock('../services/api', () => mock);
import GitHub from './GitHub';
+const renderTab = (tab) => render(
+ <MemoryRouter initialEntries={[`/devtools/github/${tab}`]}>
+ <Routes>
+ <Route path="/devtools/github" element={<GitHub />} />
+ <Route path="/devtools/github/:tab" element={<GitHub />} />
+ </Routes>
+ </MemoryRouter>,
+);
+
describe('GitHub account setup', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -40,11 +52,7 @@ describe('GitHub account setup', () => {
it('distinguishes a failed repository read from a successful empty response', async () => {
mock.getGitHubRepos.mockRejectedValueOnce(new Error('offline')).mockResolvedValueOnce({});
- render(
- <MemoryRouter initialEntries={['/devtools/github']}>
- <GitHub />
- </MemoryRouter>,
- );
+ renderTab('repos');
expect(await screen.findByText('Could not load GitHub repositories.')).toBeInTheDocument();
expect(screen.queryByText('No repos loaded yet.')).not.toBeInTheDocument();
@@ -54,11 +62,7 @@ describe('GitHub account setup', () => {
});
it('offers an in-app GitHub login flow and prevents an anonymous repo sync', async () => {
- render(
- <MemoryRouter initialEntries={['/devtools/github']}>
- <GitHub />
- </MemoryRouter>,
- );
+ renderTab('repos');
const signIn = await screen.findByRole('link', { name: 'Sign in with GitHub' });
expect(decodeURIComponent(signIn.getAttribute('href'))).toContain('/shell?cmd=gh auth login');
@@ -76,11 +80,7 @@ describe('GitHub account setup', () => {
lastRepoSync: null,
});
- render(
- <MemoryRouter initialEntries={['/devtools/github']}>
- <GitHub />
- </MemoryRouter>,
- );
+ renderTab('repos');
expect(await screen.findByText(/cached from @legacy-owner/i)).toHaveTextContent(
'Sign in and sync to replace them',
@@ -98,11 +98,7 @@ describe('GitHub account setup', () => {
lastRepoSync: null,
});
- render(
- <MemoryRouter initialEntries={['/devtools/github']}>
- <GitHub />
- </MemoryRouter>,
- );
+ renderTab('repos');
expect(await screen.findByLabelText('GitHub account @example-user')).toBeTruthy();
expect(screen.queryByText('GitHub connected')).toBeNull();
@@ -123,11 +119,7 @@ describe('GitHub account setup', () => {
lastRepoSync: null,
});
- render(
- <MemoryRouter initialEntries={['/devtools/github']}>
- <GitHub />
- </MemoryRouter>,
- );
+ renderTab('repos');
expect(await screen.findByText(/environment credentials override stored gh accounts/i)).toBeTruthy();
expect(screen.queryByRole('link', { name: /GitHub account/ })).toBeNull();
@@ -145,11 +137,7 @@ describe('GitHub account setup', () => {
lastRepoSync: null,
});
- render(
- <MemoryRouter initialEntries={['/devtools/github']}>
- <GitHub />
- </MemoryRouter>,
- );
+ renderTab('repos');
expect(await screen.findByText('GitHub environment credential rejected')).toBeTruthy();
expect(screen.queryByRole('link', { name: 'Sign in with GitHub' })).toBeNull();
@@ -159,11 +147,7 @@ describe('GitHub account setup', () => {
it('distinguishes an unavailable status check from signed out and disables sync', async () => {
mock.getGitHubStatus.mockRejectedValue(new Error('status unavailable'));
- render(
- <MemoryRouter initialEntries={['/devtools/github']}>
- <GitHub />
- </MemoryRouter>,
- );
+ renderTab('repos');
expect(await screen.findByText('GitHub status unavailable')).toBeTruthy();
expect(screen.queryByRole('link', { name: 'Sign in with GitHub' })).toBeNull();
@@ -182,11 +166,7 @@ describe('GitHub account setup', () => {
lastRepoSync: null,
});
- render(
- <MemoryRouter initialEntries={['/devtools/github']}>
- <GitHub />
- </MemoryRouter>,
- );
+ renderTab('repos');
fireEvent.click(await screen.findByRole('button', { name: 'Retry' }));
expect(await screen.findByText('@example-user')).toBeTruthy();
@@ -208,11 +188,7 @@ describe('GitHub account setup', () => {
truncated: true,
});
- render(
- <MemoryRouter initialEntries={['/devtools/github']}>
- <GitHub />
- </MemoryRouter>,
- );
+ renderTab('repos');
fireEvent.click(await screen.findByRole('button', { name: 'Sync Repos' }));
expect(await screen.findByText(/200-repository limit/i)).toBeTruthy();
@@ -229,11 +205,7 @@ describe('GitHub account setup', () => {
lastRepoSync: null,
});
- render(
- <MemoryRouter initialEntries={['/devtools/github']}>
- <GitHub />
- </MemoryRouter>,
- );
+ renderTab('repos');
expect(await screen.findByText('GitHub status unavailable')).toBeTruthy();
expect(screen.queryByRole('link', { name: 'Sign in with GitHub' })).toBeNull();
@@ -251,11 +223,7 @@ describe('GitHub account setup', () => {
lastRepoSync: null,
});
- render(
- <MemoryRouter initialEntries={['/devtools/github']}>
- <GitHub />
- </MemoryRouter>,
- );
+ renderTab('repos');
expect(await screen.findByText('GitHub CLI required')).toBeTruthy();
expect(screen.queryByRole('link', { name: 'Sign in with GitHub' })).toBeNull();
@@ -286,11 +254,7 @@ describe('GitHub account setup', () => {
lastRepoSync: null,
});
- render(
- <MemoryRouter initialEntries={['/devtools/github']}>
- <GitHub />
- </MemoryRouter>,
- );
+ renderTab('repos');
expect(await screen.findByText(/cached from @legacy-owner/i)).toBeTruthy();
expect(screen.getByRole('button', { name: 'Archive' })).toBeDisabled();
@@ -300,13 +264,7 @@ describe('GitHub account setup', () => {
});
});
-const renderAccounts = () => render(
- <MemoryRouter initialEntries={['/devtools/github/accounts']}>
- <Routes>
- <Route path="/devtools/github/:tab" element={<GitHub />} />
- </Routes>
- </MemoryRouter>,
-);
+const renderAccounts = () => renderTab('accounts');
const IMPLICIT = {
id: 'github-com', label: 'github.com', host: 'github.com', login: null,
@@ -359,3 +317,44 @@ describe('GitHub accounts tab', () => {
expect(await screen.findByText('No GitHub accounts yet.')).toBeTruthy();
});
});
+
+const NOTIFICATION = {
+ accountId: 'github-com', threadId: '101', repoFullName: 'octocat/hello', repoPrivate: false, yourRepo: true,
+ reason: 'review_requested', subjectType: 'PullRequest', title: 'Example change', htmlUrl: 'https://github.com/octocat/hello/pull/7',
+ unread: true, state: 'open', updatedAt: '2026-10-01T10:00:00.000Z',
+};
+
+describe('GitHub inbox tab', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mock.getGitHubAccounts.mockResolvedValue([IMPLICIT]);
+ mock.syncGitHubNotifications.mockResolvedValue({ results: [] });
+ mock.getGitHubNotifications.mockResolvedValue({ notifications: [NOTIFICATION], sync: {} });
+ });
+
+ it('opens by default, syncs on arrival, and links only to the stored GitHub page', async () => {
+ renderTab('');
+ expect(await screen.findByText('Example change')).toBeTruthy();
+ expect(screen.getByText('Review requested')).toBeTruthy();
+ expect(screen.getByText('Your repo')).toBeTruthy();
+ expect(screen.getByRole('link', { name: 'Open' }).getAttribute('href')).toBe(NOTIFICATION.htmlUrl);
+ expect(mock.syncGitHubNotifications).toHaveBeenCalledWith(null, { silent: true });
+ expect(mock.getGitHubRepos).not.toHaveBeenCalled();
+ });
+
+ it('marks a thread done and takes it out of Needs you', async () => {
+ mock.applyGitHubNotificationAction.mockResolvedValue({ ...NOTIFICATION, state: 'done', unread: false });
+ renderTab('inbox');
+ fireEvent.click(await screen.findByRole('button', { name: 'Done' }));
+ expect(mock.applyGitHubNotificationAction).toHaveBeenCalledWith('github-com', '101', 'done');
+ expect(await screen.findByText('Nothing needs you right now.')).toBeTruthy();
+ });
+
+ it('shows a failed sync for the account instead of an empty inbox', async () => {
+ mock.getGitHubNotifications.mockResolvedValue({
+ notifications: [], sync: { 'github-com': { lastSyncAt: null, lastError: 'gh cannot act as github.com (not-authenticated).' } },
+ });
+ renderTab('inbox');
+ expect((await screen.findByRole('alert')).textContent).toContain('not-authenticated');
+ });
+});
diff --git a/client/src/services/apiGithub.js b/client/src/services/apiGithub.js
index 9c7d2d5f4f..4f5ec8325a 100644
--- a/client/src/services/apiGithub.js
+++ b/client/src/services/apiGithub.js
@@ -28,3 +28,18 @@ 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);
+
+// Notifications inbox: rows are stored server-side; sync fetches fresh ones.
+export const getGitHubNotifications = ({ accountId, view } = {}, options = {}) => {
+ const params = new URLSearchParams();
+ if (accountId) params.set('accountId', accountId);
+ if (view) params.set('view', view);
+ const qs = params.toString();
+ return request(`/github/notifications${qs ? `?${qs}` : ''}`, options);
+};
+export const syncGitHubNotifications = (accountId = null, options = {}) =>
+ request('/github/notifications/sync', { method: 'POST', body: JSON.stringify(accountId ? { accountId } : {}), ...options });
+export const applyGitHubNotificationAction = (accountId, threadId, action, options = {}) =>
+ request(`/github/notifications/${encodeURIComponent(accountId)}/${encodeURIComponent(threadId)}`, {
+ method: 'POST', body: JSON.stringify({ action }), ...options,
+ });
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 8d7142145d..4603f5fbc5 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -610,6 +610,8 @@ Optional SDK environments under `data/venvs/` are machine-local, regenerable run
`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`.
+The notifications inbox (#12870) is `db-primary`: `github_notifications` holds one row per thread per account (repo, reason, subject title/type, a link rebuilt on the account's own host, unread flag, GitHub's `updated_at`, and the local `state` `open` | `done` | `muted` | `unsubscribed`), keyed `(account_id, thread_id)`; `github_notification_sync` holds each account's `Last-Modified` cursor, `X-Poll-Interval` and last error. The rows are queried by account, state and recency and later phases join triage results to them, so they live in Postgres. Like the accounts they describe they are machine-local and never federated. Only notification metadata is stored; no thread body or linked page is fetched. Code: `server/services/githubNotifications.js`, schema `server/lib/db/schema/githubNotifications.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/scripts/lib/dbTestFiles.js b/scripts/lib/dbTestFiles.js
index 5e6badc765..0aefa58339 100644
--- a/scripts/lib/dbTestFiles.js
+++ b/scripts/lib/dbTestFiles.js
@@ -55,6 +55,7 @@ export const DB_TEST_INCLUDE = [
'services/tribe.db.test.js',
'services/tribePurge.db.test.js',
'services/beeperSync.db.test.js',
+ 'services/githubNotifications.db.test.js',
'services/creativeDirector/projectsDB.test.js',
'services/musicVideo/projectsDB.test.js',
'routes/catalog.test.js',
diff --git a/server/lib/README.md b/server/lib/README.md
index 99f052f7a9..c2c915fa79 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -472,6 +472,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `gitForge.js` | `parseGitRemote`, `parseGitHubOwnerFromRemote`, `pickGhAccountForOwner`, `detectForgeCli`, `parsePullRequestUrl` — GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by `git.js`. Pure except that `parseGitRemote` canonicalizes an ssh `Host` alias through `sshHostAlias.js`. |
| `sshHostAlias.js` | `resolveSshHostAlias`, `parseSshHostAliases` — resolves a personal SSH `Host` alias (`git@github-acme:…`, backed by `HostName github.com` in `~/.ssh/config`) to the host a remote actually connects to. Every remote-URL host parser (`gitForge.parseGitRemote`, `gitRemote.parseGitRemoteUrl`, `workTracker.hostFromOriginUrl`) canonicalizes through it, so multi-account checkouts classify as GitHub instead of an unreachable unknown host. |
| `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. `extractAgentSummary` anchors on `agentOutputMarkers`' completion marker so a TUI agent's PR body carries its sentinel summary, not the lifecycle telemetry above it. `isBenignConcurrentFetchRefRace(stderr)` reads a non-zero `git fetch` as a SUCCESS when its only failure is a lost compare-and-swap whose refs already hold the fetched commits — the routine outcome when the Git tab, `getRemoteBranches`, and CoS agent worktrees fetch one `.git` at once. |
+| `githubNotificationParse.js` | `parseGhIncludeOutput`, `linkHeaderHasNext`, `pollIntervalSeconds`, `toNotificationRecord` — pure parsing for the GitHub notifications inbox: `gh api --include` output and thread records, with links rebuilt only onto the account's own GitHub host. |
| `gitRemote.js` | `getOriginInfo`, `classifyOriginRemote`, `parseGitRemoteUrl`, `readRemoteUrl`, `isUpstreamOwner`, `isUpstreamFullName`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — safely reads and classifies checkout remotes against PortOS or a caller-supplied canonical upstream. Used by self-update and managed integrations to detect forks. |
| `gitStaleLock.js` | `gitLockPathFromError`, `isStaleGitLock`, `clearStaleGitLock`, `clearStaleGitLocksIn`, `STALE_GIT_LOCK_MIN_AGE_MS` — recognizes the `*.lock` a KILLED git process left behind and removes it so the caller can retry. A lock under `.git/modules/<submodule>/` is shared by every worktree of the repo, so one dead process wedges submodule checkout install-wide with a bogus "another git process is running". Removal requires a `.lock` path under a `.git` directory (so a malformed message cannot aim the unlink at `yarn.lock`) that is older than 30 minutes — 3x the longest git command PortOS runs (`worktreeManager.WORKTREE_ADD_TIMEOUT_MS`, pinned by a test), which is what keeps it from deleting a LIVE competitor's lock. The threshold is deliberately not a parameter. `clearStaleGitLock(message)` is the reactive form, wired into `services/gitSubmodules.js#updateSubmodule` and `worktreeManager.addWorktreeWithRetry`; `clearStaleGitLocksIn(gitDir)` sweeps ahead of `update.sh`/`update.ps1`, the most likely producer. `scripts/doctor.js` reports one as the blocker. |
| `repoLinkFields.js` | `deriveRepoLinkFields(url)` / `normalizeRepoLinkFields(link)` / `linkIsRepo(link)` / `repoLinkLabel(link)` — the repository metadata a Brain link carries, plus the dual-write/tolerant-read shim that keeps the pre-multi-host `isGitHubRepo` field names readable across federated peers. |
diff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.md
index eebe9ebc71..583d350a96 100644
--- a/server/lib/db/schema/README.md
+++ b/server/lib/db/schema/README.md
@@ -48,6 +48,7 @@ init-db.sql, each with a one-line reason.
| `stackerNews.js` | `stackerNewsDdl` | Stacker News accounts, territories, untrusted-content analyses, and review-gated actions |
| `x.js` | `xDdl` | X account diagnostics, public post metrics, and review-gated drafts |
| `beeper.js` | `beeperDdl` | Beeper conversation mirror — accounts, the vault-encrypted access credential, conversations, messages, participants, attachment metadata, sync cursors, and the outbound send outbox (machine-local, never federated) |
+| `githubNotifications.js` | `githubNotificationsDdl` | GitHub notifications inbox — per-account notification threads (metadata only) and the fetch cursor (machine-local, never federated) |
| `audit.js` | `auditDdl`, `auditedTables`, `buildAuditTriggers()` | `record_audit` table/function + per-table audit triggers |
| `syncFeed.js` | `syncFeedDdl`, `syncFeedTables`, `buildSyncFeedTriggers()` | Commit-ordered federation change feed (`sync_feed`) + deferred capture triggers on memories and the catalog tables (#8315) |
@@ -56,7 +57,7 @@ init-db.sql, each with a one-line reason.
- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `post` → `commissions` → `userActions` → `reviewQueueTriage` → `cosAgentFeedback` → `cosTasks` → `cosAgents` → `aiGraph` → `peerExecution`).
- `buildCatalogDdl()` → phase-2 list (`catalog` → `media` → `catalogUserTypes` →
`universes` → `library` → `pipeline` → `writersRoom` → `lora` → `privacy` → `stackerNews` → `x` →
- `beeper` → `audit` DDL → audit triggers → `syncFeed` DDL → sync-feed triggers).
+ `beeper` → `githubNotifications` → `audit` DDL → audit triggers → `syncFeed` DDL → sync-feed triggers).
`ensureSchemaImpl()` calls these two builders and runs each list through
`pool.query` in order.
diff --git a/server/lib/db/schema/githubNotifications.js b/server/lib/db/schema/githubNotifications.js
new file mode 100644
index 0000000000..1ef595736b
--- /dev/null
+++ b/server/lib/db/schema/githubNotifications.js
@@ -0,0 +1,39 @@
+// GitHub notifications inbox (#12870). Machine-local mirror of each configured
+// GitHub account's notification threads (`data/github-accounts.json`), plus
+// the per-account fetch cursor. NEVER FEDERATED: which threads a login sees is
+// a property of that login on that machine, and triage state written by one
+// machine's automations must not replay on another.
+//
+// Thread text is metadata GitHub sends (repo, reason, subject title/type and
+// API urls); bodies are never stored here. `state` is the operator's (or a
+// later automation's) disposition; `unread` mirrors GitHub.
+export const githubNotificationsDdl = [
+ `CREATE TABLE IF NOT EXISTS github_notifications (
+ account_id TEXT NOT NULL,
+ thread_id TEXT NOT NULL,
+ repo_full_name TEXT NOT NULL,
+ repo_owner TEXT NOT NULL DEFAULT '',
+ repo_private BOOLEAN NOT NULL DEFAULT FALSE,
+ reason TEXT NOT NULL DEFAULT '',
+ subject_type TEXT NOT NULL DEFAULT '',
+ subject_title TEXT NOT NULL DEFAULT '',
+ subject_api_url TEXT,
+ html_url TEXT NOT NULL DEFAULT '',
+ unread BOOLEAN NOT NULL DEFAULT TRUE,
+ gh_updated_at TIMESTAMPTZ NOT NULL,
+ state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open','done','muted','unsubscribed')),
+ state_changed_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ PRIMARY KEY (account_id, thread_id)
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_github_notifications_account_updated ON github_notifications (account_id, gh_updated_at DESC)`,
+ `CREATE TABLE IF NOT EXISTS github_notification_sync (
+ account_id TEXT PRIMARY KEY,
+ last_modified TEXT,
+ poll_interval_seconds INTEGER,
+ last_sync_at TIMESTAMPTZ,
+ last_error TEXT NOT NULL DEFAULT '',
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+];
diff --git a/server/lib/db/schema/index.js b/server/lib/db/schema/index.js
index 4e5a88d6cb..c90585e019 100644
--- a/server/lib/db/schema/index.js
+++ b/server/lib/db/schema/index.js
@@ -40,6 +40,7 @@ import { xDdl } from './x.js';
import { mindToolRecipesDdl } from './mindToolRecipes.js';
import { decksDdl } from './decks.js';
import { beeperDdl } from './beeper.js';
+import { githubNotificationsDdl } from './githubNotifications.js';
import { auditDdl, auditedTables, buildAuditTriggers } from './audit.js';
import { syncFeedDdl, syncFeedTables, buildSyncFeedTriggers } from './syncFeed.js';
@@ -72,6 +73,7 @@ export {
stackerNewsDdl,
xDdl,
beeperDdl,
+ githubNotificationsDdl,
mindToolRecipesDdl,
decksDdl,
auditDdl,
@@ -126,6 +128,7 @@ export function buildCatalogDdl() {
...stackerNewsDdl,
...xDdl,
...beeperDdl,
+ ...githubNotificationsDdl,
...mindToolRecipesDdl,
...decksDdl,
...auditDdl,
diff --git a/server/lib/githubNotificationParse.js b/server/lib/githubNotificationParse.js
new file mode 100644
index 0000000000..f293e110de
--- /dev/null
+++ b/server/lib/githubNotificationParse.js
@@ -0,0 +1,98 @@
+/**
+ * Pure parsing for the GitHub notifications inbox (#12870): `gh api --include`
+ * output and the thread records GitHub returns. Every field here is external
+ * data — titles are shown as text, and the only link kept is one rebuilt from
+ * GitHub's own API url that lands on the account's own web host.
+ */
+import { z } from 'zod';
+
+const THREAD_ID_RE = /^\d{1,20}$/;
+const REPO_PART_RE = /^[A-Za-z0-9_.-]{1,100}$/;
+const MAX_TITLE_CHARS = 500;
+
+/**
+ * Split `gh api --include` stdout into status, lower-cased headers and body.
+ * Returns null for output that does not start with an HTTP status line.
+ */
+export function parseGhIncludeOutput(text) {
+ const raw = String(text ?? '');
+ const split = raw.search(/\r?\n\r?\n/);
+ const head = split === -1 ? raw : raw.slice(0, split);
+ const body = split === -1 ? '' : raw.slice(split).replace(/^\r?\n\r?\n/, '');
+ const [statusLine, ...headerLines] = head.split(/\r?\n/);
+ const status = statusLine.match(/^HTTP\/[\d.]+\s+(\d{3})\b/);
+ if (!status) return null;
+ const headers = {};
+ for (const line of headerLines) {
+ const colon = line.indexOf(':');
+ if (colon > 0) headers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim();
+ }
+ return { status: Number(status[1]), headers, body };
+}
+
+export const linkHeaderHasNext = (link) => /<[^>]+>;\s*rel="next"/.test(String(link || ''));
+
+/** `X-Poll-Interval` in seconds, or null when absent or nonsensical. */
+export function pollIntervalSeconds(value) {
+ const seconds = Number.parseInt(value, 10);
+ return Number.isInteger(seconds) && seconds > 0 && seconds <= 86_400 ? seconds : null;
+}
+
+const webHostFor = (host) => (host === 'github.com' ? 'github.com' : host);
+const apiPrefixFor = (host) => (host === 'github.com' ? 'https://api.github.com/repos/' : `https://${host}/api/v3/repos/`);
+
+const SUBJECT_PATHS = { issues: 'issues', pulls: 'pull', commits: 'commit', discussions: 'discussions' };
+
+/**
+ * The browser link for a thread on the account's own host: the subject's page
+ * when GitHub gave an API url we recognize, else the repository page. Any url
+ * that would leave `host` is dropped rather than shown.
+ */
+function notificationHtmlUrl({ subjectApiUrl, repoFullName }, host) {
+ const [owner, repo] = String(repoFullName || '').split('/');
+ if (!REPO_PART_RE.test(owner || '') || !REPO_PART_RE.test(repo || '')) return '';
+ const repoUrl = `https://${webHostFor(host)}/${owner}/${repo}`;
+ const prefix = `${apiPrefixFor(host)}${owner}/${repo}/`;
+ if (typeof subjectApiUrl !== 'string' || !subjectApiUrl.startsWith(prefix)) return repoUrl;
+ const [kind, id, ...rest] = subjectApiUrl.slice(prefix.length).split('/');
+ if (rest.length || !/^[A-Za-z0-9]{1,64}$/.test(id || '')) return repoUrl;
+ if (kind === 'releases') return `${repoUrl}/releases`;
+ return SUBJECT_PATHS[kind] ? `${repoUrl}/${SUBJECT_PATHS[kind]}/${id}` : repoUrl;
+}
+
+const rawThreadSchema = z.object({
+ id: z.string().regex(THREAD_ID_RE),
+ unread: z.boolean(),
+ reason: z.string().max(64),
+ updated_at: z.string().datetime({ offset: true }),
+ subject: z.object({
+ title: z.string(),
+ type: z.string().max(64),
+ url: z.string().max(2000).nullable().optional(),
+ }).passthrough(),
+ repository: z.object({
+ full_name: z.string().max(201),
+ private: z.boolean().optional(),
+ owner: z.object({ login: z.string().max(100) }).passthrough(),
+ }).passthrough(),
+}).passthrough();
+
+/** A stored-shape record from one raw API thread, or null when malformed. */
+export function toNotificationRecord(raw, host) {
+ const parsed = rawThreadSchema.safeParse(raw);
+ if (!parsed.success) return null;
+ const { id, unread, reason, updated_at: updatedAt, subject, repository } = parsed.data;
+ const record = {
+ threadId: id,
+ repoFullName: repository.full_name,
+ repoOwner: repository.owner.login,
+ repoPrivate: repository.private === true,
+ reason,
+ subjectType: subject.type,
+ subjectTitle: Array.from(subject.title).slice(0, MAX_TITLE_CHARS).join(''),
+ subjectApiUrl: subject.url || null,
+ unread,
+ ghUpdatedAt: updatedAt,
+ };
+ return { ...record, htmlUrl: notificationHtmlUrl(record, host) };
+}
diff --git a/server/lib/githubNotificationParse.test.js b/server/lib/githubNotificationParse.test.js
new file mode 100644
index 0000000000..63aed461f1
--- /dev/null
+++ b/server/lib/githubNotificationParse.test.js
@@ -0,0 +1,54 @@
+import { describe, it, expect } from 'vitest';
+import { parseGhIncludeOutput, toNotificationRecord } from './githubNotificationParse.js';
+
+const notificationHtmlUrl = ({ repoFullName, subjectApiUrl }, host) => toNotificationRecord({
+ id: '1', unread: true, reason: 'mention', updated_at: '2026-10-01T10:00:00Z',
+ subject: { title: 'Example', type: 'PullRequest', url: subjectApiUrl },
+ repository: { full_name: repoFullName, owner: { login: 'octocat' } },
+}, host).htmlUrl;
+
+describe('thread links', () => {
+ const repoFullName = 'octocat/hello';
+
+ it('maps recognized API urls to the subject page on the account host', () => {
+ expect(notificationHtmlUrl({ repoFullName, subjectApiUrl: 'https://api.github.com/repos/octocat/hello/pulls/7' }, 'github.com'))
+ .toBe('https://github.com/octocat/hello/pull/7');
+ expect(notificationHtmlUrl({ repoFullName, subjectApiUrl: 'https://ghe.example.com/api/v3/repos/octocat/hello/issues/3' }, 'ghe.example.com'))
+ .toBe('https://ghe.example.com/octocat/hello/issues/3');
+ expect(notificationHtmlUrl({ repoFullName, subjectApiUrl: 'https://api.github.com/repos/octocat/hello/releases/99' }, 'github.com'))
+ .toBe('https://github.com/octocat/hello/releases');
+ });
+
+ it('never links off the account host and falls back to the repo page', () => {
+ for (const subjectApiUrl of [
+ 'https://evil.example.com/repos/octocat/hello/pulls/7',
+ 'https://api.github.com/repos/other/repo/pulls/7',
+ 'https://api.github.com/repos/octocat/hello/pulls/7/../../x',
+ null,
+ ]) {
+ expect(notificationHtmlUrl({ repoFullName, subjectApiUrl }, 'github.com')).toBe('https://github.com/octocat/hello');
+ }
+ expect(notificationHtmlUrl({ repoFullName: 'bad owner/x', subjectApiUrl: null }, 'github.com')).toBe('');
+ });
+});
+
+describe('parseGhIncludeOutput', () => {
+ it('splits status, lower-cased headers and body', () => {
+ expect(parseGhIncludeOutput('HTTP/2.0 200 OK\r\nX-Poll-Interval: 60\r\n\r\n[]'))
+ .toEqual({ status: 200, headers: { 'x-poll-interval': '60' }, body: '[]' });
+ expect(parseGhIncludeOutput('[]')).toBeNull();
+ });
+});
+
+describe('toNotificationRecord', () => {
+ it('rejects malformed threads and caps long titles', () => {
+ expect(toNotificationRecord({ id: 'x' }, 'github.com')).toBeNull();
+ const record = toNotificationRecord({
+ id: '1', unread: true, reason: 'mention', updated_at: '2026-10-01T10:00:00Z',
+ subject: { title: '🙂'.repeat(600), type: 'Issue', url: null },
+ repository: { full_name: 'octocat/hello', owner: { login: 'octocat' } },
+ }, 'github.com');
+ expect(Array.from(record.subjectTitle)).toHaveLength(500);
+ expect(record.repoPrivate).toBe(false);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index d5f0e6a5a3..0099c5da19 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -431,6 +431,7 @@ export * from './gitForge.js';
export * from './gitOutputParsers.js';
export * from './gitRemote.js';
export * from './gitStaleLock.js';
+export * from './githubNotificationParse.js';
export * from './repoUrl.js';
export * from './glabArgs.js';
export * from './goalFeatureMap.js';
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 8810b7fd9c..b054cecff8 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -221,6 +221,7 @@ const RAW_NAV_COMMANDS = [
{ 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-inbox', path: '/devtools/github/inbox', label: 'GitHub Inbox', section: 'Dev Tools', aliases: ['github-inbox', 'github-notifications'], keywords: ['github', 'notifications', 'inbox', 'mentions', 'review requests', 'mute', 'unsubscribe'] },
{ 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'] },
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 093cd0471f..7180a9a9ef 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -966,6 +966,22 @@ export const githubAccountCreateSchema = z.object({
export const githubAccountUpdateSchema = githubAccountCreateSchema.partial().strict();
+// GitHub notifications inbox (#12870).
+export const githubNotificationsQuerySchema = z.object({
+ accountId: z.string().trim().min(1).max(100).optional(),
+ view: z.enum(['needs-you', 'handled', 'all']).optional(),
+}).strict();
+
+export const githubNotificationsSyncSchema = z.object({
+ accountId: z.string().trim().min(1).max(100).optional(),
+}).strict();
+
+export const githubNotificationActionSchema = z.object({
+ action: z.enum(['read', 'done', 'mute', 'unsubscribe', 'resubscribe']),
+}).strict();
+
+export const GITHUB_NOTIFICATION_THREAD_ID_RE = /^\d{1,20}$/;
+
// =============================================================================
// INSIGHTS SCHEMAS
// =============================================================================
diff --git a/server/routes/github.js b/server/routes/github.js
index c5add2bd98..b428890fc7 100644
--- a/server/routes/github.js
+++ b/server/routes/github.js
@@ -1,8 +1,10 @@
import express from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { validateRequest, githubRepoUpdateSchema, githubSecretSchema, githubAccountCreateSchema, githubAccountUpdateSchema } from '../lib/validation.js';
+import { validateRequest, githubRepoUpdateSchema, githubSecretSchema, githubAccountCreateSchema, githubAccountUpdateSchema,
+ githubNotificationsQuerySchema, githubNotificationsSyncSchema, githubNotificationActionSchema, GITHUB_NOTIFICATION_THREAD_ID_RE } from '../lib/validation.js';
import * as githubService from '../services/github.js';
import * as githubAccounts from '../services/githubAccounts.js';
+import * as githubNotifications from '../services/githubNotifications.js';
const router = express.Router();
@@ -124,4 +126,34 @@ router.get('/accounts/:id/status', asyncHandler(async (req, res) => {
res.json(await githubAccounts.getAccountStatus(req.params.id));
}));
+/**
+ * GET /api/github/notifications — stored inbox rows for one or every account
+ */
+router.get('/notifications', asyncHandler(async (req, res) => {
+ const { accountId, view } = validateRequest(githubNotificationsQuerySchema, req.query);
+ res.json(await githubNotifications.listNotifications({ accountId, view }));
+}));
+
+/**
+ * POST /api/github/notifications/sync — fetch unread notifications from GitHub
+ */
+router.post('/notifications/sync', asyncHandler(async (req, res) => {
+ const { accountId } = validateRequest(githubNotificationsSyncSchema, req.body ?? {});
+ const results = accountId
+ ? [{ ...(await githubNotifications.syncAccountNotifications(accountId)), ok: true }]
+ : await githubNotifications.syncAllNotifications();
+ res.json({ results });
+}));
+
+/**
+ * POST /api/github/notifications/:accountId/:threadId — done / read / mute / unsubscribe / resubscribe
+ */
+router.post('/notifications/:accountId/:threadId', asyncHandler(async (req, res) => {
+ const { action } = validateRequest(githubNotificationActionSchema, req.body ?? {});
+ if (!GITHUB_NOTIFICATION_THREAD_ID_RE.test(req.params.threadId)) {
+ throw new ServerError('Invalid notification thread id', { status: 400 });
+ }
+ res.json(await githubNotifications.applyNotificationAction(req.params.accountId, req.params.threadId, action));
+}));
+
export default router;
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index e1227cef81..379f932c19 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -1913,6 +1913,37 @@ CREATE TABLE IF NOT EXISTS x_drafts (
);
CREATE INDEX IF NOT EXISTS idx_x_drafts_account_state ON x_drafts (account_id, state, created_at DESC);
+-- GitHub notifications inbox (#12870): machine-local, never federated.
+CREATE TABLE IF NOT EXISTS github_notifications (
+ account_id TEXT NOT NULL,
+ thread_id TEXT NOT NULL,
+ repo_full_name TEXT NOT NULL,
+ repo_owner TEXT NOT NULL DEFAULT '',
+ repo_private BOOLEAN NOT NULL DEFAULT FALSE,
+ reason TEXT NOT NULL DEFAULT '',
+ subject_type TEXT NOT NULL DEFAULT '',
+ subject_title TEXT NOT NULL DEFAULT '',
+ subject_api_url TEXT,
+ html_url TEXT NOT NULL DEFAULT '',
+ unread BOOLEAN NOT NULL DEFAULT TRUE,
+ gh_updated_at TIMESTAMPTZ NOT NULL,
+ state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open','done','muted','unsubscribed')),
+ state_changed_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ PRIMARY KEY (account_id, thread_id)
+);
+CREATE INDEX IF NOT EXISTS idx_github_notifications_account_updated ON github_notifications (account_id, gh_updated_at DESC);
+
+CREATE TABLE IF NOT EXISTS github_notification_sync (
+ account_id TEXT PRIMARY KEY,
+ last_modified TEXT,
+ poll_interval_seconds INTEGER,
+ last_sync_at TIMESTAMPTZ,
+ last_error TEXT NOT NULL DEFAULT '',
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+);
+
-- Beeper conversation mirror (#27). Machine-local mirror of the Beeper Desktop
-- API — accounts, conversations, messages, participants, attachment metadata,
-- and per-chat sync cursors. NEVER FEDERATED: no sync_sequence column, no
diff --git a/server/services/githubAccounts.js b/server/services/githubAccounts.js
index f990c46735..c3db512909 100644
--- a/server/services/githubAccounts.js
+++ b/server/services/githubAccounts.js
@@ -109,7 +109,7 @@ export async function listAccounts() {
return currentAccounts(await loadStore());
}
-async function getAccount(id) {
+export async function getAccount(id) {
const account = (await listAccounts()).find((entry) => entry.id === id);
if (!account) throw notFound(id);
return account;
@@ -185,7 +185,7 @@ const TOKEN_LOOKUP_FAULTS = new Set(['not-installed', 'unreachable']);
* 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 } = {}) {
+export async function resolveGitHubAccountEnv(account, { baseEnv = process.env } = {}) {
const env = { ...baseEnv, GH_HOST: account.host };
if (!account.login) return { env };
const lookup = await execGh(
diff --git a/server/services/githubNotifications.db.test.js b/server/services/githubNotifications.db.test.js
new file mode 100644
index 0000000000..ab4c20d384
--- /dev/null
+++ b/server/services/githubNotifications.db.test.js
@@ -0,0 +1,151 @@
+/**
+ * Postgres-backed tests for the GitHub notifications inbox (#12870): the
+ * upsert/reopen/read-reconcile SQL and the action mirror only run here against
+ * real constraints. `gh` is the only mocked boundary; the account store is the
+ * real one on a temp data root. Runs via `npm run test:db` (portos_test only).
+ */
+import { describe, it, expect, afterAll, beforeEach, vi } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
+import { checkHealth, ensureSchema, close, query } from '../lib/db.js';
+import { requireDbOrSkip } from '../lib/dbTestGate.js';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'github-notifications-test-'));
+
+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 { createAccount } = await import('./githubAccounts.js');
+const { syncAccountNotifications, listNotifications, applyNotificationAction } = await import('./githubNotifications.js');
+
+let dbReady = false;
+let skipReason = '';
+{
+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));
+ if (!health.connected) {
+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;
+ } else {
+ await ensureSchema().catch(() => {});
+ dbReady = true;
+ }
+}
+const runDb = requireDbOrSkip('services/githubNotifications.db.test', dbReady, skipReason);
+
+const accountIds = [];
+
+const thread = (id, { updatedAt = '2026-10-01T10:00:00Z', owner = 'octocat', repo = 'hello', title = `Thread ${id}` } = {}) => ({
+ id,
+ unread: true,
+ reason: 'mention',
+ updated_at: updatedAt,
+ subject: { title, type: 'PullRequest', url: `https://api.github.com/repos/${owner}/${repo}/pulls/${id}` },
+ repository: { full_name: `${owner}/${repo}`, private: false, owner: { login: owner } },
+});
+
+const listing = (threads, headers = {}) => [
+ 'HTTP/2.0 200 OK',
+ 'Last-Modified: Thu, 01 Oct 2026 10:00:00 GMT',
+ 'X-Poll-Interval: 60',
+ ...Object.entries(headers).map(([key, value]) => `${key}: ${value}`),
+ '',
+ JSON.stringify(threads),
+].join('\r\n');
+
+// Routes gh calls: token lookup, the listing (via `respond`), and thread actions.
+function mockGh(respond) {
+ const actions = [];
+ vi.mocked(execGh).mockImplementation(async (args) => {
+ if (args[0] === 'auth') return 'gho_example';
+ const path = args.find((arg) => /^notifications/.test(arg));
+ if (path.startsWith('notifications?')) return respond(args);
+ actions.push([args[args.indexOf('--method') + 1], path]);
+ return '';
+ });
+ return actions;
+}
+
+afterAll(async () => {
+ if (dbReady) {
+ await query('DELETE FROM github_notifications WHERE account_id = ANY($1::text[])', [accountIds]).catch(() => {});
+ await query('DELETE FROM github_notification_sync WHERE account_id = ANY($1::text[])', [accountIds]).catch(() => {});
+ await close();
+ }
+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
+});
+
+describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {
+ let account;
+ beforeEach(async () => {
+ vi.mocked(execGh).mockReset();
+ account = await createAccount({ host: 'github.com', login: `octocat${accountIds.length}`, label: 'Example' });
+ accountIds.push(account.id);
+ });
+
+ it('stores threads with a host-bound link, sends If-Modified-Since next time, and reconciles reads', async () => {
+ const login = account.login;
+ const seen = [];
+ mockGh((args) => {
+ seen.push(args);
+ return seen.length === 1
+ ? listing([thread('101', { owner: login }), thread('102', { owner: 'someone-else' })])
+ : listing([thread('102', { owner: 'someone-else' })]);
+ });
+
+ expect(await syncAccountNotifications(account.id)).toMatchObject({ changed: true, fetched: 2 });
+ const first = await listNotifications({ accountId: account.id });
+ expect(first.notifications).toEqual(expect.arrayContaining([
+ expect.objectContaining({ threadId: '101', yourRepo: true, htmlUrl: `https://github.com/${login}/hello/pull/101`, unread: true }),
+ expect.objectContaining({ threadId: '102', yourRepo: false }),
+ ]));
+ expect(first.sync[account.id]).toMatchObject({ lastError: null, pollIntervalSeconds: 60 });
+
+ await syncAccountNotifications(account.id);
+ expect(seen[1]).toContain('If-Modified-Since: Thu, 01 Oct 2026 10:00:00 GMT');
+ const rows = (await listNotifications({ accountId: account.id })).notifications;
+ expect(rows.find((row) => row.threadId === '101').unread).toBe(false);
+ expect(rows.find((row) => row.threadId === '102').unread).toBe(true);
+ });
+
+ it('treats a 304 as unchanged and keeps rows', async () => {
+ let calls = 0;
+ mockGh(() => {
+ calls += 1;
+ if (calls === 1) return listing([thread('201')]);
+ throw Object.assign(new Error('gh: HTTP 304'), { ghExitCode: 1, ghStderr: 'gh: HTTP 304' });
+ });
+ await syncAccountNotifications(account.id);
+ expect(await syncAccountNotifications(account.id)).toMatchObject({ changed: false });
+ expect((await listNotifications({ accountId: account.id })).notifications).toHaveLength(1);
+ });
+
+ it('applies actions on GitHub, moves rows between views, and reopens a done thread on new activity', async () => {
+ let updatedAt = '2026-10-01T10:00:00Z';
+ const actions = mockGh(() => listing([thread('301', { updatedAt }), thread('302')]));
+ await syncAccountNotifications(account.id);
+
+ expect(await applyNotificationAction(account.id, '301', 'done')).toMatchObject({ state: 'done', unread: false });
+ expect(await applyNotificationAction(account.id, '302', 'mute')).toMatchObject({ state: 'muted' });
+ expect(actions).toEqual([
+ ['DELETE', 'notifications/threads/301'],
+ ['PUT', 'notifications/threads/302/subscription'],
+ ]);
+ expect((await listNotifications({ accountId: account.id, view: 'needs-you' })).notifications).toEqual([]);
+ expect((await listNotifications({ accountId: account.id, view: 'handled' })).notifications).toHaveLength(2);
+
+ updatedAt = '2026-10-02T10:00:00Z';
+ // A changed Last-Modified would normally gate this; the mock ignores it.
+ await syncAccountNotifications(account.id);
+ const open = (await listNotifications({ accountId: account.id, view: 'needs-you' })).notifications;
+ expect(open.map((row) => row.threadId)).toEqual(['301']);
+ });
+
+ it('records the failure on the sync cursor and refuses actions on unknown threads', async () => {
+ mockGh(() => { throw Object.assign(new Error('HTTP 502'), { ghExitCode: 1, ghStderr: 'HTTP 502' }); });
+ await expect(syncAccountNotifications(account.id)).rejects.toThrow('HTTP 502');
+ expect((await listNotifications({ accountId: account.id })).sync[account.id].lastError).toContain('HTTP 502');
+ await expect(applyNotificationAction(account.id, '999', 'done')).rejects.toMatchObject({ status: 404 });
+ });
+});
diff --git a/server/services/githubNotifications.js b/server/services/githubNotifications.js
new file mode 100644
index 0000000000..b591dedddf
--- /dev/null
+++ b/server/services/githubNotifications.js
@@ -0,0 +1,244 @@
+/**
+ * GitHub notifications inbox (#12870): fetch each account's notification
+ * threads into Postgres and apply the operator's one-tap thread actions.
+ *
+ * Only metadata is fetched (repo, reason, subject title/type); no thread body
+ * or linked page is ever read here, and no model sees any of it. Triage and
+ * automations build on these rows in later phases.
+ */
+import { query, withTransaction } from '../lib/db.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { safeJSONParse } from '../lib/fileUtils.js';
+import { createSingleFlight } from '../lib/singleFlight.js';
+import {
+ linkHeaderHasNext,
+ parseGhIncludeOutput,
+ pollIntervalSeconds,
+ toNotificationRecord,
+} from '../lib/githubNotificationParse.js';
+import { execGh } from './github.js';
+import { getAccount, listAccounts, resolveGitHubAccountEnv } from './githubAccounts.js';
+
+const GH_TIMEOUT_MS = 30_000;
+const PER_PAGE = 50;
+// GitHub lists at most 50 threads a page; past 250 unread the listing is
+// truncated and read-state is not reconciled for threads it did not return.
+const MAX_PAGES = 5;
+const LIST_LIMIT = 200;
+
+export const NOTIFICATION_VIEWS = Object.freeze(['needs-you', 'handled', 'all']);
+export const NOTIFICATION_ACTIONS = Object.freeze(['read', 'done', 'mute', 'unsubscribe', 'resubscribe']);
+
+// method + path suffix + fields for each operator action; the state it leaves
+// the stored row in. Thread ids are digits-only (validated at the route).
+const ACTION_SPECS = {
+ read: { method: 'PATCH', path: '', fields: [], state: null },
+ done: { method: 'DELETE', path: '', fields: [], state: 'done' },
+ mute: { method: 'PUT', path: '/subscription', fields: ['-F', 'ignored=true'], state: 'muted' },
+ unsubscribe: { method: 'DELETE', path: '/subscription', fields: [], state: 'unsubscribed' },
+ resubscribe: { method: 'PUT', path: '/subscription', fields: ['-F', 'ignored=false'], state: 'open' },
+};
+
+const syncFlight = createSingleFlight();
+
+const isNotModified = (error) => /\bHTTP 304\b/.test(String(error?.ghStderr || error?.message || ''));
+
+async function requireAccountEnv(account) {
+ if (!account.enabled) {
+ throw new ServerError(`${account.label} is turned off`, { status: 409, code: 'GITHUB_ACCOUNT_DISABLED' });
+ }
+ const { env, status } = await resolveGitHubAccountEnv(account);
+ if (!env) {
+ throw new ServerError(`gh cannot act as ${account.label} (${status}). Check the Accounts tab.`, {
+ status: 409, code: 'GITHUB_ACCOUNT_UNAVAILABLE',
+ });
+ }
+ return env;
+}
+
+async function fetchPage(account, env, page, ifModifiedSince) {
+ const args = ['api', '--hostname', account.host, '--include', '--method', 'GET',
+ `notifications?per_page=${PER_PAGE}&page=${page}`];
+ if (ifModifiedSince) args.push('-H', `If-Modified-Since: ${ifModifiedSince}`);
+ const output = await execGh(args, GH_TIMEOUT_MS, { env }).catch((error) => {
+ if (ifModifiedSince && isNotModified(error)) return null;
+ throw error;
+ });
+ if (output === null) return { notModified: true };
+ const parsed = parseGhIncludeOutput(output);
+ const threads = parsed ? safeJSONParse(parsed.body, null) : null;
+ if (!parsed || !Array.isArray(threads)) {
+ throw new ServerError(`GitHub returned an unreadable notification listing for ${account.label}`, {
+ status: 502, code: 'GITHUB_NOTIFICATIONS_UNPARSEABLE',
+ });
+ }
+ return { notModified: false, threads, headers: parsed.headers };
+}
+
+const UPSERT_SQL = `INSERT INTO github_notifications (
+ account_id, thread_id, repo_full_name, repo_owner, repo_private, reason, subject_type,
+ subject_title, subject_api_url, html_url, unread, gh_updated_at
+ ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)
+ ON CONFLICT (account_id, thread_id) DO UPDATE SET
+ repo_full_name = EXCLUDED.repo_full_name,
+ repo_owner = EXCLUDED.repo_owner,
+ repo_private = EXCLUDED.repo_private,
+ reason = EXCLUDED.reason,
+ subject_type = EXCLUDED.subject_type,
+ subject_title = EXCLUDED.subject_title,
+ subject_api_url = EXCLUDED.subject_api_url,
+ html_url = EXCLUDED.html_url,
+ unread = EXCLUDED.unread,
+ -- GitHub brings a thread marked done back when it has new activity.
+ state = CASE WHEN github_notifications.state = 'done' AND EXCLUDED.gh_updated_at > github_notifications.gh_updated_at
+ THEN 'open' ELSE github_notifications.state END,
+ gh_updated_at = EXCLUDED.gh_updated_at,
+ updated_at = NOW()`;
+
+async function recordSyncError(accountId, message) {
+ await query(
+ `INSERT INTO github_notification_sync (account_id, last_error, updated_at) VALUES ($1, $2, NOW())
+ ON CONFLICT (account_id) DO UPDATE SET last_error = EXCLUDED.last_error, updated_at = NOW()`,
+ [accountId, String(message).slice(0, 2000)],
+ );
+}
+
+async function syncAccountNow(account) {
+ const env = await requireAccountEnv(account);
+ const cursor = (await query('SELECT last_modified FROM github_notification_sync WHERE account_id = $1', [account.id])).rows[0];
+ const first = await fetchPage(account, env, 1, cursor?.last_modified || null);
+ if (first.notModified) {
+ await query('UPDATE github_notification_sync SET last_sync_at = NOW(), last_error = \'\', updated_at = NOW() WHERE account_id = $1', [account.id]);
+ return { accountId: account.id, changed: false, fetched: 0 };
+ }
+ const threads = [...first.threads];
+ let page = first;
+ let pageNumber = 1;
+ while (linkHeaderHasNext(page.headers.link) && pageNumber < MAX_PAGES) {
+ pageNumber += 1;
+ page = await fetchPage(account, env, pageNumber, null);
+ threads.push(...page.threads);
+ }
+ const truncated = linkHeaderHasNext(page.headers.link);
+ const records = threads.map((thread) => toNotificationRecord(thread, account.host)).filter(Boolean);
+
+ await withTransaction(async (client) => {
+ for (const r of records) {
+ await client.query(UPSERT_SQL, [
+ account.id, r.threadId, r.repoFullName, r.repoOwner, r.repoPrivate, r.reason, r.subjectType,
+ r.subjectTitle, r.subjectApiUrl, r.htmlUrl, r.unread, r.ghUpdatedAt,
+ ]);
+ }
+ // The listing holds only unread threads; one that dropped out was read
+ // elsewhere. A truncated listing proves nothing about the rest.
+ if (!truncated) {
+ await client.query(
+ 'UPDATE github_notifications SET unread = FALSE, updated_at = NOW() WHERE account_id = $1 AND unread AND NOT (thread_id = ANY($2::text[]))',
+ [account.id, records.map((r) => r.threadId)],
+ );
+ }
+ await client.query(
+ `INSERT INTO github_notification_sync (account_id, last_modified, poll_interval_seconds, last_sync_at, last_error, updated_at)
+ VALUES ($1, $2, $3, NOW(), '', NOW())
+ ON CONFLICT (account_id) DO UPDATE SET last_modified = EXCLUDED.last_modified,
+ poll_interval_seconds = EXCLUDED.poll_interval_seconds, last_sync_at = NOW(), last_error = '', updated_at = NOW()`,
+ [account.id, first.headers['last-modified'] || null, pollIntervalSeconds(first.headers['x-poll-interval'])],
+ );
+ });
+ console.log(`📬 Synced ${records.length} GitHub notifications for ${account.host}${truncated ? ' (listing truncated)' : ''}`);
+ return { accountId: account.id, changed: true, fetched: records.length, truncated };
+}
+
+/** Fetch one account's unread notifications, coalescing concurrent requests. */
+export async function syncAccountNotifications(accountId) {
+ const account = await getAccount(accountId);
+ return syncFlight.run(account.id, () => syncAccountNow(account).catch(async (error) => {
+ await recordSyncError(account.id, error.message).catch(() => {});
+ throw error;
+ }));
+}
+
+/** Sync every enabled account; one account's failure never hides another's result. */
+export async function syncAllNotifications() {
+ const accounts = (await listAccounts()).filter((account) => account.enabled);
+ const results = [];
+ for (const account of accounts) {
+ results.push(await syncAccountNotifications(account.id)
+ .then((result) => ({ ...result, ok: true }))
+ .catch((error) => ({ accountId: account.id, ok: false, error: error.message })));
+ }
+ return results;
+}
+
+const VIEW_FILTERS = {
+ 'needs-you': "state = 'open'",
+ handled: "state <> 'open'",
+ all: 'TRUE',
+};
+
+const toApi = (row, accountsById) => {
+ const account = accountsById.get(row.account_id);
+ const login = account?.login?.toLowerCase();
+ return {
+ accountId: row.account_id,
+ threadId: row.thread_id,
+ repoFullName: row.repo_full_name,
+ repoPrivate: row.repo_private,
+ yourRepo: Boolean(login) && row.repo_owner.toLowerCase() === login,
+ reason: row.reason,
+ subjectType: row.subject_type,
+ title: row.subject_title,
+ htmlUrl: row.html_url,
+ unread: row.unread,
+ state: row.state,
+ updatedAt: row.gh_updated_at instanceof Date ? row.gh_updated_at.toISOString() : row.gh_updated_at,
+ };
+};
+
+export async function listNotifications({ accountId = null, view = 'needs-you' } = {}) {
+ const accounts = await listAccounts();
+ const accountsById = new Map(accounts.map((account) => [account.id, account]));
+ const ids = accountId ? [accountId] : accounts.map((account) => account.id);
+ const [rows, syncRows] = await Promise.all([
+ query(
+ `SELECT * FROM github_notifications WHERE account_id = ANY($1::text[]) AND ${VIEW_FILTERS[view]}
+ ORDER BY gh_updated_at DESC LIMIT ${LIST_LIMIT}`,
+ [ids],
+ ),
+ query('SELECT account_id, last_sync_at, last_error, poll_interval_seconds FROM github_notification_sync WHERE account_id = ANY($1::text[])', [ids]),
+ ]);
+ return {
+ notifications: rows.rows.map((row) => toApi(row, accountsById)),
+ sync: Object.fromEntries(syncRows.rows.map((row) => [row.account_id, {
+ lastSyncAt: row.last_sync_at instanceof Date ? row.last_sync_at.toISOString() : row.last_sync_at,
+ lastError: row.last_error || null,
+ pollIntervalSeconds: row.poll_interval_seconds,
+ }])),
+ };
+}
+
+/** Apply one operator action to a thread on GitHub, then mirror it locally. */
+export async function applyNotificationAction(accountId, threadId, action) {
+ const spec = ACTION_SPECS[action];
+ const account = await getAccount(accountId);
+ const existing = (await query('SELECT * FROM github_notifications WHERE account_id = $1 AND thread_id = $2', [account.id, threadId])).rows[0];
+ if (!existing) {
+ throw new ServerError('Notification not found', { status: 404, code: 'GITHUB_NOTIFICATION_NOT_FOUND' });
+ }
+ const env = await requireAccountEnv(account);
+ await execGh(
+ ['api', '--hostname', account.host, '--method', spec.method, `notifications/threads/${threadId}${spec.path}`, ...spec.fields],
+ GH_TIMEOUT_MS,
+ { env },
+ );
+ const result = await query(
+ `UPDATE github_notifications SET
+ unread = CASE WHEN $3::text IN ('read','done') THEN FALSE ELSE unread END,
+ state = COALESCE($4::text, state),
+ state_changed_at = CASE WHEN $4::text IS NULL THEN state_changed_at ELSE NOW() END,
+ updated_at = NOW()
+ WHERE account_id = $1 AND thread_id = $2 RETURNING *`,
+ [account.id, threadId, action, spec.state],
+ );
+ return toApi(result.rows[0], new Map([[account.id, account]]));
+}