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

NewTaskDraftScreen.tsx

1,453 lines54.3 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 { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
55import { ComposerCommandPopover } from "./ComposerCommandPopover";
56import { useComposerCommandMenu } from "./use-composer-command-menu";
57import {
58 ComposerDictationCancelAction,
59 ComposerDictationPrimaryAction,
60 ComposerDictationStatus,
61 ComposerDictationToolbar,
62} from "../voice-input/ComposerDictationControl";
63import { useVoiceInputController } from "../voice-input/useVoiceInputController";
64import { resolveVoiceComposerPresentation } from "../voice-input/voiceInputPresentation";
65import {
66 useThreadSettingsSheetPresentation,
67 type NavigationWithFinishTransitioning,
68} from "./use-thread-settings-sheet-presentation";
69​
70import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
71import {
72 convertPastedImagesToAttachments,
73 pickComposerFiles,
74 pickComposerMedia,
75 type DraftComposerFileAttachment,
76} from "../../lib/composerImages";
77import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
78import {
79 clearComposerDraftContent,
80 flushComposerDrafts,
81 getComposerDraftSnapshot,
82 mergeComposerDraftContent,
83 restoreComposerDraftSnapshot,
84 scheduleUnusedComposerAttachmentCleanup,
85 type ComposerDraft,
86} from "../../state/use-composer-drafts";
87import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
88import {
89 isModelSelectionUnavailable,
90 resolveSelectableModelSelection,
91} from "../../lib/modelOptions";
92import { resolveProviderInteractionMode } from "./legacy-plan-mode";
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 "Set up Antigravity on web or desktop, 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: deriveThreadTitleSeed({
974 text: initialMessageText,
975 attachments: draft.attachments,
976 }),
977 projectTitle: selectedProject.title,
978 });
979 const creationBranch = resolveProjectThreadCreationBranch({
980 workspaceMode,
981 selectedBranch: selectedBranchName,
982 currentCheckoutBranch: flow.currentCheckoutBranchName,
983 });
984 const result = await createProjectThread({
985 project: selectedProject,
986 modelSelection,
987 envMode: workspaceMode,
988 branch: creationBranch,
989 worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
990 startFromOrigin,
991 runtimeMode,
992 interactionMode,
993 initialMessageText,
994 initialAttachments: draft.attachments,
995 onAttachmentsUploaded: async (attachments) => {
996 flow.replaceAttachments(attachments);
997 await flushComposerDrafts();
998 },
999 ...(editingPendingTask
1000 ? {
1001 turnMetadata: {
1002 threadId: editingPendingTask.threadId,
1003 commandId: editingPendingTask.commandId,
1004 messageId: editingPendingTask.messageId,
1005 createdAt: editingPendingTask.createdAt,
1006 },
1008 : {}),
1009 });
1010 flow.setSubmitting(false);
1011​
1012 if (result._tag === "Failure") {
1013 if (!isAtomCommandInterrupted(result)) {
1014 const error = squashAtomCommandFailure(result);
1015 Alert.alert(
1016 "Could not start task",
1017 error instanceof Error ? error.message : "The task could not be started.",
1018 );
1020 return;
1022​
1023 if (editingPendingTask) {
1024 try {
1025 await removeThreadOutboxMessage(editingPendingTask);
1026 } catch (error) {
1027 console.warn("[new-task] failed to remove delivered pending task", error);
1029 flow.finishEditingPendingTask();
1030 } else {
1031 clearComposerDraftContent(draftKey, {
1032 clearModelSelection: true,
1033 clearWorkspaceSelection: true,
1034 });
1036 setSubmitNavigationAction(
1037 StackActions.replace("Thread", {
1038 environmentId: String(result.value.environmentId),
1039 threadId: String(result.value.threadId),
1040 }),
1041 );
1043​
1044 if (!selectedProject) {
1045 return (
1046 <View className="flex-1 bg-sheet" collapsable={false}>
1047 {Platform.OS === "android" ? (
1048 <>
1049 <NativeStackScreenOptions options={{ headerShown: false }} />
1050 <AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
1051 </>
1052 ) : (
1053 <NativeStackScreenOptions options={{ title: "Loading task" }} />
1054 )}
1055 </View>
1056 );
1058​
1059 const isAndroid = Platform.OS === "android";
1060 const canStart =
1061 attachmentBlockReason === null &&
1062 !modelUnavailable &&
1063 Boolean(flow.selectedProject) &&
1064 Boolean(flow.selectedModel) &&
1065 flow.prompt.trim().length > 0 &&
1066 isIncomingShareReady &&
1067 !isImportingShare &&
1068 !flow.submitting &&
1069 !voiceInput.blocksSubmission &&
1070 !(flow.workspaceMode === "worktree" && !flow.selectedBranchName);
1071 const promptEditor = (
1072 <ComposerEditor
1073 ref={promptInputRef}
1074 // The context-first screen intentionally opens with the keyboard closed.
1075 // Focusing is a user action, so presenting the form sheet has one motion.
1076 autoFocus={false}
1077 editable={!isComposerInteractionLocked}
1078 readOnly={voiceInput.freezesEditor}
1079 multiline
1080 scrollEnabled
1081 value={flow.prompt}
1082 skills={composerMenu.skills}
1083 selection={composerMenu.selection}
1084 onChangeText={flow.setPrompt}
1085 onSelectionChange={composerMenu.onSelectionChange}
1086 onFocus={() => setIsComposerFocused(true)}
1087 onBlur={() => setIsComposerFocused(false)}
1088 onPasteImages={(uris) => void handleNativePasteImages(uris)}
1089 placeholder="Ask anything…"
1090 singleLineCentered={false}
1091 contentInsetVertical={0}
1092 style={{
1093 minHeight: 72,
1094 maxHeight: 160,
1095 paddingVertical: 4,
1096 }}
1097 textStyle={{ ...bodyText, color: foregroundColor, fontFamily: regularFontFamily }}
1098 />
1099 );
1100​
1101 const closeNewTask = () => {
1102 void KeyboardController.dismiss({ animated: true });
1103 const parentNavigation = navigation.getParent();
1104 if (parentNavigation) {
1105 parentNavigation.goBack();
1106 return;
1108 navigation.goBack();
1109 };
1110 const chooseProject = () => {
1111 if (isComposerInteractionLocked) {
1112 return;
1114 promptInputRef.current?.blur();
1115 void KeyboardController.dismiss({ animated: true });
1116 navigation.dispatch(StackActions.push("NewTask", { incomingShareId: props.incomingShareId }));
1117 };
1118 const openContextPicker = (routeName: "NewTaskBranch" | "NewTaskEnvironment") => {
1119 if (isComposerInteractionLocked) {
1120 return;
1122 promptInputRef.current?.blur();
1123 void KeyboardController.dismiss({ animated: true });
1124 navigation.dispatch(StackActions.push(routeName));
1125 };
1126​
1127 const hero = (
1128 <View className="items-center gap-6 px-6" testID="new-task-hero">
1129 <View className="w-full items-center gap-1.5">
1130 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
1131 What should we build
1132 </Text>
1133 <View className="max-w-full flex-row items-center justify-center">
1134 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">in </Text>
1135 <Pressable
1136 accessibilityHint="Opens the project picker"
1137 accessibilityLabel={`Change project from ${selectedProject.title}`}
1138 accessibilityRole="button"
1139 disabled={isComposerInteractionLocked}
1140 onPress={chooseProject}
1141 className="min-w-0 max-w-[250px] border-b border-foreground-muted active:opacity-65"
1143 <Text
1144 className="text-2xl font-t3-medium tracking-tight text-foreground"
1145 numberOfLines={1}
1147 {selectedProject.title}
1148 </Text>
1149 </Pressable>
1150 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">?</Text>
1151 </View>
1152 </View>
1153​
1154 <ComposerInlineControl
1155 accessibilityLabel={`Environment: ${selectedEnvironmentLabel}`}
1156 chevronDirection="right"
1157 disabled={isComposerInteractionLocked || voiceInput.isBusy}
1158 iconNode={
1159 <EnvironmentMachineSymbol
1160 kind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}
1161 size={16}
1162 tintColorClassName="accent-icon-muted"
1163 />
1165 label={`on ${selectedEnvironmentLabel}`}
1166 maxWidth={260}
1167 onPress={
1168 flow.environments.length > 1 ? () => openContextPicker("NewTaskEnvironment") : undefined
1170 showChevron={flow.environments.length > 1}
1171 static={flow.environments.length <= 1}
1172 />
1173 </View>
1174 );
1175 const heroViewport = (
1176 <View className="flex-1" collapsable={false}>
1177 <ScrollView
1178 alwaysBounceVertical={isKeyboardVisible}
1179 className="flex-1"
1180 contentInsetAdjustmentBehavior="never"
1181 contentContainerClassName="grow items-center pb-[236px] pt-12 ios:pt-[72px]"
1182 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
1183 keyboardShouldPersistTaps="handled"
1184 showsVerticalScrollIndicator={false}
1185 style={{ flex: 1 }}
1186 testID="new-task-hero-scroll"
1188 {hero}
1189 </ScrollView>
1190 </View>
1191 );
1192​
1193 const workspaceControls = (
1194 <View className="flex-row items-center gap-1 px-2">
1195 {flow.submitting && environmentConnected && flow.workspaceMode === "worktree" ? (
1196 <View
1197 accessible
1198 accessibilityLabel="Setting up worktree…"
1199 className="h-11 w-full max-w-[260px] flex-row items-center px-2"
1201 <ShimmeringWorkContent
1202 icon="arrow.triangle.branch"
1203 iconSubtleColor={theme["--color-icon-subtle"]}
1204 label="Setting up worktree…"
1205 showIcon
1206 />
1207 </View>
1208 ) : (
1209 <>
1210 <ComposerInlineControl
1211 accessibilityHint={`Switches to ${flow.workspaceMode === "local" ? "a new worktree" : "the current checkout"}`}
1212 accessibilityLabel={workspaceLabel}
1213 disabled={isComposerInteractionLocked || voiceInput.isBusy}
1214 iconNode={
1215 <NewTaskWorkspaceIcon
1216 workspaceMode={flow.workspaceMode}
1217 worktreePath={flow.selectedWorktreePath}
1218 />
1220 label={workspaceLabel}
1221 maxWidth={flow.workspaceMode === "local" ? 220 : 148}
1222 onPress={() =>
1223 flow.setWorkspaceMode(flow.workspaceMode === "local" ? "worktree" : "local")
1225 showChevron={false}
1226 />
1227​
1228 <ComposerInlineControl
1229 accessibilityLabel={`${flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}: ${selectedBranchLabel}`}
1230 chevronDirection="right"
1231 disabled={isComposerInteractionLocked}
1232 icon="arrow.triangle.branch"
1233 label={showBranchLoading ? "Loading branches…" : selectedBranchLabel}
1234 maxWidth={190}
1235 onPress={() => openContextPicker("NewTaskBranch")}
1236 />
1237 </>
1238 )}
1239 </View>
1240 );
1241​
1242 const composerDock = (
1243 <View className="bg-sheet px-[12px] pt-1" style={{ paddingBottom: controlsBottomPadding }}>
1244 {!voiceInput.isBusy && composerMenu.trigger && composerMenu.items.length > 0 ? (
1245 <View className="mb-2">
1246 <ComposerCommandPopover
1247 items={composerMenu.items}
1248 triggerKind={composerMenu.trigger.kind}
1249 isLoading={composerMenu.isLoading}
1250 onSelect={composerMenu.onSelect}
1251 />
1252 </View>
1253 ) : null}
1254 <View className="pb-1">{workspaceControls}</View>
1255​
1256 {modelUnavailable ? (
1257 <Pressable
1258 accessibilityRole="button"
1259 className="px-3 py-2"
1260 disabled={isComposerInteractionLocked}
1261 onPress={settingsSheetPresentation.open}
1263 <Text className="text-xs text-foreground">Model unavailable. Open model settings.</Text>
1264 </Pressable>
1265 ) : null}
1266​
1267 <ComposerSurface
1268 style={{
1269 borderRadius: 26,
1270 minHeight: 140,
1271 overflow: "hidden",
1272 paddingBottom: 6,
1273 paddingTop: 14,
1274 }}
1276 {flow.attachments.length > 0 ? (
1277 <View className="px-[14px] pb-2.5">
1278 <ComposerAttachmentStrip
1279 environmentId={selectedProject.environmentId}
1280 attachments={flow.attachments}
1281 imageBorderRadius={16}
1282 imageSize={72}
1283 onRemove={
1284 isComposerInteractionLocked || voiceInput.isBusy
1285 ? () => undefined
1286 : flow.removeAttachment
1288 onPressPreview={
1289 isComposerInteractionLocked || voiceInput.isBusy ? undefined : openFilePreview
1291 onPressVideo={
1292 isComposerInteractionLocked || voiceInput.isBusy ? undefined : openVideoPreview
1294 />
1295 </View>
1296 ) : null}
1297​
1298 <View className="px-[14px]">{promptEditor}</View>
1299 <View className="h-1" />
1300​
1301 <Animated.View layout={COMPOSER_LAYOUT_TRANSITION} collapsable={false}>
1302 <ComposerDictationToolbar showsDictation={isVoiceInputPresented}>
1303 <ComposerToolbarRow
1304 paddingBottom={0}
1305 paddingHorizontal={0}
1306 paddingTop={0}
1307 style={{ gap: 0 }}
1309 <ComposerDictationCancelAction
1310 presentation={voicePresentation}
1311 onCancel={voiceInput.cancel}
1312 />
1313 {isVoiceInputPresented ? (
1314 <ComposerDictationStatus
1315 audioLevels={voiceInput.audioLevels}
1316 elapsedSeconds={voiceInput.elapsedSeconds}
1317 phase={voiceInput.state.phase}
1318 presentation={voicePresentation}
1319 onDismissError={voiceInput.cancel}
1320 />
1321 ) : (
1322 <>
1323 <ComposerAttachmentButton
1324 disabled={isComposerInteractionLocked}
1325 supportsFiles={Boolean(
1326 selectedEnvironmentServerConfig?.environment.capabilities.fileAttachments,
1327 )}
1328 onPickMedia={handlePickMedia}
1329 onPickFiles={handlePickFiles}
1330 />
1331 <ComposerToolbarScroller align="end" contentPaddingRight={0} fadeSurface="sheet">
1332 <ComposerInlineControl
1333 accessibilityLabel="Model and reasoning settings"
1334 disabled={isComposerInteractionLocked}
1335 emphasized
1336 iconNode={
1337 <ProviderIcon
1338 provider={flow.selectedModelOption?.providerDriver}
1339 size={16}
1340 />
1342 label={flow.selectedModelOption?.label ?? "Choose model"}
1343 maxWidth={152}
1344 onPress={settingsSheetPresentation.open}
1345 />
1346 {flow.planModeEnabled ? (
1347 <ComposerInlineControl
1348 accessibilityHint={`Switches to ${flow.interactionMode === "plan" ? "Build" : "Plan"} mode`}
1349 accessibilityLabel={`Interaction mode: ${flow.interactionMode === "plan" ? "Plan" : "Build"}`}
1350 disabled={isComposerInteractionLocked}
1351 emphasized
1352 icon={
1353 flow.interactionMode === "plan"
1354 ? { ios: "list.bullet.clipboard", android: "auto_awesome" }
1355 : { ios: "hammer", android: "construction" }
1357 label={flow.interactionMode === "plan" ? "Plan" : "Build"}
1358 onPress={() =>
1359 flow.setInteractionMode(
1360 flow.interactionMode === "plan" ? "default" : "plan",
1363 showChevron={false}
1364 />
1365 ) : null}
1366 </ComposerToolbarScroller>
1367 </>
1368 )}
1369 <ComposerDictationPrimaryAction
1370 state={voiceInput.state}
1371 presentation={voicePresentation}
1372 isAvailable={voiceInput.isAvailable}
1373 disabled={isIncomingShareTransferPending || isImportingShare || flow.submitting}
1374 onStart={voiceInput.start}
1375 onConfirm={voiceInput.stop}
1376 onCancel={voiceInput.cancel}
1377 />
1378 {voicePresentation.showsSend ? (
1379 <ComposerActionButton
1380 accessibilityLabel={
1381 attachmentBlockReason ??
1382 (flow.submitting
1383 ? "Starting task"
1384 : environmentConnected
1385 ? "Start task"
1386 : "Queue task")
1388 disabled={!canStart}
1389 icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}
1390 onPress={() => void handleStart()}
1391 variant="primary"
1392 />
1393 ) : null}
1394 </ComposerToolbarRow>
1395 </ComposerDictationToolbar>
1396 </Animated.View>
1397 </ComposerSurface>
1398 <VideoPreviewModal source={previewVideo} onRequestClose={closeMediaPreview} />
1399 <FilePreviewModal source={previewFile} onRequestClose={closeMediaPreview} />
1400 </View>
1401 );
1402​
1403 if (isAndroid) {
1404 return (
1405 <View className="flex-1 bg-sheet" collapsable={false}>
1406 <NativeStackScreenOptions options={{ headerShown: false }} />
1407 <AndroidScreenHeader title="New task" onBack={closeNewTask} />
1408 {heroViewport}
1409​
1410 <KeyboardStickyView
1411 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
1412 offset={{ closed: 0, opened: keyboardOpenedOffset }}
1414 {composerDock}
1415 </KeyboardStickyView>
1416 </View>
1417 );
1419​
1420 return (
1421 <View className="flex-1 bg-sheet" collapsable={false}>
1422 <NativeStackScreenOptions
1423 options={{
1424 headerBackVisible: false,
1425 headerShadowVisible: false,
1426 title: "",
1427 }}
1428 />
1429 <NativeHeaderToolbar placement="left">
1430 <NativeHeaderToolbar.Button
1431 accessibilityLabel="Cancel new task"
1432 label="Cancel"
1433 onPress={closeNewTask}
1434 />
1435 </NativeHeaderToolbar>
1436​
1437 {heroViewport}
1438 <KeyboardStickyView
1439 pointerEvents="box-none"
1440 style={{ position: "absolute", top: 0, bottom: 0, left: 0, right: 0 }}
1441 offset={{ closed: 0, opened: keyboardOpenedOffset }}
1443 <Animated.View
1444 layout={COMPOSER_LAYOUT_TRANSITION}
1445 pointerEvents="box-none"
1446 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
1448 {composerDock}
1449 </Animated.View>
1450 </KeyboardStickyView>
1451 </View>
1452 );