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