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
239const TARGET = new PrimaryConnectionTarget({
240 environmentId: EnvironmentId.make("environment-1"),
241 label: "Test environment",
242 httpBaseUrl: "https://environment.example.test",
243 wsBaseUrl: "wss://environment.example.test",
244});
245
246function session(client: WsRpcProtocolClient): RpcSession {
247 return {
248 client: {
249 ...client,
250 [WS_METHODS.pullRequestsInvalidate]:
251 client[WS_METHODS.pullRequestsInvalidate] ?? (() => Effect.void),
252 },
253 initialConfig: Effect.never,
254 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
255 ready: Effect.void,
256 probe: Effect.void,
257 closed: Effect.never,
258 };
259}
260
261const makeTestRuntime = Effect.fn("makeTestRuntime")(function* (
262 client: WsRpcProtocolClient,
263 localClient?: WsRpcProtocolClient,
264 localOrigin = false,
265) {
266 const originTarget = localOrigin
267 ? new PrimaryConnectionTarget({
268 ...TARGET,
269 httpBaseUrl: "http://localhost:3774",
270 wsBaseUrl: "ws://localhost:3774",
271 })
272 : TARGET;
273 const connectionState: SupervisorConnectionState = {
274 ...AVAILABLE_CONNECTION_STATE,
275 desired: true,
276 network: "online",
277 phase: "connected",
278 attempt: 1,
279 generation: 1,
280 };
281 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
282 target: originTarget,
283 state: yield* SubscriptionRef.make(connectionState),
284 session: yield* SubscriptionRef.make(Option.some(session(client))),
285 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
286 connect: Effect.void,
287 disconnect: Effect.void,
288 retryNow: Effect.void,
289 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
290 const localTarget = new PrimaryConnectionTarget({
291 environmentId: EnvironmentId.make("local-environment"),
292 label: "Local environment",
293 httpBaseUrl: "http://localhost:3773",
294 wsBaseUrl: "ws://localhost:3773",
295 });
296 const localSupervisor = {
297 ...supervisor,
298 target: localTarget,
299 session: yield* SubscriptionRef.make(Option.some(session(localClient ?? client))),
300 };
301 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
302 entries: yield* SubscriptionRef.make<ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>>(
303 new Map([
304 [
305 originTarget.environmentId,
306 { target: originTarget, profile: Option.none(), enabled: true },
307 ],
308 ...(localClient === undefined
309 ? []
310 : [
311 [
312 localTarget.environmentId,
313 { target: localTarget, profile: Option.none(), enabled: true },
314 ] as const,
315 ]),
316 ]),
317 ),
318 run: (environmentId, effect) =>
319 Effect.provideService(
320 effect,
321 EnvironmentSupervisor.EnvironmentSupervisor,
322 environmentId === localTarget.environmentId ? localSupervisor : supervisor,
323 ),
324 runStream: (_environmentId, stream) =>
325 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
326 followStream: (_environmentId, stream) =>
327 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
328 } as EnvironmentRegistry.EnvironmentRegistry["Service"]);
329 const runtime = Atom.runtime(
330 Layer.merge(
331 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
332 Layer.succeed(
333 PullRequestDiffLoader,
334 PullRequestDiffLoader.of({ load: () => Effect.die("unused") }),
335 ),
336 ),
337 );
338 const atoms = createPullRequestEnvironmentAtoms(runtime);
339 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
340 Effect.sync(() => registry.dispose()),
341 );
342 return { runtime, atoms, registry, environmentRegistry, supervisor };
343});
344
345for (const permission of ["default", "origin-off", "destination-off", "read-only"] as const) {
346 it.effect(`does not probe another environment with ${permission} routing permission`, () =>
347 Effect.scoped(
348 Effect.gen(function* () {
349 const calls: string[] = [];
350 const failure = new PullRequestOperationError({
351 operation: "summary",
352 detail: "source failed",
353 });
354 const client = {
355 [WS_METHODS.pullRequestsSummary]: () =>
356 Effect.suspend(() => {
357 calls.push("source-read");
358 return Effect.fail(failure);
359 }),
360 [WS_METHODS.pullRequestsRunAction]: () =>
361 Effect.sync(() => {
362 calls.push("source-write");
363 }),
364 } as unknown as WsRpcProtocolClient;
365 const alternate = {
366 [WS_METHODS.pullRequestsRoutingIdentity]: () =>
367 Effect.die("untrusted environment was contacted"),
368 } as unknown as WsRpcProtocolClient;
369 const { environmentRegistry, supervisor } = yield* makeTestRuntime(client, alternate);
370 const ref = {
371 projectId: ProjectId.make("project-1"),
372 repository: "private/repo",
373 number: 7,
374 };
375 const request = Effect.gen(function* () {
376 const route = createPullRequestRouter();
377 if (permission !== "read-only")
378 yield* route(WS_METHODS.pullRequestsSummary, ref).pipe(Effect.flip);
379 yield* route(WS_METHODS.pullRequestsRunAction, { ...ref, action: "merge" });
380 }).pipe(
381 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
382 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
383 );
384 yield* permission === "default"
385 ? request
386 : request.pipe(
387 Effect.provideService(GitHubRoutingPermissions, {
388 ...trustedRouting,
389 get: (entry) =>
390 Effect.succeed(
391 permission === "read-only"
392 ? "read"
393 : (entry.target.environmentId === TARGET.environmentId) ===
394 (permission === "origin-off")
395 ? "off"
396 : "read-write",
397 ),
398 }),
399 );
400 expect(calls).toEqual(
401 permission === "read-only" ? ["source-write"] : ["source-read", "source-write"],
402 );
403 }),
404 ),
405 );
406}
407
408for (const side of ["origin", "destination"] as const) {
409 for (const stored of ["matching", "changed", "missing", "unavailable", "failed"] as const) {
410 it.effect(`checks the current ${side} SSH profile before routing with ${stored} storage`, () =>
411 Effect.scoped(
412 Effect.gen(function* () {
413 const calls: string[] = [];
414 const identity = {
415 host: "github.com",
416 provider: "github",
417 viewer: "maria",
418 accountId: "123",
419 };
420 const client = {
421 [WS_METHODS.pullRequestsRouting]: () =>
422 Effect.sync(() => {
423 calls.push("source-probe");
424 return identity;
425 }),
426 [WS_METHODS.pullRequestsRunAction]: (input: { expectedAccountId?: string }) =>
427 Effect.gen(function* () {
428 if (input.expectedAccountId !== undefined) {
429 return yield* new PullRequestOperationError({
430 operation: "routeIdentity",
431 detail: "Source guard refused.",
432 });
433 }
434 calls.push("source-write");
435 }),
436 [WS_METHODS.pullRequestsInvalidate]: () => Effect.void,
437 } as unknown as WsRpcProtocolClient;
438 const alternate = {
439 [WS_METHODS.pullRequestsRoutingIdentity]: () =>
440 Effect.sync(() => {
441 calls.push("alternate-probe");
442 return identity;
443 }),
444 [WS_METHODS.pullRequestsRunAction]: () =>
445 Effect.sync(() => {
446 calls.push("alternate-write");
447 }),
448 [WS_METHODS.pullRequestsInvalidate]: () => Effect.void,
449 } as unknown as WsRpcProtocolClient;
450 const { environmentRegistry, supervisor } = yield* makeTestRuntime(client, alternate);
451 const environmentId =
452 side === "origin" ? TARGET.environmentId : EnvironmentId.make("local-environment");
453 const profile = new SshConnectionProfile({
454 connectionId: "ssh-1",
455 environmentId,
456 label: "SSH",
457 target: { alias: "work", hostname: "work.example.test", username: "maria", port: 22 },
458 });
459 yield* SubscriptionRef.update(environmentRegistry.entries, (entries) =>
460 new Map(entries).set(environmentId, {
461 target: new SshConnectionTarget({
462 environmentId,
463 connectionId: profile.connectionId,
464 label: "SSH",
465 }),
466 profile: Option.some(profile),
467 enabled: true,
468 }),
469 );
470 const read = Effect.suspend(() =>
471 stored === "failed"
472 ? Effect.fail(
473 new ConnectionTransientError({
474 reason: "remote-unavailable",
475 detail: "Profile storage unavailable.",
476 }),
477 )
478 : Effect.succeed(
479 stored === "missing"
480 ? Option.none()
481 : Option.some(
482 stored === "changed"
483 ? new SshConnectionProfile({
484 ...profile,
485 target: { ...profile.target, hostname: "replacement.example.test" },
486 })
487 : profile,
488 ),
489 ),
490 );
491 const route = createPullRequestRouter()(WS_METHODS.pullRequestsRunAction, {
492 projectId: ProjectId.make("project-1"),
493 repository: "private/repo",
494 number: 7,
495 action: "merge",
496 }).pipe(
497 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
498 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
499 // This also represents a user enabling the stale catalog entry after re-resolution.
500 Effect.provideService(GitHubRoutingPermissions, trustedRouting),
501 );
502 yield* stored === "unavailable"
503 ? route
504 : route.pipe(
505 Effect.provideService(ConnectionProfileStore, {
506 get: () => read,
507 put: () => Effect.die("unused"),
508 remove: () => Effect.die("unused"),
509 }),
510 );
511 expect(calls).toEqual(
512 stored === "matching"
513 ? ["source-probe", "alternate-probe", "alternate-write"]
514 : ["source-write"],
515 );
516 }),
517 ),
518 );
519 }
520}
521
522for (const probe of ["origin", "alternate"] as const) {
523 it.live(`bounds a stalled ${probe} metadata probe without repeating a strict source read`, () =>
524 Effect.scoped(
525 Effect.gen(function* () {
526 let sourceReads = 0;
527 const identity = {
528 host: "github.com",
529 provider: "github",
530 viewer: "maria",
531 accountId: "123",
532 };
533 const client = {
534 [WS_METHODS.pullRequestsRouting]: () =>
535 probe === "origin" ? Effect.never : Effect.succeed(identity),
536 [WS_METHODS.pullRequestsSummary]: () =>
537 Effect.suspend(() => {
538 sourceReads += 1;
539 return Effect.fail(
540 new PullRequestOperationError({ operation: "summary", detail: "source failed" }),
541 );
542 }),
543 } as unknown as WsRpcProtocolClient;
544 const alternate = {
545 [WS_METHODS.pullRequestsRoutingIdentity]: () => Effect.never,
546 } as unknown as WsRpcProtocolClient;
547 const { environmentRegistry, supervisor } = yield* makeTestRuntime(client, alternate);
548 const error = yield* createPullRequestRouter()(WS_METHODS.pullRequestsSummary, {
549 projectId: ProjectId.make("project-1"),
550 repository: "acme/web",
551 number: 7,
552 allowStale: false,
553 }).pipe(
554 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
555 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
556 Effect.provideService(GitHubRoutingPermissions, trustedRouting),
557 Effect.flip,
558 );
559 expect(error._tag).toBe("PullRequestOperationError");
560 expect(sourceReads).toBe(1);
561 }),
562 ),
563 );
564}
565
566for (const source of ["pending", "pending-local", "failed-local", "failed", "offline"] as const) {
567 it.effect(
568 source === "offline"
569 ? "returns held source data only after both fresh paths fail"
570 : `uses one shared reader with a ${source} source`,
571 () =>
572 Effect.scoped(
573 Effect.gen(function* () {
574 const started = yield* Deferred.make<void>();
575 const calls: string[] = [];
576 const clientFor = (local: boolean) =>
577 ({
578 [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]:
579 () =>
580 Effect.succeed({
581 host: "github.com",
582 provider: "github",
583 viewer: "maria-rcks",
584 accountId: "123",
585 }),
586 [WS_METHODS.pullRequestsSummary]: (input: { allowStale?: boolean }) =>
587 Effect.gen(function* () {
588 calls.push(local ? "local" : input.allowStale === false ? "origin" : "held");
589 if (source === "offline" && !local && input.allowStale === undefined) {
590 return { state: "open" };
591 }
592 expect(input.allowStale).toBe(false);
593 if (local && source !== "offline") return null;
594 if (source !== "pending" && source !== "pending-local")
595 return yield* new PullRequestOperationError({
596 operation: "summary",
597 detail: "github unreachable",
598 });
599 yield* Deferred.succeed(started, undefined);
600 return yield* Effect.never;
601 }),
602 }) as unknown as WsRpcProtocolClient;
603 const { environmentRegistry, supervisor } = yield* makeTestRuntime(
604 clientFor(false),
605 clientFor(true),
606 source === "failed-local" || source === "pending-local",
607 );
608 const request = createPullRequestRouter()(WS_METHODS.pullRequestsSummary, {
609 projectId: ProjectId.make("project-1"),
610 repository: "acme/web",
611 number: 7,
612 }).pipe(
613 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
614 Effect.provideService(GitHubRoutingPermissions, trustedRouting),
615 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
616 );
617 const fiber = yield* request.pipe(Effect.forkChild);
618 if (source === "pending-local") {
619 yield* Deferred.await(started);
620 yield* TestClock.adjust("30 seconds");
621 }
622 const result = yield* Fiber.join(fiber);
623 if (source === "offline") {
624 expect(result).toEqual({ state: "open" });
625 expect(calls).toEqual(["local", "origin", "held"]);
626 } else {
627 expect(result).toBeNull();
628 expect(calls).toEqual(
629 source === "failed-local" || source === "pending-local"
630 ? ["origin", "local"]
631 : ["local"],
632 );
633 }
634 }),
635 ),
636 );
637}
638
639it.live("keeps source workspace metadata when an alternate answers a detail read", () =>
640 Effect.scoped(
641 Effect.gen(function* () {
642 const clientFor = (local: boolean) =>
643 ({
644 [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
645 Effect.succeed({
646 host: "github.com",
647 provider: "github",
648 viewer: "maria-rcks",
649 accountId: "123",
650 projectTitle: local ? "local project" : "source project",
651 workspaceRoot: local ? "/Users/local/repo" : "/srv/source/repo",
652 }),
653 [WS_METHODS.pullRequestsDetail]: () =>
654 local
655 ? Effect.succeed({
656 projectId: "local-project",
657 projectTitle: "local project",
658 workspaceRoot: "/Users/local/repo",
659 title: "github title",
660 })
661 : Effect.never,
662 }) as unknown as WsRpcProtocolClient;
663 const { environmentRegistry, supervisor } = yield* makeTestRuntime(
664 clientFor(false),
665 clientFor(true),
666 );
667 const result = yield* createPullRequestRouter()(WS_METHODS.pullRequestsDetail, {
668 projectId: ProjectId.make("project-1"),
669 repository: "acme/web",
670 number: 7,
671 }).pipe(
672 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
673 Effect.provideService(GitHubRoutingPermissions, trustedRouting),
674 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
675 );
676 expect(result).toEqual({
677 projectId: "project-1",
678 projectTitle: "source project",
679 workspaceRoot: "/srv/source/repo",
680 title: "github title",
681 });
682 }),
683 ),
684);
685
686it.live(
687 "refreshes identity before writes and invalidates prior readers across router instances",
688 () =>
689 Effect.scoped(
690 Effect.gen(function* () {
691 let originAccountId = "123";
692 const mutations: { environment: string; expectedAccountId: string }[] = [];
693 const invalidations: { environment: string; input: unknown }[] = [];
694 const identities: string[] = [];
695 const clientFor = (local: boolean) => {
696 const environment = local ? "local" : "origin";
697 return {
698 [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
699 Effect.sync(() => {
700 identities.push(environment);
701 return {
702 host: "github.com",
703 provider: "github",
704 viewer: "maria-rcks",
705 accountId: local ? "123" : originAccountId,
706 };
707 }),
708 [WS_METHODS.pullRequestsSummary]: () => (local ? Effect.succeed(null) : Effect.never),
709 [WS_METHODS.pullRequestsRunAction]: (input: { expectedAccountId: string }) =>
710 Effect.sync(() => {
711 mutations.push({ environment, expectedAccountId: input.expectedAccountId });
712 }),
713 [WS_METHODS.pullRequestsInvalidate]: (input: unknown) =>
714 Effect.sync(() => {
715 invalidations.push({ environment, input });
716 }),
717 } as unknown as WsRpcProtocolClient;
718 };
719 const { environmentRegistry, supervisor } = yield* makeTestRuntime(
720 clientFor(false),
721 clientFor(true),
722 );
723 const reference = {
724 projectId: ProjectId.make("project-1"),
725 repository: "acme/web",
726 number: 7,
727 };
728 const hostedReference = { ...reference, host: "github.com", allowStale: false };
729 const route = createPullRequestRouter();
730 yield* Effect.gen(function* () {
731 yield* route(WS_METHODS.pullRequestsSummary, reference);
732 originAccountId = "456";
733 yield* route(WS_METHODS.pullRequestsRunAction, { ...reference, action: "merge" });
734
735 expect(identities.filter((environment) => environment === "origin")).toHaveLength(2);
736 expect(mutations).toEqual([{ environment: "origin", expectedAccountId: "456" }]);
737 expect(invalidations).toEqual(
738 expect.arrayContaining([
739 { environment: "origin", input: { reference: expect.objectContaining(reference) } },
740 { environment: "origin", input: { reference: hostedReference } },
741 { environment: "local", input: { reference: hostedReference } },
742 { environment: "origin", input: {} },
743 { environment: "local", input: {} },
744 ]),
745 );
746
747 invalidations.length = 0;
748 const refresh = createPullRequestRouter();
749 yield* refresh(WS_METHODS.pullRequestsInvalidate, { reference });
750 expect(invalidations).toContainEqual({
751 environment: "local",
752 input: { reference: hostedReference },
753 });
754
755 invalidations.length = 0;
756 yield* refresh(WS_METHODS.pullRequestsInvalidate, {});
757 expect(invalidations).toContainEqual({ environment: "local", input: {} });
758 }).pipe(
759 Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
760 Effect.provideService(GitHubRoutingPermissions, trustedRouting),
761 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
762 );
763 }),
764 ),
765);
766
767it.effect("keeps concurrent diff file reads on different hosts separate", () =>
768 Effect.scoped(
769 Effect.gen(function* () {
770 const release = yield* Latch.make();
771 const started = yield* Latch.make();
772 const calls: string[] = [];
773 const client = {
774 [WS_METHODS.pullRequestsDiffFileContents]: (input: { readonly host: string }) =>
775 Effect.gen(function* () {
776 calls.push(input.host);
777 yield* started.open;
778 yield* release.await;
779 return { oldContents: "", newContents: input.host };
780 }),
781 } as unknown as WsRpcProtocolClient;
782 const { atoms, registry } = yield* makeTestRuntime(client);
783 const input = {
784 projectId: ProjectId.make("project-1"),
785 repository: "acme/web",
786 number: 1,
787 changeType: "change",
788 oldPath: "src/app.ts",
789 newPath: "src/app.ts",
790 } as const;
791 const first = atoms.diffFileContents.run(registry, {
792 environmentId: TARGET.environmentId,
793 input: { ...input, host: "github.com" },
794 });
795 yield* started.await;
796 const second = atoms.diffFileContents.run(registry, {
797 environmentId: TARGET.environmentId,
798 input: { ...input, host: "github.example.com" },
799 });
800 yield* release.open;
801
802 const results = yield* Effect.promise(() => Promise.all([first, second]));
803 expect(results).toMatchObject([
804 { _tag: "Success", value: { newContents: "github.com" } },
805 { _tag: "Success", value: { newContents: "github.example.com" } },
806 ]);
807 expect(calls).toEqual(["github.com", "github.example.com"]);
808 }),
809 ),
810);
811
812it.effect("shares close, reopen, and merge with an untouched client's mounted PR readers", () =>
813 Effect.scoped(
814 Effect.gen(function* () {
815 const revision = yield* SubscriptionRef.make(0);
816 let state: "open" | "closed" | "merged" = "open";
817 const client = {
818 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => SubscriptionRef.changes(revision),
819 [WS_METHODS.pullRequestsSummary]: () => Effect.sync(() => ({ state })),
820 [WS_METHODS.pullRequestsDetail]: () => Effect.sync(() => ({ state })),
821 [WS_METHODS.pullRequestsList]: () =>
822 Effect.sync(() => ({ entries: [{ number: 1, state }] })),
823 [WS_METHODS.pullRequestsRunAction]: (input: {
824 readonly action: "close" | "reopen" | "merge";
825 }) =>
826 Effect.gen(function* () {
827 state =
828 input.action === "close" ? "closed" : input.action === "merge" ? "merged" : "open";
829 yield* SubscriptionRef.update(revision, (value) => value + 1);
830 }),
831 } as unknown as WsRpcProtocolClient;
832 const writer = yield* makeTestRuntime(client);
833 const reader = yield* makeTestRuntime(client);
834 const target = {
835 environmentId: TARGET.environmentId,
836 input: {
837 projectId: ProjectId.make("project-1"),
838 host: "github.example.com",
839 repository: "acme/web",
840 number: 1,
841 },
842 };
843 const detail = reader.atoms.detail(target);
844 const summary = createLinkedPullRequestSummaryAtomFamily(
845 reader.runtime,
846 reader.atoms.refreshes,
847 )(target);
848 const list = reader.atoms.list({
849 environmentId: TARGET.environmentId,
850 input: { state: "all" },
851 });
852 const unmountDetail = reader.registry.mount(detail);
853 const unmountSummary = reader.registry.mount(summary);
854 const unmountList = reader.registry.mount(list);
855 yield* Effect.addFinalizer(() =>
856 Effect.sync(() => {
857 unmountDetail();
858 unmountSummary();
859 unmountList();
860 }),
861 );
862 expect((yield* AtomRegistry.getResult(reader.registry, detail)).state).toBe("open");
863 expect((yield* AtomRegistry.getResult(reader.registry, summary)).state).toBe("open");
864 expect((yield* AtomRegistry.getResult(reader.registry, list)).entries[0]?.state).toBe("open");
865
866 for (const [action, expected] of [
867 ["close", "closed"],
868 ["reopen", "open"],
869 ["merge", "merged"],
870 ] as const) {
871 const detailChanged = Latch.makeUnsafe();
872 const summaryChanged = Latch.makeUnsafe();
873 const listChanged = Latch.makeUnsafe();
874 const stops = [
875 reader.registry.subscribe(detail, (result) => {
876 if (AsyncResult.isSuccess(result) && result.value.state === expected) {
877 detailChanged.openUnsafe();
878 }
879 }),
880 reader.registry.subscribe(summary, (result) => {
881 if (AsyncResult.isSuccess(result) && result.value.state === expected) {
882 summaryChanged.openUnsafe();
883 }
884 }),
885 reader.registry.subscribe(list, (result) => {
886 if (AsyncResult.isSuccess(result) && result.value.entries[0]?.state === expected) {
887 listChanged.openUnsafe();
888 }
889 }),
890 ];
891 yield* Effect.addFinalizer(() => Effect.sync(() => stops.forEach((stop) => stop())));
892 const result = yield* Effect.promise(() =>
893 writer.atoms.runAction.run(writer.registry, {
894 ...target,
895 input: { ...target.input, action },
896 }),
897 );
898 expect(AsyncResult.isSuccess(result)).toBe(true);
899 // The second client receives only the server push: no local refresh or timer tick.
900 yield* detailChanged.await;
901 yield* summaryChanged.await;
902 yield* listChanged.await;
903 expect((yield* AtomRegistry.getResult(reader.registry, detail)).state).toBe(expected);
904 expect((yield* AtomRegistry.getResult(reader.registry, summary)).state).toBe(expected);
905 expect((yield* AtomRegistry.getResult(reader.registry, list)).entries[0]?.state).toBe(
906 expected,
907 );
908 stops.forEach((stop) => stop());
909 }
910 }),
911 ),
912);
913
914it.effect("refreshes pull request activity after a comment is updated", () =>
915 Effect.scoped(
916 Effect.gen(function* () {
917 const refreshEvents = yield* PubSub.unbounded<number>();
918 let commentBody = "old comment";
919 const client = {
920 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
921 [WS_METHODS.pullRequestsActivity]: () =>
922 Effect.succeed({
923 author: null,
924 reviewers: [],
925 comments: [
926 {
927 id: "comment-1",
928 kind: "issue-comment",
929 author: null,
930 body: commentBody,
931 createdAt: "2026-08-24T00:00:00Z",
932 url: null,
933 path: null,
934 reviewState: null,
935 reactions: [],
936 },
937 ],
938 commentCount: 1,
939 commentsTruncated: false,
940 reviewThreads: [],
941 commits: [],
942 reactions: [],
943 }),
944 [WS_METHODS.pullRequestsUpdateComment]: (input: { readonly body: string }) =>
945 Effect.sync(() => {
946 commentBody = input.body;
947 }),
948 } as unknown as WsRpcProtocolClient;
949 const { atoms, registry } = yield* makeTestRuntime(client);
950 const reference = {
951 projectId: ProjectId.make("project-1"),
952 host: "github.example.com",
953 repository: "acme/web",
954 number: 1,
955 } as const;
956 const activity = atoms.activity({ environmentId: TARGET.environmentId, input: reference });
957 const unmount = registry.mount(activity);
958 yield* Effect.addFinalizer(() => Effect.sync(unmount));
959
960 const initial = yield* Effect.promise(() => executeAtomQuery(registry, activity));
961 expect(AsyncResult.isSuccess(initial)).toBe(true);
962 if (!AsyncResult.isSuccess(initial)) {
963 return yield* Effect.die("activity did not load");
964 }
965 expect(initial.value.comments[0]?.body).toBe("old comment");
966
967 const update = yield* Effect.promise(() =>
968 atoms.updateComment.run(registry, {
969 environmentId: TARGET.environmentId,
970 input: { ...reference, commentId: "comment-1", kind: "issue-comment", body: "updated" },
971 }),
972 );
973
974 expect(AsyncResult.isSuccess(update)).toBe(true);
975 expect(
976 (yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true })).comments[0]
977 ?.body,
978 ).toBe("updated");
979 const refreshed = Latch.makeUnsafe();
980 const stop = registry.subscribe(activity, (result) => {
981 if (AsyncResult.isSuccess(result) && result.value.comments[0]?.body === "after turn") {
982 refreshed.openUnsafe();
983 }
984 });
985 yield* Effect.addFinalizer(() => Effect.sync(stop));
986
987 commentBody = "after turn";
988 yield* PubSub.publish(refreshEvents, 1);
989 yield* refreshed.await;
990
991 expect(
992 (yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true })).comments[0]
993 ?.body,
994 ).toBe("after turn");
995 }),
996 ),
997);
998
999it.effect("updates cached labels after successful edits without rereading the host", () =>
1000 Effect.scoped(
1001 Effect.gen(function* () {
1002 let detailReads = 0;
1003 let candidateReads = 0;
1004 let refuse = false;
1005 let failDetail = false;
1006 const existing = { name: "existing", color: "111111" };
1007 const addedLabel = { name: "new", color: "abcdef" };
1008 const detailRefreshStarted = yield* Latch.make();
1009 const releaseDetailRefresh = yield* Latch.make();
1010 const client = {
1011 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
1012 [WS_METHODS.pullRequestsDetail]: () =>
1013 Effect.gen(function* () {
1014 detailReads++;
1015 if (failDetail) {
1016 yield* detailRefreshStarted.open;
1017 yield* releaseDetailRefresh.await;
1018 return yield* Effect.fail(new MutationRefused());
1019 }
1020 return { title: "keep this title", labels: [existing] };
1021 }),
1022 [WS_METHODS.pullRequestsLabelCandidates]: () =>
1023 Effect.sync(() => {
1024 candidateReads++;
1025 return {
1026 candidates: [
1027 { ...existing, description: null, isApplied: true },
1028 { ...addedLabel, description: "description", isApplied: false },
1029 ],
1030 truncated: false,
1031 };
1032 }),
1033 [WS_METHODS.pullRequestsSetLabels]: () =>
1034 refuse ? Effect.fail(new MutationRefused()) : Effect.void,
1035 } as unknown as WsRpcProtocolClient;
1036 const { atoms, registry } = yield* makeTestRuntime(client);
1037 const target = {
1038 environmentId: TARGET.environmentId,
1039 input: {
1040 projectId: ProjectId.make("project-1"),
1041 repository: "acme/web",
1042 number: 1,
1043 host: "github.example.com",
1044 },
1045 };
1046 const detail = atoms.detail(target);
1047 const candidates = atoms.labelCandidates(target);
1048 registry.mount(detail);
1049 const unmountCandidates = registry.mount(candidates);
1050 yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
1051 yield* AtomRegistry.getResult(registry, candidates, { suspendOnWaiting: true });
1052
1053 const added = yield* Effect.promise(() =>
1054 atoms.setLabels.run(registry, {
1055 ...target,
1056 input: {
1057 host: target.input.host,
1058 projectId: target.input.projectId,
1059 repository: target.input.repository,
1060 number: target.input.number,
1061 labels: ["new"],
1062 applied: true,
1063 },
1064 }),
1065 );
1066 expect(AsyncResult.isSuccess(added)).toBe(true);
1067 expect(yield* AtomRegistry.getResult(registry, detail)).toEqual({
1068 title: "keep this title",
1069 labels: [existing, addedLabel],
1070 });
1071 unmountCandidates();
1072 registry.mount(atoms.labelCandidates(target));
1073 expect((yield* AtomRegistry.getResult(registry, candidates)).candidates[1]).toEqual({
1074 ...addedLabel,
1075 description: "description",
1076 isApplied: true,
1077 });
1078
1079 for (const name of ["existing", "new"]) {
1080 refuse = name === "new";
1081 const result = yield* Effect.promise(() =>
1082 atoms.setLabels.run(registry, {
1083 ...target,
1084 input: { ...target.input, labels: [name], applied: false },
1085 }),
1086 );
1087 expect(result._tag).toBe(refuse ? "Failure" : "Success");
1088 expect((yield* AtomRegistry.getResult(registry, detail)).labels).toEqual([addedLabel]);
1089 expect((yield* AtomRegistry.getResult(registry, candidates)).candidates).toMatchObject([
1090 { name: "existing", isApplied: false },
1091 { name: "new", isApplied: true },
1092 ]);
1093 }
1094 expect(detailReads).toBe(1);
1095 expect(candidateReads).toBe(1);
1096
1097 failDetail = true;
1098 registry.refresh(detail);
1099 yield* detailRefreshStarted.await;
1100 expect(registry.get(detail).waiting).toBe(true);
1101 expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).labels).toEqual([
1102 addedLabel,
1103 ]);
1104 yield* releaseDetailRefresh.open;
1105 yield* Effect.exit(AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true }));
1106 expect(AsyncResult.isFailure(registry.get(detail))).toBe(true);
1107 expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).labels).toEqual([
1108 addedLabel,
1109 ]);
1110 failDetail = false;
1111 registry.refresh(detail);
1112 expect(
1113 (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).labels,
1114 ).toEqual([existing]);
1115 expect(detailReads).toBe(3);
1116 }),
1117 ),
1118);
1119
1120it.effect("updates reviewer requests and enriched reviewers without rereading the host", () =>
1121 Effect.scoped(
1122 Effect.gen(function* () {
1123 let reads = 0;
1124 let refuse = false;
1125 const actor = { login: "reviewer", name: "Reviewer", avatarUrl: null };
1126 const hostActor = { ...actor, login: "Reviewer" };
1127 let hostRequested = false;
1128 let reviewed = false;
1129 let pauseActivity = false;
1130 const activityStarted = yield* Latch.make();
1131 const client = {
1132 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
1133 [WS_METHODS.pullRequestsDetail]: () =>
1134 Effect.sync(() => {
1135 reads++;
1136 return { reviewers: hostRequested ? [hostActor] : [] };
1137 }),
1138 [WS_METHODS.pullRequestsActivity]: () =>
1139 Effect.gen(function* () {
1140 reads++;
1141 if (pauseActivity) {
1142 pauseActivity = false;
1143 yield* activityStarted.open;
1144 return yield* Effect.never;
1145 }
1146 return {
1147 reviewers: hostRequested ? [hostActor] : [],
1148 comments: reviewed ? [{ kind: "review-comment", author: hostActor }] : [],
1149 };
1150 }),
1151 [WS_METHODS.pullRequestsReviewerCandidates]: (input: { number: number }) =>
1152 input.number === 2
1153 ? Effect.never
1154 : Effect.sync(() => {
1155 reads++;
1156 return {
1157 candidates: [{ ...actor, id: "12", kind: "user", isRequested: false }],
1158 truncated: false,
1159 };
1160 }),
1161 [WS_METHODS.pullRequestsRequestReviewers]: (input: { requested: boolean }) =>
1162 refuse
1163 ? Effect.fail(new MutationRefused())
1164 : Effect.sync(() => {
1165 hostRequested = input.requested;
1166 }),
1167 } as unknown as WsRpcProtocolClient;
1168 const { atoms, registry } = yield* makeTestRuntime(client);
1169 const target = {
1170 environmentId: TARGET.environmentId,
1171 input: {
1172 projectId: ProjectId.make("project-1"),
1173 repository: "acme/web",
1174 number: 1,
1175 host: "github.example.com",
1176 },
1177 };
1178 const detail = atoms.detail(target);
1179 const activity = atoms.activity(target);
1180 const candidates = atoms.reviewerCandidates(target);
1181 registry.mount(detail);
1182 registry.mount(activity);
1183 registry.mount(candidates);
1184 yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
1185 yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true });
1186 yield* AtomRegistry.getResult(registry, candidates, { suspendOnWaiting: true });
1187 const request = (requested: boolean, reference = target) =>
1188 Effect.promise(() =>
1189 atoms.requestReviewers.run(registry, {
1190 ...reference,
1191 input: { ...reference.input, reviewers: [{ id: "12", kind: "user" }], requested },
1192 }),
1193 );
1194 for (const operation of ["request", "refuse", "remove"]) {
1195 refuse = operation === "refuse";
1196 expect((yield* request(operation === "request"))._tag).toBe(refuse ? "Failure" : "Success");
1197 const expected = operation === "remove" ? [] : [actor];
1198 expect((yield* AtomRegistry.getResult(registry, detail)).reviewers).toEqual(expected);
1199 expect((yield* AtomRegistry.getResult(registry, activity)).reviewers).toEqual(expected);
1200 expect((yield* AtomRegistry.getResult(registry, candidates)).candidates).toMatchObject([
1201 { isRequested: operation !== "remove" },
1202 ]);
1203 }
1204 expect(reads).toBe(3);
1205 // A slow activity read started before the write must not hide the new request.
1206 pauseActivity = true;
1207 registry.refresh(activity);
1208 yield* activityStarted.await;
1209 expect(AsyncResult.isSuccess(yield* request(true))).toBe(true);
1210 expect(
1211 (yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true })).reviewers,
1212 ).toEqual([hostActor]);
1213 expect(reads).toBe(5);
1214 expect(AsyncResult.isSuccess(yield* request(false))).toBe(true);
1215 expect((yield* AtomRegistry.getResult(registry, activity)).reviewers).toEqual([]);
1216
1217 reviewed = true;
1218 yield* request(true);
1219 registry.refresh(activity);
1220 yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true });
1221 yield* request(false);
1222 expect((yield* AtomRegistry.getResult(registry, activity)).reviewers).toEqual([hostActor]);
1223
1224 // A caller without an open picker still needs authoritative reviewer identities.
1225 const otherTarget = { ...target, input: { ...target.input, number: 2 } };
1226 const otherDetail = atoms.detail(otherTarget);
1227 registry.mount(otherDetail);
1228 yield* AtomRegistry.getResult(registry, otherDetail, { suspendOnWaiting: true });
1229 yield* request(true, otherTarget);
1230 expect(
1231 (yield* AtomRegistry.getResult(registry, otherDetail, { suspendOnWaiting: true }))
1232 .reviewers,
1233 ).toEqual([hostActor]);
1234 }),
1235 ),
1236);
1237
1238it.effect("refreshes stack state after reopening and head SHAs after a turn", () =>
1239 Effect.scoped(
1240 Effect.gen(function* () {
1241 const refreshEvents = yield* PubSub.unbounded<number>();
1242 let state: "closed" | "open" = "closed";
1243 let headSha = "old-head";
1244 const client = {
1245 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
1246 [WS_METHODS.pullRequestsStack]: () =>
1247 Effect.sync(
1248 () =>
1249 ({
1250 id: "stack-1",
1251 number: 1,
1252 url: "https://github.com/acme/web/pull/1",
1253 base: "main",
1254 layers: [
1255 {
1256 number: 1,
1257 headBranch: "feature",
1258 headSha,
1259 state,
1260 isDraft: false,
1261 },
1262 ],
1263 }) satisfies PullRequestStack,
1264 ),
1265 } as unknown as WsRpcProtocolClient;
1266 const { runtime, registry } = yield* makeTestRuntime(client);
1267 const stacks = createPullRequestStackAtomFamily(runtime);
1268 const stack = stacks({
1269 environmentId: TARGET.environmentId,
1270 input: {
1271 projectId: ProjectId.make("project-1"),
1272 repository: "acme/web",
1273 number: 1,
1274 },
1275 });
1276 const unmount = registry.mount(stack);
1277 yield* Effect.addFinalizer(() => Effect.sync(unmount));
1278 yield* Effect.promise(() => executeAtomQuery(registry, stack));
1279 expect((yield* AtomRegistry.getResult(registry, stack))?.layers[0]?.state).toBe("closed");
1280 state = "open";
1281 registry.refresh(stack);
1282 expect(
1283 (yield* AtomRegistry.getResult(registry, stack, { suspendOnWaiting: true }))?.layers[0]
1284 ?.state,
1285 ).toBe("open");
1286
1287 const refreshed = Latch.makeUnsafe();
1288 const stop = registry.subscribe(stack, (result) => {
1289 if (AsyncResult.isSuccess(result) && result.value?.layers[0]?.headSha === "new-head") {
1290 refreshed.openUnsafe();
1291 }
1292 });
1293 yield* Effect.addFinalizer(() => Effect.sync(stop));
1294 headSha = "new-head";
1295 yield* PubSub.publish(refreshEvents, 1);
1296 yield* refreshed.await;
1297 expect((yield* AtomRegistry.getResult(registry, stack))?.layers[0]?.headSha).toBe("new-head");
1298 }),
1299 ),
1300);