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

GitActionsControl.browser.test.tsx

449 lines15.7 KB

1import {
2 AuthOrchestrationOperateScope,
3 AuthSourceControlWriteScope,
4 EnvironmentId,
5 ThreadId,
6} from "@t3tools/contracts";
7import * as Cause from "effect/Cause";
8import { AsyncResult } from "effect/reactivity";
9import { act, memo } from "react";
10import { createRoot, type Root } from "react-dom/client";
11import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
12import { page, userEvent } from "vite-plus/test/browser";
13​
14import "~/index.css";
15​
16type Branched = { readonly branch: string };
17type GitActionInput = { featureBranch?: boolean; threadId?: string; action: string };
18type Toast = { actionProps?: { onClick: () => void } };
19​
20const state = vi.hoisted(() => ({
21 scopes: new Set<string>(),
22 primaryScopes: new Set<string>(),
23 shell: null as Branched | null,
24 detail: null as Branched | null,
25 draft: null as (Branched & { worktreePath: null; envMode: "local" }) | null,
26 branch: "main",
27 isDefaultRef: false,
28 actions: [] as { scope: { cwd: string | null }; input: GitActionInput }[],
29 metadataRequests: [] as { environmentId: string; branch: string }[],
30 toasts: [] as Toast[],
31 afterGitAction: undefined as (() => void) | undefined,
32 workingTreeRoot: undefined as string | undefined,
33 files: [{ path: "file.ts", insertions: 1, deletions: 0 }],
34 editorOpens: [] as { environmentId: string; input: { cwd: string; editor: string } }[],
35}));
36​
37vi.mock(import("~/state/session"), async (original) => {
38 const hasScope = (environmentId: unknown, scope: string) =>
39 (environmentId === "environment" ? state.scopes : state.primaryScopes).has(scope);
40 return {
41 ...(await original()),
42 useEnvironmentScope: hasScope as never,
43 readEnvironmentScope: hasScope as never,
44 };
45});
46vi.mock(import("~/state/entities"), async (original) => ({
47 ...(await original()),
48 useQuietThreadShell: ((ref: { threadId: string } | null) =>
49 ref === null || state.shell === null ? null : { ...state.shell, id: ref.threadId }) as never,
50 useThreadProjection: ((ref: unknown) =>
51 ref === null || state.detail === null
52 ? null
53 : { projection: { thread: state.detail } }) as never,
54}));
55vi.mock(import("~/state/query"), async (original) => ({
56 ...(await original()),
57 // Serves both the VCS status and the source-control discovery queries.
58 useEnvironmentQuery: (() => ({
59 data: {
60 sourceControlProviders: [],
61 isRepo: true,
62 refName: state.branch,
63 isDefaultRef: state.isDefaultRef,
64 hasPrimaryRemote: true,
65 hasWorkingTreeChanges: true,
66 workingTree: {
67 ...(state.workingTreeRoot === undefined ? {} : { rootPath: state.workingTreeRoot }),
68 files: state.files,
69 insertions: 1,
70 deletions: 0,
71 },
72 hasUpstream: true,
73 aheadCount: 0,
74 behindCount: 0,
75 pr: null,
76 },
77 error: null,
78 })) as never,
79}));
80vi.mock(import("~/state/use-atom-command"), async (original) => {
81 const { shellEnvironment } = await import("~/state/shell");
82 return {
83 ...(await original()),
84 // Only the thread's branch metadata update and editor opens are observed here.
85 useAtomCommand: ((command: unknown, options: unknown) =>
86 options === "thread branch metadata update"
87 ? async ({
88 environmentId,
89 input,
90 }: {
91 environmentId: string;
92 input: { branch: string };
93 }) => {
94 state.metadataRequests.push({ environmentId, branch: input.branch });
95 if (!state.scopes.has(AuthOrchestrationOperateScope))
96 return AsyncResult.failure(Cause.fail(new Error("Task denied")));
97 if (state.shell) state.shell = { branch: input.branch };
98 if (state.detail) state.detail = { branch: input.branch };
99 return AsyncResult.success(undefined);
100 }
101 : command === shellEnvironment.openInEditor
102 ? async (request: (typeof state.editorOpens)[number]) => {
103 state.editorOpens.push(request);
104 return AsyncResult.success(undefined);
105 }
106 : async () => AsyncResult.success(undefined)) as never,
107 };
108});
109// The preferred-editor flow needs one editor the environment reports as installed.
110vi.mock(import("~/state/server"), async (original) => {
111 const actual = await original();
112 const { Atom } = await import("effect/reactivity");
113 const config = Atom.make(() => ({ availableEditors: ["cursor"] }));
114 return {
115 ...actual,
116 serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => config) as never },
117 };
118});
119vi.mock(import("~/lib/sourceControlActions"), async (original) => ({
120 ...(await original()),
121 useSourceControlActionRunning: () => false,
122 useGitStackedAction: ((scope: { cwd: string | null }) => ({
123 run: async (input: GitActionInput) => {
124 state.actions.push({ scope, input });
125 if (input.featureBranch) state.branch = "feature";
126 state.afterGitAction?.();
127 return {
128 _tag: "Success",
129 value: {
130 branch: input.featureBranch
131 ? { status: "created", name: "feature" }
132 : { status: "skipped_not_requested" },
133 toast: {
134 title: "Committed",
135 description: "Committed",
136 cta: {
137 kind: "run_action",
138 label: "Push & create PR",
139 action: { kind: "commit_push_pr" },
140 },
141 },
142 },
143 };
144 },
145 })) as never,
146}));
147vi.mock(import("@tanstack/react-router"), async (original) => ({
148 ...(await original()),
149 useNavigate: (() => async () => {}) as never,
150}));
151vi.mock(import("~/components/ui/toast"), async (original) => {
152 const actual = await original();
153 return {
154 ...actual,
155 toastManager: {
156 ...actual.toastManager,
157 add: ((toast: Toast) => {
158 state.toasts.push(toast);
159 return "toast";
160 }) as never,
161 },
162 };
163});
164​
165import { useComposerDraftStore } from "~/composerDraftStore";
166import GitActionsControl from "./GitActionsControl";
167​
168// ThreadDetailsPanel keeps this component mounted behind React.memo when threads change.
169const MemoGitActionsControl = memo(GitActionsControl);
170​
171let root: Root;
172let container: HTMLDivElement;
173​
174function render(thread = "thread", cwd = "/repo") {
175 return act(async () =>
176 root.render(
177 <MemoGitActionsControl
178 gitCwd={cwd}
179 activeThreadRef={{
180 environmentId: EnvironmentId.make("environment"),
181 threadId: ThreadId.make(thread),
182 }}
183 />,
184 ),
185 );
187​
188const button = (name: string | RegExp) =>
189 page.getByRole("button", { name, exact: typeof name === "string" });
190const commits = () => state.actions.length;
191​
192async function openCommitDialog() {
193 await userEvent.click(button("Git action options"));
194 await userEvent.click(page.getByRole("menuitem", { name: "Commit" }));
195 await expect.element(page.getByRole("dialog", { name: "Commit changes" })).toBeVisible();
197​
198beforeEach(() => {
199 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
200 state.scopes = new Set([AuthSourceControlWriteScope]);
201 state.primaryScopes = new Set([AuthSourceControlWriteScope, AuthOrchestrationOperateScope]);
202 state.shell = { branch: "main" };
203 state.detail = null;
204 state.draft = null;
205 state.branch = "main";
206 state.isDefaultRef = false;
207 state.actions = [];
208 state.metadataRequests = [];
209 state.toasts = [];
210 state.afterGitAction = undefined;
211 state.workingTreeRoot = undefined;
212 state.files = [{ path: "file.ts", insertions: 1, deletions: 0 }];
213 state.editorOpens = [];
214 useComposerDraftStore.setState({
215 getDraftSession: () => state.draft as never,
216 getDraftThreadByRef: () => state.draft as never,
217 setDraftThreadContext: (_target, input) => {
218 if (state.draft && input.branch) state.draft = { ...state.draft, branch: input.branch };
219 },
220 });
221 container = document.createElement("div");
222 document.body.append(container);
223 root = createRoot(container);
224});
225​
226afterEach(async () => {
227 await act(async () => root.unmount());
228 container.remove();
229 vi.unstubAllGlobals();
230 await vi.waitFor(() => expect(document.querySelector('[role="dialog"]')).toBeNull());
231});
232​
233describe("Git actions while thread details load", () => {
234 it("does not offer a feature branch for a server thread without task permission", async () => {
235 await render();
236 await openCommitDialog();
237​
238 // The primary environment's task grant must not leak into this thread's environment.
239 await expect.element(button("Commit on new branch")).toBeDisabled();
240 expect(commits()).toBe(0);
241 });
242​
243 it("checks the task grant again when the feature-branch commit runs", async () => {
244 state.scopes.add(AuthOrchestrationOperateScope);
245 await render();
246 await openCommitDialog();
247 state.scopes.delete(AuthOrchestrationOperateScope);
248​
249 await userEvent.click(button("Commit on new branch"));
250​
251 expect(commits()).toBe(0);
252 expect(state.branch).toBe("main");
253 expect(state.shell?.branch).toBe("main");
254 });
255​
256 it("commits and synchronizes the server thread before details finish loading", async () => {
257 state.primaryScopes.clear();
258 state.scopes.add(AuthOrchestrationOperateScope);
259 await render();
260 await openCommitDialog();
261 await userEvent.click(button("Commit on new branch"));
262​
263 await vi.waitFor(() => expect(state.shell?.branch).toBe("feature"));
264 expect(commits()).toBe(1);
265 expect(state.actions[0]?.input).toMatchObject({ action: "commit", featureBranch: true });
266 expect(state.metadataRequests).toEqual([{ environmentId: "environment", branch: "feature" }]);
267 });
268​
269 it("synchronizes archived thread detail after its shell disappears", async () => {
270 state.scopes.add(AuthOrchestrationOperateScope);
271 state.detail = { branch: "main" };
272 await render();
273 state.shell = null;
274 await render();
275 await openCommitDialog();
276 await userEvent.click(button("Commit on new branch"));
277​
278 await vi.waitFor(() => expect(state.detail?.branch).toBe("feature"));
279 expect(commits()).toBe(1);
280 expect(state.metadataRequests).toEqual([{ environmentId: "environment", branch: "feature" }]);
281 });
282​
283 it("requires task permission before changing an archived thread's branch", async () => {
284 state.shell = null;
285 state.detail = { branch: "main" };
286 await render();
287 await openCommitDialog();
288​
289 await expect.element(button("Commit on new branch")).toBeDisabled();
290 expect(state.metadataRequests).toEqual([]);
291 });
292​
293 it("uses the current shell branch when cached detail names the new branch", async () => {
294 state.scopes.add(AuthOrchestrationOperateScope);
295 state.detail = { branch: "feature" };
296 await render();
297 await openCommitDialog();
298 await userEvent.click(button("Commit on new branch"));
299​
300 await vi.waitFor(() => expect(state.shell?.branch).toBe("feature"));
301 expect(state.metadataRequests).toEqual([{ environmentId: "environment", branch: "feature" }]);
302 });
303​
304 it.each([
305 [AuthOrchestrationOperateScope, false],
306 [AuthSourceControlWriteScope, true],
307 ] as const)(
308 "uses the fresh task grant after Git finishes, revoking %s",
309 async (revokedScope, syncsThread) => {
310 state.scopes.add(AuthOrchestrationOperateScope);
311 state.afterGitAction = () => state.scopes.delete(revokedScope);
312 await render();
313 await openCommitDialog();
314 await userEvent.click(button("Commit on new branch"));
315​
316 await vi.waitFor(() => expect(state.branch).toBe("feature"));
317 expect(commits()).toBe(1);
318 expect(state.shell?.branch).toBe(syncsThread ? "feature" : "main");
319 expect(state.metadataRequests).toHaveLength(syncsThread ? 1 : 0);
320 },
321 );
322​
323 it("keeps ordinary commits available while details load", async () => {
324 await render();
325 await openCommitDialog();
326 await userEvent.click(button("Commit"));
327​
328 await vi.waitFor(() => expect(commits()).toBe(1));
329 expect(state.actions[0]?.input).not.toHaveProperty("featureBranch");
330 expect(state.branch).toBe("main");
331 });
332​
333 it("keeps feature-branch commits available for a local draft", async () => {
334 state.shell = null;
335 state.draft = { branch: "main", worktreePath: null, envMode: "local" };
336 await render();
337 await openCommitDialog();
338 await userEvent.click(button("Commit on new branch"));
339​
340 await vi.waitFor(() => expect(state.draft?.branch).toBe("feature"));
341 expect(commits()).toBe(1);
342 expect(state.metadataRequests).toEqual([]);
343 });
344});
345​
346describe("Changed-file editor targets", () => {
347 beforeEach(() => {
348 state.scopes.add(AuthOrchestrationOperateScope);
349 state.files = [
350 { path: "nested/new.txt", insertions: 0, deletions: 0 },
351 { path: "nested/tracked.txt", insertions: 1, deletions: 0 },
352 ];
353 });
354​
355 it("resolves repository-relative paths against the status root, not the project cwd", async () => {
356 state.workingTreeRoot = "/repo";
357 await render("thread", "/repo/nested");
358 await openCommitDialog();
359​
360 await userEvent.click(button("Open nested/new.txt in editor"));
361 await userEvent.click(button("Open nested/tracked.txt in editor"));
362​
363 await vi.waitFor(() => expect(state.editorOpens).toHaveLength(2));
364 expect(state.editorOpens).toEqual([
365 { environmentId: "environment", input: { cwd: "/repo/nested/new.txt", editor: "cursor" } },
366 {
367 environmentId: "environment",
368 input: { cwd: "/repo/nested/tracked.txt", editor: "cursor" },
369 },
370 ]);
371 });
372​
373 it("does not guess a file location when the server reports no root", async () => {
374 await render("thread", "/repo/nested");
375 await openCommitDialog();
376​
377 await expect.element(button("Open nested/new.txt in editor")).toBeDisabled();
378 expect(state.editorOpens).toEqual([]);
379 });
380});
381​
382describe("Default branch prompt", () => {
383 beforeEach(() => {
384 state.isDefaultRef = true;
385 state.scopes.add(AuthOrchestrationOperateScope);
386 });
387​
388 it("moves the commit to a feature branch when asked", async () => {
389 await render();
390 await userEvent.click(button(/^Commit & push/));
391 await expect
392 .element(page.getByRole("dialog", { name: "Commit & push to default ref?" }))
393 .toBeVisible();
394 expect(commits()).toBe(0);
395​
396 await userEvent.click(button("Check out feature branch & continue"));
397​
398 await vi.waitFor(() => expect(state.shell?.branch).toBe("feature"));
399 expect(state.actions[0]?.input).toMatchObject({ action: "commit_push", featureBranch: true });
400 });
401​
402 it("checks the task grant again when the feature branch is chosen", async () => {
403 await render();
404 await userEvent.click(button(/^Commit & push/));
405 await expect
406 .element(page.getByRole("dialog", { name: "Commit & push to default ref?" }))
407 .toBeVisible();
408 state.scopes.delete(AuthOrchestrationOperateScope);
409​
410 await userEvent.click(button("Check out feature branch & continue"));
411​
412 expect(commits()).toBe(0);
413 expect(state.shell?.branch).toBe("main");
414 });
415});
416​
417describe("Git action targets across thread navigation", () => {
418 const quickAction = () => button(/^Commit, push & /);
419​
420 it("runs a retained PR toast in the thread that produced it", async () => {
421 await render("first", "/first");
422 await userEvent.click(quickAction());
423 await vi.waitFor(() => expect(state.toasts.some((toast) => toast.actionProps)).toBe(true));
424 const toast = state.toasts.find((toast) => toast.actionProps)!;
425​
426 await render("second", "/second");
427 await act(async () => toast.actionProps!.onClick());
428​
429 expect(state.actions.at(-1)).toMatchObject({
430 scope: { cwd: "/first" },
431 input: { threadId: "first", action: "commit_push_pr" },
432 });
433 });
434​
435 it("runs the memoized button in the current thread after navigation", async () => {
436 for (const [thread, cwd] of [
437 ["first", "/first"],
438 ["second", "/second"],
439 ["first", "/first"],
440 ] as const) {
441 await render(thread, cwd);
442 await userEvent.click(quickAction());
443 await vi.waitFor(() =>
444 expect(state.actions.at(-1)).toMatchObject({ scope: { cwd }, input: { threadId: thread } }),
445 );
446 }
447 expect(commits()).toBe(3);
448 });
449});