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