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

GitActionsControl.browser.tsx

456 lines13.4 KB

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