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

NewTaskDraftScreen.tsx

991 lines37.8 KB

1import { DraftEnvironmentControl } from "./DraftEnvironmentControl";
2import { NativeScrollEdgeEffectsContext } from "../../native/NativeScrollViewMarker";
3import { DraftThreadHeader } from "./DraftThreadHeader";
4import { threadHeaderAppearance } from "./thread-header-appearance";
5import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
6import { useComposerAttachmentActions } from "../../state/use-composer-attachment-actions";
7import { useWorkspaceBackNavigation } from "../workspace/useAndroidWorkspaceNavigation";
8import { submittedThreadParams } from "./thread-route-state";
9import { ThreadScreenBinding, ThreadScreenFallback } from "./ThreadScreenHost";
10import { draftThreadShell } from "./draft-thread-shell";
11import { useRememberThreadProject } from "./useRememberThreadProject";
12import { scopedProjectKey } from "../../lib/scopedEntities";
13import { connectionTone } from "../connection/connectionTone";
14import { AppBar } from "../../components/ui/AppBar";
15import { ThreadId } from "@t3tools/contracts";
16​
17import * as Dialog from "../../components/ui/Dialog";
18import { useAtomValue } from "@effect/atom-react";
19import * as Cause from "effect/Cause";
20import { AsyncResult } from "effect/reactivity";
21import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
22import {
23 CommonActions,
24 StackActions,
25 useIsFocused,
26 useNavigation,
27 usePreventRemove,
28 useRoute,
29} from "@react-navigation/native";
30import { useEffect, useRef, useState } from "react";
31import { Platform, Pressable, View } from "react-native";
32import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
33import { KeyboardController } from "react-native-keyboard-controller";
34​
35import {
36 AuthOrchestrationOperateScope,
37 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
38 resolveEnvironmentMachineKind,
39} from "@t3tools/contracts";
40​
41import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
42import { composerContextImportsAtom } from "../../state/use-composer-drafts";
43import { abortComposerDraftOperations } from "../../state/composerDraftOperations";
44import { composerContextSendBlockReason } from "../../lib/composerContext";
45import { ComposerInlineControl } from "../../components/ComposerToolbar";
46​
47import {
48 composerAttachmentUploadBlockReason,
49 composerAttachmentsStillUploading,
50 composerAttachmentUploadsAtom,
51} from "../../state/composer-attachment-uploads";
52​
53import { SymbolView } from "../../components/ui/AppSymbol";
54import { AppText as Text } from "../../components/ui/AppText";
55import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences";
56​
57import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
58​
59import {
60 clearComposerDraftContent,
61 getComposerDraftSnapshot,
62 updateComposerDraftSettings,
63 scheduleUnusedComposerAttachmentCleanup,
64} from "../../state/use-composer-drafts";
65import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
66import { useProjectClone } from "../../state/projectClones";
67import { projectEnvironment } from "../../state/projects";
68import { sourceControlEnvironment } from "../../state/sourceControl";
69import { useAtomCommand } from "../../state/use-atom-command";
70import { ProjectCloneBanner } from "./ProjectCloneBanner";
71import {
72 describeUnavailableModelSelection,
73 isModelSelectionUnavailable,
74 resolveSelectableModelSelection,
75} from "../../lib/modelOptions";
76import { enqueueThreadOutboxMessage } from "../../state/thread-outbox";
77import {
78 useRemoteConnections,
79 useRemoteEnvironmentRuntime,
80} from "../../state/use-remote-environment-registry";
81import { useNewTaskFlow } from "./new-task-flow-provider";
82import {
83 nextEnvironmentId,
84 useHardwareKeyboardCommand,
85} from "../keyboard/hardwareKeyboardCommands";
86import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation";
87import { resolveDraftProjectSelection } from "./new-task-project-selection";
88import {
89 resolveNewTaskBranchLabel,
90 resolveNewTaskWorkspaceLabel,
91} from "./new-task-context-presentation";
92import { incomingShareImports, useIncomingShare } from "../sharing/IncomingShareProvider";
93import { idleShareFlagAtom, idleShareImportPhaseAtom } from "./incomingShareImport";
94import { newTaskFlowKey } from "./new-task-flow-state";
95import { appAtomRegistry } from "../../state/atom-registry";
96​
97import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
98​
99function NewTaskWorkspaceIcon(props: {
100 readonly workspaceMode: "local" | "worktree";
101 readonly worktreePath: string | null;
102 readonly size: number;
103}) {
104 if (props.workspaceMode === "local" && props.worktreePath === null) {
105 return (
106 <SymbolView
107 name="folder"
108 size={props.size}
109 tintColorClassName="accent-icon-muted"
110 type="monochrome"
111 />
112 );
113 }
114​
115 const boxSize = (14 * props.size) / 16;
116 return (
117 <View
118 className="size-4"
119 style={Platform.OS === "android" ? { width: boxSize, height: boxSize } : undefined}
120 >
121 <SymbolView
122 name="folder"
123 size={props.size}
124 tintColorClassName="accent-icon-muted"
125 type="monochrome"
126 />
127 <View
128 className="absolute -right-1 -bottom-1"
129 style={
130 Platform.OS === "android" ? { right: -boxSize / 4, bottom: -boxSize / 4 } : undefined
131 }
132 >
133 <SymbolView
134 name="arrow.triangle.branch"
135 size={Math.round((9 * props.size) / 16)}
136 tintColorClassName="accent-icon-muted"
137 type="monochrome"
138 />
139 </View>
140 </View>
141 );
143​
144export function NewTaskDraftScreen(props: {
145 readonly initialProjectRef?: {
146 readonly environmentId?: string;
147 readonly projectId?: string;
148 readonly branch?: string | null;
149 readonly worktreePath?: string | null;
150 readonly cloning?: boolean;
151 };
152 readonly draftId?: string;
153 readonly incomingShareId?: string;
154}) {
155 const [creationMetadata] = useState(makeTurnCommandMetadata);
156 const projects = useProjects();
157 const flow = useNewTaskFlow();
158 const navigation = useNavigation();
159 const isFocused = useIsFocused();
160 const goBack = useWorkspaceBackNavigation("threads");
161 const currentRoute = useRoute();
162 const flowKey = newTaskFlowKey(currentRoute);
163 const { getShare, isLoading: isIncomingShareInboxLoading } = useIncomingShare();
164 const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
165 // selectedProject falls back to the environment's first project; remember only a chosen one.
166 useRememberThreadProject(
167 selectedProject &&
168 selectedProjectKey === scopedProjectKey(selectedProject.environmentId, selectedProject.id)
169 ? selectedProject
170 : null,
171 );
172 const selectedProjectLabel = (() => {
173 if (!selectedProject) return null;
174 const scope = projectScopes.find((candidate) =>
175 candidate.projectRefs.some(
176 (ref) =>
177 ref.environmentId === selectedProject.environmentId &&
178 ref.projectId === selectedProject.id,
179 ),
180 );
181 return scope?.title ?? selectedProject.title;
182 })();
183 const { onReconnectEnvironment } = useRemoteConnections();
184 const environmentRuntime = useRemoteEnvironmentRuntime(selectedProject?.environmentId ?? null);
185 const connectionState = environmentRuntime?.connectionState ?? "offline";
186 const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
187 selectedProject?.environmentId ?? null,
188 );
189 const environmentConnected = connectionState === "connected";
190 const canOperate = useEnvironmentScope(
191 selectedProject?.environmentId ?? null,
192 AuthOrchestrationOperateScope,
193 );
194 const projectCloneState = useProjectClone(
195 selectedProject
196 ? { environmentId: selectedProject.environmentId, projectId: selectedProject.id }
197 : null,
198 );
199 const projectClone = projectCloneState === "pending" ? null : projectCloneState;
200 const awaitingKnownClone =
201 projectCloneState === "pending" &&
202 props.initialProjectRef?.cloning === true &&
203 selectedProject !== null &&
204 selectedProject.id === props.initialProjectRef.projectId &&
205 selectedProject.environmentId === props.initialProjectRef.environmentId;
206 const cloneBlocksStart =
207 awaitingKnownClone || (projectClone !== null && projectClone.phase !== "done");
208 const cancelProjectClone = useAtomCommand(sourceControlEnvironment.cancelProjectClone, {
209 reportFailure: false,
210 });
211 const retryProjectClone = useAtomCommand(sourceControlEnvironment.retryProjectClone, {
212 reportFailure: false,
213 });
214 const runCloneAction = async (
215 title: string,
216 action: () => Promise<AsyncResult.AsyncResult<unknown, unknown>>,
217 ) => {
218 const result = await action();
219 if (AsyncResult.isFailure(result)) {
220 const error = Cause.squash(result.cause);
221 Dialog.alert(title, error instanceof Error ? error.message : "An error occurred.");
222 }
223 };
224 const deleteProject = useAtomCommand(projectEnvironment.delete, { reportFailure: false });
225 const removeClonedProject = async () => {
226 if (!selectedProject) return;
227 const removed = selectedProject;
228 const result = await deleteProject({
229 environmentId: removed.environmentId,
230 input: { projectId: removed.id },
231 });
232 if (AsyncResult.isFailure(result)) {
233 const error = Cause.squash(result.cause);
234 Dialog.alert(
235 "Failed to remove project",
236 error instanceof Error ? error.message : "An error occurred.",
237 );
238 return;
239 }
240 if (flow.getSelectedProjectKey() === scopedProjectKey(removed.environmentId, removed.id)) {
241 navigation.dispatch(StackActions.replace("Home"));
242 }
243 };
244 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
245 const attachmentBlockReason = selectedProject
246 ? composerAttachmentUploadBlockReason({
247 environmentId: selectedProject.environmentId,
248 attachments: flow.attachments,
249 connected: environmentConnected,
250 serverConfig: selectedEnvironmentServerConfig,
251 states: uploadStates,
252 })
253 : null;
254 const attachmentsUploading =
255 environmentConnected &&
256 selectedProject !== null &&
257 composerAttachmentsStillUploading({
258 environmentId: selectedProject.environmentId,
259 attachments: flow.attachments,
260 serverConfig: selectedEnvironmentServerConfig,
261 states: uploadStates,
262 });
263 const queuesInsteadOfStarting = !environmentConnected || attachmentsUploading;
264 const promptInputRef = useRef<ComposerEditorHandle>(null);
265 const loadedBranchesProjectKeyRef = useRef<string | null>(null);
266 const [isReturningToProjectPicker, setIsReturningToProjectPicker] = useState(false);
267 const incomingShare = props.incomingShareId ? getShare(props.incomingShareId) : null;
268 const requestedInitialProjectAvailable = Boolean(
269 props.initialProjectRef?.environmentId &&
270 props.initialProjectRef.projectId &&
271 projects.some(
272 (project) =>
273 project.environmentId === props.initialProjectRef?.environmentId &&
274 project.id === props.initialProjectRef?.projectId,
275 ),
276 );
277 // A route naming a draft that is gone, or whose project is gone, also
278 // returns to the picker.
279 const isRouteDraftMissing =
280 props.draftId !== undefined && flow.missingRouteDraftId === props.draftId;
281 const isProjectPickerReturnActive =
282 (isReturningToProjectPicker && !requestedInitialProjectAvailable) || isRouteDraftMissing;
283 const isIncomingShareAwaitingServerConfig = Boolean(
284 incomingShare?.attachments.some((attachment) => attachment.type === "file") &&
285 selectedEnvironmentServerConfig === null,
286 );
287 const routeImportedShare = useAtomValue(
288 flowKey !== undefined && props.incomingShareId
289 ? incomingShareImports.importedAtom(flowKey, props.incomingShareId)
290 : idleShareFlagAtom,
291 );
292 const hasImportedIncomingShare = Boolean(
293 props.incomingShareId &&
294 (routeImportedShare ||
295 (flow.draftKey &&
296 getComposerDraftSnapshot(flow.draftKey).importedShareIds?.includes(props.incomingShareId))),
297 );
298 const isIncomingShareUnavailable = Boolean(
299 props.incomingShareId &&
300 !isIncomingShareInboxLoading &&
301 !incomingShare &&
302 !hasImportedIncomingShare,
303 );
304 const shareImportTarget = (() => {
305 if (!props.incomingShareId || flowKey === undefined || !flow.draftKey) return null;
306 if (!selectedProject || !incomingShare || isIncomingShareAwaitingServerConfig) return null;
307 const initialEnvironmentId = props.initialProjectRef?.environmentId;
308 const initialProjectId = props.initialProjectRef?.projectId;
309 if (
310 initialEnvironmentId &&
311 initialProjectId &&
312 (selectedProject.environmentId !== initialEnvironmentId ||
313 selectedProject.id !== initialProjectId)
314 ) {
315 return null;
316 }
317 return {
318 flowKey,
319 routeKey: currentRoute.key,
320 draftKey: flow.draftKey,
321 destination: {
322 environmentId: String(selectedProject.environmentId),
323 projectId: String(selectedProject.id),
324 },
325 shareId: incomingShare.id,
326 };
327 })();
328 const shareImportPhase = useAtomValue(
329 shareImportTarget === null
330 ? idleShareImportPhaseAtom
331 : incomingShareImports.phaseAtom(shareImportTarget),
332 );
333 // Locks on the route, not the target: the target turns null when server config
334 // drops or the project stops matching, while the import keeps writing the draft.
335 const isImportingShare = useAtomValue(
336 flowKey === undefined ? idleShareFlagAtom : incomingShareImports.inFlightAtom(flowKey),
337 );
338 const isIncomingShareTransferPending = Boolean(
339 incomingShare && shareImportPhase !== "cancelled" && !isIncomingShareAwaitingServerConfig,
340 );
341 // A failed import waits in a modal alert, and a cancel finishes its undo even
342 // after the route leaves, so neither holds the route: the cancel can leave as
343 // soon as it is done.
344 const isIncomingShareHoldingRoute =
345 isIncomingShareTransferPending &&
346 shareImportPhase !== "failed" &&
347 shareImportPhase !== "cancelling";
348 const contextImports = useAtomValue(composerContextImportsAtom);
349 const isImportingContext = flow.draftKey ? contextImports[flow.draftKey] === true : false;
350 const isComposerInteractionLocked =
351 isIncomingShareTransferPending || flow.submitting || isImportingContext;
352 const { environments, selectedEnvironmentId, switchEnvironment, switchingToEnvironmentId } = flow;
353 const cycleEnvironment = () => {
354 if (isComposerInteractionLocked) return true;
355 const next = nextEnvironmentId(environments, switchingToEnvironmentId ?? selectedEnvironmentId);
356 if (next !== null) void switchEnvironment(next);
357 return true;
358 };
359 const cycleEnvironmentCommands = environments.length > 1 ? (["cycleHost"] as const) : [];
360 useHardwareKeyboardCommand(cycleEnvironmentCommands, cycleEnvironment);
361 const composerWorkspaceCwd =
362 (flow.workspaceMode === "worktree"
363 ? selectedProject?.workspaceRoot
364 : (flow.selectedWorktreePath ?? selectedProject?.workspaceRoot)) || null;
365 const preventRemove =
366 (isIncomingShareHoldingRoute && !isProjectPickerReturnActive) || flow.submitting;
367 usePreventRemove(preventRemove, () => undefined);
368 const isIncomingShareReady =
369 !props.incomingShareId ||
370 (hasImportedIncomingShare && !incomingShare) ||
371 isIncomingShareUnavailable;
372 const appliedInitialProjectKeyRef = useRef<string | null>(null);
373 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- ends the picker return once the project arrives, else replaces the route with the picker next frame
374 useEffect(() => {
375 if (isReturningToProjectPicker && requestedInitialProjectAvailable) {
376 // oxlint-disable-next-line react/set-state-in-effect -- Ends the return-to-picker flow once the requested project arrives from the catalog.
377 setIsReturningToProjectPicker(false);
378 }
379 if (!isProjectPickerReturnActive) {
380 return;
381 }
382 // Wait for usePreventRemove to disable before replacing, or the transfer guard swallows the fallback.
383 const frame = requestAnimationFrame(() => {
384 navigation.dispatch(
385 StackActions.replace("NewTaskProject", { incomingShareId: props.incomingShareId }),
386 );
387 });
388 return () => cancelAnimationFrame(frame);
389 }, [
390 isProjectPickerReturnActive,
391 isReturningToProjectPicker,
392 navigation,
393 props.incomingShareId,
394 requestedInitialProjectAvailable,
395 ]);
396​
397 const lastInitialProjectRefRef = useRef(props.initialProjectRef);
398 const initialPickerRef = useRef<"open" | "dismissed" | null>(null);
399​
400 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- applies the route or catalog project to the draft once projects load, or opens the picker in the navigator
401 useEffect(() => {
402 if (props.draftId) {
403 return;
404 }
405 if (lastInitialProjectRefRef.current !== props.initialProjectRef) {
406 lastInitialProjectRefRef.current = props.initialProjectRef;
407 appliedInitialProjectKeyRef.current = null;
408 }
409 const initialEnvironmentId = props.initialProjectRef?.environmentId;
410 const initialProjectId = props.initialProjectRef?.projectId;
411 if (initialEnvironmentId && initialProjectId) {
412 const directProject =
413 projects.find(
414 (project) =>
415 project.environmentId === initialEnvironmentId && project.id === initialProjectId,
416 ) ?? null;
417​
418 if (directProject) {
419 // Apply the route project once or picker changes would immediately revert.
420 const directProjectKey = `${directProject.environmentId}:${directProject.id}`;
421 if (appliedInitialProjectKeyRef.current === directProjectKey) {
422 return;
423 }
424 if (props.initialProjectRef?.branch) {
425 if (
426 selectedProject?.environmentId !== directProject.environmentId ||
427 selectedProject.id !== directProject.id
428 ) {
429 setProject(directProject);
430 return;
431 }
432 if (!flow.draftKey) return;
433 // Checkout completed before mount; local mode reuses it while worktree mode would create another.
434 updateComposerDraftSettings(flow.draftKey, {
435 workspaceSelection: {
436 mode: "local",
437 branch: props.initialProjectRef.branch,
438 worktreePath: props.initialProjectRef.worktreePath ?? null,
439 startFromOrigin: false,
440 },
441 });
442 }
443 appliedInitialProjectKeyRef.current = directProjectKey;
444 if (
445 selectedProject?.environmentId === directProject.environmentId &&
446 selectedProject.id === directProject.id
447 ) {
448 return;
449 }
450 setProject(directProject);
451 return;
452 }
453​
454 if (projects.length > 0) {
455 // oxlint-disable-next-line react/set-state-in-effect -- Route-driven project resolution starts the return-to-picker flow when no project matches.
456 setIsReturningToProjectPicker(true);
457 }
458 return;
459 }
460​
461 const selection = resolveDraftProjectSelection(selectedProjectKey, projects, projectScopes, {
462 incomingShareId: props.incomingShareId,
463 pickerClosed: initialPickerRef.current === "open" && isFocused,
464 });
465 if (selection.kind === "preserve") {
466 initialPickerRef.current = null;
467 return;
468 }
469 if (selection.kind === "select") {
470 setProject(selection.project);
471 return;
472 }
473 if (selection.kind === "dismiss") {
474 initialPickerRef.current = "dismissed";
475 goBack();
476 return;
477 }
478 // Open the first picker once; catalog updates must not push it again over a cancelled draft.
479 if (initialPickerRef.current !== null) {
480 return;
481 }
482 initialPickerRef.current = "open";
483 navigation.dispatch(CommonActions.navigate("NewTaskProject"));
484 }, [
485 goBack,
486 isFocused,
487 projectScopes,
488 projects,
489 flow.draftKey,
490 props.initialProjectRef,
491 props.incomingShareId,
492 props.draftId,
493 navigation,
494 selectedProject,
495 selectedProjectKey,
496 setProject,
497 ]);
498​
499 const { loadBranches } = flow;
500 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- requests the selected project's branch list from the server once per project
501 useEffect(() => {
502 if (!selectedProject) {
503 loadedBranchesProjectKeyRef.current = null;
504 return;
505 }
506 const projectKey = `${selectedProject.environmentId}:${selectedProject.id}`;
507 if (loadedBranchesProjectKeyRef.current === projectKey) {
508 return;
509 }
510 loadedBranchesProjectKeyRef.current = projectKey;
511 loadBranches();
512 }, [loadBranches, selectedProject]);
513​
514 const selectedEnvironmentLabel =
515 flow.environments.find(
516 (environment) => environment.environmentId === flow.selectedEnvironmentId,
517 )?.environmentLabel ?? "Environment";
518 const availableCurrentBranchName =
519 flow.availableBranches.find((branch) => branch.current)?.name ??
520 flow.availableBranches.find((branch) => branch.isDefault)?.name ??
521 null;
522 const selectedBranchName = resolveProjectThreadCreationBranch({
523 workspaceMode: flow.workspaceMode,
524 selectedBranch:
525 flow.selectedBranchName ??
526 (flow.workspaceMode === "worktree" ? availableCurrentBranchName : null),
527 currentCheckoutBranch: flow.currentCheckoutBranchName,
528 });
529 const selectedBranchLabel = resolveNewTaskBranchLabel({
530 branchName: selectedBranchName,
531 startFromOrigin: flow.startFromOrigin,
532 workspaceMode: flow.workspaceMode,
533 pullRequestReference: flow.pullRequestReference,
534 });
535 const workspaceLabel = resolveNewTaskWorkspaceLabel({
536 workspaceMode: flow.workspaceMode,
537 worktreePath: flow.selectedWorktreePath,
538 });
539 const showBranchLoading =
540 environmentConnected && flow.branchesLoading && flow.availableBranches.length === 0;
541​
542 const {
543 onPickDraftMedia: handlePickMedia,
544 onPickDraftFiles: handlePickFiles,
545 onNativePasteImages: handleNativePasteImages,
546 onNativePasteText: handleNativePasteText,
547 } = useComposerAttachmentActions({
548 draftKey: flow.draftKey,
549 serverConfig: selectedEnvironmentServerConfig,
550 locked: isComposerInteractionLocked,
551 });
552​
553 async function handleStart(): Promise<import("@t3tools/contracts").MessageId | null> {
554 const selectedProject = flow.selectedProject;
555 const draftKey = flow.draftKey;
556 if (
557 !selectedProject ||
558 !draftKey ||
559 cloneBlocksStart ||
560 !isIncomingShareReady ||
561 isImportingShare ||
562 isComposerInteractionLocked
563 ) {
564 return null;
565 }
566 if (
567 environmentConnected &&
568 !readEnvironmentScope(selectedProject.environmentId, AuthOrchestrationOperateScope)
569 ) {
570 return null;
571 }
572 const draft = getComposerDraftSnapshot(draftKey);
573 if (appAtomRegistry.get(composerContextImportsAtom)[draftKey]) return null;
574 const modelSelection =
575 resolveSelectableModelSelection(
576 selectedEnvironmentServerConfig,
577 draft.modelSelection ?? null,
578 selectedProject.id,
579 ) ?? flow.selectedModel;
580 const workspaceSelection = flow.resolveWorkspaceSelection(draft.workspaceSelection);
581 const workspaceMode = workspaceSelection.mode;
582 const selectedBranchName = workspaceSelection.branch;
583 const initialMessageText = draft.text.trim();
584​
585 if (
586 attachmentBlockReason !== null ||
587 !modelSelection ||
588 (initialMessageText.length === 0 && draft.attachments.length === 0) ||
589 flow.submitting ||
590 (workspaceMode === "worktree" && !selectedBranchName)
591 ) {
592 return null;
593 }
594 if (
595 environmentConnected &&
596 isModelSelectionUnavailable(
597 selectedEnvironmentServerConfig,
598 modelSelection,
599 selectedProject.id,
600 )
601 ) {
602 const { title, detail } = describeUnavailableModelSelection(
603 selectedEnvironmentServerConfig,
604 modelSelection,
605 selectedProject.id,
606 );
607 Dialog.alert(title, detail);
608 return null;
609 }
610 // Recovery may retain over-cap attachments; block send before uploading a turn the server would reject.
611 if (draft.attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
612 Dialog.alert(
613 "Too many attachments",
614 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
615 );
616 return null;
617 }
618​
619 const contextBlockReason = composerContextSendBlockReason(draft.context);
620 if (contextBlockReason) {
621 Dialog.alert("Too much context", contextBlockReason);
622 return null;
623 }
624 const strandedThread = threadContextsOutsideEnvironment({
625 text: draft.text,
626 records: draft.context?.records ?? [],
627 environmentId: selectedProject.environmentId,
628 })[0];
629 if (strandedThread) {
630 const owner =
631 flow.environments.find(
632 (environment) => environment.environmentId === strandedThread.environmentId,
633 )?.environmentLabel ?? "its machine";
634 Dialog.alert(
635 "Attached thread unavailable",
636 `"${strandedThread.title}" is on another machine. Switch back to ${owner} or remove it from the draft.`,
637 );
638 return null;
639 }
640​
641 const message = flow.buildPendingTaskMessage(creationMetadata, {
642 currentCheckoutBranch: queuesInsteadOfStarting ? null : flow.currentCheckoutBranchName,
643 });
644 if (!message) {
645 return null;
646 }
647 // Persist locally before clearing or leaving the draft; server setup runs on the thread.
648 flow.setSubmitting(true);
649 const queued = await settlePromise(() => enqueueThreadOutboxMessage(message));
650 flow.setSubmitting(false);
651 if (AsyncResult.isFailure(queued)) {
652 const error = squashAtomCommandFailure(queued);
653 Dialog.alert(
654 "Could not queue task",
655 error instanceof Error ? error.message : "The task could not be saved to the outbox.",
656 );
657 return null;
658 }
659 promptInputRef.current?.blur();
660 navigation.dispatch(
661 CommonActions.setParams(
662 submittedThreadParams(String(message.environmentId), String(message.threadId)),
663 ),
664 );
665 // The composer has moved to the submitted thread; a pick still converting
666 // would otherwise resurrect this draft.
667 abortComposerDraftOperations(draftKey);
668 const draftSnapshot = getComposerDraftSnapshot(draftKey);
669 // The queued message owns the attachments now, so the sweep is deferred
670 // until the write confirms it.
671 clearComposerDraftContent(draftKey, {
672 clearModelSelection: true,
673 clearWorkspaceSelection: true,
674 deferAttachmentCleanup: true,
675 });
676 scheduleUnusedComposerAttachmentCleanup(draftSnapshot.attachments);
677 return message.messageId;
678 }
679​
680 // Keep the current surface until the local draft selection is ready. Publishing
681 // an empty loading surface here flashes between two already-cached threads.
682 if (!selectedProject) return null;
683​
684 const setupBlockReason =
685 isIncomingShareReady && !isImportingShare
686 ? cloneBlocksStart
687 ? "Wait for the project clone to finish."
688 : flow.submitting
689 ? "Starting the thread…"
690 : flow.workspaceMode === "worktree" && (!flow.selectedBranchName || !flow.isGitRepoKnown)
691 ? "Choose a base branch before creating a worktree."
692 : null
693 : "Wait for shared content to finish importing.";
694 const chooseProject = () => {
695 if (isComposerInteractionLocked) {
696 return;
697 }
698 promptInputRef.current?.blur();
699 void KeyboardController.dismiss({ animated: true });
700 navigation.navigate("NewTaskProject", { incomingShareId: props.incomingShareId });
701 };
702 const openContextPicker = (routeName: "NewTaskBranch" | "NewTaskEnvironment") => {
703 if (isComposerInteractionLocked) {
704 return;
705 }
706 promptInputRef.current?.blur();
707 void KeyboardController.dismiss({ animated: true });
708 navigation.navigate(routeName);
709 };
710​
711 const environmentControl = (
712 <DraftEnvironmentControl
713 connectionState={connectionState}
714 label={selectedEnvironmentLabel}
715 machineKind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}
716 disabled={isComposerInteractionLocked}
717 onChooseEnvironment={() => openContextPicker("NewTaskEnvironment")}
718 />
719 );
720 const shareUnavailableNotice = isIncomingShareUnavailable ? (
721 <Text textRole="footnote" className="text-center text-foreground-muted">
722 The shared content is no longer in the inbox. You can continue editing this task draft.
723 </Text>
724 ) : null;
725 const hero = flow.isScratchDraft ? (
726 <View className="items-center gap-2 px-6" testID="new-task-hero">
727 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
728 What should we work on?
729 </Text>
730 <View className="flex-row flex-wrap items-center justify-center gap-x-1">
731 <ComposerInlineControl
732 accessibilityHint="Opens the project picker"
733 accessibilityLabel="No project"
734 chevronDirection="right"
735 disabled={isComposerInteractionLocked}
736 icon="folder"
737 label="No project"
738 onPress={chooseProject}
739 />
740 {environmentControl}
741 </View>
742 {shareUnavailableNotice}
743 </View>
744 ) : (
745 <View className="items-center gap-6 px-6" testID="new-task-hero">
746 <View className="w-full items-center gap-1.5">
747 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
748 What should we build
749 </Text>
750 <View className="max-w-full flex-row items-center justify-center">
751 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">in </Text>
752 <Pressable
753 accessibilityHint="Opens the project picker"
754 accessibilityLabel={selectedProjectLabel ?? selectedProject.title}
755 accessibilityRole="button"
756 disabled={isComposerInteractionLocked}
757 onPress={chooseProject}
758 className="min-w-0 max-w-[250px] border-b border-foreground-muted active:opacity-65"
759 >
760 <Text
761 className="text-2xl font-t3-medium tracking-tight text-foreground"
762 numberOfLines={1}
763 >
764 {selectedProjectLabel ?? selectedProject.title}
765 </Text>
766 </Pressable>
767 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">?</Text>
768 </View>
769 </View>
770​
771 {environmentControl}
772 {shareUnavailableNotice}
773 </View>
774 );
775 // The nested hero scroll view does not receive UIKit's automatic navigation inset in split columns.
776 const heroViewport = (headerInset: number, bottomInset: number, availableHeight: number) =>
777 availableHeight < 180 ? null : (
778 <NativeScrollEdgeEffectsContext
779 value={{ top: "hidden", bottom: "hidden", left: "hidden", right: "hidden" }}
780 >
781 <View
782 collapsable={false}
783 style={{
784 position: "absolute",
785 top: headerInset,
786 bottom: bottomInset,
787 left: 0,
788 right: 0,
789 overflow: "hidden",
790 }}
791 >
792 <ScrollView
793 alwaysBounceVertical={false}
794 className="flex-1"
795 contentInsetAdjustmentBehavior="never"
796 contentContainerClassName="grow items-center"
797 contentContainerStyle={{ paddingVertical: 24 }}
798 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
799 keyboardShouldPersistTaps="handled"
800 showsVerticalScrollIndicator={false}
801 style={{ flex: 1 }}
802 testID="new-task-hero-scroll"
803 >
804 <View style={{ flexGrow: 1 }} />
805 {hero}
806 <View style={{ flexGrow: 2 }} />
807 </ScrollView>
808 </View>
809 </NativeScrollEdgeEffectsContext>
810 );
811​
812 const workspaceControls = (
813 <View className="flex-row items-center gap-1 px-2">
814 <ComposerInlineControl
815 accessibilityHint={`Switches to ${flow.workspaceMode === "local" ? "a new worktree" : "the current checkout"}`}
816 accessibilityLabel={workspaceLabel}
817 disabled={isComposerInteractionLocked || !flow.isGitRepo}
818 renderIcon={(size) => (
819 <NewTaskWorkspaceIcon
820 workspaceMode={flow.workspaceMode}
821 worktreePath={flow.selectedWorktreePath}
822 size={size}
823 />
824 )}
825 label={workspaceLabel}
826 maxWidth="100%"
827 onPress={() => flow.setWorkspaceMode(flow.workspaceMode === "local" ? "worktree" : "local")}
828 showChevron={false}
829 />
830​
831 <View className="min-w-0 shrink">
832 <ComposerInlineControl
833 accessibilityLabel={`${flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}: ${selectedBranchLabel}`}
834 chevronDirection="right"
835 disabled={isComposerInteractionLocked || !flow.isGitRepo}
836 icon="arrow.triangle.branch"
837 label={showBranchLoading ? "Loading branches…" : selectedBranchLabel}
838 maxWidth="100%"
839 onPress={() => openContextPicker("NewTaskBranch")}
840 />
841 </View>
842 </View>
843 );
844​
845 if (!flow.selectedModel) {
846 return (
847 <ThreadScreenFallback
848 header={
849 <AppBar
850 title="New thread"
851 sidebar={false}
852 onBack={goBack}
853 options={{
854 ...threadHeaderAppearance(NATIVE_LIQUID_GLASS_SUPPORTED),
855 unstable_headerSubtitle: undefined,
856 unstable_headerRightItems: () => [],
857 unstable_headerToolbarItems: () => [],
858 }}
859 />
860 }
861 >
862 <View className="flex-1 justify-end gap-3 p-4">
863 {environmentControl}
864 <Text className="text-foreground-muted">
865 Your draft is saved on this device. Connect to an environment to choose its first model.
866 </Text>
867 <ComposerEditor
868 draftKey={flow.draftKey}
869 value={flow.prompt}
870 onChangeText={flow.setPrompt}
871 placeholder="Ask anything"
872 multiline
873 style={{ minHeight: 64 }}
874 />
875 </View>
876 </ThreadScreenFallback>
877 );
878 }
879 const thread = draftThreadShell({
880 environmentId: selectedProject.environmentId,
881 projectId: selectedProject.id,
882 threadId: ThreadId.make(creationMetadata.threadId),
883 modelSelection: flow.selectedModel,
884 runtimeMode: flow.runtimeMode,
885 interactionMode: flow.interactionMode,
886 branch: flow.selectedBranchName,
887 worktreePath: flow.selectedWorktreePath,
888 createdAt: creationMetadata.createdAt,
889 });
890 return (
891 <>
892 <ThreadScreenBinding
893 environmentId={selectedProject.environmentId}
894 header={
895 <DraftThreadHeader thread={thread} project={selectedProject} cwd={composerWorkspaceCwd} />
896 }
897 draftMode={{
898 content: heroViewport,
899 controls: (
900 <View className="pb-1">
901 {projectClone && projectClone.phase !== "done" && selectedProject ? (
902 <View className="px-1 pb-2">
903 <ProjectCloneBanner
904 clone={projectClone}
905 onCancel={() =>
906 void runCloneAction("Failed to cancel clone", () =>
907 cancelProjectClone({
908 environmentId: selectedProject.environmentId,
909 input: { projectId: selectedProject.id },
910 }),
911 )
912 }
913 onRetry={() =>
914 void runCloneAction("Failed to retry clone", () =>
915 retryProjectClone({
916 environmentId: selectedProject.environmentId,
917 input: { projectId: selectedProject.id },
918 }),
919 )
920 }
921 onRemove={() => void removeClonedProject()}
922 />
923 </View>
924 ) : null}
925 {flow.canChooseWorkspace ? workspaceControls : null}
926 </View>
927 ),
928 editorRef: promptInputRef,
929 sendBlockedReason: setupBlockReason,
930 interactionLocked: isComposerInteractionLocked,
931 }}
932 canOperateThread={canOperate}
933 selectedThread={thread}
934 selectedThreadDetailRef={null}
935 contentPresentation={{ kind: "ready" }}
936 screenTone={connectionTone(connectionState)}
937 connectionError={environmentRuntime?.connectionError ?? null}
938 environmentLabel={selectedEnvironmentLabel}
939 feedbackSubmissions={[]}
940 onDismissFeedback={() => {}}
941 selectedThreadFeed={[]}
942 activityRun={null}
943 activeWorkStartedAt={null}
944 isCompacting={false}
945 creationState={null}
946 activePendingApproval={null}
947 activePendingApprovals={[]}
948 respondingApprovalId={null}
949 activePendingUserInput={null}
950 activePendingUserInputDrafts={{}}
951 activePendingUserInputAnswers={null}
952 respondingUserInputId={null}
953 connectionStateLabel={connectionState}
954 activeThreadBusy={false}
955 canStopThread={false}
956 queuedRunEdit={null}
957 composerDraftKey={flow.draftKey}
958 followUpBehavior="queue"
959 canSteerActiveTurn={false}
960 isSavingQueuedEdit={false}
961 onCancelQueuedRunEdit={() => {}}
962 onRemoveQueuedEditAttachment={() => {}}
963 projectWorkspaceRoot={selectedProject.workspaceRoot}
964 threadCwd={composerWorkspaceCwd}
965 selectedThreadQueueCount={0}
966 queuedMessages={[]}
967 dispatchingMessageId={null}
968 serverConfig={selectedEnvironmentServerConfig}
969 usesAutomaticContentInsets
970 onOpenConnectionEditor={() => navigation.navigate("Connections")}
971 onChangeDraftMessage={flow.setPrompt}
972 onPickDraftMedia={handlePickMedia}
973 onPickDraftFiles={handlePickFiles}
974 onNativePasteImages={handleNativePasteImages}
975 onNativePasteText={handleNativePasteText}
976 onRemoveDraftImage={flow.removeAttachment}
977 onStopThread={() => {}}
978 onResumeQueue={null}
979 onSendMessage={handleStart}
980 onReconnectEnvironment={() => onReconnectEnvironment(selectedProject.environmentId)}
981 canSwitchThreadProvider
982 onUpdateThreadInteractionMode={flow.planModeEnabled ? flow.setInteractionMode : undefined}
983 onRespondToApproval={async () => {}}
984 onSelectUserInputOption={() => {}}
985 onChangeUserInputCustomAnswer={() => {}}
986 onSubmitUserInput={async () => {}}
987 onDismissUserInput={async () => {}}
988 />
989 </>
990 );