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