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

GitActionsControl.browser.tsx

319 lines9.4 KB

1import { scopeThreadRef } from "@t3tools/client-runtime";
2import { ThreadId } from "@t3tools/contracts";
3import { useState } from "react";
4import { afterEach, describe, expect, it, vi } from "vitest";
5import { render } from "vitest-browser-react";
6​
7const THREAD_A = ThreadId.makeUnsafe("thread-a");
8const THREAD_B = ThreadId.makeUnsafe("thread-b");
9const ENVIRONMENT_ID = "environment-local" as never;
10const GIT_CWD = "/repo/project";
11const BRANCH_NAME = "feature/toast-scope";
12​
13function createDeferredPromise<T>() {
14 let resolve!: (value: T) => void;
15 let reject!: (reason?: unknown) => void;
16​
17 const promise = new Promise<T>((nextResolve, nextReject) => {
18 resolve = nextResolve;
19 reject = nextReject;
20 });
21​
22 return { promise, resolve, reject };
24​
25const {
26 activeRunStackedActionDeferredRef,
27 invalidateGitQueriesSpy,
28 refreshGitStatusSpy,
29 runStackedActionMutateAsyncSpy,
30 setThreadBranchSpy,
31 toastAddSpy,
32 toastCloseSpy,
33 toastPromiseSpy,
34 toastUpdateSpy,
35} = vi.hoisted(() => ({
36 activeRunStackedActionDeferredRef: { current: createDeferredPromise<never>() },
37 invalidateGitQueriesSpy: vi.fn(() => Promise.resolve()),
38 refreshGitStatusSpy: vi.fn(() => Promise.resolve(null)),
39 runStackedActionMutateAsyncSpy: vi.fn(() => activeRunStackedActionDeferredRef.current.promise),
40 setThreadBranchSpy: vi.fn(),
41 toastAddSpy: vi.fn(() => "toast-1"),
42 toastCloseSpy: vi.fn(),
43 toastPromiseSpy: vi.fn(),
44 toastUpdateSpy: vi.fn(),
45}));
46​
47vi.mock("@tanstack/react-query", async () => {
48 const actual =
49 await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query");
50​
51 return {
52 ...actual,
53 useIsMutating: vi.fn(() => 0),
54 useMutation: vi.fn((options: { __kind?: string }) => {
55 if (options.__kind === "run-stacked-action") {
56 return {
57 mutateAsync: runStackedActionMutateAsyncSpy,
58 isPending: false,
59 };
60 }
61​
62 if (options.__kind === "pull") {
63 return {
64 mutateAsync: vi.fn(),
65 isPending: false,
66 };
67 }
68​
69 return {
70 mutate: vi.fn(),
71 mutateAsync: vi.fn(),
72 isPending: false,
73 };
74 }),
75 useQuery: vi.fn(() => ({ data: null, error: null })),
76 useQueryClient: vi.fn(() => ({})),
77 };
78});
79​
80vi.mock("~/components/ui/toast", () => ({
81 toastManager: {
82 add: toastAddSpy,
83 close: toastCloseSpy,
84 promise: toastPromiseSpy,
85 update: toastUpdateSpy,
86 },
87}));
88​
89vi.mock("~/editorPreferences", () => ({
90 openInPreferredEditor: vi.fn(),
91}));
92​
93vi.mock("~/lib/gitReactQuery", () => ({
94 gitInitMutationOptions: vi.fn(() => ({ __kind: "init" })),
95 gitMutationKeys: {
96 pull: vi.fn(() => ["pull"]),
97 runStackedAction: vi.fn(() => ["run-stacked-action"]),
98 },
99 gitPullMutationOptions: vi.fn(() => ({ __kind: "pull" })),
100 gitRunStackedActionMutationOptions: vi.fn(() => ({ __kind: "run-stacked-action" })),
101 invalidateGitQueries: invalidateGitQueriesSpy,
102}));
103​
104vi.mock("~/lib/gitStatusState", () => ({
105 refreshGitStatus: refreshGitStatusSpy,
106 resetGitStatusStateForTests: () => undefined,
107 useGitStatus: vi.fn(() => ({
108 data: {
109 branch: BRANCH_NAME,
110 hasWorkingTreeChanges: false,
111 workingTree: { files: [], insertions: 0, deletions: 0 },
112 hasUpstream: true,
113 aheadCount: 1,
114 behindCount: 0,
115 pr: null,
116 },
117 error: null,
118 isPending: false,
119 })),
120}));
121​
122vi.mock("~/localApi", () => ({
123 readLocalApi: vi.fn(() => null),
124}));
125​
126vi.mock("~/store", () => ({
127 selectEnvironmentState: (
128 state: { environmentStateById: Record<string, unknown> },
129 environmentId: string | null,
130 ) => {
131 if (!environmentId) {
132 throw new Error("Missing environment id");
133 }
134 const environmentState = state.environmentStateById[environmentId];
135 if (!environmentState) {
136 throw new Error(`Unknown environment: ${environmentId}`);
137 }
138 return environmentState;
139 },
140 selectProjectsForEnvironment: () => [],
141 selectProjectsAcrossEnvironments: () => [],
142 selectThreadsForEnvironment: () => [],
143 selectThreadsAcrossEnvironments: () => [],
144 selectThreadShellsAcrossEnvironments: () => [],
145 selectSidebarThreadsAcrossEnvironments: () => [],
146 selectSidebarThreadsForProjectRef: () => [],
147 selectSidebarThreadsForProjectRefs: () => [],
148 selectBootstrapCompleteForActiveEnvironment: () => true,
149 selectProjectByRef: () => null,
150 selectThreadByRef: () => null,
151 selectSidebarThreadSummaryByRef: () => null,
152 selectThreadIdsByProjectRef: () => [],
153 useStore: (selector: (state: unknown) => unknown) =>
154 selector({
155 setThreadBranch: setThreadBranchSpy,
156 environmentStateById: {
157 [ENVIRONMENT_ID]: {
158 threadShellById: {
159 [THREAD_A]: { id: THREAD_A, branch: BRANCH_NAME, worktreePath: null },
160 [THREAD_B]: { id: THREAD_B, branch: BRANCH_NAME, worktreePath: null },
161 },
162 threadSessionById: {},
163 threadTurnStateById: {},
164 messageIdsByThreadId: {},
165 messageByThreadId: {},
166 activityIdsByThreadId: {},
167 activityByThreadId: {},
168 proposedPlanIdsByThreadId: {},
169 proposedPlanByThreadId: {},
170 turnDiffIdsByThreadId: {},
171 turnDiffSummaryByThreadId: {},
172 },
173 },
174 }),
175}));
176​
177vi.mock("~/terminal-links", () => ({
178 resolvePathLinkTarget: vi.fn(),
179}));
180​
181import GitActionsControl from "./GitActionsControl";
182​
183function findButtonByText(text: string): HTMLButtonElement | null {
184 return (Array.from(document.querySelectorAll("button")).find((button) =>
185 button.textContent?.includes(text),
186 ) ?? null) as HTMLButtonElement | null;
188​
189function Harness() {
190 const [activeThreadId, setActiveThreadId] = useState(THREAD_A);
191​
192 return (
193 <>
194 <button type="button" onClick={() => setActiveThreadId(THREAD_B)}>
195 Switch thread
196 </button>
197 <GitActionsControl
198 gitCwd={GIT_CWD}
199 activeThreadRef={scopeThreadRef(ENVIRONMENT_ID, activeThreadId)}
200 />
201 </>
202 );
204​
205describe("GitActionsControl thread-scoped progress toast", () => {
206 afterEach(() => {
207 vi.useRealTimers();
208 vi.clearAllMocks();
209 activeRunStackedActionDeferredRef.current = createDeferredPromise<never>();
210 document.body.innerHTML = "";
211 });
212​
213 it("keeps an in-flight git action toast pinned to the thread that started it", async () => {
214 vi.useFakeTimers();
215​
216 const host = document.createElement("div");
217 document.body.append(host);
218 const screen = await render(<Harness />, { container: host });
219​
220 try {
221 const quickActionButton = findButtonByText("Push & create PR");
222 expect(quickActionButton, 'Unable to find button containing "Push & create PR"').toBeTruthy();
223 if (!(quickActionButton instanceof HTMLButtonElement)) {
224 throw new Error('Unable to find button containing "Push & create PR"');
225 }
226 quickActionButton.click();
227​
228 expect(toastAddSpy).toHaveBeenCalledWith(
229 expect.objectContaining({
230 data: { threadId: THREAD_A },
231 title: "Pushing...",
232 type: "loading",
233 }),
234 );
235​
236 await vi.advanceTimersByTimeAsync(1_000);
237​
238 expect(toastUpdateSpy).toHaveBeenLastCalledWith(
239 "toast-1",
240 expect.objectContaining({
241 data: { threadId: THREAD_A },
242 title: "Pushing...",
243 type: "loading",
244 }),
245 );
246​
247 const switchThreadButton = findButtonByText("Switch thread");
248 expect(switchThreadButton, 'Unable to find button containing "Switch thread"').toBeTruthy();
249 if (!(switchThreadButton instanceof HTMLButtonElement)) {
250 throw new Error('Unable to find button containing "Switch thread"');
251 }
252 switchThreadButton.click();
253 await vi.advanceTimersByTimeAsync(1_000);
254​
255 expect(toastUpdateSpy).toHaveBeenLastCalledWith(
256 "toast-1",
257 expect.objectContaining({
258 data: { threadId: THREAD_A },
259 title: "Pushing...",
260 type: "loading",
261 }),
262 );
263 } finally {
264 activeRunStackedActionDeferredRef.current.reject(new Error("test cleanup"));
265 await Promise.resolve();
266 vi.useRealTimers();
267 await screen.unmount();
268 host.remove();
269 }
270 });
271​
272 it("debounces focus-driven git status refreshes", async () => {
273 vi.useFakeTimers();
274​
275 const originalVisibilityState = Object.getOwnPropertyDescriptor(document, "visibilityState");
276 let visibilityState: DocumentVisibilityState = "hidden";
277 Object.defineProperty(document, "visibilityState", {
278 configurable: true,
279 get: () => visibilityState,
280 });
281​
282 const host = document.createElement("div");
283 document.body.append(host);
284 const screen = await render(
285 <GitActionsControl
286 gitCwd={GIT_CWD}
287 activeThreadRef={scopeThreadRef(ENVIRONMENT_ID, THREAD_A)}
288 />,
289 {
290 container: host,
291 },
292 );
293​
294 try {
295 window.dispatchEvent(new Event("focus"));
296 visibilityState = "visible";
297 document.dispatchEvent(new Event("visibilitychange"));
298​
299 expect(refreshGitStatusSpy).not.toHaveBeenCalled();
300​
301 await vi.advanceTimersByTimeAsync(249);
302 expect(refreshGitStatusSpy).not.toHaveBeenCalled();
303​
304 await vi.advanceTimersByTimeAsync(1);
305 expect(refreshGitStatusSpy).toHaveBeenCalledTimes(1);
306 expect(refreshGitStatusSpy).toHaveBeenCalledWith({
307 environmentId: ENVIRONMENT_ID,
308 cwd: GIT_CWD,
309 });
310 } finally {
311 if (originalVisibilityState) {
312 Object.defineProperty(document, "visibilityState", originalVisibilityState);
313 }
314 vi.useRealTimers();
315 await screen.unmount();
316 host.remove();
317 }
318 });
319});