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

NewTaskDraftScreen.tsx

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