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