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

use-selected-thread-git-actions.ts

467 lines16.6 KB

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