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