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

NewTaskDraftScreen.tsx

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