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