Open History to see the last commit
1import * as Dialog from "../../components/ui/Dialog";
2import {
3 CommonActions,
4 useRoute,
5 usePreventRemove,
6 usePreventRemoveContext,
7 type StaticScreenProps,
8} from "@react-navigation/native";
9import { useEffect, useState } from "react";
10import { View } from "react-native";
11import { useAtomValue } from "@effect/atom-react";
12import {
13 isAtomCommandInterrupted,
14 runAtomCommand,
15 squashAtomCommandFailure,
16} from "@t3tools/client-runtime/state/runtime";
17import { AsyncResult, Atom } from "effect/reactivity";
18import { AppText as Text } from "../../components/ui/AppText";
19import { useProjects } from "../../state/entities";
20import { appAtomRegistry } from "../../state/atom-registry";
21import { rootNavigationRef } from "../../lib/rootNavigation";
22import { threadSelectionDeferral } from "../layout/deferred-navigation";
23import { useWorkspaceState } from "../../state/workspace";
24import { vcsEnvironment } from "../../state/vcs";
25import { checkoutNewTaskBranch } from "./checkout-new-task-branch";
26import { resolveNewTaskBranchWorktreePath } from "./new-task-context-presentation";
27import {
28 type BranchCheckoutResult,
29 branchCheckoutRequestKey,
30 makeNewTaskBranchCheckouts,
31} from "./new-task-branch-checkout";
32import { liveNewTaskFlowKeys, newTaskFlowKey } from "./new-task-flow-state";
33import { NativeStackScreenOptions } from "../../native/StackHeader";
34
35import { ThreadScreenFallback } from "./ThreadScreenHost";
36import { NewTaskDraftScreen } from "./NewTaskDraftScreen";
37
38import type { NewTaskDraftRouteParams } from "./thread-route-state";
39export type { NewTaskDraftRouteParams } from "./thread-route-state";
40
41const branchCheckouts = makeNewTaskBranchCheckouts({
42 run: (request) =>
43 checkoutNewTaskBranch({
44 branch: {
45 name: request.branch,
46 current: false,
47 isDefault: false,
48 worktreePath: request.worktreePath,
49 },
50 project:
51 request.environmentId !== null && request.workspaceRoot !== null
52 ? { environmentId: request.environmentId, workspaceRoot: request.workspaceRoot }
53 : null,
54 workspaceMode: "local",
55 readRefs: (input) =>
56 runAtomCommand(appAtomRegistry, vcsEnvironment.readRefs, input, {
57 reportFailure: false,
58 }),
59 switchRef: (input) =>
60 runAtomCommand(appAtomRegistry, vcsEnvironment.switchRef, input, {
61 reportFailure: false,
62 }),
63 }),
64 holdNavigation: threadSelectionDeferral.waitFor,
65 onFailure: (request, result) => {
66 if (!isAtomCommandInterrupted(result)) {
67 const error = squashAtomCommandFailure(result);
68 Dialog.alert(
69 "Could not switch branch",
70 error instanceof Error ? error.message : "The branch could not be checked out.",
71 );
72 }
73 rootNavigationRef.dispatch({
74 ...CommonActions.goBack(),
75 source: request.routeKey,
76 target: rootNavigationRef.getRootState()?.key,
77 });
78 },
79});
80
81/** Abandons the branch checkouts of draft routes that left the stack. */
82export function pruneNewTaskBranchCheckouts(state: Parameters<typeof liveNewTaskFlowKeys>[0]) {
83 branchCheckouts.prune(liveNewTaskFlowKeys(state));
84}
85
86const idleBranchCheckoutAtom = Atom.make(AsyncResult.initial<BranchCheckoutResult, never>()).pipe(
87 Atom.withLabel("mobile:new-task-branch-checkout:idle"),
88);
89
90export function NewTaskDraftRouteScreen({ route }: StaticScreenProps<NewTaskDraftRouteParams>) {
91 const currentRoute = useRoute();
92 const params = route.params ?? {};
93 const draftId = Array.isArray(params.draftId) ? params.draftId[0] : params.draftId;
94 const projects = useProjects();
95 const { state: catalogState } = useWorkspaceState();
96
97 const initialProjectRef = {
98 environmentId: Array.isArray(params.environmentId)
99 ? params.environmentId[0]
100 : params.environmentId,
101 projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
102 branch: params.branch,
103 worktreePath: params.worktreePath,
104 cloning: (Array.isArray(params.cloning) ? params.cloning[0] : params.cloning) === "1",
105 };
106
107 const project = projects.find(
108 (candidate) =>
109 candidate.environmentId === initialProjectRef.environmentId &&
110 candidate.id === initialProjectRef.projectId,
111 );
112 // A project can drop out of the list and come back while its catalog stays ready. The checkout
113 // keeps the last project this route resolved, so that gap reads the same checkout.
114 const [resolvedProject, setResolvedProject] = useState<Pick<
115 NonNullable<typeof project>,
116 "environmentId" | "workspaceRoot"
117 > | null>(null);
118 if (
119 project &&
120 (resolvedProject?.environmentId !== project.environmentId ||
121 resolvedProject.workspaceRoot !== project.workspaceRoot)
122 ) {
123 setResolvedProject({
124 environmentId: project.environmentId,
125 workspaceRoot: project.workspaceRoot,
126 });
127 }
128 const checkoutProject = project ?? resolvedProject;
129 const workspaceRoot = project?.workspaceRoot;
130 const needsPreparation = Boolean(initialProjectRef.branch && !draftId);
131 const waitingForProject =
132 !project &&
133 (catalogState.isLoadingConnections ||
134 (!catalogState.hasLoadedShellSnapshot &&
135 catalogState.hasConnectingEnvironment &&
136 catalogState.connectionError === null));
137
138 // The checkout is keyed by its request, so a reconnect that drops and
139 // restores the project reads the same checkout instead of running another.
140 const flowKey = newTaskFlowKey(currentRoute);
141 const checkoutKey =
142 needsPreparation && initialProjectRef.branch && !waitingForProject && flowKey !== undefined
143 ? branchCheckoutRequestKey({
144 flowKey,
145 routeKey: currentRoute.key,
146 environmentId: checkoutProject?.environmentId ?? null,
147 workspaceRoot: checkoutProject?.workspaceRoot ?? null,
148 branch: initialProjectRef.branch,
149 worktreePath: initialProjectRef.worktreePath ?? null,
150 })
151 : null;
152 const checkout = useAtomValue(
153 checkoutKey === null ? idleBranchCheckoutAtom : branchCheckouts.atom(checkoutKey),
154 );
155 const result = AsyncResult.isSuccess(checkout) ? checkout.value : null;
156 // The native-stack guard covers iOS swipe dismissal as well as back actions.
157 const checkoutPending = needsPreparation && result === null;
158 usePreventRemove(checkoutPending, () => undefined);
159 const { preventedRoutes } = usePreventRemoveContext();
160 const removalBlocked = preventedRoutes[currentRoute.key]?.preventRemove === true;
161 // Native-stack reads the provider's prevent state, which commits a render
162 // after usePreventRemove updates its registry; the deferred thread selection
163 // (and the failure goBack) must wait for that commit.
164 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- releases the branch checkout to its route once native-stack has committed the prevent-remove state
165 useEffect(() => {
166 if (checkoutKey === null || checkoutPending || removalBlocked) return;
167 branchCheckouts.release(checkoutKey);
168 }, [checkoutKey, checkoutPending, removalBlocked]);
169
170 const prepared =
171 result?._tag === "Success" && workspaceRoot
172 ? {
173 branch: result.value.name,
174 worktreePath: resolveNewTaskBranchWorktreePath({
175 workspaceMode: "local",
176 projectCwd: workspaceRoot,
177 branchWorktreePath: result.value.worktreePath,
178 }),
179 }
180 : null;
181 const preparedBranch = prepared ? prepared.branch : initialProjectRef.branch;
182 const preparedWorktreePath = prepared ? prepared.worktreePath : initialProjectRef.worktreePath;
183 // NewTaskDraftScreen re-applies the route project (and rewrites the draft's
184 // workspace) whenever this object's identity changes. initialProjectRef is new
185 // every render, so read its fields first: the compiler then memoizes this
186 // object on them, instead of on initialProjectRef.
187 const { environmentId, projectId, cloning } = initialProjectRef;
188 const preparedProjectRef = {
189 environmentId,
190 projectId,
191 branch: preparedBranch,
192 worktreePath: preparedWorktreePath,
193 cloning,
194 };
195 const preparingBranch = checkoutPending || (needsPreparation && result?._tag !== "Success");
196
197 return (
198 <>
199 {preparingBranch ? (
200 <ThreadScreenFallback>
201 <NativeStackScreenOptions options={{ title: "New thread" }} />
202 <View className="flex-1 items-center justify-center bg-screen">
203 <Text className="text-foreground">Switching branch...</Text>
204 </View>
205 </ThreadScreenFallback>
206 ) : (
207 <NewTaskDraftScreen
208 initialProjectRef={preparedProjectRef}
209 incomingShareId={
210 Array.isArray(params.incomingShareId)
211 ? params.incomingShareId[0]
212 : params.incomingShareId
213 }
214 draftId={draftId}
215 />
216 )}
217 </>
218 );
219}