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

fix: GitHub inbox mirrors GitHub's, clears finished threads, and shows agent rules on every account

Adam Eivy5a8077c00867
diff --git a/client/src/components/github/GitHubAutomationsTab.jsx b/client/src/components/github/GitHubAutomationsTab.jsx
index 7b1247f22e..4e82150900 100644
--- a/client/src/components/github/GitHubAutomationsTab.jsx
+++ b/client/src/components/github/GitHubAutomationsTab.jsx
@@ -31,7 +31,7 @@ function modeHint(account) {
const assist = `Screens and sorts notifications no rule decided, marks CI noise and closed threads done. Never acts on outside or suspect threads. ${where}`;
if (account.mode !== 'autopilot') return assist;
const handoff = account.trust === 'private' && !account.allowAgents
- ? 'Private accounts hand threads off only after you allow agents on them in Accounts.'
+ ? 'Private accounts hand threads off only after you allow agents on them below.'
: 'Also hands outside review requests, outside issues and security alerts in your PortOS apps to Untrusted:Review, the issue watcher and dependency updates when those are on for the app, one run per app for each. A security alert in another repo of yours starts one CoS task per repo that fixes it in a pull request and merges it. Agent rules below turn kinds on or off per repo and pick the provider.';
return `${assist} ${handoff}`;
}
@@ -42,7 +42,32 @@ const CADENCE_TEXT = {
off: 'Only when you tap Run now',
};
-function AccountCard({ account, running, onRun, onMode, savingMode, onSaveRules, savingRules }) {
+// A Private account's agent rules only start agents once the operator allows
+// it; the switch sits beside the rules so both ways are reachable from here.
+function AgentAccess({ account, onAllow, saving }) {
+ if (account.trust !== 'private') return null;
+ const allowed = account.allowAgents === true;
+ return (
+ <div className={`flex flex-wrap items-center gap-2 rounded-lg border p-2.5 text-xs ${allowed ? 'border-port-border text-gray-400' : 'border-port-warning/40 bg-port-warning/10 text-gray-300'}`}>
+ <p className="min-w-0 flex-1">
+ {allowed
+ ? 'Agents are allowed on this Private account. They use their own AI providers, not the ones this account allows.'
+ : 'Rules here start no agent until you allow agents on this Private account. Agents use their own AI providers, which this account\'s provider list cannot limit.'}
+ </p>
+ <button
+ type="button"
+ onClick={() => onAllow(account.id, !allowed)}
+ disabled={saving}
+ aria-pressed={allowed}
+ className={`shrink-0 rounded px-3 py-1.5 text-xs disabled:opacity-50 ${allowed ? 'border border-port-border text-gray-300' : 'bg-port-accent text-white'}`}
+ >
+ {allowed ? 'Stop allowing agents' : 'Allow agents on this account'}
+ </button>
+ </div>
+ );
+}
+
+function AccountCard({ account, running, onRun, onMode, savingMode, onAllowAgents, onSaveRules, savingRules }) {
const selectId = `github-mode-${account.id}`;
return (
<li className="min-w-0 space-y-2 rounded-lg border border-port-border bg-port-card p-4">
@@ -80,7 +105,8 @@ function AccountCard({ account, running, onRun, onMode, savingMode, onSaveRules,
>
<Play size={12} aria-hidden="true" /> {running ? 'Checking…' : 'Run now'}
</button>
- {(account.trust !== 'private' || account.allowAgents) && <GitHubAgentRules account={account} onSave={onSaveRules} saving={savingRules} />}
+ <AgentAccess account={account} onAllow={onAllowAgents} saving={savingMode} />
+ <GitHubAgentRules account={account} onSave={onSaveRules} saving={savingRules} />
</li>
);
}
@@ -181,13 +207,20 @@ export default function GitHubAutomationsTab() {
await load();
};
- const changeMode = async (accountId, mode) => {
+ const changeAccount = async (accountId, patch) => {
setSavingModeId(accountId);
- const updated = await updateGitHubAccount(accountId, { mode }).catch(() => null);
+ const updated = await updateGitHubAccount(accountId, patch).catch(() => null);
setSavingModeId(null);
if (!updated) return;
- setOverview((prev) => ({ ...prev, accounts: prev.accounts.map((account) => (account.id === accountId ? { ...account, mode: updated.mode } : account)) }));
+ setOverview((prev) => ({
+ ...prev,
+ accounts: prev.accounts.map((account) => (account.id === accountId
+ ? { ...account, mode: updated.mode, allowAgents: updated.allowAgents === true }
+ : account)),
+ }));
};
+ const changeMode = (accountId, mode) => changeAccount(accountId, { mode });
+ const allowAgents = (accountId, allow) => changeAccount(accountId, { allowAgents: allow });
const saveRules = async (accountId, agentRules) => {
setSavingRulesId(accountId);
@@ -252,7 +285,7 @@ export default function GitHubAutomationsTab() {
) : (
<ul className="grid grid-cols-1 gap-3 @3xl/page:grid-cols-2">
{overview.accounts.map((account) => (
- <AccountCard key={account.id} account={account} running={runningId === account.id} onRun={runNow} onMode={changeMode} savingMode={savingModeId === account.id} onSaveRules={saveRules} savingRules={savingRulesId === account.id} />
+ <AccountCard key={account.id} account={account} running={runningId === account.id} onRun={runNow} onMode={changeMode} savingMode={savingModeId === account.id} onAllowAgents={allowAgents} onSaveRules={saveRules} savingRules={savingRulesId === account.id} />
))}
</ul>
)}
diff --git a/client/src/components/github/GitHubInboxTab.jsx b/client/src/components/github/GitHubInboxTab.jsx
index 9745aec07c..151cd8fdca 100644
--- a/client/src/components/github/GitHubInboxTab.jsx
+++ b/client/src/components/github/GitHubInboxTab.jsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { Link, useParams } from 'react-router';
import {
- Bell, BellOff, Bot, Check, CheckCircle2, CircleDot, CircleX, ExternalLink, GitCommitHorizontal, GitPullRequest,
+ Bell, BellOff, Bot, Check, CheckCheck, CheckCircle2, CircleDot, CircleX, ExternalLink, GitCommitHorizontal, GitPullRequest,
Inbox, Layers, Mail, MailX, MessagesSquare, RefreshCw, ShieldAlert, Tag,
} from 'lucide-react';
import Pill from '../ui/Pill';
@@ -14,6 +14,7 @@ import PageSkeleton from '../ui/PageSkeleton';
import CollapsibleListItem from '../ui/CollapsibleListItem';
import { formatCount, timeAgo } from '../../utils/formatters';
import {
+ clearFinishedGitHubNotifications,
getGitHubAccounts,
getGitHubNotifications,
syncGitHubNotifications,
@@ -53,16 +54,13 @@ const MORE_ACTIONS = [
{ action: 'unsubscribe', label: 'Unsubscribe', icon: MailX },
];
-// Mirrors HANDLED_DECISIONS in server/lib/githubNotificationTriage.js:
-// nothing is left for you on these threads, so they sit under Handled.
-const HANDLED_DECISIONS = new Set(['handled-by-pr-workflow', 'duplicate', 'handed-off', 'suggest-mark-read']);
-const nothingLeft = (row) => !row.suspect && HANDLED_DECISIONS.has(row.decision);
-
-// Whether a row still belongs in the view after an action moved it.
+// Whether a row still belongs in the view after an action moved it. Mirrors
+// VIEW_FILTERS in server/services/githubNotifications.js: the inbox holds every
+// open thread, as GitHub's does, whatever its decision.
const VIEW_MATCHERS = {
- 'needs-you': (row) => row.state === 'open' && !row.suspect && !nothingLeft(row),
+ 'needs-you': (row) => row.state === 'open' && !row.suspect,
suspect: (row) => row.state === 'open' && row.suspect,
- handled: (row) => row.state !== 'open' || nothingLeft(row),
+ handled: (row) => row.state !== 'open',
all: () => true,
};
const belongsInView = (row, view) => VIEW_MATCHERS[view](row);
@@ -85,7 +83,7 @@ const kindOf = (notification) => (notification.reason === 'security_alert'
// Summary tiles double as the view picker. Counts come from the server for
// every view at once; tone follows meaning, and every tile also has a label.
const TILES = [
- { id: 'needs-you', label: 'Needs you', icon: Inbox, iconClass: 'text-port-accent' },
+ { id: 'needs-you', label: 'Inbox', icon: Inbox, iconClass: 'text-port-accent' },
{ id: 'suspect', label: 'Suspect', icon: ShieldAlert, iconClass: 'text-port-warning' },
{ id: 'handled', label: 'Handled', icon: CheckCircle2, iconClass: 'text-port-success' },
{ id: 'all', label: 'All', icon: Layers, iconClass: 'text-gray-400' },
@@ -237,6 +235,7 @@ export default function GitHubInboxTab() {
const [loadFailed, setLoadFailed] = useState(false);
const [syncing, setSyncing] = useState(false);
const [busyKey, setBusyKey] = useState(null);
+ const [clearing, setClearing] = useState(false);
const [removing, setRemoving] = useState(() => new Set());
const [syncTick, setSyncTick] = useState(0);
const requestRef = useRef(0);
@@ -299,6 +298,13 @@ export default function GitHubInboxTab() {
}
};
+ // The server's changed event re-reads the list once the batch is done.
+ const clearFinished = async () => {
+ setClearing(true);
+ await clearFinishedGitHubNotifications(accountId).catch(() => null);
+ setClearing(false);
+ };
+
const dropRow = (key) => {
setData((prev) => ({ ...prev, notifications: prev.notifications.filter((entry) => keyOf(entry) !== key) }));
setRemoving((prev) => {
@@ -354,11 +360,26 @@ export default function GitHubInboxTab() {
</div>
<SummaryTiles view={view} counts={data.counts} onSelect={setView} />
- {data.counts?.['with-agents'] > 0 && (
- <p className="flex items-center gap-1.5 text-xs text-gray-400">
- <Bot size={13} className="text-port-accent" aria-hidden="true" />
- {formatCount(data.counts['with-agents'])} with an agent now
- </p>
+ {(data.counts?.['with-agents'] > 0 || (view === 'needs-you' && data.counts?.finished > 0)) && (
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">
+ {data.counts['with-agents'] > 0 && (
+ <p className="flex items-center gap-1.5 text-xs text-gray-400">
+ <Bot size={13} className="text-port-accent" aria-hidden="true" />
+ {formatCount(data.counts['with-agents'])} with an agent now
+ </p>
+ )}
+ {view === 'needs-you' && data.counts.finished > 0 && (
+ <button
+ type="button"
+ onClick={clearFinished}
+ disabled={clearing}
+ className="inline-flex min-h-[36px] items-center gap-1.5 rounded-lg border border-port-border bg-port-card px-3 py-1.5 text-xs text-gray-200 hover:border-gray-500 disabled:opacity-60"
+ >
+ <CheckCheck size={13} aria-hidden="true" />
+ {clearing ? 'Marking done…' : `Mark ${formatCount(data.counts.finished)} finished done`}
+ </button>
+ )}
+ </div>
)}
{syncErrors.map(([id, state]) => (
@@ -393,7 +414,7 @@ export default function GitHubInboxTab() {
>
{shown.length === 0 ? (
<p className="p-6 text-center text-sm text-gray-400">
- {{ 'needs-you': 'Nothing needs you right now.', suspect: 'Nothing suspicious.' }[view] || 'No notifications here.'}
+ {{ 'needs-you': 'Your inbox is clear.', suspect: 'Nothing suspicious.' }[view] || 'No notifications here.'}
</p>
) : (
<div className="min-w-0 divide-y divide-port-border">
diff --git a/client/src/pages/GitHub.test.jsx b/client/src/pages/GitHub.test.jsx
index 28372ea659..f8dd447902 100644
--- a/client/src/pages/GitHub.test.jsx
+++ b/client/src/pages/GitHub.test.jsx
@@ -21,6 +21,7 @@ const mock = vi.hoisted(() => ({
syncGitHubNotifications: vi.fn(),
applyGitHubNotificationAction: vi.fn(),
resolveGitHubNotificationWithAgent: vi.fn(),
+ clearFinishedGitHubNotifications: vi.fn(),
getGitHubNotification: vi.fn(),
getGitHubAutomations: vi.fn(),
setGitHubNotificationCadence: vi.fn(),
@@ -405,12 +406,27 @@ describe('GitHub inbox tab', () => {
expect(mock.getGitHubRepos).not.toHaveBeenCalled();
});
- it('marks a thread done and takes it out of Needs you', async () => {
+ it('marks a thread done and takes it out of the inbox', 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();
+ expect(await screen.findByText('Your inbox is clear.')).toBeTruthy();
+ });
+
+ it('marks every finished thread done in one tap', async () => {
+ mock.getGitHubNotifications.mockResolvedValue({
+ notifications: [NOTIFICATION, { ...NOTIFICATION, threadId: '102', title: 'Folded CI notice', decision: 'duplicate' }],
+ counts: { 'needs-you': 2, suspect: 0, handled: 0, all: 2, finished: 1 },
+ sync: {},
+ });
+ mock.clearFinishedGitHubNotifications.mockResolvedValue({ cleared: 1, failed: 0 });
+ renderTab('inbox');
+ // The inbox mirrors GitHub's, so a folded duplicate is listed with its pill.
+ expect(await screen.findByText('Folded CI notice')).toBeTruthy();
+ expect(screen.getByText('Duplicate')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Mark 1 finished done' }));
+ await waitFor(() => expect(mock.clearFinishedGitHubNotifications).toHaveBeenCalledWith(null));
});
it('resolves an actionable thread with an agent in one tap, and says why when it cannot', async () => {
@@ -428,8 +444,9 @@ describe('GitHub inbox tab', () => {
expect(buttons).toHaveLength(1);
fireEvent.click(buttons[0]);
expect(mock.resolveGitHubNotificationWithAgent).toHaveBeenCalledWith('github-com', '101');
- // A handed-off thread is something else's now, so it leaves Needs you.
- await waitFor(() => expect(screen.queryByText('Example change')).toBeNull());
+ // A handed-off thread stays in the inbox, as it does on GitHub, with its pill.
+ expect(await screen.findByText('Handed off')).toBeTruthy();
+ expect(screen.getByText('Example change')).toBeTruthy();
});
it('undoes Done locally and a mute by re-subscribing', async () => {
@@ -577,16 +594,18 @@ describe('GitHub automations tab', () => {
await waitFor(() => expect(mock.getGitHubAutomations).toHaveBeenCalledTimes(2));
});
- it('shows agent rules on a Private account only once it allows agents', async () => {
+ it('shows agent rules on a Private account and allows agents, or stops, from its card', async () => {
const enterprise = { ...OVERVIEW.accounts[0], id: 'ghe', label: 'ghe.example.com', host: 'ghe.example.com', trust: 'private', mode: 'autopilot', agentRules: [], repos: [] };
mock.getGitHubAutomations.mockResolvedValue({ ...OVERVIEW, accounts: [{ ...enterprise, allowAgents: false }] });
- const { unmount } = renderTab('automations');
- expect(await screen.findByText(/only after you allow agents/)).toBeTruthy();
- expect(screen.queryByRole('button', { name: /Add rule/ })).toBeNull();
- unmount();
- mock.getGitHubAutomations.mockResolvedValue({ ...OVERVIEW, accounts: [{ ...enterprise, allowAgents: true }] });
+ mock.updateGitHubAccount.mockImplementation(async (id, data) => ({ ...enterprise, id, ...data }));
renderTab('automations');
expect(await screen.findByRole('button', { name: /Add rule/ })).toBeTruthy();
+ expect(screen.getByText(/start no agent until you allow agents/)).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Allow agents on this account' }));
+ await waitFor(() => expect(mock.updateGitHubAccount).toHaveBeenCalledWith('ghe', { allowAgents: true }));
+ fireEvent.click(await screen.findByRole('button', { name: 'Stop allowing agents' }));
+ await waitFor(() => expect(mock.updateGitHubAccount).toHaveBeenCalledWith('ghe', { allowAgents: false }));
+ expect(await screen.findByRole('button', { name: 'Allow agents on this account' })).toBeTruthy();
});
it('adds an agent rule for review requests in one repo and refuses a duplicate', async () => {
diff --git a/client/src/services/apiGithub.js b/client/src/services/apiGithub.js
index 80be6a9faa..fdb93f4dc9 100644
--- a/client/src/services/apiGithub.js
+++ b/client/src/services/apiGithub.js
@@ -39,6 +39,8 @@ export const getGitHubNotifications = ({ accountId, view } = {}, options = {}) =
};
export const syncGitHubNotifications = (accountId = null, options = {}) =>
request('/github/notifications/sync', { method: 'POST', body: JSON.stringify(accountId ? { accountId } : {}), ...options });
+export const clearFinishedGitHubNotifications = (accountId = null, options = {}) =>
+ request('/github/notifications/clear-finished', { 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/server/lib/githubNotificationTriage.js b/server/lib/githubNotificationTriage.js
index 8e5f960ca5..22350e013f 100644
--- a/server/lib/githubNotificationTriage.js
+++ b/server/lib/githubNotificationTriage.js
@@ -36,12 +36,12 @@ export const TRUST_LEVELS = Object.freeze(['yours', 'trusted', 'outside', 'unkno
// Bump when a rule change should re-decide threads that have no new activity;
// open threads triaged under an older version are triaged again.
-export const TRIAGE_RULES_VERSION = 3;
+export const TRIAGE_RULES_VERSION = 4;
-// Decisions that leave nothing for you: something else has the thread, or it
-// is already closed or merged. They sit under Handled instead of Needs you,
-// even in Observe before anything acts on GitHub.
-export const HANDLED_DECISIONS = Object.freeze(['handled-by-pr-workflow', 'duplicate', 'handed-off', 'suggest-mark-read']);
+// Open threads with nothing left for you: closed or merged, folded into a
+// newer CI notice, or owned by a PR workflow. They stay in the inbox (it
+// mirrors GitHub's) until marked done, which the inbox can do in one tap.
+export const FINISHED_DECISIONS = Object.freeze(['handled-by-pr-workflow', 'duplicate', 'suggest-mark-read']);
const NEW_ACCOUNT_DAYS = 30;
const DAY_MS = 24 * 60 * 60 * 1000;
@@ -106,7 +106,7 @@ export function decideThread({ reason, subjectType, subjectState, subjectMerged
return { decision: 'handled-by-pr-workflow', rule: 'own-pr-in-managed-repo' };
}
const finished = subjectMerged === true || subjectState === 'closed';
- if (finished && reason !== 'review_requested') return { decision: 'suggest-mark-read', rule: 'finished-thread' };
+ if (finished) return { decision: 'suggest-mark-read', rule: 'finished-thread' };
if (reason === 'ci_activity' || subjectType === 'CheckSuite') {
if (ciBranch && defaultBranch && ciBranch === defaultBranch) return { decision: 'surface', rule: 'ci-default-branch' };
if (repoManaged && ciBranch) return { decision: 'handled-by-pr-workflow', rule: 'ci-watched-by-pr-workflow' };
@@ -159,8 +159,9 @@ export function applyLearnedRule(result, learned) {
*/
export function assistAction({ decision, rule, trust, suspect = false, state = 'open' }) {
if (suspect || state !== 'open') return null;
- // A closed or merged thread has nothing left to do, so it is done, not just read.
- if (decision === 'suggest-mark-read') return 'done';
+ // A closed or merged thread has nothing left to do, so it is done, not just
+ // read; a folded CI repeat leaves its newest notice open.
+ if (decision === 'suggest-mark-read' || decision === 'duplicate') return 'done';
if (trust === 'outside') return null;
const vouched = trust === 'yours' || trust === 'trusted' || rule === 'learned';
if (decision === 'handled-by-pr-workflow') return 'done';
@@ -200,6 +201,8 @@ const RULE_REPO_RE = /^(?:\*|[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100})$/;
// A review request still waiting on you; one you sorted as done or noise is not.
const REVIEW_DECISIONS = new Set(['suggest-review', 'suggest-untrusted-review', 'needs-you', 'surface']);
const REVIEW_TRUST = new Set(['yours', 'trusted']);
+// Mirrored in CANDIDATE_SQL (githubNotificationAutopilot.js).
+const FINISHED_SUBJECT_STATES = new Set(['merged', 'closed']);
function threadAgentKind(row) {
if (row?.reason === 'security_alert') return 'security-alert';
@@ -269,7 +272,7 @@ export function agentHandoff({ account, row }) {
const kind = threadAgentKind(row);
const rule = matchAgentRule(account?.agentRules, kind, row.repo_full_name);
let plan = null;
- if (kind === 'review-request' && REVIEW_DECISIONS.has(row.decision)) {
+ if (kind === 'review-request' && REVIEW_DECISIONS.has(row.decision) && !FINISHED_SUBJECT_STATES.has(evidence.subjectState)) {
const pullNumber = Number(PULL_PATH_RE.exec(String(row.subject_api_url || ''))?.[1]);
// Only a PR by you or a trusted author goes to a plain /do:review run; an
// outside PR goes to pr-reviewer, which screens untrusted content first and
diff --git a/server/lib/githubNotificationTriage.test.js b/server/lib/githubNotificationTriage.test.js
index df697f1fad..28cc0281eb 100644
--- a/server/lib/githubNotificationTriage.test.js
+++ b/server/lib/githubNotificationTriage.test.js
@@ -60,6 +60,9 @@ describe('decideThread', () => {
expect(decide({ reason: 'invitation' })).toBe('surface');
expect(decide({ reason: 'comment', subjectState: 'closed' })).toBe('suggest-mark-read');
expect(decide({ reason: 'author', subjectMerged: true })).toBe('suggest-mark-read');
+ // A review request on a merged or closed PR has nothing left to review.
+ expect(decide({ reason: 'review_requested', trust: 'trusted', repoOwned: true, subjectMerged: true })).toBe('suggest-mark-read');
+ expect(decide({ reason: 'review_requested', repoOwned: true, subjectState: 'closed' })).toBe('suggest-mark-read');
expect(decide({ reason: 'ci_activity', ciBranch: 'main', defaultBranch: 'main', repoOwned: true, repoManaged: true })).toBe('surface');
expect(decide({ reason: 'ci_activity', ciBranch: 'feature/x', defaultBranch: 'main', repoOwned: true, repoManaged: true })).toBe('handled-by-pr-workflow');
expect(decide({ reason: 'ci_activity', ciBranch: 'feature/x', defaultBranch: 'main', repoOwned: true })).toBe('needs-you');
@@ -112,6 +115,8 @@ describe('Assist inputs', () => {
it('acts automatically only on non-outside, non-suspect threads, except to finish a closed one', () => {
expect(assistAction({ decision: 'handled-by-pr-workflow', trust: 'unknown' })).toBe('done');
expect(assistAction({ decision: 'suggest-mark-read', trust: 'outside' })).toBe('done');
+ // A CI repeat folded into a newer notice for the same branch.
+ expect(assistAction({ decision: 'duplicate', trust: 'unknown' })).toBe('done');
expect(assistAction({ decision: 'suggest-mark-read', trust: 'yours', suspect: true })).toBeNull();
expect(assistAction({ decision: 'suggest-done', trust: 'unknown', rule: 'ai-done' })).toBeNull();
expect(assistAction({ decision: 'suggest-mute', trust: 'trusted' })).toBe('mute');
@@ -164,6 +169,9 @@ describe('autopilotHandoff', () => {
expect(autopilotHandoff({ account, row: { ...review, evidence: { repoManaged: false, repoOwned: true } } })).toEqual({ lane: 'pr-reviewer', pullNumber: 42, refused: 'no-managed-app' });
expect(autopilotHandoff({ account, row: { ...review, suspect: true } })).toBeNull();
expect(autopilotHandoff({ account, row: { ...issue, state: 'done' } })).toBeNull();
+ // Nor a review request on a PR that is already merged or closed.
+ expect(agentHandoff({ account, row: { ...review, evidence: { repoManaged: true, subjectState: 'merged' } } })).toBeNull();
+ expect(agentHandoff({ account, row: { ...review, evidence: { repoManaged: true, subjectState: 'closed' } } })).toBeNull();
// An issue from you or a collaborator with no outside comment stays with you.
expect(autopilotHandoff({ account, row: { ...issue, trust: 'trusted' } })).toBeNull();
});
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.js
index 926cd6dba6..bc3fe1ed3e 100644
--- a/server/lib/hostControlRoutes.js
+++ b/server/lib/hostControlRoutes.js
@@ -1092,6 +1092,7 @@ export const HOST_CONTROL_ROUTES = Object.freeze([
// account with `gh`; the schedule arms a CoS System task; account
// create/edit pick the `gh` identity, mode, trust and allowed providers.
'POST /api/github/notifications/:accountId/:threadId',
+ 'POST /api/github/notifications/clear-finished',
'POST /api/github/audit/:accountId/apply',
'POST /api/github/audit-changes/:id/undo',
'POST /api/github/automations/activity/:id/undo',
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 935038ae00..09157eb898 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1007,6 +1007,10 @@ export const githubNotificationsSyncSchema = z.object({
accountId: z.string().trim().min(1).max(100).optional(),
}).strict();
+export const githubNotificationsClearSchema = z.object({
+ accountId: z.string().trim().min(1).max(100).optional(),
+}).strict();
+
export const githubNotificationActionSchema = z.object({
action: z.enum(['read', 'done', 'reopen', 'mute', 'unsubscribe', 'resubscribe']),
}).strict();
diff --git a/server/routes/github.js b/server/routes/github.js
index aac02a9a8f..b6405c80f1 100644
--- a/server/routes/github.js
+++ b/server/routes/github.js
@@ -1,7 +1,7 @@
import express from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest, githubRepoUpdateSchema, githubSecretSchema, githubAccountCreateSchema, githubAccountUpdateSchema,
- githubNotificationsQuerySchema, githubNotificationsSyncSchema, githubNotificationActionSchema, GITHUB_NOTIFICATION_THREAD_ID_RE,
+ githubNotificationsQuerySchema, githubNotificationsSyncSchema, githubNotificationsClearSchema, githubNotificationActionSchema, GITHUB_NOTIFICATION_THREAD_ID_RE,
githubNotificationCadenceSchema, githubAuditApplySchema } from '../lib/validation.js';
import * as githubService from '../services/github.js';
import * as githubAccounts from '../services/githubAccounts.js';
@@ -151,6 +151,15 @@ router.post('/notifications/sync', asyncHandler(async (req, res) => {
res.json({ results });
}));
+/**
+ * POST /api/github/notifications/clear-finished — mark every open closed,
+ * merged, folded-duplicate or PR-workflow thread done on GitHub
+ */
+router.post('/notifications/clear-finished', asyncHandler(async (req, res) => {
+ const { accountId } = validateRequest(githubNotificationsClearSchema, req.body ?? {});
+ res.json(await githubNotifications.clearFinishedNotifications({ accountId }));
+}));
+
const threadIdParam = (req) => {
if (!GITHUB_NOTIFICATION_THREAD_ID_RE.test(req.params.threadId)) {
throw new ServerError('Invalid notification thread id', { status: 400 });
diff --git a/server/services/githubNotificationAssist.js b/server/services/githubNotificationAssist.js
index fac96dd03d..daa794bfcc 100644
--- a/server/services/githubNotificationAssist.js
+++ b/server/services/githubNotificationAssist.js
@@ -29,7 +29,7 @@ const MAX_SORTS_PER_RUN = 10;
const MAX_ACTIONS_PER_RUN = 50;
// Autopilot includes everything Assist does.
const ASSIST_MODES = new Set(['assist', 'autopilot']);
-const ACTIONABLE_DECISIONS = ['handled-by-pr-workflow', 'suggest-mark-read', 'suggest-done', 'suggest-mute'];
+const ACTIONABLE_DECISIONS = ['handled-by-pr-workflow', 'suggest-mark-read', 'duplicate', 'suggest-done', 'suggest-mute'];
// A skipped sort is retried an hour later (a provider added, a timeout), except
// when the text itself was refused; new activity re-triages either way.
const RETRY_SKIPPED_MS = 60 * 60 * 1000;
diff --git a/server/services/githubNotificationAutopilot.js b/server/services/githubNotificationAutopilot.js
index 269b865ac9..1b9f92a342 100644
--- a/server/services/githubNotificationAutopilot.js
+++ b/server/services/githubNotificationAutopilot.js
@@ -36,7 +36,7 @@ const MAX_HANDOFFS_PER_RUN = 50;
// an older eligible thread is never starved by newer ones the rules would
// reject. `inScope(n)` reads one `agentRuleScope` as parameters $n..$n+2.
const inScope = (n) => `(($${n}::boolean AND NOT (lower(repo_full_name) = ANY($${n + 1}::text[]))) OR lower(repo_full_name) = ANY($${n + 2}::text[]))`;
-const CANDIDATE_SQL = `((reason = 'review_requested' AND subject_type = 'PullRequest' AND (
+const CANDIDATE_SQL = `((reason = 'review_requested' AND subject_type = 'PullRequest' AND COALESCE(evidence->>'subjectState', '') NOT IN ('merged', 'closed') AND (
(decision = 'suggest-untrusted-review' AND COALESCE(trust, '') NOT IN ('yours', 'trusted') AND (evidence->>'repoManaged')::boolean IS TRUE AND ${inScope(2)})
OR (decision IN ('suggest-review', 'suggest-untrusted-review', 'needs-you', 'surface') AND trust IN ('yours', 'trusted') AND ${inScope(5)})))
OR (subject_type = 'Issue' AND decision IN ('needs-you', 'surface') AND (trust = 'outside' OR evidence->>'commenter' IS NOT NULL)
diff --git a/server/services/githubNotificationTriage.js b/server/services/githubNotificationTriage.js
index 5eff0021af..26389f904f 100644
--- a/server/services/githubNotificationTriage.js
+++ b/server/services/githubNotificationTriage.js
@@ -26,13 +26,15 @@ const GH_TIMEOUT_MS = 20_000;
const MAX_THREADS_PER_RUN = 60;
// Open threads a rules-version bump re-decides without new activity: version 2
// changed your own PRs and finished threads (now marked done, not just read);
-// version 3 leaves a bot's comment on your own PR to the PR workflow. A thread
+// version 3 leaves a bot's comment on your own PR to the PR workflow; version
+// 4 finishes a review request on a merged or closed PR. A thread
// already handed off keeps its hand-off. One an Assist model sorted is not
// read again, except your own PR: the rule table decides those, so a verdict
// from before the rule existed must not keep one in front of you.
const REDECIDE_SQL = `(state = 'open' AND NOT (evidence ? 'handoff')
AND ((reason = 'author' AND subject_type = 'PullRequest' AND trust = 'yours')
- OR (decision = 'suggest-mark-read' AND COALESCE(evidence->>'rule', '') NOT LIKE 'ai-%')))`;
+ OR (decision = 'suggest-mark-read' AND COALESCE(evidence->>'rule', '') NOT LIKE 'ai-%')
+ OR (reason = 'review_requested' AND evidence->>'subjectState' IN ('merged', 'closed'))))`;
const LOGIN_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,99}(?:\[bot\])?$/;
const REPO_RE = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;
diff --git a/server/services/githubNotifications.db.test.js b/server/services/githubNotifications.db.test.js
index 2d33c69a75..8c9c79899f 100644
--- a/server/services/githubNotifications.db.test.js
+++ b/server/services/githubNotifications.db.test.js
@@ -45,7 +45,7 @@ const { addTask } = await import('./cosTaskStore.js');
const { runUntrustedContentAnalysis } = await import('./untrustedContent.js');
const { createAccount, updateAccount } = await import('./githubAccounts.js');
const {
- syncAccountNotifications, syncAllNotifications, listNotifications, applyNotificationAction, getNotification, runScheduledNotificationCheck, describeScheduledCheck,
+ syncAccountNotifications, syncAllNotifications, listNotifications, applyNotificationAction, clearFinishedNotifications, getNotification, runScheduledNotificationCheck, describeScheduledCheck,
listAutomationActivity, undoAutomationAction, listLearnedRules, resolveWithAgent, getAutomationsOverview, setNotificationCadence,
} = await import('./githubNotifications.js');
const { runAccountAudit, applyAuditSuggestion, listAuditChanges, undoAuditChange, sendDueAuditReports } = await import('./githubNotificationAudit.js');
@@ -333,11 +333,17 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {
it('folds repeat default-branch CI notices into the newest one', async () => {
const login = account.login;
const ci = (id, updatedAt) => thread(id, { owner: login, reason: 'ci_activity', type: 'CheckSuite', url: null, updatedAt, title: 'CI workflow run failed for main branch' });
- mockGh(() => listing([ci('701', '2026-10-01T10:00:00Z'), ci('702', '2026-10-01T11:00:00Z')]), { [`repos/${login}/hello`]: 'main' });
+ const actions = mockGh(() => listing([ci('701', '2026-10-01T10:00:00Z'), ci('702', '2026-10-01T11:00:00Z')]), { [`repos/${login}/hello`]: 'main' });
await syncAccountNotifications(account.id);
const rows = (await listNotifications({ accountId: account.id, view: 'all' })).notifications;
expect(rows.map((row) => [row.threadId, row.decision])).toEqual([['702', 'surface'], ['701', 'duplicate']]);
- // The folded notice is Handled while still open, so red main shows once in Needs you.
+ // The inbox mirrors GitHub's: the folded notice stays in it, still unread
+ // there, until it is marked done, which one tap does for every finished thread.
+ const inbox = await listNotifications({ accountId: account.id });
+ expect(inbox.notifications.map((row) => row.threadId)).toEqual(['702', '701']);
+ expect(inbox.counts).toMatchObject({ 'needs-you': 2, finished: 1 });
+ expect(await clearFinishedNotifications({ accountId: account.id })).toEqual({ cleared: 1, failed: 0 });
+ expect(actions).toEqual([['DELETE', 'notifications/threads/701']]);
expect((await listNotifications({ accountId: account.id })).notifications.map((row) => row.threadId)).toEqual(['702']);
});
@@ -568,9 +574,12 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {
['pr-reviewer', 'app-acme', { origin: 'github-notification' }],
]);
expect((await getNotification(account.id, '1204')).evidence.handoff).toMatchObject({ lane: 'dependency-updates', requestId: 'demand-dependency-updates', batchSize: 3 });
- // Your own PR waits for you only when someone outside commented on it.
- const needsYou = (await listNotifications({ accountId: account.id, view: 'needs-you' })).notifications.map((row) => row.threadId);
- expect(needsYou.sort()).toEqual(['1202', '1208']);
+ // Your own PR waits for you only when someone outside commented on it;
+ // a handed-off thread stays in the inbox, as it does on GitHub, with its pill.
+ const inbox = (await listNotifications({ accountId: account.id, view: 'needs-you' })).notifications;
+ expect(Object.fromEntries(inbox.map((row) => [row.threadId, row.decision]))).toEqual({
+ 1202: 'needs-you', 1203: 'handed-off', 1204: 'handed-off', 1205: 'handed-off', 1206: 'handed-off', 1207: 'handed-off', 1208: 'needs-you',
+ });
const handled = (await listNotifications({ accountId: account.id, view: 'handled' })).notifications;
// Autopilot includes Assist, which marks it done on GitHub.
expect(handled.find((row) => row.threadId === '1201')).toMatchObject({ state: 'done', decision: 'handled-by-pr-workflow', rule: 'own-pr-in-managed-repo' });
@@ -666,7 +675,9 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {
thread('1501', { owner: login, repo: 'tool', reason: 'review_requested' }),
thread('1502', { owner: 'acme', repo: 'app', reason: 'security_alert', type: 'RepositoryVulnerabilityAlert', url: null }),
thread('1503', { owner: login, repo: 'side', reason: 'review_requested' }),
+ thread('1504', { owner: login, repo: 'tool', reason: 'review_requested' }),
]), {
+ [`repos/${login}/tool/pulls/1504`]: { author: 'teammate', association: 'COLLABORATOR', state: 'closed', merged: true },
[`repos/${login}/side/pulls/1503`]: { author: 'stranger', association: 'NONE', state: 'open', merged: false },
[`repos/${login}/side/collaborators/stranger/permission`]: { user: { login: 'stranger' }, permission: 'read' },
[`repos/${login}/tool/pulls/1501`]: { author: 'teammate', association: 'COLLABORATOR', state: 'open', merged: false },
@@ -695,6 +706,18 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {
expect(outside).toMatchObject({ decision: 'suggest-untrusted-review' });
expect(outside.evidence.handoff).toBeUndefined();
expect(addTask).toHaveBeenCalledTimes(1);
+ // A review request on a merged PR is finished: marked done, never reviewed.
+ expect(await getNotification(account.id, '1504')).toMatchObject({ decision: 'suggest-mark-read', state: 'done' });
+ // A row still decided as a review suggestion is not an Autopilot candidate
+ // once its PR is merged (CANDIDATE_SQL mirrors agentHandoff).
+ await query(
+ `UPDATE github_notifications SET state = 'open', decision = 'suggest-review', evidence = evidence - 'assisted'
+ WHERE account_id = $1 AND thread_id = '1504'`,
+ [account.id],
+ );
+ await syncAccountNotifications(account.id);
+ expect((await getNotification(account.id, '1504')).evidence.handoff).toBeUndefined();
+ expect(addTask).toHaveBeenCalledTimes(1);
// A malformed rule is refused at the boundary.
expect(() => updateAccount(account.id, { agentRules: [{ id: 'x', kind: 'review-request', repo: 'not a repo', agent: true }] })).toThrow('Validation failed');
await updateAccount(account.id, { agentRules: [] });
diff --git a/server/services/githubNotifications.js b/server/services/githubNotifications.js
index 5ec9f5da74..f327a053bd 100644
--- a/server/services/githubNotifications.js
+++ b/server/services/githubNotifications.js
@@ -23,7 +23,7 @@ import { getAccount, listAccounts, resolveGitHubAccountEnv } from './githubAccou
import { githubNotificationEvents } from './githubNotificationEvents.js';
import { triageAccountNotifications } from './githubNotificationTriage.js';
import { assistAccountNotifications } from './githubNotificationAssist.js';
-import { agentHandoff, HANDLED_DECISIONS, learnedDecisionForAction } from '../lib/githubNotificationTriage.js';
+import { agentHandoff, FINISHED_DECISIONS, learnedDecisionForAction } from '../lib/githubNotificationTriage.js';
import { toPgJson } from '../lib/pgJson.js';
const GH_TIMEOUT_MS = 30_000;
@@ -277,13 +277,14 @@ export async function syncAllNotifications(options = {}) {
return results;
}
-// A thread with nothing left for you (something else has it, or it is closed
-// or merged) is Handled while it is still open on GitHub.
-const HANDLED_SQL = `decision IN (${HANDLED_DECISIONS.map((decision) => `'${decision}'`).join(', ')})`;
+// The inbox mirrors GitHub's: every open thread is in it until marked done,
+// whatever its decision says (a pill on the row). Finished threads are those
+// the inbox can clear in one tap.
+const FINISHED_SQL = `decision IN (${FINISHED_DECISIONS.map((decision) => `'${decision}'`).join(', ')})`;
const VIEW_FILTERS = {
- 'needs-you': `state = 'open' AND NOT suspect AND (decision IS NULL OR NOT ${HANDLED_SQL})`,
+ 'needs-you': "state = 'open' AND NOT suspect",
suspect: "state = 'open' AND suspect",
- handled: `(state <> 'open' OR (NOT suspect AND ${HANDLED_SQL}))`,
+ handled: "state <> 'open'",
all: 'TRUE',
};
@@ -335,7 +336,8 @@ export async function listNotifications({ accountId = null, view = 'needs-you' }
// Every view's size for the inbox's summary, plus the open threads an agent has.
query(
`SELECT ${NOTIFICATION_VIEWS.map((name) => `COUNT(*) FILTER (WHERE ${VIEW_FILTERS[name]})::int AS "${name}"`).join(', ')},
- COUNT(*) FILTER (WHERE state = 'open' AND decision = 'handed-off')::int AS "with-agents"
+ COUNT(*) FILTER (WHERE state = 'open' AND decision = 'handed-off')::int AS "with-agents",
+ COUNT(*) FILTER (WHERE state = 'open' AND NOT suspect AND ${FINISHED_SQL})::int AS finished
FROM github_notifications WHERE account_id = ANY($1::text[])`,
[ids],
),
@@ -377,7 +379,7 @@ async function learnFromOperator(client, row, action) {
* actions teach learned rules (unless `learn: false`, for a bulk audit change);
* an automation's carry the decision behind it.
*/
-export async function applyNotificationAction(accountId, threadId, action, { actor = 'operator', detail = {}, learn = actor === 'operator' } = {}) {
+export async function applyNotificationAction(accountId, threadId, action, { actor = 'operator', detail = {}, learn = actor === 'operator', emit = true } = {}) {
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];
@@ -409,10 +411,41 @@ export async function applyNotificationAction(accountId, threadId, action, { act
);
return result.rows[0];
});
- githubNotificationEvents.emit('changed', { accountId: account.id });
+ if (emit) githubNotificationEvents.emit('changed', { accountId: account.id });
return toApi(row, new Map([[account.id, account]]));
}
+/**
+ * Mark every open finished thread done on GitHub (one account, or all), as
+ * the operator but without teaching learned rules: the decision already says
+ * nothing is left. One failed thread is counted, never stops the rest.
+ */
+export async function clearFinishedNotifications({ accountId = null } = {}) {
+ const accounts = (await listAccounts()).filter(isActive).filter((account) => !accountId || account.id === accountId);
+ let cleared = 0;
+ let failed = 0;
+ for (const account of accounts) {
+ const { rows } = await query(
+ `SELECT thread_id, decision FROM github_notifications WHERE account_id = $1 AND state = 'open' AND NOT suspect AND ${FINISHED_SQL}
+ ORDER BY gh_updated_at DESC`,
+ [account.id],
+ );
+ for (const row of rows) {
+ const ok = await applyNotificationAction(account.id, row.thread_id, 'done', { learn: false, emit: false, detail: { decision: row.decision, bulk: 'finished' } })
+ .then(() => true)
+ .catch((error) => {
+ console.error(`❌ Could not mark GitHub notification ${row.thread_id} done for ${account.host}: ${error.message}`);
+ return false;
+ });
+ if (ok) cleared += 1;
+ else failed += 1;
+ }
+ if (rows.length) githubNotificationEvents.emit('changed', { accountId: account.id });
+ }
+ console.log(`🧹 Marked ${cleared} finished GitHub notification(s) done${failed ? `, ${failed} failed` : ''}`);
+ return { cleared, failed };
+}
+
// An automation action can be undone while the thread is still where it left
// it. GitHub has no "mark unread", so a read stays.
const UNDO_ACTIONS = { done: { action: 'reopen', state: 'done' }, mute: { action: 'resubscribe', state: 'muted' } };