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

NewTaskRouteScreen.tsx

538 lines20.8 KB

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