Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

NewTaskRouteScreen.tsx

542 lines20.6 KB

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