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

pullRequests.test.ts

1,378 lines54.7 KB

1import {
2 EnvironmentId,
3 ProjectId,
4 PullRequestOperationError,
5 WS_METHODS,
6 type PullRequestStack,
7} from "@t3tools/contracts";
8import { expect, it } from "@effect/vitest";
9import * as Data from "effect/Data";
10import * as Deferred from "effect/Deferred";
11import * as Fiber from "effect/Fiber";
12import * as TestClock from "effect/testing/TestClock";
13import * as Effect from "effect/Effect";
14import * as Latch from "effect/Latch";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as PubSub from "effect/PubSub";
18import * as Stream from "effect/Stream";
19import * as SubscriptionRef from "effect/SubscriptionRef";
20import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
21​
22import {
23 AVAILABLE_CONNECTION_STATE,
24 ConnectionTransientError,
25 PrimaryConnectionTarget,
26 SshConnectionTarget,
27 type PreparedConnection,
28 type SupervisorConnectionState,
29} from "../connection/model.ts";
30import * as EnvironmentRegistry from "../connection/registry.ts";
31import { SshConnectionProfile, type ConnectionCatalogEntry } from "../connection/catalog.ts";
32import { ConnectionProfileStore } from "../connection/profileStore.ts";
33import * as EnvironmentSupervisor from "../connection/supervisor.ts";
34import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
35import type { RpcSession } from "../rpc/session.ts";
36import {
37 createLinkedPullRequestSummaryAtomFamily,
38 createPullRequestEnvironmentAtoms,
39 createPullRequestStackAtomFamily,
40} from "./pullRequests.ts";
41import { PullRequestDiffLoader } from "./pullRequestDiffHttp.ts";
42import { executeAtomQuery } from "./runtime.ts";
43import { createPullRequestRouter } from "./pullRequestRouting.ts";
44import { GitHubRoutingPermissions } from "../connection/githubRoutingPermissions.ts";
45​
46const trustedRouting = {
47 get: () => Effect.succeed("read-write" as const),
48 changes: Stream.empty,
49 set: () => Effect.void,
50 forget: () => Effect.void,
51};
52​
53class MutationRefused extends Data.TaggedError("MutationRefused") {}
54​
55for (const scenario of [
56 "prefers the local environment with the same github account",
57 "falls back before mutation when the local account differs",
58 "never retries an ambiguous mutation failure",
59 "returns a fast local source read without checking alternate identities",
60 "keeps single-environment requests free of identity lookups",
61 "keeps a local origin ahead of another local environment",
62 "keeps mutations on an old origin server without retrying them",
63 "skips an old alternate server before dispatching a mutation",
64 "returns a successful mutation when source invalidation stalls",
65 "does not dispatch after routing permission is revoked during the probe",
66 "keeps mutations on the origin when the alternate is disabled",
67 "does not dispatch after the alternate is disabled during the probe",
68 "preserves a local source account rejection when alternate accounts differ",
69] as const) {
70 (scenario === "returns a successful mutation when source invalidation stalls"
71 ? it.live
72 : it.effect)(scenario, () =>
73 Effect.scoped(
74 Effect.gen(function* () {
75 const calls: string[] = [];
76 const inputs: unknown[] = [];
77 let trusted = true;
78 let disableAlternate = Effect.void;
79 const switchedAccount =
80 scenario === "preserves a local source account rejection when alternate accounts differ";
81 const mismatch =
82 scenario === "falls back before mutation when the local account differs" ||
83 switchedAccount;
84 const ambiguous = scenario === "never retries an ambiguous mutation failure";
85 const reading =
86 scenario === "returns a fast local source read without checking alternate identities";
87 const single = scenario === "keeps single-environment requests free of identity lookups";
88 const localOrigin =
89 scenario === "keeps a local origin ahead of another local environment" ||
90 switchedAccount ||
91 reading;
92 const oldOrigin =
93 scenario === "keeps mutations on an old origin server without retrying them";
94 const oldAlternate =
95 scenario === "skips an old alternate server before dispatching a mutation";
96 const failure = new PullRequestOperationError({
97 operation: switchedAccount ? "routeIdentity" : "runAction",
98 detail: "connection lost after dispatch",
99 });
100 const clientFor = (local: boolean) => {
101 const name = local ? "local" : "origin";
102 return {
103 [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: (
104 input: unknown,
105 ) =>
106 Effect.gen(function* () {
107 if (local) expect(input).toEqual({ host: "github.com" });
108 calls.push(`${name}:identity`);
109 if (
110 local &&
111 scenario === "does not dispatch after the alternate is disabled during the probe"
112 )
113 yield* disableAlternate;
114 if (
115 local &&
116 scenario ===
117 "does not dispatch after routing permission is revoked during the probe"
118 )
119 trusted = false;
120 if ((!local && oldOrigin) || (local && oldAlternate)) {
121 return yield* Effect.die(
122 `Unknown request tag: ${WS_METHODS.pullRequestsRouting}`,
123 );
124 }
125 return {
126 host: "github.com",
127 provider: "github",
128 viewer: "maria-rcks",
129 accountId: local && mismatch ? "456" : "123",
130 };
131 }),
132 [WS_METHODS.pullRequestsRunAction]: (input: unknown) =>
133 Effect.gen(function* () {
134 calls.push(`${name}:mutation`);
135 inputs.push(input);
136 if (
137 !local &&
138 switchedAccount &&
139 (input as { expectedAccountId?: string }).expectedAccountId === "123"
140 )
141 return yield* failure;
142 if (local && ambiguous) return yield* failure;
143 }),
144 [WS_METHODS.pullRequestsSummary]: (input: { allowStale?: boolean }) =>
145 Effect.gen(function* () {
146 calls.push(`${name}:read`);
147 expect(input.allowStale).toBe(false);
148 if (local) return yield* failure;
149 return null;
150 }),
151 [WS_METHODS.pullRequestsInvalidate]: () =>
152 Effect.gen(function* () {
153 calls.push(`${name}:invalidate`);
154 if (
155 !local &&
156 scenario === "returns a successful mutation when source invalidation stalls"
157 ) {
158 return yield* Effect.never;
159 }
160 }),
161 } as unknown as WsRpcProtocolClient;
162 };
163 const { environmentRegistry, supervisor } = yield* makeTestRuntime(
164 clientFor(false),
165 single ? undefined : clientFor(true),
166 localOrigin,
167 );
168 disableAlternate = SubscriptionRef.update(
169 environmentRegistry.entries,
170 (entries) =>
171 new Map(
172 [...entries].map(([id, entry]) => [
173 id,
174 id === TARGET.environmentId ? entry : { ...entry, enabled: false },
175 ]),
176 ),
177 );
178 const disabled =
179 scenario === "keeps mutations on the origin when the alternate is disabled";
180 const disabledDuringProbe =
181 scenario === "does not dispatch after the alternate is disabled during the probe";
182 if (disabled) yield* disableAlternate;
183 const input = {
184 projectId: ProjectId.make("project-1"),
185 host: "github.com",
186 repository: "acme/web",
187 number: 7,
188 action: "merge" as const,
189 };
190 const route = createPullRequestRouter();
191 const result = yield* (
192 reading
193 ? route(WS_METHODS.pullRequestsSummary, input)
194 : route(WS_METHODS.pullRequestsRunAction, input)
195 ).pipe(
196 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
197 Effect.provideService(GitHubRoutingPermissions, {
198 ...trustedRouting,
199 get: () => Effect.succeed(trusted ? "read-write" : "off"),
200 }),
201 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
202 Effect.result,
203 );
204​
205 if (switchedAccount) {
206 expect(result).toMatchObject({ _tag: "Failure", failure });
207 expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["origin:mutation"]);
208 expect(inputs).toEqual([{ ...input, expectedAccountId: "123" }]);
209 } else if (ambiguous) {
210 expect(result).toMatchObject({ _tag: "Failure", failure });
211 expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["local:mutation"]);
212 } else {
213 expect(result._tag).toBe("Success");
214 if (single || disabled) {
215 expect(calls.filter((call) => !call.endsWith(":invalidate"))).toEqual([
216 "origin:mutation",
217 ]);
218 } else if (reading) expect(calls).toEqual(["origin:read"]);
219 else if (
220 mismatch ||
221 localOrigin ||
222 oldOrigin ||
223 oldAlternate ||
224 !trusted ||
225 disabledDuringProbe
226 )
227 expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["origin:mutation"]);
228 else {
229 expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["local:mutation"]);
230 expect(calls).toContain("origin:invalidate");
231 expect(inputs).toEqual([{ ...input, expectedAccountId: "123" }]);
232 }
233 }
234 }),
235 ),
236 );
238​
239for (const provider of ["github", "gitlab", "bitbucket", "azure-devops"] as const) {
240 it.effect(`routes ${provider} viewed marks to their storage environment`, () =>
241 Effect.scoped(
242 Effect.gen(function* () {
243 const reference = {
244 projectId: ProjectId.make("project-1"),
245 host: "github.com",
246 repository: "acme/web",
247 number: 7,
248 };
249 const calls: { environment: string; operation: string; input: unknown }[] = [];
250 const clientFor = (environment: string) =>
251 ({
252 [WS_METHODS.pullRequestsRouting]: () =>
253 Effect.succeed({
254 host: reference.host,
255 provider,
256 accountId: "123",
257 viewer: "maria-rcks",
258 }),
259 [WS_METHODS.pullRequestsRoutingIdentity]: () =>
260 Effect.succeed({
261 host: reference.host,
262 provider,
263 accountId: "123",
264 viewer: "maria-rcks",
265 }),
266 [WS_METHODS.pullRequestsFilesViewed]: (input: unknown) =>
267 Effect.sync(() => {
268 calls.push({ environment, operation: "read", input });
269 return { files: [{ path: "a.ts", state: "viewed" }], truncated: false };
270 }),
271 [WS_METHODS.pullRequestsSetFilesViewed]: (input: unknown) =>
272 Effect.sync(() => {
273 calls.push({ environment, operation: "write", input });
274 }),
275 [WS_METHODS.pullRequestsInvalidate]: (input: unknown) =>
276 Effect.sync(() => {
277 calls.push({ environment, operation: "invalidate", input });
278 }),
279 }) as unknown as WsRpcProtocolClient;
280 const { environmentRegistry, supervisor } = yield* makeTestRuntime(
281 clientFor("origin"),
282 clientFor("local"),
283 );
284 const files = [{ path: "a.ts", viewed: false }];
285 const route = createPullRequestRouter();
286 yield* Effect.gen(function* () {
287 expect(yield* route(WS_METHODS.pullRequestsFilesViewed, reference)).toEqual({
288 files: [{ path: "a.ts", state: "viewed" }],
289 truncated: false,
290 });
291 yield* route(WS_METHODS.pullRequestsSetFilesViewed, { ...reference, files });
292 }).pipe(
293 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
294 Effect.provideService(GitHubRoutingPermissions, trustedRouting),
295 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
296 );
297 const environment = provider === "github" ? "local" : "origin";
298 const guard = provider === "github" ? { expectedAccountId: "123" } : {};
299 expect(calls.filter((call) => call.operation !== "invalidate")).toEqual([
300 { environment, operation: "read", input: { ...reference, allowStale: false, ...guard } },
301 { environment, operation: "write", input: { ...reference, files, ...guard } },
302 ]);
303 const invalidations = calls.filter((call) => call.operation === "invalidate");
304 if (provider === "github") expect(invalidations.length).toBeGreaterThan(0);
305 else expect(invalidations).toEqual([]);
306 for (const call of invalidations) {
307 expect(call.input).toEqual({
308 reference: expect.objectContaining(reference),
309 filesViewedOnly: true,
310 });
311 }
312 }),
313 ),
314 );
316​
317const TARGET = new PrimaryConnectionTarget({
318 environmentId: EnvironmentId.make("environment-1"),
319 label: "Test environment",
320 httpBaseUrl: "https://environment.example.test",
321 wsBaseUrl: "wss://environment.example.test",
322});
323​
324function session(client: WsRpcProtocolClient): RpcSession {
325 return {
326 client: {
327 ...client,
328 [WS_METHODS.pullRequestsInvalidate]:
329 client[WS_METHODS.pullRequestsInvalidate] ?? (() => Effect.void),
330 },
331 initialConfig: Effect.never,
332 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
333 ready: Effect.void,
334 probe: Effect.void,
335 closed: Effect.never,
336 };
338​
339const makeTestRuntime = Effect.fn("makeTestRuntime")(function* (
340 client: WsRpcProtocolClient,
341 localClient?: WsRpcProtocolClient,
342 localOrigin = false,
343) {
344 const originTarget = localOrigin
345 ? new PrimaryConnectionTarget({
346 ...TARGET,
347 httpBaseUrl: "http://localhost:3774",
348 wsBaseUrl: "ws://localhost:3774",
349 })
350 : TARGET;
351 const connectionState: SupervisorConnectionState = {
352 ...AVAILABLE_CONNECTION_STATE,
353 desired: true,
354 network: "online",
355 phase: "connected",
356 attempt: 1,
357 generation: 1,
358 };
359 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
360 target: originTarget,
361 state: yield* SubscriptionRef.make(connectionState),
362 session: yield* SubscriptionRef.make(Option.some(session(client))),
363 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
364 connect: Effect.void,
365 disconnect: Effect.void,
366 retryNow: Effect.void,
367 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
368 const localTarget = new PrimaryConnectionTarget({
369 environmentId: EnvironmentId.make("local-environment"),
370 label: "Local environment",
371 httpBaseUrl: "http://localhost:3773",
372 wsBaseUrl: "ws://localhost:3773",
373 });
374 const localSupervisor = {
375 ...supervisor,
376 target: localTarget,
377 session: yield* SubscriptionRef.make(Option.some(session(localClient ?? client))),
378 };
379 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
380 entries: yield* SubscriptionRef.make<ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>>(
381 new Map([
382 [
383 originTarget.environmentId,
384 { target: originTarget, profile: Option.none(), enabled: true },
385 ],
386 ...(localClient === undefined
387 ? []
388 : [
389 [
390 localTarget.environmentId,
391 { target: localTarget, profile: Option.none(), enabled: true },
392 ] as const,
393 ]),
394 ]),
395 ),
396 run: (environmentId, effect) =>
397 Effect.provideService(
398 effect,
399 EnvironmentSupervisor.EnvironmentSupervisor,
400 environmentId === localTarget.environmentId ? localSupervisor : supervisor,
401 ),
402 runStream: (_environmentId, stream) =>
403 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
404 followStream: (_environmentId, stream) =>
405 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
406 } as EnvironmentRegistry.EnvironmentRegistry["Service"]);
407 const runtime = Atom.runtime(
408 Layer.merge(
409 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
410 Layer.succeed(
411 PullRequestDiffLoader,
412 PullRequestDiffLoader.of({ load: () => Effect.die("unused") }),
413 ),
414 ),
415 );
416 const atoms = createPullRequestEnvironmentAtoms(runtime);
417 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
418 Effect.sync(() => registry.dispose()),
419 );
420 return { runtime, atoms, registry, environmentRegistry, supervisor };
421});
422​
423for (const permission of ["default", "origin-off", "destination-off", "read-only"] as const) {
424 it.effect(`does not probe another environment with ${permission} routing permission`, () =>
425 Effect.scoped(
426 Effect.gen(function* () {
427 const calls: string[] = [];
428 const failure = new PullRequestOperationError({
429 operation: "summary",
430 detail: "source failed",
431 });
432 const client = {
433 [WS_METHODS.pullRequestsSummary]: () =>
434 Effect.suspend(() => {
435 calls.push("source-read");
436 return Effect.fail(failure);
437 }),
438 [WS_METHODS.pullRequestsRunAction]: () =>
439 Effect.sync(() => {
440 calls.push("source-write");
441 }),
442 } as unknown as WsRpcProtocolClient;
443 const alternate = {
444 [WS_METHODS.pullRequestsRoutingIdentity]: () =>
445 Effect.die("untrusted environment was contacted"),
446 } as unknown as WsRpcProtocolClient;
447 const { environmentRegistry, supervisor } = yield* makeTestRuntime(client, alternate);
448 const ref = {
449 projectId: ProjectId.make("project-1"),
450 repository: "private/repo",
451 number: 7,
452 };
453 const request = Effect.gen(function* () {
454 const route = createPullRequestRouter();
455 if (permission !== "read-only")
456 yield* route(WS_METHODS.pullRequestsSummary, ref).pipe(Effect.flip);
457 yield* route(WS_METHODS.pullRequestsRunAction, { ...ref, action: "merge" });
458 }).pipe(
459 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
460 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
461 );
462 yield* permission === "default"
463 ? request
464 : request.pipe(
465 Effect.provideService(GitHubRoutingPermissions, {
466 ...trustedRouting,
467 get: (entry) =>
468 Effect.succeed(
469 permission === "read-only"
470 ? "read"
471 : (entry.target.environmentId === TARGET.environmentId) ===
472 (permission === "origin-off")
473 ? "off"
474 : "read-write",
475 ),
476 }),
477 );
478 expect(calls).toEqual(
479 permission === "read-only" ? ["source-write"] : ["source-read", "source-write"],
480 );
481 }),
482 ),
483 );
485​
486for (const side of ["origin", "destination"] as const) {
487 for (const stored of ["matching", "changed", "missing", "unavailable", "failed"] as const) {
488 it.effect(`checks the current ${side} SSH profile before routing with ${stored} storage`, () =>
489 Effect.scoped(
490 Effect.gen(function* () {
491 const calls: string[] = [];
492 const identity = {
493 host: "github.com",
494 provider: "github",
495 viewer: "maria",
496 accountId: "123",
497 };
498 const client = {
499 [WS_METHODS.pullRequestsRouting]: () =>
500 Effect.sync(() => {
501 calls.push("source-probe");
502 return identity;
503 }),
504 [WS_METHODS.pullRequestsRunAction]: (input: { expectedAccountId?: string }) =>
505 Effect.gen(function* () {
506 if (input.expectedAccountId !== undefined) {
507 return yield* new PullRequestOperationError({
508 operation: "routeIdentity",
509 detail: "Source guard refused.",
510 });
511 }
512 calls.push("source-write");
513 }),
514 [WS_METHODS.pullRequestsInvalidate]: () => Effect.void,
515 } as unknown as WsRpcProtocolClient;
516 const alternate = {
517 [WS_METHODS.pullRequestsRoutingIdentity]: () =>
518 Effect.sync(() => {
519 calls.push("alternate-probe");
520 return identity;
521 }),
522 [WS_METHODS.pullRequestsRunAction]: () =>
523 Effect.sync(() => {
524 calls.push("alternate-write");
525 }),
526 [WS_METHODS.pullRequestsInvalidate]: () => Effect.void,
527 } as unknown as WsRpcProtocolClient;
528 const { environmentRegistry, supervisor } = yield* makeTestRuntime(client, alternate);
529 const environmentId =
530 side === "origin" ? TARGET.environmentId : EnvironmentId.make("local-environment");
531 const profile = new SshConnectionProfile({
532 connectionId: "ssh-1",
533 environmentId,
534 label: "SSH",
535 target: { alias: "work", hostname: "work.example.test", username: "maria", port: 22 },
536 });
537 yield* SubscriptionRef.update(environmentRegistry.entries, (entries) =>
538 new Map(entries).set(environmentId, {
539 target: new SshConnectionTarget({
540 environmentId,
541 connectionId: profile.connectionId,
542 label: "SSH",
543 }),
544 profile: Option.some(profile),
545 enabled: true,
546 }),
547 );
548 const read = Effect.suspend(() =>
549 stored === "failed"
550 ? Effect.fail(
551 new ConnectionTransientError({
552 reason: "remote-unavailable",
553 detail: "Profile storage unavailable.",
554 }),
555 )
556 : Effect.succeed(
557 stored === "missing"
558 ? Option.none()
559 : Option.some(
560 stored === "changed"
561 ? new SshConnectionProfile({
562 ...profile,
563 target: { ...profile.target, hostname: "replacement.example.test" },
564 })
565 : profile,
566 ),
567 ),
568 );
569 const route = createPullRequestRouter()(WS_METHODS.pullRequestsRunAction, {
570 projectId: ProjectId.make("project-1"),
571 repository: "private/repo",
572 number: 7,
573 action: "merge",
574 }).pipe(
575 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
576 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
577 // This also represents a user enabling the stale catalog entry after re-resolution.
578 Effect.provideService(GitHubRoutingPermissions, trustedRouting),
579 );
580 yield* stored === "unavailable"
581 ? route
582 : route.pipe(
583 Effect.provideService(ConnectionProfileStore, {
584 get: () => read,
585 put: () => Effect.die("unused"),
586 remove: () => Effect.die("unused"),
587 }),
588 );
589 expect(calls).toEqual(
590 stored === "matching"
591 ? ["source-probe", "alternate-probe", "alternate-write"]
592 : ["source-write"],
593 );
594 }),
595 ),
596 );
597 }
599​
600for (const probe of ["origin", "alternate"] as const) {
601 it.live(`bounds a stalled ${probe} metadata probe without repeating a strict source read`, () =>
602 Effect.scoped(
603 Effect.gen(function* () {
604 let sourceReads = 0;
605 const identity = {
606 host: "github.com",
607 provider: "github",
608 viewer: "maria",
609 accountId: "123",
610 };
611 const client = {
612 [WS_METHODS.pullRequestsRouting]: () =>
613 probe === "origin" ? Effect.never : Effect.succeed(identity),
614 [WS_METHODS.pullRequestsSummary]: () =>
615 Effect.suspend(() => {
616 sourceReads += 1;
617 return Effect.fail(
618 new PullRequestOperationError({ operation: "summary", detail: "source failed" }),
619 );
620 }),
621 } as unknown as WsRpcProtocolClient;
622 const alternate = {
623 [WS_METHODS.pullRequestsRoutingIdentity]: () => Effect.never,
624 } as unknown as WsRpcProtocolClient;
625 const { environmentRegistry, supervisor } = yield* makeTestRuntime(client, alternate);
626 const error = yield* createPullRequestRouter()(WS_METHODS.pullRequestsSummary, {
627 projectId: ProjectId.make("project-1"),
628 repository: "acme/web",
629 number: 7,
630 allowStale: false,
631 }).pipe(
632 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
633 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
634 Effect.provideService(GitHubRoutingPermissions, trustedRouting),
635 Effect.flip,
636 );
637 expect(error._tag).toBe("PullRequestOperationError");
638 expect(sourceReads).toBe(1);
639 }),
640 ),
641 );
643​
644for (const source of ["pending", "pending-local", "failed-local", "failed", "offline"] as const) {
645 it.effect(
646 source === "offline"
647 ? "returns held source data only after both fresh paths fail"
648 : `uses one shared reader with a ${source} source`,
649 () =>
650 Effect.scoped(
651 Effect.gen(function* () {
652 const started = yield* Deferred.make<void>();
653 const calls: string[] = [];
654 const clientFor = (local: boolean) =>
655 ({
656 [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]:
657 () =>
658 Effect.succeed({
659 host: "github.com",
660 provider: "github",
661 viewer: "maria-rcks",
662 accountId: "123",
663 }),
664 [WS_METHODS.pullRequestsSummary]: (input: { allowStale?: boolean }) =>
665 Effect.gen(function* () {
666 calls.push(local ? "local" : input.allowStale === false ? "origin" : "held");
667 if (source === "offline" && !local && input.allowStale === undefined) {
668 return { state: "open" };
669 }
670 expect(input.allowStale).toBe(false);
671 if (local && source !== "offline") return null;
672 if (source !== "pending" && source !== "pending-local")
673 return yield* new PullRequestOperationError({
674 operation: "summary",
675 detail: "github unreachable",
676 });
677 yield* Deferred.succeed(started, undefined);
678 return yield* Effect.never;
679 }),
680 }) as unknown as WsRpcProtocolClient;
681 const { environmentRegistry, supervisor } = yield* makeTestRuntime(
682 clientFor(false),
683 clientFor(true),
684 source === "failed-local" || source === "pending-local",
685 );
686 const request = createPullRequestRouter()(WS_METHODS.pullRequestsSummary, {
687 projectId: ProjectId.make("project-1"),
688 repository: "acme/web",
689 number: 7,
690 }).pipe(
691 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
692 Effect.provideService(GitHubRoutingPermissions, trustedRouting),
693 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
694 );
695 const fiber = yield* request.pipe(Effect.forkChild);
696 if (source === "pending-local") {
697 yield* Deferred.await(started);
698 yield* TestClock.adjust("30 seconds");
699 }
700 const result = yield* Fiber.join(fiber);
701 if (source === "offline") {
702 expect(result).toEqual({ state: "open" });
703 expect(calls).toEqual(["local", "origin", "held"]);
704 } else {
705 expect(result).toBeNull();
706 expect(calls).toEqual(
707 source === "failed-local" || source === "pending-local"
708 ? ["origin", "local"]
709 : ["local"],
710 );
711 }
712 }),
713 ),
714 );
716​
717it.live("keeps source workspace metadata when an alternate answers a detail read", () =>
718 Effect.scoped(
719 Effect.gen(function* () {
720 const clientFor = (local: boolean) =>
721 ({
722 [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
723 Effect.succeed({
724 host: "github.com",
725 provider: "github",
726 viewer: "maria-rcks",
727 accountId: "123",
728 projectTitle: local ? "local project" : "source project",
729 workspaceRoot: local ? "/Users/local/repo" : "/srv/source/repo",
730 }),
731 [WS_METHODS.pullRequestsDetail]: () =>
732 local
733 ? Effect.succeed({
734 projectId: "local-project",
735 projectTitle: "local project",
736 workspaceRoot: "/Users/local/repo",
737 title: "github title",
738 })
739 : Effect.never,
740 }) as unknown as WsRpcProtocolClient;
741 const { environmentRegistry, supervisor } = yield* makeTestRuntime(
742 clientFor(false),
743 clientFor(true),
744 );
745 const result = yield* createPullRequestRouter()(WS_METHODS.pullRequestsDetail, {
746 projectId: ProjectId.make("project-1"),
747 repository: "acme/web",
748 number: 7,
749 }).pipe(
750 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
751 Effect.provideService(GitHubRoutingPermissions, trustedRouting),
752 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
753 );
754 expect(result).toEqual({
755 projectId: "project-1",
756 projectTitle: "source project",
757 workspaceRoot: "/srv/source/repo",
758 title: "github title",
759 });
760 }),
761 ),
762);
763​
764it.live(
765 "refreshes identity before writes and invalidates prior readers across router instances",
766 () =>
767 Effect.scoped(
768 Effect.gen(function* () {
769 let originAccountId = "123";
770 const mutations: { environment: string; expectedAccountId: string }[] = [];
771 const invalidations: { environment: string; input: unknown }[] = [];
772 const identities: string[] = [];
773 const clientFor = (local: boolean) => {
774 const environment = local ? "local" : "origin";
775 return {
776 [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
777 Effect.sync(() => {
778 identities.push(environment);
779 return {
780 host: "github.com",
781 provider: "github",
782 viewer: "maria-rcks",
783 accountId: local ? "123" : originAccountId,
784 };
785 }),
786 [WS_METHODS.pullRequestsSummary]: () => (local ? Effect.succeed(null) : Effect.never),
787 [WS_METHODS.pullRequestsRunAction]: (input: { expectedAccountId: string }) =>
788 Effect.sync(() => {
789 mutations.push({ environment, expectedAccountId: input.expectedAccountId });
790 }),
791 [WS_METHODS.pullRequestsInvalidate]: (input: unknown) =>
792 Effect.sync(() => {
793 invalidations.push({ environment, input });
794 }),
795 } as unknown as WsRpcProtocolClient;
796 };
797 const { environmentRegistry, supervisor } = yield* makeTestRuntime(
798 clientFor(false),
799 clientFor(true),
800 );
801 const reference = {
802 projectId: ProjectId.make("project-1"),
803 repository: "acme/web",
804 number: 7,
805 };
806 const hostedReference = { ...reference, host: "github.com", allowStale: false };
807 const route = createPullRequestRouter();
808 yield* Effect.gen(function* () {
809 yield* route(WS_METHODS.pullRequestsSummary, reference);
810 originAccountId = "456";
811 yield* route(WS_METHODS.pullRequestsRunAction, { ...reference, action: "merge" });
812​
813 expect(identities.filter((environment) => environment === "origin")).toHaveLength(2);
814 expect(mutations).toEqual([{ environment: "origin", expectedAccountId: "456" }]);
815 expect(invalidations).toEqual(
816 expect.arrayContaining([
817 { environment: "origin", input: { reference: expect.objectContaining(reference) } },
818 { environment: "origin", input: { reference: hostedReference } },
819 { environment: "local", input: { reference: hostedReference } },
820 { environment: "origin", input: {} },
821 { environment: "local", input: {} },
822 ]),
823 );
824​
825 invalidations.length = 0;
826 const refresh = createPullRequestRouter();
827 yield* refresh(WS_METHODS.pullRequestsInvalidate, { reference });
828 expect(invalidations).toContainEqual({
829 environment: "local",
830 input: { reference: hostedReference },
831 });
832​
833 invalidations.length = 0;
834 yield* refresh(WS_METHODS.pullRequestsInvalidate, {});
835 expect(invalidations).toContainEqual({ environment: "local", input: {} });
836 }).pipe(
837 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
838 Effect.provideService(GitHubRoutingPermissions, trustedRouting),
839 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
840 );
841 }),
842 ),
843);
844​
845it.effect("keeps concurrent diff file reads on different hosts separate", () =>
846 Effect.scoped(
847 Effect.gen(function* () {
848 const release = yield* Latch.make();
849 const started = yield* Latch.make();
850 const calls: string[] = [];
851 const client = {
852 [WS_METHODS.pullRequestsDiffFileContents]: (input: { readonly host: string }) =>
853 Effect.gen(function* () {
854 calls.push(input.host);
855 yield* started.open;
856 yield* release.await;
857 return { oldContents: "", newContents: input.host };
858 }),
859 } as unknown as WsRpcProtocolClient;
860 const { atoms, registry } = yield* makeTestRuntime(client);
861 const input = {
862 projectId: ProjectId.make("project-1"),
863 repository: "acme/web",
864 number: 1,
865 changeType: "change",
866 oldPath: "src/app.ts",
867 newPath: "src/app.ts",
868 } as const;
869 const first = atoms.diffFileContents.run(registry, {
870 environmentId: TARGET.environmentId,
871 input: { ...input, host: "github.com" },
872 });
873 yield* started.await;
874 const second = atoms.diffFileContents.run(registry, {
875 environmentId: TARGET.environmentId,
876 input: { ...input, host: "github.example.com" },
877 });
878 yield* release.open;
879​
880 const results = yield* Effect.promise(() => Promise.all([first, second]));
881 expect(results).toMatchObject([
882 { _tag: "Success", value: { newContents: "github.com" } },
883 { _tag: "Success", value: { newContents: "github.example.com" } },
884 ]);
885 expect(calls).toEqual(["github.com", "github.example.com"]);
886 }),
887 ),
888);
889​
890it.effect("shares close, reopen, and merge with an untouched client's mounted PR readers", () =>
891 Effect.scoped(
892 Effect.gen(function* () {
893 const revision = yield* SubscriptionRef.make(0);
894 let state: "open" | "closed" | "merged" = "open";
895 const client = {
896 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => SubscriptionRef.changes(revision),
897 [WS_METHODS.pullRequestsSummary]: () => Effect.sync(() => ({ state })),
898 [WS_METHODS.pullRequestsDetail]: () => Effect.sync(() => ({ state })),
899 [WS_METHODS.pullRequestsList]: () =>
900 Effect.sync(() => ({ entries: [{ number: 1, state }] })),
901 [WS_METHODS.pullRequestsRunAction]: (input: {
902 readonly action: "close" | "reopen" | "merge";
903 }) =>
904 Effect.gen(function* () {
905 state =
906 input.action === "close" ? "closed" : input.action === "merge" ? "merged" : "open";
907 yield* SubscriptionRef.update(revision, (value) => value + 1);
908 }),
909 } as unknown as WsRpcProtocolClient;
910 const writer = yield* makeTestRuntime(client);
911 const reader = yield* makeTestRuntime(client);
912 const target = {
913 environmentId: TARGET.environmentId,
914 input: {
915 projectId: ProjectId.make("project-1"),
916 host: "github.example.com",
917 repository: "acme/web",
918 number: 1,
919 },
920 };
921 const detail = reader.atoms.detail(target);
922 const summary = createLinkedPullRequestSummaryAtomFamily(
923 reader.runtime,
924 reader.atoms.refreshes,
925 )(target);
926 const list = reader.atoms.list({
927 environmentId: TARGET.environmentId,
928 input: { state: "all" },
929 });
930 const unmountDetail = reader.registry.mount(detail);
931 const unmountSummary = reader.registry.mount(summary);
932 const unmountList = reader.registry.mount(list);
933 yield* Effect.addFinalizer(() =>
934 Effect.sync(() => {
935 unmountDetail();
936 unmountSummary();
937 unmountList();
938 }),
939 );
940 expect((yield* AtomRegistry.getResult(reader.registry, detail)).state).toBe("open");
941 expect((yield* AtomRegistry.getResult(reader.registry, summary)).state).toBe("open");
942 expect((yield* AtomRegistry.getResult(reader.registry, list)).entries[0]?.state).toBe("open");
943​
944 for (const [action, expected] of [
945 ["close", "closed"],
946 ["reopen", "open"],
947 ["merge", "merged"],
948 ] as const) {
949 const detailChanged = Latch.makeUnsafe();
950 const summaryChanged = Latch.makeUnsafe();
951 const listChanged = Latch.makeUnsafe();
952 const stops = [
953 reader.registry.subscribe(detail, (result) => {
954 if (AsyncResult.isSuccess(result) && result.value.state === expected) {
955 detailChanged.openUnsafe();
956 }
957 }),
958 reader.registry.subscribe(summary, (result) => {
959 if (AsyncResult.isSuccess(result) && result.value.state === expected) {
960 summaryChanged.openUnsafe();
961 }
962 }),
963 reader.registry.subscribe(list, (result) => {
964 if (AsyncResult.isSuccess(result) && result.value.entries[0]?.state === expected) {
965 listChanged.openUnsafe();
966 }
967 }),
968 ];
969 yield* Effect.addFinalizer(() => Effect.sync(() => stops.forEach((stop) => stop())));
970 const result = yield* Effect.promise(() =>
971 writer.atoms.runAction.run(writer.registry, {
972 ...target,
973 input: { ...target.input, action },
974 }),
975 );
976 expect(AsyncResult.isSuccess(result)).toBe(true);
977 // The second client receives only the server push: no local refresh or timer tick.
978 yield* detailChanged.await;
979 yield* summaryChanged.await;
980 yield* listChanged.await;
981 expect((yield* AtomRegistry.getResult(reader.registry, detail)).state).toBe(expected);
982 expect((yield* AtomRegistry.getResult(reader.registry, summary)).state).toBe(expected);
983 expect((yield* AtomRegistry.getResult(reader.registry, list)).entries[0]?.state).toBe(
984 expected,
985 );
986 stops.forEach((stop) => stop());
987 }
988 }),
989 ),
990);
991​
992it.effect("refreshes pull request activity after a comment is updated", () =>
993 Effect.scoped(
994 Effect.gen(function* () {
995 const refreshEvents = yield* PubSub.unbounded<number>();
996 let commentBody = "old comment";
997 const client = {
998 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
999 [WS_METHODS.pullRequestsActivity]: () =>
1000 Effect.succeed({
1001 author: null,
1002 reviewers: [],
1003 comments: [
1005 id: "comment-1",
1006 kind: "issue-comment",
1007 author: null,
1008 body: commentBody,
1009 createdAt: "2026-08-24T00:00:00Z",
1010 url: null,
1011 path: null,
1012 reviewState: null,
1013 reactions: [],
1014 },
1015 ],
1016 commentCount: 1,
1017 commentsTruncated: false,
1018 reviewThreads: [],
1019 commits: [],
1020 reactions: [],
1021 }),
1022 [WS_METHODS.pullRequestsUpdateComment]: (input: { readonly body: string }) =>
1023 Effect.sync(() => {
1024 commentBody = input.body;
1025 }),
1026 } as unknown as WsRpcProtocolClient;
1027 const { atoms, registry } = yield* makeTestRuntime(client);
1028 const reference = {
1029 projectId: ProjectId.make("project-1"),
1030 host: "github.example.com",
1031 repository: "acme/web",
1032 number: 1,
1033 } as const;
1034 const activity = atoms.activity({ environmentId: TARGET.environmentId, input: reference });
1035 const unmount = registry.mount(activity);
1036 yield* Effect.addFinalizer(() => Effect.sync(unmount));
1037​
1038 const initial = yield* Effect.promise(() => executeAtomQuery(registry, activity));
1039 expect(AsyncResult.isSuccess(initial)).toBe(true);
1040 if (!AsyncResult.isSuccess(initial)) {
1041 return yield* Effect.die("activity did not load");
1043 expect(initial.value.comments[0]?.body).toBe("old comment");
1044​
1045 const update = yield* Effect.promise(() =>
1046 atoms.updateComment.run(registry, {
1047 environmentId: TARGET.environmentId,
1048 input: { ...reference, commentId: "comment-1", kind: "issue-comment", body: "updated" },
1049 }),
1050 );
1051​
1052 expect(AsyncResult.isSuccess(update)).toBe(true);
1053 expect(
1054 (yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true })).comments[0]
1055 ?.body,
1056 ).toBe("updated");
1057 const refreshed = Latch.makeUnsafe();
1058 const stop = registry.subscribe(activity, (result) => {
1059 if (AsyncResult.isSuccess(result) && result.value.comments[0]?.body === "after turn") {
1060 refreshed.openUnsafe();
1062 });
1063 yield* Effect.addFinalizer(() => Effect.sync(stop));
1064​
1065 commentBody = "after turn";
1066 yield* PubSub.publish(refreshEvents, 1);
1067 yield* refreshed.await;
1068​
1069 expect(
1070 (yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true })).comments[0]
1071 ?.body,
1072 ).toBe("after turn");
1073 }),
1074 ),
1076​
1077it.effect("updates cached labels after successful edits without rereading the host", () =>
1078 Effect.scoped(
1079 Effect.gen(function* () {
1080 let detailReads = 0;
1081 let candidateReads = 0;
1082 let refuse = false;
1083 let failDetail = false;
1084 const existing = { name: "existing", color: "111111" };
1085 const addedLabel = { name: "new", color: "abcdef" };
1086 const detailRefreshStarted = yield* Latch.make();
1087 const releaseDetailRefresh = yield* Latch.make();
1088 const client = {
1089 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
1090 [WS_METHODS.pullRequestsDetail]: () =>
1091 Effect.gen(function* () {
1092 detailReads++;
1093 if (failDetail) {
1094 yield* detailRefreshStarted.open;
1095 yield* releaseDetailRefresh.await;
1096 return yield* Effect.fail(new MutationRefused());
1098 return { title: "keep this title", labels: [existing] };
1099 }),
1100 [WS_METHODS.pullRequestsLabelCandidates]: () =>
1101 Effect.sync(() => {
1102 candidateReads++;
1103 return {
1104 candidates: [
1105 { ...existing, description: null, isApplied: true },
1106 { ...addedLabel, description: "description", isApplied: false },
1107 ],
1108 truncated: false,
1109 };
1110 }),
1111 [WS_METHODS.pullRequestsSetLabels]: () =>
1112 refuse ? Effect.fail(new MutationRefused()) : Effect.void,
1113 } as unknown as WsRpcProtocolClient;
1114 const { atoms, registry } = yield* makeTestRuntime(client);
1115 const target = {
1116 environmentId: TARGET.environmentId,
1117 input: {
1118 projectId: ProjectId.make("project-1"),
1119 repository: "acme/web",
1120 number: 1,
1121 host: "github.example.com",
1122 },
1123 };
1124 const detail = atoms.detail(target);
1125 const candidates = atoms.labelCandidates(target);
1126 registry.mount(detail);
1127 const unmountCandidates = registry.mount(candidates);
1128 yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
1129 yield* AtomRegistry.getResult(registry, candidates, { suspendOnWaiting: true });
1130​
1131 const added = yield* Effect.promise(() =>
1132 atoms.setLabels.run(registry, {
1133 ...target,
1134 input: {
1135 host: target.input.host,
1136 projectId: target.input.projectId,
1137 repository: target.input.repository,
1138 number: target.input.number,
1139 labels: ["new"],
1140 applied: true,
1141 },
1142 }),
1143 );
1144 expect(AsyncResult.isSuccess(added)).toBe(true);
1145 expect(yield* AtomRegistry.getResult(registry, detail)).toEqual({
1146 title: "keep this title",
1147 labels: [existing, addedLabel],
1148 });
1149 unmountCandidates();
1150 registry.mount(atoms.labelCandidates(target));
1151 expect((yield* AtomRegistry.getResult(registry, candidates)).candidates[1]).toEqual({
1152 ...addedLabel,
1153 description: "description",
1154 isApplied: true,
1155 });
1156​
1157 for (const name of ["existing", "new"]) {
1158 refuse = name === "new";
1159 const result = yield* Effect.promise(() =>
1160 atoms.setLabels.run(registry, {
1161 ...target,
1162 input: { ...target.input, labels: [name], applied: false },
1163 }),
1164 );
1165 expect(result._tag).toBe(refuse ? "Failure" : "Success");
1166 expect((yield* AtomRegistry.getResult(registry, detail)).labels).toEqual([addedLabel]);
1167 expect((yield* AtomRegistry.getResult(registry, candidates)).candidates).toMatchObject([
1168 { name: "existing", isApplied: false },
1169 { name: "new", isApplied: true },
1170 ]);
1172 expect(detailReads).toBe(1);
1173 expect(candidateReads).toBe(1);
1174​
1175 failDetail = true;
1176 registry.refresh(detail);
1177 yield* detailRefreshStarted.await;
1178 expect(registry.get(detail).waiting).toBe(true);
1179 expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).labels).toEqual([
1180 addedLabel,
1181 ]);
1182 yield* releaseDetailRefresh.open;
1183 yield* Effect.exit(AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true }));
1184 expect(AsyncResult.isFailure(registry.get(detail))).toBe(true);
1185 expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).labels).toEqual([
1186 addedLabel,
1187 ]);
1188 failDetail = false;
1189 registry.refresh(detail);
1190 expect(
1191 (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).labels,
1192 ).toEqual([existing]);
1193 expect(detailReads).toBe(3);
1194 }),
1195 ),
1197​
1198it.effect("updates reviewer requests and enriched reviewers without rereading the host", () =>
1199 Effect.scoped(
1200 Effect.gen(function* () {
1201 let reads = 0;
1202 let refuse = false;
1203 const actor = { login: "reviewer", name: "Reviewer", avatarUrl: null };
1204 const hostActor = { ...actor, login: "Reviewer" };
1205 let hostRequested = false;
1206 let reviewed = false;
1207 let pauseActivity = false;
1208 const activityStarted = yield* Latch.make();
1209 const client = {
1210 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
1211 [WS_METHODS.pullRequestsDetail]: () =>
1212 Effect.sync(() => {
1213 reads++;
1214 return { reviewers: hostRequested ? [hostActor] : [] };
1215 }),
1216 [WS_METHODS.pullRequestsActivity]: () =>
1217 Effect.gen(function* () {
1218 reads++;
1219 if (pauseActivity) {
1220 pauseActivity = false;
1221 yield* activityStarted.open;
1222 return yield* Effect.never;
1224 return {
1225 reviewers: hostRequested ? [hostActor] : [],
1226 comments: reviewed ? [{ kind: "review-comment", author: hostActor }] : [],
1227 };
1228 }),
1229 [WS_METHODS.pullRequestsReviewerCandidates]: (input: { number: number }) =>
1230 input.number === 2
1231 ? Effect.never
1232 : Effect.sync(() => {
1233 reads++;
1234 return {
1235 candidates: [{ ...actor, id: "12", kind: "user", isRequested: false }],
1236 truncated: false,
1237 };
1238 }),
1239 [WS_METHODS.pullRequestsRequestReviewers]: (input: { requested: boolean }) =>
1240 refuse
1241 ? Effect.fail(new MutationRefused())
1242 : Effect.sync(() => {
1243 hostRequested = input.requested;
1244 }),
1245 } as unknown as WsRpcProtocolClient;
1246 const { atoms, registry } = yield* makeTestRuntime(client);
1247 const target = {
1248 environmentId: TARGET.environmentId,
1249 input: {
1250 projectId: ProjectId.make("project-1"),
1251 repository: "acme/web",
1252 number: 1,
1253 host: "github.example.com",
1254 },
1255 };
1256 const detail = atoms.detail(target);
1257 const activity = atoms.activity(target);
1258 const candidates = atoms.reviewerCandidates(target);
1259 registry.mount(detail);
1260 registry.mount(activity);
1261 registry.mount(candidates);
1262 yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
1263 yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true });
1264 yield* AtomRegistry.getResult(registry, candidates, { suspendOnWaiting: true });
1265 const request = (requested: boolean, reference = target) =>
1266 Effect.promise(() =>
1267 atoms.requestReviewers.run(registry, {
1268 ...reference,
1269 input: { ...reference.input, reviewers: [{ id: "12", kind: "user" }], requested },
1270 }),
1271 );
1272 for (const operation of ["request", "refuse", "remove"]) {
1273 refuse = operation === "refuse";
1274 expect((yield* request(operation === "request"))._tag).toBe(refuse ? "Failure" : "Success");
1275 const expected = operation === "remove" ? [] : [actor];
1276 expect((yield* AtomRegistry.getResult(registry, detail)).reviewers).toEqual(expected);
1277 expect((yield* AtomRegistry.getResult(registry, activity)).reviewers).toEqual(expected);
1278 expect((yield* AtomRegistry.getResult(registry, candidates)).candidates).toMatchObject([
1279 { isRequested: operation !== "remove" },
1280 ]);
1282 expect(reads).toBe(3);
1283 // A slow activity read started before the write must not hide the new request.
1284 pauseActivity = true;
1285 registry.refresh(activity);
1286 yield* activityStarted.await;
1287 expect(AsyncResult.isSuccess(yield* request(true))).toBe(true);
1288 expect(
1289 (yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true })).reviewers,
1290 ).toEqual([hostActor]);
1291 expect(reads).toBe(5);
1292 expect(AsyncResult.isSuccess(yield* request(false))).toBe(true);
1293 expect((yield* AtomRegistry.getResult(registry, activity)).reviewers).toEqual([]);
1294​
1295 reviewed = true;
1296 yield* request(true);
1297 registry.refresh(activity);
1298 yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true });
1299 yield* request(false);
1300 expect((yield* AtomRegistry.getResult(registry, activity)).reviewers).toEqual([hostActor]);
1301​
1302 // A caller without an open picker still needs authoritative reviewer identities.
1303 const otherTarget = { ...target, input: { ...target.input, number: 2 } };
1304 const otherDetail = atoms.detail(otherTarget);
1305 registry.mount(otherDetail);
1306 yield* AtomRegistry.getResult(registry, otherDetail, { suspendOnWaiting: true });
1307 yield* request(true, otherTarget);
1308 expect(
1309 (yield* AtomRegistry.getResult(registry, otherDetail, { suspendOnWaiting: true }))
1310 .reviewers,
1311 ).toEqual([hostActor]);
1312 }),
1313 ),
1315​
1316it.effect("refreshes stack state after reopening and head SHAs after a turn", () =>
1317 Effect.scoped(
1318 Effect.gen(function* () {
1319 const refreshEvents = yield* PubSub.unbounded<number>();
1320 let state: "closed" | "open" = "closed";
1321 let headSha = "old-head";
1322 const client = {
1323 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
1324 [WS_METHODS.pullRequestsStack]: () =>
1325 Effect.sync(
1326 () =>
1327 ({
1328 id: "stack-1",
1329 number: 1,
1330 url: "https://github.com/acme/web/pull/1",
1331 base: "main",
1332 layers: [
1334 number: 1,
1335 headBranch: "feature",
1336 headSha,
1337 state,
1338 isDraft: false,
1339 },
1340 ],
1341 }) satisfies PullRequestStack,
1342 ),
1343 } as unknown as WsRpcProtocolClient;
1344 const { runtime, registry } = yield* makeTestRuntime(client);
1345 const stacks = createPullRequestStackAtomFamily(runtime);
1346 const stack = stacks({
1347 environmentId: TARGET.environmentId,
1348 input: {
1349 projectId: ProjectId.make("project-1"),
1350 repository: "acme/web",
1351 number: 1,
1352 },
1353 });
1354 const unmount = registry.mount(stack);
1355 yield* Effect.addFinalizer(() => Effect.sync(unmount));
1356 yield* Effect.promise(() => executeAtomQuery(registry, stack));
1357 expect((yield* AtomRegistry.getResult(registry, stack))?.layers[0]?.state).toBe("closed");
1358 state = "open";
1359 registry.refresh(stack);
1360 expect(
1361 (yield* AtomRegistry.getResult(registry, stack, { suspendOnWaiting: true }))?.layers[0]
1362 ?.state,
1363 ).toBe("open");
1364​
1365 const refreshed = Latch.makeUnsafe();
1366 const stop = registry.subscribe(stack, (result) => {
1367 if (AsyncResult.isSuccess(result) && result.value?.layers[0]?.headSha === "new-head") {
1368 refreshed.openUnsafe();
1370 });
1371 yield* Effect.addFinalizer(() => Effect.sync(stop));
1372 headSha = "new-head";
1373 yield* PubSub.publish(refreshEvents, 1);
1374 yield* refreshed.await;
1375 expect((yield* AtomRegistry.getResult(registry, stack))?.layers[0]?.headSha).toBe("new-head");
1376 }),
1377 ),