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

feat: add app pull request management

[._.]/ Adam Eivye362ea9c3d19
diff --git a/client/src/components/apps/AppDetailView.jsx b/client/src/components/apps/AppDetailView.jsx
index 6625ac1a7c..2f6f2d07f8 100644
--- a/client/src/components/apps/AppDetailView.jsx
+++ b/client/src/components/apps/AppDetailView.jsx
@@ -19,6 +19,7 @@ import DocumentsTab from './tabs/DocumentsTab';
import GitTab from './tabs/GitTab';
import GsdTab from './tabs/GsdTab';
import IssuesTab from './tabs/IssuesTab';
+import PullRequestsTab from './tabs/PullRequestsTab';
import JiraTab from './tabs/JiraTab';
import ProcessesTab from './tabs/ProcessesTab';
import ReferencesTab from './tabs/ReferencesTab';
@@ -276,6 +277,8 @@ export default function AppDetailView() {
return <GsdTab appId={appId} repoPath={app.repoPath} />;
case 'issues':
return <IssuesTab appId={appId} appName={app.name} />;
+ case 'pull-requests':
+ return <PullRequestsTab appId={appId} appName={app.name} />;
case 'jira':
return <JiraTab app={app} onRefresh={fetchApp} />;
case 'processes':
diff --git a/client/src/components/apps/constants.js b/client/src/components/apps/constants.js
index eb76526e39..b644f6f68a 100644
--- a/client/src/components/apps/constants.js
+++ b/client/src/components/apps/constants.js
@@ -181,6 +181,7 @@ export const APP_DETAIL_TABS = [
{ id: 'git', label: 'Git' },
{ id: 'gsd', label: 'GSD', feature: 'gsd' },
{ id: 'issues', label: 'Issues' },
+ { id: 'pull-requests', label: 'PRs / MRs' },
{ id: 'jira', label: 'JIRA', feature: 'jira' },
{ id: 'processes', label: 'Processes' },
{ id: 'references', label: 'References' },
diff --git a/client/src/components/apps/tabs/PullRequestsTab.jsx b/client/src/components/apps/tabs/PullRequestsTab.jsx
new file mode 100644
index 0000000000..0d7a828199
--- /dev/null
+++ b/client/src/components/apps/tabs/PullRequestsTab.jsx
@@ -0,0 +1,418 @@
+import { useState, useEffect, useCallback, useMemo, useRef, useId } from 'react';
+import { Link } from 'react-router';
+import {
+ AlertTriangle, CheckCircle2, ExternalLink, GitBranch, GitMerge,
+ GitPullRequest, Loader2, RefreshCw, Rocket, Search, ShieldAlert, User
+} from 'lucide-react';
+import BrailleSpinner from '../../BrailleSpinner';
+import Banner from '../../ui/Banner';
+import Pill from '../../ui/Pill';
+import toast from '../../ui/Toast';
+import * as api from '../../../services/api';
+import socket from '../../../services/socket';
+import { timeAgo } from '../../../utils/formatters';
+
+const FORGE_LABEL = { github: 'GitHub', gitlab: 'GitLab' };
+
+const ACTION_STATUS_RANK = { queuing: 0, queued: 1, active: 2, completed: 3, blocked: 3 };
+const ACTION_STATUS_LABEL = {
+ queued: 'Queued — view',
+ active: 'Active — view',
+ completed: 'Completed — view',
+ blocked: 'Blocked — view',
+};
+
+const actionStatusForTask = status => ({
+ pending: 'queued',
+ in_progress: 'active',
+ completed: 'completed',
+ blocked: 'blocked',
+}[status] || null);
+
+const EMPTY_REASONS = {
+ 'no-repo-path': 'This app has no repo path configured.',
+ 'unsupported-forge': 'This app\'s git origin is not a GitHub or GitLab repository, so there are no PRs/MRs to list.',
+ 'no-open-pull-requests': 'No open pull requests or merge requests.',
+};
+
+const PASSING_CHECKS = new Set(['SUCCESS', 'PASSED', 'NEUTRAL', 'SKIPPED', 'COMPLETED']);
+const FAILING_CHECKS = new Set(['FAILURE', 'FAILED', 'ERROR', 'CANCELLED', 'CANCELED', 'TIMED_OUT', 'ACTION_REQUIRED']);
+
+function checkSummary(pullRequest) {
+ const checks = Array.isArray(pullRequest.checks) ? pullRequest.checks : [];
+ if (checks.some(check => FAILING_CHECKS.has(String(check.status || '').toUpperCase()))) {
+ return { label: 'Checks failing', tone: 'error', icon: ShieldAlert };
+ }
+ if (!checks.length || checks.some(check => !PASSING_CHECKS.has(String(check.status || '').toUpperCase()))) {
+ return { label: checks.length ? 'Checks pending' : 'Checks pending · none reported', tone: 'warning', icon: RefreshCw };
+ }
+ return { label: 'Checks passing', tone: 'success', icon: CheckCircle2 };
+}
+
+function reviewSummary(pullRequest) {
+ switch (String(pullRequest.reviewDecision || '').toUpperCase()) {
+ case 'APPROVED':
+ return { label: 'Approved', tone: 'success' };
+ case 'CHANGES_REQUESTED':
+ return { label: 'Changes requested', tone: 'error' };
+ case 'REVIEW_REQUIRED':
+ return { label: 'Review required', tone: 'warning' };
+ default:
+ return { label: 'Review pending', tone: 'muted' };
+ }
+}
+
+function mergeSummary(pullRequest) {
+ const status = String(pullRequest.mergeStateStatus || pullRequest.mergeable || '').toUpperCase();
+ if (['CLEAN', 'MERGEABLE', 'CAN_BE_MERGED'].includes(status)) {
+ return { label: 'Mergeable', tone: 'success' };
+ }
+ if (['DIRTY', 'CONFLICTING', 'CANNOT_BE_MERGED'].includes(status)) {
+ return { label: 'Conflicts', tone: 'error' };
+ }
+ if (['BLOCKED', 'CANNOT_BE_MERGED_RESTRICTED'].includes(status)) {
+ return { label: 'Merge blocked', tone: 'warning' };
+ }
+ if (status === 'BEHIND') return { label: 'Behind base', tone: 'warning' };
+ return { label: 'Mergeability pending', tone: 'muted' };
+}
+
+function actionStatusFromRecord(record) {
+ return record ? actionStatusForTask(record.status) : null;
+}
+
+function actionRank(status) {
+ return ACTION_STATUS_RANK[status] ?? -1;
+}
+
+/**
+ * Open PRs/MRs for a managed app. Each row includes the forge's review/check
+ * state and can queue the same PortOS review-loop agent used by PR cleanup.
+ */
+export default function PullRequestsTab({ appId, appName }) {
+ const searchId = useId();
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState('');
+ const [query, setQuery] = useState('');
+ const [actions, setActions] = useState({});
+ const actionsRef = useRef({});
+ const requestRef = useRef(0);
+
+ const replaceActions = useCallback(updater => {
+ const next = updater(actionsRef.current);
+ actionsRef.current = next;
+ setActions(next);
+ }, []);
+
+ useEffect(() => {
+ actionsRef.current = {};
+ setActions({});
+ }, [appId]);
+
+ useEffect(() => {
+ const subscribe = () => socket.emit('cos:subscribe');
+ if (socket.connected) subscribe();
+ socket.on('connect', subscribe);
+
+ const applyTaskUpdate = task => {
+ if (!task?.id) return;
+ const nextStatus = actionStatusForTask(task.status);
+ if (!nextStatus) return;
+
+ replaceActions(current => {
+ const next = { ...current };
+ let changed = false;
+ for (const [number, action] of Object.entries(current)) {
+ const matches = action.taskId === task.id || (
+ !action.taskId
+ && task.metadata?.app === appId
+ && Number(task.metadata?.reviewLoopPRNumber) === Number(number)
+ );
+ if (!matches || actionRank(nextStatus) < actionRank(action.status)) continue;
+ next[number] = { ...action, taskId: action.taskId || task.id, status: nextStatus };
+ changed = true;
+ }
+ return changed ? next : current;
+ });
+ };
+
+ const handleTaskChanged = event => applyTaskUpdate(event?.task);
+ const handleTaskListChanged = event => (event?.tasks || []).forEach(applyTaskUpdate);
+ const handleTaskCompleted = event => (event?.tasks || []).forEach(applyTaskUpdate);
+ const handleAgentSpawned = agent => {
+ if (agent?.taskId) applyTaskUpdate({ id: agent.taskId, status: 'in_progress' });
+ };
+ const handleAgentCompleted = agent => {
+ if (agent?.taskId && agent.result?.success === true) {
+ applyTaskUpdate({ id: agent.taskId, status: 'completed' });
+ }
+ };
+
+ socket.on('cos:tasks:changed', handleTaskChanged);
+ socket.on('cos:tasks:user:changed', handleTaskListChanged);
+ socket.on('cos:tasks:user:completed', handleTaskCompleted);
+ socket.on('cos:agent:spawned', handleAgentSpawned);
+ socket.on('cos:agent:completed', handleAgentCompleted);
+
+ return () => {
+ socket.off('connect', subscribe);
+ socket.off('cos:tasks:changed', handleTaskChanged);
+ socket.off('cos:tasks:user:changed', handleTaskListChanged);
+ socket.off('cos:tasks:user:completed', handleTaskCompleted);
+ socket.off('cos:agent:spawned', handleAgentSpawned);
+ socket.off('cos:agent:completed', handleAgentCompleted);
+ };
+ }, [appId, replaceActions]);
+
+ const load = useCallback(async () => {
+ const generation = requestRef.current + 1;
+ requestRef.current = generation;
+ const isCurrent = () => requestRef.current === generation;
+
+ setLoading(true);
+ setError('');
+ const result = await api.getAppPullRequests(appId).catch(err => {
+ if (isCurrent()) setError(err?.message || 'Failed to load pull requests');
+ return null;
+ });
+ if (!isCurrent()) return;
+ setLoading(false);
+ if (!result) return;
+
+ setData(result);
+ replaceActions(previous => {
+ const next = { ...previous };
+ for (const pullRequest of result.pullRequests || []) {
+ const serverAction = actionStatusFromRecord(pullRequest.agentAction);
+ if (!serverAction) continue;
+ const current = next[pullRequest.number];
+ if (!current || actionRank(serverAction) >= actionRank(current.status)) {
+ next[pullRequest.number] = {
+ ...(current || {}),
+ taskId: current?.taskId || pullRequest.agentAction.taskId || null,
+ status: serverAction,
+ };
+ }
+ }
+ return next;
+ });
+ }, [appId, replaceActions]);
+
+ useEffect(() => { load(); }, [load]);
+
+ const filteredPullRequests = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ if (!q) return data?.pullRequests || [];
+ return (data?.pullRequests || []).filter(pullRequest => [
+ pullRequest.number,
+ pullRequest.title,
+ pullRequest.author,
+ pullRequest.headBranch,
+ pullRequest.baseBranch,
+ ...(pullRequest.labels || []),
+ ].some(value => String(value || '').toLowerCase().includes(q)));
+ }, [data, query]);
+
+ const total = data?.pullRequests?.length ?? 0;
+ const forgeLabel = FORGE_LABEL[data?.forge] || 'Forge';
+ const requestNoun = data?.forge === 'gitlab' ? 'merge requests' : 'pull requests';
+ const unavailable = data?.transient === true;
+
+ const handleResolve = async pullRequest => {
+ replaceActions(previous => ({
+ ...previous,
+ [pullRequest.number]: { status: 'queuing', taskId: null },
+ }));
+ const result = await api.resolveAppPullRequest(appId, pullRequest.number).catch(err => {
+ toast.error(err?.message || `Failed to queue an agent for #${pullRequest.number}`);
+ return null;
+ });
+ if (!result) {
+ replaceActions(previous => {
+ const next = { ...previous };
+ delete next[pullRequest.number];
+ return next;
+ });
+ return;
+ }
+
+ const taskStatus = actionStatusForTask(result.task?.status) || 'queued';
+ replaceActions(previous => {
+ const current = previous[pullRequest.number];
+ const status = actionRank(taskStatus) >= actionRank(current?.status)
+ ? taskStatus
+ : current?.status;
+ return {
+ ...previous,
+ [pullRequest.number]: {
+ ...(current || {}),
+ taskId: current?.taskId || result.task?.id || null,
+ status,
+ },
+ };
+ });
+ toast.success(result.duplicate
+ ? `An agent is already resolving ${forgeLabel} #${pullRequest.number}`
+ : `Queued an agent to resolve and merge ${forgeLabel} #${pullRequest.number}`);
+ };
+
+ if (loading && !data) return <BrailleSpinner text="Loading pull requests" />;
+
+ return (
+ <div className="space-y-4">
+ <div className="flex flex-wrap items-center gap-3">
+ <h3 className="text-lg font-semibold text-white">
+ {forgeLabel} PRs / MRs
+ {data?.fullName && <span className="ml-2 text-xs font-mono text-gray-500">{data.fullName}</span>}
+ </h3>
+ {total > 0 && (
+ <span className="text-xs text-gray-500">
+ {filteredPullRequests.length === total ? `${total} open` : `${filteredPullRequests.length} of ${total} open`}
+ </span>
+ )}
+ <div className="relative ml-auto">
+ <label htmlFor={searchId} className="sr-only">Filter pull requests</label>
+ <Search size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-500" />
+ <input
+ id={searchId}
+ type="search"
+ value={query}
+ onChange={event => setQuery(event.target.value)}
+ placeholder="Filter by title, branch, author…"
+ className="w-full sm:w-72 pl-8 pr-3 py-1.5 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden"
+ />
+ </div>
+ <button
+ type="button"
+ onClick={load}
+ disabled={loading}
+ className="px-3 py-1.5 bg-port-border hover:bg-port-border/80 text-white rounded-lg text-xs flex items-center gap-1 disabled:opacity-50"
+ >
+ <RefreshCw size={14} className={loading ? 'animate-spin' : ''} /> Refresh
+ </button>
+ </div>
+
+ <div className="px-3 py-2 text-xs text-gray-500 bg-port-card border border-port-border rounded-lg">
+ Resolve and merge queues a PortOS agent to inspect feedback, fix the branch, wait for checks, and merge when the forge allows it. It uses the configured Code Review Defaults.
+ </div>
+
+ {error && (
+ <Banner tone="error" size="md" icon={AlertTriangle}>
+ Couldn&apos;t load pull requests — {error}
+ </Banner>
+ )}
+
+ {!error && unavailable && (
+ <Banner tone="warning" size="md" icon={AlertTriangle}>
+ {data.headline || `Couldn't reach ${forgeLabel}`} ({data.reason})
+ {data.remedy ? ` — ${data.remedy}.` : ''}
+ </Banner>
+ )}
+
+ {!error && !unavailable && total === 0 && (
+ <div className="px-3 py-2 text-sm text-gray-500 bg-port-card border border-port-border rounded-lg">
+ {EMPTY_REASONS[data?.reason] ?? EMPTY_REASONS['no-open-pull-requests']}
+ </div>
+ )}
+
+ {filteredPullRequests.length === 0 && total > 0 && (
+ <div className="px-3 py-2 text-sm text-gray-500 bg-port-card border border-port-border rounded-lg">
+ No open {requestNoun} match &ldquo;{query}&rdquo;.
+ </div>
+ )}
+
+ {filteredPullRequests.length > 0 && (
+ <div className="border border-port-border rounded-lg divide-y divide-port-border overflow-hidden">
+ {filteredPullRequests.map(pullRequest => {
+ const action = actions[pullRequest.number];
+ const actionStatus = action?.status;
+ const review = reviewSummary(pullRequest);
+ const checks = checkSummary(pullRequest);
+ const merge = mergeSummary(pullRequest);
+ const openStatus = pullRequest.isDraft
+ ? { label: 'Draft', tone: 'warning' }
+ : { label: 'Open', tone: 'success' };
+
+ return (
+ <div key={pullRequest.number} className="bg-port-card p-3">
+ <div className="flex flex-col lg:flex-row lg:items-start gap-3">
+ <div className="flex-1 min-w-0">
+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">
+ <GitPullRequest size={15} className="text-port-accent shrink-0 self-center" />
+ <span className="text-xs font-mono text-gray-500">#{pullRequest.number}</span>
+ {pullRequest.url ? (
+ <a
+ href={pullRequest.url}
+ target="_blank"
+ rel="noreferrer"
+ className="text-sm text-white hover:text-port-accent transition-colors break-words"
+ >
+ {pullRequest.title || '(untitled)'}
+ </a>
+ ) : (
+ <span className="text-sm text-white break-words">{pullRequest.title || '(untitled)'}</span>
+ )}
+ {pullRequest.url && (
+ <a
+ href={pullRequest.url}
+ target="_blank"
+ rel="noreferrer"
+ aria-label={`Open ${forgeLabel} request ${pullRequest.number}`}
+ className="text-gray-500 hover:text-port-accent transition-colors self-center"
+ >
+ <ExternalLink size={12} />
+ </a>
+ )}
+ <Pill tone={openStatus.tone} size="xs">{openStatus.label}</Pill>
+ </div>
+
+ <div className="flex flex-wrap gap-1.5 mt-2">
+ <Pill tone={review.tone} size="xs">{review.label}</Pill>
+ <Pill tone={checks.tone} size="xs" icon={checks.icon}>{checks.label}</Pill>
+ <Pill tone={merge.tone} size="xs" icon={merge.tone === 'success' ? GitMerge : undefined}>{merge.label}</Pill>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 mt-2 text-xs text-gray-500">
+ {pullRequest.author && <span className="flex items-center gap-1"><User size={12} /> {pullRequest.author}</span>}
+ {(pullRequest.headBranch || pullRequest.baseBranch) && (
+ <span className="flex items-center gap-1 font-mono">
+ <GitBranch size={12} /> {pullRequest.headBranch || '?'} → {pullRequest.baseBranch || '?'}
+ </span>
+ )}
+ {pullRequest.updatedAt && <span>updated {timeAgo(pullRequest.updatedAt)}</span>}
+ </div>
+ </div>
+
+ <div className="shrink-0 lg:pt-0.5">
+ {actionStatus && actionStatus !== 'queuing' ? (
+ <Link
+ to="/cos/agents"
+ className="px-3 py-1.5 bg-port-success/20 text-port-success hover:bg-port-success/30 border border-port-border rounded-lg text-xs flex items-center gap-1.5 transition-colors"
+ >
+ <Rocket size={14} /> {ACTION_STATUS_LABEL[actionStatus] || 'Queued — view'}
+ </Link>
+ ) : (
+ <button
+ type="button"
+ onClick={() => handleResolve(pullRequest)}
+ disabled={actionStatus === 'queuing'}
+ title={`Queue a CoS agent to resolve and merge ${forgeLabel} request #${pullRequest.number} for ${appName}`}
+ className="px-3 py-1.5 bg-port-accent/20 text-port-accent enabled:hover:bg-port-accent/30 border border-port-border rounded-lg text-xs flex items-center gap-1.5 disabled:opacity-50 transition-colors"
+ >
+ {actionStatus === 'queuing'
+ ? <Loader2 size={14} className="animate-spin" />
+ : <Rocket size={14} />}
+ {actionStatus === 'queuing' ? 'Queuing…' : 'Resolve & merge'}
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/apps/tabs/PullRequestsTab.test.jsx b/client/src/components/apps/tabs/PullRequestsTab.test.jsx
new file mode 100644
index 0000000000..82b3ab1e43
--- /dev/null
+++ b/client/src/components/apps/tabs/PullRequestsTab.test.jsx
@@ -0,0 +1,162 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { render, screen, fireEvent, cleanup, waitFor, act } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+
+const { socketHandlers, socketMock } = vi.hoisted(() => {
+ const handlers = new Map();
+ const mock = {
+ connected: true,
+ on: vi.fn((event, handler) => handlers.set(event, handler)),
+ off: vi.fn((event, handler) => {
+ if (handlers.get(event) === handler) handlers.delete(event);
+ }),
+ emit: vi.fn(),
+ };
+ return { socketHandlers: handlers, socketMock: mock };
+});
+
+vi.mock('../../../services/socket', () => ({ default: socketMock }));
+vi.mock('../../../services/api', () => ({
+ getAppPullRequests: vi.fn(),
+ resolveAppPullRequest: vi.fn(),
+}));
+
+import * as api from '../../../services/api';
+import PullRequestsTab from './PullRequestsTab';
+
+const PULL_REQUEST = {
+ number: 17,
+ title: 'Fix the save path',
+ url: 'https://github.com/acme/widget/pull/17',
+ state: 'open',
+ author: 'alice',
+ createdAt: '2026-08-01T00:00:00Z',
+ updatedAt: '2026-08-02T00:00:00Z',
+ isDraft: false,
+ headBranch: 'fix/save-path',
+ baseBranch: 'main',
+ reviewDecision: 'CHANGES_REQUESTED',
+ mergeStateStatus: 'DIRTY',
+ mergeable: 'CONFLICTING',
+ labels: ['bug'],
+ checks: [
+ { name: 'unit', status: 'SUCCESS', url: null },
+ { name: 'lint', status: 'SUCCESS', url: null },
+ ],
+};
+
+const okPayload = (pullRequests) => ({
+ forge: 'github',
+ fullName: 'acme/widget',
+ pullRequests,
+ reason: pullRequests.length ? 'ok' : 'no-open-pull-requests',
+ transient: false,
+ headline: null,
+ remedy: null,
+});
+
+const renderTab = async () => {
+ const result = render(
+ <MemoryRouter>
+ <PullRequestsTab appId="app-1" appName="Widget" />
+ </MemoryRouter>,
+ );
+ await act(async () => {});
+ return result;
+};
+
+beforeEach(() => {
+ socketHandlers.clear();
+ socketMock.on.mockClear();
+ socketMock.off.mockClear();
+ socketMock.emit.mockClear();
+ api.getAppPullRequests.mockResolvedValue(okPayload([PULL_REQUEST]));
+ api.resolveAppPullRequest.mockResolvedValue({
+ task: { id: 'task-1', status: 'pending' },
+ duplicate: false,
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe('PullRequestsTab', () => {
+ it('loads open requests and renders review, check, merge, author, and branch state', async () => {
+ await renderTab();
+
+ expect(await screen.findByText('Fix the save path')).toBeInTheDocument();
+ expect(api.getAppPullRequests).toHaveBeenCalledWith('app-1');
+ expect(screen.getByText('#17')).toBeInTheDocument();
+ expect(screen.getByText('Changes requested')).toBeInTheDocument();
+ expect(screen.getByText('Checks passing')).toBeInTheDocument();
+ expect(screen.getByText('Conflicts')).toBeInTheDocument();
+ expect(screen.getByText(/alice/)).toBeInTheDocument();
+ expect(screen.getByText(/fix\/save-path/)).toBeInTheDocument();
+ expect(screen.getByText('acme/widget')).toBeInTheDocument();
+ });
+
+ it('queues a review-loop resolve action and shows its task state', async () => {
+ await renderTab();
+
+ fireEvent.click(await screen.findByRole('button', { name: /Resolve & merge/ }));
+
+ await waitFor(() => expect(api.resolveAppPullRequest).toHaveBeenCalledWith('app-1', 17));
+ expect(await screen.findByRole('link', { name: /Queued/ })).toBeInTheDocument();
+ });
+
+ it('tracks queued, active, and completed action states from the CoS socket', async () => {
+ await renderTab();
+
+ fireEvent.click(await screen.findByRole('button', { name: /Resolve & merge/ }));
+ expect(await screen.findByRole('link', { name: /Queued/ })).toBeInTheDocument();
+
+ act(() => socketHandlers.get('cos:tasks:changed')({
+ task: { id: 'task-1', status: 'in_progress' },
+ }));
+ expect(await screen.findByRole('link', { name: /Active/ })).toBeInTheDocument();
+
+ act(() => socketHandlers.get('cos:tasks:changed')({
+ task: { id: 'task-1', status: 'completed' },
+ }));
+ expect(await screen.findByRole('link', { name: /Completed/ })).toBeInTheDocument();
+ });
+
+ it('hydrates an active server-side resolve action without offering another button', async () => {
+ api.getAppPullRequests.mockResolvedValue(okPayload([{
+ ...PULL_REQUEST,
+ agentAction: { taskId: 'task-active', status: 'in_progress' },
+ }]));
+
+ await renderTab();
+
+ expect(await screen.findByRole('link', { name: /Active/ })).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /Resolve & merge/ })).not.toBeInTheDocument();
+ });
+
+ it('keeps forge failures distinct from a healthy empty list', async () => {
+ api.getAppPullRequests.mockResolvedValue({
+ forge: 'github',
+ fullName: 'acme/widget',
+ pullRequests: [],
+ reason: 'gh-unauthenticated',
+ transient: true,
+ headline: "Couldn't reach GitHub",
+ remedy: 'run gh auth login',
+ });
+
+ await renderTab();
+
+ expect(await screen.findByText(/Couldn't reach GitHub/)).toBeInTheDocument();
+ expect(screen.queryByText('No open pull requests or merge requests.')).not.toBeInTheDocument();
+ });
+
+ it('shows a healthy empty state when the forge answers with no open requests', async () => {
+ api.getAppPullRequests.mockResolvedValue(okPayload([]));
+
+ await renderTab();
+
+ expect(await screen.findByText('No open pull requests or merge requests.')).toBeInTheDocument();
+ });
+});
diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.js
index 1ec6606313..c8562f76cc 100644
--- a/client/src/services/apiApps.js
+++ b/client/src/services/apiApps.js
@@ -29,6 +29,19 @@ export const getAppWorkItems = (id, { issueAuthorFilter } = {}, options) => {
// Read-only; the tab owns its own error UI, so default to silent.
export const getAppIssues = (id, options) =>
request(`/apps/${id}/issues`, { silent: true, ...options });
+// Every OPEN PR/MR on the app's GitHub/GitLab origin, including review/check
+// state and any active PortOS resolve action. The tab owns its error UI, so
+// default to silent.
+export const getAppPullRequests = (id, options) =>
+ request(`/apps/${id}/pull-requests`, { silent: true, ...options });
+// Queue the shared review-loop follow-up for one freshly verified open PR/MR.
+// The server, not the browser, owns the forge URL/branch and duplicate guard.
+export const resolveAppPullRequest = (id, number, options = {}) =>
+ request(`/apps/${id}/pull-requests/${encodeURIComponent(number)}/resolve`, {
+ method: 'POST',
+ silent: true,
+ ...options,
+ });
// Effective Layered Intelligence config (self-improvement loop) for an app —
// stored partial merged over the shipped defaults. Read-only; saved through
// updateApp (the `layeredIntelligence` key routes to the merge helper server-
diff --git a/server/routes/apps/index.js b/server/routes/apps/index.js
index c62987b20d..15e1ea7619 100644
--- a/server/routes/apps/index.js
+++ b/server/routes/apps/index.js
@@ -12,6 +12,7 @@
* icons — icon serving + detection
* taskTypes — per-app task-type overrides, work-tracker, layered-intelligence
* issues — open GitHub/GitLab issues for the Issues tab
+ * pullRequests — open GitHub/GitLab PRs/MRs and review-loop actions
* launch — open-editor, open-claude, open-folder, open-xcode
* documents — planning-doc read/list/commit
* agents — recent CoS agent history
@@ -32,6 +33,7 @@ import xcodeRoutes from './xcode.js';
import iconRoutes from './icons.js';
import taskTypeRoutes from './taskTypes.js';
import issueRoutes from './issues.js';
+import pullRequestRoutes from './pullRequests.js';
import launchRoutes from './launch.js';
import documentRoutes from './documents.js';
import agentRoutes from './agents.js';
@@ -46,6 +48,7 @@ router.use(xcodeRoutes);
router.use(iconRoutes);
router.use(taskTypeRoutes);
router.use(issueRoutes);
+router.use(pullRequestRoutes);
router.use(launchRoutes);
router.use(documentRoutes);
router.use(agentRoutes);
diff --git a/server/routes/apps/pullRequests.js b/server/routes/apps/pullRequests.js
new file mode 100644
index 0000000000..71f7189b9b
--- /dev/null
+++ b/server/routes/apps/pullRequests.js
@@ -0,0 +1,201 @@
+/**
+ * App pull-request / merge-request routes.
+ *
+ * GET /:id/pull-requests → open forge requests
+ * POST /:id/pull-requests/:number/resolve → queue a review-loop agent
+ *
+ * The POST route only queues PortOS's existing review-loop follow-up. The
+ * follow-up owns fetching feedback, fixing the branch, waiting for checks, and
+ * merging; this route never merges a user's PR directly.
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
+import { claimSafeReviewers, normalizeReviewers, validateRequest } from '../../lib/validation.js';
+import { PR_COMPLETIONS } from '../../lib/prDisposition.js';
+import { isTruthyMeta } from '../../services/agentState.js';
+import { resolveReviewLoopOptions } from '../../services/codeReview.js';
+import { getAllTasks } from '../../services/cos.js';
+import { spawnReviewLoopFollowUp } from '../../services/agentWorktreeCleanup.js';
+import { listAppPullRequests } from '../../services/appPullRequests.js';
+import { loadApp } from './shared.js';
+
+const router = Router();
+
+const pullRequestParamsSchema = z.object({
+ number: z.coerce.number().int().positive(),
+});
+
+const ACTIVE_TASK_STATUSES = new Set(['pending', 'in_progress', 'blocked']);
+
+const flattenTasks = (taskData) => [
+ ...(Array.isArray(taskData?.user?.tasks) ? taskData.user.tasks : []),
+ ...(Array.isArray(taskData?.cos?.tasks) ? taskData.cos.tasks : []),
+];
+
+const isResolveTaskFor = (task, appId, pullRequest) => {
+ const metadata = task?.metadata;
+ return ACTIVE_TASK_STATUSES.has(task?.status)
+ && isTruthyMeta(metadata?.reviewLoopFollowUp)
+ && metadata?.app === appId
+ && Number(metadata.reviewLoopPRNumber) === pullRequest.number;
+};
+
+async function readActiveResolveTasks() {
+ const taskData = await getAllTasks().catch(err => {
+ console.error(`❌ app-pull-requests: could not read CoS tasks: ${err.message}`);
+ return null;
+ });
+ if (!Array.isArray(taskData?.user?.tasks) || !Array.isArray(taskData?.cos?.tasks)) {
+ if (taskData) console.error('❌ app-pull-requests: CoS task response had an invalid shape');
+ return null;
+ }
+ return flattenTasks(taskData);
+}
+
+function actionFor(pullRequest, tasks, appId) {
+ if (!tasks) return null;
+ const task = tasks.find(candidate => isResolveTaskFor(candidate, appId, pullRequest));
+ return task ? { taskId: task.id, status: task.status } : null;
+}
+
+const taskResponse = task => task ? {
+ id: task.id,
+ status: task.status,
+ description: task.description,
+} : null;
+
+async function listWithActionState(app) {
+ const result = await listAppPullRequests(app);
+ const pullRequests = Array.isArray(result?.pullRequests) ? result.pullRequests : [];
+ if (!pullRequests.length || result.transient) return { result, tasks: null };
+
+ const tasks = await readActiveResolveTasks();
+ return {
+ result: {
+ ...result,
+ pullRequests: pullRequests.map(pullRequest => ({
+ ...pullRequest,
+ agentAction: actionFor(pullRequest, tasks, app.id),
+ })),
+ },
+ tasks,
+ };
+}
+
+function throwForgeReadError(result) {
+ if (!result.transient) return;
+ throw new ServerError(
+ result.headline || 'Could not read open pull requests',
+ {
+ status: 503,
+ code: 'FORGE_UNAVAILABLE',
+ context: {
+ reason: result.reason,
+ remedy: result.remedy || undefined,
+ },
+ },
+ );
+}
+
+// GET /api/apps/:id/pull-requests — list every open PR/MR on the app's forge.
+// This intentionally does not gate on the app's Work Tracker: a PLAN.md or
+// JIRA app can still have a forge change request that needs attention.
+router.get('/:id/pull-requests', loadApp, asyncHandler(async (req, res) => {
+ const app = req.loadedApp;
+ const { result } = await listWithActionState(app);
+ res.json({ appId: app.id, appName: app.name, ...result });
+}));
+
+// POST /api/apps/:id/pull-requests/:number/resolve — queue the existing review
+// loop against a freshly-read open PR/MR. Re-reading before queueing prevents a
+// closed or replaced request from being attached to an agent by stale UI data.
+router.post('/:id/pull-requests/:number/resolve', loadApp, asyncHandler(async (req, res) => {
+ const app = req.loadedApp;
+ const { number } = validateRequest(pullRequestParamsSchema, req.params);
+ const { result, tasks } = await listWithActionState(app);
+ throwForgeReadError(result);
+
+ if (tasks === null && result.pullRequests.length > 0) {
+ throw new ServerError('Could not inspect existing CoS actions before queueing this request', {
+ status: 503,
+ code: 'AGENT_ACTION_UNAVAILABLE',
+ });
+ }
+
+ const pullRequest = result.pullRequests.find(candidate => candidate.number === number);
+ if (!pullRequest) {
+ throw new ServerError(`Open pull request or merge request #${number} was not found`, {
+ status: 404,
+ code: 'PULL_REQUEST_NOT_OPEN',
+ });
+ }
+ if (!pullRequest.url || !pullRequest.headBranch) {
+ throw new ServerError(`Pull request or merge request #${number} has no usable forge URL or source branch`, {
+ status: 502,
+ code: 'PULL_REQUEST_CONTEXT_UNAVAILABLE',
+ });
+ }
+
+ const existing = tasks?.find(task => isResolveTaskFor(task, app.id, pullRequest));
+ if (existing) {
+ res.json({
+ appId: app.id,
+ appName: app.name,
+ pullRequest,
+ task: taskResponse(existing),
+ duplicate: true,
+ });
+ return;
+ }
+
+ // Code Review Defaults are the one source for the installed review roster.
+ // `claimSafeReviewers` removes forge-side Copilot and supplies PortOS's
+ // unattended coding-review fallback when the defaults contain only Copilot.
+ const reviewOptions = await resolveReviewLoopOptions({}, {
+ normalize: normalizeReviewers,
+ isTruthyMeta,
+ });
+ const reviewers = claimSafeReviewers(reviewOptions.reviewers);
+ const optionalReviewers = (reviewOptions.optionalReviewers || [])
+ .filter(reviewer => reviewer !== 'copilot');
+ const appLabel = String(app.name || app.id).replace(/\s+/g, ' ').trim();
+ const title = String(pullRequest.title || '(untitled)').replace(/\s+/g, ' ').trim();
+ const originalTask = {
+ id: `app-pr-${app.id}-${number}`,
+ status: 'pending',
+ priority: 'HIGH',
+ description: `Resolve and merge ${result.forge === 'gitlab' ? 'MR' : 'PR'} #${number} for ${appLabel}: ${title}`,
+ metadata: { app: app.id },
+ };
+
+ const task = await spawnReviewLoopFollowUp({
+ originalAgentId: null,
+ originalTask,
+ prUrl: pullRequest.url,
+ prBranch: pullRequest.headBranch,
+ sourceWorkspace: app.repoPath,
+ prCompletion: PR_COMPLETIONS.REVIEW_THEN_MERGE,
+ ...reviewOptions,
+ reviewers,
+ optionalReviewers,
+ });
+ if (!task) {
+ throw new ServerError('Could not queue the pull-request resolve agent', {
+ status: 503,
+ code: 'AGENT_ACTION_UNAVAILABLE',
+ });
+ }
+
+ console.log(`🚀 Queued PR resolve agent ${task.id} for app ${app.id} request #${number}`);
+ res.status(task.duplicate ? 200 : 202).json({
+ appId: app.id,
+ appName: app.name,
+ pullRequest: { ...pullRequest, agentAction: { taskId: task.id, status: task.status } },
+ task: taskResponse(task),
+ duplicate: task.duplicate === true,
+ });
+}));
+
+export default router;
diff --git a/server/routes/apps/pullRequests.test.js b/server/routes/apps/pullRequests.test.js
new file mode 100644
index 0000000000..6a1eca5b32
--- /dev/null
+++ b/server/routes/apps/pullRequests.test.js
@@ -0,0 +1,177 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../../lib/testHelper.js';
+import pullRequestRoutes from './pullRequests.js';
+
+vi.mock('../../services/apps.js', () => ({
+ getAppById: vi.fn(),
+}));
+vi.mock('../../services/appPullRequests.js', () => ({
+ listAppPullRequests: vi.fn(),
+}));
+vi.mock('../../services/cos.js', () => ({
+ getAllTasks: vi.fn(),
+}));
+vi.mock('../../services/codeReview.js', () => ({
+ resolveReviewLoopOptions: vi.fn(),
+}));
+vi.mock('../../services/agentWorktreeCleanup.js', () => ({
+ spawnReviewLoopFollowUp: vi.fn(),
+}));
+
+import * as appsService from '../../services/apps.js';
+import { listAppPullRequests } from '../../services/appPullRequests.js';
+import { getAllTasks } from '../../services/cos.js';
+import { resolveReviewLoopOptions } from '../../services/codeReview.js';
+import { spawnReviewLoopFollowUp } from '../../services/agentWorktreeCleanup.js';
+
+const APP = { id: 'app-001', name: 'Widget', repoPath: '/repo', workTracker: 'auto' };
+const PULL_REQUEST = {
+ number: 17,
+ title: 'Fix the save path',
+ url: 'https://github.com/acme/widget/pull/17',
+ headBranch: 'fix/save-path',
+};
+
+const listResult = () => ({
+ forge: 'github',
+ tracker: 'github',
+ fullName: 'acme/widget',
+ pullRequests: [PULL_REQUEST],
+ reason: 'ok',
+ transient: false,
+ headline: null,
+ remedy: null,
+});
+
+describe('app pull-request routes', () => {
+ let app;
+
+ beforeEach(() => {
+ app = express();
+ app.use(express.json());
+ app.use('/api/apps', pullRequestRoutes);
+ vi.clearAllMocks();
+ appsService.getAppById.mockResolvedValue(APP);
+ listAppPullRequests.mockResolvedValue(listResult());
+ getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } });
+ resolveReviewLoopOptions.mockResolvedValue({
+ reviewers: ['copilot'],
+ usernames: [],
+ optionalReviewers: [],
+ reviewerMaxRounds: {},
+ reviewStopMode: 'all',
+ reviewerApplies: false,
+ reviewerModels: null,
+ reviewerEfforts: null,
+ });
+ spawnReviewLoopFollowUp.mockResolvedValue({
+ id: 'sys-rl-1',
+ status: 'pending',
+ description: '[Review Loop] Resolve and merge PR #17 for Widget (https://github.com/acme/widget/pull/17)',
+ });
+ });
+
+ it('lists open requests and annotates an active resolve task', async () => {
+ getAllTasks.mockResolvedValue({
+ user: { tasks: [] },
+ cos: { tasks: [{
+ id: 'sys-rl-existing',
+ status: 'in_progress',
+ description: 'existing',
+ metadata: { app: 'app-001', reviewLoopFollowUp: true, reviewLoopPRNumber: 17 },
+ }] },
+ });
+
+ const response = await request(app).get('/api/apps/app-001/pull-requests');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toMatchObject({ appId: 'app-001', appName: 'Widget', forge: 'github' });
+ expect(response.body.pullRequests[0].agentAction).toEqual({ taskId: 'sys-rl-existing', status: 'in_progress' });
+ });
+
+ it('preserves the transient forge sentinel', async () => {
+ listAppPullRequests.mockResolvedValue({
+ forge: 'github', fullName: 'acme/widget', pullRequests: [],
+ reason: 'gh-unauthenticated', transient: true, remedy: 'run gh auth login',
+ headline: "Couldn't reach GitHub",
+ });
+
+ const response = await request(app).get('/api/apps/app-001/pull-requests');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toMatchObject({ reason: 'gh-unauthenticated', transient: true, remedy: 'run gh auth login' });
+ });
+
+ it('queues the shared review-loop follow-up with a non-Copilot coding reviewer', async () => {
+ const response = await request(app).post('/api/apps/app-001/pull-requests/17/resolve');
+
+ expect(response.status).toBe(202);
+ expect(spawnReviewLoopFollowUp).toHaveBeenCalledWith(expect.objectContaining({
+ originalTask: expect.objectContaining({
+ id: 'app-pr-app-001-17',
+ metadata: { app: 'app-001' },
+ }),
+ prUrl: PULL_REQUEST.url,
+ prBranch: 'fix/save-path',
+ sourceWorkspace: '/repo',
+ reviewers: ['codex'],
+ }));
+ expect(response.body).toMatchObject({
+ task: { id: 'sys-rl-1', status: 'pending' },
+ duplicate: false,
+ pullRequest: { agentAction: { taskId: 'sys-rl-1', status: 'pending' } },
+ });
+ });
+
+ it('returns the existing active task instead of queuing a duplicate', async () => {
+ const existing = {
+ id: 'sys-rl-existing',
+ status: 'blocked',
+ description: 'existing',
+ metadata: { app: 'app-001', reviewLoopFollowUp: true, reviewLoopPRNumber: 17 },
+ };
+ getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [existing] } });
+
+ const response = await request(app).post('/api/apps/app-001/pull-requests/17/resolve');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toMatchObject({ duplicate: true, task: { id: 'sys-rl-existing', status: 'blocked' } });
+ expect(spawnReviewLoopFollowUp).not.toHaveBeenCalled();
+ });
+
+ it('fails closed when active CoS task state cannot be read', async () => {
+ getAllTasks.mockRejectedValue(new Error('task store unavailable'));
+
+ const response = await request(app).post('/api/apps/app-001/pull-requests/17/resolve');
+
+ expect(response.status).toBe(503);
+ expect(response.body.code).toBe('AGENT_ACTION_UNAVAILABLE');
+ expect(spawnReviewLoopFollowUp).not.toHaveBeenCalled();
+ });
+
+ it('rejects a request that is no longer open', async () => {
+ listAppPullRequests.mockResolvedValue({ ...listResult(), pullRequests: [] });
+
+ const response = await request(app).post('/api/apps/app-001/pull-requests/17/resolve');
+
+ expect(response.status).toBe(404);
+ expect(spawnReviewLoopFollowUp).not.toHaveBeenCalled();
+ });
+
+ it('validates the PR/MR number before querying the forge', async () => {
+ const response = await request(app).post('/api/apps/app-001/pull-requests/not-a-number/resolve');
+
+ expect(response.status).toBe(400);
+ expect(listAppPullRequests).not.toHaveBeenCalled();
+ });
+
+ it('returns 404 for an unknown app', async () => {
+ appsService.getAppById.mockResolvedValue(null);
+
+ const response = await request(app).get('/api/apps/app-999/pull-requests');
+
+ expect(response.status).toBe(404);
+ expect(listAppPullRequests).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/appPullRequests.js b/server/services/appPullRequests.js
new file mode 100644
index 0000000000..fa627adde4
--- /dev/null
+++ b/server/services/appPullRequests.js
@@ -0,0 +1,219 @@
+/**
+ * Open pull-request / merge-request listing for a managed app's PR tab.
+ *
+ * This is deliberately separate from `prWatcher.js`: the watcher only needs a
+ * small GitHub-shaped row to decide whether to dispatch a scheduled task, while
+ * the app UI needs the review, merge, and check state the user sees before
+ * asking an agent to resolve a change request.
+ *
+ * Read-only. The resolve action is owned by the app route and queues the shared
+ * review-loop follow-up; this service never changes a forge or calls an LLM.
+ */
+
+import { execGh, ensureForgeReachable } from './github.js';
+import { execGlabJson } from './gitlab.js';
+import { resolveAppForgeTarget } from '../lib/workTracker.js';
+import { safeJSONParse } from '../lib/fileUtils.js';
+
+const GH_LIST_LIMIT = 200;
+const GL_PER_PAGE = 100;
+
+const GH_PR_FIELDS = [
+ 'number', 'title', 'author', 'url', 'createdAt', 'updatedAt', 'isDraft',
+ 'headRefName', 'baseRefName', 'reviewDecision', 'mergeStateStatus',
+ 'mergeable', 'statusCheckRollup', 'labels'
+].join(',');
+
+const baseResult = {
+ forge: null,
+ tracker: null,
+ fullName: null,
+ pullRequests: [],
+ transient: false,
+ headline: null,
+ remedy: null,
+};
+
+const normalizeStatus = (value, fallback = 'PENDING') => {
+ const status = typeof value === 'string' ? value.trim().toUpperCase() : '';
+ return status || fallback;
+};
+
+function normalizeCheck(check, fallbackName = 'Check') {
+ return {
+ name: [check?.name, check?.workflowName, check?.context]
+ .find(value => typeof value === 'string' && value) || fallbackName,
+ status: normalizeStatus(check?.conclusion || check?.state || check?.status),
+ url: [check?.detailsUrl, check?.targetUrl, check?.web_url]
+ .find(value => typeof value === 'string' && value) || null,
+ };
+}
+
+function normalizeGithubPullRequest(pr) {
+ return {
+ number: Number(pr?.number),
+ title: typeof pr?.title === 'string' ? pr.title : '',
+ url: typeof pr?.url === 'string' ? pr.url : '',
+ state: 'open',
+ author: typeof pr?.author?.login === 'string' ? pr.author.login : null,
+ createdAt: typeof pr?.createdAt === 'string' ? pr.createdAt : null,
+ updatedAt: typeof pr?.updatedAt === 'string' ? pr.updatedAt : null,
+ isDraft: pr?.isDraft === true,
+ headBranch: typeof pr?.headRefName === 'string' ? pr.headRefName : '',
+ baseBranch: typeof pr?.baseRefName === 'string' ? pr.baseRefName : '',
+ reviewDecision: typeof pr?.reviewDecision === 'string' ? pr.reviewDecision : null,
+ mergeStateStatus: typeof pr?.mergeStateStatus === 'string' ? pr.mergeStateStatus : null,
+ mergeable: typeof pr?.mergeable === 'string' ? pr.mergeable : null,
+ labels: Array.isArray(pr?.labels)
+ ? pr.labels.map(label => label?.name).filter(label => typeof label === 'string' && label)
+ : [],
+ checks: Array.isArray(pr?.statusCheckRollup)
+ ? pr.statusCheckRollup.filter(Boolean).map(check => normalizeCheck(check))
+ : [],
+ };
+}
+
+function normalizeGitlabPipeline(mr) {
+ const pipeline = mr?.head_pipeline || mr?.pipeline;
+ if (!pipeline) return [];
+ return [normalizeCheck(pipeline, 'Pipeline')];
+}
+
+function normalizeGitlabReviewDecision(mr) {
+ if (mr?.approved === true || (Array.isArray(mr?.approved_by) && mr.approved_by.length > 0)) {
+ return 'APPROVED';
+ }
+ if (mr?.approved === false) return 'REVIEW_REQUIRED';
+ return null;
+}
+
+function normalizeGitlabPullRequest(mr) {
+ return {
+ number: Number(mr?.iid),
+ title: typeof mr?.title === 'string' ? mr.title : '',
+ url: typeof mr?.web_url === 'string' ? mr.web_url : '',
+ state: 'open',
+ author: typeof mr?.author?.username === 'string'
+ ? mr.author.username
+ : (typeof mr?.author?.name === 'string' ? mr.author.name : null),
+ createdAt: typeof mr?.created_at === 'string' ? mr.created_at : null,
+ updatedAt: typeof mr?.updated_at === 'string' ? mr.updated_at : null,
+ isDraft: mr?.draft === true || mr?.work_in_progress === true,
+ headBranch: typeof mr?.source_branch === 'string' ? mr.source_branch : '',
+ baseBranch: typeof mr?.target_branch === 'string' ? mr.target_branch : '',
+ reviewDecision: normalizeGitlabReviewDecision(mr),
+ mergeStateStatus: typeof mr?.detailed_merge_status === 'string'
+ ? mr.detailed_merge_status
+ : (typeof mr?.merge_status === 'string' ? mr.merge_status : null),
+ mergeable: typeof mr?.merge_status === 'string' ? mr.merge_status : null,
+ labels: Array.isArray(mr?.labels)
+ ? mr.labels.map(label => typeof label === 'string' ? label : label?.name)
+ .filter(label => typeof label === 'string' && label)
+ : [],
+ checks: normalizeGitlabPipeline(mr),
+ };
+}
+
+function answeredResult(rows, normalize) {
+ const pullRequests = rows.map(normalize).filter(pr => Number.isInteger(pr.number) && pr.number > 0);
+ if (rows.length > 0 && pullRequests.length === 0) {
+ return {
+ pullRequests: [],
+ reason: 'unreadable-response',
+ transient: true,
+ headline: "The forge returned an unreadable pull-request list",
+ remedy: 'retry the request after checking the forge CLI version',
+ };
+ }
+ return {
+ pullRequests,
+ reason: rows.length ? 'ok' : 'no-open-pull-requests',
+ transient: false,
+ };
+}
+
+async function fetchGithubPullRequests(repoSpec, apiHost) {
+ const forge = await ensureForgeReachable('app-pull-requests', { hostname: apiHost });
+ if (!forge.ok) {
+ return {
+ pullRequests: [],
+ reason: `gh-${forge.status}`,
+ transient: true,
+ remedy: forge.remedy || null,
+ };
+ }
+
+ const raw = await execGh([
+ 'pr', 'list', '--repo', repoSpec, '--state', 'open',
+ '--limit', String(GH_LIST_LIMIT), '--json', GH_PR_FIELDS,
+ ]).catch(err => {
+ console.error(`❌ app-pull-requests: gh pr list failed for ${repoSpec}: ${err.message}`);
+ return null;
+ });
+ const rows = safeJSONParse(raw, null);
+ if (!Array.isArray(rows)) {
+ return {
+ pullRequests: [],
+ reason: 'fetch-failed',
+ transient: true,
+ headline: "Couldn't read GitHub's pull-request list",
+ remedy: 'run `gh pr list` in the repo to see what gh reports',
+ };
+ }
+ return answeredResult(rows, normalizeGithubPullRequest);
+}
+
+async function fetchGitlabPullRequests(repoPath) {
+ const { rows, reason } = await execGlabJson(['mr', 'list', '--per-page', String(GL_PER_PAGE)], repoPath);
+ if (rows) return answeredResult(rows, normalizeGitlabPullRequest);
+ if (reason === 'not-json') {
+ return {
+ pullRequests: [],
+ reason: 'glab-output-not-json',
+ transient: true,
+ headline: "Reached GitLab, but couldn't read its answer",
+ remedy: 'update `glab` — its JSON output flag moved (check `glab mr list --help`)',
+ };
+ }
+ return {
+ pullRequests: [],
+ reason: 'fetch-failed',
+ transient: true,
+ headline: "Couldn't reach GitLab",
+ remedy: 'check `glab auth status` and that `glab` is installed and can reach the host',
+ };
+}
+
+/**
+ * List open PRs/MRs for the repository behind a managed app.
+ *
+ * Unlike the Issues tab, this is not gated on the app's work tracker: an app
+ * can use PLAN.md or JIRA for work and still have a GitHub/GitLab change
+ * request that needs attention. `resolveAppForgeTarget` is still used so an
+ * explicit forge pin can identify self-hosted installations.
+ *
+ * @param {object} app - managed app record (needs `repoPath`)
+ * @returns {Promise<{forge:string|null, tracker:string|null, fullName:string|null, pullRequests:object[], reason:string, transient:boolean, headline:string|null, remedy:string|null}>}
+ */
+export async function listAppPullRequests(app) {
+ if (!app?.repoPath) return { ...baseResult, reason: 'no-repo-path' };
+
+ const { tracker, target } = await resolveAppForgeTarget(app);
+ if (!target) return { ...baseResult, tracker, reason: 'unsupported-forge' };
+
+ const result = target.forge === 'github'
+ ? await fetchGithubPullRequests(target.repoSpec, target.apiHost)
+ : await fetchGitlabPullRequests(app.repoPath);
+
+ return {
+ ...baseResult,
+ forge: target.forge,
+ tracker,
+ fullName: target.fullName,
+ pullRequests: result.pullRequests,
+ reason: result.reason,
+ transient: result.transient,
+ headline: result.headline || null,
+ remedy: result.remedy || null,
+ };
+}
diff --git a/server/services/appPullRequests.test.js b/server/services/appPullRequests.test.js
new file mode 100644
index 0000000000..052247dfb8
--- /dev/null
+++ b/server/services/appPullRequests.test.js
@@ -0,0 +1,175 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./github.js', () => ({
+ execGh: vi.fn(),
+ ensureForgeReachable: vi.fn(),
+}));
+vi.mock('./gitlab.js', () => ({
+ execGlabJson: vi.fn(),
+}));
+vi.mock('../lib/workTracker.js', () => ({
+ resolveAppForgeTarget: vi.fn(),
+}));
+
+import { execGh, ensureForgeReachable } from './github.js';
+import { execGlabJson } from './gitlab.js';
+import { resolveAppForgeTarget } from '../lib/workTracker.js';
+import { listAppPullRequests } from './appPullRequests.js';
+
+const APP = { id: 'app-001', name: 'Widget', repoPath: '/repo', workTracker: 'auto' };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ ensureForgeReachable.mockResolvedValue({ ok: true });
+ resolveAppForgeTarget.mockResolvedValue({
+ tracker: 'github',
+ target: { forge: 'github', fullName: 'acme/widget', repoSpec: 'github.com/acme/widget', apiHost: 'github.com' },
+ });
+});
+
+describe('listAppPullRequests', () => {
+ it('normalizes GitHub review, merge, branch, label, and check state', async () => {
+ execGh.mockResolvedValue(JSON.stringify([{
+ number: 17,
+ title: 'Fix the save path',
+ url: 'https://github.com/acme/widget/pull/17',
+ author: { login: 'alice' },
+ createdAt: '2026-08-01T00:00:00Z',
+ updatedAt: '2026-08-02T00:00:00Z',
+ isDraft: false,
+ headRefName: 'fix/save-path',
+ baseRefName: 'main',
+ reviewDecision: 'CHANGES_REQUESTED',
+ mergeStateStatus: 'DIRTY',
+ mergeable: 'CONFLICTING',
+ labels: [{ name: 'bug' }],
+ statusCheckRollup: [
+ { name: 'unit', conclusion: 'SUCCESS', detailsUrl: 'https://ci.example/unit' },
+ { name: 'lint', status: 'IN_PROGRESS' },
+ ],
+ }]));
+
+ const result = await listAppPullRequests(APP);
+
+ expect(ensureForgeReachable).toHaveBeenCalledWith('app-pull-requests', { hostname: 'github.com' });
+ expect(execGh).toHaveBeenCalledWith(expect.arrayContaining([
+ 'pr', 'list', '--repo', 'github.com/acme/widget', '--state', 'open', '--limit', '200',
+ ]));
+ expect(result).toMatchObject({
+ forge: 'github',
+ tracker: 'github',
+ fullName: 'acme/widget',
+ reason: 'ok',
+ transient: false,
+ pullRequests: [{
+ number: 17,
+ title: 'Fix the save path',
+ author: 'alice',
+ headBranch: 'fix/save-path',
+ baseBranch: 'main',
+ reviewDecision: 'CHANGES_REQUESTED',
+ mergeStateStatus: 'DIRTY',
+ mergeable: 'CONFLICTING',
+ labels: ['bug'],
+ checks: [
+ { name: 'unit', status: 'SUCCESS', url: 'https://ci.example/unit' },
+ { name: 'lint', status: 'IN_PROGRESS', url: null },
+ ],
+ }],
+ });
+ });
+
+ it('keeps an answered empty GitHub list distinct from a failed read', async () => {
+ execGh.mockResolvedValue('[]');
+
+ const result = await listAppPullRequests(APP);
+
+ expect(result).toMatchObject({ pullRequests: [], reason: 'no-open-pull-requests', transient: false });
+ });
+
+ it('does not turn a malformed nonempty GitHub response into an empty success', async () => {
+ execGh.mockResolvedValue(JSON.stringify([null, { title: 'missing number' }]));
+
+ const result = await listAppPullRequests(APP);
+
+ expect(result).toMatchObject({
+ pullRequests: [],
+ reason: 'unreadable-response',
+ transient: true,
+ });
+ });
+
+ it('returns a transient sentinel when the forge cannot be reached', async () => {
+ ensureForgeReachable.mockResolvedValue({
+ ok: false,
+ status: 'unauthenticated',
+ remedy: 'run gh auth login',
+ });
+
+ const result = await listAppPullRequests(APP);
+
+ expect(execGh).not.toHaveBeenCalled();
+ expect(result).toMatchObject({
+ pullRequests: [],
+ reason: 'gh-unauthenticated',
+ transient: true,
+ remedy: 'run gh auth login',
+ });
+ });
+
+ it('normalizes GitLab merge-request and pipeline state from the repo cwd', async () => {
+ resolveAppForgeTarget.mockResolvedValue({
+ tracker: 'plan',
+ target: { forge: 'gitlab', fullName: 'group/widget', repoSpec: null, apiHost: null },
+ });
+ execGlabJson.mockResolvedValue({
+ reason: 'ok',
+ rows: [{
+ iid: 8,
+ title: 'Improve the editor',
+ web_url: 'https://gitlab.example/group/widget/-/merge_requests/8',
+ author: { username: 'bob' },
+ created_at: '2026-08-03T00:00:00Z',
+ updated_at: '2026-08-04T00:00:00Z',
+ draft: true,
+ source_branch: 'feat/editor',
+ target_branch: 'main',
+ approved: true,
+ detailed_merge_status: 'mergeable',
+ merge_status: 'can_be_merged',
+ labels: ['enhancement'],
+ head_pipeline: { status: 'success', web_url: 'https://gitlab.example/group/widget/-/pipelines/4' },
+ }],
+ });
+
+ const result = await listAppPullRequests(APP);
+
+ expect(execGlabJson).toHaveBeenCalledWith(['mr', 'list', '--per-page', '100'], '/repo');
+ expect(result).toMatchObject({
+ forge: 'gitlab',
+ tracker: 'plan',
+ pullRequests: [{
+ number: 8,
+ state: 'open',
+ author: 'bob',
+ isDraft: true,
+ headBranch: 'feat/editor',
+ baseBranch: 'main',
+ reviewDecision: 'APPROVED',
+ mergeStateStatus: 'mergeable',
+ mergeable: 'can_be_merged',
+ checks: [{ name: 'Pipeline', status: 'SUCCESS', url: 'https://gitlab.example/group/widget/-/pipelines/4' }],
+ }],
+ });
+ });
+
+ it('returns a non-transient unsupported-forge sentinel without invoking a CLI', async () => {
+ resolveAppForgeTarget.mockResolvedValue({ tracker: 'plan', target: null });
+
+ const result = await listAppPullRequests(APP);
+
+ expect(execGh).not.toHaveBeenCalled();
+ expect(execGlabJson).not.toHaveBeenCalled();
+ expect(result).toMatchObject({ tracker: 'plan', pullRequests: [], reason: 'unsupported-forge', transient: false });
+ });
+});