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

GitActionsControl.browser.tsx

463 lines13.7 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 SHARED_THREAD_ID = ThreadId.make("thread-shared");
8const ENVIRONMENT_A = "environment-local" as never;
9const ENVIRONMENT_B = "environment-remote" 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 activeDraftThreadRef,
28 hasServerThreadRef,
29 invalidateGitQueriesSpy,
30 refreshGitStatusSpy,
31 runStackedActionMutateAsyncSpy,
32 setDraftThreadContextSpy,
33 setThreadBranchSpy,
34 toastAddSpy,
35 toastCloseSpy,
36 toastPromiseSpy,
37 toastUpdateSpy,
38} = vi.hoisted(() => ({
39 activeRunStackedActionDeferredRef: { current: createDeferredPromise<never>() },
40 activeDraftThreadRef: { current: null as unknown },
41 hasServerThreadRef: { current: true },
42 invalidateGitQueriesSpy: vi.fn(() => Promise.resolve()),
43 refreshGitStatusSpy: vi.fn(() => Promise.resolve(null)),
44 runStackedActionMutateAsyncSpy: vi.fn(() => activeRunStackedActionDeferredRef.current.promise),
45 setDraftThreadContextSpy: vi.fn(),
46 setThreadBranchSpy: vi.fn(),
47 toastAddSpy: vi.fn(() => "toast-1"),
48 toastCloseSpy: vi.fn(),
49 toastPromiseSpy: vi.fn(),
50 toastUpdateSpy: vi.fn(),
51}));
52​
53vi.mock("@tanstack/react-query", async () => {
54 const actual =
55 await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query");
56​
57 return {
58 ...actual,
59 useIsMutating: vi.fn(() => 0),
60 useMutation: vi.fn((options: { __kind?: string }) => {
61 if (options.__kind === "run-stacked-action") {
62 return {
63 mutateAsync: runStackedActionMutateAsyncSpy,
64 isPending: false,
65 };
66 }
67​
68 if (options.__kind === "pull") {
69 return {
70 mutateAsync: vi.fn(),
71 isPending: false,
72 };
73 }
74​
75 return {
76 mutate: vi.fn(),
77 mutateAsync: vi.fn(),
78 isPending: false,
79 };
80 }),
81 useQuery: vi.fn(() => ({ data: null, error: null })),
82 useQueryClient: vi.fn(() => ({})),
83 };
84});
85​
86vi.mock("~/components/ui/toast", () => ({
87 toastManager: {
88 add: toastAddSpy,
89 close: toastCloseSpy,
90 promise: toastPromiseSpy,
91 update: toastUpdateSpy,
92 },
93 stackedThreadToast: vi.fn((options: unknown) => options),
94}));
95​
96vi.mock("~/editorPreferences", () => ({
97 openInPreferredEditor: vi.fn(),
98}));
99​
100vi.mock("~/lib/gitReactQuery", () => ({
101 gitInitMutationOptions: vi.fn(() => ({ __kind: "init" })),
102 gitMutationKeys: {
103 pull: vi.fn(() => ["pull"]),
104 runStackedAction: vi.fn(() => ["run-stacked-action"]),
105 },
106 gitPullMutationOptions: vi.fn(() => ({ __kind: "pull" })),
107 gitRunStackedActionMutationOptions: vi.fn(() => ({ __kind: "run-stacked-action" })),
108 invalidateGitQueries: invalidateGitQueriesSpy,
109}));
110​
111vi.mock("~/lib/gitStatusState", () => ({
112 refreshGitStatus: refreshGitStatusSpy,
113 resetGitStatusStateForTests: () => undefined,
114 useGitStatus: vi.fn(() => ({
115 data: {
116 branch: BRANCH_NAME,
117 hasWorkingTreeChanges: false,
118 workingTree: { files: [], insertions: 0, deletions: 0 },
119 hasUpstream: true,
120 aheadCount: 1,
121 behindCount: 0,
122 pr: null,
123 },
124 error: null,
125 isPending: false,
126 })),
127}));
128​
129vi.mock("~/localApi", () => ({
130 ensureLocalApi: vi.fn(() => {
131 throw new Error("ensureLocalApi not implemented in browser test");
132 }),
133 readLocalApi: vi.fn(() => null),
134}));
135​
136vi.mock("~/composerDraftStore", async () => {
137 const draftStoreState = {
138 getDraftThreadByRef: () => activeDraftThreadRef.current,
139 getDraftSession: () => activeDraftThreadRef.current,
140 getDraftThread: () => activeDraftThreadRef.current,
141 getDraftSessionByLogicalProjectKey: () => null,
142 setDraftThreadContext: setDraftThreadContextSpy,
143 setLogicalProjectDraftThreadId: vi.fn(),
144 setProjectDraftThreadId: vi.fn(),
145 hasDraftThreadsInEnvironment: () => false,
146 clearDraftThread: vi.fn(),
147 };
148​
149 return {
150 DraftId: {
151 makeUnsafe: (value: string) => value,
152 },
153 useComposerDraftStore: Object.assign(
154 (selector: (state: unknown) => unknown) => selector(draftStoreState),
155 { getState: () => draftStoreState },
156 ),
157 markPromotedDraftThread: vi.fn(),
158 markPromotedDraftThreadByRef: vi.fn(),
159 markPromotedDraftThreads: vi.fn(),
160 markPromotedDraftThreadsByRef: vi.fn(),
161 finalizePromotedDraftThreadByRef: vi.fn(),
162 finalizePromotedDraftThreadsByRef: vi.fn(),
163 };
164});
165​
166vi.mock("~/store", () => ({
167 selectEnvironmentState: (
168 state: { environmentStateById: Record<string, unknown> },
169 environmentId: string | null,
170 ) => {
171 if (!environmentId) {
172 throw new Error("Missing environment id");
173 }
174 const environmentState = state.environmentStateById[environmentId];
175 if (!environmentState) {
176 throw new Error(`Unknown environment: ${environmentId}`);
177 }
178 return environmentState;
179 },
180 selectProjectsForEnvironment: () => [],
181 selectProjectsAcrossEnvironments: () => [],
182 selectThreadsForEnvironment: () => [],
183 selectThreadsAcrossEnvironments: () => [],
184 selectThreadShellsAcrossEnvironments: () => [],
185 selectSidebarThreadsAcrossEnvironments: () => [],
186 selectSidebarThreadsForProjectRef: () => [],
187 selectSidebarThreadsForProjectRefs: () => [],
188 selectBootstrapCompleteForActiveEnvironment: () => true,
189 selectProjectByRef: () => null,
190 selectThreadByRef: () => null,
191 selectSidebarThreadSummaryByRef: () => null,
192 selectThreadIdsByProjectRef: () => [],
193 useStore: (selector: (state: unknown) => unknown) =>
194 selector({
195 setThreadBranch: setThreadBranchSpy,
196 environmentStateById: {
197 [ENVIRONMENT_A]: {
198 threadShellById: hasServerThreadRef.current
199 ? {
200 [SHARED_THREAD_ID]: {
201 id: SHARED_THREAD_ID,
202 branch: BRANCH_NAME,
203 worktreePath: null,
204 },
205 }
206 : {},
207 threadSessionById: {},
208 threadTurnStateById: {},
209 messageIdsByThreadId: {},
210 messageByThreadId: {},
211 activityIdsByThreadId: {},
212 activityByThreadId: {},
213 proposedPlanIdsByThreadId: {},
214 proposedPlanByThreadId: {},
215 turnDiffIdsByThreadId: {},
216 turnDiffSummaryByThreadId: {},
217 },
218 [ENVIRONMENT_B]: {
219 threadShellById: hasServerThreadRef.current
220 ? {
221 [SHARED_THREAD_ID]: {
222 id: SHARED_THREAD_ID,
223 branch: BRANCH_NAME,
224 worktreePath: null,
225 },
226 }
227 : {},
228 threadSessionById: {},
229 threadTurnStateById: {},
230 messageIdsByThreadId: {},
231 messageByThreadId: {},
232 activityIdsByThreadId: {},
233 activityByThreadId: {},
234 proposedPlanIdsByThreadId: {},
235 proposedPlanByThreadId: {},
236 turnDiffIdsByThreadId: {},
237 turnDiffSummaryByThreadId: {},
238 },
239 },
240 }),
241}));
242​
243vi.mock("~/terminal-links", () => ({
244 resolvePathLinkTarget: vi.fn(),
245}));
246​
247import GitActionsControl from "./GitActionsControl";
248​
249function findButtonByText(text: string): HTMLButtonElement | null {
250 return (Array.from(document.querySelectorAll("button")).find((button) =>
251 button.textContent?.includes(text),
252 ) ?? null) as HTMLButtonElement | null;
254​
255function Harness() {
256 const [activeThreadRef, setActiveThreadRef] = useState(
257 scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID),
258 );
259​
260 return (
261 <>
262 <button
263 type="button"
264 onClick={() => setActiveThreadRef(scopeThreadRef(ENVIRONMENT_B, SHARED_THREAD_ID))}
265 >
266 Switch environment
267 </button>
268 <GitActionsControl gitCwd={GIT_CWD} activeThreadRef={activeThreadRef} />
269 </>
270 );
272​
273describe("GitActionsControl thread-scoped progress toast", () => {
274 afterEach(() => {
275 vi.useRealTimers();
276 vi.clearAllMocks();
277 activeRunStackedActionDeferredRef.current = createDeferredPromise<never>();
278 activeDraftThreadRef.current = null;
279 hasServerThreadRef.current = true;
280 document.body.innerHTML = "";
281 });
282​
283 it("keeps an in-flight git action toast pinned to the thread ref that started it", async () => {
284 vi.useFakeTimers();
285​
286 const host = document.createElement("div");
287 document.body.append(host);
288 const screen = await render(<Harness />, { container: host });
289​
290 try {
291 const quickActionButton = findButtonByText("Push & create PR");
292 expect(quickActionButton, 'Unable to find button containing "Push & create PR"').toBeTruthy();
293 if (!(quickActionButton instanceof HTMLButtonElement)) {
294 throw new Error('Unable to find button containing "Push & create PR"');
295 }
296 quickActionButton.click();
297​
298 expect(toastAddSpy).toHaveBeenCalledWith(
299 expect.objectContaining({
300 data: { threadRef: scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID) },
301 title: "Pushing...",
302 type: "loading",
303 }),
304 );
305​
306 await vi.advanceTimersByTimeAsync(1_000);
307​
308 expect(toastUpdateSpy).toHaveBeenLastCalledWith(
309 "toast-1",
310 expect.objectContaining({
311 data: { threadRef: scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID) },
312 title: "Pushing...",
313 type: "loading",
314 }),
315 );
316​
317 const switchEnvironmentButton = findButtonByText("Switch environment");
318 expect(
319 switchEnvironmentButton,
320 'Unable to find button containing "Switch environment"',
321 ).toBeTruthy();
322 if (!(switchEnvironmentButton instanceof HTMLButtonElement)) {
323 throw new Error('Unable to find button containing "Switch environment"');
324 }
325 switchEnvironmentButton.click();
326 await vi.advanceTimersByTimeAsync(1_000);
327​
328 expect(toastUpdateSpy).toHaveBeenLastCalledWith(
329 "toast-1",
330 expect.objectContaining({
331 data: { threadRef: scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID) },
332 title: "Pushing...",
333 type: "loading",
334 }),
335 );
336 } finally {
337 activeRunStackedActionDeferredRef.current.reject(new Error("test cleanup"));
338 await Promise.resolve();
339 vi.useRealTimers();
340 await screen.unmount();
341 host.remove();
342 }
343 });
344​
345 it("debounces focus-driven git status refreshes", async () => {
346 vi.useFakeTimers();
347​
348 const originalVisibilityState = Object.getOwnPropertyDescriptor(document, "visibilityState");
349 let visibilityState: DocumentVisibilityState = "hidden";
350 Object.defineProperty(document, "visibilityState", {
351 configurable: true,
352 get: () => visibilityState,
353 });
354​
355 const host = document.createElement("div");
356 document.body.append(host);
357 const screen = await render(
358 <GitActionsControl
359 gitCwd={GIT_CWD}
360 activeThreadRef={scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID)}
361 />,
362 {
363 container: host,
364 },
365 );
366​
367 try {
368 window.dispatchEvent(new Event("focus"));
369 visibilityState = "visible";
370 document.dispatchEvent(new Event("visibilitychange"));
371​
372 expect(refreshGitStatusSpy).not.toHaveBeenCalled();
373​
374 await vi.advanceTimersByTimeAsync(249);
375 expect(refreshGitStatusSpy).not.toHaveBeenCalled();
376​
377 await vi.advanceTimersByTimeAsync(1);
378 expect(refreshGitStatusSpy).toHaveBeenCalledTimes(1);
379 expect(refreshGitStatusSpy).toHaveBeenCalledWith({
380 environmentId: ENVIRONMENT_A,
381 cwd: GIT_CWD,
382 });
383 } finally {
384 if (originalVisibilityState) {
385 Object.defineProperty(document, "visibilityState", originalVisibilityState);
386 }
387 vi.useRealTimers();
388 await screen.unmount();
389 host.remove();
390 }
391 });
392​
393 it("syncs the live branch into the active draft thread when no server thread exists", async () => {
394 hasServerThreadRef.current = false;
395 activeDraftThreadRef.current = {
396 threadId: SHARED_THREAD_ID,
397 environmentId: ENVIRONMENT_A,
398 branch: null,
399 worktreePath: null,
400 };
401​
402 const host = document.createElement("div");
403 document.body.append(host);
404 const screen = await render(
405 <GitActionsControl
406 gitCwd={GIT_CWD}
407 activeThreadRef={scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID)}
408 />,
409 {
410 container: host,
411 },
412 );
413​
414 try {
415 await Promise.resolve();
416​
417 expect(setDraftThreadContextSpy).toHaveBeenCalledWith(
418 scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID),
419 {
420 branch: BRANCH_NAME,
421 worktreePath: null,
422 },
423 );
424 expect(setThreadBranchSpy).not.toHaveBeenCalled();
425 } finally {
426 await screen.unmount();
427 host.remove();
428 }
429 });
430​
431 it("does not overwrite a selected base branch while a new worktree draft is being configured", async () => {
432 hasServerThreadRef.current = false;
433 activeDraftThreadRef.current = {
434 threadId: SHARED_THREAD_ID,
435 environmentId: ENVIRONMENT_A,
436 branch: "feature/base-branch",
437 worktreePath: null,
438 envMode: "worktree",
439 };
440​
441 const host = document.createElement("div");
442 document.body.append(host);
443 const screen = await render(
444 <GitActionsControl
445 gitCwd={GIT_CWD}
446 activeThreadRef={scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID)}
447 />,
448 {
449 container: host,
450 },
451 );
452​
453 try {
454 await Promise.resolve();
455​
456 expect(setDraftThreadContextSpy).not.toHaveBeenCalled();
457 expect(setThreadBranchSpy).not.toHaveBeenCalled();
458 } finally {
459 await screen.unmount();
460 host.remove();
461 }
462 });
463});