Open History to see the last commit
1import { EnvironmentId, type VcsListRefsResult } from "@t3tools/contracts";
2import { AtomRegistry } from "effect/unstable/reactivity";
3import { afterEach, describe, expect, it, vi } from "vitest";
4
5import {
6 createVcsRefManager,
7 EMPTY_VCS_REF_STATE,
8 vcsRefStateAtom,
9 type VcsRefClient,
10} from "./vcsRefState.ts";
11
12let atomRegistry = AtomRegistry.make();
13
14function resetAtomRegistry() {
15 atomRegistry.dispose();
16 atomRegistry = AtomRegistry.make();
17}
18
19const noop = () => undefined;
20
21const TARGET = { environmentId: EnvironmentId.make("env-local"), cwd: "/repo" } as const;
22
23const FIRST_PAGE: VcsListRefsResult = {
24 refs: [
25 { name: "main", current: true, isDefault: true, worktreePath: null },
26 { name: "feature/a", current: false, isDefault: false, worktreePath: null },
27 ],
28 isRepo: true,
29 hasPrimaryRemote: true,
30 nextCursor: 2,
31 totalCount: 3,
32};
33
34const SECOND_PAGE: VcsListRefsResult = {
35 refs: [{ name: "feature/b", current: false, isDefault: false, worktreePath: null }],
36 isRepo: true,
37 hasPrimaryRemote: true,
38 nextCursor: null,
39 totalCount: 3,
40};
41
42function createMockClient() {
43 const listRefs = vi.fn(async (input: Parameters<VcsRefClient["listRefs"]>[0]) => {
44 if (input.query === "feature") {
45 return {
46 ...FIRST_PAGE,
47 refs: FIRST_PAGE.refs.filter((branch) => branch.name.includes("feature")),
48 nextCursor: null,
49 totalCount: 2,
50 } satisfies VcsListRefsResult;
51 }
52
53 if (input.cursor === 2) {
54 return SECOND_PAGE;
55 }
56
57 return FIRST_PAGE;
58 });
59
60 return {
61 client: { listRefs } satisfies VcsRefClient,
62 listRefs,
63 };
64}
65
66function deferred<T>() {
67 let resolve!: (value: T) => void;
68 let reject!: (error: unknown) => void;
69 const promise = new Promise<T>((resolvePromise, rejectPromise) => {
70 resolve = resolvePromise;
71 reject = rejectPromise;
72 });
73 return { promise, resolve, reject };
74}
75
76describe("createVcsRefManager", () => {
77 afterEach(() => {
78 resetAtomRegistry();
79 });
80
81 it("loads the first page and stores it in atom state", async () => {
82 const mock = createMockClient();
83 const manager = createVcsRefManager({
84 getRegistry: () => atomRegistry,
85 getClient: () => mock.client,
86 });
87
88 const promise = manager.load(TARGET, mock.client, { limit: 100 });
89
90 expect(manager.getSnapshot(TARGET)).toEqual({
91 data: null,
92 isPending: true,
93 error: null,
94 });
95
96 await expect(promise).resolves.toEqual(FIRST_PAGE);
97 expect(manager.getSnapshot(TARGET)).toEqual({
98 data: FIRST_PAGE,
99 isPending: false,
100 error: null,
101 });
102 expect(mock.listRefs).toHaveBeenCalledWith({ cwd: "/repo", limit: 100 });
103 });
104
105 it("loads the next page and appends refs", async () => {
106 const mock = createMockClient();
107 const manager = createVcsRefManager({
108 getRegistry: () => atomRegistry,
109 getClient: () => mock.client,
110 });
111
112 await manager.load(TARGET, mock.client);
113 const next = await manager.loadNext(TARGET, mock.client);
114
115 expect(next).toEqual({
116 ...SECOND_PAGE,
117 refs: [...FIRST_PAGE.refs, ...SECOND_PAGE.refs],
118 });
119 expect(manager.getSnapshot(TARGET)).toEqual({
120 data: {
121 ...SECOND_PAGE,
122 refs: [...FIRST_PAGE.refs, ...SECOND_PAGE.refs],
123 },
124 isPending: false,
125 error: null,
126 });
127 });
128
129 it("keeps cached refs visible while refreshing", async () => {
130 const nextLoad = deferred<VcsListRefsResult>();
131 let callCount = 0;
132 const listRefs = vi.fn((async () => {
133 callCount += 1;
134 return callCount === 1 ? FIRST_PAGE : nextLoad.promise;
135 }) satisfies VcsRefClient["listRefs"]);
136 const client = { listRefs } satisfies VcsRefClient;
137 const manager = createVcsRefManager({
138 getRegistry: () => atomRegistry,
139 getClient: () => client,
140 });
141
142 await manager.load(TARGET, client);
143
144 const refresh = manager.load(TARGET, client);
145 expect(manager.getSnapshot(TARGET)).toEqual({
146 data: FIRST_PAGE,
147 isPending: true,
148 error: null,
149 });
150
151 nextLoad.resolve(SECOND_PAGE);
152 await expect(refresh).resolves.toEqual(SECOND_PAGE);
153 expect(manager.getSnapshot(TARGET)).toEqual({
154 data: SECOND_PAGE,
155 isPending: false,
156 error: null,
157 });
158 });
159
160 it("preserves loaded pages during first-page revalidation", async () => {
161 const refreshedFirstPage: VcsListRefsResult = {
162 ...FIRST_PAGE,
163 refs: [{ name: "main", current: true, isDefault: true, worktreePath: null }],
164 nextCursor: 1,
165 totalCount: 3,
166 };
167 let callCount = 0;
168 const listRefs = vi.fn((async (input) => {
169 callCount += 1;
170 if (input.cursor === 2) {
171 return SECOND_PAGE;
172 }
173 return callCount === 1 ? FIRST_PAGE : refreshedFirstPage;
174 }) satisfies VcsRefClient["listRefs"]);
175 const client = { listRefs } satisfies VcsRefClient;
176 const manager = createVcsRefManager({
177 getRegistry: () => atomRegistry,
178 getClient: () => client,
179 });
180
181 await manager.load(TARGET, client);
182 await manager.loadNext(TARGET, client);
183 const beforeRefresh = manager.getSnapshot(TARGET).data;
184 expect(beforeRefresh?.refs.map((ref) => ref.name)).toEqual(["main", "feature/a", "feature/b"]);
185
186 await manager.load(TARGET, client, { preserveLoadedRefs: true });
187
188 const afterRefresh = manager.getSnapshot(TARGET).data;
189 expect(afterRefresh?.refs.map((ref) => ref.name)).toEqual(["main", "feature/a", "feature/b"]);
190 expect(afterRefresh?.nextCursor).toBeNull();
191 });
192
193 it("stores query-specific state independently", async () => {
194 const mock = createMockClient();
195 const manager = createVcsRefManager({
196 getRegistry: () => atomRegistry,
197 getClient: () => mock.client,
198 });
199
200 const queriedTarget = { ...TARGET, query: "feature" } as const;
201 const queried = await manager.load(queriedTarget, mock.client);
202
203 expect(queried?.refs.map((branch) => branch.name)).toEqual(["feature/a"]);
204 expect(manager.getSnapshot(TARGET).data).toBeNull();
205 expect(manager.getSnapshot(queriedTarget).data?.refs.map((branch) => branch.name)).toEqual([
206 "feature/a",
207 ]);
208 });
209
210 it("returns cached data when no client is available", async () => {
211 const manager = createVcsRefManager({
212 getRegistry: () => atomRegistry,
213 getClient: () => null,
214 });
215
216 atomRegistry.set(vcsRefStateAtom("env-local:/repo:"), {
217 data: FIRST_PAGE,
218 isPending: false,
219 error: null,
220 });
221
222 await expect(manager.load(TARGET)).resolves.toEqual(FIRST_PAGE);
223 });
224
225 it("resets state", async () => {
226 const mock = createMockClient();
227 const manager = createVcsRefManager({
228 getRegistry: () => atomRegistry,
229 getClient: () => mock.client,
230 });
231
232 await manager.load(TARGET, mock.client);
233 manager.reset();
234
235 expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_VCS_REF_STATE);
236 });
237
238 it("invalidates every query for a cwd scope", async () => {
239 const mock = createMockClient();
240 const manager = createVcsRefManager({
241 getRegistry: () => atomRegistry,
242 getClient: () => mock.client,
243 });
244 const queriedTarget = { ...TARGET, query: "feature" } as const;
245
246 await manager.load(TARGET, mock.client);
247 await manager.load(queriedTarget, mock.client);
248
249 manager.invalidateScope({ environmentId: TARGET.environmentId, cwd: TARGET.cwd });
250
251 expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_VCS_REF_STATE);
252 expect(manager.getSnapshot(queriedTarget)).toEqual(EMPTY_VCS_REF_STATE);
253 });
254
255 it("invalidates target in-flight loads before they can write stale data", async () => {
256 const firstLoad = deferred<VcsListRefsResult>();
257 let callCount = 0;
258 const listRefs = vi.fn((async () => {
259 callCount += 1;
260 return callCount === 1 ? firstLoad.promise : SECOND_PAGE;
261 }) satisfies VcsRefClient["listRefs"]);
262 const client = { listRefs } satisfies VcsRefClient;
263 const manager = createVcsRefManager({
264 getRegistry: () => atomRegistry,
265 getClient: () => client,
266 });
267
268 const staleLoad = manager.load(TARGET, client);
269 manager.invalidate(TARGET);
270 const freshLoad = manager.load(TARGET, client);
271
272 expect(listRefs).toHaveBeenCalledTimes(2);
273
274 firstLoad.resolve(FIRST_PAGE);
275 await expect(staleLoad).resolves.toEqual(FIRST_PAGE);
276 await expect(freshLoad).resolves.toEqual(SECOND_PAGE);
277 expect(manager.getSnapshot(TARGET).data).toEqual(SECOND_PAGE);
278 });
279
280 it("watches refs with a ref-counted client-change subscription", async () => {
281 const mock = createMockClient();
282 let listener: () => void = noop;
283 const unsubscribe = vi.fn();
284 const manager = createVcsRefManager({
285 getRegistry: () => atomRegistry,
286 getClient: () => mock.client,
287 subscribeClientChanges: (nextListener) => {
288 listener = nextListener;
289 return unsubscribe;
290 },
291 watchLimit: 100,
292 });
293
294 const firstUnwatch = manager.watch(TARGET);
295 const secondUnwatch = manager.watch(TARGET);
296 await Promise.resolve();
297
298 expect(mock.listRefs).toHaveBeenCalledTimes(1);
299 expect(mock.listRefs).toHaveBeenCalledWith({ cwd: "/repo", limit: 100 });
300
301 listener();
302 await Promise.resolve();
303 expect(mock.listRefs).toHaveBeenCalledTimes(1);
304
305 firstUnwatch();
306 expect(unsubscribe).not.toHaveBeenCalled();
307 secondUnwatch();
308 expect(unsubscribe).toHaveBeenCalledTimes(1);
309 });
310
311 it("skips watched refresh while cached refs are fresh", async () => {
312 const mock = createMockClient();
313 const manager = createVcsRefManager({
314 getRegistry: () => atomRegistry,
315 getClient: () => mock.client,
316 staleTimeMs: 60_000,
317 watchLimit: 100,
318 });
319
320 const firstUnwatch = manager.watch(TARGET);
321 await vi.waitFor(() => {
322 expect(manager.getSnapshot(TARGET).data).toEqual(FIRST_PAGE);
323 });
324 firstUnwatch();
325
326 const secondUnwatch = manager.watch(TARGET);
327 await Promise.resolve();
328 expect(mock.listRefs).toHaveBeenCalledTimes(1);
329 expect(manager.getSnapshot(TARGET)).toEqual({
330 data: FIRST_PAGE,
331 isPending: false,
332 error: null,
333 });
334
335 secondUnwatch();
336 });
337
338 it("swallows watched refresh failures after storing error state", async () => {
339 const refreshError = new Error("backend unavailable");
340 const listRefs = vi.fn(async () => {
341 throw refreshError;
342 });
343 const onBackgroundError = vi.fn();
344 const manager = createVcsRefManager({
345 getRegistry: () => atomRegistry,
346 getClient: () => ({ listRefs }),
347 onBackgroundError,
348 });
349
350 manager.watch(TARGET);
351 await Promise.resolve();
352 await Promise.resolve();
353
354 await vi.waitFor(() => {
355 expect(manager.getSnapshot(TARGET)).toEqual({
356 data: null,
357 isPending: false,
358 error: "backend unavailable",
359 });
360 expect(onBackgroundError).toHaveBeenCalledWith(refreshError);
361 });
362 });
363
364 it("starts a new watched refresh when the client is replaced while a load is in flight", async () => {
365 const firstLoad = deferred<VcsListRefsResult>();
366 const secondLoad = deferred<VcsListRefsResult>();
367 const firstListRefs = vi.fn(() => firstLoad.promise);
368 const secondListRefs = vi.fn(() => secondLoad.promise);
369 const firstClient = { listRefs: firstListRefs } satisfies VcsRefClient;
370 const secondClient = { listRefs: secondListRefs } satisfies VcsRefClient;
371 let currentClient: VcsRefClient = firstClient;
372 let listener: () => void = noop;
373 const manager = createVcsRefManager({
374 getRegistry: () => atomRegistry,
375 getClient: () => currentClient,
376 subscribeClientChanges: (nextListener) => {
377 listener = nextListener;
378 return noop;
379 },
380 });
381
382 manager.watch(TARGET);
383 await Promise.resolve();
384 expect(firstListRefs).toHaveBeenCalledTimes(1);
385
386 currentClient = secondClient;
387 listener();
388 await Promise.resolve();
389 expect(secondListRefs).toHaveBeenCalledTimes(1);
390
391 secondLoad.resolve(SECOND_PAGE);
392 await secondLoad.promise;
393 expect(manager.getSnapshot(TARGET).data).toEqual(SECOND_PAGE);
394
395 firstLoad.resolve(FIRST_PAGE);
396 await firstLoad.promise;
397 expect(manager.getSnapshot(TARGET).data).toEqual(SECOND_PAGE);
398 });
399});