Skip to content

Commit d2de1b3

Browse files
mchwangclaude
andcommitted
Keep the Merge button pending across renders, and pin every full-response job guard
A render while a Merge PR click's request is in flight (selecting an item, a plan reload) re-derived the control from merge.ready and offered "Merge PR" again. A click-pending flag now keeps it marked and labelled "Requesting merge…" until the request settles. Add browser regressions for the newerMergeJob guards at the review action, Plans refresh, plan import and Apply draft reload sites, and give the two no-reload checks time for a background reload to arrive. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 25444dd commit d2de1b3

3 files changed

Lines changed: 142 additions & 3 deletions

File tree

‎docs/implementation/merge-handoff.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,8 @@ Schema v19 adds `task_pull_requests.check_id` (the pre-PR check each opening fol
7575
- `POST /api/action` with `merge` returns at once when the server runs merge jobs (a runner and a pull request published by it, which requires preparation): the reloaded review with the job's latest record as `job`, or, if that reload failed, `{ job, mergeRefreshRequired: true }`. The job may already have moved on or ended by then; the page follows a running job and, for an ended one, asks for a refresh.
7676
- `GET /api/merge` returns `{ queue, job }`: `job` is the task's latest job. A saved refusal is not a job; it is replayed only to its own click.
7777
- Merge PR is offered only while the task is in a mergeable status (read after the inspection) and the only blockers left are ones the job resolves or reports: preparation, a moved base (with a merge conflict it causes), `cmd:` checks, required checks (the job waits for pending ones and ends `blocked` on failing ones, so a person can retry after re-running CI), and mergeability GitHub is still computing.
78-
- While a job runs, the Merge button keeps keyboard focus: it is marked `aria-disabled`, not disabled, and a repeat activation starts nothing.
79-
- The browser polls `GET /api/merge` with the existing 2 s to 30 s backoff while a job runs, shows its step in the merge banner, and lists waiting checks in the blocker dialog. A full review response read before the poll's latest record of the same job (by its `updatedAt`) keeps that newer record, so a slow **Refresh** does not restart following a job the poll saw end. A click's key is kept until its own job ends or a job newer than the one shown at the click is the latest, so a retry that failed with no answer is resent with the same key. When the job ends, the page updates only the merge control and banner (the outcome, and "Refresh to see the result"), so a person's selection and input survive; after **Refresh**, the page offers **Retry merge** when the job is `blocked`. The design's full step list and a Cancel button come later.
78+
- While a job runs, the Merge button keeps keyboard focus: it is marked `aria-disabled`, not disabled, and a repeat activation starts nothing. While the click's own request is in flight, the button reads **Requesting merge…** and stays marked, also when the page renders meanwhile (for example when a person selects an item).
79+
- The browser polls `GET /api/merge` with the existing 2 s to 30 s backoff while a job runs, shows its step in the merge banner, and lists waiting checks in the blocker dialog. A full review response read before the poll's latest record of the same job (by its `updatedAt`) keeps that newer record, so a slow **Refresh**, review action, **Refresh plan**, plan import or **Apply** reload does not restart following a job the poll saw end. A click's key is kept until its own job ends or a job newer than the one shown at the click is the latest, so a retry that failed with no answer is resent with the same key. When the job ends, the page updates only the merge control and banner (the outcome, and "Refresh to see the result"), so a person's selection and input survive; after **Refresh**, the page offers **Retry merge** when the job is `blocked`. The design's full step list and a Cancel button come later.
8080

8181
## Tests
8282

‎test/browser/review.spec.ts‎

Lines changed: 125 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { request as httpRequest, type IncomingMessage } from 'node:http';
88
import { createDemo } from '../../scripts/demo.ts';
99
import { choiceKeys } from '../../core/approvals.ts';
1010
import { ReviewService } from '../../runner/review.ts';
11-
import { startServer } from '../../web/server.ts';
11+
import { startServer, type PlanningDeps } from '../../web/server.ts';
1212
import type { MergeGateway, MergeQueueGateway } from '../../github/merge.ts';
1313
import { fixtureGit } from '../fixtures/git.ts';
1414
let root: string, app: Awaited<ReturnType<typeof startServer>>;
@@ -784,6 +784,126 @@ test('keeps a merge-job outcome a poll saw while an older Refresh response was h
784784
await expect(page.getByRole('button',{name:'Preparing…',exact:true})).toHaveCount(0);
785785
});
786786

787+
/** A runner server whose every full review shows a running merge job (each was read while it ran); the job poll reports
788+
* it merged once `ended` is set. Used to hold one full response while a poll sees the job end. */
789+
async function mergeJobOutcomeRace(page:import('@playwright/test').Page,planning?:PlanningDeps){
790+
const config={...app.service.config,demo:false};await app.close();removeDemoOutOfScope(config);
791+
const gateway:MergeGateway={inspect:async()=>{const snapshot=(await app.service.load()).snapshot;return {base:snapshot.base,head:snapshot.head,pullRequestState:'OPEN',mergeable:'MERGEABLE',rulesKnown:true,atomicBaseGuard:true,mergeQueue:false,requiredChecks:[],alreadyFixed:'clear',pullRequest:7,draft:false};},merge:async()=>{throw new Error('The browser test answers every merge request itself.');}};
792+
app=await startServer(config,0,undefined,gateway,undefined,undefined,undefined,planning);
793+
let view=await app.service.load();for(const segment of view.segments.filter(value=>value.row==='Unplanned'||value.row==='Ambiguous'))view=await app.service.act({action:'accept',key:segment.key,token:view.token});for(const item of view.items)view=await app.service.act({action:'approve',item:item.id,confirmNoChange:item.count===0,token:view.token});
794+
const running={id:'0f6b0000-0000-4000-8000-0000000000c1',state:'running',step:'preparing',reason:null,checks:[],url:null,startedAt:'2026-10-11T00:00:00Z',updatedAt:'2026-10-11T00:00:00Z'};
795+
const merged={...running,state:'merged',step:null,url:'https://github.com/owner/repo/pull/7',updatedAt:'2026-10-11T00:05:00Z'};
796+
const race={ended:false,polls:0,hold:false,config,release:()=>{},held:Promise.resolve()};
797+
let holding!:()=>void;race.held=new Promise<void>(resolve=>{holding=resolve;});
798+
const released=new Promise<void>(resolve=>{race.release=resolve;});
799+
await page.route('**/api/merge',route=>{race.polls++;return route.fulfill({status:200,contentType:'application/json',body:JSON.stringify({queue:null,job:race.ended?merged:running})});});
800+
// A full response (review or action) read while the job ran. The one marked held waits, and the job ends meanwhile.
801+
const answer=async(route:import('@playwright/test').Route)=>{const response=await route.fetch(),body=await response.json();
802+
body.merge={...body.merge,ready:false,action:null,job:running};
803+
if(race.hold){race.hold=false;race.ended=true;holding();await released;}
804+
await route.fulfill({response,json:body});};
805+
await page.route('**/api/review',answer);
806+
await page.route('**/api/action',answer);
807+
await page.goto(app.url);
808+
await expect(page.getByRole('button',{name:'Preparing…',exact:true})).toBeVisible();
809+
/** The poll saw the job end while the full response was held; release it and show it does not restore the running job. */
810+
const settle=async(response:Promise<unknown>)=>{
811+
await expect(page.locator('#banner')).toHaveText('Merged. Refresh to see the result.',{timeout:10_000});
812+
const seen=race.polls;
813+
race.release();await response;
814+
// No poll restarts (the poll interval is 2 s), and the page still shows the outcome.
815+
await page.waitForTimeout(3_000);
816+
expect(race.polls).toBe(seen);
817+
await expect(page.locator('#banner')).toHaveText('Merged. Refresh to see the result.');
818+
await expect(page.getByRole('button',{name:'Preparing…',exact:true})).toHaveCount(0);
819+
};
820+
return {race,settle};
821+
}
822+
823+
test('keeps a merge-job outcome a poll saw while an older review action response was held (F6b)',async({page})=>{
824+
const {race,settle}=await mergeJobOutcomeRace(page);
825+
await page.getByRole('button',{name:'Request change',exact:true}).click();
826+
await page.getByLabel('Change to request').fill('Keep the merge outcome.');
827+
race.hold=true;
828+
const answered=page.waitForResponse(response=>response.url().endsWith('/api/action'));
829+
await page.getByRole('button',{name:'Save change request',exact:true}).click();await race.held;
830+
// Selecting an item while the action waits renders the merge control, which schedules a poll; that poll sees the job end.
831+
await page.getByRole('button',{name:/P2 Document retry behavior/}).click();
832+
await settle(answered);
833+
await page.getByRole('button',{name:/P1 Bound exponential retries/}).click();
834+
await expect(page.getByText('Keep the merge outcome.',{exact:true})).toBeVisible();
835+
});
836+
837+
test('keeps a merge-job outcome a poll saw while an older Plans refresh response was held (F6b)',async({page})=>{
838+
const {race,settle}=await mergeJobOutcomeRace(page);
839+
await page.getByRole('link',{name:'Plans',exact:true}).click();
840+
race.hold=true;
841+
const refreshed=page.waitForResponse(response=>response.url().endsWith('/api/review'));
842+
await page.locator('#plans-refresh').click();await race.held;
843+
await page.getByRole('link',{name:'Review',exact:true}).click();
844+
await page.getByRole('button',{name:/P2 Document retry behavior/}).click();
845+
await settle(refreshed);
846+
await expect(page.locator('#plans-status')).toHaveText('✓ Revision r1 is current.');
847+
});
848+
849+
test('keeps a merge-job outcome a poll saw while an older plan-import reload was held (F6b)',async({page})=>{
850+
const {race,settle}=await mergeJobOutcomeRace(page);
851+
const current=app.service.store.getPlan(race.config.identity),next={...structuredClone(current),revision:current.revision+1,summary:'Make retry limits visible to operators'};
852+
await page.getByRole('link',{name:'Plans',exact:true}).click();
853+
await page.getByLabel('Plan file').setInputFiles({name:'plan.json',mimeType:'application/json',buffer:Buffer.from(JSON.stringify(next))});
854+
race.hold=true;
855+
const reloaded=page.waitForResponse(response=>response.url().endsWith('/api/review'));
856+
// The import's success renders the merge control, which schedules a poll; the poll sees the job end during the reload.
857+
await page.getByRole('button',{name:'Import next revision'}).click();await race.held;
858+
await settle(reloaded);
859+
await expect(page.locator('#plans-status')).toHaveText('✓ Revision r2 is current.');
860+
});
861+
862+
test('keeps a merge-job outcome a poll saw while an older Apply draft reload was held (F6b)',async({page})=>{
863+
let plan:unknown;
864+
const planning:PlanningDeps={provider:{invoke:async()=>JSON.stringify(plan)},describe:()=>({repo:{name:'retry-service',baseRef:'main'},issue:{number:3,title:'Retries',body:'',comments:[]},approvedLessons:[],validate:()=>undefined})};
865+
const {race,settle}=await mergeJobOutcomeRace(page,planning);
866+
const current=app.service.store.getPlan(race.config.identity);
867+
plan={...structuredClone(current),revision:current.revision+1,summary:'Make retry limits visible to operators'};
868+
await page.getByRole('link',{name:'Plans',exact:true}).click();
869+
await page.getByRole('button',{name:'Draft next revision'}).click();
870+
const apply=page.getByRole('button',{name:'Apply draft',exact:true});
871+
await expect(apply).toBeVisible();
872+
race.hold=true;
873+
const reloaded=page.waitForResponse(response=>response.url().endsWith('/api/review'));
874+
// Apply's success renders the merge control, which schedules a poll; the poll sees the job end during the reload.
875+
await apply.click();await race.held;
876+
await settle(reloaded);
877+
await expect(page.locator('#plans-status')).toHaveText('✓ Revision r2 is current.');
878+
});
879+
880+
test('keeps the Merge button pending while its click is in flight, across a render (F6b)',async({page})=>{
881+
const config={...app.service.config,demo:false};await app.close();removeDemoOutOfScope(config);
882+
const gateway:MergeGateway={inspect:async()=>{const snapshot=(await app.service.load()).snapshot;return {base:snapshot.base,head:snapshot.head,pullRequestState:'OPEN',mergeable:'MERGEABLE',rulesKnown:true,atomicBaseGuard:true,mergeQueue:false,requiredChecks:[],alreadyFixed:'clear',pullRequest:7,draft:false};},merge:async()=>{throw new Error('The browser test answers every merge request itself.');}};
883+
app=await startServer(config,0,undefined,gateway);
884+
let view=await app.service.load();for(const segment of view.segments.filter(value=>value.row==='Unplanned'||value.row==='Ambiguous'))view=await app.service.act({action:'accept',key:segment.key,token:view.token});for(const item of view.items)view=await app.service.act({action:'approve',item:item.id,confirmNoChange:item.count===0,token:view.token});
885+
const running={id:'0f6b0000-0000-4000-8000-0000000000d1',state:'running',step:'preparing',reason:null,checks:[],url:null,startedAt:'2026-10-11T00:00:00Z',updatedAt:'2026-10-11T00:00:00Z'};
886+
let release!:()=>void,arrived!:()=>void;const released=new Promise<void>(resolve=>{release=resolve;}),held=new Promise<void>(resolve=>{arrived=resolve;});
887+
await page.route('**/api/action',async route=>{const body=route.request().postDataJSON();if(body.action!=='merge'){await route.continue();return;}
888+
const response=await route.fetch({url:route.request().url().replace('/api/action','/api/review'),method:'GET'}),review=await response.json();
889+
arrived();await released;
890+
await route.fulfill({status:200,contentType:'application/json',body:JSON.stringify({...review,merge:{...review.merge,ready:false,action:null,job:running},job:running})});});
891+
await page.route('**/api/merge',route=>route.fulfill({status:200,contentType:'application/json',body:JSON.stringify({queue:null,job:running})}));
892+
// A runner server reports merging as a job (its merge status carries `job`).
893+
await page.route('**/api/review',async route=>{const response=await route.fetch(),body=await response.json();body.merge={...body.merge,job:null};await route.fulfill({response,json:body});});
894+
await page.goto(app.url);page.on('dialog',dialog=>dialog.accept());
895+
const button=page.locator('#merge');
896+
await page.getByRole('button',{name:'Merge PR',exact:true}).click();await held;
897+
await expect(button).toHaveAttribute('aria-disabled','true');await expect(button).toHaveText('Requesting merge…');
898+
// Selecting an item renders the page, merge control included, while the click's request is still in flight.
899+
await page.getByRole('button',{name:/P2 Document retry behavior/}).click();
900+
await expect(page.getByRole('button',{name:/P2 Document retry behavior/})).toHaveAttribute('aria-current','true');
901+
await expect(button).toHaveAttribute('aria-disabled','true');await expect(button).toHaveText('Requesting merge…');
902+
await expect(button).toHaveJSProperty('disabled',false);
903+
release();
904+
await expect(page.getByRole('button',{name:'Preparing…',exact:true})).toHaveAttribute('aria-disabled','true');
905+
});
906+
787907
test('keeps focus on the Merge button when a merge-job click is refused (F6b)',async({page})=>{
788908
const config={...app.service.config,demo:false};await app.close();removeDemoOutOfScope(config);
789909
const gateway:MergeGateway={inspect:async()=>{const snapshot=(await app.service.load()).snapshot;return {base:snapshot.base,head:snapshot.head,pullRequestState:'OPEN',mergeable:'MERGEABLE',rulesKnown:true,atomicBaseGuard:true,mergeQueue:false,requiredChecks:[],alreadyFixed:'clear',pullRequest:7,draft:false};},merge:async()=>{throw new Error('The browser test answers every merge request itself.');}};
@@ -860,6 +980,8 @@ test('follows a started merge job when the server could not reload the review af
860980
await expect(page.locator('#banner')).toContainText('Preparing the merge');
861981
await expect(page.locator('#banner')).toHaveText('Merged. Refresh to see the result.',{timeout:15000});
862982
expect(polls).toBeGreaterThanOrEqual(2);
983+
// Give a background reload started by the job's end time to reach the route before counting.
984+
await page.waitForTimeout(2500);
863985
expect(reviews).toBe(reloadsBefore);
864986
expect(await page.locator('#items button').count()).toBe(items);
865987
});
@@ -901,6 +1023,8 @@ test('follows a one-click merge job from preparation through the required-check
9011023
// The job's end updates only the merge control (AGENTS.md, Async review UI): no background reload erases the
9021024
// person's selection or input.
9031025
await expect(page.locator('#banner')).toHaveText('Merged. Refresh to see the result.');
1026+
// Give a background reload started by the job's end time to reach the route before counting.
1027+
await page.waitForTimeout(2500);
9041028
expect(reviews).toBe(reloadsBeforeEnd);
9051029
await expect(button).toHaveAttribute('aria-disabled','true');await expect(button).toHaveJSProperty('disabled',false);
9061030
expect(polls).toBe(3);

‎web/public/app.js‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ let snippetSelection = null;
3636
// Kept until the server answers, so a resend after a lost response replays the same click instead of merging twice.
3737
// The key travels with the exact request it was made for: a later Refresh changes data.token, not this request.
3838
let mergeAction = null;
39+
// True while a Merge PR click's request is in flight: a render meanwhile (selecting an item, a plan reload) keeps the
40+
// control marked and labelled as pending instead of offering it again from `merge.ready`.
41+
let mergeClickPending = false;
3942
const statusClass = (text) =>
4043
text.startsWith("✓")
4144
? "good"
@@ -188,6 +191,14 @@ function renderMerge() {
188191
$("merge").disabled = !merge.ready;
189192
$("merge").removeAttribute("aria-disabled");
190193
}
194+
if (mergeClickPending) {
195+
if ("job" in merge) $("merge").setAttribute("aria-disabled", "true");
196+
else $("merge").disabled = true;
197+
$("merge").textContent = "Requesting merge…";
198+
$("merge-details").textContent = merge.queue ? "Merge status" : "Review blockers";
199+
scheduleMergePoll();
200+
return;
201+
}
191202
const job = merge.job;
192203
if (job?.state === "running") {
193204
// Keep the control focusable while its job runs; repeat activation is ignored because the merge is not ready.
@@ -622,10 +633,13 @@ $("merge").onclick = async () => {
622633
// With merge jobs, the click returns at once and the focused control must keep focus: mark it, do not disable it.
623634
if (data.merge && "job" in data.merge) $("merge").setAttribute("aria-disabled", "true");
624635
else $("merge").disabled = true;
636+
mergeClickPending = true;
637+
$("merge").textContent = "Requesting merge…";
625638
try {
626639
rememberDraft();
627640
mergeAction ??= { actionId: crypto.randomUUID(), token: data.token, jobBefore: data.merge.job?.id ?? null };
628641
const updated = await api("/api/action", { action: "merge", token: mergeAction.token, actionId: mergeAction.actionId });
642+
mergeClickPending = false;
629643
// The composer stayed editable while the request was in flight: keep what the person typed meanwhile.
630644
rememberDraft();
631645
mergeAction = null;
@@ -657,6 +671,7 @@ $("merge").onclick = async () => {
657671
render();
658672
$("banner").textContent = `${queued ? "Merge queued" : "Merge submitted"}. ${updated.mergeResult.url}`;
659673
} catch (error) {
674+
mergeClickPending = false;
660675
rememberDraft();
661676
// Only a parsed, definite server answer resolves this click. No response, an unreadable body, 503 (nothing
662677
// applied) or an admitted attempt with an unknown outcome keeps the key until that attempt ends.

0 commit comments

Comments
 (0)