Open History to see the last commit
1import { AuthFilesystemReadScope, EnvironmentId } from "@t3tools/contracts";
2import { RegistryContext } from "@effect/atom-react";
3import type { VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
4import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
5import { act, useLayoutEffect } from "react";
6import { createRoot } from "react-dom/client";
7import { expect, it, vi } from "vite-plus/test";
8
9const mocks = vi.hoisted(() => ({
10 sessionAtom: {},
11 searchEntries: vi.fn(() => null),
12 listRefs: vi.fn(),
13 refresh: vi.fn(),
14}));
15
16vi.mock("./session", () => ({
17 environmentSession: { sessionStateAtom: () => mocks.sessionAtom },
18}));
19vi.mock("./presentation", () => ({
20 useEnvironmentPresentation: () => ({
21 isReady: true,
22 presentation: { connection: { phase: "connected", error: null } },
23 }),
24}));
25vi.mock("./pull-requests", () => ({ composerPullRequests: {} }));
26vi.mock("./projects", () => ({
27 projectEnvironment: { searchEntries: mocks.searchEntries },
28}));
29vi.mock("./atom-registry", () => ({ appAtomRegistry: { refresh: mocks.refresh } }));
30vi.mock("./orchestration", () => ({ orchestrationEnvironment: {} }));
31vi.mock("./vcs", () => ({ vcsEnvironment: { listRefs: mocks.listRefs } }));
32vi.mock("./threads", () => ({ olderSettledThreads: {}, threadFamilies: {} }));
33vi.mock("./query", () => ({
34 useEnvironmentQuery: (atom: unknown) => ({
35 data:
36 atom === mocks.sessionAtom
37 ? { authenticated: true, scopes: [AuthFilesystemReadScope] }
38 : null,
39 error: null,
40 isPending: false,
41 refresh: () => {},
42 }),
43}));
44
45import {
46 useComposerPathSearch,
47 usePaginatedBranches,
48 type ComposerPathSearchTarget,
49} from "./queries";
50
51function setup() {
52 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
53 vi.useFakeTimers();
54 mocks.searchEntries.mockClear();
55 const root = createRoot(document.createElement("div"));
56 function Probe({ target }: { readonly target: ComposerPathSearchTarget }) {
57 useComposerPathSearch(target);
58 return null;
59 }
60
61 return {
62 render(target: ComposerPathSearchTarget) {
63 act(() => root.render(<Probe target={{ ...target }} />));
64 },
65 [Symbol.dispose]() {
66 act(() => root.unmount());
67 vi.useRealTimers();
68 },
69 };
70}
71
72const target = {
73 environmentId: EnvironmentId.make("test-environment"),
74 cwd: "/repo",
75 query: "src",
76};
77
78it("keeps the original search deadline when rerenders have equivalent targets", () => {
79 using harness = setup();
80 harness.render({ ...target, query: null });
81 harness.render({ ...target, query: " src " });
82 act(() => vi.advanceTimersByTime(100));
83 harness.render(target);
84 act(() => vi.advanceTimersByTime(99));
85 expect(mocks.searchEntries).not.toHaveBeenCalled();
86
87 act(() => vi.advanceTimersByTime(1));
88 expect(mocks.searchEntries).toHaveBeenCalledExactlyOnceWith({
89 environmentId: target.environmentId,
90 input: { cwd: target.cwd, query: target.query, limit: 20 },
91 });
92});
93
94it.each([
95 { field: "environment", changed: { ...target, environmentId: EnvironmentId.make("other") } },
96 { field: "project directory", changed: { ...target, cwd: "/other" } },
97 { field: "query", changed: { ...target, query: "test" } },
98])("restarts the search deadline when the $field changes", ({ changed }) => {
99 using harness = setup();
100 harness.render({ ...target, query: null });
101 harness.render(target);
102 act(() => vi.advanceTimersByTime(100));
103 harness.render(changed);
104
105 act(() => vi.advanceTimersByTime(100));
106 expect(mocks.searchEntries).not.toHaveBeenCalled();
107 act(() => vi.advanceTimersByTime(99));
108 expect(mocks.searchEntries).not.toHaveBeenCalled();
109
110 act(() => vi.advanceTimersByTime(1));
111 expect(mocks.searchEntries).toHaveBeenCalledExactlyOnceWith({
112 environmentId: changed.environmentId,
113 input: { cwd: changed.cwd, query: changed.query, limit: 20 },
114 });
115});
116
117it("keeps compiled branch results stable and resets pagination for a new target or refresh", () => {
118 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
119 const registry = AtomRegistry.make();
120 const pages = Atom.family((key: string) => {
121 const [, cwd, cursor] = JSON.parse(key) as [string, string, number | null];
122 return Atom.make(
123 AsyncResult.success({
124 refs: [
125 { name: `${cwd}-${cursor ?? 0}`, current: false, isDefault: false, worktreePath: null },
126 ],
127 isRepo: true,
128 hasPrimaryRemote: true,
129 nextCursor: cursor === null ? 100 : null,
130 totalCount: 2,
131 }),
132 );
133 });
134 mocks.listRefs.mockImplementation(
135 ({
136 environmentId,
137 input,
138 }: {
139 environmentId: EnvironmentId;
140 input: { cwd: string; cursor?: number };
141 }) => pages(JSON.stringify([environmentId, input.cwd, input.cursor ?? null])),
142 );
143 mocks.refresh.mockClear();
144 const root = createRoot(document.createElement("div"));
145 using _cleanup = {
146 [Symbol.dispose]() {
147 act(() => root.unmount());
148 registry.dispose();
149 },
150 };
151 let current: ReturnType<typeof usePaginatedBranches>;
152 function Probe({ target }: { target: VcsRefTarget }) {
153 const result = usePaginatedBranches(target);
154 useLayoutEffect(() => {
155 current = result;
156 });
157 return null;
158 }
159 const render = (cwd: string | null, options: Partial<VcsRefTarget> = {}) =>
160 act(() =>
161 root.render(
162 <RegistryContext.Provider value={registry}>
163 <Probe target={{ environmentId: target.environmentId, cwd, ...options }} />
164 </RegistryContext.Provider>,
165 ),
166 );
167 render("/repo");
168 const first = current!;
169 render("/repo");
170 expect(current!.data).toBe(first.data);
171 expect(current!.refs).toBe(first.refs);
172 expect(current!.refresh).toBe(first.refresh);
173 expect(current!.loadNext).toBe(first.loadNext);
174 act(() =>
175 registry.set(
176 pages(JSON.stringify([target.environmentId, "/repo", null])),
177 AsyncResult.success({
178 ...first.data!,
179 refs: [{ name: "/repo-0", current: true, isDefault: false, worktreePath: null }],
180 }),
181 ),
182 );
183 expect(current!.refs[0]?.current).toBe(true);
184 act(() => current!.loadNext());
185 expect(current!.refs.map((ref) => ref.name)).toEqual(["/repo-0", "/repo-100"]);
186 act(() => current!.refresh());
187 expect(current!.refs.map((ref) => ref.name)).toEqual(["/repo-0"]);
188 expect(mocks.refresh).toHaveBeenCalledExactlyOnceWith(
189 pages(JSON.stringify([target.environmentId, "/repo", null])),
190 );
191 act(() => current!.loadNext());
192 render("/other");
193 expect(current!.refs.map((ref) => ref.name)).toEqual(["/other-0"]);
194 act(() => current!.loadNext());
195 render("/other", { query: "feature" });
196 expect(current!.refs).toHaveLength(1);
197 act(() => current!.loadNext());
198 render("/other", { environmentId: EnvironmentId.make("other-environment"), query: "feature" });
199 expect(current!.refs).toHaveLength(1);
200 render(null);
201 expect(current!.data).toBeNull();
202 expect(current!.refs).toEqual([]);
203});