Open History to see the last commit
1import { T, useGT, useMessages, Var } from "gt-react-native";
2import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3import { DraftEnvironmentControl } from "./DraftEnvironmentControl";
4import { NativeScrollEdgeEffectsContext } from "../../native/NativeScrollViewMarker";
5import { DraftThreadHeader } from "./DraftThreadHeader";
6import { useComposerAttachmentActions } from "../../state/use-composer-attachment-actions";
7import { useWorkspaceBackNavigation } from "../layout/workspace/useAndroidWorkspaceNavigation";
8import { submittedThreadParams } from "./thread-route-state";
9import { ThreadScreenBinding, ThreadScreenFallback } from "./ThreadScreenHost";
10import { draftThreadShell } from "./draft-thread-shell";
11import { useRememberThreadProject } from "./useRememberThreadProject";
12import { scopedProjectKey } from "../../lib/scopedEntities";
13import { connectionTone } from "../connection/connectionTone";
14import { runtimeConnectionErrorText } from "../connection/environmentStatusText";
15import { AppBar } from "../../components/ui/AppBar";
16import { ThreadId } from "@t3tools/contracts";
17
18import * as Dialog from "../../components/ui/Dialog";
19import { useAtomValue } from "@effect/atom-react";
20import * as Cause from "effect/Cause";
21import { AsyncResult } from "effect/reactivity";
22import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping";
23import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
24import {
25 CommonActions,
26 StackActions,
27 useIsFocused,
28 useNavigation,
29 usePreventRemove,
30 useRoute,
31} from "@react-navigation/native";
32import { useEffect, useRef, useState } from "react";
33import { Platform, Pressable, View } from "react-native";
34import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
35import { KeyboardController } from "react-native-keyboard-controller";
36
37import {
38 AuthOrchestrationOperateScope,
39 DEFAULT_PROVIDER_INTERACTION_MODE,
40 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
41 resolveEnvironmentMachineKind,
42} from "@t3tools/contracts";
43
44import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
45import { composerContextImportsAtom } from "../../state/use-composer-drafts";
46import { abortComposerDraftOperations } from "../../state/composerDraftOperations";
47import { composerContextSendBlockReason } from "../../lib/composerContext";
48import { ComposerInlineControl } from "../../components/ComposerToolbar";
49
50import {
51 composerAttachmentUploadBlockReason,
52 composerAttachmentsStillUploading,
53 composerAttachmentUploadsAtom,
54} from "../../state/composer-attachment-uploads";
55
56import { SymbolView } from "../../components/ui/AppSymbol";
57import { AppText as Text } from "../../components/ui/AppText";
58import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences";
59
60import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
61
62import {
63 clearComposerDraftContent,
64 getComposerDraftSnapshot,
65 updateComposerDraftSettings,
66 scheduleUnusedComposerAttachmentCleanup,
67} from "../../state/use-composer-drafts";
68import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
69import { useProjectClone } from "../../state/projectClones";
70import { projectEnvironment } from "../../state/projects";
71import { sourceControlEnvironment } from "../../state/sourceControl";
72import { useAtomCommand } from "../../state/use-atom-command";
73import { ProjectCloneBanner } from "./ProjectCloneBanner";
74import {
75 describeUnavailableModelSelection,
76 isModelSelectionUnavailable,
77 resolveSelectableModelSelection,
78} from "../../lib/modelOptions";
79import { enqueueThreadOutboxMessage } from "../../state/thread-outbox";
80import {
81 useRemoteConnections,
82 useRemoteEnvironmentRuntime,
83} from "../../state/use-remote-environment-registry";
84import { useNewTaskFlow } from "./new-task-flow-provider";
85import {
86 nextEnvironmentId,
87 useHardwareKeyboardCommand,
88} from "../keyboard/hardwareKeyboardCommands";
89import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation";
90import { resolveDraftProjectSelection } from "./new-task-project-selection";
91import {
92 resolveNewTaskBranchLabel,
93 resolveNewTaskWorkspaceLabel,
94} from "./new-task-context-presentation";
95import { incomingShareImports, useIncomingShare } from "../sharing/IncomingShareProvider";
96import { idleShareFlagAtom, idleShareImportPhaseAtom } from "./incomingShareImport";
97import { newTaskFlowKey } from "./new-task-flow-state";
98import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
99import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";
100import { appAtomRegistry } from "../../state/atom-registry";
101import { mobilePreferencesAtom } from "../../state/preferences";
102
103import { 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.
107const SHORT_DRAFT_VIEWPORT_HEIGHT = 380;
108const HEADING_PROJECT_SLOT = "\uE000";
109
110function 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
155export 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" && flow.isGitRepo && !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" &&
732 (!flow.isGitRepoKnown || (flow.isGitRepo && !flow.selectedBranchName))
733 ? gt("Choose a base branch before creating a worktree.")
734 : null
735 : gt("Wait for shared content to finish importing.");
736 const chooseProject = () => {
737 if (isComposerInteractionLocked) {
738 return;
739 }
740 promptInputRef.current?.blur();
741 void KeyboardController.dismiss({ animated: true });
742 navigation.navigate("NewTaskProject", { incomingShareId: props.incomingShareId });
743 };
744 const openContextPicker = (
745 routeName: "NewTaskBranch" | "NewTaskEnvironment" | "NewTaskRepositories",
746 ) => {
747 if (isComposerInteractionLocked) {
748 return;
749 }
750 promptInputRef.current?.blur();
751 void KeyboardController.dismiss({ animated: true });
752 navigation.navigate(routeName);
753 };
754
755 const environmentControl = (
756 <DraftEnvironmentControl
757 connectionState={connectionState}
758 label={selectedEnvironmentLabel}
759 machineKind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}
760 disabled={isComposerInteractionLocked}
761 onChooseEnvironment={() => openContextPicker("NewTaskEnvironment")}
762 />
763 );
764 const shareUnavailableNotice = isIncomingShareUnavailable ? (
765 <Text textRole="footnote" className="text-center text-foreground-muted">
766 <T>The shared content is no longer in the inbox. You can continue editing this task draft.</T>
767 </Text>
768 ) : null;
769 const headingParts = gt("What should we build in {project}?", {
770 project: HEADING_PROJECT_SLOT,
771 }).split(HEADING_PROJECT_SLOT);
772 const headingBefore = headingParts[0] ?? "";
773 const headingAfter = headingParts[1] ?? "";
774 const headingBreak = headingBefore.trimEnd().lastIndexOf(" ");
775 const headingFirstLine = headingBreak < 0 ? headingBefore : headingBefore.slice(0, headingBreak);
776 const headingLead = headingBreak < 0 ? "" : headingBefore.slice(headingBreak + 1);
777 const hero = flow.isScratchDraft ? (
778 <View className="items-center gap-2 px-6" testID="new-task-hero">
779 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
780 <T>What should we work on?</T>
781 </Text>
782 <View className="flex-row flex-wrap items-center justify-center gap-x-1">
783 <ComposerInlineControl
784 accessibilityHint={gt("Opens the project picker")}
785 accessibilityLabel={gt("No project")}
786 chevronDirection="right"
787 disabled={isComposerInteractionLocked}
788 icon="folder"
789 label={gt("No project")}
790 onPress={chooseProject}
791 />
792 {environmentControl}
793 </View>
794 {shareUnavailableNotice}
795 </View>
796 ) : (
797 <View className="items-center gap-6 px-6" testID="new-task-hero">
798 <View className="w-full items-center gap-1.5">
799 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
800 {headingFirstLine}
801 </Text>
802 <View className="max-w-full flex-row items-center justify-center">
803 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">
804 {headingLead}
805 </Text>
806 <Pressable
807 accessibilityHint={gt("Opens the project picker")}
808 accessibilityLabel={selectedProjectLabel ?? selectedProject.title}
809 accessibilityRole="button"
810 disabled={isComposerInteractionLocked}
811 onPress={chooseProject}
812 className="min-w-0 max-w-[250px] border-b border-foreground-muted active:opacity-65"
813 >
814 <Text
815 className="text-2xl font-t3-medium tracking-tight text-foreground"
816 numberOfLines={1}
817 >
818 {selectedProjectLabel ?? selectedProject.title}
819 </Text>
820 </Pressable>
821 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">
822 {headingAfter}
823 </Text>
824 </View>
825 </View>
826
827 {environmentControl}
828 {shareUnavailableNotice}
829 </View>
830 );
831 // The nested hero scroll view does not receive UIKit's automatic navigation inset in split columns.
832 const heroViewport = (headerInset: number, bottomInset: number, viewportHeight: number) =>
833 viewportHeight < SHORT_DRAFT_VIEWPORT_HEIGHT ? null : (
834 <NativeScrollEdgeEffectsContext
835 value={{ top: "hidden", bottom: "hidden", left: "hidden", right: "hidden" }}
836 >
837 <View
838 collapsable={false}
839 style={{
840 position: "absolute",
841 top: headerInset,
842 bottom: bottomInset,
843 left: 0,
844 right: 0,
845 overflow: "hidden",
846 }}
847 >
848 <ScrollView
849 alwaysBounceVertical={false}
850 className="flex-1"
851 contentInsetAdjustmentBehavior="never"
852 contentContainerClassName="grow items-center"
853 contentContainerStyle={{ paddingVertical: 24 }}
854 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
855 keyboardShouldPersistTaps="handled"
856 showsVerticalScrollIndicator={false}
857 style={{ flex: 1 }}
858 testID="new-task-hero-scroll"
859 >
860 <View style={{ flexGrow: 1 }} />
861 {hero}
862 <View style={{ flexGrow: 2 }} />
863 </ScrollView>
864 </View>
865 </NativeScrollEdgeEffectsContext>
866 );
867
868 const contextProjectLabel = flow.isScratchDraft
869 ? gt("No project")
870 : (selectedProjectLabel ?? selectedProject.title);
871 const contextControls = (
872 <View className="flex-row items-center gap-1 px-2">
873 <View className="min-w-0 shrink">
874 <ComposerInlineControl
875 accessibilityHint={gt("Opens the project picker")}
876 accessibilityLabel={gt("Project: {project}", { project: contextProjectLabel })}
877 chevronDirection="right"
878 disabled={isComposerInteractionLocked}
879 icon="folder"
880 label={contextProjectLabel}
881 maxWidth="100%"
882 onPress={chooseProject}
883 />
884 </View>
885 <View className="min-w-0 shrink">
886 <ComposerInlineControl
887 accessibilityLabel={
888 connectionState === "connected"
889 ? gt("Choose environment, {label}, Connected", { label: selectedEnvironmentLabel })
890 : gt("Choose environment, {label}, Offline", { label: selectedEnvironmentLabel })
891 }
892 chevronDirection="right"
893 disabled={isComposerInteractionLocked}
894 renderIcon={(size) => (
895 <EnvironmentMachineSymbol
896 kind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}
897 size={size}
898 tintColorClassName="accent-icon-muted"
899 />
900 )}
901 label={selectedEnvironmentLabel}
902 maxWidth="100%"
903 onPress={() => openContextPicker("NewTaskEnvironment")}
904 suffix={
905 connectionState === "connected" ? null : (
906 <ConnectionStatusDot state="error" pulse={false} size={6} />
907 )
908 }
909 />
910 </View>
911 </View>
912 );
913
914 const startsNewWorktree = flow.workspaceMode === "worktree";
915 const offersRepositoryChoice =
916 startsNewWorktree && (flow.worktreeRepositoryChoices?.length ?? 0) > 0;
917 const workspaceControls = (
918 <View className="flex-row flex-wrap items-center gap-x-1 px-2">
919 <ComposerInlineControl
920 accessibilityHint={
921 flow.workspaceMode === "local"
922 ? gt("Switches to a new worktree")
923 : gt("Switches to the current checkout")
924 }
925 accessibilityLabel={workspaceLabel}
926 disabled={isComposerInteractionLocked || !(flow.isGitRepo || flow.tracksGitRepositories)}
927 renderIcon={(size) => (
928 <NewTaskWorkspaceIcon
929 workspaceMode={flow.workspaceMode}
930 worktreePath={flow.selectedWorktreePath}
931 size={size}
932 />
933 )}
934 label={workspaceLabel}
935 maxWidth="100%"
936 onPress={() => flow.setWorkspaceMode(flow.workspaceMode === "local" ? "worktree" : "local")}
937 showChevron={false}
938 />
939
940 {offersRepositoryChoice ? (
941 <View className="min-w-0 shrink">
942 <ComposerInlineControl
943 accessibilityHint={gt("Chooses the repositories the new worktree holds")}
944 accessibilityLabel={gt("Repositories in the new worktree: {selection}", {
945 selection: flow.worktreeRepositorySelection.label,
946 })}
947 chevronDirection="right"
948 disabled={isComposerInteractionLocked}
949 icon="folder.badge.plus"
950 label={flow.worktreeRepositorySelection.label}
951 maxWidth="100%"
952 onPress={() => openContextPicker("NewTaskRepositories")}
953 {...(flow.worktreeRepositorySelection.needsChoice ? { tone: "warning" as const } : {})}
954 />
955 </View>
956 ) : null}
957 {startsNewWorktree && !flow.isGitRepo ? (
958 <View className="min-h-8 min-w-0 shrink justify-center px-2">
959 <Text className="text-sm text-foreground-muted" numberOfLines={1}>
960 <T>Each repository starts from its own default branch</T>
961 </Text>
962 </View>
963 ) : (
964 <View className="min-w-0 shrink">
965 <ComposerInlineControl
966 accessibilityLabel={
967 startsNewWorktree
968 ? gt("Base branch: {branch}", { branch: selectedBranchLabel })
969 : gt("Branch: {branch}", { branch: selectedBranchLabel })
970 }
971 chevronDirection="right"
972 disabled={isComposerInteractionLocked || !flow.isGitRepo}
973 icon="arrow.triangle.branch"
974 label={showBranchLoading ? gt("Loading branches…") : selectedBranchLabel}
975 maxWidth="100%"
976 onPress={() => openContextPicker("NewTaskBranch")}
977 />
978 </View>
979 )}
980 </View>
981 );
982
983 const draftControls = (viewportHeight: number) => (
984 <View className="pb-1">
985 {projectClone && projectClone.phase !== "done" && selectedProject ? (
986 <View className="px-1 pb-2">
987 <ProjectCloneBanner
988 clone={projectClone}
989 onCancel={() =>
990 void runCloneAction(gt("Failed to cancel clone"), () =>
991 cancelProjectClone({
992 environmentId: selectedProject.environmentId,
993 input: { projectId: selectedProject.id },
994 }),
995 )
996 }
997 onRetry={() =>
998 void runCloneAction(gt("Failed to retry clone"), () =>
999 retryProjectClone({
1000 environmentId: selectedProject.environmentId,
1001 input: { projectId: selectedProject.id },
1002 }),
1003 )
1004 }
1005 onRemove={() => void removeClonedProject()}
1006 />
1007 </View>
1008 ) : null}
1009 {viewportHeight < SHORT_DRAFT_VIEWPORT_HEIGHT ? contextControls : null}
1010 {flow.canChooseWorkspace ? workspaceControls : null}
1011 </View>
1012 );
1013
1014 if (!flow.selectedModel) {
1015 return (
1016 <ThreadScreenFallback header={<AppBar title={gt("New thread")} onBack={goBack} />}>
1017 <View className="flex-1 justify-end gap-3 p-4">
1018 {environmentControl}
1019 <Text className="text-foreground-muted">
1020 {environmentConnected && selectedEnvironmentServerConfig ? (
1021 <T>
1022 Your draft is saved on this device. <Var>{selectedEnvironmentLabel}</Var> has no
1023 model available. Install or sign in to a provider there to choose one.
1024 </T>
1025 ) : (
1026 <T>
1027 Your draft is saved on this device. Connect to an environment to choose its first
1028 model.
1029 </T>
1030 )}
1031 </Text>
1032 <ComposerEditor
1033 draftKey={flow.draftKey}
1034 value={flow.prompt}
1035 onChangeText={flow.setPrompt}
1036 placeholder={gt("Ask anything")}
1037 multiline
1038 style={{ minHeight: 64 }}
1039 />
1040 </View>
1041 </ThreadScreenFallback>
1042 );
1043 }
1044 const thread = draftThreadShell(
1045 {
1046 environmentId: selectedProject.environmentId,
1047 projectId: selectedProject.id,
1048 threadId: ThreadId.make(creationMetadata.threadId),
1049 modelSelection: flow.selectedModel,
1050 runtimeMode: flow.runtimeMode,
1051 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1052 branch: flow.selectedBranchName,
1053 worktreePath: flow.selectedWorktreePath,
1054 createdAt: creationMetadata.createdAt,
1055 },
1056 m,
1057 );
1058 return (
1059 <>
1060 <ThreadScreenBinding
1061 environmentId={selectedProject.environmentId}
1062 header={
1063 <DraftThreadHeader thread={thread} project={selectedProject} cwd={flow.workspaceCwd} />
1064 }
1065 draftMode={{
1066 content: heroViewport,
1067 controls: draftControls,
1068 editorRef: promptInputRef,
1069 sendBlockedReason: setupBlockReason,
1070 interactionLocked: isComposerInteractionLocked,
1071 }}
1072 canOperateThread={canOperate}
1073 selectedThread={thread}
1074 selectedThreadDetailRef={null}
1075 contentPresentation={{ kind: "ready" }}
1076 screenTone={connectionTone(
1077 connectionState,
1078 environmentRuntime?.connectionAwaitingApproval === true,
1079 m,
1080 )}
1081 connectionError={
1082 environmentRuntime ? runtimeConnectionErrorText(environmentRuntime, m) : null
1083 }
1084 environmentLabel={selectedEnvironmentLabel}
1085 feedbackSubmissions={[]}
1086 onDismissFeedback={() => {}}
1087 selectedThreadFeed={[]}
1088 activityRun={null}
1089 activeWorkStartedAt={null}
1090 isCompacting={false}
1091 creationState={null}
1092 activePendingApproval={null}
1093 activePendingApprovals={[]}
1094 respondingApprovalId={null}
1095 activePendingUserInput={null}
1096 activePendingUserInputDrafts={{}}
1097 activePendingUserInputAnswers={null}
1098 respondingUserInputId={null}
1099 connectionStateLabel={connectionState}
1100 activeThreadBusy={false}
1101 canStopThread={false}
1102 queuedRunEdit={null}
1103 composerDraftKey={flow.draftKey}
1104 followUpBehavior="queue"
1105 canSteerActiveTurn={false}
1106 isSavingQueuedEdit={false}
1107 onCancelQueuedRunEdit={() => {}}
1108 onRemoveQueuedEditAttachment={() => {}}
1109 projectWorkspaceRoot={selectedProject.workspaceRoot}
1110 threadCwd={flow.workspaceCwd}
1111 selectedThreadQueueCount={0}
1112 queuedMessages={[]}
1113 dispatchingMessageId={null}
1114 serverConfig={selectedEnvironmentServerConfig}
1115 usesAutomaticContentInsets
1116 onOpenConnectionEditor={() => navigation.navigate("Connections")}
1117 onChangeDraftMessage={flow.setPrompt}
1118 onPickDraftMedia={handlePickMedia}
1119 onPickDraftFiles={handlePickFiles}
1120 onNativePasteImages={handleNativePasteImages}
1121 onNativePasteText={handleNativePasteText}
1122 onRemoveDraftImage={flow.removeAttachment}
1123 onStopThread={() => {}}
1124 onResumeQueue={null}
1125 onSendMessage={handleStart}
1126 offersSideChat={false}
1127 onSendCommand={async () => null}
1128 onReconnectEnvironment={() => onReconnectEnvironment(selectedProject.environmentId)}
1129 canSwitchThreadProvider
1130 onRespondToApproval={async () => {}}
1131 onSelectUserInputOption={() => {}}
1132 onChangeUserInputCustomAnswer={() => {}}
1133 onSubmitUserInput={async () => {}}
1134 onDismissUserInput={async () => {}}
1135 />
1136 </>
1137 );
1138}