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

NewTaskDraftScreen.tsx

992 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 linkedEnvironments: flow.linkedEnvironments,
629 })[0];
630 if (strandedThread) {
631 const owner =
632 flow.environments.find(
633 (environment) => environment.environmentId === strandedThread.environmentId,
634 )?.environmentLabel ?? "its machine";
635 Dialog.alert(
636 "Attached thread unavailable",
637 `"${strandedThread.title}" is on another machine. Switch back to ${owner} or remove it from the draft.`,
638 );
639 return null;
640 }
641​
642 const message = flow.buildPendingTaskMessage(creationMetadata, {
643 currentCheckoutBranch: queuesInsteadOfStarting ? null : flow.currentCheckoutBranchName,
644 });
645 if (!message) {
646 return null;
647 }
648 // Persist locally before clearing or leaving the draft; server setup runs on the thread.
649 flow.setSubmitting(true);
650 const queued = await settlePromise(() => enqueueThreadOutboxMessage(message));
651 flow.setSubmitting(false);
652 if (AsyncResult.isFailure(queued)) {
653 const error = squashAtomCommandFailure(queued);
654 Dialog.alert(
655 "Could not queue task",
656 error instanceof Error ? error.message : "The task could not be saved to the outbox.",
657 );
658 return null;
659 }
660 promptInputRef.current?.blur();
661 navigation.dispatch(
662 CommonActions.setParams(
663 submittedThreadParams(String(message.environmentId), String(message.threadId)),
664 ),
665 );
666 // The composer has moved to the submitted thread; a pick still converting
667 // would otherwise resurrect this draft.
668 abortComposerDraftOperations(draftKey);
669 const draftSnapshot = getComposerDraftSnapshot(draftKey);
670 // The queued message owns the attachments now, so the sweep is deferred
671 // until the write confirms it.
672 clearComposerDraftContent(draftKey, {
673 clearModelSelection: true,
674 clearWorkspaceSelection: true,
675 deferAttachmentCleanup: true,
676 });
677 scheduleUnusedComposerAttachmentCleanup(draftSnapshot.attachments);
678 return message.messageId;
679 }
680​
681 // Keep the current surface until the local draft selection is ready. Publishing
682 // an empty loading surface here flashes between two already-cached threads.
683 if (!selectedProject) return null;
684​
685 const setupBlockReason =
686 isIncomingShareReady && !isImportingShare
687 ? cloneBlocksStart
688 ? "Wait for the project clone to finish."
689 : flow.submitting
690 ? "Starting the thread…"
691 : flow.workspaceMode === "worktree" && (!flow.selectedBranchName || !flow.isGitRepoKnown)
692 ? "Choose a base branch before creating a worktree."
693 : null
694 : "Wait for shared content to finish importing.";
695 const chooseProject = () => {
696 if (isComposerInteractionLocked) {
697 return;
698 }
699 promptInputRef.current?.blur();
700 void KeyboardController.dismiss({ animated: true });
701 navigation.navigate("NewTaskProject", { incomingShareId: props.incomingShareId });
702 };
703 const openContextPicker = (routeName: "NewTaskBranch" | "NewTaskEnvironment") => {
704 if (isComposerInteractionLocked) {
705 return;
706 }
707 promptInputRef.current?.blur();
708 void KeyboardController.dismiss({ animated: true });
709 navigation.navigate(routeName);
710 };
711​
712 const environmentControl = (
713 <DraftEnvironmentControl
714 connectionState={connectionState}
715 label={selectedEnvironmentLabel}
716 machineKind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}
717 disabled={isComposerInteractionLocked}
718 onChooseEnvironment={() => openContextPicker("NewTaskEnvironment")}
719 />
720 );
721 const shareUnavailableNotice = isIncomingShareUnavailable ? (
722 <Text textRole="footnote" className="text-center text-foreground-muted">
723 The shared content is no longer in the inbox. You can continue editing this task draft.
724 </Text>
725 ) : null;
726 const hero = flow.isScratchDraft ? (
727 <View className="items-center gap-2 px-6" testID="new-task-hero">
728 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
729 What should we work on?
730 </Text>
731 <View className="flex-row flex-wrap items-center justify-center gap-x-1">
732 <ComposerInlineControl
733 accessibilityHint="Opens the project picker"
734 accessibilityLabel="No project"
735 chevronDirection="right"
736 disabled={isComposerInteractionLocked}
737 icon="folder"
738 label="No project"
739 onPress={chooseProject}
740 />
741 {environmentControl}
742 </View>
743 {shareUnavailableNotice}
744 </View>
745 ) : (
746 <View className="items-center gap-6 px-6" testID="new-task-hero">
747 <View className="w-full items-center gap-1.5">
748 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
749 What should we build
750 </Text>
751 <View className="max-w-full flex-row items-center justify-center">
752 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">in </Text>
753 <Pressable
754 accessibilityHint="Opens the project picker"
755 accessibilityLabel={selectedProjectLabel ?? selectedProject.title}
756 accessibilityRole="button"
757 disabled={isComposerInteractionLocked}
758 onPress={chooseProject}
759 className="min-w-0 max-w-[250px] border-b border-foreground-muted active:opacity-65"
760 >
761 <Text
762 className="text-2xl font-t3-medium tracking-tight text-foreground"
763 numberOfLines={1}
764 >
765 {selectedProjectLabel ?? selectedProject.title}
766 </Text>
767 </Pressable>
768 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">?</Text>
769 </View>
770 </View>
771​
772 {environmentControl}
773 {shareUnavailableNotice}
774 </View>
775 );
776 // The nested hero scroll view does not receive UIKit's automatic navigation inset in split columns.
777 const heroViewport = (headerInset: number, bottomInset: number, availableHeight: number) =>
778 availableHeight < 180 ? null : (
779 <NativeScrollEdgeEffectsContext
780 value={{ top: "hidden", bottom: "hidden", left: "hidden", right: "hidden" }}
781 >
782 <View
783 collapsable={false}
784 style={{
785 position: "absolute",
786 top: headerInset,
787 bottom: bottomInset,
788 left: 0,
789 right: 0,
790 overflow: "hidden",
791 }}
792 >
793 <ScrollView
794 alwaysBounceVertical={false}
795 className="flex-1"
796 contentInsetAdjustmentBehavior="never"
797 contentContainerClassName="grow items-center"
798 contentContainerStyle={{ paddingVertical: 24 }}
799 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
800 keyboardShouldPersistTaps="handled"
801 showsVerticalScrollIndicator={false}
802 style={{ flex: 1 }}
803 testID="new-task-hero-scroll"
804 >
805 <View style={{ flexGrow: 1 }} />
806 {hero}
807 <View style={{ flexGrow: 2 }} />
808 </ScrollView>
809 </View>
810 </NativeScrollEdgeEffectsContext>
811 );
812​
813 const workspaceControls = (
814 <View className="flex-row items-center gap-1 px-2">
815 <ComposerInlineControl
816 accessibilityHint={`Switches to ${flow.workspaceMode === "local" ? "a new worktree" : "the current checkout"}`}
817 accessibilityLabel={workspaceLabel}
818 disabled={isComposerInteractionLocked || !flow.isGitRepo}
819 renderIcon={(size) => (
820 <NewTaskWorkspaceIcon
821 workspaceMode={flow.workspaceMode}
822 worktreePath={flow.selectedWorktreePath}
823 size={size}
824 />
825 )}
826 label={workspaceLabel}
827 maxWidth="100%"
828 onPress={() => flow.setWorkspaceMode(flow.workspaceMode === "local" ? "worktree" : "local")}
829 showChevron={false}
830 />
831​
832 <View className="min-w-0 shrink">
833 <ComposerInlineControl
834 accessibilityLabel={`${flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}: ${selectedBranchLabel}`}
835 chevronDirection="right"
836 disabled={isComposerInteractionLocked || !flow.isGitRepo}
837 icon="arrow.triangle.branch"
838 label={showBranchLoading ? "Loading branches…" : selectedBranchLabel}
839 maxWidth="100%"
840 onPress={() => openContextPicker("NewTaskBranch")}
841 />
842 </View>
843 </View>
844 );
845​
846 if (!flow.selectedModel) {
847 return (
848 <ThreadScreenFallback
849 header={
850 <AppBar
851 title="New thread"
852 sidebar={false}
853 onBack={goBack}
854 options={{
855 ...threadHeaderAppearance(NATIVE_LIQUID_GLASS_SUPPORTED),
856 unstable_headerSubtitle: undefined,
857 unstable_headerRightItems: () => [],
858 unstable_headerToolbarItems: () => [],
859 }}
860 />
861 }
862 >
863 <View className="flex-1 justify-end gap-3 p-4">
864 {environmentControl}
865 <Text className="text-foreground-muted">
866 Your draft is saved on this device. Connect to an environment to choose its first model.
867 </Text>
868 <ComposerEditor
869 draftKey={flow.draftKey}
870 value={flow.prompt}
871 onChangeText={flow.setPrompt}
872 placeholder="Ask anything"
873 multiline
874 style={{ minHeight: 64 }}
875 />
876 </View>
877 </ThreadScreenFallback>
878 );
879 }
880 const thread = draftThreadShell({
881 environmentId: selectedProject.environmentId,
882 projectId: selectedProject.id,
883 threadId: ThreadId.make(creationMetadata.threadId),
884 modelSelection: flow.selectedModel,
885 runtimeMode: flow.runtimeMode,
886 interactionMode: flow.interactionMode,
887 branch: flow.selectedBranchName,
888 worktreePath: flow.selectedWorktreePath,
889 createdAt: creationMetadata.createdAt,
890 });
891 return (
892 <>
893 <ThreadScreenBinding
894 environmentId={selectedProject.environmentId}
895 header={
896 <DraftThreadHeader thread={thread} project={selectedProject} cwd={composerWorkspaceCwd} />
897 }
898 draftMode={{
899 content: heroViewport,
900 controls: (
901 <View className="pb-1">
902 {projectClone && projectClone.phase !== "done" && selectedProject ? (
903 <View className="px-1 pb-2">
904 <ProjectCloneBanner
905 clone={projectClone}
906 onCancel={() =>
907 void runCloneAction("Failed to cancel clone", () =>
908 cancelProjectClone({
909 environmentId: selectedProject.environmentId,
910 input: { projectId: selectedProject.id },
911 }),
912 )
913 }
914 onRetry={() =>
915 void runCloneAction("Failed to retry clone", () =>
916 retryProjectClone({
917 environmentId: selectedProject.environmentId,
918 input: { projectId: selectedProject.id },
919 }),
920 )
921 }
922 onRemove={() => void removeClonedProject()}
923 />
924 </View>
925 ) : null}
926 {flow.canChooseWorkspace ? workspaceControls : null}
927 </View>
928 ),
929 editorRef: promptInputRef,
930 sendBlockedReason: setupBlockReason,
931 interactionLocked: isComposerInteractionLocked,
932 }}
933 canOperateThread={canOperate}
934 selectedThread={thread}
935 selectedThreadDetailRef={null}
936 contentPresentation={{ kind: "ready" }}
937 screenTone={connectionTone(connectionState)}
938 connectionError={environmentRuntime?.connectionError ?? null}
939 environmentLabel={selectedEnvironmentLabel}
940 feedbackSubmissions={[]}
941 onDismissFeedback={() => {}}
942 selectedThreadFeed={[]}
943 activityRun={null}
944 activeWorkStartedAt={null}
945 isCompacting={false}
946 creationState={null}
947 activePendingApproval={null}
948 activePendingApprovals={[]}
949 respondingApprovalId={null}
950 activePendingUserInput={null}
951 activePendingUserInputDrafts={{}}
952 activePendingUserInputAnswers={null}
953 respondingUserInputId={null}
954 connectionStateLabel={connectionState}
955 activeThreadBusy={false}
956 canStopThread={false}
957 queuedRunEdit={null}
958 composerDraftKey={flow.draftKey}
959 followUpBehavior="queue"
960 canSteerActiveTurn={false}
961 isSavingQueuedEdit={false}
962 onCancelQueuedRunEdit={() => {}}
963 onRemoveQueuedEditAttachment={() => {}}
964 projectWorkspaceRoot={selectedProject.workspaceRoot}
965 threadCwd={composerWorkspaceCwd}
966 selectedThreadQueueCount={0}
967 queuedMessages={[]}
968 dispatchingMessageId={null}
969 serverConfig={selectedEnvironmentServerConfig}
970 usesAutomaticContentInsets
971 onOpenConnectionEditor={() => navigation.navigate("Connections")}
972 onChangeDraftMessage={flow.setPrompt}
973 onPickDraftMedia={handlePickMedia}
974 onPickDraftFiles={handlePickFiles}
975 onNativePasteImages={handleNativePasteImages}
976 onNativePasteText={handleNativePasteText}
977 onRemoveDraftImage={flow.removeAttachment}
978 onStopThread={() => {}}
979 onResumeQueue={null}
980 onSendMessage={handleStart}
981 onReconnectEnvironment={() => onReconnectEnvironment(selectedProject.environmentId)}
982 canSwitchThreadProvider
983 onUpdateThreadInteractionMode={flow.planModeEnabled ? flow.setInteractionMode : undefined}
984 onRespondToApproval={async () => {}}
985 onSelectUserInputOption={() => {}}
986 onChangeUserInputCustomAnswer={() => {}}
987 onSubmitUserInput={async () => {}}
988 onDismissUserInput={async () => {}}
989 />
990 </>
991 );