Open History to see the last commit
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 );
237}
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 );
315}
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 };
337}
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 );
484}
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 }
598}
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 );
642}
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 );
715}
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("keeps hover previews fresh after edits and turns", () =>
891 Effect.scoped(
892 Effect.gen(function* () {
893 const refreshEvents = yield* PubSub.unbounded<number>();
894 let title = "Original title";
895 let reads = 0;
896 const read = (input: unknown) =>
897 Effect.sync(() => {
898 expect(input).toEqual(reference);
899 reads++;
900 return { ...reference, title };
901 });
902 const reference = {
903 projectId: ProjectId.make("project-1"),
904 repository: "acme/web",
905 number: 1,
906 host: "github.example.com",
907 };
908 const client = {
909 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
910 [WS_METHODS.pullRequestsPreview]: read,
911 [WS_METHODS.pullRequestsDetail]: read,
912 [WS_METHODS.pullRequestsUpdate]: (input: { title: string }) =>
913 Effect.sync(() => {
914 title = input.title;
915 }),
916 [WS_METHODS.pullRequestsRunAction]: () =>
917 Effect.sync(() => {
918 title = "Closed";
919 }),
920 [WS_METHODS.pullRequestsInvalidate]: () => Effect.void,
921 } as unknown as WsRpcProtocolClient;
922 const { atoms, registry } = yield* makeTestRuntime(client);
923 const target = { environmentId: TARGET.environmentId, input: reference };
924 const preview = atoms.preview(target);
925 const unmount = registry.mount(preview);
926 yield* Effect.addFinalizer(() => Effect.sync(unmount));
927 expect(
928 (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title,
929 ).toBe(title);
930 yield* Effect.promise(() => executeAtomQuery(registry, preview));
931 expect(reads).toBe(1);
932 const edited = yield* Effect.promise(() =>
933 atoms.update.run(registry, { ...target, input: { ...reference, title: "Edited" } }),
934 );
935 expect(AsyncResult.isSuccess(edited)).toBe(true);
936 expect(
937 (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title,
938 ).toBe("Edited");
939 yield* Effect.promise(() =>
940 atoms.runAction.run(registry, { ...target, input: { ...reference, action: "close" } }),
941 );
942 expect(
943 (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title,
944 ).toBe("Closed");
945 title = "Refreshed";
946 yield* Effect.promise(() =>
947 atoms.invalidate.run(registry, {
948 environmentId: target.environmentId,
949 input: { reference },
950 }),
951 );
952 expect(
953 (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title,
954 ).toBe("Refreshed");
955 const refreshed = Latch.makeUnsafe();
956 const stop = registry.subscribe(preview, (result) => {
957 if (AsyncResult.isSuccess(result) && result.value.title === "After turn")
958 refreshed.openUnsafe();
959 });
960 yield* Effect.addFinalizer(() => Effect.sync(stop));
961 title = "After turn";
962 yield* PubSub.publish(refreshEvents, 1);
963 yield* refreshed.await;
964 }),
965 ),
966);
967
968it.effect("shares close, reopen, and merge with an untouched client's mounted PR readers", () =>
969 Effect.scoped(
970 Effect.gen(function* () {
971 const revision = yield* SubscriptionRef.make(0);
972 let state: "open" | "closed" | "merged" = "open";
973 const client = {
974 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => SubscriptionRef.changes(revision),
975 [WS_METHODS.pullRequestsSummary]: () => Effect.sync(() => ({ state })),
976 [WS_METHODS.pullRequestsDetail]: () => Effect.sync(() => ({ state })),
977 [WS_METHODS.pullRequestsList]: () =>
978 Effect.sync(() => ({ entries: [{ number: 1, state }] })),
979 [WS_METHODS.pullRequestsRunAction]: (input: {
980 readonly action: "close" | "reopen" | "merge";
981 }) =>
982 Effect.gen(function* () {
983 state =
984 input.action === "close" ? "closed" : input.action === "merge" ? "merged" : "open";
985 yield* SubscriptionRef.update(revision, (value) => value + 1);
986 }),
987 } as unknown as WsRpcProtocolClient;
988 const writer = yield* makeTestRuntime(client);
989 const reader = yield* makeTestRuntime(client);
990 const target = {
991 environmentId: TARGET.environmentId,
992 input: {
993 projectId: ProjectId.make("project-1"),
994 host: "github.example.com",
995 repository: "acme/web",
996 number: 1,
997 },
998 };
999 const detail = reader.atoms.detail(target);
1000 const summary = createLinkedPullRequestSummaryAtomFamily(
1001 reader.runtime,
1002 reader.atoms.refreshes,
1003 )(target);
1004 const list = reader.atoms.list({
1005 environmentId: TARGET.environmentId,
1006 input: { state: "all" },
1007 });
1008 const unmountDetail = reader.registry.mount(detail);
1009 const unmountSummary = reader.registry.mount(summary);
1010 const unmountList = reader.registry.mount(list);
1011 yield* Effect.addFinalizer(() =>
1012 Effect.sync(() => {
1013 unmountDetail();
1014 unmountSummary();
1015 unmountList();
1016 }),
1017 );
1018 expect((yield* AtomRegistry.getResult(reader.registry, detail)).state).toBe("open");
1019 expect((yield* AtomRegistry.getResult(reader.registry, summary)).state).toBe("open");
1020 expect((yield* AtomRegistry.getResult(reader.registry, list)).entries[0]?.state).toBe("open");
1021
1022 for (const [action, expected] of [
1023 ["close", "closed"],
1024 ["reopen", "open"],
1025 ["merge", "merged"],
1026 ] as const) {
1027 const detailChanged = Latch.makeUnsafe();
1028 const summaryChanged = Latch.makeUnsafe();
1029 const listChanged = Latch.makeUnsafe();
1030 const stops = [
1031 reader.registry.subscribe(detail, (result) => {
1032 if (AsyncResult.isSuccess(result) && result.value.state === expected) {
1033 detailChanged.openUnsafe();
1034 }
1035 }),
1036 reader.registry.subscribe(summary, (result) => {
1037 if (AsyncResult.isSuccess(result) && result.value.state === expected) {
1038 summaryChanged.openUnsafe();
1039 }
1040 }),
1041 reader.registry.subscribe(list, (result) => {
1042 if (AsyncResult.isSuccess(result) && result.value.entries[0]?.state === expected) {
1043 listChanged.openUnsafe();
1044 }
1045 }),
1046 ];
1047 yield* Effect.addFinalizer(() => Effect.sync(() => stops.forEach((stop) => stop())));
1048 const result = yield* Effect.promise(() =>
1049 writer.atoms.runAction.run(writer.registry, {
1050 ...target,
1051 input: { ...target.input, action },
1052 }),
1053 );
1054 expect(AsyncResult.isSuccess(result)).toBe(true);
1055 // The second client receives only the server push: no local refresh or timer tick.
1056 yield* detailChanged.await;
1057 yield* summaryChanged.await;
1058 yield* listChanged.await;
1059 expect((yield* AtomRegistry.getResult(reader.registry, detail)).state).toBe(expected);
1060 expect((yield* AtomRegistry.getResult(reader.registry, summary)).state).toBe(expected);
1061 expect((yield* AtomRegistry.getResult(reader.registry, list)).entries[0]?.state).toBe(
1062 expected,
1063 );
1064 stops.forEach((stop) => stop());
1065 }
1066 }),
1067 ),
1068);
1069
1070it.effect("refreshes pull request activity after a comment is updated", () =>
1071 Effect.scoped(
1072 Effect.gen(function* () {
1073 const refreshEvents = yield* PubSub.unbounded<number>();
1074 let commentBody = "old comment";
1075 const client = {
1076 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
1077 [WS_METHODS.pullRequestsActivity]: () =>
1078 Effect.succeed({
1079 author: null,
1080 reviewers: [],
1081 comments: [
1082 {
1083 id: "comment-1",
1084 kind: "issue-comment",
1085 author: null,
1086 body: commentBody,
1087 createdAt: "2026-08-24T00:00:00Z",
1088 url: null,
1089 path: null,
1090 reviewState: null,
1091 reactions: [],
1092 },
1093 ],
1094 commentCount: 1,
1095 commentsTruncated: false,
1096 reviewThreads: [],
1097 commits: [],
1098 reactions: [],
1099 }),
1100 [WS_METHODS.pullRequestsUpdateComment]: (input: { readonly body: string }) =>
1101 Effect.sync(() => {
1102 commentBody = input.body;
1103 }),
1104 } as unknown as WsRpcProtocolClient;
1105 const { atoms, registry } = yield* makeTestRuntime(client);
1106 const reference = {
1107 projectId: ProjectId.make("project-1"),
1108 host: "github.example.com",
1109 repository: "acme/web",
1110 number: 1,
1111 } as const;
1112 const activity = atoms.activity({ environmentId: TARGET.environmentId, input: reference });
1113 const unmount = registry.mount(activity);
1114 yield* Effect.addFinalizer(() => Effect.sync(unmount));
1115
1116 const initial = yield* Effect.promise(() => executeAtomQuery(registry, activity));
1117 expect(AsyncResult.isSuccess(initial)).toBe(true);
1118 if (!AsyncResult.isSuccess(initial)) {
1119 return yield* Effect.die("activity did not load");
1120 }
1121 expect(initial.value.comments[0]?.body).toBe("old comment");
1122
1123 const update = yield* Effect.promise(() =>
1124 atoms.updateComment.run(registry, {
1125 environmentId: TARGET.environmentId,
1126 input: { ...reference, commentId: "comment-1", kind: "issue-comment", body: "updated" },
1127 }),
1128 );
1129
1130 expect(AsyncResult.isSuccess(update)).toBe(true);
1131 expect(
1132 (yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true })).comments[0]
1133 ?.body,
1134 ).toBe("updated");
1135 const refreshed = Latch.makeUnsafe();
1136 const stop = registry.subscribe(activity, (result) => {
1137 if (AsyncResult.isSuccess(result) && result.value.comments[0]?.body === "after turn") {
1138 refreshed.openUnsafe();
1139 }
1140 });
1141 yield* Effect.addFinalizer(() => Effect.sync(stop));
1142
1143 commentBody = "after turn";
1144 yield* PubSub.publish(refreshEvents, 1);
1145 yield* refreshed.await;
1146
1147 expect(
1148 (yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true })).comments[0]
1149 ?.body,
1150 ).toBe("after turn");
1151 }),
1152 ),
1153);
1154
1155it.effect("updates cached labels after successful edits without rereading the host", () =>
1156 Effect.scoped(
1157 Effect.gen(function* () {
1158 let detailReads = 0;
1159 let candidateReads = 0;
1160 let refuse = false;
1161 let failDetail = false;
1162 const existing = { name: "existing", color: "111111" };
1163 const addedLabel = { name: "new", color: "abcdef" };
1164 const detailRefreshStarted = yield* Latch.make();
1165 const releaseDetailRefresh = yield* Latch.make();
1166 const client = {
1167 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
1168 [WS_METHODS.pullRequestsDetail]: () =>
1169 Effect.gen(function* () {
1170 detailReads++;
1171 if (failDetail) {
1172 yield* detailRefreshStarted.open;
1173 yield* releaseDetailRefresh.await;
1174 return yield* new MutationRefused();
1175 }
1176 return { title: "keep this title", labels: [existing] };
1177 }),
1178 [WS_METHODS.pullRequestsLabelCandidates]: () =>
1179 Effect.sync(() => {
1180 candidateReads++;
1181 return {
1182 candidates: [
1183 { ...existing, description: null, isApplied: true },
1184 { ...addedLabel, description: "description", isApplied: false },
1185 ],
1186 truncated: false,
1187 };
1188 }),
1189 [WS_METHODS.pullRequestsSetLabels]: () =>
1190 refuse ? Effect.fail(new MutationRefused()) : Effect.void,
1191 } as unknown as WsRpcProtocolClient;
1192 const { atoms, registry } = yield* makeTestRuntime(client);
1193 const target = {
1194 environmentId: TARGET.environmentId,
1195 input: {
1196 projectId: ProjectId.make("project-1"),
1197 repository: "acme/web",
1198 number: 1,
1199 host: "github.example.com",
1200 },
1201 };
1202 const detail = atoms.detail(target);
1203 const candidates = atoms.labelCandidates(target);
1204 registry.mount(detail);
1205 const unmountCandidates = registry.mount(candidates);
1206 yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
1207 yield* AtomRegistry.getResult(registry, candidates, { suspendOnWaiting: true });
1208
1209 const added = yield* Effect.promise(() =>
1210 atoms.setLabels.run(registry, {
1211 ...target,
1212 input: {
1213 host: target.input.host,
1214 projectId: target.input.projectId,
1215 repository: target.input.repository,
1216 number: target.input.number,
1217 labels: ["new"],
1218 applied: true,
1219 },
1220 }),
1221 );
1222 expect(AsyncResult.isSuccess(added)).toBe(true);
1223 expect(yield* AtomRegistry.getResult(registry, detail)).toEqual({
1224 title: "keep this title",
1225 labels: [existing, addedLabel],
1226 });
1227 unmountCandidates();
1228 registry.mount(atoms.labelCandidates(target));
1229 expect((yield* AtomRegistry.getResult(registry, candidates)).candidates[1]).toEqual({
1230 ...addedLabel,
1231 description: "description",
1232 isApplied: true,
1233 });
1234
1235 for (const name of ["existing", "new"]) {
1236 refuse = name === "new";
1237 const result = yield* Effect.promise(() =>
1238 atoms.setLabels.run(registry, {
1239 ...target,
1240 input: { ...target.input, labels: [name], applied: false },
1241 }),
1242 );
1243 expect(result._tag).toBe(refuse ? "Failure" : "Success");
1244 expect((yield* AtomRegistry.getResult(registry, detail)).labels).toEqual([addedLabel]);
1245 expect((yield* AtomRegistry.getResult(registry, candidates)).candidates).toMatchObject([
1246 { name: "existing", isApplied: false },
1247 { name: "new", isApplied: true },
1248 ]);
1249 }
1250 expect(detailReads).toBe(1);
1251 expect(candidateReads).toBe(1);
1252
1253 failDetail = true;
1254 registry.refresh(detail);
1255 yield* detailRefreshStarted.await;
1256 expect(registry.get(detail).waiting).toBe(true);
1257 expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).labels).toEqual([
1258 addedLabel,
1259 ]);
1260 yield* releaseDetailRefresh.open;
1261 yield* Effect.exit(AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true }));
1262 expect(AsyncResult.isFailure(registry.get(detail))).toBe(true);
1263 expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).labels).toEqual([
1264 addedLabel,
1265 ]);
1266 failDetail = false;
1267 registry.refresh(detail);
1268 expect(
1269 (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).labels,
1270 ).toEqual([existing]);
1271 expect(detailReads).toBe(3);
1272 }),
1273 ),
1274);
1275
1276it.effect("updates reviewer requests and enriched reviewers without rereading the host", () =>
1277 Effect.scoped(
1278 Effect.gen(function* () {
1279 let reads = 0;
1280 let refuse = false;
1281 const actor = { login: "reviewer", name: "Reviewer", avatarUrl: null };
1282 const hostActor = { ...actor, login: "Reviewer" };
1283 let hostRequested = false;
1284 let reviewed = false;
1285 let pauseActivity = false;
1286 const activityStarted = yield* Latch.make();
1287 const client = {
1288 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
1289 [WS_METHODS.pullRequestsDetail]: () =>
1290 Effect.sync(() => {
1291 reads++;
1292 return { reviewers: hostRequested ? [hostActor] : [] };
1293 }),
1294 [WS_METHODS.pullRequestsActivity]: () =>
1295 Effect.gen(function* () {
1296 reads++;
1297 if (pauseActivity) {
1298 pauseActivity = false;
1299 yield* activityStarted.open;
1300 return yield* Effect.never;
1301 }
1302 return {
1303 reviewers: hostRequested ? [hostActor] : [],
1304 comments: reviewed ? [{ kind: "review-comment", author: hostActor }] : [],
1305 };
1306 }),
1307 [WS_METHODS.pullRequestsReviewerCandidates]: (input: { number: number }) =>
1308 input.number === 2
1309 ? Effect.never
1310 : Effect.sync(() => {
1311 reads++;
1312 return {
1313 candidates: [{ ...actor, id: "12", kind: "user", isRequested: false }],
1314 truncated: false,
1315 };
1316 }),
1317 [WS_METHODS.pullRequestsRequestReviewers]: (input: { requested: boolean }) =>
1318 refuse
1319 ? Effect.fail(new MutationRefused())
1320 : Effect.sync(() => {
1321 hostRequested = input.requested;
1322 }),
1323 } as unknown as WsRpcProtocolClient;
1324 const { atoms, registry } = yield* makeTestRuntime(client);
1325 const target = {
1326 environmentId: TARGET.environmentId,
1327 input: {
1328 projectId: ProjectId.make("project-1"),
1329 repository: "acme/web",
1330 number: 1,
1331 host: "github.example.com",
1332 },
1333 };
1334 const detail = atoms.detail(target);
1335 const activity = atoms.activity(target);
1336 const candidates = atoms.reviewerCandidates(target);
1337 registry.mount(detail);
1338 registry.mount(activity);
1339 registry.mount(candidates);
1340 yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
1341 yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true });
1342 yield* AtomRegistry.getResult(registry, candidates, { suspendOnWaiting: true });
1343 const request = (requested: boolean, reference = target) =>
1344 Effect.promise(() =>
1345 atoms.requestReviewers.run(registry, {
1346 ...reference,
1347 input: { ...reference.input, reviewers: [{ id: "12", kind: "user" }], requested },
1348 }),
1349 );
1350 for (const operation of ["request", "refuse", "remove"]) {
1351 refuse = operation === "refuse";
1352 expect((yield* request(operation === "request"))._tag).toBe(refuse ? "Failure" : "Success");
1353 const expected = operation === "remove" ? [] : [actor];
1354 expect((yield* AtomRegistry.getResult(registry, detail)).reviewers).toEqual(expected);
1355 expect((yield* AtomRegistry.getResult(registry, activity)).reviewers).toEqual(expected);
1356 expect((yield* AtomRegistry.getResult(registry, candidates)).candidates).toMatchObject([
1357 { isRequested: operation !== "remove" },
1358 ]);
1359 }
1360 expect(reads).toBe(3);
1361 // A slow activity read started before the write must not hide the new request.
1362 pauseActivity = true;
1363 registry.refresh(activity);
1364 yield* activityStarted.await;
1365 expect(AsyncResult.isSuccess(yield* request(true))).toBe(true);
1366 expect(
1367 (yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true })).reviewers,
1368 ).toEqual([hostActor]);
1369 expect(reads).toBe(5);
1370 expect(AsyncResult.isSuccess(yield* request(false))).toBe(true);
1371 expect((yield* AtomRegistry.getResult(registry, activity)).reviewers).toEqual([]);
1372
1373 reviewed = true;
1374 yield* request(true);
1375 registry.refresh(activity);
1376 yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true });
1377 yield* request(false);
1378 expect((yield* AtomRegistry.getResult(registry, activity)).reviewers).toEqual([hostActor]);
1379
1380 // A caller without an open picker still needs authoritative reviewer identities.
1381 const otherTarget = { ...target, input: { ...target.input, number: 2 } };
1382 const otherDetail = atoms.detail(otherTarget);
1383 registry.mount(otherDetail);
1384 yield* AtomRegistry.getResult(registry, otherDetail, { suspendOnWaiting: true });
1385 yield* request(true, otherTarget);
1386 expect(
1387 (yield* AtomRegistry.getResult(registry, otherDetail, { suspendOnWaiting: true }))
1388 .reviewers,
1389 ).toEqual([hostActor]);
1390 }),
1391 ),
1392);
1393
1394it.effect("refreshes stack state after reopening and head SHAs after a turn", () =>
1395 Effect.scoped(
1396 Effect.gen(function* () {
1397 const refreshEvents = yield* PubSub.unbounded<number>();
1398 let state: "closed" | "open" = "closed";
1399 let headSha = "old-head";
1400 const client = {
1401 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
1402 [WS_METHODS.pullRequestsStack]: () =>
1403 Effect.sync(
1404 () =>
1405 ({
1406 id: "stack-1",
1407 number: 1,
1408 url: "https://github.com/acme/web/pull/1",
1409 base: "main",
1410 layers: [
1411 {
1412 number: 1,
1413 headBranch: "feature",
1414 headSha,
1415 state,
1416 isDraft: false,
1417 },
1418 ],
1419 }) satisfies PullRequestStack,
1420 ),
1421 } as unknown as WsRpcProtocolClient;
1422 const { runtime, registry } = yield* makeTestRuntime(client);
1423 const stacks = createPullRequestStackAtomFamily(runtime);
1424 const stack = stacks({
1425 environmentId: TARGET.environmentId,
1426 input: {
1427 projectId: ProjectId.make("project-1"),
1428 repository: "acme/web",
1429 number: 1,
1430 },
1431 });
1432 const unmount = registry.mount(stack);
1433 yield* Effect.addFinalizer(() => Effect.sync(unmount));
1434 yield* Effect.promise(() => executeAtomQuery(registry, stack));
1435 expect((yield* AtomRegistry.getResult(registry, stack))?.layers[0]?.state).toBe("closed");
1436 state = "open";
1437 registry.refresh(stack);
1438 expect(
1439 (yield* AtomRegistry.getResult(registry, stack, { suspendOnWaiting: true }))?.layers[0]
1440 ?.state,
1441 ).toBe("open");
1442
1443 const refreshed = Latch.makeUnsafe();
1444 const stop = registry.subscribe(stack, (result) => {
1445 if (AsyncResult.isSuccess(result) && result.value?.layers[0]?.headSha === "new-head") {
1446 refreshed.openUnsafe();
1447 }
1448 });
1449 yield* Effect.addFinalizer(() => Effect.sync(stop));
1450 headSha = "new-head";
1451 yield* PubSub.publish(refreshEvents, 1);
1452 yield* refreshed.await;
1453 expect((yield* AtomRegistry.getResult(registry, stack))?.layers[0]?.headSha).toBe("new-head");
1454 }),
1455 ),
1456);