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

use-selected-thread-git-actions.ts

442 lines15.5 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 // Key refreshes on primitives; streaming frequently replaces the selected thread object.
145 const selectedEnvironmentId = selectedThread?.environmentId ?? null;
146 const selectedThreadId = selectedThread?.id ?? null;
147 const hasSelectedThreadProject = selectedThreadProject !== null;
148 const isEnvironmentConnected = selectedEnvironmentRuntime?.connectionState === "connected";
149 const refreshOnSelection = useEffectEvent(() => {
150 void refreshSelectedThreadGitStatus({ quiet: true });
151 });
152 useEffect(() => {
153 if (
154 selectedEnvironmentId === null ||
155 selectedThreadId === null ||
156 !hasSelectedThreadProject ||
157 selectedThreadCwd === null ||
158 !isEnvironmentConnected
159 ) {
160 return;
161 }
162 refreshOnSelection();
163 }, [
164 selectedEnvironmentId,
165 selectedThreadId,
166 hasSelectedThreadProject,
167 selectedThreadCwd,
168 isEnvironmentConnected,
169 ]);
170​
171 const runSelectedThreadGitMutation = useCallback(
172 async <T, E>(
173 operation: VcsActionOperation,
174 label: string,
175 execute: (input: {
176 readonly thread: EnvironmentThreadShell;
177 readonly project: EnvironmentProject;
178 readonly cwd: string;
179 }) => Promise<AtomCommandResult<T, E>>,
180 options?: { readonly managedExternally?: boolean; readonly changesThreadBranch?: boolean },
181 ): Promise<T | null> => {
182 if (
183 !selectedThread ||
184 !selectedThreadProject ||
185 !selectedThreadCwd ||
186 !readEnvironmentScope(selectedThread.environmentId, AuthSourceControlWriteScope) ||
187 (options?.changesThreadBranch === true &&
188 !readEnvironmentScope(selectedThread.environmentId, AuthOrchestrationOperateScope))
189 ) {
190 return null;
191 }
192​
193 const target = {
194 environmentId: selectedThread.environmentId,
195 cwd: selectedThreadCwd,
196 };
197 setPendingConnectionError(null);
198 const run = () =>
199 execute({
200 thread: selectedThread,
201 project: selectedThreadProject,
202 cwd: selectedThreadCwd,
203 });
204 const result =
205 options?.managedExternally === true
206 ? await run()
207 : await vcsActionManager.track(appAtomRegistry, target, { operation, label }, run);
208 if (AsyncResult.isFailure(result)) {
209 const error = Cause.squash(result.cause);
210 const message = error instanceof Error ? error.message : "Git action failed.";
211 setPendingConnectionError(message);
212 showGitActionResult({ type: "error", title: "Git action failed", description: message });
213 return null;
214 }
215 return result.value;
216 },
217 [selectedThread, selectedThreadCwd, selectedThreadProject],
218 );
219​
220 const refreshSelectedThreadBranches = useCallback(async (): Promise<ReadonlyArray<VcsRef>> => {
221 branchState.refresh();
222 return dedupeRemoteBranchesWithLocalMatches(branchState.data?.refs ?? []).filter(
223 (branch) => !branch.isRemote,
224 );
225 }, [branchState]);
226​
227 const syncSelectedThreadBranchState = useCallback(
228 async (input: {
229 readonly thread: EnvironmentThreadShell;
230 readonly cwd: string;
231 readonly nextThreadState?: {
232 readonly branch?: string | null;
233 readonly worktreePath?: string | null;
234 };
235 }): Promise<AtomCommandResult<void, unknown>> => {
236 // Git already changed; refresh even if metadata updates fail so the sheet shows the current branch.
237 const updateResult = input.nextThreadState
238 ? await updateThreadGitContext(input.thread, input.nextThreadState)
239 : AsyncResult.success(undefined);
240 branchState.refresh();
241 await refreshSelectedThreadGitStatus({ quiet: true, cwd: input.cwd });
242 return AsyncResult.isFailure(updateResult)
243 ? AsyncResult.failure(updateResult.cause)
244 : AsyncResult.success(undefined);
245 },
246 [branchState, refreshSelectedThreadGitStatus, updateThreadGitContext],
247 );
248​
249 const onCheckoutSelectedThreadBranch = useCallback(
250 async (branch: string) => {
251 return runSelectedThreadGitMutation(
252 "switch_ref",
253 "Switching branch",
254 async ({ thread, cwd }) => {
255 const result = await switchRef({
256 environmentId: thread.environmentId,
257 input: { cwd, refName: branch },
258 });
259 if (AsyncResult.isFailure(result)) {
260 return result;
261 }
262 const syncResult = await syncSelectedThreadBranchState({
263 thread,
264 cwd,
265 nextThreadState: {
266 branch: result.value.refName ?? thread.branch,
267 worktreePath: selectedThreadWorktreePath,
268 },
269 });
270 return AsyncResult.isFailure(syncResult) ? AsyncResult.failure(syncResult.cause) : result;
271 },
272 { changesThreadBranch: true },
273 );
274 },
275 [
276 runSelectedThreadGitMutation,
277 selectedThreadWorktreePath,
278 syncSelectedThreadBranchState,
279 switchRef,
280 ],
281 );
282​
283 const onCreateSelectedThreadBranch = useCallback(
284 async (branch: string) => {
285 return runSelectedThreadGitMutation(
286 "create_ref",
287 "Creating branch",
288 async ({ thread, cwd }) => {
289 const result = await createRef({
290 environmentId: thread.environmentId,
291 input: { cwd, refName: branch, switchRef: true },
292 });
293 if (AsyncResult.isFailure(result)) {
294 return result;
295 }
296 const syncResult = await syncSelectedThreadBranchState({
297 thread,
298 cwd,
299 nextThreadState: {
300 branch: result.value.refName ?? thread.branch,
301 worktreePath: selectedThreadWorktreePath,
302 },
303 });
304 return AsyncResult.isFailure(syncResult) ? AsyncResult.failure(syncResult.cause) : result;
305 },
306 { changesThreadBranch: true },
307 );
308 },
309 [
310 runSelectedThreadGitMutation,
311 selectedThreadWorktreePath,
312 syncSelectedThreadBranchState,
313 createRef,
314 ],
315 );
316​
317 const onCreateSelectedThreadWorktree = useCallback(
318 async (nextWorktree: { readonly baseBranch: string; readonly newBranch: string }) => {
319 return runSelectedThreadGitMutation(
320 "create_worktree",
321 "Creating worktree",
322 async ({ thread, project }) => {
323 const result = await createWorktree({
324 environmentId: thread.environmentId,
325 input: {
326 cwd: project.workspaceRoot,
327 refName: nextWorktree.baseBranch,
328 newRefName: sanitizeFeatureBranchName(nextWorktree.newBranch),
329 path: null,
330 },
331 });
332 if (AsyncResult.isFailure(result)) {
333 return result;
334 }
335 const syncResult = await syncSelectedThreadBranchState({
336 thread,
337 cwd: result.value.worktree.path,
338 nextThreadState: {
339 branch: result.value.worktree.refName,
340 worktreePath: result.value.worktree.path,
341 },
342 });
343 return AsyncResult.isFailure(syncResult) ? AsyncResult.failure(syncResult.cause) : result;
344 },
345 { changesThreadBranch: true },
346 );
347 },
348 [createWorktree, runSelectedThreadGitMutation, syncSelectedThreadBranchState],
349 );
350​
351 const onPullSelectedThreadBranch = useCallback(async () => {
352 await runSelectedThreadGitMutation(
353 "pull",
354 "Pulling latest changes",
355 async ({ thread, cwd }) => {
356 const result = await pull({
357 environmentId: thread.environmentId,
358 input: { cwd },
359 });
360 if (AsyncResult.isFailure(result)) {
361 return result;
362 }
363 await refreshSelectedThreadGitStatus({ quiet: true, cwd });
364 showGitActionResult({
365 type: "success",
366 title:
367 result.value.status === "skipped_up_to_date"
368 ? "Already up to date"
369 : `Pulled latest on ${result.value.refName}`,
370 });
371 return result;
372 },
373 );
374 }, [pull, refreshSelectedThreadGitStatus, runSelectedThreadGitMutation]);
375​
376 const onRunSelectedThreadGitAction = useCallback(
377 async (input: GitActionRequestInput): Promise<GitRunStackedActionResult | null> => {
378 const actionId = uuidv4();
379 return await runSelectedThreadGitMutation(
380 "run_change_request",
381 "Running source control action",
382 async ({ thread, cwd }) => {
383 const result = await runStackedAction({
384 actionId,
385 action: input.action,
386 ...(input.commitMessage ? { commitMessage: input.commitMessage } : {}),
387 ...(input.featureBranch ? { featureBranch: input.featureBranch } : {}),
388 ...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}),
389 threadId: thread.id,
390 });
391 if (AsyncResult.isFailure(result)) {
392 return result;
393 }
394​
395 if (result.value.branch.status === "created" && result.value.branch.name) {
396 const syncResult = await syncSelectedThreadBranchState({
397 thread,
398 cwd,
399 nextThreadState: {
400 branch: result.value.branch.name,
401 worktreePath: selectedThreadWorktreePath,
402 },
403 });
404 if (AsyncResult.isFailure(syncResult)) {
405 return AsyncResult.failure(syncResult.cause);
406 }
407 } else {
408 await refreshSelectedThreadGitStatus({ quiet: true, cwd });
409 }
410 showGitActionResult({
411 type: "success",
412 title: result.value.toast.title,
413 description: result.value.toast.description,
414 prUrl:
415 result.value.toast.cta.kind === "open_pr" ? result.value.toast.cta.url : undefined,
416 });
417 return result;
418 },
419 { managedExternally: true, changesThreadBranch: input.featureBranch === true },
420 );
421 },
422 [
423 runStackedAction,
424 refreshSelectedThreadGitStatus,
425 runSelectedThreadGitMutation,
426 selectedThreadWorktreePath,
427 syncSelectedThreadBranchState,
428 ],
429 );
430​
431 return {
432 canWriteSourceControl,
433 canChangeThreadBranch,
434 refreshSelectedThreadGitStatus,
435 refreshSelectedThreadBranches,
436 onCheckoutSelectedThreadBranch,
437 onCreateSelectedThreadBranch,
438 onCreateSelectedThreadWorktree,
439 onPullSelectedThreadBranch,
440 onRunSelectedThreadGitAction,
441 };