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