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";
40import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
41
42type NewTaskRouteParams = {
43 readonly incomingShareId?: string | string[];
44 readonly prompt?: string | string[];
45 readonly repo?: string | string[];
46 readonly pr?: string | string[];
47 readonly provider?: string | string[];
48 readonly model?: string | string[];
49};
50
51function deriveProjectEmptyState(catalogState: WorkspaceState): {
52 readonly title: string;
53 readonly detail: string;
54 readonly loading: boolean;
55} {
56 if (catalogState.isLoadingConnections) {
57 return {
58 title: "Loading environments",
59 detail: "Checking saved environments on this device.",
60 loading: true,
61 };
62 }
63
64 if (!catalogState.hasConnections) {
65 return {
66 title: "No environments connected",
67 detail: "Add an environment before creating a task.",
68 loading: false,
69 };
70 }
71
72 if (
73 (catalogState.connectionState === "available" ||
74 catalogState.connectionState === "offline" ||
75 catalogState.connectionState === "error" ||
76 catalogState.connectionState === "unsupported") &&
77 !catalogState.hasLoadedShellSnapshot
78 ) {
79 return {
80 title:
81 catalogState.connectionState === "unsupported"
82 ? "Client not supported"
83 : "Environment unavailable",
84 detail:
85 catalogState.connectionError ??
86 "The saved environment is offline. Check the URL or start the environment, then retry.",
87 loading: false,
88 };
89 }
90
91 if (
92 catalogState.hasConnectingEnvironment &&
93 !catalogState.hasLoadedShellSnapshot &&
94 catalogState.connectionError === null
95 ) {
96 return {
97 title: "Connecting to environment",
98 detail: "Loading projects from the saved environment.",
99 loading: true,
100 };
101 }
102
103 return {
104 title: "No projects found",
105 detail: "The connected environment did not report any projects.",
106 loading: false,
107 };
108}
109
110function NewTaskHeader(props: {
111 readonly title: string;
112 readonly subtitle: string | null;
113 readonly canAddProject: boolean;
114 readonly searchText: string;
115 readonly onSearchTextChange: (text: string) => void;
116}) {
117 const navigation = useNavigation();
118 const goBack = () => {
119 if (navigation.canGoBack()) navigation.goBack();
120 else navigation.getParent()?.goBack();
121 };
122 return (
123 <>
124 <AppBar
125 title={props.title}
126 subtitle={props.subtitle ?? undefined}
127 sidebar={false}
128 options={{ headerBackVisible: true }}
129 hideBottomBorder
130 onBack={goBack}
131 actions={
132 props.canAddProject
133 ? [
134 {
135 accessibilityLabel: "Add project",
136 icon: "plus",
137 onPress: () => navigation.dispatch(StackActions.push("AddProject")),
138 },
139 ]
140 : []
141 }
142 search={{
143 value: props.searchText,
144 onChangeText: props.onSearchTextChange,
145 placeholder: "Search projects",
146 }}
147 />
148 </>
149 );
150}
151
152export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
153 const projects = useProjects();
154 const [searchText, setSearchText] = useState("");
155 const { projectScopes, selectedEnvironmentId, setProject } = useNewTaskFlow();
156 const { state: catalogState } = useWorkspaceState();
157 const navigation = useNavigation();
158 const selectDetail = useSelectWorkspaceDetail();
159 const isFocused = useIsFocused();
160 const insets = useSafeAreaInsets();
161 const { getShare, releaseShareReservation } = useIncomingShare();
162 usePromptLinkResolver(route.params);
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 = 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 openScratch = useAtomCommand(projectEnvironment.openScratch, {
194 reportFailure: false,
195 });
196 const scratchEnvironments = connectedEnvironments.filter(
197 (environment) =>
198 availableScratchWorkspaceRoot(
199 environment.connectionState,
200 serverConfigs.get(environment.environmentId),
201 ) !== null,
202 );
203 const scratchEnvironment =
204 scratchEnvironments.find(
205 (environment) => environment.environmentId === selectedEnvironmentId,
206 ) ??
207 scratchEnvironments[0] ??
208 null;
209 const canStartScratch = scratchEnvironment !== null && reservedDestinationProject === null;
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 (!scratchEnvironment || scratchStartInFlightRef.current) return;
250 const environmentId = scratchEnvironment.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 useEffect(() => {
272 const destination = incomingShare?.destination;
273 if (!destination) {
274 resumedDestinationKeyRef.current = null;
275 return;
276 }
277 if (!isFocused) {
278 // Reset on return so reserved-draft resume can retry without leaving project rows disabled.
279 resumedDestinationKeyRef.current = null;
280 return;
281 }
282 const destinationKey = `${incomingShare.id}:${destination.environmentId}:${destination.projectId}`;
283 if (resumedDestinationKeyRef.current === destinationKey) {
284 return;
285 }
286 if (!reservedDestinationProject) {
287 return;
288 }
289 resumedDestinationKeyRef.current = destinationKey;
290 selectDetail({
291 name: "Thread",
292 params: {
293 draft: {
294 environmentId: reservedDestinationProject.environmentId,
295 projectId: reservedDestinationProject.id,
296 title: reservedDestinationProject.title,
297 incomingShareId: incomingShare.id,
298 },
299 },
300 });
301 }, [incomingShare, isFocused, reservedDestinationProject, selectDetail]);
302
303 return (
304 <View collapsable={false} className="flex-1 bg-sheet">
305 <NewTaskHeader
306 title={screenTitle}
307 subtitle={incomingShareSubtitle}
308 canAddProject={catalogState.hasReadyEnvironment}
309 searchText={searchText}
310 onSearchTextChange={setSearchText}
311 />
312
313 <ScreenContent>
314 <ScrollView
315 contentInsetAdjustmentBehavior="automatic"
316 showsVerticalScrollIndicator={false}
317 keyboardShouldPersistTaps="handled"
318 keyboardDismissMode="on-drag"
319 className="flex-1"
320 contentContainerStyle={{
321 gap: Platform.OS === "android" ? 8 : 12,
322 paddingBottom: Math.max(insets.bottom, 18) + 18,
323 paddingHorizontal: Platform.OS === "android" ? 16 : 20,
324 paddingTop: Platform.OS === "android" ? 16 : 8,
325 ...(Platform.OS === "android" && visibleScopes.length === 0
326 ? { flexGrow: 1, justifyContent: "center" as const }
327 : {}),
328 }}
329 >
330 {canStartScratch && listScopes.length > 0 ? (
331 Platform.OS === "android" ? (
332 <View collapsable={false} className="overflow-hidden rounded-[28px] bg-grouped-card">
333 <NavigationRow
334 className="bg-grouped-card"
335 title="No project"
336 subtitle="Start a task without a project"
337 onPress={() => void startScratch()}
338 leading={
339 <SymbolView
340 name="text.bubble"
341 size={22}
342 tintColorClassName="accent-icon-muted"
343 type="monochrome"
344 />
345 }
346 />
347 </View>
348 ) : (
349 <View collapsable={false} className="overflow-hidden rounded-[24px] bg-grouped-card">
350 <Pressable
351 accessibilityRole="button"
352 accessibilityLabel="No project"
353 onPress={() => void startScratch()}
354 className="flex-row items-center gap-3 bg-grouped-card px-4 py-3.5"
355 >
356 <View className="h-7 w-7 items-center justify-center">
357 <SymbolView
358 name="text.bubble"
359 size={18}
360 tintColorClassName="accent-icon-muted"
361 type="monochrome"
362 />
363 </View>
364 <View className="min-w-0 flex-1">
365 <Text className="text-base font-t3-bold leading-snug">No project</Text>
366 <Text className="text-xs leading-snug text-foreground-muted" numberOfLines={1}>
367 Start a task without a project
368 </Text>
369 </View>
370 <SymbolView
371 name="chevron.right"
372 size={14}
373 tintColorClassName="accent-chevron"
374 type="monochrome"
375 />
376 </Pressable>
377 </View>
378 )
379 ) : null}
380 {listScopes.length === 0 ? (
381 <View
382 collapsable={false}
383 className={cn(
384 "items-center gap-3 px-6 py-8",
385 Platform.OS !== "android" && "rounded-[24px] bg-grouped-card",
386 )}
387 >
388 {projectEmptyState.loading ? (
389 <AppActivityIndicator colorClassName="accent-icon-muted" />
390 ) : null}
391 <Text className="text-center text-lg font-t3-bold text-foreground">
392 {projectEmptyState.title}
393 </Text>
394 <Text className="text-center text-sm leading-normal text-foreground-muted">
395 {projectEmptyState.detail}
396 </Text>
397 {Platform.OS === "android" ? (
398 <>
399 <Button
400 label={catalogState.hasReadyEnvironment ? "Add new project" : "Add environment"}
401 tone="primary"
402 onPress={() =>
403 catalogState.hasReadyEnvironment
404 ? navigation.dispatch(StackActions.push("AddProject"))
405 : navigation.navigate("ConnectionsNew")
406 }
407 />
408 {canStartScratch ? (
409 <Button
410 label="Start without a project"
411 tone="secondary"
412 onPress={() => void startScratch()}
413 />
414 ) : null}
415 </>
416 ) : !catalogState.hasReadyEnvironment ? (
417 <View className="mt-1">
418 <Button
419 label="Add environment"
420 tone="primary"
421 onPress={() => navigation.navigate("ConnectionsNew")}
422 />
423 </View>
424 ) : (
425 <>
426 <View className="mt-1">
427 <Button
428 label="Add new project"
429 tone="primary"
430 onPress={() => navigation.dispatch(StackActions.push("AddProject"))}
431 />
432 </View>
433 {canStartScratch ? (
434 <Button
435 label="Start without a project"
436 tone="secondary"
437 onPress={() => void startScratch()}
438 />
439 ) : null}
440 </>
441 )}
442 </View>
443 ) : visibleScopes.length === 0 ? (
444 <View className="items-center gap-2 px-6 py-8">
445 <Text className="text-center text-lg font-t3-bold text-foreground">
446 No matching projects
447 </Text>
448 <Text className="text-center text-sm leading-normal text-foreground-muted">
449 Try a different project name or workspace path.
450 </Text>
451 </View>
452 ) : (
453 <View
454 collapsable={false}
455 className={
456 Platform.OS === "android"
457 ? "overflow-hidden rounded-[28px] bg-grouped-card"
458 : "overflow-hidden rounded-[24px] bg-grouped-card"
459 }
460 >
461 {visibleScopes.map((scope, scopeIndex) => {
462 const hasMultipleProjects = scope.projects.length > 1;
463 const selectionTarget = getProjectScopeSelectionTarget(
464 scope,
465 selectedEnvironmentId,
466 );
467 if (Platform.OS === "android") {
468 return (
469 <NavigationRow
470 className="bg-grouped-card"
471 key={scope.key}
472 title={scope.title}
473 subtitle={
474 hasMultipleProjects
475 ? `${scope.projects.length} workspaces`
476 : selectionTarget.workspaceRoot
477 }
478 subtitleNumberOfLines={1}
479 subtitleEllipsizeMode="middle"
480 disabled={reservedDestinationProject !== null}
481 onPress={() => void selectProject(selectionTarget)}
482 leading={
483 <ProjectFavicon
484 environmentId={scope.representative.environmentId}
485 faviconPath={scope.representative.faviconPath}
486 projectIcon={scope.representative.projectIcon}
487 size={24}
488 projectTitle={scope.title}
489 workspaceRoot={scope.representative.workspaceRoot}
490 />
491 }
492 />
493 );
494 }
495 return (
496 <View
497 key={scope.key}
498 className={cn(scopeIndex > 0 && "border-t border-border-subtle")}
499 >
500 <Pressable
501 accessibilityRole="button"
502 accessibilityLabel={scope.title}
503 disabled={reservedDestinationProject !== null}
504 onPress={() => void selectProject(selectionTarget)}
505 className="flex-row items-center gap-3 bg-grouped-card px-4 py-3.5"
506 >
507 <View className="h-7 w-7 items-center justify-center">
508 <ProjectFavicon
509 environmentId={scope.representative.environmentId}
510 faviconPath={scope.representative.faviconPath}
511 projectIcon={scope.representative.projectIcon}
512 size={20}
513 projectTitle={scope.title}
514 workspaceRoot={scope.representative.workspaceRoot}
515 />
516 </View>
517 <View className="min-w-0 flex-1">
518 <Text className={cn("text-base leading-snug", "font-t3-bold")}>
519 {scope.title}
520 </Text>
521 <Text
522 className="text-xs leading-snug text-foreground-muted"
523 ellipsizeMode="middle"
524 numberOfLines={1}
525 >
526 {hasMultipleProjects
527 ? `${scope.projects.length} workspaces`
528 : selectionTarget.workspaceRoot}
529 </Text>
530 </View>
531 <SymbolView
532 name="chevron.right"
533 size={14}
534 tintColorClassName="accent-chevron"
535 type="monochrome"
536 />
537 </Pressable>
538 </View>
539 );
540 })}
541 </View>
542 )}
543 </ScrollView>
544 </ScreenContent>
545 </View>
546 );
547}