Open History to see the last commit
1import { AuthOrchestrationOperateScope, AuthSourceControlWriteScope } from "@t3tools/contracts";
2import type { VcsListRefsResult } from "@t3tools/contracts";
3import { resolveAutoFeatureBranchName } from "@t3tools/shared/git";
4import * as Cause from "effect/Cause";
5import { AsyncResult } from "effect/reactivity";
6import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
7
8const state = vi.hoisted(() => ({
9 scopes: new Set<string>(),
10 primaryScopes: new Set<string>(),
11 branch: "main",
12 worktrees: [] as string[],
13 thread: {
14 id: "thread",
15 environmentId: "environment",
16 branch: "main",
17 worktreePath: null as string | null,
18 },
19 commits: 0,
20 pushes: 0,
21 actionCwds: [] as (string | null)[],
22 repositoryActions: [] as { cwd: string }[],
23 metadataRequests: [] as { environmentId: string; branch: string }[],
24 results: [] as { type: string; description?: string }[],
25 afterGitAction: undefined as (() => void) | undefined,
26 statusRefreshes: 0,
27 readRefs: vi.fn(),
28 cachedRefs: [] as VcsListRefsResult["refs"],
29}));
30
31vi.mock("react", () => ({
32 useCallback: (callback: unknown) => callback,
33 useMemo: (factory: () => unknown) => factory(),
34}));
35vi.mock("@effect/atom-react", () => ({ useAtomMount: () => {} }));
36vi.mock("./session", () => ({
37 useEnvironmentScope: (environmentId: unknown, scope: string) =>
38 (environmentId === state.thread.environmentId ? state.scopes : state.primaryScopes).has(scope),
39 readEnvironmentScope: (environmentId: unknown, scope: string) =>
40 (environmentId === state.thread.environmentId ? state.scopes : state.primaryScopes).has(scope),
41}));
42vi.mock("./use-thread-selection", () => ({
43 useThreadSelection: () => ({
44 selectedThread: state.thread,
45 selectedThreadProject: { workspaceRoot: "/repo" },
46 }),
47}));
48vi.mock("./use-selected-thread-worktree", () => ({
49 useSelectedThreadWorktree: () => ({
50 selectedThreadCwd: "/repo",
51 selectedThreadWorktreePath: null,
52 }),
53}));
54vi.mock("./queries", () => ({
55 useBranches: () => ({ data: { refs: state.cachedRefs }, refresh: () => {} }),
56}));
57vi.mock("./use-atom-command", () => ({ useAtomCommand: (command: unknown) => command }));
58vi.mock("./atom-registry", () => ({ appAtomRegistry: {} }));
59vi.mock("./use-remote-environment-registry", () => ({
60 environmentConnectedAtom: () => null,
61 setPendingConnectionError: () => {},
62}));
63vi.mock("./use-vcs-action-state", () => ({
64 showGitActionResult: (result: { type: string; description?: string }) =>
65 state.results.push(result),
66 noteRepositoryGitAction: (action: { cwd: string }) => state.repositoryActions.push(action),
67}));
68vi.mock("../lib/uuid", () => ({ uuidv4: () => "action" }));
69vi.mock("./threads", () => ({
70 threadEnvironment: {
71 updateMetadata: async ({
72 environmentId,
73 input,
74 }: {
75 environmentId: string;
76 input: { branch: string; worktreePath: string | null };
77 }) => {
78 state.metadataRequests.push({ environmentId, branch: input.branch });
79 if (!state.scopes.has(AuthOrchestrationOperateScope)) {
80 return AsyncResult.failure(Cause.fail(new Error("Task operation denied")));
81 }
82 Object.assign(state.thread, input);
83 return AsyncResult.success(undefined);
84 },
85 },
86}));
87vi.mock("./vcs", () => ({
88 vcsEnvironment: {
89 readRefs: state.readRefs,
90 refreshStatus: async () => {
91 state.statusRefreshes += 1;
92 return AsyncResult.success({ refName: state.branch });
93 },
94 switchRef: async ({ input }: { input: { refName: string } }) => {
95 state.branch = input.refName;
96 state.afterGitAction?.();
97 return AsyncResult.success({ refName: state.branch });
98 },
99 createRef: async ({ input }: { input: { refName: string } }) => {
100 state.branch = input.refName;
101 state.afterGitAction?.();
102 return AsyncResult.success({ refName: state.branch });
103 },
104 createWorktree: async ({ input }: { input: { newRefName: string } }) => {
105 state.worktrees.push("/repo-worktree");
106 state.afterGitAction?.();
107 return AsyncResult.success({
108 worktree: { path: "/repo-worktree", refName: input.newRefName },
109 });
110 },
111 pull: async () => AsyncResult.success({ status: "pulled", refName: state.branch }),
112 },
113 vcsActionManager: {
114 track: (_registry: unknown, _target: unknown, _operation: unknown, run: () => unknown) => run(),
115 runStackedAction:
116 (target: { cwd: string | null }) =>
117 async (input: { action: string; featureBranch?: boolean }) => {
118 state.actionCwds.push(target.cwd);
119 if (input.featureBranch) state.branch = "feature";
120 if (input.action === "commit") state.commits += 1;
121 if (input.action === "push") state.pushes += 1;
122 state.afterGitAction?.();
123 return AsyncResult.success({
124 branch: input.featureBranch
125 ? { status: "created", name: "feature" }
126 : { status: "skipped_not_requested" },
127 toast: { title: "Done", description: "Done", cta: { kind: "none" } },
128 });
129 },
130 },
131}));
132
133import { useSelectedThreadGitActions } from "./use-selected-thread-git-actions";
134
135describe("thread Git mutation permissions", () => {
136 beforeEach(() => {
137 state.scopes = new Set([AuthSourceControlWriteScope]);
138 state.primaryScopes = new Set([AuthSourceControlWriteScope, AuthOrchestrationOperateScope]);
139 state.branch = "main";
140 state.worktrees = [];
141 state.thread.branch = "main";
142 state.thread.worktreePath = null;
143 state.commits = 0;
144 state.pushes = 0;
145 state.actionCwds = [];
146 state.repositoryActions = [];
147 state.metadataRequests = [];
148 state.results = [];
149 state.afterGitAction = undefined;
150 state.statusRefreshes = 0;
151 });
152
153 it.each([false, true])(
154 "requires task permission before creating and attaching a worktree: %s",
155 async (canOperate) => {
156 if (canOperate) state.scopes.add(AuthOrchestrationOperateScope);
157 const actions = useSelectedThreadGitActions();
158 const result = await actions.onCreateSelectedThreadWorktree({
159 baseBranch: "main",
160 newBranch: "feature/task",
161 });
162 expect(result).toEqual(
163 canOperate ? { worktree: { path: "/repo-worktree", refName: "feature/task" } } : null,
164 );
165 expect(state.worktrees).toEqual(canOperate ? ["/repo-worktree"] : []);
166 expect(state.thread.worktreePath).toBe(canOperate ? "/repo-worktree" : null);
167 expect(state.thread.branch).toBe(canOperate ? "feature/task" : "main");
168 },
169 );
170
171 it("keeps ordinary commits and pushes available without task permission", async () => {
172 const actions = useSelectedThreadGitActions();
173 await actions.onRunSelectedThreadGitAction({ action: "commit" });
174 await actions.onRunSelectedThreadGitAction({ action: "push" });
175 expect(state.commits).toBe(1);
176 expect(state.pushes).toBe(1);
177 expect(state.thread.branch).toBe("main");
178 expect(state.metadataRequests).toEqual([]);
179 });
180
181 it.each(["create", "checkout", "worktree", "commit"] as const)(
182 "does not send thread metadata after task permission is revoked during %s",
183 async (operation) => {
184 state.scopes.add(AuthOrchestrationOperateScope);
185 state.afterGitAction = () => state.scopes.delete(AuthOrchestrationOperateScope);
186 const actions = useSelectedThreadGitActions();
187 if (operation === "create")
188 expect(await actions.onCreateSelectedThreadBranch("feature")).toBeNull();
189 if (operation === "checkout")
190 expect(await actions.onCheckoutSelectedThreadBranch("feature")).toBeNull();
191 if (operation === "worktree")
192 expect(
193 await actions.onCreateSelectedThreadWorktree({
194 baseBranch: "main",
195 newBranch: "feature",
196 }),
197 ).toBeNull();
198 if (operation === "commit")
199 expect(
200 await actions.onRunSelectedThreadGitAction({ action: "commit", featureBranch: true }),
201 ).toBeNull();
202 if (operation === "worktree") expect(state.worktrees).toEqual(["/repo-worktree"]);
203 else expect(state.branch).toBe("feature");
204 expect(state.thread.branch).toBe("main");
205 expect(state.thread.worktreePath).toBeNull();
206 expect(state.metadataRequests).toEqual([]);
207 expect(state.results.map((result) => result.type)).toEqual(["error"]);
208 },
209 );
210
211 it("runs a tracked repository's actions in its folder without touching the thread", async () => {
212 const actions = useSelectedThreadGitActions({
213 key: "/repo/api",
214 cwd: "/repo/api",
215 name: "api",
216 });
217 expect(actions.canChangeThreadBranch).toBe(false);
218 expect(actions.canCreateFeatureBranch).toBe(true);
219 expect(
220 await actions.onRunSelectedThreadGitAction({ action: "commit", featureBranch: true }),
221 ).not.toBeNull();
222 expect(await actions.onCreateSelectedThreadBranch("feature/api")).toEqual({
223 refName: "feature/api",
224 });
225 expect(
226 await actions.onCreateSelectedThreadWorktree({ baseBranch: "main", newBranch: "feature" }),
227 ).toBeNull();
228 expect(state.actionCwds).toEqual(["/repo/api"]);
229 expect(state.repositoryActions.map((action) => action.cwd)).toEqual(["/repo/api", "/repo/api"]);
230 expect(state.worktrees).toEqual([]);
231 expect(state.thread.branch).toBe("main");
232 expect(state.metadataRequests).toEqual([]);
233 expect(state.results.map((result) => result.type)).toEqual(["success"]);
234 });
235
236 it("refreshes the worktree status when the metadata update is denied after checkout", async () => {
237 state.scopes.add(AuthOrchestrationOperateScope);
238 state.afterGitAction = () => state.scopes.delete(AuthOrchestrationOperateScope);
239 expect(
240 await useSelectedThreadGitActions().onCheckoutSelectedThreadBranch("feature"),
241 ).toBeNull();
242 expect(state.branch).toBe("feature");
243 expect(state.statusRefreshes).toBe(1);
244 });
245
246 it.each(["create", "checkout", "worktree"] as const)(
247 "returns the accepted %s result when only source-control permission is revoked after Git",
248 async (operation) => {
249 state.scopes.add(AuthOrchestrationOperateScope);
250 state.afterGitAction = () => state.scopes.delete(AuthSourceControlWriteScope);
251 const actions = useSelectedThreadGitActions();
252 const result =
253 operation === "create"
254 ? await actions.onCreateSelectedThreadBranch("feature/task")
255 : operation === "checkout"
256 ? await actions.onCheckoutSelectedThreadBranch("feature/task")
257 : await actions.onCreateSelectedThreadWorktree({
258 baseBranch: "main",
259 newBranch: "feature/task",
260 });
261 expect(result).toEqual(
262 operation === "worktree"
263 ? { worktree: { path: "/repo-worktree", refName: "feature/task" } }
264 : { refName: "feature/task" },
265 );
266 expect(state.thread.branch).toBe("feature/task");
267 expect(state.metadataRequests).toHaveLength(1);
268 expect(state.results).toEqual([]);
269 },
270 );
271});
272
273describe("automatic feature branch refs", () => {
274 const empty: VcsListRefsResult = {
275 refs: [],
276 isRepo: true,
277 hasPrimaryRemote: true,
278 nextCursor: null,
279 totalCount: 0,
280 };
281
282 it.each([false, true])("awaits fresh refs before naming, cached: %s", async (cached) => {
283 const request = Promise.withResolvers<VcsListRefsResult>();
284 state.cachedRefs = cached
285 ? [
286 {
287 name: "old-branch",
288 isRemote: false,
289 current: false,
290 isDefault: false,
291 worktreePath: null,
292 },
293 ]
294 : [];
295 state.readRefs.mockReturnValue(request.promise.then(AsyncResult.success));
296 let settled = false;
297 const refresh = useSelectedThreadGitActions()
298 .refreshSelectedThreadBranches()
299 .then((refs) => {
300 settled = true;
301 return refs;
302 });
303 await Promise.resolve();
304 expect(settled).toBe(false);
305 const local = {
306 name: "feature/update",
307 isRemote: false,
308 current: false,
309 isDefault: false,
310 worktreePath: null,
311 };
312 request.resolve({
313 ...empty,
314 refs: [
315 local,
316 { ...local, name: "origin/feature/update", isRemote: true, remoteName: "origin" },
317 ],
318 totalCount: 2,
319 });
320 const refs = await refresh;
321 expect(refs).toEqual([local]);
322 expect(resolveAutoFeatureBranchName(refs!.map((ref) => ref.name))).toBe("feature/update-2");
323 expect(state.readRefs).toHaveBeenCalledWith({
324 environmentId: "environment",
325 input: { cwd: "/repo", limit: 100, refresh: true },
326 });
327 });
328
329 it("reports lookup failure instead of returning empty refs", async () => {
330 state.results = [];
331 state.readRefs.mockResolvedValue(
332 AsyncResult.failure(Cause.fail(new Error("Cannot list refs"))),
333 );
334 expect(await useSelectedThreadGitActions().refreshSelectedThreadBranches()).toBeNull();
335 expect(state.results).toEqual([
336 {
337 threadRef: { environmentId: "environment", threadId: "thread" },
338 type: "error",
339 title: "Git action failed",
340 description: "Cannot list refs",
341 },
342 ]);
343 });
344});