TypeScript
fix(prs): queue fast actions and close batches by dragging (#15851)
maria7ffa2184a7cf
diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.tsindex d248d51d985..14785b3f8e6 100644--- a/apps/server/src/pullRequest/PullRequestService.test.ts+++ b/apps/server/src/pullRequest/PullRequestService.test.ts@@ -2,9 +2,11 @@ import * as NodeServices from "@effect/platform-node/NodeServices";import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";import * as KeyValueStore from "effect/unstable/persistence/KeyValueStore";import { assert, it } from "@effect/vitest";+import * as Cause from "effect/Cause";import * as Clock from "effect/Clock";import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";+import * as Exit from "effect/Exit";import * as Fiber from "effect/Fiber";import * as Layer from "effect/Layer";import * as Option from "effect/Option";@@ -3348,6 +3350,72 @@ it.effect("answers a repeated listing from cache, and concurrent readers share o}),);+it.effect.each(["list", "listStats"] as const)(+ "retries a replacement %s read that joins a canceled lookup",+ (operation) =>+ Effect.gen(function* () {+ const started = yield* Deferred.make<void>();+ const stopping = yield* Deferred.make<void>();+ const finishShutdown = yield* Deferred.make<void>();+ let hostCalls = 0;+ const lookup = Effect.gen(function* () {+ if (++hostCalls !== 1) return;+ yield* Deferred.succeed(started, undefined);+ return yield* Effect.never.pipe(+ Effect.onInterrupt(() =>+ Deferred.succeed(stopping, undefined).pipe(+ Effect.andThen(Deferred.await(finishShutdown)),+ ),+ ),+ );+ });+ const service = yield* makeService({+ projects: [+ project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),+ ],+ providers: [+ fakeProvider("github", {+ listChangeRequests: () =>+ lookup.pipe(+ Effect.as({+ items: [changeRequest(1, "2026-07-02T00:00:00Z")],+ truncated: false,+ continues: false,+ }),+ ),+ listChangeRequestStats: () =>+ lookup.pipe(+ Effect.as([{ repository: "acme/web", number: 1, additions: 3, deletions: 1 }]),+ ),+ }),+ ],+ });+ const read =+ operation === "list"+ ? service+ .list({ state: "open" })+ .pipe(Effect.map((result) => result.entries.map((entry) => entry.number)))+ : service+ .listStats({+ refs: [{ projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }],+ })+ .pipe(Effect.map((result) => result.stats.map((stat) => stat.number)));+ const original = yield* Effect.forkScoped(read);+ yield* Deferred.await(started);+ const cancellation = yield* Effect.forkScoped(Fiber.interrupt(original));+ yield* Deferred.await(stopping);+ // Join the old entry while its lookup is still finishing cancellation.+ const replacement = yield* Effect.forkScoped(read, { startImmediately: true });+ yield* Deferred.succeed(finishShutdown, undefined);+ yield* Fiber.join(cancellation);+ const canceled = yield* Fiber.await(original);+ assert.isTrue(Exit.isFailure(canceled));+ if (Exit.isFailure(canceled)) assert.isTrue(Cause.hasInterruptsOnly(canceled.cause));+ assert.deepStrictEqual(yield* Fiber.join(replacement), [1]);+ assert.strictEqual(hostCalls, 2);+ }),+);+it.effect("shares one cold viewer lookup across distinct concurrent lists", () =>Effect.gen(function* () {let viewerCalls = 0;diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.tsindex afe2d9683ca..a5a1a5b01d6 100644--- a/apps/server/src/pullRequest/PullRequestService.ts+++ b/apps/server/src/pullRequest/PullRequestService.ts@@ -5,6 +5,7 @@ import {} from "@t3tools/shared/sourceControl";import { normalizeGitRemoteUrl } from "@t3tools/shared/git";import * as Cache from "effect/Cache";+import * as Cause from "effect/Cause";import * as Clock from "effect/Clock";import * as Context from "effect/Context";import * as DateTime from "effect/DateTime";@@ -2887,7 +2888,12 @@ export const make = Effect.gen(function* () {? null: Object.entries(input.cursors).toSorted(([left], [right]) => left.localeCompare(right)),]);- return Cache.get(listCache, key);+ // A replacement reader can join a lookup still finishing its previous reader's cancellation.+ return Cache.get(listCache, key).pipe(+ Effect.catchCause((cause) =>+ Cause.hasInterruptsOnly(cause) ? Cache.get(listCache, key) : Effect.failCause(cause),+ ),+ );};const checksCache = yield* Cache.makeWith(@@ -3134,7 +3140,11 @@ export const make = Effect.gen(function* () {}if (missing.size === 0) return { stats: held };const key = statsBatchKey(missing.values());- const { result, at } = yield* Cache.get(listStatsCache, key);+ const { result, at } = yield* Cache.get(listStatsCache, key).pipe(+ Effect.catchCause((cause) =>+ Cause.hasInterruptsOnly(cause) ? Cache.get(listStatsCache, key) : Effect.failCause(cause),+ ),+ );for (const [key, ref] of missing) {const stat = result.stats.find((stat) =>diff --git a/apps/web/src/components/Sidebar.pointer.test.ts b/apps/web/src/components/Sidebar.pointer.test.tsindex 3a54498c230..0c171313612 100644--- a/apps/web/src/components/Sidebar.pointer.test.ts+++ b/apps/web/src/components/Sidebar.pointer.test.ts@@ -166,9 +166,9 @@ describe("sidebar pointer lifecycle", () => {expect(drag.onCancel).not.toHaveBeenCalled();});- it("suppresses a delayed release click after cancellation, then accepts the next click", () => {+ it.each([false, true])("suppresses a cancelled release click, started=%s", (started) => {const drag = gesture();- document.dispatchEvent(pointer("pointermove", { clientY: 20 }));+ if (started) document.dispatchEvent(pointer("pointermove", { clientY: 20 }));drag.sensor.cancel();vi.advanceTimersByTime(1000);const releaseClick = new Event("click");@@ -182,9 +182,9 @@ describe("sidebar pointer lifecycle", () => {expect(nextPropagation).not.toHaveBeenCalled();});- it("allows the next click when the cancelled release happened outside the document", () => {+ it.each([false, true])("allows a fresh click after an outside release, started=%s", (started) => {const drag = gesture();- document.dispatchEvent(pointer("pointermove", { clientY: 20 }));+ if (started) document.dispatchEvent(pointer("pointermove", { clientY: 20 }));drag.sensor.cancel();document.dispatchEvent(pointer("pointerdown"));const click = new Event("click");diff --git a/apps/web/src/components/Sidebar.pointer.ts b/apps/web/src/components/Sidebar.pointer.tsindex 5ae83901ed1..23f95481485 100644--- a/apps/web/src/components/Sidebar.pointer.ts+++ b/apps/web/src/components/Sidebar.pointer.ts@@ -137,7 +137,8 @@ export class SidebarPointerSensor {// Cancellation can precede release by an arbitrary amount of time. Consume// that release click, or let a fresh pointerdown end suppression if release// happened outside the document. Ordinary clicks never install this guard.- if (!aborted) {+ if (!aborted || cancelled) {+ this.document.addEventListener("click", this.suppressClick, { capture: true });this.document.addEventListener("pointerdown", this.clearClickSuppression, { capture: true });}try {diff --git a/apps/web/src/components/pullRequest/PullRequestRow.tsx b/apps/web/src/components/pullRequest/PullRequestRow.tsxindex 1f4de90f55b..29bfa3702d9 100644--- a/apps/web/src/components/pullRequest/PullRequestRow.tsx+++ b/apps/web/src/components/pullRequest/PullRequestRow.tsx@@ -91,6 +91,9 @@ function PullRequestRowImpl({onSelect,speedMode,onActed,+ closing = false,+ sweeping = false,+ onCloseSweepStart,}: {entry: EnvironmentPullRequestEntry;selected: boolean;@@ -110,12 +113,16 @@ function PullRequestRowImpl({onSelect: (entry: PullRequestRowTarget) => void;speedMode: boolean;onActed: (result: PullRequestSpeedActionResult) => void;+ closing?: boolean;+ sweeping?: boolean;+ onCloseSweepStart?: (entry: EnvironmentPullRequestEntry, event: PointerEvent) => void;}) {const { Icon, providerName } = getSourceControlPresentationForKind(entry.provider);return (<divref={statsRef}data-pull-request-stats-key={statsKey}+ data-pull-request-key={statsKey}className={cn(// Keep the action buttons inside the same skipped row, but outside its selection button."flex items-center rounded-md [content-visibility:auto] [contain-intrinsic-block-size:56.5px]",@@ -249,7 +256,14 @@ function PullRequestRowImpl({/></button>{entry.state !== "merged" && entry.provider === "github" ? (- <PullRequestSpeedActions entry={entry} visible={speedMode} onActed={onActed} />+ <PullRequestSpeedActions+ entry={entry}+ visible={speedMode}+ onActed={onActed}+ closing={closing}+ sweeping={sweeping}+ {...(onCloseSweepStart ? { onCloseSweepStart } : {})}+ />) : null}</div>);diff --git a/apps/web/src/components/pullRequest/PullRequestSpeedActions.tsx b/apps/web/src/components/pullRequest/PullRequestSpeedActions.tsxindex 613928733d3..ee1bc5dcc02 100644--- a/apps/web/src/components/pullRequest/PullRequestSpeedActions.tsx+++ b/apps/web/src/components/pullRequest/PullRequestSpeedActions.tsx@@ -1,8 +1,4 @@import type { PullRequestAction } from "@t3tools/contracts";-import { Effect } from "effect";-import { AtomRegistry } from "effect/unstable/reactivity";-import { appAtomRegistry } from "~/rpc/atomRegistry";-import { pullRequestEnvironment, pullRequestStackAtom } from "~/state/pullRequests";import { useUiStateStore } from "~/uiStateStore";import { Button } from "../ui/button";import { Spinner } from "../ui/spinner";@@ -25,10 +21,16 @@ export function PullRequestSpeedActions({entry,visible,onActed,+ closing = false,+ sweeping = false,+ onCloseSweepStart,}: {entry: EnvironmentPullRequestEntry;visible: boolean;onActed: (result: PullRequestSpeedActionResult) => void;+ closing?: boolean;+ sweeping?: boolean;+ onCloseSweepStart?: (entry: EnvironmentPullRequestEntry, event: PointerEvent) => void;}) {const resolveProjectDefault = usePullRequestDefaultMergeMethodResolver(entry.environmentId,@@ -44,32 +46,7 @@ export function PullRequestSpeedActions({environmentId: entry.environmentId,reference,onSuccess: (action) => onActed({ entry, action }),- resolveMergeMethod: async () => {- const target = { environmentId: entry.environmentId, input: reference };- const detailAtom = pullRequestEnvironment.detail({- ...target,- input: { ...reference, allowStale: false },- });- appAtomRegistry.refresh(detailAtom);- const detail = await Effect.runPromise(- AtomRegistry.getResult(appAtomRegistry, detailAtom, { suspendOnWaiting: true }),- );- if (- detail.state !== "open" ||- detail.isDraft ||- !detail.capabilities.actions.includes("merge") ||- !detail.viewerPermissions.actions.includes("merge")- ) {- throw new Error("This pull request cannot be merged.");- }- if (detail.capabilities.stackActions) {- const stackAtom = pullRequestStackAtom(target);- appAtomRegistry.refresh(stackAtom);- const stack = await Effect.runPromise(- AtomRegistry.getResult(appAtomRegistry, stackAtom, { suspendOnWaiting: true }),- );- if (stack !== null) throw new Error("Open this pull request to merge its stack.");- }+ resolveMergeMethod: (detail) => {const allowed = detail.capabilities.mergeMethods.filter((method) => detail.mergeCapabilities[method],);@@ -89,12 +66,14 @@ export function PullRequestSpeedActions({: entry.isDraft? (["close", "ready"] as const): (["close", "merge"] as const);+ const busy = actionPending || closing || sweeping;return (<divclassName="shrink-0 items-center gap-1 pr-3"- style={{ display: visible || actionPending ? "flex" : "none" }}+ style={{ display: visible || busy ? "flex" : "none" }}role="group"aria-label={`Quick actions for pull request #${entry.number}`}+ data-pull-request-action-pending={actionPending || closing}>{actions.map((action) => {const label = ACTIONS[action].label;@@ -106,19 +85,26 @@ export function PullRequestSpeedActions({<Buttonvariant={action === "close" ? "destructive-outline" : "outline"}size="xs"- disabled={actionPending || (action === "merge" && entry.stack !== undefined)}+ disabled={busy || (action === "merge" && entry.stack !== undefined)}aria-label={`${label} #${entry.number}`}onClick={() => void perform(action)}+ onPointerDown={(event) => {+ if (action !== "close" || !event.isPrimary || event.button !== 0) return;+ event.stopPropagation();+ onCloseSweepStart?.(entry, event.nativeEvent);+ }}/>}>- {actionPending ? <Spinner size="xs" /> : <Icon aria-hidden className="size-3" />}+ {busy ? <Spinner size="xs" /> : <Icon aria-hidden className="size-3" />}{label}</TooltipTrigger><TooltipPopup>{action === "merge" && entry.stack? "Open this pull request to merge its stack"- : `${label} immediately`}+ : action === "close"+ ? "Close immediately, or drag across rows to close several"+ : `${label} immediately`}</TooltipPopup></Tooltip>);diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.test.tsindex 357ea20ad76..3bd486fa9e9 100644--- a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts@@ -1650,6 +1650,31 @@ describe("pull request list overrides", () => {expect(applyPullRequestOverrides(rows, new Map(), key, "open")).toBe(rows);});+ it.each([+ ["open", [1]],+ ["closed", [2]],+ ["merged", [3]],+ ["all", [1, 2, 3]],+ ] as const)("filters host rows by %s after pending actions settle", (state, expected) => {+ const rows = [entry(1, "open"), entry(2, "closed"), entry(3, "merged")];+ expect(applyPullRequestOverrides(rows, new Map(), key, state).map((row) => row.number)).toEqual(+ expected,+ );+ });++ 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")];+ const overrides = new Map([+ ["#1", { state: "closed" as const, updatedAt: "2026-07-03T00:00:00Z", token: 1, at }],+ ]);+ const settled = settlePullRequestOverrides(overrides, rows, key, at + 5_000);+ expect(settled.size).toBe(0);+ expect(applyPullRequestOverrides(rows, settled, key, "open").map((row) => row.number)).toEqual([+ 2,+ ]);+ });+it("hands back the held object for a row a refresh did not change", () => {const previous = [entry(1, "open"), entry(2, "open")];const next = [{ ...entry(1, "open") }, { ...entry(2, "open"), state: "merged" as const }];diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.tsindex f4cb3a31f46..04f4711aeaa 100644--- a/apps/web/src/components/pullRequest/pullRequestList.logic.ts+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.ts@@ -1189,18 +1189,14 @@ export function applyPullRequestOverrides<Entry extends PullRequestListEntry>(keyOf: (entry: Entry) => string,state: PullRequestListState,): ReadonlyArray<Entry> {- if (overrides.size === 0) return entries;+ if (overrides.size === 0 && state === "all") return entries;const out: Entry[] = [];for (const entry of entries) {const override = overrides.get(keyOf(entry));- if (override === undefined) {- out.push(entry);- continue;- }- if (state !== "all" && override.state !== state) continue;- out.push({ ...entry, ...override });+ if (state !== "all" && (override?.state ?? entry.state) !== state) continue;+ out.push(override === undefined ? entry : { ...entry, ...override });}- return out;+ return overrides.size === 0 && out.length === entries.length ? entries : out;}/**diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.ts b/apps/web/src/components/pullRequest/usePullRequestActions.tsindex 01c2789e820..5cff68b531e 100644--- a/apps/web/src/components/pullRequest/usePullRequestActions.ts+++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts@@ -35,6 +35,7 @@ import { useAtomCommand } from "~/state/use-atom-command";import { toastManager } from "../ui/toast";import { handoffPrompt, handoffReviewComments, readableFailure } from "./pullRequestDetail.logic";+import { pullRequestEntryKey, type EnvironmentPullRequestEntry } from "./pullRequestList.logic";/** Resolve on demand so hidden quick actions do not rebuild the legacy project grouping. */export function usePullRequestDefaultMergeMethodResolver(@@ -137,7 +138,7 @@ export function usePullRequestActionRunner({reference: PullRequestRef | null;onSuccess?: (action: PullRequestAction) => void;/** Small surfaces resolve repository settings on the click, not for every visible row. */- resolveMergeMethod?: () => Promise<PullRequestMergeMethod>;+ resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;}) {const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });const [actionPending, setActionPending] = useState(false);@@ -148,10 +149,13 @@ export function usePullRequestActionRunner({pendingRef.current = true;setActionPending(true);try {- const mergeMethod = method ?? (action === "merge" ? await resolveMergeMethod?.() : undefined);const result = await runAction({environmentId,- input: { ...reference, action, ...(mergeMethod ? { mergeMethod } : {}) },+ input: {+ ...reference,+ action,+ ...(method ? { mergeMethod: method } : resolveMergeMethod ? { resolveMergeMethod } : {}),+ },});if (result._tag === "Failure") throw squashAtomCommandFailure(result);toastManager.add({ type: "success", title: ACTION_SUCCESS_LABELS[action] });@@ -171,6 +175,64 @@ export function usePullRequestActionRunner({return { actionPending, perform };}+/** Queue a close sweep through the same environment lanes as individual actions. */+export function usePullRequestCloseBatch(onClosed: (entry: EnvironmentPullRequestEntry) => void) {+ const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });+ const pending = useRef(new Set<string>());+ const [closingKeys, setClosingKeys] = useState<ReadonlySet<string>>(() => new Set());+ const close = useCallback(+ async (entries: readonly EnvironmentPullRequestEntry[]) => {+ const batch = entries.filter((entry) => {+ const key = pullRequestEntryKey(entry);+ if (entry.state !== "open" || entry.provider !== "github" || pending.current.has(key))+ return false;+ pending.current.add(key);+ return true;+ });+ if (batch.length === 0) return;+ setClosingKeys(new Set(pending.current));+ let closed = 0;+ const failures: string[] = [];+ await Promise.all(+ batch.map(async (entry) => {+ try {+ const result = await runAction({+ environmentId: entry.environmentId,+ input: {+ projectId: entry.projectId,+ host: entry.host,+ repository: entry.repository,+ number: entry.number,+ action: "close",+ },+ });+ if (result._tag === "Failure") throw squashAtomCommandFailure(result);+ closed++;+ onClosed(entry);+ } catch (failure) {+ failures.push(+ `#${entry.number}: ${readableFailure(failure, ACTION_FAILURE_HINTS.close)}`,+ );+ } finally {+ pending.current.delete(pullRequestEntryKey(entry));+ setClosingKeys(new Set(pending.current));+ }+ }),+ );+ toastManager.add({+ type: failures.length > 0 ? "error" : "success",+ title:+ failures.length > 0+ ? `Closed ${closed} of ${batch.length} pull requests`+ : `Closed ${closed} pull request${closed === 1 ? "" : "s"}`,+ ...(failures.length > 0 ? { description: failures.slice(0, 3).join("\n") } : {}),+ });+ },+ [onClosed, runAction],+ );+ return { close, closingKeys };+}+export interface PullRequestThreadTask {prompt: string;reviewComments?: ReadonlyArray<ReviewCommentContext>;diff --git a/apps/web/src/routes/_chat.pull-requests.tsx b/apps/web/src/routes/_chat.pull-requests.tsxindex b67f7923481..56862b1e9af 100644--- a/apps/web/src/routes/_chat.pull-requests.tsx+++ b/apps/web/src/routes/_chat.pull-requests.tsx@@ -2,6 +2,9 @@ import { RefreshIcon } from "~/components/ui/refresh-icon";import { Spinner } from "~/components/ui/spinner";import { useShortcutModifierState } from "~/shortcutModifierState";import type { PullRequestSpeedActionResult } from "~/components/pullRequest/PullRequestSpeedActions";+import { usePullRequestCloseBatch } from "~/components/pullRequest/usePullRequestActions";+import { SidebarPointerSensor } from "~/components/Sidebar.pointer";+import { resolveSidebarSweepKeys } from "~/components/Sidebar.logic";import { pullRequestHostOf, resolveEnvironmentMachineKind } from "@t3tools/contracts";import type {EnvironmentId,@@ -793,6 +796,11 @@ function PullRequestsRouteView() {],);const baselineQuery = usePullRequestList(baselineTargets);+ const baselineEmpty =+ baselineQuery.data?.entries.length === 0 &&+ baselineQuery.data.errors.length === 0 &&+ !baselineQuery.isPending &&+ baselineQuery.error === null;const facetTargets = useMemo(() => {if (!filtersOpen) return NO_LIST_TARGETS;return environmentQueries.map(({ environmentId, projectIds }) => ({@@ -961,12 +969,14 @@ function PullRequestsRouteView() {speedActionRef.current = ({ entry, action }) => {// Some hosts accept a merge before it completes. Let the next host read declare it merged.if (action !== "merge") overrideEntry(entry, action);- setDetailRefreshToken((token) => token + 1);- refreshListAndStats(undefined, entry.environmentId);};const onSpeedAction = useCallback((result: PullRequestSpeedActionResult) => {speedActionRef.current(result);}, []);+ const onBatchClosed = useCallback((entry: EnvironmentPullRequestEntry) => {+ speedActionRef.current({ entry, action: "close" });+ }, []);+ const { close: closeBatch, closingKeys } = usePullRequestCloseBatch(onBatchClosed);// A reload recreates the registry the queries live in, so with nothing held the page would// cold-start into skeletons even though almost every row is unchanged. The last answer for// this set of environments is kept across reloads and hydrated here as the carried rows: they@@ -1005,13 +1015,15 @@ function PullRequestsRouteView() {// stay — hydrated or previously answered — rather than being dropped for a feed that// merely settled first.const partitions =- partitionsWanted && authoredQuery.data !== null && reviewingQuery.data !== null- ? { authored: authoredQuery.data.entries, reviewing: reviewingQuery.data.entries }- : current !== null &&- current.environmentKey === environmentKey &&- current.scope === scopeKey- ? current.partitions- : undefined;+ partitionsWanted && baselineEmpty+ ? { authored: [], reviewing: [] }+ : partitionsWanted && authoredQuery.data !== null && reviewingQuery.data !== null+ ? { authored: authoredQuery.data.entries, reviewing: reviewingQuery.data.entries }+ : current !== null &&+ current.environmentKey === environmentKey &&+ current.scope === scopeKey+ ? current.partitions+ : undefined;// A search's answer is the search's, not the workspace's, so only unsearched lists// persist. Written here where the held partitions are in reach, so a feed settling// ahead of them cannot overwrite a stored snapshot that already had both groups.@@ -1052,6 +1064,7 @@ function PullRequestsRouteView() {sentQuery,listQuery.data,listQuery.isPending,+ baselineEmpty,partitionsWanted,authoredQuery.data,reviewingQuery.data,@@ -1343,6 +1356,11 @@ function PullRequestsRouteView() {*/const groups = useMemo(() => {if (search.involvement !== "all") return [{ key: "others" as const, label: "", entries }];+ // An empty whole-list answer also empties the priority groups. Their old snapshot must+ // not restore the last merged rows after the partition reads are no longer mounted.+ if (baselineEmpty) {+ return groupPullRequestsByInvolvement(entries, viewers);+ }// Until both partitions have answered, the snapshot's stand in — they are yesterday's// groups, but whole ones, where grouping the feed's first page locally loses every// authored row older than it. Once the live reads land they take over; with neither,@@ -1372,6 +1390,7 @@ function PullRequestsRouteView() {return partitionPullRequestsWithPriority(entries, authored, reviewing);}, [hasLocalFilters,+ baselineEmpty,localFilters,authoredQuery.data?.entries,entries,@@ -1573,6 +1592,97 @@ function PullRequestsRouteView() {]);/** What is actually on screen once the reader's pending answers are on the rows. */const shownCount = displayGroups.reduce((count, group) => count + group.entries.length, 0);+ const [closeSweepKeys, setCloseSweepKeys] = useState<ReadonlySet<string>>(() => new Set());+ const closeSensorRef = useRef<SidebarPointerSensor | null>(null);+ const closeSweepRows = useMemo(+ () =>+ new Map(+ displayGroups.flatMap((group) =>+ group.entries.map(+ (entry) => [pullRequestEntryKey(entry), { entry, groupKey: group.key }] as const,+ ),+ ),+ ),+ [displayGroups],+ );+ const closeSweepRef = useRef({ displayGroups, closeSweepRows, closingKeys, closeBatch });+ closeSweepRef.current = { displayGroups, closeSweepRows, closingKeys, closeBatch };+ useEffect(() => () => closeSensorRef.current?.cancel(), [filterKey, search.q, sort]);+ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key !== "Escape" || closeSensorRef.current === null) return;+ event.preventDefault();+ closeSensorRef.current.cancel();+ };+ document.addEventListener("keydown", onKeyDown, true);+ return () => document.removeEventListener("keydown", onKeyDown, true);+ }, []);+ const startCloseSweep = useCallback((entry: EnvironmentPullRequestEntry, event: PointerEvent) => {+ closeSensorRef.current?.cancel();+ const originKey = pullRequestEntryKey(entry);+ const group = closeSweepRef.current.displayGroups.find((candidate) =>+ candidate.entries.some((row) => pullRequestEntryKey(row) === originKey),+ );+ if (!group || closeSweepRef.current.closingKeys.has(originKey)) return;+ const orderedKeys = closeSweepRef.current.displayGroups.flatMap((candidate) =>+ candidate.entries.map(pullRequestEntryKey),+ );+ const canClose = (key: string) => {+ const row = closeSweepRef.current.closeSweepRows.get(key);+ return (+ row?.groupKey === group.key &&+ row.entry.state === "open" &&+ row.entry.provider === "github" &&+ !closeSweepRef.current.closingKeys.has(key) &&+ !scrollRef.current?.querySelector(+ `[data-pull-request-key="${CSS.escape(key)}"] [data-pull-request-action-pending="true"]`,+ )+ );+ };+ let sweptKeys: string[] = [];+ let targetKey: string | null = null;+ const sweepTo = (key: string) => {+ if (key === targetKey) return;+ targetKey = key;+ sweptKeys = resolveSidebarSweepKeys(orderedKeys, originKey, key, canClose);+ setCloseSweepKeys(new Set(sweptKeys));+ };+ closeSensorRef.current = new SidebarPointerSensor({+ active: originKey,+ event,+ options: {+ distance: 6,+ onAttach: () => {},+ onFinish: () => {+ closeSensorRef.current = null;+ setCloseSweepKeys(new Set());+ },+ },+ onPending: () => {},+ onStart: () => sweepTo(originKey),+ onMove: ({ y }) => {+ const viewport = scrollRef.current;+ if (!viewport) return;+ const bounds = viewport.getBoundingClientRect();+ const visibleY = Math.min(Math.max(y, bounds.top), bounds.bottom - 1);+ let key: string | null = null;+ for (const row of viewport.querySelectorAll<HTMLElement>("[data-pull-request-key]")) {+ if (key !== null && row.getBoundingClientRect().top > visibleY) break;+ key = row.dataset.pullRequestKey ?? null;+ }+ if (key !== null) sweepTo(key);+ },+ onEnd: () => {+ const batch = sweptKeys.filter(canClose).flatMap((key) => {+ const row = closeSweepRef.current.closeSweepRows.get(key);+ return row ? [row.entry] : [];+ });+ void closeSweepRef.current.closeBatch(batch);+ },+ onCancel: () => {},+ onAbort: () => {},+ });+ }, []);const heldPullRequestsBySurface = useMemo(() =>new Map(@@ -1801,7 +1911,7 @@ function PullRequestsRouteView() {onLoadMore={loadMore}/>) : (- <div className="space-y-3">+ <div className={cn("space-y-3", closeSweepKeys.size > 0 && "**:pointer-events-none")}>{displayGroups.map((group) => (<div key={group.key} className="space-y-0.5">{group.label ? <PullRequestGroupHeader group={group} /> : null}@@ -1834,6 +1944,9 @@ function PullRequestsRouteView() {onSelect={selectEntry}speedMode={speedMode}onActed={onSpeedAction}+ closing={closingKeys.has(entryKey)}+ sweeping={closeSweepKeys.has(entryKey)}+ onCloseSweepStart={startCloseSweep}/>);})}diff --git a/docs/user/source-control.md b/docs/user/source-control.mdindex 64beb946c40..c8c2612d0d6 100644--- a/docs/user/source-control.md+++ b/docs/user/source-control.md@@ -113,6 +113,10 @@ Open **Pull requests** to review changes and comments, request reviewers, checkor merge. You can edit review titles and descriptions and your own comments where the host allows it.GitLab calls these merge requests.+On web and desktop, hold **Shift** in the GitHub pull request list for quick actions.+To close several, press **Close**, drag across the rows in the same group, and release.+Press **Escape** before releasing to cancel. Failed closes stay in the list so you can retry them.+GitHub, GitLab, and Azure DevOps support auto-merge while checks are outstanding. GitHub alsosupports approving waiting fork workflows and opening a revert pull request for a merged change.diff --git a/packages/client-runtime/src/state/pullRequests.test.ts b/packages/client-runtime/src/state/pullRequests.test.tsindex c33623bbe1b..254fce370ec 100644--- a/packages/client-runtime/src/state/pullRequests.test.ts+++ b/packages/client-runtime/src/state/pullRequests.test.ts@@ -891,6 +891,159 @@ it.effect("keeps concurrent diff file reads on different hosts separate", () =>),);+it.effect("queues merge preparation with actions without restarting it on refresh", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const started = yield* Deferred.make<void>();+ const release = yield* Deferred.make<void>();+ const refreshEvents = yield* PubSub.unbounded<number>();+ const calls: string[] = [];+ const client = {+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),+ [WS_METHODS.pullRequestsDetail]: (input: { number: number; allowStale?: boolean }) =>+ Effect.gen(function* () {+ expect(input.allowStale).toBe(false);+ calls.push(`detail:${input.number}`);+ yield* Deferred.succeed(started, undefined);+ yield* Deferred.await(release);+ return {+ state: "open",+ isDraft: false,+ capabilities: { actions: ["merge"], stackActions: true },+ viewerPermissions: { actions: ["merge"] },+ };+ }),+ [WS_METHODS.pullRequestsStack]: (input: { number: number; allowStale?: boolean }) =>+ Effect.sync(() => {+ expect(input.allowStale).toBe(false);+ calls.push(`stack:${input.number}`);+ return null;+ }),+ [WS_METHODS.pullRequestsRunAction]: (input: {+ action: string;+ number: number;+ mergeMethod?: string;+ }) =>+ Effect.sync(() => {+ if (input.action === "merge") expect(input.mergeMethod).toBe("squash");+ expect(input).not.toHaveProperty("resolveMergeMethod");+ calls.push(`${input.action}:${input.number}`);+ }),+ } as unknown as WsRpcProtocolClient;+ const { atoms, registry } = yield* makeTestRuntime(client);+ const unmount = registry.mount(+ atoms.refreshes({ environmentId: TARGET.environmentId, input: {} }),+ );+ yield* Effect.addFinalizer(() => Effect.sync(unmount));+ const reference = { projectId: ProjectId.make("project-1"), repository: "acme/web" };+ const first = atoms.runAction.run(registry, {+ environmentId: TARGET.environmentId,+ input: { ...reference, number: 1, action: "merge", resolveMergeMethod: () => "squash" },+ });+ yield* Deferred.await(started);+ const second = atoms.runAction.run(registry, {+ environmentId: TARGET.environmentId,+ input: { ...reference, number: 2, action: "close" },+ });+ yield* PubSub.publish(refreshEvents, 1);+ expect(calls).toEqual(["detail:1"]);+ yield* Deferred.succeed(release, undefined);+ const results = yield* Effect.promise(() => Promise.all([first, second]));+ expect(results.every(AsyncResult.isSuccess)).toBe(true);+ expect(calls).toEqual(["detail:1", "stack:1", "merge:1", "close:2"]);+ }),+ ),+);++it.effect.each(["closed", "draft", "permission", "stack", "method"] as const)(+ "rejects an unsafe quick merge with %s and keeps later actions running",+ (reason) =>+ Effect.scoped(+ Effect.gen(function* () {+ const calls: string[] = [];+ const client = {+ [WS_METHODS.pullRequestsDetail]: () =>+ Effect.succeed({+ state: reason === "closed" ? "closed" : "open",+ isDraft: reason === "draft",+ capabilities: { actions: ["merge"], stackActions: true },+ viewerPermissions: { actions: reason === "permission" ? [] : ["merge"] },+ }),+ [WS_METHODS.pullRequestsStack]: () => Effect.succeed(reason === "stack" ? {} : null),+ [WS_METHODS.pullRequestsRunAction]: (input: { action: string }) =>+ Effect.sync(() => calls.push(input.action)),+ } as unknown as WsRpcProtocolClient;+ const { atoms, registry } = yield* makeTestRuntime(client);+ const target = {+ environmentId: TARGET.environmentId,+ input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 },+ };+ const merge = atoms.runAction.run(registry, {+ ...target,+ input: {+ ...target.input,+ action: "merge",+ resolveMergeMethod: () => {+ if (reason === "method") throw new Error("No merge method is available.");+ return "squash";+ },+ },+ });+ const close = atoms.runAction.run(registry, {+ ...target,+ input: { ...target.input, action: "close" },+ });+ const results = yield* Effect.promise(() => Promise.all([merge, close]));+ expect(results.map((result) => result._tag)).toEqual(["Failure", "Success"]);+ expect(calls).toEqual(["close"]);+ }),+ ),+);++it.effect("keeps a close batch ordered and continues after a refused close", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const calls: number[] = [];+ const started = yield* Deferred.make<void>();+ const release = yield* Deferred.make<void>();+ const client = {+ [WS_METHODS.pullRequestsRunAction]: (input: { number: number; action: string }) =>+ Effect.gen(function* () {+ expect(input.action).toBe("close");+ calls.push(input.number);+ if (input.number === 6) {+ yield* Deferred.succeed(started, undefined);+ yield* Deferred.await(release);+ }+ if (input.number === 5)+ return yield* new PullRequestOperationError({+ operation: "runAction",+ detail: "You cannot close this pull request.",+ });+ }),+ } as unknown as WsRpcProtocolClient;+ const { atoms, registry } = yield* makeTestRuntime(client);+ const batch = [6, 5, 4].map((number) =>+ atoms.runAction.run(registry, {+ environmentId: TARGET.environmentId,+ input: {+ projectId: ProjectId.make("project-1"),+ repository: "acme/web",+ number,+ action: "close",+ },+ }),+ );+ yield* Deferred.await(started);+ expect(calls).toEqual([6]);+ yield* Deferred.succeed(release, undefined);+ const results = yield* Effect.promise(() => Promise.all(batch));+ expect(results.map((result) => result._tag)).toEqual(["Success", "Failure", "Success"]);+ expect(calls).toEqual([6, 5, 4]);+ }),+ ),+);+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.tsindex ad6f4f9e120..6031b05b6f9 100644--- a/packages/client-runtime/src/state/pullRequests.ts+++ b/packages/client-runtime/src/state/pullRequests.ts@@ -2,9 +2,12 @@ import {WS_METHODS,type EnvironmentId,type PullRequestActor,+ type PullRequestActionInput,type PullRequestDetail,type PullRequestDiffInput,type PullRequestRef,+ type PullRequestMergeMethod,+ PullRequestOperationError,type PullRequestSummary,type VcsStatusResult,} from "@t3tools/contracts";@@ -16,6 +19,7 @@ import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";import {createAtomCommandScheduler,+ createEnvironmentCommand,createEnvironmentRpcCommand,createEnvironmentRpcQueryAtomFamily,createEnvironmentRpcSubscriptionAtomFamily,@@ -316,11 +320,58 @@ export function createPullRequestEnvironmentAtoms<R, E>(JSON.stringify([environmentId, input.projectId, input.repository, input.number]),},}),- runAction: createEnvironmentRpcCommand(runtime, {+ runAction: createEnvironmentCommand(runtime, {label: "environment-data:pull-requests:run-action",- tag: WS_METHODS.pullRequestsRunAction,- execute: (input) => routedRequest(WS_METHODS.pullRequestsRunAction, input),- onSuccess: (target, registry) => Effect.sync(() => registry.refresh(preview(target))),+ // 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: (+ input: PullRequestActionInput & {+ readonly resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;+ },+ registry,+ environmentId,+ ) =>+ Effect.gen(function* () {+ const { resolveMergeMethod, ...actionInput } = input;+ let preparedInput = actionInput;+ if (actionInput.action === "merge" && resolveMergeMethod !== undefined) {+ const { projectId, host, repository, number } = actionInput;+ const reference = { projectId, host, repository, number, allowStale: false };+ const detail = yield* routedRequest(WS_METHODS.pullRequestsDetail, reference);+ if (+ detail.state !== "open" ||+ detail.isDraft ||+ !detail.capabilities.actions.includes("merge") ||+ !detail.viewerPermissions.actions.includes("merge")+ ) {+ return yield* new PullRequestOperationError({+ operation: "runAction",+ detail: "This pull request cannot be merged.",+ });+ }+ if (detail.capabilities.stackActions) {+ const stack = yield* routedRequest(WS_METHODS.pullRequestsStack, reference);+ if (stack !== null) {+ return yield* new PullRequestOperationError({+ operation: "runAction",+ detail: "Open this pull request to merge its stack.",+ });+ }+ }+ const mergeMethod = yield* Effect.try({+ try: () => resolveMergeMethod(detail),+ catch: (cause) =>+ new PullRequestOperationError({+ operation: "runAction",+ detail:+ cause instanceof Error ? cause.message : "Could not choose a merge method.",+ }),+ });+ preparedInput = { ...actionInput, mergeMethod };+ }+ yield* routedRequest(WS_METHODS.pullRequestsRunAction, preparedInput);+ registry.refresh(preview({ environmentId, input: actionInput }));+ }),scheduler: commandScheduler,concurrency: serialPerEnvironment,}),