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