The best way to control Claude Code, Codex and more from any computer or phone

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