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