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

GitActionsControl.browser.tsx

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