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