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