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