Skip to content
TypeScript

perf(pr): actions update every client from the host's reply instead of re-reads (#25761)

Bilal Bakre1494ae25b78
diff --git a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx
index cc09ac5c5d6..2d0414b5036 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx
@@ -162,7 +162,7 @@ export function PullRequestMergeControls(props: {
},
});
// A stack can partly merge before the provider reports a failure.
- refreshDetail();
+ if (!AsyncResult.isSuccess(response)) refreshDetail();
refreshActivity();
stack.refresh();
pending.current = false;
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestAction.ts b/apps/mobile/src/features/pull-requests/usePullRequestAction.ts
index 4658330dd6c..676937b9282 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestAction.ts
+++ b/apps/mobile/src/features/pull-requests/usePullRequestAction.ts
@@ -19,7 +19,6 @@ export function usePullRequestAction(params: PullRequestParams, pr: PullRequestD
const target = pullRequestTarget(params);
const permissions = usePullRequestPermissions(params, pr);
const run = useAtomCommand(composerPullRequests.runAction, { reportFailure: false });
- const refreshDetail = useAtomRefresh(composerPullRequests.detail(target));
const refreshActivity = useAtomRefresh(composerPullRequests.activity(target));
const pending = useRef(false);
const [busy, setBusy] = useState(false);
@@ -43,7 +42,6 @@ export function usePullRequestAction(params: PullRequestParams, pr: PullRequestD
);
return;
}
- refreshDetail();
refreshActivity();
};
const confirm = (action: PullRequestAction, title: string, message: string) =>
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestListActions.ts b/apps/mobile/src/features/pull-requests/usePullRequestListActions.ts
index c7cfe62f43b..8a81ef6d73c 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestListActions.ts
+++ b/apps/mobile/src/features/pull-requests/usePullRequestListActions.ts
@@ -94,6 +94,7 @@ export function usePullRequestListActions(
throw new Error(`This action isn't available for this ${terminology.singular}.`);
const result = await run({ ...target, input: { ...target.input, action } });
if (result._tag === "Failure") throw squashAtomCommandFailure(result);
+ if (result.value !== undefined) return;
onChanged(
entry,
action === "close"
diff --git a/apps/mobile/src/state/pull-requests.ts b/apps/mobile/src/state/pull-requests.ts
index 96fd3b6a729..6d7872fa560 100644
--- a/apps/mobile/src/state/pull-requests.ts
+++ b/apps/mobile/src/state/pull-requests.ts
@@ -1,6 +1,7 @@
import {
createPullRequestEnvironmentAtoms,
createPullRequestStackAtomFamily,
+ patchPullRequestListEntries,
} from "@t3tools/client-runtime/state/pull-requests";
import type { EnvironmentId, PullRequestListInput } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
@@ -21,10 +22,17 @@ export const pullRequestListPagesKey = (target: {
readonly input: PullRequestListInput;
}) => JSON.stringify([target.environmentId, target.input]);
+// Which listing each pages atom holds, so an action's reply can reach the pages past its head.
+const pullRequestListPagesTargets = new WeakMap<
+ object,
+ readonly [EnvironmentId, PullRequestListInput]
+>();
/** The pages loaded past each listing's head, keyed by {@link pullRequestListPagesKey}. */
-export const pullRequestListPagesFamily = Atom.family((_key: string) =>
- Atom.make<PullRequestListPages | null>(null).pipe(Atom.setIdleTTL(5 * 60_000)),
-);
+export const pullRequestListPagesFamily = Atom.family((key: string) => {
+ const atom = Atom.make<PullRequestListPages | null>(null).pipe(Atom.setIdleTTL(5 * 60_000));
+ pullRequestListPagesTargets.set(atom, JSON.parse(key));
+ return atom;
+});
/** Diff stats each environment has answered so far, so rows keep them when they scroll away. */
export const pullRequestListStatsFamily = Atom.family((_environmentId: string) =>
@@ -34,6 +42,25 @@ export const pullRequestListStatsFamily = Atom.family((_environmentId: string) =
);
export const composerPullRequests = createPullRequestEnvironmentAtoms(connectionAtomRuntime, {
+ // Rows on pages past each listing's head; the head itself is patched where it is cached.
+ actionReply: (target, reply, registry) =>
+ Effect.sync(() => {
+ for (const atom of registry.getNodes().keys()) {
+ const listing =
+ typeof atom === "string" ? undefined : pullRequestListPagesTargets.get(atom);
+ if (listing === undefined || listing[0] !== target.environmentId) continue;
+ registry.update(atom as Atom.Writable<PullRequestListPages | null>, (pages) => {
+ if (pages === null) return pages;
+ const entries = patchPullRequestListEntries(
+ listing[1],
+ pages.entries,
+ target.input,
+ reply,
+ );
+ return entries === "refresh" || entries === pages.entries ? pages : { ...pages, entries };
+ });
+ }
+ }),
// A new head can change which files GitHub still counts as viewed, so the viewed-files read is
// refreshed where the new head lands. The detail atom still holds the previous answer here.
detail: (target, value, registry) =>
diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts
index 50581506ea1..279642674b7 100644
--- a/apps/server/src/pullRequest/PullRequestService.test.ts
+++ b/apps/server/src/pullRequest/PullRequestService.test.ts
@@ -1239,7 +1239,7 @@ it.effect("publishes a merge for immediate settlement only after host confirmati
detail: "HTTP 504",
}),
)
- : Effect.succeed({ ...changeRequest(1, mergedAt), state }),
+ : Effect.succeed({ ...changeRequest(1, mergedAt), state, mergedAt }),
}),
],
});
@@ -1248,7 +1248,7 @@ it.effect("publishes a merge for immediate settlement only after host confirmati
Effect.forkChild({ startImmediately: true }),
);
- yield* service.runAction({ ...reference, action: "merge" });
+ assert.isUndefined(yield* service.runAction({ ...reference, action: "merge" }));
const queuedRefresh = Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes));
confirmationFails = true;
yield* service.runAction({ ...reference, action: "merge" });
@@ -1258,7 +1258,8 @@ it.effect("publishes a merge for immediate settlement only after host confirmati
);
confirmationFails = false;
state = "merged";
- yield* TestClock.setTime(Date.parse(mergedAt));
+ // The event carries the host's merge time, not the moment the confirmation ran.
+ yield* TestClock.setTime(Date.parse(mergedAt) + 60_000);
yield* service.runAction({
...reference,
repository: " ACME/WEB ",
@@ -1274,6 +1275,71 @@ it.effect("publishes a merge for immediate settlement only after host confirmati
),
);
+it.effect("returns the host's merged reply as a summary and trusts it without another read", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const mergedAt = "2026-09-03T02:00:00.000Z";
+ const merged = {
+ number: 1,
+ title: "Change request 1",
+ url: "https://host/pull/1",
+ headBranch: "feat/1",
+ baseBranch: "main",
+ state: "merged" as const,
+ isDraft: false,
+ updatedAt: mergedAt,
+ mergedAt,
+ headSha: "abc123",
+ autoMergeEnabled: false,
+ };
+ let summaryReads = 0;
+ const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
+ const service = yield* makeService({
+ projects: [
+ project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
+ ],
+ providers: [
+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {
+ runAction: () => Effect.succeed(merged),
+ getChangeRequestSummary: () =>
+ Effect.sync(() => {
+ summaryReads++;
+ return { ...changeRequest(1, mergedAt), state: "merged" as const, mergedAt };
+ }),
+ }),
+ ],
+ });
+ const merges = yield* service.subscribeMerges;
+ const observedMerge = yield* Stream.runHead(merges).pipe(
+ Effect.forkChild({ startImmediately: true }),
+ );
+ const observedAt = Date.parse("2026-09-03T02:00:01.000Z");
+ yield* TestClock.setTime(observedAt);
+
+ // Clients that did not ask decode the success as void, so they must get nothing back.
+ assert.isUndefined(yield* service.runAction({ ...reference, action: "merge" }));
+ const result = yield* service.runAction({
+ ...reference,
+ action: "merge",
+ replyWithSummary: true,
+ });
+
+ assert.deepStrictEqual(result, {
+ ...merged,
+ provider: SourceControlProviderKind.make("github"),
+ projectId: reference.projectId,
+ repository: reference.repository,
+ observedAt,
+ });
+ assert.strictEqual(summaryReads, 0);
+ assert.deepStrictEqual(Option.getOrThrow(yield* Fiber.join(observedMerge)), {
+ ...reference,
+ mergedAt,
+ });
+ }),
+ ),
+);
+
it.effect("refreshes every reader before a queued merge confirmation finishes", () =>
Effect.scoped(
Effect.gen(function* () {
diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts
index 304ce2d3fa5..89986c7fa78 100644
--- a/apps/server/src/pullRequest/PullRequestService.ts
+++ b/apps/server/src/pullRequest/PullRequestService.ts
@@ -86,9 +86,11 @@ import type { SourceControlProviderContext } from "@t3tools/source-control-core/
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
import {
type ProviderChangeRequest,
+ type ProviderChangeRequestDetail,
type ProviderDiffFilePaths,
type ProviderFilterOptionPage,
type ProviderListCursor,
+ type ProviderChangeRequestSummary,
type ProviderChangeRequestWatchFingerprint,
type PullRequestProviderApi,
PullRequestProviderError,
@@ -250,7 +252,9 @@ export class PullRequestService extends Context.Service<
readonly changeBreakdown: (
input: PullRequestRef,
) => Effect.Effect<PullRequestChangeBreakdown, PullRequestError>;
- readonly runAction: (input: PullRequestActionInput) => Effect.Effect<void, PullRequestError>;
+ readonly runAction: (
+ input: PullRequestActionInput,
+ ) => Effect.Effect<PullRequestSummary | undefined, PullRequestError>;
readonly update: (input: PullRequestUpdateInput) => Effect.Effect<void, PullRequestError>;
readonly comment: (input: PullRequestCommentInput) => Effect.Effect<void, PullRequestError>;
readonly updateComment: (
@@ -1663,6 +1667,54 @@ export const make = Effect.gen(function* () {
};
});
+ const toSummary = (
+ project: SupportedProject,
+ changeRequest: ProviderChangeRequestSummary | ProviderChangeRequestDetail,
+ observedAt: number,
+ reply = false,
+ ): PullRequestSummary => ({
+ provider: project.api.kind,
+ projectId: project.project.id,
+ repository: project.repository,
+ number: changeRequest.number,
+ title: changeRequest.title,
+ url: changeRequest.url,
+ state: changeRequest.state,
+ headBranch: changeRequest.headBranch,
+ baseBranch: changeRequest.baseBranch,
+ // An action reply may not carry these, and null would erase a time a client already holds.
+ ...(changeRequest.closedAt === undefined && reply
+ ? {}
+ : { closedAt: changeRequest.closedAt ?? null }),
+ ...(changeRequest.mergedAt === undefined && reply
+ ? {}
+ : { mergedAt: changeRequest.mergedAt ?? null }),
+ updatedAt: changeRequest.updatedAt,
+ observedAt,
+ ...(changeRequest.isDraft === undefined ? {} : { isDraft: changeRequest.isDraft }),
+ ...(changeRequest.author === undefined ? {} : { author: changeRequest.author }),
+ ...(changeRequest.additions === undefined ? {} : { additions: changeRequest.additions }),
+ ...(changeRequest.deletions === undefined ? {} : { deletions: changeRequest.deletions }),
+ ...(changeRequest.changedFiles === undefined
+ ? {}
+ : { changedFiles: changeRequest.changedFiles }),
+ ...(changeRequest.reviewDecision === undefined
+ ? {}
+ : { reviewDecision: changeRequest.reviewDecision }),
+ ...(changeRequest.checksState === undefined ? {} : { checksState: changeRequest.checksState }),
+ ...(changeRequest.mergeability === undefined
+ ? {}
+ : { mergeability: changeRequest.mergeability }),
+ ...(changeRequest.stack === undefined ? {} : { stack: changeRequest.stack }),
+ ...(changeRequest.headSha?.trim() ? { headSha: changeRequest.headSha.trim() } : {}),
+ ...(changeRequest.autoMergeEnabled === undefined
+ ? {}
+ : { autoMergeEnabled: changeRequest.autoMergeEnabled }),
+ ...(changeRequest.autoMergeMethod === undefined
+ ? {}
+ : { autoMergeMethod: changeRequest.autoMergeMethod }),
+ });
+
const summaryUncached: PullRequestService["Service"]["summary"] = (input) =>
requireProject(input).pipe(
Effect.flatMap((project) => {
@@ -1672,49 +1724,17 @@ export const make = Effect.gen(function* () {
host: project.host,
number: input.number,
};
- const read =
+ const read: Effect.Effect<
+ ProviderChangeRequestSummary | ProviderChangeRequestDetail,
+ PullRequestProviderError
+ > =
project.api.getChangeRequestSummary === undefined
? project.api.getChangeRequest(providerInput)
: project.api.getChangeRequestSummary(providerInput);
return read.pipe(
Effect.mapError(toPullRequestError("summary")),
observeRead,
- Effect.map(({ value: changeRequest, observedAt }): PullRequestSummary => ({
- provider: project.api.kind,
- projectId: project.project.id,
- repository: project.repository,
- number: changeRequest.number,
- title: changeRequest.title,
- url: changeRequest.url,
- state: changeRequest.state,
- headBranch: changeRequest.headBranch,
- baseBranch: changeRequest.baseBranch,
- closedAt: changeRequest.closedAt ?? null,
- mergedAt: changeRequest.mergedAt ?? null,
- updatedAt: changeRequest.updatedAt,
- observedAt,
- ...(changeRequest.isDraft === undefined ? {} : { isDraft: changeRequest.isDraft }),
- ...(changeRequest.author === undefined ? {} : { author: changeRequest.author }),
- ...(changeRequest.additions === undefined
- ? {}
- : { additions: changeRequest.additions }),
- ...(changeRequest.deletions === undefined
- ? {}
- : { deletions: changeRequest.deletions }),
- ...(changeRequest.changedFiles === undefined
- ? {}
- : { changedFiles: changeRequest.changedFiles }),
- ...(changeRequest.reviewDecision === undefined
- ? {}
- : { reviewDecision: changeRequest.reviewDecision }),
- ...(changeRequest.checksState === undefined
- ? {}
- : { checksState: changeRequest.checksState }),
- ...(changeRequest.mergeability === undefined
- ? {}
- : { mergeability: changeRequest.mergeability }),
- ...(changeRequest.stack === undefined ? {} : { stack: changeRequest.stack }),
- })),
+ Effect.map(({ value, observedAt }) => toSummary(project, value, observedAt)),
);
}),
);
@@ -1988,9 +2008,15 @@ export const make = Effect.gen(function* () {
),
);
- const runAction = (input: PullRequestActionInput): Effect.Effect<string, PullRequestError> =>
+ type ActionOutcome = {
+ readonly repository: string;
+ readonly summary: PullRequestSummary | undefined;
+ };
+ const runAction = (
+ input: PullRequestActionInput,
+ ): Effect.Effect<ActionOutcome, PullRequestError> =>
requireProject(input).pipe(
- Effect.flatMap((project): Effect.Effect<string, PullRequestError> => {
+ Effect.flatMap((project): Effect.Effect<ActionOutcome, PullRequestError> => {
if (input.action === "delete-branch" && project.api.capabilities.deleteBranch !== true) {
return Effect.fail(
new PullRequestOperationError({
@@ -2050,7 +2076,7 @@ export const make = Effect.gen(function* () {
"runAction",
input.action === "update-branch",
).pipe(
- Effect.flatMap((viewer): Effect.Effect<string, PullRequestError> => {
+ Effect.flatMap((viewer): Effect.Effect<ActionOutcome, PullRequestError> => {
const stackRebase = input.stackNumber !== undefined && input.action === "update-branch";
if (
stackRebase ? viewer.stackRebase !== true : !viewer.actions.includes(input.action)
@@ -2119,9 +2145,17 @@ export const make = Effect.gen(function* () {
: refreshAfterTurn(project.project.id),
),
Effect.mapError(toPullRequestError("runAction")),
- Effect.as(
- project.repositoryKey !== null ? input.repository.trim() : project.repository,
- ),
+ observeRead,
+ Effect.map(({ value, observedAt }) => ({
+ repository:
+ project.repositoryKey !== null
+ ? input.repository.trim()
+ : project.repository,
+ summary:
+ value === undefined || input.stackNumber !== undefined
+ ? undefined
+ : toSummary(project, value, observedAt, true),
+ })),
),
),
);
@@ -3571,7 +3605,7 @@ export const make = Effect.gen(function* () {
)(function* (input) {
const ref = yield* canonicalRef(input);
yield* readCache.invalidate(refScope(ref));
- const repository = yield* runAction(input).pipe(
+ const { repository, summary } = yield* runAction(input).pipe(
Effect.ensuring(readCache.invalidate(refScope(ref))),
);
bumpRefEpoch({ ...ref, repository });
@@ -3579,21 +3613,28 @@ export const make = Effect.gen(function* () {
yield* SubscriptionRef.set(pullRequestRefreshes, listingsEpoch);
if (input.action === "merge") {
// A successful merge action can merely enqueue the PR or enable auto-merge.
- const confirmed = yield* summaryUncached({ ...input, repository }).pipe(
- Effect.catch((error) =>
- Effect.logWarning("failed to confirm pull request merge", { error }).pipe(
- Effect.as(null),
- ),
- ),
- );
- if (confirmed?.state !== "merged") return;
- yield* PubSub.publish(mergedPullRequests, {
- projectId: input.projectId,
- repository,
- number: input.number,
- mergedAt: DateTime.formatIso(yield* DateTime.now),
- });
+ const merged = summary?.state === "merged" ? summary : null;
+ const confirmed =
+ merged?.mergedAt != null
+ ? merged
+ : yield* summaryUncached({ ...input, repository }).pipe(
+ Effect.map((reread) => (reread.state === "merged" ? reread : merged)),
+ Effect.catch((error) =>
+ Effect.logWarning("failed to confirm pull request merge", { error }).pipe(
+ Effect.as(merged),
+ ),
+ ),
+ );
+ if (confirmed?.state === "merged") {
+ yield* PubSub.publish(mergedPullRequests, {
+ projectId: input.projectId,
+ repository,
+ number: input.number,
+ mergedAt: confirmed.mergedAt ?? DateTime.formatIso(yield* DateTime.now),
+ });
+ }
}
+ return input.replyWithSummary === true ? summary : undefined;
});
const credentialCached =
diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx
index 8c3f8144279..5a9b20586a2 100644
--- a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx
+++ b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx
@@ -163,7 +163,6 @@ export function ThreadDetailsPrRow({
reference,
terminology,
onSuccess: () => {
- detailQuery.refresh();
checksQuery.refresh();
onActed?.();
},
diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
index c70a424ed1a..8510503e499 100644
--- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
@@ -22,6 +22,7 @@ import {
type PullRequestUpdateMethod,
type PullRequestRef,
type PullRequestReviewGuideStop,
+ type PullRequestSummary,
resolveEnvironmentMachineKind,
type ScopedThreadRef,
} from "@t3tools/contracts";
@@ -292,7 +293,11 @@ export function PullRequestDetailPanel({
* notification can switch it.
*/
tabOnPage?: boolean;
- onActed?: (action?: PullRequestAction, phase?: "sent" | "done" | "failed") => void;
+ onActed?: (
+ action?: PullRequestAction,
+ phase?: "sent" | "done" | "failed",
+ reply?: PullRequestSummary,
+ ) => void;
onClose?: () => void;
context?: "page" | "thread";
composerDraftTarget?: ScopedThreadRef | DraftId;
@@ -697,9 +702,11 @@ export function PullRequestDetailPanel({
if (pullRequestActionNeedsHostRefresh(action)) {
void refreshFromHost();
} else {
- refreshDetail();
+ // The action command already showed the reply in the detail or re-read it.
+ activityQuery.refresh();
+ nativeStackQuery.refresh();
}
- onActed?.(action, "done");
+ onActed?.(action, "done", result.value);
return true;
};
diff --git a/apps/web/src/components/pullRequest/PullRequestSpeedActions.tsx b/apps/web/src/components/pullRequest/PullRequestSpeedActions.tsx
index 53f8af15ead..38d054d7c0e 100644
--- a/apps/web/src/components/pullRequest/PullRequestSpeedActions.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestSpeedActions.tsx
@@ -1,5 +1,5 @@
import { useAtomValue } from "@effect/atom-react";
-import type { PullRequestAction } from "@t3tools/contracts";
+import type { PullRequestAction, PullRequestSummary } from "@t3tools/contracts";
import { createContext, use, type ReactNode } from "react";
import type { ChangeRequestTerminology } from "@t3tools/client-runtime/source-control-clients";
@@ -25,6 +25,7 @@ type PullRequestSpeedActionEntry = Pick<
export interface PullRequestSpeedActionResult<Entry = EnvironmentPullRequestEntry> {
readonly entry: Entry;
readonly action: PullRequestAction;
+ readonly reply?: PullRequestSummary | undefined;
}
export function PullRequestSpeedActions<Entry extends PullRequestSpeedActionEntry>({
@@ -61,7 +62,7 @@ export function PullRequestSpeedActions<Entry extends PullRequestSpeedActionEntr
environmentId: entry.environmentId,
reference,
terminology,
- onSuccess: (action) => onActed?.({ entry, action }),
+ onSuccess: (action, reply) => onActed?.({ entry, action, reply }),
resolveMergeMethod: (detail) => {
const allowed = detail.capabilities.mergeMethods.filter(
(method) => detail.mergeCapabilities[method],
diff --git a/apps/web/src/components/pullRequest/PullRequestsPage.tsx b/apps/web/src/components/pullRequest/PullRequestsPage.tsx
index 0fc32bce325..2af8383bebc 100644
--- a/apps/web/src/components/pullRequest/PullRequestsPage.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestsPage.tsx
@@ -16,6 +16,7 @@ import type {
PullRequestListInput,
PullRequestListResult,
PullRequestListState,
+ PullRequestSummary,
} from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import { useNavigate, useSearch } from "@tanstack/react-router";
@@ -432,9 +433,10 @@ export function PullRequestsPage() {
const overrideEntry = (
entry: EnvironmentPullRequestEntry,
action: PullRequestAction,
+ reply?: PullRequestSummary,
): number | null => {
const token = ++overrideToken.current;
- const override = pullRequestOverrideAfterAction(entry, action, new Date(), token);
+ const override = pullRequestOverrideAfterAction(entry, action, new Date(), token, reply);
if (override === null) return null;
setOverrides((current) => new Map(current).set(pullRequestEntryKey(entry), override));
return token;
@@ -449,13 +451,17 @@ export function PullRequestsPage() {
});
};
const detailOverrideTokens = useRef(new Map<string, number | null>());
- const onSpeedAction = useStableCallback(({ entry, action }: PullRequestSpeedActionResult) => {
- // Some hosts accept a merge before it completes. Let the next host read declare it merged.
- if (action !== "merge") overrideEntry(entry, action);
- });
- const onBatchClosed = useStableCallback((entry: EnvironmentPullRequestEntry) => {
- onSpeedAction({ entry, action: "close" });
- });
+ const onSpeedAction = useStableCallback(
+ ({ entry, action, reply }: PullRequestSpeedActionResult) => {
+ // Some hosts accept a merge before it completes. Without a reply, let the next read say so.
+ if (reply !== undefined || action !== "merge") overrideEntry(entry, action, reply);
+ },
+ );
+ const onBatchClosed = useStableCallback(
+ (entry: EnvironmentPullRequestEntry, reply: PullRequestSummary | undefined) => {
+ onSpeedAction({ entry, action: "close", reply });
+ },
+ );
const { close: closeBatch, closingKeys } = usePullRequestCloseBatch(onBatchClosed);
const [snapshotEnvironmentKey, setSnapshotEnvironmentKey] = useState("");
if (environmentKey.length > 0 && snapshotEnvironmentKey !== environmentKey) {
@@ -1545,12 +1551,19 @@ export function PullRequestsPage() {
}
refreshToken={detailRefreshToken}
tabOnPage
- onActed={(action, phase = "done") => {
+ onActed={(action, phase = "done", reply) => {
// From every row held, not the ones on screen: a pull request closed from an open
// list has left the screen, and reopening it has to find it anyway.
const acted = heldPullRequestsBySurface.get(
pullRequestListEntryId(renderedPullRequestSurface),
);
+ if (reply !== undefined) {
+ if (acted !== undefined) {
+ if (action !== undefined) overrideEntry(acted, action, reply);
+ detailOverrideTokens.current.delete(pullRequestEntryKey(acted));
+ }
+ return;
+ }
const stateOnly =
action !== undefined &&
acted !== undefined &&
diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
index 1ed83fba3dd..123111ff6a3 100644
--- a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
@@ -4,6 +4,7 @@ import type {
ProjectId,
PullRequestAction,
PullRequestListEntry,
+ PullRequestSummary,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
@@ -33,6 +34,7 @@ import {
resolveSelectedEnvironmentId,
type EnvironmentPullRequestEntry,
applyPullRequestOverrides,
+ pullRequestOverrideAfterAction,
reusePullRequestEntries,
settlePullRequestOverrides,
} from "./pullRequestList.logic";
@@ -596,6 +598,26 @@ describe("pull request list overrides", () => {
expect(applyPullRequestOverrides(rows, new Map(), key, "open")).toBe(rows);
});
+ it("shows a reply's queued merge as open and never un-merges a merged row", () => {
+ const reply = { state: "open", updatedAt: "2026-07-03T00:00:00Z", observedAt: 300 } as const;
+ const override = pullRequestOverrideAfterAction(
+ entry(1, "open"),
+ "merge",
+ new Date(900),
+ 1,
+ reply as unknown as PullRequestSummary,
+ )!;
+ const overrides = new Map([["#1", override]]);
+ expect(applyPullRequestOverrides([entry(1, "open")], overrides, key, "open")).toMatchObject([
+ { state: "open", updatedAt: reply.updatedAt, observedAt: 300 },
+ ]);
+ expect(
+ applyPullRequestOverrides([entry(1, "merged")], overrides, key, "all").map(
+ (row) => row.state,
+ ),
+ ).toEqual(["merged"]);
+ });
+
it("keeps a confirmed close hidden when its override is cleared", () => {
const at = 1_000_000;
const rows = [entry(1, "closed"), entry(2, "open"), entry(3, "merged")];
diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.ts
index b3e447a82e5..fb95b44b81e 100644
--- a/apps/web/src/components/pullRequest/pullRequestList.logic.ts
+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.ts
@@ -17,8 +17,10 @@ import type {
PullRequestListFilters,
PullRequestListState,
PullRequestState,
+ PullRequestSummary,
} from "@t3tools/contracts";
+import { isStalePullRequestReply } from "@t3tools/client-runtime/pull-request-reply";
import { toSortableTimestamp } from "@t3tools/client-runtime/state/thread-sort";
import type { PullRequestListSort } from "./pullRequestListPreferences";
@@ -802,6 +804,9 @@ export interface PullRequestListOverride {
readonly updatedAt: string;
readonly token: number;
readonly at: number;
+ /** Set when the host reported this state, so a newer row can outrank it. */
+ readonly fromReply?: true;
+ readonly observedAt?: number;
}
export function pullRequestOverrideAfterAction(
@@ -809,7 +814,20 @@ export function pullRequestOverrideAfterAction(
action: PullRequestAction,
now: Date,
token: number,
+ reply?: PullRequestSummary,
): PullRequestListOverride | null {
+ if (reply !== undefined) {
+ const { state, isDraft, updatedAt, observedAt } = reply;
+ return {
+ state,
+ ...(isDraft === undefined ? {} : { isDraft }),
+ updatedAt,
+ ...(observedAt === undefined ? {} : { observedAt }),
+ fromReply: true,
+ token,
+ at: now.getTime(),
+ };
+ }
const stamp = { updatedAt: now.toISOString(), token, at: now.getTime() };
switch (action) {
case "close":
@@ -836,7 +854,9 @@ export function applyPullRequestOverrides<Entry extends PullRequestListEntry>(
if (overrides.size === 0 && state === "all") return entries;
const out: Entry[] = [];
for (const entry of entries) {
- const override = overrides.get(keyOf(entry));
+ const held = overrides.get(keyOf(entry));
+ const override =
+ held?.fromReply === true && isStalePullRequestReply(entry, held) ? undefined : held;
if (state !== "all" && (override?.state ?? entry.state) !== state) continue;
out.push(override === undefined ? entry : { ...entry, ...override });
}
diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.ts b/apps/web/src/components/pullRequest/usePullRequestActions.ts
index 82ce86ab8f4..d6e8de7ffa5 100644
--- a/apps/web/src/components/pullRequest/usePullRequestActions.ts
+++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts
@@ -11,6 +11,7 @@ import type {
PullRequestDetail,
PullRequestMergeMethod,
PullRequestRef,
+ PullRequestSummary,
} from "@t3tools/contracts";
import { useRef, useState } from "react";
import {
@@ -133,7 +134,7 @@ export function usePullRequestActionRunner({
environmentId: EnvironmentId;
reference: PullRequestRef | null;
terminology: ChangeRequestTerminology;
- onSuccess?: (action: PullRequestAction) => void;
+ onSuccess?: (action: PullRequestAction, reply: PullRequestSummary | undefined) => void;
/** Resolve repository settings on click to avoid per-row reads. */
resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;
}) {
@@ -179,13 +180,15 @@ export function usePullRequestActionRunner({
return;
}
toastManager.add({ type: "success", title: actionSuccessLabels(terminology.singular)[action] });
- onSuccess?.(action);
+ onSuccess?.(action, result.value);
};
return { actionPending, perform };
}
-export function usePullRequestCloseBatch(onClosed: (entry: EnvironmentPullRequestEntry) => void) {
+export function usePullRequestCloseBatch(
+ onClosed: (entry: EnvironmentPullRequestEntry, reply: PullRequestSummary | undefined) => void,
+) {
const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });
const pending = useRef(new Set<string>());
const [closingKeys, setClosingKeys] = useState<ReadonlySet<string>>(() => new Set());
@@ -219,7 +222,7 @@ export function usePullRequestCloseBatch(onClosed: (entry: EnvironmentPullReques
);
return;
}
- onClosed(entry);
+ onClosed(entry, result.value);
return true;
}),
);
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index 15d9bc66962..851972ce80c 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -515,6 +515,10 @@
"types": "./src/pullRequestReactions.ts",
"default": "./src/pullRequestReactions.ts"
},
+ "./pull-request-reply": {
+ "types": "./src/pullRequestReply.ts",
+ "default": "./src/pullRequestReply.ts"
+ },
"./pull-request-query": {
"types": "./src/pullRequestQuery.ts",
"default": "./src/pullRequestQuery.ts"
diff --git a/packages/client-runtime/src/pullRequestReply.ts b/packages/client-runtime/src/pullRequestReply.ts
new file mode 100644
index 00000000000..7f684763b95
--- /dev/null
+++ b/packages/client-runtime/src/pullRequestReply.ts
@@ -0,0 +1,20 @@
+import type { PullRequestState } from "@t3tools/contracts";
+
+interface ObservedPullRequest {
+ readonly state: PullRequestState;
+ readonly updatedAt?: string | undefined;
+ readonly observedAt?: number | undefined;
+}
+
+/** Older than what is shown by host update time, then server read time, or a merge undone. */
+export function isStalePullRequestReply(
+ shown: ObservedPullRequest,
+ reply: ObservedPullRequest,
+): boolean {
+ if (shown.state === "merged" && reply.state !== "merged") return true;
+ if (shown.updatedAt !== undefined && reply.updatedAt !== undefined) {
+ const updated = Date.parse(reply.updatedAt) - Date.parse(shown.updatedAt);
+ if (Number.isFinite(updated) && updated !== 0) return updated < 0;
+ }
+ return (reply.observedAt ?? -Infinity) < (shown.observedAt ?? -Infinity);
+}
diff --git a/packages/client-runtime/src/state/pullRequests.test.ts b/packages/client-runtime/src/state/pullRequests.test.ts
index 6efc11818ce..37ba0225340 100644
--- a/packages/client-runtime/src/state/pullRequests.test.ts
+++ b/packages/client-runtime/src/state/pullRequests.test.ts
@@ -9,6 +9,7 @@ import {
PullRequestOperationError,
WS_METHODS,
type AuthSessionState,
+ type PullRequestListInput,
} from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Schema from "effect/Schema";
@@ -42,7 +43,8 @@ import {
createPullRequestEnvironmentAtoms,
} from "./pullRequests.ts";
import * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts";
-import { executeAtomQuery } from "./runtime.ts";
+import { executeAtomQuery, queryPersistenceKey } from "./runtime.ts";
+import { EnvironmentQueryStore } from "./queryPersistence.ts";
import { createPullRequestRouter } from "./pullRequestRouting.ts";
import { PullRequestRoutingPermissions } from "../connection/pullRequestRoutingPermissions.ts";
@@ -522,6 +524,8 @@ const makeTestRuntime = Effect.fn("makeTestRuntime")(function* (
client: WsRpcProtocolClient,
localClient?: WsRpcProtocolClient,
localOrigin = false,
+ onAnswer: Parameters<typeof createPullRequestEnvironmentAtoms>[1] = {},
+ queryStore: typeof EnvironmentQueryStore.Service = null,
) {
const originTarget = localOrigin
? new PrimaryConnectionTarget({
@@ -587,15 +591,16 @@ const makeTestRuntime = Effect.fn("makeTestRuntime")(function* (
Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
} as EnvironmentRegistry.EnvironmentRegistry["Service"]);
const runtime = Atom.runtime(
- Layer.merge(
+ Layer.mergeAll(
Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
Layer.succeed(
PullRequestDiffLoader.PullRequestDiffLoader,
PullRequestDiffLoader.PullRequestDiffLoader.of({ load: () => Effect.die("unused") }),
),
+ Layer.succeed(EnvironmentQueryStore, queryStore),
),
);
- const atoms = createPullRequestEnvironmentAtoms(runtime);
+ const atoms = createPullRequestEnvironmentAtoms(runtime, onAnswer);
const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
Effect.sync(() => registry.dispose()),
);
@@ -1099,6 +1104,613 @@ it.effect("keeps a close batch ordered and continues after a refused close", ()
),
);
+const actionReference = {
+ projectId: ProjectId.make("project-1"),
+ host: "github.example.com",
+ repository: "acme/web",
+ number: 1,
+};
+const actionReply = {
+ ...actionReference,
+ provider: "github",
+ title: "Ship it",
+ url: "https://github.example.com/acme/web/pull/1",
+ headBranch: "feature",
+ baseBranch: "main",
+ state: "merged" as const,
+ isDraft: false,
+ updatedAt: "2026-10-27T10:00:00Z",
+ observedAt: 200,
+};
+
+function actionReplyClient(overrides: Record<string, unknown> = {}) {
+ return {
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
+ [WS_METHODS.pullRequestsRunAction]: () => Effect.succeed(actionReply),
+ ...overrides,
+ } as unknown as WsRpcProtocolClient;
+}
+
+it.effect("shows an action's reply in loaded readers and moves list rows without reads", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const reads: string[] = [];
+ const open = { ...actionReference, state: "open", isDraft: true, observedAt: 100 };
+ const read = (name: string) => () =>
+ Effect.sync(() => {
+ reads.push(name);
+ return open;
+ });
+ const replies: unknown[] = [];
+ const listAnswers: unknown[] = [];
+ const client = actionReplyClient({
+ [WS_METHODS.pullRequestsDetail]: read("detail"),
+ [WS_METHODS.pullRequestsPreview]: read("preview"),
+ [WS_METHODS.pullRequestsSummary]: read("summary"),
+ [WS_METHODS.pullRequestsList]: (input: { readonly state: string }) =>
+ Effect.sync(() => {
+ reads.push(`list:${input.state}`);
+ return {
+ entries: input.state === "merged" ? [] : [open],
+ viewers: {},
+ providers: [],
+ errors: [],
+ truncated: false,
+ nextCursors: {},
+ };
+ }),
+ });
+ const saved = new Map<string, string>();
+ const { atoms, registry, runtime } = yield* makeTestRuntime(
+ client,
+ undefined,
+ false,
+ {
+ actionReply: (target, reply) => Effect.sync(() => replies.push({ target, reply })),
+ list: (_target, value) => Effect.sync(() => listAnswers.push(value.entries)),
+ },
+ {
+ load: (_environmentId, key) => Effect.sync(() => Option.fromUndefinedOr(saved.get(key))),
+ save: (_environmentId, key, payload) => Effect.sync(() => void saved.set(key, payload)),
+ },
+ );
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
+ const list = (input: PullRequestListInput) =>
+ atoms.list({ environmentId: target.environmentId, input });
+ const readers: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [
+ atoms.detail(target),
+ atoms.preview(target),
+ createLinkedPullRequestSummaryAtomFamily(runtime, atoms.refreshes)(target),
+ ];
+ const all = list({ state: "all" });
+ const openDrafts = list({ state: "open", filters: { draft: "only" } });
+ const merged = list({ state: "merged" });
+ for (const atom of [...readers, all, openDrafts, merged]) {
+ registry.mount(atom);
+ yield* Effect.promise(() => executeAtomQuery(registry, atom));
+ }
+ reads.length = 0;
+
+ const answer = yield* Effect.promise(() =>
+ atoms.runAction.run(registry, { ...target, input: { ...target.input, action: "merge" } }),
+ );
+
+ expect(answer).toMatchObject({ _tag: "Success", value: actionReply });
+ for (const atom of readers) {
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(atom)))).toMatchObject({
+ state: "merged",
+ isDraft: false,
+ title: "Ship it",
+ });
+ }
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(all))).entries).toMatchObject([
+ // The row keeps its own read time: the reply does not carry its checks or labels.
+ { state: "merged", isDraft: false, observedAt: 100 },
+ ]);
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(openDrafts))).entries).toEqual([]);
+ expect(replies).toEqual([{ target, reply: actionReply }]);
+ // A cold start paints the saved copy, so the patch must replace the saved answer.
+ const summaryKey = queryPersistenceKey(
+ "environment-data:pull-requests:linked-summary",
+ actionReference,
+ );
+ expect(JSON.parse(saved.get(summaryKey) ?? "null")).toMatchObject({ state: "merged" });
+ // Snapshot writers see the patched rows the way they see an answer.
+ expect(listAnswers).toContainEqual([expect.objectContaining({ state: "merged" })]);
+ // Only a read can place a row the listing did not hold.
+ yield* AtomRegistry.getResult(registry, merged, { suspendOnWaiting: true });
+ expect(reads).toEqual(["list:merged"]);
+ }),
+ ),
+);
+
+it.effect("keeps an action's reply when a refresh started before the action answers late", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ let state: "open" | "merged" = "open";
+ let reads = 0;
+ const started = yield* Deferred.make<void>();
+ const release = yield* Deferred.make<void>();
+ const settled = yield* Deferred.make<void>();
+ const client = actionReplyClient({
+ [WS_METHODS.pullRequestsDetail]: () =>
+ Effect.gen(function* () {
+ reads++;
+ const snapshot = { ...actionReference, state, isDraft: false, observedAt: 100 };
+ if (reads === 2) {
+ yield* Deferred.succeed(started, undefined);
+ yield* Deferred.await(release).pipe(
+ Effect.onExit(() => Deferred.succeed(settled, undefined)),
+ );
+ }
+ return snapshot;
+ }),
+ [WS_METHODS.pullRequestsRunAction]: () =>
+ Effect.sync(() => {
+ state = "merged";
+ return actionReply;
+ }),
+ });
+ const { atoms, registry } = yield* makeTestRuntime(client);
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
+ const detail = atoms.detail(target);
+ registry.mount(detail);
+ yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
+ registry.refresh(detail);
+ yield* Deferred.await(started);
+
+ yield* Effect.promise(() =>
+ atoms.runAction.run(registry, {
+ ...target,
+ input: { ...actionReference, action: "merge" },
+ }),
+ );
+ yield* Deferred.succeed(release, undefined);
+ yield* Deferred.await(settled);
+
+ expect(
+ (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).state,
+ ).toBe("merged");
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("merged");
+ }),
+ ),
+);
+
+it.effect("keeps a list read the server's refresh started before the action replied", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const refreshEvents = yield* PubSub.unbounded<number>();
+ let state: "open" | "merged" = "open";
+ let reads = 0;
+ const actionInputs: unknown[] = [];
+ const listWaiting = Latch.makeUnsafe();
+ const release = yield* Deferred.make<void>();
+ const client = actionReplyClient({
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
+ [WS_METHODS.pullRequestsList]: () =>
+ Effect.gen(function* () {
+ reads++;
+ const entries = [
+ { ...actionReference, state, isDraft: false, updatedAt: actionReply.updatedAt },
+ ];
+ if (reads === 2) yield* Deferred.await(release);
+ return {
+ entries,
+ viewers: {},
+ providers: [],
+ errors: [],
+ truncated: false,
+ nextCursors: {},
+ };
+ }),
+ [WS_METHODS.pullRequestsRunAction]: (input: unknown) =>
+ Effect.gen(function* () {
+ actionInputs.push(input);
+ state = "merged";
+ // The server announces its refresh before it replies.
+ yield* PubSub.publish(refreshEvents, 1);
+ yield* listWaiting.await;
+ return actionReply;
+ }),
+ });
+ const { atoms, registry } = yield* makeTestRuntime(client);
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
+ const list = atoms.list({ environmentId: target.environmentId, input: { state: "all" } });
+ const unmount = registry.mount(list);
+ yield* Effect.addFinalizer(() => Effect.sync(unmount));
+ yield* Effect.promise(() => executeAtomQuery(registry, list));
+ const stop = registry.subscribe(list, (result) => {
+ if (result.waiting) listWaiting.openUnsafe();
+ });
+ yield* Effect.addFinalizer(() => Effect.sync(stop));
+
+ yield* Effect.promise(() =>
+ atoms.runAction.run(registry, {
+ ...target,
+ input: { ...actionReference, action: "merge" },
+ }),
+ );
+ yield* Deferred.succeed(release, undefined);
+
+ expect(
+ (yield* AtomRegistry.getResult(registry, list, { suspendOnWaiting: true })).entries,
+ ).toMatchObject([{ state: "merged" }]);
+ expect(reads).toBe(2);
+ expect(actionInputs).toEqual([expect.objectContaining({ replyWithSummary: true })]);
+ }),
+ ),
+);
+
+it.effect("restarts a list page read sent while the action was in flight", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const refreshEvents = yield* PubSub.unbounded<number>();
+ let state: "open" | "closed" = "open";
+ let pageReads = 0;
+ const actionSent = yield* Deferred.make<void>();
+ const pageStarted = yield* Deferred.make<void>();
+ const release = yield* Deferred.make<void>();
+ const settled = yield* Deferred.make<void>();
+ const listResult = (entries: ReadonlyArray<object>) => ({
+ entries,
+ viewers: {},
+ providers: [],
+ errors: [],
+ truncated: false,
+ nextCursors: {},
+ });
+ const client = actionReplyClient({
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
+ [WS_METHODS.pullRequestsList]: (input: PullRequestListInput) =>
+ Effect.gen(function* () {
+ const entries =
+ state === "open"
+ ? [{ ...actionReference, state, isDraft: false, updatedAt: "2026-10-27T09:00:00Z" }]
+ : [];
+ if (input.cursors !== undefined && ++pageReads === 2) {
+ yield* Deferred.succeed(pageStarted, undefined);
+ yield* Deferred.await(release).pipe(
+ Effect.onExit(() => Deferred.succeed(settled, undefined)),
+ );
+ }
+ return listResult(input.cursors === undefined ? [] : entries);
+ }),
+ [WS_METHODS.pullRequestsRunAction]: () =>
+ Effect.gen(function* () {
+ yield* Deferred.succeed(actionSent, undefined);
+ yield* Deferred.await(pageStarted);
+ state = "closed";
+ yield* PubSub.publish(refreshEvents, 1);
+ return { ...actionReply, state: "closed" };
+ }),
+ });
+ const { atoms, registry } = yield* makeTestRuntime(client);
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
+ const listInput = { state: "open" } as const;
+ const head = atoms.list({ environmentId: target.environmentId, input: listInput });
+ const page = atoms.list({
+ environmentId: target.environmentId,
+ input: { ...listInput, cursors: { "github.example.com": "page-2" } },
+ });
+ for (const atom of [head, page]) {
+ const unmount = registry.mount(atom);
+ yield* Effect.addFinalizer(() => Effect.sync(unmount));
+ yield* Effect.promise(() => executeAtomQuery(registry, atom));
+ }
+
+ const action = yield* Effect.promise(() =>
+ atoms.runAction.run(registry, {
+ ...target,
+ input: { ...actionReference, action: "close" },
+ }),
+ ).pipe(Effect.forkScoped);
+ yield* Deferred.await(actionSent);
+ // Loading more rows re-reads a page while the close is on the wire.
+ registry.refresh(page);
+ yield* Fiber.join(action);
+ yield* Deferred.succeed(release, undefined);
+ yield* Deferred.await(settled);
+
+ expect(
+ (yield* AtomRegistry.getResult(registry, page, { suspendOnWaiting: true })).entries,
+ ).toEqual([]);
+ }),
+ ),
+);
+
+it.effect("shows a reopen reply at once and re-reads the fields it lacks", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ let reads = 0;
+ const release = yield* Deferred.make<void>();
+ const client = actionReplyClient({
+ [WS_METHODS.pullRequestsDetail]: () =>
+ Effect.gen(function* () {
+ reads++;
+ if (reads === 1) return { ...actionReference, state: "closed", observedAt: 100 };
+ yield* Deferred.await(release);
+ return { ...actionReference, state: "open", observedAt: 300 };
+ }),
+ [WS_METHODS.pullRequestsRunAction]: () => Effect.succeed({ ...actionReply, state: "open" }),
+ });
+ const { atoms, registry } = yield* makeTestRuntime(client);
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
+ const detail = atoms.detail(target);
+ registry.mount(detail);
+ yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
+
+ yield* Effect.promise(() =>
+ atoms.runAction.run(registry, {
+ ...target,
+ input: { ...actionReference, action: "reopen" },
+ }),
+ );
+
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("open");
+ expect(reads).toBe(2);
+ yield* Deferred.succeed(release, undefined);
+ expect(
+ (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).observedAt,
+ ).toBe(300);
+ }),
+ ),
+);
+
+it.effect("keeps each reader's read time when a reply leaves its checks as they were", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const shown = {
+ ...actionReference,
+ state: "open",
+ isDraft: true,
+ updatedAt: "2026-10-27T09:00:00Z",
+ observedAt: 100,
+ checks: [{ status: "success" }],
+ checksState: "passing",
+ };
+ const client = actionReplyClient({
+ [WS_METHODS.pullRequestsDetail]: () => Effect.succeed(shown),
+ [WS_METHODS.pullRequestsSummary]: () => Effect.succeed(shown),
+ [WS_METHODS.pullRequestsList]: () =>
+ Effect.succeed({
+ entries: [shown],
+ viewers: {},
+ providers: [],
+ errors: [],
+ truncated: false,
+ nextCursors: {},
+ }),
+ [WS_METHODS.pullRequestsRunAction]: () =>
+ Effect.succeed({ ...actionReply, state: "open", observedAt: 300 }),
+ });
+ const answeredAt: Array<number | undefined> = [];
+ const { atoms, registry, runtime } = yield* makeTestRuntime(client, undefined, false, {
+ detail: (_target, value) => Effect.sync(() => answeredAt.push(value.observedAt)),
+ });
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
+ const readers: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [
+ atoms.detail(target),
+ createLinkedPullRequestSummaryAtomFamily(runtime, atoms.refreshes)(target),
+ ];
+ const list = atoms.list({ environmentId: target.environmentId, input: { state: "all" } });
+ for (const atom of [...readers, list]) {
+ registry.mount(atom);
+ yield* Effect.promise(() => executeAtomQuery(registry, atom));
+ }
+
+ yield* Effect.promise(() =>
+ atoms.runAction.run(registry, {
+ ...target,
+ input: { ...actionReference, action: "ready" },
+ }),
+ );
+
+ // Checks read at 100 must not pass for a read at 300 against a newer checks read.
+ for (const atom of readers) {
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(atom)))).toMatchObject({
+ isDraft: false,
+ observedAt: 100,
+ });
+ }
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(list))).entries).toMatchObject([
+ { isDraft: false, checksState: "passing", observedAt: 100 },
+ ]);
+ expect(answeredAt).toEqual([100, 100]);
+ }),
+ ),
+);
+
+it.effect("re-reads an unstamped preview rather than order a reply against it", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ let reads = 0;
+ const client = actionReplyClient({
+ // Previews from servers before action replies carry neither update nor read time.
+ [WS_METHODS.pullRequestsPreview]: () =>
+ Effect.sync(() => {
+ reads++;
+ return {
+ ...actionReference,
+ title: "Reopened elsewhere",
+ url: actionReply.url,
+ author: null,
+ state: "open",
+ isDraft: false,
+ createdAt: "2026-10-27T08:00:00Z",
+ };
+ }),
+ [WS_METHODS.pullRequestsRunAction]: () =>
+ Effect.succeed({ ...actionReply, state: "closed" }),
+ });
+ const { atoms, registry } = yield* makeTestRuntime(client);
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
+ const preview = atoms.preview(target);
+ registry.mount(preview);
+ yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true });
+
+ yield* Effect.promise(() =>
+ atoms.runAction.run(registry, {
+ ...target,
+ input: { ...actionReference, action: "close" },
+ }),
+ );
+
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(preview))).state).toBe("open");
+ expect(
+ (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).state,
+ ).toBe("open");
+ expect(reads).toBe(2);
+ }),
+ ),
+);
+
+it.effect("leaves a loaded list page alone when the reply concerns none of its rows", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ let pageReads = 0;
+ const client = actionReplyClient({
+ [WS_METHODS.pullRequestsList]: () =>
+ Effect.sync(() => {
+ pageReads++;
+ return {
+ entries: [
+ {
+ ...actionReference,
+ number: 2,
+ state: "open",
+ isDraft: false,
+ updatedAt: "2026-10-27T09:00:00Z",
+ },
+ ],
+ viewers: {},
+ providers: [],
+ errors: [],
+ truncated: false,
+ nextCursors: {},
+ };
+ }),
+ [WS_METHODS.pullRequestsRunAction]: () => Effect.succeed({ ...actionReply, state: "open" }),
+ });
+ const { atoms, registry } = yield* makeTestRuntime(client);
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
+ const page = atoms.list({
+ environmentId: target.environmentId,
+ input: { state: "open", cursors: { "github.example.com": "page-2" } },
+ });
+ const unmount = registry.mount(page);
+ yield* Effect.addFinalizer(() => Effect.sync(unmount));
+ yield* Effect.promise(() => executeAtomQuery(registry, page));
+
+ yield* Effect.promise(() =>
+ atoms.runAction.run(registry, {
+ ...target,
+ input: { ...actionReference, action: "ready" },
+ }),
+ );
+
+ yield* AtomRegistry.getResult(registry, page, { suspendOnWaiting: true });
+ expect(pageReads).toBe(1);
+ }),
+ ),
+);
+
+it.effect("keeps the server's post-commit read when a reopen reply lacks fields", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const refreshEvents = yield* PubSub.unbounded<number>();
+ let reads = 0;
+ const detailWaiting = Latch.makeUnsafe();
+ const release = yield* Deferred.make<void>();
+ const client = actionReplyClient({
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
+ [WS_METHODS.pullRequestsDetail]: () =>
+ Effect.gen(function* () {
+ reads++;
+ if (reads === 1) return { ...actionReference, state: "closed", observedAt: 100 };
+ yield* Deferred.await(release);
+ return { ...actionReference, state: "open", observedAt: 300 };
+ }),
+ [WS_METHODS.pullRequestsRunAction]: () =>
+ Effect.gen(function* () {
+ // The server announces its refresh before it replies.
+ yield* PubSub.publish(refreshEvents, 1);
+ yield* detailWaiting.await;
+ return { ...actionReply, state: "open" };
+ }),
+ });
+ const { atoms, registry } = yield* makeTestRuntime(client);
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
+ const detail = atoms.detail(target);
+ const unmount = registry.mount(detail);
+ yield* Effect.addFinalizer(() => Effect.sync(unmount));
+ yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
+ const stop = registry.subscribe(detail, (result) => {
+ if (result.waiting) detailWaiting.openUnsafe();
+ });
+ yield* Effect.addFinalizer(() => Effect.sync(stop));
+
+ yield* Effect.promise(() =>
+ atoms.runAction.run(registry, {
+ ...target,
+ input: { ...actionReference, action: "reopen" },
+ }),
+ );
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("open");
+ yield* Deferred.succeed(release, undefined);
+
+ expect(
+ (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).observedAt,
+ ).toBe(300);
+ expect(reads).toBe(2);
+ }),
+ ),
+);
+
+it.effect.each([
+ ["a newer update", "open", "2026-10-27T10:00:01Z", 100, "open"],
+ ["a merge", "merged", "2026-10-27T09:00:00Z", 100, "open"],
+] as const)(
+ "keeps %s when an older or reverting action reply arrives",
+ ([, shownState, updatedAt, observedAt, replyState]) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const shown = {
+ ...actionReference,
+ state: shownState,
+ isDraft: true,
+ updatedAt,
+ observedAt,
+ };
+ const client = actionReplyClient({
+ [WS_METHODS.pullRequestsDetail]: () => Effect.succeed(shown),
+ [WS_METHODS.pullRequestsPreview]: () => Effect.succeed(shown),
+ [WS_METHODS.pullRequestsRunAction]: () =>
+ Effect.succeed({ ...actionReply, state: replyState }),
+ });
+ const { atoms, registry } = yield* makeTestRuntime(client);
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
+ const readers = [atoms.detail(target), atoms.preview(target), atoms.previewCard(target)];
+ for (const reader of readers) {
+ registry.mount(reader);
+ yield* AtomRegistry.getResult(registry, reader, { suspendOnWaiting: true });
+ }
+
+ yield* Effect.promise(() =>
+ atoms.runAction.run(registry, {
+ ...target,
+ input: { ...actionReference, action: "ready" },
+ }),
+ );
+ for (const reader of readers) {
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(reader)))).toMatchObject({
+ state: shownState,
+ isDraft: true,
+ });
+ }
+ }),
+ ),
+);
+
it.effect("keeps hover previews fresh after edits and turns", () =>
Effect.scoped(
Effect.gen(function* () {
diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.ts
index b92f00c8a36..3dc2710d96f 100644
--- a/packages/client-runtime/src/state/pullRequests.ts
+++ b/packages/client-runtime/src/state/pullRequests.ts
@@ -18,6 +18,7 @@ import {
type PullRequestListStatsResult,
type PullRequestDetail,
type PullRequestDiffInput,
+ type PullRequestListEntry,
type PullRequestRef,
type PullRequestMergeMethod,
PullRequestOperationError,
@@ -27,7 +28,7 @@ import {
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { persistPullRequestStats } from "./pullRequestStatsPersistence.ts";
-import { persistQuery } from "./queryPersistence.ts";
+import { persistQuery, type QueryPersistence } from "./queryPersistence.ts";
import * as Option from "effect/Option";
import * as SubscriptionRef from "effect/SubscriptionRef";
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
@@ -38,12 +39,16 @@ import {
createEnvironmentRpcQueryAtomFamily,
createEnvironmentRpcSubscriptionAtomFamily,
createEnvironmentQueryAtomFamily,
+ queryPersistenceKey,
type QueryAnswerHandler,
} from "./runtime.ts";
import { createPullRequestRouter } from "./pullRequestRouting.ts";
import * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts";
import type { EnvironmentRegistry } from "../connection/registry.ts";
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
+import { isStalePullRequestReply } from "../pullRequestReply.ts";
+import { parsePullRequestQuery } from "../pullRequestQuery.ts";
+import { reuseUnchanged } from "./serverConfigProjection.ts";
export {
type PullRequestDiffLoadError,
@@ -79,6 +84,26 @@ function normalizePullRequestQuery<A>(
});
}
+function writableQuery<A, E>(
+ source: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
+ idleTtlMs = 5 * 60_000,
+) {
+ return Atom.writable(
+ (get) => {
+ const result = get(source);
+ if (result._tag === "Success" && !result.waiting) return result;
+ const previous = get.self<AsyncResult.AsyncResult<A, E>>();
+ const value = Option.flatMap(previous, AsyncResult.value);
+ if (Option.isNone(value)) return result;
+ return result._tag === "Failure"
+ ? AsyncResult.failureWithPrevious(result.cause, { previous, waiting: result.waiting })
+ : AsyncResult.success<A, E>(value.value, result);
+ },
+ (context, value: AsyncResult.AsyncResult<A, E>) => context.setSelf(value),
+ (refresh) => refresh(source),
+ ).pipe(Atom.setIdleTTL(idleTtlMs));
+}
+
function writableQueryFamily<A, E>(
family: (target: {
readonly environmentId: EnvironmentId;
@@ -86,20 +111,7 @@ function writableQueryFamily<A, E>(
}) => Atom.Atom<AsyncResult.AsyncResult<A, E>>,
) {
const writable = Atom.family((source: Atom.Atom<AsyncResult.AsyncResult<A, E>>) =>
- Atom.writable(
- (get) => {
- const result = get(source);
- if (result._tag === "Success" && !result.waiting) return result;
- const previous = get.self<AsyncResult.AsyncResult<A, E>>();
- const value = Option.flatMap(previous, AsyncResult.value);
- if (Option.isNone(value)) return result;
- return result._tag === "Failure"
- ? AsyncResult.failureWithPrevious(result.cause, { previous, waiting: result.waiting })
- : AsyncResult.success<A, E>(value.value, result);
- },
- (context, value: AsyncResult.AsyncResult<A, E>) => context.setSelf(value),
- (refresh) => refresh(source),
- ).pipe(Atom.setIdleTTL(5 * 60_000)),
+ writableQuery(source),
);
return normalizePullRequestQuery((target) => writable(family(target)));
}
@@ -115,6 +127,196 @@ function updateCached<A, E>(
registry.update(atom, AsyncResult.map(update));
}
+interface ActionReplyPatch {
+ /** The read this reader is waiting on, if any. */
+ readonly pendingRead: (registry: AtomRegistry.AtomRegistry) => object | undefined;
+ readonly apply: (
+ registry: AtomRegistry.AtomRegistry,
+ environmentId: EnvironmentId,
+ reference: PullRequestRef,
+ reply: PullRequestSummary | undefined,
+ readsBeforeSend: ReadonlySet<object>,
+ ) => Effect.Effect<void>;
+}
+
+// Module-wide so readers built by separate factories, such as linked summaries, are patched too.
+const actionReplyPatches = new WeakMap<object, ActionReplyPatch>();
+
+function samePullRequest(reader: PullRequestRef, acted: PullRequestRef) {
+ return (
+ reader.projectId === acted.projectId &&
+ // A missing host is not a wildcard: one project can reach the same repository on two hosts.
+ reader.host?.toLowerCase() === acted.host?.toLowerCase() &&
+ reader.repository.toLowerCase() === acted.repository.toLowerCase() &&
+ reader.number === acted.number &&
+ reader.expectedAccountId === acted.expectedAccountId
+ );
+}
+
+function pickDefined<T extends object, K extends keyof T>(
+ source: T,
+ keys: ReadonlyArray<K>,
+): { [P in K]?: Exclude<T[P], undefined> } {
+ const picked: { [P in K]?: T[P] } = {};
+ for (const key of keys) if (source[key] !== undefined) picked[key] = source[key];
+ return picked as { [P in K]?: Exclude<T[P], undefined> };
+}
+
+function listAccepts(input: PullRequestListInput, state: string, isDraft: boolean | undefined) {
+ const draft = parsePullRequestQuery(input.query ?? "").filters.draft ?? input.filters?.draft;
+ return (
+ (input.state === "all" || input.state === state) &&
+ (draft !== "only" || isDraft !== false) &&
+ (draft !== "hide" || isDraft !== true)
+ );
+}
+
+/**
+ * Listing rows with an action's reply applied, the same array when it changes none, and `refresh`
+ * when the reply adds the pull request to a listing, which only a read can place.
+ */
+export function patchPullRequestListEntries<Entry extends PullRequestListEntry>(
+ input: PullRequestListInput,
+ entries: ReadonlyArray<Entry>,
+ reference: PullRequestRef,
+ reply: PullRequestSummary,
+): ReadonlyArray<Entry> | "refresh" {
+ let found = false;
+ let changed = false;
+ const patched = entries.flatMap((entry): Entry[] => {
+ if (!samePullRequest(entry, reference)) return [entry];
+ found = true;
+ if (isStalePullRequestReply(entry, reply)) return [entry];
+ changed = true;
+ const next = {
+ ...entry,
+ ...pickDefined(reply, [
+ "title",
+ "url",
+ "author",
+ "headBranch",
+ "baseBranch",
+ "state",
+ "isDraft",
+ "mergeability",
+ "updatedAt",
+ ]),
+ };
+ return listAccepts(input, next.state, next.isDraft) ? [next] : [];
+ });
+ if (!found) {
+ return input.cursors === undefined && listAccepts(input, reply.state, reply.isDraft)
+ ? "refresh"
+ : entries;
+ }
+ return changed
+ ? patched.sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt))
+ : entries;
+}
+
+function patchListWithReply(
+ input: PullRequestListInput,
+ value: PullRequestListResult,
+ reference: PullRequestRef,
+ reply: PullRequestSummary,
+): PullRequestListResult | "refresh" {
+ const entries = patchPullRequestListEntries(input, value.entries, reference, reply);
+ if (entries === "refresh") return entries;
+ return entries === value.entries ? value : { ...value, entries };
+}
+
+/**
+ * The query atom for one target, writable so an action's reply can replace what it shows. The
+ * patch is saved and announced the way an answer would be, so cold starts and snapshots see it.
+ */
+function actionPatchedQuery<Input, A, E>(
+ source: (target: {
+ readonly environmentId: EnvironmentId;
+ readonly input: Input;
+ }) => Atom.Atom<AsyncResult.AsyncResult<A, E>>,
+ options: {
+ readonly label: string;
+ readonly persistence?: QueryPersistence<A> | undefined;
+ readonly onAnswer?: QueryAnswerHandler<Input, A> | undefined;
+ readonly idleTtlMs?: number | undefined;
+ readonly concerns: (input: Input, reference: PullRequestRef) => boolean;
+ readonly patch: (
+ input: Input,
+ value: A,
+ reference: PullRequestRef,
+ reply: PullRequestSummary,
+ ) => A | "refresh";
+ /** Fields the reply lacks also changed, so the patched value shows while a read fetches them. */
+ readonly rereads?: (value: A, reply: PullRequestSummary) => boolean;
+ /** Re-read when the host's reply did not carry the pull request. */
+ readonly rereadWithoutReply?: boolean;
+ /** False for reads the refresh stream does not restart; defaults to true. */
+ readonly refreshedByServer?: (input: Input) => boolean;
+ },
+) {
+ const writable = Atom.family((atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>) =>
+ writableQuery(atom, options.idleTtlMs),
+ );
+ return (target: { readonly environmentId: EnvironmentId; readonly input: Input }) => {
+ const query = source(target);
+ const atom = writable(query);
+ if (actionReplyPatches.has(atom)) return atom;
+ const pendingRead = (registry: AtomRegistry.AtomRegistry) => {
+ const result = Option.getOrUndefined(
+ registry.getNodes().get(query)?.valueOption() ?? Option.none(),
+ ) as AsyncResult.AsyncResult<A, E> | undefined;
+ return result?.waiting === true ? result : undefined;
+ };
+ actionReplyPatches.set(atom, {
+ pendingRead,
+ apply: Effect.fnUntraced(
+ function* (registry, environmentId, reference, reply, readsBeforeSend) {
+ if (environmentId !== target.environmentId || !options.concerns(target.input, reference))
+ return;
+ const pending = pendingRead(registry);
+ // A read sent before the action may miss its result, and so may one sent before the host
+ // committed. The server's post-commit refresh restarts that one, but not a read outside
+ // its stream, whose re-read need not even show as waiting, so a mounted one the reply
+ // changes restarts here.
+ const unrefreshed = options.refreshedByServer?.(target.input) === false;
+ const freshRead = pending !== undefined && !unrefreshed && !readsBeforeSend.has(pending);
+ const reread = () => (freshRead ? undefined : registry.refresh(atom));
+ if (reply === undefined) {
+ return options.rereadWithoutReply === true ? reread() : undefined;
+ }
+ const shown = Option.flatMap(
+ registry.getNodes().get(atom)?.valueOption() ?? Option.none(),
+ (current: AsyncResult.AsyncResult<A, E>) => AsyncResult.value(current),
+ );
+ if (Option.isNone(shown)) return reread();
+ const patched = options.patch(target.input, shown.value, reference, reply);
+ if (patched === "refresh") return reread();
+ const lacking = options.rereads?.(shown.value, reply) === true;
+ const next = reuseUnchanged(shown.value, patched);
+ if (next === shown.value)
+ return lacking || (unrefreshed && pending !== undefined) ? reread() : undefined;
+ yield* options.onAnswer?.(target, next, registry) ?? Effect.void;
+ const mounted = (registry.getNodes().get(atom)?.listeners.size ?? 0) > 0;
+ if (!freshRead && (pending !== undefined || lacking || (unrefreshed && mounted)))
+ registry.refresh(atom);
+ registry.update(
+ atom,
+ AsyncResult.map(() => next),
+ );
+ if (options.persistence !== undefined) {
+ yield* options.persistence.save(
+ environmentId,
+ queryPersistenceKey(options.label, target.input),
+ next,
+ );
+ }
+ },
+ ),
+ });
+ return atom;
+ };
+}
+
function makePullRequestRefreshAtomFamily<R, E>(
runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
) {
@@ -145,18 +347,41 @@ export function createLinkedPullRequestSummaryAtomFamily<R, E>(
onAnswer?: QueryAnswerHandler<PullRequestRef, PullRequestSummary>,
) {
const routedRequest = createPullRequestRouter();
- return createEnvironmentRpcQueryAtomFamily(runtime, {
- label: "environment-data:pull-requests:linked-summary",
- persistence: persistQuery(PullRequestSummary),
- tag: WS_METHODS.pullRequestsSummary,
- execute: (input) => routedRequest(WS_METHODS.pullRequestsSummary, input),
- staleTimeMs: 60_000,
- refreshIntervalMs: 60_000,
- idleTtlMs: LINKED_PULL_REQUEST_IDLE_TTL_MS,
- refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
- isFinal: (summary) => summary.state === "merged",
- ...(onAnswer === undefined ? {} : { onAnswer }),
- });
+ const label = "environment-data:pull-requests:linked-summary";
+ const persistence = persistQuery(PullRequestSummary);
+ return actionPatchedQuery(
+ createEnvironmentRpcQueryAtomFamily(runtime, {
+ label,
+ persistence,
+ tag: WS_METHODS.pullRequestsSummary,
+ execute: (input) => routedRequest(WS_METHODS.pullRequestsSummary, input),
+ staleTimeMs: 60_000,
+ refreshIntervalMs: 60_000,
+ idleTtlMs: LINKED_PULL_REQUEST_IDLE_TTL_MS,
+ refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
+ isFinal: (summary) => summary.state === "merged",
+ ...(onAnswer === undefined ? {} : { onAnswer }),
+ }),
+ {
+ label,
+ persistence,
+ onAnswer,
+ idleTtlMs: LINKED_PULL_REQUEST_IDLE_TTL_MS,
+ concerns: samePullRequest,
+ // A routed action replies with the destination's project and repository names.
+ patch: (_input, value, _reference, reply) =>
+ isStalePullRequestReply(value, reply)
+ ? value
+ : {
+ ...value,
+ ...reply,
+ projectId: value.projectId,
+ repository: value.repository,
+ number: value.number,
+ ...(value.observedAt === undefined ? {} : { observedAt: value.observedAt }),
+ },
+ },
+ );
}
/** Lets a client record what each answer says where it lands, rather than watching the data. */
@@ -166,6 +391,8 @@ export interface PullRequestAnswerHandlers {
readonly detail?: QueryAnswerHandler<PullRequestRef, PullRequestDetail>;
readonly checks?: QueryAnswerHandler<PullRequestRef, PullRequestChecks | null>;
readonly reviewGuide?: QueryAnswerHandler<PullRequestRef, PullRequestReviewGuideResult>;
+ /** Once per action reply, after the loaded readers show it; unscoped references only. */
+ readonly actionReply?: QueryAnswerHandler<PullRequestRef, PullRequestSummary>;
}
export function createPullRequestStackAtomFamily<R, E>(
@@ -230,23 +457,66 @@ export function createPullRequestEnvironmentAtoms<R, E>(
const detailAnswers = normalizePullRequestQuery((target) =>
detailAnswerAtoms(JSON.stringify(target)),
);
- const detail = writableQueryFamily(
- createEnvironmentRpcQueryAtomFamily(runtime, {
- label: "environment-data:pull-requests:detail",
- persistence: persistQuery(PullRequestDetailSchema),
- tag: WS_METHODS.pullRequestsDetail,
- execute: (input) => routedRequest(WS_METHODS.pullRequestsDetail, input),
- staleTimeMs: 60_000,
- refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
- onAnswer: (target, value, registry) =>
- Effect.sync(() => {
- // Cache reads bypass onAnswer, and server freshness stays separate from local readbacks.
- registry.update(detailAnswers(target), (previous) => ({
- value,
- version: (previous?.version ?? 0) + 1,
- }));
- }).pipe(Effect.andThen(() => onAnswer.detail?.(target, value, registry) ?? Effect.void)),
- }),
+ const detailLabel = "environment-data:pull-requests:detail";
+ const detailPersistence = persistQuery(PullRequestDetailSchema);
+ const detail = normalizePullRequestQuery(
+ actionPatchedQuery(
+ createEnvironmentRpcQueryAtomFamily(runtime, {
+ label: detailLabel,
+ persistence: detailPersistence,
+ tag: WS_METHODS.pullRequestsDetail,
+ execute: (input) => routedRequest(WS_METHODS.pullRequestsDetail, input),
+ staleTimeMs: 60_000,
+ refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
+ onAnswer: (target, value, registry) =>
+ Effect.sync(() => {
+ // Cache reads bypass onAnswer, and server freshness stays separate from local readbacks.
+ registry.update(detailAnswers(target), (previous) => ({
+ value,
+ version: (previous?.version ?? 0) + 1,
+ }));
+ }).pipe(Effect.andThen(() => onAnswer.detail?.(target, value, registry) ?? Effect.void)),
+ }),
+ {
+ label: detailLabel,
+ persistence: detailPersistence,
+ onAnswer: onAnswer.detail,
+ concerns: samePullRequest,
+ rereadWithoutReply: true,
+ // Reopening or a new head changes branch data and permissions the reply lacks.
+ rereads: (value, reply) =>
+ !isStalePullRequestReply(value, reply) &&
+ ((value.state === "closed" && reply.state === "open") ||
+ (reply.headSha !== undefined && reply.headSha !== value.headSha)),
+ patch: (_input, value, _reference, reply) => {
+ if (isStalePullRequestReply(value, reply)) return value;
+ const patched = {
+ ...value,
+ ...pickDefined(reply, [
+ "title",
+ "url",
+ "author",
+ "state",
+ "isDraft",
+ "mergeability",
+ "additions",
+ "deletions",
+ "changedFiles",
+ "headBranch",
+ "baseBranch",
+ "updatedAt",
+ "mergedAt",
+ "closedAt",
+ "autoMergeEnabled",
+ "autoMergeMethod",
+ ]),
+ };
+ if (reply.autoMergeEnabled !== false) return patched;
+ const { autoMergeMethod: _disarmed, ...withoutAutoMerge } = patched;
+ return withoutAutoMerge;
+ },
+ },
+ ),
);
const detailReadVersions = Atom.family((source: ReturnType<typeof detail>) =>
Atom.family((answer: ReturnType<typeof detailAnswers>) =>
@@ -262,28 +532,48 @@ export function createPullRequestEnvironmentAtoms<R, E>(
const detailReadVersion = normalizePullRequestQuery((target) =>
detailReadVersions(detail(target))(detailAnswers(target)),
);
- const preview = writableQueryFamily(
- createEnvironmentRpcQueryAtomFamily(runtime, {
- label: "environment-data:pull-requests:preview",
- persistence: persistQuery(PullRequestPreview),
- tag: WS_METHODS.pullRequestsPreview,
- execute: (input) => routedRequest(WS_METHODS.pullRequestsPreview, input),
- staleTimeMs: 60_000,
- refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
- }),
- );
+ const previewPersistence = persistQuery(PullRequestPreview);
+ const previewQuery = (label: string) =>
+ normalizePullRequestQuery(
+ actionPatchedQuery(
+ createEnvironmentRpcQueryAtomFamily(runtime, {
+ label,
+ persistence: previewPersistence,
+ tag: WS_METHODS.pullRequestsPreview,
+ execute: (input) => routedRequest(WS_METHODS.pullRequestsPreview, input),
+ staleTimeMs: 60_000,
+ refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
+ }),
+ {
+ label,
+ persistence: previewPersistence,
+ concerns: samePullRequest,
+ rereadWithoutReply: true,
+ // Servers before action replies send unstamped previews, which only a read can order.
+ patch: (_input, value, _reference, reply) =>
+ value.updatedAt === undefined && value.observedAt === undefined
+ ? "refresh"
+ : isStalePullRequestReply(value, reply)
+ ? value
+ : {
+ ...value,
+ ...pickDefined(reply, [
+ "title",
+ "url",
+ "author",
+ "state",
+ "isDraft",
+ "updatedAt",
+ "observedAt",
+ ]),
+ },
+ },
+ ),
+ );
+ const preview = previewQuery("environment-data:pull-requests:preview");
// Hover cards read their own atoms, so a pending or failed hover read never decides where a
// click on the same link goes.
- const previewCard = writableQueryFamily(
- createEnvironmentRpcQueryAtomFamily(runtime, {
- label: "environment-data:pull-requests:preview-card",
- persistence: persistQuery(PullRequestPreview),
- tag: WS_METHODS.pullRequestsPreview,
- execute: (input) => routedRequest(WS_METHODS.pullRequestsPreview, input),
- staleTimeMs: 60_000,
- refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
- }),
- );
+ const previewCard = previewQuery("environment-data:pull-requests:preview-card");
const labelCandidates = writableQueryFamily(
createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:pull-requests:label-candidates",
@@ -364,8 +654,36 @@ export function createPullRequestEnvironmentAtoms<R, E>(
});
preparedInput = { ...actionInput, mergeMethod };
}
- return yield* routedRequest(WS_METHODS.pullRequestsRunAction, preparedInput);
+ return yield* routedRequest(WS_METHODS.pullRequestsRunAction, {
+ ...preparedInput,
+ replyWithSummary: true,
+ });
});
+ const actionReplyReaders = (registry: AtomRegistry.AtomRegistry) =>
+ Array.from(registry.getNodes().keys()).flatMap((atom) => {
+ const patch = typeof atom === "string" ? undefined : actionReplyPatches.get(atom);
+ return patch === undefined ? [] : [patch];
+ });
+ const readsInFlight = (registry: AtomRegistry.AtomRegistry): ReadonlySet<object> =>
+ new Set(actionReplyReaders(registry).flatMap((reader) => reader.pendingRead(registry) ?? []));
+ const applyActionReply = Effect.fn("PullRequests.applyActionReply")(function* (
+ registry: AtomRegistry.AtomRegistry,
+ environmentId: EnvironmentId,
+ reference: PullRequestRef,
+ reply: PullRequestSummary | undefined,
+ readsBeforeSend: ReadonlySet<object>,
+ ) {
+ for (const reader of actionReplyReaders(registry)) {
+ yield* reader.apply(registry, environmentId, reference, reply, readsBeforeSend);
+ }
+ if (reply !== undefined && reference.expectedAccountId === undefined) {
+ yield* (
+ onAnswer.actionReply?.({ environmentId, input: reference }, reply, registry) ?? Effect.void
+ );
+ }
+ });
+ const listLabel = "environment-data:pull-requests:list";
+ const listPersistence = persistQuery(PullRequestListResult);
return {
refreshes,
@@ -385,15 +703,32 @@ export function createPullRequestEnvironmentAtoms<R, E>(
staleTimeMs: 0,
idleTtlMs: 0,
}),
- list: createEnvironmentRpcQueryAtomFamily(runtime, {
- label: "environment-data:pull-requests:list",
- persistence: persistQuery(PullRequestListResult),
- tag: WS_METHODS.pullRequestsList,
- staleTimeMs: 30_000,
- refreshTrigger: ({ environmentId, input }) =>
- input.cursors === undefined ? refreshes({ environmentId, input: {} }) : undefined,
- ...(onAnswer.list === undefined ? {} : { onAnswer: onAnswer.list }),
- }),
+ list: actionPatchedQuery(
+ createEnvironmentRpcQueryAtomFamily(runtime, {
+ label: listLabel,
+ persistence: listPersistence,
+ tag: WS_METHODS.pullRequestsList,
+ staleTimeMs: 30_000,
+ refreshTrigger: ({ environmentId, input }) =>
+ input.cursors === undefined ? refreshes({ environmentId, input: {} }) : undefined,
+ ...(onAnswer.list === undefined ? {} : { onAnswer: onAnswer.list }),
+ }),
+ {
+ label: listLabel,
+ persistence: listPersistence,
+ onAnswer: onAnswer.list,
+ // Rows carry no account scope, so a reply read through another account leaves them alone.
+ concerns: (input, reference) =>
+ reference.expectedAccountId === undefined &&
+ (input.projectId === undefined || input.projectId === reference.projectId) &&
+ (input.projectIds === undefined || input.projectIds.includes(reference.projectId)) &&
+ (input.host === undefined ||
+ reference.host === undefined ||
+ input.host.toLowerCase() === reference.host.toLowerCase()),
+ refreshedByServer: (input) => input.cursors === undefined,
+ patch: patchListWithReply,
+ },
+ ),
/**
* Its own query because the listing is quicker without them — measured over twelve
* 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>(
// Preparation belongs to the write's lane. Refreshable queries would restart it after
// every preceding action, and preparing outside the lane could reorder the clicks.
execute: runAction,
- onSuccess: ({ environmentId, input }, registry) =>
- Effect.sync(() => {
- registry.refresh(preview({ environmentId, input }));
- registry.refresh(previewCard({ environmentId, input }));
- }),
+ onStart: (_target, registry) => readsInFlight(registry),
+ // Loaded readers show the reply, or re-read when the host's reply lacked the pull request.
+ onSuccess: ({ environmentId, input }, registry, reply, readsBeforeSend) => {
+ const { projectId, host, repository, number, expectedAccountId } = input;
+ return applyActionReply(
+ registry,
+ environmentId,
+ {
+ projectId,
+ ...(host === undefined ? {} : { host }),
+ repository,
+ number,
+ ...(expectedAccountId === undefined ? {} : { expectedAccountId }),
+ },
+ reply,
+ readsBeforeSend ?? new Set(),
+ );
+ },
scheduler: commandScheduler,
concurrency: serialPerEnvironment,
}),
diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.ts
index 78e0cec6437..b0ed9505728 100644
--- a/packages/client-runtime/src/state/runtime.ts
+++ b/packages/client-runtime/src/state/runtime.ts
@@ -477,6 +477,10 @@ export async function settlePromise<A>(
}
}
+/** Where a query's answer is persisted, so an action's reply can be saved where a read would be. */
+export const queryPersistenceKey = (label: string, input: unknown): string =>
+ JSON.stringify([label, input]);
+
function environmentRpcKey<Input>(target: {
readonly environmentId: EnvironmentIdType;
readonly input: Input;
@@ -765,7 +769,7 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
);
if (!options.persistence) return answer();
const persistence = options.persistence;
- const cacheKey = JSON.stringify([options.label, target.input]);
+ const cacheKey = queryPersistenceKey(options.label, target.input);
const previous = Option.flatMap(
get.self<AsyncResult.AsyncResult<A, unknown>>(),
AsyncResult.value,
@@ -960,11 +964,20 @@ export function createEnvironmentRpcCommand<
ER,
TTag extends EnvironmentUnaryRpcTag,
Input extends EnvironmentRpcInput<TTag> = EnvironmentRpcInput<TTag>,
+ Started = undefined,
>(
runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
options: {
readonly label: string;
readonly tag: TTag;
+ /** Runs once authorized, as the request starts; what it returns reaches `onSuccess`. */
+ readonly onStart?: (
+ target: {
+ readonly environmentId: EnvironmentIdType;
+ readonly input: NoInfer<Input>;
+ },
+ registry: AtomRegistry.AtomRegistry,
+ ) => Started;
readonly execute?: (
input: Input,
) => Effect.Effect<
@@ -984,6 +997,7 @@ export function createEnvironmentRpcCommand<
},
registry: AtomRegistry.AtomRegistry,
result: EnvironmentRpcSuccess<TTag>,
+ started: Started | undefined,
) => Effect.Effect<void, never, R>;
readonly onSettled?: (
target: {
@@ -1004,15 +1018,21 @@ export function createEnvironmentRpcCommand<
environmentId,
input,
};
+ let started: Started | undefined;
// Routing requires consent on the origin as well as the actual destination.
// The transport check below deliberately checks the destination again.
return permissions.authorize(registry, environmentId, input).pipe(
- Effect.andThen(() => options.execute?.(input) ?? requestGuarded(options.tag, input)),
+ Effect.andThen(() => {
+ started = options.onStart?.(target, registry);
+ return options.execute?.(input) ?? requestGuarded(options.tag, input);
+ }),
Effect.provideService(RpcPermissionGuard, {
authorize: (id, method, payload) =>
createCommandPermissions(runtime, method).authorize(registry, id, payload),
}),
- Effect.tap((result) => options.onSuccess?.(target, registry, result) ?? Effect.void),
+ Effect.tap(
+ (result) => options.onSuccess?.(target, registry, result, started) ?? Effect.void,
+ ),
Effect.ensuring(options.onSettled?.(target, registry) ?? Effect.void),
);
},
diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts
index 64111ab4742..ad18ee6303e 100644
--- a/packages/contracts/src/pullRequest.ts
+++ b/packages/contracts/src/pullRequest.ts
@@ -448,6 +448,8 @@ export const PullRequestPreview = Schema.Struct({
state: PullRequestState,
isDraft: Schema.Boolean,
createdAt: IsoDateTime,
+ updatedAt: Schema.optional(IsoDateTime),
+ observedAt: Schema.optional(Schema.Finite),
});
export type PullRequestPreview = typeof PullRequestPreview.Type;
@@ -475,6 +477,10 @@ export const PullRequestSummary = Schema.Struct({
mergeability: Schema.optional(PullRequestMergeability),
/** Null when the host says the pull request is in no stack; absent when the read did not ask. */
stack: Schema.optional(Schema.NullOr(PullRequestStackMembership)),
+ headSha: Schema.optional(TrimmedNonEmptyString),
+ /** Absent means the read did not report auto-merge state, not that it is off. */
+ autoMergeEnabled: Schema.optional(Schema.Boolean),
+ autoMergeMethod: Schema.optional(PullRequestMergeMethod),
});
export type PullRequestSummary = typeof PullRequestSummary.Type;
@@ -733,6 +739,8 @@ export const PullRequestActionInput = Schema.Struct({
action: PullRequestAction,
mergeMethod: Schema.optional(PullRequestMergeMethod),
updateMethod: Schema.optional(PullRequestUpdateMethod),
+ /** Opt-in, because older clients decode the action's success as void and reject a summary. */
+ replyWithSummary: Schema.optional(Schema.Literal(true)),
});
export type PullRequestActionInput = typeof PullRequestActionInput.Type;
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index 4171bdd7ff4..c014114cc06 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -1117,7 +1117,8 @@ const WsPullRequestsSetFilesViewedRpc = Rpc.make(WS_METHODS.pullRequestsSetFiles
const WsPullRequestsRunActionRpc = Rpc.make(WS_METHODS.pullRequestsRunAction, {
payload: PullRequestActionInput,
- success: Schema.Void,
+ // Undefined unless asked for with replyWithSummary, or when the host's reply lacked it.
+ success: Schema.UndefinedOr(PullRequestSummary),
error: PullRequestRpcError,
});
diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts
index 5856d7c0bea..07d9c2a2057 100644
--- a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts
+++ b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestCli.ts
@@ -189,7 +189,7 @@ export class AzureDevOpsPullRequestCli extends Context.Service<
readonly number: number;
readonly action: PullRequestAction;
readonly mergeMethod?: PullRequestMergeMethod;
- }) => Effect.Effect<void, AzureDevOpsPullRequestCliError>;
+ }) => Effect.Effect<AzureDevOpsPullRequest | void, AzureDevOpsPullRequestCliError>;
readonly updatePullRequest: (input: {
readonly cwd: string;
@@ -663,7 +663,13 @@ export const make = Effect.gen(function* () {
"json",
],
})
- .pipe(Effect.asVoid);
+ .pipe(
+ // `pr update` prints the pull request it left, in the shape `pr show` prints.
+ Effect.map((result) => {
+ const decoded = decodePullRequestJson(result.stdout.trim());
+ return Result.isSuccess(decoded) ? (decoded.success ?? undefined) : undefined;
+ }),
+ );
},
),
diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts
index a1d3ddb6b8c..17aaed9a930 100644
--- a/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts
+++ b/packages/source-control-azure-devops/src/server/AzureDevOpsPullRequestProvider.ts
@@ -113,6 +113,23 @@ function toChangeRequest(pullRequest: AzureDevOpsPullRequest): ProviderChangeReq
};
}
+function toSummary(pullRequest: AzureDevOpsPullRequest): ProviderChangeRequestSummary {
+ return {
+ number: pullRequest.number,
+ title: pullRequest.title,
+ url: pullRequest.url,
+ author: pullRequest.author,
+ headBranch: pullRequest.headBranch,
+ baseBranch: pullRequest.baseBranch,
+ state: pullRequest.state,
+ isDraft: pullRequest.isDraft,
+ mergeability: pullRequest.mergeability,
+ closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
+ mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
+ updatedAt: pullRequest.updatedAt,
+ };
+}
+
export const make = Effect.gen(function* () {
const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
const diffSpawns = yield* Semaphore.make(MAX_DIFF_SPAWNS);
@@ -289,23 +306,9 @@ export const make = Effect.gen(function* () {
),
getChangeRequestSummary: (input) =>
- cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(
- Effect.mapError(fail("getChangeRequestSummary")),
- Effect.map((pullRequest): ProviderChangeRequestSummary => ({
- number: pullRequest.number,
- title: pullRequest.title,
- url: pullRequest.url,
- author: pullRequest.author,
- headBranch: pullRequest.headBranch,
- baseBranch: pullRequest.baseBranch,
- state: pullRequest.state,
- isDraft: pullRequest.isDraft,
- mergeability: pullRequest.mergeability,
- closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
- mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
- updatedAt: pullRequest.updatedAt,
- })),
- ),
+ cli
+ .getPullRequest({ cwd: input.cwd, number: input.number })
+ .pipe(Effect.mapError(fail("getChangeRequestSummary")), Effect.map(toSummary)),
getChangeRequest: Effect.fn("AzureDevOpsPullRequestProvider.getChangeRequest")(
function* (input) {
@@ -535,7 +538,19 @@ export const make = Effect.gen(function* () {
action: input.action,
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
})
- .pipe(Effect.mapError(fail("runAction"))),
+ .pipe(
+ Effect.mapError(fail("runAction")),
+ Effect.map(
+ (pullRequest) =>
+ pullRequest && {
+ ...toSummary(pullRequest),
+ autoMergeEnabled: pullRequest.autoMergeEnabled,
+ ...(pullRequest.autoMergeMethod === undefined
+ ? {}
+ : { autoMergeMethod: pullRequest.autoMergeMethod }),
+ },
+ ),
+ ),
updateChangeRequest: (input) =>
cli
diff --git a/packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.ts b/packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.ts
index 4d3f96b812a..cb0d100decd 100644
--- a/packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.ts
+++ b/packages/source-control-bitbucket/src/server/BitbucketPullRequestApi.ts
@@ -228,7 +228,7 @@ export class BitbucketPullRequestApi extends Context.Service<
readonly number: number;
readonly action: PullRequestAction;
readonly mergeMethod?: PullRequestMergeMethod;
- }) => Effect.Effect<void, BitbucketPullRequestApiError>;
+ }) => Effect.Effect<BitbucketPullRequest | void, BitbucketPullRequestApiError>;
readonly updateChangeRequest: (input: {
readonly repository: string;
@@ -745,6 +745,11 @@ export const make = Effect.gen(function* () {
runAction: Effect.fn("BitbucketPullRequestApi.runAction")(function (input) {
return withRepository(input.repository, (path) => {
const pullRequest = `${path}/pullrequests/${input.number}`;
+ // Both reply with the pull request; a merge that runs long replies with a task instead.
+ const reply = Effect.map((response: { readonly body: string }) => {
+ const decoded = decodePullRequestJson(response.body);
+ return Result.isSuccess(decoded) ? decoded.success : undefined;
+ });
if (input.action === "merge") {
return bitbucket
.request({
@@ -752,11 +757,9 @@ export const make = Effect.gen(function* () {
url: `${pullRequest}/merge`,
body: JSON.stringify({ merge_strategy: mergeStrategy(input.mergeMethod) }),
})
- .pipe(Effect.asVoid);
+ .pipe(reply);
}
- return bitbucket
- .request({ method: "POST", url: `${pullRequest}/decline` })
- .pipe(Effect.asVoid);
+ return bitbucket.request({ method: "POST", url: `${pullRequest}/decline` }).pipe(reply);
});
}),
diff --git a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts
index a2bd46a285b..b5db87d089a 100644
--- a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts
+++ b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts
@@ -10,6 +10,7 @@ import {
type ProviderChangeRequest,
type ProviderChangeRequestActivity,
type ProviderChangeRequestDetail,
+ type ProviderChangeRequestSummary,
type PullRequestProviderApi,
} from "@t3tools/source-control-core/server/PullRequestProvider";
import type { BitbucketPullRequest } from "./bitbucketPullRequestJson.ts";
@@ -108,6 +109,22 @@ function toChangeRequest(pullRequest: BitbucketPullRequest): ProviderChangeReque
};
}
+/** The write's reply has no `closed_on`, line counts, or conflict state, so those stay absent. */
+function toActionSummary(pullRequest: BitbucketPullRequest): ProviderChangeRequestSummary {
+ return {
+ number: pullRequest.number,
+ title: pullRequest.title,
+ url: pullRequest.url,
+ author: pullRequest.author,
+ headBranch: pullRequest.headBranch,
+ baseBranch: pullRequest.baseBranch,
+ state: pullRequest.state,
+ isDraft: pullRequest.isDraft,
+ updatedAt: pullRequest.updatedAt,
+ ...(pullRequest.headSha ? { headSha: pullRequest.headSha } : {}),
+ };
+}
+
export const make = Effect.gen(function* () {
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
const servesHost = yield* BitbucketApi.BitbucketServesHost.pipe(Effect.orDie);
@@ -313,7 +330,10 @@ export const make = Effect.gen(function* () {
action: input.action,
...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
})
- .pipe(Effect.mapError(fail("runAction"))),
+ .pipe(
+ Effect.mapError(fail("runAction")),
+ Effect.map((pullRequest) => pullRequest && toActionSummary(pullRequest)),
+ ),
updateChangeRequest: (input) =>
api
diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts
index 3156efdd7d8..9769bc66347 100644
--- a/packages/source-control-core/src/server/PullRequestProvider.ts
+++ b/packages/source-control-core/src/server/PullRequestProvider.ts
@@ -122,6 +122,10 @@ export interface ProviderChangeRequestSummary {
readonly mergeability?: PullRequestMergeability | undefined;
/** Null means no stack; absent means not requested. */
readonly stack?: PullRequestStackMembership | null | undefined;
+ readonly headSha?: string | undefined;
+ /** Absent means the read did not report auto-merge state, not that it is off. */
+ readonly autoMergeEnabled?: boolean | undefined;
+ readonly autoMergeMethod?: PullRequestMergeMethod | undefined;
}
export interface ProviderChangeRequestStackLayer {
@@ -470,6 +474,7 @@ export interface PullRequestProviderApi {
},
) => Effect.Effect<ProviderFileRevisions, PullRequestProviderError>;
+ /** Returns the change request as the host's reply left it, or void when the reply lacks it. */
readonly runAction: (
input: ProviderRepositoryRef & {
readonly number: number;
@@ -480,7 +485,7 @@ export interface PullRequestProviderApi {
readonly mergeMethod?: PullRequestMergeMethod;
readonly updateMethod?: PullRequestUpdateMethod;
},
- ) => Effect.Effect<void, PullRequestProviderError>;
+ ) => Effect.Effect<ProviderChangeRequestSummary | void, PullRequestProviderError>;
/** Requires edit capability and at least one field. */
readonly updateChangeRequest?: (
diff --git a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts
index 9ff08b9d8a6..d9b0054fe02 100644
--- a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts
+++ b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts
@@ -9,6 +9,7 @@ import { parseDiffFileRevisions } from "@t3tools/source-control-core/server/diff
import {
PullRequestProviderError,
type ProviderChangeRequestDetail,
+ type ProviderChangeRequestSummary,
type ProviderRepositoryRef,
type PullRequestProviderApi,
} from "@t3tools/source-control-core/server/PullRequestProvider";
@@ -80,6 +81,24 @@ const issuePath = (input: ProviderRepositoryRef & { readonly number: number }) =
const reviewCommentId = (review: typeof ForgejoReview.Type) =>
/#issuecomment-([1-9]\d*)$/.exec(review.html_url ?? "")?.[1];
+const decodePullRequest = decodeJsonResult(ForgejoPullRequest);
+
+/** Only the PATCH reply carries the pull request; merge and update reply with an empty body. */
+function forgejoActionSummary(stdout: string): ProviderChangeRequestSummary | undefined {
+ const decoded = decodePullRequest(stdout);
+ if (Result.isFailure(decoded)) return undefined;
+ const pr = decoded.success;
+ // A state PATCH does not recompute conflicts, so "unknown" there would hide a known conflict.
+ const { mergeability, ...summary } = forgejoChangeRequest(pr);
+ return {
+ ...summary,
+ ...(mergeability === "unknown" ? {} : { mergeability }),
+ additions: pr.additions ?? undefined,
+ deletions: pr.deletions ?? undefined,
+ ...(pr.head.sha.trim() === "" ? {} : { headSha: pr.head.sha }),
+ };
+}
+
export const make = Effect.gen(function* () {
const cli = yield* ForgejoCli.ForgejoCli;
const failure = (operation: string, detail: string, cause?: unknown) =>
@@ -537,12 +556,12 @@ export const make = Effect.gen(function* () {
});
case "close":
case "reopen":
- return write({
+ return request({
...input,
path: pullPath(input),
method: "PATCH",
body: { state: input.action === "close" ? "closed" : "open" },
- });
+ }).pipe(Effect.map((result) => forgejoActionSummary(result.stdout)));
case "update-branch":
return write({
...input,
diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
index 7f8b4bab29d..ad60b486840 100644
--- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
+++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts
@@ -4,6 +4,7 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid";
import {
+ IsoDateTime,
NonNegativeInt,
resolvePullRequestAuthorFilter,
TrimmedNonEmptyString,
@@ -166,6 +167,17 @@ const MergeOutcome = Schema.Struct({
const StackOutcome = Schema.Struct({ id: Schema.String, state: Schema.String });
const FAILED_STACK_STATES = new Set(["failed", "stopped", "cancelled", "reconciliation_required"]);
+// A pull action replies with the pull it left; `closedAt`/`mergedAt` are read only when sent.
+const decodeActionReply = Schema.decodeUnknownOption(
+ Schema.fromJsonString(
+ Schema.Struct({
+ ...Json.GitCafePull.fields,
+ closedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
+ mergedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
+ }),
+ ),
+);
+
type PullRef = ProviderRepositoryRef & { readonly number: number };
/** 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* () {
case "reopen": {
const pull = yield* readPull(input.action, input);
const path = yield* pullPath(input.action, input);
- yield* send(input.action, input, {
+ const reply = yield* send(input.action, input, {
method: "POST",
path: `${path}/${input.action}`,
body: { expectedVersion: pull.version },
});
- return;
+ const left = decodeActionReply(reply);
+ if (Option.isNone(left)) return;
+ // The reply carries no line totals or conflict state, so they stay absent.
+ const {
+ additions: _additions,
+ deletions: _deletions,
+ mergeability: _mergeability,
+ ...summary
+ } = Json.toChangeRequest(left.value, input);
+ return {
+ ...summary,
+ ...(left.value.headOid === null ? {} : { headSha: left.value.headOid }),
+ ...(left.value.closedAt === undefined ? {} : { closedAt: left.value.closedAt }),
+ ...(left.value.mergedAt === undefined ? {} : { mergedAt: left.value.mergedAt }),
+ };
}
default:
return yield* failure(input.action, `GitCafe cannot ${input.action} from T3 Code.`);
diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
index b676a91f0ca..4ba8dceeee5 100644
--- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
@@ -2065,6 +2065,84 @@ layer("GitHubPullRequestApi.layer", (it) => {
},
});
+ it.effect.each([
+ { queued: false, field: "mergePullRequest", state: "MERGED", autoMergeRequest: null },
+ {
+ queued: true,
+ field: "enablePullRequestAutoMerge",
+ state: "OPEN",
+ autoMergeRequest: { mergeMethod: "MERGE" },
+ },
+ ] as const)(
+ "returns the pull request from GitHub's $field reply",
+ ({ queued, field, state, autoMergeRequest }) =>
+ Effect.gen(function* () {
+ const mergedAt = state === "MERGED" ? "2026-10-27T11:59:00Z" : null;
+ route(
+ ["query PullRequestActionState", actionState({ isMergeQueueEnabled: queued })],
+ [
+ field + "(",
+ {
+ data: {
+ [field]: {
+ pullRequest: {
+ number: 7,
+ title: "Pull request 7",
+ url: "https://github.com/acme/web/pull/7",
+ headRefName: "feat/page",
+ baseRefName: "main",
+ state,
+ isDraft: false,
+ updatedAt: "2026-10-27T12:00:00Z",
+ mergedAt,
+ closedAt: mergedAt,
+ headRefOid: "response-head",
+ author: { __typename: "User", login: "alice", avatarUrl: "", name: null },
+ autoMergeRequest,
+ },
+ },
+ },
+ },
+ ],
+ );
+ const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
+ expect(yield* cli.runPullRequestAction({ ...pullRequestInput, action: "merge" })).toEqual({
+ number: 7,
+ title: "Pull request 7",
+ url: "https://github.com/acme/web/pull/7",
+ headBranch: "feat/page",
+ baseBranch: "main",
+ state: state.toLowerCase(),
+ isDraft: false,
+ updatedAt: "2026-10-27T12:00:00Z",
+ mergedAt,
+ closedAt: mergedAt,
+ author: { login: "alice", name: null, avatarUrl: null },
+ headSha: "response-head",
+ autoMergeEnabled: queued,
+ ...(queued ? { autoMergeMethod: "merge" } : {}),
+ });
+ // The action-state read and the mutation; no re-read of the pull request.
+ expect(mockedExecute).toHaveBeenCalledTimes(2);
+ }),
+ );
+
+ it.effect("succeeds without a summary when GitHub's merge reply does not decode", () =>
+ Effect.gen(function* () {
+ route(
+ ["query PullRequestActionState", actionState({ isMergeQueueEnabled: false })],
+ [
+ "mergePullRequest(",
+ { data: { mergePullRequest: { pullRequest: { state: "MERGING" } } } },
+ ],
+ );
+ const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
+ expect(
+ yield* cli.runPullRequestAction({ ...pullRequestInput, action: "merge" }),
+ ).toBeUndefined();
+ }),
+ );
+
it.effect.each([
{
description: "base-only write",
@@ -3446,7 +3524,7 @@ layer("GitHubPullRequestApi.layer", (it) => {
checkSuite: { workflowRun: { workflow: { name: "windows" } } },
}),
],
- pageInfo: { hasNextPage: false },
+ pageInfo: { hasNextPage: false, endCursor: null },
},
},
},
@@ -3483,7 +3561,7 @@ layer("GitHubPullRequestApi.layer", (it) => {
);
it.effect.each([false, true])(
- "reads every check when the combined response has another page (reviewer refusal: %s)",
+ "continues after the core check page without reading it twice (reviewer refusal: %s)",
(refused) =>
Effect.gen(function* () {
if (refused) mockedExecute.mockReturnValueOnce(refusedReviewerResponse());
@@ -3498,13 +3576,7 @@ layer("GitHubPullRequestApi.layer", (it) => {
commit: {
statusCheckRollup: {
contexts: {
- nodes: [
- checkRun({
- name: "first",
- status: "COMPLETED",
- conclusion: "SUCCESS",
- }),
- ],
+ nodes: [checkRun({ name: "first", conclusion: "SUCCESS" })],
pageInfo: { hasNextPage: true, endCursor: "c1" },
},
},
@@ -3519,15 +3591,7 @@ layer("GitHubPullRequestApi.layer", (it) => {
);
mockedExecute.mockReturnValueOnce(
Effect.succeed(
- output(
- checkContextsPage(
- [
- checkRun({ name: "first", status: "COMPLETED", conclusion: "SUCCESS" }),
- checkRun({ name: "last", status: "COMPLETED", conclusion: "FAILURE" }),
- ],
- null,
- ),
- ),
+ output(checkContextsPage([checkRun({ name: "last", conclusion: "FAILURE" })], null)),
),
);
const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi;
@@ -3543,12 +3607,12 @@ layer("GitHubPullRequestApi.layer", (it) => {
expect(variablesOf("PullRequestCore").map((v) => v["requestedReviewers"])).toEqual([
100, 0,
]);
- expect(detail.checks).toHaveLength(2);
+ expect(detail.checks.map((check) => check.name).sort()).toEqual(["first", "last"]);
expect(detail.checksState).toBe("failing");
expect(detail.checksTruncated).toBe(false);
- // The whole rollup is walked from its start, so no check is counted twice or skipped.
- expect(variablesOf("CheckContexts")).toEqual([expect.objectContaining({ number: 7 })]);
- expect(variablesOf("CheckContexts")[0]).not.toHaveProperty("after");
+ expect(variablesOf("CheckContexts")).toEqual([
+ expect.objectContaining({ number: 7, after: "c1" }),
+ ]);
expect(mockedExecute).toHaveBeenCalledTimes(refused ? 3 : 2);
if (refused) {
@@ -3573,7 +3637,7 @@ layer("GitHubPullRequestApi.layer", (it) => {
statusCheckRollup: {
contexts: {
nodes: [],
- pageInfo: { hasNextPage: true },
+ pageInfo: { hasNextPage: true, endCursor: "c1" },
},
},
},
diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts
index cb96b97d855..cb3c3d994b4 100644
--- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts
+++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts
@@ -50,7 +50,10 @@ import * as GitHubRest from "./GitHubRest.ts";
import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
import * as GitHubGraphQlClient from "./gitHubGraphQlClient.ts";
import { PullRequestBatchesGraphQLGroup } from "./pullRequestBatches.graphql.ts";
-import { PullRequestMutationsGraphQLGroup } from "./pullRequestMutations.graphql.ts";
+import {
+ PullRequestMutationsGraphQLGroup,
+ type PullRequestActionSummary,
+} from "./pullRequestMutations.graphql.ts";
import { PullRequestReadsGraphQLGroup } from "./pullRequestReads.graphql.ts";
import { PullRequestReviewsGraphQLGroup } from "./pullRequestReviews.graphql.ts";
import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
@@ -73,6 +76,7 @@ import {
toRepositoryAuthors,
toRepositoryLabels,
toPullRequestActivityPage,
+ toPullRequestActionSummary,
toPullRequestCommitStats,
toPullRequestCheckContextsPage,
toPullRequestCore,
@@ -658,7 +662,7 @@ export class GitHubPullRequestApi extends Context.Service<
readonly removeAgentCreditsOnMerge?: boolean;
readonly mergeMethod?: PullRequestMergeMethod;
readonly updateMethod?: PullRequestUpdateMethod;
- }) => Effect.Effect<void, GitHubPullRequestApiError>;
+ }) => Effect.Effect<ProviderChangeRequestSummary | void, GitHubPullRequestApiError>;
readonly commentOnPullRequest: (input: {
readonly cwd: string;
@@ -1378,48 +1382,35 @@ export const make = Effect.gen(function* () {
const readAllCheckContexts = Effect.fn("GitHubPullRequestApi.readAllCheckContexts")(function* (
input: Parameters<GitHubPullRequestApi["Service"]["getPullRequestDetail"]>[0],
allowReserve: boolean,
+ first: NonNullable<ReturnType<typeof toPullRequestCheckContextsPage>>,
) {
const { owner, name } = parseRepositorySelector(input.repository);
const target = { ...input, operation: "getPullRequestDetail", allowReserve };
- let headSha: string | null = null;
- const { pages, truncated } = yield* readPages(
- GraphQLClient.pages(client.PullRequestCheckContexts, {
- variables: { owner, name, number: input.number, required: asksRequired(input.host) },
- connection: (result) => {
- const page = toPullRequestCheckContextsPage(result);
- if (page === null) return null;
- headSha ??= page.headSha;
- return {
- ...page,
- // Past the first page a different head is a push mid-walk.
- changed: page.headSha !== headSha,
- pageInfo: { hasNextPage: page.nextCursor !== null, endCursor: page.nextCursor },
- };
- },
- }).pipe(
- Stream.mapEffect((page) =>
- page.changed
- ? Effect.fail(
- readError(
- input.cwd,
- "getPullRequestDetail",
- new Error("Pull request head changed while reading checks."),
- ),
- )
- : Effect.succeed(page),
- ),
- ),
- {
- ...target,
- maxPages: CHECK_CONTEXT_PAGES,
- hasNextPage: (page) => page.nextCursor !== null,
- },
- ).pipe(graphql(target));
- return {
- headSha: pages[0]?.headSha ?? null,
- contexts: pages.flatMap((page) => page.contexts),
- truncated,
- };
+ const contexts = [...first.contexts];
+ let after = first.nextCursor;
+ for (let page = 1; after !== null && page < CHECK_CONTEXT_PAGES; page++) {
+ const result = yield* client
+ .PullRequestCheckContexts({
+ owner,
+ name,
+ number: input.number,
+ required: asksRequired(input.host),
+ after,
+ })
+ .pipe(graphql(target));
+ const next = toPullRequestCheckContextsPage(result);
+ if (next === null || next.headSha !== first.headSha) {
+ return yield* readError(
+ input.cwd,
+ "getPullRequestDetail",
+ new Error("Pull request head changed while reading checks."),
+ );
+ }
+ if (next.nextCursor === after) return { contexts, truncated: true };
+ contexts.push(...next.contexts);
+ after = next.nextCursor;
+ }
+ return { contexts, truncated: first.nextCursor === null || after !== null };
});
// 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* () {
Effect.flatMap((allowReserve) =>
readRequestedReviewers(input, 100, read).pipe(
graphql({ ...input, operation, allowReserve }),
- Effect.map(toPullRequestCore),
- Effect.flatMap(found({ ...input, operation })),
- // Past a hundred checks the first page would let the rest imply success, so the whole
- // rollup is walked instead.
- Effect.filterOrElse(
- (core) => !core.checksTruncated,
- (core) =>
- readAllCheckContexts(input, allowReserve).pipe(
- Effect.filterOrFail(
- (all) => all.headSha === core.headSha,
- () =>
- readError(
- input.cwd,
- operation,
- new Error("Pull request head changed while reading checks."),
- ),
- ),
- Effect.map((all) => ({
- ...core,
- ...pullRequestChecksFromContexts(all.contexts),
- checksTruncated: all.truncated,
- })),
+ Effect.flatMap((result) =>
+ found({ ...input, operation })(toPullRequestCore(result)).pipe(
+ Effect.filterOrElse(
+ (core) => !core.checksTruncated,
+ (core) =>
+ readAllCheckContexts(
+ input,
+ allowReserve,
+ toPullRequestCheckContextsPage(result)!,
+ ).pipe(
+ Effect.map((all) => ({
+ ...core,
+ ...pullRequestChecksFromContexts(all.contexts),
+ checksTruncated: all.truncated,
+ })),
+ ),
),
+ ),
),
),
),
@@ -1636,17 +1622,39 @@ export const make = Effect.gen(function* () {
const simpleActionMutations = {
"disable-auto-merge": (pullRequestId: string) =>
- client.DisablePullRequestAutoMerge({ pullRequestId }).pipe(Effect.asVoid),
+ client
+ .DisablePullRequestAutoMerge({ pullRequestId })
+ .pipe(Effect.map((result) => result.disablePullRequestAutoMerge?.pullRequest)),
ready: (pullRequestId: string) =>
- client.MarkPullRequestReadyForReview({ pullRequestId }).pipe(Effect.asVoid),
+ client
+ .MarkPullRequestReadyForReview({ pullRequestId })
+ .pipe(Effect.map((result) => result.markPullRequestReadyForReview?.pullRequest)),
draft: (pullRequestId: string) =>
- client.ConvertPullRequestToDraft({ pullRequestId }).pipe(Effect.asVoid),
+ client
+ .ConvertPullRequestToDraft({ pullRequestId })
+ .pipe(Effect.map((result) => result.convertPullRequestToDraft?.pullRequest)),
close: (pullRequestId: string) =>
- client.ClosePullRequest({ pullRequestId }).pipe(Effect.asVoid),
+ client
+ .ClosePullRequest({ pullRequestId })
+ .pipe(Effect.map((result) => result.closePullRequest?.pullRequest)),
reopen: (pullRequestId: string) =>
- client.ReopenPullRequest({ pullRequestId }).pipe(Effect.asVoid),
+ client
+ .ReopenPullRequest({ pullRequestId })
+ .pipe(Effect.map((result) => result.reopenPullRequest?.pullRequest)),
} satisfies Partial<Record<PullRequestAction, unknown>>;
+ /** The mutation already landed, so a reply that does not decode only loses the summary. */
+ const actionSummary = <E, R>(
+ effect: Effect.Effect<PullRequestActionSummary | null | undefined, E, R>,
+ ) =>
+ effect.pipe(
+ Effect.map(toPullRequestActionSummary),
+ Effect.catchIf(
+ (error) => isGraphQlClientError(error) && error.reason._tag === "DecodeError",
+ () => Effect.void,
+ ),
+ );
+
/** Preserve policy errors; map not-found per lookup and other failures to read errors. */
const batchedRead = <A, E, R>(
input: { readonly cwd: string; readonly host: string; readonly operation: string },
@@ -2575,7 +2583,9 @@ export const make = Effect.gen(function* () {
const mutate = simpleActionMutations[action as keyof typeof simpleActionMutations];
return pullRequestNodeId({ ...input, operation: "runPullRequestAction" }).pipe(
Effect.flatMap((pullRequestId) =>
- mutate(pullRequestId).pipe(graphql({ ...input, operation: "runPullRequestAction" })),
+ actionSummary(mutate(pullRequestId)).pipe(
+ graphql({ ...input, operation: "runPullRequestAction" }),
+ ),
),
);
}
@@ -2603,7 +2613,11 @@ export const make = Effect.gen(function* () {
expectedHeadOid: state.headRefOid,
updateMethod: input.updateMethod === "rebase" ? "REBASE" : "MERGE",
})
- .pipe(graphql(target), Effect.asVoid);
+ .pipe(
+ Effect.map((result) => result.updatePullRequestBranch?.pullRequest),
+ actionSummary,
+ graphql(target),
+ );
}
let body: string | undefined;
let expectedHead: string | undefined;
@@ -2641,10 +2655,14 @@ export const make = Effect.gen(function* () {
...(expectedHead === undefined ? {} : { expectedHeadOid: expectedHead }),
...(body === undefined ? {} : { commitBody: body }),
};
- yield* (
+ return yield* actionSummary(
auto
- ? client.EnablePullRequestAutoMerge({ input: merge }).pipe(Effect.asVoid)
- : client.MergePullRequest({ input: merge }).pipe(Effect.asVoid)
+ ? client
+ .EnablePullRequestAutoMerge({ input: merge })
+ .pipe(Effect.map((result) => result.enablePullRequestAutoMerge?.pullRequest))
+ : client
+ .MergePullRequest({ input: merge })
+ .pipe(Effect.map((result) => result.mergePullRequest?.pullRequest)),
).pipe(graphql(target));
});
}),
diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts
index c816f76a780..58b7969277c 100644
--- a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts
+++ b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts
@@ -379,7 +379,10 @@ describe("pull request detail decoding", () => {
{
commit: {
statusCheckRollup: {
- contexts: { nodes: rollup, pageInfo: { hasNextPage: false } },
+ contexts: {
+ nodes: rollup,
+ pageInfo: { hasNextPage: false, endCursor: null },
+ },
},
},
},
diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.ts
index 7b8851f7bed..76c101766b3 100644
--- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts
+++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts
@@ -37,6 +37,7 @@ import type {
import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { dedupeChecks } from "@t3tools/source-control-core/server/pullRequestChecks";
+import type { ProviderChangeRequestSummary } from "@t3tools/source-control-core/server/PullRequestProvider";
import type * as GitHubSchema from "../../schema/github.graphql.ts";
import type {
@@ -49,6 +50,7 @@ import {
PullRequestRow,
PullRequestSearch,
} from "./pullRequestListings.graphql.ts";
+import type { PullRequestActionSummary } from "./pullRequestMutations.graphql.ts";
import type {
CheckContext,
LabelCandidates,
@@ -479,6 +481,29 @@ function toMergeMethod(value: string | null | undefined): PullRequestMergeMethod
}
}
+export function toPullRequestActionSummary(
+ raw: PullRequestActionSummary | null | undefined,
+): ProviderChangeRequestSummary | undefined {
+ if (raw == null) return undefined;
+ const autoMergeMethod = toMergeMethod(raw.autoMergeRequest?.mergeMethod);
+ return {
+ number: raw.number,
+ title: raw.title,
+ url: raw.url,
+ headBranch: raw.headRefName,
+ baseBranch: raw.baseRefName,
+ state: toState(raw),
+ isDraft: raw.isDraft,
+ updatedAt: raw.updatedAt,
+ mergedAt: trimmed(raw.mergedAt),
+ closedAt: trimmed(raw.closedAt),
+ author: toActor(raw.author),
+ headSha: raw.headRefOid,
+ autoMergeEnabled: raw.autoMergeRequest !== null,
+ ...(autoMergeMethod === undefined ? {} : { autoMergeMethod }),
+ };
+}
+
/** GitHub's reviewDecision ignores reviews outside branch rules, including app approvals. */
function toReviewDecisionWithReviews(
value: string | null | undefined,
diff --git a/packages/source-control-github/src/server/pullRequestMutations.graphql b/packages/source-control-github/src/server/pullRequestMutations.graphql
index 3e2d5b3133a..550b26ca4fd 100644
--- a/packages/source-control-github/src/server/pullRequestMutations.graphql
+++ b/packages/source-control-github/src/server/pullRequestMutations.graphql
@@ -1,5 +1,29 @@
-# Writes to a pull request and the remarks on it. None reads its answer back beyond what GitHub
-# requires a mutation to select.
+# Writes to a pull request and the remarks on it. Only pull request actions read their answer back,
+# so clients can show the result without another read.
+
+fragment PullRequestActionSummary on PullRequest {
+ number
+ title
+ url
+ headRefName
+ baseRefName
+ state
+ isDraft
+ updatedAt
+ mergedAt
+ closedAt
+ headRefOid
+ author {
+ login
+ avatarUrl
+ ... on User {
+ name
+ }
+ }
+ autoMergeRequest {
+ mergeMethod
+ }
+}
mutation AddReviewThreadReply($threadId: ID!, $body: String!) {
addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $threadId, body: $body }) {
@@ -105,19 +129,25 @@ mutation SetFileViewed($pullRequestId: ID!, $path: String!, $viewed: Boolean!) {
mutation MergePullRequest($input: MergePullRequestInput!) {
mergePullRequest(input: $input) {
- clientMutationId
+ pullRequest {
+ ...PullRequestActionSummary
+ }
}
}
mutation EnablePullRequestAutoMerge($input: EnablePullRequestAutoMergeInput!) {
enablePullRequestAutoMerge(input: $input) {
- clientMutationId
+ pullRequest {
+ ...PullRequestActionSummary
+ }
}
}
mutation DisablePullRequestAutoMerge($pullRequestId: ID!) {
disablePullRequestAutoMerge(input: { pullRequestId: $pullRequestId }) {
- clientMutationId
+ pullRequest {
+ ...PullRequestActionSummary
+ }
}
}
@@ -133,31 +163,41 @@ mutation UpdatePullRequestBranch(
updateMethod: $updateMethod
}
) {
- clientMutationId
+ pullRequest {
+ ...PullRequestActionSummary
+ }
}
}
mutation MarkPullRequestReadyForReview($pullRequestId: ID!) {
markPullRequestReadyForReview(input: { pullRequestId: $pullRequestId }) {
- clientMutationId
+ pullRequest {
+ ...PullRequestActionSummary
+ }
}
}
mutation ConvertPullRequestToDraft($pullRequestId: ID!) {
convertPullRequestToDraft(input: { pullRequestId: $pullRequestId }) {
- clientMutationId
+ pullRequest {
+ ...PullRequestActionSummary
+ }
}
}
mutation ClosePullRequest($pullRequestId: ID!) {
closePullRequest(input: { pullRequestId: $pullRequestId }) {
- clientMutationId
+ pullRequest {
+ ...PullRequestActionSummary
+ }
}
}
mutation ReopenPullRequest($pullRequestId: ID!) {
reopenPullRequest(input: { pullRequestId: $pullRequestId }) {
- clientMutationId
+ pullRequest {
+ ...PullRequestActionSummary
+ }
}
}
diff --git a/packages/source-control-github/src/server/pullRequestMutations.graphql.ts b/packages/source-control-github/src/server/pullRequestMutations.graphql.ts
index d11b2b1e69f..b62bf959731 100644
--- a/packages/source-control-github/src/server/pullRequestMutations.graphql.ts
+++ b/packages/source-control-github/src/server/pullRequestMutations.graphql.ts
@@ -3,6 +3,76 @@ import { GraphQL, GraphQLGroup } from "effect/graphql"
import * as Schema from "effect/Schema"
import * as Shared from "../../schema/github.graphql.ts"
+/** A user is an individual's account on GitHub that owns repositories and can make new content. */
+export const User = Schema.Struct({
+ __typename: Schema.Literal("User"),
+ /** The username used to login. */
+ login: Schema.String,
+ /** A URL pointing to the user's public avatar. */
+ avatarUrl: Shared.URI,
+ /** The user's public profile name. */
+ name: Schema.NullOr(Schema.String)
+})
+export interface User extends Schema.Struct.Type<typeof User.fields> {}
+
+/** Represents an object which can take actions on GitHub. Typically a User or Bot. */
+export const ActorOther = Schema.Struct({
+ __typename: GraphQL.otherTypename<Shared.Typename.Actor>()(["User"]),
+ /** The username of the actor. */
+ login: Schema.String,
+ /** A URL pointing to the actor's public avatar. */
+ avatarUrl: Shared.URI
+})
+export interface ActorOther extends Schema.Struct.Type<typeof ActorOther.fields> {}
+
+/** Represents an auto-merge request for a pull request */
+export const AutoMergeRequest = Schema.Struct({
+ /**
+ * The merge method of the auto-merge request. If a merge queue is required by
+ * the base branch, this value will be set by the merge queue when merging.
+ */
+ mergeMethod: GraphQL.enumLiterals(Shared.PullRequestMergeMethod.literals)
+})
+export interface AutoMergeRequest extends Schema.Struct.Type<typeof AutoMergeRequest.fields> {}
+
+/**
+ * `fragment PullRequestActionSummary on PullRequest`
+ *
+ * A repository pull request.
+ */
+export const PullRequestActionSummary = Schema.Struct({
+ /** Identifies the pull request number. */
+ number: Shared.Int,
+ /** Identifies the pull request title. */
+ title: Schema.String,
+ /** The HTTP URL for this pull request. */
+ url: Shared.URI,
+ /** Identifies the name of the head Ref associated with the pull request, even if the ref has been deleted. */
+ headRefName: Schema.String,
+ /** Identifies the name of the base Ref associated with the pull request, even if the ref has been deleted. */
+ baseRefName: Schema.String,
+ /** Identifies the state of the pull request. */
+ state: GraphQL.enumLiterals(Shared.PullRequestState.literals),
+ /** Identifies if the pull request is a draft. */
+ isDraft: Schema.Boolean,
+ /** Identifies the date and time when the object was last updated. */
+ updatedAt: Shared.DateTime,
+ /** The date and time that the pull request was merged. */
+ mergedAt: Schema.NullOr(Shared.DateTime),
+ /** Identifies the date and time when the object was closed. */
+ closedAt: Schema.NullOr(Shared.DateTime),
+ /** Identifies the oid of the head ref associated with the pull request, even if the ref has been deleted. */
+ headRefOid: Shared.GitObjectID,
+ /** The actor who authored the comment. */
+ author: Schema.NullOr(Schema.Union([
+ User,
+ ActorOther
+ ])),
+ /** Returns the auto-merge request object if one exists for this pull request. */
+ autoMergeRequest: Schema.NullOr(AutoMergeRequest)
+})
+export interface PullRequestActionSummary extends Schema.Struct.Type<typeof PullRequestActionSummary.fields> {}
+
/** A review comment associated with a given repository pull request. */
export const PullRequestReviewComment = Schema.Struct({
/** The Node ID of the PullRequestReviewComment object */
@@ -380,8 +450,8 @@ export declare namespace SetFileViewed {
/** Autogenerated return type of MergePullRequest. */
export const MergePullRequestPayload = Schema.Struct({
- /** A unique identifier for the client performing the mutation. */
- clientMutationId: Schema.NullOr(Schema.String)
+ /** The pull request that was merged. */
+ pullRequest: Schema.NullOr(PullRequestActionSummary)
})
export interface MergePullRequestPayload extends Schema.Struct.Type<typeof MergePullRequestPayload.fields> {}
@@ -392,9 +462,11 @@ export const MergePullRequest = GraphQL.mutation("MergePullRequest", {
{ name: "input", body: "MergePullRequestInput!" }
],
selections: [
- { name: "mergePullRequest", body: ["(input:$", "input", "){clientMutationId}"] }
+ { name: "mergePullRequest", body: ["(input:$", "input", "){pullRequest{...PullRequestActionSummary}}"] }
],
- fragments: []
+ fragments: [
+ { 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}}"] }
+ ]
},
variables: {
input: Shared.MergePullRequestInput
@@ -418,8 +490,8 @@ export declare namespace MergePullRequest {
/** Autogenerated return type of EnablePullRequestAutoMerge. */
export const EnablePullRequestAutoMergePayload = Schema.Struct({
- /** A unique identifier for the client performing the mutation. */
- clientMutationId: Schema.NullOr(Schema.String)
+ /** The pull request auto-merge was enabled on. */
+ pullRequest: Schema.NullOr(PullRequestActionSummary)
})
export interface EnablePullRequestAutoMergePayload extends Schema.Struct.Type<typeof EnablePullRequestAutoMergePayload.fields> {}
@@ -430,9 +502,11 @@ export const EnablePullRequestAutoMerge = GraphQL.mutation("EnablePullRequestAut
{ name: "input", body: "EnablePullRequestAutoMergeInput!" }
],
selections: [
- { name: "enablePullRequestAutoMerge", body: ["(input:$", "input", "){clientMutationId}"] }
+ { name: "enablePullRequestAutoMerge", body: ["(input:$", "input", "){pullRequest{...PullRequestActionSummary}}"] }
],
- fragments: []
+ fragments: [
+ { 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}}"] }
+ ]
},
variables: {
input: Shared.EnablePullRequestAutoMergeInput
@@ -449,8 +523,8 @@ export declare namespace EnablePullRequestAutoMerge {
/** Autogenerated return type of DisablePullRequestAutoMerge. */
export const DisablePullRequestAutoMergePayload = Schema.Struct({
- /** A unique identifier for the client performing the mutation. */
- clientMutationId: Schema.NullOr(Schema.String)
+ /** The pull request auto merge was disabled on. */
+ pullRequest: Schema.NullOr(PullRequestActionSummary)
})
export interface DisablePullRequestAutoMergePayload extends Schema.Struct.Type<typeof DisablePullRequestAutoMergePayload.fields> {}
@@ -461,9 +535,11 @@ export const DisablePullRequestAutoMerge = GraphQL.mutation("DisablePullRequestA
{ name: "pullRequestId", body: "ID!" }
],
selections: [
- { name: "disablePullRequestAutoMerge", body: ["(input:{pullRequestId:$", "pullRequestId", "}){clientMutationId}"] }
+ { name: "disablePullRequestAutoMerge", body: ["(input:{pullRequestId:$", "pullRequestId", "}){pullRequest{...PullRequestActionSummary}}"] }
],
- fragments: []
+ fragments: [
+ { 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}}"] }
+ ]
},
variables: {
pullRequestId: Shared.ID
@@ -480,8 +556,8 @@ export declare namespace DisablePullRequestAutoMerge {
/** Autogenerated return type of UpdatePullRequestBranch. */
export const UpdatePullRequestBranchPayload = Schema.Struct({
- /** A unique identifier for the client performing the mutation. */
- clientMutationId: Schema.NullOr(Schema.String)
+ /** The updated pull request. */
+ pullRequest: Schema.NullOr(PullRequestActionSummary)
})
export interface UpdatePullRequestBranchPayload extends Schema.Struct.Type<typeof UpdatePullRequestBranchPayload.fields> {}
@@ -494,9 +570,11 @@ export const UpdatePullRequestBranch = GraphQL.mutation("UpdatePullRequestBranch
{ name: "updateMethod", body: "PullRequestBranchUpdateMethod!" }
],
selections: [
- { name: "updatePullRequestBranch", body: ["(input:{pullRequestId:$", "pullRequestId", " expectedHeadOid:$", "expectedHeadOid", " updateMethod:$", "updateMethod", "}){clientMutationId}"] }
+ { name: "updatePullRequestBranch", body: ["(input:{pullRequestId:$", "pullRequestId", " expectedHeadOid:$", "expectedHeadOid", " updateMethod:$", "updateMethod", "}){pullRequest{...PullRequestActionSummary}}"] }
],
- fragments: []
+ fragments: [
+ { 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}}"] }
+ ]
},
variables: {
pullRequestId: Shared.ID,
@@ -515,8 +593,8 @@ export declare namespace UpdatePullRequestBranch {
/** Autogenerated return type of MarkPullRequestReadyForReview. */
export const MarkPullRequestReadyForReviewPayload = Schema.Struct({
- /** A unique identifier for the client performing the mutation. */
- clientMutationId: Schema.NullOr(Schema.String)
+ /** The pull request that is ready for review. */
+ pullRequest: Schema.NullOr(PullRequestActionSummary)
})
export interface MarkPullRequestReadyForReviewPayload extends Schema.Struct.Type<typeof MarkPullRequestReadyForReviewPayload.fields> {}
@@ -527,9 +605,11 @@ export const MarkPullRequestReadyForReview = GraphQL.mutation("MarkPullRequestRe
{ name: "pullRequestId", body: "ID!" }
],
selections: [
- { name: "markPullRequestReadyForReview", body: ["(input:{pullRequestId:$", "pullRequestId", "}){clientMutationId}"] }
+ { name: "markPullRequestReadyForReview", body: ["(input:{pullRequestId:$", "pullRequestId", "}){pullRequest{...PullRequestActionSummary}}"] }
],
- fragments: []
+ fragments: [
+ { 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}}"] }
+ ]
},
variables: {
pullRequestId: Shared.ID
@@ -546,8 +626,8 @@ export declare namespace MarkPullRequestReadyForReview {
/** Autogenerated return type of ConvertPullRequestToDraft. */
export const ConvertPullRequestToDraftPayload = Schema.Struct({
- /** A unique identifier for the client performing the mutation. */
- clientMutationId: Schema.NullOr(Schema.String)
+ /** The pull request that is now a draft. */
+ pullRequest: Schema.NullOr(PullRequestActionSummary)
})
export interface ConvertPullRequestToDraftPayload extends Schema.Struct.Type<typeof ConvertPullRequestToDraftPayload.fields> {}
@@ -558,9 +638,11 @@ export const ConvertPullRequestToDraft = GraphQL.mutation("ConvertPullRequestToD
{ name: "pullRequestId", body: "ID!" }
],
selections: [
- { name: "convertPullRequestToDraft", body: ["(input:{pullRequestId:$", "pullRequestId", "}){clientMutationId}"] }
+ { name: "convertPullRequestToDraft", body: ["(input:{pullRequestId:$", "pullRequestId", "}){pullRequest{...PullRequestActionSummary}}"] }
],
- fragments: []
+ fragments: [
+ { 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}}"] }
+ ]
},
variables: {
pullRequestId: Shared.ID
@@ -577,8 +659,8 @@ export declare namespace ConvertPullRequestToDraft {
/** Autogenerated return type of ClosePullRequest. */
export const ClosePullRequestPayload = Schema.Struct({
- /** A unique identifier for the client performing the mutation. */
- clientMutationId: Schema.NullOr(Schema.String)
+ /** The pull request that was closed. */
+ pullRequest: Schema.NullOr(PullRequestActionSummary)
})
export interface ClosePullRequestPayload extends Schema.Struct.Type<typeof ClosePullRequestPayload.fields> {}
@@ -589,9 +671,11 @@ export const ClosePullRequest = GraphQL.mutation("ClosePullRequest", {
{ name: "pullRequestId", body: "ID!" }
],
selections: [
- { name: "closePullRequest", body: ["(input:{pullRequestId:$", "pullRequestId", "}){clientMutationId}"] }
+ { name: "closePullRequest", body: ["(input:{pullRequestId:$", "pullRequestId", "}){pullRequest{...PullRequestActionSummary}}"] }
],
- fragments: []
+ fragments: [
+ { 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}}"] }
+ ]
},
variables: {
pullRequestId: Shared.ID
@@ -608,8 +692,8 @@ export declare namespace ClosePullRequest {
/** Autogenerated return type of ReopenPullRequest. */
export const ReopenPullRequestPayload = Schema.Struct({
- /** A unique identifier for the client performing the mutation. */
- clientMutationId: Schema.NullOr(Schema.String)
+ /** The pull request that was reopened. */
+ pullRequest: Schema.NullOr(PullRequestActionSummary)
})
export interface ReopenPullRequestPayload extends Schema.Struct.Type<typeof ReopenPullRequestPayload.fields> {}
@@ -620,9 +704,11 @@ export const ReopenPullRequest = GraphQL.mutation("ReopenPullRequest", {
{ name: "pullRequestId", body: "ID!" }
],
selections: [
- { name: "reopenPullRequest", body: ["(input:{pullRequestId:$", "pullRequestId", "}){clientMutationId}"] }
+ { name: "reopenPullRequest", body: ["(input:{pullRequestId:$", "pullRequestId", "}){pullRequest{...PullRequestActionSummary}}"] }
],
- fragments: []
+ fragments: [
+ { 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}}"] }
+ ]
},
variables: {
pullRequestId: Shared.ID
diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql b/packages/source-control-github/src/server/pullRequestReads.graphql
index 78e5efe0e45..f317ae0f5ea 100644
--- a/packages/source-control-github/src/server/pullRequestReads.graphql
+++ b/packages/source-control-github/src/server/pullRequestReads.graphql
@@ -156,6 +156,7 @@ query PullRequestCore(
}
pageInfo {
hasNextPage
+ endCursor
}
}
}
diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql.ts b/packages/source-control-github/src/server/pullRequestReads.graphql.ts
index 5bc09fa4e2c..ff19cfd0f6a 100644
--- a/packages/source-control-github/src/server/pullRequestReads.graphql.ts
+++ b/packages/source-control-github/src/server/pullRequestReads.graphql.ts
@@ -310,32 +310,34 @@ export const PullRequestCoreRepositoryPullRequestLabelsLabelConnection = Schema.
export interface PullRequestCoreRepositoryPullRequestLabelsLabelConnection extends Schema.Struct.Type<typeof PullRequestCoreRepositoryPullRequestLabelsLabelConnection.fields> {}
/** Information about pagination in a connection. */
-export const PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo = Schema.Struct({
+export const ContextsPageInfoPageInfo = Schema.Struct({
/** When paginating forwards, are there more items? */
- hasNextPage: Schema.Boolean
+ hasNextPage: Schema.Boolean,
+ /** When paginating forwards, the cursor to continue. */
+ endCursor: Schema.NullOr(Schema.String)
})
-export interface PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo extends Schema.Struct.Type<typeof PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo.fields> {}
+export interface ContextsPageInfoPageInfo extends Schema.Struct.Type<typeof ContextsPageInfoPageInfo.fields> {}
/** The connection type for StatusCheckRollupContext. */
-export const PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsStatusCheckRollupContextConnection = Schema.Struct({
+export const StatusCheckRollupContextConnection = Schema.Struct({
/** A list of nodes. */
nodes: Schema.NullOr(Schema.Array(Schema.NullOr(CheckContext))),
/** Information to aid in pagination. */
- pageInfo: PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo
+ pageInfo: ContextsPageInfoPageInfo
})
-export interface PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsStatusCheckRollupContextConnection extends Schema.Struct.Type<typeof PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsStatusCheckRollupContextConnection.fields> {}
+export interface StatusCheckRollupContextConnection extends Schema.Struct.Type<typeof StatusCheckRollupContextConnection.fields> {}
/** Represents the rollup for both the check runs and status for a commit. */
-export const PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupStatusCheckRollup = Schema.Struct({
+export const StatusCheckRollup = Schema.Struct({
/** A list of status contexts and check runs for this commit. */
- contexts: PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsStatusCheckRollupContextConnection
+ contexts: StatusCheckRollupContextConnection
})
-export interface PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupStatusCheckRollup extends Schema.Struct.Type<typeof PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupStatusCheckRollup.fields> {}
+export interface StatusCheckRollup extends Schema.Struct.Type<typeof StatusCheckRollup.fields> {}
/** Represents a Git commit. */
export const PullRequestCoreRepositoryPullRequestCommitsNodesCommitCommit = Schema.Struct({
/** Check and Status rollup information for this commit. */
- statusCheckRollup: Schema.NullOr(PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupStatusCheckRollup)
+ statusCheckRollup: Schema.NullOr(StatusCheckRollup)
})
export interface PullRequestCoreRepositoryPullRequestCommitsNodesCommitCommit extends Schema.Struct.Type<typeof PullRequestCoreRepositoryPullRequestCommitsNodesCommitCommit.fields> {}
@@ -459,7 +461,7 @@ export const PullRequestCore = GraphQL.query("PullRequestCore", {
{ name: "requestedReviewers", body: "Int!" }
],
selections: [
- { 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}}}}}}}}"] }
+ { 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}}}}}}}}"] }
],
fragments: [
{ 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 {
export type Result = typeof PullRequestCore.result.Type
}
-/** Information about pagination in a connection. */
-export const PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo = Schema.Struct({
- /** When paginating forwards, are there more items? */
- hasNextPage: Schema.Boolean,
- /** When paginating forwards, the cursor to continue. */
- endCursor: Schema.NullOr(Schema.String)
-})
-export interface PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo extends Schema.Struct.Type<typeof PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo.fields> {}
-
-/** The connection type for StatusCheckRollupContext. */
-export const PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsStatusCheckRollupContextConnection = Schema.Struct({
- /** A list of nodes. */
- nodes: Schema.NullOr(Schema.Array(Schema.NullOr(CheckContext))),
- /** Information to aid in pagination. */
- pageInfo: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo
-})
-export interface PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsStatusCheckRollupContextConnection extends Schema.Struct.Type<typeof PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsStatusCheckRollupContextConnection.fields> {}
-
-/** Represents the rollup for both the check runs and status for a commit. */
-export const PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupStatusCheckRollup = Schema.Struct({
- /** A list of status contexts and check runs for this commit. */
- contexts: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsStatusCheckRollupContextConnection
-})
-export interface PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupStatusCheckRollup extends Schema.Struct.Type<typeof PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupStatusCheckRollup.fields> {}
-
-/** Represents a Git commit. */
-export const PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitCommit = Schema.Struct({
- /** Check and Status rollup information for this commit. */
- statusCheckRollup: Schema.NullOr(PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupStatusCheckRollup)
-})
-export interface PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitCommit extends Schema.Struct.Type<typeof PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitCommit.fields> {}
-
-/** Represents a Git commit part of a pull request. */
-export const PullRequestCheckContextsRepositoryPullRequestCommitsNodesPullRequestCommit = Schema.Struct({
- /** The Git commit object */
- commit: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitCommit
-})
-export interface PullRequestCheckContextsRepositoryPullRequestCommitsNodesPullRequestCommit extends Schema.Struct.Type<typeof PullRequestCheckContextsRepositoryPullRequestCommitsNodesPullRequestCommit.fields> {}
-
-/** The connection type for PullRequestCommit. */
-export const PullRequestCheckContextsRepositoryPullRequestCommitsPullRequestCommitConnection = Schema.Struct({
- /** A list of nodes. */
- nodes: Schema.NullOr(Schema.Array(Schema.NullOr(PullRequestCheckContextsRepositoryPullRequestCommitsNodesPullRequestCommit)))
-})
-export interface PullRequestCheckContextsRepositoryPullRequestCommitsPullRequestCommitConnection extends Schema.Struct.Type<typeof PullRequestCheckContextsRepositoryPullRequestCommitsPullRequestCommitConnection.fields> {}
-
/** A repository pull request. */
export const PullRequestCheckContextsRepositoryPullRequestPullRequest = Schema.Struct({
/** Identifies the oid of the head ref associated with the pull request, even if the ref has been deleted. */
headRefOid: Shared.GitObjectID,
/** A list of commits present in this pull request's head branch not present in the base branch. */
- commits: PullRequestCheckContextsRepositoryPullRequestCommitsPullRequestCommitConnection
+ commits: PullRequestCoreRepositoryPullRequestCommitsPullRequestCommitConnection
})
export interface PullRequestCheckContextsRepositoryPullRequestPullRequest extends Schema.Struct.Type<typeof PullRequestCheckContextsRepositoryPullRequestPullRequest.fields> {}
@@ -737,7 +693,7 @@ export interface NodesIssueComment extends Schema.Struct.Type<typeof NodesIssueC
/** The connection type for IssueComment. */
export const IssueCommentConnection = Schema.Struct({
/** Information to aid in pagination. */
- pageInfo: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
+ pageInfo: ContextsPageInfoPageInfo,
/** A list of nodes. */
nodes: Schema.NullOr(Schema.Array(Schema.NullOr(NodesIssueComment)))
})
@@ -768,7 +724,7 @@ export interface NodesPullRequestReview extends Schema.Struct.Type<typeof NodesP
/** The connection type for PullRequestReview. */
export const PullRequestReviewConnection = Schema.Struct({
/** Information to aid in pagination. */
- pageInfo: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
+ pageInfo: ContextsPageInfoPageInfo,
/** A list of nodes. */
nodes: Schema.NullOr(Schema.Array(Schema.NullOr(NodesPullRequestReview)))
})
@@ -896,7 +852,7 @@ export interface NodesPullRequest extends Schema.Struct.Type<typeof NodesPullReq
/** The connection type for PullRequest. */
export const PullRequestConnection = Schema.Struct({
/** Information to aid in pagination. */
- pageInfo: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
+ pageInfo: ContextsPageInfoPageInfo,
/** A list of nodes. */
nodes: Schema.NullOr(Schema.Array(Schema.NullOr(NodesPullRequest)))
})
@@ -1123,6 +1079,13 @@ export declare namespace ViewerPermissions {
export type Result = typeof ViewerPermissions.result.Type
}
+/** Information about pagination in a connection. */
+export const AssignableUsersPageInfoPageInfo = Schema.Struct({
+ /** When paginating forwards, are there more items? */
+ hasNextPage: Schema.Boolean
+})
+export interface AssignableUsersPageInfoPageInfo extends Schema.Struct.Type<typeof AssignableUsersPageInfoPageInfo.fields> {}
+
/** A user is an individual's account on GitHub that owns repositories and can make new content. */
export const AssignableUsersNodesUser = Schema.Struct({
/** The username used to login. */
@@ -1137,7 +1100,7 @@ export interface AssignableUsersNodesUser extends Schema.Struct.Type<typeof Assi
/** A list of users. */
export const UserConnection = Schema.Struct({
/** Information to aid in pagination. */
- pageInfo: PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
+ pageInfo: AssignableUsersPageInfoPageInfo,
/** A list of nodes. */
nodes: Schema.NullOr(Schema.Array(Schema.NullOr(AssignableUsersNodesUser)))
})
@@ -1230,7 +1193,7 @@ export interface RepositoryLabelsNodesLabel extends Schema.Struct.Type<typeof Re
/** The connection type for Label. */
export const LabelCandidatesRepositoryLabelsLabelConnection = Schema.Struct({
/** Information to aid in pagination. */
- pageInfo: PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
+ pageInfo: AssignableUsersPageInfoPageInfo,
/** A list of nodes. */
nodes: Schema.NullOr(Schema.Array(Schema.NullOr(RepositoryLabelsNodesLabel)))
})
@@ -1297,7 +1260,7 @@ export declare namespace LabelCandidates {
/** The connection type for Label. */
export const RepositoryLabelsRepositoryLabelsLabelConnection = Schema.Struct({
/** Information to aid in pagination. */
- pageInfo: PullRequestCoreRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
+ pageInfo: AssignableUsersPageInfoPageInfo,
/** A list of nodes. */
nodes: Schema.NullOr(Schema.Array(Schema.NullOr(PullRequestCoreRepositoryPullRequestLabelsNodesLabel)))
})
@@ -1385,7 +1348,7 @@ export interface PullRequestFilesViewedRepositoryPullRequestFilesNodesPullReques
/** The connection type for PullRequestChangedFile. */
export const PullRequestFilesViewedRepositoryPullRequestFilesPullRequestChangedFileConnection = Schema.Struct({
/** Information to aid in pagination. */
- pageInfo: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
+ pageInfo: ContextsPageInfoPageInfo,
/** A list of nodes. */
nodes: Schema.NullOr(Schema.Array(Schema.NullOr(PullRequestFilesViewedRepositoryPullRequestFilesNodesPullRequestChangedFile)))
})
@@ -1449,7 +1412,7 @@ export interface PullRequestFileStatsRepositoryPullRequestFilesNodesPullRequestC
/** The connection type for PullRequestChangedFile. */
export const PullRequestFileStatsRepositoryPullRequestFilesPullRequestChangedFileConnection = Schema.Struct({
/** Information to aid in pagination. */
- pageInfo: PullRequestCheckContextsRepositoryPullRequestCommitsNodesCommitStatusCheckRollupContextsPageInfoPageInfo,
+ pageInfo: ContextsPageInfoPageInfo,
/** A list of nodes. */
nodes: Schema.NullOr(Schema.Array(Schema.NullOr(PullRequestFileStatsRepositoryPullRequestFilesNodesPullRequestChangedFile)))
})
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
index d223ca7180d..b05e692576d 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
@@ -64,6 +64,7 @@ import {
type GitLabProjectUsers,
} from "./gitLabMergeRequestJson.ts";
import type {
+ ProviderChangeRequestSummary,
ProviderFileStats,
ProviderListCursor,
} from "@t3tools/source-control-core/server/PullRequestProvider";
@@ -390,7 +391,7 @@ export class GitLabPullRequestCli extends Context.Service<
readonly action: PullRequestAction;
readonly mergeMethod?: PullRequestMergeMethod;
readonly removeAgentCreditsOnMerge?: boolean;
- }) => Effect.Effect<void, GitLabPullRequestCliError>;
+ }) => Effect.Effect<ProviderChangeRequestSummary | void, GitLabPullRequestCliError>;
readonly updateMergeRequest: (input: {
readonly cwd: string;
@@ -1655,12 +1656,23 @@ export const make = Effect.gen(function* () {
// no flag for is asked of GitLab directly through the same `api` passthrough the rest of
// this module writes with.
if (input.action === "disable-auto-merge") {
- return yield* api({
+ const result = yield* api({
cwd: input.cwd,
host: input.host,
path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/cancel_merge_when_pipeline_succeeds`,
method: "POST",
- }).pipe(Effect.asVoid);
+ });
+ // The other actions run `glab mr`, which prints prose rather than the merge request.
+ const decoded = decodeMergeRequestDetailJson(result.stdout.trim());
+ if (Result.isFailure(decoded)) return;
+ // The decoder fills absent counts with zeros, which would be guesses here.
+ const {
+ additions: _additions,
+ deletions: _deletions,
+ changedFiles: _changedFiles,
+ ...summary
+ } = decoded.success;
+ return summary;
}
const executeMr = (subcommand: string, ...flags: ReadonlyArray<string>) =>
gitlab.execute({