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

vcs.test.ts

919 lines33.9 KB

1import { vi } from "vite-plus/test";
2import {
3 EnvironmentId,
4 AuthSourceControlWriteScope,
5 WS_METHODS,
6 VcsProcessExitError,
7 type VcsListRefsInput,
8 type VcsListRefsResult,
9 type VcsStatusResult,
10 type ServerConfig,
11} from "@t3tools/contracts";
12import { describe, expect, it } from "@effect/vitest";
13import * as Deferred from "effect/Deferred";
14import * as Effect from "effect/Effect";
15import * as Exit from "effect/Exit";
16import * as Fiber from "effect/Fiber";
17import * as Layer from "effect/Layer";
18import * as Logger from "effect/Logger";
19import * as Option from "effect/Option";
20import * as Queue from "effect/Queue";
21import * as Ref from "effect/Ref";
22import * as Stream from "effect/Stream";
23import * as SubscriptionRef from "effect/SubscriptionRef";
24import * as TestClock from "effect/testing/TestClock";
25import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
26​
27import {
28 AVAILABLE_CONNECTION_STATE,
29 PrimaryConnectionTarget,
30 type PreparedConnection,
31 type SupervisorConnectionState,
32} from "../connection/model.ts";
33import * as EnvironmentRegistry from "../connection/registry.ts";
34import * as EnvironmentSupervisor from "../connection/supervisor.ts";
35import * as Persistence from "../platform/persistence.ts";
36import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
37import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
38import type { RpcSession } from "../rpc/session.ts";
39import { createGitEnvironmentAtoms } from "./git.ts";
40​
41import {
42 commitVcsRefsRefresh,
43 createVcsEnvironmentAtoms,
44 makeCachedVcsRefsChanges,
45 resolveQuickAction,
46} from "./vcs.ts";
47import {
48 invalidateCachedVcsRefs,
49 invalidateVcsRefs,
50 vcsRefsCacheStateAtom,
51} from "./vcsRefInvalidation.ts";
52​
53const TARGET = new PrimaryConnectionTarget({
54 environmentId: EnvironmentId.make("environment-1"),
55 label: "Test environment",
56 httpBaseUrl: "https://environment.example.test",
57 wsBaseUrl: "wss://environment.example.test",
58});
59​
60const CONNECTED_CONNECTION_STATE: SupervisorConnectionState = {
61 ...AVAILABLE_CONNECTION_STATE,
62 desired: true,
63 network: "online",
64 phase: "connected",
65 attempt: 1,
66 generation: 1,
67};
68​
69const CACHED_REFS: VcsListRefsResult = {
70 refs: [
71 {
72 name: "main",
73 current: true,
74 isDefault: true,
75 worktreePath: "/repo",
76 },
77 ],
78 isRepo: true,
79 hasPrimaryRemote: true,
80 nextCursor: null,
81 totalCount: 1,
82};
83​
84const LIVE_REFS: VcsListRefsResult = {
85 ...CACHED_REFS,
86 refs: [
87 {
88 name: "release",
89 current: true,
90 isDefault: true,
91 worktreePath: "/repo",
92 },
93 ],
94};
95​
96function session(client: WsRpcProtocolClient): RpcSession {
97 return {
98 client,
99 initialConfig: Effect.never,
100 subscribeServerConfig: (input = {}) => client.subscribeServerConfig(input),
101 ready: Effect.void,
102 probe: Effect.void,
103 inboundFrames: Effect.succeed(0),
104 closed: Effect.never,
105 };
107​
108function cacheWithRefs(
109 refs: Option.Option<VcsListRefsResult>,
110 overrides: Partial<Persistence.EnvironmentCacheStore["Service"]> = {},
111) {
112 return Persistence.EnvironmentCacheStore.of({
113 loadShell: () => Effect.succeedNone,
114 saveShell: () => Effect.void,
115 loadThread: () => Effect.succeedNone,
116 saveThread: () => Effect.void,
117 removeThread: () => Effect.void,
118 loadServerConfig: () => Effect.succeedNone,
119 saveServerConfig: () => Effect.void,
120 loadVcsRefs: () => Effect.succeed(refs),
121 saveVcsRefs: () => Effect.void,
122 removeVcsRefs: () => Effect.void,
123 clearVcsRefs: () => Effect.void,
124 clear: () => Effect.void,
125 ...overrides,
126 });
128​
129describe("branch subscriptions", () => {
130 it.effect.each([true, false])(
131 "shares and releases branch streams across session replacement (capability %s)",
132 (supported) =>
133 Effect.gen(function* () {
134 const released = yield* Queue.unbounded<string>();
135 let subscriptions = 0;
136 const clientFor = (refName: string, branchSupported: boolean) =>
137 ({
138 [branchSupported ? WS_METHODS.subscribeVcsBranch : WS_METHODS.subscribeVcsStatus]:
139 () => {
140 subscriptions += 1;
141 return Stream.concat(
142 Stream.make(
143 branchSupported
144 ? { refName, isRepo: true }
145 : { _tag: "snapshot", local: status({ refName }), remote: null },
146 ),
147 Stream.never,
148 ).pipe(Stream.ensuring(Queue.offer(released, refName)));
149 },
150 }) as unknown as WsRpcProtocolClient;
151 const branchSession = (refName: string, branchSupported: boolean): RpcSession => ({
152 ...session(clientFor(refName, branchSupported)),
153 initialConfig: Effect.succeed({
154 environment: { capabilities: branchSupported ? { vcsBranchStatus: true } : {} },
155 } as ServerConfig),
156 });
157 const activeSession = yield* SubscriptionRef.make(
158 Option.some(branchSession("main", supported)),
159 );
160 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
161 target: TARGET,
162 state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
163 session: activeSession,
164 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
165 connect: Effect.void,
166 disconnect: Effect.void,
167 retryNow: Effect.void,
168 });
169 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
170 followStream: (_environmentId, stream) =>
171 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
172 } as EnvironmentRegistry.EnvironmentRegistry["Service"]);
173 const runtime = Atom.runtime(
174 Layer.merge(
175 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
176 Layer.succeed(Persistence.EnvironmentCacheStore, cacheWithRefs(Option.none())),
177 ),
178 );
179 const atoms = createVcsEnvironmentAtoms(runtime);
180 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (value) =>
181 Effect.sync(() => value.dispose()),
182 );
183 const target = { environmentId: TARGET.environmentId, input: { cwd: "/repo" } };
184 const first = yield* Stream.toPull(
185 AtomRegistry.toStreamResult(registry, atoms.branch(target)),
186 );
187 expect(yield* first).toEqual([{ refName: "main", isRepo: true }]);
188 const second = yield* Stream.toPull(
189 AtomRegistry.toStreamResult(registry, atoms.branch(target)),
190 );
191 expect(yield* second).toEqual([{ refName: "main", isRepo: true }]);
192 expect(subscriptions).toBe(1);
193 yield* SubscriptionRef.set(
194 activeSession,
195 Option.some(branchSession("external", !supported)),
196 );
197 expect(yield* Queue.take(released)).toBe("main");
198 expect(yield* first).toEqual([{ refName: "external", isRepo: true }]);
199 expect(yield* second).toEqual([{ refName: "external", isRepo: true }]);
200 registry.dispose();
201 expect(yield* Queue.take(released)).toBe("external");
202 }),
203 );
204});
205​
206describe("cached VCS refs", () => {
207 it("invalidates all ref streams in the mutated environment", () => {
208 const registry = AtomRegistry.make();
209 const environment = {
210 environmentId: TARGET.environmentId,
211 };
212 const otherEnvironment = {
213 environmentId: EnvironmentId.make("environment-2"),
214 };
215​
216 expect(registry.get(vcsRefsCacheStateAtom(environment))).toEqual({
217 revision: 0,
218 persistedCacheReadable: true,
219 });
220 expect(registry.get(vcsRefsCacheStateAtom(otherEnvironment))).toEqual({
221 revision: 0,
222 persistedCacheReadable: true,
223 });
224​
225 invalidateVcsRefs(registry, environment);
226​
227 expect(registry.get(vcsRefsCacheStateAtom(environment))).toEqual({
228 revision: 1,
229 persistedCacheReadable: true,
230 });
231 expect(registry.get(vcsRefsCacheStateAtom(otherEnvironment))).toEqual({
232 revision: 0,
233 persistedCacheReadable: true,
234 });
235 registry.dispose();
236 });
237​
238 it.effect("bypasses the server ref snapshot when a mounted list is invalidated", () =>
239 Effect.gen(function* () {
240 const requests = yield* Queue.unbounded<VcsListRefsInput>();
241 const client = {
242 [WS_METHODS.vcsListRefs]: (input: VcsListRefsInput) =>
243 Effect.sync(() => {
244 Queue.offerUnsafe(requests, input);
245 return LIVE_REFS;
246 }),
247 } as unknown as WsRpcProtocolClient;
248 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
249 target: TARGET,
250 state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
251 session: yield* SubscriptionRef.make(Option.some(session(client))),
252 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
253 connect: Effect.void,
254 disconnect: Effect.void,
255 retryNow: Effect.void,
256 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
257 const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
258 _environmentId,
259 stream,
260 ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
261 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
262 followStream,
263 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
264 const runtime = Atom.runtime(
265 Layer.merge(
266 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
267 Layer.succeed(Persistence.EnvironmentCacheStore, cacheWithRefs(Option.none())),
268 ),
269 );
270 const atoms = createVcsEnvironmentAtoms(runtime);
271 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
272 Effect.sync(() => registry.dispose()),
273 );
274 yield* Effect.acquireRelease(
275 Effect.sync(() =>
276 registry.mount(
277 atoms.listRefs({
278 environmentId: TARGET.environmentId,
279 input: { cwd: "/repo", limit: 100 },
280 }),
281 ),
282 ),
283 (unmount) => Effect.sync(unmount),
284 );
285​
286 expect(yield* Queue.take(requests)).toEqual({ cwd: "/repo", limit: 100 });
287​
288 invalidateVcsRefs(registry, TARGET);
289​
290 expect(yield* Queue.take(requests)).toEqual({ cwd: "/repo", limit: 100, refresh: true });
291​
292 yield* Effect.acquireRelease(
293 Effect.sync(() =>
294 registry.mount(
295 atoms.listRefs({
296 environmentId: TARGET.environmentId,
297 input: { cwd: "/other-repo", limit: 100 },
298 }),
299 ),
300 ),
301 (unmount) => Effect.sync(unmount),
302 );
303 expect(yield* Queue.take(requests)).toEqual({
304 cwd: "/other-repo",
305 limit: 100,
306 refresh: true,
307 });
308​
309 yield* Effect.acquireRelease(
310 Effect.sync(() =>
311 registry.mount(
312 atoms.listRefs({
313 environmentId: TARGET.environmentId,
314 input: { cwd: "/other-repo", query: "release", limit: 100 },
315 }),
316 ),
317 ),
318 (unmount) => Effect.sync(unmount),
319 );
320 expect(yield* Queue.take(requests)).toEqual({
321 cwd: "/other-repo",
322 query: "release",
323 limit: 100,
324 });
325 }),
326 );
327​
328 it.effect("does not repersist a refresh superseded by ref invalidation", () =>
329 Effect.gen(function* () {
330 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
331 Effect.sync(() => registry.dispose()),
332 );
333 const saved = yield* Ref.make<ReadonlyArray<VcsListRefsResult>>([]);
334 const clears = yield* Ref.make(0);
335 const revisionsObservedDuringClear = yield* Ref.make<ReadonlyArray<number>>([]);
336 const cache = cacheWithRefs(Option.none(), {
337 saveVcsRefs: (_environmentId, _cwd, refs) =>
338 Ref.update(saved, (current) => [...current, refs]),
339 clearVcsRefs: () =>
340 Effect.all([
341 Ref.update(clears, (count) => count + 1),
342 Ref.update(revisionsObservedDuringClear, (current) => [
343 ...current,
344 registry.get(vcsRefsCacheStateAtom(TARGET)).revision,
345 ]),
346 ]).pipe(Effect.asVoid),
347 });
348​
349 yield* invalidateCachedVcsRefs(registry, {
350 environmentId: TARGET.environmentId,
351 cwd: "/repo-worktree",
352 }).pipe(Effect.provideService(Persistence.EnvironmentCacheStore, cache));
353​
354 expect(
355 yield* commitVcsRefsRefresh(registry, cache, {
356 environmentId: TARGET.environmentId,
357 cwd: "/repo",
358 refs: CACHED_REFS,
359 expectedRevision: 0,
360 persist: true,
361 }),
362 ).toBe(false);
363​
364 expect(yield* Ref.get(saved)).toEqual([]);
365 expect(yield* Ref.get(clears)).toBe(1);
366 expect(yield* Ref.get(revisionsObservedDuringClear)).toEqual([0]);
367 expect(registry.get(vcsRefsCacheStateAtom(TARGET))).toEqual({
368 revision: 1,
369 persistedCacheReadable: true,
370 });
371​
372 expect(
373 yield* commitVcsRefsRefresh(registry, cache, {
374 environmentId: TARGET.environmentId,
375 cwd: "/repo",
376 refs: LIVE_REFS,
377 expectedRevision: 1,
378 persist: true,
379 }),
380 ).toBe(true);
381 expect(yield* Ref.get(saved)).toEqual([LIVE_REFS]);
382 }),
383 );
384​
385 it.effect("invalidates persisted refs when ref-affecting commands settle", () =>
386 Effect.gen(function* () {
387 const refsDigest = yield* Ref.make("refs-a");
388 const expectedError = new EnvironmentRpcUnavailableError({
389 environmentId: TARGET.environmentId,
390 message: "pull failed after fetching refs",
391 });
392 const client = {
393 [WS_METHODS.vcsPull]: () => Effect.fail(expectedError),
394 [WS_METHODS.vcsRefreshStatus]: () =>
395 Ref.get(refsDigest).pipe(Effect.map((digest) => ({ refsDigest: digest }))),
396 [WS_METHODS.gitPreparePullRequestThread]: () =>
397 Effect.succeed({ branch: "feature/pr", worktreePath: null }),
398 } as unknown as WsRpcProtocolClient;
399 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
400 target: TARGET,
401 state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
402 session: yield* SubscriptionRef.make(Option.some(session(client))),
403 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
404 connect: Effect.void,
405 disconnect: Effect.void,
406 retryNow: Effect.void,
407 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
408 const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (
409 _environmentId,
410 effect,
411 ) => Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
412 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
413 run,
414 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
415 const clears = yield* Ref.make(0);
416 const runtime = Atom.runtime(
417 Layer.merge(
418 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
419 Layer.succeed(
420 Persistence.EnvironmentCacheStore,
421 cacheWithRefs(Option.none(), {
422 clearVcsRefs: () => Ref.update(clears, (count) => count + 1),
423 }),
424 ),
425 ),
426 );
427 const atoms = createVcsEnvironmentAtoms(runtime);
428 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
429 Effect.sync(() => registry.dispose()),
430 );
431​
432 const result = yield* Effect.exit(
433 atoms.pull.run(registry, {
434 environmentId: TARGET.environmentId,
435 input: { cwd: "/repo" },
436 }),
437 );
438​
439 expect(Exit.isFailure(result)).toBe(true);
440 expect(yield* Ref.get(clears)).toBe(1);
441 expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(1);
442​
443 const refreshResult = yield* Effect.exit(
444 atoms.refreshStatus.run(registry, {
445 environmentId: TARGET.environmentId,
446 input: { cwd: "/repo" },
447 }),
448 );
449​
450 expect(Exit.isSuccess(refreshResult)).toBe(true);
451 expect(yield* Ref.get(clears)).toBe(2);
452 expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(2);
453​
454 const refreshStatus = atoms.refreshStatus.run(registry, {
455 environmentId: TARGET.environmentId,
456 input: { cwd: "/repo" },
457 });
458 yield* refreshStatus;
459 expect(yield* Ref.get(clears)).toBe(2);
460 expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(2);
461​
462 yield* Ref.set(refsDigest, "refs-b");
463 yield* refreshStatus;
464 expect(yield* Ref.get(clears)).toBe(3);
465 expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(3);
466​
467 yield* atoms.refreshLocalStatusForPicker.run(registry, {
468 environmentId: TARGET.environmentId,
469 input: { cwd: "/repo", localOnly: true },
470 });
471 expect(yield* Ref.get(clears)).toBe(3);
472 expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(3);
473​
474 const prepareResult = yield* Effect.exit(
475 createGitEnvironmentAtoms(runtime).preparePullRequestThread.run(registry, {
476 environmentId: TARGET.environmentId,
477 input: { cwd: "/repo", reference: "42", mode: "local" },
478 }),
479 );
480​
481 expect(Exit.isSuccess(prepareResult)).toBe(true);
482 expect(yield* Ref.get(clears)).toBe(4);
483 expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(4);
484 }),
485 );
486​
487 it.effect("a checkout does not wait behind a picker's local status refresh", () =>
488 Effect.gen(function* () {
489 const refreshStarted = yield* Deferred.make<void>();
490 const releaseRefresh = yield* Deferred.make<void>();
491 const client = {
492 [WS_METHODS.vcsRefreshStatus]: () =>
493 Deferred.succeed(refreshStarted, undefined).pipe(
494 Effect.andThen(Deferred.await(releaseRefresh)),
495 Effect.as({}),
496 ),
497 [WS_METHODS.vcsSwitchRef]: () => Effect.succeed({ refName: "feature" }),
498 } as unknown as WsRpcProtocolClient;
499 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
500 target: TARGET,
501 state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
502 session: yield* SubscriptionRef.make(Option.some(session(client))),
503 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
504 connect: Effect.void,
505 disconnect: Effect.void,
506 retryNow: Effect.void,
507 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
508 const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (
509 _environmentId,
510 effect,
511 ) => Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
512 const runtime = Atom.runtime(
513 Layer.merge(
514 Layer.succeed(
515 EnvironmentRegistry.EnvironmentRegistry,
516 EnvironmentRegistry.EnvironmentRegistry.of({
517 run,
518 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]),
519 ),
520 Layer.succeed(Persistence.EnvironmentCacheStore, cacheWithRefs(Option.none())),
521 ),
522 );
523 const atoms = createVcsEnvironmentAtoms(runtime);
524 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
525 Effect.sync(() => registry.dispose()),
526 );
527 const target = { environmentId: TARGET.environmentId, input: { cwd: "/repo" } };
528​
529 const refresh = yield* Effect.forkChild(
530 Effect.exit(
531 atoms.refreshLocalStatusForPicker.run(registry, {
532 ...target,
533 input: { cwd: "/repo", localOnly: true },
534 }),
535 ),
536 { startImmediately: true },
537 );
538 yield* Deferred.await(refreshStarted);
539 const checkout = yield* Effect.exit(
540 atoms.switchRef.run(registry, {
541 ...target,
542 input: { cwd: "/repo", refName: "feature" },
543 }),
544 );
545​
546 expect(Exit.isSuccess(checkout)).toBe(true);
547 yield* Deferred.succeed(releaseRefresh, undefined);
548 expect(Exit.isSuccess(yield* Fiber.join(refresh))).toBe(true);
549 }),
550 );
551​
552 it.effect("suppresses persisted snapshots after an environment-wide clear fails", () =>
553 Effect.gen(function* () {
554 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
555 Effect.sync(() => registry.dispose()),
556 );
557 const persisted = yield* Ref.make<Option.Option<VcsListRefsResult>>(Option.some(CACHED_REFS));
558 const loads = yield* Ref.make(0);
559 const clearAttempts = yield* Ref.make(0);
560 const cache = cacheWithRefs(Option.none(), {
561 loadVcsRefs: () =>
562 Ref.update(loads, (count) => count + 1).pipe(Effect.andThen(Ref.get(persisted))),
563 saveVcsRefs: (_environmentId, _cwd, refs) => Ref.set(persisted, Option.some(refs)),
564 clearVcsRefs: () =>
565 Ref.updateAndGet(clearAttempts, (count) => count + 1).pipe(
566 Effect.flatMap((attempt) =>
567 attempt === 1
568 ? Effect.fail(
569 new Persistence.ConnectionPersistenceError({
570 operation: "clear-vcs-refs",
571 message: "storage unavailable",
572 }),
573 )
574 : Ref.set(persisted, Option.none()),
575 ),
576 ),
577 });
578​
579 yield* invalidateCachedVcsRefs(registry, {
580 environmentId: TARGET.environmentId,
581 cwd: "/repo",
582 }).pipe(Effect.provideService(Persistence.EnvironmentCacheStore, cache));
583​
584 const state = registry.get(vcsRefsCacheStateAtom(TARGET));
585 expect(state).toEqual({
586 revision: 1,
587 persistedCacheReadable: false,
588 });
589​
590 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
591 target: TARGET,
592 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
593 session: yield* SubscriptionRef.make(Option.none<RpcSession>()),
594 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
595 connect: Effect.void,
596 disconnect: Effect.void,
597 retryNow: Effect.void,
598 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
599 const refs = yield* Stream.unwrap(
600 makeCachedVcsRefsChanges(
601 { cwd: "/repo", limit: 100 },
602 state.revision,
603 registry,
604 state.persistedCacheReadable,
605 ).pipe(
606 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
607 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
608 ),
609 ).pipe(Stream.runHead, Effect.forkChild({ startImmediately: true }));
610​
611 yield* Effect.yieldNow;
612 expect(yield* Ref.get(loads)).toBe(0);
613 yield* Fiber.interrupt(refs);
614 expect(registry.get(vcsRefsCacheStateAtom(TARGET))).toEqual(state);
615​
616 expect(
617 yield* commitVcsRefsRefresh(registry, cache, {
618 environmentId: TARGET.environmentId,
619 cwd: "/repo",
620 refs: LIVE_REFS,
621 expectedRevision: state.revision,
622 persist: true,
623 }),
624 ).toBe(true);
625 const recoveredState = registry.get(vcsRefsCacheStateAtom(TARGET));
626 expect(recoveredState).toEqual({
627 revision: 1,
628 persistedCacheReadable: true,
629 });
630 expect(yield* Ref.get(clearAttempts)).toBe(2);
631​
632 const recoveredRefs = yield* Stream.unwrap(
633 makeCachedVcsRefsChanges(
634 { cwd: "/repo", limit: 100 },
635 recoveredState.revision,
636 registry,
637 recoveredState.persistedCacheReadable,
638 ).pipe(
639 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
640 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
641 ),
642 ).pipe(Stream.runHead);
643​
644 expect(Option.getOrThrow(recoveredRefs)).toEqual(LIVE_REFS);
645 expect(yield* Ref.get(loads)).toBe(1);
646 }),
647 );
648​
649 it.effect("loads an unfiltered branch list without a connection", () =>
650 Effect.gen(function* () {
651 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
652 target: TARGET,
653 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
654 session: yield* SubscriptionRef.make(Option.none<RpcSession>()),
655 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
656 connect: Effect.void,
657 disconnect: Effect.void,
658 retryNow: Effect.void,
659 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
660 const refs = yield* Stream.unwrap(
661 makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
662 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
663 Effect.provideService(
664 Persistence.EnvironmentCacheStore,
665 cacheWithRefs(Option.some(CACHED_REFS)),
666 ),
667 ),
668 ).pipe(Stream.runHead);
669​
670 expect(Option.getOrThrow(refs)).toEqual(CACHED_REFS);
671 }),
672 );
673​
674 it.effect("waits silently for a session while the connection phase is still connected", () =>
675 Effect.gen(function* () {
676 const logs: unknown[] = [];
677 const logger = Logger.make(({ message }) => logs.push(message));
678 const liveSession = yield* SubscriptionRef.make(Option.none<RpcSession>());
679 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
680 target: TARGET,
681 state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
682 session: liveSession,
683 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
684 connect: Effect.void,
685 disconnect: Effect.void,
686 retryNow: Effect.void,
687 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
688 const refs = yield* Stream.unwrap(
689 makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
690 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
691 Effect.provideService(
692 Persistence.EnvironmentCacheStore,
693 cacheWithRefs(Option.some(CACHED_REFS)),
694 ),
695 ),
696 ).pipe(
697 Stream.take(2),
698 Stream.runCollect,
699 Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
700 Effect.forkChild({ startImmediately: true }),
701 );
702​
703 yield* TestClock.adjust("1 minute");
704 expect(logs).toEqual([]);
705​
706 const client = {
707 [WS_METHODS.vcsListRefs]: () => Effect.succeed(LIVE_REFS),
708 } as unknown as WsRpcProtocolClient;
709 yield* SubscriptionRef.set(liveSession, Option.some(session(client)));
710 expect(yield* Fiber.join(refs)).toEqual([CACHED_REFS, LIVE_REFS]);
711 expect(logs).toEqual([]);
712 }),
713 );
714​
715 it.effect("cancels an in-flight refresh and restarts when the RPC session changes", () =>
716 Effect.gen(function* () {
717 const started = yield* Deferred.make<void>();
718 const interrupted = yield* Deferred.make<void>();
719 const calls = yield* Ref.make(0);
720 const interruptions = yield* Ref.make(0);
721 const client = {
722 [WS_METHODS.vcsListRefs]: () =>
723 Ref.updateAndGet(calls, (count) => count + 1).pipe(
724 Effect.flatMap((count) =>
725 count === 1
726 ? Deferred.succeed(started, undefined).pipe(
727 Effect.andThen(Effect.never),
728 Effect.onInterrupt(() =>
729 Ref.update(interruptions, (interruptions) => interruptions + 1).pipe(
730 Effect.andThen(Deferred.succeed(interrupted, undefined)),
731 ),
732 ),
733 )
734 : Effect.succeed(LIVE_REFS),
735 ),
736 ),
737 } as unknown as WsRpcProtocolClient;
738 const liveSession = yield* SubscriptionRef.make(Option.some(session(client)));
739 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
740 target: TARGET,
741 state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
742 session: liveSession,
743 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
744 connect: Effect.void,
745 disconnect: Effect.void,
746 retryNow: Effect.void,
747 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
748​
749 const fiber = yield* Stream.unwrap(
750 makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
751 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
752 Effect.provideService(Persistence.EnvironmentCacheStore, cacheWithRefs(Option.none())),
753 ),
754 ).pipe(Stream.runHead, Effect.forkChild);
755​
756 yield* Deferred.await(started);
757 yield* SubscriptionRef.set(liveSession, Option.none());
758 yield* Deferred.await(interrupted);
759 expect(yield* Ref.get(interruptions)).toBe(1);
760​
761 yield* SubscriptionRef.set(liveSession, Option.some(session(client)));
762 expect(Option.getOrThrow(yield* Fiber.join(fiber))).toEqual(LIVE_REFS);
763 expect(yield* Ref.get(calls)).toBe(2);
764 }),
765 );
766​
767 it.effect("retries Git failures and cancels pending retries when the session is removed", () =>
768 Effect.gen(function* () {
769 const calls = yield* Ref.make(0);
770 const warnings = yield* Queue.unbounded<unknown>();
771 const logger = Logger.make(({ message }) => Queue.offerUnsafe(warnings, message));
772 const failure = new VcsProcessExitError({
773 operation: "listRefs",
774 command: "git",
775 cwd: "/repo",
776 exitCode: 128,
777 detail: "Could not read refs.",
778 });
779 const client = {
780 [WS_METHODS.vcsListRefs]: () =>
781 Ref.updateAndGet(calls, (count) => count + 1).pipe(
782 Effect.flatMap((count) =>
783 count < 3 ? Effect.fail(failure) : Effect.succeed(LIVE_REFS),
784 ),
785 ),
786 } as unknown as WsRpcProtocolClient;
787 const liveSession = yield* SubscriptionRef.make(Option.some(session(client)));
788 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
789 target: TARGET,
790 state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
791 session: liveSession,
792 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
793 connect: Effect.void,
794 disconnect: Effect.void,
795 retryNow: Effect.void,
796 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
797 const refs = yield* Stream.unwrap(
798 makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
799 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
800 Effect.provideService(
801 Persistence.EnvironmentCacheStore,
802 cacheWithRefs(Option.some(CACHED_REFS)),
803 ),
804 ),
805 ).pipe(
806 Stream.take(2),
807 Stream.runCollect,
808 Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
809 Effect.forkChild({ startImmediately: true }),
810 );
811​
812 yield* Queue.take(warnings);
813 expect(yield* Ref.get(calls)).toBe(1);
814 yield* TestClock.adjust("1 second");
815 expect(yield* Ref.get(calls)).toBe(2);
816 expect(yield* Queue.size(warnings)).toBe(1);
817​
818 yield* SubscriptionRef.set(liveSession, Option.none());
819 yield* TestClock.adjust("1 minute");
820 expect(yield* Ref.get(calls)).toBe(2);
821 expect(yield* Queue.size(warnings)).toBe(1);
822​
823 yield* SubscriptionRef.set(liveSession, Option.some(session(client)));
824 expect(yield* Fiber.join(refs)).toEqual([CACHED_REFS, LIVE_REFS]);
825 expect(yield* Ref.get(calls)).toBe(3);
826 }),
827 );
828​
829 it.effect("emits persisted refs before a live refresh", () =>
830 Effect.gen(function* () {
831 const client = {
832 [WS_METHODS.vcsListRefs]: () => Effect.succeed(LIVE_REFS),
833 } as unknown as WsRpcProtocolClient;
834 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
835 target: TARGET,
836 state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
837 session: yield* SubscriptionRef.make(Option.some(session(client))),
838 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
839 connect: Effect.void,
840 disconnect: Effect.void,
841 retryNow: Effect.void,
842 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
843​
844 const refs = yield* Stream.unwrap(
845 makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
846 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
847 Effect.provideService(
848 Persistence.EnvironmentCacheStore,
849 cacheWithRefs(Option.some(CACHED_REFS)),
850 ),
851 ),
852 ).pipe(Stream.take(2), Stream.runCollect);
853​
854 expect(refs).toEqual([CACHED_REFS, LIVE_REFS]);
855 }),
856 );
857});
858​
859vi.mock("./session.ts", () => ({
860 createEnvironmentSessionAtoms: () => ({ sessionStateAtom: grantedSessions }),
861}));
862const grantedSessions = Atom.family((_id: EnvironmentId) =>
863 Atom.make(
864 AsyncResult.success({
865 authenticated: true,
866 auth: {
867 policy: "remote-reachable",
868 bootstrapMethods: [],
869 sessionMethods: [],
870 sessionCookieName: "test",
871 },
872 scopes: [AuthSourceControlWriteScope],
873 }),
874 ),
875);
876​
877function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
878 return {
879 isRepo: true,
880 hasPrimaryRemote: true,
881 isDefaultRef: false,
882 refName: "feature/test",
883 hasWorkingTreeChanges: false,
884 workingTree: {
885 files: [],
886 insertions: 0,
887 deletions: 0,
888 },
889 hasUpstream: true,
890 aheadCount: 0,
891 behindCount: 0,
892 pr: null,
893 ...overrides,
894 };
896​
897describe("resolveQuickAction", () => {
898 it("commits local changes without pushing when the branch is behind upstream", () => {
899 const behind = status({ hasWorkingTreeChanges: true, behindCount: 2 });
900 const commit = { label: "Commit", disabled: false, kind: "run_action", action: "commit" };
901 expect(resolveQuickAction(behind, false)).toEqual(commit);
902 expect(
903 resolveQuickAction(
904 {
905 ...behind,
906 pr: {
907 number: 13,
908 title: "Open PR",
909 url: "https://example.com/pr/13",
910 baseRef: "main",
911 headRef: "feature/test",
912 state: "open",
913 },
914 },
915 false,
916 ),
917 ).toEqual(commit);
918 });
919});