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