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