Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

NewTaskDraftScreen.tsx

1,449 lines54.2 KB

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