Open History to see the last commit
1import { isDraftThreadRoute } from "./thread-route-state";
2import * as Dialog from "../../components/ui/Dialog";
3import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
4import { NavigationRow } from "../../components/ui/NavigationRow";
5import { AppBar } from "../../components/ui/AppBar";
6import {
7 StackActions,
8 useIsFocused,
9 useNavigation,
10 type StaticScreenProps,
11} from "@react-navigation/native";
12import { SymbolView } from "../../components/ui/AppSymbol";
13import { availableScratchWorkspaceRoot } from "@t3tools/client-runtime/operations/projects";
14import { isScratchProject } from "@t3tools/client-runtime/state/projects";
15import {
16 isAtomCommandInterrupted,
17 squashAtomCommandFailure,
18} from "@t3tools/client-runtime/state/runtime";
19import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
20import { useEffect, useRef, useState } from "react";
21import { Platform, Pressable, View } from "react-native";
22import { useSafeAreaInsets } from "react-native-safe-area-context";
23import { cn } from "../../lib/cn";
24import { ScreenContent } from "../../components/ui/ScreenContent";
25import { Button } from "../../components/ui/Button";
26import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
27import { AppText as Text } from "../../components/ui/AppText";
28import { ProjectFavicon } from "../../components/ProjectFavicon";
29import { useProjects, useServerConfigs } from "../../state/entities";
30import { projectEnvironment } from "../../state/projects";
31import { useAtomCommand } from "../../state/use-atom-command";
32import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
33import type { WorkspaceState } from "../../state/workspaceModel";
34import { useWorkspaceState } from "../../state/workspace";
35
36import { usePromptLinkResolver } from "../prompt-links/usePromptLinkResolver";
37import { useIncomingShare } from "../sharing/IncomingShareProvider";
38import { useNewTaskFlow } from "./new-task-flow-provider";
39import { filterProjectScopes, getProjectScopeSelectionTarget } from "./new-task-project-selection";
40
41type NewTaskRouteParams = {
42 readonly incomingShareId?: string | string[];
43 readonly prompt?: string | string[];
44 readonly repo?: string | string[];
45 readonly pr?: string | string[];
46 readonly provider?: string | string[];
47 readonly model?: string | string[];
48};
49
50function deriveProjectEmptyState(catalogState: WorkspaceState): {
51 readonly title: string;
52 readonly detail: string;
53 readonly loading: boolean;
54} {
55 if (catalogState.isLoadingConnections) {
56 return {
57 title: "Loading environments",
58 detail: "Checking saved environments on this device.",
59 loading: true,
60 };
61 }
62
63 if (!catalogState.hasConnections) {
64 return {
65 title: "No environments connected",
66 detail: "Add an environment before creating a task.",
67 loading: false,
68 };
69 }
70
71 if (
72 (catalogState.connectionState === "available" ||
73 catalogState.connectionState === "offline" ||
74 catalogState.connectionState === "error" ||
75 catalogState.connectionState === "unsupported") &&
76 !catalogState.hasLoadedShellSnapshot
77 ) {
78 return {
79 title:
80 catalogState.connectionState === "unsupported"
81 ? "Client not supported"
82 : "Environment unavailable",
83 detail:
84 catalogState.connectionError ??
85 "The saved environment is offline. Check the URL or start the environment, then retry.",
86 loading: false,
87 };
88 }
89
90 if (
91 catalogState.hasConnectingEnvironment &&
92 !catalogState.hasLoadedShellSnapshot &&
93 catalogState.connectionError === null
94 ) {
95 return {
96 title: "Connecting to environment",
97 detail: "Loading projects from the saved environment.",
98 loading: true,
99 };
100 }
101
102 return {
103 title: "No projects found",
104 detail: "The connected environment did not report any projects.",
105 loading: false,
106 };
107}
108
109function NewTaskHeader(props: {
110 readonly title: string;
111 readonly subtitle: string | null;
112 readonly canAddProject: boolean;
113 readonly searchText: string;
114 readonly onSearchTextChange: (text: string) => void;
115}) {
116 const navigation = useNavigation();
117 const goBack = () => {
118 if (navigation.canGoBack()) navigation.goBack();
119 else navigation.getParent()?.goBack();
120 };
121 return (
122 <>
123 <AppBar
124 title={props.title}
125 subtitle={props.subtitle ?? undefined}
126 sidebar={false}
127 options={{ headerBackVisible: true }}
128 hideBottomBorder
129 onBack={goBack}
130 actions={
131 props.canAddProject
132 ? [
133 {
134 accessibilityLabel: "Add project",
135 icon: "plus",
136 onPress: () => navigation.dispatch(StackActions.push("AddProject")),
137 },
138 ]
139 : []
140 }
141 search={{
142 value: props.searchText,
143 onChangeText: props.onSearchTextChange,
144 placeholder: "Search projects",
145 }}
146 />
147 </>
148 );
149}
150
151export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
152 const projects = useProjects();
153 const [searchText, setSearchText] = useState("");
154 const { projectScopes, selectedEnvironmentId, setProject } = useNewTaskFlow();
155 const { state: catalogState } = useWorkspaceState();
156 const navigation = useNavigation();
157 const isFocused = useIsFocused();
158 const insets = useSafeAreaInsets();
159 const { getShare, releaseShareReservation } = useIncomingShare();
160 usePromptLinkResolver(route.params);
161 const routeShareId = Array.isArray(route.params?.incomingShareId)
162 ? route.params.incomingShareId[0]
163 : route.params?.incomingShareId;
164 const incomingShare = routeShareId ? getShare(routeShareId) : null;
165 const incomingShareSubtitle = incomingShare
166 ? incomingShare.attachments.length === 0
167 ? "Choose a project for what you shared"
168 : incomingShare.attachments.length === 1
169 ? `Choose a project for the ${incomingShare.attachments[0]?.type === "image" ? "image" : "file"} you shared`
170 : `Choose a project for the ${incomingShare.attachments.length} ${incomingShare.attachments.every((attachment) => attachment.type === "image") ? "images" : "files"} you shared`
171 : null;
172 const screenTitle = incomingShare ? "Start a task" : "Choose project";
173 const projectEmptyState = deriveProjectEmptyState(catalogState);
174 const serverConfigs = useServerConfigs();
175 const listScopes = projectScopes.filter(
176 (scope) =>
177 !scope.projects.every((project) =>
178 isScratchProject(project, serverConfigs.get(project.environmentId)?.scratchWorkspaceRoot),
179 ),
180 );
181 const visibleScopes = filterProjectScopes(listScopes, searchText);
182 const resumedDestinationKeyRef = useRef<string | null>(null);
183 const reservedDestinationProject = incomingShare?.destination
184 ? (projects.find(
185 (project) =>
186 project.environmentId === incomingShare.destination?.environmentId &&
187 project.id === incomingShare.destination?.projectId,
188 ) ?? null)
189 : null;
190 const { connectedEnvironments } = useRemoteConnectionStatus();
191 const openScratch = useAtomCommand(projectEnvironment.openScratch, {
192 reportFailure: false,
193 });
194 const scratchEnvironments = connectedEnvironments.filter(
195 (environment) =>
196 availableScratchWorkspaceRoot(
197 environment.connectionState,
198 serverConfigs.get(environment.environmentId),
199 ) !== null,
200 );
201 const scratchEnvironment =
202 scratchEnvironments.find(
203 (environment) => environment.environmentId === selectedEnvironmentId,
204 ) ??
205 scratchEnvironments[0] ??
206 null;
207 const canStartScratch = scratchEnvironment !== null && reservedDestinationProject === null;
208 const scratchStartInFlightRef = useRef(false);
209
210 async function selectProject(project: EnvironmentProject): Promise<void> {
211 if (incomingShare?.destination && !reservedDestinationProject) {
212 try {
213 await releaseShareReservation(incomingShare.id, incomingShare.destination);
214 } catch (error) {
215 Dialog.alert(
216 "Could not change project",
217 error instanceof Error
218 ? error.message
219 : "The shared content reservation could not be updated.",
220 );
221 return;
222 }
223 }
224 const root = navigation.getState()?.routeNames.includes("NewTaskProject")
225 ? navigation
226 : navigation.getParent();
227 const rootState = root?.getState();
228 const threadRoute = rootState?.routes[rootState.index - 1];
229 if (isDraftThreadRoute(threadRoute)) {
230 setProject(project);
231 root?.goBack();
232 return;
233 }
234 root?.navigate("Thread", {
235 draft: {
236 environmentId: String(project.environmentId),
237 projectId: String(project.id),
238 incomingShareId: incomingShare?.id,
239 },
240 });
241 }
242
243 async function startScratch(): Promise<void> {
244 if (!scratchEnvironment || scratchStartInFlightRef.current) return;
245 const environmentId = scratchEnvironment.environmentId;
246 scratchStartInFlightRef.current = true;
247 const result = await openScratch({ environmentId, input: {} });
248 if (result._tag === "Failure") {
249 scratchStartInFlightRef.current = false;
250 if (!isAtomCommandInterrupted(result)) {
251 const error = squashAtomCommandFailure(result);
252 Dialog.alert(
253 "Could not start without a project",
254 error instanceof Error
255 ? error.message
256 : "The folder for threads without a project could not be created.",
257 );
258 }
259 return;
260 }
261 // selectProject handles its own failures, so this never throws.
262 await selectProject(result.value);
263 scratchStartInFlightRef.current = false;
264 }
265
266 useEffect(() => {
267 const destination = incomingShare?.destination;
268 if (!destination) {
269 resumedDestinationKeyRef.current = null;
270 return;
271 }
272 if (!isFocused) {
273 // Returning from the reserved draft is a fresh resume attempt. Keeping
274 // this latch set would leave every project row disabled with no route.
275 resumedDestinationKeyRef.current = null;
276 return;
277 }
278 const destinationKey = `${incomingShare.id}:${destination.environmentId}:${destination.projectId}`;
279 if (resumedDestinationKeyRef.current === destinationKey) {
280 return;
281 }
282 if (!reservedDestinationProject) {
283 return;
284 }
285 resumedDestinationKeyRef.current = destinationKey;
286 (navigation.getState()?.routeNames.includes("NewTaskProject")
287 ? navigation
288 : navigation.getParent()
289 )?.navigate("Thread", {
290 draft: {
291 environmentId: reservedDestinationProject.environmentId,
292 projectId: reservedDestinationProject.id,
293 title: reservedDestinationProject.title,
294 incomingShareId: incomingShare.id,
295 },
296 });
297 }, [incomingShare, isFocused, navigation, reservedDestinationProject]);
298
299 return (
300 <View collapsable={false} className="flex-1 bg-sheet">
301 <NewTaskHeader
302 title={screenTitle}
303 subtitle={incomingShareSubtitle}
304 canAddProject={catalogState.hasReadyEnvironment}
305 searchText={searchText}
306 onSearchTextChange={setSearchText}
307 />
308
309 <ScreenContent>
310 <ScrollView
311 contentInsetAdjustmentBehavior="automatic"
312 showsVerticalScrollIndicator={false}
313 keyboardShouldPersistTaps="handled"
314 keyboardDismissMode="on-drag"
315 className="flex-1"
316 contentContainerStyle={{
317 gap: Platform.OS === "android" ? 8 : 12,
318 paddingBottom: Math.max(insets.bottom, 18) + 18,
319 paddingHorizontal: Platform.OS === "android" ? 16 : 20,
320 paddingTop: Platform.OS === "android" ? 16 : 8,
321 ...(Platform.OS === "android" && visibleScopes.length === 0
322 ? { flexGrow: 1, justifyContent: "center" as const }
323 : {}),
324 }}
325 >
326 {canStartScratch && listScopes.length > 0 ? (
327 Platform.OS === "android" ? (
328 <View collapsable={false} className="overflow-hidden rounded-[28px] bg-grouped-card">
329 <NavigationRow
330 className="bg-grouped-card"
331 title="No project"
332 subtitle="Start a task without a project"
333 onPress={() => void startScratch()}
334 leading={
335 <SymbolView
336 name="text.bubble"
337 size={22}
338 tintColorClassName="accent-icon-muted"
339 type="monochrome"
340 />
341 }
342 />
343 </View>
344 ) : (
345 <View collapsable={false} className="overflow-hidden rounded-[24px] bg-grouped-card">
346 <Pressable
347 accessibilityRole="button"
348 accessibilityLabel="No project"
349 onPress={() => void startScratch()}
350 className="flex-row items-center gap-3 bg-grouped-card px-4 py-3.5"
351 >
352 <View className="h-7 w-7 items-center justify-center">
353 <SymbolView
354 name="text.bubble"
355 size={18}
356 tintColorClassName="accent-icon-muted"
357 type="monochrome"
358 />
359 </View>
360 <View className="min-w-0 flex-1">
361 <Text className="text-base font-t3-bold leading-snug">No project</Text>
362 <Text className="text-xs leading-snug text-foreground-muted" numberOfLines={1}>
363 Start a task without a project
364 </Text>
365 </View>
366 <SymbolView
367 name="chevron.right"
368 size={14}
369 tintColorClassName="accent-chevron"
370 type="monochrome"
371 />
372 </Pressable>
373 </View>
374 )
375 ) : null}
376 {listScopes.length === 0 ? (
377 <View
378 collapsable={false}
379 className={cn(
380 "items-center gap-3 px-6 py-8",
381 Platform.OS !== "android" && "rounded-[24px] bg-grouped-card",
382 )}
383 >
384 {projectEmptyState.loading ? (
385 <AppActivityIndicator colorClassName="accent-icon-muted" />
386 ) : null}
387 <Text className="text-center text-lg font-t3-bold text-foreground">
388 {projectEmptyState.title}
389 </Text>
390 <Text className="text-center text-sm leading-normal text-foreground-muted">
391 {projectEmptyState.detail}
392 </Text>
393 {Platform.OS === "android" ? (
394 <>
395 <Button
396 label={catalogState.hasReadyEnvironment ? "Add new project" : "Add environment"}
397 tone="primary"
398 onPress={() =>
399 catalogState.hasReadyEnvironment
400 ? navigation.dispatch(StackActions.push("AddProject"))
401 : navigation.navigate("ConnectionsNew")
402 }
403 />
404 {canStartScratch ? (
405 <Button
406 label="Start without a project"
407 tone="secondary"
408 onPress={() => void startScratch()}
409 />
410 ) : null}
411 </>
412 ) : !catalogState.hasReadyEnvironment ? (
413 <View className="mt-1">
414 <Button
415 label="Add environment"
416 tone="primary"
417 onPress={() => navigation.navigate("ConnectionsNew")}
418 />
419 </View>
420 ) : (
421 <>
422 <View className="mt-1">
423 <Button
424 label="Add new project"
425 tone="primary"
426 onPress={() => navigation.dispatch(StackActions.push("AddProject"))}
427 />
428 </View>
429 {canStartScratch ? (
430 <Button
431 label="Start without a project"
432 tone="secondary"
433 onPress={() => void startScratch()}
434 />
435 ) : null}
436 </>
437 )}
438 </View>
439 ) : visibleScopes.length === 0 ? (
440 <View className="items-center gap-2 px-6 py-8">
441 <Text className="text-center text-lg font-t3-bold text-foreground">
442 No matching projects
443 </Text>
444 <Text className="text-center text-sm leading-normal text-foreground-muted">
445 Try a different project name or workspace path.
446 </Text>
447 </View>
448 ) : (
449 <View
450 collapsable={false}
451 className={
452 Platform.OS === "android"
453 ? "overflow-hidden rounded-[28px] bg-grouped-card"
454 : "overflow-hidden rounded-[24px] bg-grouped-card"
455 }
456 >
457 {visibleScopes.map((scope, scopeIndex) => {
458 const hasMultipleProjects = scope.projects.length > 1;
459 const selectionTarget = getProjectScopeSelectionTarget(
460 scope,
461 selectedEnvironmentId,
462 );
463 if (Platform.OS === "android") {
464 return (
465 <NavigationRow
466 className="bg-grouped-card"
467 key={scope.key}
468 title={scope.title}
469 subtitle={
470 hasMultipleProjects
471 ? `${scope.projects.length} workspaces`
472 : selectionTarget.workspaceRoot
473 }
474 subtitleNumberOfLines={1}
475 subtitleEllipsizeMode="middle"
476 disabled={reservedDestinationProject !== null}
477 onPress={() => void selectProject(selectionTarget)}
478 leading={
479 <ProjectFavicon
480 environmentId={scope.representative.environmentId}
481 faviconPath={scope.representative.faviconPath}
482 projectIcon={scope.representative.projectIcon}
483 size={24}
484 projectTitle={scope.title}
485 workspaceRoot={scope.representative.workspaceRoot}
486 />
487 }
488 />
489 );
490 }
491 return (
492 <View
493 key={scope.key}
494 className={cn(scopeIndex > 0 && "border-t border-border-subtle")}
495 >
496 <Pressable
497 accessibilityRole="button"
498 accessibilityLabel={scope.title}
499 disabled={reservedDestinationProject !== null}
500 onPress={() => void selectProject(selectionTarget)}
501 className="flex-row items-center gap-3 bg-grouped-card px-4 py-3.5"
502 >
503 <View className="h-7 w-7 items-center justify-center">
504 <ProjectFavicon
505 environmentId={scope.representative.environmentId}
506 faviconPath={scope.representative.faviconPath}
507 projectIcon={scope.representative.projectIcon}
508 size={20}
509 projectTitle={scope.title}
510 workspaceRoot={scope.representative.workspaceRoot}
511 />
512 </View>
513 <View className="min-w-0 flex-1">
514 <Text className={cn("text-base leading-snug", "font-t3-bold")}>
515 {scope.title}
516 </Text>
517 <Text
518 className="text-xs leading-snug text-foreground-muted"
519 ellipsizeMode="middle"
520 numberOfLines={1}
521 >
522 {hasMultipleProjects
523 ? `${scope.projects.length} workspaces`
524 : selectionTarget.workspaceRoot}
525 </Text>
526 </View>
527 <SymbolView
528 name="chevron.right"
529 size={14}
530 tintColorClassName="accent-chevron"
531 type="monochrome"
532 />
533 </Pressable>
534 </View>
535 );
536 })}
537 </View>
538 )}
539 </ScrollView>
540 </ScreenContent>
541 </View>
542 );
543}