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