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

use-selected-thread-git-actions.test.ts

283 lines11.1 KB

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 useEffect: () => {},
29}));
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", () => ({ setPendingConnectionError: () => {} }));
54vi.mock("./use-vcs-action-state", () => ({
55 showGitActionResult: (result: { type: string; description?: string }) =>
56 state.results.push(result),
57}));
58vi.mock("../lib/uuid", () => ({ uuidv4: () => "action" }));
59vi.mock("./threads", () => ({
60 threadEnvironment: {
61 updateMetadata: async ({
62 environmentId,
63 input,
64 }: {
65 environmentId: string;
66 input: { branch: string; worktreePath: string | null };
67 }) => {
68 state.metadataRequests.push({ environmentId, branch: input.branch });
69 if (!state.scopes.has(AuthOrchestrationOperateScope)) {
70 return AsyncResult.failure(Cause.fail(new Error("Task operation denied")));
71 }
72 Object.assign(state.thread, input);
73 return AsyncResult.success(undefined);
74 },
75 },
76}));
77vi.mock("./vcs", () => ({
78 vcsEnvironment: {
79 refreshStatus: async () => {
80 state.statusRefreshes += 1;
81 return AsyncResult.success({ refName: state.branch });
82 },
83 switchRef: async ({ input }: { input: { refName: string } }) => {
84 state.branch = input.refName;
85 state.afterGitAction?.();
86 return AsyncResult.success({ refName: state.branch });
87 },
88 createRef: async ({ input }: { input: { refName: string } }) => {
89 state.branch = input.refName;
90 state.afterGitAction?.();
91 return AsyncResult.success({ refName: state.branch });
92 },
93 createWorktree: async ({ input }: { input: { newRefName: string } }) => {
94 state.worktrees.push("/repo-worktree");
95 state.afterGitAction?.();
96 return AsyncResult.success({
97 worktree: { path: "/repo-worktree", refName: input.newRefName },
98 });
99 },
100 pull: async () => AsyncResult.success({ status: "pulled", refName: state.branch }),
101 },
102 vcsActionManager: {
103 track: (_registry: unknown, _target: unknown, _operation: unknown, run: () => unknown) => run(),
104 runStackedAction: () => async (input: { action: string; featureBranch?: boolean }) => {
105 if (input.featureBranch) state.branch = "feature";
106 if (input.action === "commit") state.commits += 1;
107 if (input.action === "push") state.pushes += 1;
108 state.afterGitAction?.();
109 return AsyncResult.success({
110 branch: input.featureBranch
111 ? { status: "created", name: "feature" }
112 : { status: "skipped_not_requested" },
113 toast: { title: "Done", description: "Done", cta: { kind: "none" } },
114 });
115 },
116 },
117}));
118​
119import { useSelectedThreadGitActions } from "./use-selected-thread-git-actions";
120​
121describe("thread Git mutation permissions", () => {
122 beforeEach(() => {
123 state.scopes = new Set([AuthSourceControlWriteScope]);
124 state.primaryScopes = new Set([AuthSourceControlWriteScope, AuthOrchestrationOperateScope]);
125 state.branch = "main";
126 state.worktrees = [];
127 state.thread.branch = "main";
128 state.thread.worktreePath = null;
129 state.commits = 0;
130 state.pushes = 0;
131 state.metadataRequests = [];
132 state.results = [];
133 state.afterGitAction = undefined;
134 state.statusRefreshes = 0;
135 });
136​
137 it.each([false, true])(
138 "requires task permission before creating and attaching a worktree: %s",
139 async (canOperate) => {
140 if (canOperate) state.scopes.add(AuthOrchestrationOperateScope);
141 const actions = useSelectedThreadGitActions();
142 const result = await actions.onCreateSelectedThreadWorktree({
143 baseBranch: "main",
144 newBranch: "feature/task",
145 });
146 expect(result).toEqual(
147 canOperate ? { worktree: { path: "/repo-worktree", refName: "feature/task" } } : null,
148 );
149 expect(state.worktrees).toEqual(canOperate ? ["/repo-worktree"] : []);
150 expect(state.thread.worktreePath).toBe(canOperate ? "/repo-worktree" : null);
151 expect(state.thread.branch).toBe(canOperate ? "feature/task" : "main");
152 },
153 );
154​
155 it.each(["create", "checkout", "commit on new branch"] as const)(
156 "requires task permission before %s",
157 async (operation) => {
158 const actions = useSelectedThreadGitActions();
159 if (operation === "create") {
160 expect(await actions.onCreateSelectedThreadBranch("feature")).toBeNull();
161 }
162 if (operation === "checkout")
163 expect(await actions.onCheckoutSelectedThreadBranch("feature")).toBeNull();
164 if (operation === "commit on new branch")
165 await actions.onRunSelectedThreadGitAction({ action: "commit", featureBranch: true });
166 expect(state.branch).toBe("main");
167 expect(state.thread.branch).toBe("main");
168 expect(state.commits).toBe(0);
169 },
170 );
171​
172 it("rechecks task permission when a retained menu callback runs", async () => {
173 state.scopes.add(AuthOrchestrationOperateScope);
174 const actions = useSelectedThreadGitActions();
175 state.scopes.delete(AuthOrchestrationOperateScope);
176 expect(
177 await actions.onCreateSelectedThreadWorktree({
178 baseBranch: "main",
179 newBranch: "feature/task",
180 }),
181 ).toBeNull();
182 expect(state.worktrees).toEqual([]);
183 expect(state.thread.worktreePath).toBeNull();
184 });
185​
186 it("keeps ordinary commits and pushes available without task permission", async () => {
187 const actions = useSelectedThreadGitActions();
188 await actions.onRunSelectedThreadGitAction({ action: "commit" });
189 await actions.onRunSelectedThreadGitAction({ action: "push" });
190 expect(state.commits).toBe(1);
191 expect(state.pushes).toBe(1);
192 expect(state.thread.branch).toBe("main");
193 expect(state.metadataRequests).toEqual([]);
194 });
195​
196 it.each(["create", "checkout", "worktree", "commit"] as const)(
197 "does not send thread metadata after task permission is revoked during %s",
198 async (operation) => {
199 state.scopes.add(AuthOrchestrationOperateScope);
200 state.afterGitAction = () => state.scopes.delete(AuthOrchestrationOperateScope);
201 const actions = useSelectedThreadGitActions();
202 if (operation === "create")
203 expect(await actions.onCreateSelectedThreadBranch("feature")).toBeNull();
204 if (operation === "checkout")
205 expect(await actions.onCheckoutSelectedThreadBranch("feature")).toBeNull();
206 if (operation === "worktree")
207 expect(
208 await actions.onCreateSelectedThreadWorktree({
209 baseBranch: "main",
210 newBranch: "feature",
211 }),
212 ).toBeNull();
213 if (operation === "commit")
214 expect(
215 await actions.onRunSelectedThreadGitAction({ action: "commit", featureBranch: true }),
216 ).toBeNull();
217 if (operation === "worktree") expect(state.worktrees).toEqual(["/repo-worktree"]);
218 else expect(state.branch).toBe("feature");
219 expect(state.thread.branch).toBe("main");
220 expect(state.thread.worktreePath).toBeNull();
221 expect(state.metadataRequests).toEqual([]);
222 expect(state.results.map((result) => result.type)).toEqual(["error"]);
223 },
224 );
225​
226 it("refreshes the worktree status when the metadata update is denied after checkout", async () => {
227 state.scopes.add(AuthOrchestrationOperateScope);
228 // Git already switched the branch, so the sheet must show it even though the
229 // thread record could not be updated.
230 state.afterGitAction = () => state.scopes.delete(AuthOrchestrationOperateScope);
231 expect(
232 await useSelectedThreadGitActions().onCheckoutSelectedThreadBranch("feature"),
233 ).toBeNull();
234 expect(state.branch).toBe("feature");
235 expect(state.statusRefreshes).toBe(1);
236 });
237​
238 it("uses a newly granted task permission for a retained branch callback", async () => {
239 state.primaryScopes.clear();
240 const actions = useSelectedThreadGitActions();
241 state.scopes.add(AuthOrchestrationOperateScope);
242 await actions.onCreateSelectedThreadBranch("feature");
243 expect(state.thread.branch).toBe("feature");
244 expect(state.metadataRequests).toEqual([{ environmentId: "environment", branch: "feature" }]);
245 });
246​
247 it.each(["create", "checkout", "worktree"] as const)(
248 "returns the accepted %s result when only source-control permission is revoked after Git",
249 async (operation) => {
250 state.scopes.add(AuthOrchestrationOperateScope);
251 state.afterGitAction = () => state.scopes.delete(AuthSourceControlWriteScope);
252 const actions = useSelectedThreadGitActions();
253 const result =
254 operation === "create"
255 ? await actions.onCreateSelectedThreadBranch("feature/task")
256 : operation === "checkout"
257 ? await actions.onCheckoutSelectedThreadBranch("feature/task")
258 : await actions.onCreateSelectedThreadWorktree({
259 baseBranch: "main",
260 newBranch: "feature/task",
261 });
262 expect(result).toEqual(
263 operation === "worktree"
264 ? { worktree: { path: "/repo-worktree", refName: "feature/task" } }
265 : { refName: "feature/task" },
266 );
267 expect(state.thread.branch).toBe("feature/task");
268 expect(state.metadataRequests).toHaveLength(1);
269 expect(state.results).toEqual([]);
270 },
271 );
272​
273 it("returns a successful checkout when the requested branch is already selected", async () => {
274 state.scopes.add(AuthOrchestrationOperateScope);
275​
276 expect(await useSelectedThreadGitActions().onCheckoutSelectedThreadBranch("main")).toEqual({
277 refName: "main",
278 });
279 expect(state.branch).toBe("main");
280 expect(state.thread.branch).toBe("main");
281 expect(state.results).toEqual([]);
282 });
283});