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