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