Open History to see the last commit
1import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
2import {
3 StackActions,
4 useFocusEffect,
5 useNavigation,
6 usePreventRemove,
7} from "@react-navigation/native";
8import { useCallback, useEffect, useRef, useState } from "react";
9import { Alert, Platform, Pressable, ScrollView, View } from "react-native";
10import {
11 KeyboardController,
12 KeyboardStickyView,
13 useKeyboardState,
14} from "react-native-keyboard-controller";
15import { useSafeAreaInsets } from "react-native-safe-area-context";
16import { useUniwindTheme } from "../../lib/useUniwindTheme";
17import { useFontFamily } from "../../lib/useFontFamily";
18
19import {
20 isAtomCommandInterrupted,
21 squashAtomCommandFailure,
22} from "@t3tools/client-runtime/state/runtime";
23
24import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
25import {
26 ComposerInlineControl,
27 ComposerToolbarButton,
28 ComposerToolbarRow,
29 ComposerToolbarScroller,
30} from "../../components/ComposerToolbar";
31import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
32import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
33import { ProviderIcon } from "../../components/ProviderIcon";
34import { SymbolView } from "../../components/AppSymbol";
35import { AppText as Text } from "../../components/AppText";
36import { ComposerSurface } from "./ThreadComposer";
37import { ComposerCommandPopover } from "./ComposerCommandPopover";
38import { useComposerCommandMenu } from "./use-composer-command-menu";
39import {
40 useThreadSettingsSheetPresentation,
41 type NavigationWithFinishTransitioning,
42} from "./use-thread-settings-sheet-presentation";
43
44import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
45import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
46import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
47import {
48 clearComposerDraftContent,
49 getComposerDraftSnapshot,
50 mergeComposerDraftContent,
51 restoreComposerDraftSnapshot,
52 type ComposerDraft,
53} from "../../state/use-composer-drafts";
54import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
55import { resolveSelectableModelSelection } from "../../lib/modelOptions";
56import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
57import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
58import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
59import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
60import { useNewTaskFlow } from "./new-task-flow-provider";
61import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation";
62import { useCreateProjectThread } from "./use-project-actions";
63import { resolveDraftProjectSelection } from "./new-task-project-selection";
64import {
65 resolveNewTaskBranchLabel,
66 resolveNewTaskWorkspaceLabel,
67} from "./new-task-context-presentation";
68import { useIncomingShare } from "../sharing/IncomingShareProvider";
69
70function NewTaskWorkspaceIcon(props: {
71 readonly workspaceMode: "local" | "worktree";
72 readonly worktreePath: string | null;
73}) {
74 if (props.workspaceMode === "local" && props.worktreePath === null) {
75 return (
76 <SymbolView
77 name="folder"
78 size={16}
79 tintColorClassName={"accent-icon-muted"}
80 type="monochrome"
81 />
82 );
83 }
84
85 return (
86 <View className="size-4">
87 <SymbolView
88 name="folder"
89 size={16}
90 tintColorClassName={"accent-icon-muted"}
91 type="monochrome"
92 />
93 <View className="absolute -right-1 -bottom-1">
94 <SymbolView
95 name="arrow.triangle.branch"
96 size={9}
97 tintColorClassName={"accent-icon-muted"}
98 type="monochrome"
99 />
100 </View>
101 </View>
102 );
103}
104
105export function NewTaskDraftScreen(props: {
106 readonly initialProjectRef?: {
107 readonly environmentId?: string;
108 readonly projectId?: string;
109 };
110 /** Queued outbox message id when editing an existing pending task. */
111 readonly pendingTaskId?: string;
112 /** Durable native share inbox item to merge into this project draft. */
113 readonly incomingShareId?: string;
114}) {
115 const projects = useProjects();
116 const createProjectThread = useCreateProjectThread();
117 const flow = useNewTaskFlow();
118 const navigation = useNavigation();
119 const {
120 consumeShare,
121 getShare,
122 isLoading: isIncomingShareInboxLoading,
123 releaseShareReservation,
124 reserveShare,
125 } = useIncomingShare();
126 const insets = useSafeAreaInsets();
127 const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
128 const controlsBottomPadding = Math.max(insets.bottom, 10);
129 const keyboardOpenedOffset = Math.max(0, controlsBottomPadding - 8);
130 const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
131 const { connectedEnvironments } = useRemoteConnectionStatus();
132 const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
133 selectedProject?.environmentId ?? null,
134 );
135 const environmentConnected =
136 selectedProject !== null &&
137 connectedEnvironments.find(
138 (environment) => environment.environmentId === selectedProject.environmentId,
139 )?.connectionState === "connected";
140 const promptInputRef = useRef<ComposerEditorHandle>(null);
141 const loadedBranchesProjectKeyRef = useRef<string | null>(null);
142 const [isComposerFocused, setIsComposerFocused] = useState(false);
143 const settingsSheetPresentation = useThreadSettingsSheetPresentation({
144 editorRef: promptInputRef,
145 isEditorFocused: isComposerFocused,
146 });
147 useEffect(() => {
148 if (Platform.OS !== "ios") {
149 return;
150 }
151
152 navigation.getParent()?.setOptions({ gestureEnabled: !isKeyboardVisible });
153 }, [isKeyboardVisible, navigation]);
154 useEffect(() => {
155 return () => {
156 if (Platform.OS === "ios") {
157 navigation.getParent()?.setOptions({ gestureEnabled: true });
158 }
159 };
160 }, [navigation]);
161 const settingsRoutePresentedRef = useRef(false);
162 useEffect(() => {
163 if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
164 return;
165 }
166
167 settingsRoutePresentedRef.current = true;
168 navigation.dispatch(StackActions.push("ThreadSettings"));
169 }, [navigation, settingsSheetPresentation.isVisible]);
170 useFocusEffect(
171 useCallback(() => {
172 if (!settingsRoutePresentedRef.current) {
173 return;
174 }
175
176 settingsRoutePresentedRef.current = false;
177 settingsSheetPresentation.onDismissed();
178 }, [settingsSheetPresentation.onDismissed]),
179 );
180 useEffect(
181 () =>
182 // UIKit's completion callback for the sheet dismissal, surfaced by the
183 // native-stack patch. This is when the queued keyboard restore runs.
184 (navigation as unknown as NavigationWithFinishTransitioning).addListener(
185 "finishTransitioning",
186 settingsSheetPresentation.onStackTransitionsFinished,
187 ),
188 [navigation, settingsSheetPresentation.onStackTransitionsFinished],
189 );
190 const [importingShareKey, setImportingShareKey] = useState<string | null>(null);
191 const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);
192 const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);
193 const [isReturningToProjectPicker, setIsReturningToProjectPicker] = useState(false);
194 const [shareImportAttempt, setShareImportAttempt] = useState(0);
195 const startedShareImportKeyRef = useRef<string | null>(null);
196 const cancellingShareImportKeyRef = useRef<string | null>(null);
197 const shareImportDraftBackupRef = useRef(new Map<string, ComposerDraft>());
198 const activeShareImportTokenRef = useRef<symbol | null>(null);
199 const shareImportMountedRef = useRef(true);
200 const latestDraftKeyRef = useRef(flow.draftKey);
201 const latestIncomingShareIdRef = useRef(props.incomingShareId);
202 latestDraftKeyRef.current = flow.draftKey;
203 latestIncomingShareIdRef.current = props.incomingShareId;
204 const isImportingShare = importingShareKey !== null;
205 const alertedUnavailableIncomingShareIdRef = useRef<string | null>(null);
206 const incomingShare = props.incomingShareId ? getShare(props.incomingShareId) : null;
207 const requestedInitialProjectAvailable = Boolean(
208 props.initialProjectRef?.environmentId &&
209 props.initialProjectRef.projectId &&
210 projects.some(
211 (project) =>
212 project.environmentId === props.initialProjectRef?.environmentId &&
213 project.id === props.initialProjectRef?.projectId,
214 ),
215 );
216 const isProjectPickerReturnActive =
217 isReturningToProjectPicker && !requestedInitialProjectAvailable;
218 const isIncomingShareTransferPending = Boolean(
219 incomingShare && cancelledIncomingShareId !== props.incomingShareId,
220 );
221 const composerMenu = useComposerCommandMenu({
222 draftMessage: flow.prompt,
223 environmentId: selectedProject?.environmentId ?? null,
224 projectCwd:
225 (flow.workspaceMode === "worktree"
226 ? selectedProject?.workspaceRoot
227 : (flow.selectedWorktreePath ?? selectedProject?.workspaceRoot)) || null,
228 selectedProviderStatus: flow.selectedProviderStatus,
229 hasThread: false,
230 enabled: isComposerFocused && !isIncomingShareTransferPending,
231 onChangeDraftMessage: flow.setPrompt,
232 onUpdateInteractionMode: flow.planModeEnabled ? flow.setInteractionMode : undefined,
233 });
234 usePreventRemove(
235 (isIncomingShareTransferPending && !isProjectPickerReturnActive) || isCancellingShareImport,
236 () => undefined,
237 );
238 const hasImportedIncomingShare = Boolean(
239 props.incomingShareId &&
240 flow.draftKey &&
241 getComposerDraftSnapshot(flow.draftKey).importedShareIds?.includes(props.incomingShareId),
242 );
243 const isIncomingShareUnavailable = Boolean(
244 props.incomingShareId &&
245 !isIncomingShareInboxLoading &&
246 !incomingShare &&
247 !hasImportedIncomingShare,
248 );
249 const isIncomingShareReady =
250 !props.incomingShareId ||
251 (hasImportedIncomingShare && !incomingShare) ||
252 isIncomingShareUnavailable;
253 const appliedInitialProjectKeyRef = useRef<string | null>(null);
254 useEffect(() => {
255 if (cancelledIncomingShareId === props.incomingShareId) {
256 navigation.goBack();
257 }
258 }, [cancelledIncomingShareId, navigation, props.incomingShareId]);
259 useEffect(() => {
260 if (!isReturningToProjectPicker) {
261 return;
262 }
263 if (requestedInitialProjectAvailable) {
264 setIsReturningToProjectPicker(false);
265 return;
266 }
267 // Let usePreventRemove commit its disabled state before replacing this
268 // route, otherwise the transfer guard can swallow the fallback action.
269 const frame = requestAnimationFrame(() => {
270 navigation.dispatch(
271 StackActions.replace("NewTask", { incomingShareId: props.incomingShareId }),
272 );
273 });
274 return () => cancelAnimationFrame(frame);
275 }, [
276 isReturningToProjectPicker,
277 navigation,
278 props.incomingShareId,
279 requestedInitialProjectAvailable,
280 ]);
281 useEffect(() => {
282 if (!shareImportMountedRef.current) {
283 startedShareImportKeyRef.current = null;
284 }
285 shareImportMountedRef.current = true;
286 return () => {
287 appliedInitialProjectKeyRef.current = null;
288 shareImportMountedRef.current = false;
289 activeShareImportTokenRef.current = null;
290 cancellingShareImportKeyRef.current = null;
291 };
292 }, []);
293
294 const { beginEditingPendingTask, cancelEditingPendingTask, editingPendingTask } = flow;
295 const attemptedPendingTaskIdRef = useRef<string | null>(null);
296 useEffect(() => {
297 if (!props.pendingTaskId || editingPendingTask?.messageId === props.pendingTaskId) {
298 return;
299 }
300 // Attempt each pending task once: after it is delivered or deleted the
301 // editing session legitimately ends, and re-running must not navigate.
302 if (attemptedPendingTaskIdRef.current === props.pendingTaskId) {
303 return;
304 }
305 attemptedPendingTaskIdRef.current = props.pendingTaskId;
306 if (!beginEditingPendingTask(props.pendingTaskId)) {
307 // The queued task no longer exists (sent or deleted before opening).
308 navigation.dispatch(StackActions.replace("NewTask"));
309 }
310 }, [beginEditingPendingTask, editingPendingTask?.messageId, navigation, props.pendingTaskId]);
311
312 useEffect(() => {
313 if (!props.pendingTaskId) return;
314 return () => {
315 // Allow a later navigation for the same pending task to re-hydrate it.
316 attemptedPendingTaskIdRef.current = null;
317 cancelEditingPendingTask();
318 };
319 }, [props.pendingTaskId, cancelEditingPendingTask]);
320
321 const foregroundColor = useUniwindTheme()["--color-foreground"];
322 const regularFontFamily = useFontFamily("regular");
323 const bodyText = useScaledTextRole("body");
324
325 // A new navigation to this mounted screen delivers a fresh initialProjectRef
326 // reference — treat it as a new request and let it apply again.
327 const lastInitialProjectRefRef = useRef(props.initialProjectRef);
328
329 useEffect(() => {
330 // Pending-task editing owns project selection (and must not fall through
331 // to the replace("NewTask") fallback while its hydration is in flight).
332 if (props.pendingTaskId) {
333 return;
334 }
335 if (lastInitialProjectRefRef.current !== props.initialProjectRef) {
336 lastInitialProjectRefRef.current = props.initialProjectRef;
337 appliedInitialProjectKeyRef.current = null;
338 }
339 const initialEnvironmentId = props.initialProjectRef?.environmentId;
340 const initialProjectId = props.initialProjectRef?.projectId;
341 if (initialEnvironmentId && initialProjectId) {
342 const directProject =
343 projects.find(
344 (project) =>
345 project.environmentId === initialEnvironmentId && project.id === initialProjectId,
346 ) ?? null;
347
348 if (directProject) {
349 // Apply the route's project once. Re-applying on every change would
350 // instantly revert environment/project switches made in the picker.
351 const directProjectKey = `${directProject.environmentId}:${directProject.id}`;
352 if (appliedInitialProjectKeyRef.current === directProjectKey) {
353 return;
354 }
355 appliedInitialProjectKeyRef.current = directProjectKey;
356 if (
357 selectedProject?.environmentId === directProject.environmentId &&
358 selectedProject.id === directProject.id
359 ) {
360 return;
361 }
362 setProject(directProject);
363 return;
364 }
365
366 if (projects.length > 0) {
367 // Never fall through to the flow provider's temporary first-project
368 // default. Return to the picker with the share id intact so the user
369 // can choose an available destination.
370 setIsReturningToProjectPicker(true);
371 }
372 return;
373 }
374
375 const selection = resolveDraftProjectSelection(selectedProjectKey, projects, projectScopes);
376 if (selection.kind === "preserve") {
377 return;
378 }
379 if (selection.kind === "select") {
380 setProject(selection.project);
381 return;
382 }
383
384 navigation.dispatch(StackActions.replace("NewTask"));
385 }, [
386 projectScopes,
387 projects,
388 props.initialProjectRef,
389 props.incomingShareId,
390 props.pendingTaskId,
391 navigation,
392 selectedProject,
393 selectedProjectKey,
394 setProject,
395 ]);
396
397 useEffect(() => {
398 if (!selectedProject) {
399 loadedBranchesProjectKeyRef.current = null;
400 return;
401 }
402 const projectKey = `${selectedProject.environmentId}:${selectedProject.id}`;
403 if (loadedBranchesProjectKeyRef.current === projectKey) {
404 return;
405 }
406 loadedBranchesProjectKeyRef.current = projectKey;
407 flow.loadBranches();
408 }, [flow.loadBranches, selectedProject]);
409
410 useEffect(() => {
411 const shareId = props.incomingShareId;
412 const draftKey = flow.draftKey;
413 const destinationProject = selectedProject;
414 const initialEnvironmentId = props.initialProjectRef?.environmentId;
415 const initialProjectId = props.initialProjectRef?.projectId;
416 const selectedProjectMatchesRoute =
417 !initialEnvironmentId ||
418 !initialProjectId ||
419 (destinationProject?.environmentId === initialEnvironmentId &&
420 destinationProject.id === initialProjectId);
421 if (
422 !shareId ||
423 !draftKey ||
424 !destinationProject ||
425 !selectedProjectMatchesRoute ||
426 cancelledIncomingShareId === shareId
427 ) {
428 return;
429 }
430 const importKey = `${shareId}:${draftKey}`;
431 if (
432 startedShareImportKeyRef.current === importKey ||
433 cancellingShareImportKeyRef.current === importKey
434 ) {
435 return;
436 }
437
438 if (!incomingShare) {
439 if (isIncomingShareUnavailable && alertedUnavailableIncomingShareIdRef.current !== shareId) {
440 alertedUnavailableIncomingShareIdRef.current = shareId;
441 Alert.alert(
442 "Shared content unavailable",
443 "The shared content is no longer in the inbox. You can continue editing this task draft.",
444 );
445 }
446 return;
447 }
448
449 if (alertedUnavailableIncomingShareIdRef.current === shareId) {
450 alertedUnavailableIncomingShareIdRef.current = null;
451 }
452 startedShareImportKeyRef.current = importKey;
453 const draftBackup =
454 shareImportDraftBackupRef.current.get(importKey) ?? getComposerDraftSnapshot(draftKey);
455 shareImportDraftBackupRef.current.set(importKey, draftBackup);
456 const importToken = Symbol(importKey);
457 let didReserveShare = false;
458 let needsDraftRestore = false;
459 activeShareImportTokenRef.current = importToken;
460 setImportingShareKey(importKey);
461 void (async () => {
462 await reserveShare(shareId, {
463 environmentId: String(destinationProject.environmentId),
464 projectId: String(destinationProject.id),
465 });
466 didReserveShare = true;
467 if (
468 !shareImportMountedRef.current ||
469 activeShareImportTokenRef.current !== importToken ||
470 latestDraftKeyRef.current !== draftKey ||
471 latestIncomingShareIdRef.current !== shareId
472 ) {
473 return;
474 }
475 needsDraftRestore = true;
476 const { skippedAttachmentCount } = await mergeComposerDraftContent(draftKey, {
477 text: incomingShare.text,
478 attachments: incomingShare.attachments,
479 sourceShareId: shareId,
480 });
481 if (
482 !shareImportMountedRef.current ||
483 activeShareImportTokenRef.current !== importToken ||
484 latestDraftKeyRef.current !== draftKey ||
485 latestIncomingShareIdRef.current !== shareId
486 ) {
487 // The durable reservation makes an interrupted transfer resume only
488 // in this project instead of copying into a second project draft.
489 return;
490 }
491 await consumeShare(shareId);
492 if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {
493 return;
494 }
495 const warnings = [...incomingShare.warnings];
496 if (skippedAttachmentCount > 0) {
497 warnings.push(
498 `${skippedAttachmentCount} shared image${skippedAttachmentCount === 1 ? " was" : "s were"} skipped because this draft reached the attachment limit.`,
499 );
500 }
501 if (warnings.length > 0) {
502 Alert.alert("Some shared content was skipped", warnings.join("\n"));
503 }
504 shareImportDraftBackupRef.current.delete(importKey);
505 })()
506 .catch((error) => {
507 if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {
508 return;
509 }
510 Alert.alert(
511 "Could not import shared content",
512 error instanceof Error ? error.message : "The shared content could not be saved.",
513 [
514 {
515 text: "Cancel import",
516 style: "cancel",
517 onPress: () => {
518 const cancelImport = async (): Promise<void> => {
519 if (!shareImportMountedRef.current) {
520 return;
521 }
522 // Latch synchronously before restoring the draft. The
523 // restore publishes atom state and can re-run the import
524 // effect before React commits the cancelling state update.
525 cancellingShareImportKeyRef.current = importKey;
526 setIsCancellingShareImport(true);
527 try {
528 if (needsDraftRestore) {
529 await restoreComposerDraftSnapshot(draftKey, draftBackup);
530 needsDraftRestore = false;
531 }
532 if (didReserveShare) {
533 await releaseShareReservation(shareId, {
534 environmentId: String(destinationProject.environmentId),
535 projectId: String(destinationProject.id),
536 });
537 }
538 shareImportDraftBackupRef.current.delete(importKey);
539 if (shareImportMountedRef.current) {
540 setIsCancellingShareImport(false);
541 setCancelledIncomingShareId(shareId);
542 }
543 } catch (cancelError) {
544 if (!shareImportMountedRef.current) {
545 return;
546 }
547 Alert.alert(
548 "Could not cancel import",
549 cancelError instanceof Error
550 ? cancelError.message
551 : "The shared content could not be restored safely.",
552 [
553 {
554 text: "Retry import",
555 onPress: () => {
556 cancellingShareImportKeyRef.current = null;
557 setIsCancellingShareImport(false);
558 setShareImportAttempt((attempt) => attempt + 1);
559 },
560 },
561 {
562 text: "Retry cancel",
563 onPress: () => void cancelImport(),
564 },
565 ],
566 { cancelable: false },
567 );
568 }
569 };
570 void cancelImport();
571 },
572 },
573 {
574 text: "Retry",
575 onPress: () => setShareImportAttempt((attempt) => attempt + 1),
576 },
577 ],
578 { cancelable: false },
579 );
580 })
581 .finally(() => {
582 if (startedShareImportKeyRef.current === importKey) {
583 // Every terminal path, including an invalidated operation, must
584 // release the synchronous start latch so this transfer can retry.
585 startedShareImportKeyRef.current = null;
586 }
587 if (shareImportMountedRef.current && activeShareImportTokenRef.current === importToken) {
588 activeShareImportTokenRef.current = null;
589 setImportingShareKey(null);
590 }
591 });
592 }, [
593 consumeShare,
594 cancelledIncomingShareId,
595 flow.draftKey,
596 hasImportedIncomingShare,
597 incomingShare,
598 isIncomingShareInboxLoading,
599 isIncomingShareUnavailable,
600 props.incomingShareId,
601 props.initialProjectRef?.environmentId,
602 props.initialProjectRef?.projectId,
603 releaseShareReservation,
604 reserveShare,
605 selectedProject,
606 shareImportAttempt,
607 ]);
608
609 const selectedEnvironmentLabel =
610 flow.environments.find(
611 (environment) => environment.environmentId === flow.selectedEnvironmentId,
612 )?.environmentLabel ?? "Environment";
613 const availableCurrentBranchName =
614 flow.availableBranches.find((branch) => branch.current)?.name ??
615 flow.availableBranches.find((branch) => branch.isDefault)?.name ??
616 null;
617 const selectedBranchName = resolveProjectThreadCreationBranch({
618 workspaceMode: flow.workspaceMode,
619 selectedBranch:
620 flow.selectedBranchName ??
621 (flow.workspaceMode === "worktree" ? availableCurrentBranchName : null),
622 currentCheckoutBranch: flow.currentCheckoutBranchName,
623 });
624 const selectedBranchLabel = resolveNewTaskBranchLabel({
625 branchName: selectedBranchName,
626 startFromOrigin: flow.startFromOrigin,
627 workspaceMode: flow.workspaceMode,
628 });
629 const workspaceLabel = resolveNewTaskWorkspaceLabel({
630 workspaceMode: flow.workspaceMode,
631 worktreePath: flow.selectedWorktreePath,
632 });
633 const showBranchLoading = flow.branchesLoading && flow.availableBranches.length === 0;
634
635 async function handlePickImages(): Promise<void> {
636 if (isIncomingShareTransferPending) {
637 return;
638 }
639 const result = await pickComposerImages({ existingCount: flow.attachments.length });
640 if (result.images.length > 0) {
641 flow.appendAttachments(result.images);
642 }
643 }
644
645 const handleNativePasteImages = useCallback(
646 async (uris: ReadonlyArray<string>) => {
647 try {
648 const images = await convertPastedImagesToAttachments({
649 uris,
650 existingCount: flow.attachments.length,
651 });
652 if (images.length > 0) {
653 flow.appendAttachments(images);
654 }
655 } catch (error) {
656 console.error("[native paste] error converting images", error);
657 }
658 },
659 [flow],
660 );
661
662 async function handleStart(): Promise<void> {
663 const selectedProject = flow.selectedProject;
664 const draftKey = flow.draftKey;
665 if (!selectedProject || !draftKey) {
666 return;
667 }
668 const draft = getComposerDraftSnapshot(draftKey);
669 // Snapshot read keeps just-typed selector state; the availability gate
670 // still applies so a stored selection on a disabled provider falls back
671 // to the flow's resolved model.
672 const modelSelection =
673 resolveSelectableModelSelection(
674 selectedEnvironmentServerConfig,
675 draft.modelSelection ?? null,
676 ) ?? flow.selectedModel;
677 const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
678 const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
679 const selectedWorktreePath =
680 draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;
681 const startFromOrigin = draft.workspaceSelection?.startFromOrigin ?? flow.startFromOrigin;
682 const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;
683 const interactionMode = flow.planModeEnabled
684 ? (draft.interactionMode ?? flow.interactionMode)
685 : "default";
686 const initialMessageText = draft.text.trim();
687
688 if (
689 !modelSelection ||
690 initialMessageText.length === 0 ||
691 flow.submitting ||
692 (workspaceMode === "worktree" && !selectedBranchName)
693 ) {
694 return;
695 }
696
697 const editingPendingTask = flow.editingPendingTask;
698
699 if (!environmentConnected) {
700 // Offline: park the task in the outbox; the drain sends it when the
701 // environment reconnects. Editing an existing pending task re-queues it
702 // under its original identifiers.
703 const metadata = editingPendingTask
704 ? {
705 threadId: editingPendingTask.threadId,
706 commandId: editingPendingTask.commandId,
707 messageId: editingPendingTask.messageId,
708 createdAt: editingPendingTask.createdAt,
709 }
710 : makeTurnCommandMetadata();
711 const message = flow.buildPendingTaskMessage(metadata);
712 if (!message) {
713 return;
714 }
715 flow.setSubmitting(true);
716 try {
717 await enqueueThreadOutboxMessage(message);
718 } catch (error) {
719 Alert.alert(
720 "Could not queue task",
721 error instanceof Error ? error.message : "The task could not be saved to the outbox.",
722 );
723 return;
724 } finally {
725 flow.setSubmitting(false);
726 }
727 if (editingPendingTask) {
728 flow.finishEditingPendingTask();
729 } else {
730 // Drop draft-local model/workspace selections with the content. The
731 // next task re-resolves project defaults before sticky app defaults.
732 clearComposerDraftContent(draftKey, {
733 clearModelSelection: true,
734 clearWorkspaceSelection: true,
735 });
736 }
737 navigation.getParent()?.goBack();
738 return;
739 }
740
741 flow.setSubmitting(true);
742 // Arm the lock-screen card before the async thread creation: backgrounding
743 // the app right after tapping submit would otherwise reject the foreground
744 // -only Activity start. If creation fails, the token registration's replay
745 // finds no work and ends the card within seconds.
746 armAgentAwarenessLiveActivityForLocalWork({
747 environmentId: selectedProject.environmentId,
748 threadTitle: deriveThreadTitleFromPrompt(initialMessageText),
749 projectTitle: selectedProject.title,
750 });
751 const creationBranch = resolveProjectThreadCreationBranch({
752 workspaceMode,
753 selectedBranch: selectedBranchName,
754 currentCheckoutBranch: flow.currentCheckoutBranchName,
755 });
756 const result = await createProjectThread({
757 project: selectedProject,
758 modelSelection,
759 envMode: workspaceMode,
760 branch: creationBranch,
761 worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
762 startFromOrigin,
763 runtimeMode,
764 interactionMode,
765 initialMessageText,
766 initialAttachments: draft.attachments,
767 ...(editingPendingTask
768 ? {
769 turnMetadata: {
770 threadId: editingPendingTask.threadId,
771 commandId: editingPendingTask.commandId,
772 messageId: editingPendingTask.messageId,
773 createdAt: editingPendingTask.createdAt,
774 },
775 }
776 : {}),
777 });
778 flow.setSubmitting(false);
779
780 if (result._tag === "Failure") {
781 if (!isAtomCommandInterrupted(result)) {
782 const error = squashAtomCommandFailure(result);
783 Alert.alert(
784 "Could not start task",
785 error instanceof Error ? error.message : "The task could not be started.",
786 );
787 }
788 return;
789 }
790
791 if (editingPendingTask) {
792 try {
793 await removeThreadOutboxMessage(editingPendingTask);
794 } catch (error) {
795 console.warn("[new-task] failed to remove delivered pending task", error);
796 }
797 flow.finishEditingPendingTask();
798 } else {
799 clearComposerDraftContent(draftKey, {
800 clearModelSelection: true,
801 clearWorkspaceSelection: true,
802 });
803 }
804 navigation.dispatch(
805 StackActions.replace("Thread", {
806 environmentId: String(result.value.environmentId),
807 threadId: String(result.value.threadId),
808 }),
809 );
810 }
811
812 if (!selectedProject) {
813 return (
814 <View className="flex-1 bg-sheet" collapsable={false}>
815 {Platform.OS === "android" ? (
816 <>
817 <NativeStackScreenOptions options={{ headerShown: false }} />
818 <AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
819 </>
820 ) : (
821 <NativeStackScreenOptions options={{ title: "Loading task" }} />
822 )}
823 </View>
824 );
825 }
826
827 const isAndroid = Platform.OS === "android";
828 const canStart =
829 Boolean(flow.selectedProject) &&
830 Boolean(flow.selectedModel) &&
831 flow.prompt.trim().length > 0 &&
832 isIncomingShareReady &&
833 !isImportingShare &&
834 !flow.submitting &&
835 !(flow.workspaceMode === "worktree" && !flow.selectedBranchName);
836 const promptEditor = (
837 <ComposerEditor
838 ref={promptInputRef}
839 // The context-first screen intentionally opens with the keyboard closed.
840 // Focusing is a user action, so presenting the form sheet has one motion.
841 autoFocus={false}
842 editable={!isIncomingShareTransferPending}
843 multiline
844 scrollEnabled
845 value={flow.prompt}
846 skills={flow.selectedProviderStatus?.skills ?? []}
847 selection={composerMenu.selection}
848 onChangeText={flow.setPrompt}
849 onSelectionChange={composerMenu.onSelectionChange}
850 onFocus={() => setIsComposerFocused(true)}
851 onBlur={() => setIsComposerFocused(false)}
852 onPasteImages={(uris) => void handleNativePasteImages(uris)}
853 placeholder="Ask anything…"
854 singleLineCentered={false}
855 contentInsetVertical={0}
856 style={{
857 minHeight: 72,
858 maxHeight: 160,
859 paddingHorizontal: 4,
860 paddingVertical: 4,
861 }}
862 textStyle={{ ...bodyText, color: foregroundColor, fontFamily: regularFontFamily }}
863 />
864 );
865
866 const closeNewTask = () => {
867 void KeyboardController.dismiss({ animated: true });
868 const parentNavigation = navigation.getParent();
869 if (parentNavigation) {
870 parentNavigation.goBack();
871 return;
872 }
873 navigation.goBack();
874 };
875 const chooseProject = () => {
876 if (isIncomingShareTransferPending) {
877 return;
878 }
879 promptInputRef.current?.blur();
880 void KeyboardController.dismiss({ animated: true });
881 navigation.dispatch(StackActions.push("NewTask", { incomingShareId: props.incomingShareId }));
882 };
883 const openContextPicker = (routeName: "NewTaskBranch" | "NewTaskEnvironment") => {
884 if (isIncomingShareTransferPending) {
885 return;
886 }
887 promptInputRef.current?.blur();
888 void KeyboardController.dismiss({ animated: true });
889 navigation.dispatch(StackActions.push(routeName));
890 };
891
892 const hero = (
893 <View className="items-center gap-6 px-6" testID="new-task-hero">
894 <View className="w-full items-center gap-1.5">
895 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
896 What should we build
897 </Text>
898 <View className="max-w-full flex-row items-center justify-center">
899 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">in </Text>
900 <Pressable
901 accessibilityHint="Opens the project picker"
902 accessibilityLabel={`Change project from ${selectedProject.title}`}
903 accessibilityRole="button"
904 disabled={isIncomingShareTransferPending}
905 onPress={chooseProject}
906 className="min-w-0 max-w-[250px] border-b border-foreground-muted active:opacity-65"
907 >
908 <Text
909 className="text-2xl font-t3-medium tracking-tight text-foreground"
910 numberOfLines={1}
911 >
912 {selectedProject.title}
913 </Text>
914 </Pressable>
915 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">?</Text>
916 </View>
917 </View>
918
919 <ComposerInlineControl
920 accessibilityLabel={`Environment: ${selectedEnvironmentLabel}`}
921 chevronDirection="right"
922 disabled={isIncomingShareTransferPending}
923 icon="desktopcomputer"
924 label={`on ${selectedEnvironmentLabel}`}
925 maxWidth={260}
926 onPress={
927 flow.environments.length > 1 ? () => openContextPicker("NewTaskEnvironment") : undefined
928 }
929 showChevron={flow.environments.length > 1}
930 static={flow.environments.length <= 1}
931 />
932 </View>
933 );
934 const heroViewport = (
935 <View className="flex-1" collapsable={false}>
936 <ScrollView
937 alwaysBounceVertical={isKeyboardVisible}
938 className="flex-1"
939 contentInsetAdjustmentBehavior="never"
940 contentContainerClassName="grow items-center pb-[236px] pt-12 ios:pt-[72px]"
941 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
942 keyboardShouldPersistTaps="handled"
943 showsVerticalScrollIndicator={false}
944 style={{ flex: 1 }}
945 testID="new-task-hero-scroll"
946 >
947 {hero}
948 </ScrollView>
949 </View>
950 );
951
952 const workspaceControls = (
953 <View className="flex-row items-center gap-1 px-2">
954 <ComposerInlineControl
955 accessibilityHint={`Switches to ${flow.workspaceMode === "local" ? "a new worktree" : "the current checkout"}`}
956 accessibilityLabel={workspaceLabel}
957 disabled={isIncomingShareTransferPending}
958 iconNode={
959 <NewTaskWorkspaceIcon
960 workspaceMode={flow.workspaceMode}
961 worktreePath={flow.selectedWorktreePath}
962 />
963 }
964 label={workspaceLabel}
965 maxWidth={flow.workspaceMode === "local" ? 220 : 148}
966 onPress={() => flow.setWorkspaceMode(flow.workspaceMode === "local" ? "worktree" : "local")}
967 showChevron={false}
968 />
969
970 <ComposerInlineControl
971 accessibilityLabel={`${flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}: ${selectedBranchLabel}`}
972 chevronDirection="right"
973 disabled={isIncomingShareTransferPending}
974 icon="arrow.triangle.branch"
975 label={showBranchLoading ? "Loading branches…" : selectedBranchLabel}
976 maxWidth={190}
977 onPress={() => openContextPicker("NewTaskBranch")}
978 />
979 </View>
980 );
981
982 const composerDock = (
983 <View className="bg-sheet px-4 pt-1" style={{ paddingBottom: controlsBottomPadding }}>
984 {composerMenu.trigger && composerMenu.items.length > 0 ? (
985 <View className="mb-2">
986 <ComposerCommandPopover
987 items={composerMenu.items}
988 triggerKind={composerMenu.trigger.kind}
989 isLoading={composerMenu.isLoading}
990 onSelect={composerMenu.onSelect}
991 />
992 </View>
993 ) : null}
994 <View className="pb-1">{workspaceControls}</View>
995
996 <ComposerSurface
997 animateLayout={false}
998 style={{
999 borderRadius: 26,
1000 minHeight: 140,
1001 overflow: "hidden",
1002 paddingBottom: 6,
1003 paddingHorizontal: 14,
1004 paddingTop: 14,
1005 }}
1006 >
1007 {flow.attachments.length > 0 ? (
1008 <View className="pb-2.5">
1009 <ComposerAttachmentStrip
1010 attachments={flow.attachments}
1011 imageBorderRadius={16}
1012 imageSize={72}
1013 onRemove={isIncomingShareTransferPending ? () => undefined : flow.removeAttachment}
1014 />
1015 </View>
1016 ) : null}
1017
1018 {promptEditor}
1019
1020 <ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={4}>
1021 <ComposerToolbarScroller contentPaddingRight={8} fadeSurface="sheet">
1022 <ComposerToolbarButton
1023 accessibilityLabel="Add attachment"
1024 disabled={isIncomingShareTransferPending}
1025 icon="plus"
1026 onPress={() => void handlePickImages()}
1027 showChevron={false}
1028 />
1029 <ComposerInlineControl
1030 accessibilityLabel="Model and reasoning settings"
1031 disabled={isIncomingShareTransferPending}
1032 emphasized
1033 iconNode={
1034 <ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />
1035 }
1036 label={flow.selectedModelOption?.label ?? "Choose model"}
1037 maxWidth={152}
1038 onPress={settingsSheetPresentation.open}
1039 />
1040 {flow.planModeEnabled ? (
1041 <ComposerInlineControl
1042 accessibilityHint={`Switches to ${flow.interactionMode === "plan" ? "Build" : "Plan"} mode`}
1043 accessibilityLabel={`Interaction mode: ${flow.interactionMode === "plan" ? "Plan" : "Build"}`}
1044 disabled={isIncomingShareTransferPending}
1045 emphasized
1046 icon={
1047 flow.interactionMode === "plan"
1048 ? { ios: "list.bullet.clipboard", android: "auto_awesome" }
1049 : { ios: "hammer", android: "construction" }
1050 }
1051 label={flow.interactionMode === "plan" ? "Plan" : "Build"}
1052 onPress={() =>
1053 flow.setInteractionMode(flow.interactionMode === "plan" ? "default" : "plan")
1054 }
1055 showChevron={false}
1056 />
1057 ) : null}
1058 </ComposerToolbarScroller>
1059 <ComposerToolbarButton
1060 accessibilityLabel={
1061 flow.submitting ? "Starting task" : environmentConnected ? "Start task" : "Queue task"
1062 }
1063 disabled={!canStart}
1064 icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}
1065 onPress={() => void handleStart()}
1066 showChevron={false}
1067 variant="primary"
1068 />
1069 </ComposerToolbarRow>
1070 </ComposerSurface>
1071 </View>
1072 );
1073
1074 if (isAndroid) {
1075 return (
1076 <View className="flex-1 bg-sheet" collapsable={false}>
1077 <NativeStackScreenOptions options={{ headerShown: false }} />
1078 <AndroidScreenHeader title="New task" onBack={closeNewTask} />
1079 {heroViewport}
1080
1081 <KeyboardStickyView
1082 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
1083 offset={{ closed: 0, opened: keyboardOpenedOffset }}
1084 >
1085 {composerDock}
1086 </KeyboardStickyView>
1087 </View>
1088 );
1089 }
1090
1091 return (
1092 <View className="flex-1 bg-sheet" collapsable={false}>
1093 <NativeStackScreenOptions
1094 options={{
1095 headerBackVisible: false,
1096 headerShadowVisible: false,
1097 title: "",
1098 }}
1099 />
1100 <NativeHeaderToolbar placement="left">
1101 <NativeHeaderToolbar.Button
1102 accessibilityLabel="Cancel new task"
1103 label="Cancel"
1104 onPress={closeNewTask}
1105 />
1106 </NativeHeaderToolbar>
1107
1108 {heroViewport}
1109 <KeyboardStickyView
1110 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
1111 offset={{ closed: 0, opened: keyboardOpenedOffset }}
1112 >
1113 {composerDock}
1114 </KeyboardStickyView>
1115 </View>
1116 );
1117}