The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 632 lines 24.1 KB
Raw
1 import { isDraftThreadRoute } from "./thread-route-state";
2 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3 import { msg, T, useGT, useMessages } from "gt-react-native";
4 import * as Dialog from "../../components/ui/Dialog";
5 import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
6 import { NavigationRow } from "../../components/ui/NavigationRow";
7 import { AppBar } from "../../components/ui/AppBar";
8 import {
9 StackActions,
10 useFocusEffect,
11 useIsFocused,
12 useNavigation,
13 type StaticScreenProps,
14 } from "@react-navigation/native";
15 import { SymbolView } from "../../components/ui/AppSymbol";
16 import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping";
17 import { isScratchProject } from "@t3tools/client-runtime/state/projects";
18 import {
19 isAtomCommandInterrupted,
20 squashAtomCommandFailure,
21 } from "@t3tools/client-runtime/state/runtime";
22 import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
23 import { useCallback, useEffect, useRef, useState } from "react";
24 import { Platform, Pressable, View } from "react-native";
25 import { useSafeAreaInsets } from "react-native-safe-area-context";
26 import { cn } from "../../lib/cn";
27 import { runtimeConnectionErrorText } from "../connection/environmentStatusText";
28 import { ScreenContent } from "../../components/ui/ScreenContent";
29 import { Button } from "../../components/ui/Button";
30 import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
31 import { AppText as Text } from "../../components/ui/AppText";
32 import { ProjectFavicon } from "../../components/ProjectFavicon";
33 import { useProjects, useServerConfigs } from "../../state/entities";
34 import { projectEnvironment } from "../../state/projects";
35 import { useAtomCommand } from "../../state/use-atom-command";
36 import { retargetSavedNewTaskDraft } from "../../state/use-composer-drafts";
37 import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
38 import type { WorkspaceState } from "../../state/workspaceModel";
39 import type { MessageResolver } from "../../i18n/messages";
40 import { useWorkspaceState } from "../../state/workspace";
41
42 import { useIncomingShare } from "../sharing/IncomingShareProvider";
43 import { useNewTaskFlow } from "./new-task-flow-provider";
44 import {
45 filterProjectScopes,
46 getProjectScopeSelectionTarget,
47 resolveNewTaskScratchOption,
48 } from "./new-task-project-selection";
49 import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail";
50
51 type NewTaskRouteParams = {
52 readonly incomingShareId?: string | string[];
53 /** An existing draft whose project is gone; the chosen project takes it over. */
54 readonly draftId?: string | string[];
55 readonly prompt?: string | string[];
56 readonly repo?: string | string[];
57 readonly pr?: string | string[];
58 readonly provider?: string | string[];
59 readonly model?: string | string[];
60 };
61
62 function deriveProjectEmptyState(
63 catalogState: WorkspaceState,
64 resolve: MessageResolver,
65 ): {
66 readonly title: string;
67 readonly detail: string;
68 readonly loading: boolean;
69 } {
70 if (catalogState.isLoadingConnections) {
71 return {
72 title: resolve(msg("Loading environments")),
73 detail: resolve(msg("Checking saved environments on this device.")),
74 loading: true,
75 };
76 }
77
78 if (!catalogState.hasConnections) {
79 return {
80 title: resolve(msg("No environments connected")),
81 detail: resolve(msg("Add an environment before creating a task.")),
82 loading: false,
83 };
84 }
85
86 if (
87 (catalogState.connectionState === "available" ||
88 catalogState.connectionState === "offline" ||
89 catalogState.connectionState === "error" ||
90 catalogState.connectionState === "unsupported") &&
91 !catalogState.hasLoadedShellSnapshot
92 ) {
93 return {
94 title:
95 catalogState.connectionState === "unsupported"
96 ? resolve(msg("Client not supported"))
97 : resolve(msg("Environment unavailable")),
98 detail:
99 runtimeConnectionErrorText(catalogState, resolve) ??
100 resolve(
101 msg(
102 "The saved environment is offline. Check the URL or start the environment, then retry.",
103 ),
104 ),
105 loading: false,
106 };
107 }
108
109 if (
110 catalogState.hasConnectingEnvironment &&
111 !catalogState.hasLoadedShellSnapshot &&
112 catalogState.connectionError === null
113 ) {
114 return {
115 title: resolve(msg("Connecting to environment")),
116 detail: resolve(msg("Loading projects from the saved environment.")),
117 loading: true,
118 };
119 }
120
121 return {
122 title: resolve(msg("No projects found")),
123 detail: resolve(msg("The connected environment did not report any projects.")),
124 loading: false,
125 };
126 }
127
128 function NewTaskHeader(props: {
129 readonly title: string;
130 readonly subtitle: string | null;
131 readonly canAddProject: boolean;
132 readonly searchText: string;
133 readonly onSearchTextChange: (text: string) => void;
134 }) {
135 const gt = useGT();
136 const navigation = useNavigation();
137 const goBack = () => {
138 if (navigation.canGoBack()) navigation.goBack();
139 else navigation.getParent()?.goBack();
140 };
141 return (
142 <>
143 <AppBar
144 title={props.title}
145 subtitle={props.subtitle ?? undefined}
146 hideBottomBorder
147 onBack={goBack}
148 actions={
149 props.canAddProject
150 ? [
151 {
152 accessibilityLabel: gt("Add project"),
153 icon: "plus",
154 onPress: () => navigation.dispatch(StackActions.push("AddProject")),
155 },
156 ]
157 : []
158 }
159 search={{
160 value: props.searchText,
161 onChangeText: props.onSearchTextChange,
162 placeholder: gt("Search projects"),
163 }}
164 />
165 </>
166 );
167 }
168
169 export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
170 const gt = useGT();
171 const m = useMessages();
172 const projects = useProjects();
173 const [searchText, setSearchText] = useState("");
174 const { projectScopes, selectedEnvironmentId, setProject } = useNewTaskFlow();
175 const { state: catalogState } = useWorkspaceState();
176 const navigation = useNavigation();
177 const selectDetail = useSelectWorkspaceDetail();
178 const isFocused = useIsFocused();
179 const insets = useSafeAreaInsets();
180 const { getShare, releaseShareReservation } = useIncomingShare();
181 const routeShareId = Array.isArray(route.params?.incomingShareId)
182 ? route.params.incomingShareId[0]
183 : route.params?.incomingShareId;
184 const incomingShare = routeShareId ? getShare(routeShareId) : null;
185 const routeDraftId = Array.isArray(route.params?.draftId)
186 ? route.params.draftId[0]
187 : route.params?.draftId;
188 const incomingShareSubtitle = incomingShare
189 ? incomingShare.attachments.length === 0
190 ? gt("Choose a project for what you shared")
191 : incomingShare.attachments.length === 1
192 ? incomingShare.attachments[0]?.type === "image"
193 ? gt("Choose a project for the image you shared")
194 : gt("Choose a project for the file you shared")
195 : incomingShare.attachments.every((attachment) => attachment.type === "image")
196 ? gt("{count, plural, other {Choose a project for the {count} images you shared}}", {
197 count: incomingShare.attachments.length,
198 })
199 : gt("{count, plural, other {Choose a project for the {count} files you shared}}", {
200 count: incomingShare.attachments.length,
201 })
202 : null;
203 const screenTitle = incomingShare ? gt("Start a task") : gt("Choose project");
204 const projectEmptyState = deriveProjectEmptyState(catalogState, m);
205 const serverConfigs = useServerConfigs();
206 const listScopes = pickableProjectGroups(projectScopes).filter(
207 (scope) =>
208 !scope.projects.every((project) =>
209 isScratchProject(project, serverConfigs.get(project.environmentId)?.scratchWorkspaceRoot),
210 ),
211 );
212 const visibleScopes = filterProjectScopes(listScopes, searchText);
213 const resumedDestinationKeyRef = useRef<string | null>(null);
214 const reservedDestinationProject = incomingShare?.destination
215 ? (projects.find(
216 (project) =>
217 project.environmentId === incomingShare.destination?.environmentId &&
218 project.id === incomingShare.destination?.projectId,
219 ) ?? null)
220 : null;
221 const { connectedEnvironments } = useRemoteConnectionStatus();
222 const connectedEnvironmentIds = new Set(
223 connectedEnvironments
224 .filter((environment) => environment.connectionState === "connected")
225 .map((environment) => environment.environmentId),
226 );
227 const openScratch = useAtomCommand(projectEnvironment.openScratch, {
228 reportFailure: false,
229 });
230 const scratchOption =
231 reservedDestinationProject === null
232 ? resolveNewTaskScratchOption({
233 environments: connectedEnvironments,
234 serverConfigs,
235 selectedEnvironmentId,
236 })
237 : null;
238 const canStartScratch = scratchOption?.ready === true;
239 const pendingScratchRef = useRef<AbortController | null>(null);
240 const cancelPendingScratch = useCallback(() => {
241 pendingScratchRef.current?.abort();
242 pendingScratchRef.current = null;
243 }, []);
244 useFocusEffect(useCallback(() => cancelPendingScratch, [cancelPendingScratch]));
245
246 async function selectProject(project: EnvironmentProject, signal?: AbortSignal): Promise<void> {
247 if (incomingShare?.destination && !reservedDestinationProject) {
248 try {
249 await releaseShareReservation(incomingShare.id, incomingShare.destination);
250 } catch (error) {
251 if (signal?.aborted) return;
252 Dialog.alert(
253 gt("Could not change project"),
254 errorDisplayMessage(error, m) ??
255 gt("The shared content reservation could not be updated."),
256 );
257 return;
258 }
259 if (signal?.aborted) return;
260 }
261 const root = navigation.getState()?.routeNames.includes("NewTaskProject")
262 ? navigation
263 : navigation.getParent();
264 const rootState = root?.getState();
265 const threadRoute = rootState?.routes[rootState.index - 1];
266 if (routeDraftId === undefined && isDraftThreadRoute(threadRoute)) {
267 setProject(project);
268 root?.goBack();
269 return;
270 }
271 // Restamp only on choice, so backing out leaves the draft as it was.
272 const retargeted =
273 routeDraftId === undefined
274 ? false
275 : await retargetSavedNewTaskDraft(
276 routeDraftId,
277 { environmentId: project.environmentId, projectId: project.id },
278 signal,
279 ).then(
280 (found) => found,
281 () => null,
282 );
283 if (signal?.aborted) return;
284 if (retargeted === null) {
285 Dialog.alert(
286 gt("Could not change project"),
287 gt("Saved drafts could not be loaded. Try again."),
288 );
289 return;
290 }
291 const draftId = retargeted ? routeDraftId : undefined;
292 selectDetail({
293 name: "Thread",
294 params: {
295 draft: {
296 environmentId: String(project.environmentId),
297 projectId: String(project.id),
298 draftId,
299 incomingShareId: incomingShare?.id,
300 },
301 },
302 });
303 }
304
305 function chooseProject(project: EnvironmentProject): void {
306 cancelPendingScratch();
307 void selectProject(project);
308 }
309
310 async function startScratch(): Promise<void> {
311 if (!canStartScratch || !scratchOption || pendingScratchRef.current) return;
312 const environmentId = scratchOption.environmentId;
313 const request = new AbortController();
314 pendingScratchRef.current = request;
315 const result = await openScratch({ environmentId, input: {} });
316 if (request.signal.aborted) return;
317 if (result._tag === "Failure") {
318 pendingScratchRef.current = null;
319 if (!isAtomCommandInterrupted(result)) {
320 const error = squashAtomCommandFailure(result);
321 Dialog.alert(
322 gt("Could not start without a project"),
323 errorDisplayMessage(error, m) ??
324 gt("The folder for threads without a project could not be created."),
325 );
326 }
327 return;
328 }
329 await selectProject(result.value, request.signal);
330 if (pendingScratchRef.current === request) pendingScratchRef.current = null;
331 }
332
333 // 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
334 useEffect(() => {
335 const destination = incomingShare?.destination;
336 if (!destination) {
337 resumedDestinationKeyRef.current = null;
338 return;
339 }
340 if (!isFocused) {
341 // Reset on return so reserved-draft resume can retry without leaving project rows disabled.
342 resumedDestinationKeyRef.current = null;
343 return;
344 }
345 const destinationKey = `${incomingShare.id}:${destination.environmentId}:${destination.projectId}`;
346 if (resumedDestinationKeyRef.current === destinationKey) {
347 return;
348 }
349 if (!reservedDestinationProject) {
350 return;
351 }
352 resumedDestinationKeyRef.current = destinationKey;
353 selectDetail({
354 name: "Thread",
355 params: {
356 draft: {
357 environmentId: reservedDestinationProject.environmentId,
358 projectId: reservedDestinationProject.id,
359 title: reservedDestinationProject.title,
360 incomingShareId: incomingShare.id,
361 },
362 },
363 });
364 }, [incomingShare, isFocused, reservedDestinationProject, selectDetail]);
365
366 return (
367 <View collapsable={false} className="flex-1 bg-sheet">
368 <NewTaskHeader
369 title={screenTitle}
370 subtitle={incomingShareSubtitle}
371 canAddProject={catalogState.hasReadyEnvironment}
372 searchText={searchText}
373 onSearchTextChange={setSearchText}
374 />
375
376 <ScreenContent>
377 <ScrollView
378 contentInsetAdjustmentBehavior="automatic"
379 showsVerticalScrollIndicator={false}
380 keyboardShouldPersistTaps="handled"
381 keyboardDismissMode="on-drag"
382 className="flex-1"
383 contentContainerStyle={{
384 gap: Platform.OS === "android" ? 8 : 12,
385 paddingBottom: Math.max(insets.bottom, 18) + 18,
386 paddingHorizontal: Platform.OS === "android" ? 16 : 20,
387 paddingTop: Platform.OS === "android" ? 16 : 8,
388 ...(Platform.OS === "android" && visibleScopes.length === 0
389 ? { flexGrow: 1, justifyContent: "center" as const }
390 : {}),
391 }}
392 >
393 {scratchOption !== null && listScopes.length > 0 ? (
394 Platform.OS === "android" ? (
395 <View collapsable={false} className="overflow-hidden rounded-[28px] bg-grouped-card">
396 <NavigationRow
397 className="bg-grouped-card"
398 title={gt("No project")}
399 subtitle={gt("Start a task without a project")}
400 disabled={!canStartScratch}
401 onPress={() => void startScratch()}
402 leading={
403 <SymbolView
404 name="text.bubble"
405 size={22}
406 tintColorClassName="accent-icon-muted"
407 type="monochrome"
408 />
409 }
410 />
411 </View>
412 ) : (
413 <View collapsable={false} className="overflow-hidden rounded-[24px] bg-grouped-card">
414 <Pressable
415 accessibilityRole="button"
416 accessibilityLabel={gt("No project")}
417 disabled={!canStartScratch}
418 onPress={() => void startScratch()}
419 className={cn(
420 "flex-row items-center gap-3 bg-grouped-card px-4 py-3.5",
421 !canStartScratch && "opacity-45",
422 )}
423 >
424 <View className="h-7 w-7 items-center justify-center">
425 <SymbolView
426 name="text.bubble"
427 size={18}
428 tintColorClassName="accent-icon-muted"
429 type="monochrome"
430 />
431 </View>
432 <View className="min-w-0 flex-1">
433 <Text className="text-base font-t3-bold leading-snug">
434 <T>No project</T>
435 </Text>
436 <Text className="text-xs leading-snug text-foreground-muted" numberOfLines={1}>
437 <T>Start a task without a project</T>
438 </Text>
439 </View>
440 <SymbolView
441 name="chevron.right"
442 size={14}
443 tintColorClassName="accent-chevron"
444 type="monochrome"
445 />
446 </Pressable>
447 </View>
448 )
449 ) : null}
450 {listScopes.length === 0 ? (
451 <View
452 collapsable={false}
453 className={cn(
454 "items-center gap-3 px-6 py-8",
455 Platform.OS !== "android" && "rounded-[24px] bg-grouped-card",
456 )}
457 >
458 {projectEmptyState.loading ? (
459 <AppActivityIndicator colorClassName="accent-icon-muted" />
460 ) : null}
461 <Text className="text-center text-lg font-t3-bold text-foreground">
462 {projectEmptyState.title}
463 </Text>
464 <Text className="text-center text-sm leading-normal text-foreground-muted">
465 {projectEmptyState.detail}
466 </Text>
467 {Platform.OS === "android" ? (
468 <>
469 <View>
470 <Button
471 label={
472 catalogState.hasReadyEnvironment
473 ? gt("Add new project")
474 : gt("Add environment")
475 }
476 tone="primary"
477 onPress={() =>
478 catalogState.hasReadyEnvironment
479 ? navigation.dispatch(StackActions.push("AddProject"))
480 : navigation.navigate("ConnectionsNew")
481 }
482 />
483 </View>
484 {canStartScratch ? (
485 <View>
486 <Button
487 label={gt("Start without a project")}
488 tone="secondary"
489 onPress={() => void startScratch()}
490 />
491 </View>
492 ) : null}
493 </>
494 ) : !catalogState.hasReadyEnvironment ? (
495 <View className="mt-1">
496 <Button
497 label={gt("Add environment")}
498 tone="primary"
499 onPress={() => navigation.navigate("ConnectionsNew")}
500 />
501 </View>
502 ) : (
503 <>
504 <View className="mt-1">
505 <Button
506 label={gt("Add new project")}
507 tone="primary"
508 onPress={() => navigation.dispatch(StackActions.push("AddProject"))}
509 />
510 </View>
511 {canStartScratch ? (
512 <View>
513 <Button
514 label={gt("Start without a project")}
515 tone="secondary"
516 onPress={() => void startScratch()}
517 />
518 </View>
519 ) : null}
520 </>
521 )}
522 </View>
523 ) : visibleScopes.length === 0 ? (
524 <View className="items-center gap-2 px-6 py-8">
525 <Text className="text-center text-lg font-t3-bold text-foreground">
526 <T>No matching projects</T>
527 </Text>
528 <Text className="text-center text-sm leading-normal text-foreground-muted">
529 <T>Try a different project name or workspace path.</T>
530 </Text>
531 </View>
532 ) : (
533 <View
534 collapsable={false}
535 className={
536 Platform.OS === "android"
537 ? "overflow-hidden rounded-[28px] bg-grouped-card"
538 : "overflow-hidden rounded-[24px] bg-grouped-card"
539 }
540 >
541 {visibleScopes.map((scope, scopeIndex) => {
542 const hasMultipleProjects = scope.projects.length > 1;
543 const selectionTarget = getProjectScopeSelectionTarget(
544 scope,
545 selectedEnvironmentId,
546 connectedEnvironmentIds,
547 );
548 if (Platform.OS === "android") {
549 return (
550 <NavigationRow
551 className="bg-grouped-card"
552 key={scope.key}
553 title={scope.title}
554 subtitle={
555 hasMultipleProjects
556 ? gt("{count, plural, other {{count} workspaces}}", {
557 count: scope.projects.length,
558 })
559 : selectionTarget.workspaceRoot
560 }
561 subtitleNumberOfLines={1}
562 subtitleEllipsizeMode="middle"
563 disabled={reservedDestinationProject !== null}
564 onPress={() => chooseProject(selectionTarget)}
565 leading={
566 <ProjectFavicon
567 environmentId={scope.representative.environmentId}
568 faviconPath={scope.representative.faviconPath}
569 projectIcon={scope.representative.projectIcon}
570 size={24}
571 projectTitle={scope.representative.title}
572 workspaceRoot={scope.representative.workspaceRoot}
573 />
574 }
575 />
576 );
577 }
578 return (
579 <View
580 key={scope.key}
581 className={cn(scopeIndex > 0 && "border-t border-border-subtle")}
582 >
583 <Pressable
584 accessibilityRole="button"
585 accessibilityLabel={scope.title}
586 disabled={reservedDestinationProject !== null}
587 onPress={() => chooseProject(selectionTarget)}
588 className="flex-row items-center gap-3 bg-grouped-card px-4 py-3.5"
589 >
590 <View className="h-7 w-7 items-center justify-center">
591 <ProjectFavicon
592 environmentId={scope.representative.environmentId}
593 faviconPath={scope.representative.faviconPath}
594 projectIcon={scope.representative.projectIcon}
595 size={20}
596 projectTitle={scope.representative.title}
597 workspaceRoot={scope.representative.workspaceRoot}
598 />
599 </View>
600 <View className="min-w-0 flex-1">
601 <Text className={cn("text-base leading-snug", "font-t3-bold")}>
602 {scope.title}
603 </Text>
604 <Text
605 className="text-xs leading-snug text-foreground-muted"
606 ellipsizeMode="middle"
607 numberOfLines={1}
608 >
609 {hasMultipleProjects
610 ? gt("{count, plural, other {{count} workspaces}}", {
611 count: scope.projects.length,
612 })
613 : selectionTarget.workspaceRoot}
614 </Text>
615 </View>
616 <SymbolView
617 name="chevron.right"
618 size={14}
619 tintColorClassName="accent-chevron"
620 type="monochrome"
621 />
622 </Pressable>
623 </View>
624 );
625 })}
626 </View>
627 )}
628 </ScrollView>
629 </ScreenContent>
630 </View>
631 );
632 }