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

NewTaskDraftScreen.tsx

1,155 lines41.8 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 : "Full access",
586 subactions: [
587 { id: "options:runtime:approval-required", title: "Approve actions" },
588 { id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
589 { id: "options:runtime:full-access", title: "Full access" },
590 ].map((option) => {
591 const value = option.id.replace("options:runtime:", "");
592 return {
593 id: option.id,
594 title: option.title,
595 state: flow.runtimeMode === value ? ("on" as const) : undefined,
596 };
597 }),
598 },
599 {
600 id: "options-interaction",
601 title: "Interaction",
602 subtitle: flow.interactionMode === "plan" ? "Plan" : "Default",
603 subactions: [
604 { id: "options:interaction:default", title: "Default" },
605 { id: "options:interaction:plan", title: "Plan" },
606 ].map((option) => {
607 const value = option.id.replace("options:interaction:", "");
608 return {
609 id: option.id,
610 title: option.title,
611 state: flow.interactionMode === value ? ("on" as const) : undefined,
612 };
613 }),
614 },
615 ],
616 [flow.interactionMode, flow.runtimeMode, providerOptionDescriptors],
617 );
618​
619 const workspaceMenuActions = useMemo(() => {
620 const branchActions =
621 flow.availableBranches.length === 0
622 ? [
623 {
624 id: "workspace:branch:none",
625 title: flow.branchesLoading ? "Loading branches…" : "No branches available",
626 attributes: { disabled: true },
627 },
628 ]
629 : flow.availableBranches.slice(0, 12).map((branch) => {
630 const badge = branchBadgeLabel({
631 branch,
632 project: flow.selectedProject,
633 });
634​
635 return {
636 id: `workspace:branch:${branch.name}`,
637 title: branch.name,
638 subtitle: badge ? badge.toUpperCase() : undefined,
639 state: flow.selectedBranchName === branch.name ? ("on" as const) : undefined,
640 };
641 });
642​
643 return [
644 {
645 id: "workspace:mode",
646 title: "Mode",
647 subtitle: flow.workspaceMode === "local" ? "Current checkout" : "New worktree",
648 subactions: (["local", "worktree"] as const).map((value) => ({
649 id: `workspace:mode:${value}`,
650 title: value === "local" ? "Current checkout" : "New worktree",
651 state: flow.workspaceMode === value ? ("on" as const) : undefined,
652 })),
653 },
654 {
655 id: "workspace:branch",
656 title: "Branch",
657 subtitle: flow.selectedBranchName ?? "Choose branch",
658 subactions: branchActions,
659 },
660 ...(flow.workspaceMode === "worktree"
661 ? [
662 {
663 id: "workspace:start-from-origin",
664 title: "Start from origin",
665 subtitle: "Base the worktree on the latest origin branch",
666 image: "arrow.triangle.pull",
667 state: flow.startFromOrigin ? ("on" as const) : undefined,
668 },
669 ]
670 : []),
671 ];
672 }, [
673 flow.availableBranches,
674 flow.branchesLoading,
675 flow.selectedBranchName,
676 flow.selectedProject,
677 flow.startFromOrigin,
678 flow.workspaceMode,
679 ]);
680​
681 const selectedEnvironmentLabel =
682 flow.environments.find(
683 (environment) => environment.environmentId === flow.selectedEnvironmentId,
684 )?.environmentLabel ?? "Environment";
685 const currentBranchName =
686 flow.availableBranches.find((branch) => branch.current)?.name ??
687 flow.availableBranches.find((branch) => branch.isDefault)?.name ??
688 null;
689 const configurationLabel = useMemo(
690 () => providerOptionsConfigurationLabel(providerOptionDescriptors),
691 [providerOptionDescriptors],
692 );
693 const workspaceLabel = useMemo(
694 () =>
695 formatWorkspaceLabel({
696 currentBranchName,
697 selectedBranchName: flow.selectedBranchName,
698 workspaceMode: flow.workspaceMode,
699 }),
700 [currentBranchName, flow.selectedBranchName, flow.workspaceMode],
701 );
702 function handleModelMenuAction(event: string) {
703 if (isIncomingShareTransferPending || !event.startsWith("model:")) {
704 return;
705 }
706 flow.setSelectedModelKey(event.slice("model:".length));
707 }
708​
709 function handleEnvironmentMenuAction(event: string) {
710 if (isIncomingShareTransferPending || !event.startsWith("environment:")) {
711 return;
712 }
713 flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));
714 }
715​
716 function handleOptionsMenuAction(event: string) {
717 if (isIncomingShareTransferPending) {
718 return;
719 }
720 const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
721 if (providerOptions) {
722 flow.setSelectedModelOptions(providerOptions);
723 return;
724 }
725 if (event.startsWith("options:runtime:")) {
726 flow.setRuntimeMode(
727 event.slice("options:runtime:".length) as Parameters<typeof flow.setRuntimeMode>[0],
728 );
729 return;
730 }
731 if (event.startsWith("options:interaction:")) {
732 flow.setInteractionMode(
733 event.slice("options:interaction:".length) as Parameters<typeof flow.setInteractionMode>[0],
734 );
735 }
736 }
737​
738 function handleWorkspaceMenuAction(event: string) {
739 if (isIncomingShareTransferPending) {
740 return;
741 }
742 if (event.startsWith("workspace:mode:")) {
743 flow.setWorkspaceMode(
744 event.slice("workspace:mode:".length) as Parameters<typeof flow.setWorkspaceMode>[0],
745 );
746 return;
747 }
748 if (event === "workspace:start-from-origin") {
749 flow.setStartFromOrigin(!flow.startFromOrigin);
750 return;
751 }
752 if (event.startsWith("workspace:branch:")) {
753 const branchName = event.slice("workspace:branch:".length);
754 const branch = flow.availableBranches.find((candidate) => candidate.name === branchName);
755 if (branch) {
756 flow.selectBranch(branch);
757 }
758 }
759 }
760​
761 async function handlePickImages(): Promise<void> {
762 if (isIncomingShareTransferPending) {
763 return;
764 }
765 const result = await pickComposerImages({ existingCount: flow.attachments.length });
766 if (result.images.length > 0) {
767 flow.appendAttachments(result.images);
768 }
769 }
770​
771 const handleNativePasteImages = useCallback(
772 async (uris: ReadonlyArray<string>) => {
773 try {
774 const images = await convertPastedImagesToAttachments({
775 uris,
776 existingCount: flow.attachments.length,
777 });
778 if (images.length > 0) {
779 flow.appendAttachments(images);
780 }
781 } catch (error) {
782 console.error("[native paste] error converting images", error);
783 }
784 },
785 [flow],
786 );
787​
788 async function handleStart(): Promise<void> {
789 const selectedProject = flow.selectedProject;
790 const draftKey = flow.draftKey;
791 if (!selectedProject || !draftKey) {
792 return;
793 }
794 const draft = getComposerDraftSnapshot(draftKey);
795 const modelSelection = draft.modelSelection ?? flow.selectedModel;
796 const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
797 const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
798 const selectedWorktreePath =
799 draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;
800 const startFromOrigin = draft.workspaceSelection?.startFromOrigin ?? flow.startFromOrigin;
801 const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;
802 const interactionMode = draft.interactionMode ?? flow.interactionMode;
803 const initialMessageText = draft.text.trim();
804​
805 if (
806 !modelSelection ||
807 initialMessageText.length === 0 ||
808 flow.submitting ||
809 (workspaceMode === "worktree" && !selectedBranchName)
810 ) {
811 return;
812 }
813​
814 const editingPendingTask = flow.editingPendingTask;
815​
816 if (!environmentConnected) {
817 // Offline: park the task in the outbox; the drain sends it when the
818 // environment reconnects. Editing an existing pending task re-queues it
819 // under its original identifiers.
820 const metadata = editingPendingTask
821 ? {
822 threadId: editingPendingTask.threadId,
823 commandId: editingPendingTask.commandId,
824 messageId: editingPendingTask.messageId,
825 createdAt: editingPendingTask.createdAt,
826 }
827 : makeTurnCommandMetadata();
828 const message = flow.buildPendingTaskMessage(metadata);
829 if (!message) {
830 return;
831 }
832 flow.setSubmitting(true);
833 try {
834 await enqueueThreadOutboxMessage(message);
835 } catch (error) {
836 Alert.alert(
837 "Could not queue task",
838 error instanceof Error ? error.message : "The task could not be saved to the outbox.",
839 );
840 return;
841 } finally {
842 flow.setSubmitting(false);
843 }
844 if (editingPendingTask) {
845 flow.finishEditingPendingTask();
846 } else {
847 clearComposerDraftContent(draftKey);
848 }
849 navigation.getParent()?.goBack();
850 return;
851 }
852​
853 flow.setSubmitting(true);
854 // Arm the lock-screen card before the async thread creation: backgrounding
855 // the app right after tapping submit would otherwise reject the foreground
856 // -only Activity start. If creation fails, the token registration's replay
857 // finds no work and ends the card within seconds.
858 armAgentAwarenessLiveActivityForLocalWork({
859 threadTitle: deriveThreadTitleFromPrompt(initialMessageText),
860 projectTitle: selectedProject.title,
861 });
862 const result = await createProjectThread({
863 project: selectedProject,
864 modelSelection,
865 envMode: workspaceMode,
866 branch: selectedBranchName,
867 worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
868 startFromOrigin,
869 runtimeMode,
870 interactionMode,
871 initialMessageText,
872 initialAttachments: draft.attachments,
873 ...(editingPendingTask
874 ? {
875 turnMetadata: {
876 threadId: editingPendingTask.threadId,
877 commandId: editingPendingTask.commandId,
878 messageId: editingPendingTask.messageId,
879 createdAt: editingPendingTask.createdAt,
880 },
881 }
882 : {}),
883 });
884 flow.setSubmitting(false);
885​
886 if (result._tag === "Failure") {
887 if (!isAtomCommandInterrupted(result)) {
888 const error = squashAtomCommandFailure(result);
889 Alert.alert(
890 "Could not start task",
891 error instanceof Error ? error.message : "The task could not be started.",
892 );
893 }
894 return;
895 }
896​
897 if (editingPendingTask) {
898 try {
899 await removeThreadOutboxMessage(editingPendingTask);
900 } catch (error) {
901 console.warn("[new-task] failed to remove delivered pending task", error);
902 }
903 flow.finishEditingPendingTask();
904 } else {
905 clearComposerDraftContent(draftKey);
906 }
907 navigation.dispatch(
908 StackActions.replace("Thread", {
909 environmentId: String(result.value.environmentId),
910 threadId: String(result.value.threadId),
911 }),
912 );
913 }
914​
915 if (!selectedProject) {
916 return (
917 <View className="flex-1 bg-sheet">
918 {Platform.OS === "android" ? (
919 <>
920 <NativeStackScreenOptions options={{ headerShown: false }} />
921 <AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
922 </>
923 ) : (
924 <NativeStackScreenOptions options={{ title: "Loading task" }} />
925 )}
926 </View>
927 );
928 }
929​
930 const isAndroid = Platform.OS === "android";
931 const isDarkMode = colorScheme === "dark";
932 // Android expansion follows native editor focus so relayout cannot race
933 // the touch gesture that opens the keyboard.
934 const isExpanded = !isAndroid || isComposerFocused;
935 const canStart =
936 Boolean(flow.selectedProject) &&
937 Boolean(flow.selectedModel) &&
938 flow.prompt.trim().length > 0 &&
939 isIncomingShareReady &&
940 !isImportingShare &&
941 !flow.submitting &&
942 !(flow.workspaceMode === "worktree" && !flow.selectedBranchName);
943 const promptEditor = (
944 <ComposerEditor
945 ref={promptInputRef}
946 autoFocus={!isAndroid}
947 editable={!isIncomingShareTransferPending}
948 multiline
949 scrollEnabled={isExpanded}
950 value={flow.prompt}
951 skills={flow.selectedProviderSkills}
952 onChangeText={flow.setPrompt}
953 onFocus={() => setIsComposerFocused(true)}
954 onBlur={() => setIsComposerFocused(false)}
955 onPasteImages={(uris) => void handleNativePasteImages(uris)}
956 placeholder={`Describe a coding task in ${selectedProject.title}`}
957 // Same collapsed centering as ThreadComposer: native vertical gravity
958 // in a pill-height box.
959 singleLineCentered={!isExpanded}
960 contentInsetVertical={isAndroid ? 0 : undefined}
961 style={
962 isAndroid
963 ? isExpanded
964 ? { minHeight: 80, maxHeight: 160, paddingHorizontal: 4, paddingVertical: 4 }
965 : { height: 36 }
966 : { flex: 1, minHeight: 0 }
967 }
968 textStyle={
969 isAndroid
970 ? { ...bodyText, color: foregroundColor, fontFamily: regularFontFamily }
971 : headlineText
972 }
973 />
974 );
975​
976 const toolbarPills = (
977 <>
978 <ComposerToolbarButton
979 icon="plus"
980 onPress={() => void handlePickImages()}
981 showChevron={false}
982 disabled={isIncomingShareTransferPending}
983 />
984 <ControlPillMenu
985 actions={modelMenuActions}
986 onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
987 >
988 <ComposerToolbarTrigger
989 accessibilityLabel="Model"
990 disabled={isIncomingShareTransferPending}
991 iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
992 label={flow.selectedModelOption?.label ?? "Model"}
993 />
994 </ControlPillMenu>
995 <ControlPillMenu
996 actions={optionsMenuActions}
997 onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
998 >
999 <ComposerToolbarTrigger
1000 accessibilityLabel="Configuration"
1001 disabled={isIncomingShareTransferPending}
1002 icon="slider.horizontal.3"
1003 label={configurationLabel}
1004 />
1005 </ControlPillMenu>
1006 <ControlPillMenu
1007 actions={environmentMenuActions}
1008 onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
1010 <ComposerToolbarTrigger
1011 accessibilityLabel="Environment"
1012 disabled={isIncomingShareTransferPending}
1013 icon="desktopcomputer"
1014 label={selectedEnvironmentLabel}
1015 />
1016 </ControlPillMenu>
1017 <ControlPillMenu
1018 actions={workspaceMenuActions}
1019 onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}
1021 <ComposerToolbarTrigger
1022 accessibilityLabel="Workspace"
1023 disabled={isIncomingShareTransferPending}
1024 icon="point.topleft.down.curvedto.point.bottomright.up"
1025 label={workspaceLabel}
1026 />
1027 </ControlPillMenu>
1028 </>
1029 );
1030​
1031 const startButton = (
1032 <ComposerToolbarButton
1033 accessibilityLabel={
1034 flow.submitting ? "Starting task" : environmentConnected ? "Start task" : "Queue task"
1036 icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}
1037 onPress={() => void handleStart()}
1038 variant="primary"
1039 showChevron={false}
1040 disabled={!canStart}
1041 />
1042 );
1043​
1044 if (isAndroid) {
1045 // The draft is a thread that doesn't exist yet, so it mirrors the thread
1046 // page: in-screen header, empty feed canvas above, and the same floating
1047 // composer chrome as ThreadComposer (collapsed pill → expanded card).
1048 return (
1049 <View className="flex-1 bg-screen">
1050 <NativeStackScreenOptions options={{ headerShown: false }} />
1051 <AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
1052​
1053 <KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
1054 <View className="flex-1" />
1055​
1056 <View
1057 className="px-4 pt-2"
1058 style={{
1059 paddingBottom: controlsBottomPadding,
1060 experimental_backgroundImage: isDarkMode
1061 ? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.85) 40%, rgba(0,0,0,0.95) 100%)"
1062 : "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.85) 40%, rgba(255,255,255,0.95) 100%)",
1063 }}
1065 <ComposerSurface
1066 isDarkMode={isDarkMode}
1067 style={
1068 isExpanded
1069 ? {
1070 borderRadius: 20,
1071 overflow: "hidden",
1072 paddingHorizontal: 14,
1073 paddingVertical: 12,
1075 : {
1076 borderRadius: 999,
1077 overflow: "hidden",
1078 flexDirection: "row",
1079 alignItems: "center",
1080 paddingLeft: 18,
1081 paddingRight: 5,
1082 paddingVertical: 5,
1086 {isExpanded && flow.attachments.length > 0 ? (
1087 <View className="pb-2.5">
1088 <ComposerAttachmentStrip
1089 attachments={flow.attachments}
1090 onRemove={
1091 isIncomingShareTransferPending ? () => undefined : flow.removeAttachment
1093 />
1094 </View>
1095 ) : null}
1096 <View className={isExpanded ? undefined : "min-w-0 flex-1"}>{promptEditor}</View>
1097 {!isExpanded ? (
1098 <ControlPill
1099 icon="arrow.up"
1100 variant="primary"
1101 disabled={!canStart}
1102 onPress={() => void handleStart()}
1103 />
1104 ) : null}
1105 </ComposerSurface>
1106​
1107 {isExpanded ? (
1108 <ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
1109 <ComposerToolbarScroller
1110 fadeOpaque={isDarkMode ? "rgba(0,0,0,0.95)" : "rgba(255,255,255,0.95)"}
1111 fadeTransparent={isDarkMode ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)"}
1113 {toolbarPills}
1114 </ComposerToolbarScroller>
1115 {startButton}
1116 </ComposerToolbarRow>
1117 ) : null}
1118 </View>
1119 </KeyboardAvoidingView>
1120 </View>
1121 );
1123​
1124 return (
1125 <View className="flex-1 bg-sheet">
1126 <NativeStackScreenOptions options={{ title: selectedProject.title }} />
1127​
1128 <KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
1129 <View className="min-h-0 flex-1 px-5 pt-2">{promptEditor}</View>
1130​
1131 <View className="border-t border-border" style={{ paddingBottom: controlsBottomPadding }}>
1132 {flow.attachments.length > 0 ? (
1133 <View className="px-4 pt-3">
1134 <ComposerAttachmentStrip
1135 attachments={flow.attachments}
1136 onRemove={isIncomingShareTransferPending ? () => undefined : flow.removeAttachment}
1137 imageSize={88}
1138 imageBorderRadius={20}
1139 />
1140 </View>
1141 ) : null}
1142 <ComposerToolbarRow paddingBottom={controlsBottomPadding} paddingHorizontal={6}>
1143 <ComposerToolbarScroller
1144 fadeOpaque={sheetFadeOpaque}
1145 fadeTransparent={sheetFadeTransparent}
1147 {toolbarPills}
1148 </ComposerToolbarScroller>
1149 {startButton}
1150 </ComposerToolbarRow>
1151 </View>
1152 </KeyboardAvoidingView>
1153 </View>
1154 );