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