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 Effect from "effect/Effect";
4import * as Latch from "effect/Latch";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as PubSub from "effect/PubSub";
8import * as Stream from "effect/Stream";
9import * as SubscriptionRef from "effect/SubscriptionRef";
10import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
11
12import {
13 AVAILABLE_CONNECTION_STATE,
14 PrimaryConnectionTarget,
15 type PreparedConnection,
16 type SupervisorConnectionState,
17} from "../connection/model.ts";
18import * as EnvironmentRegistry from "../connection/registry.ts";
19import * as EnvironmentSupervisor from "../connection/supervisor.ts";
20import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
21import type { RpcSession } from "../rpc/session.ts";
22import {
23 createPullRequestEnvironmentAtoms,
24 createPullRequestStackAtomFamily,
25} from "./pullRequests.ts";
26import { PullRequestDiffLoader } from "./pullRequestDiffHttp.ts";
27import { executeAtomQuery } from "./runtime.ts";
28
29const TARGET = new PrimaryConnectionTarget({
30 environmentId: EnvironmentId.make("environment-1"),
31 label: "Test environment",
32 httpBaseUrl: "https://environment.example.test",
33 wsBaseUrl: "wss://environment.example.test",
34});
35
36function session(client: WsRpcProtocolClient): RpcSession {
37 return {
38 client,
39 initialConfig: Effect.never,
40 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
41 ready: Effect.void,
42 probe: Effect.void,
43 closed: Effect.never,
44 };
45}
46
47const makeTestRuntime = Effect.fn("makeTestRuntime")(function* (client: WsRpcProtocolClient) {
48 const connectionState: SupervisorConnectionState = {
49 ...AVAILABLE_CONNECTION_STATE,
50 desired: true,
51 network: "online",
52 phase: "connected",
53 attempt: 1,
54 generation: 1,
55 };
56 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
57 target: TARGET,
58 state: yield* SubscriptionRef.make(connectionState),
59 session: yield* SubscriptionRef.make(Option.some(session(client))),
60 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
61 connect: Effect.void,
62 disconnect: Effect.void,
63 retryNow: Effect.void,
64 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
65 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
66 run: (_environmentId, effect) =>
67 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
68 runStream: (_environmentId, stream) =>
69 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
70 followStream: (_environmentId, stream) =>
71 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
72 } as EnvironmentRegistry.EnvironmentRegistry["Service"]);
73 const runtime = Atom.runtime(
74 Layer.merge(
75 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
76 Layer.succeed(
77 PullRequestDiffLoader,
78 PullRequestDiffLoader.of({ load: () => Effect.die("unused") }),
79 ),
80 ),
81 );
82 const atoms = createPullRequestEnvironmentAtoms(runtime);
83 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
84 Effect.sync(() => registry.dispose()),
85 );
86 return { runtime, atoms, registry };
87});
88
89it.effect("keeps concurrent diff file reads on different hosts separate", () =>
90 Effect.scoped(
91 Effect.gen(function* () {
92 const release = yield* Latch.make();
93 const started = yield* Latch.make();
94 const calls: string[] = [];
95 const client = {
96 [WS_METHODS.pullRequestsDiffFileContents]: (input: { readonly host: string }) =>
97 Effect.gen(function* () {
98 calls.push(input.host);
99 yield* started.open;
100 yield* release.await;
101 return { oldContents: "", newContents: input.host };
102 }),
103 } as unknown as WsRpcProtocolClient;
104 const { atoms, registry } = yield* makeTestRuntime(client);
105 const input = {
106 projectId: ProjectId.make("project-1"),
107 repository: "acme/web",
108 number: 1,
109 changeType: "change",
110 oldPath: "src/app.ts",
111 newPath: "src/app.ts",
112 } as const;
113 const first = atoms.diffFileContents.run(registry, {
114 environmentId: TARGET.environmentId,
115 input: { ...input, host: "github.com" },
116 });
117 yield* started.await;
118 const second = atoms.diffFileContents.run(registry, {
119 environmentId: TARGET.environmentId,
120 input: { ...input, host: "github.example.com" },
121 });
122 yield* release.open;
123
124 const results = yield* Effect.promise(() => Promise.all([first, second]));
125 expect(results).toMatchObject([
126 { _tag: "Success", value: { newContents: "github.com" } },
127 { _tag: "Success", value: { newContents: "github.example.com" } },
128 ]);
129 expect(calls).toEqual(["github.com", "github.example.com"]);
130 }),
131 ),
132);
133
134it.effect("refreshes pull request activity after a comment is updated", () =>
135 Effect.scoped(
136 Effect.gen(function* () {
137 const refreshEvents = yield* PubSub.unbounded<number>();
138 let commentBody = "old comment";
139 const client = {
140 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
141 [WS_METHODS.pullRequestsActivity]: () =>
142 Effect.succeed({
143 author: null,
144 reviewers: [],
145 comments: [
146 {
147 id: "comment-1",
148 kind: "issue-comment",
149 author: null,
150 body: commentBody,
151 createdAt: "2026-08-24T00:00:00Z",
152 url: null,
153 path: null,
154 reviewState: null,
155 reactions: [],
156 },
157 ],
158 commentCount: 1,
159 commentsTruncated: false,
160 reviewThreads: [],
161 commits: [],
162 reactions: [],
163 }),
164 [WS_METHODS.pullRequestsUpdateComment]: (input: { readonly body: string }) =>
165 Effect.sync(() => {
166 commentBody = input.body;
167 }),
168 } as unknown as WsRpcProtocolClient;
169 const { atoms, registry } = yield* makeTestRuntime(client);
170 const reference = {
171 projectId: ProjectId.make("project-1"),
172 host: "github.example.com",
173 repository: "acme/web",
174 number: 1,
175 } as const;
176 const activity = atoms.activity({ environmentId: TARGET.environmentId, input: reference });
177 const unmount = registry.mount(activity);
178 yield* Effect.addFinalizer(() => Effect.sync(unmount));
179
180 const initial = yield* Effect.promise(() => executeAtomQuery(registry, activity));
181 expect(AsyncResult.isSuccess(initial)).toBe(true);
182 if (!AsyncResult.isSuccess(initial)) {
183 return yield* Effect.die("activity did not load");
184 }
185 expect(initial.value.comments[0]?.body).toBe("old comment");
186
187 const update = yield* Effect.promise(() =>
188 atoms.updateComment.run(registry, {
189 environmentId: TARGET.environmentId,
190 input: { ...reference, commentId: "comment-1", kind: "issue-comment", body: "updated" },
191 }),
192 );
193
194 expect(AsyncResult.isSuccess(update)).toBe(true);
195 expect(
196 (yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true })).comments[0]
197 ?.body,
198 ).toBe("updated");
199 const refreshed = Latch.makeUnsafe();
200 const stop = registry.subscribe(activity, (result) => {
201 if (AsyncResult.isSuccess(result) && result.value.comments[0]?.body === "after turn") {
202 refreshed.openUnsafe();
203 }
204 });
205 yield* Effect.addFinalizer(() => Effect.sync(stop));
206
207 commentBody = "after turn";
208 yield* PubSub.publish(refreshEvents, 1);
209 yield* refreshed.await;
210
211 expect(
212 (yield* AtomRegistry.getResult(registry, activity, { suspendOnWaiting: true })).comments[0]
213 ?.body,
214 ).toBe("after turn");
215 }),
216 ),
217);
218
219it.effect("refreshes stack state after reopening and head SHAs after a turn", () =>
220 Effect.scoped(
221 Effect.gen(function* () {
222 const refreshEvents = yield* PubSub.unbounded<number>();
223 let state: "closed" | "open" = "closed";
224 let headSha = "old-head";
225 const client = {
226 [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
227 [WS_METHODS.pullRequestsStack]: () =>
228 Effect.sync(
229 () =>
230 ({
231 id: "stack-1",
232 number: 1,
233 url: "https://github.com/acme/web/pull/1",
234 base: "main",
235 layers: [
236 {
237 number: 1,
238 headBranch: "feature",
239 headSha,
240 state,
241 isDraft: false,
242 },
243 ],
244 }) satisfies PullRequestStack,
245 ),
246 } as unknown as WsRpcProtocolClient;
247 const { runtime, registry } = yield* makeTestRuntime(client);
248 const stacks = createPullRequestStackAtomFamily(runtime);
249 const stack = stacks({
250 environmentId: TARGET.environmentId,
251 input: {
252 projectId: ProjectId.make("project-1"),
253 repository: "acme/web",
254 number: 1,
255 },
256 });
257 const unmount = registry.mount(stack);
258 yield* Effect.addFinalizer(() => Effect.sync(unmount));
259 yield* Effect.promise(() => executeAtomQuery(registry, stack));
260 expect((yield* AtomRegistry.getResult(registry, stack))?.layers[0]?.state).toBe("closed");
261 state = "open";
262 registry.refresh(stack);
263 expect(
264 (yield* AtomRegistry.getResult(registry, stack, { suspendOnWaiting: true }))?.layers[0]
265 ?.state,
266 ).toBe("open");
267
268 const refreshed = Latch.makeUnsafe();
269 const stop = registry.subscribe(stack, (result) => {
270 if (AsyncResult.isSuccess(result) && result.value?.layers[0]?.headSha === "new-head") {
271 refreshed.openUnsafe();
272 }
273 });
274 yield* Effect.addFinalizer(() => Effect.sync(stop));
275 headSha = "new-head";
276 yield* PubSub.publish(refreshEvents, 1);
277 yield* refreshed.await;
278 expect((yield* AtomRegistry.getResult(registry, stack))?.layers[0]?.headSha).toBe("new-head");
279 }),
280 ),
281);