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

use-selected-thread-git-actions.ts

445 lines15.6 KB

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