@devries-cameron20 / t3code-1 / commits / d5a50a1d0d
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

perf(pr): actions, title edits and labels show the moment you click, on every host (#32774)

Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: GPT-6.1 Sol <noreply@openai.com> Co-authored-by: Shivam Sharma <91240327+shivamhwp@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Bilal Bakr committed Nov 15, 2026 at 08:21 UTC d5a50a1d0d178dfaea0811b9dfd0ff1e00cd823f
11 files changed +1412 -132
apps/mobile/src/features/pull-requests/usePullRequestList.ts
+36 -13
@@ -1,3 +1,8 @@
1 +import {
2 + editHeldPullRequestListEntries,
3 + pullRequestHostAnswer,
4 + pullRequestPendingEditsFor,
5 +} from "@t3tools/client-runtime/state/pull-requests";
6 import { RegistryContext, useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
7 import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
8 import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
@@ -31,7 +36,10 @@ type Read = <A>(atom: Atom.Atom<A>) => A;
36
37 /** The head the list query holds now, cached or answered. */
38 function currentHead(read: Read, target: ListTarget) {
34 - return AsyncResult.getOrElse(read(composerPullRequests.list(target)), () => null);
39 + return AsyncResult.getOrElse(
40 + read(pullRequestHostAnswer(composerPullRequests.list(target))),
41 + () => null,
42 + );
43 }
44
45 function currentPages(read: Read, target: ListTarget): PullRequestListPages | null {
@@ -44,12 +52,23 @@ function currentPages(read: Read, target: ListTarget): PullRequestListPages | nu
52 const sourcesFamily = Atom.family((key: string) => {
53 const targets: readonly ListTarget[] = JSON.parse(key);
54 return Atom.make((get) =>
47 - targets.map((target) => ({
48 - target,
49 - result: get(composerPullRequests.list(target)),
50 - pages: currentPages(get, target),
51 - stats: get(pullRequestListStatsFamily(target.environmentId)),
52 - })),
55 + targets.map((target) => {
56 + const pages = currentPages(get, target);
57 + return {
58 + target,
59 + result: get(composerPullRequests.list(target)),
60 + pages:
61 + pages === null
62 + ? null
63 + : {
64 + ...pages,
65 + entries: editHeldPullRequestListEntries(target.input, pages.entries, (entry) =>
66 + get(pullRequestPendingEditsFor(target.environmentId, entry)),
67 + ),
68 + },
69 + stats: get(pullRequestListStatsFamily(target.environmentId)),
70 + };
71 + }),
72 );
73 });
74
@@ -71,7 +90,7 @@ async function loadNextPages(
90 continuations(registry, targets).map(async ({ target, pages, input }) => {
91 const response = await executeAtomQuery(
92 registry,
74 - composerPullRequests.list({ ...target, input }),
93 + pullRequestHostAnswer(composerPullRequests.list({ ...target, input })),
94 {
95 signal,
96 refresh: retry,
@@ -113,11 +132,15 @@ async function refreshHeads(
132 input: {},
133 });
134 if (signal.aborted) return;
116 - const response = await executeAtomQuery(registry, composerPullRequests.list(target), {
117 - refresh: true,
118 - signal,
119 - reportFailure: false,
120 - });
135 + const response = await executeAtomQuery(
136 + registry,
137 + pullRequestHostAnswer(composerPullRequests.list(target)),
138 + {
139 + refresh: true,
140 + signal,
141 + reportFailure: false,
142 + },
143 + );
144 if (signal.aborted) return;
145 if (response._tag === "Failure") throw squashAtomCommandFailure(response);
146 registry.set(
apps/mobile/src/state/pull-requests.ts
+21
@@ -1,7 +1,9 @@
1 import {
2 createPullRequestEnvironmentAtoms,
3 + editHeldPullRequestListEntries,
4 createPullRequestStackAtomFamily,
5 patchPullRequestListEntries,
6 + pullRequestPendingEditsAtom,
7 } from "@t3tools/client-runtime/state/pull-requests";
8 import type { EnvironmentId, PullRequestListInput, PullRequestRef } from "@t3tools/contracts";
9 import * as Effect from "effect/Effect";
@@ -66,11 +68,30 @@ export const composerPullRequests = createPullRequestEnvironmentAtoms(connection
68 pages.entries,
69 target.input,
70 reply,
71 + registry.get(pullRequestPendingEditsAtom(target.environmentId)),
72 );
73 return entries === "refresh" || entries === pages.entries ? pages : { ...pages, entries };
74 });
75 }
76 }),
77 + acceptedEdit: (target, edit, registry) =>
78 + Effect.sync(() => {
79 + for (const atom of registry.getNodes().keys()) {
80 + const listing =
81 + typeof atom === "string" ? undefined : pullRequestListPagesTargets.get(atom);
82 + if (listing === undefined || listing[0] !== target.environmentId) continue;
83 + registry.update(atom as Atom.Writable<PullRequestListPages | null>, (pages) => {
84 + if (pages === null) return pages;
85 + const entries = editHeldPullRequestListEntries(
86 + listing[1],
87 + pages.entries,
88 + () => [edit],
89 + registry.get(pullRequestPendingEditsAtom(target.environmentId)),
90 + );
91 + return entries === pages.entries ? pages : { ...pages, entries };
92 + });
93 + }
94 + }),
95 // A new head can change which files GitHub still counts as viewed, so the viewed-files read is
96 // refreshed where the new head lands. The detail atom still holds the previous answer here.
97 detail: (target, value, registry) =>
apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx
-1
@@ -1650,7 +1650,6 @@ export function PullRequestDetailPanel({
1650 pullRequestKey={pullRequestKey}
1651 detail={detail}
1652 canWriteSourceControl={canWriteSourceControl}
1653 - onSaved={refreshDetail}
1653 />
1654 }
1655 author={
apps/web/src/components/pullRequest/PullRequestLabelPicker.tsx
+2 -5
@@ -32,7 +32,6 @@ export function PullRequestLabelPicker({
32 }) {
33 const [open, setOpen] = useState(false);
34 const [query, setQuery] = useState("");
35 - const [pending, setPending] = useState<string | null>(null);
35
36 const candidatesQuery = useEnvironmentQuery(
37 open ? pullRequestEnvironment.labelCandidates({ environmentId, input: reference }) : null,
@@ -45,14 +44,12 @@ export function PullRequestLabelPicker({
44 matches(entry, query),
45 );
46
47 + // Each change shows at once and queues behind the one before it on the host.
48 const toggle = async (candidate: PullRequestLabelCandidate) => {
49 - if (pending !== null) return;
50 - setPending(candidate.name);
49 const result = await setLabels({
50 environmentId,
51 input: { ...reference, labels: [candidate.name], applied: !candidate.isApplied },
52 });
55 - setPending(null);
53 if (result._tag === "Failure") {
54 toastManager.add({
55 type: "error",
@@ -88,7 +85,7 @@ export function PullRequestLabelPicker({
85 truncated={candidatesQuery.data?.truncated === true}
86 truncatedLabel="This repository has more labels than are listed here. Apply the rest on the host."
87 candidateKey={(candidate) => candidate.name}
91 - disabled={pending !== null}
88 + disabled={false}
89 onSelect={(candidate) => void toggle(candidate)}
90 >
91 {(candidate) => {
apps/web/src/components/pullRequest/PullRequestTitleEditor.tsx
+3 -5
@@ -24,14 +24,12 @@ export function PullRequestTitleEditor({
24 pullRequestKey,
25 detail,
26 canWriteSourceControl,
27 - onSaved,
27 }: {
28 environmentId: EnvironmentId;
29 reference: PullRequestRef;
30 pullRequestKey: string;
31 detail: PullRequestDetail;
32 canWriteSourceControl: boolean;
34 - onSaved: () => void;
33 }) {
34 const update = useAtomCommand(pullRequestEnvironment.update, { reportFailure: false });
35 const [titleScope, setTitleScope] = useState<{
@@ -49,9 +47,12 @@ export function PullRequestTitleEditor({
47 return;
48 }
49 setTitleSaving(true);
50 + // The new title shows while the host takes it, so the editor closes at once.
51 + setTitleScope(null);
52 const result = await update({ environmentId, input: { ...reference, title } });
53 setTitleSaving(false);
54 if (result._tag === "Failure") {
55 + setTitleScope({ pullRequestKey, text: title });
56 toastManager.add({
57 type: "error",
58 title: "The title could not be saved",
@@ -60,10 +61,7 @@ export function PullRequestTitleEditor({
61 "The host refused the new title.",
62 ),
63 });
63 - return;
64 }
65 - setTitleScope(null);
66 - onSaved();
65 };
66
67 if (titleDraft === null) {
apps/web/src/components/pullRequest/PullRequestsPage.tsx
+67 -13
@@ -1,3 +1,5 @@
1 +import { heldPullRequestListEntriesAtom } from "@t3tools/client-runtime/state/pull-requests";
2 +import { AsyncResult, Atom } from "effect/reactivity";
3 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
4 import { applyPullRequestDraftFilterChange } from "@t3tools/client-runtime/pull-request-query";
5 import { Spinner } from "~/components/ui/spinner";
@@ -104,7 +106,7 @@ import {
106 import { useSidebarProjectGroups } from "~/hooks/useSidebarProjectGroups";
107 import {
108 pullRequestEnvironment,
107 - usePullRequestList,
109 + usePullRequestHostList,
110 usePullRequestListStats,
111 restoredPullRequestList,
112 usePullRequestTurnRefreshes,
@@ -147,6 +149,35 @@ const EMPTY_PREVIEW_SESSIONS = {};
149 const EMPTY_PREVIEW_DESKTOP_STATE = {};
150 const EMPTY_TERMINAL_LABELS = new Map<string, string>();
151 const EMPTY_PENDING_SURFACES = new Set<string>();
152 +const heldRowReaders = new WeakMap<
153 + EnvironmentPullRequestEntry,
154 + Map<string, ReturnType<typeof heldPullRequestListEntriesAtom<EnvironmentPullRequestEntry>>>
155 +>();
156 +
157 +function usePendingListEntries(
158 + input: PullRequestListInput,
159 + entries: ReadonlyArray<EnvironmentPullRequestEntry> | undefined,
160 +) {
161 + const key = JSON.stringify(input);
162 + return useAtomValue(
163 + Atom.make((get) =>
164 + (entries ?? []).flatMap((entry) => {
165 + let readers = heldRowReaders.get(entry);
166 + if (readers === undefined) {
167 + readers = new Map();
168 + heldRowReaders.set(entry, readers);
169 + }
170 + let reader = readers.get(key);
171 + if (reader === undefined) {
172 + reader = heldPullRequestListEntriesAtom(entry.environmentId, input, [entry]);
173 + readers.set(key, reader);
174 + }
175 + return AsyncResult.getOrElse(get(reader), () => []);
176 + }),
177 + ),
178 + );
179 +}
180 +
181 export function PullRequestsPage() {
182 const search = useSearch({ from: "/_chat/pull-requests" });
183 const sort = search.sort ?? "ready";
@@ -341,7 +372,7 @@ export function PullRequestsPage() {
372 ];
373 });
374 const listTargets = listTargetsFor(environmentQueries);
344 - const listQuery = usePullRequestList(listTargets);
375 + const listQuery = usePullRequestHostList(listTargets);
376
377 /**
378 * Kept as its own read rather than remembered from an earlier answer because an answer cannot
@@ -362,7 +393,7 @@ export function PullRequestsPage() {
393 } satisfies PullRequestListInput,
394 }));
395 const baselineTargets = baselineTargetsFor(environmentQueries);
365 - const baselineQuery = usePullRequestList(baselineTargets);
396 + const baselineQuery = usePullRequestHostList(baselineTargets);
397 const observedHosts = rememberPullRequestHosts(
398 rememberPullRequestHosts(hostReads, baselineQuery.observations),
399 listQuery.observations,
@@ -387,7 +418,7 @@ export function PullRequestsPage() {
418 } satisfies PullRequestListInput,
419 }));
420 })();
390 - const facetQuery = usePullRequestList(facetTargets);
421 + const facetQuery = usePullRequestHostList(facetTargets);
422 const filterOptionScope = environmentQueries.map(({ environmentId, projectIds }) => ({
423 environmentId,
424 input: {
@@ -423,8 +454,8 @@ export function PullRequestsPage() {
454 }));
455 return { authored: targetsFor("authored"), reviewing: targetsFor("reviewing") };
456 })();
426 - const authoredQuery = usePullRequestList(partitionTargets.authored);
427 - const reviewingQuery = usePullRequestList(partitionTargets.reviewing);
457 + const authoredQuery = usePullRequestHostList(partitionTargets.authored);
458 + const reviewingQuery = usePullRequestHostList(partitionTargets.reviewing);
459 const invalidate = useAtomCommand(pullRequestEnvironment.invalidate, { reportFailure: false });
460 const [detailRefreshToken, setDetailRefreshToken] = useState(0);
461 const [invalidating, setInvalidating] = useState(false);
@@ -703,6 +734,23 @@ export function PullRequestsPage() {
734 search.state,
735 );
736
737 + const heldEntries = ordered?.key === filterKey ? ordered.entries : (listData?.entries ?? []);
738 + const overlayInput = { state: search.state, filters };
739 + const shownEntries = usePendingListEntries(overlayInput, heldEntries);
740 + const shownBaseline = usePendingListEntries(
741 + overlayInput,
742 + typedParsed.filters.checks === undefined ? baselineQuery.data?.entries : undefined,
743 + );
744 + const shownAuthored = usePendingListEntries(
745 + overlayInput,
746 + partitionsWanted ? authoredQuery.data?.entries : undefined,
747 + );
748 + const shownReviewing = usePendingListEntries(
749 + overlayInput,
750 + partitionsWanted ? reviewingQuery.data?.entries : undefined,
751 + );
752 + const shownHeldAuthored = usePendingListEntries(overlayInput, heldPartitions?.authored);
753 + const shownHeldReviewing = usePendingListEntries(overlayInput, heldPartitions?.reviewing);
754 const scrollRef = useRef<HTMLDivElement>(null);
755 const {
756 entries,
@@ -711,9 +759,12 @@ export function PullRequestsPage() {
759 entriesByStatsKey,
760 heldPullRequestsBySurface,
761 } = pullRequestGroups({
714 - known: ordered?.key === filterKey ? ordered.entries : (listData?.entries ?? []),
762 + known: shownEntries,
763 // The baseline was read without typed qualifiers, and rows cannot be checked for `checks:`.
716 - baseline: typedParsed.filters.checks === undefined ? baselineQuery.data?.entries : undefined,
764 + baseline:
765 + typedParsed.filters.checks === undefined && baselineQuery.data !== null
766 + ? shownBaseline
767 + : undefined,
768 providers: baselineQuery.data?.providers ?? listData?.providers ?? [],
769 viewers,
770 involvement: search.involvement,
@@ -723,11 +774,14 @@ export function PullRequestsPage() {
774 answeredLocally: querySettled && !showingCarried,
775 baselineEmpty,
776 held:
726 - loaded !== null && loaded.environmentKey === environmentKey && loaded.scope === scopeKey
727 - ? loaded.partitions
728 - : undefined,
729 - authored: partitionsWanted ? authoredQuery.data?.entries : undefined,
730 - reviewing: partitionsWanted ? reviewingQuery.data?.entries : undefined,
777 + heldPartitions === undefined
778 + ? undefined
779 + : {
780 + authored: shownHeldAuthored,
781 + reviewing: shownHeldReviewing,
782 + },
783 + authored: partitionsWanted && authoredQuery.data !== null ? shownAuthored : undefined,
784 + reviewing: partitionsWanted && reviewingQuery.data !== null ? shownReviewing : undefined,
785 partitionsWanted,
786 });
787
apps/web/src/components/pullRequest/usePullRequestDetail.ts
+9 -2
@@ -1,4 +1,6 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 import { resolvePullRequestDetailChecks } from "@t3tools/client-runtime/pull-request-checks";
3 +import { pullRequestPendingEditsFor } from "@t3tools/client-runtime/state/pull-requests";
4 import {
5 AuthSourceControlWriteScope,
6 type EnvironmentId,
@@ -13,6 +15,7 @@ import { useServerConfigs } from "~/state/entities";
15 import { useEnvironmentQuery } from "~/state/query";
16 import { useEnvironmentScope } from "~/state/session";
17 import {
18 + newestDisplayedPullRequestSummary,
19 newestPullRequestSummary,
20 pullRequestEnvironment,
21 pullRequestListEntryToSummary,
@@ -105,6 +108,7 @@ export function usePullRequestDetail(
108 setCachedDetail(detailQuery.data);
109 }
110 const observedSummary = useSharedPullRequestSummary(environmentId, reference);
111 + const pendingEdits = useAtomValue(pullRequestPendingEditsFor(environmentId, reference));
112 const activity = activityQuery.data;
113 const resolvedCoreDetail = resolveDisplayedPullRequestDetail({
114 live: liveDetail,
@@ -115,9 +119,12 @@ export function usePullRequestDetail(
119 // `detail` would cost it its cache scope.
120 const listSummary = listEntry === null ? null : pullRequestListEntryToSummary(listEntry);
121 // The row can come from the page's stored snapshot, which no answer has published yet.
118 - const sharedSummary = newestPullRequestSummary(
122 + const sharedSummary = newestDisplayedPullRequestSummary(
123 resolvedCoreDetail,
120 - newestPullRequestSummary(observedSummary, listSummary),
124 + liveDetail === null,
125 + newestPullRequestSummary(listSummary, observedSummary),
126 + reference,
127 + pendingEdits,
128 );
129 const coreDetail =
130 resolvedCoreDetail === null || sharedSummary === null || sharedSummary === resolvedCoreDetail
apps/web/src/state/pullRequests.test.ts
+10
@@ -44,6 +44,7 @@ import {
44 observePullRequestChecks,
45 observePullRequestMetadata,
46 newestPullRequestSummary,
47 + newestDisplayedPullRequestSummary,
48 rememberPullRequestListAnswer,
49 restorePullRequestList,
50 restoredPullRequestList,
@@ -154,6 +155,15 @@ describe("pull request summary cache", () => {
155 const older = summary({ updatedAt: "2026-09-11T00:00:00Z", observedAt: 999 });
156 expect(newestPullRequestSummary(older, reopened)).toBe(reopened);
157 expect(newestPullRequestSummary(reopened, older)).toBe(reopened);
158 + const edited = summary({ title: "Accepted title" });
159 + expect(newestPullRequestSummary(summary(), edited)).toBe(edited);
160 + const loaded = summary();
161 + expect(newestDisplayedPullRequestSummary(loaded, false, edited, loaded, [])).toBe(loaded);
162 + expect(newestDisplayedPullRequestSummary(summary(), true, edited, loaded, [])).toBe(edited);
163 + const titleEdit = { reference: loaded, title: "Pending title" };
164 + expect(newestDisplayedPullRequestSummary(loaded, true, null, loaded, [titleEdit])?.title).toBe(
165 + "Pending title",
166 + );
167 });
168
169 it("reuses saved thread state while detail is stale and lets newer detail replace it", () => {
apps/web/src/state/pullRequests.ts
+65 -1
@@ -1,9 +1,13 @@
1 import { useAtomValue } from "@effect/atom-react";
2 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3 import {
4 + applyPullRequestSummaryEdits,
5 createLinkedPullRequestSummaryAtomFamily,
6 createPullRequestEnvironmentAtoms,
7 createPullRequestStackAtomFamily,
8 + pullRequestPendingEditsFor,
9 + pullRequestHostAnswer,
10 + type PullRequestPendingEdit,
11 } from "@t3tools/client-runtime/state/pull-requests";
12 import {
13 PullRequestListResult,
@@ -69,6 +73,24 @@ export function newestPullRequestSummary(
73 return compareSummaries(current, observed) >= 0 ? observed : current;
74 }
75
76 +/** A stored snapshot carries no edit, so a shared summary dated the same wins over it. */
77 +export function newestDisplayedPullRequestSummary(
78 + detail: PullRequestSummary | null,
79 + fromSnapshot: boolean,
80 + shared: PullRequestSummary | null,
81 + reference: PullRequestRef,
82 + edits: ReadonlyArray<PullRequestPendingEdit>,
83 +): PullRequestSummary | null {
84 + // With no shared summary the snapshot is all there is, and no answer applied its edits yet.
85 + return applyPullRequestSummaryEdits(
86 + reference,
87 + fromSnapshot
88 + ? newestPullRequestSummary(detail, shared)
89 + : newestPullRequestSummary(shared, detail),
90 + edits,
91 + );
92 +}
93 +
94 export function pullRequestListEntryToSummary(entry: PullRequestListEntry): PullRequestSummary {
95 return {
96 provider: entry.provider,
@@ -403,6 +425,20 @@ export function subscribePullRequestFilesViewedAnswers(
425
426 // Answers are stamped on arrival: older servers leave no other ordering for same-dated reads.
427 export const pullRequestEnvironment = createPullRequestEnvironmentAtoms(connectionAtomRuntime, {
428 + acceptedEdit: ({ environmentId, input }, edit, registry) =>
429 + Effect.map(Clock.currentTimeMillis, (observedAt) => {
430 + const saved = registry.get(
431 + savedPullRequestSummaryAtom(savedPullRequestKey(environmentId, input)),
432 + );
433 + recordObservation(registry, pullRequestSummaryKey(environmentId, input), (current) => {
434 + const summary = applyPullRequestSummaryEdits(
435 + input,
436 + newestPullRequestSummary(saved, observedPullRequestSummary(current)),
437 + [edit],
438 + );
439 + return summary === null ? current : { ...current, metadata: { summary, observedAt } };
440 + });
441 + }),
442 filesViewed: (target, answer) =>
443 Effect.sync(() => {
444 for (const listener of filesViewedAnswerListeners.get(filesViewedAnswerKey(target)) ?? [])
@@ -543,6 +579,7 @@ export function useSharedPullRequestSummary(
579 ? "none"
580 : pullRequestSummaryKey(environmentId, reference);
581 const observations = useAtomValue(pullRequestObservationsAtom(key));
582 + const edits = useAtomValue(pullRequestPendingEditsFor(environmentId, reference));
583 const saved = useAtomValue(
584 savedPullRequestSummaryAtom(
585 environmentId === null || reference === null
@@ -550,7 +587,11 @@ export function useSharedPullRequestSummary(
587 : savedPullRequestKey(environmentId, reference),
588 ),
589 );
553 - return newestPullRequestSummary(observedPullRequestSummary(observations), saved);
590 + return applyPullRequestSummaryEdits(
591 + reference,
592 + newestPullRequestSummary(saved, observedPullRequestSummary(observations)),
593 + edits,
594 + );
595 }
596 export const pullRequestStackAtom = createPullRequestStackAtomFamily(
597 connectionAtomRuntime,
@@ -664,6 +705,13 @@ function createMergedEnvironmentQuery<Input, A>(
705 };
706 }
707
708 +const usePullRequestHostListsQuery = createMergedEnvironmentQuery(
709 + "web-pull-requests:host-list",
710 + (target: EnvironmentQueryTarget<PullRequestListInput>) =>
711 + pullRequestHostAnswer(pullRequestEnvironment.list(target)),
712 + observeFailedPullRequestList,
713 +);
714 +
715 const usePullRequestListsQuery = createMergedEnvironmentQuery(
716 "web-pull-requests:list",
717 pullRequestEnvironment.list,
@@ -707,6 +755,8 @@ export interface MergedPullRequestListView {
755 readonly refresh: (targets?: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>) => void;
756 }
757
758 +// Merge inside each hook: the React Compiler memoizes it on `query.values` only there, and
759 +// PullRequestsPage sets state when the merged list's identity changes.
760 export function usePullRequestList(
761 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
762 ): MergedPullRequestListView {
@@ -721,6 +771,20 @@ export function usePullRequestList(
771 };
772 }
773
774 +export function usePullRequestHostList(
775 + targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
776 +): MergedPullRequestListView {
777 + const query = usePullRequestHostListsQuery(targets);
778 + const data = mergePullRequestLists(query.values);
779 + return {
780 + data,
781 + error: query.error,
782 + isPending: query.isPending,
783 + observations: query.observations,
784 + refresh: query.refresh,
785 + };
786 +}
787 +
788 export function usePullRequestListStats(
789 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListStatsInput>>,
790 ): {
packages/client-runtime/src/state/pullRequests.test.ts
+668
@@ -7,9 +7,11 @@ import {
7 AuthOrchestrationOperateScope,
8 ProjectId,
9 PullRequestOperationError,
10 + SourceControlProviderKind,
11 WS_METHODS,
12 type AuthSessionState,
13 type PullRequestListInput,
14 + type PullRequestListEntry,
15 } from "@t3tools/contracts";
16 import { expect, it } from "@effect/vitest";
17 import * as Schema from "effect/Schema";
@@ -40,8 +42,14 @@ import * as EnvironmentSupervisor from "../connection/supervisor.ts";
42 import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
43 import type { RpcSession } from "../rpc/session.ts";
44 import {
45 + applyPullRequestSummaryEdits,
46 createLinkedPullRequestSummaryAtomFamily,
47 createPullRequestEnvironmentAtoms,
48 + editHeldPullRequestListEntries,
49 + heldPullRequestListEntriesAtom,
50 + pullRequestHostAnswer,
51 + pullRequestPendingEditsAtom,
52 + pullRequestPendingEditsFor,
53 } from "./pullRequests.ts";
54 import * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts";
55 import { executeAtomQuery, queryPersistenceKey } from "./runtime.ts";
@@ -1095,6 +1103,20 @@ const actionReply = {
1103 observedAt: 200,
1104 };
1105
1106 +const actionListEntry: PullRequestListEntry = {
1107 + ...actionReply,
1108 + provider: SourceControlProviderKind.make("github"),
1109 + projectTitle: "Web",
1110 + state: "open",
1111 + author: null,
1112 + mergeability: "unknown",
1113 + additions: 0,
1114 + deletions: 0,
1115 + createdAt: actionReply.updatedAt,
1116 + viewerReviewRequested: false,
1117 + labels: [],
1118 +};
1119 +
1120 function actionReplyClient(overrides: Record<string, unknown> = {}) {
1121 return {
1122 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
@@ -2262,3 +2284,649 @@ it.effect("publishes the accepted guide run before the follow-up read finishes",
2284 expect(AsyncResult.getOrElse(registry.get(query), () => null)).toEqual(accepted);
2285 }),
2286 );
2287 +
2288 +const listResult = (entries: ReadonlyArray<object>) => ({
2289 + entries,
2290 + viewers: {},
2291 + providers: [],
2292 + errors: [],
2293 + truncated: false,
2294 + nextCursors: {},
2295 +});
2296 +
2297 +it.effect.each([
2298 + ["close", { state: "closed" }, "open"],
2299 + ["reopen", { state: "open" }, "closed"],
2300 + ["ready", { isDraft: false }, "open"],
2301 + ["draft", { isDraft: true }, "open"],
2302 + ["enable-auto-merge", { autoMergeEnabled: true }, "open"],
2303 + ["disable-auto-merge", { autoMergeEnabled: false }, "open"],
2304 +] as const)("shows %s in loaded readers before the host replies", ([action, shown, from]) =>
2305 + Effect.scoped(
2306 + Effect.gen(function* () {
2307 + let reads = 0;
2308 + const sent = yield* Deferred.make<void>();
2309 + const release = yield* Deferred.make<void>();
2310 + const before = {
2311 + ...actionReference,
2312 + provider: "github",
2313 + title: "Ship it",
2314 + url: actionReply.url,
2315 + author: null,
2316 + headBranch: "feature",
2317 + baseBranch: "main",
2318 + state: from,
2319 + isDraft: action === "ready",
2320 + autoMergeEnabled: action === "disable-auto-merge",
2321 + createdAt: "2026-10-27T08:00:00Z",
2322 + updatedAt: "2026-10-27T09:00:00Z",
2323 + observedAt: 100,
2324 + };
2325 + const read = () =>
2326 + Effect.sync(() => {
2327 + reads++;
2328 + return before;
2329 + });
2330 + const client = actionReplyClient({
2331 + [WS_METHODS.pullRequestsDetail]: read,
2332 + [WS_METHODS.pullRequestsPreview]: read,
2333 + [WS_METHODS.pullRequestsSummary]: read,
2334 + [WS_METHODS.pullRequestsList]: () =>
2335 + Effect.sync(() => {
2336 + reads++;
2337 + return listResult([before]);
2338 + }),
2339 + [WS_METHODS.pullRequestsRunAction]: () =>
2340 + Effect.gen(function* () {
2341 + yield* Deferred.succeed(sent, undefined);
2342 + yield* Deferred.await(release);
2343 + return { ...before, ...shown, updatedAt: "2026-10-27T10:00:00Z", observedAt: 200 };
2344 + }),
2345 + });
2346 + const { atoms, registry, runtime } = yield* makeTestRuntime(client);
2347 + const target = { environmentId: TARGET.environmentId, input: actionReference };
2348 + const readers: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [
2349 + atoms.detail(target),
2350 + atoms.preview(target),
2351 + createLinkedPullRequestSummaryAtomFamily(runtime, atoms.refreshes)(target),
2352 + ];
2353 + const list = atoms.list({ environmentId: target.environmentId, input: { state: from } });
2354 + for (const atom of [...readers, list]) {
2355 + registry.mount(atom);
2356 + yield* Effect.promise(() => executeAtomQuery(registry, atom));
2357 + }
2358 + reads = 0;
2359 +
2360 + const acting = yield* Effect.promise(() =>
2361 + atoms.runAction.run(registry, { ...target, input: { ...actionReference, action } }),
2362 + ).pipe(Effect.forkScoped);
2363 + yield* Deferred.await(sent);
2364 +
2365 + for (const atom of readers.slice(0, action.includes("auto-merge") ? 1 : readers.length)) {
2366 + expect(Option.getOrThrow(AsyncResult.value(registry.get(atom)))).toMatchObject(shown);
2367 + }
2368 + const rows = Option.getOrThrow(AsyncResult.value(registry.get(list))).entries;
2369 + if ("state" in shown) expect(rows).toEqual([]);
2370 + else if ("isDraft" in shown) expect(rows).toMatchObject([shown]);
2371 + else expect(rows).toHaveLength(1);
2372 + yield* Deferred.succeed(release, undefined);
2373 + yield* Fiber.join(acting);
2374 + expect(Option.getOrThrow(AsyncResult.value(registry.get(readers[0]!)))).toMatchObject({
2375 + ...shown,
2376 + updatedAt: "2026-10-27T10:00:00Z",
2377 + });
2378 + // Only a reopen re-reads, for the branch data and permissions its reply lacks.
2379 + expect(reads).toBe(action === "reopen" ? 1 : 0);
2380 + }),
2381 + ),
2382 +);
2383 +
2384 +it.effect("puts readers back when the host refuses an action, and saves nothing it guessed", () =>
2385 + Effect.scoped(
2386 + Effect.gen(function* () {
2387 + const sent = yield* Deferred.make<void>();
2388 + const release = yield* Deferred.make<void>();
2389 + const open = { ...actionReference, state: "open", isDraft: false, observedAt: 100 };
2390 + const saved = new Map<string, string>();
2391 + const client = actionReplyClient({
2392 + [WS_METHODS.pullRequestsDetail]: () => Effect.succeed(open),
2393 + [WS_METHODS.pullRequestsList]: () => Effect.succeed(listResult([open])),
2394 + [WS_METHODS.pullRequestsRunAction]: () =>
2395 + Effect.gen(function* () {
2396 + yield* Deferred.succeed(sent, undefined);
2397 + yield* Deferred.await(release);
2398 + return yield* new PullRequestOperationError({
2399 + operation: "runAction",
2400 + detail: "You cannot close this pull request.",
2401 + });
2402 + }),
2403 + });
2404 + const { atoms, registry } = yield* makeTestRuntime(
2405 + client,
2406 + undefined,
2407 + false,
2408 + {},
2409 + {
2410 + load: (_environmentId, key) => Effect.sync(() => Option.fromUndefinedOr(saved.get(key))),
2411 + save: (_environmentId, key, payload) => Effect.sync(() => void saved.set(key, payload)),
2412 + },
2413 + );
2414 + const target = { environmentId: TARGET.environmentId, input: actionReference };
2415 + const detail = atoms.detail(target);
2416 + const list = atoms.list({ environmentId: target.environmentId, input: { state: "open" } });
2417 + const loaded: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [
2418 + detail,
2419 + list,
2420 + ];
2421 + for (const atom of loaded) {
2422 + registry.mount(atom);
2423 + yield* Effect.promise(() => executeAtomQuery(registry, atom));
2424 + }
2425 +
2426 + const acting = yield* Effect.promise(() =>
2427 + atoms.runAction.run(registry, {
2428 + ...target,
2429 + input: { ...actionReference, action: "close" },
2430 + }),
2431 + ).pipe(Effect.forkScoped);
2432 + yield* Deferred.await(sent);
2433 + expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("closed");
2434 + const held = Option.getOrThrow(
2435 + AsyncResult.value(registry.get(pullRequestHostAnswer(list))),
2436 + ).entries;
2437 + const shownHeld = () =>
2438 + editHeldPullRequestListEntries({ state: "open" }, held, () =>
2439 + registry.get(pullRequestPendingEditsFor(target.environmentId, actionReference)),
2440 + );
2441 + expect(shownHeld()).toEqual([]);
2442 + yield* Deferred.succeed(release, undefined);
2443 + expect((yield* Fiber.join(acting))._tag).toBe("Failure");
2444 +
2445 + expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("open");
2446 + expect(Option.getOrThrow(AsyncResult.value(registry.get(list))).entries).toMatchObject([
2447 + { state: "open" },
2448 + ]);
2449 + expect(shownHeld()).toMatchObject([{ state: "open" }]);
2450 + expect([...saved.values()].some((payload) => payload.includes('"closed"'))).toBe(false);
2451 + }),
2452 + ),
2453 +);
2454 +
2455 +it.effect(
2456 + "keeps an accepted change on screen until the re-read when the reply has no summary",
2457 + () =>
2458 + Effect.scoped(
2459 + Effect.gen(function* () {
2460 + let state = "open";
2461 + let reads = 0;
2462 + const rereadStarted = yield* Deferred.make<void>();
2463 + const releaseReread = yield* Deferred.make<void>();
2464 + const client = actionReplyClient({
2465 + [WS_METHODS.pullRequestsDetail]: () =>
2466 + Effect.gen(function* () {
2467 + reads++;
2468 + const answer = { ...actionReference, state, observedAt: reads };
2469 + if (reads === 2) {
2470 + yield* Deferred.succeed(rereadStarted, undefined);
2471 + yield* Deferred.await(releaseReread);
2472 + }
2473 + return answer;
2474 + }),
2475 + [WS_METHODS.pullRequestsRunAction]: () =>
2476 + Effect.sync(() => {
2477 + state = "closed";
2478 + return undefined;
2479 + }),
2480 + });
2481 + let held = [actionListEntry] as ReadonlyArray<PullRequestListEntry>;
2482 + const { atoms, registry } = yield* makeTestRuntime(client, undefined, false, {
2483 + acceptedEdit: (_target, edit) =>
2484 + Effect.sync(() => {
2485 + held = editHeldPullRequestListEntries({ state: "all" }, held, () => [edit]);
2486 + }),
2487 + });
2488 + const target = { environmentId: TARGET.environmentId, input: actionReference };
2489 + const retained = heldPullRequestListEntriesAtom(
2490 + target.environmentId,
2491 + { state: "all" },
2492 + held,
2493 + );
2494 + registry.mount(retained);
2495 + const detail = atoms.detail(target);
2496 + registry.mount(detail);
2497 + yield* Effect.promise(() => executeAtomQuery(registry, detail));
2498 +
2499 + yield* Effect.promise(() =>
2500 + atoms.runAction.run(registry, {
2501 + ...target,
2502 + input: { ...actionReference, action: "close" },
2503 + }),
2504 + );
2505 + yield* Deferred.await(rereadStarted);
2506 +
2507 + expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("closed");
2508 + expect(held[0]?.state).toBe("closed");
2509 + expect(Option.getOrThrow(AsyncResult.value(registry.get(retained)))[0]?.state).toBe(
2510 + "closed",
2511 + );
2512 + yield* Deferred.succeed(releaseReread, undefined);
2513 + expect(
2514 + (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).observedAt,
2515 + ).toBe(2);
2516 + }),
2517 + ),
2518 +);
2519 +
2520 +it.effect.each([
2521 + ["with", { ...actionReply, state: "closed" as const }],
2522 + ["without", undefined],
2523 +] as const)("shows a queued close before the action ahead of it answers, %s a reply", ([, reply]) =>
2524 + Effect.scoped(
2525 + Effect.gen(function* () {
2526 + const firstSent = yield* Deferred.make<void>();
2527 + const release = yield* Deferred.make<void>();
2528 + const releaseReopen = yield* Deferred.make<void>();
2529 + const rows = [1, 2].map((number) => ({
2530 + ...actionReference,
2531 + number,
2532 + state: "open",
2533 + isDraft: false,
2534 + updatedAt: `2026-10-27T0${number}:00:00Z`,
2535 + }));
2536 + const client = actionReplyClient({
2537 + [WS_METHODS.pullRequestsList]: () => Effect.succeed(listResult(rows)),
2538 + [WS_METHODS.pullRequestsRunAction]: (input: {
2539 + readonly number: number;
2540 + readonly action: string;
2541 + }) =>
2542 + Effect.gen(function* () {
2543 + if (input.action === "reopen") {
2544 + yield* Deferred.await(releaseReopen);
2545 + return yield* new PullRequestOperationError({
2546 + operation: "runAction",
2547 + detail: "reopen refused",
2548 + });
2549 + }
2550 + if (input.number === 1) {
2551 + yield* Deferred.succeed(firstSent, undefined);
2552 + yield* Deferred.await(release);
2553 + return reply;
2554 + }
2555 + return undefined;
2556 + }),
2557 + });
2558 + const { atoms, registry } = yield* makeTestRuntime(client);
2559 + const list = atoms.list({ environmentId: TARGET.environmentId, input: { state: "open" } });
2560 + registry.mount(list);
2561 + yield* Effect.promise(() => executeAtomQuery(registry, list));
2562 +
2563 + const closes = [1, 2].map((number) =>
2564 + atoms.runAction.run(registry, {
2565 + environmentId: TARGET.environmentId,
2566 + input: { ...actionReference, number, action: "close" },
2567 + }),
2568 + );
2569 + yield* Deferred.await(firstSent);
2570 +
2571 + expect(Option.getOrThrow(AsyncResult.value(registry.get(list))).entries).toEqual([]);
2572 +
2573 + const reopen = atoms.runAction.run(registry, {
2574 + environmentId: TARGET.environmentId,
2575 + input: { ...actionReference, number: 1, action: "reopen" },
2576 + });
2577 + expect(
2578 + Option.getOrThrow(AsyncResult.value(registry.get(list))).entries.map((row) => row.number),
2579 + ).toEqual([1]);
2580 + yield* Deferred.succeed(release, undefined);
2581 + yield* Effect.promise(() => Promise.all(closes));
2582 + expect(
2583 + Option.getOrThrow(AsyncResult.value(registry.get(list))).entries.map((row) => row.number),
2584 + ).toEqual([1]);
2585 + yield* Deferred.succeed(releaseReopen, undefined);
2586 + expect((yield* Effect.promise(() => reopen))._tag).toBe("Failure");
2587 + expect(Option.getOrThrow(AsyncResult.value(registry.get(list))).entries).toEqual([]);
2588 + }),
2589 + ),
2590 +);
2591 +
2592 +it.effect("leaves a merge as it is until the host says what it did", () =>
2593 + Effect.scoped(
2594 + Effect.gen(function* () {
2595 + const sent = yield* Deferred.make<void>();
2596 + const release = yield* Deferred.make<void>();
2597 + const client = actionReplyClient({
2598 + [WS_METHODS.pullRequestsDetail]: () =>
2599 + Effect.succeed({ ...actionReference, state: "open", observedAt: 100 }),
2600 + [WS_METHODS.pullRequestsRunAction]: () =>
2601 + Effect.gen(function* () {
2602 + yield* Deferred.succeed(sent, undefined);
2603 + yield* Deferred.await(release);
2604 + // A merge queue takes the merge and merges later.
2605 + return { ...actionReply, state: "open", autoMergeEnabled: true };
2606 + }),
2607 + });
2608 + const { atoms, registry } = yield* makeTestRuntime(client);
2609 + const target = { environmentId: TARGET.environmentId, input: actionReference };
2610 + const detail = atoms.detail(target);
2611 + registry.mount(detail);
2612 + yield* Effect.promise(() => executeAtomQuery(registry, detail));
2613 +
2614 + const acting = yield* Effect.promise(() =>
2615 + atoms.runAction.run(registry, {
2616 + ...target,
2617 + input: { ...actionReference, action: "merge" },
2618 + }),
2619 + ).pipe(Effect.forkScoped);
2620 + yield* Deferred.await(sent);
2621 + expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("open");
2622 + yield* Deferred.succeed(release, undefined);
2623 + yield* Fiber.join(acting);
2624 + expect(Option.getOrThrow(AsyncResult.value(registry.get(detail)))).toMatchObject({
2625 + state: "open",
2626 + autoMergeEnabled: true,
2627 + });
2628 + }),
2629 + ),
2630 +);
2631 +
2632 +it.effect.each(["accepted", "refused"] as const)(
2633 + "shows a title edit at once and keeps it only when the host takes it (%s)",
2634 + (outcome) =>
2635 + Effect.scoped(
2636 + Effect.gen(function* () {
2637 + let title = "Original";
2638 + let reads = 0;
2639 + const sent = yield* Deferred.make<void>();
2640 + const release = yield* Deferred.make<void>();
2641 + const read = () =>
2642 + Effect.sync(() => {
2643 + reads++;
2644 + return { ...actionReference, state: "open", title, observedAt: reads };
2645 + });
2646 + const client = actionReplyClient({
2647 + [WS_METHODS.pullRequestsDetail]: read,
2648 + [WS_METHODS.pullRequestsPreview]: read,
2649 + [WS_METHODS.pullRequestsList]: () =>
2650 + Effect.sync(() => {
2651 + reads++;
2652 + return listResult([
2653 + { ...actionReference, state: "open", title, updatedAt: actionReply.updatedAt },
2654 + ]);
2655 + }),
2656 + [WS_METHODS.pullRequestsUpdate]: (input: { readonly title: string }) =>
2657 + Effect.gen(function* () {
2658 + yield* Deferred.succeed(sent, undefined);
2659 + yield* Deferred.await(release);
2660 + if (outcome === "refused") return yield* new MutationRefused();
2661 + title = input.title;
2662 + }),
2663 + });
2664 + let held: ReadonlyArray<PullRequestListEntry> = [];
2665 + let observedTitle = "Original";
2666 + const handlers = {
2667 + detail: (_target: unknown, detail: { readonly title: string }) =>
2668 + Effect.sync(() => {
2669 + observedTitle = detail.title;
2670 + }),
2671 + acceptedEdit: (
2672 + _target: unknown,
2673 + edit: Parameters<typeof applyPullRequestSummaryEdits>[2][number],
2674 + ) =>
2675 + Effect.sync(() => {
2676 + observedTitle = edit.title ?? observedTitle;
2677 + held = editHeldPullRequestListEntries({ state: "open" }, held, () => [edit]);
2678 + }),
2679 + };
2680 + const { atoms, registry } = yield* makeTestRuntime(client, undefined, false, handlers);
2681 + const target = { environmentId: TARGET.environmentId, input: actionReference };
2682 + const detail = atoms.detail(target);
2683 + const preview = atoms.preview(target);
2684 + const list = atoms.list({ environmentId: target.environmentId, input: { state: "open" } });
2685 + const loaded: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [
2686 + detail,
2687 + preview,
2688 + list,
2689 + ];
2690 + for (const atom of loaded) {
2691 + registry.mount(atom);
2692 + yield* Effect.promise(() => executeAtomQuery(registry, atom));
2693 + }
2694 + held = Option.getOrThrow(
2695 + AsyncResult.value(registry.get(pullRequestHostAnswer(list))),
2696 + ).entries;
2697 + const retained = heldPullRequestListEntriesAtom(
2698 + target.environmentId,
2699 + { state: "open" },
2700 + held,
2701 + );
2702 + registry.mount(retained);
2703 + const titles = () => [
2704 + Option.getOrThrow(AsyncResult.value(registry.get(detail))).title,
2705 + Option.getOrThrow(AsyncResult.value(registry.get(preview))).title,
2706 + Option.getOrThrow(AsyncResult.value(registry.get(list))).entries[0]?.title,
2707 + applyPullRequestSummaryEdits(
2708 + actionReference,
2709 + {
2710 + ...actionReply,
2711 + provider: SourceControlProviderKind.make("github"),
2712 + title: observedTitle,
2713 + },
2714 + registry.get(pullRequestPendingEditsAtom(target.environmentId)),
2715 + )?.title,
2716 + ];
2717 +
2718 + const editing = yield* Effect.promise(() =>
2719 + atoms.update.run(registry, { ...target, input: { ...actionReference, title: "Edited" } }),
2720 + ).pipe(Effect.forkScoped);
2721 + yield* Deferred.await(sent);
2722 + expect(titles()).toEqual(["Edited", "Edited", "Edited", "Edited"]);
2723 + yield* Deferred.succeed(release, undefined);
2724 + yield* Fiber.join(editing);
2725 +
2726 + expect(titles()).toEqual(
2727 + outcome === "refused"
2728 + ? ["Original", "Original", "Original", "Original"]
2729 + : ["Edited", "Edited", "Edited", "Edited"],
2730 + );
2731 + expect(observedTitle).toBe(outcome === "refused" ? "Original" : "Edited");
2732 + expect(held[0]?.title).toBe(outcome === "refused" ? "Original" : "Edited");
2733 + expect(Option.getOrThrow(AsyncResult.value(registry.get(retained)))[0]?.title).toBe(
2734 + outcome === "refused" ? "Original" : "Edited",
2735 + );
2736 + // The edit is known, so no reader asks the host again.
2737 + expect(reads).toBe(3);
2738 + }),
2739 + ),
2740 +);
2741 +
2742 +it.effect.each(["accepted", "refused"] as const)(
2743 + "keeps a label change on retained rows only when the host takes it (%s)",
2744 + (outcome) =>
2745 + Effect.scoped(
2746 + Effect.gen(function* () {
2747 + const sent = yield* Deferred.make<void>();
2748 + const release = yield* Deferred.make<void>();
2749 + const existing = { name: "existing", color: "111111" };
2750 + const added = { name: "new", color: "abcdef" };
2751 + const client = actionReplyClient({
2752 + [WS_METHODS.pullRequestsDetail]: () =>
2753 + Effect.succeed({ ...actionReference, state: "open", labels: [existing] }),
2754 + [WS_METHODS.pullRequestsLabelCandidates]: () =>
2755 + Effect.succeed({
2756 + candidates: [
2757 + { ...existing, description: null, isApplied: true },
2758 + { ...added, description: null, isApplied: false },
2759 + ],
2760 + truncated: false,
2761 + }),
2762 + [WS_METHODS.pullRequestsSetLabels]: () =>
2763 + Effect.gen(function* () {
2764 + yield* Deferred.succeed(sent, undefined);
2765 + yield* Deferred.await(release);
2766 + if (outcome === "refused") return yield* new MutationRefused();
2767 + }),
2768 + });
2769 + let held: ReadonlyArray<PullRequestListEntry> = [
2770 + { ...actionListEntry, labels: [existing] },
2771 + ];
2772 + const { atoms, registry } = yield* makeTestRuntime(client, undefined, false, {
2773 + acceptedEdit: (_target, edit) =>
2774 + Effect.sync(() => {
2775 + held = editHeldPullRequestListEntries({ state: "open" }, held, () => [edit]);
2776 + }),
2777 + });
2778 + const target = { environmentId: TARGET.environmentId, input: actionReference };
2779 + const retained = heldPullRequestListEntriesAtom(
2780 + target.environmentId,
2781 + { state: "open" },
2782 + held,
2783 + );
2784 + registry.mount(retained);
2785 + const detail = atoms.detail(target);
2786 + const candidates = atoms.labelCandidates(target);
2787 + const loaded: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [
2788 + detail,
2789 + candidates,
2790 + ];
2791 + for (const atom of loaded) {
2792 + registry.mount(atom);
2793 + yield* Effect.promise(() => executeAtomQuery(registry, atom));
2794 + }
2795 +
2796 + const labelling = yield* Effect.promise(() =>
2797 + atoms.setLabels.run(registry, {
2798 + ...target,
2799 + input: { ...actionReference, labels: ["new"], applied: true },
2800 + }),
2801 + ).pipe(Effect.forkScoped);
2802 + yield* Deferred.await(sent);
2803 + expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).labels).toEqual([
2804 + existing,
2805 + added,
2806 + ]);
2807 + expect(
2808 + Option.getOrThrow(AsyncResult.value(registry.get(candidates))).candidates.map(
2809 + (candidate) => candidate.isApplied,
2810 + ),
2811 + ).toEqual([true, true]);
2812 + yield* Deferred.succeed(release, undefined);
2813 + expect((yield* Fiber.join(labelling))._tag).toBe(
2814 + outcome === "refused" ? "Failure" : "Success",
2815 + );
2816 + expect(held[0]?.labels).toEqual(outcome === "refused" ? [existing] : [existing, added]);
2817 + expect(Option.getOrThrow(AsyncResult.value(registry.get(retained)))[0]?.labels).toEqual(
2818 + outcome === "refused" ? [existing] : [existing, added],
2819 + );
2820 +
2821 + expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).labels).toEqual(
2822 + outcome === "refused" ? [existing] : [existing, added],
2823 + );
2824 + expect(
2825 + Option.getOrThrow(AsyncResult.value(registry.get(candidates))).candidates.map(
2826 + (candidate) => candidate.isApplied,
2827 + ),
2828 + ).toEqual(outcome === "refused" ? [true, false] : [true, true]);
2829 + }),
2830 + ),
2831 +);
2832 +
2833 +it.effect.each(["loaded", "loading"] as const)(
2834 + "keeps an accepted label change when a candidates read sent before it answers late (%s)",
2835 + (shown) =>
2836 + Effect.scoped(
2837 + Effect.gen(function* () {
2838 + let applied = false;
2839 + let reads = 0;
2840 + const readStarted = yield* Deferred.make<void>();
2841 + const releaseRead = yield* Deferred.make<void>();
2842 + const client = actionReplyClient({
2843 + [WS_METHODS.pullRequestsLabelCandidates]: () =>
2844 + Effect.gen(function* () {
2845 + reads++;
2846 + const answer = {
2847 + candidates: [{ name: "new", color: null, description: null, isApplied: applied }],
2848 + truncated: false,
2849 + };
2850 + if (reads === (shown === "loaded" ? 2 : 1)) {
2851 + yield* Deferred.succeed(readStarted, undefined);
2852 + yield* Deferred.await(releaseRead);
2853 + }
2854 + return answer;
2855 + }),
2856 + [WS_METHODS.pullRequestsSetLabels]: () =>
2857 + Effect.sync(() => {
2858 + applied = true;
2859 + }),
2860 + });
2861 + const { atoms, registry } = yield* makeTestRuntime(client);
2862 + const target = { environmentId: TARGET.environmentId, input: actionReference };
2863 + const candidates = atoms.labelCandidates(target);
2864 + registry.mount(candidates);
2865 + if (shown === "loaded") {
2866 + yield* Effect.promise(() => executeAtomQuery(registry, candidates));
2867 + registry.refresh(candidates);
2868 + }
2869 + yield* Deferred.await(readStarted);
2870 +
2871 + yield* Effect.promise(() =>
2872 + atoms.setLabels.run(registry, {
2873 + ...target,
2874 + input: { ...actionReference, labels: ["new"], applied: true },
2875 + }),
2876 + );
2877 + yield* Deferred.succeed(releaseRead, undefined);
2878 +
2879 + expect(
2880 + (yield* AtomRegistry.getResult(registry, candidates, { suspendOnWaiting: true }))
2881 + .candidates[0]?.isApplied,
2882 + ).toBe(true);
2883 + }),
2884 + ),
2885 +);
2886 +
2887 +it.effect.each(["accepted", "refused"] as const)(
2888 + "shows a close in the checks read the panel takes its state from (%s)",
2889 + (outcome) =>
2890 + Effect.scoped(
2891 + Effect.gen(function* () {
2892 + const sent = yield* Deferred.make<void>();
2893 + const release = yield* Deferred.make<void>();
2894 + let reads = 0;
2895 + const client = actionReplyClient({
2896 + [WS_METHODS.pullRequestsChecks]: () =>
2897 + reads++ === 0
2898 + ? Effect.succeed({ state: "open", checks: [], observedAt: 100 })
2899 + : Effect.never,
2900 + [WS_METHODS.pullRequestsRunAction]: () =>
2901 + Effect.gen(function* () {
2902 + yield* Deferred.succeed(sent, undefined);
2903 + yield* Deferred.await(release);
2904 + if (outcome === "accepted") return { ...actionReply, state: "closed" as const };
2905 + return yield* new PullRequestOperationError({
2906 + operation: "runAction",
2907 + detail: "You cannot close this pull request.",
2908 + });
2909 + }),
2910 + });
2911 + const { atoms, registry } = yield* makeTestRuntime(client);
2912 + const target = { environmentId: TARGET.environmentId, input: actionReference };
2913 + const checks = atoms.checks(target);
2914 + registry.mount(checks);
2915 + yield* Effect.promise(() => executeAtomQuery(registry, checks));
2916 + const state = () => Option.getOrThrow(AsyncResult.value(registry.get(checks)))?.state;
2917 +
2918 + const acting = yield* Effect.promise(() =>
2919 + atoms.runAction.run(registry, {
2920 + ...target,
2921 + input: { ...actionReference, action: "close" },
2922 + }),
2923 + ).pipe(Effect.forkScoped);
2924 + yield* Deferred.await(sent);
2925 + expect(state()).toBe("closed");
2926 + yield* Deferred.succeed(release, undefined);
2927 + yield* Fiber.join(acting);
2928 + // An accepted close stays while the next checks read is still out.
2929 + expect(state()).toBe(outcome === "accepted" ? "closed" : "open");
2930 + }),
2931 + ),
2932 +);
packages/client-runtime/src/state/pullRequests.ts
+531 -92
@@ -16,11 +16,15 @@ import {
16 type PullRequestListInput,
17 type PullRequestListStatsInput,
18 type PullRequestListStatsResult,
19 + type PullRequestUpdateInput,
20 type PullRequestDetail,
21 type PullRequestDiffInput,
22 type PullRequestListEntry,
23 type PullRequestRef,
24 type PullRequestMergeMethod,
25 + type PullRequestLabel,
26 + type PullRequestLabelCandidateList,
27 + type PullRequestState,
28 PullRequestOperationError,
29 PullRequestSummary,
30 type VcsStatusResult,
@@ -34,6 +38,7 @@ import * as SubscriptionRef from "effect/SubscriptionRef";
38 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
39
40 import {
41 + type AtomCommand,
42 createAtomCommandScheduler,
43 createEnvironmentRpcCommand,
44 createEnvironmentRpcQueryAtomFamily,
@@ -120,10 +125,11 @@ function writableQueryFamily<A, E>(
125 /** Restart pre-mutation reads before patching so they cannot restore stale values. */
126 function updateCached<A, E>(
127 registry: AtomRegistry.AtomRegistry,
123 - atom: Atom.Writable<AsyncResult.AsyncResult<A, E>>,
128 + shown: Atom.Writable<AsyncResult.AsyncResult<A, E>>,
129 update: (value: A) => A,
130 refresh = false,
131 ) {
132 + const atom = (uneditedReaders.get(shown) ?? shown) as typeof shown;
133 if (refresh || registry.get(atom).waiting) registry.refresh(atom);
134 registry.update(atom, AsyncResult.map(update));
135 }
@@ -143,6 +149,253 @@ interface ActionReplyPatch {
149 // Module-wide so readers built by separate factories, such as linked summaries, are patched too.
150 const actionReplyPatches = new WeakMap<object, ActionReplyPatch>();
151
152 +/** What a write in flight will change, shown by every reader until the host answers. */
153 +export interface PullRequestPendingEdit {
154 + readonly reference: PullRequestRef;
155 + readonly state?: PullRequestState;
156 + readonly isDraft?: boolean;
157 + readonly autoMergeEnabled?: boolean;
158 + readonly title?: string;
159 + readonly body?: string;
160 + readonly labels?: {
161 + readonly applied: boolean;
162 + readonly labels: ReadonlyArray<PullRequestLabel>;
163 + };
164 +}
165 +
166 +type EditedField = "state" | "isDraft" | "autoMergeEnabled" | "title" | "body";
167 +
168 +interface EditableReader {
169 + readonly environmentId: EnvironmentId;
170 + readonly concerns: (reference: PullRequestRef) => boolean;
171 + readonly edit: (
172 + value: never,
173 + edits: ReadonlyArray<PullRequestPendingEdit>,
174 + pending?: ReadonlyArray<PullRequestPendingEdit>,
175 + ) => unknown;
176 +}
177 +
178 +// Module-wide like the reply patches, so separately built readers see the same writes.
179 +export const pullRequestPendingEditsAtom = Atom.family((_environmentId: EnvironmentId | null) =>
180 + Atom.make<ReadonlyArray<PullRequestPendingEdit>>([]).pipe(Atom.keepAlive),
181 +);
182 +const editableReaders = new WeakMap<object, EditableReader>();
183 +const editedReaders = new WeakMap<object, object>();
184 +const uneditedReaders = new WeakMap<object, object>();
185 +
186 +const pendingEditsByPullRequest = Atom.family((key: string) => {
187 + const [environmentId, reference] = JSON.parse(key) as [EnvironmentId, PullRequestRef];
188 + return Atom.make((get) =>
189 + get(pullRequestPendingEditsAtom(environmentId)).filter((edit) =>
190 + samePullRequest(reference, edit.reference),
191 + ),
192 + ).pipe(
193 + Atom.withEquality(
194 + (previous: ReadonlyArray<PullRequestPendingEdit>, next) =>
195 + previous.length === next.length && previous.every((edit, index) => edit === next[index]),
196 + ),
197 + );
198 +});
199 +const noPendingEdits = Atom.make<ReadonlyArray<PullRequestPendingEdit>>([]);
200 +
201 +export function pullRequestPendingEditsFor(
202 + environmentId: EnvironmentId | null,
203 + reference: PullRequestRef | null,
204 +): Atom.Atom<ReadonlyArray<PullRequestPendingEdit>> {
205 + return environmentId === null || reference === null
206 + ? noPendingEdits
207 + : pendingEditsByPullRequest(JSON.stringify([environmentId, pullRequestReference(reference)]));
208 +}
209 +
210 +export function pullRequestHostAnswer<A>(reader: Atom.Atom<A>): Atom.Atom<A> {
211 + return (uneditedReaders.get(reader) ?? reader) as Atom.Atom<A>;
212 +}
213 +
214 +function loadedValue<A>(registry: AtomRegistry.AtomRegistry, atom: Atom.Atom<unknown>) {
215 + return Option.flatMap(registry.getNodes().get(atom)?.valueOption() ?? Option.none(), (result) =>
216 + AsyncResult.value(result as AsyncResult.AsyncResult<A, unknown>),
217 + );
218 +}
219 +
220 +function withEdit<T extends object>(
221 + value: T,
222 + edit: PullRequestPendingEdit,
223 + fields: ReadonlyArray<EditedField>,
224 +): T {
225 + const held = value as Record<string, unknown>;
226 + const changed = fields.filter(
227 + (field) => edit[field] !== undefined && held[field] !== edit[field],
228 + );
229 + let next =
230 + changed.length === 0
231 + ? held
232 + : { ...held, ...Object.fromEntries(changed.map((field) => [field, edit[field]])) };
233 + if (edit.autoMergeEnabled === false && next.autoMergeMethod !== undefined) {
234 + const { autoMergeMethod: _disarmed, ...withoutAutoMerge } = next;
235 + next = withoutAutoMerge;
236 + }
237 + return next as T;
238 +}
239 +
240 +function withLabelEdit<T extends { readonly labels: ReadonlyArray<PullRequestLabel> }>(
241 + value: T,
242 + edit: PullRequestPendingEdit,
243 +): T {
244 + if (edit.labels === undefined) return value;
245 + const { applied, labels: changed } = edit.labels;
246 + const names = new Set(changed.map((label) => label.name));
247 + const labels = applied
248 + ? [
249 + ...value.labels,
250 + ...changed.filter((label) => !value.labels.some((held) => held.name === label.name)),
251 + ]
252 + : value.labels.filter((label) => !names.has(label.name));
253 + return labels.length === value.labels.length ? value : { ...value, labels };
254 +}
255 +
256 +function withLabelCandidateEdit(
257 + value: PullRequestLabelCandidateList,
258 + edit: PullRequestPendingEdit,
259 +): PullRequestLabelCandidateList {
260 + if (edit.labels === undefined) return value;
261 + const { applied, labels } = edit.labels;
262 + let changed = false;
263 + const candidates = value.candidates.map((candidate) => {
264 + if (candidate.isApplied === applied || !labels.some((label) => label.name === candidate.name))
265 + return candidate;
266 + changed = true;
267 + return { ...candidate, isApplied: applied };
268 + });
269 + return changed ? { ...value, candidates } : value;
270 +}
271 +
272 +/**
273 + * The reader with every write in flight for its pull request applied. Writes go to the reader
274 + * underneath, so a refused edit never stays behind in what the host said.
275 + */
276 +function editedQuery<A, E>(
277 + inner: Atom.Writable<AsyncResult.AsyncResult<A, E>>,
278 + reader: Omit<EditableReader, "edit"> & {
279 + readonly edit: (
280 + value: A,
281 + edits: ReadonlyArray<PullRequestPendingEdit>,
282 + pending?: ReadonlyArray<PullRequestPendingEdit>,
283 + ) => A;
284 + },
285 + idleTtlMs = 5 * 60_000,
286 +): Atom.Writable<AsyncResult.AsyncResult<A, E>> {
287 + const existing = editedReaders.get(inner);
288 + if (existing !== undefined) return existing as Atom.Writable<AsyncResult.AsyncResult<A, E>>;
289 + const shown = Atom.writable(
290 + (get) => {
291 + const result = get(inner);
292 + const edits = get(pullRequestPendingEditsAtom(reader.environmentId)).filter((edit) =>
293 + reader.concerns(edit.reference),
294 + );
295 + const value = AsyncResult.value(result);
296 + if (Option.isNone(value)) return result;
297 + const next = reader.edit(value.value, edits);
298 + return next === value.value ? result : AsyncResult.map(result, () => next);
299 + },
300 + (context, value: AsyncResult.AsyncResult<A, E>) => context.set(inner, value),
301 + (refresh) => refresh(inner),
302 + ).pipe(Atom.setIdleTTL(idleTtlMs));
303 + editableReaders.set(inner, reader as EditableReader);
304 + editedReaders.set(inner, shown);
305 + uneditedReaders.set(shown, inner);
306 + return shown;
307 +}
308 +
309 +/** Shows the command's edit from the click until it settles, queued behind others or not. */
310 +function showWhileInFlight<Target extends { readonly environmentId: EnvironmentId }, A, E, C>(
311 + command: C & AtomCommand<Target, A, E>,
312 + editOf: (registry: AtomRegistry.AtomRegistry, target: Target) => PullRequestPendingEdit | null,
313 +): C {
314 + return {
315 + ...command,
316 + run: async (registry, target) => {
317 + const edit = editOf(registry, target);
318 + if (edit === null) return command.run(registry, target);
319 + const edits = pullRequestPendingEditsAtom(target.environmentId);
320 + registry.update(edits, (current) => [...current, edit]);
321 + try {
322 + return await command.run(registry, target);
323 + } finally {
324 + registry.update(edits, (current) => current.filter((entry) => entry !== edit));
325 + }
326 + },
327 + } satisfies AtomCommand<Target, A, E>;
328 +}
329 +
330 +/** Keeps an accepted edit in loaded readers once it stops being in flight. */
331 +function settleEdit(
332 + registry: AtomRegistry.AtomRegistry,
333 + environmentId: EnvironmentId,
334 + edit: PullRequestPendingEdit | null,
335 + readsAfterWrite = false,
336 +) {
337 + if (edit === null) return;
338 + const pending = registry.get(pullRequestPendingEditsAtom(environmentId));
339 + for (const atom of registry.getNodes().keys()) {
340 + const reader = typeof atom === "string" ? undefined : editableReaders.get(atom);
341 + if (reader?.environmentId !== environmentId || !reader.concerns(edit.reference)) continue;
342 + const shown = loadedValue<never>(registry, atom as Atom.Atom<unknown>);
343 + const writable = atom as Atom.Writable<AsyncResult.AsyncResult<never, unknown>>;
344 + const unchanged =
345 + Option.isSome(shown) && reader.edit(shown.value, [edit], pending) === shown.value;
346 + if (unchanged) continue;
347 + // A read still waiting may predate the write, unless the caller started it after the commit.
348 + if (!readsAfterWrite && registry.get(writable).waiting) registry.refresh(writable);
349 + if (Option.isNone(shown)) continue;
350 + registry.update(
351 + writable,
352 + AsyncResult.map((value) => reader.edit(value, [edit], pending) as never),
353 + );
354 + }
355 +}
356 +
357 +function pullRequestReference(input: PullRequestRef): PullRequestRef {
358 + const { projectId, host, repository, number, expectedAccountId } = input;
359 + return {
360 + projectId,
361 + ...(host === undefined ? {} : { host }),
362 + repository,
363 + number,
364 + ...(expectedAccountId === undefined ? {} : { expectedAccountId }),
365 + };
366 +}
367 +
368 +/** What an action changes, left out where only the host knows, as when a queue takes a merge. */
369 +function actionEdit(input: PullRequestActionInput): PullRequestPendingEdit | null {
370 + if (input.stackNumber !== undefined) return null;
371 + const reference = pullRequestReference(input);
372 + switch (input.action) {
373 + case "close":
374 + return { reference, state: "closed" };
375 + case "reopen":
376 + return { reference, state: "open" };
377 + case "ready":
378 + return { reference, isDraft: false };
379 + case "draft":
380 + return { reference, isDraft: true };
381 + case "enable-auto-merge":
382 + return { reference, autoMergeEnabled: true };
383 + case "disable-auto-merge":
384 + return { reference, autoMergeEnabled: false };
385 + default:
386 + return null;
387 + }
388 +}
389 +
390 +function updateEdit(input: PullRequestUpdateInput): PullRequestPendingEdit | null {
391 + if (input.title === undefined && input.body === undefined) return null;
392 + return {
393 + reference: pullRequestReference(input),
394 + ...(input.title === undefined ? {} : { title: input.title }),
395 + ...(input.body === undefined ? {} : { body: input.body }),
396 + };
397 +}
398 +
399 function samePullRequest(reader: PullRequestRef, acted: PullRequestRef) {
400 return (
401 reader.projectId === acted.projectId &&
@@ -154,6 +407,21 @@ function samePullRequest(reader: PullRequestRef, acted: PullRequestRef) {
407 );
408 }
409
410 +export function applyPullRequestSummaryEdits(
411 + reference: PullRequestRef | null,
412 + summary: PullRequestSummary | null,
413 + edits: ReadonlyArray<PullRequestPendingEdit>,
414 +): PullRequestSummary | null {
415 + if (reference === null || summary === null) return summary;
416 + return edits.reduce(
417 + (current, edit) =>
418 + samePullRequest(reference, edit.reference)
419 + ? withEdit(current, edit, ["state", "isDraft", "autoMergeEnabled", "title"])
420 + : current,
421 + summary,
422 + );
423 +}
424 +
425 function pickDefined<T extends object, K extends keyof T>(
426 source: T,
427 keys: ReadonlyArray<K>,
@@ -172,6 +440,22 @@ function listAccepts(input: PullRequestListInput, state: string, isDraft: boolea
440 );
441 }
442
443 +function listKeeps(
444 + input: PullRequestListInput,
445 + entry: PullRequestListEntry,
446 + pending: ReadonlyArray<PullRequestPendingEdit>,
447 +) {
448 + if (listAccepts(input, entry.state, entry.isDraft)) return true;
449 + const edited = pending.reduce(
450 + (current, edit) =>
451 + samePullRequest(entry, edit.reference)
452 + ? withEdit(current, edit, ["state", "isDraft"])
453 + : current,
454 + entry,
455 + );
456 + return edited !== entry && listAccepts(input, edited.state, edited.isDraft);
457 +}
458 +
459 /**
460 * Listing rows with an action's reply applied, the same array when it changes none, and `refresh`
461 * when the reply adds the pull request to a listing, which only a read can place.
@@ -181,6 +465,7 @@ export function patchPullRequestListEntries<Entry extends PullRequestListEntry>(
465 entries: ReadonlyArray<Entry>,
466 reference: PullRequestRef,
467 reply: PullRequestSummary,
468 + pending: ReadonlyArray<PullRequestPendingEdit> = [],
469 ): ReadonlyArray<Entry> | "refresh" {
470 let found = false;
471 let changed = false;
@@ -203,7 +488,7 @@ export function patchPullRequestListEntries<Entry extends PullRequestListEntry>(
488 "updatedAt",
489 ]),
490 };
206 - return listAccepts(input, next.state, next.isDraft) ? [next] : [];
491 + return listKeeps(input, next, pending) ? [next] : [];
492 });
493 if (!found) {
494 return input.cursors === undefined && listAccepts(input, reply.state, reply.isDraft)
@@ -215,13 +500,66 @@ export function patchPullRequestListEntries<Entry extends PullRequestListEntry>(
500 : entries;
501 }
502
503 +function editPullRequestListEntries<Entry extends PullRequestListEntry>(
504 + input: PullRequestListInput,
505 + entries: ReadonlyArray<Entry>,
506 + edits: ReadonlyArray<PullRequestPendingEdit>,
507 + pending = edits,
508 +): ReadonlyArray<Entry> {
509 + let changed = false;
510 + const edited = entries.flatMap((entry): Entry[] => {
511 + const next = edits.reduce(
512 + (current, edit) =>
513 + samePullRequest(entry, edit.reference)
514 + ? withLabelEdit(withEdit(current, edit, ["state", "isDraft", "title"]), edit)
515 + : current,
516 + entry,
517 + );
518 + if (next === entry && listAccepts(input, next.state, next.isDraft)) return [entry];
519 + changed = true;
520 + return listKeeps(input, next, pending) ? [next] : [];
521 + });
522 + return changed ? edited : entries;
523 +}
524 +
525 +export function editHeldPullRequestListEntries<Entry extends PullRequestListEntry>(
526 + input: PullRequestListInput,
527 + entries: ReadonlyArray<Entry>,
528 + editsOf: (entry: Entry) => ReadonlyArray<PullRequestPendingEdit>,
529 + pending?: ReadonlyArray<PullRequestPendingEdit>,
530 +): ReadonlyArray<Entry> {
531 + let changed = false;
532 + const shown = entries.flatMap((entry) => {
533 + const edits = editsOf(entry);
534 + const next = editPullRequestListEntries(input, [entry], edits, pending);
535 + if (next[0] !== entry) changed = true;
536 + return next;
537 + });
538 + return changed ? shown : entries;
539 +}
540 +
541 +export function heldPullRequestListEntriesAtom<Entry extends PullRequestListEntry>(
542 + environmentId: EnvironmentId,
543 + input: PullRequestListInput,
544 + entries: ReadonlyArray<Entry>,
545 +) {
546 + return actionPatchedQuery(() => Atom.make(AsyncResult.success(entries)), {
547 + label: "pull-requests:held-list-entries",
548 + concerns: (_input: PullRequestListInput, reference) =>
549 + entries.some((entry) => samePullRequest(entry, reference)),
550 + edit: editPullRequestListEntries<Entry>,
551 + patch: patchPullRequestListEntries<Entry>,
552 + })({ environmentId, input });
553 +}
554 +
555 function patchListWithReply(
556 input: PullRequestListInput,
557 value: PullRequestListResult,
558 reference: PullRequestRef,
559 reply: PullRequestSummary,
560 + pending: ReadonlyArray<PullRequestPendingEdit>,
561 ): PullRequestListResult | "refresh" {
224 - const entries = patchPullRequestListEntries(input, value.entries, reference, reply);
562 + const entries = patchPullRequestListEntries(input, value.entries, reference, reply, pending);
563 if (entries === "refresh") return entries;
564 return entries === value.entries ? value : { ...value, entries };
565 }
@@ -246,6 +584,7 @@ function actionPatchedQuery<Input, A, E>(
584 value: A,
585 reference: PullRequestRef,
586 reply: PullRequestSummary,
587 + pending: ReadonlyArray<PullRequestPendingEdit>,
588 ) => A | "refresh";
589 /** Fields the reply lacks also changed, so the patched value shows while a read fetches them. */
590 readonly rereads?: (value: A, reply: PullRequestSummary) => boolean;
@@ -253,6 +592,13 @@ function actionPatchedQuery<Input, A, E>(
592 readonly rereadWithoutReply?: boolean;
593 /** False for reads the refresh stream does not restart; defaults to true. */
594 readonly refreshedByServer?: (input: Input) => boolean;
595 + /** Shows a write in flight; absent where the reader holds nothing such a write changes. */
596 + readonly edit?: (
597 + input: Input,
598 + value: A,
599 + edits: ReadonlyArray<PullRequestPendingEdit>,
600 + pending?: ReadonlyArray<PullRequestPendingEdit>,
601 + ) => A;
602 },
603 ) {
604 const writable = Atom.family((atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>) =>
@@ -261,7 +607,20 @@ function actionPatchedQuery<Input, A, E>(
607 return (target: { readonly environmentId: EnvironmentId; readonly input: Input }) => {
608 const query = source(target);
609 const atom = writable(query);
264 - if (actionReplyPatches.has(atom)) return atom;
610 + const edit = options.edit;
611 + const reader =
612 + edit === undefined
613 + ? atom
614 + : editedQuery(
615 + atom,
616 + {
617 + environmentId: target.environmentId,
618 + concerns: (reference) => options.concerns(target.input, reference),
619 + edit: (value, edits, pending) => edit(target.input, value, edits, pending),
620 + },
621 + options.idleTtlMs,
622 + );
623 + if (actionReplyPatches.has(atom)) return reader;
624 const pendingRead = (registry: AtomRegistry.AtomRegistry) => {
625 const result = Option.getOrUndefined(
626 registry.getNodes().get(query)?.valueOption() ?? Option.none(),
@@ -290,14 +649,22 @@ function actionPatchedQuery<Input, A, E>(
649 (current: AsyncResult.AsyncResult<A, E>) => AsyncResult.value(current),
650 );
651 if (Option.isNone(shown)) return reread();
293 - const patched = options.patch(target.input, shown.value, reference, reply);
652 + const patched = options.patch(
653 + target.input,
654 + shown.value,
655 + reference,
656 + reply,
657 + registry.get(pullRequestPendingEditsAtom(environmentId)),
658 + );
659 if (patched === "refresh") return reread();
660 const lacking = options.rereads?.(shown.value, reply) === true;
661 const next = reuseUnchanged(shown.value, patched);
662 if (next === shown.value)
663 return lacking || (unrefreshed && pending !== undefined) ? reread() : undefined;
664 yield* options.onAnswer?.(target, next, registry) ?? Effect.void;
300 - const mounted = (registry.getNodes().get(atom)?.listeners.size ?? 0) > 0;
665 + const mounted = [atom, reader].some(
666 + (shownBy) => (registry.getNodes().get(shownBy)?.listeners.size ?? 0) > 0,
667 + );
668 if (!freshRead && (pending !== undefined || lacking || (unrefreshed && mounted)))
669 registry.refresh(atom);
670 registry.update(
@@ -314,7 +681,7 @@ function actionPatchedQuery<Input, A, E>(
681 },
682 ),
683 });
317 - return atom;
684 + return reader;
685 };
686 }
687
@@ -381,6 +748,12 @@ export function createLinkedPullRequestSummaryAtomFamily<R, E>(
748 number: value.number,
749 ...(value.observedAt === undefined ? {} : { observedAt: value.observedAt }),
750 },
751 + edit: (_input, value, edits) =>
752 + edits.reduce(
753 + (current, edit) =>
754 + withEdit(current, edit, ["state", "isDraft", "autoMergeEnabled", "title"]),
755 + value,
756 + ),
757 },
758 );
759 }
@@ -395,6 +768,7 @@ export interface PullRequestAnswerHandlers {
768 readonly reviewGuide?: QueryAnswerHandler<PullRequestRef, PullRequestReviewGuideResult>;
769 /** Once per action reply, after the loaded readers show it; unscoped references only. */
770 readonly actionReply?: QueryAnswerHandler<PullRequestRef, PullRequestSummary>;
771 + readonly acceptedEdit?: QueryAnswerHandler<PullRequestRef, PullRequestPendingEdit>;
772 }
773
774 export function createPullRequestStackAtomFamily<R, E>(
@@ -536,6 +910,15 @@ export function createPullRequestEnvironmentAtoms<R, E>(
910 const { autoMergeMethod: _disarmed, ...withoutAutoMerge } = patched;
911 return withoutAutoMerge;
912 },
913 + edit: (_input, value, edits) =>
914 + edits.reduce(
915 + (current, edit) =>
916 + withLabelEdit(
917 + withEdit(current, edit, ["state", "isDraft", "autoMergeEnabled", "title", "body"]),
918 + edit,
919 + ),
920 + value,
921 + ),
922 },
923 ),
924 );
@@ -598,6 +981,11 @@ export function createPullRequestEnvironmentAtoms<R, E>(
981 "observedAt",
982 ]),
983 },
984 + edit: (_input, value, edits) =>
985 + edits.reduce(
986 + (current, edit) => withEdit(current, edit, ["state", "isDraft", "title"]),
987 + value,
988 + ),
989 },
990 ),
991 );
@@ -605,7 +993,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(
993 // Hover cards read their own atoms, so a pending or failed hover read never decides where a
994 // click on the same link goes.
995 const previewCard = previewQuery("environment-data:pull-requests:preview-card");
608 - const labelCandidates = writableQueryFamily(
996 + const labelCandidateQueries = writableQueryFamily(
997 createEnvironmentRpcQueryAtomFamily(runtime, {
998 label: "environment-data:pull-requests:label-candidates",
999 tag: WS_METHODS.pullRequestsLabelCandidates,
@@ -613,6 +1001,37 @@ export function createPullRequestEnvironmentAtoms<R, E>(
1001 staleTimeMs: 60_000,
1002 }),
1003 );
1004 + const labelCandidates = normalizePullRequestQuery((target) =>
1005 + editedQuery(labelCandidateQueries(target), {
1006 + environmentId: target.environmentId,
1007 + concerns: (reference) => samePullRequest(target.input, reference),
1008 + edit: (value, edits) => edits.reduce(withLabelCandidateEdit, value),
1009 + }),
1010 + );
1011 + const labelEdit = (
1012 + registry: AtomRegistry.AtomRegistry,
1013 + target: {
1014 + readonly environmentId: EnvironmentId;
1015 + readonly input: PullRequestRef & {
1016 + readonly labels: ReadonlyArray<string>;
1017 + readonly applied: boolean;
1018 + };
1019 + },
1020 + ): PullRequestPendingEdit => {
1021 + const candidates = Option.getOrUndefined(
1022 + loadedValue<PullRequestLabelCandidateList>(registry, labelCandidates(target)),
1023 + )?.candidates;
1024 + return {
1025 + reference: pullRequestReference(target.input),
1026 + labels: {
1027 + applied: target.input.applied,
1028 + labels: target.input.labels.map((name) => ({
1029 + name,
1030 + color: candidates?.find((candidate) => candidate.name === name)?.color ?? null,
1031 + })),
1032 + },
1033 + };
1034 + };
1035 const reviewGuide = writableQueryFamily(
1036 createEnvironmentRpcQueryAtomFamily(runtime, {
1037 label: "environment-data:pull-requests:review-guide",
@@ -720,6 +1139,52 @@ export function createPullRequestEnvironmentAtoms<R, E>(
1139 );
1140 }
1141 });
1142 + const checksLabel = "environment-data:pull-requests:checks";
1143 + const checksPersistence = persistQuery(Schema.NullOr(PullRequestChecks));
1144 + // Panels take the state from the newest of detail and checks, so checks show writes too.
1145 + const checks = normalizePullRequestQuery(
1146 + actionPatchedQuery(
1147 + createEnvironmentRpcQueryAtomFamily(runtime, {
1148 + label: checksLabel,
1149 + persistence: checksPersistence,
1150 + tag: WS_METHODS.pullRequestsChecks,
1151 + execute: (input) => routedRequest(WS_METHODS.pullRequestsChecks, input),
1152 + staleTimeMs: 45_000,
1153 + refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
1154 + ...(onAnswer.checks === undefined ? {} : { onAnswer: onAnswer.checks }),
1155 + }),
1156 + {
1157 + label: checksLabel,
1158 + persistence: checksPersistence,
1159 + onAnswer: onAnswer.checks,
1160 + concerns: samePullRequest,
1161 + patch: (_input, value, _reference, reply) =>
1162 + value === null || value.state === reply.state || isStalePullRequestReply(value, reply)
1163 + ? value
1164 + : { ...value, state: reply.state },
1165 + edit: (_input, value, edits) => {
1166 + const state = edits.findLast((edit) => edit.state !== undefined)?.state;
1167 + return value === null || state === undefined || value.state === state
1168 + ? value
1169 + : { ...value, state };
1170 + },
1171 + },
1172 + ),
1173 + );
1174 + const acceptEdit = (
1175 + registry: AtomRegistry.AtomRegistry,
1176 + environmentId: EnvironmentId,
1177 + edit: PullRequestPendingEdit | null,
1178 + readsAfterWrite = false,
1179 + ) =>
1180 + Effect.sync(() => settleEdit(registry, environmentId, edit, readsAfterWrite)).pipe(
1181 + Effect.andThen(() =>
1182 + edit === null
1183 + ? Effect.void
1184 + : (onAnswer.acceptedEdit?.({ environmentId, input: edit.reference }, edit, registry) ??
1185 + Effect.void),
1186 + ),
1187 + );
1188 const listLabel = "environment-data:pull-requests:list";
1189 const listPersistence = persistQuery(PullRequestListResult);
1190
@@ -764,6 +1229,10 @@ export function createPullRequestEnvironmentAtoms<R, E>(
1229 input.host.toLowerCase() === reference.host.toLowerCase()),
1230 refreshedByServer: (input) => input.cursors === undefined,
1231 patch: patchListWithReply,
1232 + edit: (input, value, edits, pending) => {
1233 + const entries = editPullRequestListEntries(input, value.entries, edits, pending);
1234 + return entries === value.entries ? value : { ...value, entries };
1235 + },
1236 },
1237 ),
1238 /**
@@ -788,17 +1257,7 @@ export function createPullRequestEnvironmentAtoms<R, E>(
1257 detailReadVersion,
1258 preview,
1259 previewCard,
791 - checks: normalizePullRequestQuery(
792 - createEnvironmentRpcQueryAtomFamily(runtime, {
793 - label: "environment-data:pull-requests:checks",
794 - persistence: persistQuery(Schema.NullOr(PullRequestChecks)),
795 - tag: WS_METHODS.pullRequestsChecks,
796 - execute: (input) => routedRequest(WS_METHODS.pullRequestsChecks, input),
797 - staleTimeMs: 45_000,
798 - refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
799 - ...(onAnswer.checks === undefined ? {} : { onAnswer: onAnswer.checks }),
800 - }),
801 - ),
1260 + checks,
1261 activity,
1262 threadComments: createEnvironmentRpcCommand(runtime, {
1263 label: "environment-data:pull-requests:thread-comments",
@@ -869,41 +1328,47 @@ export function createPullRequestEnvironmentAtoms<R, E>(
1328 JSON.stringify([environmentId, input.projectId, input.repository, input.number]),
1329 },
1330 }),
872 - runAction: createEnvironmentRpcCommand(runtime, {
873 - tag: WS_METHODS.pullRequestsRunAction,
874 - label: "environment-data:pull-requests:run-action",
875 - // Preparation belongs to the write's lane. Refreshable queries would restart it after
876 - // every preceding action, and preparing outside the lane could reorder the clicks.
877 - execute: runAction,
878 - onStart: (_target, registry) => readsInFlight(registry),
879 - // Loaded readers show the reply, or re-read when the host's reply lacked the pull request.
880 - onSuccess: ({ environmentId, input }, registry, reply, readsBeforeSend) => {
881 - const { projectId, host, repository, number, expectedAccountId } = input;
882 - return applyActionReply(
883 - registry,
884 - environmentId,
885 - {
886 - projectId,
887 - ...(host === undefined ? {} : { host }),
888 - repository,
889 - number,
890 - ...(expectedAccountId === undefined ? {} : { expectedAccountId }),
891 - },
892 - reply,
893 - readsBeforeSend ?? new Set(),
894 - );
895 - },
896 - scheduler: commandScheduler,
897 - concurrency: serialPerEnvironment,
898 - }),
899 - update: createEnvironmentRpcCommand(runtime, {
900 - label: "environment-data:pull-requests:update",
901 - tag: WS_METHODS.pullRequestsUpdate,
902 - execute: (input) => routedRequest(WS_METHODS.pullRequestsUpdate, input),
903 - onSuccess: (target, registry) => Effect.sync(() => registry.refresh(preview(target))),
904 - scheduler: commandScheduler,
905 - concurrency: serialPerEnvironment,
906 - }),
1331 + runAction: showWhileInFlight(
1332 + createEnvironmentRpcCommand(runtime, {
1333 + tag: WS_METHODS.pullRequestsRunAction,
1334 + label: "environment-data:pull-requests:run-action",
1335 + // Preparation belongs to the write's lane. Refreshable queries would restart it after
1336 + // every preceding action, and preparing outside the lane could reorder the clicks.
1337 + execute: runAction,
1338 + onStart: (_target, registry) => readsInFlight(registry),
1339 + // Loaded readers show the reply, or re-read when the host's reply lacked the pull request.
1340 + onSuccess: ({ environmentId, input }, registry, reply, readsBeforeSend) =>
1341 + applyActionReply(
1342 + registry,
1343 + environmentId,
1344 + pullRequestReference(input),
1345 + reply,
1346 + readsBeforeSend ?? new Set(),
1347 + ).pipe(
1348 + // The re-read a bare reply starts would otherwise show the old state until it answers.
1349 + Effect.andThen(
1350 + reply === undefined
1351 + ? acceptEdit(registry, environmentId, actionEdit(input), true)
1352 + : Effect.void,
1353 + ),
1354 + ),
1355 + scheduler: commandScheduler,
1356 + concurrency: serialPerEnvironment,
1357 + }),
1358 + (_registry, { input }) => actionEdit(input),
1359 + ),
1360 + update: showWhileInFlight(
1361 + createEnvironmentRpcCommand(runtime, {
1362 + label: "environment-data:pull-requests:update",
1363 + tag: WS_METHODS.pullRequestsUpdate,
1364 + execute: (input) => routedRequest(WS_METHODS.pullRequestsUpdate, input),
1365 + onSuccess: (target, registry) =>
1366 + acceptEdit(registry, target.environmentId, updateEdit(target.input)),
1367 + scheduler: commandScheduler,
1368 + concurrency: serialPerEnvironment,
1369 + }),
1370 + (_registry, { input }) => updateEdit(input),
1371 + ),
1372 comment: createEnvironmentRpcCommand(runtime, {
1373 label: "environment-data:pull-requests:comment",
1374 tag: WS_METHODS.pullRequestsComment,
@@ -1039,44 +1504,18 @@ export function createPullRequestEnvironmentAtoms<R, E>(
1504 }),
1505 }),
1506 labelCandidates,
1042 - setLabels: createEnvironmentRpcCommand(runtime, {
1043 - label: "environment-data:pull-requests:set-labels",
1044 - tag: WS_METHODS.pullRequestsSetLabels,
1045 - execute: (input) => routedRequest(WS_METHODS.pullRequestsSetLabels, input),
1046 - scheduler: commandScheduler,
1047 - concurrency: serialPerEnvironment,
1048 - onSuccess: (target, registry) =>
1049 - Effect.sync(() => {
1050 - const { labels, applied } = target.input;
1051 - const candidatesAtom = labelCandidates(target);
1052 - const candidates = AsyncResult.getOrElse(registry.get(candidatesAtom), () => null);
1053 - const names = new Set(labels);
1054 - updateCached(registry, candidatesAtom, (value) => ({
1055 - ...value,
1056 - candidates: value.candidates.map((candidate) =>
1057 - names.has(candidate.name) ? { ...candidate, isApplied: applied } : candidate,
1058 - ),
1059 - }));
1060 - for (const atom of loadedDetails(registry, target)) {
1061 - updateCached(registry, atom, (value) => ({
1062 - ...value,
1063 - labels: applied
1064 - ? [
1065 - ...value.labels,
1066 - ...labels
1067 - .filter((name) => !value.labels.some((label) => label.name === name))
1068 - .map((name) => ({
1069 - name,
1070 - color:
1071 - candidates?.candidates.find((candidate) => candidate.name === name)
1072 - ?.color ?? null,
1073 - })),
1074 - ]
1075 - : value.labels.filter((label) => !names.has(label.name)),
1076 - }));
1077 - }
1078 - }),
1079 - }),
1507 + setLabels: showWhileInFlight(
1508 + createEnvironmentRpcCommand(runtime, {
1509 + label: "environment-data:pull-requests:set-labels",
1510 + tag: WS_METHODS.pullRequestsSetLabels,
1511 + execute: (input) => routedRequest(WS_METHODS.pullRequestsSetLabels, input),
1512 + scheduler: commandScheduler,
1513 + concurrency: serialPerEnvironment,
1514 + onSuccess: (target, registry) =>
1515 + acceptEdit(registry, target.environmentId, labelEdit(registry, target)),
1516 + }),
1517 + labelEdit,
1518 + ),
1519 setThreadResolution: createEnvironmentRpcCommand(runtime, {
1520 label: "environment-data:pull-requests:set-thread-resolution",
1521 tag: WS_METHODS.pullRequestsSetThreadResolution,