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