Open History to see the last commit
1import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
2import {
3 StackActions,
4 useFocusEffect,
5 useNavigation,
6 usePreventRemove,
7} from "@react-navigation/native";
8import { useCallback, useEffect, useRef, useState } from "react";
9import { Alert, Platform, Pressable, ScrollView, View, useColorScheme } from "react-native";
10import {
11 KeyboardController,
12 KeyboardStickyView,
13 useKeyboardState,
14} from "react-native-keyboard-controller";
15import { useSafeAreaInsets } from "react-native-safe-area-context";
16import { useThemeColor } from "../../lib/useThemeColor";
17import { useFontFamily } from "../../lib/useFontFamily";
18
19import {
20 isAtomCommandInterrupted,
21 squashAtomCommandFailure,
22} from "@t3tools/client-runtime/state/runtime";
23
24import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
25import {
26 ComposerInlineControl,
27 ComposerToolbarButton,
28 ComposerToolbarRow,
29 ComposerToolbarScroller,
30} from "../../components/ComposerToolbar";
31import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
32import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
33import { ProviderIcon } from "../../components/ProviderIcon";
34import { SymbolView } from "../../components/AppSymbol";
35import { AppText as Text } from "../../components/AppText";
36import { ComposerSurface } from "./ThreadComposer";
37import {
38 useThreadSettingsSheetPresentation,
39 type NavigationWithFinishTransitioning,
40} from "./use-thread-settings-sheet-presentation";
41
42import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
43import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
44import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
45import {
46 clearComposerDraftContent,
47 getComposerDraftSnapshot,
48 mergeComposerDraftContent,
49 restoreComposerDraftSnapshot,
50 type ComposerDraft,
51} from "../../state/use-composer-drafts";
52import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
53import { resolveSelectableModelSelection } from "../../lib/modelOptions";
54import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
55import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
56import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
57import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
58import { useNewTaskFlow } from "./new-task-flow-provider";
59import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation";
60import { useCreateProjectThread } from "./use-project-actions";
61import { resolveDraftProjectSelection } from "./new-task-project-selection";
62import {
63 resolveNewTaskBranchLabel,
64 resolveNewTaskWorkspaceLabel,
65} from "./new-task-context-presentation";
66import { useIncomingShare } from "../sharing/IncomingShareProvider";
67
68function NewTaskWorkspaceIcon(props: {
69 readonly workspaceMode: "local" | "worktree";
70 readonly worktreePath: string | null;
71}) {
72 const iconColor = useThemeColor("--color-icon-muted");
73
74 if (props.workspaceMode === "local" && props.worktreePath === null) {
75 return <SymbolView name="folder" size={16} tintColor={iconColor} type="monochrome" />;
76 }
77
78 return (
79 <View className="size-4">
80 <SymbolView name="folder" size={16} tintColor={iconColor} type="monochrome" />
81 <View className="absolute -right-1 -bottom-1">
82 <SymbolView name="arrow.triangle.branch" size={9} tintColor={iconColor} type="monochrome" />
83 </View>
84 </View>
85 );
86}
87
88export function NewTaskDraftScreen(props: {
89 readonly initialProjectRef?: {
90 readonly environmentId?: string;
91 readonly projectId?: string;
92 };
93 /** Queued outbox message id when editing an existing pending task. */
94 readonly pendingTaskId?: string;
95 /** Durable native share inbox item to merge into this project draft. */
96 readonly incomingShareId?: string;
97}) {
98 const projects = useProjects();
99 const createProjectThread = useCreateProjectThread();
100 const flow = useNewTaskFlow();
101 const navigation = useNavigation();
102 const {
103 consumeShare,
104 getShare,
105 isLoading: isIncomingShareInboxLoading,
106 releaseShareReservation,
107 reserveShare,
108 } = useIncomingShare();
109 const insets = useSafeAreaInsets();
110 const colorScheme = useColorScheme();
111 const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
112 const controlsBottomPadding = Math.max(insets.bottom, 10);
113 const keyboardOpenedOffset = Math.max(0, controlsBottomPadding - 8);
114 const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
115 const { connectedEnvironments } = useRemoteConnectionStatus();
116 const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
117 selectedProject?.environmentId ?? null,
118 );
119 const environmentConnected =
120 selectedProject !== null &&
121 connectedEnvironments.find(
122 (environment) => environment.environmentId === selectedProject.environmentId,
123 )?.connectionState === "connected";
124 const promptInputRef = useRef<ComposerEditorHandle>(null);
125 const loadedBranchesProjectKeyRef = useRef<string | null>(null);
126 const [isComposerFocused, setIsComposerFocused] = useState(false);
127 const settingsSheetPresentation = useThreadSettingsSheetPresentation({
128 editorRef: promptInputRef,
129 isEditorFocused: isComposerFocused,
130 });
131 useEffect(() => {
132 if (Platform.OS !== "ios") {
133 return;
134 }
135
136 navigation.getParent()?.setOptions({ gestureEnabled: !isKeyboardVisible });
137 }, [isKeyboardVisible, navigation]);
138 useEffect(() => {
139 return () => {
140 if (Platform.OS === "ios") {
141 navigation.getParent()?.setOptions({ gestureEnabled: true });
142 }
143 };
144 }, [navigation]);
145 const settingsRoutePresentedRef = useRef(false);
146 useEffect(() => {
147 if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
148 return;
149 }
150
151 settingsRoutePresentedRef.current = true;
152 navigation.dispatch(StackActions.push("ThreadSettings"));
153 }, [navigation, settingsSheetPresentation.isVisible]);
154 useFocusEffect(
155 useCallback(() => {
156 if (!settingsRoutePresentedRef.current) {
157 return;
158 }
159
160 settingsRoutePresentedRef.current = false;
161 settingsSheetPresentation.onDismissed();
162 }, [settingsSheetPresentation.onDismissed]),
163 );
164 useEffect(
165 () =>
166 // UIKit's completion callback for the sheet dismissal, surfaced by the
167 // native-stack patch. This is when the queued keyboard restore runs.
168 (navigation as unknown as NavigationWithFinishTransitioning).addListener(
169 "finishTransitioning",
170 settingsSheetPresentation.onStackTransitionsFinished,
171 ),
172 [navigation, settingsSheetPresentation.onStackTransitionsFinished],
173 );
174 const [importingShareKey, setImportingShareKey] = useState<string | null>(null);
175 const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);
176 const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);
177 const [isReturningToProjectPicker, setIsReturningToProjectPicker] = useState(false);
178 const [shareImportAttempt, setShareImportAttempt] = useState(0);
179 const startedShareImportKeyRef = useRef<string | null>(null);
180 const cancellingShareImportKeyRef = useRef<string | null>(null);
181 const shareImportDraftBackupRef = useRef(new Map<string, ComposerDraft>());
182 const activeShareImportTokenRef = useRef<symbol | null>(null);
183 const shareImportMountedRef = useRef(true);
184 const latestDraftKeyRef = useRef(flow.draftKey);
185 const latestIncomingShareIdRef = useRef(props.incomingShareId);
186 latestDraftKeyRef.current = flow.draftKey;
187 latestIncomingShareIdRef.current = props.incomingShareId;
188 const isImportingShare = importingShareKey !== null;
189 const alertedUnavailableIncomingShareIdRef = useRef<string | null>(null);
190 const incomingShare = props.incomingShareId ? getShare(props.incomingShareId) : null;
191 const requestedInitialProjectAvailable = Boolean(
192 props.initialProjectRef?.environmentId &&
193 props.initialProjectRef.projectId &&
194 projects.some(
195 (project) =>
196 project.environmentId === props.initialProjectRef?.environmentId &&
197 project.id === props.initialProjectRef?.projectId,
198 ),
199 );
200 const isProjectPickerReturnActive =
201 isReturningToProjectPicker && !requestedInitialProjectAvailable;
202 const isIncomingShareTransferPending = Boolean(
203 incomingShare && cancelledIncomingShareId !== props.incomingShareId,
204 );
205 usePreventRemove(
206 (isIncomingShareTransferPending && !isProjectPickerReturnActive) || isCancellingShareImport,
207 () => undefined,
208 );
209 const hasImportedIncomingShare = Boolean(
210 props.incomingShareId &&
211 flow.draftKey &&
212 getComposerDraftSnapshot(flow.draftKey).importedShareIds?.includes(props.incomingShareId),
213 );
214 const isIncomingShareUnavailable = Boolean(
215 props.incomingShareId &&
216 !isIncomingShareInboxLoading &&
217 !incomingShare &&
218 !hasImportedIncomingShare,
219 );
220 const isIncomingShareReady =
221 !props.incomingShareId ||
222 (hasImportedIncomingShare && !incomingShare) ||
223 isIncomingShareUnavailable;
224 const appliedInitialProjectKeyRef = useRef<string | null>(null);
225 useEffect(() => {
226 if (cancelledIncomingShareId === props.incomingShareId) {
227 navigation.goBack();
228 }
229 }, [cancelledIncomingShareId, navigation, props.incomingShareId]);
230 useEffect(() => {
231 if (!isReturningToProjectPicker) {
232 return;
233 }
234 if (requestedInitialProjectAvailable) {
235 setIsReturningToProjectPicker(false);
236 return;
237 }
238 // Let usePreventRemove commit its disabled state before replacing this
239 // route, otherwise the transfer guard can swallow the fallback action.
240 const frame = requestAnimationFrame(() => {
241 navigation.dispatch(
242 StackActions.replace("NewTask", { incomingShareId: props.incomingShareId }),
243 );
244 });
245 return () => cancelAnimationFrame(frame);
246 }, [
247 isReturningToProjectPicker,
248 navigation,
249 props.incomingShareId,
250 requestedInitialProjectAvailable,
251 ]);
252 useEffect(() => {
253 if (!shareImportMountedRef.current) {
254 startedShareImportKeyRef.current = null;
255 }
256 shareImportMountedRef.current = true;
257 return () => {
258 appliedInitialProjectKeyRef.current = null;
259 shareImportMountedRef.current = false;
260 activeShareImportTokenRef.current = null;
261 cancellingShareImportKeyRef.current = null;
262 };
263 }, []);
264
265 const { beginEditingPendingTask, cancelEditingPendingTask, editingPendingTask } = flow;
266 const attemptedPendingTaskIdRef = useRef<string | null>(null);
267 useEffect(() => {
268 if (!props.pendingTaskId || editingPendingTask?.messageId === props.pendingTaskId) {
269 return;
270 }
271 // Attempt each pending task once: after it is delivered or deleted the
272 // editing session legitimately ends, and re-running must not navigate.
273 if (attemptedPendingTaskIdRef.current === props.pendingTaskId) {
274 return;
275 }
276 attemptedPendingTaskIdRef.current = props.pendingTaskId;
277 if (!beginEditingPendingTask(props.pendingTaskId)) {
278 // The queued task no longer exists (sent or deleted before opening).
279 navigation.dispatch(StackActions.replace("NewTask"));
280 }
281 }, [beginEditingPendingTask, editingPendingTask?.messageId, navigation, props.pendingTaskId]);
282
283 useEffect(() => {
284 if (!props.pendingTaskId) return;
285 return () => {
286 // Allow a later navigation for the same pending task to re-hydrate it.
287 attemptedPendingTaskIdRef.current = null;
288 cancelEditingPendingTask();
289 };
290 }, [props.pendingTaskId, cancelEditingPendingTask]);
291
292 const foregroundColor = useThemeColor("--color-foreground");
293 const projectUnderlineColor = useThemeColor("--color-foreground-muted");
294 const regularFontFamily = useFontFamily("regular");
295 const bodyText = useScaledTextRole("body");
296 const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
297 const sheetFadeTransparent = colorScheme === "dark" ? "rgba(14,14,14,0)" : "rgba(242,242,247,0)";
298
299 // A new navigation to this mounted screen delivers a fresh initialProjectRef
300 // reference — treat it as a new request and let it apply again.
301 const lastInitialProjectRefRef = useRef(props.initialProjectRef);
302
303 useEffect(() => {
304 // Pending-task editing owns project selection (and must not fall through
305 // to the replace("NewTask") fallback while its hydration is in flight).
306 if (props.pendingTaskId) {
307 return;
308 }
309 if (lastInitialProjectRefRef.current !== props.initialProjectRef) {
310 lastInitialProjectRefRef.current = props.initialProjectRef;
311 appliedInitialProjectKeyRef.current = null;
312 }
313 const initialEnvironmentId = props.initialProjectRef?.environmentId;
314 const initialProjectId = props.initialProjectRef?.projectId;
315 if (initialEnvironmentId && initialProjectId) {
316 const directProject =
317 projects.find(
318 (project) =>
319 project.environmentId === initialEnvironmentId && project.id === initialProjectId,
320 ) ?? null;
321
322 if (directProject) {
323 // Apply the route's project once. Re-applying on every change would
324 // instantly revert environment/project switches made in the picker.
325 const directProjectKey = `${directProject.environmentId}:${directProject.id}`;
326 if (appliedInitialProjectKeyRef.current === directProjectKey) {
327 return;
328 }
329 appliedInitialProjectKeyRef.current = directProjectKey;
330 if (
331 selectedProject?.environmentId === directProject.environmentId &&
332 selectedProject.id === directProject.id
333 ) {
334 return;
335 }
336 setProject(directProject);
337 return;
338 }
339
340 if (projects.length > 0) {
341 // Never fall through to the flow provider's temporary first-project
342 // default. Return to the picker with the share id intact so the user
343 // can choose an available destination.
344 setIsReturningToProjectPicker(true);
345 }
346 return;
347 }
348
349 const selection = resolveDraftProjectSelection(selectedProjectKey, projects, projectScopes);
350 if (selection.kind === "preserve") {
351 return;
352 }
353 if (selection.kind === "select") {
354 setProject(selection.project);
355 return;
356 }
357
358 navigation.dispatch(StackActions.replace("NewTask"));
359 }, [
360 projectScopes,
361 projects,
362 props.initialProjectRef,
363 props.incomingShareId,
364 props.pendingTaskId,
365 navigation,
366 selectedProject,
367 selectedProjectKey,
368 setProject,
369 ]);
370
371 useEffect(() => {
372 if (!selectedProject) {
373 loadedBranchesProjectKeyRef.current = null;
374 return;
375 }
376 const projectKey = `${selectedProject.environmentId}:${selectedProject.id}`;
377 if (loadedBranchesProjectKeyRef.current === projectKey) {
378 return;
379 }
380 loadedBranchesProjectKeyRef.current = projectKey;
381 flow.loadBranches();
382 }, [flow.loadBranches, selectedProject]);
383
384 useEffect(() => {
385 const shareId = props.incomingShareId;
386 const draftKey = flow.draftKey;
387 const destinationProject = selectedProject;
388 const initialEnvironmentId = props.initialProjectRef?.environmentId;
389 const initialProjectId = props.initialProjectRef?.projectId;
390 const selectedProjectMatchesRoute =
391 !initialEnvironmentId ||
392 !initialProjectId ||
393 (destinationProject?.environmentId === initialEnvironmentId &&
394 destinationProject.id === initialProjectId);
395 if (
396 !shareId ||
397 !draftKey ||
398 !destinationProject ||
399 !selectedProjectMatchesRoute ||
400 cancelledIncomingShareId === shareId
401 ) {
402 return;
403 }
404 const importKey = `${shareId}:${draftKey}`;
405 if (
406 startedShareImportKeyRef.current === importKey ||
407 cancellingShareImportKeyRef.current === importKey
408 ) {
409 return;
410 }
411
412 if (!incomingShare) {
413 if (isIncomingShareUnavailable && alertedUnavailableIncomingShareIdRef.current !== shareId) {
414 alertedUnavailableIncomingShareIdRef.current = shareId;
415 Alert.alert(
416 "Shared content unavailable",
417 "The shared content is no longer in the inbox. You can continue editing this task draft.",
418 );
419 }
420 return;
421 }
422
423 if (alertedUnavailableIncomingShareIdRef.current === shareId) {
424 alertedUnavailableIncomingShareIdRef.current = null;
425 }
426 startedShareImportKeyRef.current = importKey;
427 const draftBackup =
428 shareImportDraftBackupRef.current.get(importKey) ?? getComposerDraftSnapshot(draftKey);
429 shareImportDraftBackupRef.current.set(importKey, draftBackup);
430 const importToken = Symbol(importKey);
431 let didReserveShare = false;
432 let needsDraftRestore = false;
433 activeShareImportTokenRef.current = importToken;
434 setImportingShareKey(importKey);
435 void (async () => {
436 await reserveShare(shareId, {
437 environmentId: String(destinationProject.environmentId),
438 projectId: String(destinationProject.id),
439 });
440 didReserveShare = true;
441 if (
442 !shareImportMountedRef.current ||
443 activeShareImportTokenRef.current !== importToken ||
444 latestDraftKeyRef.current !== draftKey ||
445 latestIncomingShareIdRef.current !== shareId
446 ) {
447 return;
448 }
449 needsDraftRestore = true;
450 const { skippedAttachmentCount } = await mergeComposerDraftContent(draftKey, {
451 text: incomingShare.text,
452 attachments: incomingShare.attachments,
453 sourceShareId: shareId,
454 });
455 if (
456 !shareImportMountedRef.current ||
457 activeShareImportTokenRef.current !== importToken ||
458 latestDraftKeyRef.current !== draftKey ||
459 latestIncomingShareIdRef.current !== shareId
460 ) {
461 // The durable reservation makes an interrupted transfer resume only
462 // in this project instead of copying into a second project draft.
463 return;
464 }
465 await consumeShare(shareId);
466 if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {
467 return;
468 }
469 const warnings = [...incomingShare.warnings];
470 if (skippedAttachmentCount > 0) {
471 warnings.push(
472 `${skippedAttachmentCount} shared image${skippedAttachmentCount === 1 ? " was" : "s were"} skipped because this draft reached the attachment limit.`,
473 );
474 }
475 if (warnings.length > 0) {
476 Alert.alert("Some shared content was skipped", warnings.join("\n"));
477 }
478 shareImportDraftBackupRef.current.delete(importKey);
479 })()
480 .catch((error) => {
481 if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {
482 return;
483 }
484 Alert.alert(
485 "Could not import shared content",
486 error instanceof Error ? error.message : "The shared content could not be saved.",
487 [
488 {
489 text: "Cancel import",
490 style: "cancel",
491 onPress: () => {
492 const cancelImport = async (): Promise<void> => {
493 if (!shareImportMountedRef.current) {
494 return;
495 }
496 // Latch synchronously before restoring the draft. The
497 // restore publishes atom state and can re-run the import
498 // effect before React commits the cancelling state update.
499 cancellingShareImportKeyRef.current = importKey;
500 setIsCancellingShareImport(true);
501 try {
502 if (needsDraftRestore) {
503 await restoreComposerDraftSnapshot(draftKey, draftBackup);
504 needsDraftRestore = false;
505 }
506 if (didReserveShare) {
507 await releaseShareReservation(shareId, {
508 environmentId: String(destinationProject.environmentId),
509 projectId: String(destinationProject.id),
510 });
511 }
512 shareImportDraftBackupRef.current.delete(importKey);
513 if (shareImportMountedRef.current) {
514 setIsCancellingShareImport(false);
515 setCancelledIncomingShareId(shareId);
516 }
517 } catch (cancelError) {
518 if (!shareImportMountedRef.current) {
519 return;
520 }
521 Alert.alert(
522 "Could not cancel import",
523 cancelError instanceof Error
524 ? cancelError.message
525 : "The shared content could not be restored safely.",
526 [
527 {
528 text: "Retry import",
529 onPress: () => {
530 cancellingShareImportKeyRef.current = null;
531 setIsCancellingShareImport(false);
532 setShareImportAttempt((attempt) => attempt + 1);
533 },
534 },
535 {
536 text: "Retry cancel",
537 onPress: () => void cancelImport(),
538 },
539 ],
540 { cancelable: false },
541 );
542 }
543 };
544 void cancelImport();
545 },
546 },
547 {
548 text: "Retry",
549 onPress: () => setShareImportAttempt((attempt) => attempt + 1),
550 },
551 ],
552 { cancelable: false },
553 );
554 })
555 .finally(() => {
556 if (startedShareImportKeyRef.current === importKey) {
557 // Every terminal path, including an invalidated operation, must
558 // release the synchronous start latch so this transfer can retry.
559 startedShareImportKeyRef.current = null;
560 }
561 if (shareImportMountedRef.current && activeShareImportTokenRef.current === importToken) {
562 activeShareImportTokenRef.current = null;
563 setImportingShareKey(null);
564 }
565 });
566 }, [
567 consumeShare,
568 cancelledIncomingShareId,
569 flow.draftKey,
570 hasImportedIncomingShare,
571 incomingShare,
572 isIncomingShareInboxLoading,
573 isIncomingShareUnavailable,
574 props.incomingShareId,
575 props.initialProjectRef?.environmentId,
576 props.initialProjectRef?.projectId,
577 releaseShareReservation,
578 reserveShare,
579 selectedProject,
580 shareImportAttempt,
581 ]);
582
583 const selectedEnvironmentLabel =
584 flow.environments.find(
585 (environment) => environment.environmentId === flow.selectedEnvironmentId,
586 )?.environmentLabel ?? "Environment";
587 const availableCurrentBranchName =
588 flow.availableBranches.find((branch) => branch.current)?.name ??
589 flow.availableBranches.find((branch) => branch.isDefault)?.name ??
590 null;
591 const selectedBranchName = resolveProjectThreadCreationBranch({
592 workspaceMode: flow.workspaceMode,
593 selectedBranch:
594 flow.selectedBranchName ??
595 (flow.workspaceMode === "worktree" ? availableCurrentBranchName : null),
596 currentCheckoutBranch: flow.currentCheckoutBranchName,
597 });
598 const selectedBranchLabel = resolveNewTaskBranchLabel({
599 branchName: selectedBranchName,
600 startFromOrigin: flow.startFromOrigin,
601 workspaceMode: flow.workspaceMode,
602 });
603 const workspaceLabel = resolveNewTaskWorkspaceLabel({
604 workspaceMode: flow.workspaceMode,
605 worktreePath: flow.selectedWorktreePath,
606 });
607 const showBranchLoading = flow.branchesLoading && flow.availableBranches.length === 0;
608
609 async function handlePickImages(): Promise<void> {
610 if (isIncomingShareTransferPending) {
611 return;
612 }
613 const result = await pickComposerImages({ existingCount: flow.attachments.length });
614 if (result.images.length > 0) {
615 flow.appendAttachments(result.images);
616 }
617 }
618
619 const handleNativePasteImages = useCallback(
620 async (uris: ReadonlyArray<string>) => {
621 try {
622 const images = await convertPastedImagesToAttachments({
623 uris,
624 existingCount: flow.attachments.length,
625 });
626 if (images.length > 0) {
627 flow.appendAttachments(images);
628 }
629 } catch (error) {
630 console.error("[native paste] error converting images", error);
631 }
632 },
633 [flow],
634 );
635
636 async function handleStart(): Promise<void> {
637 const selectedProject = flow.selectedProject;
638 const draftKey = flow.draftKey;
639 if (!selectedProject || !draftKey) {
640 return;
641 }
642 const draft = getComposerDraftSnapshot(draftKey);
643 // Snapshot read keeps just-typed selector state; the availability gate
644 // still applies so a stored selection on a disabled provider falls back
645 // to the flow's resolved model.
646 const modelSelection =
647 resolveSelectableModelSelection(
648 selectedEnvironmentServerConfig,
649 draft.modelSelection ?? null,
650 ) ?? flow.selectedModel;
651 const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
652 const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
653 const selectedWorktreePath =
654 draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;
655 const startFromOrigin = draft.workspaceSelection?.startFromOrigin ?? flow.startFromOrigin;
656 const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;
657 const interactionMode = flow.planModeEnabled
658 ? (draft.interactionMode ?? flow.interactionMode)
659 : "default";
660 const initialMessageText = draft.text.trim();
661
662 if (
663 !modelSelection ||
664 initialMessageText.length === 0 ||
665 flow.submitting ||
666 (workspaceMode === "worktree" && !selectedBranchName)
667 ) {
668 return;
669 }
670
671 const editingPendingTask = flow.editingPendingTask;
672
673 if (!environmentConnected) {
674 // Offline: park the task in the outbox; the drain sends it when the
675 // environment reconnects. Editing an existing pending task re-queues it
676 // under its original identifiers.
677 const metadata = editingPendingTask
678 ? {
679 threadId: editingPendingTask.threadId,
680 commandId: editingPendingTask.commandId,
681 messageId: editingPendingTask.messageId,
682 createdAt: editingPendingTask.createdAt,
683 }
684 : makeTurnCommandMetadata();
685 const message = flow.buildPendingTaskMessage(metadata);
686 if (!message) {
687 return;
688 }
689 flow.setSubmitting(true);
690 try {
691 await enqueueThreadOutboxMessage(message);
692 } catch (error) {
693 Alert.alert(
694 "Could not queue task",
695 error instanceof Error ? error.message : "The task could not be saved to the outbox.",
696 );
697 return;
698 } finally {
699 flow.setSubmitting(false);
700 }
701 if (editingPendingTask) {
702 flow.finishEditingPendingTask();
703 } else {
704 // Drop the workspace selection with the content: the next task should
705 // re-resolve mode/branch/origin from the server's configured defaults
706 // instead of resurrecting this task's picks.
707 clearComposerDraftContent(draftKey, { clearWorkspaceSelection: true });
708 }
709 navigation.getParent()?.goBack();
710 return;
711 }
712
713 flow.setSubmitting(true);
714 // Arm the lock-screen card before the async thread creation: backgrounding
715 // the app right after tapping submit would otherwise reject the foreground
716 // -only Activity start. If creation fails, the token registration's replay
717 // finds no work and ends the card within seconds.
718 armAgentAwarenessLiveActivityForLocalWork({
719 environmentId: selectedProject.environmentId,
720 threadTitle: deriveThreadTitleFromPrompt(initialMessageText),
721 projectTitle: selectedProject.title,
722 });
723 const creationBranch = resolveProjectThreadCreationBranch({
724 workspaceMode,
725 selectedBranch: selectedBranchName,
726 currentCheckoutBranch: flow.currentCheckoutBranchName,
727 });
728 const result = await createProjectThread({
729 project: selectedProject,
730 modelSelection,
731 envMode: workspaceMode,
732 branch: creationBranch,
733 worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
734 startFromOrigin,
735 runtimeMode,
736 interactionMode,
737 initialMessageText,
738 initialAttachments: draft.attachments,
739 ...(editingPendingTask
740 ? {
741 turnMetadata: {
742 threadId: editingPendingTask.threadId,
743 commandId: editingPendingTask.commandId,
744 messageId: editingPendingTask.messageId,
745 createdAt: editingPendingTask.createdAt,
746 },
747 }
748 : {}),
749 });
750 flow.setSubmitting(false);
751
752 if (result._tag === "Failure") {
753 if (!isAtomCommandInterrupted(result)) {
754 const error = squashAtomCommandFailure(result);
755 Alert.alert(
756 "Could not start task",
757 error instanceof Error ? error.message : "The task could not be started.",
758 );
759 }
760 return;
761 }
762
763 if (editingPendingTask) {
764 try {
765 await removeThreadOutboxMessage(editingPendingTask);
766 } catch (error) {
767 console.warn("[new-task] failed to remove delivered pending task", error);
768 }
769 flow.finishEditingPendingTask();
770 } else {
771 clearComposerDraftContent(draftKey, { clearWorkspaceSelection: true });
772 }
773 navigation.dispatch(
774 StackActions.replace("Thread", {
775 environmentId: String(result.value.environmentId),
776 threadId: String(result.value.threadId),
777 }),
778 );
779 }
780
781 if (!selectedProject) {
782 return (
783 <View className="flex-1 bg-sheet" collapsable={false}>
784 {Platform.OS === "android" ? (
785 <>
786 <NativeStackScreenOptions options={{ headerShown: false }} />
787 <AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
788 </>
789 ) : (
790 <NativeStackScreenOptions options={{ title: "Loading task" }} />
791 )}
792 </View>
793 );
794 }
795
796 const isAndroid = Platform.OS === "android";
797 const isDarkMode = colorScheme === "dark";
798 const canStart =
799 Boolean(flow.selectedProject) &&
800 Boolean(flow.selectedModel) &&
801 flow.prompt.trim().length > 0 &&
802 isIncomingShareReady &&
803 !isImportingShare &&
804 !flow.submitting &&
805 !(flow.workspaceMode === "worktree" && !flow.selectedBranchName);
806 const promptEditor = (
807 <ComposerEditor
808 ref={promptInputRef}
809 // The context-first screen intentionally opens with the keyboard closed.
810 // Focusing is a user action, so presenting the form sheet has one motion.
811 autoFocus={false}
812 editable={!isIncomingShareTransferPending}
813 multiline
814 scrollEnabled
815 value={flow.prompt}
816 skills={flow.selectedProviderSkills}
817 onChangeText={flow.setPrompt}
818 onFocus={() => setIsComposerFocused(true)}
819 onBlur={() => setIsComposerFocused(false)}
820 onPasteImages={(uris) => void handleNativePasteImages(uris)}
821 placeholder="Ask anything…"
822 singleLineCentered={false}
823 contentInsetVertical={0}
824 style={{
825 minHeight: 72,
826 maxHeight: 160,
827 paddingHorizontal: 4,
828 paddingVertical: 4,
829 }}
830 textStyle={{ ...bodyText, color: foregroundColor, fontFamily: regularFontFamily }}
831 />
832 );
833
834 const closeNewTask = () => {
835 void KeyboardController.dismiss({ animated: true });
836 const parentNavigation = navigation.getParent();
837 if (parentNavigation) {
838 parentNavigation.goBack();
839 return;
840 }
841 navigation.goBack();
842 };
843 const chooseProject = () => {
844 if (isIncomingShareTransferPending) {
845 return;
846 }
847 promptInputRef.current?.blur();
848 void KeyboardController.dismiss({ animated: true });
849 navigation.dispatch(StackActions.push("NewTask", { incomingShareId: props.incomingShareId }));
850 };
851 const openContextPicker = (routeName: "NewTaskBranch" | "NewTaskEnvironment") => {
852 if (isIncomingShareTransferPending) {
853 return;
854 }
855 promptInputRef.current?.blur();
856 void KeyboardController.dismiss({ animated: true });
857 navigation.dispatch(StackActions.push(routeName));
858 };
859
860 const hero = (
861 <View className="items-center gap-6 px-6" testID="new-task-hero">
862 <View className="w-full items-center gap-1.5">
863 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
864 What should we build
865 </Text>
866 <View className="max-w-full flex-row items-center justify-center">
867 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">in </Text>
868 <Pressable
869 accessibilityHint="Opens the project picker"
870 accessibilityLabel={`Change project from ${selectedProject.title}`}
871 accessibilityRole="button"
872 disabled={isIncomingShareTransferPending}
873 onPress={chooseProject}
874 className="min-w-0 max-w-[250px] active:opacity-65"
875 style={{
876 borderBottomColor: projectUnderlineColor,
877 borderBottomWidth: 1,
878 }}
879 >
880 <Text
881 className="text-2xl font-t3-medium tracking-tight text-foreground"
882 numberOfLines={1}
883 >
884 {selectedProject.title}
885 </Text>
886 </Pressable>
887 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">?</Text>
888 </View>
889 </View>
890
891 <ComposerInlineControl
892 accessibilityLabel={`Environment: ${selectedEnvironmentLabel}`}
893 chevronDirection="right"
894 disabled={isIncomingShareTransferPending}
895 icon="desktopcomputer"
896 label={`on ${selectedEnvironmentLabel}`}
897 maxWidth={260}
898 onPress={
899 flow.environments.length > 1 ? () => openContextPicker("NewTaskEnvironment") : undefined
900 }
901 showChevron={flow.environments.length > 1}
902 static={flow.environments.length <= 1}
903 />
904 </View>
905 );
906 const heroViewport = (
907 <View className="flex-1" collapsable={false}>
908 <ScrollView
909 alwaysBounceVertical={isKeyboardVisible}
910 className="flex-1"
911 contentInsetAdjustmentBehavior="never"
912 contentContainerClassName="grow items-center pb-[236px] pt-12 ios:pt-[72px]"
913 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
914 keyboardShouldPersistTaps="handled"
915 showsVerticalScrollIndicator={false}
916 style={{ flex: 1 }}
917 testID="new-task-hero-scroll"
918 >
919 {hero}
920 </ScrollView>
921 </View>
922 );
923
924 const workspaceControls = (
925 <View className="flex-row items-center gap-1 px-2">
926 <ComposerInlineControl
927 accessibilityHint={`Switches to ${flow.workspaceMode === "local" ? "a new worktree" : "the current checkout"}`}
928 accessibilityLabel={workspaceLabel}
929 disabled={isIncomingShareTransferPending}
930 iconNode={
931 <NewTaskWorkspaceIcon
932 workspaceMode={flow.workspaceMode}
933 worktreePath={flow.selectedWorktreePath}
934 />
935 }
936 label={workspaceLabel}
937 maxWidth={flow.workspaceMode === "local" ? 220 : 148}
938 onPress={() => flow.setWorkspaceMode(flow.workspaceMode === "local" ? "worktree" : "local")}
939 showChevron={false}
940 />
941
942 <ComposerInlineControl
943 accessibilityLabel={`${flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}: ${selectedBranchLabel}`}
944 chevronDirection="right"
945 disabled={isIncomingShareTransferPending}
946 icon="arrow.triangle.branch"
947 label={showBranchLoading ? "Loading branches…" : selectedBranchLabel}
948 maxWidth={190}
949 onPress={() => openContextPicker("NewTaskBranch")}
950 />
951 </View>
952 );
953
954 const composerDock = (
955 <View className="bg-sheet px-4 pt-1" style={{ paddingBottom: controlsBottomPadding }}>
956 <View className="pb-1">{workspaceControls}</View>
957
958 <ComposerSurface
959 animateLayout={false}
960 isDarkMode={isDarkMode}
961 style={{
962 borderRadius: 26,
963 minHeight: 140,
964 overflow: "hidden",
965 paddingBottom: 6,
966 paddingHorizontal: 14,
967 paddingTop: 14,
968 }}
969 >
970 {flow.attachments.length > 0 ? (
971 <View className="pb-2.5">
972 <ComposerAttachmentStrip
973 attachments={flow.attachments}
974 imageBorderRadius={16}
975 imageSize={72}
976 onRemove={isIncomingShareTransferPending ? () => undefined : flow.removeAttachment}
977 />
978 </View>
979 ) : null}
980
981 {promptEditor}
982
983 <ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={4}>
984 <ComposerToolbarScroller
985 fadeOpaque={sheetFadeOpaque}
986 fadeTransparent={sheetFadeTransparent}
987 contentPaddingRight={8}
988 >
989 <ComposerToolbarButton
990 accessibilityLabel="Add attachment"
991 disabled={isIncomingShareTransferPending}
992 icon="plus"
993 onPress={() => void handlePickImages()}
994 showChevron={false}
995 />
996 <ComposerInlineControl
997 accessibilityLabel="Model and reasoning settings"
998 disabled={isIncomingShareTransferPending}
999 emphasized
1000 iconNode={
1001 <ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />
1002 }
1003 label={flow.selectedModelOption?.label ?? "Choose model"}
1004 maxWidth={152}
1005 onPress={settingsSheetPresentation.open}
1006 />
1007 {flow.planModeEnabled ? (
1008 <ComposerInlineControl
1009 accessibilityHint={`Switches to ${flow.interactionMode === "plan" ? "Build" : "Plan"} mode`}
1010 accessibilityLabel={`Interaction mode: ${flow.interactionMode === "plan" ? "Plan" : "Build"}`}
1011 disabled={isIncomingShareTransferPending}
1012 emphasized
1013 icon={
1014 flow.interactionMode === "plan"
1015 ? { ios: "list.bullet.clipboard", android: "auto_awesome" }
1016 : { ios: "hammer", android: "construction" }
1017 }
1018 label={flow.interactionMode === "plan" ? "Plan" : "Build"}
1019 onPress={() =>
1020 flow.setInteractionMode(flow.interactionMode === "plan" ? "default" : "plan")
1021 }
1022 showChevron={false}
1023 />
1024 ) : null}
1025 </ComposerToolbarScroller>
1026 <ComposerToolbarButton
1027 accessibilityLabel={
1028 flow.submitting ? "Starting task" : environmentConnected ? "Start task" : "Queue task"
1029 }
1030 disabled={!canStart}
1031 icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}
1032 onPress={() => void handleStart()}
1033 showChevron={false}
1034 variant="primary"
1035 />
1036 </ComposerToolbarRow>
1037 </ComposerSurface>
1038 </View>
1039 );
1040
1041 if (isAndroid) {
1042 return (
1043 <View className="flex-1 bg-sheet" collapsable={false}>
1044 <NativeStackScreenOptions options={{ headerShown: false }} />
1045 <AndroidScreenHeader title="New task" onBack={closeNewTask} />
1046 {heroViewport}
1047
1048 <KeyboardStickyView
1049 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
1050 offset={{ closed: 0, opened: keyboardOpenedOffset }}
1051 >
1052 {composerDock}
1053 </KeyboardStickyView>
1054 </View>
1055 );
1056 }
1057
1058 return (
1059 <View className="flex-1 bg-sheet" collapsable={false}>
1060 <NativeStackScreenOptions
1061 options={{
1062 headerBackVisible: false,
1063 headerShadowVisible: false,
1064 title: "",
1065 }}
1066 />
1067 <NativeHeaderToolbar placement="left">
1068 <NativeHeaderToolbar.Button
1069 accessibilityLabel="Cancel new task"
1070 label="Cancel"
1071 onPress={closeNewTask}
1072 />
1073 </NativeHeaderToolbar>
1074
1075 {heroViewport}
1076 <KeyboardStickyView
1077 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
1078 offset={{ closed: 0, opened: keyboardOpenedOffset }}
1079 >
1080 {composerDock}
1081 </KeyboardStickyView>
1082 </View>
1083 );
1084}