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

main
ts 189 lines 6.44 KB
Raw
1 import {
2 AuthOrchestrationOperateScope,
3 AuthSourceControlWriteScope,
4 EnvironmentId,
5 ThreadId,
6 } from "@t3tools/contracts";
7 import * as Cause from "effect/Cause";
8 import { AsyncResult } from "effect/reactivity";
9 import { isValidElement, type ReactNode } from "react";
10 import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
11
12 const state = vi.hoisted(() => ({
13 canOperate: false,
14 canWriteSourceControl: true,
15 hookValues: [] as unknown[],
16 hookIndex: 0,
17 tracks: 0,
18 resets: 0,
19 manager: { operation: null as string | null, error: null, isRunning: false },
20 interrupted: false,
21 pendingResponse: undefined as Promise<void> | undefined,
22 openChanges: [] as boolean[],
23 checkouts: [] as string[],
24 setupScripts: 0,
25 prepared: [] as { branch: string; worktreePath: string | null }[],
26 }));
27
28 vi.mock("react", async (importOriginal) => ({
29 ...(await importOriginal<typeof import("react")>()),
30 useCallback: (callback: unknown) => callback,
31 useMemo: (factory: () => unknown) => factory(),
32 useState: (initial: unknown) => {
33 const index = state.hookIndex++;
34 if (index === state.hookValues.length) state.hookValues.push(initial);
35 return [state.hookValues[index], (value: unknown) => (state.hookValues[index] = value)];
36 },
37 useRef: (current: unknown) => ({ current }),
38 useEffect: () => {},
39 }));
40 vi.mock("gt-react", async (importOriginal) => ({
41 ...(await importOriginal<typeof import("gt-react")>()),
42 useGT:
43 () =>
44 (text: string, values: Record<string, unknown> = {}) =>
45 text.replace(/\{(\w+)\}/g, (_, key: string) => String(values[key])),
46 useMessages: () => (text: string) => text,
47 T: ({ children }: { children: ReactNode }) => children,
48 Var: ({ children }: { children: ReactNode }) => children,
49 }));
50 vi.mock("@tanstack/react-pacer", () => ({
51 useDebouncedValue: (value: unknown) => [value, { state: { isPending: false } }],
52 }));
53 vi.mock("~/state/session", () => ({
54 useEnvironmentScope: (_environmentId: unknown, scope: string) =>
55 scope === AuthOrchestrationOperateScope
56 ? state.canOperate
57 : scope === AuthSourceControlWriteScope && state.canWriteSourceControl,
58 readEnvironmentScope: (_environmentId: unknown, scope: string) =>
59 scope === AuthOrchestrationOperateScope
60 ? state.canOperate
61 : scope === AuthSourceControlWriteScope && state.canWriteSourceControl,
62 }));
63 vi.mock("~/state/sourceControlActions", async () => {
64 const { usePreparePullRequestThreadAction } = await vi.importActual<
65 typeof import("~/state/sourceControlActions")
66 >("~/state/sourceControlActions");
67 return {
68 readCachedPullRequestResolution: () => null,
69 usePullRequestResolutionState: () => ({
70 data: { pullRequest: { number: 123, title: "Pull request", state: "open" } },
71 }),
72 usePreparePullRequestThreadAction,
73 };
74 });
75 vi.mock("@effect/atom-react", () => ({ useAtomValue: () => state.manager }));
76 vi.mock("~/rpc/atomRegistry", () => ({ appAtomRegistry: {} }));
77 vi.mock("~/state/use-atom-command", () => ({
78 useAtomCommand: (command: unknown) => command,
79 }));
80 vi.mock("~/state/sourceControl", () => ({ sourceControlEnvironment: {} }));
81 vi.mock("~/state/git", () => ({
82 gitEnvironment: {
83 preparePullRequestThread: async ({
84 input: { mode, threadId },
85 }: {
86 input: { mode: string; threadId?: string };
87 }) => {
88 state.checkouts.push(mode);
89 if (mode === "worktree" && threadId) state.setupScripts += 1;
90 await state.pendingResponse;
91 if (state.interrupted) return AsyncResult.failure(Cause.interrupt());
92 return AsyncResult.success({
93 branch: "feature/pr",
94 worktreePath: mode === "worktree" ? "/worktree" : null,
95 isOnPullRequestHead: true,
96 });
97 },
98 },
99 }));
100 vi.mock("~/lib/utils", () => ({ cn: () => "" }));
101 vi.mock("~/state/query", () => ({ useEnvironmentQuery: () => ({ data: null }) }));
102 vi.mock("~/state/vcs", () => ({
103 vcsEnvironment: { status: () => null },
104 vcsActionManager: {
105 stateAtom: () => "vcs-state",
106 track: (_registry: unknown, _target: unknown, _input: unknown, execute: () => unknown) => {
107 state.tracks += 1;
108 return execute();
109 },
110 resetError: () => state.resets++,
111 },
112 }));
113 vi.mock("./ui/button", () => ({ Button: "Button" }));
114 vi.mock("./ui/input", () => ({ Input: "Input" }));
115 vi.mock("./ui/spinner", () => ({ Spinner: "Spinner" }));
116 vi.mock("./ui/toast", () => ({ toastManager: { add: vi.fn() } }));
117 vi.mock("./ui/dialog", () => ({
118 Dialog: "Dialog",
119 DialogDescription: "DialogDescription",
120 DialogFooter: "DialogFooter",
121 DialogHeader: "DialogHeader",
122 DialogPanel: "DialogPanel",
123 DialogPopup: "DialogPopup",
124 DialogTitle: "DialogTitle",
125 }));
126
127 import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
128
129 function findAction(node: ReactNode, label: string): (() => unknown) | null {
130 if (Array.isArray(node)) {
131 for (const child of node) {
132 const action = findAction(child, label);
133 if (action) return action;
134 }
135 return null;
136 }
137 if (!isValidElement<{ children?: ReactNode; onClick?: () => unknown }>(node)) return null;
138 if (node.props.children === label) return node.props.onClick ?? null;
139 return findAction(node.props.children, label);
140 }
141
142 function renderDialog() {
143 state.hookIndex = 0;
144 return PullRequestThreadDialog({
145 open: true,
146 environmentId: EnvironmentId.make("environment"),
147 threadId: ThreadId.make("thread"),
148 cwd: "/repo",
149 initialReference: "123",
150 onOpenChange: (open) => state.openChanges.push(open),
151 onPrepared: (input) => {
152 state.prepared.push(input);
153 },
154 });
155 }
156
157 function prepareAction(label: "Local" | "Worktree") {
158 const action = findAction(renderDialog(), label);
159 if (!action) throw new Error(`${label} action missing`);
160 return action;
161 }
162
163 describe("pull request worktree permissions", () => {
164 beforeEach(() => {
165 state.canOperate = false;
166 state.canWriteSourceControl = true;
167 state.hookValues = [];
168 state.hookIndex = 0;
169 state.tracks = 0;
170 state.resets = 0;
171 state.manager = { operation: null, error: null, isRunning: false };
172 state.interrupted = false;
173 state.pendingResponse = undefined;
174 state.openChanges = [];
175 state.checkouts = [];
176 state.setupScripts = 0;
177 state.prepared = [];
178 });
179
180 it("rechecks task permission before invoking a retained worktree action", async () => {
181 state.canOperate = true;
182 const prepare = prepareAction("Worktree");
183 state.canOperate = false;
184 await prepare();
185
186 expect(state.checkouts).toEqual([]);
187 expect(state.setupScripts).toBe(0);
188 });
189 });