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 { useIncomingShare } from "../sharing/IncomingShareProvider";
37import { useNewTaskFlow } from "./new-task-flow-provider";
38import { filterProjectScopes, getProjectScopeSelectionTarget } from "./new-task-project-selection";
39import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
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 selectDetail = useSelectWorkspaceDetail();
158 const isFocused = useIsFocused();
159 const insets = useSafeAreaInsets();
160 const { getShare, releaseShareReservation } = useIncomingShare();
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 connectedEnvironmentIds = new Set(
192 connectedEnvironments
193 .filter((environment) => environment.connectionState === "connected")
194 .map((environment) => environment.environmentId),
195 );
196 const openScratch = useAtomCommand(projectEnvironment.openScratch, {
197 reportFailure: false,
198 });
199 const scratchEnvironments = connectedEnvironments.filter(
200 (environment) =>
201 availableScratchWorkspaceRoot(
202 environment.connectionState,
203 serverConfigs.get(environment.environmentId),
204 ) !== null,
205 );
206 const scratchEnvironment =
207 scratchEnvironments.find(
208 (environment) => environment.environmentId === selectedEnvironmentId,
209 ) ??
210 scratchEnvironments[0] ??
211 null;
212 const canStartScratch = scratchEnvironment !== null && reservedDestinationProject === null;
213 const scratchStartInFlightRef = useRef(false);
214
215 async function selectProject(project: EnvironmentProject): Promise<void> {
216 if (incomingShare?.destination && !reservedDestinationProject) {
217 try {
218 await releaseShareReservation(incomingShare.id, incomingShare.destination);
219 } catch (error) {
220 Dialog.alert(
221 "Could not change project",
222 error instanceof Error
223 ? error.message
224 : "The shared content reservation could not be updated.",
225 );
226 return;
227 }
228 }
229 const root = navigation.getState()?.routeNames.includes("NewTaskProject")
230 ? navigation
231 : navigation.getParent();
232 const rootState = root?.getState();
233 const threadRoute = rootState?.routes[rootState.index - 1];
234 if (isDraftThreadRoute(threadRoute)) {
235 setProject(project);
236 root?.goBack();
237 return;
238 }
239 selectDetail({
240 name: "Thread",
241 params: {
242 draft: {
243 environmentId: String(project.environmentId),
244 projectId: String(project.id),
245 incomingShareId: incomingShare?.id,
246 },
247 },
248 });
249 }
250
251 async function startScratch(): Promise<void> {
252 if (!scratchEnvironment || scratchStartInFlightRef.current) return;
253 const environmentId = scratchEnvironment.environmentId;
254 scratchStartInFlightRef.current = true;
255 const result = await openScratch({ environmentId, input: {} });
256 if (result._tag === "Failure") {
257 scratchStartInFlightRef.current = false;
258 if (!isAtomCommandInterrupted(result)) {
259 const error = squashAtomCommandFailure(result);
260 Dialog.alert(
261 "Could not start without a project",
262 error instanceof Error
263 ? error.message
264 : "The folder for threads without a project could not be created.",
265 );
266 }
267 return;
268 }
269 // selectProject handles its own failures, so this never throws.
270 await selectProject(result.value);
271 scratchStartInFlightRef.current = false;
272 }
273
274 // 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
275 useEffect(() => {
276 const destination = incomingShare?.destination;
277 if (!destination) {
278 resumedDestinationKeyRef.current = null;
279 return;
280 }
281 if (!isFocused) {
282 // Reset on return so reserved-draft resume can retry without leaving project rows disabled.
283 resumedDestinationKeyRef.current = null;
284 return;
285 }
286 const destinationKey = `${incomingShare.id}:${destination.environmentId}:${destination.projectId}`;
287 if (resumedDestinationKeyRef.current === destinationKey) {
288 return;
289 }
290 if (!reservedDestinationProject) {
291 return;
292 }
293 resumedDestinationKeyRef.current = destinationKey;
294 selectDetail({
295 name: "Thread",
296 params: {
297 draft: {
298 environmentId: reservedDestinationProject.environmentId,
299 projectId: reservedDestinationProject.id,
300 title: reservedDestinationProject.title,
301 incomingShareId: incomingShare.id,
302 },
303 },
304 });
305 }, [incomingShare, isFocused, reservedDestinationProject, selectDetail]);
306
307 return (
308 <View collapsable={false} className="flex-1 bg-sheet">
309 <NewTaskHeader
310 title={screenTitle}
311 subtitle={incomingShareSubtitle}
312 canAddProject={catalogState.hasReadyEnvironment}
313 searchText={searchText}
314 onSearchTextChange={setSearchText}
315 />
316
317 <ScreenContent>
318 <ScrollView
319 contentInsetAdjustmentBehavior="automatic"
320 showsVerticalScrollIndicator={false}
321 keyboardShouldPersistTaps="handled"
322 keyboardDismissMode="on-drag"
323 className="flex-1"
324 contentContainerStyle={{
325 gap: Platform.OS === "android" ? 8 : 12,
326 paddingBottom: Math.max(insets.bottom, 18) + 18,
327 paddingHorizontal: Platform.OS === "android" ? 16 : 20,
328 paddingTop: Platform.OS === "android" ? 16 : 8,
329 ...(Platform.OS === "android" && visibleScopes.length === 0
330 ? { flexGrow: 1, justifyContent: "center" as const }
331 : {}),
332 }}
333 >
334 {canStartScratch && listScopes.length > 0 ? (
335 Platform.OS === "android" ? (
336 <View collapsable={false} className="overflow-hidden rounded-[28px] bg-grouped-card">
337 <NavigationRow
338 className="bg-grouped-card"
339 title="No project"
340 subtitle="Start a task without a project"
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 onPress={() => void startScratch()}
358 className="flex-row items-center gap-3 bg-grouped-card px-4 py-3.5"
359 >
360 <View className="h-7 w-7 items-center justify-center">
361 <SymbolView
362 name="text.bubble"
363 size={18}
364 tintColorClassName="accent-icon-muted"
365 type="monochrome"
366 />
367 </View>
368 <View className="min-w-0 flex-1">
369 <Text className="text-base font-t3-bold leading-snug">No project</Text>
370 <Text className="text-xs leading-snug text-foreground-muted" numberOfLines={1}>
371 Start a task without a project
372 </Text>
373 </View>
374 <SymbolView
375 name="chevron.right"
376 size={14}
377 tintColorClassName="accent-chevron"
378 type="monochrome"
379 />
380 </Pressable>
381 </View>
382 )
383 ) : null}
384 {listScopes.length === 0 ? (
385 <View
386 collapsable={false}
387 className={cn(
388 "items-center gap-3 px-6 py-8",
389 Platform.OS !== "android" && "rounded-[24px] bg-grouped-card",
390 )}
391 >
392 {projectEmptyState.loading ? (
393 <AppActivityIndicator colorClassName="accent-icon-muted" />
394 ) : null}
395 <Text className="text-center text-lg font-t3-bold text-foreground">
396 {projectEmptyState.title}
397 </Text>
398 <Text className="text-center text-sm leading-normal text-foreground-muted">
399 {projectEmptyState.detail}
400 </Text>
401 {Platform.OS === "android" ? (
402 <>
403 <Button
404 label={catalogState.hasReadyEnvironment ? "Add new project" : "Add environment"}
405 tone="primary"
406 onPress={() =>
407 catalogState.hasReadyEnvironment
408 ? navigation.dispatch(StackActions.push("AddProject"))
409 : navigation.navigate("ConnectionsNew")
410 }
411 />
412 {canStartScratch ? (
413 <Button
414 label="Start without a project"
415 tone="secondary"
416 onPress={() => void startScratch()}
417 />
418 ) : null}
419 </>
420 ) : !catalogState.hasReadyEnvironment ? (
421 <View className="mt-1">
422 <Button
423 label="Add environment"
424 tone="primary"
425 onPress={() => navigation.navigate("ConnectionsNew")}
426 />
427 </View>
428 ) : (
429 <>
430 <View className="mt-1">
431 <Button
432 label="Add new project"
433 tone="primary"
434 onPress={() => navigation.dispatch(StackActions.push("AddProject"))}
435 />
436 </View>
437 {canStartScratch ? (
438 <Button
439 label="Start without a project"
440 tone="secondary"
441 onPress={() => void startScratch()}
442 />
443 ) : null}
444 </>
445 )}
446 </View>
447 ) : visibleScopes.length === 0 ? (
448 <View className="items-center gap-2 px-6 py-8">
449 <Text className="text-center text-lg font-t3-bold text-foreground">
450 No matching projects
451 </Text>
452 <Text className="text-center text-sm leading-normal text-foreground-muted">
453 Try a different project name or workspace path.
454 </Text>
455 </View>
456 ) : (
457 <View
458 collapsable={false}
459 className={
460 Platform.OS === "android"
461 ? "overflow-hidden rounded-[28px] bg-grouped-card"
462 : "overflow-hidden rounded-[24px] bg-grouped-card"
463 }
464 >
465 {visibleScopes.map((scope, scopeIndex) => {
466 const hasMultipleProjects = scope.projects.length > 1;
467 const selectionTarget = getProjectScopeSelectionTarget(
468 scope,
469 selectedEnvironmentId,
470 connectedEnvironmentIds,
471 );
472 if (Platform.OS === "android") {
473 return (
474 <NavigationRow
475 className="bg-grouped-card"
476 key={scope.key}
477 title={scope.title}
478 subtitle={
479 hasMultipleProjects
480 ? `${scope.projects.length} workspaces`
481 : selectionTarget.workspaceRoot
482 }
483 subtitleNumberOfLines={1}
484 subtitleEllipsizeMode="middle"
485 disabled={reservedDestinationProject !== null}
486 onPress={() => void selectProject(selectionTarget)}
487 leading={
488 <ProjectFavicon
489 environmentId={scope.representative.environmentId}
490 faviconPath={scope.representative.faviconPath}
491 projectIcon={scope.representative.projectIcon}
492 size={24}
493 projectTitle={scope.title}
494 workspaceRoot={scope.representative.workspaceRoot}
495 />
496 }
497 />
498 );
499 }
500 return (
501 <View
502 key={scope.key}
503 className={cn(scopeIndex > 0 && "border-t border-border-subtle")}
504 >
505 <Pressable
506 accessibilityRole="button"
507 accessibilityLabel={scope.title}
508 disabled={reservedDestinationProject !== null}
509 onPress={() => void selectProject(selectionTarget)}
510 className="flex-row items-center gap-3 bg-grouped-card px-4 py-3.5"
511 >
512 <View className="h-7 w-7 items-center justify-center">
513 <ProjectFavicon
514 environmentId={scope.representative.environmentId}
515 faviconPath={scope.representative.faviconPath}
516 projectIcon={scope.representative.projectIcon}
517 size={20}
518 projectTitle={scope.title}
519 workspaceRoot={scope.representative.workspaceRoot}
520 />
521 </View>
522 <View className="min-w-0 flex-1">
523 <Text className={cn("text-base leading-snug", "font-t3-bold")}>
524 {scope.title}
525 </Text>
526 <Text
527 className="text-xs leading-snug text-foreground-muted"
528 ellipsizeMode="middle"
529 numberOfLines={1}
530 >
531 {hasMultipleProjects
532 ? `${scope.projects.length} workspaces`
533 : selectionTarget.workspaceRoot}
534 </Text>
535 </View>
536 <SymbolView
537 name="chevron.right"
538 size={14}
539 tintColorClassName="accent-chevron"
540 type="monochrome"
541 />
542 </Pressable>
543 </View>
544 );
545 })}
546 </View>
547 )}
548 </ScrollView>
549 </ScreenContent>
550 </View>
551 );
552}