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

AddProjectScreen.tsx

1,478 lines50.9 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 { suggestAppAccessForRemote } from "./suggestAppAccess";
91import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
92import {
93 useRemoteConnectionStatus,
94 useRemoteEnvironmentRuntime,
95 useSavedRemoteConnections,
96} from "../../state/use-remote-environment-registry";
97import { resolveAddProjectEnvironment } from "./AddProjectScreen.logic";
98import {
99 createNewTaskDraft,
100 setComposerDraftText,
101 waitForComposerDraftsLoaded,
102} from "../../state/use-composer-drafts";
103​
104interface EnvironmentOption {
105 readonly environmentId: EnvironmentId;
106 readonly label: string;
107 readonly platform: string;
108 readonly machine: EnvironmentMachineKind;
109 readonly baseDirectory: string | null;
110 readonly newProjectsRoot: string | null;
111 readonly connectionState: EnvironmentConnectionPhase;
112 readonly connectionError: string | null;
113 readonly connectionErrorTraceId: string | null;
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 };
405 });
406 return Arr.sort(
407 options.filter(
408 (environment) =>
409 canCreateProjectInEnvironment(environment.connectionState) ||
410 environment.environmentId === selectedEnvironmentId,
411 ),
412 environmentOptionOrder,
413 );
414 })();
416​
417function useSelectedEnvironment(requestedEnvironmentId: EnvironmentId | null): {
418 readonly environmentOptions: ReadonlyArray<EnvironmentOption>;
419 readonly selectedEnvironment: EnvironmentOption | null;
420 readonly setSelectedEnvironmentId: (environmentId: EnvironmentId) => void;
421} {
422 const [selectedEnvironmentId, setSelectedEnvironmentId] = useState(requestedEnvironmentId);
423 const [previousRequest, setPreviousRequest] = useState(requestedEnvironmentId);
424 if (previousRequest !== requestedEnvironmentId) {
425 setPreviousRequest(requestedEnvironmentId);
426 setSelectedEnvironmentId(requestedEnvironmentId);
427 }
428 const environmentOptions = useEnvironmentOptions(selectedEnvironmentId);
429 const selectedEnvironment =
430 environmentOptions.find((environment) => environment.environmentId === selectedEnvironmentId) ??
431 environmentOptions.find((environment) =>
432 canCreateProjectInEnvironment(environment.connectionState),
433 ) ??
434 null;
435​
436 return {
437 environmentOptions,
438 selectedEnvironment,
439 setSelectedEnvironmentId,
440 };
442​
443function EmptyEnvironmentState() {
444 const navigation = useNavigation();
445​
446 return (
447 <View className="items-center gap-3 rounded-2xl bg-grouped-card px-5 py-8">
448 <Text className="text-center text-lg font-t3-bold">Environment unavailable</Text>
449 <Text className="text-center text-sm leading-normal text-foreground-muted">
450 Start or reconnect an environment before adding a project.
451 </Text>
452 <View className="mt-1">
453 <Button
454 label="Add environment"
455 tone="primary"
456 onPress={() => navigation.dispatch(StackActions.replace("ConnectionsNew"))}
457 />
458 </View>
459 </View>
460 );
462​
463function SourceControlRow(props: {
464 readonly source: AddProjectRemoteSource;
465 readonly selectedEnvironmentId: EnvironmentId;
466 readonly ready: boolean;
467 readonly hint: string;
468 readonly isFirst: boolean;
469}) {
470 const navigation = useNavigation();
471 const title =
472 props.source === "url" ? "Git URL" : `${addProjectRemoteSourceLabel(props.source)} repository`;
473 const subtitle =
474 props.source === "url"
475 ? "Clone from a remote URL"
476 : `Clone ${addProjectRemoteSourceLabel(props.source)} ${props.hint}`;
477 const icon =
478 props.source === "url" ? (
479 <SymbolView
480 name="link"
481 size={Platform.OS === "android" ? 24 : 17}
482 tintColorClassName="accent-icon"
483 type="monochrome"
484 />
485 ) : (
486 <SourceControlIcon
487 icon={sourceControlClients.get(props.source).icon}
488 size={Platform.OS === "android" ? 24 : 18}
489 colorClassName="accent-icon"
490 />
491 );
492​
493 if (!props.ready) {
494 return (
495 <ListRow title={title} subtitle={props.hint} icon={icon} disabled isFirst={props.isFirst} />
496 );
497 }
498​
499 return (
500 <ListRow
501 title={title}
502 subtitle={subtitle}
503 icon={icon}
504 isFirst={props.isFirst}
505 onPress={() =>
506 navigation.dispatch(
507 StackActions.push("AddProjectRepository", {
508 environmentId: props.selectedEnvironmentId,
509 source: props.source,
510 }),
511 )
512 }
513 />
514 );
516​
517export function AddProjectSourceScreen(props: { readonly environmentId?: string | string[] }) {
518 const navigation = useNavigation();
519 const { environmentOptions, selectedEnvironment, setSelectedEnvironmentId } =
520 useSelectedEnvironment(stringParam(props.environmentId) as EnvironmentId | null);
521 const canWriteSourceControl = useEnvironmentScope(
522 selectedEnvironment?.environmentId ?? null,
523 AuthSourceControlWriteScope,
524 );
525 const canCreateProject = useEnvironmentScope(
526 selectedEnvironment?.environmentId ?? null,
527 AuthOrchestrationOperateScope,
528 );
529 const isConnected = canCreateProjectInEnvironment(selectedEnvironment?.connectionState);
530 const canCloneProject = isConnected && canWriteSourceControl && canCreateProject;
531 const discoveryState = useEnvironmentQuery(
532 selectedEnvironment === null || !isConnected
533 ? null
534 : sourceControlEnvironment.discovery({
535 environmentId: selectedEnvironment.environmentId,
536 input: {},
537 }),
538 );
539 const readiness = buildAddProjectRemoteSourceReadiness(discoveryState.data);
540​
541 return (
542 <AddProjectShell title="Add project">
543 {selectedEnvironment === null ? <EmptyEnvironmentState /> : null}
544​
545 {environmentOptions.length > 1 || (selectedEnvironment !== null && !isConnected) ? (
546 <>
547 <SectionTitle>Environments</SectionTitle>
548 <ListSection>
549 {environmentOptions.map((environment, index) => (
550 <ListRow
551 key={environment.environmentId}
552 title={environment.label}
553 subtitle={
554 canCreateProjectInEnvironment(environment.connectionState)
555 ? undefined
556 : connectionStatusText({
557 phase: environment.connectionState,
558 error: environment.connectionError,
559 traceId: environment.connectionErrorTraceId,
560 })
561 }
562 icon={
563 <EnvironmentMachineSymbol
564 kind={environment.machine}
565 size={Platform.OS === "android" ? 24 : 17}
566 tintColorClassName="accent-icon"
567 />
568 }
569 selected={environment.environmentId === selectedEnvironment?.environmentId}
570 disabled={!canCreateProjectInEnvironment(environment.connectionState)}
571 isFirst={index === 0}
572 right={
573 environment.environmentId === selectedEnvironment?.environmentId ? (
574 <SymbolView
575 name="checkmark"
576 size={Platform.OS === "android" ? 20 : 14}
577 tintColorClassName="accent-icon"
578 type="monochrome"
579 />
580 ) : null
581 }
582 onPress={() => setSelectedEnvironmentId(environment.environmentId)}
583 />
584 ))}
585 </ListSection>
586 </>
587 ) : null}
588​
589 {selectedEnvironment ? (
590 <>
591 <ListSection>
592 {selectedEnvironment.newProjectsRoot !== null ? (
593 <ListRow
594 title="New project"
595 subtitle="Start a new Git repository from a name"
596 disabled={!isConnected}
597 icon={
598 <SymbolView
599 name="plus"
600 size={Platform.OS === "android" ? 24 : 17}
601 tintColorClassName="accent-icon"
602 type="monochrome"
603 />
604 }
605 isFirst
606 onPress={() =>
607 navigation.dispatch(
608 StackActions.push("AddProjectNew", {
609 environmentId: selectedEnvironment.environmentId,
610 }),
611 )
612 }
613 />
614 ) : null}
615 <ListRow
616 title="Local folder"
617 subtitle={
618 canCreateProject
619 ? "Browse a folder on disk"
620 : "This connection cannot add projects."
621 }
622 icon={
623 <SymbolView
624 name="folder.badge.plus"
625 size={Platform.OS === "android" ? 24 : 17}
626 tintColorClassName="accent-icon"
627 type="monochrome"
628 />
629 }
630 isFirst={selectedEnvironment.newProjectsRoot === null}
631 disabled={!isConnected || !canCreateProject}
632 onPress={() =>
633 navigation.dispatch(
634 StackActions.push("AddProjectLocal", {
635 environmentId: selectedEnvironment.environmentId,
636 }),
637 )
638 }
639 />
640 {(["url", ...sortAddProjectProviderSources(readiness)] as AddProjectRemoteSource[]).map(
641 (candidate) => (
642 <SourceControlRow
643 key={candidate}
644 source={candidate}
645 selectedEnvironmentId={selectedEnvironment.environmentId}
646 ready={canCloneProject && readiness(candidate).ready}
647 hint={
648 !canCloneProject
649 ? "This connection cannot clone projects."
650 : readiness(candidate).ready
651 ? addProjectRemoteSourcePathHint(candidate)
652 : (readiness(candidate).hint ?? "")
653 }
654 isFirst={false}
655 />
656 ),
657 )}
658 </ListSection>
659 {discoveryState.isPending ? (
660 <AppActivityIndicator colorClassName="accent-icon-muted" />
661 ) : null}
662 </>
663 ) : null}
664 </AddProjectShell>
665 );
667​
668function getActiveRoute(navigation: {
669 getState: () => NavigationState<ParamListBase> | undefined;
670}) {
671 const state = navigation.getState();
672 return state?.routes[state.index];
674​
675function useOpenNewTaskDraft() {
676 const navigation = useNavigation<NativeStackNavigationProp<ReactNavigation.RootParamList>>();
677 const selectDetail = useSelectWorkspaceDetail();
678 return (
679 params: {
680 environmentId: EnvironmentId;
681 projectId: ProjectId;
682 title: string;
683 cloning?: "1";
684 draftId?: string;
685 },
686 originRoute: NavigationState<ParamListBase>["routes"][number] | undefined,
687 ) => {
688 const activeRoute = getActiveRoute(navigation);
689 // A warm link can change the task without replacing its native route key.
690 if (
691 !originRoute ||
692 activeRoute?.key !== originRoute.key ||
693 activeRoute.name !== originRoute.name ||
694 activeRoute.params !== originRoute.params
695 )
696 return;
697 selectDetail({ name: "Thread", params: { draft: params } });
698 };
700​
701async function draftWithPrompt(
702 environmentId: EnvironmentId,
703 projectId: ProjectId,
704 prompt: string,
705): Promise<string> {
706 await waitForComposerDraftsLoaded();
707 const draftId = createNewTaskDraft({ environmentId, projectId });
708 setComposerDraftText(draftId, prompt);
709 return draftId;
711​
712function useCreateProject(environment: EnvironmentOption | null) {
713 const openNewTaskDraft = useOpenNewTaskDraft();
714 const navigation = useNavigation();
715 const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false });
716 const updateProject = useAtomCommand(projectEnvironment.update, {
717 label: "project unarchive",
718 });
719 const projects = useProjects();
720​
721 return async (workspaceRoot: string, originRoute = getActiveRoute(navigation)) => {
722 if (
723 !environment ||
724 !canCreateProjectInEnvironment(environment.connectionState) ||
725 !readEnvironmentScope(environment.environmentId, AuthOrchestrationOperateScope)
726 ) {
727 Dialog.alert(
728 "Project not added",
729 `This connection cannot add projects right now. Any existing files remain at ${workspaceRoot}.`,
730 );
731 return;
732 }
733​
734 const existing = findExistingAddProject({
735 projects,
736 environmentId: environment.environmentId,
737 path: workspaceRoot,
738 });
739 if (existing) {
740 // Adding an archived project's folder again brings the project back.
741 const unarchived =
742 existing.archivedAt == null ||
743 (
744 await updateProject({
745 environmentId: existing.environmentId,
746 input: { projectId: existing.id, archived: false },
747 })
748 )._tag === "Success";
749 Dialog.alert(
750 "Project already exists",
751 unarchived ? existing.title : `${existing.title} is still archived. Try again later.`,
752 );
753 openNewTaskDraft(
754 {
755 environmentId: existing.environmentId,
756 projectId: existing.id,
757 title: existing.title,
758 },
759 originRoute,
760 );
761 return;
762 }
763​
764 const projectId = ProjectId.make(uuidv4());
765 const command = buildProjectCreateCommand({
766 commandId: CommandId.make(uuidv4()),
767 projectId,
768 workspaceRoot,
769 });
770 const result = await createProject({
771 environmentId: environment.environmentId,
772 input: command,
773 });
774 if (AsyncResult.isFailure(result)) {
775 return result;
776 }
777 // A successful command can precede its project in the client store. The
778 // draft treats a missing project as a reason to return to the chooser.
779 const project = await waitForProject(
780 { environmentId: environment.environmentId, projectId },
781 15_000,
782 );
783 if (project === null) {
784 Dialog.alert(
785 "Project added",
786 "The project was created but has not reached this device yet. It will appear in the project list once the connection catches up.",
787 );
788 return result;
789 }
790 openNewTaskDraft(
791 {
792 environmentId: environment.environmentId,
793 projectId,
794 title: inferProjectTitleFromPath(workspaceRoot),
795 },
796 originRoute,
797 );
798 return result;
799 };
801​
802function useEnvironmentFromParam(
803 environmentIdParam: string | string[] | undefined,
804): EnvironmentOption | null {
805 const environmentOptions = useEnvironmentOptions();
806 const environmentId = stringParam(environmentIdParam) as EnvironmentId | null;
807 return resolveAddProjectEnvironment(environmentOptions, environmentId);
809​
810export function AddProjectRepositoryScreen(props: {
811 readonly environmentId?: string | string[];
812 readonly source?: string | string[];
813}) {
814 const lookupRepositoryQuery = useAtomQueryRunner(sourceControlEnvironment.repository, {
815 reportFailure: false,
816 });
817 const navigation = useNavigation();
818 const environment = useEnvironmentFromParam(props.environmentId);
819 const source = sourceFromParam(props.source);
820 const [repositoryInput, setRepositoryInput] = useState("");
821 const [isSubmitting, setIsSubmitting] = useState(false);
822 const [error, setError] = useState<string | null>(null);
823​
824 const lookupRepository = async () => {
825 if (!environment || repositoryInput.trim().length === 0 || isSubmitting) return;
826 setError(null);
827 setIsSubmitting(true);
828 const provider = addProjectRemoteSourceProvider(source);
829 if (!provider) {
830 const remoteUrl = normalizePastedCloneUrl(repositoryInput);
831 navigation.dispatch(
832 StackActions.push("AddProjectDestination", {
833 environmentId: environment.environmentId,
834 source,
835 remoteUrl,
836 repositoryTitle: remoteUrl,
837 repositoryName: getCloneDirectoryName(remoteUrl),
838 }),
839 );
840 setIsSubmitting(false);
841 return;
842 }
843​
844 const result = await lookupRepositoryQuery({
845 environmentId: environment.environmentId,
846 input: {
847 provider,
848 repository: repositoryInput.trim(),
849 },
850 });
851 if (AsyncResult.isFailure(result)) {
852 setError(errorMessage(Cause.squash(result.cause)));
853 } else {
854 const repository = result.value;
855 navigation.dispatch(
856 StackActions.push("AddProjectDestination", {
857 environmentId: environment.environmentId,
858 source,
859 remoteUrl: getDefaultCloneUrl(repository),
860 repositoryTitle: repository.nameWithOwner,
861 repositoryName: getCloneDirectoryName(repository.nameWithOwner),
862 }),
863 );
864 }
865 setIsSubmitting(false);
866 };
867​
868 return (
869 <AddProjectShell title={source === "url" ? "Git URL" : addProjectRemoteSourceLabel(source)}>
870 {error ? <ErrorBanner message={error} /> : null}
871 {environment ? (
872 <>
873 <TextInput
874 className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
875 value={repositoryInput}
876 onChangeText={setRepositoryInput}
877 autoCapitalize="none"
878 autoCorrect={false}
879 placeholder={
880 source === "url"
881 ? (defaultHostCloneUrl("org/repo") ?? "https://example.com/org/repo.git")
882 : addProjectRemoteSourcePathHint(source)
883 }
884 returnKeyType="next"
885 onSubmitEditing={() => void lookupRepository()}
886 />
887 <PrimaryActionButton
888 label={source === "url" ? "Continue" : "Lookup repository"}
889 disabled={isSubmitting || repositoryInput.trim().length === 0}
890 onPress={() => void lookupRepository()}
891 loading={isSubmitting}
892 />
893 </>
894 ) : (
895 <EmptyEnvironmentState />
896 )}
897 </AddProjectShell>
898 );
900​
901function FolderBrowser(props: {
902 readonly environment: EnvironmentOption;
903 readonly pathInput: string;
904 readonly setPathInput: (path: string) => void;
905 readonly navigateToBrowsePath: (input: {
906 readonly browseDirectoryPath: string;
907 readonly selectedDirectoryName?: string;
908 }) => Promise<boolean>;
909 readonly pinnedDirectoryName?: string;
910}) {
911 const browsePath = getFilesystemBrowsePath(props.pathInput, props.environment.platform);
912 const browseInput =
913 browsePath.directoryPath.length > 0 ? { partialPath: browsePath.directoryPath } : null;
914 const fileAccessSession = useEnvironmentQuery(
915 environmentSession.sessionStateAtom(props.environment.environmentId),
916 );
917 const fileEnvironment = useEnvironmentPresentation(props.environment.environmentId);
918 const fileAccess = resolveFilesystemReadAccess({
919 isCatalogReady: fileEnvironment.isReady,
920 connection: fileEnvironment.presentation?.connection ?? null,
921 session: fileAccessSession.data,
922 sessionError: fileAccessSession.error,
923 });
924 const { canReadFiles } = fileAccess;
925 const browseState = useEnvironmentQuery(
926 !canReadFiles || browseInput === null
927 ? null
928 : filesystemEnvironment.browse({
929 environmentId: props.environment.environmentId,
930 input: browseInput,
931 }),
932 );
933 const pinnedDirectoryName = props.pinnedDirectoryName ?? "";
934 const pinnedDirectoryMatches = isWindowsPlatform(props.environment.platform)
935 ? browsePath.filterQuery.toLowerCase() === pinnedDirectoryName.toLowerCase()
936 : browsePath.filterQuery === pinnedDirectoryName;
937 const browseFilterQuery = pinnedDirectoryMatches ? "" : browsePath.filterQuery;
938 const { visibleEntries: visibleBrowseEntries } = filterFilesystemBrowseEntries(
939 browseState.data?.entries ?? [],
940 browseFilterQuery,
941 );
942​
943 return (
944 <>
945 <SectionTitle>Browse folders</SectionTitle>
946 {!canReadFiles && !fileAccess.isPending ? (
947 <ErrorBanner message={fileAccess.error ?? "This connection cannot browse host folders."} />
948 ) : null}
949 {browseState.error ? <ErrorBanner message={browseState.error} /> : null}
950 <ListSection>
951 {fileAccess.isPending || (browseState.isPending && browseState.data === null) ? (
952 <View className="items-center py-5">
953 <AppActivityIndicator colorClassName="accent-icon-muted" />
954 </View>
955 ) : null}
956 {browsePath.canBrowseUp ? (
957 <ListRow
958 title=".."
959 icon={
960 <SymbolView
961 name="arrow.turn.left.up"
962 size={Platform.OS === "android" ? 24 : 17}
963 tintColorClassName="accent-icon-muted"
964 type="monochrome"
965 />
966 }
967 isFirst
968 right={null}
969 onPress={() => {
970 if (browsePath.parentPath) {
971 void props.navigateToBrowsePath({
972 browseDirectoryPath: browsePath.parentPath,
973 });
974 }
975 }}
976 />
977 ) : null}
978 {visibleBrowseEntries.map((entry, index) => (
979 <ListRow
980 key={entry.fullPath}
981 title={entry.name}
982 icon={
983 <SymbolView
984 name="folder"
985 size={Platform.OS === "android" ? 24 : 17}
986 tintColorClassName="accent-icon-muted"
987 type="monochrome"
988 />
989 }
990 isFirst={index === 0 && !browsePath.canBrowseUp}
991 right={null}
992 onPress={() => {
993 void props.navigateToBrowsePath({
994 browseDirectoryPath: browsePath.directoryPath,
995 selectedDirectoryName: entry.name,
996 });
997 }}
998 />
999 ))}
1000 </ListSection>
1001 </>
1002 );
1004​
1005export function AddProjectNewScreen(props: { readonly environmentId?: string | string[] }) {
1006 const openNewTaskDraft = useOpenNewTaskDraft();
1007 const navigation = useNavigation();
1008 const environmentOptions = useEnvironmentOptions().filter(
1009 (option) => option.newProjectsRoot !== null,
1010 );
1011 const [selectedEnvironmentId, setSelectedEnvironmentId] = useState(
1012 () => stringParam(props.environmentId) as EnvironmentId | null,
1013 );
1014 const environment = resolveAddProjectEnvironment(environmentOptions, selectedEnvironmentId);
1015 const createNew = useAtomCommand(projectEnvironment.createNew, { reportFailure: false });
1016 const checkPublishedAppAccess = useAtomCommand(sourceControlEnvironment.checkAppAccess, {
1017 reportFailure: false,
1018 reportDefect: false,
1019 });
1020 const publishRepository = useAtomCommand(sourceControlEnvironment.publishRepository, {
1021 reportFailure: false,
1022 });
1023 const discoveryState = useEnvironmentQuery(
1024 environment === null
1025 ? null
1026 : sourceControlEnvironment.discovery({
1027 environmentId: environment.environmentId,
1028 input: {},
1029 }),
1030 );
1031 const publishTargets = getNewProjectPublishTargets(discoveryState.data);
1032 const [name, setName] = useState("");
1033 const [publishes, setPublishes] = useState(false);
1034 const [publishKind, setPublishKind] = useState<SourceControlProviderKind | null>(null);
1035 const publishTarget = getNewProjectPublishTarget(publishTargets, publishKind);
1036 const [isSubmitting, setIsSubmitting] = useState(false);
1037 const [error, setError] = useState<string | null>(null);
1038 const trimmedName = name.trim();
1039 const pathPreview =
1040 environment?.newProjectsRoot != null
1041 ? getNewProjectPathPreview(environment.newProjectsRoot, trimmedName)
1042 : null;
1043​
1044 const showMachines =
1045 environmentOptions.length > 1 || (environment === null && environmentOptions.length > 0);
1046 const machineRows = showMachines ? (
1047 <ListSection>
1048 {environmentOptions.map((option, index) => {
1049 const selected = option.environmentId === environment?.environmentId;
1050 return (
1051 <ListRow
1052 key={option.environmentId}
1053 title={option.label}
1054 icon={
1055 <EnvironmentMachineSymbol
1056 kind={option.machine}
1057 size={Platform.OS === "android" ? 24 : 17}
1058 tintColorClassName="accent-icon"
1059 />
1061 selected={selected}
1062 disabled={isSubmitting}
1063 isFirst={index === 0}
1064 right={
1065 selected ? (
1066 <SymbolView
1067 name="checkmark"
1068 size={Platform.OS === "android" ? 20 : 14}
1069 tintColorClassName="accent-icon"
1070 type="monochrome"
1071 />
1072 ) : null
1074 onPress={() => setSelectedEnvironmentId(option.environmentId)}
1075 />
1076 );
1077 })}
1078 </ListSection>
1079 ) : null;
1080​
1081 // State lags a render behind, so a double tap could start a second create.
1082 const submittingRef = useRef(false);
1083 const submit = async () => {
1084 if (!environment || trimmedName.length === 0 || submittingRef.current) return;
1085 const originRoute = getActiveRoute(navigation);
1086 submittingRef.current = true;
1087 setError(null);
1088 setIsSubmitting(true);
1089 const result = await createNew({
1090 environmentId: environment.environmentId,
1091 input: { name: trimmedName },
1092 });
1093 if (AsyncResult.isFailure(result)) {
1094 submittingRef.current = false;
1095 setIsSubmitting(false);
1096 setError(errorMessage(Cause.squash(result.cause)));
1097 return;
1099 const { projectId, workspaceRoot, commitError } = result.value;
1100 if (commitError !== undefined) {
1101 Dialog.alert("Created without a first commit", commitError);
1103 if (publishes && publishTarget !== null) {
1104 void publishRepository({
1105 environmentId: environment.environmentId,
1106 input: {
1107 cwd: workspaceRoot,
1108 provider: publishTarget.definition.kind,
1109 repository: getNewProjectRepository(publishTarget, workspaceRoot),
1110 visibility: "private",
1111 },
1112 }).then((publishResult) => {
1113 if (AsyncResult.isFailure(publishResult)) {
1114 Dialog.alert(
1115 `Could not create the ${publishTarget.definition.label} repository`,
1116 errorMessage(Cause.squash(publishResult.cause)),
1117 );
1118 } else {
1119 void suggestAppAccessForRemote(
1120 checkPublishedAppAccess,
1121 environment.environmentId,
1122 publishResult.value.remoteUrl,
1123 );
1125 });
1127 // The draft screen resolves its project from the client store, so it
1128 // must not open before the create event has arrived.
1129 const project = await waitForProject(
1130 { environmentId: environment.environmentId, projectId },
1131 15_000,
1132 );
1133 submittingRef.current = false;
1134 setIsSubmitting(false);
1135 if (project === null) {
1136 setName("");
1137 setError(
1138 "The project was created but has not reached this device yet. It will appear in the project list once the connection catches up.",
1139 );
1140 return;
1142 openNewTaskDraft(
1144 environmentId: environment.environmentId,
1145 projectId,
1146 title: trimmedName,
1147 },
1148 originRoute,
1149 );
1150 };
1151​
1152 return (
1153 <AddProjectShell title="New project">
1154 {error ? <ErrorBanner message={error} /> : null}
1155 {environment ? (
1156 <>
1157 <TextInput
1158 className="h-12 min-h-12 rounded-[24px] px-4 py-0 text-base leading-snug"
1159 value={name}
1160 onChangeText={setName}
1161 autoCorrect={false}
1162 autoFocus
1163 placeholder="Project name"
1164 returnKeyType="done"
1165 onSubmitEditing={() => void submit()}
1166 />
1167 {pathPreview !== null ? (
1168 <Text className="px-1 text-sm leading-snug text-foreground-muted" numberOfLines={2}>
1169 {trimmedName.length > 0
1170 ? `Creates ${pathPreview}`
1171 : `Goes in ${environment.newProjectsRoot}`}
1172 {showMachines ? ` on ${environment.label}` : null}
1173 </Text>
1174 ) : null}
1175 {machineRows}
1176 {publishTarget !== null ? (
1177 <ListSection>
1178 <ListRow
1179 title={`Create private repository on ${publishTarget.definition.label}`}
1180 subtitle={
1181 trimmedName.length > 0 && pathPreview !== null
1182 ? getNewProjectRepository(publishTarget, pathPreview)
1183 : publishTarget.owner
1185 icon={
1186 <SourceControlIcon
1187 icon={publishTarget.definition.icon}
1188 size={Platform.OS === "android" ? 24 : 18}
1189 colorClassName="accent-icon"
1190 />
1192 isFirst
1193 right={
1194 <ThemedSwitch
1195 accessibilityLabel={`Create private repository on ${publishTarget.definition.label}`}
1196 value={publishes}
1197 onValueChange={setPublishes}
1198 />
1200 onPress={() => setPublishes((current) => !current)}
1201 />
1202 {publishes && publishTargets.length > 1
1203 ? publishTargets.map((target) => {
1204 const selected = target.definition.kind === publishTarget.definition.kind;
1205 return (
1206 <ListRow
1207 key={target.definition.kind}
1208 title={target.definition.label}
1209 icon={
1210 <SourceControlIcon
1211 icon={target.definition.icon}
1212 size={Platform.OS === "android" ? 24 : 17}
1213 colorClassName="accent-icon"
1214 />
1216 selected={selected}
1217 disabled={isSubmitting}
1218 right={
1219 selected ? (
1220 <SymbolView
1221 name="checkmark"
1222 size={Platform.OS === "android" ? 20 : 14}
1223 tintColorClassName="accent-icon"
1224 type="monochrome"
1225 />
1226 ) : null
1228 onPress={() => setPublishKind(target.definition.kind)}
1229 />
1230 );
1231 })
1232 : null}
1233 </ListSection>
1234 ) : null}
1235 <PrimaryActionButton
1236 label="Create project"
1237 disabled={isSubmitting || trimmedName.length === 0}
1238 onPress={() => void submit()}
1239 loading={isSubmitting}
1240 />
1241 <ListSection>
1242 <ListRow
1243 title="Add existing project"
1244 subtitle="Open a folder or clone a repository"
1245 icon={
1246 <SymbolView
1247 name="folder.badge.plus"
1248 size={Platform.OS === "android" ? 24 : 17}
1249 tintColorClassName="accent-icon"
1250 type="monochrome"
1251 />
1253 isFirst
1254 onPress={() =>
1255 navigation.canGoBack()
1256 ? navigation.goBack()
1257 : navigation.dispatch(StackActions.replace("AddProject"))
1259 />
1260 </ListSection>
1261 </>
1262 ) : environmentOptions.length > 0 ? (
1263 machineRows
1264 ) : (
1265 <EmptyEnvironmentState />
1266 )}
1267 </AddProjectShell>
1268 );
1270​
1271export function AddProjectLocalFolderScreen(props: { readonly environmentId?: string | string[] }) {
1272 const environment = useEnvironmentFromParam(props.environmentId);
1273 const canCreateProject = useEnvironmentScope(
1274 environment?.environmentId ?? null,
1275 AuthOrchestrationOperateScope,
1276 );
1277 const createProject = useCreateProject(environment);
1278 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
1279 useBrowsePathInput(environment);
1280 const [isSubmitting, setIsSubmitting] = useState(false);
1281 const [error, setError] = useState<string | null>(null);
1282​
1283 const submitPath = async () => {
1284 if (!environment || isBrowseNavigating || isSubmitting) return;
1285 setError(null);
1286 const resolved = resolveAddProjectPath({
1287 rawPath: pathInput,
1288 currentProjectCwd: null,
1289 platform: environment.platform,
1290 });
1291 if (!resolved.ok) {
1292 setError(resolved.error);
1293 return;
1295​
1296 setIsSubmitting(true);
1297 const result = await createProject(resolved.path);
1298 if (result && AsyncResult.isFailure(result)) {
1299 setError(errorMessage(Cause.squash(result.cause)));
1301 setIsSubmitting(false);
1302 };
1303​
1304 return (
1305 <AddProjectShell title="Local folder">
1306 {error ? <ErrorBanner message={error} /> : null}
1307 {environment ? (
1308 <>
1309 {!canCreateProject ? (
1310 <ErrorBanner message="This connection cannot add projects." />
1311 ) : null}
1312 <ProjectPathInput value={pathInput} onChangeText={setPathInput} onSubmit={submitPath} />
1313 <PrimaryActionButton
1314 label="Add project"
1315 disabled={!canCreateProject || isBrowseNavigating || isSubmitting}
1316 onPress={submitPath}
1317 loading={isSubmitting}
1318 />
1319 <FolderBrowser
1320 environment={environment}
1321 navigateToBrowsePath={navigateToBrowsePath}
1322 pathInput={pathInput}
1323 setPathInput={setPathInput}
1324 />
1325 </>
1326 ) : (
1327 <EmptyEnvironmentState />
1328 )}
1329 </AddProjectShell>
1330 );
1332​
1333export function AddProjectDestinationScreen(props: {
1334 readonly environmentId?: string | string[];
1335 readonly remoteUrl?: string | string[];
1336 readonly repositoryTitle?: string | string[];
1337 readonly repositoryName?: string | string[];
1338 readonly prompt?: string | string[];
1339}) {
1340 const openNewTaskDraft = useOpenNewTaskDraft();
1341 const startProjectClone = useAtomCommand(sourceControlEnvironment.startProjectClone, {
1342 reportFailure: false,
1343 });
1344 const checkAppAccess = useAtomCommand(sourceControlEnvironment.checkAppAccess, {
1345 reportFailure: false,
1346 reportDefect: false,
1347 });
1348 const navigation = useNavigation();
1349 const environment = useEnvironmentFromParam(props.environmentId);
1350 const canWriteSourceControl = useEnvironmentScope(
1351 environment?.environmentId ?? null,
1352 AuthSourceControlWriteScope,
1353 );
1354 const canCreateProject = useEnvironmentScope(
1355 environment?.environmentId ?? null,
1356 AuthOrchestrationOperateScope,
1357 );
1358 const canCloneProject = canWriteSourceControl && canCreateProject;
1359 const remoteUrl = stringParam(props.remoteUrl);
1360 const repositoryTitle = stringParam(props.repositoryTitle);
1361 const prompt = stringParam(props.prompt);
1362 const repositoryName = stringParam(props.repositoryName)?.trim() ?? "";
1363 const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = useBrowsePathInput(
1364 environment,
1365 repositoryName,
1366 );
1367 const [isSubmitting, setIsSubmitting] = useState(false);
1368 const [error, setError] = useState<string | null>(null);
1369​
1370 const submitPath = async () => {
1371 if (
1372 !environment ||
1373 !readEnvironmentScope(environment.environmentId, AuthSourceControlWriteScope) ||
1374 !readEnvironmentScope(environment.environmentId, AuthOrchestrationOperateScope) ||
1375 !remoteUrl ||
1376 isBrowseNavigating ||
1377 isSubmitting
1378 ) {
1379 return;
1381 setError(null);
1382 const resolved = resolveAddProjectPath({
1383 rawPath: pathInput,
1384 currentProjectCwd: null,
1385 platform: environment.platform,
1386 });
1387 if (!resolved.ok) {
1388 setError(resolved.error);
1389 return;
1391​
1392 const originRoute = getActiveRoute(navigation);
1393 setIsSubmitting(true);
1394 const projectId = ProjectId.make(uuidv4());
1395 const title = inferProjectTitleFromPath(resolved.path);
1396 const startResult = await startProjectClone({
1397 environmentId: environment.environmentId,
1398 input: {
1399 projectId,
1400 title,
1401 createdAt: new Date().toISOString(),
1402 remoteUrl,
1403 destinationPath: resolved.path,
1404 },
1405 });
1406 if (AsyncResult.isFailure(startResult)) {
1407 setError(errorMessage(Cause.squash(startResult.cause)));
1408 } else {
1409 void suggestAppAccessForRemote(checkAppAccess, environment.environmentId, remoteUrl);
1410 // Wait for the create event; the client store otherwise falls back to the project picker and loses clone controls.
1411 const project = await waitForProject(
1412 { environmentId: environment.environmentId, projectId },
1413 15_000,
1414 );
1415 if (project === null) {
1416 setError(
1417 "The project was created but has not reached this device yet. It will appear in the project list once the connection catches up.",
1418 );
1419 } else {
1420 openNewTaskDraft(
1422 environmentId: environment.environmentId,
1423 projectId,
1424 title,
1425 cloning: "1",
1426 ...(prompt
1427 ? await draftWithPrompt(environment.environmentId, projectId, prompt).then(
1428 (draftId) => ({ draftId }),
1429 () => ({}),
1431 : {}),
1432 },
1433 originRoute,
1434 );
1437 setIsSubmitting(false);
1438 };
1439​
1440 return (
1441 <AddProjectShell title="Clone destination">
1442 {error ? <ErrorBanner message={error} /> : null}
1443 {repositoryTitle ? (
1444 <View className="rounded-[24px] bg-grouped-card px-4 py-3">
1445 <Text className="text-base font-t3-bold">{repositoryTitle}</Text>
1446 <Text className="mt-0.5 text-xs text-foreground-muted" numberOfLines={2}>
1447 {remoteUrl}
1448 </Text>
1449 </View>
1450 ) : null}
1451 {environment ? (
1452 <>
1453 <ProjectPathInput value={pathInput} onChangeText={setPathInput} onSubmit={submitPath} />
1454 <PrimaryActionButton
1455 label="Clone project"
1456 disabled={!canCloneProject || isBrowseNavigating || isSubmitting || !remoteUrl}
1457 onPress={submitPath}
1458 loading={isSubmitting}
1459 />
1460 {!canCloneProject ? (
1461 <Text className="text-sm text-foreground-muted">
1462 This connection cannot clone projects.
1463 </Text>
1464 ) : null}
1465 <FolderBrowser
1466 environment={environment}
1467 navigateToBrowsePath={navigateToBrowsePath}
1468 pathInput={pathInput}
1469 setPathInput={setPathInput}
1470 pinnedDirectoryName={repositoryName}
1471 />
1472 </>
1473 ) : (
1474 <EmptyEnvironmentState />
1475 )}
1476 </AddProjectShell>
1477 );