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

AddProjectScreen.tsx

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