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

NewTaskDraftScreen.tsx

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