The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 03:15 UTC
perf(pr): actions update every client from the host's reply instead of re-reads (#25761)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com> Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com>
Bilal Bakr committed
Nov 6, 2026 at 01:45 UTC
e1494ae25b788b764035604de4eda6d3269fbaa9
36 files changed
+1930
-413
apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx
+1
-1
@@ -162,7 +162,7 @@ export function PullRequestMergeControls(props: {
162
},
163
});
164
// A stack can partly merge before the provider reports a failure.
165
- refreshDetail();
165
+ if (!AsyncResult.isSuccess(response)) refreshDetail();
166
refreshActivity();
167
stack.refresh();
168
pending.current = false;
apps/mobile/src/features/pull-requests/usePullRequestAction.ts
-2
@@ -19,7 +19,6 @@ export function usePullRequestAction(params: PullRequestParams, pr: PullRequestD
19
const target = pullRequestTarget(params);
20
const permissions = usePullRequestPermissions(params, pr);
21
const run = useAtomCommand(composerPullRequests.runAction, { reportFailure: false });
22
- const refreshDetail = useAtomRefresh(composerPullRequests.detail(target));
22
const refreshActivity = useAtomRefresh(composerPullRequests.activity(target));
23
const pending = useRef(false);
24
const [busy, setBusy] = useState(false);
@@ -43,7 +42,6 @@ export function usePullRequestAction(params: PullRequestParams, pr: PullRequestD
42
);
43
return;
44
}
46
- refreshDetail();
45
refreshActivity();
46
};
47
const confirm = (action: PullRequestAction, title: string, message: string) =>
apps/mobile/src/features/pull-requests/usePullRequestListActions.ts
+1
@@ -94,6 +94,7 @@ export function usePullRequestListActions(
94
throw new Error(`This action isn't available for this ${terminology.singular}.`);
95
const result = await run({ ...target, input: { ...target.input, action } });
96
if (result._tag === "Failure") throw squashAtomCommandFailure(result);
97
+ if (result.value !== undefined) return;
98
onChanged(
99
entry,
100
action === "close"
apps/mobile/src/state/pull-requests.ts
+30
-3
@@ -1,6 +1,7 @@
1
import {
2
createPullRequestEnvironmentAtoms,
3
createPullRequestStackAtomFamily,
4
+ patchPullRequestListEntries,
5
} from "@t3tools/client-runtime/state/pull-requests";
6
import type { EnvironmentId, PullRequestListInput } from "@t3tools/contracts";
7
import * as Effect from "effect/Effect";
@@ -21,10 +22,17 @@ export const pullRequestListPagesKey = (target: {
22
readonly input: PullRequestListInput;
23
}) => JSON.stringify([target.environmentId, target.input]);
24
25
+// Which listing each pages atom holds, so an action's reply can reach the pages past its head.
26
+const pullRequestListPagesTargets = new WeakMap<
27
+ object,
28
+ readonly [EnvironmentId, PullRequestListInput]
29
+>();
30
/** The pages loaded past each listing's head, keyed by {@link pullRequestListPagesKey}. */
25
-export const pullRequestListPagesFamily = Atom.family((_key: string) =>
26
- Atom.make<PullRequestListPages | null>(null).pipe(Atom.setIdleTTL(5 * 60_000)),
27
-);
31
+export const pullRequestListPagesFamily = Atom.family((key: string) => {
32
+ const atom = Atom.make<PullRequestListPages | null>(null).pipe(Atom.setIdleTTL(5 * 60_000));
33
+ pullRequestListPagesTargets.set(atom, JSON.parse(key));
34
+ return atom;
35
+});
36
37
/** Diff stats each environment has answered so far, so rows keep them when they scroll away. */
38
export const pullRequestListStatsFamily = Atom.family((_environmentId: string) =>
@@ -34,6 +42,25 @@ export const pullRequestListStatsFamily = Atom.family((_environmentId: string) =
42
);
43
44
export const composerPullRequests = createPullRequestEnvironmentAtoms(connectionAtomRuntime, {
45
+ // Rows on pages past each listing's head; the head itself is patched where it is cached.
46
+ actionReply: (target, reply, registry) =>
47
+ Effect.sync(() => {
48
+ for (const atom of registry.getNodes().keys()) {
49
+ const listing =
50
+ typeof atom === "string" ? undefined : pullRequestListPagesTargets.get(atom);
51
+ if (listing === undefined || listing[0] !== target.environmentId) continue;
52
+ registry.update(atom as Atom.Writable<PullRequestListPages | null>, (pages) => {
53
+ if (pages === null) return pages;
54
+ const entries = patchPullRequestListEntries(
55
+ listing[1],
56
+ pages.entries,
57
+ target.input,
58
+ reply,
59
+ );
60
+ return entries === "refresh" || entries === pages.entries ? pages : { ...pages, entries };
61
+ });
62
+ }
63
+ }),
64
// A new head can change which files GitHub still counts as viewed, so the viewed-files read is
65
// refreshed where the new head lands. The detail atom still holds the previous answer here.
66
detail: (target, value, registry) =>
apps/server/src/pullRequest/PullRequestService.test.ts
+69
-3
@@ -1239,7 +1239,7 @@ it.effect("publishes a merge for immediate settlement only after host confirmati
1239
detail: "HTTP 504",
1240
}),
1241
)
1242
- : Effect.succeed({ ...changeRequest(1, mergedAt), state }),
1242
+ : Effect.succeed({ ...changeRequest(1, mergedAt), state, mergedAt }),
1243
}),
1244
],
1245
});
@@ -1248,7 +1248,7 @@ it.effect("publishes a merge for immediate settlement only after host confirmati
1248
Effect.forkChild({ startImmediately: true }),
1249
);
1250
1251
- yield* service.runAction({ ...reference, action: "merge" });
1251
+ assert.isUndefined(yield* service.runAction({ ...reference, action: "merge" }));
1252
const queuedRefresh = Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes));
1253
confirmationFails = true;
1254
yield* service.runAction({ ...reference, action: "merge" });
@@ -1258,7 +1258,8 @@ it.effect("publishes a merge for immediate settlement only after host confirmati
1258
);
1259
confirmationFails = false;
1260
state = "merged";
1261
- yield* TestClock.setTime(Date.parse(mergedAt));
1261
+ // The event carries the host's merge time, not the moment the confirmation ran.
1262
+ yield* TestClock.setTime(Date.parse(mergedAt) + 60_000);
1263
yield* service.runAction({
1264
...reference,
1265
repository: " ACME/WEB ",
@@ -1274,6 +1275,71 @@ it.effect("publishes a merge for immediate settlement only after host confirmati
1275
),
1276
);
1277
1278
+it.effect("returns the host's merged reply as a summary and trusts it without another read", () =>
1279
+ Effect.scoped(
1280
+ Effect.gen(function* () {
1281
+ const mergedAt = "2026-09-03T02:00:00.000Z";
1282
+ const merged = {
1283
+ number: 1,
1284
+ title: "Change request 1",
1285
+ url: "https://host/pull/1",
1286
+ headBranch: "feat/1",
1287
+ baseBranch: "main",
1288
+ state: "merged" as const,
1289
+ isDraft: false,
1290
+ updatedAt: mergedAt,
1291
+ mergedAt,
1292
+ headSha: "abc123",
1293
+ autoMergeEnabled: false,
1294
+ };
1295
+ let summaryReads = 0;
1296
+ const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
1297
+ const service = yield* makeService({
1298
+ projects: [
1299
+ project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
1300
+ ],
1301
+ providers: [
1302
+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1303
+ runAction: () => Effect.succeed(merged),
1304
+ getChangeRequestSummary: () =>
1305
+ Effect.sync(() => {
1306
+ summaryReads++;
1307
+ return { ...changeRequest(1, mergedAt), state: "merged" as const, mergedAt };
1308
+ }),
1309
+ }),
1310
+ ],
1311
+ });
1312
+ const merges = yield* service.subscribeMerges;
1313
+ const observedMerge = yield* Stream.runHead(merges).pipe(
1314
+ Effect.forkChild({ startImmediately: true }),
1315
+ );
1316
+ const observedAt = Date.parse("2026-09-03T02:00:01.000Z");
1317
+ yield* TestClock.setTime(observedAt);
1318
+
1319
+ // Clients that did not ask decode the success as void, so they must get nothing back.
1320
+ assert.isUndefined(yield* service.runAction({ ...reference, action: "merge" }));
1321
+ const result = yield* service.runAction({
1322
+ ...reference,
1323
+ action: "merge",
1324
+ replyWithSummary: true,
1325
+ });
1326
+
1327
+ assert.deepStrictEqual(result, {
1328
+ ...merged,
1329
+ provider: SourceControlProviderKind.make("github"),
1330
+ projectId: reference.projectId,
1331
+ repository: reference.repository,
1332
+ observedAt,
1333
+ });
1334
+ assert.strictEqual(summaryReads, 0);
1335
+ assert.deepStrictEqual(Option.getOrThrow(yield* Fiber.join(observedMerge)), {
1336
+ ...reference,
1337
+ mergedAt,
1338
+ });
1339
+ }),
1340
+ ),
1341
+);
1342
+
1343
it.effect("refreshes every reader before a queued merge confirmation finishes", () =>
1344
Effect.scoped(
1345
Effect.gen(function* () {
apps/server/src/pullRequest/PullRequestService.ts
+100
-59
@@ -86,9 +86,11 @@ import type { SourceControlProviderContext } from "@t3tools/source-control-core/
86
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
87
import {
88
type ProviderChangeRequest,
89
+ type ProviderChangeRequestDetail,
90
type ProviderDiffFilePaths,
91
type ProviderFilterOptionPage,
92
type ProviderListCursor,
93
+ type ProviderChangeRequestSummary,
94
type ProviderChangeRequestWatchFingerprint,
95
type PullRequestProviderApi,
96
PullRequestProviderError,
@@ -250,7 +252,9 @@ export class PullRequestService extends Context.Service<
252
readonly changeBreakdown: (
253
input: PullRequestRef,
254
) => Effect.Effect<PullRequestChangeBreakdown, PullRequestError>;
253
- readonly runAction: (input: PullRequestActionInput) => Effect.Effect<void, PullRequestError>;
255
+ readonly runAction: (
256
+ input: PullRequestActionInput,
257
+ ) => Effect.Effect<PullRequestSummary | undefined, PullRequestError>;
258
readonly update: (input: PullRequestUpdateInput) => Effect.Effect<void, PullRequestError>;
259
readonly comment: (input: PullRequestCommentInput) => Effect.Effect<void, PullRequestError>;
260
readonly updateComment: (
@@ -1663,6 +1667,54 @@ export const make = Effect.gen(function* () {
1667
};
1668
});
1669
1670
+ const toSummary = (
1671
+ project: SupportedProject,
1672
+ changeRequest: ProviderChangeRequestSummary | ProviderChangeRequestDetail,
1673
+ observedAt: number,
1674
+ reply = false,
1675
+ ): PullRequestSummary => ({
1676
+ provider: project.api.kind,
1677
+ projectId: project.project.id,
1678
+ repository: project.repository,
1679
+ number: changeRequest.number,
1680
+ title: changeRequest.title,
1681
+ url: changeRequest.url,
1682
+ state: changeRequest.state,
1683
+ headBranch: changeRequest.headBranch,
1684
+ baseBranch: changeRequest.baseBranch,
1685
+ // An action reply may not carry these, and null would erase a time a client already holds.
1686
+ ...(changeRequest.closedAt === undefined && reply
1687
+ ? {}
1688
+ : { closedAt: changeRequest.closedAt ?? null }),
1689
+ ...(changeRequest.mergedAt === undefined && reply
1690
+ ? {}
1691
+ : { mergedAt: changeRequest.mergedAt ?? null }),
1692
+ updatedAt: changeRequest.updatedAt,
1693
+ observedAt,
1694
+ ...(changeRequest.isDraft === undefined ? {} : { isDraft: changeRequest.isDraft }),
1695
+ ...(changeRequest.author === undefined ? {} : { author: changeRequest.author }),
1696
+ ...(changeRequest.additions === undefined ? {} : { additions: changeRequest.additions }),
1697
+ ...(changeRequest.deletions === undefined ? {} : { deletions: changeRequest.deletions }),
1698
+ ...(changeRequest.changedFiles === undefined
1699
+ ? {}
1700
+ : { changedFiles: changeRequest.changedFiles }),
1701
+ ...(changeRequest.reviewDecision === undefined
1702
+ ? {}
1703
+ : { reviewDecision: changeRequest.reviewDecision }),
1704
+ ...(changeRequest.checksState === undefined ? {} : { checksState: changeRequest.checksState }),
1705
+ ...(changeRequest.mergeability === undefined
1706
+ ? {}
1707
+ : { mergeability: changeRequest.mergeability }),
1708
+ ...(changeRequest.stack === undefined ? {} : { stack: changeRequest.stack }),
1709
+ ...(changeRequest.headSha?.trim() ? { headSha: changeRequest.headSha.trim() } : {}),
1710
+ ...(changeRequest.autoMergeEnabled === undefined
1711
+ ? {}
1712
+ : { autoMergeEnabled: changeRequest.autoMergeEnabled }),
1713
+ ...(changeRequest.autoMergeMethod === undefined
1714
+ ? {}
1715
+ : { autoMergeMethod: changeRequest.autoMergeMethod }),
1716
+ });
1717
+
1718
const summaryUncached: PullRequestService["Service"]["summary"] = (input) =>
1719
requireProject(input).pipe(
1720
Effect.flatMap((project) => {
@@ -1672,49 +1724,17 @@ export const make = Effect.gen(function* () {
1724
host: project.host,
1725
number: input.number,
1726
};
1675
- const read =
1727
+ const read: Effect.Effect<
1728
+ ProviderChangeRequestSummary | ProviderChangeRequestDetail,
1729
+ PullRequestProviderError
1730
+ > =
1731
project.api.getChangeRequestSummary === undefined
1732
? project.api.getChangeRequest(providerInput)
1733
: project.api.getChangeRequestSummary(providerInput);
1734
return read.pipe(
1735
Effect.mapError(toPullRequestError("summary")),
1736
observeRead,
1682
- Effect.map(({ value: changeRequest, observedAt }): PullRequestSummary => ({
1683
- provider: project.api.kind,
1684
- projectId: project.project.id,
1685
- repository: project.repository,
1686
- number: changeRequest.number,
1687
- title: changeRequest.title,
1688
- url: changeRequest.url,
1689
- state: changeRequest.state,
1690
- headBranch: changeRequest.headBranch,
1691
- baseBranch: changeRequest.baseBranch,
1692
- closedAt: changeRequest.closedAt ?? null,
1693
- mergedAt: changeRequest.mergedAt ?? null,
1694
- updatedAt: changeRequest.updatedAt,
1695
- observedAt,
1696
- ...(changeRequest.isDraft === undefined ? {} : { isDraft: changeRequest.isDraft }),
1697
- ...(changeRequest.author === undefined ? {} : { author: changeRequest.author }),
1698
- ...(changeRequest.additions === undefined
1699
- ? {}
1700
- : { additions: changeRequest.additions }),
1701
- ...(changeRequest.deletions === undefined
1702
- ? {}
1703
- : { deletions: changeRequest.deletions }),
1704
- ...(changeRequest.changedFiles === undefined
1705
- ? {}
1706
- : { changedFiles: changeRequest.changedFiles }),
1707
- ...(changeRequest.reviewDecision === undefined
1708
- ? {}
1709
- : { reviewDecision: changeRequest.reviewDecision }),
1710
- ...(changeRequest.checksState === undefined
1711
- ? {}
1712
- : { checksState: changeRequest.checksState }),
1713
- ...(changeRequest.mergeability === undefined
1714
- ? {}
1715
- : { mergeability: changeRequest.mergeability }),
1716
- ...(changeRequest.stack === undefined ? {} : { stack: changeRequest.stack }),
1717
- })),
1737
+ Effect.map(({ value, observedAt }) => toSummary(project, value, observedAt)),
1738
);
1739
}),
1740
);
@@ -1988,9 +2008,15 @@ export const make = Effect.gen(function* () {
2008
),
2009
);
2010
1991
- const runAction = (input: PullRequestActionInput): Effect.Effect<string, PullRequestError> =>
2011
+ type ActionOutcome = {
2012
+ readonly repository: string;
2013
+ readonly summary: PullRequestSummary | undefined;
2014
+ };
2015
+ const runAction = (
2016
+ input: PullRequestActionInput,
2017
+ ): Effect.Effect<ActionOutcome, PullRequestError> =>
2018
requireProject(input).pipe(
1993
- Effect.flatMap((project): Effect.Effect<string, PullRequestError> => {
2019
+ Effect.flatMap((project): Effect.Effect<ActionOutcome, PullRequestError> => {
2020
if (input.action === "delete-branch" && project.api.capabilities.deleteBranch !== true) {
2021
return Effect.fail(
2022
new PullRequestOperationError({
@@ -2050,7 +2076,7 @@ export const make = Effect.gen(function* () {
2076
"runAction",
2077
input.action === "update-branch",
2078
).pipe(
2053
- Effect.flatMap((viewer): Effect.Effect<string, PullRequestError> => {
2079
+ Effect.flatMap((viewer): Effect.Effect<ActionOutcome, PullRequestError> => {
2080
const stackRebase = input.stackNumber !== undefined && input.action === "update-branch";
2081
if (
2082
stackRebase ? viewer.stackRebase !== true : !viewer.actions.includes(input.action)
@@ -2119,9 +2145,17 @@ export const make = Effect.gen(function* () {
2145
: refreshAfterTurn(project.project.id),
2146
),
2147
Effect.mapError(toPullRequestError("runAction")),
2122
- Effect.as(
2123
- project.repositoryKey !== null ? input.repository.trim() : project.repository,
2124
- ),
2148
+ observeRead,
2149
+ Effect.map(({ value, observedAt }) => ({
2150
+ repository:
2151
+ project.repositoryKey !== null
2152
+ ? input.repository.trim()
2153
+ : project.repository,
2154
+ summary:
2155
+ value === undefined || input.stackNumber !== undefined
2156
+ ? undefined
2157
+ : toSummary(project, value, observedAt, true),
2158
+ })),
2159
),
2160
),
2161
);
@@ -3571,7 +3605,7 @@ export const make = Effect.gen(function* () {
3605
)(function* (input) {
3606
const ref = yield* canonicalRef(input);
3607
yield* readCache.invalidate(refScope(ref));
3574
- const repository = yield* runAction(input).pipe(
3608
+ const { repository, summary } = yield* runAction(input).pipe(
3609
Effect.ensuring(readCache.invalidate(refScope(ref))),
3610
);
3611
bumpRefEpoch({ ...ref, repository });
@@ -3579,21 +3613,28 @@ export const make = Effect.gen(function* () {
3613
yield* SubscriptionRef.set(pullRequestRefreshes, listingsEpoch);
3614
if (input.action === "merge") {
3615
// A successful merge action can merely enqueue the PR or enable auto-merge.
3582
- const confirmed = yield* summaryUncached({ ...input, repository }).pipe(
3583
- Effect.catch((error) =>
3584
- Effect.logWarning("failed to confirm pull request merge", { error }).pipe(
3585
- Effect.as(null),
3586
- ),
3587
- ),
3588
- );
3589
- if (confirmed?.state !== "merged") return;
3590
- yield* PubSub.publish(mergedPullRequests, {
3591
- projectId: input.projectId,
3592
- repository,
3593
- number: input.number,
3594
- mergedAt: DateTime.formatIso(yield* DateTime.now),
3595
- });
3616
+ const merged = summary?.state === "merged" ? summary : null;
3617
+ const confirmed =
3618
+ merged?.mergedAt != null
3619
+ ? merged
3620
+ : yield* summaryUncached({ ...input, repository }).pipe(
3621
+ Effect.map((reread) => (reread.state === "merged" ? reread : merged)),
3622
+ Effect.catch((error) =>
3623
+ Effect.logWarning("failed to confirm pull request merge", { error }).pipe(
3624
+ Effect.as(merged),
3625
+ ),
3626
+ ),
3627
+ );
3628
+ if (confirmed?.state === "merged") {
3629
+ yield* PubSub.publish(mergedPullRequests, {
3630
+ projectId: input.projectId,
3631
+ repository,
3632
+ number: input.number,
3633
+ mergedAt: confirmed.mergedAt ?? DateTime.formatIso(yield* DateTime.now),
3634
+ });
3635
+ }
3636
}
3637
+ return input.replyWithSummary === true ? summary : undefined;
3638
});
3639
3640
const credentialCached =
apps/web/src/components/chat/ThreadDetailsPrRow.tsx
-1
@@ -163,7 +163,6 @@ export function ThreadDetailsPrRow({
163
reference,
164
terminology,
165
onSuccess: () => {
166
- detailQuery.refresh();
166
checksQuery.refresh();
167
onActed?.();
168
},
apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+10
-3
@@ -22,6 +22,7 @@ import {
22
type PullRequestUpdateMethod,
23
type PullRequestRef,
24
type PullRequestReviewGuideStop,
25
+ type PullRequestSummary,
26
resolveEnvironmentMachineKind,
27
type ScopedThreadRef,
28
} from "@t3tools/contracts";
@@ -292,7 +293,11 @@ export function PullRequestDetailPanel({
293
* notification can switch it.
294
*/
295
tabOnPage?: boolean;
295
- onActed?: (action?: PullRequestAction, phase?: "sent" | "done" | "failed") => void;
296
+ onActed?: (
297
+ action?: PullRequestAction,
298
+ phase?: "sent" | "done" | "failed",
299
+ reply?: PullRequestSummary,
300
+ ) => void;
301
onClose?: () => void;
302
context?: "page" | "thread";
303
composerDraftTarget?: ScopedThreadRef | DraftId;
@@ -697,9 +702,11 @@ export function PullRequestDetailPanel({
702
if (pullRequestActionNeedsHostRefresh(action)) {
703
void refreshFromHost();
704
} else {
700
- refreshDetail();
705
+ // The action command already showed the reply in the detail or re-read it.
706
+ activityQuery.refresh();
707
+ nativeStackQuery.refresh();
708
}
702
- onActed?.(action, "done");
709
+ onActed?.(action, "done", result.value);
710
return true;
711
};
712
apps/web/src/components/pullRequest/PullRequestSpeedActions.tsx
+3
-2
@@ -1,5 +1,5 @@
1
import { useAtomValue } from "@effect/atom-react";
2
-import type { PullRequestAction } from "@t3tools/contracts";
2
+import type { PullRequestAction, PullRequestSummary } from "@t3tools/contracts";
3
import { createContext, use, type ReactNode } from "react";
4
import type { ChangeRequestTerminology } from "@t3tools/client-runtime/source-control-clients";
5
@@ -25,6 +25,7 @@ type PullRequestSpeedActionEntry = Pick<
25
export interface PullRequestSpeedActionResult<Entry = EnvironmentPullRequestEntry> {
26
readonly entry: Entry;
27
readonly action: PullRequestAction;
28
+ readonly reply?: PullRequestSummary | undefined;
29
}
30
31
export function PullRequestSpeedActions<Entry extends PullRequestSpeedActionEntry>({
@@ -61,7 +62,7 @@ export function PullRequestSpeedActions<Entry extends PullRequestSpeedActionEntr
62
environmentId: entry.environmentId,
63
reference,
64
terminology,
64
- onSuccess: (action) => onActed?.({ entry, action }),
65
+ onSuccess: (action, reply) => onActed?.({ entry, action, reply }),
66
resolveMergeMethod: (detail) => {
67
const allowed = detail.capabilities.mergeMethods.filter(
68
(method) => detail.mergeCapabilities[method],
apps/web/src/components/pullRequest/PullRequestsPage.tsx
+22
-9
@@ -16,6 +16,7 @@ import type {
16
PullRequestListInput,
17
PullRequestListResult,
18
PullRequestListState,
19
+ PullRequestSummary,
20
} from "@t3tools/contracts";
21
import { useAtomValue } from "@effect/atom-react";
22
import { useNavigate, useSearch } from "@tanstack/react-router";
@@ -432,9 +433,10 @@ export function PullRequestsPage() {
433
const overrideEntry = (
434
entry: EnvironmentPullRequestEntry,
435
action: PullRequestAction,
436
+ reply?: PullRequestSummary,
437
): number | null => {
438
const token = ++overrideToken.current;
437
- const override = pullRequestOverrideAfterAction(entry, action, new Date(), token);
439
+ const override = pullRequestOverrideAfterAction(entry, action, new Date(), token, reply);
440
if (override === null) return null;
441
setOverrides((current) => new Map(current).set(pullRequestEntryKey(entry), override));
442
return token;
@@ -449,13 +451,17 @@ export function PullRequestsPage() {
451
});
452
};
453
const detailOverrideTokens = useRef(new Map<string, number | null>());
452
- const onSpeedAction = useStableCallback(({ entry, action }: PullRequestSpeedActionResult) => {
453
- // Some hosts accept a merge before it completes. Let the next host read declare it merged.
454
- if (action !== "merge") overrideEntry(entry, action);
455
- });
456
- const onBatchClosed = useStableCallback((entry: EnvironmentPullRequestEntry) => {
457
- onSpeedAction({ entry, action: "close" });
458
- });
454
+ const onSpeedAction = useStableCallback(
455
+ ({ entry, action, reply }: PullRequestSpeedActionResult) => {
456
+ // Some hosts accept a merge before it completes. Without a reply, let the next read say so.
457
+ if (reply !== undefined || action !== "merge") overrideEntry(entry, action, reply);
458
+ },
459
+ );
460
+ const onBatchClosed = useStableCallback(
461
+ (entry: EnvironmentPullRequestEntry, reply: PullRequestSummary | undefined) => {
462
+ onSpeedAction({ entry, action: "close", reply });
463
+ },
464
+ );
465
const { close: closeBatch, closingKeys } = usePullRequestCloseBatch(onBatchClosed);
466
const [snapshotEnvironmentKey, setSnapshotEnvironmentKey] = useState("");
467
if (environmentKey.length > 0 && snapshotEnvironmentKey !== environmentKey) {
@@ -1545,12 +1551,19 @@ export function PullRequestsPage() {
1551
}
1552
refreshToken={detailRefreshToken}
1553
tabOnPage
1548
- onActed={(action, phase = "done") => {
1554
+ onActed={(action, phase = "done", reply) => {
1555
// From every row held, not the ones on screen: a pull request closed from an open
1556
// list has left the screen, and reopening it has to find it anyway.
1557
const acted = heldPullRequestsBySurface.get(
1558
pullRequestListEntryId(renderedPullRequestSurface),
1559
);
1560
+ if (reply !== undefined) {
1561
+ if (acted !== undefined) {
1562
+ if (action !== undefined) overrideEntry(acted, action, reply);
1563
+ detailOverrideTokens.current.delete(pullRequestEntryKey(acted));
1564
+ }
1565
+ return;
1566
+ }
1567
const stateOnly =
1568
action !== undefined &&
1569
acted !== undefined &&
apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
+22
@@ -4,6 +4,7 @@ import type {
4
ProjectId,
5
PullRequestAction,
6
PullRequestListEntry,
7
+ PullRequestSummary,
8
} from "@t3tools/contracts";
9
import { describe, expect, it } from "vite-plus/test";
10
@@ -33,6 +34,7 @@ import {
34
resolveSelectedEnvironmentId,
35
type EnvironmentPullRequestEntry,
36
applyPullRequestOverrides,
37
+ pullRequestOverrideAfterAction,
38
reusePullRequestEntries,
39
settlePullRequestOverrides,
40
} from "./pullRequestList.logic";
@@ -596,6 +598,26 @@ describe("pull request list overrides", () => {
598
expect(applyPullRequestOverrides(rows, new Map(), key, "open")).toBe(rows);
599
});
600
601
+ it("shows a reply's queued merge as open and never un-merges a merged row", () => {
602
+ const reply = { state: "open", updatedAt: "2026-07-03T00:00:00Z", observedAt: 300 } as const;
603
+ const override = pullRequestOverrideAfterAction(
604
+ entry(1, "open"),
605
+ "merge",
606
+ new Date(900),
607
+ 1,
608
+ reply as unknown as PullRequestSummary,
609
+ )!;
610
+ const overrides = new Map([["#1", override]]);
611
+ expect(applyPullRequestOverrides([entry(1, "open")], overrides, key, "open")).toMatchObject([
612
+ { state: "open", updatedAt: reply.updatedAt, observedAt: 300 },
613
+ ]);
614
+ expect(
615
+ applyPullRequestOverrides([entry(1, "merged")], overrides, key, "all").map(
616
+ (row) => row.state,
617
+ ),
618
+ ).toEqual(["merged"]);
619
+ });
620
+
621
it("keeps a confirmed close hidden when its override is cleared", () => {
622
const at = 1_000_000;
623
const rows = [entry(1, "closed"), entry(2, "open"), entry(3, "merged")];
apps/web/src/components/pullRequest/pullRequestList.logic.ts
+21
-1
@@ -17,8 +17,10 @@ import type {
17
PullRequestListFilters,
18
PullRequestListState,
19
PullRequestState,
20
+ PullRequestSummary,
21
} from "@t3tools/contracts";
22
23
+import { isStalePullRequestReply } from "@t3tools/client-runtime/pull-request-reply";
24
import { toSortableTimestamp } from "@t3tools/client-runtime/state/thread-sort";
25
import type { PullRequestListSort } from "./pullRequestListPreferences";
26
@@ -802,6 +804,9 @@ export interface PullRequestListOverride {
804
readonly updatedAt: string;
805
readonly token: number;
806
readonly at: number;
807
+ /** Set when the host reported this state, so a newer row can outrank it. */
808
+ readonly fromReply?: true;
809
+ readonly observedAt?: number;
810
}
811
812
export function pullRequestOverrideAfterAction(
@@ -809,7 +814,20 @@ export function pullRequestOverrideAfterAction(
814
action: PullRequestAction,
815
now: Date,
816
token: number,
817
+ reply?: PullRequestSummary,
818
): PullRequestListOverride | null {
819
+ if (reply !== undefined) {
820
+ const { state, isDraft, updatedAt, observedAt } = reply;
821
+ return {
822
+ state,
823
+ ...(isDraft === undefined ? {} : { isDraft }),
824
+ updatedAt,
825
+ ...(observedAt === undefined ? {} : { observedAt }),
826
+ fromReply: true,
827
+ token,
828
+ at: now.getTime(),
829
+ };
830
+ }
831
const stamp = { updatedAt: now.toISOString(), token, at: now.getTime() };
832
switch (action) {
833
case "close":
@@ -836,7 +854,9 @@ export function applyPullRequestOverrides<Entry extends PullRequestListEntry>(
854
if (overrides.size === 0 && state === "all") return entries;
855
const out: Entry[] = [];
856
for (const entry of entries) {
839
- const override = overrides.get(keyOf(entry));
857
+ const held = overrides.get(keyOf(entry));
858
+ const override =
859
+ held?.fromReply === true && isStalePullRequestReply(entry, held) ? undefined : held;
860
if (state !== "all" && (override?.state ?? entry.state) !== state) continue;
861
out.push(override === undefined ? entry : { ...entry, ...override });
862
}
apps/web/src/components/pullRequest/usePullRequestActions.ts
+7
-4
@@ -11,6 +11,7 @@ import type {
11
PullRequestDetail,
12
PullRequestMergeMethod,
13
PullRequestRef,
14
+ PullRequestSummary,
15
} from "@t3tools/contracts";
16
import { useRef, useState } from "react";
17
import {
@@ -133,7 +134,7 @@ export function usePullRequestActionRunner({
134
environmentId: EnvironmentId;
135
reference: PullRequestRef | null;
136
terminology: ChangeRequestTerminology;
136
- onSuccess?: (action: PullRequestAction) => void;
137
+ onSuccess?: (action: PullRequestAction, reply: PullRequestSummary | undefined) => void;
138
/** Resolve repository settings on click to avoid per-row reads. */
139
resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;
140
}) {
@@ -179,13 +180,15 @@ export function usePullRequestActionRunner({
180
return;
181
}
182
toastManager.add({ type: "success", title: actionSuccessLabels(terminology.singular)[action] });
182
- onSuccess?.(action);
183
+ onSuccess?.(action, result.value);
184
};
185
186
return { actionPending, perform };
187
}
188
188
-export function usePullRequestCloseBatch(onClosed: (entry: EnvironmentPullRequestEntry) => void) {
189
+export function usePullRequestCloseBatch(
190
+ onClosed: (entry: EnvironmentPullRequestEntry, reply: PullRequestSummary | undefined) => void,
191
+) {
192
const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });
193
const pending = useRef(new Set<string>());
194
const [closingKeys, setClosingKeys] = useState<ReadonlySet<string>>(() => new Set());
@@ -219,7 +222,7 @@ export function usePullRequestCloseBatch(onClosed: (entry: EnvironmentPullReques
222
);
223
return;
224
}
222
- onClosed(entry);
225
+ onClosed(entry, result.value);
226
return true;
227
}),
228
);
packages/client-runtime/package.json
+4
@@ -515,6 +515,10 @@
515
"types": "./src/pullRequestReactions.ts",
516
"default": "./src/pullRequestReactions.ts"
517
},
518
+ "./pull-request-reply": {
519
+ "types": "./src/pullRequestReply.ts",
520
+ "default": "./src/pullRequestReply.ts"
521
+ },
522
"./pull-request-query": {
523
"types": "./src/pullRequestQuery.ts",
524
"default": "./src/pullRequestQuery.ts"
packages/client-runtime/src/pullRequestReply.ts
new
+20
@@ -0,0 +1,20 @@
1
+import type { PullRequestState } from "@t3tools/contracts";
2
+
3
+interface ObservedPullRequest {
4
+ readonly state: PullRequestState;
5
+ readonly updatedAt?: string | undefined;
6
+ readonly observedAt?: number | undefined;
7
+}
8
+
9
+/** Older than what is shown by host update time, then server read time, or a merge undone. */
10
+export function isStalePullRequestReply(
11
+ shown: ObservedPullRequest,
12
+ reply: ObservedPullRequest,
13
+): boolean {
14
+ if (shown.state === "merged" && reply.state !== "merged") return true;
15
+ if (shown.updatedAt !== undefined && reply.updatedAt !== undefined) {
16
+ const updated = Date.parse(reply.updatedAt) - Date.parse(shown.updatedAt);
17
+ if (Number.isFinite(updated) && updated !== 0) return updated < 0;
18
+ }
19
+ return (reply.observedAt ?? -Infinity) < (shown.observedAt ?? -Infinity);
20
+}
packages/client-runtime/src/state/pullRequests.test.ts
+615
-3
@@ -9,6 +9,7 @@ import {
9
PullRequestOperationError,
10
WS_METHODS,
11
type AuthSessionState,
12
+ type PullRequestListInput,
13
} from "@t3tools/contracts";
14
import { expect, it } from "@effect/vitest";
15
import * as Schema from "effect/Schema";
@@ -42,7 +43,8 @@ import {
43
createPullRequestEnvironmentAtoms,
44
} from "./pullRequests.ts";
45
import * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts";
45
-import { executeAtomQuery } from "./runtime.ts";
46
+import { executeAtomQuery, queryPersistenceKey } from "./runtime.ts";
47
+import { EnvironmentQueryStore } from "./queryPersistence.ts";
48
import { createPullRequestRouter } from "./pullRequestRouting.ts";
49
import { PullRequestRoutingPermissions } from "../connection/pullRequestRoutingPermissions.ts";
50
@@ -522,6 +524,8 @@ const makeTestRuntime = Effect.fn("makeTestRuntime")(function* (
524
client: WsRpcProtocolClient,
525
localClient?: WsRpcProtocolClient,
526
localOrigin = false,
527
+ onAnswer: Parameters<typeof createPullRequestEnvironmentAtoms>[1] = {},
528
+ queryStore: typeof EnvironmentQueryStore.Service = null,
529
) {
530
const originTarget = localOrigin
531
? new PrimaryConnectionTarget({
@@ -587,15 +591,16 @@ const makeTestRuntime = Effect.fn("makeTestRuntime")(function* (
591
Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
592
} as EnvironmentRegistry.EnvironmentRegistry["Service"]);
593
const runtime = Atom.runtime(
590
- Layer.merge(
594
+ Layer.mergeAll(
595
Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
596
Layer.succeed(
597
PullRequestDiffLoader.PullRequestDiffLoader,
598
PullRequestDiffLoader.PullRequestDiffLoader.of({ load: () => Effect.die("unused") }),
599
),
600
+ Layer.succeed(EnvironmentQueryStore, queryStore),
601
),
602
);
598
- const atoms = createPullRequestEnvironmentAtoms(runtime);
603
+ const atoms = createPullRequestEnvironmentAtoms(runtime, onAnswer);
604
const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
605
Effect.sync(() => registry.dispose()),
606
);
@@ -1099,6 +1104,613 @@ it.effect("keeps a close batch ordered and continues after a refused close", ()
1104
),
1105
);
1106
1107
+const actionReference = {
1108
+ projectId: ProjectId.make("project-1"),
1109
+ host: "github.example.com",
1110
+ repository: "acme/web",
1111
+ number: 1,
1112
+};
1113
+const actionReply = {
1114
+ ...actionReference,
1115
+ provider: "github",
1116
+ title: "Ship it",
1117
+ url: "https://github.example.com/acme/web/pull/1",
1118
+ headBranch: "feature",
1119
+ baseBranch: "main",
1120
+ state: "merged" as const,
1121
+ isDraft: false,
1122
+ updatedAt: "2026-10-27T10:00:00Z",
1123
+ observedAt: 200,
1124
+};
1125
+
1126
+function actionReplyClient(overrides: Record<string, unknown> = {}) {
1127
+ return {
1128
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
1129
+ [WS_METHODS.pullRequestsRunAction]: () => Effect.succeed(actionReply),
1130
+ ...overrides,
1131
+ } as unknown as WsRpcProtocolClient;
1132
+}
1133
+
1134
+it.effect("shows an action's reply in loaded readers and moves list rows without reads", () =>
1135
+ Effect.scoped(
1136
+ Effect.gen(function* () {
1137
+ const reads: string[] = [];
1138
+ const open = { ...actionReference, state: "open", isDraft: true, observedAt: 100 };
1139
+ const read = (name: string) => () =>
1140
+ Effect.sync(() => {
1141
+ reads.push(name);
1142
+ return open;
1143
+ });
1144
+ const replies: unknown[] = [];
1145
+ const listAnswers: unknown[] = [];
1146
+ const client = actionReplyClient({
1147
+ [WS_METHODS.pullRequestsDetail]: read("detail"),
1148
+ [WS_METHODS.pullRequestsPreview]: read("preview"),
1149
+ [WS_METHODS.pullRequestsSummary]: read("summary"),
1150
+ [WS_METHODS.pullRequestsList]: (input: { readonly state: string }) =>
1151
+ Effect.sync(() => {
1152
+ reads.push(`list:${input.state}`);
1153
+ return {
1154
+ entries: input.state === "merged" ? [] : [open],
1155
+ viewers: {},
1156
+ providers: [],
1157
+ errors: [],
1158
+ truncated: false,
1159
+ nextCursors: {},
1160
+ };
1161
+ }),
1162
+ });
1163
+ const saved = new Map<string, string>();
1164
+ const { atoms, registry, runtime } = yield* makeTestRuntime(
1165
+ client,
1166
+ undefined,
1167
+ false,
1168
+ {
1169
+ actionReply: (target, reply) => Effect.sync(() => replies.push({ target, reply })),
1170
+ list: (_target, value) => Effect.sync(() => listAnswers.push(value.entries)),
1171
+ },
1172
+ {
1173
+ load: (_environmentId, key) => Effect.sync(() => Option.fromUndefinedOr(saved.get(key))),
1174
+ save: (_environmentId, key, payload) => Effect.sync(() => void saved.set(key, payload)),
1175
+ },
1176
+ );
1177
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1178
+ const list = (input: PullRequestListInput) =>
1179
+ atoms.list({ environmentId: target.environmentId, input });
1180
+ const readers: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [
1181
+ atoms.detail(target),
1182
+ atoms.preview(target),
1183
+ createLinkedPullRequestSummaryAtomFamily(runtime, atoms.refreshes)(target),
1184
+ ];
1185
+ const all = list({ state: "all" });
1186
+ const openDrafts = list({ state: "open", filters: { draft: "only" } });
1187
+ const merged = list({ state: "merged" });
1188
+ for (const atom of [...readers, all, openDrafts, merged]) {
1189
+ registry.mount(atom);
1190
+ yield* Effect.promise(() => executeAtomQuery(registry, atom));
1191
+ }
1192
+ reads.length = 0;
1193
+
1194
+ const answer = yield* Effect.promise(() =>
1195
+ atoms.runAction.run(registry, { ...target, input: { ...target.input, action: "merge" } }),
1196
+ );
1197
+
1198
+ expect(answer).toMatchObject({ _tag: "Success", value: actionReply });
1199
+ for (const atom of readers) {
1200
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(atom)))).toMatchObject({
1201
+ state: "merged",
1202
+ isDraft: false,
1203
+ title: "Ship it",
1204
+ });
1205
+ }
1206
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(all))).entries).toMatchObject([
1207
+ // The row keeps its own read time: the reply does not carry its checks or labels.
1208
+ { state: "merged", isDraft: false, observedAt: 100 },
1209
+ ]);
1210
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(openDrafts))).entries).toEqual([]);
1211
+ expect(replies).toEqual([{ target, reply: actionReply }]);
1212
+ // A cold start paints the saved copy, so the patch must replace the saved answer.
1213
+ const summaryKey = queryPersistenceKey(
1214
+ "environment-data:pull-requests:linked-summary",
1215
+ actionReference,
1216
+ );
1217
+ expect(JSON.parse(saved.get(summaryKey) ?? "null")).toMatchObject({ state: "merged" });
1218
+ // Snapshot writers see the patched rows the way they see an answer.
1219
+ expect(listAnswers).toContainEqual([expect.objectContaining({ state: "merged" })]);
1220
+ // Only a read can place a row the listing did not hold.
1221
+ yield* AtomRegistry.getResult(registry, merged, { suspendOnWaiting: true });
1222
+ expect(reads).toEqual(["list:merged"]);
1223
+ }),
1224
+ ),
1225
+);
1226
+
1227
+it.effect("keeps an action's reply when a refresh started before the action answers late", () =>
1228
+ Effect.scoped(
1229
+ Effect.gen(function* () {
1230
+ let state: "open" | "merged" = "open";
1231
+ let reads = 0;
1232
+ const started = yield* Deferred.make<void>();
1233
+ const release = yield* Deferred.make<void>();
1234
+ const settled = yield* Deferred.make<void>();
1235
+ const client = actionReplyClient({
1236
+ [WS_METHODS.pullRequestsDetail]: () =>
1237
+ Effect.gen(function* () {
1238
+ reads++;
1239
+ const snapshot = { ...actionReference, state, isDraft: false, observedAt: 100 };
1240
+ if (reads === 2) {
1241
+ yield* Deferred.succeed(started, undefined);
1242
+ yield* Deferred.await(release).pipe(
1243
+ Effect.onExit(() => Deferred.succeed(settled, undefined)),
1244
+ );
1245
+ }
1246
+ return snapshot;
1247
+ }),
1248
+ [WS_METHODS.pullRequestsRunAction]: () =>
1249
+ Effect.sync(() => {
1250
+ state = "merged";
1251
+ return actionReply;
1252
+ }),
1253
+ });
1254
+ const { atoms, registry } = yield* makeTestRuntime(client);
1255
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1256
+ const detail = atoms.detail(target);
1257
+ registry.mount(detail);
1258
+ yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
1259
+ registry.refresh(detail);
1260
+ yield* Deferred.await(started);
1261
+
1262
+ yield* Effect.promise(() =>
1263
+ atoms.runAction.run(registry, {
1264
+ ...target,
1265
+ input: { ...actionReference, action: "merge" },
1266
+ }),
1267
+ );
1268
+ yield* Deferred.succeed(release, undefined);
1269
+ yield* Deferred.await(settled);
1270
+
1271
+ expect(
1272
+ (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).state,
1273
+ ).toBe("merged");
1274
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("merged");
1275
+ }),
1276
+ ),
1277
+);
1278
+
1279
+it.effect("keeps a list read the server's refresh started before the action replied", () =>
1280
+ Effect.scoped(
1281
+ Effect.gen(function* () {
1282
+ const refreshEvents = yield* PubSub.unbounded<number>();
1283
+ let state: "open" | "merged" = "open";
1284
+ let reads = 0;
1285
+ const actionInputs: unknown[] = [];
1286
+ const listWaiting = Latch.makeUnsafe();
1287
+ const release = yield* Deferred.make<void>();
1288
+ const client = actionReplyClient({
1289
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
1290
+ [WS_METHODS.pullRequestsList]: () =>
1291
+ Effect.gen(function* () {
1292
+ reads++;
1293
+ const entries = [
1294
+ { ...actionReference, state, isDraft: false, updatedAt: actionReply.updatedAt },
1295
+ ];
1296
+ if (reads === 2) yield* Deferred.await(release);
1297
+ return {
1298
+ entries,
1299
+ viewers: {},
1300
+ providers: [],
1301
+ errors: [],
1302
+ truncated: false,
1303
+ nextCursors: {},
1304
+ };
1305
+ }),
1306
+ [WS_METHODS.pullRequestsRunAction]: (input: unknown) =>
1307
+ Effect.gen(function* () {
1308
+ actionInputs.push(input);
1309
+ state = "merged";
1310
+ // The server announces its refresh before it replies.
1311
+ yield* PubSub.publish(refreshEvents, 1);
1312
+ yield* listWaiting.await;
1313
+ return actionReply;
1314
+ }),
1315
+ });
1316
+ const { atoms, registry } = yield* makeTestRuntime(client);
1317
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1318
+ const list = atoms.list({ environmentId: target.environmentId, input: { state: "all" } });
1319
+ const unmount = registry.mount(list);
1320
+ yield* Effect.addFinalizer(() => Effect.sync(unmount));
1321
+ yield* Effect.promise(() => executeAtomQuery(registry, list));
1322
+ const stop = registry.subscribe(list, (result) => {
1323
+ if (result.waiting) listWaiting.openUnsafe();
1324
+ });
1325
+ yield* Effect.addFinalizer(() => Effect.sync(stop));
1326
+
1327
+ yield* Effect.promise(() =>
1328
+ atoms.runAction.run(registry, {
1329
+ ...target,
1330
+ input: { ...actionReference, action: "merge" },
1331
+ }),
1332
+ );
1333
+ yield* Deferred.succeed(release, undefined);
1334
+
1335
+ expect(
1336
+ (yield* AtomRegistry.getResult(registry, list, { suspendOnWaiting: true })).entries,
1337
+ ).toMatchObject([{ state: "merged" }]);
1338
+ expect(reads).toBe(2);
1339
+ expect(actionInputs).toEqual([expect.objectContaining({ replyWithSummary: true })]);
1340
+ }),
1341
+ ),
1342
+);
1343
+
1344
+it.effect("restarts a list page read sent while the action was in flight", () =>
1345
+ Effect.scoped(
1346
+ Effect.gen(function* () {
1347
+ const refreshEvents = yield* PubSub.unbounded<number>();
1348
+ let state: "open" | "closed" = "open";
1349
+ let pageReads = 0;
1350
+ const actionSent = yield* Deferred.make<void>();
1351
+ const pageStarted = yield* Deferred.make<void>();
1352
+ const release = yield* Deferred.make<void>();
1353
+ const settled = yield* Deferred.make<void>();
1354
+ const listResult = (entries: ReadonlyArray<object>) => ({
1355
+ entries,
1356
+ viewers: {},
1357
+ providers: [],
1358
+ errors: [],
1359
+ truncated: false,
1360
+ nextCursors: {},
1361
+ });
1362
+ const client = actionReplyClient({
1363
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
1364
+ [WS_METHODS.pullRequestsList]: (input: PullRequestListInput) =>
1365
+ Effect.gen(function* () {
1366
+ const entries =
1367
+ state === "open"
1368
+ ? [{ ...actionReference, state, isDraft: false, updatedAt: "2026-10-27T09:00:00Z" }]
1369
+ : [];
1370
+ if (input.cursors !== undefined && ++pageReads === 2) {
1371
+ yield* Deferred.succeed(pageStarted, undefined);
1372
+ yield* Deferred.await(release).pipe(
1373
+ Effect.onExit(() => Deferred.succeed(settled, undefined)),
1374
+ );
1375
+ }
1376
+ return listResult(input.cursors === undefined ? [] : entries);
1377
+ }),
1378
+ [WS_METHODS.pullRequestsRunAction]: () =>
1379
+ Effect.gen(function* () {
1380
+ yield* Deferred.succeed(actionSent, undefined);
1381
+ yield* Deferred.await(pageStarted);
1382
+ state = "closed";
1383
+ yield* PubSub.publish(refreshEvents, 1);
1384
+ return { ...actionReply, state: "closed" };
1385
+ }),
1386
+ });
1387
+ const { atoms, registry } = yield* makeTestRuntime(client);
1388
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1389
+ const listInput = { state: "open" } as const;
1390
+ const head = atoms.list({ environmentId: target.environmentId, input: listInput });
1391
+ const page = atoms.list({
1392
+ environmentId: target.environmentId,
1393
+ input: { ...listInput, cursors: { "github.example.com": "page-2" } },
1394
+ });
1395
+ for (const atom of [head, page]) {
1396
+ const unmount = registry.mount(atom);
1397
+ yield* Effect.addFinalizer(() => Effect.sync(unmount));
1398
+ yield* Effect.promise(() => executeAtomQuery(registry, atom));
1399
+ }
1400
+
1401
+ const action = yield* Effect.promise(() =>
1402
+ atoms.runAction.run(registry, {
1403
+ ...target,
1404
+ input: { ...actionReference, action: "close" },
1405
+ }),
1406
+ ).pipe(Effect.forkScoped);
1407
+ yield* Deferred.await(actionSent);
1408
+ // Loading more rows re-reads a page while the close is on the wire.
1409
+ registry.refresh(page);
1410
+ yield* Fiber.join(action);
1411
+ yield* Deferred.succeed(release, undefined);
1412
+ yield* Deferred.await(settled);
1413
+
1414
+ expect(
1415
+ (yield* AtomRegistry.getResult(registry, page, { suspendOnWaiting: true })).entries,
1416
+ ).toEqual([]);
1417
+ }),
1418
+ ),
1419
+);
1420
+
1421
+it.effect("shows a reopen reply at once and re-reads the fields it lacks", () =>
1422
+ Effect.scoped(
1423
+ Effect.gen(function* () {
1424
+ let reads = 0;
1425
+ const release = yield* Deferred.make<void>();
1426
+ const client = actionReplyClient({
1427
+ [WS_METHODS.pullRequestsDetail]: () =>
1428
+ Effect.gen(function* () {
1429
+ reads++;
1430
+ if (reads === 1) return { ...actionReference, state: "closed", observedAt: 100 };
1431
+ yield* Deferred.await(release);
1432
+ return { ...actionReference, state: "open", observedAt: 300 };
1433
+ }),
1434
+ [WS_METHODS.pullRequestsRunAction]: () => Effect.succeed({ ...actionReply, state: "open" }),
1435
+ });
1436
+ const { atoms, registry } = yield* makeTestRuntime(client);
1437
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1438
+ const detail = atoms.detail(target);
1439
+ registry.mount(detail);
1440
+ yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
1441
+
1442
+ yield* Effect.promise(() =>
1443
+ atoms.runAction.run(registry, {
1444
+ ...target,
1445
+ input: { ...actionReference, action: "reopen" },
1446
+ }),
1447
+ );
1448
+
1449
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("open");
1450
+ expect(reads).toBe(2);
1451
+ yield* Deferred.succeed(release, undefined);
1452
+ expect(
1453
+ (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).observedAt,
1454
+ ).toBe(300);
1455
+ }),
1456
+ ),
1457
+);
1458
+
1459
+it.effect("keeps each reader's read time when a reply leaves its checks as they were", () =>
1460
+ Effect.scoped(
1461
+ Effect.gen(function* () {
1462
+ const shown = {
1463
+ ...actionReference,
1464
+ state: "open",
1465
+ isDraft: true,
1466
+ updatedAt: "2026-10-27T09:00:00Z",
1467
+ observedAt: 100,
1468
+ checks: [{ status: "success" }],
1469
+ checksState: "passing",
1470
+ };
1471
+ const client = actionReplyClient({
1472
+ [WS_METHODS.pullRequestsDetail]: () => Effect.succeed(shown),
1473
+ [WS_METHODS.pullRequestsSummary]: () => Effect.succeed(shown),
1474
+ [WS_METHODS.pullRequestsList]: () =>
1475
+ Effect.succeed({
1476
+ entries: [shown],
1477
+ viewers: {},
1478
+ providers: [],
1479
+ errors: [],
1480
+ truncated: false,
1481
+ nextCursors: {},
1482
+ }),
1483
+ [WS_METHODS.pullRequestsRunAction]: () =>
1484
+ Effect.succeed({ ...actionReply, state: "open", observedAt: 300 }),
1485
+ });
1486
+ const answeredAt: Array<number | undefined> = [];
1487
+ const { atoms, registry, runtime } = yield* makeTestRuntime(client, undefined, false, {
1488
+ detail: (_target, value) => Effect.sync(() => answeredAt.push(value.observedAt)),
1489
+ });
1490
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1491
+ const readers: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [
1492
+ atoms.detail(target),
1493
+ createLinkedPullRequestSummaryAtomFamily(runtime, atoms.refreshes)(target),
1494
+ ];
1495
+ const list = atoms.list({ environmentId: target.environmentId, input: { state: "all" } });
1496
+ for (const atom of [...readers, list]) {
1497
+ registry.mount(atom);
1498
+ yield* Effect.promise(() => executeAtomQuery(registry, atom));
1499
+ }
1500
+
1501
+ yield* Effect.promise(() =>
1502
+ atoms.runAction.run(registry, {
1503
+ ...target,
1504
+ input: { ...actionReference, action: "ready" },
1505
+ }),
1506
+ );
1507
+
1508
+ // Checks read at 100 must not pass for a read at 300 against a newer checks read.
1509
+ for (const atom of readers) {
1510
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(atom)))).toMatchObject({
1511
+ isDraft: false,
1512
+ observedAt: 100,
1513
+ });
1514
+ }
1515
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(list))).entries).toMatchObject([
1516
+ { isDraft: false, checksState: "passing", observedAt: 100 },
1517
+ ]);
1518
+ expect(answeredAt).toEqual([100, 100]);
1519
+ }),
1520
+ ),
1521
+);
1522
+
1523
+it.effect("re-reads an unstamped preview rather than order a reply against it", () =>
1524
+ Effect.scoped(
1525
+ Effect.gen(function* () {
1526
+ let reads = 0;
1527
+ const client = actionReplyClient({
1528
+ // Previews from servers before action replies carry neither update nor read time.
1529
+ [WS_METHODS.pullRequestsPreview]: () =>
1530
+ Effect.sync(() => {
1531
+ reads++;
1532
+ return {
1533
+ ...actionReference,
1534
+ title: "Reopened elsewhere",
1535
+ url: actionReply.url,
1536
+ author: null,
1537
+ state: "open",
1538
+ isDraft: false,
1539
+ createdAt: "2026-10-27T08:00:00Z",
1540
+ };
1541
+ }),
1542
+ [WS_METHODS.pullRequestsRunAction]: () =>
1543
+ Effect.succeed({ ...actionReply, state: "closed" }),
1544
+ });
1545
+ const { atoms, registry } = yield* makeTestRuntime(client);
1546
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1547
+ const preview = atoms.preview(target);
1548
+ registry.mount(preview);
1549
+ yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true });
1550
+
1551
+ yield* Effect.promise(() =>
1552
+ atoms.runAction.run(registry, {
1553
+ ...target,
1554
+ input: { ...actionReference, action: "close" },
1555
+ }),
1556
+ );
1557
+
1558
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(preview))).state).toBe("open");
1559
+ expect(
1560
+ (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).state,
1561
+ ).toBe("open");
1562
+ expect(reads).toBe(2);
1563
+ }),
1564
+ ),
1565
+);
1566
+
1567
+it.effect("leaves a loaded list page alone when the reply concerns none of its rows", () =>
1568
+ Effect.scoped(
1569
+ Effect.gen(function* () {
1570
+ let pageReads = 0;
1571
+ const client = actionReplyClient({
1572
+ [WS_METHODS.pullRequestsList]: () =>
1573
+ Effect.sync(() => {
1574
+ pageReads++;
1575
+ return {
1576
+ entries: [
1577
+ {
1578
+ ...actionReference,
1579
+ number: 2,
1580
+ state: "open",
1581
+ isDraft: false,
1582
+ updatedAt: "2026-10-27T09:00:00Z",
1583
+ },
1584
+ ],
1585
+ viewers: {},
1586
+ providers: [],
1587
+ errors: [],
1588
+ truncated: false,
1589
+ nextCursors: {},
1590
+ };
1591
+ }),
1592
+ [WS_METHODS.pullRequestsRunAction]: () => Effect.succeed({ ...actionReply, state: "open" }),
1593
+ });
1594
+ const { atoms, registry } = yield* makeTestRuntime(client);
1595
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1596
+ const page = atoms.list({
1597
+ environmentId: target.environmentId,
1598
+ input: { state: "open", cursors: { "github.example.com": "page-2" } },
1599
+ });
1600
+ const unmount = registry.mount(page);
1601
+ yield* Effect.addFinalizer(() => Effect.sync(unmount));
1602
+ yield* Effect.promise(() => executeAtomQuery(registry, page));
1603
+
1604
+ yield* Effect.promise(() =>
1605
+ atoms.runAction.run(registry, {
1606
+ ...target,
1607
+ input: { ...actionReference, action: "ready" },
1608
+ }),
1609
+ );
1610
+
1611
+ yield* AtomRegistry.getResult(registry, page, { suspendOnWaiting: true });
1612
+ expect(pageReads).toBe(1);
1613
+ }),
1614
+ ),
1615
+);
1616
+
1617
+it.effect("keeps the server's post-commit read when a reopen reply lacks fields", () =>
1618
+ Effect.scoped(
1619
+ Effect.gen(function* () {
1620
+ const refreshEvents = yield* PubSub.unbounded<number>();
1621
+ let reads = 0;
1622
+ const detailWaiting = Latch.makeUnsafe();
1623
+ const release = yield* Deferred.make<void>();
1624
+ const client = actionReplyClient({
1625
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
1626
+ [WS_METHODS.pullRequestsDetail]: () =>
1627
+ Effect.gen(function* () {
1628
+ reads++;
1629
+ if (reads === 1) return { ...actionReference, state: "closed", observedAt: 100 };
1630
+ yield* Deferred.await(release);
1631
+ return { ...actionReference, state: "open", observedAt: 300 };
1632
+ }),
1633
+ [WS_METHODS.pullRequestsRunAction]: () =>
1634
+ Effect.gen(function* () {
1635
+ // The server announces its refresh before it replies.
1636
+ yield* PubSub.publish(refreshEvents, 1);
1637
+ yield* detailWaiting.await;
1638
+ return { ...actionReply, state: "open" };
1639
+ }),
1640
+ });
1641
+ const { atoms, registry } = yield* makeTestRuntime(client);
1642
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1643
+ const detail = atoms.detail(target);
1644
+ const unmount = registry.mount(detail);
1645
+ yield* Effect.addFinalizer(() => Effect.sync(unmount));
1646
+ yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
1647
+ const stop = registry.subscribe(detail, (result) => {
1648
+ if (result.waiting) detailWaiting.openUnsafe();
1649
+ });
1650
+ yield* Effect.addFinalizer(() => Effect.sync(stop));
1651
+
1652
+ yield* Effect.promise(() =>
1653
+ atoms.runAction.run(registry, {
1654
+ ...target,
1655
+ input: { ...actionReference, action: "reopen" },
1656
+ }),
1657
+ );
1658
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("open");
1659
+ yield* Deferred.succeed(release, undefined);
1660
+
1661
+ expect(
1662
+ (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).observedAt,
1663
+ ).toBe(300);
1664
+ expect(reads).toBe(2);
1665
+ }),
1666
+ ),
1667
+);
1668
+
1669
+it.effect.each([
1670
+ ["a newer update", "open", "2026-10-27T10:00:01Z", 100, "open"],
1671
+ ["a merge", "merged", "2026-10-27T09:00:00Z", 100, "open"],
1672
+] as const)(
1673
+ "keeps %s when an older or reverting action reply arrives",
1674
+ ([, shownState, updatedAt, observedAt, replyState]) =>
1675
+ Effect.scoped(
1676
+ Effect.gen(function* () {
1677
+ const shown = {
1678
+ ...actionReference,
1679
+ state: shownState,
1680
+ isDraft: true,
1681
+ updatedAt,
1682
+ observedAt,
1683
+ };
1684
+ const client = actionReplyClient({
1685
+ [WS_METHODS.pullRequestsDetail]: () => Effect.succeed(shown),
1686
+ [WS_METHODS.pullRequestsPreview]: () => Effect.succeed(shown),
1687
+ [WS_METHODS.pullRequestsRunAction]: () =>
1688
+ Effect.succeed({ ...actionReply, state: replyState }),
1689
+ });
1690
+ const { atoms, registry } = yield* makeTestRuntime(client);
1691
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1692
+ const readers = [atoms.detail(target), atoms.preview(target), atoms.previewCard(target)];
1693
+ for (const reader of readers) {
1694
+ registry.mount(reader);
1695
+ yield* AtomRegistry.getResult(registry, reader, { suspendOnWaiting: true });
1696
+ }
1697
+
1698
+ yield* Effect.promise(() =>
1699
+ atoms.runAction.run(registry, {
1700
+ ...target,
1701
+ input: { ...actionReference, action: "ready" },
1702
+ }),
1703
+ );
1704
+ for (const reader of readers) {
1705
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(reader)))).toMatchObject({
1706
+ state: shownState,
1707
+ isDraft: true,
1708
+ });
1709
+ }
1710
+ }),
1711
+ ),
1712
+);
1713
+
1714
it.effect("keeps hover previews fresh after edits and turns", () =>
1715
Effect.scoped(
1716
Effect.gen(function* () {
packages/client-runtime/src/state/pullRequests.ts
+427
-79
@@ -18,6 +18,7 @@ import {
18
type PullRequestListStatsResult,
19
type PullRequestDetail,
20
type PullRequestDiffInput,
21
+ type PullRequestListEntry,
22
type PullRequestRef,
23
type PullRequestMergeMethod,
24
PullRequestOperationError,
@@ -27,7 +28,7 @@ import {
28
import * as Effect from "effect/Effect";
29
import * as Schema from "effect/Schema";
30
import { persistPullRequestStats } from "./pullRequestStatsPersistence.ts";
30
-import { persistQuery } from "./queryPersistence.ts";
31
+import { persistQuery, type QueryPersistence } from "./queryPersistence.ts";
32
import * as Option from "effect/Option";
33
import * as SubscriptionRef from "effect/SubscriptionRef";
34
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
@@ -38,12 +39,16 @@ import {
39
createEnvironmentRpcQueryAtomFamily,
40
createEnvironmentRpcSubscriptionAtomFamily,
41
createEnvironmentQueryAtomFamily,
42
+ queryPersistenceKey,
43
type QueryAnswerHandler,
44
} from "./runtime.ts";
45
import { createPullRequestRouter } from "./pullRequestRouting.ts";
46
import * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts";
47
import type { EnvironmentRegistry } from "../connection/registry.ts";
48
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
49
+import { isStalePullRequestReply } from "../pullRequestReply.ts";
50
+import { parsePullRequestQuery } from "../pullRequestQuery.ts";
51
+import { reuseUnchanged } from "./serverConfigProjection.ts";
52
53
export {
54
type PullRequestDiffLoadError,
@@ -79,6 +84,26 @@ function normalizePullRequestQuery<A>(
84
});
85
}
86
87
+function writableQuery<A, E>(
88
+ source: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
89
+ idleTtlMs = 5 * 60_000,
90
+) {
91
+ return Atom.writable(
92
+ (get) => {
93
+ const result = get(source);
94
+ if (result._tag === "Success" && !result.waiting) return result;
95
+ const previous = get.self<AsyncResult.AsyncResult<A, E>>();
96
+ const value = Option.flatMap(previous, AsyncResult.value);
97
+ if (Option.isNone(value)) return result;
98
+ return result._tag === "Failure"
99
+ ? AsyncResult.failureWithPrevious(result.cause, { previous, waiting: result.waiting })
100
+ : AsyncResult.success<A, E>(value.value, result);
101
+ },
102
+ (context, value: AsyncResult.AsyncResult<A, E>) => context.setSelf(value),
103
+ (refresh) => refresh(source),
104
+ ).pipe(Atom.setIdleTTL(idleTtlMs));
105
+}
106
+
107
function writableQueryFamily<A, E>(
108
family: (target: {
109
readonly environmentId: EnvironmentId;
@@ -86,20 +111,7 @@ function writableQueryFamily<A, E>(
111
}) => Atom.Atom<AsyncResult.AsyncResult<A, E>>,
112
) {
113
const writable = Atom.family((source: Atom.Atom<AsyncResult.AsyncResult<A, E>>) =>
89
- Atom.writable(
90
- (get) => {
91
- const result = get(source);
92
- if (result._tag === "Success" && !result.waiting) return result;
93
- const previous = get.self<AsyncResult.AsyncResult<A, E>>();
94
- const value = Option.flatMap(previous, AsyncResult.value);
95
- if (Option.isNone(value)) return result;
96
- return result._tag === "Failure"
97
- ? AsyncResult.failureWithPrevious(result.cause, { previous, waiting: result.waiting })
98
- : AsyncResult.success<A, E>(value.value, result);
99
- },
100
- (context, value: AsyncResult.AsyncResult<A, E>) => context.setSelf(value),
101
- (refresh) => refresh(source),
102
- ).pipe(Atom.setIdleTTL(5 * 60_000)),
114
+ writableQuery(source),
115
);
116
return normalizePullRequestQuery((target) => writable(family(target)));
117
}
@@ -115,6 +127,196 @@ function updateCached<A, E>(
127
registry.update(atom, AsyncResult.map(update));
128
}
129
130
+interface ActionReplyPatch {
131
+ /** The read this reader is waiting on, if any. */
132
+ readonly pendingRead: (registry: AtomRegistry.AtomRegistry) => object | undefined;
133
+ readonly apply: (
134
+ registry: AtomRegistry.AtomRegistry,
135
+ environmentId: EnvironmentId,
136
+ reference: PullRequestRef,
137
+ reply: PullRequestSummary | undefined,
138
+ readsBeforeSend: ReadonlySet<object>,
139
+ ) => Effect.Effect<void>;
140
+}
141
+
142
+// Module-wide so readers built by separate factories, such as linked summaries, are patched too.
143
+const actionReplyPatches = new WeakMap<object, ActionReplyPatch>();
144
+
145
+function samePullRequest(reader: PullRequestRef, acted: PullRequestRef) {
146
+ return (
147
+ reader.projectId === acted.projectId &&
148
+ // A missing host is not a wildcard: one project can reach the same repository on two hosts.
149
+ reader.host?.toLowerCase() === acted.host?.toLowerCase() &&
150
+ reader.repository.toLowerCase() === acted.repository.toLowerCase() &&
151
+ reader.number === acted.number &&
152
+ reader.expectedAccountId === acted.expectedAccountId
153
+ );
154
+}
155
+
156
+function pickDefined<T extends object, K extends keyof T>(
157
+ source: T,
158
+ keys: ReadonlyArray<K>,
159
+): { [P in K]?: Exclude<T[P], undefined> } {
160
+ const picked: { [P in K]?: T[P] } = {};
161
+ for (const key of keys) if (source[key] !== undefined) picked[key] = source[key];
162
+ return picked as { [P in K]?: Exclude<T[P], undefined> };
163
+}
164
+
165
+function listAccepts(input: PullRequestListInput, state: string, isDraft: boolean | undefined) {
166
+ const draft = parsePullRequestQuery(input.query ?? "").filters.draft ?? input.filters?.draft;
167
+ return (
168
+ (input.state === "all" || input.state === state) &&
169
+ (draft !== "only" || isDraft !== false) &&
170
+ (draft !== "hide" || isDraft !== true)
171
+ );
172
+}
173
+
174
+/**
175
+ * Listing rows with an action's reply applied, the same array when it changes none, and `refresh`
176
+ * when the reply adds the pull request to a listing, which only a read can place.
177
+ */
178
+export function patchPullRequestListEntries<Entry extends PullRequestListEntry>(
179
+ input: PullRequestListInput,
180
+ entries: ReadonlyArray<Entry>,
181
+ reference: PullRequestRef,
182
+ reply: PullRequestSummary,
183
+): ReadonlyArray<Entry> | "refresh" {
184
+ let found = false;
185
+ let changed = false;
186
+ const patched = entries.flatMap((entry): Entry[] => {
187
+ if (!samePullRequest(entry, reference)) return [entry];
188
+ found = true;
189
+ if (isStalePullRequestReply(entry, reply)) return [entry];
190
+ changed = true;
191
+ const next = {
192
+ ...entry,
193
+ ...pickDefined(reply, [
194
+ "title",
195
+ "url",
196
+ "author",
197
+ "headBranch",
198
+ "baseBranch",
199
+ "state",
200
+ "isDraft",
201
+ "mergeability",
202
+ "updatedAt",
203
+ ]),
204
+ };
205
+ return listAccepts(input, next.state, next.isDraft) ? [next] : [];
206
+ });
207
+ if (!found) {
208
+ return input.cursors === undefined && listAccepts(input, reply.state, reply.isDraft)
209
+ ? "refresh"
210
+ : entries;
211
+ }
212
+ return changed
213
+ ? patched.sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt))
214
+ : entries;
215
+}
216
+
217
+function patchListWithReply(
218
+ input: PullRequestListInput,
219
+ value: PullRequestListResult,
220
+ reference: PullRequestRef,
221
+ reply: PullRequestSummary,
222
+): PullRequestListResult | "refresh" {
223
+ const entries = patchPullRequestListEntries(input, value.entries, reference, reply);
224
+ if (entries === "refresh") return entries;
225
+ return entries === value.entries ? value : { ...value, entries };
226
+}
227
+
228
+/**
229
+ * The query atom for one target, writable so an action's reply can replace what it shows. The
230
+ * patch is saved and announced the way an answer would be, so cold starts and snapshots see it.
231
+ */
232
+function actionPatchedQuery<Input, A, E>(
233
+ source: (target: {
234
+ readonly environmentId: EnvironmentId;
235
+ readonly input: Input;
236
+ }) => Atom.Atom<AsyncResult.AsyncResult<A, E>>,
237
+ options: {
238
+ readonly label: string;
239
+ readonly persistence?: QueryPersistence<A> | undefined;
240
+ readonly onAnswer?: QueryAnswerHandler<Input, A> | undefined;
241
+ readonly idleTtlMs?: number | undefined;
242
+ readonly concerns: (input: Input, reference: PullRequestRef) => boolean;
243
+ readonly patch: (
244
+ input: Input,
245
+ value: A,
246
+ reference: PullRequestRef,
247
+ reply: PullRequestSummary,
248
+ ) => A | "refresh";
249
+ /** Fields the reply lacks also changed, so the patched value shows while a read fetches them. */
250
+ readonly rereads?: (value: A, reply: PullRequestSummary) => boolean;
251
+ /** Re-read when the host's reply did not carry the pull request. */
252
+ readonly rereadWithoutReply?: boolean;
253
+ /** False for reads the refresh stream does not restart; defaults to true. */
254
+ readonly refreshedByServer?: (input: Input) => boolean;
255
+ },
256
+) {
257
+ const writable = Atom.family((atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>) =>
258
+ writableQuery(atom, options.idleTtlMs),
259
+ );
260
+ return (target: { readonly environmentId: EnvironmentId; readonly input: Input }) => {
261
+ const query = source(target);
262
+ const atom = writable(query);
263
+ if (actionReplyPatches.has(atom)) return atom;
264
+ const pendingRead = (registry: AtomRegistry.AtomRegistry) => {
265
+ const result = Option.getOrUndefined(
266
+ registry.getNodes().get(query)?.valueOption() ?? Option.none(),
267
+ ) as AsyncResult.AsyncResult<A, E> | undefined;
268
+ return result?.waiting === true ? result : undefined;
269
+ };
270
+ actionReplyPatches.set(atom, {
271
+ pendingRead,
272
+ apply: Effect.fnUntraced(
273
+ function* (registry, environmentId, reference, reply, readsBeforeSend) {
274
+ if (environmentId !== target.environmentId || !options.concerns(target.input, reference))
275
+ return;
276
+ const pending = pendingRead(registry);
277
+ // A read sent before the action may miss its result, and so may one sent before the host
278
+ // committed. The server's post-commit refresh restarts that one, but not a read outside
279
+ // its stream, whose re-read need not even show as waiting, so a mounted one the reply
280
+ // changes restarts here.
281
+ const unrefreshed = options.refreshedByServer?.(target.input) === false;
282
+ const freshRead = pending !== undefined && !unrefreshed && !readsBeforeSend.has(pending);
283
+ const reread = () => (freshRead ? undefined : registry.refresh(atom));
284
+ if (reply === undefined) {
285
+ return options.rereadWithoutReply === true ? reread() : undefined;
286
+ }
287
+ const shown = Option.flatMap(
288
+ registry.getNodes().get(atom)?.valueOption() ?? Option.none(),
289
+ (current: AsyncResult.AsyncResult<A, E>) => AsyncResult.value(current),
290
+ );
291
+ if (Option.isNone(shown)) return reread();
292
+ const patched = options.patch(target.input, shown.value, reference, reply);
293
+ if (patched === "refresh") return reread();
294
+ const lacking = options.rereads?.(shown.value, reply) === true;
295
+ const next = reuseUnchanged(shown.value, patched);
296
+ if (next === shown.value)
297
+ return lacking || (unrefreshed && pending !== undefined) ? reread() : undefined;
298
+ yield* options.onAnswer?.(target, next, registry) ?? Effect.void;
299
+ const mounted = (registry.getNodes().get(atom)?.listeners.size ?? 0) > 0;
300
+ if (!freshRead && (pending !== undefined || lacking || (unrefreshed && mounted)))
301
+ registry.refresh(atom);
302
+ registry.update(
303
+ atom,
304
+ AsyncResult.map(() => next),
305
+ );
306
+ if (options.persistence !== undefined) {
307
+ yield* options.persistence.save(
308
+ environmentId,
309
+ queryPersistenceKey(options.label, target.input),
310
+ next,
311
+ );
312
+ }
313
+ },
314
+ ),
315
+ });
316
+ return atom;
317
+ };
318
+}
319
+
320
function makePullRequestRefreshAtomFamily<R, E>(
321
runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
322
) {
@@ -145,18 +347,41 @@ export function createLinkedPullRequestSummaryAtomFamily<R, E>(
347
onAnswer?: QueryAnswerHandler<PullRequestRef, PullRequestSummary>,
348
) {
349
const routedRequest = createPullRequestRouter();
148
- return createEnvironmentRpcQueryAtomFamily(runtime, {
149
- label: "environment-data:pull-requests:linked-summary",
150
- persistence: persistQuery(PullRequestSummary),
151
- tag: WS_METHODS.pullRequestsSummary,
152
- execute: (input) => routedRequest(WS_METHODS.pullRequestsSummary, input),
153
- staleTimeMs: 60_000,
154
- refreshIntervalMs: 60_000,
155
- idleTtlMs: LINKED_PULL_REQUEST_IDLE_TTL_MS,
156
- refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
157
- isFinal: (summary) => summary.state === "merged",
158
- ...(onAnswer === undefined ? {} : { onAnswer }),
159
- });
350
+ const label = "environment-data:pull-requests:linked-summary";
351
+ const persistence = persistQuery(PullRequestSummary);
352
+ return actionPatchedQuery(
353
+ createEnvironmentRpcQueryAtomFamily(runtime, {
354
+ label,
355
+ persistence,
356
+ tag: WS_METHODS.pullRequestsSummary,
357
+ execute: (input) => routedRequest(WS_METHODS.pullRequestsSummary, input),
358
+ staleTimeMs: 60_000,
359
+ refreshIntervalMs: 60_000,
360
+ idleTtlMs: LINKED_PULL_REQUEST_IDLE_TTL_MS,
361
+ refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
362
+ isFinal: (summary) => summary.state === "merged",
363
+ ...(onAnswer === undefined ? {} : { onAnswer }),
364
+ }),
365
+ {
366
+ label,
367
+ persistence,
368
+ onAnswer,
369
+ idleTtlMs: LINKED_PULL_REQUEST_IDLE_TTL_MS,
370
+ concerns: samePullRequest,
371
+ // A routed action replies with the destination's project and repository names.
372
+ patch: (_input, value, _reference, reply) =>
373
+ isStalePullRequestReply(value, reply)
374
+ ? value
375
+ : {
376
+ ...value,
377
+ ...reply,
378
+ projectId: value.projectId,
379
+ repository: value.repository,
380
+ number: value.number,
381
+ ...(value.observedAt === undefined ? {} : { observedAt: value.observedAt }),
382
+ },
383
+ },
384
+ );
385
}
386
387
/** Lets a client record what each answer says where it lands, rather than watching the data. */
@@ -166,6 +391,8 @@ export interface PullRequestAnswerHandlers {
391
readonly detail?: QueryAnswerHandler<PullRequestRef, PullRequestDetail>;
392
readonly checks?: QueryAnswerHandler<PullRequestRef, PullRequestChecks | null>;
393
readonly reviewGuide?: QueryAnswerHandler<PullRequestRef, PullRequestReviewGuideResult>;
394
+ /** Once per action reply, after the loaded readers show it; unscoped references only. */
395
+ readonly actionReply?: QueryAnswerHandler<PullRequestRef, PullRequestSummary>;
396
}
397
398
export function createPullRequestStackAtomFamily<R, E>(
@@ -230,23 +457,66 @@ export function createPullRequestEnvironmentAtoms<R, E>(
457
const detailAnswers = normalizePullRequestQuery((target) =>
458
detailAnswerAtoms(JSON.stringify(target)),
459
);
233
- const detail = writableQueryFamily(
234
- createEnvironmentRpcQueryAtomFamily(runtime, {
235
- label: "environment-data:pull-requests:detail",
236
- persistence: persistQuery(PullRequestDetailSchema),
237
- tag: WS_METHODS.pullRequestsDetail,
238
- execute: (input) => routedRequest(WS_METHODS.pullRequestsDetail, input),
239
- staleTimeMs: 60_000,
240
- refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
241
- onAnswer: (target, value, registry) =>
242
- Effect.sync(() => {
243
- // Cache reads bypass onAnswer, and server freshness stays separate from local readbacks.
244
- registry.update(detailAnswers(target), (previous) => ({
245
- value,
246
- version: (previous?.version ?? 0) + 1,
247
- }));
248
- }).pipe(Effect.andThen(() => onAnswer.detail?.(target, value, registry) ?? Effect.void)),
249
- }),
460
+ const detailLabel = "environment-data:pull-requests:detail";
461
+ const detailPersistence = persistQuery(PullRequestDetailSchema);
462
+ const detail = normalizePullRequestQuery(
463
+ actionPatchedQuery(
464
+ createEnvironmentRpcQueryAtomFamily(runtime, {
465
+ label: detailLabel,
466
+ persistence: detailPersistence,
467
+ tag: WS_METHODS.pullRequestsDetail,
468
+ execute: (input) => routedRequest(WS_METHODS.pullRequestsDetail, input),
469
+ staleTimeMs: 60_000,
470
+ refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
471
+ onAnswer: (target, value, registry) =>
472
+ Effect.sync(() => {
473
+ // Cache reads bypass onAnswer, and server freshness stays separate from local readbacks.
474
+ registry.update(detailAnswers(target), (previous) => ({
475
+ value,
476
+ version: (previous?.version ?? 0) + 1,
477
+ }));
478
+ }).pipe(Effect.andThen(() => onAnswer.detail?.(target, value, registry) ?? Effect.void)),
479
+ }),
480
+ {
481
+ label: detailLabel,
482
+ persistence: detailPersistence,
483
+ onAnswer: onAnswer.detail,
484
+ concerns: samePullRequest,
485
+ rereadWithoutReply: true,
486
+ // Reopening or a new head changes branch data and permissions the reply lacks.
487
+ rereads: (value, reply) =>
488
+ !isStalePullRequestReply(value, reply) &&
489
+ ((value.state === "closed" && reply.state === "open") ||
490
+ (reply.headSha !== undefined && reply.headSha !== value.headSha)),
491
+ patch: (_input, value, _reference, reply) => {
492
+ if (isStalePullRequestReply(value, reply)) return value;
493
+ const patched = {
494
+ ...value,
495
+ ...pickDefined(reply, [
496
+ "title",
497
+ "url",
498
+ "author",
499
+ "state",
500
+ "isDraft",
501
+ "mergeability",
502
+ "additions",
503
+ "deletions",
504
+ "changedFiles",
505
+ "headBranch",
506
+ "baseBranch",
507
+ "updatedAt",
508
+ "mergedAt",
509
+ "closedAt",
510
+ "autoMergeEnabled",
511
+ "autoMergeMethod",
512
+ ]),
513
+ };
514
+ if (reply.autoMergeEnabled !== false) return patched;
515
+ const { autoMergeMethod: _disarmed, ...withoutAutoMerge } = patched;
516
+ return withoutAutoMerge;
517
+ },
518
+ },
519
+ ),
520
);
521
const detailReadVersions = Atom.family((source: ReturnType<typeof detail>) =>
522
Atom.family((answer: ReturnType<typeof detailAnswers>) =>
@@ -262,28 +532,48 @@ export function createPullRequestEnvironmentAtoms<R, E>(
532
const detailReadVersion = normalizePullRequestQuery((target) =>
533
detailReadVersions(detail(target))(detailAnswers(target)),
534
);
265
- const preview = writableQueryFamily(
266
- createEnvironmentRpcQueryAtomFamily(runtime, {
267
- label: "environment-data:pull-requests:preview",
268
- persistence: persistQuery(PullRequestPreview),
269
- tag: WS_METHODS.pullRequestsPreview,
270
- execute: (input) => routedRequest(WS_METHODS.pullRequestsPreview, input),
271
- staleTimeMs: 60_000,
272
- refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
273
- }),
274
- );
535
+ const previewPersistence = persistQuery(PullRequestPreview);
536
+ const previewQuery = (label: string) =>
537
+ normalizePullRequestQuery(
538
+ actionPatchedQuery(
539
+ createEnvironmentRpcQueryAtomFamily(runtime, {
540
+ label,
541
+ persistence: previewPersistence,
542
+ tag: WS_METHODS.pullRequestsPreview,
543
+ execute: (input) => routedRequest(WS_METHODS.pullRequestsPreview, input),
544
+ staleTimeMs: 60_000,
545
+ refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
546
+ }),
547
+ {
548
+ label,
549
+ persistence: previewPersistence,
550
+ concerns: samePullRequest,
551
+ rereadWithoutReply: true,
552
+ // Servers before action replies send unstamped previews, which only a read can order.
553
+ patch: (_input, value, _reference, reply) =>
554
+ value.updatedAt === undefined && value.observedAt === undefined
555
+ ? "refresh"
556
+ : isStalePullRequestReply(value, reply)
557
+ ? value
558
+ : {
559
+ ...value,
560
+ ...pickDefined(reply, [
561
+ "title",
562
+ "url",
563
+ "author",
564
+ "state",
565
+ "isDraft",
566
+ "updatedAt",
567
+ "observedAt",
568
+ ]),
569
+ },
570
+ },
571
+ ),
572
+ );
573
+ const preview = previewQuery("environment-data:pull-requests:preview");
574
// Hover cards read their own atoms, so a pending or failed hover read never decides where a
575
// click on the same link goes.
277
- const previewCard = writableQueryFamily(
278
- createEnvironmentRpcQueryAtomFamily(runtime, {
279
- label: "environment-data:pull-requests:preview-card",
280
- persistence: persistQuery(PullRequestPreview),
281
- tag: WS_METHODS.pullRequestsPreview,
282
- execute: (input) => routedRequest(WS_METHODS.pullRequestsPreview, input),
283
- staleTimeMs: 60_000,
284
- refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
285
- }),
286
- );
576
+ const previewCard = previewQuery("environment-data:pull-requests:preview-card");
577
const labelCandidates = writableQueryFamily(
578
createEnvironmentRpcQueryAtomFamily(runtime, {
579
label: "environment-data:pull-requests:label-candidates",
@@ -364,8 +654,36 @@ export function createPullRequestEnvironmentAtoms<R, E>(
654
});
655
preparedInput = { ...actionInput, mergeMethod };
656
}
367
- return yield* routedRequest(WS_METHODS.pullRequestsRunAction, preparedInput);
657
+ return yield* routedRequest(WS_METHODS.pullRequestsRunAction, {
658
+ ...preparedInput,
659
+ replyWithSummary: true,
660
+ });
661
});
662
+ const actionReplyReaders = (registry: AtomRegistry.AtomRegistry) =>
663
+ Array.from(registry.getNodes().keys()).flatMap((atom) => {
664
+ const patch = typeof atom === "string" ? undefined : actionReplyPatches.get(atom);
665
+ return patch === undefined ? [] : [patch];
666
+ });
667
+ const readsInFlight = (registry: AtomRegistry.AtomRegistry): ReadonlySet<object> =>
668
+ new Set(actionReplyReaders(registry).flatMap((reader) => reader.pendingRead(registry) ?? []));
669
+ const applyActionReply = Effect.fn("PullRequests.applyActionReply")(function* (
670
+ registry: AtomRegistry.AtomRegistry,
671
+ environmentId: EnvironmentId,
672
+ reference: PullRequestRef,
673
+ reply: PullRequestSummary | undefined,
674
+ readsBeforeSend: ReadonlySet<object>,
675
+ ) {
676
+ for (const reader of actionReplyReaders(registry)) {
677
+ yield* reader.apply(registry, environmentId, reference, reply, readsBeforeSend);
678
+ }
679
+ if (reply !== undefined && reference.expectedAccountId === undefined) {
680
+ yield* (
681
+ onAnswer.actionReply?.({ environmentId, input: reference }, reply, registry) ?? Effect.void
682
+ );
683
+ }
684
+ });
685
+ const listLabel = "environment-data:pull-requests:list";
686
+ const listPersistence = persistQuery(PullRequestListResult);
687
688
return {
689
refreshes,
@@ -385,15 +703,32 @@ export function createPullRequestEnvironmentAtoms<R, E>(
703
staleTimeMs: 0,
704
idleTtlMs: 0,
705
}),
388
- list: createEnvironmentRpcQueryAtomFamily(runtime, {
389
- label: "environment-data:pull-requests:list",
390
- persistence: persistQuery(PullRequestListResult),
391
- tag: WS_METHODS.pullRequestsList,
392
- staleTimeMs: 30_000,
393
- refreshTrigger: ({ environmentId, input }) =>
394
- input.cursors === undefined ? refreshes({ environmentId, input: {} }) : undefined,
395
- ...(onAnswer.list === undefined ? {} : { onAnswer: onAnswer.list }),
396
- }),
706
+ list: actionPatchedQuery(
707
+ createEnvironmentRpcQueryAtomFamily(runtime, {
708
+ label: listLabel,
709
+ persistence: listPersistence,
710
+ tag: WS_METHODS.pullRequestsList,
711
+ staleTimeMs: 30_000,
712
+ refreshTrigger: ({ environmentId, input }) =>
713
+ input.cursors === undefined ? refreshes({ environmentId, input: {} }) : undefined,
714
+ ...(onAnswer.list === undefined ? {} : { onAnswer: onAnswer.list }),
715
+ }),
716
+ {
717
+ label: listLabel,
718
+ persistence: listPersistence,
719
+ onAnswer: onAnswer.list,
720
+ // Rows carry no account scope, so a reply read through another account leaves them alone.
721
+ concerns: (input, reference) =>
722
+ reference.expectedAccountId === undefined &&
723
+ (input.projectId === undefined || input.projectId === reference.projectId) &&
724
+ (input.projectIds === undefined || input.projectIds.includes(reference.projectId)) &&
725
+ (input.host === undefined ||
726
+ reference.host === undefined ||
727
+ input.host.toLowerCase() === reference.host.toLowerCase()),
728
+ refreshedByServer: (input) => input.cursors === undefined,
729
+ patch: patchListWithReply,
730
+ },
731
+ ),
732
/**
733
* Its own query because the listing is quicker without them — measured over twelve
734
* repositories, ~4.0s against ~7.1s — so the rows arrive first and their stats a moment
@@ -502,11 +837,24 @@ export function createPullRequestEnvironmentAtoms<R, E>(
837
// Preparation belongs to the write's lane. Refreshable queries would restart it after
838
// every preceding action, and preparing outside the lane could reorder the clicks.
839
execute: runAction,
505
- onSuccess: ({ environmentId, input }, registry) =>
506
- Effect.sync(() => {
507
- registry.refresh(preview({ environmentId, input }));
508
- registry.refresh(previewCard({ environmentId, input }));
509
- }),
840
+ onStart: (_target, registry) => readsInFlight(registry),
841
+ // Loaded readers show the reply, or re-read when the host's reply lacked the pull request.
842
+ onSuccess: ({ environmentId, input }, registry, reply, readsBeforeSend) => {
843
+ const { projectId, host, repository, number, expectedAccountId } = input;
844
+ return applyActionReply(
845
+ registry,
846
+ environmentId,
847
+ {
848
+ projectId,
849
+ ...(host === undefined ? {} : { host }),
850
+ repository,
851
+ number,
852
+ ...(expectedAccountId === undefined ? {} : { expectedAccountId }),
853
+ },
854
+ reply,
855
+ readsBeforeSend ?? new Set(),
856
+ );
857
+ },
858
scheduler: commandScheduler,
859
concurrency: serialPerEnvironment,
860
}),
packages/client-runtime/src/state/runtime.ts
+23
-3
@@ -477,6 +477,10 @@ export async function settlePromise<A>(
477
}
478
}
479
480
+/** Where a query's answer is persisted, so an action's reply can be saved where a read would be. */
481
+export const queryPersistenceKey = (label: string, input: unknown): string =>
482
+ JSON.stringify([label, input]);
483
+
484
function environmentRpcKey<Input>(target: {
485
readonly environmentId: EnvironmentIdType;
486
readonly input: Input;
@@ -765,7 +769,7 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
769
);
770
if (!options.persistence) return answer();
771
const persistence = options.persistence;
768
- const cacheKey = JSON.stringify([options.label, target.input]);
772
+ const cacheKey = queryPersistenceKey(options.label, target.input);
773
const previous = Option.flatMap(
774
get.self<AsyncResult.AsyncResult<A, unknown>>(),
775
AsyncResult.value,
@@ -960,11 +964,20 @@ export function createEnvironmentRpcCommand<
964
ER,
965
TTag extends EnvironmentUnaryRpcTag,
966
Input extends EnvironmentRpcInput<TTag> = EnvironmentRpcInput<TTag>,
967
+ Started = undefined,
968
>(
969
runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
970
options: {
971
readonly label: string;
972
readonly tag: TTag;
973
+ /** Runs once authorized, as the request starts; what it returns reaches `onSuccess`. */
974
+ readonly onStart?: (
975
+ target: {
976
+ readonly environmentId: EnvironmentIdType;
977
+ readonly input: NoInfer<Input>;
978
+ },
979
+ registry: AtomRegistry.AtomRegistry,
980
+ ) => Started;
981
readonly execute?: (
982
input: Input,
983
) => Effect.Effect<
@@ -984,6 +997,7 @@ export function createEnvironmentRpcCommand<
997
},
998
registry: AtomRegistry.AtomRegistry,
999
result: EnvironmentRpcSuccess<TTag>,
1000
+ started: Started | undefined,
1001
) => Effect.Effect<void, never, R>;
1002
readonly onSettled?: (
1003
target: {
@@ -1004,15 +1018,21 @@ export function createEnvironmentRpcCommand<
1018
environmentId,
1019
input,
1020
};
1021
+ let started: Started | undefined;
1022
// Routing requires consent on the origin as well as the actual destination.
1023
// The transport check below deliberately checks the destination again.
1024
return permissions.authorize(registry, environmentId, input).pipe(
1010
- Effect.andThen(() => options.execute?.(input) ?? requestGuarded(options.tag, input)),
1025
+ Effect.andThen(() => {
1026
+ started = options.onStart?.(target, registry);
1027
+ return options.execute?.(input) ?? requestGuarded(options.tag, input);
1028
+ }),
1029
Effect.provideService(RpcPermissionGuard, {
1030
authorize: (id, method, payload) =>
1031
createCommandPermissions(runtime, method).authorize(registry, id, payload),
1032
}),
1015
- Effect.tap((result) => options.onSuccess?.(target, registry, result) ?? Effect.void),
1033
+ Effect.tap(
1034
+ (result) => options.onSuccess?.(target, registry, result, started) ?? Effect.void,
1035
+ ),
1036
Effect.ensuring(options.onSettled?.(target, registry) ?? Effect.void),
1037
);
1038
},
packages/contracts/src/pullRequest.ts
+8
@@ -448,6 +448,8 @@ export const PullRequestPreview = Schema.Struct({
448
state: PullRequestState,
449
isDraft: Schema.Boolean,
450
createdAt: IsoDateTime,
451
+ updatedAt: Schema.optional(IsoDateTime),
452
+ observedAt: Schema.optional(Schema.Finite),
453
});
454
export type PullRequestPreview = typeof PullRequestPreview.Type;
455
@@ -475,6 +477,10 @@ export const PullRequestSummary = Schema.Struct({
477
mergeability: Schema.optional(PullRequestMergeability),
478
/** Null when the host says the pull request is in no stack; absent when the read did not ask. */
479
stack: Schema.optional(Schema.NullOr(PullRequestStackMembership)),
480
+ headSha: Schema.optional(TrimmedNonEmptyString),
481
+ /** Absent means the read did not report auto-merge state, not that it is off. */
482
+ autoMergeEnabled: Schema.optional(Schema.Boolean),
483
+ autoMergeMethod: Schema.optional(PullRequestMergeMethod),
484
});
485
export type PullRequestSummary = typeof PullRequestSummary.Type;
486
@@ -733,6 +739,8 @@ export const PullRequestActionInput = Schema.Struct({
739
action: PullRequestAction,
740
mergeMethod: Schema.optional(PullRequestMergeMethod),
741
updateMethod: Schema.optional(PullRequestUpdateMethod),
742
+ /** Opt-in, because older clients decode the action's success as void and reject a summary. */
743
+ replyWithSummary: Schema.optional(Schema.Literal(true)),
744
});
745
export type PullRequestActionInput = typeof PullRequestActionInput.Type;
746
packages/contracts/src/rpc.ts
+2
-1
@@ -1117,7 +1117,8 @@ const WsPullRequestsSetFilesViewedRpc = Rpc.make(WS_METHODS.pullRequestsSetFiles
1117
1118
const WsPullRequestsRunActionRpc = Rpc.make(WS_METHODS.pullRequestsRunAction, {
1119
payload: PullRequestActionInput,
1120
- success: Schema.Void,
1120
+ // Undefined unless asked for with replyWithSummary, or when the host's reply lacked it.
1121
+ success: Schema.UndefinedOr(PullRequestSummary),
1122
error: PullRequestRpcError,
1123
});
1124
packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts
+8
-2
@@ -189,7 +189,7 @@ export class AzureDevOpsPullRequestCli extends Context.Service<
189
readonly number: number;
190
readonly action: PullRequestAction;
191
readonly mergeMethod?: PullRequestMergeMethod;
192
- }) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
192
+ }) => Effect.Effect<AzureDevOpsPullRequest | void, AzureDevOpsPullRequestCliError>;
193
194
readonly updatePullRequest: (input: {
195
readonly cwd: string;
@@ -663,7 +663,13 @@ export const make = Effect.gen(function* () {
663
"json",
664
],
665
})
666
- .pipe(Effect.asVoid);
666
+ .pipe(
667
+ // `pr update` prints the pull request it left, in the shape `pr show` prints.
668
+ Effect.map((result) => {
669
+ const decoded = decodePullRequestJson(result.stdout.trim());
670
+ return Result.isSuccess(decoded) ? (decoded.success ?? undefined) : undefined;
671
+ }),
672
+ );
673
},
674
),
675
packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts
+33
-18
@@ -113,6 +113,23 @@ function toChangeRequest(pullRequest: AzureDevOpsPullRequest): ProviderChangeReq
113
};
114
}
115
116
+function toSummary(pullRequest: AzureDevOpsPullRequest): ProviderChangeRequestSummary {
117
+ return {
118
+ number: pullRequest.number,
119
+ title: pullRequest.title,
120
+ url: pullRequest.url,
121
+ author: pullRequest.author,
122
+ headBranch: pullRequest.headBranch,
123
+ baseBranch: pullRequest.baseBranch,
124
+ state: pullRequest.state,
125
+ isDraft: pullRequest.isDraft,
126
+ mergeability: pullRequest.mergeability,
127
+ closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
128
+ mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
129
+ updatedAt: pullRequest.updatedAt,
130
+ };
131
+}
132
+
133
export const make = Effect.gen(function* () {
134
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
135
const diffSpawns = yield* Semaphore.make(MAX_DIFF_SPAWNS);
@@ -289,23 +306,9 @@ export const make = Effect.gen(function* () {
306
),
307
308
getChangeRequestSummary: (input) =>
292
- cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(
293
- Effect.mapError(fail("getChangeRequestSummary")),
294
- Effect.map((pullRequest): ProviderChangeRequestSummary => ({
295
- number: pullRequest.number,
296
- title: pullRequest.title,
297
- url: pullRequest.url,
298
- author: pullRequest.author,
299
- headBranch: pullRequest.headBranch,
300
- baseBranch: pullRequest.baseBranch,
301
- state: pullRequest.state,
302
- isDraft: pullRequest.isDraft,
303
- mergeability: pullRequest.mergeability,
304
- closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
305
- mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
306
- updatedAt: pullRequest.updatedAt,
307
- })),
308
- ),
309
+ cli
310
+ .getPullRequest({ cwd: input.cwd, number: input.number })
311
+ .pipe(Effect.mapError(fail("getChangeRequestSummary")), Effect.map(toSummary)),
312
313
getChangeRequest: Effect.fn("AzureDevOpsPullRequestProvider.getChangeRequest")(
314
function* (input) {
@@ -535,7 +538,19 @@ export const make = Effect.gen(function* () {
538
action: input.action,
539
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
540
})
538
- .pipe(Effect.mapError(fail("runAction"))),
541
+ .pipe(
542
+ Effect.mapError(fail("runAction")),
543
+ Effect.map(
544
+ (pullRequest) =>
545
+ pullRequest && {
546
+ ...toSummary(pullRequest),
547
+ autoMergeEnabled: pullRequest.autoMergeEnabled,
548
+ ...(pullRequest.autoMergeMethod === undefined
549
+ ? {}
550
+ : { autoMergeMethod: pullRequest.autoMergeMethod }),
551
+ },
552
+ ),
553
+ ),
554
555
updateChangeRequest: (input) =>
556
cli
packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.ts
+8
-5
@@ -228,7 +228,7 @@ export class BitbucketPullRequestApi extends Context.Service<
228
readonly number: number;
229
readonly action: PullRequestAction;
230
readonly mergeMethod?: PullRequestMergeMethod;
231
- }) => Effect.Effect<void, BitbucketPullRequestApiError>;
231
+ }) => Effect.Effect<BitbucketPullRequest | void, BitbucketPullRequestApiError>;
232
233
readonly updateChangeRequest: (input: {
234
readonly repository: string;
@@ -745,6 +745,11 @@ export const make = Effect.gen(function* () {
745
runAction: Effect.fn("BitbucketPullRequestApi.runAction")(function (input) {
746
return withRepository(input.repository, (path) => {
747
const pullRequest = `${path}/pullrequests/${input.number}`;
748
+ // Both reply with the pull request; a merge that runs long replies with a task instead.
749
+ const reply = Effect.map((response: { readonly body: string }) => {
750
+ const decoded = decodePullRequestJson(response.body);
751
+ return Result.isSuccess(decoded) ? decoded.success : undefined;
752
+ });
753
if (input.action === "merge") {
754
return bitbucket
755
.request({
@@ -752,11 +757,9 @@ export const make = Effect.gen(function* () {
757
url: `${pullRequest}/merge`,
758
body: JSON.stringify({ merge_strategy: mergeStrategy(input.mergeMethod) }),
759
})
755
- .pipe(Effect.asVoid);
760
+ .pipe(reply);
761
}
757
- return bitbucket
758
- .request({ method: "POST", url: `${pullRequest}/decline` })
759
- .pipe(Effect.asVoid);
762
+ return bitbucket.request({ method: "POST", url: `${pullRequest}/decline` }).pipe(reply);
763
});
764
}),
765
packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts
+21
-1
@@ -10,6 +10,7 @@ import {
10
type ProviderChangeRequest,
11
type ProviderChangeRequestActivity,
12
type ProviderChangeRequestDetail,
13
+ type ProviderChangeRequestSummary,
14
type PullRequestProviderApi,
15
} from "@t3tools/source-control-core/server/PullRequestProvider";
16
import type { BitbucketPullRequest } from "./bitbucketPullRequestJson.ts";
@@ -108,6 +109,22 @@ function toChangeRequest(pullRequest: BitbucketPullRequest): ProviderChangeReque
109
};
110
}
111
112
+/** The write's reply has no `closed_on`, line counts, or conflict state, so those stay absent. */
113
+function toActionSummary(pullRequest: BitbucketPullRequest): ProviderChangeRequestSummary {
114
+ return {
115
+ number: pullRequest.number,
116
+ title: pullRequest.title,
117
+ url: pullRequest.url,
118
+ author: pullRequest.author,
119
+ headBranch: pullRequest.headBranch,
120
+ baseBranch: pullRequest.baseBranch,
121
+ state: pullRequest.state,
122
+ isDraft: pullRequest.isDraft,
123
+ updatedAt: pullRequest.updatedAt,
124
+ ...(pullRequest.headSha ? { headSha: pullRequest.headSha } : {}),
125
+ };
126
+}
127
+
128
export const make = Effect.gen(function* () {
129
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
130
const servesHost = yield* BitbucketApi.BitbucketServesHost.pipe(Effect.orDie);
@@ -313,7 +330,10 @@ export const make = Effect.gen(function* () {
330
action: input.action,
331
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
332
})
316
- .pipe(Effect.mapError(fail("runAction"))),
333
+ .pipe(
334
+ Effect.mapError(fail("runAction")),
335
+ Effect.map((pullRequest) => pullRequest && toActionSummary(pullRequest)),
336
+ ),
337
338
updateChangeRequest: (input) =>
339
api
packages/source-control-core/src/server/PullRequestProvider.ts
+6
-1
@@ -122,6 +122,10 @@ export interface ProviderChangeRequestSummary {
122
readonly mergeability?: PullRequestMergeability | undefined;
123
/** Null means no stack; absent means not requested. */
124
readonly stack?: PullRequestStackMembership | null | undefined;
125
+ readonly headSha?: string | undefined;
126
+ /** Absent means the read did not report auto-merge state, not that it is off. */
127
+ readonly autoMergeEnabled?: boolean | undefined;
128
+ readonly autoMergeMethod?: PullRequestMergeMethod | undefined;
129
}
130
131
export interface ProviderChangeRequestStackLayer {
@@ -470,6 +474,7 @@ export interface PullRequestProviderApi {
474
},
475
) => Effect.Effect<ProviderFileRevisions, PullRequestProviderError>;
476
477
+ /** Returns the change request as the host's reply left it, or void when the reply lacks it. */
478
readonly runAction: (
479
input: ProviderRepositoryRef & {
480
readonly number: number;
@@ -480,7 +485,7 @@ export interface PullRequestProviderApi {
485
readonly mergeMethod?: PullRequestMergeMethod;
486
readonly updateMethod?: PullRequestUpdateMethod;
487
},
483
- ) => Effect.Effect<void, PullRequestProviderError>;
488
+ ) => Effect.Effect<ProviderChangeRequestSummary | void, PullRequestProviderError>;
489
490
/** Requires edit capability and at least one field. */
491
readonly updateChangeRequest?: (
packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts
+21
-2
@@ -9,6 +9,7 @@ import { parseDiffFileRevisions } from "@t3tools/source-control-core/server/diff
9
import {
10
PullRequestProviderError,
11
type ProviderChangeRequestDetail,
12
+ type ProviderChangeRequestSummary,
13
type ProviderRepositoryRef,
14
type PullRequestProviderApi,
15
} from "@t3tools/source-control-core/server/PullRequestProvider";
@@ -80,6 +81,24 @@ const issuePath = (input: ProviderRepositoryRef & { readonly number: number }) =
81
const reviewCommentId = (review: typeof ForgejoReview.Type) =>
82
/#issuecomment-([1-9]\d*)$/.exec(review.html_url ?? "")?.[1];
83
84
+const decodePullRequest = decodeJsonResult(ForgejoPullRequest);
85
+
86
+/** Only the PATCH reply carries the pull request; merge and update reply with an empty body. */
87
+function forgejoActionSummary(stdout: string): ProviderChangeRequestSummary | undefined {
88
+ const decoded = decodePullRequest(stdout);
89
+ if (Result.isFailure(decoded)) return undefined;
90
+ const pr = decoded.success;
91
+ // A state PATCH does not recompute conflicts, so "unknown" there would hide a known conflict.
92
+ const { mergeability, ...summary } = forgejoChangeRequest(pr);
93
+ return {
94
+ ...summary,
95
+ ...(mergeability === "unknown" ? {} : { mergeability }),
96
+ additions: pr.additions ?? undefined,
97
+ deletions: pr.deletions ?? undefined,
98
+ ...(pr.head.sha.trim() === "" ? {} : { headSha: pr.head.sha }),
99
+ };
100
+}
101
+
102
export const make = Effect.gen(function* () {
103
const cli = yield* ForgejoCli.ForgejoCli;
104
const failure = (operation: string, detail: string, cause?: unknown) =>
@@ -537,12 +556,12 @@ export const make = Effect.gen(function* () {
556
});
557
case "close":
558
case "reopen":
540
- return write({
559
+ return request({
560
...input,
561
path: pullPath(input),
562
method: "PATCH",
563
body: { state: input.action === "close" ? "closed" : "open" },
545
- });
564
+ }).pipe(Effect.map((result) => forgejoActionSummary(result.stdout)));
565
case "update-branch":
566
return write({
567
...input,
packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
+28
-2
@@ -4,6 +4,7 @@ import * as Option from "effect/Option";
4
import * as Schema from "effect/Schema";
5
import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid";
6
import {
7
+ IsoDateTime,
8
NonNegativeInt,
9
resolvePullRequestAuthorFilter,
10
TrimmedNonEmptyString,
@@ -166,6 +167,17 @@ const MergeOutcome = Schema.Struct({
167
const StackOutcome = Schema.Struct({ id: Schema.String, state: Schema.String });
168
const FAILED_STACK_STATES = new Set(["failed", "stopped", "cancelled", "reconciliation_required"]);
169
170
+// A pull action replies with the pull it left; `closedAt`/`mergedAt` are read only when sent.
171
+const decodeActionReply = Schema.decodeUnknownOption(
172
+ Schema.fromJsonString(
173
+ Schema.Struct({
174
+ ...Json.GitCafePull.fields,
175
+ closedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
176
+ mergedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
177
+ }),
178
+ ),
179
+);
180
+
181
type PullRef = ProviderRepositoryRef & { readonly number: number };
182
183
/** GitHub's merge counts as soon as GitCafe records it, ahead of the sync that reports it. */
@@ -1127,12 +1139,26 @@ export const make = Effect.gen(function* () {
1139
case "reopen": {
1140
const pull = yield* readPull(input.action, input);
1141
const path = yield* pullPath(input.action, input);
1130
- yield* send(input.action, input, {
1142
+ const reply = yield* send(input.action, input, {
1143
method: "POST",
1144
path: `${path}/${input.action}`,
1145
body: { expectedVersion: pull.version },
1146
});
1135
- return;
1147
+ const left = decodeActionReply(reply);
1148
+ if (Option.isNone(left)) return;
1149
+ // The reply carries no line totals or conflict state, so they stay absent.
1150
+ const {
1151
+ additions: _additions,
1152
+ deletions: _deletions,
1153
+ mergeability: _mergeability,
1154
+ ...summary
1155
+ } = Json.toChangeRequest(left.value, input);
1156
+ return {
1157
+ ...summary,
1158
+ ...(left.value.headOid === null ? {} : { headSha: left.value.headOid }),
1159
+ ...(left.value.closedAt === undefined ? {} : { closedAt: left.value.closedAt }),
1160
+ ...(left.value.mergedAt === undefined ? {} : { mergedAt: left.value.mergedAt }),
1161
+ };
1162
}
1163
default:
1164
return yield* failure(input.action, `GitCafe cannot ${input.action} from T3 Code.`);
packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
+87
-23
@@ -2065,6 +2065,84 @@ layer("GitHubPullRequestApi.layer", (it) => {
2065
},
2066
});
2067
2068
+ it.effect.each([
2069
+ { queued: false, field: "mergePullRequest", state: "MERGED", autoMergeRequest: null },
2070
+ {
2071
+ queued: true,
2072
+ field: "enablePullRequestAutoMerge",
2073
+ state: "OPEN",
2074
+ autoMergeRequest: { mergeMethod: "MERGE" },
2075
+ },
2076
+ ] as const)(
2077
+ "returns the pull request from GitHub's $field reply",
2078
+ ({ queued, field, state, autoMergeRequest }) =>
2079
+ Effect.gen(function* () {
2080
+ const mergedAt = state === "MERGED" ? "2026-10-27T11:59:00Z" : null;
2081
+ route(
2082
+ ["query PullRequestActionState", actionState({ isMergeQueueEnabled: queued })],
2083
+ [
2084
+ field + "(",
2085
+ {
2086
+ data: {
2087
+ [field]: {
2088
+ pullRequest: {
2089
+ number: 7,
2090
+ title: "Pull request 7",
2091
+ url: "https://github.com/acme/web/pull/7",
2092
+ headRefName: "feat/page",
2093
+ baseRefName: "main",
2094
+ state,
2095
+ isDraft: false,
2096
+ updatedAt: "2026-10-27T12:00:00Z",
2097
+ mergedAt,
2098
+ closedAt: mergedAt,
2099
+ headRefOid: "response-head",
2100
+ author: { __typename: "User", login: "alice", avatarUrl: "", name: null },
2101
+ autoMergeRequest,
2102
+ },
2103
+ },
2104
+ },
2105
+ },
2106
+ ],
2107
+ );
2108
+ const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2109
+ expect(yield* cli.runPullRequestAction({ ...pullRequestInput, action: "merge" })).toEqual({
2110
+ number: 7,
2111
+ title: "Pull request 7",
2112
+ url: "https://github.com/acme/web/pull/7",
2113
+ headBranch: "feat/page",
2114
+ baseBranch: "main",
2115
+ state: state.toLowerCase(),
2116
+ isDraft: false,
2117
+ updatedAt: "2026-10-27T12:00:00Z",
2118
+ mergedAt,
2119
+ closedAt: mergedAt,
2120
+ author: { login: "alice", name: null, avatarUrl: null },
2121
+ headSha: "response-head",
2122
+ autoMergeEnabled: queued,
2123
+ ...(queued ? { autoMergeMethod: "merge" } : {}),
2124
+ });
2125
+ // The action-state read and the mutation; no re-read of the pull request.
2126
+ expect(mockedExecute).toHaveBeenCalledTimes(2);
2127
+ }),
2128
+ );
2129
+
2130
+ it.effect("succeeds without a summary when GitHub's merge reply does not decode", () =>
2131
+ Effect.gen(function* () {
2132
+ route(
2133
+ ["query PullRequestActionState", actionState({ isMergeQueueEnabled: false })],
2134
+ [
2135
+ "mergePullRequest(",
2136
+ { data: { mergePullRequest: { pullRequest: { state: "MERGING" } } } },
2137
+ ],
2138
+ );
2139
+ const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
2140
+ expect(
2141
+ yield* cli.runPullRequestAction({ ...pullRequestInput, action: "merge" }),
2142
+ ).toBeUndefined();
2143
+ }),
2144
+ );
2145
+
2146
it.effect.each([
2147
{
2148
description: "base-only write",
@@ -3446,7 +3524,7 @@ layer("GitHubPullRequestApi.layer", (it) => {
3524
checkSuite: { workflowRun: { workflow: { name: "windows" } } },
3525
}),
3526
],
3449
- pageInfo: { hasNextPage: false },
3527
+ pageInfo: { hasNextPage: false, endCursor: null },
3528
},
3529
},
3530
},
@@ -3483,7 +3561,7 @@ layer("GitHubPullRequestApi.layer", (it) => {
3561
);
3562
3563
it.effect.each([false, true])(
3486
- "reads every check when the combined response has another page (reviewer refusal: %s)",
3564
+ "continues after the core check page without reading it twice (reviewer refusal: %s)",
3565
(refused) =>
3566
Effect.gen(function* () {
3567
if (refused) mockedExecute.mockReturnValueOnce(refusedReviewerResponse());
@@ -3498,13 +3576,7 @@ layer("GitHubPullRequestApi.layer", (it) => {
3576
commit: {
3577
statusCheckRollup: {
3578
contexts: {
3501
- nodes: [
3502
- checkRun({
3503
- name: "first",
3504
- status: "COMPLETED",
3505
- conclusion: "SUCCESS",
3506
- }),
3507
- ],
3579
+ nodes: [checkRun({ name: "first", conclusion: "SUCCESS" })],
3580
pageInfo: { hasNextPage: true, endCursor: "c1" },
3581
},
3582
},
@@ -3519,15 +3591,7 @@ layer("GitHubPullRequestApi.layer", (it) => {
3591
);
3592
mockedExecute.mockReturnValueOnce(
3593
Effect.succeed(
3522
- output(
3523
- checkContextsPage(
3524
- [
3525
- checkRun({ name: "first", status: "COMPLETED", conclusion: "SUCCESS" }),
3526
- checkRun({ name: "last", status: "COMPLETED", conclusion: "FAILURE" }),
3527
- ],
3528
- null,
3529
- ),
3530
- ),
3594
+ output(checkContextsPage([checkRun({ name: "last", conclusion: "FAILURE" })], null)),
3595
),
3596
);
3597
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
@@ -3543,12 +3607,12 @@ layer("GitHubPullRequestApi.layer", (it) => {
3607
expect(variablesOf("PullRequestCore").map((v) => v["requestedReviewers"])).toEqual([
3608
100, 0,
3609
]);
3546
- expect(detail.checks).toHaveLength(2);
3610
+ expect(detail.checks.map((check) => check.name).sort()).toEqual(["first", "last"]);
3611
expect(detail.checksState).toBe("failing");
3612
expect(detail.checksTruncated).toBe(false);
3549
- // The whole rollup is walked from its start, so no check is counted twice or skipped.
3550
- expect(variablesOf("CheckContexts")).toEqual([expect.objectContaining({ number: 7 })]);
3551
- expect(variablesOf("CheckContexts")[0]).not.toHaveProperty("after");
3613
+ expect(variablesOf("CheckContexts")).toEqual([
3614
+ expect.objectContaining({ number: 7, after: "c1" }),
3615
+ ]);
3616
expect(mockedExecute).toHaveBeenCalledTimes(refused ? 3 : 2);
3617
3618
if (refused) {
@@ -3573,7 +3637,7 @@ layer("GitHubPullRequestApi.layer", (it) => {
3637
statusCheckRollup: {
3638
contexts: {
3639
nodes: [],
3576
- pageInfo: { hasNextPage: true },
3640
+ pageInfo: { hasNextPage: true, endCursor: "c1" },
3641
},
3642
},
3643
},
packages/source-control-github/src/server/GitHubPullRequestApi.ts
+91
-73
@@ -50,7 +50,10 @@ import * as GitHubRest from "./GitHubRest.ts";
50
import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
51
import * as GitHubGraphQlClient from "./gitHubGraphQlClient.ts";
52
import { PullRequestBatchesGraphQLGroup } from "./pullRequestBatches.graphql.ts";
53
-import { PullRequestMutationsGraphQLGroup } from "./pullRequestMutations.graphql.ts";
53
+import {
54
+ PullRequestMutationsGraphQLGroup,
55
+ type PullRequestActionSummary,
56
+} from "./pullRequestMutations.graphql.ts";
57
import { PullRequestReadsGraphQLGroup } from "./pullRequestReads.graphql.ts";
58
import { PullRequestReviewsGraphQLGroup } from "./pullRequestReviews.graphql.ts";
59
import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
@@ -73,6 +76,7 @@ import {
76
toRepositoryAuthors,
77
toRepositoryLabels,
78
toPullRequestActivityPage,
79
+ toPullRequestActionSummary,
80
toPullRequestCommitStats,
81
toPullRequestCheckContextsPage,
82
toPullRequestCore,
@@ -658,7 +662,7 @@ export class GitHubPullRequestApi extends Context.Service<
662
readonly removeAgentCreditsOnMerge?: boolean;
663
readonly mergeMethod?: PullRequestMergeMethod;
664
readonly updateMethod?: PullRequestUpdateMethod;
661
- }) => Effect.Effect<void, GitHubPullRequestApiError>;
665
+ }) => Effect.Effect<ProviderChangeRequestSummary | void, GitHubPullRequestApiError>;
666
667
readonly commentOnPullRequest: (input: {
668
readonly cwd: string;
@@ -1378,48 +1382,35 @@ export const make = Effect.gen(function* () {
1382
const readAllCheckContexts = Effect.fn("GitHubPullRequestApi.readAllCheckContexts")(function* (
1383
input: Parameters<GitHubPullRequestApi["Service"]["getPullRequestDetail"]>[0],
1384
allowReserve: boolean,
1385
+ first: NonNullable<ReturnType<typeof toPullRequestCheckContextsPage>>,
1386
) {
1387
const { owner, name } = parseRepositorySelector(input.repository);
1388
const target = { ...input, operation: "getPullRequestDetail", allowReserve };
1384
- let headSha: string | null = null;
1385
- const { pages, truncated } = yield* readPages(
1386
- GraphQLClient.pages(client.PullRequestCheckContexts, {
1387
- variables: { owner, name, number: input.number, required: asksRequired(input.host) },
1388
- connection: (result) => {
1389
- const page = toPullRequestCheckContextsPage(result);
1390
- if (page === null) return null;
1391
- headSha ??= page.headSha;
1392
- return {
1393
- ...page,
1394
- // Past the first page a different head is a push mid-walk.
1395
- changed: page.headSha !== headSha,
1396
- pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },
1397
- };
1398
- },
1399
- }).pipe(
1400
- Stream.mapEffect((page) =>
1401
- page.changed
1402
- ? Effect.fail(
1403
- readError(
1404
- input.cwd,
1405
- "getPullRequestDetail",
1406
- new Error("Pull request head changed while reading checks."),
1407
- ),
1408
- )
1409
- : Effect.succeed(page),
1410
- ),
1411
- ),
1412
- {
1413
- ...target,
1414
- maxPages: CHECK_CONTEXT_PAGES,
1415
- hasNextPage: (page) => page.nextCursor !== null,
1416
- },
1417
- ).pipe(graphql(target));
1418
- return {
1419
- headSha: pages[0]?.headSha ?? null,
1420
- contexts: pages.flatMap((page) => page.contexts),
1421
- truncated,
1422
- };
1389
+ const contexts = [...first.contexts];
1390
+ let after = first.nextCursor;
1391
+ for (let page = 1; after !== null && page < CHECK_CONTEXT_PAGES; page++) {
1392
+ const result = yield* client
1393
+ .PullRequestCheckContexts({
1394
+ owner,
1395
+ name,
1396
+ number: input.number,
1397
+ required: asksRequired(input.host),
1398
+ after,
1399
+ })
1400
+ .pipe(graphql(target));
1401
+ const next = toPullRequestCheckContextsPage(result);
1402
+ if (next === null || next.headSha !== first.headSha) {
1403
+ return yield* readError(
1404
+ input.cwd,
1405
+ "getPullRequestDetail",
1406
+ new Error("Pull request head changed while reading checks."),
1407
+ );
1408
+ }
1409
+ if (next.nextCursor === after) return { contexts, truncated: true };
1410
+ contexts.push(...next.contexts);
1411
+ after = next.nextCursor;
1412
+ }
1413
+ return { contexts, truncated: first.nextCursor === null || after !== null };
1414
});
1415
1416
// GitHub refuses a requested-reviewer list holding a team the viewer cannot see. Remember the
@@ -1463,29 +1454,24 @@ export const make = Effect.gen(function* () {
1454
Effect.flatMap((allowReserve) =>
1455
readRequestedReviewers(input, 100, read).pipe(
1456
graphql({ ...input, operation, allowReserve }),
1466
- Effect.map(toPullRequestCore),
1467
- Effect.flatMap(found({ ...input, operation })),
1468
- // Past a hundred checks the first page would let the rest imply success, so the whole
1469
- // rollup is walked instead.
1470
- Effect.filterOrElse(
1471
- (core) => !core.checksTruncated,
1472
- (core) =>
1473
- readAllCheckContexts(input, allowReserve).pipe(
1474
- Effect.filterOrFail(
1475
- (all) => all.headSha === core.headSha,
1476
- () =>
1477
- readError(
1478
- input.cwd,
1479
- operation,
1480
- new Error("Pull request head changed while reading checks."),
1481
- ),
1482
- ),
1483
- Effect.map((all) => ({
1484
- ...core,
1485
- ...pullRequestChecksFromContexts(all.contexts),
1486
- checksTruncated: all.truncated,
1487
- })),
1457
+ Effect.flatMap((result) =>
1458
+ found({ ...input, operation })(toPullRequestCore(result)).pipe(
1459
+ Effect.filterOrElse(
1460
+ (core) => !core.checksTruncated,
1461
+ (core) =>
1462
+ readAllCheckContexts(
1463
+ input,
1464
+ allowReserve,
1465
+ toPullRequestCheckContextsPage(result)!,
1466
+ ).pipe(
1467
+ Effect.map((all) => ({
1468
+ ...core,
1469
+ ...pullRequestChecksFromContexts(all.contexts),
1470
+ checksTruncated: all.truncated,
1471
+ })),
1472
+ ),
1473
),
1474
+ ),
1475
),
1476
),
1477
),
@@ -1636,17 +1622,39 @@ export const make = Effect.gen(function* () {
1622
1623
const simpleActionMutations = {
1624
"disable-auto-merge": (pullRequestId: string) =>
1639
- client.DisablePullRequestAutoMerge({ pullRequestId }).pipe(Effect.asVoid),
1625
+ client
1626
+ .DisablePullRequestAutoMerge({ pullRequestId })
1627
+ .pipe(Effect.map((result) => result.disablePullRequestAutoMerge?.pullRequest)),
1628
ready: (pullRequestId: string) =>
1641
- client.MarkPullRequestReadyForReview({ pullRequestId }).pipe(Effect.asVoid),
1629
+ client
1630
+ .MarkPullRequestReadyForReview({ pullRequestId })
1631
+ .pipe(Effect.map((result) => result.markPullRequestReadyForReview?.pullRequest)),
1632
draft: (pullRequestId: string) =>
1643
- client.ConvertPullRequestToDraft({ pullRequestId }).pipe(Effect.asVoid),
1633
+ client
1634
+ .ConvertPullRequestToDraft({ pullRequestId })
1635
+ .pipe(Effect.map((result) => result.convertPullRequestToDraft?.pullRequest)),
1636
close: (pullRequestId: string) =>
1645
- client.ClosePullRequest({ pullRequestId }).pipe(Effect.asVoid),
1637
+ client
1638
+ .ClosePullRequest({ pullRequestId })
1639
+ .pipe(Effect.map((result) => result.closePullRequest?.pullRequest)),
1640
reopen: (pullRequestId: string) =>
1647
- client.ReopenPullRequest({ pullRequestId }).pipe(Effect.asVoid),
1641
+ client
1642
+ .ReopenPullRequest({ pullRequestId })
1643
+ .pipe(Effect.map((result) => result.reopenPullRequest?.pullRequest)),
1644
} satisfies Partial<Record<PullRequestAction, unknown>>;
1645
1646
+ /** The mutation already landed, so a reply that does not decode only loses the summary. */
1647
+ const actionSummary = <E, R>(
1648
+ effect: Effect.Effect<PullRequestActionSummary | null | undefined, E, R>,
1649
+ ) =>
1650
+ effect.pipe(
1651
+ Effect.map(toPullRequestActionSummary),
1652
+ Effect.catchIf(
1653
+ (error) => isGraphQlClientError(error) && error.reason._tag === "DecodeError",
1654
+ () => Effect.void,
1655
+ ),
1656
+ );
1657
+
1658
/** Preserve policy errors; map not-found per lookup and other failures to read errors. */
1659
const batchedRead = <A, E, R>(
1660
input: { readonly cwd: string; readonly host: string; readonly operation: string },
@@ -2575,7 +2583,9 @@ export const make = Effect.gen(function* () {
2583
const mutate = simpleActionMutations[action as keyof typeof simpleActionMutations];
2584
return pullRequestNodeId({ ...input, operation: "runPullRequestAction" }).pipe(
2585
Effect.flatMap((pullRequestId) =>
2578
- mutate(pullRequestId).pipe(graphql({ ...input, operation: "runPullRequestAction" })),
2586
+ actionSummary(mutate(pullRequestId)).pipe(
2587
+ graphql({ ...input, operation: "runPullRequestAction" }),
2588
+ ),
2589
),
2590
);
2591
}
@@ -2603,7 +2613,11 @@ export const make = Effect.gen(function* () {
2613
expectedHeadOid: state.headRefOid,
2614
updateMethod: input.updateMethod === "rebase" ? "REBASE" : "MERGE",
2615
})
2606
- .pipe(graphql(target), Effect.asVoid);
2616
+ .pipe(
2617
+ Effect.map((result) => result.updatePullRequestBranch?.pullRequest),
2618
+ actionSummary,
2619
+ graphql(target),
2620
+ );
2621
}
2622
let body: string | undefined;
2623
let expectedHead: string | undefined;
@@ -2641,10 +2655,14 @@ export const make = Effect.gen(function* () {
2655
...(expectedHead === undefined ? {} : { expectedHeadOid: expectedHead }),
2656
...(body === undefined ? {} : { commitBody: body }),
2657
};
2644
- yield* (
2658
+ return yield* actionSummary(
2659
auto
2646
- ? client.EnablePullRequestAutoMerge({ input: merge }).pipe(Effect.asVoid)
2647
- : client.MergePullRequest({ input: merge }).pipe(Effect.asVoid)
2660
+ ? client
2661
+ .EnablePullRequestAutoMerge({ input: merge })
2662
+ .pipe(Effect.map((result) => result.enablePullRequestAutoMerge?.pullRequest))
2663
+ : client
2664
+ .MergePullRequest({ input: merge })
2665
+ .pipe(Effect.map((result) => result.mergePullRequest?.pullRequest)),
2666
).pipe(graphql(target));
2667
});
2668
}),
packages/source-control-github/src/server/gitHubPullRequestJson.test.ts
+4
-1
@@ -379,7 +379,10 @@ describe("pull request detail decoding", () => {
379
{
380
commit: {
381
statusCheckRollup: {
382
- contexts: { nodes: rollup, pageInfo: { hasNextPage: false } },
382
+ contexts: {
383
+ nodes: rollup,
384
+ pageInfo: { hasNextPage: false, endCursor: null },
385
+ },
386
},
387
},
388
},
packages/source-control-github/src/server/gitHubPullRequestJson.ts
+25
@@ -37,6 +37,7 @@ import type {
37
import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
38
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
39
import { dedupeChecks } from "@t3tools/source-control-core/server/pullRequestChecks";
40
+import type { ProviderChangeRequestSummary } from "@t3tools/source-control-core/server/PullRequestProvider";
41
42
import type * as GitHubSchema from "../../schema/github.graphql.ts";
43
import type {
@@ -49,6 +50,7 @@ import {
50
PullRequestRow,
51
PullRequestSearch,
52
} from "./pullRequestListings.graphql.ts";
53
+import type { PullRequestActionSummary } from "./pullRequestMutations.graphql.ts";
54
import type {
55
CheckContext,
56
LabelCandidates,
@@ -479,6 +481,29 @@ function toMergeMethod(value: string | null | undefined): PullRequestMergeMethod
481
}
482
}
483
484
+export function toPullRequestActionSummary(
485
+ raw: PullRequestActionSummary | null | undefined,
486
+): ProviderChangeRequestSummary | undefined {
487
+ if (raw == null) return undefined;
488
+ const autoMergeMethod = toMergeMethod(raw.autoMergeRequest?.mergeMethod);
489
+ return {
490
+ number: raw.number,
491
+ title: raw.title,
492
+ url: raw.url,
493
+ headBranch: raw.headRefName,
494
+ baseBranch: raw.baseRefName,
495
+ state: toState(raw),
496
+ isDraft: raw.isDraft,
497
+ updatedAt: raw.updatedAt,
498
+ mergedAt: trimmed(raw.mergedAt),
499
+ closedAt: trimmed(raw.closedAt),
500
+ author: toActor(raw.author),
501
+ headSha: raw.headRefOid,
502
+ autoMergeEnabled: raw.autoMergeRequest !== null,
503
+ ...(autoMergeMethod === undefined ? {} : { autoMergeMethod }),
504
+ };
505
+}
506
+
507
/** GitHub's reviewDecision ignores reviews outside branch rules, including app approvals. */
508
function toReviewDecisionWithReviews(
509
value: string | null | undefined,
packages/source-control-github/src/server/pullRequestMutations.graphql
+50
-10
@@ -1,5 +1,29 @@
1
-# Writes to a pull request and the remarks on it. None reads its answer back beyond what GitHub
2
-# requires a mutation to select.
1
+# Writes to a pull request and the remarks on it. Only pull request actions read their answer back,
2
+# so clients can show the result without another read.
3
+
4
+fragment PullRequestActionSummary on PullRequest {
5
+ number
6
+ title
7
+ url
8
+ headRefName
9
+ baseRefName
10
+ state
11
+ isDraft
12
+ updatedAt
13
+ mergedAt
14
+ closedAt
15
+ headRefOid
16
+ author {
17
+ login
18
+ avatarUrl
19
+ ... on User {
20
+ name
21
+ }
22
+ }
23
+ autoMergeRequest {
24
+ mergeMethod
25
+ }
26
+}
27
28
mutation AddReviewThreadReply($threadId: ID!, $body: String!) {
29
addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $threadId, body: $body }) {
@@ -105,19 +129,25 @@ mutation SetFileViewed($pullRequestId: ID!, $path: String!, $viewed: Boolean!) {
129
130
mutation MergePullRequest($input: MergePullRequestInput!) {
131
mergePullRequest(input: $input) {
108
- clientMutationId
132
+ pullRequest {
133
+ ...PullRequestActionSummary
134
+ }
135
}
136
}
137
138
mutation EnablePullRequestAutoMerge($input: EnablePullRequestAutoMergeInput!) {
139
enablePullRequestAutoMerge(input: $input) {
114
- clientMutationId
140
+ pullRequest {
141
+ ...PullRequestActionSummary
142
+ }
143
}
144
}
145
146
mutation DisablePullRequestAutoMerge($pullRequestId: ID!) {
147
disablePullRequestAutoMerge(input: { pullRequestId: $pullRequestId }) {
120
- clientMutationId
148
+ pullRequest {
149
+ ...PullRequestActionSummary
150
+ }
151
}
152
}
153
@@ -133,31 +163,41 @@ mutation UpdatePullRequestBranch(
163
updateMethod: $updateMethod
164
}
165
) {
136
- clientMutationId
166
+ pullRequest {
167
+ ...PullRequestActionSummary
168
+ }
169
}
170
}
171
172
mutation MarkPullRequestReadyForReview($pullRequestId: ID!) {
173
markPullRequestReadyForReview(input: { pullRequestId: $pullRequestId }) {
142
- clientMutationId
174
+ pullRequest {
175
+ ...PullRequestActionSummary
176
+ }
177
}
178
}
179
180
mutation ConvertPullRequestToDraft($pullRequestId: ID!) {
181
convertPullRequestToDraft(input: { pullRequestId: $pullRequestId }) {
148
- clientMutationId
182
+ pullRequest {
183
+ ...PullRequestActionSummary
184
+ }
185
}
186
}
187
188
mutation ClosePullRequest($pullRequestId: ID!) {
189
closePullRequest(input: { pullRequestId: $pullRequestId }) {
154
- clientMutationId
190
+ pullRequest {
191
+ ...PullRequestActionSummary
192
+ }
193
}
194
}
195
196
mutation ReopenPullRequest($pullRequestId: ID!) {
197
reopenPullRequest(input: { pullRequestId: $pullRequestId }) {
160
- clientMutationId
198
+ pullRequest {
199
+ ...PullRequestActionSummary
200
+ }
201
}
202
}
203
packages/source-control-github/src/server/pullRequestMutations.graphql.ts
+118
-32
@@ -3,6 +3,76 @@ import { GraphQL, GraphQLGroup } from "effect/graphql"
3
import * as Schema from "effect/Schema"
4
import * as Shared from "../../schema/github.graphql.ts"
5
6
+/** A user is an individual's account on GitHub that owns repositories and can make new content. */
7
+export const User = Schema.Struct({
8
+ __typename: Schema.Literal("User"),
9
+ /** The username used to login. */
10
+ login: Schema.String,
11
+ /** A URL pointing to the user's public avatar. */
12
+ avatarUrl: Shared.URI,
13
+ /** The user's public profile name. */
14
+ name: Schema.NullOr(Schema.String)
15
+})
16
+export interface User extends Schema.Struct.Type<typeof User.fields> {}
17
+
18
+/** Represents an object which can take actions on GitHub. Typically a User or Bot. */
19
+export const ActorOther = Schema.Struct({
20
+ __typename: GraphQL.otherTypename<Shared.Typename.Actor>()(["User"]),
21
+ /** The username of the actor. */
22
+ login: Schema.String,
23
+ /** A URL pointing to the actor's public avatar. */
24
+ avatarUrl: Shared.URI
25
+})
26
+export interface ActorOther extends Schema.Struct.Type<typeof ActorOther.fields> {}
27
+
28
+/** Represents an auto-merge request for a pull request */
29
+export const AutoMergeRequest = Schema.Struct({
30
+ /**
31
+ * The merge method of the auto-merge request. If a merge queue is required by
32
+ * the base branch, this value will be set by the merge queue when merging.
33
+ */
34
+ mergeMethod: GraphQL.enumLiterals(Shared.PullRequestMergeMethod.literals)
35
+})
36
+export interface AutoMergeRequest extends Schema.Struct.Type<typeof AutoMergeRequest.fields> {}
37
+
38
+/**
39
+ * `fragment PullRequestActionSummary on PullRequest`
40
+ *
41
+ * A repository pull request.
42
+ */
43
+export const PullRequestActionSummary = Schema.Struct({
44
+ /** Identifies the pull request number. */
45
+ number: Shared.Int,
46
+ /** Identifies the pull request title. */
47
+ title: Schema.String,
48
+ /** The HTTP URL for this pull request. */
49
+ url: Shared.URI,
50
+ /** Identifies the name of the head Ref associated with the pull request, even if the ref has been deleted. */
51
+ headRefName: Schema.String,
52
+ /** Identifies the name of the base Ref associated with the pull request, even if the ref has been deleted. */
53
+ baseRefName: Schema.String,
54
+ /** Identifies the state of the pull request. */
55
+ state: GraphQL.enumLiterals(Shared.PullRequestState.literals),
56
+ /** Identifies if the pull request is a draft. */
57
+ isDraft: Schema.Boolean,
58
+ /** Identifies the date and time when the object was last updated. */
59
+ updatedAt: Shared.DateTime,
60
+ /** The date and time that the pull request was merged. */
61
+ mergedAt: Schema.NullOr(Shared.DateTime),
62
+ /** Identifies the date and time when the object was closed. */
63
+ closedAt: Schema.NullOr(Shared.DateTime),
64
+ /** Identifies the oid of the head ref associated with the pull request, even if the ref has been deleted. */
65
+ headRefOid: Shared.GitObjectID,
66
+ /** The actor who authored the comment. */
67
+ author: Schema.NullOr(Schema.Union([
68
+ User,
69
+ ActorOther
70
+ ])),
71
+ /** Returns the auto-merge request object if one exists for this pull request. */
72
+ autoMergeRequest: Schema.NullOr(AutoMergeRequest)
73
+})
74
+export interface PullRequestActionSummary extends Schema.Struct.Type<typeof PullRequestActionSummary.fields> {}
75
+
76
/** A review comment associated with a given repository pull request. */
77
export const PullRequestReviewComment = Schema.Struct({
78
/** The Node ID of the PullRequestReviewComment object */
@@ -380,8 +450,8 @@ export declare namespace SetFileViewed {
450
451
/** Autogenerated return type of MergePullRequest. */
452
export const MergePullRequestPayload = Schema.Struct({
383
- /** A unique identifier for the client performing the mutation. */
384
- clientMutationId: Schema.NullOr(Schema.String)
453
+ /** The pull request that was merged. */
454
+ pullRequest: Schema.NullOr(PullRequestActionSummary)
455
})
456
export interface MergePullRequestPayload extends Schema.Struct.Type<typeof MergePullRequestPayload.fields> {}
457
@@ -392,9 +462,11 @@ export const MergePullRequest = GraphQL.mutation("MergePullRequest", {
462
{ name: "input", body: "MergePullRequestInput!" }
463
],
464
selections: [
395
- { name: "mergePullRequest", body: ["(input:$", "input", "){clientMutationId}"] }
465
+ { name: "mergePullRequest", body: ["(input:$", "input", "){pullRequest{...PullRequestActionSummary}}"] }
466
],
397
- fragments: []
467
+ fragments: [
468
+ { name: "PullRequestActionSummary", body: ["on PullRequest{number title url headRefName baseRefName state isDraft updatedAt mergedAt closedAt headRefOid author{__typename login avatarUrl...on User{name}}autoMergeRequest{mergeMethod}}"] }
469
+ ]
470
},
471
variables: {
472
input: Shared.MergePullRequestInput
@@ -418,8 +490,8 @@ export declare namespace MergePullRequest {
490
491
/** Autogenerated return type of EnablePullRequestAutoMerge. */
492
export const EnablePullRequestAutoMergePayload = Schema.Struct({
421
- /** A unique identifier for the client performing the mutation. */
422
- clientMutationId: Schema.NullOr(Schema.String)
493
+ /** The pull request auto-merge was enabled on. */
494
+ pullRequest: Schema.NullOr(PullRequestActionSummary)
495
})
496
export interface EnablePullRequestAutoMergePayload extends Schema.Struct.Type<typeof EnablePullRequestAutoMergePayload.fields> {}
497
@@ -430,9 +502,11 @@ export const EnablePullRequestAutoMerge = GraphQL.mutation("EnablePullRequestAut
502
{ name: "input", body: "EnablePullRequestAutoMergeInput!" }
503
],
504
selections: [
433
- { name: "enablePullRequestAutoMerge", body: ["(input:$", "input", "){clientMutationId}"] }
505
+ { name: "enablePullRequestAutoMerge", body: ["(input:$", "input", "){pullRequest{...PullRequestActionSummary}}"] }
506
],
435
- fragments: []
507
+ fragments: [
508
+ { name: "PullRequestActionSummary", body: ["on PullRequest{number title url headRefName baseRefName state isDraft updatedAt mergedAt closedAt headRefOid author{__typename login avatarUrl...on User{name}}autoMergeRequest{mergeMethod}}"] }
509
+ ]
510
},
511
variables: {
512
input: Shared.EnablePullRequestAutoMergeInput
@@ -449,8 +523,8 @@ export declare namespace EnablePullRequestAutoMerge {
523
524
/** Autogenerated return type of DisablePullRequestAutoMerge. */
525
export const DisablePullRequestAutoMergePayload = Schema.Struct({
452
- /** A unique identifier for the client performing the mutation. */
453
- clientMutationId: Schema.NullOr(Schema.String)
526
+ /** The pull request auto merge was disabled on. */
527
+ pullRequest: Schema.NullOr(PullRequestActionSummary)
528
})
529
export interface DisablePullRequestAutoMergePayload extends Schema.Struct.Type<typeof DisablePullRequestAutoMergePayload.fields> {}
530
@@ -461,9 +535,11 @@ export const DisablePullRequestAutoMerge = GraphQL.mutation("DisablePullRequestA
535
{ name: "pullRequestId", body: "ID!" }
536
],
537
selections: [
464
- { name: "disablePullRequestAutoMerge", body: ["(input:{pullRequestId:$", "pullRequestId", "}){clientMutationId}"] }
538
+ { name: "disablePullRequestAutoMerge", body: ["(input:{pullRequestId:$", "pullRequestId", "}){pullRequest{...PullRequestActionSummary}}"] }
539
],
466
- fragments: []
540
+ fragments: [
541
+ { name: "PullRequestActionSummary", body: ["on PullRequest{number title url headRefName baseRefName state isDraft updatedAt mergedAt closedAt headRefOid author{__typename login avatarUrl...on User{name}}autoMergeRequest{mergeMethod}}"] }
542
+ ]
543
},
544
variables: {
545
pullRequestId: Shared.ID
@@ -480,8 +556,8 @@ export declare namespace DisablePullRequestAutoMerge {
556
557
/** Autogenerated return type of UpdatePullRequestBranch. */
558
export const UpdatePullRequestBranchPayload = Schema.Struct({
483
- /** A unique identifier for the client performing the mutation. */
484
- clientMutationId: Schema.NullOr(Schema.String)
559
+ /** The updated pull request. */
560
+ pullRequest: Schema.NullOr(PullRequestActionSummary)
561
})
562
export interface UpdatePullRequestBranchPayload extends Schema.Struct.Type<typeof UpdatePullRequestBranchPayload.fields> {}
563
@@ -494,9 +570,11 @@ export const UpdatePullRequestBranch = GraphQL.mutation("UpdatePullRequestBranch
570
{ name: "updateMethod", body: "PullRequestBranchUpdateMethod!" }
571
],
572
selections: [
497
- { name: "updatePullRequestBranch", body: ["(input:{pullRequestId:$", "pullRequestId", " expectedHeadOid:$", "expectedHeadOid", " updateMethod:$", "updateMethod", "}){clientMutationId}"] }
573
+ { name: "updatePullRequestBranch", body: ["(input:{pullRequestId:$", "pullRequestId", " expectedHeadOid:$", "expectedHeadOid", " updateMethod:$", "updateMethod", "}){pullRequest{...PullRequestActionSummary}}"] }
574
],
499
- fragments: []
575
+ fragments: [
576
+ { name: "PullRequestActionSummary", body: ["on PullRequest{number title url headRefName baseRefName state isDraft updatedAt mergedAt closedAt headRefOid author{__typename login avatarUrl...on User{name}}autoMergeRequest{mergeMethod}}"] }
577
+ ]
578
},
579
variables: {
580
pullRequestId: Shared.ID,
@@ -515,8 +593,8 @@ export declare namespace UpdatePullRequestBranch {
593
594
/** Autogenerated return type of MarkPullRequestReadyForReview. */
595
export const MarkPullRequestReadyForReviewPayload = Schema.Struct({
518
- /** A unique identifier for the client performing the mutation. */
519
- clientMutationId: Schema.NullOr(Schema.String)
596
+ /** The pull request that is ready for review. */
597
+ pullRequest: Schema.NullOr(PullRequestActionSummary)
598
})
599
export interface MarkPullRequestReadyForReviewPayload extends Schema.Struct.Type<typeof MarkPullRequestReadyForReviewPayload.fields> {}
600
@@ -527,9 +605,11 @@ export const MarkPullRequestReadyForReview = GraphQL.mutation("MarkPullRequestRe
605
{ name: "pullRequestId", body: "ID!" }
606
],
607
selections: [
530
- { name: "markPullRequestReadyForReview", body: ["(input:{pullRequestId:$", "pullRequestId", "}){clientMutationId}"] }
608
+ { name: "markPullRequestReadyForReview", body: ["(input:{pullRequestId:$", "pullRequestId", "}){pullRequest{...PullRequestActionSummary}}"] }
609
],
532
- fragments: []
610
+ fragments: [
611
+ { name: "PullRequestActionSummary", body: ["on PullRequest{number title url headRefName baseRefName state isDraft updatedAt mergedAt closedAt headRefOid author{__typename login avatarUrl...on User{name}}autoMergeRequest{mergeMethod}}"] }
612
+ ]
613
},
614
variables: {
615
pullRequestId: Shared.ID
@@ -546,8 +626,8 @@ export declare namespace MarkPullRequestReadyForReview {
626
627
/** Autogenerated return type of ConvertPullRequestToDraft. */
628
export const ConvertPullRequestToDraftPayload = Schema.Struct({
549
- /** A unique identifier for the client performing the mutation. */
550
- clientMutationId: Schema.NullOr(Schema.String)
629
+ /** The pull request that is now a draft. */
630
+ pullRequest: Schema.NullOr(PullRequestActionSummary)
631
})
632
export interface ConvertPullRequestToDraftPayload extends Schema.Struct.Type<typeof ConvertPullRequestToDraftPayload.fields> {}
633
@@ -558,9 +638,11 @@ export const ConvertPullRequestToDraft = GraphQL.mutation("ConvertPullRequestToD
638
{ name: "pullRequestId", body: "ID!" }
639
],
640
selections: [
561
- { name: "convertPullRequestToDraft", body: ["(input:{pullRequestId:$", "pullRequestId", "}){clientMutationId}"] }
641
+ { name: "convertPullRequestToDraft", body: ["(input:{pullRequestId:$", "pullRequestId", "}){pullRequest{...PullRequestActionSummary}}"] }
642
],
563
- fragments: []
643
+ fragments: [
644
+ { name: "PullRequestActionSummary", body: ["on PullRequest{number title url headRefName baseRefName state isDraft updatedAt mergedAt closedAt headRefOid author{__typename login avatarUrl...on User{name}}autoMergeRequest{mergeMethod}}"] }
645
+ ]
646
},
647
variables: {
648
pullRequestId: Shared.ID
@@ -577,8 +659,8 @@ export declare namespace ConvertPullRequestToDraft {
659
660
/** Autogenerated return type of ClosePullRequest. */
661
export const ClosePullRequestPayload = Schema.Struct({
580
- /** A unique identifier for the client performing the mutation. */
581
- clientMutationId: Schema.NullOr(Schema.String)
662
+ /** The pull request that was closed. */
663
+ pullRequest: Schema.NullOr(PullRequestActionSummary)
664
})
665
export interface ClosePullRequestPayload extends Schema.Struct.Type<typeof ClosePullRequestPayload.fields> {}
666
@@ -589,9 +671,11 @@ export const ClosePullRequest = GraphQL.mutation("ClosePullRequest", {
671
{ name: "pullRequestId", body: "ID!" }
672
],
673
selections: [
592
- { name: "closePullRequest", body: ["(input:{pullRequestId:$", "pullRequestId", "}){clientMutationId}"] }
674
+ { name: "closePullRequest", body: ["(input:{pullRequestId:$", "pullRequestId", "}){pullRequest{...PullRequestActionSummary}}"] }
675
],
594
- fragments: []
676
+ fragments: [
677
+ { name: "PullRequestActionSummary", body: ["on PullRequest{number title url headRefName baseRefName state isDraft updatedAt mergedAt closedAt headRefOid author{__typename login avatarUrl...on User{name}}autoMergeRequest{mergeMethod}}"] }
678
+ ]
679
},
680
variables: {
681
pullRequestId: Shared.ID
@@ -608,8 +692,8 @@ export declare namespace ClosePullRequest {
692
693
/** Autogenerated return type of ReopenPullRequest. */
694
export const ReopenPullRequestPayload = Schema.Struct({
611
- /** A unique identifier for the client performing the mutation. */
612
- clientMutationId: Schema.NullOr(Schema.String)
695
+ /** The pull request that was reopened. */
696
+ pullRequest: Schema.NullOr(PullRequestActionSummary)
697
})
698
export interface ReopenPullRequestPayload extends Schema.Struct.Type<typeof ReopenPullRequestPayload.fields> {}
699
@@ -620,9 +704,11 @@ export const ReopenPullRequest = GraphQL.mutation("ReopenPullRequest", {
704
{ name: "pullRequestId", body: "ID!" }
705
],
706
selections: [
623
- { name: "reopenPullRequest", body: ["(input:{pullRequestId:$", "pullRequestId", "}){clientMutationId}"] }
707
+ { name: "reopenPullRequest", body: ["(input:{pullRequestId:$", "pullRequestId", "}){pullRequest{...PullRequestActionSummary}}"] }
708
],
625
- fragments: []
709
+ fragments: [
710
+ { name: "PullRequestActionSummary", body: ["on PullRequest{number title url headRefName baseRefName state isDraft updatedAt mergedAt closedAt headRefOid author{__typename login avatarUrl...on User{name}}autoMergeRequest{mergeMethod}}"] }
711
+ ]
712
},
713
variables: {
714
pullRequestId: Shared.ID
packages/source-control-github/src/server/pullRequestReads.graphql
+1
@@ -156,6 +156,7 @@ query PullRequestCore(
156
}
157
pageInfo {
158
hasNextPage
159
+ endCursor
160
}
161
}
162
}
packages/source-control-github/src/server/pullRequestReads.graphql.ts
+29
-66
@@ -310,32 +310,34 @@ export const PullRequestCoreRepositoryPullRequestLabelsLabelConnection = Schema.
310
export interface PullRequestCoreRepositoryPullRequestLabelsLabelConnection extends Schema.Struct.Type<typeof PullRequestCoreRepositoryPullRequestLabelsLabelConnection.fields> {}
311
312
/** Information about pagination in a connection. */
313
-export const PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo = Schema.Struct({
313
+export const ContextsPageInfoPageInfo = Schema.Struct({
314
/** When paginating forwards, are there more items? */
315
- hasNextPage: Schema.Boolean
315
+ hasNextPage: Schema.Boolean,
316
+ /** When paginating forwards, the cursor to continue. */
317
+ endCursor: Schema.NullOr(Schema.String)
318
})
317
-export interface PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo extends Schema.Struct.Type<typeof PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo.fields> {}
319
+export interface ContextsPageInfoPageInfo extends Schema.Struct.Type<typeof ContextsPageInfoPageInfo.fields> {}
320
321
/** The connection type for StatusCheckRollupContext. */
320
-export const PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsStatusCheckRollupContextConnection = Schema.Struct({
322
+export const StatusCheckRollupContextConnection = Schema.Struct({
323
/** A list of nodes. */
324
nodes: Schema.NullOr(Schema.Array(Schema.NullOr(CheckContext))),
325
/** Information to aid in pagination. */
324
- pageInfo: PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo
326
+ pageInfo: ContextsPageInfoPageInfo
327
})
326
-export interface PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsStatusCheckRollupContextConnection extends Schema.Struct.Type<typeof PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsStatusCheckRollupContextConnection.fields> {}
328
+export interface StatusCheckRollupContextConnection extends Schema.Struct.Type<typeof StatusCheckRollupContextConnection.fields> {}
329
330
/** Represents the rollup for both the check runs and status for a commit. */
329
-export const PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupStatusCheckRollup = Schema.Struct({
331
+export const StatusCheckRollup = Schema.Struct({
332
/** A list of status contexts and check runs for this commit. */
331
- contexts: PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsStatusCheckRollupContextConnection
333
+ contexts: StatusCheckRollupContextConnection
334
})
333
-export interface PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupStatusCheckRollup extends Schema.Struct.Type<typeof PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupStatusCheckRollup.fields> {}
335
+export interface StatusCheckRollup extends Schema.Struct.Type<typeof StatusCheckRollup.fields> {}
336
337
/** Represents a Git commit. */
338
export const PullRequestCoreRepositoryPullRequestCommitsNodesCommitCommit = Schema.Struct({
339
/** Check and Status rollup information for this commit. */
338
- statusCheckRollup: Schema.NullOr(PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupStatusCheckRollup)
340
+ statusCheckRollup: Schema.NullOr(StatusCheckRollup)
341
})
342
export interface PullRequestCoreRepositoryPullRequestCommitsNodesCommitCommit extends Schema.Struct.Type<typeof PullRequestCoreRepositoryPullRequestCommitsNodesCommitCommit.fields> {}
343
@@ -459,7 +461,7 @@ export const PullRequestCore = GraphQL.query("PullRequestCore", {
461
{ name: "requestedReviewers", body: "Int!" }
462
],
463
selections: [
462
- { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed autoMergeAllowed viewerPermission pullRequest(number:$", "number", "){number title url body state isDraft mergeable mergeStateStatus reviewDecision additions deletions changedFiles createdAt updatedAt mergedAt closedAt headRefName baseRefName headRefOid isCrossRepository maintainerCanModify headRepositoryOwner{__typename login}headRepository{nameWithOwner viewerPermission}headRef{id}author{__typename login avatarUrl...on User{id name}}autoMergeRequest{mergeMethod}viewerCanUpdate viewerDidAuthor viewerCanUpdateBranch baseRef{compare(headRef:$", "headRef", "){behindBy}}reviewRequests(first:$", "requestedReviewers", "){nodes{requestedReviewer{__typename...on User{login name}...on Bot{login}...on Team{slug combinedSlug teamName:name teamAvatarUrl:avatarUrl}}}}labels(first:100){nodes{name color}}commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage}}}}}}}}"] }
464
+ { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed autoMergeAllowed viewerPermission pullRequest(number:$", "number", "){number title url body state isDraft mergeable mergeStateStatus reviewDecision additions deletions changedFiles createdAt updatedAt mergedAt closedAt headRefName baseRefName headRefOid isCrossRepository maintainerCanModify headRepositoryOwner{__typename login}headRepository{nameWithOwner viewerPermission}headRef{id}author{__typename login avatarUrl...on User{id name}}autoMergeRequest{mergeMethod}viewerCanUpdate viewerDidAuthor viewerCanUpdateBranch baseRef{compare(headRef:$", "headRef", "){behindBy}}reviewRequests(first:$", "requestedReviewers", "){nodes{requestedReviewer{__typename...on User{login name}...on Bot{login}...on Team{slug combinedSlug teamName:name teamAvatarUrl:avatarUrl}}}}labels(first:100){nodes{name color}}commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] }
465
],
466
fragments: [
467
{ name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{workflow{name}}}}}"] }
@@ -483,58 +485,12 @@ export declare namespace PullRequestCore {
485
export type Result = typeof PullRequestCore.result.Type
486
}
487
486
-/** Information about pagination in a connection. */
487
-export const PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo = Schema.Struct({
488
- /** When paginating forwards, are there more items? */
489
- hasNextPage: Schema.Boolean,
490
- /** When paginating forwards, the cursor to continue. */
491
- endCursor: Schema.NullOr(Schema.String)
492
-})
493
-export interface PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo extends Schema.Struct.Type<typeof PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo.fields> {}
494
-
495
-/** The connection type for StatusCheckRollupContext. */
496
-export const PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsStatusCheckRollupContextConnection = Schema.Struct({
497
- /** A list of nodes. */
498
- nodes: Schema.NullOr(Schema.Array(Schema.NullOr(CheckContext))),
499
- /** Information to aid in pagination. */
500
- pageInfo: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo
501
-})
502
-export interface PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsStatusCheckRollupContextConnection extends Schema.Struct.Type<typeof PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsStatusCheckRollupContextConnection.fields> {}
503
-
504
-/** Represents the rollup for both the check runs and status for a commit. */
505
-export const PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupStatusCheckRollup = Schema.Struct({
506
- /** A list of status contexts and check runs for this commit. */
507
- contexts: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsStatusCheckRollupContextConnection
508
-})
509
-export interface PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupStatusCheckRollup extends Schema.Struct.Type<typeof PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupStatusCheckRollup.fields> {}
510
-
511
-/** Represents a Git commit. */
512
-export const PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitCommit = Schema.Struct({
513
- /** Check and Status rollup information for this commit. */
514
- statusCheckRollup: Schema.NullOr(PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupStatusCheckRollup)
515
-})
516
-export interface PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitCommit extends Schema.Struct.Type<typeof PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitCommit.fields> {}
517
-
518
-/** Represents a Git commit part of a pull request. */
519
-export const PullRequestCheckContextsRepositoryPullRequestCommitsNodesPullRequestCommit = Schema.Struct({
520
- /** The Git commit object */
521
- commit: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitCommit
522
-})
523
-export interface PullRequestCheckContextsRepositoryPullRequestCommitsNodesPullRequestCommit extends Schema.Struct.Type<typeof PullRequestCheckContextsRepositoryPullRequestCommitsNodesPullRequestCommit.fields> {}
524
-
525
-/** The connection type for PullRequestCommit. */
526
-export const PullRequestCheckContextsRepositoryPullRequestCommitsPullRequestCommitConnection = Schema.Struct({
527
- /** A list of nodes. */
528
- nodes: Schema.NullOr(Schema.Array(Schema.NullOr(PullRequestCheckContextsRepositoryPullRequestCommitsNodesPullRequestCommit)))
529
-})
530
-export interface PullRequestCheckContextsRepositoryPullRequestCommitsPullRequestCommitConnection extends Schema.Struct.Type<typeof PullRequestCheckContextsRepositoryPullRequestCommitsPullRequestCommitConnection.fields> {}
531
-
488
/** A repository pull request. */
489
export const PullRequestCheckContextsRepositoryPullRequestPullRequest = Schema.Struct({
490
/** Identifies the oid of the head ref associated with the pull request, even if the ref has been deleted. */
491
headRefOid: Shared.GitObjectID,
492
/** A list of commits present in this pull request's head branch not present in the base branch. */
537
- commits: PullRequestCheckContextsRepositoryPullRequestCommitsPullRequestCommitConnection
493
+ commits: PullRequestCoreRepositoryPullRequestCommitsPullRequestCommitConnection
494
})
495
export interface PullRequestCheckContextsRepositoryPullRequestPullRequest extends Schema.Struct.Type<typeof PullRequestCheckContextsRepositoryPullRequestPullRequest.fields> {}
496
@@ -737,7 +693,7 @@ export interface NodesIssueComment extends Schema.Struct.Type<typeof NodesIssueC
693
/** The connection type for IssueComment. */
694
export const IssueCommentConnection = Schema.Struct({
695
/** Information to aid in pagination. */
740
- pageInfo: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
696
+ pageInfo: ContextsPageInfoPageInfo,
697
/** A list of nodes. */
698
nodes: Schema.NullOr(Schema.Array(Schema.NullOr(NodesIssueComment)))
699
})
@@ -768,7 +724,7 @@ export interface NodesPullRequestReview extends Schema.Struct.Type<typeof NodesP
724
/** The connection type for PullRequestReview. */
725
export const PullRequestReviewConnection = Schema.Struct({
726
/** Information to aid in pagination. */
771
- pageInfo: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
727
+ pageInfo: ContextsPageInfoPageInfo,
728
/** A list of nodes. */
729
nodes: Schema.NullOr(Schema.Array(Schema.NullOr(NodesPullRequestReview)))
730
})
@@ -896,7 +852,7 @@ export interface NodesPullRequest extends Schema.Struct.Type<typeof NodesPullReq
852
/** The connection type for PullRequest. */
853
export const PullRequestConnection = Schema.Struct({
854
/** Information to aid in pagination. */
899
- pageInfo: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
855
+ pageInfo: ContextsPageInfoPageInfo,
856
/** A list of nodes. */
857
nodes: Schema.NullOr(Schema.Array(Schema.NullOr(NodesPullRequest)))
858
})
@@ -1123,6 +1079,13 @@ export declare namespace ViewerPermissions {
1079
export type Result = typeof ViewerPermissions.result.Type
1080
}
1081
1082
+/** Information about pagination in a connection. */
1083
+export const AssignableUsersPageInfoPageInfo = Schema.Struct({
1084
+ /** When paginating forwards, are there more items? */
1085
+ hasNextPage: Schema.Boolean
1086
+})
1087
+export interface AssignableUsersPageInfoPageInfo extends Schema.Struct.Type<typeof AssignableUsersPageInfoPageInfo.fields> {}
1088
+
1089
/** A user is an individual's account on GitHub that owns repositories and can make new content. */
1090
export const AssignableUsersNodesUser = Schema.Struct({
1091
/** The username used to login. */
@@ -1137,7 +1100,7 @@ export interface AssignableUsersNodesUser extends Schema.Struct.Type<typeof Assi
1100
/** A list of users. */
1101
export const UserConnection = Schema.Struct({
1102
/** Information to aid in pagination. */
1140
- pageInfo: PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
1103
+ pageInfo: AssignableUsersPageInfoPageInfo,
1104
/** A list of nodes. */
1105
nodes: Schema.NullOr(Schema.Array(Schema.NullOr(AssignableUsersNodesUser)))
1106
})
@@ -1230,7 +1193,7 @@ export interface RepositoryLabelsNodesLabel extends Schema.Struct.Type<typeof Re
1193
/** The connection type for Label. */
1194
export const LabelCandidatesRepositoryLabelsLabelConnection = Schema.Struct({
1195
/** Information to aid in pagination. */
1233
- pageInfo: PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
1196
+ pageInfo: AssignableUsersPageInfoPageInfo,
1197
/** A list of nodes. */
1198
nodes: Schema.NullOr(Schema.Array(Schema.NullOr(RepositoryLabelsNodesLabel)))
1199
})
@@ -1297,7 +1260,7 @@ export declare namespace LabelCandidates {
1260
/** The connection type for Label. */
1261
export const RepositoryLabelsRepositoryLabelsLabelConnection = Schema.Struct({
1262
/** Information to aid in pagination. */
1300
- pageInfo: PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
1263
+ pageInfo: AssignableUsersPageInfoPageInfo,
1264
/** A list of nodes. */
1265
nodes: Schema.NullOr(Schema.Array(Schema.NullOr(PullRequestCoreRepositoryPullRequestLabelsNodesLabel)))
1266
})
@@ -1385,7 +1348,7 @@ export interface PullRequestFilesViewedRepositoryPullRequestFilesNodesPullReques
1348
/** The connection type for PullRequestChangedFile. */
1349
export const PullRequestFilesViewedRepositoryPullRequestFilesPullRequestChangedFileConnection = Schema.Struct({
1350
/** Information to aid in pagination. */
1388
- pageInfo: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
1351
+ pageInfo: ContextsPageInfoPageInfo,
1352
/** A list of nodes. */
1353
nodes: Schema.NullOr(Schema.Array(Schema.NullOr(PullRequestFilesViewedRepositoryPullRequestFilesNodesPullRequestChangedFile)))
1354
})
@@ -1449,7 +1412,7 @@ export interface PullRequestFileStatsRepositoryPullRequestFilesNodesPullRequestC
1412
/** The connection type for PullRequestChangedFile. */
1413
export const PullRequestFileStatsRepositoryPullRequestFilesPullRequestChangedFileConnection = Schema.Struct({
1414
/** Information to aid in pagination. */
1452
- pageInfo: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
1415
+ pageInfo: ContextsPageInfoPageInfo,
1416
/** A list of nodes. */
1417
nodes: Schema.NullOr(Schema.Array(Schema.NullOr(PullRequestFileStatsRepositoryPullRequestFilesNodesPullRequestChangedFile)))
1418
})
packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+15
-3
@@ -64,6 +64,7 @@ import {
64
type GitLabProjectUsers,
65
} from "./gitLabMergeRequestJson.ts";
66
import type {
67
+ ProviderChangeRequestSummary,
68
ProviderFileStats,
69
ProviderListCursor,
70
} from "@t3tools/source-control-core/server/PullRequestProvider";
@@ -390,7 +391,7 @@ export class GitLabPullRequestCli extends Context.Service<
391
readonly action: PullRequestAction;
392
readonly mergeMethod?: PullRequestMergeMethod;
393
readonly removeAgentCreditsOnMerge?: boolean;
393
- }) => Effect.Effect<void, GitLabPullRequestCliError>;
394
+ }) => Effect.Effect<ProviderChangeRequestSummary | void, GitLabPullRequestCliError>;
395
396
readonly updateMergeRequest: (input: {
397
readonly cwd: string;
@@ -1655,12 +1656,23 @@ export const make = Effect.gen(function* () {
1656
// no flag for is asked of GitLab directly through the same `api` passthrough the rest of
1657
// this module writes with.
1658
if (input.action === "disable-auto-merge") {
1658
- return yield* api({
1659
+ const result = yield* api({
1660
cwd: input.cwd,
1661
host: input.host,
1662
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/cancel_merge_when_pipeline_succeeds`,
1663
method: "POST",
1663
- }).pipe(Effect.asVoid);
1664
+ });
1665
+ // The other actions run `glab mr`, which prints prose rather than the merge request.
1666
+ const decoded = decodeMergeRequestDetailJson(result.stdout.trim());
1667
+ if (Result.isFailure(decoded)) return;
1668
+ // The decoder fills absent counts with zeros, which would be guesses here.
1669
+ const {
1670
+ additions: _additions,
1671
+ deletions: _deletions,
1672
+ changedFiles: _changedFiles,
1673
+ ...summary
1674
+ } = decoded.success;
1675
+ return summary;
1676
}
1677
const executeMr = (subcommand: string, ...flags: ReadonlyArray<string>) =>
1678
gitlab.execute({