Open History to see the last commit
1// @vitest-environment jsdom
2import {
3 AuthOrchestrationOperateScope,
4 AuthSourceControlWriteScope,
5 EnvironmentId,
6 ThreadId,
7} from "@t3tools/contracts";
8import * as Cause from "effect/Cause";
9import { AsyncResult } from "effect/reactivity";
10import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
11
12const state = vi.hoisted(() => ({
13 scopes: new Set<string>(),
14 primaryScopes: new Set<string>(),
15 shell: { branch: "main" } as { branch: string } | null,
16 detail: null as { branch: string } | null,
17 draft: null as { branch: string; worktreePath: null; envMode: "local" } | null,
18 branch: "main",
19 commits: 0,
20 metadataRequests: [] as { environmentId: string; branch: string }[],
21 afterGitAction: undefined as (() => void) | undefined,
22}));
23
24vi.mock("@effect/atom-react", () => ({
25 useAtomValue: (atom: unknown) => (atom === "vcs-state" ? { isRunning: false } : null),
26}));
27vi.mock("~/state/entities", () => ({
28 useThreadProjection: (ref: unknown) =>
29 ref === null || state.detail === null ? null : { projection: { thread: state.detail } },
30 useThreadShell: () => state.shell,
31}));
32vi.mock("~/state/session", () => ({
33 useEnvironmentScope: (environmentId: unknown, scope: string) =>
34 (environmentId === "environment" ? state.scopes : state.primaryScopes).has(scope),
35 readEnvironmentScope: (environmentId: unknown, scope: string) =>
36 (environmentId === "environment" ? state.scopes : state.primaryScopes).has(scope),
37}));
38vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command }));
39vi.mock("~/state/server", () => ({ serverEnvironment: { configValueAtom: () => null } }));
40vi.mock("~/state/sourceControl", () => ({ sourceControlEnvironment: { discovery: () => null } }));
41vi.mock("@tanstack/react-router", () => ({ useNavigate: () => () => {} }));
42vi.mock("~/state/vcs", () => ({
43 vcsEnvironment: { status: () => null },
44 vcsActionManager: { stateAtom: () => "vcs-state" },
45}));
46vi.mock("~/state/threads", () => ({
47 threadEnvironment: {
48 updateMetadata: async ({
49 environmentId,
50 input,
51 }: {
52 environmentId: string;
53 input: { branch: string };
54 }) => {
55 state.metadataRequests.push({ environmentId, branch: input.branch });
56 if (!state.scopes.has(AuthOrchestrationOperateScope))
57 return AsyncResult.failure(Cause.fail(new Error("Task denied")));
58 if (state.shell) state.shell.branch = input.branch;
59 if (state.detail) state.detail.branch = input.branch;
60 return AsyncResult.success(undefined);
61 },
62 },
63}));
64vi.mock("~/state/query", () => ({
65 useEnvironmentQuery: () => ({
66 data: {
67 sourceControlProviders: [],
68 isRepo: true,
69 refName: state.branch,
70 isDefaultRef: false,
71 hasPrimaryRemote: true,
72 hasWorkingTreeChanges: true,
73 workingTree: {
74 files: [{ path: "file.ts", status: "modified", insertions: 1, deletions: 0 }],
75 },
76 },
77 error: null,
78 }),
79}));
80vi.mock("~/composerDraftStore", () => ({
81 useComposerDraftStore: (
82 select: (store: {
83 getDraftSession: () => typeof state.draft;
84 getDraftThreadByRef: () => typeof state.draft;
85 setDraftThreadContext: (_target: unknown, input: { branch: string }) => void;
86 }) => unknown,
87 ) =>
88 select({
89 getDraftSession: () => state.draft,
90 getDraftThreadByRef: () => state.draft,
91 setDraftThreadContext: (_target, input) => {
92 if (state.draft) state.draft.branch = input.branch;
93 },
94 }),
95}));
96vi.mock("~/lib/sourceControlActions", () => ({
97 useSourceControlActionRunning: () => false,
98 useVcsInitAction: () => ({}),
99 useVcsPullAction: () => ({}),
100 useSourceControlPublishRepositoryAction: () => ({}),
101 useGitStackedAction: () => ({
102 run: async ({ featureBranch }: { featureBranch?: boolean }) => {
103 state.commits += 1;
104 if (featureBranch) state.branch = "feature";
105 state.afterGitAction?.();
106 return {
107 _tag: "Success",
108 value: {
109 branch: featureBranch
110 ? { status: "created", name: "feature" }
111 : { status: "skipped_not_requested" },
112 toast: { title: "Committed", description: "Committed", cta: { kind: "none" } },
113 },
114 };
115 },
116 }),
117}));
118vi.mock("~/lib/utils", () => ({ cn: () => "", randomUUID: () => "action" }));
119vi.mock("~/editorPreferences", () => ({ useOpenInPreferredEditor: () => () => {} }));
120vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => () => {} }));
121vi.mock("~/lib/openPullRequestLink", () => ({ useOpenPrLink: () => () => {} }));
122vi.mock("~/components/ui/toast", () => ({
123 stackedThreadToast: (input: unknown) => input,
124 toastManager: { add: () => "toast", update: () => {}, close: () => {} },
125}));
126vi.mock("~/components/ui/dialog", () => ({
127 Dialog: "Dialog",
128 DialogDescription: "DialogDescription",
129 DialogFooter: "DialogFooter",
130 DialogHeader: "DialogHeader",
131 DialogPanel: "DialogPanel",
132 DialogPopup: "DialogPopup",
133 DialogTitle: "DialogTitle",
134}));
135vi.mock("~/components/ui/group", () => ({ Group: "Group", GroupSeparator: "GroupSeparator" }));
136vi.mock("~/components/ui/menu", () => ({
137 Menu: "Menu",
138 MenuItem: "MenuItem",
139 MenuItemLabel: "MenuItemLabel",
140 MenuPopup: "MenuPopup",
141 MenuTrigger: "MenuTrigger",
142}));
143vi.mock("~/components/ui/popover", () => ({
144 Popover: "Popover",
145 PopoverPopup: "PopoverPopup",
146 PopoverTrigger: "PopoverTrigger",
147}));
148vi.mock("~/components/ui/tooltip", () => ({
149 Tooltip: "Tooltip",
150 TooltipPopup: "TooltipPopup",
151 TooltipTrigger: "TooltipTrigger",
152}));
153vi.mock("~/components/ui/button", () => ({ Button: "Button" }));
154vi.mock("~/components/ui/checkbox", () => ({ Checkbox: "Checkbox" }));
155vi.mock("~/components/ui/input", () => ({ Input: "Input" }));
156vi.mock("~/components/ui/radio-group", () => ({ RadioGroup: "RadioGroup" }));
157vi.mock("~/components/ui/scroll-area", () => ({ ScrollArea: "ScrollArea" }));
158vi.mock("~/components/ui/spinner", () => ({ Spinner: "Spinner" }));
159vi.mock("~/components/ui/textarea", () => ({ Textarea: "Textarea" }));
160vi.mock("~/components/ui/toggle", () => ({ toggleVariants: () => "" }));
161vi.mock("./AnimatedHeight", () => ({ AnimatedHeight: "AnimatedHeight" }));
162
163import GitActionsControl from "./GitActionsControl";
164
165import { createElement } from "react";
166import { act, create, type ReactTestRenderer } from "react-test-renderer";
167
168vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
169
170let renderer: ReactTestRenderer | null = null;
171
172// Opens the commit dialog and returns its buttons' handlers from this render, so a test can
173// change grants afterwards and still click what the user saw.
174async function renderActions() {
175 const element = createElement(GitActionsControl, {
176 gitCwd: "/repo",
177 activeThreadRef: {
178 environmentId: EnvironmentId.make("environment"),
179 threadId: ThreadId.make("thread"),
180 },
181 });
182 await act(async () => {
183 if (renderer) renderer.update(element);
184 else renderer = create(element);
185 });
186 const root = renderer!.root;
187 const commitMenuItem = root.find(
188 (node) => String(node.type) === "MenuItemLabel" && node.props.children === "Commit",
189 ).parent!;
190 await act(async () => {
191 commitMenuItem.props.onClick();
192 });
193 const buttonHandler = (label: string): (() => void) =>
194 root.find((node) => String(node.type) === "Button" && node.props.children === label).props
195 .onClick;
196 const commit = buttonHandler("Commit");
197 const commitOnNewBranch = buttonHandler("Commit on new branch");
198 return async ({ featureBranch }: { action: "commit"; featureBranch?: boolean }) => {
199 await act(async () => {
200 (featureBranch ? commitOnNewBranch : commit)();
201 });
202 };
203}
204
205afterEach(async () => {
206 await act(async () => {
207 renderer?.unmount();
208 });
209 renderer = null;
210});
211
212describe("Git actions while thread details load", () => {
213 beforeEach(() => {
214 state.scopes = new Set([AuthSourceControlWriteScope]);
215 state.primaryScopes = new Set([AuthSourceControlWriteScope, AuthOrchestrationOperateScope]);
216 state.shell = { branch: "main" };
217 state.detail = null;
218 state.draft = null;
219 state.branch = "main";
220 state.commits = 0;
221 state.metadataRequests = [];
222 state.afterGitAction = undefined;
223 });
224
225 it("does not create a feature branch for a server thread without task permission", async () => {
226 await (
227 await renderActions()
228 )({ action: "commit", featureBranch: true });
229
230 expect(state.branch).toBe("main");
231 expect(state.commits).toBe(0);
232 expect(state.shell?.branch).toBe("main");
233 });
234
235 it("commits and synchronizes the server thread before details finish loading", async () => {
236 state.primaryScopes.clear();
237 state.scopes.add(AuthOrchestrationOperateScope);
238 await (
239 await renderActions()
240 )({ action: "commit", featureBranch: true });
241
242 expect(state.branch).toBe("feature");
243 expect(state.commits).toBe(1);
244 expect(state.shell?.branch).toBe("feature");
245 expect(state.metadataRequests).toEqual([{ environmentId: "environment", branch: "feature" }]);
246 });
247
248 it("synchronizes archived thread detail after its shell disappears", async () => {
249 state.scopes.add(AuthOrchestrationOperateScope);
250 state.detail = { branch: "main" };
251 await renderActions();
252 state.shell = null;
253
254 await (
255 await renderActions()
256 )({ action: "commit", featureBranch: true });
257
258 expect(state.commits).toBe(1);
259 expect(state.branch).toBe("feature");
260 expect(state.detail.branch).toBe("feature");
261 expect(state.metadataRequests).toEqual([{ environmentId: "environment", branch: "feature" }]);
262 });
263
264 it("requires task permission before changing an archived thread's branch", async () => {
265 state.shell = null;
266 state.detail = { branch: "main" };
267
268 await (
269 await renderActions()
270 )({ action: "commit", featureBranch: true });
271
272 expect(state.commits).toBe(0);
273 expect(state.detail.branch).toBe("main");
274 expect(state.metadataRequests).toEqual([]);
275 });
276
277 it("uses the current shell branch when cached detail names the new branch", async () => {
278 state.scopes.add(AuthOrchestrationOperateScope);
279 state.detail = { branch: "feature" };
280
281 await (
282 await renderActions()
283 )({ action: "commit", featureBranch: true });
284
285 expect(state.commits).toBe(1);
286 expect(state.shell?.branch).toBe("feature");
287 expect(state.metadataRequests).toEqual([{ environmentId: "environment", branch: "feature" }]);
288 });
289
290 it("synchronizes a retained callback after the thread grant is gained", async () => {
291 const run = await renderActions();
292 state.scopes.add(AuthOrchestrationOperateScope);
293 await run({ action: "commit", featureBranch: true });
294 expect(state.commits).toBe(1);
295 expect(state.shell?.branch).toBe("feature");
296 expect(state.metadataRequests).toHaveLength(1);
297 });
298
299 it.each([
300 [AuthOrchestrationOperateScope, false],
301 [AuthSourceControlWriteScope, true],
302 ] as const)(
303 "uses the fresh task grant after Git finishes, revoking %s",
304 async (revokedScope, syncsThread) => {
305 state.scopes.add(AuthOrchestrationOperateScope);
306 state.afterGitAction = () => state.scopes.delete(revokedScope);
307 await (
308 await renderActions()
309 )({ action: "commit", featureBranch: true });
310 expect(state.commits).toBe(1);
311 expect(state.branch).toBe("feature");
312 expect(state.shell?.branch).toBe(syncsThread ? "feature" : "main");
313 expect(state.metadataRequests).toHaveLength(syncsThread ? 1 : 0);
314 },
315 );
316
317 it("keeps ordinary commits available while details load", async () => {
318 await (
319 await renderActions()
320 )({ action: "commit" });
321
322 expect(state.commits).toBe(1);
323 expect(state.branch).toBe("main");
324 });
325
326 it("keeps feature-branch commits available for a local draft", async () => {
327 state.shell = null;
328 state.draft = { branch: "main", worktreePath: null, envMode: "local" };
329 await (
330 await renderActions()
331 )({ action: "commit", featureBranch: true });
332
333 expect(state.commits).toBe(1);
334 expect(state.draft.branch).toBe("feature");
335 expect(state.metadataRequests).toEqual([]);
336 });
337});