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

vcs.test.ts

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