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