Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AddProjectScreen.tsx

1,472 lines50.8 KB

1import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
2import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
3import * as Dialog from "../../components/ui/Dialog";
4import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
5import { NavigationRow } from "../../components/ui/NavigationRow";
6import { SettingsScreen } from "../settings/components/SettingsScreen";
7import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
8import { Button } from "../../components/ui/Button";
9import {
10 addProjectRemoteSourceLabel,
11 addProjectRemoteSourcePathHint,
12 addProjectRemoteSourceProvider,
13 buildAddProjectRemoteSourceReadiness,
14 buildProjectCreateCommand,
15 canCreateProjectInEnvironment,
16 findExistingAddProject,
17 getAddProjectInitialQuery,
18 getCloneDestinationBrowsePath,
19 getCloneDestinationPath,
20 getCloneDirectoryName,
21 getDefaultCloneUrl,
22 getNewProjectPathPreview,
23 getNewProjectPublishTarget,
24 getNewProjectPublishTargets,
25 getNewProjectRepository,
26 defaultHostCloneUrl,
27 normalizePastedCloneUrl,
28 parseAddProjectRemoteSource,
29 resolveAddProjectPath,
30 sortAddProjectProviderSources,
31 type AddProjectRemoteSource,
32} from "@t3tools/client-runtime/operations/projects";
33import {
34 connectionStatusText,
35 type EnvironmentConnectionPhase,
36} from "@t3tools/client-runtime/connection";
37import {
38 canPreloadBrowsePath,
39 createBrowseNavigationCoordinator,
40 filterFilesystemBrowseEntries,
41 getFilesystemBrowsePath,
42 resolveFilesystemReadAccess,
43} from "@t3tools/client-runtime/state/filesystem";
44import {
45 appendBrowsePathSegment,
46 inferProjectTitleFromPath,
47 isWindowsPlatform,
48} from "@t3tools/client-runtime/state/projects";
49import {
50 AuthOrchestrationOperateScope,
51 AuthSourceControlWriteScope,
52 AuthFilesystemReadScope,
53 CommandId,
54 type EnvironmentId,
55 type EnvironmentMachineKind,
56 ProjectId,
57 resolveEnvironmentMachineKind,
58 SourceControlProviderKind,
59} from "@t3tools/contracts";
60import {
61 StackActions,
62 useNavigation,
63 type NavigationState,
64 type ParamListBase,
65} from "@react-navigation/native";
66import { SymbolView } from "../../components/ui/AppSymbol";
67import { useEffect, useRef, useState, type ReactNode } from "react";
68import { Platform, Pressable, View } from "react-native";
69import { useSafeAreaInsets } from "react-native-safe-area-context";
70import * as Arr from "effect/Array";
71import * as Cause from "effect/Cause";
72import * as Order from "effect/Order";
73import { AsyncResult } from "effect/reactivity";
74import { cn } from "../../lib/cn";
75import { useProjects, useServerConfigs, waitForProject } from "../../state/entities";
76import { filesystemEnvironment } from "../../state/filesystem";
77import { projectEnvironment } from "../../state/projects";
78import { useEnvironmentQuery } from "../../state/query";
79import { environmentSession, useEnvironmentScope, readEnvironmentScope } from "../../state/session";
80import { useEnvironmentPresentation } from "../../state/presentation";
81import { sourceControlEnvironment } from "../../state/sourceControl";
82import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
83import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
84import { ErrorBanner } from "../../components/ui/ErrorBanner";
85import { SourceControlIcon } from "./SourceControlIcon";
86import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
87import { ThemedSwitch } from "../../components/ui/ThemedSwitch";
88import { uuidv4 } from "../../lib/uuid";
89import { useAtomCommand } from "../../state/use-atom-command";
90import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
91import {
92 useRemoteConnectionStatus,
93 useRemoteEnvironmentRuntime,
94 useSavedRemoteConnections,
95} from "../../state/use-remote-environment-registry";
96import { resolveAddProjectEnvironment } from "./AddProjectScreen.logic";
97import {
98 createNewTaskDraft,
99 setComposerDraftText,
100 waitForComposerDraftsLoaded,
101} from "../../state/use-composer-drafts";
102​
103interface EnvironmentOption {
104 readonly environmentId: EnvironmentId;
105 readonly label: string;
106 readonly platform: string;
107 readonly machine: EnvironmentMachineKind;
108 readonly baseDirectory: string | null;
109 readonly newProjectsRoot: string | null;
110 readonly connectionState: EnvironmentConnectionPhase;
111 readonly connectionError: string | null;
112 readonly connectionErrorTraceId: string | null;
113 readonly supportsCloneTracking: boolean;
115​
116const environmentOptionOrder = Order.mapInput(
117 Order.Struct({
118 label: Order.String,
119 }),
120 (environment: EnvironmentOption) => ({ label: environment.label }),
121);
122​
123function platformFromOs(os: string | null | undefined): string {
124 if (os === "windows") return "Win32";
125 if (os === "darwin") return "MacIntel";
126 if (os === "linux") return "Linux";
127 return "";
129​
130function errorMessage(error: unknown): string {
131 return error instanceof Error && error.message.trim().length > 0
132 ? error.message
133 : "An error occurred.";
135​
136function stringParam(value: string | string[] | undefined): string | null {
137 if (Array.isArray(value)) return value[0] ?? null;
138 return value ?? null;
140​
141function sourceFromParam(value: string | string[] | undefined): AddProjectRemoteSource {
142 return parseAddProjectRemoteSource(stringParam(value));
144​
145function SectionTitle(props: { readonly children: string }) {
146 return (
147 <Text
148 className={
149 Platform.OS === "android"
150 ? "px-4 text-sm font-t3-medium text-primary-text"
151 : "px-1 text-2xs font-t3-bold tracking-[0.7px] uppercase text-foreground-muted"
152 }
153 >
154 {props.children}
155 </Text>
156 );
158​
159function AddProjectShell(props: { readonly children: ReactNode; readonly title: string }) {
160 const insets = useSafeAreaInsets();
161​
162 return (
163 // A collapsible wrapper lets formSheet resizing mistake the full-height view for a header and collapse the ScrollView.
164 <SettingsScreen title={props.title}>
165 <ScrollView
166 keyboardShouldPersistTaps="handled"
167 contentInsetAdjustmentBehavior="automatic"
168 contentContainerStyle={{
169 paddingHorizontal: Platform.OS === "android" ? 16 : 20,
170 paddingTop: 16,
171 paddingBottom: Math.max(insets.bottom, 18) + 18,
172 gap: Platform.OS === "android" ? 16 : 10,
173 }}
174 >
175 {props.children}
176 </ScrollView>
177 </SettingsScreen>
178 );
180​
181function ListSection(props: { readonly children: ReactNode }) {
182 return (
183 <View
184 className={
185 Platform.OS === "android"
186 ? "overflow-hidden rounded-[28px] bg-grouped-card"
187 : "overflow-hidden rounded-[24px] bg-grouped-card"
188 }
189 >
190 {props.children}
191 </View>
192 );
194​
195function ListRow(props: {
196 readonly title: string;
197 readonly subtitle?: string | null;
198 readonly icon: ReactNode;
199 readonly disabled?: boolean;
200 readonly selected?: boolean;
201 readonly isFirst?: boolean;
202 readonly right?: ReactNode;
203 readonly onPress?: () => void;
204}) {
205 if (Platform.OS === "android") {
206 return (
207 <NavigationRow
208 className="bg-grouped-card"
209 title={props.title}
210 subtitle={props.subtitle}
211 leading={props.icon}
212 trailing={props.right}
213 disabled={props.disabled}
214 onPress={props.onPress}
215 accessibilityRole={props.selected !== undefined ? "radio" : "button"}
216 accessibilityState={props.selected !== undefined ? { checked: props.selected } : undefined}
217 />
218 );
219 }
220 return (
221 <Pressable
222 disabled={props.disabled}
223 onPress={props.onPress}
224 className={cn(
225 "bg-grouped-card px-3.5 py-2.5 active:opacity-70",
226 !props.isFirst && "border-t border-border-subtle",
227 props.disabled && "opacity-[0.45]",
228 )}
229 >
230 <View className="flex-row items-center gap-3">
231 <View
232 className={
233 props.selected
234 ? "h-7 w-7 items-center justify-center rounded-full bg-primary"
235 : "h-7 w-7 items-center justify-center"
236 }
237 >
238 {props.icon}
239 </View>
240 <View className="flex-1 gap-0.5">
241 <Text className="text-base leading-snug font-t3-bold">{props.title}</Text>
242 {props.subtitle ? (
243 <Text className="text-sm leading-snug text-foreground-muted" numberOfLines={2}>
244 {props.subtitle}
245 </Text>
246 ) : null}
247 </View>
248 {"right" in props ? (
249 props.right
250 ) : !props.disabled ? (
251 <SymbolView
252 name="chevron.right"
253 size={13}
254 tintColorClassName="accent-chevron"
255 type="monochrome"
256 />
257 ) : null}
258 </View>
259 </Pressable>
260 );
262​
263function PrimaryActionButton(props: {
264 readonly label: string;
265 readonly disabled?: boolean;
266 readonly loading?: boolean;
267 readonly onPress: () => void;
268}) {
269 return <Button {...props} tone="primary" fullWidth />;
271​
272function ProjectPathInput(props: {
273 readonly value: string;
274 readonly onChangeText: (value: string) => void;
275 readonly onSubmit: () => void;
276}) {
277 return (
278 <TextInput
279 className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
280 value={props.value}
281 onChangeText={props.onChangeText}
282 autoCapitalize="none"
283 autoCorrect={false}
284 placeholder="~/projects/my-app"
285 returnKeyType="done"
286 onSubmitEditing={props.onSubmit}
287 />
288 );
290​
291function useBrowsePathInput(environment: EnvironmentOption | null, pinnedDirectoryName = "") {
292 const environmentId = environment?.environmentId ?? null;
293 const environmentBaseDirectory = environment?.baseDirectory ?? null;
294 const clonePathCaseSensitive = !isWindowsPlatform(environment?.platform ?? "");
295 const seedPath = getCloneDestinationPath(
296 getAddProjectInitialQuery(environmentBaseDirectory),
297 pinnedDirectoryName,
298 );
299 // Each host keeps the path last typed or browsed for it, and shows its own default until then,
300 // so switching hosts and back loses nothing. With no host selected (one dropping out briefly),
301 // the field keeps the last path typed anywhere.
302 const [paths, setPaths] = useState<{
303 readonly byHost: ReadonlyMap<EnvironmentId, string>;
304 readonly last: string;
305 }>(() => ({ byHost: new Map(), last: seedPath }));
306 const pathInput =
307 environmentId === null ? paths.last : (paths.byHost.get(environmentId) ?? seedPath);
308 const commitPathInput = (path: string) =>
309 setPaths((current) => {
310 const byHost = new Map(current.byHost);
311 if (environmentId !== null) {
312 byHost.set(environmentId, path);
313 }
314 return { byHost, last: path };
315 });
316 const environmentRuntime = useRemoteEnvironmentRuntime(environmentId);
317 const loadBrowsePath = useAtomQueryRunner(filesystemEnvironment.browse, {
318 reportFailure: false,
319 reportDefect: false,
320 });
321 const [browseNavigation] = useState(createBrowseNavigationCoordinator);
322 const [navigatingEnvironmentId, setNavigatingEnvironmentId] = useState<
323 EnvironmentId | null | undefined
324 >(undefined);
325 const isBrowseNavigating = navigatingEnvironmentId === environmentId;
326 const setPathInput = (path: string) => {
327 browseNavigation.invalidate();
328 setNavigatingEnvironmentId(undefined);
329 commitPathInput(path);
330 };
331 const navigateToBrowsePath = async (input: {
332 readonly browseDirectoryPath: string;
333 readonly selectedDirectoryName?: string;
334 }) => {
335 const selectedDirectoryPath = input.selectedDirectoryName
336 ? appendBrowsePathSegment(input.browseDirectoryPath, input.selectedDirectoryName)
337 : input.browseDirectoryPath;
338 const nextPathInput =
339 pinnedDirectoryName && input.selectedDirectoryName
340 ? getCloneDestinationBrowsePath({
341 browseDirectoryPath: input.browseDirectoryPath,
342 selectedDirectoryName: input.selectedDirectoryName,
343 cloneDirectoryName: pinnedDirectoryName,
344 caseSensitive: clonePathCaseSensitive,
345 })
346 : getCloneDestinationPath(selectedDirectoryPath, pinnedDirectoryName);
347 setNavigatingEnvironmentId(environmentId);
348 const committed = await browseNavigation.run(
349 async () => {
350 if (
351 environment &&
352 readEnvironmentScope(environment.environmentId, AuthFilesystemReadScope) &&
353 canPreloadBrowsePath(environmentRuntime?.connectionState)
354 ) {
355 await loadBrowsePath({
356 environmentId: environment.environmentId,
357 input: { partialPath: selectedDirectoryPath },
358 });
359 }
360 },
361 () => commitPathInput(nextPathInput),
362 );
363 if (committed) {
364 setNavigatingEnvironmentId(undefined);
365 }
366 return committed;
367 };
368​
369 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- invalidates the browse navigation coordinator on unmount so in-flight browses do not commit
370 useEffect(
371 () => () => {
372 browseNavigation.invalidate();
373 },
374 [browseNavigation],
375 );
376​
377 return { isBrowseNavigating, pathInput, setPathInput, navigateToBrowsePath };
379​
380function useEnvironmentOptions(
381 selectedEnvironmentId: EnvironmentId | null = null,
382): ReadonlyArray<EnvironmentOption> {
383 const serverConfigByEnvironmentId = useServerConfigs();
384 const { savedConnectionsById } = useSavedRemoteConnections();
385 const { connectedEnvironments } = useRemoteConnectionStatus();
386​
387 return ((): ReadonlyArray<EnvironmentOption> => {
388 const runtimeByEnvironmentId = new Map(
389 connectedEnvironments.map((environment) => [environment.environmentId, environment] as const),
390 );
391 const options = Object.values(savedConnectionsById).map((connection) => {
392 const config = serverConfigByEnvironmentId.get(connection.environmentId);
393 const runtime = runtimeByEnvironmentId.get(connection.environmentId);
394 return {
395 environmentId: connection.environmentId,
396 label: connection.environmentLabel,
397 platform: platformFromOs(config?.environment.platform.os ?? null),
398 machine: resolveEnvironmentMachineKind(config ?? null),
399 baseDirectory: config?.settings.addProjectBaseDirectory ?? null,
400 newProjectsRoot: config?.newProjectsRoot ?? null,
401 connectionState: runtime?.connectionState ?? "available",
402 connectionError: runtime?.connectionError ?? null,
403 connectionErrorTraceId: runtime?.connectionErrorTraceId ?? null,
404 supportsCloneTracking: config?.environment.capabilities.projectCloneTracking === true,
405 };
406 });
407 return Arr.sort(
408 options.filter(
409 (environment) =>
410 canCreateProjectInEnvironment(environment.connectionState) ||
411 environment.environmentId === selectedEnvironmentId,
412 ),
413 environmentOptionOrder,
414 );
415 })();
417​
418function useSelectedEnvironment(requestedEnvironmentId: EnvironmentId | null): {
419 readonly environmentOptions: ReadonlyArray<EnvironmentOption>;
420 readonly selectedEnvironment: EnvironmentOption | null;
421 readonly setSelectedEnvironmentId: (environmentId: EnvironmentId) => void;
422} {
423 const [selectedEnvironmentId, setSelectedEnvironmentId] = useState(requestedEnvironmentId);
424 const [previousRequest, setPreviousRequest] = useState(requestedEnvironmentId);
425 if (previousRequest !== requestedEnvironmentId) {
426 setPreviousRequest(requestedEnvironmentId);
427 setSelectedEnvironmentId(requestedEnvironmentId);
428 }
429 const environmentOptions = useEnvironmentOptions(selectedEnvironmentId);
430 const selectedEnvironment =
431 environmentOptions.find((environment) => environment.environmentId === selectedEnvironmentId) ??
432 environmentOptions.find((environment) =>
433 canCreateProjectInEnvironment(environment.connectionState),
434 ) ??
435 null;
436​
437 return {
438 environmentOptions,
439 selectedEnvironment,
440 setSelectedEnvironmentId,
441 };
443​
444function EmptyEnvironmentState() {
445 const navigation = useNavigation();
446​
447 return (
448 <View className="items-center gap-3 rounded-2xl bg-grouped-card px-5 py-8">
449 <Text className="text-center text-lg font-t3-bold">Environment unavailable</Text>
450 <Text className="text-center text-sm leading-normal text-foreground-muted">
451 Start or reconnect an environment before adding a project.
452 </Text>
453 <View className="mt-1">
454 <Button
455 label="Add environment"
456 tone="primary"
457 onPress={() => navigation.dispatch(StackActions.replace("ConnectionsNew"))}
458 />
459 </View>
460 </View>
461 );
463​
464function SourceControlRow(props: {
465 readonly source: AddProjectRemoteSource;
466 readonly selectedEnvironmentId: EnvironmentId;
467 readonly ready: boolean;
468 readonly hint: string;
469 readonly isFirst: boolean;
470}) {
471 const navigation = useNavigation();
472 const title =
473 props.source === "url" ? "Git URL" : `${addProjectRemoteSourceLabel(props.source)} repository`;
474 const subtitle =
475 props.source === "url"
476 ? "Clone from a remote URL"
477 : `Clone ${addProjectRemoteSourceLabel(props.source)} ${props.hint}`;
478 const icon =
479 props.source === "url" ? (
480 <SymbolView
481 name="link"
482 size={Platform.OS === "android" ? 24 : 17}
483 tintColorClassName="accent-icon"
484 type="monochrome"
485 />
486 ) : (
487 <SourceControlIcon
488 icon={sourceControlClients.get(props.source).icon}
489 size={Platform.OS === "android" ? 24 : 18}
490 colorClassName="accent-icon"
491 />
492 );
493​
494 if (!props.ready) {
495 return (
496 <ListRow title={title} subtitle={props.hint} icon={icon} disabled isFirst={props.isFirst} />
497 );
498 }
499​
500 return (
501 <ListRow
502 title={title}
503 subtitle={subtitle}
504 icon={icon}
505 isFirst={props.isFirst}
506 onPress={() =>
507 navigation.dispatch(
508 StackActions.push("AddProjectRepository", {
509 environmentId: props.selectedEnvironmentId,
510 source: props.source,
511 }),
512 )
513 }
514 />
515 );
517​
518export function AddProjectSourceScreen(props: { readonly environmentId?: string | string[] }) {
519 const navigation = useNavigation();
520 const { environmentOptions, selectedEnvironment, setSelectedEnvironmentId } =
521 useSelectedEnvironment(stringParam(props.environmentId) as EnvironmentId | null);
522 const canWriteSourceControl = useEnvironmentScope(
523 selectedEnvironment?.environmentId ?? null,
524 AuthSourceControlWriteScope,
525 );
526 const canCreateProject = useEnvironmentScope(
527 selectedEnvironment?.environmentId ?? null,
528 AuthOrchestrationOperateScope,
529 );
530 const isConnected = canCreateProjectInEnvironment(selectedEnvironment?.connectionState);
531 const canCloneProject = isConnected && canWriteSourceControl && canCreateProject;
532 const discoveryState = useEnvironmentQuery(
533 selectedEnvironment === null || !isConnected
534 ? null
535 : sourceControlEnvironment.discovery({
536 environmentId: selectedEnvironment.environmentId,
537 input: {},
538 }),
539 );
540 const readiness = buildAddProjectRemoteSourceReadiness(discoveryState.data);
541​
542 return (
543 <AddProjectShell title="Add project">
544 {selectedEnvironment === null ? <EmptyEnvironmentState /> : null}
545​
546 {environmentOptions.length > 1 || (selectedEnvironment !== null && !isConnected) ? (
547 <>
548 <SectionTitle>Environments</SectionTitle>
549 <ListSection>
550 {environmentOptions.map((environment, index) => (
551 <ListRow
552 key={environment.environmentId}
553 title={environment.label}
554 subtitle={
555 canCreateProjectInEnvironment(environment.connectionState)
556 ? undefined
557 : connectionStatusText({
558 phase: environment.connectionState,
559 error: environment.connectionError,
560 traceId: environment.connectionErrorTraceId,
561 })
562 }
563 icon={
564 <EnvironmentMachineSymbol
565 kind={environment.machine}
566 size={Platform.OS === "android" ? 24 : 17}
567 tintColorClassName="accent-icon"
568 />
569 }
570 selected={environment.environmentId === selectedEnvironment?.environmentId}
571 disabled={!canCreateProjectInEnvironment(environment.connectionState)}
572 isFirst={index === 0}
573 right={
574 environment.environmentId === selectedEnvironment?.environmentId ? (
575 <SymbolView
576 name="checkmark"
577 size={Platform.OS === "android" ? 20 : 14}
578 tintColorClassName="accent-icon"
579 type="monochrome"
580 />
581 ) : null
582 }
583 onPress={() => setSelectedEnvironmentId(environment.environmentId)}
584 />
585 ))}
586 </ListSection>
587 </>
588 ) : null}
589​
590 {selectedEnvironment ? (
591 <>
592 <ListSection>
593 {selectedEnvironment.newProjectsRoot !== null ? (
594 <ListRow
595 title="New project"
596 subtitle="Start a new Git repository from a name"
597 disabled={!isConnected}
598 icon={
599 <SymbolView
600 name="plus"
601 size={Platform.OS === "android" ? 24 : 17}
602 tintColorClassName="accent-icon"
603 type="monochrome"
604 />
605 }
606 isFirst
607 onPress={() =>
608 navigation.dispatch(
609 StackActions.push("AddProjectNew", {
610 environmentId: selectedEnvironment.environmentId,
611 }),
612 )
613 }
614 />
615 ) : null}
616 <ListRow
617 title="Local folder"
618 subtitle={
619 canCreateProject
620 ? "Browse a folder on disk"
621 : "This connection cannot add projects."
622 }
623 icon={
624 <SymbolView
625 name="folder.badge.plus"
626 size={Platform.OS === "android" ? 24 : 17}
627 tintColorClassName="accent-icon"
628 type="monochrome"
629 />
630 }
631 isFirst={selectedEnvironment.newProjectsRoot === null}
632 disabled={!isConnected || !canCreateProject}
633 onPress={() =>
634 navigation.dispatch(
635 StackActions.push("AddProjectLocal", {
636 environmentId: selectedEnvironment.environmentId,
637 }),
638 )
639 }
640 />
641 {(["url", ...sortAddProjectProviderSources(readiness)] as AddProjectRemoteSource[]).map(
642 (candidate) => (
643 <SourceControlRow
644 key={candidate}
645 source={candidate}
646 selectedEnvironmentId={selectedEnvironment.environmentId}
647 ready={canCloneProject && readiness(candidate).ready}
648 hint={
649 !canCloneProject
650 ? "This connection cannot clone projects."
651 : readiness(candidate).ready
652 ? addProjectRemoteSourcePathHint(candidate)
653 : (readiness(candidate).hint ?? "")
654 }
655 isFirst={false}
656 />
657 ),
658 )}
659 </ListSection>
660 {discoveryState.isPending ? (
661 <AppActivityIndicator colorClassName="accent-icon-muted" />
662 ) : null}
663 </>
664 ) : null}
665 </AddProjectShell>
666 );
668​
669function getActiveRoute(navigation: {
670 getState: () => NavigationState<ParamListBase> | undefined;
671}) {
672 const state = navigation.getState();
673 return state?.routes[state.index];
675​
676function useOpenNewTaskDraft() {
677 const navigation = useNavigation<NativeStackNavigationProp<ReactNavigation.RootParamList>>();
678 const selectDetail = useSelectWorkspaceDetail();
679 return (
680 params: {
681 environmentId: EnvironmentId;
682 projectId: ProjectId;
683 title: string;
684 cloning?: "1";
685 draftId?: string;
686 },
687 originRoute: NavigationState<ParamListBase>["routes"][number] | undefined,
688 ) => {
689 const activeRoute = getActiveRoute(navigation);
690 // A warm link can change the task without replacing its native route key.
691 if (
692 !originRoute ||
693 activeRoute?.key !== originRoute.key ||
694 activeRoute.name !== originRoute.name ||
695 activeRoute.params !== originRoute.params
696 )
697 return;
698 selectDetail({ name: "Thread", params: { draft: params } });
699 };
701​
702async function draftWithPrompt(
703 environmentId: EnvironmentId,
704 projectId: ProjectId,
705 prompt: string,
706): Promise<string> {
707 await waitForComposerDraftsLoaded();
708 const draftId = createNewTaskDraft({ environmentId, projectId });
709 setComposerDraftText(draftId, prompt);
710 return draftId;
712​
713function useCreateProject(environment: EnvironmentOption | null) {
714 const openNewTaskDraft = useOpenNewTaskDraft();
715 const navigation = useNavigation();
716 const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
717 const projects = useProjects();
718​
719 return async (workspaceRoot: string, originRoute = getActiveRoute(navigation)) => {
720 if (
721 !environment ||
722 !canCreateProjectInEnvironment(environment.connectionState) ||
723 !readEnvironmentScope(environment.environmentId, AuthOrchestrationOperateScope)
724 ) {
725 Dialog.alert(
726 "Project not added",
727 `This connection cannot add projects right now. Any existing files remain at ${workspaceRoot}.`,
728 );
729 return;
730 }
731​
732 const existing = findExistingAddProject({
733 projects,
734 environmentId: environment.environmentId,
735 path: workspaceRoot,
736 });
737 if (existing) {
738 Dialog.alert("Project already exists", existing.title);
739 openNewTaskDraft(
740 {
741 environmentId: existing.environmentId,
742 projectId: existing.id,
743 title: existing.title,
744 },
745 originRoute,
746 );
747 return;
748 }
749​
750 const projectId = ProjectId.make(uuidv4());
751 const command = buildProjectCreateCommand({
752 commandId: CommandId.make(uuidv4()),
753 projectId,
754 workspaceRoot,
755 });
756 const result = await createProject({
757 environmentId: environment.environmentId,
758 input: command,
759 });
760 if (AsyncResult.isFailure(result)) {
761 return result;
762 }
763 // A successful command can precede its project in the client store. The
764 // draft treats a missing project as a reason to return to the chooser.
765 const project = await waitForProject(
766 { environmentId: environment.environmentId, projectId },
767 15_000,
768 );
769 if (project === null) {
770 Dialog.alert(
771 "Project added",
772 "The project was created but has not reached this device yet. It will appear in the project list once the connection catches up.",
773 );
774 return result;
775 }
776 openNewTaskDraft(
777 {
778 environmentId: environment.environmentId,
779 projectId,
780 title: inferProjectTitleFromPath(workspaceRoot),
781 },
782 originRoute,
783 );
784 return result;
785 };
787​
788function useEnvironmentFromParam(
789 environmentIdParam: string | string[] | undefined,
790): EnvironmentOption | null {
791 const environmentOptions = useEnvironmentOptions();
792 const environmentId = stringParam(environmentIdParam) as EnvironmentId | null;
793 return resolveAddProjectEnvironment(environmentOptions, environmentId);
795​
796export function AddProjectRepositoryScreen(props: {
797 readonly environmentId?: string | string[];
798 readonly source?: string | string[];
799}) {
800 const lookupRepositoryQuery = useAtomQueryRunner(sourceControlEnvironment.repository, {
801 reportFailure: false,
802 });
803 const navigation = useNavigation();
804 const environment = useEnvironmentFromParam(props.environmentId);
805 const source = sourceFromParam(props.source);
806 const [repositoryInput, setRepositoryInput] = useState("");
807 const [isSubmitting, setIsSubmitting] = useState(false);
808 const [error, setError] = useState<string | null>(null);
809​
810 const lookupRepository = async () => {
811 if (!environment || repositoryInput.trim().length === 0 || isSubmitting) return;
812 setError(null);
813 setIsSubmitting(true);
814 const provider = addProjectRemoteSourceProvider(source);
815 if (!provider) {
816 const remoteUrl = normalizePastedCloneUrl(repositoryInput);
817 navigation.dispatch(
818 StackActions.push("AddProjectDestination", {
819 environmentId: environment.environmentId,
820 source,
821 remoteUrl,
822 repositoryTitle: remoteUrl,
823 repositoryName: getCloneDirectoryName(remoteUrl),
824 }),
825 );
826 setIsSubmitting(false);
827 return;
828 }
829​
830 const result = await lookupRepositoryQuery({
831 environmentId: environment.environmentId,
832 input: {
833 provider,
834 repository: repositoryInput.trim(),
835 },
836 });
837 if (AsyncResult.isFailure(result)) {
838 setError(errorMessage(Cause.squash(result.cause)));
839 } else {
840 const repository = result.value;
841 navigation.dispatch(
842 StackActions.push("AddProjectDestination", {
843 environmentId: environment.environmentId,
844 source,
845 remoteUrl: getDefaultCloneUrl(repository),
846 repositoryTitle: repository.nameWithOwner,
847 repositoryName: getCloneDirectoryName(repository.nameWithOwner),
848 }),
849 );
850 }
851 setIsSubmitting(false);
852 };
853​
854 return (
855 <AddProjectShell title={source === "url" ? "Git URL" : addProjectRemoteSourceLabel(source)}>
856 {error ? <ErrorBanner message={error} /> : null}
857 {environment ? (
858 <>
859 <TextInput
860 className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
861 value={repositoryInput}
862 onChangeText={setRepositoryInput}
863 autoCapitalize="none"
864 autoCorrect={false}
865 placeholder={
866 source === "url"
867 ? (defaultHostCloneUrl("org/repo") ?? "https://example.com/org/repo.git")
868 : addProjectRemoteSourcePathHint(source)
869 }
870 returnKeyType="next"
871 onSubmitEditing={() => void lookupRepository()}
872 />
873 <PrimaryActionButton
874 label={source === "url" ? "Continue" : "Lookup repository"}
875 disabled={isSubmitting || repositoryInput.trim().length === 0}
876 onPress={() => void lookupRepository()}
877 loading={isSubmitting}
878 />
879 </>
880 ) : (
881 <EmptyEnvironmentState />
882 )}
883 </AddProjectShell>
884 );
886​
887function FolderBrowser(props: {
888 readonly environment: EnvironmentOption;
889 readonly pathInput: string;
890 readonly setPathInput: (path: string) => void;
891 readonly navigateToBrowsePath: (input: {
892 readonly browseDirectoryPath: string;
893 readonly selectedDirectoryName?: string;
894 }) => Promise<boolean>;
895 readonly pinnedDirectoryName?: string;
896}) {
897 const browsePath = getFilesystemBrowsePath(props.pathInput, props.environment.platform);
898 const browseInput =
899 browsePath.directoryPath.length > 0 ? { partialPath: browsePath.directoryPath } : null;
900 const fileAccessSession = useEnvironmentQuery(
901 environmentSession.sessionStateAtom(props.environment.environmentId),
902 );
903 const fileEnvironment = useEnvironmentPresentation(props.environment.environmentId);
904 const fileAccess = resolveFilesystemReadAccess({
905 isCatalogReady: fileEnvironment.isReady,
906 connection: fileEnvironment.presentation?.connection ?? null,
907 session: fileAccessSession.data,
908 sessionError: fileAccessSession.error,
909 });
910 const { canReadFiles } = fileAccess;
911 const browseState = useEnvironmentQuery(
912 !canReadFiles || browseInput === null
913 ? null
914 : filesystemEnvironment.browse({
915 environmentId: props.environment.environmentId,
916 input: browseInput,
917 }),
918 );
919 const pinnedDirectoryName = props.pinnedDirectoryName ?? "";
920 const pinnedDirectoryMatches = isWindowsPlatform(props.environment.platform)
921 ? browsePath.filterQuery.toLowerCase() === pinnedDirectoryName.toLowerCase()
922 : browsePath.filterQuery === pinnedDirectoryName;
923 const browseFilterQuery = pinnedDirectoryMatches ? "" : browsePath.filterQuery;
924 const { visibleEntries: visibleBrowseEntries } = filterFilesystemBrowseEntries(
925 browseState.data?.entries ?? [],
926 browseFilterQuery,
927 );
928​
929 return (
930 <>
931 <SectionTitle>Browse folders</SectionTitle>
932 {!canReadFiles && !fileAccess.isPending ? (
933 <ErrorBanner message={fileAccess.error ?? "This connection cannot browse host folders."} />
934 ) : null}
935 {browseState.error ? <ErrorBanner message={browseState.error} /> : null}
936 <ListSection>
937 {fileAccess.isPending || (browseState.isPending && browseState.data === null) ? (
938 <View className="items-center py-5">
939 <AppActivityIndicator colorClassName="accent-icon-muted" />
940 </View>
941 ) : null}
942 {browsePath.canBrowseUp ? (
943 <ListRow
944 title=".."
945 icon={
946 <SymbolView
947 name="arrow.turn.left.up"
948 size={Platform.OS === "android" ? 24 : 17}
949 tintColorClassName="accent-icon-muted"
950 type="monochrome"
951 />
952 }
953 isFirst
954 right={null}
955 onPress={() => {
956 if (browsePath.parentPath) {
957 void props.navigateToBrowsePath({
958 browseDirectoryPath: browsePath.parentPath,
959 });
960 }
961 }}
962 />
963 ) : null}
964 {visibleBrowseEntries.map((entry, index) => (
965 <ListRow
966 key={entry.fullPath}
967 title={entry.name}
968 icon={
969 <SymbolView
970 name="folder"
971 size={Platform.OS === "android" ? 24 : 17}
972 tintColorClassName="accent-icon-muted"
973 type="monochrome"
974 />
975 }
976 isFirst={index === 0 && !browsePath.canBrowseUp}
977 right={null}
978 onPress={() => {
979 void props.navigateToBrowsePath({
980 browseDirectoryPath: browsePath.directoryPath,
981 selectedDirectoryName: entry.name,
982 });
983 }}
984 />
985 ))}
986 </ListSection>
987 </>
988 );
990​
991export function AddProjectNewScreen(props: { readonly environmentId?: string | string[] }) {
992 const openNewTaskDraft = useOpenNewTaskDraft();
993 const navigation = useNavigation();
994 const environmentOptions = useEnvironmentOptions().filter(
995 (option) => option.newProjectsRoot !== null,
996 );
997 const [selectedEnvironmentId, setSelectedEnvironmentId] = useState(
998 () => stringParam(props.environmentId) as EnvironmentId | null,
999 );
1000 const environment = resolveAddProjectEnvironment(environmentOptions, selectedEnvironmentId);
1001 const createNew = useAtomCommand(projectEnvironment.createNew, { reportFailure: false });
1002 const publishRepository = useAtomCommand(sourceControlEnvironment.publishRepository, {
1003 reportFailure: false,
1004 });
1005 const discoveryState = useEnvironmentQuery(
1006 environment === null
1007 ? null
1008 : sourceControlEnvironment.discovery({
1009 environmentId: environment.environmentId,
1010 input: {},
1011 }),
1012 );
1013 const publishTargets = getNewProjectPublishTargets(discoveryState.data);
1014 const [name, setName] = useState("");
1015 const [publishes, setPublishes] = useState(false);
1016 const [publishKind, setPublishKind] = useState<SourceControlProviderKind | null>(null);
1017 const publishTarget = getNewProjectPublishTarget(publishTargets, publishKind);
1018 const [isSubmitting, setIsSubmitting] = useState(false);
1019 const [error, setError] = useState<string | null>(null);
1020 const trimmedName = name.trim();
1021 const pathPreview =
1022 environment?.newProjectsRoot != null
1023 ? getNewProjectPathPreview(environment.newProjectsRoot, trimmedName)
1024 : null;
1025​
1026 const showMachines =
1027 environmentOptions.length > 1 || (environment === null && environmentOptions.length > 0);
1028 const machineRows = showMachines ? (
1029 <ListSection>
1030 {environmentOptions.map((option, index) => {
1031 const selected = option.environmentId === environment?.environmentId;
1032 return (
1033 <ListRow
1034 key={option.environmentId}
1035 title={option.label}
1036 icon={
1037 <EnvironmentMachineSymbol
1038 kind={option.machine}
1039 size={Platform.OS === "android" ? 24 : 17}
1040 tintColorClassName="accent-icon"
1041 />
1043 selected={selected}
1044 disabled={isSubmitting}
1045 isFirst={index === 0}
1046 right={
1047 selected ? (
1048 <SymbolView
1049 name="checkmark"
1050 size={Platform.OS === "android" ? 20 : 14}
1051 tintColorClassName="accent-icon"
1052 type="monochrome"
1053 />
1054 ) : null
1056 onPress={() => setSelectedEnvironmentId(option.environmentId)}
1057 />
1058 );
1059 })}
1060 </ListSection>
1061 ) : null;
1062​
1063 // State lags a render behind, so a double tap could start a second create.
1064 const submittingRef = useRef(false);
1065 const submit = async () => {
1066 if (!environment || trimmedName.length === 0 || submittingRef.current) return;
1067 const originRoute = getActiveRoute(navigation);
1068 submittingRef.current = true;
1069 setError(null);
1070 setIsSubmitting(true);
1071 const result = await createNew({
1072 environmentId: environment.environmentId,
1073 input: { name: trimmedName },
1074 });
1075 if (AsyncResult.isFailure(result)) {
1076 submittingRef.current = false;
1077 setIsSubmitting(false);
1078 setError(errorMessage(Cause.squash(result.cause)));
1079 return;
1081 const { projectId, workspaceRoot, commitError } = result.value;
1082 if (commitError !== undefined) {
1083 Dialog.alert("Created without a first commit", commitError);
1085 if (publishes && publishTarget !== null) {
1086 void publishRepository({
1087 environmentId: environment.environmentId,
1088 input: {
1089 cwd: workspaceRoot,
1090 provider: publishTarget.definition.kind,
1091 repository: getNewProjectRepository(publishTarget, workspaceRoot),
1092 visibility: "private",
1093 },
1094 }).then((publishResult) => {
1095 if (AsyncResult.isFailure(publishResult)) {
1096 Dialog.alert(
1097 `Could not create the ${publishTarget.definition.label} repository`,
1098 errorMessage(Cause.squash(publishResult.cause)),
1099 );
1101 });
1103 // The draft screen resolves its project from the client store, so it
1104 // must not open before the create event has arrived.
1105 const project = await waitForProject(
1106 { environmentId: environment.environmentId, projectId },
1107 15_000,
1108 );
1109 submittingRef.current = false;
1110 setIsSubmitting(false);
1111 if (project === null) {
1112 setName("");
1113 setError(
1114 "The project was created but has not reached this device yet. It will appear in the project list once the connection catches up.",
1115 );
1116 return;
1118 openNewTaskDraft(
1120 environmentId: environment.environmentId,
1121 projectId,
1122 title: trimmedName,
1123 },
1124 originRoute,
1125 );
1126 };
1127​
1128 return (
1129 <AddProjectShell title="New project">
1130 {error ? <ErrorBanner message={error} /> : null}
1131 {environment ? (
1132 <>
1133 <TextInput
1134 className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
1135 value={name}
1136 onChangeText={setName}
1137 autoCorrect={false}
1138 autoFocus
1139 placeholder="Project name"
1140 returnKeyType="done"
1141 onSubmitEditing={() => void submit()}
1142 />
1143 {pathPreview !== null ? (
1144 <Text className="px-1 text-sm leading-snug text-foreground-muted" numberOfLines={2}>
1145 {trimmedName.length > 0
1146 ? `Creates ${pathPreview}`
1147 : `Goes in ${environment.newProjectsRoot}`}
1148 {showMachines ? ` on ${environment.label}` : null}
1149 </Text>
1150 ) : null}
1151 {machineRows}
1152 {publishTarget !== null ? (
1153 <ListSection>
1154 <ListRow
1155 title={`Create private repository on ${publishTarget.definition.label}`}
1156 subtitle={
1157 trimmedName.length > 0 && pathPreview !== null
1158 ? getNewProjectRepository(publishTarget, pathPreview)
1159 : publishTarget.owner
1161 icon={
1162 <SourceControlIcon
1163 icon={publishTarget.definition.icon}
1164 size={Platform.OS === "android" ? 24 : 18}
1165 colorClassName="accent-icon"
1166 />
1168 isFirst
1169 right={
1170 <ThemedSwitch
1171 accessibilityLabel={`Create private repository on ${publishTarget.definition.label}`}
1172 value={publishes}
1173 onValueChange={setPublishes}
1174 />
1176 onPress={() => setPublishes((current) => !current)}
1177 />
1178 {publishes && publishTargets.length > 1
1179 ? publishTargets.map((target) => {
1180 const selected = target.definition.kind === publishTarget.definition.kind;
1181 return (
1182 <ListRow
1183 key={target.definition.kind}
1184 title={target.definition.label}
1185 icon={
1186 <SourceControlIcon
1187 icon={target.definition.icon}
1188 size={Platform.OS === "android" ? 24 : 17}
1189 colorClassName="accent-icon"
1190 />
1192 selected={selected}
1193 disabled={isSubmitting}
1194 right={
1195 selected ? (
1196 <SymbolView
1197 name="checkmark"
1198 size={Platform.OS === "android" ? 20 : 14}
1199 tintColorClassName="accent-icon"
1200 type="monochrome"
1201 />
1202 ) : null
1204 onPress={() => setPublishKind(target.definition.kind)}
1205 />
1206 );
1207 })
1208 : null}
1209 </ListSection>
1210 ) : null}
1211 <PrimaryActionButton
1212 label="Create project"
1213 disabled={isSubmitting || trimmedName.length === 0}
1214 onPress={() => void submit()}
1215 loading={isSubmitting}
1216 />
1217 <ListSection>
1218 <ListRow
1219 title="Add existing project"
1220 subtitle="Open a folder or clone a repository"
1221 icon={
1222 <SymbolView
1223 name="folder.badge.plus"
1224 size={Platform.OS === "android" ? 24 : 17}
1225 tintColorClassName="accent-icon"
1226 type="monochrome"
1227 />
1229 isFirst
1230 onPress={() =>
1231 navigation.canGoBack()
1232 ? navigation.goBack()
1233 : navigation.dispatch(StackActions.replace("AddProject"))
1235 />
1236 </ListSection>
1237 </>
1238 ) : environmentOptions.length > 0 ? (
1239 machineRows
1240 ) : (
1241 <EmptyEnvironmentState />
1242 )}
1243 </AddProjectShell>
1244 );
1246​
1247export function AddProjectLocalFolderScreen(props: { readonly environmentId?: string | string[] }) {
1248 const environment = useEnvironmentFromParam(props.environmentId);
1249 const canCreateProject = useEnvironmentScope(
1250 environment?.environmentId ?? null,
1251 AuthOrchestrationOperateScope,
1252 );
1253 const createProject = useCreateProject(environment);
1254 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
1255 useBrowsePathInput(environment);
1256 const [isSubmitting, setIsSubmitting] = useState(false);
1257 const [error, setError] = useState<string | null>(null);
1258​
1259 const submitPath = async () => {
1260 if (!environment || isBrowseNavigating || isSubmitting) return;
1261 setError(null);
1262 const resolved = resolveAddProjectPath({
1263 rawPath: pathInput,
1264 currentProjectCwd: null,
1265 platform: environment.platform,
1266 });
1267 if (!resolved.ok) {
1268 setError(resolved.error);
1269 return;
1271​
1272 setIsSubmitting(true);
1273 const result = await createProject(resolved.path);
1274 if (result && AsyncResult.isFailure(result)) {
1275 setError(errorMessage(Cause.squash(result.cause)));
1277 setIsSubmitting(false);
1278 };
1279​
1280 return (
1281 <AddProjectShell title="Local folder">
1282 {error ? <ErrorBanner message={error} /> : null}
1283 {environment ? (
1284 <>
1285 {!canCreateProject ? (
1286 <ErrorBanner message="This connection cannot add projects." />
1287 ) : null}
1288 <ProjectPathInput value={pathInput} onChangeText={setPathInput} onSubmit={submitPath} />
1289 <PrimaryActionButton
1290 label="Add project"
1291 disabled={!canCreateProject || isBrowseNavigating || isSubmitting}
1292 onPress={submitPath}
1293 loading={isSubmitting}
1294 />
1295 <FolderBrowser
1296 environment={environment}
1297 navigateToBrowsePath={navigateToBrowsePath}
1298 pathInput={pathInput}
1299 setPathInput={setPathInput}
1300 />
1301 </>
1302 ) : (
1303 <EmptyEnvironmentState />
1304 )}
1305 </AddProjectShell>
1306 );
1308​
1309export function AddProjectDestinationScreen(props: {
1310 readonly environmentId?: string | string[];
1311 readonly remoteUrl?: string | string[];
1312 readonly repositoryTitle?: string | string[];
1313 readonly repositoryName?: string | string[];
1314 readonly prompt?: string | string[];
1315}) {
1316 const openNewTaskDraft = useOpenNewTaskDraft();
1317 const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
1318 reportFailure: false,
1319 });
1320 const startProjectClone = useAtomCommand(sourceControlEnvironment.startProjectClone, {
1321 reportFailure: false,
1322 });
1323 const navigation = useNavigation();
1324 const environment = useEnvironmentFromParam(props.environmentId);
1325 const canWriteSourceControl = useEnvironmentScope(
1326 environment?.environmentId ?? null,
1327 AuthSourceControlWriteScope,
1328 );
1329 const canCreateProject = useEnvironmentScope(
1330 environment?.environmentId ?? null,
1331 AuthOrchestrationOperateScope,
1332 );
1333 const canCloneProject = canWriteSourceControl && canCreateProject;
1334 const createProject = useCreateProject(environment);
1335 const remoteUrl = stringParam(props.remoteUrl);
1336 const repositoryTitle = stringParam(props.repositoryTitle);
1337 const prompt = stringParam(props.prompt);
1338 const repositoryName = stringParam(props.repositoryName)?.trim() ?? "";
1339 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = useBrowsePathInput(
1340 environment,
1341 repositoryName,
1342 );
1343 const [isSubmitting, setIsSubmitting] = useState(false);
1344 const [error, setError] = useState<string | null>(null);
1345​
1346 const submitPath = async () => {
1347 if (
1348 !environment ||
1349 !readEnvironmentScope(environment.environmentId, AuthSourceControlWriteScope) ||
1350 !readEnvironmentScope(environment.environmentId, AuthOrchestrationOperateScope) ||
1351 !remoteUrl ||
1352 isBrowseNavigating ||
1353 isSubmitting
1354 ) {
1355 return;
1357 setError(null);
1358 const resolved = resolveAddProjectPath({
1359 rawPath: pathInput,
1360 currentProjectCwd: null,
1361 platform: environment.platform,
1362 });
1363 if (!resolved.ok) {
1364 setError(resolved.error);
1365 return;
1367​
1368 const originRoute = getActiveRoute(navigation);
1369 setIsSubmitting(true);
1370 if (environment.supportsCloneTracking) {
1371 const projectId = ProjectId.make(uuidv4());
1372 const title = inferProjectTitleFromPath(resolved.path);
1373 const startResult = await startProjectClone({
1374 environmentId: environment.environmentId,
1375 input: {
1376 projectId,
1377 title,
1378 createdAt: new Date().toISOString(),
1379 remoteUrl,
1380 destinationPath: resolved.path,
1381 },
1382 });
1383 if (AsyncResult.isFailure(startResult)) {
1384 setError(errorMessage(Cause.squash(startResult.cause)));
1385 } else {
1386 // Wait for the create event; the client store otherwise falls back to the project picker and loses clone controls.
1387 const project = await waitForProject(
1388 { environmentId: environment.environmentId, projectId },
1389 15_000,
1390 );
1391 if (project === null) {
1392 setError(
1393 "The project was created but has not reached this device yet. It will appear in the project list once the connection catches up.",
1394 );
1395 } else {
1396 openNewTaskDraft(
1398 environmentId: environment.environmentId,
1399 projectId,
1400 title,
1401 cloning: "1",
1402 ...(prompt
1403 ? await draftWithPrompt(environment.environmentId, projectId, prompt).then(
1404 (draftId) => ({ draftId }),
1405 () => ({}),
1407 : {}),
1408 },
1409 originRoute,
1410 );
1413 setIsSubmitting(false);
1414 return;
1416 const cloneResult = await cloneRepository({
1417 environmentId: environment.environmentId,
1418 input: {
1419 remoteUrl,
1420 destinationPath: resolved.path,
1421 },
1422 });
1423 if (AsyncResult.isFailure(cloneResult)) {
1424 setError(errorMessage(Cause.squash(cloneResult.cause)));
1425 } else {
1426 const createResult = await createProject(cloneResult.value.cwd, originRoute);
1427 if (createResult && AsyncResult.isFailure(createResult)) {
1428 setError(errorMessage(Cause.squash(createResult.cause)));
1431 setIsSubmitting(false);
1432 };
1433​
1434 return (
1435 <AddProjectShell title="Clone destination">
1436 {error ? <ErrorBanner message={error} /> : null}
1437 {repositoryTitle ? (
1438 <View className="rounded-[24px] bg-grouped-card px-4 py-3">
1439 <Text className="text-base font-t3-bold">{repositoryTitle}</Text>
1440 <Text className="mt-0.5 text-xs text-foreground-muted" numberOfLines={2}>
1441 {remoteUrl}
1442 </Text>
1443 </View>
1444 ) : null}
1445 {environment ? (
1446 <>
1447 <ProjectPathInput value={pathInput} onChangeText={setPathInput} onSubmit={submitPath} />
1448 <PrimaryActionButton
1449 label="Clone project"
1450 disabled={!canCloneProject || isBrowseNavigating || isSubmitting || !remoteUrl}
1451 onPress={submitPath}
1452 loading={isSubmitting}
1453 />
1454 {!canCloneProject ? (
1455 <Text className="text-sm text-foreground-muted">
1456 This connection cannot clone projects.
1457 </Text>
1458 ) : null}
1459 <FolderBrowser
1460 environment={environment}
1461 navigateToBrowsePath={navigateToBrowsePath}
1462 pathInput={pathInput}
1463 setPathInput={setPathInput}
1464 pinnedDirectoryName={repositoryName}
1465 />
1466 </>
1467 ) : (
1468 <EmptyEnvironmentState />
1469 )}
1470 </AddProjectShell>
1471 );