@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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