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

NewTaskDraftScreen.tsx

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