Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

pullRequests.ts

620 lines25.8 KB

1import {
2 WS_METHODS,
3 PullRequestActivity,
4 PullRequestDetail as PullRequestDetailSchema,
5 PullRequestPreview,
6 PullRequestReviewGuideResult,
7 PullRequestListResult,
8 PullRequestChecks,
9 PullRequestDiffResult,
10 PullRequestFilesViewedResult,
11 PullRequestLinkedThreadsResult,
12 type EnvironmentId,
13 type PullRequestActor,
14 type PullRequestActionInput,
15 type PullRequestDetail,
16 type PullRequestDiffInput,
17 type PullRequestRef,
18 type PullRequestMergeMethod,
19 PullRequestOperationError,
20 type PullRequestSummary,
21 type VcsStatusResult,
22} from "@t3tools/contracts";
23import * as Data from "effect/Data";
24import * as Effect from "effect/Effect";
25import * as Schema from "effect/Schema";
26import { persistPullRequestStats } from "./pullRequestStatsPersistence.ts";
27import { persistQuery } from "./queryPersistence.ts";
28import * as Option from "effect/Option";
29import * as SubscriptionRef from "effect/SubscriptionRef";
30import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
31​
32import {
33 createAtomCommandScheduler,
34 createEnvironmentRpcCommand,
35 createEnvironmentRpcQueryAtomFamily,
36 createEnvironmentRpcSubscriptionAtomFamily,
37 createEnvironmentQueryAtomFamily,
38} from "./runtime.ts";
39import { createPullRequestRouter } from "./pullRequestRouting.ts";
40import * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts";
41import type { EnvironmentRegistry } from "../connection/registry.ts";
42import * as EnvironmentSupervisor from "../connection/supervisor.ts";
43​
44export {
45 type PullRequestDiffLoadError,
46 PullRequestDiffCredentialRejectedError,
47} from "./pullRequestDiffHttp.ts";
48export * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts";
49​
50/** @public Required to name the error in consumers' inferred pull request results. */
51export class EnvironmentHttpConnectionNotReadyError extends Data.TaggedError(
52 "EnvironmentHttpConnectionNotReadyError",
53)<{ readonly message: string }> {}
54​
55const LINKED_PULL_REQUEST_IDLE_TTL_MS = 5_000;
56​
57/** Keep confirmed edits on the same cached reference regardless of input property order. */
58function writableQueryFamily<A, E>(
59 family: (target: {
60 readonly environmentId: EnvironmentId;
61 readonly input: PullRequestRef;
62 }) => Atom.Atom<AsyncResult.AsyncResult<A, E>>,
63) {
64 const writable = Atom.family((source: Atom.Atom<AsyncResult.AsyncResult<A, E>>) =>
65 Atom.writable(
66 (get) => {
67 const result = get(source);
68 if (result._tag === "Success" && !result.waiting) return result;
69 const previous = get.self<AsyncResult.AsyncResult<A, E>>();
70 const value = Option.flatMap(previous, AsyncResult.value);
71 if (Option.isNone(value)) return result;
72 return result._tag === "Failure"
73 ? AsyncResult.failureWithPrevious(result.cause, { previous, waiting: result.waiting })
74 : AsyncResult.success<A, E>(value.value, result);
75 },
76 (context, value: AsyncResult.AsyncResult<A, E>) => context.setSelf(value),
77 (refresh) => refresh(source),
78 ).pipe(Atom.setIdleTTL(5 * 60_000)),
79 );
80 return ({
81 environmentId,
82 input: { projectId, host, repository, number, allowStale },
83 }: Parameters<typeof family>[0]) =>
84 writable(
85 family({
86 environmentId,
87 input: {
88 projectId,
89 ...(host === undefined ? {} : { host }),
90 repository,
91 number,
92 ...(allowStale === undefined ? {} : { allowStale }),
93 },
94 }),
95 );
97​
98/** Restart pre-mutation reads before patching so they cannot restore stale values. */
99function updateCached<A, E>(
100 registry: AtomRegistry.AtomRegistry,
101 atom: Atom.Writable<AsyncResult.AsyncResult<A, E>>,
102 update: (value: A) => A,
103 refresh = false,
104) {
105 if (refresh || registry.get(atom).waiting) registry.refresh(atom);
106 registry.update(atom, AsyncResult.map(update));
108​
109function createPullRequestRefreshAtomFamily<R, E>(
110 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
111) {
112 return createEnvironmentRpcSubscriptionAtomFamily(runtime, {
113 label: "environment-data:pull-requests:turn-refreshes",
114 tag: WS_METHODS.pullRequestsSubscribeRefreshes,
115 });
117​
118/** Refresh only the live fields a linked thread renders. */
119export function createLinkedPullRequestSummaryAtomFamily<R, E>(
120 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
121 refreshes = createPullRequestRefreshAtomFamily(runtime),
122) {
123 const routedRequest = createPullRequestRouter();
124 return createEnvironmentRpcQueryAtomFamily(runtime, {
125 label: "environment-data:pull-requests:linked-summary",
126 tag: WS_METHODS.pullRequestsSummary,
127 execute: (input) => routedRequest(WS_METHODS.pullRequestsSummary, input),
128 staleTimeMs: 60_000,
129 refreshIntervalMs: 60_000,
130 idleTtlMs: LINKED_PULL_REQUEST_IDLE_TTL_MS,
131 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
132 });
134​
135/** The host-native stack a pull request belongs to; null where it is not stacked. */
136export function createPullRequestStackAtomFamily<R, E>(
137 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
138 refreshes = createPullRequestRefreshAtomFamily(runtime),
139) {
140 const routedRequest = createPullRequestRouter();
141 return createEnvironmentRpcQueryAtomFamily(runtime, {
142 label: "environment-data:pull-requests:stack",
143 tag: WS_METHODS.pullRequestsStack,
144 execute: (input) => routedRequest(WS_METHODS.pullRequestsStack, input),
145 staleTimeMs: 60_000,
146 idleTtlMs: LINKED_PULL_REQUEST_IDLE_TTL_MS,
147 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
148 });
150​
151export function pullRequestDetailToVcsStatus(
152 detail: PullRequestDetail | PullRequestSummary,
153): NonNullable<VcsStatusResult["pr"]> {
154 return {
155 number: detail.number,
156 title: detail.title,
157 url: detail.url,
158 baseRef: detail.baseBranch,
159 headRef: detail.headBranch,
160 state: detail.state,
161 ...(detail.isDraft === true ? { isDraft: true } : {}),
162 updatedAt: detail.updatedAt,
163 };
165​
166/**
167 * Reopening a PR within a minute reuses detail and activity. Explicit refreshes and
168 * turn notifications still revalidate. Mutations run serially per environment: actions on the same
169 * pull request are order-sensitive. Confirmed label and reviewer edits update cached state.
170 */
171export function createPullRequestEnvironmentAtoms<R, E>(
172 runtime: Atom.AtomRuntime<
173 EnvironmentRegistry | PullRequestDiffLoader.PullRequestDiffLoader | R,
174 E
175 >,
176) {
177 const refreshes = createPullRequestRefreshAtomFamily(runtime);
178 const commandScheduler = createAtomCommandScheduler();
179 const routedRequest = createPullRequestRouter();
180 const serialPerEnvironment = {
181 mode: "serial",
182 key: ({ environmentId }: { readonly environmentId: string }) => environmentId,
183 } as const;
184 const activity = writableQueryFamily(
185 createEnvironmentRpcQueryAtomFamily(runtime, {
186 label: "environment-data:pull-requests:activity",
187 persistence: persistQuery(PullRequestActivity),
188 tag: WS_METHODS.pullRequestsActivity,
189 execute: (input) => routedRequest(WS_METHODS.pullRequestsActivity, input),
190 staleTimeMs: 60_000,
191 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
192 }),
193 );
194 const detail = writableQueryFamily(
195 createEnvironmentRpcQueryAtomFamily(runtime, {
196 label: "environment-data:pull-requests:detail",
197 persistence: persistQuery(PullRequestDetailSchema),
198 tag: WS_METHODS.pullRequestsDetail,
199 execute: (input) => routedRequest(WS_METHODS.pullRequestsDetail, input),
200 staleTimeMs: 60_000,
201 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
202 }),
203 );
204 const preview = writableQueryFamily(
205 createEnvironmentRpcQueryAtomFamily(runtime, {
206 label: "environment-data:pull-requests:preview",
207 persistence: persistQuery(PullRequestPreview),
208 tag: WS_METHODS.pullRequestsPreview,
209 execute: (input) => routedRequest(WS_METHODS.pullRequestsPreview, input),
210 staleTimeMs: 60_000,
211 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
212 }),
213 );
214 const labelCandidates = writableQueryFamily(
215 createEnvironmentRpcQueryAtomFamily(runtime, {
216 label: "environment-data:pull-requests:label-candidates",
217 tag: WS_METHODS.pullRequestsLabelCandidates,
218 execute: (input) => routedRequest(WS_METHODS.pullRequestsLabelCandidates, input),
219 staleTimeMs: 60_000,
220 }),
221 );
222 // The stored guide only changes when somebody generates one, which refreshes it below.
223 const reviewGuide = writableQueryFamily(
224 createEnvironmentRpcQueryAtomFamily(runtime, {
225 label: "environment-data:pull-requests:review-guide",
226 persistence: persistQuery(PullRequestReviewGuideResult),
227 tag: WS_METHODS.pullRequestsReviewGuide,
228 execute: (input) => routedRequest(WS_METHODS.pullRequestsReviewGuide, input),
229 staleTimeMs: 60_000,
230 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
231 }),
232 );
233 const reviewerCandidates = writableQueryFamily(
234 createEnvironmentRpcQueryAtomFamily(runtime, {
235 label: "environment-data:pull-requests:reviewer-candidates",
236 tag: WS_METHODS.pullRequestsReviewerCandidates,
237 execute: (input) => routedRequest(WS_METHODS.pullRequestsReviewerCandidates, input),
238 staleTimeMs: 60_000,
239 }),
240 );
241 return {
242 refreshes,
243 linkedThreads: createEnvironmentRpcQueryAtomFamily(runtime, {
244 label: "environment-data:pull-requests:linked-threads",
245 persistence: persistQuery(PullRequestLinkedThreadsResult),
246 tag: WS_METHODS.pullRequestsLinkedThreads,
247 staleTimeMs: 0,
248 refreshIntervalMs: 10_000,
249 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
250 }),
251 list: createEnvironmentRpcQueryAtomFamily(runtime, {
252 label: "environment-data:pull-requests:list",
253 persistence: persistQuery(PullRequestListResult),
254 tag: WS_METHODS.pullRequestsList,
255 staleTimeMs: 30_000,
256 refreshTrigger: ({ environmentId, input }) =>
257 input.cursors === undefined ? refreshes({ environmentId, input: {} }) : undefined,
258 }),
259 /**
260 * The line counts for rows the listing has already handed over. Its own query because the
261 * listing is quicker without them — measured over twelve repositories, ~4.0s against ~7.1s —
262 * so the rows arrive first and their stats a moment later. Kept longer than the listing:
263 * a change request's size only moves when somebody pushes to it.
264 */
265 listStats: createEnvironmentRpcQueryAtomFamily(runtime, {
266 label: "environment-data:pull-requests:list-stats",
267 persistence: persistPullRequestStats(),
268 tag: WS_METHODS.pullRequestsListStats,
269 staleTimeMs: 60_000,
270 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
271 }),
272 detail,
273 preview,
274 checks: createEnvironmentRpcQueryAtomFamily(runtime, {
275 label: "environment-data:pull-requests:checks",
276 persistence: persistQuery(Schema.NullOr(PullRequestChecks)),
277 tag: WS_METHODS.pullRequestsChecks,
278 execute: (input) => routedRequest(WS_METHODS.pullRequestsChecks, input),
279 staleTimeMs: 45_000,
280 refreshTrigger: ({ environmentId }) => refreshes({ environmentId, input: {} }),
281 }),
282 activity,
283 threadComments: createEnvironmentRpcCommand(runtime, {
284 label: "environment-data:pull-requests:thread-comments",
285 tag: WS_METHODS.pullRequestsThreadComments,
286 execute: (input) => routedRequest(WS_METHODS.pullRequestsThreadComments, input),
287 scheduler: commandScheduler,
288 concurrency: {
289 mode: "singleFlight",
290 key: ({ environmentId, input }) =>
291 JSON.stringify([environmentId, input.threadId, input.cursor]),
292 },
293 }),
294 diff: createEnvironmentQueryAtomFamily(runtime, {
295 label: "environment-data:pull-requests:diff",
296 persistence: persistQuery(PullRequestDiffResult),
297 staleTimeMs: 60_000,
298 execute: (input: PullRequestDiffInput) =>
299 Effect.gen(function* () {
300 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
301 const loader = yield* PullRequestDiffLoader.PullRequestDiffLoader;
302 const prepared = yield* SubscriptionRef.get(supervisor.prepared);
303 if (Option.isNone(prepared)) {
304 return yield* new EnvironmentHttpConnectionNotReadyError({
305 message: "The environment HTTP connection is not ready.",
306 });
307 }
308 return yield* loader.load(prepared.value, input);
309 }),
310 }),
311 diffFileContents: createEnvironmentRpcCommand(runtime, {
312 label: "environment-data:pull-requests:diff-file-contents",
313 tag: WS_METHODS.pullRequestsDiffFileContents,
314 execute: (input) => routedRequest(WS_METHODS.pullRequestsDiffFileContents, input),
315 scheduler: commandScheduler,
316 concurrency: {
317 mode: "singleFlight",
318 key: ({ environmentId, input }) =>
319 JSON.stringify([
320 environmentId,
321 input.projectId,
322 input.host?.toLowerCase() ?? null,
323 input.repository,
324 input.number,
325 input.commit ?? null,
326 input.changeType,
327 input.oldPath,
328 input.newPath,
329 ]),
330 },
331 }),
332 filesViewed: createEnvironmentRpcQueryAtomFamily(runtime, {
333 label: "environment-data:pull-requests:files-viewed",
334 persistence: persistQuery(PullRequestFilesViewedResult),
335 tag: WS_METHODS.pullRequestsFilesViewed,
336 execute: (input) => routedRequest(WS_METHODS.pullRequestsFilesViewed, input),
337 staleTimeMs: 15_000,
338 }),
339 /**
340 * One write in flight per change request: the host applies these in order, and a reader
341 * ticking down a file list faster than the round trip would otherwise race their own presses.
342 */
343 setFilesViewed: createEnvironmentRpcCommand(runtime, {
344 label: "environment-data:pull-requests:set-files-viewed",
345 tag: WS_METHODS.pullRequestsSetFilesViewed,
346 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetFilesViewed, input),
347 scheduler: commandScheduler,
348 concurrency: {
349 mode: "serial",
350 key: ({ environmentId, input }) =>
351 JSON.stringify([environmentId, input.projectId, input.repository, input.number]),
352 },
353 }),
354 runAction: createEnvironmentRpcCommand(runtime, {
355 tag: WS_METHODS.pullRequestsRunAction,
356 label: "environment-data:pull-requests:run-action",
357 // Preparation belongs to the write's lane. Refreshable queries would restart it after
358 // every preceding action, and preparing outside the lane could reorder the clicks.
359 execute: (
360 input: PullRequestActionInput & {
361 readonly resolveMergeMethod?: (detail: PullRequestDetail) => PullRequestMergeMethod;
362 },
363 ) =>
364 Effect.gen(function* () {
365 const { resolveMergeMethod, ...actionInput } = input;
366 let preparedInput = actionInput;
367 if (actionInput.action === "merge" && resolveMergeMethod !== undefined) {
368 const { projectId, host, repository, number } = actionInput;
369 const reference = { projectId, host, repository, number, allowStale: false };
370 const detail = yield* routedRequest(WS_METHODS.pullRequestsDetail, reference);
371 if (
372 detail.state !== "open" ||
373 detail.isDraft ||
374 !detail.capabilities.actions.includes("merge") ||
375 !detail.viewerPermissions.actions.includes("merge")
376 ) {
377 return yield* new PullRequestOperationError({
378 operation: "runAction",
379 detail: "This pull request cannot be merged.",
380 });
381 }
382 if (detail.capabilities.stackActions) {
383 const stack = yield* routedRequest(WS_METHODS.pullRequestsStack, reference);
384 if (stack !== null) {
385 return yield* new PullRequestOperationError({
386 operation: "runAction",
387 detail: "Open this pull request to merge its stack.",
388 });
389 }
390 }
391 const mergeMethod = yield* Effect.try({
392 try: () => resolveMergeMethod(detail),
393 catch: (cause) =>
394 new PullRequestOperationError({
395 operation: "runAction",
396 detail:
397 cause instanceof Error ? cause.message : "Could not choose a merge method.",
398 }),
399 });
400 preparedInput = { ...actionInput, mergeMethod };
401 }
402 return yield* routedRequest(WS_METHODS.pullRequestsRunAction, preparedInput);
403 }),
404 onSuccess: ({ environmentId, input }, registry) =>
405 Effect.sync(() => registry.refresh(preview({ environmentId, input }))),
406 scheduler: commandScheduler,
407 concurrency: serialPerEnvironment,
408 }),
409 update: createEnvironmentRpcCommand(runtime, {
410 label: "environment-data:pull-requests:update",
411 tag: WS_METHODS.pullRequestsUpdate,
412 execute: (input) => routedRequest(WS_METHODS.pullRequestsUpdate, input),
413 onSuccess: (target, registry) => Effect.sync(() => registry.refresh(preview(target))),
414 scheduler: commandScheduler,
415 concurrency: serialPerEnvironment,
416 }),
417 comment: createEnvironmentRpcCommand(runtime, {
418 label: "environment-data:pull-requests:comment",
419 tag: WS_METHODS.pullRequestsComment,
420 execute: (input) => routedRequest(WS_METHODS.pullRequestsComment, input),
421 scheduler: commandScheduler,
422 concurrency: serialPerEnvironment,
423 }),
424 updateComment: createEnvironmentRpcCommand(runtime, {
425 label: "environment-data:pull-requests:update-comment",
426 tag: WS_METHODS.pullRequestsUpdateComment,
427 execute: (input) => routedRequest(WS_METHODS.pullRequestsUpdateComment, input),
428 scheduler: commandScheduler,
429 concurrency: serialPerEnvironment,
430 onSuccess: ({ environmentId, input: { projectId, host, repository, number } }, registry) =>
431 Effect.sync(() =>
432 registry.refresh(
433 activity({
434 environmentId,
435 input: { projectId, ...(host === undefined ? {} : { host }), repository, number },
436 }),
437 ),
438 ),
439 }),
440 submitReview: createEnvironmentRpcCommand(runtime, {
441 label: "environment-data:pull-requests:submit-review",
442 tag: WS_METHODS.pullRequestsSubmitReview,
443 execute: (input) => routedRequest(WS_METHODS.pullRequestsSubmitReview, input),
444 scheduler: commandScheduler,
445 concurrency: serialPerEnvironment,
446 }),
447 replyToThread: createEnvironmentRpcCommand(runtime, {
448 label: "environment-data:pull-requests:reply-to-thread",
449 tag: WS_METHODS.pullRequestsReplyToThread,
450 execute: (input) => routedRequest(WS_METHODS.pullRequestsReplyToThread, input),
451 scheduler: commandScheduler,
452 concurrency: serialPerEnvironment,
453 }),
454 /**
455 * Its own query rather than part of the detail: the people who may be asked are only wanted
456 * once somebody opens the reviewer menu, so this atom is read then and not before. Kept fresh
457 * for a minute, because who has access to a repository changes far more slowly than the
458 * change request it is being read for.
459 */
460 reviewerCandidates,
461 requestReviewers: createEnvironmentRpcCommand(runtime, {
462 label: "environment-data:pull-requests:request-reviewers",
463 tag: WS_METHODS.pullRequestsRequestReviewers,
464 execute: (input) => routedRequest(WS_METHODS.pullRequestsRequestReviewers, input),
465 scheduler: commandScheduler,
466 concurrency: serialPerEnvironment,
467 onSuccess: (target, registry) =>
468 Effect.sync(() => {
469 const { reviewers, requested } = target.input;
470 const candidatesAtom = reviewerCandidates(target);
471 const candidates = Option.getOrNull(AsyncResult.value(registry.get(candidatesAtom)));
472 const selected =
473 candidates?.candidates.filter((candidate) =>
474 reviewers.some(
475 (reviewer) => reviewer.id === candidate.id && reviewer.kind === candidate.kind,
476 ),
477 ) ?? [];
478 const missingIdentities = selected.length < reviewers.length;
479 updateCached(registry, candidatesAtom, (value) => ({
480 ...value,
481 candidates: value.candidates.map((candidate) =>
482 selected.includes(candidate) ? { ...candidate, isRequested: requested } : candidate,
483 ),
484 }));
485 const selectedLogins = new Set(
486 selected.map((candidate) => candidate.login.toLowerCase()),
487 );
488 const updateReviewers = (
489 actors: ReadonlyArray<PullRequestActor>,
490 keep = (_actor: PullRequestActor) => false,
491 ) =>
492 requested
493 ? [
494 ...actors,
495 ...selected
496 .filter(
497 (candidate) =>
498 !actors.some(
499 (actor) => actor.login.toLowerCase() === candidate.login.toLowerCase(),
500 ),
501 )
502 .map(({ login, name, avatarUrl }) => ({ login, name, avatarUrl })),
503 ]
504 : actors.filter(
505 (actor) => !selectedLogins.has(actor.login.toLowerCase()) || keep(actor),
506 );
507 updateCached(
508 registry,
509 detail(target),
510 (value) => ({
511 ...value,
512 reviewers: updateReviewers(value.reviewers),
513 }),
514 missingIdentities,
515 );
516 updateCached(
517 registry,
518 activity(target),
519 (value) => ({
520 ...value,
521 reviewers:
522 value.reviewers === undefined
523 ? undefined
524 : updateReviewers(value.reviewers, (actor) =>
525 value.comments.some(
526 (comment) =>
527 (comment.kind === "review" || comment.kind === "review-comment") &&
528 comment.author?.login.toLowerCase() === actor.login.toLowerCase(),
529 ),
530 ),
531 }),
532 missingIdentities,
533 );
534 }),
535 }),
536 reviewGuide,
537 /** Runs a model on the environment; never fired without the reader asking for it. */
538 generateReviewGuide: createEnvironmentRpcCommand(runtime, {
539 label: "environment-data:pull-requests:generate-review-guide",
540 tag: WS_METHODS.pullRequestsGenerateReviewGuide,
541 execute: (input) => routedRequest(WS_METHODS.pullRequestsGenerateReviewGuide, input),
542 onSuccess: (target, registry, result) =>
543 Effect.sync(() => {
544 // The command returns the accepted run. Publish it before starting ends so readers
545 // never fall back to the empty/failed state while the follow-up query is in flight.
546 updateCached(registry, reviewGuide(target), () => result, true);
547 }),
548 }),
549 /** Read when the label menu opens, and kept for a minute, like the reviewer candidates. */
550 labelCandidates,
551 setLabels: createEnvironmentRpcCommand(runtime, {
552 label: "environment-data:pull-requests:set-labels",
553 tag: WS_METHODS.pullRequestsSetLabels,
554 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetLabels, input),
555 scheduler: commandScheduler,
556 concurrency: serialPerEnvironment,
557 onSuccess: (target, registry) =>
558 Effect.sync(() => {
559 const { labels, applied } = target.input;
560 const candidatesAtom = labelCandidates(target);
561 const candidates = Option.getOrNull(AsyncResult.value(registry.get(candidatesAtom)));
562 const names = new Set(labels);
563 updateCached(registry, candidatesAtom, (value) => ({
564 ...value,
565 candidates: value.candidates.map((candidate) =>
566 names.has(candidate.name) ? { ...candidate, isApplied: applied } : candidate,
567 ),
568 }));
569 updateCached(registry, detail(target), (value) => ({
570 ...value,
571 labels: applied
572 ? [
573 ...value.labels,
574 ...labels
575 .filter((name) => !value.labels.some((label) => label.name === name))
576 .map((name) => ({
577 name,
578 color:
579 candidates?.candidates.find((candidate) => candidate.name === name)
580 ?.color ?? null,
581 })),
582 ]
583 : value.labels.filter((label) => !names.has(label.name)),
584 }));
585 }),
586 }),
587 setThreadResolution: createEnvironmentRpcCommand(runtime, {
588 label: "environment-data:pull-requests:set-thread-resolution",
589 tag: WS_METHODS.pullRequestsSetThreadResolution,
590 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetThreadResolution, input),
591 scheduler: commandScheduler,
592 concurrency: serialPerEnvironment,
593 }),
594 setReaction: createEnvironmentRpcCommand(runtime, {
595 label: "environment-data:pull-requests:set-reaction",
596 tag: WS_METHODS.pullRequestsSetReaction,
597 execute: (input) => routedRequest(WS_METHODS.pullRequestsSetReaction, input),
598 scheduler: commandScheduler,
599 concurrency: serialPerEnvironment,
600 }),
601 /**
602 * Explicit refresh: forget the server's cached answers, then re-run the reads. A separate
603 * request rather than a flag on a read, so only a person's refresh spends host requests
604 * while every silent re-read shares the cache.
605 */
606 invalidate: createEnvironmentRpcCommand(runtime, {
607 label: "environment-data:pull-requests:invalidate",
608 tag: WS_METHODS.pullRequestsInvalidate,
609 execute: (input) => routedRequest(WS_METHODS.pullRequestsInvalidate, input),
610 onSuccess: ({ environmentId, input }, registry) =>
611 Effect.sync(() => {
612 if (input.reference !== undefined) {
613 registry.refresh(preview({ environmentId, input: input.reference }));
614 }
615 }),
616 scheduler: commandScheduler,
617 concurrency: serialPerEnvironment,
618 }),
619 };