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

GitActionsControl.browser.test.tsx

229 lines8.0 KB

1import {
2 AuthOrchestrationOperateScope,
3 AuthSourceControlWriteScope,
4 EnvironmentId,
5 ThreadId,
6} from "@t3tools/contracts";
7import * as Cause from "effect/Cause";
8import { AsyncResult } from "effect/reactivity";
9import { memo } from "react";
10import { describe, expect, it, vi } from "vite-plus/test";
11import { page, userEvent } from "vite-plus/test/browser";
12​
13import "~/index.css";
14import { act, render } from "../../test/render";
15​
16type Branched = { readonly branch: string };
17type GitActionInput = { featureBranch?: boolean; threadId?: string; action: string };
18type Toast = { actionProps?: { onClick: () => void } };
19​
20const state = vi.hoisted(() => ({
21 scopes: new Set<string>(),
22 primaryScopes: new Set<string>(),
23 shell: null as Branched | null,
24 detail: null as Branched | null,
25 draft: null as (Branched & { worktreePath: null; envMode: "local" }) | null,
26 branch: "main",
27 isDefaultRef: false,
28 actions: [] as { scope: { cwd: string | null }; input: GitActionInput }[],
29 metadataRequests: [] as { environmentId: string; branch: string }[],
30 toasts: [] as Toast[],
31 afterGitAction: undefined as (() => void) | undefined,
32 workingTreeRoot: undefined as string | undefined,
33 files: [{ path: "file.ts", insertions: 1, deletions: 0 }],
34 editorOpens: [] as { environmentId: string; input: { cwd: string; editor: string } }[],
35}));
36​
37vi.mock(import("~/state/session"), async (original) => {
38 const hasScope = (environmentId: unknown, scope: string) =>
39 (environmentId === "environment" ? state.scopes : state.primaryScopes).has(scope);
40 return {
41 ...(await original()),
42 useEnvironmentScope: hasScope as never,
43 readEnvironmentScope: hasScope as never,
44 };
45});
46vi.mock(import("~/state/entities"), async (original) => ({
47 ...(await original()),
48 useQuietThreadShell: ((ref: { threadId: string } | null) =>
49 ref === null || state.shell === null ? null : { ...state.shell, id: ref.threadId }) as never,
50 useThreadProjection: ((ref: unknown) =>
51 ref === null || state.detail === null
52 ? null
53 : { projection: { thread: state.detail } }) as never,
54}));
55vi.mock(import("~/state/query"), async (original) => ({
56 ...(await original()),
57 // Serves both the VCS status and the source-control discovery queries.
58 useEnvironmentQuery: (() => ({
59 data: {
60 sourceControlProviders: [],
61 isRepo: true,
62 refName: state.branch,
63 isDefaultRef: state.isDefaultRef,
64 hasPrimaryRemote: true,
65 hasWorkingTreeChanges: true,
66 workingTree: {
67 ...(state.workingTreeRoot === undefined ? {} : { rootPath: state.workingTreeRoot }),
68 files: state.files,
69 insertions: 1,
70 deletions: 0,
71 },
72 hasUpstream: true,
73 aheadCount: 0,
74 behindCount: 0,
75 pr: null,
76 },
77 error: null,
78 })) as never,
79}));
80vi.mock(import("~/state/use-atom-command"), async (original) => {
81 const { shellEnvironment } = await import("~/state/shell");
82 return {
83 ...(await original()),
84 // Only the thread's branch metadata update and editor opens are observed here.
85 useAtomCommand: ((command: unknown, options: unknown) =>
86 options === "thread branch metadata update"
87 ? async ({
88 environmentId,
89 input,
90 }: {
91 environmentId: string;
92 input: { branch: string };
93 }) => {
94 state.metadataRequests.push({ environmentId, branch: input.branch });
95 if (!state.scopes.has(AuthOrchestrationOperateScope))
96 return AsyncResult.failure(Cause.fail(new Error("Task denied")));
97 if (state.shell) state.shell = { branch: input.branch };
98 if (state.detail) state.detail = { branch: input.branch };
99 return AsyncResult.success(undefined);
100 }
101 : command === shellEnvironment.openInEditor
102 ? async (request: (typeof state.editorOpens)[number]) => {
103 state.editorOpens.push(request);
104 return AsyncResult.success(undefined);
105 }
106 : async () => AsyncResult.success(undefined)) as never,
107 };
108});
109// The preferred-editor flow needs one editor the environment reports as installed.
110vi.mock(import("~/state/server"), async (original) => {
111 const actual = await original();
112 const { Atom } = await import("effect/reactivity");
113 const config = Atom.make(() => ({ availableEditors: ["cursor"] }));
114 return {
115 ...actual,
116 serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => config) as never },
117 };
118});
119vi.mock(import("~/lib/sourceControlActions"), async (original) => ({
120 ...(await original()),
121 useSourceControlActionRunning: () => false,
122 useGitStackedAction: ((scope: { cwd: string | null }) => ({
123 run: async (input: GitActionInput) => {
124 state.actions.push({ scope, input });
125 if (input.featureBranch) state.branch = "feature";
126 state.afterGitAction?.();
127 return {
128 _tag: "Success",
129 value: {
130 branch: input.featureBranch
131 ? { status: "created", name: "feature" }
132 : { status: "skipped_not_requested" },
133 toast: {
134 title: "Committed",
135 description: "Committed",
136 cta: {
137 kind: "run_action",
138 label: "Push & create PR",
139 action: { kind: "commit_push_pr" },
140 },
141 },
142 },
143 };
144 },
145 })) as never,
146}));
147vi.mock(import("@tanstack/react-router"), async (original) => ({
148 ...(await original()),
149 useNavigate: (() => async () => {}) as never,
150}));
151vi.mock(import("~/components/ui/toast"), async (original) => {
152 const actual = await original();
153 return {
154 ...actual,
155 toastManager: {
156 ...actual.toastManager,
157 add: ((toast: Toast) => {
158 state.toasts.push(toast);
159 return "toast";
160 }) as never,
161 },
162 };
163});
164​
165import { useComposerDraftStore } from "~/composerDraftStore";
166import GitActionsControl from "./GitActionsControl";
167​
168// ThreadDetailsPanel keeps this component mounted behind React.memo when threads change.
169const MemoGitActionsControl = memo(GitActionsControl);
170​
171function control(thread = "thread", cwd = "/repo") {
172 return (
173 <MemoGitActionsControl
174 gitCwd={cwd}
175 activeThreadRef={{
176 environmentId: EnvironmentId.make("environment"),
177 threadId: ThreadId.make(thread),
178 }}
179 />
180 );
182​
183const button = (name: string | RegExp) =>
184 page.getByRole("button", { name, exact: typeof name === "string" });
185​
186// The mocked modules read `state`, so every test starts by resetting all of it.
187function setup() {
188 state.scopes = new Set([AuthSourceControlWriteScope]);
189 state.primaryScopes = new Set([AuthSourceControlWriteScope, AuthOrchestrationOperateScope]);
190 state.shell = { branch: "main" };
191 state.detail = null;
192 state.draft = null;
193 state.branch = "main";
194 state.isDefaultRef = false;
195 state.actions = [];
196 state.metadataRequests = [];
197 state.toasts = [];
198 state.afterGitAction = undefined;
199 state.workingTreeRoot = undefined;
200 state.files = [{ path: "file.ts", insertions: 1, deletions: 0 }];
201 state.editorOpens = [];
202 useComposerDraftStore.setState({
203 getDraftSession: () => state.draft as never,
204 getDraftThreadByRef: () => state.draft as never,
205 setDraftThreadContext: (_target, input) => {
206 if (state.draft && input.branch) state.draft = { ...state.draft, branch: input.branch };
207 },
208 });
210​
211describe("Git action targets across thread navigation", () => {
212 const quickAction = () => button(/^Commit, push & /);
213​
214 it("runs a retained PR toast in the thread that produced it", async () => {
215 setup();
216 await using screen = await render(control("first", "/first"));
217 await userEvent.click(quickAction());
218 await vi.waitFor(() => expect(state.toasts.some((toast) => toast.actionProps)).toBe(true));
219 const toast = state.toasts.find((toast) => toast.actionProps)!;
220​
221 await screen.rerender(control("second", "/second"));
222 await act(async () => toast.actionProps!.onClick());
223​
224 expect(state.actions.at(-1)).toMatchObject({
225 scope: { cwd: "/first" },
226 input: { threadId: "first", action: "commit_push_pr" },
227 });
228 });
229});