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