Open History to see the last commit
1import { AuthOrchestrationOperateScope, AuthSourceControlWriteScope } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import { AsyncResult } from "effect/reactivity";
4import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
5
6const state = vi.hoisted(() => ({
7 scopes: new Set<string>(),
8 primaryScopes: new Set<string>(),
9 branch: "main",
10 worktrees: [] as string[],
11 thread: {
12 id: "thread",
13 environmentId: "environment",
14 branch: "main",
15 worktreePath: null as string | null,
16 },
17 commits: 0,
18 pushes: 0,
19 metadataRequests: [] as { environmentId: string; branch: string }[],
20 results: [] as { type: string; description?: string }[],
21 afterGitAction: undefined as (() => void) | undefined,
22 statusRefreshes: 0,
23}));
24
25vi.mock("react", () => ({
26 useCallback: (callback: unknown) => callback,
27 useMemo: (factory: () => unknown) => factory(),
28}));
29vi.mock("@effect/atom-react", () => ({ useAtomMount: () => {} }));
30vi.mock("./session", () => ({
31 useEnvironmentScope: (environmentId: unknown, scope: string) =>
32 (environmentId === state.thread.environmentId ? state.scopes : state.primaryScopes).has(scope),
33 readEnvironmentScope: (environmentId: unknown, scope: string) =>
34 (environmentId === state.thread.environmentId ? state.scopes : state.primaryScopes).has(scope),
35}));
36vi.mock("./use-thread-selection", () => ({
37 useThreadSelection: () => ({
38 selectedThread: state.thread,
39 selectedThreadProject: { workspaceRoot: "/repo" },
40 }),
41}));
42vi.mock("./use-selected-thread-worktree", () => ({
43 useSelectedThreadWorktree: () => ({
44 selectedThreadCwd: "/repo",
45 selectedThreadWorktreePath: null,
46 }),
47}));
48vi.mock("./queries", () => ({
49 useBranches: () => ({ data: { refs: [] }, refresh: () => {} }),
50}));
51vi.mock("./use-atom-command", () => ({ useAtomCommand: (command: unknown) => command }));
52vi.mock("./atom-registry", () => ({ appAtomRegistry: {} }));
53vi.mock("./use-remote-environment-registry", () => ({
54 environmentConnectedAtom: () => null,
55 setPendingConnectionError: () => {},
56}));
57vi.mock("./use-vcs-action-state", () => ({
58 showGitActionResult: (result: { type: string; description?: string }) =>
59 state.results.push(result),
60}));
61vi.mock("../lib/uuid", () => ({ uuidv4: () => "action" }));
62vi.mock("./threads", () => ({
63 threadEnvironment: {
64 updateMetadata: async ({
65 environmentId,
66 input,
67 }: {
68 environmentId: string;
69 input: { branch: string; worktreePath: string | null };
70 }) => {
71 state.metadataRequests.push({ environmentId, branch: input.branch });
72 if (!state.scopes.has(AuthOrchestrationOperateScope)) {
73 return AsyncResult.failure(Cause.fail(new Error("Task operation denied")));
74 }
75 Object.assign(state.thread, input);
76 return AsyncResult.success(undefined);
77 },
78 },
79}));
80vi.mock("./vcs", () => ({
81 vcsEnvironment: {
82 refreshStatus: async () => {
83 state.statusRefreshes += 1;
84 return AsyncResult.success({ refName: state.branch });
85 },
86 switchRef: async ({ input }: { input: { refName: string } }) => {
87 state.branch = input.refName;
88 state.afterGitAction?.();
89 return AsyncResult.success({ refName: state.branch });
90 },
91 createRef: async ({ input }: { input: { refName: string } }) => {
92 state.branch = input.refName;
93 state.afterGitAction?.();
94 return AsyncResult.success({ refName: state.branch });
95 },
96 createWorktree: async ({ input }: { input: { newRefName: string } }) => {
97 state.worktrees.push("/repo-worktree");
98 state.afterGitAction?.();
99 return AsyncResult.success({
100 worktree: { path: "/repo-worktree", refName: input.newRefName },
101 });
102 },
103 pull: async () => AsyncResult.success({ status: "pulled", refName: state.branch }),
104 },
105 vcsActionManager: {
106 track: (_registry: unknown, _target: unknown, _operation: unknown, run: () => unknown) => run(),
107 runStackedAction: () => async (input: { action: string; featureBranch?: boolean }) => {
108 if (input.featureBranch) state.branch = "feature";
109 if (input.action === "commit") state.commits += 1;
110 if (input.action === "push") state.pushes += 1;
111 state.afterGitAction?.();
112 return AsyncResult.success({
113 branch: input.featureBranch
114 ? { status: "created", name: "feature" }
115 : { status: "skipped_not_requested" },
116 toast: { title: "Done", description: "Done", cta: { kind: "none" } },
117 });
118 },
119 },
120}));
121
122import { useSelectedThreadGitActions } from "./use-selected-thread-git-actions";
123
124describe("thread Git mutation permissions", () => {
125 beforeEach(() => {
126 state.scopes = new Set([AuthSourceControlWriteScope]);
127 state.primaryScopes = new Set([AuthSourceControlWriteScope, AuthOrchestrationOperateScope]);
128 state.branch = "main";
129 state.worktrees = [];
130 state.thread.branch = "main";
131 state.thread.worktreePath = null;
132 state.commits = 0;
133 state.pushes = 0;
134 state.metadataRequests = [];
135 state.results = [];
136 state.afterGitAction = undefined;
137 state.statusRefreshes = 0;
138 });
139
140 it.each([false, true])(
141 "requires task permission before creating and attaching a worktree: %s",
142 async (canOperate) => {
143 if (canOperate) state.scopes.add(AuthOrchestrationOperateScope);
144 const actions = useSelectedThreadGitActions();
145 const result = await actions.onCreateSelectedThreadWorktree({
146 baseBranch: "main",
147 newBranch: "feature/task",
148 });
149 expect(result).toEqual(
150 canOperate ? { worktree: { path: "/repo-worktree", refName: "feature/task" } } : null,
151 );
152 expect(state.worktrees).toEqual(canOperate ? ["/repo-worktree"] : []);
153 expect(state.thread.worktreePath).toBe(canOperate ? "/repo-worktree" : null);
154 expect(state.thread.branch).toBe(canOperate ? "feature/task" : "main");
155 },
156 );
157
158 it("keeps ordinary commits and pushes available without task permission", async () => {
159 const actions = useSelectedThreadGitActions();
160 await actions.onRunSelectedThreadGitAction({ action: "commit" });
161 await actions.onRunSelectedThreadGitAction({ action: "push" });
162 expect(state.commits).toBe(1);
163 expect(state.pushes).toBe(1);
164 expect(state.thread.branch).toBe("main");
165 expect(state.metadataRequests).toEqual([]);
166 });
167
168 it.each(["create", "checkout", "worktree", "commit"] as const)(
169 "does not send thread metadata after task permission is revoked during %s",
170 async (operation) => {
171 state.scopes.add(AuthOrchestrationOperateScope);
172 state.afterGitAction = () => state.scopes.delete(AuthOrchestrationOperateScope);
173 const actions = useSelectedThreadGitActions();
174 if (operation === "create")
175 expect(await actions.onCreateSelectedThreadBranch("feature")).toBeNull();
176 if (operation === "checkout")
177 expect(await actions.onCheckoutSelectedThreadBranch("feature")).toBeNull();
178 if (operation === "worktree")
179 expect(
180 await actions.onCreateSelectedThreadWorktree({
181 baseBranch: "main",
182 newBranch: "feature",
183 }),
184 ).toBeNull();
185 if (operation === "commit")
186 expect(
187 await actions.onRunSelectedThreadGitAction({ action: "commit", featureBranch: true }),
188 ).toBeNull();
189 if (operation === "worktree") expect(state.worktrees).toEqual(["/repo-worktree"]);
190 else expect(state.branch).toBe("feature");
191 expect(state.thread.branch).toBe("main");
192 expect(state.thread.worktreePath).toBeNull();
193 expect(state.metadataRequests).toEqual([]);
194 expect(state.results.map((result) => result.type)).toEqual(["error"]);
195 },
196 );
197
198 it("refreshes the worktree status when the metadata update is denied after checkout", async () => {
199 state.scopes.add(AuthOrchestrationOperateScope);
200 state.afterGitAction = () => state.scopes.delete(AuthOrchestrationOperateScope);
201 expect(
202 await useSelectedThreadGitActions().onCheckoutSelectedThreadBranch("feature"),
203 ).toBeNull();
204 expect(state.branch).toBe("feature");
205 expect(state.statusRefreshes).toBe(1);
206 });
207
208 it.each(["create", "checkout", "worktree"] as const)(
209 "returns the accepted %s result when only source-control permission is revoked after Git",
210 async (operation) => {
211 state.scopes.add(AuthOrchestrationOperateScope);
212 state.afterGitAction = () => state.scopes.delete(AuthSourceControlWriteScope);
213 const actions = useSelectedThreadGitActions();
214 const result =
215 operation === "create"
216 ? await actions.onCreateSelectedThreadBranch("feature/task")
217 : operation === "checkout"
218 ? await actions.onCheckoutSelectedThreadBranch("feature/task")
219 : await actions.onCreateSelectedThreadWorktree({
220 baseBranch: "main",
221 newBranch: "feature/task",
222 });
223 expect(result).toEqual(
224 operation === "worktree"
225 ? { worktree: { path: "/repo-worktree", refName: "feature/task" } }
226 : { refName: "feature/task" },
227 );
228 expect(state.thread.branch).toBe("feature/task");
229 expect(state.metadataRequests).toHaveLength(1);
230 expect(state.results).toEqual([]);
231 },
232 );
233});