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

use-selected-thread-git-actions.ts

404 lines13.8 KB

1import { useAtomMount } from "@effect/atom-react";
2​
3import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
4import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
5import {
6 createVcsStatusRevalidationAtomFamily,
7 type GitActionRequestInput,
8 type VcsActionOperation,
9 type VcsRef,
10} from "@t3tools/client-runtime/state/vcs";
11import {
12 AuthOrchestrationOperateScope,
13 AuthSourceControlWriteScope,
14 EnvironmentAuthorizationError,
15 type GitRunStackedActionResult,
16} from "@t3tools/contracts";
17import {
18 dedupeRemoteBranchesWithLocalMatches,
19 sanitizeFeatureBranchName,
20} from "@t3tools/shared/git";
21import * as Cause from "effect/Cause";
22import { AsyncResult } from "effect/reactivity";
23​
24import { useBranches } from "../state/queries";
25import { threadEnvironment } from "../state/threads";
26import { vcsActionManager, vcsEnvironment } from "../state/vcs";
27import { uuidv4 } from "../lib/uuid";
28import { appAtomRegistry } from "./atom-registry";
29import { readEnvironmentScope, useEnvironmentScope } from "./session";
30import {
31 environmentConnectedAtom,
32 setPendingConnectionError,
33} from "./use-remote-environment-registry";
34import { useAtomCommand } from "./use-atom-command";
35import { showGitActionResult } from "./use-vcs-action-state";
36import { useThreadSelection } from "./use-thread-selection";
37import { useSelectedThreadWorktree } from "./use-selected-thread-worktree";
38​
39function refreshFailureMessage(cause: Cause.Cause<unknown>): string {
40 const error = Cause.squash(cause);
41 return error instanceof Error ? error.message : "Failed to refresh git status.";
43​
44// Selecting a thread or reconnecting its environment refreshes the checkout's
45// status once, shared by every sheet that shows it.
46const selectedThreadStatusRevalidation = createVcsStatusRevalidationAtomFamily({
47 refreshStatus: vcsEnvironment.refreshStatus,
48 connected: environmentConnectedAtom,
49 onRefreshed: (result) =>
50 setPendingConnectionError(
51 AsyncResult.isFailure(result) ? refreshFailureMessage(result.cause) : null,
52 ),
53});
54​
55export function useSelectedThreadGitActions() {
56 const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
57 reportFailure: false,
58 });
59 const refreshStatus = useAtomCommand(vcsEnvironment.refreshStatus, { reportFailure: false });
60 const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
61 const createRef = useAtomCommand(vcsEnvironment.createRef, { reportFailure: false });
62 const createWorktree = useAtomCommand(vcsEnvironment.createWorktree, { reportFailure: false });
63 const pull = useAtomCommand(vcsEnvironment.pull, { reportFailure: false });
64 const { selectedThread, selectedThreadProject } = useThreadSelection();
65 const canWriteSourceControl = useEnvironmentScope(
66 selectedThread?.environmentId ?? null,
67 AuthSourceControlWriteScope,
68 );
69 const canOperateThread = useEnvironmentScope(
70 selectedThread?.environmentId ?? null,
71 AuthOrchestrationOperateScope,
72 );
73 const canChangeThreadBranch = canWriteSourceControl && canOperateThread;
74 const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree();
75 const runStackedAction = useAtomCommand(
76 vcsActionManager.runStackedAction({
77 environmentId: selectedThread?.environmentId ?? null,
78 cwd: selectedThreadCwd,
79 }),
80 { reportFailure: false },
81 );
82​
83 const selectedThreadGitRootCwd = selectedThreadProject?.workspaceRoot ?? null;
84 const branchTarget = {
85 environmentId: selectedThread?.environmentId ?? null,
86 cwd: selectedThreadGitRootCwd,
87 query: null,
88 };
89 const branchState = useBranches(branchTarget);
90 const updateThreadGitContext = async (
91 thread: NonNullable<typeof selectedThread>,
92 nextState: {
93 readonly branch?: string | null;
94 readonly worktreePath?: string | null;
95 },
96 ) => {
97 if (!readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope)) {
98 return AsyncResult.failure<never, EnvironmentAuthorizationError>(
99 Cause.fail(
100 new EnvironmentAuthorizationError({
101 requiredScope: AuthOrchestrationOperateScope,
102 message: "This connection cannot update the thread's branch.",
103 }),
104 ),
105 );
106 }
107 return updateThreadMetadata({
108 environmentId: thread.environmentId,
109 input: {
110 threadId: thread.id,
111 ...(nextState.branch !== undefined ? { branch: nextState.branch } : {}),
112 ...(nextState.worktreePath !== undefined ? { worktreePath: nextState.worktreePath } : {}),
113 },
114 });
115 };
116​
117 const refreshSelectedThreadGitStatus = async (options?: {
118 readonly quiet?: boolean;
119 readonly cwd?: string | null;
120 }) => {
121 if (!selectedThread || !selectedThreadProject) {
122 return null;
123 }
124​
125 const cwd = options?.cwd ?? selectedThreadCwd;
126 if (!cwd) {
127 return null;
128 }
129​
130 const target = { environmentId: selectedThread.environmentId, cwd };
131 const execute = () =>
132 refreshStatus({
133 environmentId: selectedThread.environmentId,
134 input: { cwd },
135 });
136 const result = options?.quiet
137 ? await execute()
138 : await vcsActionManager.track(
139 appAtomRegistry,
140 target,
141 {
142 operation: "refresh_status",
143 label: "Refreshing source control status",
144 },
145 execute,
146 );
147 if (AsyncResult.isFailure(result)) {
148 setPendingConnectionError(refreshFailureMessage(result.cause));
149 return null;
150 }
151 setPendingConnectionError(null);
152 return result.value;
153 };
154​
155 useAtomMount(
156 selectedThreadStatusRevalidation(
157 selectedThread && selectedThreadProject && selectedThreadCwd
158 ? { environmentId: selectedThread.environmentId, cwd: selectedThreadCwd }
159 : null,
160 ),
161 );
162​
163 const runSelectedThreadGitMutation = async <T, E>(
164 operation: VcsActionOperation,
165 label: string,
166 execute: (input: {
167 readonly thread: EnvironmentThreadShell;
168 readonly project: EnvironmentProject;
169 readonly cwd: string;
170 }) => Promise<AtomCommandResult<T, E>>,
171 options?: { readonly managedExternally?: boolean; readonly changesThreadBranch?: boolean },
172 ): Promise<T | null> => {
173 if (
174 !selectedThread ||
175 !selectedThreadProject ||
176 !selectedThreadCwd ||
177 !readEnvironmentScope(selectedThread.environmentId, AuthSourceControlWriteScope) ||
178 (options?.changesThreadBranch === true &&
179 !readEnvironmentScope(selectedThread.environmentId, AuthOrchestrationOperateScope))
180 ) {
181 return null;
182 }
183​
184 const target = {
185 environmentId: selectedThread.environmentId,
186 cwd: selectedThreadCwd,
187 };
188 setPendingConnectionError(null);
189 const run = () =>
190 execute({
191 thread: selectedThread,
192 project: selectedThreadProject,
193 cwd: selectedThreadCwd,
194 });
195 const result =
196 options?.managedExternally === true
197 ? await run()
198 : await vcsActionManager.track(appAtomRegistry, target, { operation, label }, run);
199 if (AsyncResult.isFailure(result)) {
200 const error = Cause.squash(result.cause);
201 const message = error instanceof Error ? error.message : "Git action failed.";
202 setPendingConnectionError(message);
203 showGitActionResult({ type: "error", title: "Git action failed", description: message });
204 return null;
205 }
206 return result.value;
207 };
208​
209 const refreshSelectedThreadBranches = async (): Promise<ReadonlyArray<VcsRef>> => {
210 branchState.refresh();
211 return dedupeRemoteBranchesWithLocalMatches(branchState.data?.refs ?? []).filter(
212 (branch) => !branch.isRemote,
213 );
214 };
215​
216 const syncSelectedThreadBranchState = async (input: {
217 readonly thread: EnvironmentThreadShell;
218 readonly cwd: string;
219 readonly nextThreadState?: {
220 readonly branch?: string | null;
221 readonly worktreePath?: string | null;
222 };
223 }): Promise<AtomCommandResult<void, unknown>> => {
224 // Git already changed; refresh even if metadata updates fail so the sheet shows the current branch.
225 const updateResult = input.nextThreadState
226 ? await updateThreadGitContext(input.thread, input.nextThreadState)
227 : AsyncResult.success(undefined);
228 branchState.refresh();
229 await refreshSelectedThreadGitStatus({ quiet: true, cwd: input.cwd });
230 return AsyncResult.isFailure(updateResult)
231 ? AsyncResult.failure(updateResult.cause)
232 : AsyncResult.success(undefined);
233 };
234​
235 const onCheckoutSelectedThreadBranch = async (branch: string) => {
236 return runSelectedThreadGitMutation(
237 "switch_ref",
238 "Switching branch",
239 async ({ thread, cwd }) => {
240 const result = await switchRef({
241 environmentId: thread.environmentId,
242 input: { cwd, refName: branch },
243 });
244 if (AsyncResult.isFailure(result)) {
245 return result;
246 }
247 const syncResult = await syncSelectedThreadBranchState({
248 thread,
249 cwd,
250 nextThreadState: {
251 branch: result.value.refName ?? thread.branch,
252 worktreePath: selectedThreadWorktreePath,
253 },
254 });
255 return AsyncResult.isFailure(syncResult) ? AsyncResult.failure(syncResult.cause) : result;
256 },
257 { changesThreadBranch: true },
258 );
259 };
260​
261 const onCreateSelectedThreadBranch = async (branch: string) => {
262 return runSelectedThreadGitMutation(
263 "create_ref",
264 "Creating branch",
265 async ({ thread, cwd }) => {
266 const result = await createRef({
267 environmentId: thread.environmentId,
268 input: { cwd, refName: branch, switchRef: true },
269 });
270 if (AsyncResult.isFailure(result)) {
271 return result;
272 }
273 const syncResult = await syncSelectedThreadBranchState({
274 thread,
275 cwd,
276 nextThreadState: {
277 branch: result.value.refName ?? thread.branch,
278 worktreePath: selectedThreadWorktreePath,
279 },
280 });
281 return AsyncResult.isFailure(syncResult) ? AsyncResult.failure(syncResult.cause) : result;
282 },
283 { changesThreadBranch: true },
284 );
285 };
286​
287 const onCreateSelectedThreadWorktree = async (nextWorktree: {
288 readonly baseBranch: string;
289 readonly newBranch: string;
290 }) => {
291 return runSelectedThreadGitMutation(
292 "create_worktree",
293 "Creating worktree",
294 async ({ thread, project }) => {
295 const result = await createWorktree({
296 environmentId: thread.environmentId,
297 input: {
298 cwd: project.workspaceRoot,
299 refName: nextWorktree.baseBranch,
300 newRefName: sanitizeFeatureBranchName(nextWorktree.newBranch),
301 path: null,
302 },
303 });
304 if (AsyncResult.isFailure(result)) {
305 return result;
306 }
307 const syncResult = await syncSelectedThreadBranchState({
308 thread,
309 cwd: result.value.worktree.path,
310 nextThreadState: {
311 branch: result.value.worktree.refName,
312 worktreePath: result.value.worktree.path,
313 },
314 });
315 return AsyncResult.isFailure(syncResult) ? AsyncResult.failure(syncResult.cause) : result;
316 },
317 { changesThreadBranch: true },
318 );
319 };
320​
321 const onPullSelectedThreadBranch = async () => {
322 await runSelectedThreadGitMutation(
323 "pull",
324 "Pulling latest changes",
325 async ({ thread, cwd }) => {
326 const result = await pull({
327 environmentId: thread.environmentId,
328 input: { cwd },
329 });
330 if (AsyncResult.isFailure(result)) {
331 return result;
332 }
333 await refreshSelectedThreadGitStatus({ quiet: true, cwd });
334 showGitActionResult({
335 type: "success",
336 title:
337 result.value.status === "skipped_up_to_date"
338 ? "Already up to date"
339 : `Pulled latest on ${result.value.refName}`,
340 });
341 return result;
342 },
343 );
344 };
345​
346 const onRunSelectedThreadGitAction = async (
347 input: GitActionRequestInput,
348 ): Promise<GitRunStackedActionResult | null> => {
349 const actionId = uuidv4();
350 return await runSelectedThreadGitMutation(
351 "run_change_request",
352 "Running source control action",
353 async ({ thread, cwd }) => {
354 const result = await runStackedAction({
355 actionId,
356 action: input.action,
357 ...(input.commitMessage ? { commitMessage: input.commitMessage } : {}),
358 ...(input.featureBranch ? { featureBranch: input.featureBranch } : {}),
359 ...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}),
360 threadId: thread.id,
361 });
362 if (AsyncResult.isFailure(result)) {
363 return result;
364 }
365​
366 if (result.value.branch.status === "created" && result.value.branch.name) {
367 const syncResult = await syncSelectedThreadBranchState({
368 thread,
369 cwd,
370 nextThreadState: {
371 branch: result.value.branch.name,
372 worktreePath: selectedThreadWorktreePath,
373 },
374 });
375 if (AsyncResult.isFailure(syncResult)) {
376 return AsyncResult.failure(syncResult.cause);
377 }
378 } else {
379 await refreshSelectedThreadGitStatus({ quiet: true, cwd });
380 }
381 showGitActionResult({
382 type: "success",
383 title: result.value.toast.title,
384 description: result.value.toast.description,
385 prUrl: result.value.toast.cta.kind === "open_pr" ? result.value.toast.cta.url : undefined,
386 });
387 return result;
388 },
389 { managedExternally: true, changesThreadBranch: input.featureBranch === true },
390 );
391 };
392​
393 return {
394 canWriteSourceControl,
395 canChangeThreadBranch,
396 refreshSelectedThreadGitStatus,
397 refreshSelectedThreadBranches,
398 onCheckoutSelectedThreadBranch,
399 onCreateSelectedThreadBranch,
400 onCreateSelectedThreadWorktree,
401 onPullSelectedThreadBranch,
402 onRunSelectedThreadGitAction,
403 };