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

NewTaskDraftScreen.tsx

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