@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 1,107 lines 41.9 KB
Raw
1 import { T, useGT, useMessages, Var } from "gt-react-native";
2 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3 import { DraftEnvironmentControl } from "./DraftEnvironmentControl";
4 import { NativeScrollEdgeEffectsContext } from "../../native/NativeScrollViewMarker";
5 import { DraftThreadHeader } from "./DraftThreadHeader";
6 import { useComposerAttachmentActions } from "../../state/use-composer-attachment-actions";
7 import { useWorkspaceBackNavigation } from "../layout/workspace/useAndroidWorkspaceNavigation";
8 import { submittedThreadParams } from "./thread-route-state";
9 import { ThreadScreenBinding, ThreadScreenFallback } from "./ThreadScreenHost";
10 import { draftThreadShell } from "./draft-thread-shell";
11 import { useRememberThreadProject } from "./useRememberThreadProject";
12 import { scopedProjectKey } from "../../lib/scopedEntities";
13 import { connectionTone } from "../connection/connectionTone";
14 import { runtimeConnectionErrorText } from "../connection/environmentStatusText";
15 import { AppBar } from "../../components/ui/AppBar";
16 import { ThreadId } from "@t3tools/contracts";
17
18 import * as Dialog from "../../components/ui/Dialog";
19 import { useAtomValue } from "@effect/atom-react";
20 import * as Cause from "effect/Cause";
21 import { AsyncResult } from "effect/reactivity";
22 import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping";
23 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
24 import {
25 CommonActions,
26 StackActions,
27 useIsFocused,
28 useNavigation,
29 usePreventRemove,
30 useRoute,
31 } from "@react-navigation/native";
32 import { useEffect, useRef, useState } from "react";
33 import { Platform, Pressable, View } from "react-native";
34 import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
35 import { KeyboardController } from "react-native-keyboard-controller";
36
37 import {
38 AuthOrchestrationOperateScope,
39 DEFAULT_PROVIDER_INTERACTION_MODE,
40 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
41 resolveEnvironmentMachineKind,
42 } from "@t3tools/contracts";
43
44 import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
45 import { composerContextImportsAtom } from "../../state/use-composer-drafts";
46 import { abortComposerDraftOperations } from "../../state/composerDraftOperations";
47 import { composerContextSendBlockReason } from "../../lib/composerContext";
48 import { ComposerInlineControl } from "../../components/ComposerToolbar";
49
50 import {
51 composerAttachmentUploadBlockReason,
52 composerAttachmentsStillUploading,
53 composerAttachmentUploadsAtom,
54 } from "../../state/composer-attachment-uploads";
55
56 import { SymbolView } from "../../components/ui/AppSymbol";
57 import { AppText as Text } from "../../components/ui/AppText";
58 import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences";
59
60 import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
61
62 import {
63 clearComposerDraftContent,
64 getComposerDraftSnapshot,
65 updateComposerDraftSettings,
66 scheduleUnusedComposerAttachmentCleanup,
67 } from "../../state/use-composer-drafts";
68 import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
69 import { useProjectClone } from "../../state/projectClones";
70 import { projectEnvironment } from "../../state/projects";
71 import { sourceControlEnvironment } from "../../state/sourceControl";
72 import { useAtomCommand } from "../../state/use-atom-command";
73 import { ProjectCloneBanner } from "./ProjectCloneBanner";
74 import {
75 describeUnavailableModelSelection,
76 isModelSelectionUnavailable,
77 resolveSelectableModelSelection,
78 } from "../../lib/modelOptions";
79 import { enqueueThreadOutboxMessage } from "../../state/thread-outbox";
80 import {
81 useRemoteConnections,
82 useRemoteEnvironmentRuntime,
83 } from "../../state/use-remote-environment-registry";
84 import { useNewTaskFlow } from "./new-task-flow-provider";
85 import {
86 nextEnvironmentId,
87 useHardwareKeyboardCommand,
88 } from "../keyboard/hardwareKeyboardCommands";
89 import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation";
90 import { resolveDraftProjectSelection } from "./new-task-project-selection";
91 import {
92 resolveNewTaskBranchLabel,
93 resolveNewTaskWorkspaceLabel,
94 } from "./new-task-context-presentation";
95 import { incomingShareImports, useIncomingShare } from "../sharing/IncomingShareProvider";
96 import { idleShareFlagAtom, idleShareImportPhaseAtom } from "./incomingShareImport";
97 import { newTaskFlowKey } from "./new-task-flow-state";
98 import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
99 import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";
100 import { appAtomRegistry } from "../../state/atom-registry";
101 import { mobilePreferencesAtom } from "../../state/preferences";
102
103 import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
104
105 // Below this (keyboard up on iPad, phone landscape) the hero cannot fit above the composer,
106 // so the project and environment pickers move into the composer controls instead.
107 const SHORT_DRAFT_VIEWPORT_HEIGHT = 380;
108 const HEADING_PROJECT_SLOT = "\uE000";
109
110 function NewTaskWorkspaceIcon(props: {
111 readonly workspaceMode: "local" | "worktree";
112 readonly worktreePath: string | null;
113 readonly size: number;
114 }) {
115 if (props.workspaceMode === "local" && props.worktreePath === null) {
116 return (
117 <SymbolView
118 name="folder"
119 size={props.size}
120 tintColorClassName="accent-icon-muted"
121 type="monochrome"
122 />
123 );
124 }
125
126 const boxSize = (14 * props.size) / 16;
127 return (
128 <View
129 className="size-4"
130 style={Platform.OS === "android" ? { width: boxSize, height: boxSize } : undefined}
131 >
132 <SymbolView
133 name="folder"
134 size={props.size}
135 tintColorClassName="accent-icon-muted"
136 type="monochrome"
137 />
138 <View
139 className="absolute -right-1 -bottom-1"
140 style={
141 Platform.OS === "android" ? { right: -boxSize / 4, bottom: -boxSize / 4 } : undefined
142 }
143 >
144 <SymbolView
145 name="arrow.triangle.branch"
146 size={Math.round((9 * props.size) / 16)}
147 tintColorClassName="accent-icon-muted"
148 type="monochrome"
149 />
150 </View>
151 </View>
152 );
153 }
154
155 export function NewTaskDraftScreen(props: {
156 readonly initialProjectRef?: {
157 readonly environmentId?: string;
158 readonly projectId?: string;
159 readonly branch?: string | null;
160 readonly worktreePath?: string | null;
161 readonly cloning?: boolean;
162 };
163 readonly draftId?: string;
164 readonly incomingShareId?: string;
165 }) {
166 const gt = useGT();
167 const m = useMessages();
168 const [creationMetadata] = useState(makeTurnCommandMetadata);
169 const projects = useProjects();
170 const flow = useNewTaskFlow();
171 const navigation = useNavigation();
172 const isFocused = useIsFocused();
173 const goBack = useWorkspaceBackNavigation();
174 const currentRoute = useRoute();
175 const flowKey = newTaskFlowKey(currentRoute);
176 const { getShare, isLoading: isIncomingShareInboxLoading } = useIncomingShare();
177 const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
178 // selectedProject falls back to the environment's first project; remember only a chosen one.
179 useRememberThreadProject(
180 selectedProject &&
181 selectedProjectKey === scopedProjectKey(selectedProject.environmentId, selectedProject.id)
182 ? selectedProject
183 : null,
184 );
185 const selectedProjectLabel = (() => {
186 if (!selectedProject) return null;
187 const scope = projectScopes.find((candidate) =>
188 candidate.projectRefs.some(
189 (ref) =>
190 ref.environmentId === selectedProject.environmentId &&
191 ref.projectId === selectedProject.id,
192 ),
193 );
194 return scope?.title ?? selectedProject.title;
195 })();
196 const { onReconnectEnvironment } = useRemoteConnections();
197 const environmentRuntime = useRemoteEnvironmentRuntime(selectedProject?.environmentId ?? null);
198 const connectionState = environmentRuntime?.connectionState ?? "offline";
199 const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
200 selectedProject?.environmentId ?? null,
201 );
202 const environmentConnected = connectionState === "connected";
203 const canOperate = useEnvironmentScope(
204 selectedProject?.environmentId ?? null,
205 AuthOrchestrationOperateScope,
206 );
207 const projectCloneState = useProjectClone(
208 selectedProject
209 ? { environmentId: selectedProject.environmentId, projectId: selectedProject.id }
210 : null,
211 );
212 const projectClone = projectCloneState === "pending" ? null : projectCloneState;
213 const awaitingKnownClone =
214 projectCloneState === "pending" &&
215 props.initialProjectRef?.cloning === true &&
216 selectedProject !== null &&
217 selectedProject.id === props.initialProjectRef.projectId &&
218 selectedProject.environmentId === props.initialProjectRef.environmentId;
219 const cloneBlocksStart =
220 awaitingKnownClone || (projectClone !== null && projectClone.phase !== "done");
221 const cancelProjectClone = useAtomCommand(sourceControlEnvironment.cancelProjectClone, {
222 reportFailure: false,
223 });
224 const retryProjectClone = useAtomCommand(sourceControlEnvironment.retryProjectClone, {
225 reportFailure: false,
226 });
227 const runCloneAction = async (
228 title: string,
229 action: () => Promise<AsyncResult.AsyncResult<unknown, unknown>>,
230 ) => {
231 const result = await action();
232 if (AsyncResult.isFailure(result)) {
233 const error = Cause.squash(result.cause);
234 Dialog.alert(title, errorDisplayMessage(error, m) ?? gt("An error occurred."));
235 }
236 };
237 const deleteProject = useAtomCommand(projectEnvironment.delete, { reportFailure: false });
238 const removeClonedProject = async () => {
239 if (!selectedProject) return;
240 const removed = selectedProject;
241 const result = await deleteProject({
242 environmentId: removed.environmentId,
243 input: { projectId: removed.id },
244 });
245 if (AsyncResult.isFailure(result)) {
246 const error = Cause.squash(result.cause);
247 Dialog.alert(
248 gt("Failed to remove project"),
249 errorDisplayMessage(error, m) ?? gt("An error occurred."),
250 );
251 return;
252 }
253 if (flow.getSelectedProjectKey() === scopedProjectKey(removed.environmentId, removed.id)) {
254 navigation.dispatch(StackActions.replace("Home"));
255 }
256 };
257 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
258 const attachmentBlockReason = selectedProject
259 ? composerAttachmentUploadBlockReason(
260 {
261 environmentId: selectedProject.environmentId,
262 attachments: flow.attachments,
263 connected: environmentConnected,
264 serverConfig: selectedEnvironmentServerConfig,
265 states: uploadStates,
266 },
267 m,
268 )
269 : null;
270 const attachmentsUploading =
271 environmentConnected &&
272 selectedProject !== null &&
273 composerAttachmentsStillUploading({
274 environmentId: selectedProject.environmentId,
275 attachments: flow.attachments,
276 serverConfig: selectedEnvironmentServerConfig,
277 states: uploadStates,
278 });
279 const queuesInsteadOfStarting = !environmentConnected || attachmentsUploading;
280 const promptInputRef = useRef<ComposerEditorHandle>(null);
281 const loadedBranchesProjectKeyRef = useRef<string | null>(null);
282 const [isReturningToProjectPicker, setIsReturningToProjectPicker] = useState(false);
283 const incomingShare = props.incomingShareId ? getShare(props.incomingShareId) : null;
284 const requestedInitialProjectAvailable = Boolean(
285 props.initialProjectRef?.environmentId &&
286 props.initialProjectRef.projectId &&
287 projects.some(
288 (project) =>
289 project.environmentId === props.initialProjectRef?.environmentId &&
290 project.id === props.initialProjectRef?.projectId,
291 ),
292 );
293 // A route naming a draft that is gone, or whose project is gone, also
294 // returns to the picker; a draft that survives goes along with it.
295 const unopenableRouteDraftKind =
296 props.draftId !== undefined && flow.unopenableRouteDraft?.draftId === props.draftId
297 ? flow.unopenableRouteDraft.kind
298 : null;
299 const pickerDraftId = unopenableRouteDraftKind === "pickProject" ? props.draftId : undefined;
300 const isProjectPickerReturnActive =
301 (isReturningToProjectPicker && !requestedInitialProjectAvailable) ||
302 unopenableRouteDraftKind !== null;
303 const isIncomingShareAwaitingServerConfig = Boolean(
304 incomingShare?.attachments.some((attachment) => attachment.type === "file") &&
305 selectedEnvironmentServerConfig === null,
306 );
307 const routeImportedShare = useAtomValue(
308 flowKey !== undefined && props.incomingShareId
309 ? incomingShareImports.importedAtom(flowKey, props.incomingShareId)
310 : idleShareFlagAtom,
311 );
312 const hasImportedIncomingShare = Boolean(
313 props.incomingShareId &&
314 (routeImportedShare ||
315 (flow.draftKey &&
316 getComposerDraftSnapshot(flow.draftKey).importedShareIds?.includes(props.incomingShareId))),
317 );
318 const isIncomingShareUnavailable = Boolean(
319 props.incomingShareId &&
320 !isIncomingShareInboxLoading &&
321 !incomingShare &&
322 !hasImportedIncomingShare,
323 );
324 const shareImportTarget = (() => {
325 if (!props.incomingShareId || flowKey === undefined || !flow.draftKey) return null;
326 if (!selectedProject || !incomingShare || isIncomingShareAwaitingServerConfig) return null;
327 const initialEnvironmentId = props.initialProjectRef?.environmentId;
328 const initialProjectId = props.initialProjectRef?.projectId;
329 if (
330 initialEnvironmentId &&
331 initialProjectId &&
332 (selectedProject.environmentId !== initialEnvironmentId ||
333 selectedProject.id !== initialProjectId)
334 ) {
335 return null;
336 }
337 return {
338 flowKey,
339 routeKey: currentRoute.key,
340 draftKey: flow.draftKey,
341 destination: {
342 environmentId: String(selectedProject.environmentId),
343 projectId: String(selectedProject.id),
344 },
345 shareId: incomingShare.id,
346 };
347 })();
348 const shareImportPhase = useAtomValue(
349 shareImportTarget === null
350 ? idleShareImportPhaseAtom
351 : incomingShareImports.phaseAtom(shareImportTarget),
352 );
353 // Locks on the route, not the target: the target turns null when server config
354 // drops or the project stops matching, while the import keeps writing the draft.
355 const isImportingShare = useAtomValue(
356 flowKey === undefined ? idleShareFlagAtom : incomingShareImports.inFlightAtom(flowKey),
357 );
358 const isIncomingShareTransferPending = Boolean(
359 incomingShare && shareImportPhase !== "cancelled" && !isIncomingShareAwaitingServerConfig,
360 );
361 // A failed import waits in a modal alert, and a cancel finishes its undo even
362 // after the route leaves, so neither holds the route: the cancel can leave as
363 // soon as it is done.
364 const isIncomingShareHoldingRoute =
365 isIncomingShareTransferPending &&
366 shareImportPhase !== "failed" &&
367 shareImportPhase !== "cancelling";
368 const contextImports = useAtomValue(composerContextImportsAtom);
369 const isImportingContext = flow.draftKey ? contextImports[flow.draftKey] === true : false;
370 const isComposerInteractionLocked =
371 isIncomingShareTransferPending || flow.submitting || isImportingContext;
372 const { environments, selectedEnvironmentId, switchEnvironment, switchingToEnvironmentId } = flow;
373 const cycleEnvironment = () => {
374 if (isComposerInteractionLocked) return true;
375 const next = nextEnvironmentId(environments, switchingToEnvironmentId ?? selectedEnvironmentId);
376 if (next !== null) void switchEnvironment(next);
377 return true;
378 };
379 const cycleEnvironmentCommands = environments.length > 1 ? (["cycleHost"] as const) : [];
380 useHardwareKeyboardCommand(cycleEnvironmentCommands, cycleEnvironment);
381 const preventRemove =
382 (isIncomingShareHoldingRoute && !isProjectPickerReturnActive) || flow.submitting;
383 usePreventRemove(preventRemove, () => undefined);
384 const isIncomingShareReady =
385 !props.incomingShareId ||
386 (hasImportedIncomingShare && !incomingShare) ||
387 isIncomingShareUnavailable;
388 const appliedInitialProjectKeyRef = useRef<string | null>(null);
389 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- ends the picker return once the project arrives, else replaces the route with the picker next frame
390 useEffect(() => {
391 if (isReturningToProjectPicker && requestedInitialProjectAvailable) {
392 // oxlint-disable-next-line react/set-state-in-effect -- Ends the return-to-picker flow once the requested project arrives from the catalog.
393 setIsReturningToProjectPicker(false);
394 }
395 if (!isProjectPickerReturnActive) {
396 return;
397 }
398 // Wait for usePreventRemove to disable before replacing, or the transfer guard swallows the fallback.
399 const frame = requestAnimationFrame(() => {
400 navigation.dispatch(
401 StackActions.replace("NewTaskProject", {
402 incomingShareId: props.incomingShareId,
403 draftId: pickerDraftId,
404 }),
405 );
406 });
407 return () => cancelAnimationFrame(frame);
408 }, [
409 isProjectPickerReturnActive,
410 isReturningToProjectPicker,
411 navigation,
412 pickerDraftId,
413 props.incomingShareId,
414 requestedInitialProjectAvailable,
415 ]);
416
417 const lastInitialProjectRefRef = useRef(props.initialProjectRef);
418 const initialPickerRef = useRef<"open" | "dismissed" | null>(null);
419
420 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- applies the route or catalog project to the draft once projects load, or opens the picker in the navigator
421 useEffect(() => {
422 if (props.draftId) {
423 return;
424 }
425 if (lastInitialProjectRefRef.current !== props.initialProjectRef) {
426 lastInitialProjectRefRef.current = props.initialProjectRef;
427 appliedInitialProjectKeyRef.current = null;
428 }
429 const initialEnvironmentId = props.initialProjectRef?.environmentId;
430 const initialProjectId = props.initialProjectRef?.projectId;
431 if (initialEnvironmentId && initialProjectId) {
432 const directProject =
433 projects.find(
434 (project) =>
435 project.environmentId === initialEnvironmentId && project.id === initialProjectId,
436 ) ?? null;
437
438 if (directProject) {
439 // Apply the route project once or picker changes would immediately revert.
440 const directProjectKey = `${directProject.environmentId}:${directProject.id}`;
441 if (appliedInitialProjectKeyRef.current === directProjectKey) {
442 return;
443 }
444 // setProject creates the draft, so it also runs when the fallback already shows this project.
445 const showsDirectProject =
446 flow.draftKey !== null &&
447 selectedProject?.environmentId === directProject.environmentId &&
448 selectedProject.id === directProject.id;
449 if (props.initialProjectRef?.branch) {
450 if (!showsDirectProject || !flow.draftKey) {
451 setProject(directProject);
452 return;
453 }
454 // Checkout completed before mount; local mode reuses it while worktree mode would create another.
455 updateComposerDraftSettings(flow.draftKey, {
456 workspaceSelection: {
457 mode: "local",
458 branch: props.initialProjectRef.branch,
459 worktreePath: props.initialProjectRef.worktreePath ?? null,
460 startFromOrigin: false,
461 },
462 });
463 }
464 appliedInitialProjectKeyRef.current = directProjectKey;
465 if (showsDirectProject) return;
466 setProject(directProject);
467 return;
468 }
469
470 if (projects.length > 0) {
471 // oxlint-disable-next-line react/set-state-in-effect -- Route-driven project resolution starts the return-to-picker flow when no project matches.
472 setIsReturningToProjectPicker(true);
473 }
474 return;
475 }
476
477 const preferences = appAtomRegistry.get(mobilePreferencesAtom);
478 const saved = AsyncResult.isSuccess(preferences) ? preferences.value : undefined;
479 const selection = resolveDraftProjectSelection(
480 selectedProjectKey,
481 projects,
482 pickableProjectGroups(projectScopes),
483 {
484 incomingShareId: props.incomingShareId,
485 pickerClosed: initialPickerRef.current === "open" && isFocused,
486 useLastProject: saved?.useLastProjectForNewThreads,
487 lastProject: saved?.lastThreadProject,
488 },
489 );
490 if (selection.kind === "preserve") {
491 initialPickerRef.current = null;
492 return;
493 }
494 if (selection.kind === "select") {
495 setProject(selection.project);
496 return;
497 }
498 if (selection.kind === "dismiss") {
499 initialPickerRef.current = "dismissed";
500 goBack();
501 return;
502 }
503 // Open the first picker once; catalog updates must not push it again over a cancelled draft.
504 if (initialPickerRef.current !== null) {
505 return;
506 }
507 initialPickerRef.current = "open";
508 navigation.dispatch(CommonActions.navigate("NewTaskProject"));
509 }, [
510 goBack,
511 isFocused,
512 projectScopes,
513 projects,
514 flow.draftKey,
515 props.initialProjectRef,
516 props.incomingShareId,
517 props.draftId,
518 navigation,
519 selectedProject,
520 selectedProjectKey,
521 setProject,
522 ]);
523
524 const { loadBranches } = flow;
525 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- requests the selected project's branch list from the server once per project
526 useEffect(() => {
527 if (!selectedProject) {
528 loadedBranchesProjectKeyRef.current = null;
529 return;
530 }
531 const projectKey = `${selectedProject.environmentId}:${selectedProject.id}`;
532 if (loadedBranchesProjectKeyRef.current === projectKey) {
533 return;
534 }
535 loadedBranchesProjectKeyRef.current = projectKey;
536 loadBranches();
537 }, [loadBranches, selectedProject]);
538
539 const selectedEnvironmentLabel =
540 flow.environments.find(
541 (environment) => environment.environmentId === flow.selectedEnvironmentId,
542 )?.environmentLabel ?? gt("Environment");
543 const availableCurrentBranchName =
544 flow.availableBranches.find((branch) => branch.current)?.name ??
545 flow.availableBranches.find((branch) => branch.isDefault)?.name ??
546 null;
547 const selectedBranchName = resolveProjectThreadCreationBranch({
548 workspaceMode: flow.workspaceMode,
549 selectedBranch:
550 flow.selectedBranchName ??
551 (flow.workspaceMode === "worktree" ? availableCurrentBranchName : null),
552 currentCheckoutBranch: flow.currentCheckoutBranchName,
553 });
554 const selectedBranchLabel = resolveNewTaskBranchLabel(
555 {
556 branchName: selectedBranchName,
557 startFromOrigin: flow.startFromOrigin,
558 workspaceMode: flow.workspaceMode,
559 pullRequestReference: flow.pullRequestReference,
560 },
561 m,
562 );
563 const workspaceLabel = resolveNewTaskWorkspaceLabel(
564 {
565 workspaceMode: flow.workspaceMode,
566 worktreePath: flow.selectedWorktreePath,
567 },
568 m,
569 );
570 const showBranchLoading =
571 environmentConnected && flow.branchesLoading && flow.availableBranches.length === 0;
572
573 const {
574 onPickDraftMedia: handlePickMedia,
575 onPickDraftFiles: handlePickFiles,
576 onNativePasteImages: handleNativePasteImages,
577 onNativePasteText: handleNativePasteText,
578 } = useComposerAttachmentActions({
579 draftKey: flow.draftKey,
580 serverConfig: selectedEnvironmentServerConfig,
581 locked: isComposerInteractionLocked,
582 });
583
584 async function handleStart(): Promise<import("@t3tools/contracts").MessageId | null> {
585 const selectedProject = flow.selectedProject;
586 const draftKey = flow.draftKey;
587 if (
588 !selectedProject ||
589 !draftKey ||
590 cloneBlocksStart ||
591 !isIncomingShareReady ||
592 isImportingShare ||
593 isComposerInteractionLocked
594 ) {
595 return null;
596 }
597 if (
598 environmentConnected &&
599 !readEnvironmentScope(selectedProject.environmentId, AuthOrchestrationOperateScope)
600 ) {
601 return null;
602 }
603 const draft = getComposerDraftSnapshot(draftKey);
604 if (appAtomRegistry.get(composerContextImportsAtom)[draftKey]) return null;
605 const modelSelection =
606 resolveSelectableModelSelection(
607 selectedEnvironmentServerConfig,
608 draft.modelSelection ?? null,
609 selectedProject.id,
610 ) ?? flow.selectedModel;
611 const workspaceSelection = flow.resolveWorkspaceSelection(draft.workspaceSelection);
612 const workspaceMode = workspaceSelection.mode;
613 const selectedBranchName = workspaceSelection.branch;
614 const initialMessageText = draft.text.trim();
615
616 if (
617 attachmentBlockReason !== null ||
618 !modelSelection ||
619 (initialMessageText.length === 0 && draft.attachments.length === 0) ||
620 flow.submitting ||
621 (workspaceMode === "worktree" && !selectedBranchName)
622 ) {
623 return null;
624 }
625 if (
626 environmentConnected &&
627 isModelSelectionUnavailable(
628 selectedEnvironmentServerConfig,
629 modelSelection,
630 selectedProject.id,
631 )
632 ) {
633 const { title, detail } = describeUnavailableModelSelection(
634 selectedEnvironmentServerConfig,
635 modelSelection,
636 selectedProject.id,
637 );
638 Dialog.alert(title, detail);
639 return null;
640 }
641 // Recovery may retain over-cap attachments; block send before uploading a turn the server would reject.
642 if (draft.attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
643 Dialog.alert(
644 gt("Too many attachments"),
645 gt("Remove attachments until there are at most {max}.", {
646 max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
647 }),
648 );
649 return null;
650 }
651
652 const contextBlockReason = composerContextSendBlockReason(draft.context);
653 if (contextBlockReason) {
654 Dialog.alert(gt("Too much context"), contextBlockReason);
655 return null;
656 }
657 const strandedThread = threadContextsOutsideEnvironment({
658 text: draft.text,
659 records: draft.context?.records ?? [],
660 environmentId: selectedProject.environmentId,
661 linkedEnvironments: flow.linkedEnvironments,
662 })[0];
663 if (strandedThread) {
664 const owner = flow.environments.find(
665 (environment) => environment.environmentId === strandedThread.environmentId,
666 )?.environmentLabel;
667 Dialog.alert(
668 gt("Attached thread unavailable"),
669 owner === undefined
670 ? gt(
671 '"{title}" is on another machine. Switch back to its machine or remove it from the draft.',
672 { title: strandedThread.title },
673 )
674 : gt(
675 '"{title}" is on another machine. Switch back to {owner} or remove it from the draft.',
676 { title: strandedThread.title, owner },
677 ),
678 );
679 return null;
680 }
681
682 const message = flow.buildPendingTaskMessage(creationMetadata, {
683 currentCheckoutBranch: queuesInsteadOfStarting ? null : flow.currentCheckoutBranchName,
684 });
685 if (!message) {
686 return null;
687 }
688 // Persist locally before clearing or leaving the draft; server setup runs on the thread.
689 flow.setSubmitting(true);
690 const queued = await settlePromise(() => enqueueThreadOutboxMessage(message));
691 flow.setSubmitting(false);
692 if (AsyncResult.isFailure(queued)) {
693 const error = squashAtomCommandFailure(queued);
694 Dialog.alert(
695 gt("Could not queue task"),
696 errorDisplayMessage(error, m) ?? gt("The task could not be saved to the outbox."),
697 );
698 return null;
699 }
700 promptInputRef.current?.blur();
701 navigation.dispatch(
702 CommonActions.setParams(
703 submittedThreadParams(String(message.environmentId), String(message.threadId)),
704 ),
705 );
706 // The composer has moved to the submitted thread; a pick still converting
707 // would otherwise resurrect this draft.
708 abortComposerDraftOperations(draftKey);
709 const draftSnapshot = getComposerDraftSnapshot(draftKey);
710 // The queued message owns the attachments now, so the sweep is deferred
711 // until the write confirms it.
712 clearComposerDraftContent(draftKey, {
713 clearModelSelection: true,
714 clearWorkspaceSelection: true,
715 deferAttachmentCleanup: true,
716 });
717 scheduleUnusedComposerAttachmentCleanup(draftSnapshot.attachments);
718 return message.messageId;
719 }
720
721 // Keep the current surface until the local draft selection is ready. Publishing
722 // an empty loading surface here flashes between two already-cached threads.
723 if (!selectedProject) return null;
724
725 const setupBlockReason =
726 isIncomingShareReady && !isImportingShare
727 ? cloneBlocksStart
728 ? gt("Wait for the project clone to finish.")
729 : flow.submitting
730 ? gt("Starting the thread…")
731 : flow.workspaceMode === "worktree" && (!flow.selectedBranchName || !flow.isGitRepoKnown)
732 ? gt("Choose a base branch before creating a worktree.")
733 : null
734 : gt("Wait for shared content to finish importing.");
735 const chooseProject = () => {
736 if (isComposerInteractionLocked) {
737 return;
738 }
739 promptInputRef.current?.blur();
740 void KeyboardController.dismiss({ animated: true });
741 navigation.navigate("NewTaskProject", { incomingShareId: props.incomingShareId });
742 };
743 const openContextPicker = (routeName: "NewTaskBranch" | "NewTaskEnvironment") => {
744 if (isComposerInteractionLocked) {
745 return;
746 }
747 promptInputRef.current?.blur();
748 void KeyboardController.dismiss({ animated: true });
749 navigation.navigate(routeName);
750 };
751
752 const environmentControl = (
753 <DraftEnvironmentControl
754 connectionState={connectionState}
755 label={selectedEnvironmentLabel}
756 machineKind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}
757 disabled={isComposerInteractionLocked}
758 onChooseEnvironment={() => openContextPicker("NewTaskEnvironment")}
759 />
760 );
761 const shareUnavailableNotice = isIncomingShareUnavailable ? (
762 <Text textRole="footnote" className="text-center text-foreground-muted">
763 <T>The shared content is no longer in the inbox. You can continue editing this task draft.</T>
764 </Text>
765 ) : null;
766 const headingParts = gt("What should we build in {project}?", {
767 project: HEADING_PROJECT_SLOT,
768 }).split(HEADING_PROJECT_SLOT);
769 const headingBefore = headingParts[0] ?? "";
770 const headingAfter = headingParts[1] ?? "";
771 const headingBreak = headingBefore.trimEnd().lastIndexOf(" ");
772 const headingFirstLine = headingBreak < 0 ? headingBefore : headingBefore.slice(0, headingBreak);
773 const headingLead = headingBreak < 0 ? "" : headingBefore.slice(headingBreak + 1);
774 const hero = flow.isScratchDraft ? (
775 <View className="items-center gap-2 px-6" testID="new-task-hero">
776 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
777 <T>What should we work on?</T>
778 </Text>
779 <View className="flex-row flex-wrap items-center justify-center gap-x-1">
780 <ComposerInlineControl
781 accessibilityHint={gt("Opens the project picker")}
782 accessibilityLabel={gt("No project")}
783 chevronDirection="right"
784 disabled={isComposerInteractionLocked}
785 icon="folder"
786 label={gt("No project")}
787 onPress={chooseProject}
788 />
789 {environmentControl}
790 </View>
791 {shareUnavailableNotice}
792 </View>
793 ) : (
794 <View className="items-center gap-6 px-6" testID="new-task-hero">
795 <View className="w-full items-center gap-1.5">
796 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
797 {headingFirstLine}
798 </Text>
799 <View className="max-w-full flex-row items-center justify-center">
800 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">
801 {headingLead}
802 </Text>
803 <Pressable
804 accessibilityHint={gt("Opens the project picker")}
805 accessibilityLabel={selectedProjectLabel ?? selectedProject.title}
806 accessibilityRole="button"
807 disabled={isComposerInteractionLocked}
808 onPress={chooseProject}
809 className="min-w-0 max-w-[250px] border-b border-foreground-muted active:opacity-65"
810 >
811 <Text
812 className="text-2xl font-t3-medium tracking-tight text-foreground"
813 numberOfLines={1}
814 >
815 {selectedProjectLabel ?? selectedProject.title}
816 </Text>
817 </Pressable>
818 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">
819 {headingAfter}
820 </Text>
821 </View>
822 </View>
823
824 {environmentControl}
825 {shareUnavailableNotice}
826 </View>
827 );
828 // The nested hero scroll view does not receive UIKit's automatic navigation inset in split columns.
829 const heroViewport = (headerInset: number, bottomInset: number, viewportHeight: number) =>
830 viewportHeight < SHORT_DRAFT_VIEWPORT_HEIGHT ? null : (
831 <NativeScrollEdgeEffectsContext
832 value={{ top: "hidden", bottom: "hidden", left: "hidden", right: "hidden" }}
833 >
834 <View
835 collapsable={false}
836 style={{
837 position: "absolute",
838 top: headerInset,
839 bottom: bottomInset,
840 left: 0,
841 right: 0,
842 overflow: "hidden",
843 }}
844 >
845 <ScrollView
846 alwaysBounceVertical={false}
847 className="flex-1"
848 contentInsetAdjustmentBehavior="never"
849 contentContainerClassName="grow items-center"
850 contentContainerStyle={{ paddingVertical: 24 }}
851 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
852 keyboardShouldPersistTaps="handled"
853 showsVerticalScrollIndicator={false}
854 style={{ flex: 1 }}
855 testID="new-task-hero-scroll"
856 >
857 <View style={{ flexGrow: 1 }} />
858 {hero}
859 <View style={{ flexGrow: 2 }} />
860 </ScrollView>
861 </View>
862 </NativeScrollEdgeEffectsContext>
863 );
864
865 const contextProjectLabel = flow.isScratchDraft
866 ? gt("No project")
867 : (selectedProjectLabel ?? selectedProject.title);
868 const contextControls = (
869 <View className="flex-row items-center gap-1 px-2">
870 <View className="min-w-0 shrink">
871 <ComposerInlineControl
872 accessibilityHint={gt("Opens the project picker")}
873 accessibilityLabel={gt("Project: {project}", { project: contextProjectLabel })}
874 chevronDirection="right"
875 disabled={isComposerInteractionLocked}
876 icon="folder"
877 label={contextProjectLabel}
878 maxWidth="100%"
879 onPress={chooseProject}
880 />
881 </View>
882 <View className="min-w-0 shrink">
883 <ComposerInlineControl
884 accessibilityLabel={
885 connectionState === "connected"
886 ? gt("Choose environment, {label}, Connected", { label: selectedEnvironmentLabel })
887 : gt("Choose environment, {label}, Offline", { label: selectedEnvironmentLabel })
888 }
889 chevronDirection="right"
890 disabled={isComposerInteractionLocked}
891 renderIcon={(size) => (
892 <EnvironmentMachineSymbol
893 kind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}
894 size={size}
895 tintColorClassName="accent-icon-muted"
896 />
897 )}
898 label={selectedEnvironmentLabel}
899 maxWidth="100%"
900 onPress={() => openContextPicker("NewTaskEnvironment")}
901 suffix={
902 connectionState === "connected" ? null : (
903 <ConnectionStatusDot state="error" pulse={false} size={6} />
904 )
905 }
906 />
907 </View>
908 </View>
909 );
910
911 const workspaceControls = (
912 <View className="flex-row items-center gap-1 px-2">
913 <ComposerInlineControl
914 accessibilityHint={
915 flow.workspaceMode === "local"
916 ? gt("Switches to a new worktree")
917 : gt("Switches to the current checkout")
918 }
919 accessibilityLabel={workspaceLabel}
920 disabled={isComposerInteractionLocked || !flow.isGitRepo}
921 renderIcon={(size) => (
922 <NewTaskWorkspaceIcon
923 workspaceMode={flow.workspaceMode}
924 worktreePath={flow.selectedWorktreePath}
925 size={size}
926 />
927 )}
928 label={workspaceLabel}
929 maxWidth="100%"
930 onPress={() => flow.setWorkspaceMode(flow.workspaceMode === "local" ? "worktree" : "local")}
931 showChevron={false}
932 />
933
934 <View className="min-w-0 shrink">
935 <ComposerInlineControl
936 accessibilityLabel={
937 flow.workspaceMode === "worktree"
938 ? gt("Base branch: {branch}", { branch: selectedBranchLabel })
939 : gt("Branch: {branch}", { branch: selectedBranchLabel })
940 }
941 chevronDirection="right"
942 disabled={isComposerInteractionLocked || !flow.isGitRepo}
943 icon="arrow.triangle.branch"
944 label={showBranchLoading ? gt("Loading branches…") : selectedBranchLabel}
945 maxWidth="100%"
946 onPress={() => openContextPicker("NewTaskBranch")}
947 />
948 </View>
949 </View>
950 );
951
952 const draftControls = (viewportHeight: number) => (
953 <View className="pb-1">
954 {projectClone && projectClone.phase !== "done" && selectedProject ? (
955 <View className="px-1 pb-2">
956 <ProjectCloneBanner
957 clone={projectClone}
958 onCancel={() =>
959 void runCloneAction(gt("Failed to cancel clone"), () =>
960 cancelProjectClone({
961 environmentId: selectedProject.environmentId,
962 input: { projectId: selectedProject.id },
963 }),
964 )
965 }
966 onRetry={() =>
967 void runCloneAction(gt("Failed to retry clone"), () =>
968 retryProjectClone({
969 environmentId: selectedProject.environmentId,
970 input: { projectId: selectedProject.id },
971 }),
972 )
973 }
974 onRemove={() => void removeClonedProject()}
975 />
976 </View>
977 ) : null}
978 {viewportHeight < SHORT_DRAFT_VIEWPORT_HEIGHT ? contextControls : null}
979 {flow.canChooseWorkspace ? workspaceControls : null}
980 </View>
981 );
982
983 if (!flow.selectedModel) {
984 return (
985 <ThreadScreenFallback header={<AppBar title={gt("New thread")} onBack={goBack} />}>
986 <View className="flex-1 justify-end gap-3 p-4">
987 {environmentControl}
988 <Text className="text-foreground-muted">
989 {environmentConnected && selectedEnvironmentServerConfig ? (
990 <T>
991 Your draft is saved on this device. <Var>{selectedEnvironmentLabel}</Var> has no
992 model available. Install or sign in to a provider there to choose one.
993 </T>
994 ) : (
995 <T>
996 Your draft is saved on this device. Connect to an environment to choose its first
997 model.
998 </T>
999 )}
1000 </Text>
1001 <ComposerEditor
1002 draftKey={flow.draftKey}
1003 value={flow.prompt}
1004 onChangeText={flow.setPrompt}
1005 placeholder={gt("Ask anything")}
1006 multiline
1007 style={{ minHeight: 64 }}
1008 />
1009 </View>
1010 </ThreadScreenFallback>
1011 );
1012 }
1013 const thread = draftThreadShell(
1014 {
1015 environmentId: selectedProject.environmentId,
1016 projectId: selectedProject.id,
1017 threadId: ThreadId.make(creationMetadata.threadId),
1018 modelSelection: flow.selectedModel,
1019 runtimeMode: flow.runtimeMode,
1020 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1021 branch: flow.selectedBranchName,
1022 worktreePath: flow.selectedWorktreePath,
1023 createdAt: creationMetadata.createdAt,
1024 },
1025 m,
1026 );
1027 return (
1028 <>
1029 <ThreadScreenBinding
1030 environmentId={selectedProject.environmentId}
1031 header={
1032 <DraftThreadHeader thread={thread} project={selectedProject} cwd={flow.workspaceCwd} />
1033 }
1034 draftMode={{
1035 content: heroViewport,
1036 controls: draftControls,
1037 editorRef: promptInputRef,
1038 sendBlockedReason: setupBlockReason,
1039 interactionLocked: isComposerInteractionLocked,
1040 }}
1041 canOperateThread={canOperate}
1042 selectedThread={thread}
1043 selectedThreadDetailRef={null}
1044 contentPresentation={{ kind: "ready" }}
1045 screenTone={connectionTone(
1046 connectionState,
1047 environmentRuntime?.connectionAwaitingApproval === true,
1048 m,
1049 )}
1050 connectionError={
1051 environmentRuntime ? runtimeConnectionErrorText(environmentRuntime, m) : null
1052 }
1053 environmentLabel={selectedEnvironmentLabel}
1054 feedbackSubmissions={[]}
1055 onDismissFeedback={() => {}}
1056 selectedThreadFeed={[]}
1057 activityRun={null}
1058 activeWorkStartedAt={null}
1059 isCompacting={false}
1060 creationState={null}
1061 activePendingApproval={null}
1062 activePendingApprovals={[]}
1063 respondingApprovalId={null}
1064 activePendingUserInput={null}
1065 activePendingUserInputDrafts={{}}
1066 activePendingUserInputAnswers={null}
1067 respondingUserInputId={null}
1068 connectionStateLabel={connectionState}
1069 activeThreadBusy={false}
1070 canStopThread={false}
1071 queuedRunEdit={null}
1072 composerDraftKey={flow.draftKey}
1073 followUpBehavior="queue"
1074 canSteerActiveTurn={false}
1075 isSavingQueuedEdit={false}
1076 onCancelQueuedRunEdit={() => {}}
1077 onRemoveQueuedEditAttachment={() => {}}
1078 projectWorkspaceRoot={selectedProject.workspaceRoot}
1079 threadCwd={flow.workspaceCwd}
1080 selectedThreadQueueCount={0}
1081 queuedMessages={[]}
1082 dispatchingMessageId={null}
1083 serverConfig={selectedEnvironmentServerConfig}
1084 usesAutomaticContentInsets
1085 onOpenConnectionEditor={() => navigation.navigate("Connections")}
1086 onChangeDraftMessage={flow.setPrompt}
1087 onPickDraftMedia={handlePickMedia}
1088 onPickDraftFiles={handlePickFiles}
1089 onNativePasteImages={handleNativePasteImages}
1090 onNativePasteText={handleNativePasteText}
1091 onRemoveDraftImage={flow.removeAttachment}
1092 onStopThread={() => {}}
1093 onResumeQueue={null}
1094 onSendMessage={handleStart}
1095 offersSideChat={false}
1096 onSendCommand={async () => null}
1097 onReconnectEnvironment={() => onReconnectEnvironment(selectedProject.environmentId)}
1098 canSwitchThreadProvider
1099 onRespondToApproval={async () => {}}
1100 onSelectUserInputOption={() => {}}
1101 onChangeUserInputCustomAnswer={() => {}}
1102 onSubmitUserInput={async () => {}}
1103 onDismissUserInput={async () => {}}
1104 />
1105 </>
1106 );
1107 }