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

NewTaskDraftScreen.tsx

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