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