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

NewTaskDraftScreen.tsx

1,162 lines42.2 KB

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