Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
add a plain Merge button to the app PR/MR tab, with no agent in the loop
[._.]/ Adam Eivy82690fc4ba86
diff --git a/client/src/components/apps/tabs/PullRequestsTab.jsx b/client/src/components/apps/tabs/PullRequestsTab.jsxindex 2349615f0a..aec58b8cc2 100644--- a/client/src/components/apps/tabs/PullRequestsTab.jsx+++ b/client/src/components/apps/tabs/PullRequestsTab.jsx@@ -6,9 +6,11 @@ import {} from 'lucide-react';import BrailleSpinner from '../../BrailleSpinner';import Banner from '../../ui/Banner';+import ConfirmButtonPair from '../../ui/ConfirmButtonPair';import Pill from '../../ui/Pill';import toast from '../../ui/Toast';import ProviderModelSelector from '../../ProviderModelSelector';+import { useConfirmDelete } from '../../../hooks/useConfirmDelete';import { useCosTaskUpdates } from '../../../hooks/useCosTaskUpdates';import useProviderModels from '../../../hooks/useProviderModels';import { enabledProcessProviderFilter } from '../../../utils/providers';@@ -94,6 +96,70 @@ const ACTION_KINDS = {},};const KIND_IDS = Object.keys(ACTION_KINDS);++// The direct merge's methods, in the order the forges list them.+const MERGE_METHOD_LABELS = { merge: 'Merge commit', squash: 'Squash', rebase: 'Rebase' };+const DEFAULT_MERGE_METHOD = 'merge';++/**+ * The one row action that runs no agent. Armed into an inline confirm rather+ * than merging on the first click: the forge merge is irreversible, and the+ * method and branch deletion are choices the user should see before it happens.+ */+function MergeAction({+ pullRequest, idPrefix, title, armed, merging, method, onMethodChange,+ deleteBranch, onDeleteBranchChange, onArm, onCancel, onConfirm,+}) {+ if (!armed) {+ return (+ <button+ type="button"+ onClick={onArm}+ title={title}+ className="px-3 py-1.5 bg-port-border hover:bg-port-border/80 text-white border border-port-border rounded-lg text-xs flex items-center gap-1.5 whitespace-nowrap transition-colors"+ >+ <GitMerge size={14} /> Merge+ </button>+ );+ }+ return (+ <div className="flex flex-wrap items-center gap-2 px-2 py-1.5 bg-port-bg border border-port-border rounded-lg">+ <label htmlFor={`${idPrefix}-method-${pullRequest.number}`} className="sr-only">+ Merge method for #{pullRequest.number}+ </label>+ <select+ id={`${idPrefix}-method-${pullRequest.number}`}+ value={method}+ onChange={event => onMethodChange(event.target.value)}+ className="px-2 py-1 bg-port-card border border-port-border rounded-lg text-white text-xs focus:border-port-accent focus:outline-hidden"+ >+ {Object.entries(MERGE_METHOD_LABELS).map(([value, methodLabel]) => (+ <option key={value} value={value}>{methodLabel}</option>+ ))}+ </select>+ <input+ id={`${idPrefix}-delete-${pullRequest.number}`}+ type="checkbox"+ checked={deleteBranch}+ onChange={event => onDeleteBranchChange(event.target.checked)}+ />+ <label htmlFor={`${idPrefix}-delete-${pullRequest.number}`} className="text-xs text-gray-400">+ Delete branch+ </label>+ <ConfirmButtonPair+ tone="success"+ confirmText={`Merge #${pullRequest.number}`}+ confirmIcon={GitMerge}+ busy={merging}+ busyText="Merging…"+ ariaLabel={`Confirm merging #${pullRequest.number}`}+ onConfirm={onConfirm}+ onCancel={onCancel}+ />+ </div>+ );+}+const actionRecord = (kind, result) =>(ACTION_KINDS[kind].queued || (r => r[ACTION_KINDS[kind].field]))(result);const emptyActions = () => Object.fromEntries(KIND_IDS.map(kind => [kind, {}]));@@ -160,6 +226,7 @@ function actionRank(status) {*/export default function PullRequestsTab({ appId, appName }) {const searchId = useId();+ const mergeId = useId();const [data, setData] = useState(null);const [loading, setLoading] = useState(true);const [error, setError] = useState('');@@ -167,6 +234,16 @@ export default function PullRequestsTab({ appId, appName }) {const [actions, setActions] = useState(emptyActions);const actionsRef = useRef(emptyActions());const requestRef = useRef(0);+ // Direct merge: no CoS task backs it, so it needs none of the action+ // machinery above — only the shared single-row confirm state, an in-flight+ // flag, and the two knobs the confirm row exposes (kept across rows as a+ // session default).+ const {+ isConfirming, requestDelete: requestMerge, cancelDelete: cancelMerge,+ } = useConfirmDelete();+ const [merging, setMerging] = useState(false);+ const [mergeMethod, setMergeMethod] = useState(DEFAULT_MERGE_METHOD);+ const [deleteBranchOnMerge, setDeleteBranchOnMerge] = useState(true);// Resolve & merge defaults to the active provider. PR review follows its// saved stages unless the user explicitly enables the eligibility override.@@ -359,6 +436,40 @@ export default function PullRequestsTab({ appId, appName }) {}};+ // The one action that runs no agent: merge the request on the forge and drop+ // it from the list. A failure deliberately leaves the confirm row open — a+ // method the project forbids is answered by picking another one, not by+ // starting over.+ const confirmMerge = async pullRequest => {+ const { number } = pullRequest;+ setMerging(true);+ const result = await api.mergeAppPullRequest(appId, number, {+ method: mergeMethod,+ deleteBranch: deleteBranchOnMerge,+ }).catch(err => {+ toast.error(err?.message || `Failed to merge #${number}`);+ return null;+ });+ setMerging(false);+ if (!result) return;++ cancelMerge();+ // `deletedBranch` is the server's answer, not the request: it refuses to+ // delete a long-lived head however the checkbox was left.+ const branchNote = result.deletedBranch+ ? ' and deleted its branch'+ : (deleteBranchOnMerge ? ` — kept ${pullRequest.headBranch || 'the source branch'}` : '');+ toast.success(`Merged ${forgeLabel} #${number}${branchNote}`);+ // Drop the row now rather than waiting out the forge round trip the reload+ // costs. The reload still runs: landing a commit on the base branch changes+ // the mergeability and check state of every other open row.+ setData(current => current && {+ ...current,+ pullRequests: (current.pullRequests || []).filter(candidate => candidate.number !== number),+ });+ load();+ };+// Which actions this row offers. Each kind names the server's own per-row// verdict (`eligibleField`) rather than the tab re-deriving one: two copies of// an eligibility rule drift, and the button would then promise an action the@@ -407,6 +518,9 @@ export default function PullRequestsTab({ appId, appName }) {</div><div className="px-3 py-2 text-xs text-gray-500 bg-port-card border border-port-border rounded-lg space-y-1">+ <p>+ Merge lands the request on the forge immediately — no agent, no review, no model spend. Pick the merge method and whether to delete the source branch, then confirm. A long-lived source branch (a <span className="font-mono">main → release</span> request) is never deleted.+ </p><p>Resolve and merge starts a PortOS agent right away to inspect feedback, fix the branch, wait for checks, and merge when the forge allows it. It uses the configured Code Review Defaults.</p>@@ -590,6 +704,23 @@ export default function PullRequestsTab({ appId, appName }) {</button>);})}++ {pullRequest.mergeEligible && (+ <MergeAction+ pullRequest={pullRequest}+ idPrefix={mergeId}+ title={`Merge ${forgeLabel} request #${pullRequest.number} for ${appName} now, without an agent`}+ armed={isConfirming(pullRequest.number)}+ merging={merging}+ method={mergeMethod}+ onMethodChange={setMergeMethod}+ deleteBranch={deleteBranchOnMerge}+ onDeleteBranchChange={setDeleteBranchOnMerge}+ onArm={() => requestMerge(pullRequest.number)}+ onCancel={cancelMerge}+ onConfirm={() => confirmMerge(pullRequest)}+ />+ )}</div></div></div>diff --git a/client/src/components/apps/tabs/PullRequestsTab.test.jsx b/client/src/components/apps/tabs/PullRequestsTab.test.jsxindex d3615342d5..f032f6a651 100644--- a/client/src/components/apps/tabs/PullRequestsTab.test.jsx+++ b/client/src/components/apps/tabs/PullRequestsTab.test.jsx@@ -29,6 +29,7 @@ vi.mock('../../../services/api', () => ({resolveAppPullRequest: vi.fn(),reviewAppPullRequest: vi.fn(),doReviewAppPullRequest: vi.fn(),+ mergeAppPullRequest: vi.fn(),getProviders: vi.fn(),}));@@ -52,6 +53,7 @@ const PULL_REQUEST = {labels: ['bug'],reviewEligible: true,doReviewEligible: true,+ mergeEligible: true,checks: [{ name: 'unit', status: 'SUCCESS', url: null },{ name: 'lint', status: 'SUCCESS', url: null },@@ -102,6 +104,7 @@ beforeEach(() => {started: true,queueReason: null,});+ api.mergeAppPullRequest.mockResolvedValue({ number: 17, merged: true, method: 'merge', deletedBranch: true });api.getProviders.mockResolvedValue({ activeProvider: '', providers: [] });});@@ -478,6 +481,60 @@ describe('PullRequestsTab', () => {expect(screen.queryByRole('button', { name: /PR review/ })).not.toBeInTheDocument();});+ it('merges a request directly once the inline confirm is answered', async () => {+ await renderTab();+ // The row must clear on the merge itself, not on the reload behind it — a+ // merged request still offering a Merge button is the misleading state.+ api.getAppPullRequests.mockImplementation(() => new Promise(() => {}));++ fireEvent.click(await screen.findByRole('button', { name: /^Merge$/ }));+ // Arming alone must not merge — the confirm row is the approval.+ expect(api.mergeAppPullRequest).not.toHaveBeenCalled();++ fireEvent.change(screen.getByLabelText('Merge method for #17'), { target: { value: 'squash' } });+ fireEvent.click(screen.getByRole('button', { name: /Merge #17/ }));++ await waitFor(() => expect(api.mergeAppPullRequest).toHaveBeenCalledWith(+ 'app-1', 17, { method: 'squash', deleteBranch: true },+ ));+ expect(toastMock.success).toHaveBeenCalledWith(expect.stringContaining('Merged GitHub #17'));+ await waitFor(() => expect(screen.queryByText('Fix the save path')).not.toBeInTheDocument());+ });++ it('honors an unchecked delete-branch box', async () => {+ await renderTab();++ fireEvent.click(await screen.findByRole('button', { name: /^Merge$/ }));+ fireEvent.click(screen.getByLabelText('Delete branch'));+ fireEvent.click(screen.getByRole('button', { name: /Merge #17/ }));++ await waitFor(() => expect(api.mergeAppPullRequest).toHaveBeenCalledWith(+ 'app-1', 17, { method: 'merge', deleteBranch: false },+ ));+ });++ it('keeps the confirm row open so a refused merge method can be changed', async () => {+ api.mergeAppPullRequest.mockRejectedValue(new Error('Squash merges are not allowed on this repository'));++ await renderTab();++ fireEvent.click(await screen.findByRole('button', { name: /^Merge$/ }));+ fireEvent.click(screen.getByRole('button', { name: /Merge #17/ }));++ await waitFor(() => expect(toastMock.error).toHaveBeenCalledWith(expect.stringContaining('Squash merges are not allowed')));+ expect(screen.getByLabelText('Merge method for #17')).toBeInTheDocument();+ expect(screen.getByText('Fix the save path')).toBeInTheDocument();+ });++ it('omits the merge action on a row the server marked unmergeable', async () => {+ api.getAppPullRequests.mockResolvedValue(okPayload([{ ...PULL_REQUEST, mergeEligible: false }]));++ await renderTab();++ expect(await screen.findByRole('button', { name: /Resolve & merge/ })).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /^Merge$/ })).not.toBeInTheDocument();+ });+it('keeps forge failures distinct from a healthy empty list', async () => {api.getAppPullRequests.mockResolvedValue({forge: 'github',diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.jsindex 6c56515f9f..77a7f4deb3 100644--- a/client/src/services/apiApps.js+++ b/client/src/services/apiApps.js@@ -123,6 +123,17 @@ export const doReviewAppPullRequest = (id, number, settings = {}, options = {})silent: true,...options,});+// Merge ONE open PR/MR right now with no agent and no model spend — the forge's+// own merge button, for a change the user has already read. `deleteBranch` is a+// request, not a promise: the server keeps a long-lived head (a `main → release`+// request) and answers with the `deletedBranch` it actually did.+export const mergeAppPullRequest = (id, number, { method, deleteBranch } = {}, options = {}) =>+ request(`/apps/${id}/pull-requests/${encodeURIComponent(number)}/merge`, {+ method: 'POST',+ body: JSON.stringify({ method, deleteBranch }),+ 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/pullRequests.js b/server/routes/apps/pullRequests.jsindex cd0b554ef9..3120bcb594 100644--- a/server/routes/apps/pullRequests.js+++ b/server/routes/apps/pullRequests.js@@ -5,17 +5,20 @@* POST /:id/pull-requests/:number/resolve → queue a review-loop agent* POST /:id/pull-requests/:number/review → queue pr-reviewer for ONE PR* POST /:id/pull-requests/:number/do-review → queue /do:review for ONE PR+ * POST /:id/pull-requests/:number/merge → merge it now, no agent*- * No POST route merges a user's PR directly. `/resolve` queues PortOS's- * existing review-loop follow-up, which owns fetching feedback, fixing the- * branch, waiting for checks, and merging — and starts it immediately, because- * pressing the button is the approval. `/review` queues the `pr-reviewer`- * scheduled task narrowed to a single request, so the security-scan → review- * pipeline that normally sweeps every external PR can be pointed at one.- * `/do-review` runs the bundled `/do:review` workflow against one request with- * the install's Code Review Defaults and publishes an inline review — the only- * one of the three that offers a review on EVERY open GitHub PR, whoever opened- * it, because `pr-reviewer` covers untrusted contributors alone.+ * Three of the four queue an agent. `/resolve` queues PortOS's existing+ * review-loop follow-up, which owns fetching feedback, fixing the branch,+ * waiting for checks, and merging — and starts it immediately, because pressing+ * the button is the approval. `/review` queues the `pr-reviewer` scheduled task+ * narrowed to a single request, so the security-scan → review pipeline that+ * normally sweeps every external PR can be pointed at one. `/do-review` runs the+ * bundled `/do:review` workflow against one request with the install's Code+ * Review Defaults and publishes an inline review — the only one of the three+ * that offers a review on EVERY open GitHub PR, whoever opened it, because+ * `pr-reviewer` covers untrusted contributors alone. `/merge` is the one that+ * queues nothing and spends nothing: the forge's own merge button, for a change+ * the user has already read.*/import { Router } from 'express';@@ -29,6 +32,12 @@ 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 {+ MERGE_METHODS,+ DEFAULT_MERGE_METHOD,+ isDirectlyMergeablePullRequest,+ mergeAppPullRequest,+} from '../../services/appPullRequestMerge.js';import { isDoReviewTask, spawnPrDoReviewTask } from '../../services/prDoReviewTask.js';import {isReviewablePullRequest,@@ -44,6 +53,14 @@ const pullRequestParamsSchema = z.object({number: z.coerce.number().int().positive(),});+// The direct merge's only inputs; the tab always sends both. A caller that omits+// `deleteBranch` gets the conservative answer — the flag is irreversible on the+// forge, and the merge service refuses it outright for a long-lived head.+const pullRequestMergeSchema = z.object({+ method: z.enum(MERGE_METHODS).optional(),+ deleteBranch: z.boolean().optional(),+});+const ACTIVE_TASK_STATUSES = new Set(['pending', 'in_progress', 'blocked']);const PR_REVIEWER_TASK_TYPE = 'pr-reviewer';@@ -196,12 +213,27 @@ async function listWithActionState(app) {doReviewAction: actionFor(pullRequest, tasks, app.id, isDoReviewTaskFor),reviewEligible: reviewEligible(pullRequest),doReviewEligible: isDoReviewablePullRequest(result, pullRequest),+ mergeEligible: isDirectlyMergeablePullRequest(pullRequest),})),},tasks,};}+// The one spelling of "this row is still open", shared by every route that+// re-reads the open set before acting on a single request — the message and+// code would otherwise drift across three doors with nothing catching it.+function findOpenPullRequest(result, number) {+ 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',+ });+ }+ return pullRequest;+}+function throwForgeReadError(result) {if (!result.transient) return;throw new ServerError(@@ -247,13 +279,7 @@ router.post('/:id/pull-requests/:number/resolve', loadApp, asyncHandler(async (r});}- 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',- });- }+ const pullRequest = findOpenPullRequest(result, number);if (!pullRequest.url || !pullRequest.headBranch) {throw new ServerError(`Pull request or merge request #${number} has no usable forge URL or source branch`, {status: 502,@@ -352,6 +378,51 @@ router.post('/:id/pull-requests/:number/resolve', loadApp, asyncHandler(async (r});}));+// POST /api/apps/:id/pull-requests/:number/merge — merge one open request NOW,+// with no agent and no model spend. The open set is re-read first, exactly as+// `/resolve` does: a tab left open for an hour must not merge a request that has+// since been closed, replaced, or turned into a draft.+router.post('/:id/pull-requests/:number/merge', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;+ const { number } = validateRequest(pullRequestParamsSchema, req.params);+ const { method = DEFAULT_MERGE_METHOD, deleteBranch = false } =+ validateRequest(pullRequestMergeSchema, req.body || {});++ const result = await listAppPullRequests(app);+ throwForgeReadError(result);++ const pullRequest = findOpenPullRequest(result, number);+ if (!isDirectlyMergeablePullRequest(pullRequest)) {+ throw new ServerError(`${result.forge === 'gitlab' ? 'Merge' : 'Pull'} request #${number} is a draft — mark it ready for review before merging`, {+ status: 409,+ code: 'PULL_REQUEST_IS_DRAFT',+ });+ }++ const merge = await mergeAppPullRequest(app, pullRequest, { method, deleteBranch });+ if (!merge.ok) {+ const refused = merge.code === 'method-not-allowed';+ throw new ServerError(merge.error, {+ // Only the forge failing the merge itself is a bad gateway; everything+ // else is this request asking for something the project does not allow.+ status: merge.code === 'merge-failed' ? 502 : 409,+ code: refused ? 'MERGE_METHOD_NOT_ALLOWED' : 'PULL_REQUEST_MERGE_FAILED',+ context: { method, reason: merge.code },+ });+ }++ res.json({+ appId: app.id,+ appName: app.name,+ number,+ merged: true,+ method: merge.method,+ // The ANSWER, not the request: a long-lived head (a `main → release`+ // request) merges without its branch being deleted.+ deletedBranch: merge.deletedBranch,+ });+}));+// POST /api/apps/:id/pull-requests/:number/review — queue the `pr-reviewer`// scheduled task narrowed to ONE request. The scheduled task normally decides// for itself which of the app's external PRs to sweep; a targeted request pins@@ -470,13 +541,7 @@ router.post('/:id/pull-requests/:number/do-review', loadApp, asyncHandler(async);}- 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',- });- }+ const pullRequest = findOpenPullRequest(result, number);if (!isDoReviewablePullRequest(result, pullRequest)) {throw new ServerError(`Pull request #${number} has no usable forge URL`, {status: 502,diff --git a/server/routes/apps/pullRequests.test.js b/server/routes/apps/pullRequests.test.jsindex efa5b2521c..91cf4a4eec 100644--- a/server/routes/apps/pullRequests.test.js+++ b/server/routes/apps/pullRequests.test.js@@ -9,6 +9,10 @@ vi.mock('../../services/apps.js', () => ({vi.mock('../../services/appPullRequests.js', () => ({listAppPullRequests: vi.fn(),}));+vi.mock('../../services/appPullRequestMerge.js', async (importOriginal) => ({+ ...(await importOriginal()),+ mergeAppPullRequest: vi.fn(),+}));vi.mock('../../services/cos.js', () => ({getAllTasks: vi.fn(),}));@@ -34,6 +38,7 @@ vi.mock('../../services/taskSchedule.js', () => ({import * as appsService from '../../services/apps.js';import { listAppPullRequests } from '../../services/appPullRequests.js';+import { mergeAppPullRequest } from '../../services/appPullRequestMerge.js';import { getAllTasks } from '../../services/cos.js';import { resolveReviewLoopOptions } from '../../services/codeReview.js';import { spawnReviewLoopFollowUp } from '../../services/agentWorktreeCleanup.js';@@ -110,6 +115,7 @@ describe('app pull-request routes', () => {duplicate: false,dispatch: { started: true, reason: null },});+ mergeAppPullRequest.mockResolvedValue({ ok: true, method: 'merge', deletedBranch: false });});it('lists open requests and annotates an active resolve task', async () => {@@ -620,6 +626,89 @@ describe('app pull-request routes', () => {expect(response.body.pullRequests[0].doReviewAction).toEqual({ taskId: 'task-doreview-live', status: 'pending' });});+ it('merges a request directly, with no agent queued', async () => {+ mergeAppPullRequest.mockResolvedValue({ ok: true, method: 'squash', deletedBranch: true });++ const response = await request(app).post('/api/apps/app-001/pull-requests/17/merge')+ .send({ method: 'squash', deleteBranch: true });++ expect(response.status).toBe(200);+ expect(response.body).toMatchObject({ number: 17, merged: true, method: 'squash', deletedBranch: true });+ expect(mergeAppPullRequest).toHaveBeenCalledWith(APP, expect.objectContaining({ number: 17 }), {+ method: 'squash',+ deleteBranch: true,+ });+ // The whole point of this action: nothing is queued and no model is spent.+ expect(spawnReviewLoopFollowUp).not.toHaveBeenCalled();+ expect(spawnPrDoReviewTask).not.toHaveBeenCalled();+ expect(triggerOnDemandTask).not.toHaveBeenCalled();+ });++ it('defaults an unqualified merge to a merge commit that keeps the branch', async () => {+ const response = await request(app).post('/api/apps/app-001/pull-requests/17/merge');++ expect(response.status).toBe(200);+ expect(mergeAppPullRequest.mock.calls[0][2]).toEqual({ method: 'merge', deleteBranch: false });+ });++ it('refuses to merge a draft request', async () => {+ listAppPullRequests.mockResolvedValue({+ ...listResult(),+ pullRequests: [{ ...PULL_REQUEST, isDraft: true }],+ });++ const response = await request(app).post('/api/apps/app-001/pull-requests/17/merge');++ expect(response.status).toBe(409);+ expect(response.body.code).toBe('PULL_REQUEST_IS_DRAFT');+ expect(mergeAppPullRequest).not.toHaveBeenCalled();+ });++ it('refuses to merge 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/merge');++ expect(response.status).toBe(404);+ expect(response.body.code).toBe('PULL_REQUEST_NOT_OPEN');+ expect(mergeAppPullRequest).not.toHaveBeenCalled();+ });++ it('surfaces a forbidden merge method as an explained 409', async () => {+ mergeAppPullRequest.mockResolvedValue({+ ok: false,+ code: 'method-not-allowed',+ error: 'GraphQL: Squash merges are not allowed on this repository',+ });++ const response = await request(app).post('/api/apps/app-001/pull-requests/17/merge')+ .send({ method: 'squash' });++ expect(response.status).toBe(409);+ expect(response.body.code).toBe('MERGE_METHOD_NOT_ALLOWED');+ expect(response.body.error).toContain('Squash merges are not allowed');+ });++ it('rejects an unknown merge method before reaching the forge', async () => {+ const response = await request(app).post('/api/apps/app-001/pull-requests/17/merge')+ .send({ method: 'fast-forward' });++ expect(response.status).toBe(400);+ expect(mergeAppPullRequest).not.toHaveBeenCalled();+ });++ it('marks a listed request mergeable unless it is a draft', async () => {+ listAppPullRequests.mockResolvedValue({+ ...listResult(),+ pullRequests: [PULL_REQUEST, { ...PULL_REQUEST, number: 18, isDraft: true }],+ });++ const response = await request(app).get('/api/apps/app-001/pull-requests');++ expect(response.body.pullRequests[0].mergeEligible).toBe(true);+ expect(response.body.pullRequests[1].mergeEligible).toBe(false);+ });+it('returns 404 for an unknown app', async () => {appsService.getAppById.mockResolvedValue(null);diff --git a/server/services/appPullRequestMerge.js b/server/services/appPullRequestMerge.jsnew file mode 100644index 0000000000..8aae74a914--- /dev/null+++ b/server/services/appPullRequestMerge.js@@ -0,0 +1,133 @@+/**+ * Direct PR/MR merge for a managed app's Pull Requests tab.+ *+ * Every other row action queues a CoS agent. This one deliberately does not:+ * it runs the forge CLI's own merge and reports the outcome, for the case where+ * the user has already read the change and just wants the button GitHub/GitLab+ * would have given them — no agent, no model spend, no review loop.+ *+ * The merge METHOD is never silently substituted. Squash and merge-commit are+ * different histories, so a project that forbids the chosen one gets an+ * explained refusal naming the alternatives rather than a quiet swap.+ */++import { execGh } from './github.js';+import { execGlab } from './gitlab.js';+import { resolveForgeExecOptions } from './forgeExecOptions.js';+import { resolveAppForgeTarget } from '../lib/workTracker.js';+import { PROTECTED_BRANCHES } from '../lib/gitArgs.js';++export const MERGE_METHODS = Object.freeze(['merge', 'squash', 'rebase']);+export const DEFAULT_MERGE_METHOD = 'merge';++// A merge can sit behind the forge's own mergeability recompute; the list+// timeouts are tuned for reads and are too tight for a write that lands commits.+const MERGE_TIMEOUT_MS = 120_000;++// gh answers a forbidden method with GraphQL prose ("Squash merges are not+// allowed on this repository", "This branch can't be rebased"); glab answers a+// forbidden squash with its own. Recognized only to turn a cryptic CLI dump into+// "pick another method" — never to pick one automatically.+const METHOD_REFUSED = /not allowed|cannot be rebased|can't be rebased|only fast-forward/i;++// glab renamed this flag across versions (`--when-pipeline-succeeds` →+// `--auto-merge`), and an unknown flag is a hard exit, not a warning.+const GLAB_UNKNOWN_FLAG = /unknown flag|unknown shorthand/i;++const GLAB_METHOD_ARGS = { merge: [], squash: ['--squash'], rebase: ['--rebase'] };++/**+ * Whether this request may be merged at all. Both forges refuse a draft, so the+ * tab does not offer the action on one and the route refuses it — the rule lives+ * here, with the merge, rather than only in the door it happens to arrive at.+ *+ * Conflicts and pending checks deliberately do NOT gate it: the row already+ * shows them, and hiding the action there would remove the only way to merge a+ * request whose non-required check never reports.+ *+ * @param {object} pullRequest - a listed row+ * @returns {boolean}+ */+export const isDirectlyMergeablePullRequest = pullRequest => pullRequest?.isDraft !== true;++// A release-shaped request's head is a LONG-LIVED branch (PortOS ships+// `main → release`), so an unconditional delete there deletes `main`. An+// unreadable head counts as long-lived: never delete a branch we cannot name.+const isLongLivedSourceBranch = (headBranch, baseBranch) => {+ const head = String(headBranch || '').trim();+ return !head || PROTECTED_BRANCHES.includes(head) || head === String(baseBranch || '').trim();+};++const classifyFailure = detail => ({+ ok: false,+ code: METHOD_REFUSED.test(detail) ? 'method-not-allowed' : 'merge-failed',+ error: detail,+});++async function mergeGithub(app, target, number, method, deleteBranch) {+ if (!target.repoSpec) {+ return { ok: false, code: 'unsupported-forge', error: "This app's GitHub origin could not be resolved to an OWNER/REPO" };+ }+ // Same owner-pinned gh environment the listing uses: an app whose repo belongs+ // to a different logged-in account 404s without it (#7540).+ const { cwd, env } = await resolveForgeExecOptions(app.repoPath, { forgeAccount: app.forgeAccount });+ const args = ['pr', 'merge', String(number), '--repo', target.repoSpec, `--${method}`];+ // `--repo` puts gh in remote mode, so `--delete-branch` deletes the REMOTE+ // branch only — it never runs a local checkout in the user's working tree.+ if (deleteBranch) args.push('--delete-branch');++ const error = await execGh(args, MERGE_TIMEOUT_MS, { cwd, env }).then(() => null, err => err);+ return error ? classifyFailure(error.ghStderr || error.message || 'gh pr merge failed') : { ok: true };+}++async function mergeGitlab(app, number, method, deleteBranch) {+ const { env } = await resolveForgeExecOptions(app.repoPath, { forgeAccount: app.forgeAccount });+ const tail = [...GLAB_METHOD_ARGS[method], ...(deleteBranch ? ['--remove-source-branch'] : [])];+ const run = args => execGlab(args, app.repoPath, MERGE_TIMEOUT_MS, { env, rejectOnError: true })+ .then(() => null, err => err);++ // glab has historically defaulted to "merge when the pipeline succeeds", which+ // would leave the request open and make this button silently mean something+ // else. Ask for an immediate merge; drop the flag on a glab that renamed it+ // rather than failing the merge over its spelling.+ let error = await run(['mr', 'merge', String(number), '--yes', '--when-pipeline-succeeds=false', ...tail]);+ if (error && GLAB_UNKNOWN_FLAG.test(error.message || '')) {+ error = await run(['mr', 'merge', String(number), '--yes', ...tail]);+ }+ return error ? classifyFailure(error.message || 'glab mr merge failed') : { ok: true };+}++/**+ * Merge one open request on the app's forge, directly.+ *+ * `deletedBranch` is the answer, not the request: asking to delete a long-lived+ * source branch merges without deleting it rather than refusing the merge.+ *+ * @param {object} app - managed app record (needs `repoPath`)+ * @param {object} pullRequest - the freshly re-read row being merged+ * @param {object} [options]+ * @param {'merge'|'squash'|'rebase'} [options.method='merge']+ * @param {boolean} [options.deleteBranch=false] - delete the source branch, unless it is long-lived+ * @returns {Promise<{ok:boolean, code?:string, error?:string, method?:string, deletedBranch?:boolean}>}+ */+export async function mergeAppPullRequest(app, pullRequest, { method = DEFAULT_MERGE_METHOD, deleteBranch = false } = {}) {+ if (!MERGE_METHODS.includes(method)) {+ return { ok: false, code: 'invalid-method', error: `Unsupported merge method '${method}'` };+ }+ if (!isDirectlyMergeablePullRequest(pullRequest)) {+ return { ok: false, code: 'draft', error: `Request #${pullRequest.number} is a draft` };+ }+ const { target } = await resolveAppForgeTarget(app);+ if (!target) {+ return { ok: false, code: 'unsupported-forge', error: "This app's git origin is not a GitHub or GitLab repository" };+ }++ const deleting = deleteBranch && !isLongLivedSourceBranch(pullRequest.headBranch, pullRequest.baseBranch);+ const result = target.forge === 'gitlab'+ ? await mergeGitlab(app, pullRequest.number, method, deleting)+ : await mergeGithub(app, target, pullRequest.number, method, deleting);+ if (!result.ok) return result;++ console.log(`🔀 Merged ${target.forge === 'gitlab' ? 'MR' : 'PR'} #${pullRequest.number} for app ${app.id} via ${method}${deleting ? ' (source branch deleted)' : ''}`);+ return { ok: true, method, deletedBranch: deleting };+}diff --git a/server/services/appPullRequestMerge.test.js b/server/services/appPullRequestMerge.test.jsnew file mode 100644index 0000000000..6f8f832ea0--- /dev/null+++ b/server/services/appPullRequestMerge.test.js@@ -0,0 +1,125 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('./github.js', () => ({ execGh: vi.fn() }));+vi.mock('./gitlab.js', () => ({ execGlab: vi.fn() }));+vi.mock('./forgeExecOptions.js', () => ({+ resolveForgeExecOptions: vi.fn(async () => ({ cwd: '/repo', env: { GH_TOKEN: 'x' }, customEnv: { GH_TOKEN: 'x' } })),+}));+vi.mock('../lib/workTracker.js', () => ({ resolveAppForgeTarget: vi.fn() }));++import { execGh } from './github.js';+import { execGlab } from './gitlab.js';+import { resolveAppForgeTarget } from '../lib/workTracker.js';+import { mergeAppPullRequest } from './appPullRequestMerge.js';++const APP = { id: 'app-001', name: 'Widget', repoPath: '/repo' };+const PR = { number: 17, headBranch: 'fix/save-path', baseBranch: 'main' };++const githubTarget = () => ({+ tracker: 'github',+ target: { forge: 'github', fullName: 'acme/widget', repoSpec: 'github.com/acme/widget', apiHost: 'github.com' },+});++beforeEach(() => {+ vi.clearAllMocks();+ resolveAppForgeTarget.mockResolvedValue(githubTarget());+ execGh.mockResolvedValue('');+ execGlab.mockResolvedValue('');+});++describe('mergeAppPullRequest', () => {+ it('merges a GitHub request with the requested method and deletes the branch remotely', async () => {+ const result = await mergeAppPullRequest(APP, PR, { method: 'squash', deleteBranch: true });++ expect(result).toMatchObject({ ok: true, method: 'squash', deletedBranch: true });+ // `--repo` keeps gh in remote mode, so `--delete-branch` never checks out a+ // branch in the user's working tree.+ expect(execGh).toHaveBeenCalledWith(+ ['pr', 'merge', '17', '--repo', 'github.com/acme/widget', '--squash', '--delete-branch'],+ expect.any(Number),+ { cwd: '/repo', env: { GH_TOKEN: 'x' } },+ );+ });++ // A `main → release` request's head is a long-lived branch, so an obedient+ // `--delete-branch` there deletes `main`. An unnamed head is treated the same+ // way: never delete a branch we cannot identify.+ it.each([+ ['a long-lived head', { number: 9, headBranch: 'main', baseBranch: 'release' }],+ ['a head equal to the base', { number: 9, headBranch: 'topic', baseBranch: 'topic' }],+ ['an unreadable head', { number: 9, headBranch: '', baseBranch: 'main' }],+ ])('merges but refuses to delete %s', async (_label, pullRequest) => {+ const result = await mergeAppPullRequest(APP, pullRequest, { deleteBranch: true });++ expect(result).toMatchObject({ ok: true, deletedBranch: false });+ expect(execGh.mock.calls[0][0]).not.toContain('--delete-branch');+ });++ it('refuses a draft, which both forges would reject anyway', async () => {+ const result = await mergeAppPullRequest(APP, { ...PR, isDraft: true }, {});++ expect(result).toMatchObject({ ok: false, code: 'draft' });+ expect(execGh).not.toHaveBeenCalled();+ });++ it('reports a forbidden merge method rather than silently using another one', async () => {+ execGh.mockRejectedValue(Object.assign(new Error('failed'), {+ ghStderr: 'GraphQL: Squash merges are not allowed on this repository',+ }));++ const result = await mergeAppPullRequest(APP, PR, { method: 'squash' });++ expect(result).toMatchObject({ ok: false, code: 'method-not-allowed' });+ expect(result.error).toContain('Squash merges are not allowed');+ expect(execGh).toHaveBeenCalledTimes(1);+ });++ it('reports a failed merge with the forge message', async () => {+ execGh.mockRejectedValue(Object.assign(new Error('failed'), {+ ghStderr: 'GraphQL: Pull Request is not mergeable',+ }));++ const result = await mergeAppPullRequest(APP, PR, {});++ expect(result).toMatchObject({ ok: false, code: 'merge-failed' });+ });++ it('merges a GitLab request immediately instead of waiting on its pipeline', async () => {+ resolveAppForgeTarget.mockResolvedValue({+ tracker: 'gitlab',+ target: { forge: 'gitlab', fullName: 'acme/widget', repoSpec: null, apiHost: null },+ });++ const result = await mergeAppPullRequest(APP, PR, { method: 'rebase', deleteBranch: true });++ expect(result).toMatchObject({ ok: true, method: 'rebase', deletedBranch: true });+ expect(execGlab).toHaveBeenCalledWith(+ ['mr', 'merge', '17', '--yes', '--when-pipeline-succeeds=false', '--rebase', '--remove-source-branch'],+ '/repo',+ expect.any(Number),+ { env: { GH_TOKEN: 'x' }, rejectOnError: true },+ );+ });++ it('retries without the immediate-merge flag on a glab that renamed it', async () => {+ resolveAppForgeTarget.mockResolvedValue({+ tracker: 'gitlab',+ target: { forge: 'gitlab', fullName: 'acme/widget', repoSpec: null, apiHost: null },+ });+ execGlab.mockRejectedValueOnce(new Error('unknown flag: --when-pipeline-succeeds'));++ const result = await mergeAppPullRequest(APP, PR, {});++ expect(result).toMatchObject({ ok: true, method: 'merge' });+ expect(execGlab).toHaveBeenCalledTimes(2);+ expect(execGlab.mock.calls[1][0]).toEqual(['mr', 'merge', '17', '--yes']);+ });++ it('refuses a forge it cannot merge on', async () => {+ resolveAppForgeTarget.mockResolvedValue({ tracker: null, target: null });++ expect(await mergeAppPullRequest(APP, PR, {})).toMatchObject({ ok: false, code: 'unsupported-forge' });+ expect(execGh).not.toHaveBeenCalled();+ });+});+