Open History to see the last commit
1import { EnvironmentId, ProjectId, WS_METHODS, type PullRequestStack } from "@t3tools/contracts";
2import { expect, it } from "@effect/vitest";
3import * as Data from "effect/Data";
4import * as Effect from "effect/Effect";
5import * as Latch from "effect/Latch";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as PubSub from "effect/PubSub";
9import * as Stream from "effect/Stream";
10import * as SubscriptionRef from "effect/SubscriptionRef";
11import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
12
13import {
14 AVAILABLE_CONNECTION_STATE,
15 PrimaryConnectionTarget,
16 type PreparedConnection,
17 type SupervisorConnectionState,
18} from "../connection/model.ts";
19import * as EnvironmentRegistry from "../connection/registry.ts";
20import * as EnvironmentSupervisor from "../connection/supervisor.ts";
21import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
22import type { RpcSession } from "../rpc/session.ts";
23import {
24 createPullRequestEnvironmentAtoms,
25 createPullRequestStackAtomFamily,
26} from "./pullRequests.ts";
27import { PullRequestDiffLoader } from "./pullRequestDiffHttp.ts";
28import { executeAtomQuery } from "./runtime.ts";
29
30class MutationRefused extends Data.TaggedError("MutationRefused") {}
31
32const TARGET = new PrimaryConnectionTarget({
33 environmentId: EnvironmentId.make("environment-1"),
34 label: "Test environment",
35 httpBaseUrl: "https://environment.example.test",
36 wsBaseUrl: "wss://environment.example.test",
37});
38
39function session(client: WsRpcProtocolClient): RpcSession {
40 return {
41 client,
42 initialConfig: Effect.never,
43 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
44 ready: Effect.void,
45 probe: Effect.void,
46 closed: Effect.never,
47 };
48}
49
50const makeTestRuntime = Effect.fn("makeTestRuntime")(function* (client: WsRpcProtocolClient) {
51 const connectionState: SupervisorConnectionState = {
52 ...AVAILABLE_CONNECTION_STATE,
53 desired: true,
54 network: "online",
55 phase: "connected",
56 attempt: 1,
57 generation: 1,
58 };
59 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
60 target: TARGET,
61 state: yield* SubscriptionRef.make(connectionState),
62 session: yield* SubscriptionRef.make(Option.some(session(client))),
63 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
64 connect: Effect.void,
65 disconnect: Effect.void,
66 retryNow: Effect.void,
67 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
68 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
69 run: (_environmentId, effect) =>
70 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
71 runStream: (_environmentId, stream) =>
72 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
73 followStream: (_environmentId, stream) =>
74 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
75 } as EnvironmentRegistry.EnvironmentRegistry["Service"]);
76 const runtime = Atom.runtime(
77 Layer.merge(
78 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
79 Layer.succeed(
80 PullRequestDiffLoader,
81 PullRequestDiffLoader.of({ load: () => Effect.die("unused") }),
82 ),
83 ),
84 );
85 const atoms = createPullRequestEnvironmentAtoms(runtime);
86 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
87 Effect.sync(() => registry.dispose()),
88 );
89 return { runtime, atoms, registry };
90});
91
92it.effect("keeps concurrent diff file reads on different hosts separate", () =>
93 Effect.scoped(
94 Effect.gen(function* () {
95 const release = yield* Latch.make();
96 const started = yield* Latch.make();
97 const calls: string[] = [];
98 const client = {
99 [WS_METHODS.pullRequestsDiffFileContents]: (input: { readonly host: string }) =>
100 Effect.gen(function* () {
101 calls.push(input.host);
102 yield* started.open;
103 yield* release.await;
104 return { oldContents: "", newContents: input.host };
105 }),
106 } as unknown as WsRpcProtocolClient;
107 const { atoms, registry } = yield* makeTestRuntime(client);
108 const input = {
109 projectId: ProjectId.make("project-1"),
110 repository: "acme/web",
111 number: 1,
112 changeType: "change",
113 oldPath: "src/app.ts",
114 newPath: "src/app.ts",
115 } as const;
116 const first = atoms.diffFileContents.run(registry, {
117 environmentId: TARGET.environmentId,
118 input: { ...input, host: "github.com" },
119 });
120 yield* started.await;
121 const second = atoms.diffFileContents.run(registry, {
122 environmentId: TARGET.environmentId,
123 input: { ...input, host: "github.example.com" },
124 });
125 yield* release.open;
126
127 const results = yield* Effect.promise(() => Promise.all([first, second]));
128 expect(results).toMatchObject([
129 { _tag: "Success", value: { newContents: "github.com" } },
130 { _tag: "Success", value: { newContents: "github.example.com" } },
131 ]);
132 expect(calls).toEqual(["github.com", "github.example.com"]);
133 }),
134 ),
135);
136
137it.effect("refreshes pull request activity after a comment is updated", () =>
138 Effect.scoped(
139 Effect.gen(function* () {
140 const refreshEvents = yield* PubSub.unbounded<number>();
141 let commentBody = "old comment";
142 const client = {
143 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
144 [WS_METHODS.pullRequestsActivity]: () =>
145 Effect.succeed({
146 author: null,
147 reviewers: [],
148 comments: [
149 {
150 id: "comment-1",
151 kind: "issue-comment",
152 author: null,
153 body: commentBody,
154 createdAt: "2026-08-24T00:00:00Z",
155 url: null,
156 path: null,
157 reviewState: null,
158 reactions: [],
159 },
160 ],
161 commentCount: 1,
162 commentsTruncated: false,
163 reviewThreads: [],
164 commits: [],
165 reactions: [],
166 }),
167 [WS_METHODS.pullRequestsUpdateComment]: (input: { readonly body: string }) =>
168 Effect.sync(() => {
169 commentBody = input.body;
170 }),
171 } as unknown as WsRpcProtocolClient;
172 const { atoms, registry } = yield* makeTestRuntime(client);
173 const reference = {
174 projectId: ProjectId.make("project-1"),
175 host: "github.example.com",
176 repository: "acme/web",
177 number: 1,
178 } as const;
179 const activity = atoms.activity({ environmentId: TARGET.environmentId, input: reference });
180 const unmount = registry.mount(activity);
181 yield* Effect.addFinalizer(() => Effect.sync(unmount));
182
183 const initial = yield* Effect.promise(() => executeAtomQuery(registry, activity));
184 expect(AsyncResult.isSuccess(initial)).toBe(true);
185 if (!AsyncResult.isSuccess(initial)) {
186 return yield* Effect.die("activity did not load");
187 }
188 expect(initial.value.comments[0]?.body).toBe("old comment");
189
190 const update = yield* Effect.promise(() =>
191 atoms.updateComment.run(registry, {
192 environmentId: TARGET.environmentId,
193 input: { ...reference, commentId: "comment-1", kind: "issue-comment", body: "updated" },
194 }),
195 );
196
197 expect(AsyncResult.isSuccess(update)).toBe(true);
198 expect(
199 (yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true })).comments[0]
200 ?.body,
201 ).toBe("updated");
202 const refreshed = Latch.makeUnsafe();
203 const stop = registry.subscribe(activity, (result) => {
204 if (AsyncResult.isSuccess(result) && result.value.comments[0]?.body === "after turn") {
205 refreshed.openUnsafe();
206 }
207 });
208 yield* Effect.addFinalizer(() => Effect.sync(stop));
209
210 commentBody = "after turn";
211 yield* PubSub.publish(refreshEvents, 1);
212 yield* refreshed.await;
213
214 expect(
215 (yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true })).comments[0]
216 ?.body,
217 ).toBe("after turn");
218 }),
219 ),
220);
221
222it.effect("updates cached labels after successful edits without rereading the host", () =>
223 Effect.scoped(
224 Effect.gen(function* () {
225 let detailReads = 0;
226 let candidateReads = 0;
227 let refuse = false;
228 let failDetail = false;
229 const existing = { name: "existing", color: "111111" };
230 const addedLabel = { name: "new", color: "abcdef" };
231 const detailRefreshStarted = yield* Latch.make();
232 const releaseDetailRefresh = yield* Latch.make();
233 const client = {
234 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
235 [WS_METHODS.pullRequestsDetail]: () =>
236 Effect.gen(function* () {
237 detailReads++;
238 if (failDetail) {
239 yield* detailRefreshStarted.open;
240 yield* releaseDetailRefresh.await;
241 return yield* Effect.fail(new MutationRefused());
242 }
243 return { title: "keep this title", labels: [existing] };
244 }),
245 [WS_METHODS.pullRequestsLabelCandidates]: () =>
246 Effect.sync(() => {
247 candidateReads++;
248 return {
249 candidates: [
250 { ...existing, description: null, isApplied: true },
251 { ...addedLabel, description: "description", isApplied: false },
252 ],
253 truncated: false,
254 };
255 }),
256 [WS_METHODS.pullRequestsSetLabels]: () =>
257 refuse ? Effect.fail(new MutationRefused()) : Effect.void,
258 } as unknown as WsRpcProtocolClient;
259 const { atoms, registry } = yield* makeTestRuntime(client);
260 const target = {
261 environmentId: TARGET.environmentId,
262 input: {
263 projectId: ProjectId.make("project-1"),
264 repository: "acme/web",
265 number: 1,
266 host: "github.example.com",
267 },
268 };
269 const detail = atoms.detail(target);
270 const candidates = atoms.labelCandidates(target);
271 registry.mount(detail);
272 const unmountCandidates = registry.mount(candidates);
273 yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
274 yield* AtomRegistry.getResult(registry, candidates, { suspendOnWaiting: true });
275
276 const added = yield* Effect.promise(() =>
277 atoms.setLabels.run(registry, {
278 ...target,
279 input: {
280 host: target.input.host,
281 projectId: target.input.projectId,
282 repository: target.input.repository,
283 number: target.input.number,
284 labels: ["new"],
285 applied: true,
286 },
287 }),
288 );
289 expect(AsyncResult.isSuccess(added)).toBe(true);
290 expect(yield* AtomRegistry.getResult(registry, detail)).toEqual({
291 title: "keep this title",
292 labels: [existing, addedLabel],
293 });
294 unmountCandidates();
295 registry.mount(atoms.labelCandidates(target));
296 expect((yield* AtomRegistry.getResult(registry, candidates)).candidates[1]).toEqual({
297 ...addedLabel,
298 description: "description",
299 isApplied: true,
300 });
301
302 for (const name of ["existing", "new"]) {
303 refuse = name === "new";
304 const result = yield* Effect.promise(() =>
305 atoms.setLabels.run(registry, {
306 ...target,
307 input: { ...target.input, labels: [name], applied: false },
308 }),
309 );
310 expect(result._tag).toBe(refuse ? "Failure" : "Success");
311 expect((yield* AtomRegistry.getResult(registry, detail)).labels).toEqual([addedLabel]);
312 expect((yield* AtomRegistry.getResult(registry, candidates)).candidates).toMatchObject([
313 { name: "existing", isApplied: false },
314 { name: "new", isApplied: true },
315 ]);
316 }
317 expect(detailReads).toBe(1);
318 expect(candidateReads).toBe(1);
319
320 failDetail = true;
321 registry.refresh(detail);
322 yield* detailRefreshStarted.await;
323 expect(registry.get(detail).waiting).toBe(true);
324 expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).labels).toEqual([
325 addedLabel,
326 ]);
327 yield* releaseDetailRefresh.open;
328 yield* Effect.exit(AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true }));
329 expect(AsyncResult.isFailure(registry.get(detail))).toBe(true);
330 expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).labels).toEqual([
331 addedLabel,
332 ]);
333 failDetail = false;
334 registry.refresh(detail);
335 expect(
336 (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).labels,
337 ).toEqual([existing]);
338 expect(detailReads).toBe(3);
339 }),
340 ),
341);
342
343it.effect("updates reviewer requests and enriched reviewers without rereading the host", () =>
344 Effect.scoped(
345 Effect.gen(function* () {
346 let reads = 0;
347 let refuse = false;
348 const actor = { login: "reviewer", name: "Reviewer", avatarUrl: null };
349 const hostActor = { ...actor, login: "Reviewer" };
350 let hostRequested = false;
351 let reviewed = false;
352 let pauseActivity = false;
353 const activityStarted = yield* Latch.make();
354 const client = {
355 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
356 [WS_METHODS.pullRequestsDetail]: () =>
357 Effect.sync(() => {
358 reads++;
359 return { reviewers: hostRequested ? [hostActor] : [] };
360 }),
361 [WS_METHODS.pullRequestsActivity]: () =>
362 Effect.gen(function* () {
363 reads++;
364 if (pauseActivity) {
365 pauseActivity = false;
366 yield* activityStarted.open;
367 return yield* Effect.never;
368 }
369 return {
370 reviewers: hostRequested ? [hostActor] : [],
371 comments: reviewed ? [{ kind: "review-comment", author: hostActor }] : [],
372 };
373 }),
374 [WS_METHODS.pullRequestsReviewerCandidates]: (input: { number: number }) =>
375 input.number === 2
376 ? Effect.never
377 : Effect.sync(() => {
378 reads++;
379 return {
380 candidates: [{ ...actor, id: "12", kind: "user", isRequested: false }],
381 truncated: false,
382 };
383 }),
384 [WS_METHODS.pullRequestsRequestReviewers]: (input: { requested: boolean }) =>
385 refuse
386 ? Effect.fail(new MutationRefused())
387 : Effect.sync(() => {
388 hostRequested = input.requested;
389 }),
390 } as unknown as WsRpcProtocolClient;
391 const { atoms, registry } = yield* makeTestRuntime(client);
392 const target = {
393 environmentId: TARGET.environmentId,
394 input: {
395 projectId: ProjectId.make("project-1"),
396 repository: "acme/web",
397 number: 1,
398 host: "github.example.com",
399 },
400 };
401 const detail = atoms.detail(target);
402 const activity = atoms.activity(target);
403 const candidates = atoms.reviewerCandidates(target);
404 registry.mount(detail);
405 registry.mount(activity);
406 registry.mount(candidates);
407 yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
408 yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true });
409 yield* AtomRegistry.getResult(registry, candidates, { suspendOnWaiting: true });
410 const request = (requested: boolean, reference = target) =>
411 Effect.promise(() =>
412 atoms.requestReviewers.run(registry, {
413 ...reference,
414 input: { ...reference.input, reviewers: [{ id: "12", kind: "user" }], requested },
415 }),
416 );
417 for (const operation of ["request", "refuse", "remove"]) {
418 refuse = operation === "refuse";
419 expect((yield* request(operation === "request"))._tag).toBe(refuse ? "Failure" : "Success");
420 const expected = operation === "remove" ? [] : [actor];
421 expect((yield* AtomRegistry.getResult(registry, detail)).reviewers).toEqual(expected);
422 expect((yield* AtomRegistry.getResult(registry, activity)).reviewers).toEqual(expected);
423 expect((yield* AtomRegistry.getResult(registry, candidates)).candidates).toMatchObject([
424 { isRequested: operation !== "remove" },
425 ]);
426 }
427 expect(reads).toBe(3);
428 // A slow activity read started before the write must not hide the new request.
429 pauseActivity = true;
430 registry.refresh(activity);
431 yield* activityStarted.await;
432 expect(AsyncResult.isSuccess(yield* request(true))).toBe(true);
433 expect(
434 (yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true })).reviewers,
435 ).toEqual([hostActor]);
436 expect(reads).toBe(5);
437 expect(AsyncResult.isSuccess(yield* request(false))).toBe(true);
438 expect((yield* AtomRegistry.getResult(registry, activity)).reviewers).toEqual([]);
439
440 reviewed = true;
441 yield* request(true);
442 registry.refresh(activity);
443 yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true });
444 yield* request(false);
445 expect((yield* AtomRegistry.getResult(registry, activity)).reviewers).toEqual([hostActor]);
446
447 // A caller without an open picker still needs authoritative reviewer identities.
448 const otherTarget = { ...target, input: { ...target.input, number: 2 } };
449 const otherDetail = atoms.detail(otherTarget);
450 registry.mount(otherDetail);
451 yield* AtomRegistry.getResult(registry, otherDetail, { suspendOnWaiting: true });
452 yield* request(true, otherTarget);
453 expect(
454 (yield* AtomRegistry.getResult(registry, otherDetail, { suspendOnWaiting: true }))
455 .reviewers,
456 ).toEqual([hostActor]);
457 }),
458 ),
459);
460
461it.effect("refreshes stack state after reopening and head SHAs after a turn", () =>
462 Effect.scoped(
463 Effect.gen(function* () {
464 const refreshEvents = yield* PubSub.unbounded<number>();
465 let state: "closed" | "open" = "closed";
466 let headSha = "old-head";
467 const client = {
468 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
469 [WS_METHODS.pullRequestsStack]: () =>
470 Effect.sync(
471 () =>
472 ({
473 id: "stack-1",
474 number: 1,
475 url: "https://github.com/acme/web/pull/1",
476 base: "main",
477 layers: [
478 {
479 number: 1,
480 headBranch: "feature",
481 headSha,
482 state,
483 isDraft: false,
484 },
485 ],
486 }) satisfies PullRequestStack,
487 ),
488 } as unknown as WsRpcProtocolClient;
489 const { runtime, registry } = yield* makeTestRuntime(client);
490 const stacks = createPullRequestStackAtomFamily(runtime);
491 const stack = stacks({
492 environmentId: TARGET.environmentId,
493 input: {
494 projectId: ProjectId.make("project-1"),
495 repository: "acme/web",
496 number: 1,
497 },
498 });
499 const unmount = registry.mount(stack);
500 yield* Effect.addFinalizer(() => Effect.sync(unmount));
501 yield* Effect.promise(() => executeAtomQuery(registry, stack));
502 expect((yield* AtomRegistry.getResult(registry, stack))?.layers[0]?.state).toBe("closed");
503 state = "open";
504 registry.refresh(stack);
505 expect(
506 (yield* AtomRegistry.getResult(registry, stack, { suspendOnWaiting: true }))?.layers[0]
507 ?.state,
508 ).toBe("open");
509
510 const refreshed = Latch.makeUnsafe();
511 const stop = registry.subscribe(stack, (result) => {
512 if (AsyncResult.isSuccess(result) && result.value?.layers[0]?.headSha === "new-head") {
513 refreshed.openUnsafe();
514 }
515 });
516 yield* Effect.addFinalizer(() => Effect.sync(stop));
517 headSha = "new-head";
518 yield* PubSub.publish(refreshEvents, 1);
519 yield* refreshed.await;
520 expect((yield* AtomRegistry.getResult(registry, stack))?.layers[0]?.headSha).toBe("new-head");
521 }),
522 ),
523);