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