Open History to see the last commit
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 };
106}
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 });
127}
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" },
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]: (input: { cwd: string; localOnly?: boolean }) =>
493 Deferred.succeed(refreshStarted, undefined).pipe(
494 Effect.tap(() => Effect.sync(() => expect(input.localOnly).toBe(true))),
495 Effect.andThen(Deferred.await(releaseRefresh)),
496 Effect.as({}),
497 ),
498 [WS_METHODS.vcsSwitchRef]: () => Effect.succeed({ refName: "feature" }),
499 } as unknown as WsRpcProtocolClient;
500 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
501 target: TARGET,
502 state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
503 session: yield* SubscriptionRef.make(Option.some(session(client))),
504 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
505 connect: Effect.void,
506 disconnect: Effect.void,
507 retryNow: Effect.void,
508 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
509 const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (
510 _environmentId,
511 effect,
512 ) => Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
513 const runtime = Atom.runtime(
514 Layer.merge(
515 Layer.succeed(
516 EnvironmentRegistry.EnvironmentRegistry,
517 EnvironmentRegistry.EnvironmentRegistry.of({
518 run,
519 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]),
520 ),
521 Layer.succeed(Persistence.EnvironmentCacheStore, cacheWithRefs(Option.none())),
522 ),
523 );
524 const atoms = createVcsEnvironmentAtoms(runtime);
525 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
526 Effect.sync(() => registry.dispose()),
527 );
528 const target = { environmentId: TARGET.environmentId, input: { cwd: "/repo" } };
529
530 const refresh = yield* Effect.forkChild(
531 Effect.exit(atoms.refreshLocalStatusForPicker.run(registry, target)),
532 { startImmediately: true },
533 );
534 yield* Deferred.await(refreshStarted);
535 const checkout = yield* Effect.exit(
536 atoms.switchRef.run(registry, {
537 ...target,
538 input: { cwd: "/repo", refName: "feature" },
539 }),
540 );
541
542 expect(Exit.isSuccess(checkout)).toBe(true);
543 yield* Deferred.succeed(releaseRefresh, undefined);
544 expect(Exit.isSuccess(yield* Fiber.join(refresh))).toBe(true);
545 }),
546 );
547
548 it.effect("suppresses persisted snapshots after an environment-wide clear fails", () =>
549 Effect.gen(function* () {
550 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
551 Effect.sync(() => registry.dispose()),
552 );
553 const persisted = yield* Ref.make<Option.Option<VcsListRefsResult>>(Option.some(CACHED_REFS));
554 const loads = yield* Ref.make(0);
555 const clearAttempts = yield* Ref.make(0);
556 const cache = cacheWithRefs(Option.none(), {
557 loadVcsRefs: () =>
558 Ref.update(loads, (count) => count + 1).pipe(Effect.andThen(Ref.get(persisted))),
559 saveVcsRefs: (_environmentId, _cwd, refs) => Ref.set(persisted, Option.some(refs)),
560 clearVcsRefs: () =>
561 Ref.updateAndGet(clearAttempts, (count) => count + 1).pipe(
562 Effect.flatMap((attempt) =>
563 attempt === 1
564 ? Effect.fail(
565 new Persistence.ConnectionPersistenceError({
566 operation: "clear-vcs-refs",
567 message: "storage unavailable",
568 }),
569 )
570 : Ref.set(persisted, Option.none()),
571 ),
572 ),
573 });
574
575 yield* invalidateCachedVcsRefs(registry, {
576 environmentId: TARGET.environmentId,
577 cwd: "/repo",
578 }).pipe(Effect.provideService(Persistence.EnvironmentCacheStore, cache));
579
580 const state = registry.get(vcsRefsCacheStateAtom(TARGET));
581 expect(state).toEqual({
582 revision: 1,
583 persistedCacheReadable: false,
584 });
585
586 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
587 target: TARGET,
588 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
589 session: yield* SubscriptionRef.make(Option.none<RpcSession>()),
590 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
591 connect: Effect.void,
592 disconnect: Effect.void,
593 retryNow: Effect.void,
594 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
595 const refs = yield* Stream.unwrap(
596 makeCachedVcsRefsChanges(
597 { cwd: "/repo", limit: 100 },
598 state.revision,
599 registry,
600 state.persistedCacheReadable,
601 ).pipe(
602 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
603 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
604 ),
605 ).pipe(Stream.runHead, Effect.forkChild({ startImmediately: true }));
606
607 yield* Effect.yieldNow;
608 expect(yield* Ref.get(loads)).toBe(0);
609 yield* Fiber.interrupt(refs);
610 expect(registry.get(vcsRefsCacheStateAtom(TARGET))).toEqual(state);
611
612 expect(
613 yield* commitVcsRefsRefresh(registry, cache, {
614 environmentId: TARGET.environmentId,
615 cwd: "/repo",
616 refs: LIVE_REFS,
617 expectedRevision: state.revision,
618 persist: true,
619 }),
620 ).toBe(true);
621 const recoveredState = registry.get(vcsRefsCacheStateAtom(TARGET));
622 expect(recoveredState).toEqual({
623 revision: 1,
624 persistedCacheReadable: true,
625 });
626 expect(yield* Ref.get(clearAttempts)).toBe(2);
627
628 const recoveredRefs = yield* Stream.unwrap(
629 makeCachedVcsRefsChanges(
630 { cwd: "/repo", limit: 100 },
631 recoveredState.revision,
632 registry,
633 recoveredState.persistedCacheReadable,
634 ).pipe(
635 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
636 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
637 ),
638 ).pipe(Stream.runHead);
639
640 expect(Option.getOrThrow(recoveredRefs)).toEqual(LIVE_REFS);
641 expect(yield* Ref.get(loads)).toBe(1);
642 }),
643 );
644
645 it.effect("loads an unfiltered branch list without a connection", () =>
646 Effect.gen(function* () {
647 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
648 target: TARGET,
649 state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
650 session: yield* SubscriptionRef.make(Option.none<RpcSession>()),
651 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
652 connect: Effect.void,
653 disconnect: Effect.void,
654 retryNow: Effect.void,
655 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
656 const refs = yield* Stream.unwrap(
657 makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
658 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
659 Effect.provideService(
660 Persistence.EnvironmentCacheStore,
661 cacheWithRefs(Option.some(CACHED_REFS)),
662 ),
663 ),
664 ).pipe(Stream.runHead);
665
666 expect(Option.getOrThrow(refs)).toEqual(CACHED_REFS);
667 }),
668 );
669
670 it.effect("waits silently for a session while the connection phase is still connected", () =>
671 Effect.gen(function* () {
672 const logs: unknown[] = [];
673 const logger = Logger.make(({ message }) => logs.push(message));
674 const liveSession = yield* SubscriptionRef.make(Option.none<RpcSession>());
675 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
676 target: TARGET,
677 state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
678 session: liveSession,
679 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
680 connect: Effect.void,
681 disconnect: Effect.void,
682 retryNow: Effect.void,
683 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
684 const refs = yield* Stream.unwrap(
685 makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
686 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
687 Effect.provideService(
688 Persistence.EnvironmentCacheStore,
689 cacheWithRefs(Option.some(CACHED_REFS)),
690 ),
691 ),
692 ).pipe(
693 Stream.take(2),
694 Stream.runCollect,
695 Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
696 Effect.forkChild({ startImmediately: true }),
697 );
698
699 yield* TestClock.adjust("1 minute");
700 expect(logs).toEqual([]);
701
702 const client = {
703 [WS_METHODS.vcsListRefs]: () => Effect.succeed(LIVE_REFS),
704 } as unknown as WsRpcProtocolClient;
705 yield* SubscriptionRef.set(liveSession, Option.some(session(client)));
706 expect(yield* Fiber.join(refs)).toEqual([CACHED_REFS, LIVE_REFS]);
707 expect(logs).toEqual([]);
708 }),
709 );
710
711 it.effect("cancels an in-flight refresh and restarts when the RPC session changes", () =>
712 Effect.gen(function* () {
713 const started = yield* Deferred.make<void>();
714 const interrupted = yield* Deferred.make<void>();
715 const calls = yield* Ref.make(0);
716 const interruptions = yield* Ref.make(0);
717 const client = {
718 [WS_METHODS.vcsListRefs]: () =>
719 Ref.updateAndGet(calls, (count) => count + 1).pipe(
720 Effect.flatMap((count) =>
721 count === 1
722 ? Deferred.succeed(started, undefined).pipe(
723 Effect.andThen(Effect.never),
724 Effect.onInterrupt(() =>
725 Ref.update(interruptions, (interruptions) => interruptions + 1).pipe(
726 Effect.andThen(Deferred.succeed(interrupted, undefined)),
727 ),
728 ),
729 )
730 : Effect.succeed(LIVE_REFS),
731 ),
732 ),
733 } as unknown as WsRpcProtocolClient;
734 const liveSession = yield* SubscriptionRef.make(Option.some(session(client)));
735 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
736 target: TARGET,
737 state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
738 session: liveSession,
739 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
740 connect: Effect.void,
741 disconnect: Effect.void,
742 retryNow: Effect.void,
743 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
744
745 const fiber = yield* Stream.unwrap(
746 makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
747 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
748 Effect.provideService(Persistence.EnvironmentCacheStore, cacheWithRefs(Option.none())),
749 ),
750 ).pipe(Stream.runHead, Effect.forkChild);
751
752 yield* Deferred.await(started);
753 yield* SubscriptionRef.set(liveSession, Option.none());
754 yield* Deferred.await(interrupted);
755 expect(yield* Ref.get(interruptions)).toBe(1);
756
757 yield* SubscriptionRef.set(liveSession, Option.some(session(client)));
758 expect(Option.getOrThrow(yield* Fiber.join(fiber))).toEqual(LIVE_REFS);
759 expect(yield* Ref.get(calls)).toBe(2);
760 }),
761 );
762
763 it.effect("retries Git failures and cancels pending retries when the session is removed", () =>
764 Effect.gen(function* () {
765 const calls = yield* Ref.make(0);
766 const warnings = yield* Queue.unbounded<unknown>();
767 const logger = Logger.make(({ message }) => Queue.offerUnsafe(warnings, message));
768 const failure = new VcsProcessExitError({
769 operation: "listRefs",
770 command: "git",
771 cwd: "/repo",
772 exitCode: 128,
773 detail: "Could not read refs.",
774 });
775 const client = {
776 [WS_METHODS.vcsListRefs]: () =>
777 Ref.updateAndGet(calls, (count) => count + 1).pipe(
778 Effect.flatMap((count) =>
779 count < 3 ? Effect.fail(failure) : Effect.succeed(LIVE_REFS),
780 ),
781 ),
782 } as unknown as WsRpcProtocolClient;
783 const liveSession = yield* SubscriptionRef.make(Option.some(session(client)));
784 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
785 target: TARGET,
786 state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
787 session: liveSession,
788 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
789 connect: Effect.void,
790 disconnect: Effect.void,
791 retryNow: Effect.void,
792 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
793 const refs = yield* Stream.unwrap(
794 makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
795 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
796 Effect.provideService(
797 Persistence.EnvironmentCacheStore,
798 cacheWithRefs(Option.some(CACHED_REFS)),
799 ),
800 ),
801 ).pipe(
802 Stream.take(2),
803 Stream.runCollect,
804 Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
805 Effect.forkChild({ startImmediately: true }),
806 );
807
808 yield* Queue.take(warnings);
809 expect(yield* Ref.get(calls)).toBe(1);
810 yield* TestClock.adjust("1 second");
811 expect(yield* Ref.get(calls)).toBe(2);
812 expect(yield* Queue.size(warnings)).toBe(1);
813
814 yield* SubscriptionRef.set(liveSession, Option.none());
815 yield* TestClock.adjust("1 minute");
816 expect(yield* Ref.get(calls)).toBe(2);
817 expect(yield* Queue.size(warnings)).toBe(1);
818
819 yield* SubscriptionRef.set(liveSession, Option.some(session(client)));
820 expect(yield* Fiber.join(refs)).toEqual([CACHED_REFS, LIVE_REFS]);
821 expect(yield* Ref.get(calls)).toBe(3);
822 }),
823 );
824
825 it.effect("emits persisted refs before a live refresh", () =>
826 Effect.gen(function* () {
827 const client = {
828 [WS_METHODS.vcsListRefs]: () => Effect.succeed(LIVE_REFS),
829 } as unknown as WsRpcProtocolClient;
830 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
831 target: TARGET,
832 state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
833 session: yield* SubscriptionRef.make(Option.some(session(client))),
834 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
835 connect: Effect.void,
836 disconnect: Effect.void,
837 retryNow: Effect.void,
838 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
839
840 const refs = yield* Stream.unwrap(
841 makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
842 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
843 Effect.provideService(
844 Persistence.EnvironmentCacheStore,
845 cacheWithRefs(Option.some(CACHED_REFS)),
846 ),
847 ),
848 ).pipe(Stream.take(2), Stream.runCollect);
849
850 expect(refs).toEqual([CACHED_REFS, LIVE_REFS]);
851 }),
852 );
853});
854
855vi.mock("./session.ts", () => ({
856 createEnvironmentSessionAtoms: () => ({ sessionStateAtom: grantedSessions }),
857}));
858const grantedSessions = Atom.family((_id: EnvironmentId) =>
859 Atom.make(
860 AsyncResult.success({
861 authenticated: true,
862 auth: {
863 policy: "remote-reachable",
864 bootstrapMethods: [],
865 sessionMethods: [],
866 sessionCookieName: "test",
867 },
868 scopes: [AuthSourceControlWriteScope],
869 }),
870 ),
871);
872
873function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
874 return {
875 isRepo: true,
876 hasPrimaryRemote: true,
877 isDefaultRef: false,
878 refName: "feature/test",
879 hasWorkingTreeChanges: false,
880 workingTree: {
881 files: [],
882 insertions: 0,
883 deletions: 0,
884 },
885 hasUpstream: true,
886 aheadCount: 0,
887 behindCount: 0,
888 pr: null,
889 ...overrides,
890 };
891}
892
893describe("resolveQuickAction", () => {
894 it("commits local changes without pushing when the branch is behind upstream", () => {
895 const behind = status({ hasWorkingTreeChanges: true, behindCount: 2 });
896 const commit = { label: "Commit", disabled: false, kind: "run_action", action: "commit" };
897 expect(resolveQuickAction(behind, false)).toEqual(commit);
898 expect(
899 resolveQuickAction(
900 {
901 ...behind,
902 pr: {
903 number: 13,
904 title: "Open PR",
905 url: "https://example.com/pr/13",
906 baseRef: "main",
907 headRef: "feature/test",
908 state: "open",
909 },
910 },
911 false,
912 ),
913 ).toEqual(commit);
914 });
915});