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

NewTaskDraftScreen.tsx

1,472 lines55.8 KB

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