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

NewTaskDraftScreen.tsx

1,085 lines39.3 KB

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