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 { AppBar } from "../../components/ui/AppBar";
34import { useWorkspaceBackNavigation } from "../layout/workspace/useAndroidWorkspaceNavigation";
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 goBack = useWorkspaceBackNavigation();
94 const params = route.params ?? {};
95 const draftId = Array.isArray(params.draftId) ? params.draftId[0] : params.draftId;
96 const projects = useProjects();
97 const { state: catalogState } = useWorkspaceState();
98
99 const initialProjectRef = {
100 environmentId: Array.isArray(params.environmentId)
101 ? params.environmentId[0]
102 : params.environmentId,
103 projectId: Array.isArray(params.projectId) ? params.projectId[0] : params.projectId,
104 branch: params.branch,
105 worktreePath: params.worktreePath,
106 cloning: (Array.isArray(params.cloning) ? params.cloning[0] : params.cloning) === "1",
107 };
108
109 const project = projects.find(
110 (candidate) =>
111 candidate.environmentId === initialProjectRef.environmentId &&
112 candidate.id === initialProjectRef.projectId,
113 );
114 // A project can drop out of the list and come back while its catalog stays ready. The checkout
115 // keeps the last project this route resolved, so that gap reads the same checkout.
116 const [resolvedProject, setResolvedProject] = useState<Pick<
117 NonNullable<typeof project>,
118 "environmentId" | "workspaceRoot"
119 > | null>(null);
120 if (
121 project &&
122 (resolvedProject?.environmentId !== project.environmentId ||
123 resolvedProject.workspaceRoot !== project.workspaceRoot)
124 ) {
125 setResolvedProject({
126 environmentId: project.environmentId,
127 workspaceRoot: project.workspaceRoot,
128 });
129 }
130 const checkoutProject = project ?? resolvedProject;
131 const workspaceRoot = project?.workspaceRoot;
132 const needsPreparation = Boolean(initialProjectRef.branch && !draftId);
133 const waitingForProject =
134 !project &&
135 (catalogState.isLoadingConnections ||
136 (!catalogState.hasLoadedShellSnapshot &&
137 catalogState.hasConnectingEnvironment &&
138 catalogState.connectionError === null));
139
140 // The checkout is keyed by its request, so a reconnect that drops and
141 // restores the project reads the same checkout instead of running another.
142 const flowKey = newTaskFlowKey(currentRoute);
143 const checkoutKey =
144 needsPreparation && initialProjectRef.branch && !waitingForProject && flowKey !== undefined
145 ? branchCheckoutRequestKey({
146 flowKey,
147 routeKey: currentRoute.key,
148 environmentId: checkoutProject?.environmentId ?? null,
149 workspaceRoot: checkoutProject?.workspaceRoot ?? null,
150 branch: initialProjectRef.branch,
151 worktreePath: initialProjectRef.worktreePath ?? null,
152 })
153 : null;
154 const checkout = useAtomValue(
155 checkoutKey === null ? idleBranchCheckoutAtom : branchCheckouts.atom(checkoutKey),
156 );
157 const result = AsyncResult.isSuccess(checkout) ? checkout.value : null;
158 // The native-stack guard covers iOS swipe dismissal as well as back actions.
159 const checkoutPending = needsPreparation && result === null;
160 usePreventRemove(checkoutPending, () => undefined);
161 const { preventedRoutes } = usePreventRemoveContext();
162 const removalBlocked = preventedRoutes[currentRoute.key]?.preventRemove === true;
163 // Native-stack reads the provider's prevent state, which commits a render
164 // after usePreventRemove updates its registry; the deferred thread selection
165 // (and the failure goBack) must wait for that commit.
166 // 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
167 useEffect(() => {
168 if (checkoutKey === null || checkoutPending || removalBlocked) return;
169 branchCheckouts.release(checkoutKey);
170 }, [checkoutKey, checkoutPending, removalBlocked]);
171
172 const prepared =
173 result?._tag === "Success" && workspaceRoot
174 ? {
175 branch: result.value.name,
176 worktreePath: resolveNewTaskBranchWorktreePath({
177 workspaceMode: "local",
178 projectCwd: workspaceRoot,
179 branchWorktreePath: result.value.worktreePath,
180 }),
181 }
182 : null;
183 const preparedBranch = prepared ? prepared.branch : initialProjectRef.branch;
184 const preparedWorktreePath = prepared ? prepared.worktreePath : initialProjectRef.worktreePath;
185 // NewTaskDraftScreen re-applies the route project (and rewrites the draft's
186 // workspace) whenever this object's identity changes. initialProjectRef is new
187 // every render, so read its fields first: the compiler then memoizes this
188 // object on them, instead of on initialProjectRef.
189 const { environmentId, projectId, cloning } = initialProjectRef;
190 const preparedProjectRef = {
191 environmentId,
192 projectId,
193 branch: preparedBranch,
194 worktreePath: preparedWorktreePath,
195 cloning,
196 };
197 const preparingBranch = checkoutPending || (needsPreparation && result?._tag !== "Success");
198
199 return (
200 <>
201 {preparingBranch ? (
202 <ThreadScreenFallback header={<AppBar title="New thread" onBack={goBack} />}>
203 <View className="flex-1 items-center justify-center bg-screen">
204 <Text className="text-foreground">Switching branch...</Text>
205 </View>
206 </ThreadScreenFallback>
207 ) : (
208 <NewTaskDraftScreen
209 initialProjectRef={preparedProjectRef}
210 incomingShareId={
211 Array.isArray(params.incomingShareId)
212 ? params.incomingShareId[0]
213 : params.incomingShareId
214 }
215 draftId={draftId}
216 />
217 )}
218 </>
219 );
220}