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

use-selected-thread-git-actions.ts

441 lines15.4 KB

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