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

main
ts 1,581 lines 62.4 KB
Raw
1 import { msg } from "gt-i18n";
2 import { MarkedText, translatableMessage } from "../errors/translatable.ts";
3 import {
4 WS_METHODS,
5 PullRequestActivity,
6 PullRequestDetail as PullRequestDetailSchema,
7 PullRequestPreview,
8 PullRequestReviewGuideResult,
9 PullRequestStack,
10 PullRequestListResult,
11 PullRequestChecks,
12 PullRequestDiffResult,
13 PullRequestChangeBreakdown,
14 PullRequestFilesViewedResult,
15 PullRequestLinkedThreadsResult,
16 type EnvironmentId,
17 type PullRequestActor,
18 type PullRequestActionInput,
19 type PullRequestListInput,
20 type PullRequestListStatsInput,
21 type PullRequestListStatsResult,
22 type PullRequestUpdateInput,
23 type PullRequestDetail,
24 type PullRequestDiffInput,
25 type PullRequestListEntry,
26 type PullRequestRef,
27 type PullRequestMergeMethod,
28 type PullRequestLabel,
29 type PullRequestLabelCandidateList,
30 type PullRequestState,
31 PullRequestOperationError,
32 PullRequestSummary,
33 type VcsStatusResult,
34 } from "@t3tools/contracts";
35 import * as Effect from "effect/Effect";
36 import * as Schema from "effect/Schema";
37 import { persistPullRequestStats } from "./pullRequestStatsPersistence.ts";
38 import { persistQuery, type QueryPersistence } from "./queryPersistence.ts";
39 import * as Option from "effect/Option";
40 import * as SubscriptionRef from "effect/SubscriptionRef";
41 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
42
43 import {
44 type AtomCommand,
45 createAtomCommandScheduler,
46 createEnvironmentRpcCommand,
47 createEnvironmentRpcQueryAtomFamily,
48 createEnvironmentRpcSubscriptionAtomFamily,
49 createEnvironmentQueryAtomFamily,
50 queryPersistenceKey,
51 type QueryAnswerHandler,
52 } from "./runtime.ts";
53 import { createPullRequestRouter } from "./pullRequestRouting.ts";
54 import * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts";
55 import type { EnvironmentRegistry } from "../connection/registry.ts";
56 import * as EnvironmentSupervisor from "../connection/supervisor.ts";
57 import { isStalePullRequestReply } from "../pullRequestReply.ts";
58 import { parsePullRequestQuery } from "../pullRequestQuery.ts";
59 import { reuseUnchanged } from "./serverConfigProjection.ts";
60 import { createEnvironmentSessionAtoms } from "./session.ts";
61
62 export {
63 type PullRequestDiffLoadError,
64 PullRequestDiffCredentialRejectedError,
65 } from "./pullRequestDiffHttp.ts";
66 export * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts";
67
68 /** @public Required to name the error in consumers' inferred pull request results. */
69 export class EnvironmentHttpConnectionNotReadyError extends Schema.TaggedError<EnvironmentHttpConnectionNotReadyError>()(
70 "EnvironmentHttpConnectionNotReadyError",
71 { message: Schema.String, i18nMessage: Schema.optionalKey(MarkedText) },
72 ) {}
73
74 const LINKED_PULL_REQUEST_IDLE_TTL_MS = 5_000;
75
76 function normalizePullRequestQuery<A>(
77 query: (target: { readonly environmentId: EnvironmentId; readonly input: PullRequestRef }) => A,
78 ) {
79 return ({
80 environmentId,
81 input: { projectId, host, repository, number, allowStale, expectedAccountId },
82 }: Parameters<typeof query>[0]) =>
83 query({
84 environmentId,
85 input: {
86 projectId,
87 ...(host === undefined ? {} : { host }),
88 repository,
89 number,
90 ...(allowStale === undefined ? {} : { allowStale }),
91 ...(expectedAccountId === undefined ? {} : { expectedAccountId }),
92 },
93 });
94 }
95
96 function writableQuery<A, E>(
97 source: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
98 idleTtlMs = 5 * 60_000,
99 ) {
100 return Atom.writable(
101 (get) => {
102 const result = get(source);
103 if (result._tag === "Success" && !result.waiting) return result;
104 const previous = get.self<AsyncResult.AsyncResult<A, E>>();
105 const value = Option.flatMap(previous, AsyncResult.value);
106 if (Option.isNone(value)) return result;
107 return result._tag === "Failure"
108 ? AsyncResult.failureWithPrevious(result.cause, { previous, waiting: result.waiting })
109 : AsyncResult.success<A, E>(value.value, result);
110 },
111 (context, value: AsyncResult.AsyncResult<A, E>) => context.setSelf(value),
112 (refresh) => refresh(source),
113 ).pipe(Atom.setIdleTTL(idleTtlMs));
114 }
115
116 function writableQueryFamily<A, E>(
117 family: (target: {
118 readonly environmentId: EnvironmentId;
119 readonly input: PullRequestRef;
120 }) => Atom.Atom<AsyncResult.AsyncResult<A, E>>,
121 ) {
122 const writable = Atom.family((source: Atom.Atom<AsyncResult.AsyncResult<A, E>>) =>
123 writableQuery(source),
124 );
125 return normalizePullRequestQuery((target) => writable(family(target)));
126 }
127
128 /** Restart pre-mutation reads before patching so they cannot restore stale values. */
129 function updateCached<A, E>(
130 registry: AtomRegistry.AtomRegistry,
131 shown: Atom.Writable<AsyncResult.AsyncResult<A, E>>,
132 update: (value: A) => A,
133 refresh = false,
134 ) {
135 const atom = (uneditedReaders.get(shown) ?? shown) as typeof shown;
136 if (refresh || registry.get(atom).waiting) registry.refresh(atom);
137 registry.update(atom, AsyncResult.map(update));
138 }
139
140 interface ActionReplyPatch {
141 /** The read this reader is waiting on, if any. */
142 readonly pendingRead: (registry: AtomRegistry.AtomRegistry) => object | undefined;
143 readonly apply: (
144 registry: AtomRegistry.AtomRegistry,
145 environmentId: EnvironmentId,
146 reference: PullRequestRef,
147 reply: PullRequestSummary | undefined,
148 readsBeforeSend: ReadonlySet<object>,
149 ) => Effect.Effect<void>;
150 }
151
152 // Module-wide so readers built by separate factories, such as linked summaries, are patched too.
153 const actionReplyPatches = new WeakMap<object, ActionReplyPatch>();
154
155 /** What a write in flight will change, shown by every reader until the host answers. */
156 export interface PullRequestPendingEdit {
157 readonly reference: PullRequestRef;
158 readonly state?: PullRequestState;
159 readonly isDraft?: boolean;
160 readonly autoMergeEnabled?: boolean;
161 readonly title?: string;
162 readonly body?: string;
163 readonly labels?: {
164 readonly applied: boolean;
165 readonly labels: ReadonlyArray<PullRequestLabel>;
166 };
167 }
168
169 type EditedField = "state" | "isDraft" | "autoMergeEnabled" | "title" | "body";
170
171 interface EditableReader {
172 readonly environmentId: EnvironmentId;
173 readonly concerns: (reference: PullRequestRef) => boolean;
174 readonly edit: (
175 value: never,
176 edits: ReadonlyArray<PullRequestPendingEdit>,
177 pending?: ReadonlyArray<PullRequestPendingEdit>,
178 ) => unknown;
179 }
180
181 // Module-wide like the reply patches, so separately built readers see the same writes.
182 export const pullRequestPendingEditsAtom = Atom.family((_environmentId: EnvironmentId | null) =>
183 Atom.make<ReadonlyArray<PullRequestPendingEdit>>([]).pipe(Atom.keepAlive),
184 );
185 const editableReaders = new WeakMap<object, EditableReader>();
186 const editedReaders = new WeakMap<object, object>();
187 const uneditedReaders = new WeakMap<object, object>();
188
189 const pendingEditsByPullRequest = Atom.family((key: string) => {
190 const [environmentId, reference] = JSON.parse(key) as [EnvironmentId, PullRequestRef];
191 return Atom.make((get) =>
192 get(pullRequestPendingEditsAtom(environmentId)).filter((edit) =>
193 samePullRequest(reference, edit.reference),
194 ),
195 ).pipe(
196 Atom.withEquality(
197 (previous: ReadonlyArray<PullRequestPendingEdit>, next) =>
198 previous.length === next.length && previous.every((edit, index) => edit === next[index]),
199 ),
200 );
201 });
202 const noPendingEdits = Atom.make<ReadonlyArray<PullRequestPendingEdit>>([]);
203
204 export function pullRequestPendingEditsFor(
205 environmentId: EnvironmentId | null,
206 reference: PullRequestRef | null,
207 ): Atom.Atom<ReadonlyArray<PullRequestPendingEdit>> {
208 return environmentId === null || reference === null
209 ? noPendingEdits
210 : pendingEditsByPullRequest(JSON.stringify([environmentId, pullRequestReference(reference)]));
211 }
212
213 export function pullRequestHostAnswer<A>(reader: Atom.Atom<A>): Atom.Atom<A> {
214 return (uneditedReaders.get(reader) ?? reader) as Atom.Atom<A>;
215 }
216
217 function loadedValue<A>(registry: AtomRegistry.AtomRegistry, atom: Atom.Atom<unknown>) {
218 return Option.flatMap(registry.getNodes().get(atom)?.valueOption() ?? Option.none(), (result) =>
219 AsyncResult.value(result as AsyncResult.AsyncResult<A, unknown>),
220 );
221 }
222
223 function withEdit<T extends object>(
224 value: T,
225 edit: PullRequestPendingEdit,
226 fields: ReadonlyArray<EditedField>,
227 ): T {
228 const held = value as Record<string, unknown>;
229 const changed = fields.filter(
230 (field) => edit[field] !== undefined && held[field] !== edit[field],
231 );
232 let next =
233 changed.length === 0
234 ? held
235 : { ...held, ...Object.fromEntries(changed.map((field) => [field, edit[field]])) };
236 if (edit.autoMergeEnabled === false && next.autoMergeMethod !== undefined) {
237 const { autoMergeMethod: _disarmed, ...withoutAutoMerge } = next;
238 next = withoutAutoMerge;
239 }
240 return next as T;
241 }
242
243 function withLabelEdit<T extends { readonly labels: ReadonlyArray<PullRequestLabel> }>(
244 value: T,
245 edit: PullRequestPendingEdit,
246 ): T {
247 if (edit.labels === undefined) return value;
248 const { applied, labels: changed } = edit.labels;
249 const names = new Set(changed.map((label) => label.name));
250 const labels = applied
251 ? [
252 ...value.labels,
253 ...changed.filter((label) => !value.labels.some((held) => held.name === label.name)),
254 ]
255 : value.labels.filter((label) => !names.has(label.name));
256 return labels.length === value.labels.length ? value : { ...value, labels };
257 }
258
259 function withLabelCandidateEdit(
260 value: PullRequestLabelCandidateList,
261 edit: PullRequestPendingEdit,
262 ): PullRequestLabelCandidateList {
263 if (edit.labels === undefined) return value;
264 const { applied, labels } = edit.labels;
265 let changed = false;
266 const candidates = value.candidates.map((candidate) => {
267 if (candidate.isApplied === applied || !labels.some((label) => label.name === candidate.name))
268 return candidate;
269 changed = true;
270 return { ...candidate, isApplied: applied };
271 });
272 return changed ? { ...value, candidates } : value;
273 }
274
275 /**
276 * The reader with every write in flight for its pull request applied. Writes go to the reader
277 * underneath, so a refused edit never stays behind in what the host said.
278 */
279 function editedQuery<A, E>(
280 inner: Atom.Writable<AsyncResult.AsyncResult<A, E>>,
281 reader: Omit<EditableReader, "edit"> & {
282 readonly edit: (
283 value: A,
284 edits: ReadonlyArray<PullRequestPendingEdit>,
285 pending?: ReadonlyArray<PullRequestPendingEdit>,
286 ) => A;
287 },
288 idleTtlMs = 5 * 60_000,
289 ): Atom.Writable<AsyncResult.AsyncResult<A, E>> {
290 const existing = editedReaders.get(inner);
291 if (existing !== undefined) return existing as Atom.Writable<AsyncResult.AsyncResult<A, E>>;
292 const shown = Atom.writable(
293 (get) => {
294 const result = get(inner);
295 const edits = get(pullRequestPendingEditsAtom(reader.environmentId)).filter((edit) =>
296 reader.concerns(edit.reference),
297 );
298 const value = AsyncResult.value(result);
299 if (Option.isNone(value)) return result;
300 const next = reader.edit(value.value, edits);
301 return next === value.value ? result : AsyncResult.map(result, () => next);
302 },
303 (context, value: AsyncResult.AsyncResult<A, E>) => context.set(inner, value),
304 (refresh) => refresh(inner),
305 ).pipe(Atom.setIdleTTL(idleTtlMs));
306 editableReaders.set(inner, reader as EditableReader);
307 editedReaders.set(inner, shown);
308 uneditedReaders.set(shown, inner);
309 return shown;
310 }
311
312 /** Shows the command's edit from the click until it settles, queued behind others or not. */
313 function showWhileInFlight<Target extends { readonly environmentId: EnvironmentId }, A, E, C>(
314 command: C & AtomCommand<Target, A, E>,
315 editOf: (registry: AtomRegistry.AtomRegistry, target: Target) => PullRequestPendingEdit | null,
316 ): C {
317 return {
318 ...command,
319 run: (registry, target) =>
320 Effect.suspend(() => {
321 const edit = editOf(registry, target);
322 if (edit === null) return command.run(registry, target);
323 const edits = pullRequestPendingEditsAtom(target.environmentId);
324 return Effect.acquireUseRelease(
325 Effect.sync(() => registry.update(edits, (current) => [...current, edit])),
326 () => command.run(registry, target),
327 () =>
328 Effect.sync(() =>
329 registry.update(edits, (current) => current.filter((entry) => entry !== edit)),
330 ),
331 );
332 }),
333 } satisfies AtomCommand<Target, A, E>;
334 }
335
336 /** Keeps an accepted edit in loaded readers once it stops being in flight. */
337 function settleEdit(
338 registry: AtomRegistry.AtomRegistry,
339 environmentId: EnvironmentId,
340 edit: PullRequestPendingEdit | null,
341 readsAfterWrite = false,
342 ) {
343 if (edit === null) return;
344 const pending = registry.get(pullRequestPendingEditsAtom(environmentId));
345 for (const atom of registry.getNodes().keys()) {
346 const reader = typeof atom === "string" ? undefined : editableReaders.get(atom);
347 if (reader?.environmentId !== environmentId || !reader.concerns(edit.reference)) continue;
348 const shown = loadedValue<never>(registry, atom as Atom.Atom<unknown>);
349 const writable = atom as Atom.Writable<AsyncResult.AsyncResult<never, unknown>>;
350 const unchanged =
351 Option.isSome(shown) && reader.edit(shown.value, [edit], pending) === shown.value;
352 if (unchanged) continue;
353 // A read still waiting may predate the write, unless the caller started it after the commit.
354 if (!readsAfterWrite && registry.get(writable).waiting) registry.refresh(writable);
355 if (Option.isNone(shown)) continue;
356 registry.update(
357 writable,
358 AsyncResult.map((value) => reader.edit(value, [edit], pending) as never),
359 );
360 }
361 }
362
363 function pullRequestReference(input: PullRequestRef): PullRequestRef {
364 const { projectId, host, repository, number, expectedAccountId } = input;
365 return {
366 projectId,
367 ...(host === undefined ? {} : { host }),
368 repository,
369 number,
370 ...(expectedAccountId === undefined ? {} : { expectedAccountId }),
371 };
372 }
373
374 /** What an action changes, left out where only the host knows, as when a queue takes a merge. */
375 function actionEdit(input: PullRequestActionInput): PullRequestPendingEdit | null {
376 if (input.stackNumber !== undefined) return null;
377 const reference = pullRequestReference(input);
378 switch (input.action) {
379 case "close":
380 return { reference, state: "closed" };
381 case "reopen":
382 return { reference, state: "open" };
383 case "ready":
384 return { reference, isDraft: false };
385 case "draft":
386 return { reference, isDraft: true };
387 case "enable-auto-merge":
388 return { reference, autoMergeEnabled: true };
389 case "disable-auto-merge":
390 return { reference, autoMergeEnabled: false };
391 default:
392 return null;
393 }
394 }
395
396 function updateEdit(input: PullRequestUpdateInput): PullRequestPendingEdit | null {
397 if (input.title === undefined && input.body === undefined) return null;
398 return {
399 reference: pullRequestReference(input),
400 ...(input.title === undefined ? {} : { title: input.title }),
401 ...(input.body === undefined ? {} : { body: input.body }),
402 };
403 }
404
405 function samePullRequest(reader: PullRequestRef, acted: PullRequestRef) {
406 return (
407 reader.projectId === acted.projectId &&
408 // A missing host is not a wildcard: one project can reach the same repository on two hosts.
409 reader.host?.toLowerCase() === acted.host?.toLowerCase() &&
410 reader.repository.toLowerCase() === acted.repository.toLowerCase() &&
411 reader.number === acted.number &&
412 reader.expectedAccountId === acted.expectedAccountId
413 );
414 }
415
416 export function applyPullRequestSummaryEdits(
417 reference: PullRequestRef | null,
418 summary: PullRequestSummary | null,
419 edits: ReadonlyArray<PullRequestPendingEdit>,
420 ): PullRequestSummary | null {
421 if (reference === null || summary === null) return summary;
422 return edits.reduce(
423 (current, edit) =>
424 samePullRequest(reference, edit.reference)
425 ? withEdit(current, edit, ["state", "isDraft", "autoMergeEnabled", "title"])
426 : current,
427 summary,
428 );
429 }
430
431 function pickDefined<T extends object, K extends keyof T>(
432 source: T,
433 keys: ReadonlyArray<K>,
434 ): { [P in K]?: Exclude<T[P], undefined> } {
435 const picked: { [P in K]?: T[P] } = {};
436 for (const key of keys) if (source[key] !== undefined) picked[key] = source[key];
437 return picked as { [P in K]?: Exclude<T[P], undefined> };
438 }
439
440 function listAccepts(input: PullRequestListInput, state: string, isDraft: boolean | undefined) {
441 const draft = parsePullRequestQuery(input.query ?? "").filters.draft ?? input.filters?.draft;
442 return (
443 (input.state === "all" || input.state === state) &&
444 (draft !== "only" || isDraft !== false) &&
445 (draft !== "hide" || isDraft !== true)
446 );
447 }
448
449 function listKeeps(
450 input: PullRequestListInput,
451 entry: PullRequestListEntry,
452 pending: ReadonlyArray<PullRequestPendingEdit>,
453 ) {
454 if (listAccepts(input, entry.state, entry.isDraft)) return true;
455 const edited = pending.reduce(
456 (current, edit) =>
457 samePullRequest(entry, edit.reference)
458 ? withEdit(current, edit, ["state", "isDraft"])
459 : current,
460 entry,
461 );
462 return edited !== entry && listAccepts(input, edited.state, edited.isDraft);
463 }
464
465 /**
466 * Listing rows with an action's reply applied, the same array when it changes none, and `refresh`
467 * when the reply adds the pull request to a listing, which only a read can place.
468 */
469 export function patchPullRequestListEntries<Entry extends PullRequestListEntry>(
470 input: PullRequestListInput,
471 entries: ReadonlyArray<Entry>,
472 reference: PullRequestRef,
473 reply: PullRequestSummary,
474 pending: ReadonlyArray<PullRequestPendingEdit> = [],
475 ): ReadonlyArray<Entry> | "refresh" {
476 let found = false;
477 let changed = false;
478 const patched = entries.flatMap((entry): Entry[] => {
479 if (!samePullRequest(entry, reference)) return [entry];
480 found = true;
481 if (isStalePullRequestReply(entry, reply)) return [entry];
482 changed = true;
483 const next = {
484 ...entry,
485 ...pickDefined(reply, [
486 "title",
487 "url",
488 "author",
489 "headBranch",
490 "baseBranch",
491 "state",
492 "isDraft",
493 "mergeability",
494 "updatedAt",
495 ]),
496 };
497 return listKeeps(input, next, pending) ? [next] : [];
498 });
499 if (!found) {
500 return input.cursors === undefined && listAccepts(input, reply.state, reply.isDraft)
501 ? "refresh"
502 : entries;
503 }
504 return changed
505 ? patched.sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt))
506 : entries;
507 }
508
509 function editPullRequestListEntries<Entry extends PullRequestListEntry>(
510 input: PullRequestListInput,
511 entries: ReadonlyArray<Entry>,
512 edits: ReadonlyArray<PullRequestPendingEdit>,
513 pending = edits,
514 ): ReadonlyArray<Entry> {
515 let changed = false;
516 const edited = entries.flatMap((entry): Entry[] => {
517 const next = edits.reduce(
518 (current, edit) =>
519 samePullRequest(entry, edit.reference)
520 ? withLabelEdit(withEdit(current, edit, ["state", "isDraft", "title"]), edit)
521 : current,
522 entry,
523 );
524 if (next === entry && listAccepts(input, next.state, next.isDraft)) return [entry];
525 changed = true;
526 return listKeeps(input, next, pending) ? [next] : [];
527 });
528 return changed ? edited : entries;
529 }
530
531 export function editHeldPullRequestListEntries<Entry extends PullRequestListEntry>(
532 input: PullRequestListInput,
533 entries: ReadonlyArray<Entry>,
534 editsOf: (entry: Entry) => ReadonlyArray<PullRequestPendingEdit>,
535 pending?: ReadonlyArray<PullRequestPendingEdit>,
536 ): ReadonlyArray<Entry> {
537 let changed = false;
538 const shown = entries.flatMap((entry) => {
539 const edits = editsOf(entry);
540 const next = editPullRequestListEntries(input, [entry], edits, pending);
541 if (next[0] !== entry) changed = true;
542 return next;
543 });
544 return changed ? shown : entries;
545 }
546
547 export function heldPullRequestListEntriesAtom<Entry extends PullRequestListEntry>(
548 environmentId: EnvironmentId,
549 input: PullRequestListInput,
550 entries: ReadonlyArray<Entry>,
551 ) {
552 return actionPatchedQuery(() => Atom.make(AsyncResult.success(entries)), {
553 label: "pull-requests:held-list-entries",
554 concerns: (_input: PullRequestListInput, reference) =>
555 entries.some((entry) => samePullRequest(entry, reference)),
556 edit: editPullRequestListEntries<Entry>,
557 patch: patchPullRequestListEntries<Entry>,
558 })({ environmentId, input });
559 }
560
561 function patchListWithReply(
562 input: PullRequestListInput,
563 value: PullRequestListResult,
564 reference: PullRequestRef,
565 reply: PullRequestSummary,
566 pending: ReadonlyArray<PullRequestPendingEdit>,
567 ): PullRequestListResult | "refresh" {
568 const entries = patchPullRequestListEntries(input, value.entries, reference, reply, pending);
569 if (entries === "refresh") return entries;
570 return entries === value.entries ? value : { ...value, entries };
571 }
572
573 /**
574 * The query atom for one target, writable so an action's reply can replace what it shows. The
575 * patch is saved and announced the way an answer would be, so cold starts and snapshots see it.
576 */
577 function actionPatchedQuery<Input, A, E>(
578 source: (target: {
579 readonly environmentId: EnvironmentId;
580 readonly input: Input;
581 }) => Atom.Atom<AsyncResult.AsyncResult<A, E>>,
582 options: {
583 readonly label: string;
584 readonly persistence?: QueryPersistence<A> | undefined;
585 readonly onAnswer?: QueryAnswerHandler<Input, A> | undefined;
586 readonly idleTtlMs?: number | undefined;
587 readonly concerns: (input: Input, reference: PullRequestRef) => boolean;
588 readonly patch: (
589 input: Input,
590 value: A,
591 reference: PullRequestRef,
592 reply: PullRequestSummary,
593 pending: ReadonlyArray<PullRequestPendingEdit>,
594 ) => A | "refresh";
595 /** Fields the reply lacks also changed, so the patched value shows while a read fetches them. */
596 readonly rereads?: (value: A, reply: PullRequestSummary) => boolean;
597 /** Re-read when the host's reply did not carry the pull request. */
598 readonly rereadWithoutReply?: boolean;
599 /** False for reads the refresh stream does not restart; defaults to true. */
600 readonly refreshedByServer?: (input: Input) => boolean;
601 /** Shows a write in flight; absent where the reader holds nothing such a write changes. */
602 readonly edit?: (
603 input: Input,
604 value: A,
605 edits: ReadonlyArray<PullRequestPendingEdit>,
606 pending?: ReadonlyArray<PullRequestPendingEdit>,
607 ) => A;
608 },
609 ) {
610 const writable = Atom.family((atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>) =>
611 writableQuery(atom, options.idleTtlMs),
612 );
613 return (target: { readonly environmentId: EnvironmentId; readonly input: Input }) => {
614 const query = source(target);
615 const atom = writable(query);
616 const edit = options.edit;
617 const reader =
618 edit === undefined
619 ? atom
620 : editedQuery(
621 atom,
622 {
623 environmentId: target.environmentId,
624 concerns: (reference) => options.concerns(target.input, reference),
625 edit: (value, edits, pending) => edit(target.input, value, edits, pending),
626 },
627 options.idleTtlMs,
628 );
629 if (actionReplyPatches.has(atom)) return reader;
630 const pendingRead = (registry: AtomRegistry.AtomRegistry) => {
631 const result = Option.getOrUndefined(
632 registry.getNodes().get(query)?.valueOption() ?? Option.none(),
633 ) as AsyncResult.AsyncResult<A, E> | undefined;
634 return result?.waiting === true ? result : undefined;
635 };
636 actionReplyPatches.set(atom, {
637 pendingRead,
638 apply: Effect.fnUntraced(
639 function* (registry, environmentId, reference, reply, readsBeforeSend) {
640 if (environmentId !== target.environmentId || !options.concerns(target.input, reference))
641 return;
642 const pending = pendingRead(registry);
643 // A read sent before the action may miss its result, and so may one sent before the host
644 // committed. The server's post-commit refresh restarts that one, but not a read outside
645 // its stream, whose re-read need not even show as waiting, so a mounted one the reply
646 // changes restarts here.
647 const unrefreshed = options.refreshedByServer?.(target.input) === false;
648 const freshRead = pending !== undefined && !unrefreshed && !readsBeforeSend.has(pending);
649 const reread = () => (freshRead ? undefined : registry.refresh(atom));
650 if (reply === undefined) {
651 return options.rereadWithoutReply === true ? reread() : undefined;
652 }
653 const shown = Option.flatMap(
654 registry.getNodes().get(atom)?.valueOption() ?? Option.none(),
655 (current: AsyncResult.AsyncResult<A, E>) => AsyncResult.value(current),
656 );
657 if (Option.isNone(shown)) return reread();
658 const patched = options.patch(
659 target.input,
660 shown.value,
661 reference,
662 reply,
663 registry.get(pullRequestPendingEditsAtom(environmentId)),
664 );
665 if (patched === "refresh") return reread();
666 const lacking = options.rereads?.(shown.value, reply) === true;
667 const next = reuseUnchanged(shown.value, patched);
668 if (next === shown.value)
669 return lacking || (unrefreshed && pending !== undefined) ? reread() : undefined;
670 yield* options.onAnswer?.(target, next, registry) ?? Effect.void;
671 const mounted = [atom, reader].some(
672 (shownBy) => (registry.getNodes().get(shownBy)?.listeners.size ?? 0) > 0,
673 );
674 if (!freshRead && (pending !== undefined || lacking || (unrefreshed && mounted)))
675 registry.refresh(atom);
676 registry.update(
677 atom,
678 AsyncResult.map(() => next),
679 );
680 if (options.persistence !== undefined) {
681 yield* options.persistence.save(
682 environmentId,
683 queryPersistenceKey(options.label, target.input),
684 next,
685 );
686 }
687 },
688 ),
689 });
690 return reader;
691 };
692 }
693
694 function makePullRequestRefreshAtomFamily<R, E>(
695 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
696 ) {
697 return createEnvironmentRpcSubscriptionAtomFamily(runtime, {
698 label: "environment-data:pull-requests:turn-refreshes",
699 tag: WS_METHODS.pullRequestsSubscribeRefreshes,
700 });
701 }
702
703 const refreshFamiliesByRuntime = new WeakMap<
704 object,
705 ReturnType<typeof makePullRequestRefreshAtomFamily>
706 >();
707
708 function createPullRequestRefreshAtomFamily<R, E>(
709 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
710 ): ReturnType<typeof makePullRequestRefreshAtomFamily<R, E>> {
711 const existing = refreshFamiliesByRuntime.get(runtime);
712 if (existing) return existing as ReturnType<typeof makePullRequestRefreshAtomFamily<R, E>>;
713 const refreshes = makePullRequestRefreshAtomFamily(runtime);
714 refreshFamiliesByRuntime.set(runtime, refreshes);
715 return refreshes;
716 }
717
718 export function createLinkedPullRequestSummaryAtomFamily<R, E>(
719 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
720 refreshes = createPullRequestRefreshAtomFamily(runtime),
721 onAnswer?: QueryAnswerHandler<PullRequestRef, PullRequestSummary>,
722 ) {
723 const routedRequest = createPullRequestRouter();
724 const label = "environment-data:pull-requests:linked-summary";
725 const persistence = persistQuery(PullRequestSummary);
726 return actionPatchedQuery(
727 createEnvironmentRpcQueryAtomFamily(runtime, {
728 label,
729 persistence,
730 tag: WS_METHODS.pullRequestsSummary,
731 execute: (input) => routedRequest(WS_METHODS.pullRequestsSummary, input),
732 staleTimeMs: 60_000,
733 refreshIntervalMs: 60_000,
734 idleTtlMs: LINKED_PULL_REQUEST_IDLE_TTL_MS,
735 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
736 isFinal: (summary) => summary.state === "merged",
737 ...(onAnswer === undefined ? {} : { onAnswer }),
738 }),
739 {
740 label,
741 persistence,
742 onAnswer,
743 idleTtlMs: LINKED_PULL_REQUEST_IDLE_TTL_MS,
744 concerns: samePullRequest,
745 // A routed action replies with the destination's project and repository names.
746 patch: (_input, value, _reference, reply) =>
747 isStalePullRequestReply(value, reply)
748 ? value
749 : {
750 ...value,
751 ...reply,
752 projectId: value.projectId,
753 repository: value.repository,
754 number: value.number,
755 ...(value.observedAt === undefined ? {} : { observedAt: value.observedAt }),
756 },
757 edit: (_input, value, edits) =>
758 edits.reduce(
759 (current, edit) =>
760 withEdit(current, edit, ["state", "isDraft", "autoMergeEnabled", "title"]),
761 value,
762 ),
763 },
764 );
765 }
766
767 /** Lets a client record what each answer says where it lands, rather than watching the data. */
768 export interface PullRequestAnswerHandlers {
769 readonly list?: QueryAnswerHandler<PullRequestListInput, PullRequestListResult>;
770 readonly listStats?: QueryAnswerHandler<PullRequestListStatsInput, PullRequestListStatsResult>;
771 readonly detail?: QueryAnswerHandler<PullRequestRef, PullRequestDetail>;
772 readonly filesViewed?: QueryAnswerHandler<PullRequestRef, PullRequestFilesViewedResult>;
773 readonly checks?: QueryAnswerHandler<PullRequestRef, PullRequestChecks | null>;
774 readonly reviewGuide?: QueryAnswerHandler<PullRequestRef, PullRequestReviewGuideResult>;
775 /** Once per action reply, after the loaded readers show it; unscoped references only. */
776 readonly actionReply?: QueryAnswerHandler<PullRequestRef, PullRequestSummary>;
777 readonly acceptedEdit?: QueryAnswerHandler<PullRequestRef, PullRequestPendingEdit>;
778 }
779
780 export function createPullRequestStackAtomFamily<R, E>(
781 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
782 refreshes = createPullRequestRefreshAtomFamily(runtime),
783 ) {
784 const routedRequest = createPullRequestRouter();
785 const hostAnswers = Atom.family((_key: string) =>
786 Atom.make(false).pipe(Atom.setIdleTTL(5 * 60_000)),
787 );
788 const answeredKey = (target: {
789 readonly environmentId: EnvironmentId;
790 readonly input: PullRequestRef;
791 }) => JSON.stringify([target.environmentId, target.input]);
792 const stack = createEnvironmentRpcQueryAtomFamily(runtime, {
793 label: "environment-data:pull-requests:stack",
794 // A saved answer paints at once; `answered` stays false until the host answers.
795 persistence: persistQuery(Schema.NullOr(PullRequestStack)),
796 tag: WS_METHODS.pullRequestsStack,
797 execute: (input) => routedRequest(WS_METHODS.pullRequestsStack, input),
798 staleTimeMs: 60_000,
799 idleTtlMs: LINKED_PULL_REQUEST_IDLE_TTL_MS,
800 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
801 onAnswer: (target, _value, registry) =>
802 Effect.sync(() => registry.set(hostAnswers(answeredKey(target)), true)),
803 });
804 /** Whether this session has the host's own answer, which is what merging one layer alone needs. */
805 const answered = (target: {
806 readonly environmentId: EnvironmentId;
807 readonly input: PullRequestRef;
808 }) => hostAnswers(answeredKey(target));
809 return Object.assign(stack, { answered });
810 }
811
812 export function pullRequestDetailToVcsStatus(
813 detail: PullRequestDetail | PullRequestSummary,
814 ): NonNullable<VcsStatusResult["pr"]> {
815 return {
816 number: detail.number,
817 title: detail.title,
818 url: detail.url,
819 baseRef: detail.baseBranch,
820 headRef: detail.headBranch,
821 state: detail.state,
822 ...(detail.isDraft === true ? { isDraft: true } : {}),
823 updatedAt: detail.updatedAt,
824 };
825 }
826
827 export function createPullRequestEnvironmentAtoms<R, E>(
828 runtime: Atom.AtomRuntime<
829 EnvironmentRegistry | PullRequestDiffLoader.PullRequestDiffLoader | R,
830 E
831 >,
832 onAnswer: PullRequestAnswerHandlers = {},
833 ) {
834 const refreshes = createPullRequestRefreshAtomFamily(runtime);
835 const sessions = createEnvironmentSessionAtoms(runtime);
836 const linkedThreadSignals = createEnvironmentRpcSubscriptionAtomFamily(runtime, {
837 label: "environment-data:pull-requests:linked-thread-refreshes",
838 tag: WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes,
839 });
840 // Servers without `linkedThreadRefreshes` never signal link changes, so poll them instead.
841 const linkedThreadsRefreshes = Atom.family((environmentId: EnvironmentId) =>
842 Atom.make((get): unknown => {
843 const signal = get(refreshes({ environmentId, input: {} }));
844 const config = get(sessions.initialConfigValueAtom(environmentId));
845 if (config?.environment.capabilities.linkedThreadRefreshes === true) {
846 return [signal, get(linkedThreadSignals({ environmentId, input: {} }))];
847 }
848 // @effect-diagnostics-next-line globalTimers:off - Mirrors `Atom.withRefresh`, outside an Effect runtime.
849 const handle = setTimeout(() => get.refreshSelf(), 10_000);
850 get.addFinalizer(() => clearTimeout(handle));
851 return {};
852 }),
853 );
854 const commandScheduler = createAtomCommandScheduler();
855 const routedRequest = createPullRequestRouter();
856 const serialPerEnvironment = {
857 mode: "serial",
858 key: ({ environmentId }: { readonly environmentId: string }) => environmentId,
859 } as const;
860 const activity = writableQueryFamily(
861 createEnvironmentRpcQueryAtomFamily(runtime, {
862 label: "environment-data:pull-requests:activity",
863 persistence: persistQuery(PullRequestActivity),
864 tag: WS_METHODS.pullRequestsActivity,
865 execute: (input) => routedRequest(WS_METHODS.pullRequestsActivity, input),
866 staleTimeMs: 60_000,
867 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
868 }),
869 );
870 const detailAnswerAtoms = Atom.family((_key: string) =>
871 Atom.make<{ readonly value: PullRequestDetail; readonly version: number } | null>(null).pipe(
872 Atom.setIdleTTL(5 * 60_000),
873 ),
874 );
875 const detailAnswers = normalizePullRequestQuery((target) =>
876 detailAnswerAtoms(JSON.stringify(target)),
877 );
878 const detailLabel = "environment-data:pull-requests:detail";
879 const detailPersistence = persistQuery(PullRequestDetailSchema);
880 const detail = normalizePullRequestQuery(
881 actionPatchedQuery(
882 createEnvironmentRpcQueryAtomFamily(runtime, {
883 label: detailLabel,
884 persistence: detailPersistence,
885 tag: WS_METHODS.pullRequestsDetail,
886 execute: (input) => routedRequest(WS_METHODS.pullRequestsDetail, input),
887 staleTimeMs: 60_000,
888 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
889 onAnswer: (target, value, registry) =>
890 Effect.sync(() => {
891 // Cache reads bypass onAnswer, and server freshness stays separate from local readbacks.
892 registry.update(detailAnswers(target), (previous) => ({
893 value,
894 version: (previous?.version ?? 0) + 1,
895 }));
896 }).pipe(Effect.andThen(() => onAnswer.detail?.(target, value, registry) ?? Effect.void)),
897 }),
898 {
899 label: detailLabel,
900 persistence: detailPersistence,
901 onAnswer: onAnswer.detail,
902 concerns: samePullRequest,
903 rereadWithoutReply: true,
904 // Reopening or a new head changes branch data and permissions the reply lacks.
905 rereads: (value, reply) =>
906 !isStalePullRequestReply(value, reply) &&
907 ((value.state === "closed" && reply.state === "open") ||
908 (reply.headSha !== undefined && reply.headSha !== value.headSha)),
909 patch: (_input, value, _reference, reply) => {
910 if (isStalePullRequestReply(value, reply)) return value;
911 const patched = {
912 ...value,
913 ...pickDefined(reply, [
914 "title",
915 "url",
916 "author",
917 "state",
918 "isDraft",
919 "mergeability",
920 "additions",
921 "deletions",
922 "changedFiles",
923 "headBranch",
924 "baseBranch",
925 "updatedAt",
926 "mergedAt",
927 "closedAt",
928 "autoMergeEnabled",
929 "autoMergeMethod",
930 ]),
931 };
932 if (reply.autoMergeEnabled !== false) return patched;
933 const { autoMergeMethod: _disarmed, ...withoutAutoMerge } = patched;
934 return withoutAutoMerge;
935 },
936 edit: (_input, value, edits) =>
937 edits.reduce(
938 (current, edit) =>
939 withLabelEdit(
940 withEdit(current, edit, ["state", "isDraft", "autoMergeEnabled", "title", "body"]),
941 edit,
942 ),
943 value,
944 ),
945 },
946 ),
947 );
948 // Pages read the strict detail and other surfaces the default one; patch whichever is loaded
949 // without starting a read of the other.
950 const loadedDetails = (
951 registry: AtomRegistry.AtomRegistry,
952 target: { readonly environmentId: EnvironmentId; readonly input: PullRequestRef },
953 ) =>
954 [
955 detail({ ...target, input: { ...target.input, allowStale: undefined } }),
956 detail({ ...target, input: { ...target.input, allowStale: false } }),
957 ].filter((atom) => registry.getNodes().has(atom));
958 const detailReadVersions = Atom.family((source: ReturnType<typeof detail>) =>
959 Atom.family((answer: ReturnType<typeof detailAnswers>) =>
960 Atom.make((get) => {
961 const result = get(source);
962 const latest = get(answer);
963 return result._tag === "Success" && !result.waiting && result.value === latest?.value
964 ? latest.version
965 : Option.getOrElse(get.self<number>(), () => 0);
966 }).pipe(Atom.setIdleTTL(5 * 60_000)),
967 ),
968 );
969 const detailReadVersion = normalizePullRequestQuery((target) =>
970 detailReadVersions(detail(target))(detailAnswers(target)),
971 );
972 const previewPersistence = persistQuery(PullRequestPreview);
973 const previewQuery = (label: string) =>
974 normalizePullRequestQuery(
975 actionPatchedQuery(
976 createEnvironmentRpcQueryAtomFamily(runtime, {
977 label,
978 persistence: previewPersistence,
979 tag: WS_METHODS.pullRequestsPreview,
980 execute: (input) => routedRequest(WS_METHODS.pullRequestsPreview, input),
981 staleTimeMs: 60_000,
982 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
983 }),
984 {
985 label,
986 persistence: previewPersistence,
987 concerns: samePullRequest,
988 rereadWithoutReply: true,
989 // Servers before action replies send unstamped previews, which only a read can order.
990 patch: (_input, value, _reference, reply) =>
991 value.updatedAt === undefined && value.observedAt === undefined
992 ? "refresh"
993 : isStalePullRequestReply(value, reply)
994 ? value
995 : {
996 ...value,
997 ...pickDefined(reply, [
998 "title",
999 "url",
1000 "author",
1001 "state",
1002 "isDraft",
1003 "updatedAt",
1004 "observedAt",
1005 ]),
1006 },
1007 edit: (_input, value, edits) =>
1008 edits.reduce(
1009 (current, edit) => withEdit(current, edit, ["state", "isDraft", "title"]),
1010 value,
1011 ),
1012 },
1013 ),
1014 );
1015 const preview = previewQuery("environment-data:pull-requests:preview");
1016 // Hover cards read their own atoms, so a pending or failed hover read never decides where a
1017 // click on the same link goes.
1018 const previewCard = previewQuery("environment-data:pull-requests:preview-card");
1019 const labelCandidateQueries = writableQueryFamily(
1020 createEnvironmentRpcQueryAtomFamily(runtime, {
1021 label: "environment-data:pull-requests:label-candidates",
1022 tag: WS_METHODS.pullRequestsLabelCandidates,
1023 execute: (input) => routedRequest(WS_METHODS.pullRequestsLabelCandidates, input),
1024 staleTimeMs: 60_000,
1025 }),
1026 );
1027 const labelCandidates = normalizePullRequestQuery((target) =>
1028 editedQuery(labelCandidateQueries(target), {
1029 environmentId: target.environmentId,
1030 concerns: (reference) => samePullRequest(target.input, reference),
1031 edit: (value, edits) => edits.reduce(withLabelCandidateEdit, value),
1032 }),
1033 );
1034 const labelEdit = (
1035 registry: AtomRegistry.AtomRegistry,
1036 target: {
1037 readonly environmentId: EnvironmentId;
1038 readonly input: PullRequestRef & {
1039 readonly labels: ReadonlyArray<string>;
1040 readonly applied: boolean;
1041 };
1042 },
1043 ): PullRequestPendingEdit => {
1044 const candidates = Option.getOrUndefined(
1045 loadedValue<PullRequestLabelCandidateList>(registry, labelCandidates(target)),
1046 )?.candidates;
1047 return {
1048 reference: pullRequestReference(target.input),
1049 labels: {
1050 applied: target.input.applied,
1051 labels: target.input.labels.map((name) => ({
1052 name,
1053 color: candidates?.find((candidate) => candidate.name === name)?.color ?? null,
1054 })),
1055 },
1056 };
1057 };
1058 const reviewGuide = writableQueryFamily(
1059 createEnvironmentRpcQueryAtomFamily(runtime, {
1060 label: "environment-data:pull-requests:review-guide",
1061 persistence: persistQuery(PullRequestReviewGuideResult),
1062 tag: WS_METHODS.pullRequestsReviewGuide,
1063 execute: (input) => routedRequest(WS_METHODS.pullRequestsReviewGuide, input),
1064 staleTimeMs: 60_000,
1065 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
1066 ...(onAnswer.reviewGuide === undefined ? {} : { onAnswer: onAnswer.reviewGuide }),
1067 }),
1068 );
1069 const reviewerCandidates = writableQueryFamily(
1070 createEnvironmentRpcQueryAtomFamily(runtime, {
1071 label: "environment-data:pull-requests:reviewer-candidates",
1072 tag: WS_METHODS.pullRequestsReviewerCandidates,
1073 execute: (input) => routedRequest(WS_METHODS.pullRequestsReviewerCandidates, input),
1074 staleTimeMs: 60_000,
1075 }),
1076 );
1077 // Asked only when the menu's first page is not everybody, so a query cannot be answered from it.
1078 const reviewerSearch = createEnvironmentRpcQueryAtomFamily(runtime, {
1079 label: "environment-data:pull-requests:reviewer-search",
1080 tag: WS_METHODS.pullRequestsReviewerCandidates,
1081 execute: (input) => routedRequest(WS_METHODS.pullRequestsReviewerCandidates, input),
1082 staleTimeMs: 60_000,
1083 });
1084 const loadDiff = Effect.fn("PullRequests.loadDiff")(function* (input: PullRequestDiffInput) {
1085 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
1086 const loader = yield* PullRequestDiffLoader.PullRequestDiffLoader;
1087 const prepared = yield* SubscriptionRef.get(supervisor.prepared);
1088 if (Option.isNone(prepared)) {
1089 return yield* new EnvironmentHttpConnectionNotReadyError({
1090 ...translatableMessage(msg("The environment HTTP connection is not ready.")),
1091 });
1092 }
1093 return yield* loader.load(prepared.value, input);
1094 });
1095
1096 const runAction = Effect.fn("PullRequests.runAction")(function* (
1097 input: PullRequestActionInput & {
1098 readonly resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;
1099 },
1100 ) {
1101 const { resolveMergeMethod, ...actionInput } = input;
1102 let preparedInput = actionInput;
1103 if (actionInput.action === "merge" && resolveMergeMethod !== undefined) {
1104 const { projectId, host, repository, number } = actionInput;
1105 const reference = { projectId, host, repository, number, allowStale: false };
1106 const detail = yield* routedRequest(WS_METHODS.pullRequestsDetail, reference);
1107 if (
1108 detail.state !== "open" ||
1109 detail.isDraft ||
1110 !detail.capabilities.actions.includes("merge") ||
1111 !detail.viewerPermissions.actions.includes("merge")
1112 ) {
1113 return yield* new PullRequestOperationError({
1114 operation: "runAction",
1115 detail: "This pull request cannot be merged.",
1116 });
1117 }
1118 if (detail.capabilities.stackActions) {
1119 const stack = yield* routedRequest(WS_METHODS.pullRequestsStack, reference);
1120 if (stack !== null) {
1121 return yield* new PullRequestOperationError({
1122 operation: "runAction",
1123 detail: "Open this pull request to merge its stack.",
1124 });
1125 }
1126 }
1127 const mergeMethod = yield* Effect.try({
1128 try: () => resolveMergeMethod(detail),
1129 catch: (cause) =>
1130 new PullRequestOperationError({
1131 operation: "runAction",
1132 detail: cause instanceof Error ? cause.message : "Could not choose a merge method.",
1133 }),
1134 });
1135 preparedInput = { ...actionInput, mergeMethod };
1136 }
1137 return yield* routedRequest(WS_METHODS.pullRequestsRunAction, {
1138 ...preparedInput,
1139 replyWithSummary: true,
1140 });
1141 });
1142 const actionReplyReaders = (registry: AtomRegistry.AtomRegistry) =>
1143 Array.from(registry.getNodes().keys()).flatMap((atom) => {
1144 const patch = typeof atom === "string" ? undefined : actionReplyPatches.get(atom);
1145 return patch === undefined ? [] : [patch];
1146 });
1147 const readsInFlight = (registry: AtomRegistry.AtomRegistry): ReadonlySet<object> =>
1148 new Set(actionReplyReaders(registry).flatMap((reader) => reader.pendingRead(registry) ?? []));
1149 const applyActionReply = Effect.fn("PullRequests.applyActionReply")(function* (
1150 registry: AtomRegistry.AtomRegistry,
1151 environmentId: EnvironmentId,
1152 reference: PullRequestRef,
1153 reply: PullRequestSummary | undefined,
1154 readsBeforeSend: ReadonlySet<object>,
1155 ) {
1156 for (const reader of actionReplyReaders(registry)) {
1157 yield* reader.apply(registry, environmentId, reference, reply, readsBeforeSend);
1158 }
1159 if (reply !== undefined && reference.expectedAccountId === undefined) {
1160 yield* (
1161 onAnswer.actionReply?.({ environmentId, input: reference }, reply, registry) ?? Effect.void
1162 );
1163 }
1164 });
1165 const checksLabel = "environment-data:pull-requests:checks";
1166 const checksPersistence = persistQuery(Schema.NullOr(PullRequestChecks));
1167 // Panels take the state from the newest of detail and checks, so checks show writes too.
1168 const checks = normalizePullRequestQuery(
1169 actionPatchedQuery(
1170 createEnvironmentRpcQueryAtomFamily(runtime, {
1171 label: checksLabel,
1172 persistence: checksPersistence,
1173 tag: WS_METHODS.pullRequestsChecks,
1174 execute: (input) => routedRequest(WS_METHODS.pullRequestsChecks, input),
1175 staleTimeMs: 45_000,
1176 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
1177 ...(onAnswer.checks === undefined ? {} : { onAnswer: onAnswer.checks }),
1178 }),
1179 {
1180 label: checksLabel,
1181 persistence: checksPersistence,
1182 onAnswer: onAnswer.checks,
1183 concerns: samePullRequest,
1184 patch: (_input, value, _reference, reply) =>
1185 value === null || value.state === reply.state || isStalePullRequestReply(value, reply)
1186 ? value
1187 : { ...value, state: reply.state },
1188 edit: (_input, value, edits) => {
1189 const state = edits.findLast((edit) => edit.state !== undefined)?.state;
1190 return value === null || state === undefined || value.state === state
1191 ? value
1192 : { ...value, state };
1193 },
1194 },
1195 ),
1196 );
1197 const acceptEdit = (
1198 registry: AtomRegistry.AtomRegistry,
1199 environmentId: EnvironmentId,
1200 edit: PullRequestPendingEdit | null,
1201 readsAfterWrite = false,
1202 ) =>
1203 Effect.sync(() => settleEdit(registry, environmentId, edit, readsAfterWrite)).pipe(
1204 Effect.andThen(() =>
1205 edit === null
1206 ? Effect.void
1207 : (onAnswer.acceptedEdit?.({ environmentId, input: edit.reference }, edit, registry) ??
1208 Effect.void),
1209 ),
1210 );
1211 const listLabel = "environment-data:pull-requests:list";
1212 const listPersistence = persistQuery(PullRequestListResult);
1213
1214 return {
1215 refreshes,
1216 linkedThreads: createEnvironmentRpcQueryAtomFamily(runtime, {
1217 label: "environment-data:pull-requests:linked-threads",
1218 persistence: persistQuery(PullRequestLinkedThreadsResult),
1219 tag: WS_METHODS.pullRequestsLinkedThreads,
1220 staleTimeMs: 0,
1221 refreshTrigger: ({ environmentId }) => linkedThreadsRefreshes(environmentId),
1222 }),
1223 // For callers that open a thread from the answer: a persisted one reads as final before
1224 // the connection is known, and a kept one can predate the thread.
1225 linkedThreadsUncached: createEnvironmentRpcQueryAtomFamily(runtime, {
1226 label: "environment-data:pull-requests:linked-threads-uncached",
1227 tag: WS_METHODS.pullRequestsLinkedThreads,
1228 staleTimeMs: 0,
1229 idleTtlMs: 0,
1230 }),
1231 list: actionPatchedQuery(
1232 createEnvironmentRpcQueryAtomFamily(runtime, {
1233 label: listLabel,
1234 persistence: listPersistence,
1235 tag: WS_METHODS.pullRequestsList,
1236 staleTimeMs: 30_000,
1237 refreshTrigger: ({ environmentId, input }) =>
1238 input.cursors === undefined ? refreshes({ environmentId, input: {} }) : undefined,
1239 ...(onAnswer.list === undefined ? {} : { onAnswer: onAnswer.list }),
1240 }),
1241 {
1242 label: listLabel,
1243 persistence: listPersistence,
1244 onAnswer: onAnswer.list,
1245 // Rows carry no account scope, so a reply read through another account leaves them alone.
1246 concerns: (input, reference) =>
1247 reference.expectedAccountId === undefined &&
1248 (input.projectId === undefined || input.projectId === reference.projectId) &&
1249 (input.projectIds === undefined || input.projectIds.includes(reference.projectId)) &&
1250 (input.host === undefined ||
1251 reference.host === undefined ||
1252 input.host.toLowerCase() === reference.host.toLowerCase()),
1253 refreshedByServer: (input) => input.cursors === undefined,
1254 patch: patchListWithReply,
1255 edit: (input, value, edits, pending) => {
1256 const entries = editPullRequestListEntries(input, value.entries, edits, pending);
1257 return entries === value.entries ? value : { ...value, entries };
1258 },
1259 },
1260 ),
1261 /**
1262 * Its own query because the listing is quicker without them — measured over twelve
1263 * repositories, ~4.0s against ~7.1s — so the rows arrive first and their stats a moment
1264 * later.
1265 */
1266 listStats: createEnvironmentRpcQueryAtomFamily(runtime, {
1267 label: "environment-data:pull-requests:list-stats",
1268 persistence: persistPullRequestStats(),
1269 tag: WS_METHODS.pullRequestsListStats,
1270 staleTimeMs: 60_000,
1271 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
1272 ...(onAnswer.listStats === undefined ? {} : { onAnswer: onAnswer.listStats }),
1273 }),
1274 filterOptions: createEnvironmentRpcQueryAtomFamily(runtime, {
1275 label: "environment-data:pull-requests:filter-options",
1276 tag: WS_METHODS.pullRequestsFilterOptions,
1277 staleTimeMs: 5 * 60_000,
1278 }),
1279 detail,
1280 detailReadVersion,
1281 preview,
1282 previewCard,
1283 checks,
1284 activity,
1285 threadComments: createEnvironmentRpcCommand(runtime, {
1286 label: "environment-data:pull-requests:thread-comments",
1287 tag: WS_METHODS.pullRequestsThreadComments,
1288 execute: (input) => routedRequest(WS_METHODS.pullRequestsThreadComments, input),
1289 scheduler: commandScheduler,
1290 concurrency: {
1291 mode: "singleFlight",
1292 key: ({ environmentId, input }) =>
1293 JSON.stringify([environmentId, input.threadId, input.cursor]),
1294 },
1295 }),
1296 diff: createEnvironmentQueryAtomFamily(runtime, {
1297 label: "environment-data:pull-requests:diff",
1298 persistence: persistQuery(PullRequestDiffResult),
1299 staleTimeMs: 60_000,
1300 // A guide tied to a commit must not reuse another push's cached pages.
1301 execute: ({
1302 cacheHeadSha: _cacheHeadSha,
1303 ...input
1304 }: PullRequestDiffInput & {
1305 readonly cacheHeadSha?: string;
1306 }) => loadDiff(input),
1307 }),
1308 diffFileContents: createEnvironmentRpcCommand(runtime, {
1309 label: "environment-data:pull-requests:diff-file-contents",
1310 tag: WS_METHODS.pullRequestsDiffFileContents,
1311 execute: (input) => routedRequest(WS_METHODS.pullRequestsDiffFileContents, input),
1312 scheduler: commandScheduler,
1313 concurrency: {
1314 mode: "singleFlight",
1315 key: ({ environmentId, input }) =>
1316 JSON.stringify([
1317 environmentId,
1318 input.projectId,
1319 input.host?.toLowerCase() ?? null,
1320 input.repository,
1321 input.number,
1322 input.commit ?? null,
1323 input.changeType,
1324 input.oldPath,
1325 input.newPath,
1326 ]),
1327 },
1328 }),
1329 filesViewed: createEnvironmentRpcQueryAtomFamily(runtime, {
1330 label: "environment-data:pull-requests:files-viewed",
1331 ...(onAnswer.filesViewed === undefined ? {} : { onAnswer: onAnswer.filesViewed }),
1332 persistence: persistQuery(PullRequestFilesViewedResult),
1333 tag: WS_METHODS.pullRequestsFilesViewed,
1334 execute: (input) => routedRequest(WS_METHODS.pullRequestsFilesViewed, input),
1335 staleTimeMs: 15_000,
1336 }),
1337 changeBreakdown: createEnvironmentRpcQueryAtomFamily(runtime, {
1338 label: "environment-data:pull-requests:change-breakdown",
1339 persistence: persistQuery(PullRequestChangeBreakdown),
1340 tag: WS_METHODS.pullRequestsChangeBreakdown,
1341 execute: (input) => routedRequest(WS_METHODS.pullRequestsChangeBreakdown, input),
1342 staleTimeMs: 60_000,
1343 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
1344 }),
1345 /**
1346 * One write in flight per change request: the host applies these in order, and a reader
1347 * ticking down a file list faster than the round trip would otherwise race their own presses.
1348 */
1349 setFilesViewed: createEnvironmentRpcCommand(runtime, {
1350 label: "environment-data:pull-requests:set-files-viewed",
1351 tag: WS_METHODS.pullRequestsSetFilesViewed,
1352 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetFilesViewed, input),
1353 scheduler: commandScheduler,
1354 concurrency: {
1355 mode: "serial",
1356 key: ({ environmentId, input }) =>
1357 JSON.stringify([environmentId, input.projectId, input.repository, input.number]),
1358 },
1359 }),
1360 runAction: showWhileInFlight(
1361 createEnvironmentRpcCommand(runtime, {
1362 tag: WS_METHODS.pullRequestsRunAction,
1363 label: "environment-data:pull-requests:run-action",
1364 // Preparation belongs to the write's lane. Refreshable queries would restart it after
1365 // every preceding action, and preparing outside the lane could reorder the clicks.
1366 execute: runAction,
1367 onStart: (_target, registry) => readsInFlight(registry),
1368 // Loaded readers show the reply, or re-read when the host's reply lacked the pull request.
1369 onSuccess: ({ environmentId, input }, registry, reply, readsBeforeSend) =>
1370 applyActionReply(
1371 registry,
1372 environmentId,
1373 pullRequestReference(input),
1374 reply,
1375 readsBeforeSend ?? new Set(),
1376 ).pipe(
1377 // The re-read a bare reply starts would otherwise show the old state until it answers.
1378 Effect.andThen(
1379 reply === undefined
1380 ? acceptEdit(registry, environmentId, actionEdit(input), true)
1381 : Effect.void,
1382 ),
1383 ),
1384 scheduler: commandScheduler,
1385 concurrency: serialPerEnvironment,
1386 }),
1387 (_registry, { input }) => actionEdit(input),
1388 ),
1389 update: showWhileInFlight(
1390 createEnvironmentRpcCommand(runtime, {
1391 label: "environment-data:pull-requests:update",
1392 tag: WS_METHODS.pullRequestsUpdate,
1393 execute: (input) => routedRequest(WS_METHODS.pullRequestsUpdate, input),
1394 onSuccess: (target, registry) =>
1395 acceptEdit(registry, target.environmentId, updateEdit(target.input)),
1396 scheduler: commandScheduler,
1397 concurrency: serialPerEnvironment,
1398 }),
1399 (_registry, { input }) => updateEdit(input),
1400 ),
1401 comment: createEnvironmentRpcCommand(runtime, {
1402 label: "environment-data:pull-requests:comment",
1403 tag: WS_METHODS.pullRequestsComment,
1404 execute: (input) => routedRequest(WS_METHODS.pullRequestsComment, input),
1405 scheduler: commandScheduler,
1406 concurrency: serialPerEnvironment,
1407 }),
1408 updateComment: createEnvironmentRpcCommand(runtime, {
1409 label: "environment-data:pull-requests:update-comment",
1410 tag: WS_METHODS.pullRequestsUpdateComment,
1411 execute: (input) => routedRequest(WS_METHODS.pullRequestsUpdateComment, input),
1412 scheduler: commandScheduler,
1413 concurrency: serialPerEnvironment,
1414 onSuccess: ({ environmentId, input: { projectId, host, repository, number } }, registry) =>
1415 Effect.sync(() =>
1416 registry.refresh(
1417 activity({
1418 environmentId,
1419 input: { projectId, ...(host === undefined ? {} : { host }), repository, number },
1420 }),
1421 ),
1422 ),
1423 }),
1424 submitReview: createEnvironmentRpcCommand(runtime, {
1425 label: "environment-data:pull-requests:submit-review",
1426 tag: WS_METHODS.pullRequestsSubmitReview,
1427 execute: (input) => routedRequest(WS_METHODS.pullRequestsSubmitReview, input),
1428 scheduler: commandScheduler,
1429 concurrency: serialPerEnvironment,
1430 }),
1431 replyToThread: createEnvironmentRpcCommand(runtime, {
1432 label: "environment-data:pull-requests:reply-to-thread",
1433 tag: WS_METHODS.pullRequestsReplyToThread,
1434 execute: (input) => routedRequest(WS_METHODS.pullRequestsReplyToThread, input),
1435 scheduler: commandScheduler,
1436 concurrency: serialPerEnvironment,
1437 }),
1438 reviewerCandidates,
1439 /** The host's search for reviewers past the first page, keyed by what was typed. */
1440 reviewerSearch,
1441 requestReviewers: createEnvironmentRpcCommand(runtime, {
1442 label: "environment-data:pull-requests:request-reviewers",
1443 tag: WS_METHODS.pullRequestsRequestReviewers,
1444 execute: (input) => routedRequest(WS_METHODS.pullRequestsRequestReviewers, input),
1445 scheduler: commandScheduler,
1446 concurrency: serialPerEnvironment,
1447 onSuccess: (target, registry) =>
1448 Effect.sync(() => {
1449 const { reviewers, requested } = target.input;
1450 const candidatesAtom = reviewerCandidates(target);
1451 const candidates = AsyncResult.getOrElse(registry.get(candidatesAtom), () => null);
1452 const selected =
1453 candidates?.candidates.filter((candidate) =>
1454 reviewers.some(
1455 (reviewer) => reviewer.id === candidate.id && reviewer.kind === candidate.kind,
1456 ),
1457 ) ?? [];
1458 const missingIdentities = selected.length < reviewers.length;
1459 // Somebody found only by the host's search is not in the loaded list yet; the host
1460 // puts requested reviewers first, so reading it again brings them in.
1461 updateCached(
1462 registry,
1463 candidatesAtom,
1464 (value) => ({
1465 ...value,
1466 candidates: value.candidates.map((candidate) =>
1467 selected.includes(candidate) ? { ...candidate, isRequested: requested } : candidate,
1468 ),
1469 }),
1470 missingIdentities,
1471 );
1472 const selectedLogins = new Set(
1473 selected.map((candidate) => candidate.login.toLowerCase()),
1474 );
1475 const updateReviewers = (
1476 actors: ReadonlyArray<PullRequestActor>,
1477 keep = (_actor: PullRequestActor) => false,
1478 ) =>
1479 requested
1480 ? [
1481 ...actors,
1482 ...selected
1483 .filter(
1484 (candidate) =>
1485 !actors.some(
1486 (actor) => actor.login.toLowerCase() === candidate.login.toLowerCase(),
1487 ),
1488 )
1489 .map(({ login, name, avatarUrl }) => ({ login, name, avatarUrl })),
1490 ]
1491 : actors.filter(
1492 (actor) => !selectedLogins.has(actor.login.toLowerCase()) || keep(actor),
1493 );
1494 for (const atom of loadedDetails(registry, target)) {
1495 updateCached(
1496 registry,
1497 atom,
1498 (value) => ({
1499 ...value,
1500 reviewers: updateReviewers(value.reviewers),
1501 }),
1502 missingIdentities,
1503 );
1504 }
1505 updateCached(
1506 registry,
1507 activity(target),
1508 (value) => ({
1509 ...value,
1510 reviewers:
1511 value.reviewers === undefined
1512 ? undefined
1513 : updateReviewers(value.reviewers, (actor) =>
1514 value.comments.some(
1515 (comment) =>
1516 (comment.kind === "review" || comment.kind === "review-comment") &&
1517 comment.author?.login.toLowerCase() === actor.login.toLowerCase(),
1518 ),
1519 ),
1520 }),
1521 missingIdentities,
1522 );
1523 }),
1524 }),
1525 reviewGuide,
1526 generateReviewGuide: createEnvironmentRpcCommand(runtime, {
1527 label: "environment-data:pull-requests:generate-review-guide",
1528 tag: WS_METHODS.pullRequestsGenerateReviewGuide,
1529 execute: (input) => routedRequest(WS_METHODS.pullRequestsGenerateReviewGuide, input),
1530 onSuccess: (target, registry, result) =>
1531 Effect.sync(() => {
1532 updateCached(registry, reviewGuide(target), () => result, true);
1533 }),
1534 }),
1535 labelCandidates,
1536 setLabels: showWhileInFlight(
1537 createEnvironmentRpcCommand(runtime, {
1538 label: "environment-data:pull-requests:set-labels",
1539 tag: WS_METHODS.pullRequestsSetLabels,
1540 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetLabels, input),
1541 scheduler: commandScheduler,
1542 concurrency: serialPerEnvironment,
1543 onSuccess: (target, registry) =>
1544 acceptEdit(registry, target.environmentId, labelEdit(registry, target)),
1545 }),
1546 labelEdit,
1547 ),
1548 setThreadResolution: createEnvironmentRpcCommand(runtime, {
1549 label: "environment-data:pull-requests:set-thread-resolution",
1550 tag: WS_METHODS.pullRequestsSetThreadResolution,
1551 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetThreadResolution, input),
1552 scheduler: commandScheduler,
1553 concurrency: serialPerEnvironment,
1554 }),
1555 setReaction: createEnvironmentRpcCommand(runtime, {
1556 label: "environment-data:pull-requests:set-reaction",
1557 tag: WS_METHODS.pullRequestsSetReaction,
1558 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetReaction, input),
1559 scheduler: commandScheduler,
1560 concurrency: serialPerEnvironment,
1561 }),
1562 /**
1563 * A separate request rather than a flag on a read, so only a person's refresh spends
1564 * host requests while every silent re-read shares the cache.
1565 */
1566 invalidate: createEnvironmentRpcCommand(runtime, {
1567 label: "environment-data:pull-requests:invalidate",
1568 tag: WS_METHODS.pullRequestsInvalidate,
1569 execute: (input) => routedRequest(WS_METHODS.pullRequestsInvalidate, input),
1570 onSuccess: ({ environmentId, input }, registry) =>
1571 Effect.sync(() => {
1572 if (input.reference !== undefined) {
1573 registry.refresh(preview({ environmentId, input: input.reference }));
1574 registry.refresh(previewCard({ environmentId, input: input.reference }));
1575 }
1576 }),
1577 scheduler: commandScheduler,
1578 concurrency: serialPerEnvironment,
1579 }),
1580 };
1581 }