Open History to see the last commit
1import { NativeStackScreenOptions } from "../../native/StackHeader";
2import { StackActions, useNavigation } from "@react-navigation/native";
3import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4import { Alert, InteractionManager, Platform, View, useColorScheme } from "react-native";
5import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
6import { useSafeAreaInsets } from "react-native-safe-area-context";
7import { useThemeColor } from "../../lib/useThemeColor";
8import { useFontFamily } from "../../lib/useFontFamily";
9
10import { EnvironmentId } from "@t3tools/contracts";
11import {
12 isAtomCommandInterrupted,
13 squashAtomCommandFailure,
14} from "@t3tools/client-runtime/state/runtime";
15
16import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
17import {
18 ComposerToolbarButton,
19 ComposerToolbarRow,
20 ComposerToolbarScroller,
21 ComposerToolbarTrigger,
22} from "../../components/ComposerToolbarTrigger";
23import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
24import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
25import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
26import { ProviderIcon } from "../../components/ProviderIcon";
27import { ComposerSurface } from "./ThreadComposer";
28
29import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
30import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
31import {
32 applyProviderOptionMenuEvent,
33 buildProviderOptionMenuActions,
34 providerOptionsConfigurationLabel,
35 resolveProviderOptionDescriptors,
36} from "../../lib/providerOptions";
37import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
38import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
39import { useProjects } from "../../state/entities";
40import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
41import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
42import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
43import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
44import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
45import { useCreateProjectThread } from "./use-project-actions";
46
47function formatWorkspaceLabel(input: {
48 readonly workspaceMode: string;
49 readonly currentBranchName: string | null;
50 readonly selectedBranchName: string | null;
51}): string {
52 const branchName = input.selectedBranchName ?? input.currentBranchName;
53 if (input.workspaceMode === "worktree") {
54 return branchName ? `New worktree · ${branchName}` : "New worktree";
55 }
56 return branchName ? `Current · ${branchName}` : "Current checkout";
57}
58
59export function NewTaskDraftScreen(props: {
60 readonly initialProjectRef?: {
61 readonly environmentId?: string;
62 readonly projectId?: string;
63 };
64 /** Queued outbox message id when editing an existing pending task. */
65 readonly pendingTaskId?: string;
66}) {
67 const projects = useProjects();
68 const createProjectThread = useCreateProjectThread();
69 const flow = useNewTaskFlow();
70 const navigation = useNavigation();
71 const insets = useSafeAreaInsets();
72 const colorScheme = useColorScheme();
73 const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
74 const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
75 const { logicalProjects, selectedProject, setProject } = flow;
76 const { connectedEnvironments } = useRemoteConnectionStatus();
77 const environmentConnected =
78 selectedProject !== null &&
79 connectedEnvironments.find(
80 (environment) => environment.environmentId === selectedProject.environmentId,
81 )?.connectionState === "connected";
82 const promptInputRef = useRef<ComposerEditorHandle>(null);
83 const loadedBranchesProjectKeyRef = useRef<string | null>(null);
84 const [isComposerFocused, setIsComposerFocused] = useState(false);
85 const appliedInitialProjectKeyRef = useRef<string | null>(null);
86 useEffect(() => {
87 return () => {
88 appliedInitialProjectKeyRef.current = null;
89 };
90 }, []);
91
92 const { beginEditingPendingTask, cancelEditingPendingTask, editingPendingTask } = flow;
93 const attemptedPendingTaskIdRef = useRef<string | null>(null);
94 useEffect(() => {
95 if (!props.pendingTaskId || editingPendingTask?.messageId === props.pendingTaskId) {
96 return;
97 }
98 // Attempt each pending task once: after it is delivered or deleted the
99 // editing session legitimately ends, and re-running must not navigate.
100 if (attemptedPendingTaskIdRef.current === props.pendingTaskId) {
101 return;
102 }
103 attemptedPendingTaskIdRef.current = props.pendingTaskId;
104 if (!beginEditingPendingTask(props.pendingTaskId)) {
105 // The queued task no longer exists (sent or deleted before opening).
106 navigation.dispatch(StackActions.replace("NewTask"));
107 }
108 }, [beginEditingPendingTask, editingPendingTask?.messageId, navigation, props.pendingTaskId]);
109
110 useEffect(() => {
111 if (!props.pendingTaskId) return;
112 return () => {
113 // Allow a later navigation for the same pending task to re-hydrate it.
114 attemptedPendingTaskIdRef.current = null;
115 cancelEditingPendingTask();
116 };
117 }, [props.pendingTaskId, cancelEditingPendingTask]);
118
119 const foregroundColor = useThemeColor("--color-foreground");
120 const regularFontFamily = useFontFamily("regular");
121 const bodyText = useScaledTextRole("body");
122 const headlineText = useScaledTextRole("headline");
123 const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
124 const sheetFadeTransparent = colorScheme === "dark" ? "rgba(14,14,14,0)" : "rgba(242,242,247,0)";
125
126 // A new navigation to this mounted screen delivers a fresh initialProjectRef
127 // reference — treat it as a new request and let it apply again.
128 const lastInitialProjectRefRef = useRef(props.initialProjectRef);
129
130 useEffect(() => {
131 // Pending-task editing owns project selection (and must not fall through
132 // to the replace("NewTask") fallback while its hydration is in flight).
133 if (props.pendingTaskId) {
134 return;
135 }
136 if (lastInitialProjectRefRef.current !== props.initialProjectRef) {
137 lastInitialProjectRefRef.current = props.initialProjectRef;
138 appliedInitialProjectKeyRef.current = null;
139 }
140 const initialEnvironmentId = props.initialProjectRef?.environmentId;
141 const initialProjectId = props.initialProjectRef?.projectId;
142 if (initialEnvironmentId && initialProjectId) {
143 const directProject =
144 projects.find(
145 (project) =>
146 project.environmentId === initialEnvironmentId && project.id === initialProjectId,
147 ) ?? null;
148
149 if (directProject) {
150 // Apply the route's project once. Re-applying on every change would
151 // instantly revert environment/project switches made in the picker.
152 const directProjectKey = `${directProject.environmentId}:${directProject.id}`;
153 if (appliedInitialProjectKeyRef.current === directProjectKey) {
154 return;
155 }
156 appliedInitialProjectKeyRef.current = directProjectKey;
157 if (
158 selectedProject?.environmentId === directProject.environmentId &&
159 selectedProject.id === directProject.id
160 ) {
161 return;
162 }
163 setProject(directProject);
164 return;
165 }
166 }
167
168 if (selectedProject) {
169 return;
170 }
171
172 if (logicalProjects.length === 1) {
173 setProject(logicalProjects[0]!.project);
174 return;
175 }
176
177 navigation.dispatch(StackActions.replace("NewTask"));
178 }, [
179 logicalProjects,
180 projects,
181 props.initialProjectRef,
182 props.pendingTaskId,
183 navigation,
184 selectedProject,
185 setProject,
186 ]);
187
188 useEffect(() => {
189 if (!selectedProject) {
190 loadedBranchesProjectKeyRef.current = null;
191 return;
192 }
193 const projectKey = `${selectedProject.environmentId}:${selectedProject.id}`;
194 if (loadedBranchesProjectKeyRef.current === projectKey) {
195 return;
196 }
197 loadedBranchesProjectKeyRef.current = projectKey;
198 void flow.loadBranches();
199 }, [flow.loadBranches, selectedProject]);
200
201 useEffect(() => {
202 // Android starts with the collapsed composer pill (like an open thread)
203 // and only expands/focuses when tapped.
204 if (!selectedProject || Platform.OS === "android") {
205 return;
206 }
207
208 let focusFrame: ReturnType<typeof requestAnimationFrame> | null = null;
209 const interaction = InteractionManager.runAfterInteractions(() => {
210 focusFrame = requestAnimationFrame(() => promptInputRef.current?.focus());
211 });
212
213 return () => {
214 interaction.cancel();
215 if (focusFrame !== null) {
216 cancelAnimationFrame(focusFrame);
217 }
218 };
219 }, [selectedProject]);
220
221 const environmentMenuActions = useMemo(
222 () =>
223 flow.environments.map((environment) => ({
224 id: `environment:${environment.environmentId}`,
225 title: environment.environmentLabel,
226 state:
227 flow.selectedEnvironmentId === environment.environmentId ? ("on" as const) : undefined,
228 })),
229 [flow.environments, flow.selectedEnvironmentId],
230 );
231
232 const modelMenuActions = useMemo(
233 () =>
234 flow.providerGroups.map((group) => ({
235 id: `provider:${group.providerKey}`,
236 title: group.providerLabel,
237 subtitle: group.models.find(
238 (model) =>
239 flow.selectedModel &&
240 model.selection.instanceId === flow.selectedModel.instanceId &&
241 model.selection.model === flow.selectedModel.model,
242 )?.label,
243 subactions: group.models.map((option) => ({
244 id: `model:${option.key}`,
245 title: option.label,
246 state:
247 flow.selectedModel &&
248 option.selection.instanceId === flow.selectedModel.instanceId &&
249 option.selection.model === flow.selectedModel.model
250 ? ("on" as const)
251 : undefined,
252 })),
253 })),
254 [flow.providerGroups, flow.selectedModel],
255 );
256 const providerOptionDescriptors = useMemo(
257 () =>
258 resolveProviderOptionDescriptors({
259 capabilities: flow.selectedModelOption?.capabilities,
260 selections: flow.selectedModel?.options,
261 }),
262 [flow.selectedModel?.options, flow.selectedModelOption?.capabilities],
263 );
264
265 const optionsMenuActions = useMemo(
266 () => [
267 ...buildProviderOptionMenuActions(providerOptionDescriptors),
268 {
269 id: "options-runtime",
270 title: "Runtime",
271 subtitle:
272 flow.runtimeMode === "approval-required"
273 ? "Approve actions"
274 : flow.runtimeMode === "auto-accept-edits"
275 ? "Auto-accept edits"
276 : "Full access",
277 subactions: [
278 { id: "options:runtime:approval-required", title: "Approve actions" },
279 { id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
280 { id: "options:runtime:full-access", title: "Full access" },
281 ].map((option) => {
282 const value = option.id.replace("options:runtime:", "");
283 return {
284 id: option.id,
285 title: option.title,
286 state: flow.runtimeMode === value ? ("on" as const) : undefined,
287 };
288 }),
289 },
290 {
291 id: "options-interaction",
292 title: "Interaction",
293 subtitle: flow.interactionMode === "plan" ? "Plan" : "Default",
294 subactions: [
295 { id: "options:interaction:default", title: "Default" },
296 { id: "options:interaction:plan", title: "Plan" },
297 ].map((option) => {
298 const value = option.id.replace("options:interaction:", "");
299 return {
300 id: option.id,
301 title: option.title,
302 state: flow.interactionMode === value ? ("on" as const) : undefined,
303 };
304 }),
305 },
306 ],
307 [flow.interactionMode, flow.runtimeMode, providerOptionDescriptors],
308 );
309
310 const workspaceMenuActions = useMemo(() => {
311 const branchActions =
312 flow.availableBranches.length === 0
313 ? [
314 {
315 id: "workspace:branch:none",
316 title: flow.branchesLoading ? "Loading branches…" : "No branches available",
317 attributes: { disabled: true },
318 },
319 ]
320 : flow.availableBranches.slice(0, 12).map((branch) => {
321 const badge = branchBadgeLabel({
322 branch,
323 project: flow.selectedProject,
324 });
325
326 return {
327 id: `workspace:branch:${branch.name}`,
328 title: branch.name,
329 subtitle: badge ? badge.toUpperCase() : undefined,
330 state: flow.selectedBranchName === branch.name ? ("on" as const) : undefined,
331 };
332 });
333
334 return [
335 {
336 id: "workspace:mode",
337 title: "Mode",
338 subtitle: flow.workspaceMode === "local" ? "Current checkout" : "New worktree",
339 subactions: (["local", "worktree"] as const).map((value) => ({
340 id: `workspace:mode:${value}`,
341 title: value === "local" ? "Current checkout" : "New worktree",
342 state: flow.workspaceMode === value ? ("on" as const) : undefined,
343 })),
344 },
345 {
346 id: "workspace:branch",
347 title: "Branch",
348 subtitle: flow.selectedBranchName ?? "Choose branch",
349 subactions: branchActions,
350 },
351 ...(flow.workspaceMode === "worktree"
352 ? [
353 {
354 id: "workspace:start-from-origin",
355 title: "Start from origin",
356 subtitle: "Base the worktree on the latest origin branch",
357 image: "arrow.triangle.pull",
358 state: flow.startFromOrigin ? ("on" as const) : undefined,
359 },
360 ]
361 : []),
362 ];
363 }, [
364 flow.availableBranches,
365 flow.branchesLoading,
366 flow.selectedBranchName,
367 flow.selectedProject,
368 flow.startFromOrigin,
369 flow.workspaceMode,
370 ]);
371
372 const selectedEnvironmentLabel =
373 flow.environments.find(
374 (environment) => environment.environmentId === flow.selectedEnvironmentId,
375 )?.environmentLabel ?? "Environment";
376 const currentBranchName =
377 flow.availableBranches.find((branch) => branch.current)?.name ??
378 flow.availableBranches.find((branch) => branch.isDefault)?.name ??
379 null;
380 const configurationLabel = useMemo(
381 () => providerOptionsConfigurationLabel(providerOptionDescriptors),
382 [providerOptionDescriptors],
383 );
384 const workspaceLabel = useMemo(
385 () =>
386 formatWorkspaceLabel({
387 currentBranchName,
388 selectedBranchName: flow.selectedBranchName,
389 workspaceMode: flow.workspaceMode,
390 }),
391 [currentBranchName, flow.selectedBranchName, flow.workspaceMode],
392 );
393 function handleModelMenuAction(event: string) {
394 if (!event.startsWith("model:")) {
395 return;
396 }
397 flow.setSelectedModelKey(event.slice("model:".length));
398 }
399
400 function handleEnvironmentMenuAction(event: string) {
401 if (!event.startsWith("environment:")) {
402 return;
403 }
404 flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));
405 }
406
407 function handleOptionsMenuAction(event: string) {
408 const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
409 if (providerOptions) {
410 flow.setSelectedModelOptions(providerOptions);
411 return;
412 }
413 if (event.startsWith("options:runtime:")) {
414 flow.setRuntimeMode(
415 event.slice("options:runtime:".length) as Parameters<typeof flow.setRuntimeMode>[0],
416 );
417 return;
418 }
419 if (event.startsWith("options:interaction:")) {
420 flow.setInteractionMode(
421 event.slice("options:interaction:".length) as Parameters<typeof flow.setInteractionMode>[0],
422 );
423 }
424 }
425
426 function handleWorkspaceMenuAction(event: string) {
427 if (event.startsWith("workspace:mode:")) {
428 flow.setWorkspaceMode(
429 event.slice("workspace:mode:".length) as Parameters<typeof flow.setWorkspaceMode>[0],
430 );
431 return;
432 }
433 if (event === "workspace:start-from-origin") {
434 flow.setStartFromOrigin(!flow.startFromOrigin);
435 return;
436 }
437 if (event.startsWith("workspace:branch:")) {
438 const branchName = event.slice("workspace:branch:".length);
439 const branch = flow.availableBranches.find((candidate) => candidate.name === branchName);
440 if (branch) {
441 flow.selectBranch(branch);
442 }
443 }
444 }
445
446 async function handlePickImages(): Promise<void> {
447 const result = await pickComposerImages({ existingCount: flow.attachments.length });
448 if (result.images.length > 0) {
449 flow.appendAttachments(result.images);
450 }
451 }
452
453 const handleNativePasteImages = useCallback(
454 async (uris: ReadonlyArray<string>) => {
455 try {
456 const images = await convertPastedImagesToAttachments({
457 uris,
458 existingCount: flow.attachments.length,
459 });
460 if (images.length > 0) {
461 flow.appendAttachments(images);
462 }
463 } catch (error) {
464 console.error("[native paste] error converting images", error);
465 }
466 },
467 [flow],
468 );
469
470 async function handleStart(): Promise<void> {
471 const selectedProject = flow.selectedProject;
472 const draftKey = flow.draftKey;
473 if (!selectedProject || !draftKey) {
474 return;
475 }
476 const draft = getComposerDraftSnapshot(draftKey);
477 const modelSelection = draft.modelSelection ?? flow.selectedModel;
478 const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
479 const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
480 const selectedWorktreePath =
481 draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;
482 const startFromOrigin = draft.workspaceSelection?.startFromOrigin ?? flow.startFromOrigin;
483 const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;
484 const interactionMode = draft.interactionMode ?? flow.interactionMode;
485 const initialMessageText = draft.text.trim();
486
487 if (
488 !modelSelection ||
489 initialMessageText.length === 0 ||
490 flow.submitting ||
491 (workspaceMode === "worktree" && !selectedBranchName)
492 ) {
493 return;
494 }
495
496 const editingPendingTask = flow.editingPendingTask;
497
498 if (!environmentConnected) {
499 // Offline: park the task in the outbox; the drain sends it when the
500 // environment reconnects. Editing an existing pending task re-queues it
501 // under its original identifiers.
502 const metadata = editingPendingTask
503 ? {
504 threadId: editingPendingTask.threadId,
505 commandId: editingPendingTask.commandId,
506 messageId: editingPendingTask.messageId,
507 createdAt: editingPendingTask.createdAt,
508 }
509 : makeTurnCommandMetadata();
510 const message = flow.buildPendingTaskMessage(metadata);
511 if (!message) {
512 return;
513 }
514 flow.setSubmitting(true);
515 try {
516 await enqueueThreadOutboxMessage(message);
517 } catch (error) {
518 Alert.alert(
519 "Could not queue task",
520 error instanceof Error ? error.message : "The task could not be saved to the outbox.",
521 );
522 return;
523 } finally {
524 flow.setSubmitting(false);
525 }
526 if (editingPendingTask) {
527 flow.finishEditingPendingTask();
528 } else {
529 flow.setPrompt("");
530 flow.clearAttachments();
531 }
532 navigation.getParent()?.goBack();
533 return;
534 }
535
536 flow.setSubmitting(true);
537 // Arm the lock-screen card before the async thread creation: backgrounding
538 // the app right after tapping submit would otherwise reject the foreground
539 // -only Activity start. If creation fails, the token registration's replay
540 // finds no work and ends the card within seconds.
541 armAgentAwarenessLiveActivityForLocalWork({
542 threadTitle: deriveThreadTitleFromPrompt(initialMessageText),
543 projectTitle: selectedProject.title,
544 });
545 const result = await createProjectThread({
546 project: selectedProject,
547 modelSelection,
548 envMode: workspaceMode,
549 branch: selectedBranchName,
550 worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
551 startFromOrigin,
552 runtimeMode,
553 interactionMode,
554 initialMessageText,
555 initialAttachments: draft.attachments,
556 ...(editingPendingTask
557 ? {
558 turnMetadata: {
559 threadId: editingPendingTask.threadId,
560 commandId: editingPendingTask.commandId,
561 messageId: editingPendingTask.messageId,
562 createdAt: editingPendingTask.createdAt,
563 },
564 }
565 : {}),
566 });
567 flow.setSubmitting(false);
568
569 if (result._tag === "Failure") {
570 if (!isAtomCommandInterrupted(result)) {
571 const error = squashAtomCommandFailure(result);
572 Alert.alert(
573 "Could not start task",
574 error instanceof Error ? error.message : "The task could not be started.",
575 );
576 }
577 return;
578 }
579
580 if (editingPendingTask) {
581 try {
582 await removeThreadOutboxMessage(editingPendingTask);
583 } catch (error) {
584 console.warn("[new-task] failed to remove delivered pending task", error);
585 }
586 flow.finishEditingPendingTask();
587 } else {
588 flow.setPrompt("");
589 flow.clearAttachments();
590 }
591 navigation.dispatch(
592 StackActions.replace("Thread", {
593 environmentId: String(result.value.environmentId),
594 threadId: String(result.value.threadId),
595 }),
596 );
597 }
598
599 if (!selectedProject) {
600 return (
601 <View className="flex-1 bg-sheet">
602 {Platform.OS === "android" ? (
603 <>
604 <NativeStackScreenOptions options={{ headerShown: false }} />
605 <AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
606 </>
607 ) : (
608 <NativeStackScreenOptions options={{ title: "Loading task" }} />
609 )}
610 </View>
611 );
612 }
613
614 const isAndroid = Platform.OS === "android";
615 const isDarkMode = colorScheme === "dark";
616 // Android expansion follows native editor focus so relayout cannot race
617 // the touch gesture that opens the keyboard.
618 const isExpanded = !isAndroid || isComposerFocused;
619 const canStart =
620 Boolean(flow.selectedProject) &&
621 Boolean(flow.selectedModel) &&
622 flow.prompt.trim().length > 0 &&
623 !flow.submitting &&
624 !(flow.workspaceMode === "worktree" && !flow.selectedBranchName);
625 const promptEditor = (
626 <ComposerEditor
627 ref={promptInputRef}
628 autoFocus={!isAndroid}
629 multiline
630 scrollEnabled={isExpanded}
631 value={flow.prompt}
632 skills={flow.selectedProviderSkills}
633 onChangeText={flow.setPrompt}
634 onFocus={() => setIsComposerFocused(true)}
635 onBlur={() => setIsComposerFocused(false)}
636 onPasteImages={(uris) => void handleNativePasteImages(uris)}
637 placeholder={`Describe a coding task in ${selectedProject.title}`}
638 // Same collapsed centering as ThreadComposer: native vertical gravity
639 // in a pill-height box.
640 singleLineCentered={!isExpanded}
641 contentInsetVertical={isAndroid ? 0 : undefined}
642 style={
643 isAndroid
644 ? isExpanded
645 ? { minHeight: 80, maxHeight: 160, paddingHorizontal: 4, paddingVertical: 4 }
646 : { height: 36 }
647 : { flex: 1, minHeight: 0 }
648 }
649 textStyle={
650 isAndroid
651 ? { ...bodyText, color: foregroundColor, fontFamily: regularFontFamily }
652 : headlineText
653 }
654 />
655 );
656
657 const toolbarPills = (
658 <>
659 <ComposerToolbarButton
660 icon="plus"
661 onPress={() => void handlePickImages()}
662 showChevron={false}
663 />
664 <ControlPillMenu
665 actions={modelMenuActions}
666 onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
667 >
668 <ComposerToolbarTrigger
669 accessibilityLabel="Model"
670 iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
671 label={flow.selectedModelOption?.label ?? "Model"}
672 />
673 </ControlPillMenu>
674 <ControlPillMenu
675 actions={optionsMenuActions}
676 onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
677 >
678 <ComposerToolbarTrigger
679 accessibilityLabel="Configuration"
680 icon="slider.horizontal.3"
681 label={configurationLabel}
682 />
683 </ControlPillMenu>
684 <ControlPillMenu
685 actions={environmentMenuActions}
686 onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
687 >
688 <ComposerToolbarTrigger
689 accessibilityLabel="Environment"
690 icon="desktopcomputer"
691 label={selectedEnvironmentLabel}
692 />
693 </ControlPillMenu>
694 <ControlPillMenu
695 actions={workspaceMenuActions}
696 onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}
697 >
698 <ComposerToolbarTrigger
699 accessibilityLabel="Workspace"
700 icon="point.topleft.down.curvedto.point.bottomright.up"
701 label={workspaceLabel}
702 />
703 </ControlPillMenu>
704 </>
705 );
706
707 const startButton = (
708 <ComposerToolbarButton
709 accessibilityLabel={
710 flow.submitting ? "Starting task" : environmentConnected ? "Start task" : "Queue task"
711 }
712 icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}
713 onPress={() => void handleStart()}
714 variant="primary"
715 showChevron={false}
716 disabled={!canStart}
717 />
718 );
719
720 if (isAndroid) {
721 // The draft is a thread that doesn't exist yet, so it mirrors the thread
722 // page: in-screen header, empty feed canvas above, and the same floating
723 // composer chrome as ThreadComposer (collapsed pill → expanded card).
724 return (
725 <View className="flex-1 bg-screen">
726 <NativeStackScreenOptions options={{ headerShown: false }} />
727 <AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
728
729 <KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
730 <View className="flex-1" />
731
732 <View
733 className="px-4 pt-2"
734 style={{
735 paddingBottom: controlsBottomPadding,
736 experimental_backgroundImage: isDarkMode
737 ? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.85) 40%, rgba(0,0,0,0.95) 100%)"
738 : "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.85) 40%, rgba(255,255,255,0.95) 100%)",
739 }}
740 >
741 <ComposerSurface
742 isDarkMode={isDarkMode}
743 style={
744 isExpanded
745 ? {
746 borderRadius: 20,
747 overflow: "hidden",
748 paddingHorizontal: 14,
749 paddingVertical: 12,
750 }
751 : {
752 borderRadius: 999,
753 overflow: "hidden",
754 flexDirection: "row",
755 alignItems: "center",
756 paddingLeft: 18,
757 paddingRight: 5,
758 paddingVertical: 5,
759 }
760 }
761 >
762 {isExpanded && flow.attachments.length > 0 ? (
763 <View className="pb-2.5">
764 <ComposerAttachmentStrip
765 attachments={flow.attachments}
766 onRemove={flow.removeAttachment}
767 />
768 </View>
769 ) : null}
770 <View className={isExpanded ? undefined : "min-w-0 flex-1"}>{promptEditor}</View>
771 {!isExpanded ? (
772 <ControlPill
773 icon="arrow.up"
774 variant="primary"
775 disabled={!canStart}
776 onPress={() => void handleStart()}
777 />
778 ) : null}
779 </ComposerSurface>
780
781 {isExpanded ? (
782 <ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
783 <ComposerToolbarScroller
784 fadeOpaque={isDarkMode ? "rgba(0,0,0,0.95)" : "rgba(255,255,255,0.95)"}
785 fadeTransparent={isDarkMode ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)"}
786 >
787 {toolbarPills}
788 </ComposerToolbarScroller>
789 {startButton}
790 </ComposerToolbarRow>
791 ) : null}
792 </View>
793 </KeyboardAvoidingView>
794 </View>
795 );
796 }
797
798 return (
799 <View className="flex-1 bg-sheet">
800 <NativeStackScreenOptions options={{ title: selectedProject.title }} />
801
802 <KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
803 <View className="min-h-0 flex-1 px-5 pt-2">{promptEditor}</View>
804
805 <View className="border-t border-border" style={{ paddingBottom: controlsBottomPadding }}>
806 {flow.attachments.length > 0 ? (
807 <View className="px-4 pt-3">
808 <ComposerAttachmentStrip
809 attachments={flow.attachments}
810 onRemove={flow.removeAttachment}
811 imageSize={88}
812 imageBorderRadius={20}
813 />
814 </View>
815 ) : null}
816 <ComposerToolbarRow paddingBottom={controlsBottomPadding} paddingHorizontal={6}>
817 <ComposerToolbarScroller
818 fadeOpaque={sheetFadeOpaque}
819 fadeTransparent={sheetFadeTransparent}
820 >
821 {toolbarPills}
822 </ComposerToolbarScroller>
823 {startButton}
824 </ComposerToolbarRow>
825 </View>
826 </KeyboardAvoidingView>
827 </View>
828 );
829}