@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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