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

pullRequests.test.ts

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