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

NewTaskDraftScreen.tsx

983 lines37.4 KB

1import { DraftEnvironmentControl } from "./DraftEnvironmentControl";
2import { NativeScrollEdgeEffectsContext } from "../../native/NativeScrollViewMarker";
3import { DraftThreadHeader } from "./DraftThreadHeader";
4import { useComposerAttachmentActions } from "../../state/use-composer-attachment-actions";
5import { useWorkspaceBackNavigation } from "../layout/workspace/useAndroidWorkspaceNavigation";
6import { submittedThreadParams } from "./thread-route-state";
7import { ThreadScreenBinding, ThreadScreenFallback } from "./ThreadScreenHost";
8import { draftThreadShell } from "./draft-thread-shell";
9import { useRememberThreadProject } from "./useRememberThreadProject";
10import { scopedProjectKey } from "../../lib/scopedEntities";
11import { connectionTone } from "../connection/connectionTone";
12import { AppBar } from "../../components/ui/AppBar";
13import { ThreadId } from "@t3tools/contracts";
14​
15import * as Dialog from "../../components/ui/Dialog";
16import { useAtomValue } from "@effect/atom-react";
17import * as Cause from "effect/Cause";
18import { AsyncResult } from "effect/reactivity";
19import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping";
20import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
21import {
22 CommonActions,
23 StackActions,
24 useIsFocused,
25 useNavigation,
26 usePreventRemove,
27 useRoute,
28} from "@react-navigation/native";
29import { useEffect, useRef, useState } from "react";
30import { Platform, Pressable, View } from "react-native";
31import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
32import { KeyboardController } from "react-native-keyboard-controller";
33​
34import {
35 AuthOrchestrationOperateScope,
36 DEFAULT_PROVIDER_INTERACTION_MODE,
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(
462 selectedProjectKey,
463 projects,
464 pickableProjectGroups(projectScopes),
465 {
466 incomingShareId: props.incomingShareId,
467 pickerClosed: initialPickerRef.current === "open" && isFocused,
468 },
469 );
470 if (selection.kind === "preserve") {
471 initialPickerRef.current = null;
472 return;
473 }
474 if (selection.kind === "select") {
475 setProject(selection.project);
476 return;
477 }
478 if (selection.kind === "dismiss") {
479 initialPickerRef.current = "dismissed";
480 goBack();
481 return;
482 }
483 // Open the first picker once; catalog updates must not push it again over a cancelled draft.
484 if (initialPickerRef.current !== null) {
485 return;
486 }
487 initialPickerRef.current = "open";
488 navigation.dispatch(CommonActions.navigate("NewTaskProject"));
489 }, [
490 goBack,
491 isFocused,
492 projectScopes,
493 projects,
494 flow.draftKey,
495 props.initialProjectRef,
496 props.incomingShareId,
497 props.draftId,
498 navigation,
499 selectedProject,
500 selectedProjectKey,
501 setProject,
502 ]);
503​
504 const { loadBranches } = flow;
505 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- requests the selected project's branch list from the server once per project
506 useEffect(() => {
507 if (!selectedProject) {
508 loadedBranchesProjectKeyRef.current = null;
509 return;
510 }
511 const projectKey = `${selectedProject.environmentId}:${selectedProject.id}`;
512 if (loadedBranchesProjectKeyRef.current === projectKey) {
513 return;
514 }
515 loadedBranchesProjectKeyRef.current = projectKey;
516 loadBranches();
517 }, [loadBranches, selectedProject]);
518​
519 const selectedEnvironmentLabel =
520 flow.environments.find(
521 (environment) => environment.environmentId === flow.selectedEnvironmentId,
522 )?.environmentLabel ?? "Environment";
523 const availableCurrentBranchName =
524 flow.availableBranches.find((branch) => branch.current)?.name ??
525 flow.availableBranches.find((branch) => branch.isDefault)?.name ??
526 null;
527 const selectedBranchName = resolveProjectThreadCreationBranch({
528 workspaceMode: flow.workspaceMode,
529 selectedBranch:
530 flow.selectedBranchName ??
531 (flow.workspaceMode === "worktree" ? availableCurrentBranchName : null),
532 currentCheckoutBranch: flow.currentCheckoutBranchName,
533 });
534 const selectedBranchLabel = resolveNewTaskBranchLabel({
535 branchName: selectedBranchName,
536 startFromOrigin: flow.startFromOrigin,
537 workspaceMode: flow.workspaceMode,
538 pullRequestReference: flow.pullRequestReference,
539 });
540 const workspaceLabel = resolveNewTaskWorkspaceLabel({
541 workspaceMode: flow.workspaceMode,
542 worktreePath: flow.selectedWorktreePath,
543 });
544 const showBranchLoading =
545 environmentConnected && flow.branchesLoading && flow.availableBranches.length === 0;
546​
547 const {
548 onPickDraftMedia: handlePickMedia,
549 onPickDraftFiles: handlePickFiles,
550 onNativePasteImages: handleNativePasteImages,
551 onNativePasteText: handleNativePasteText,
552 } = useComposerAttachmentActions({
553 draftKey: flow.draftKey,
554 serverConfig: selectedEnvironmentServerConfig,
555 locked: isComposerInteractionLocked,
556 });
557​
558 async function handleStart(): Promise<import("@t3tools/contracts").MessageId | null> {
559 const selectedProject = flow.selectedProject;
560 const draftKey = flow.draftKey;
561 if (
562 !selectedProject ||
563 !draftKey ||
564 cloneBlocksStart ||
565 !isIncomingShareReady ||
566 isImportingShare ||
567 isComposerInteractionLocked
568 ) {
569 return null;
570 }
571 if (
572 environmentConnected &&
573 !readEnvironmentScope(selectedProject.environmentId, AuthOrchestrationOperateScope)
574 ) {
575 return null;
576 }
577 const draft = getComposerDraftSnapshot(draftKey);
578 if (appAtomRegistry.get(composerContextImportsAtom)[draftKey]) return null;
579 const modelSelection =
580 resolveSelectableModelSelection(
581 selectedEnvironmentServerConfig,
582 draft.modelSelection ?? null,
583 selectedProject.id,
584 ) ?? flow.selectedModel;
585 const workspaceSelection = flow.resolveWorkspaceSelection(draft.workspaceSelection);
586 const workspaceMode = workspaceSelection.mode;
587 const selectedBranchName = workspaceSelection.branch;
588 const initialMessageText = draft.text.trim();
589​
590 if (
591 attachmentBlockReason !== null ||
592 !modelSelection ||
593 (initialMessageText.length === 0 && draft.attachments.length === 0) ||
594 flow.submitting ||
595 (workspaceMode === "worktree" && !selectedBranchName)
596 ) {
597 return null;
598 }
599 if (
600 environmentConnected &&
601 isModelSelectionUnavailable(
602 selectedEnvironmentServerConfig,
603 modelSelection,
604 selectedProject.id,
605 )
606 ) {
607 const { title, detail } = describeUnavailableModelSelection(
608 selectedEnvironmentServerConfig,
609 modelSelection,
610 selectedProject.id,
611 );
612 Dialog.alert(title, detail);
613 return null;
614 }
615 // Recovery may retain over-cap attachments; block send before uploading a turn the server would reject.
616 if (draft.attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
617 Dialog.alert(
618 "Too many attachments",
619 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
620 );
621 return null;
622 }
623​
624 const contextBlockReason = composerContextSendBlockReason(draft.context);
625 if (contextBlockReason) {
626 Dialog.alert("Too much context", contextBlockReason);
627 return null;
628 }
629 const strandedThread = threadContextsOutsideEnvironment({
630 text: draft.text,
631 records: draft.context?.records ?? [],
632 environmentId: selectedProject.environmentId,
633 linkedEnvironments: flow.linkedEnvironments,
634 })[0];
635 if (strandedThread) {
636 const owner =
637 flow.environments.find(
638 (environment) => environment.environmentId === strandedThread.environmentId,
639 )?.environmentLabel ?? "its machine";
640 Dialog.alert(
641 "Attached thread unavailable",
642 `"${strandedThread.title}" is on another machine. Switch back to ${owner} or remove it from the draft.`,
643 );
644 return null;
645 }
646​
647 const message = flow.buildPendingTaskMessage(creationMetadata, {
648 currentCheckoutBranch: queuesInsteadOfStarting ? null : flow.currentCheckoutBranchName,
649 });
650 if (!message) {
651 return null;
652 }
653 // Persist locally before clearing or leaving the draft; server setup runs on the thread.
654 flow.setSubmitting(true);
655 const queued = await settlePromise(() => enqueueThreadOutboxMessage(message));
656 flow.setSubmitting(false);
657 if (AsyncResult.isFailure(queued)) {
658 const error = squashAtomCommandFailure(queued);
659 Dialog.alert(
660 "Could not queue task",
661 error instanceof Error ? error.message : "The task could not be saved to the outbox.",
662 );
663 return null;
664 }
665 promptInputRef.current?.blur();
666 navigation.dispatch(
667 CommonActions.setParams(
668 submittedThreadParams(String(message.environmentId), String(message.threadId)),
669 ),
670 );
671 // The composer has moved to the submitted thread; a pick still converting
672 // would otherwise resurrect this draft.
673 abortComposerDraftOperations(draftKey);
674 const draftSnapshot = getComposerDraftSnapshot(draftKey);
675 // The queued message owns the attachments now, so the sweep is deferred
676 // until the write confirms it.
677 clearComposerDraftContent(draftKey, {
678 clearModelSelection: true,
679 clearWorkspaceSelection: true,
680 deferAttachmentCleanup: true,
681 });
682 scheduleUnusedComposerAttachmentCleanup(draftSnapshot.attachments);
683 return message.messageId;
684 }
685​
686 // Keep the current surface until the local draft selection is ready. Publishing
687 // an empty loading surface here flashes between two already-cached threads.
688 if (!selectedProject) return null;
689​
690 const setupBlockReason =
691 isIncomingShareReady && !isImportingShare
692 ? cloneBlocksStart
693 ? "Wait for the project clone to finish."
694 : flow.submitting
695 ? "Starting the thread…"
696 : flow.workspaceMode === "worktree" && (!flow.selectedBranchName || !flow.isGitRepoKnown)
697 ? "Choose a base branch before creating a worktree."
698 : null
699 : "Wait for shared content to finish importing.";
700 const chooseProject = () => {
701 if (isComposerInteractionLocked) {
702 return;
703 }
704 promptInputRef.current?.blur();
705 void KeyboardController.dismiss({ animated: true });
706 navigation.navigate("NewTaskProject", { incomingShareId: props.incomingShareId });
707 };
708 const openContextPicker = (routeName: "NewTaskBranch" | "NewTaskEnvironment") => {
709 if (isComposerInteractionLocked) {
710 return;
711 }
712 promptInputRef.current?.blur();
713 void KeyboardController.dismiss({ animated: true });
714 navigation.navigate(routeName);
715 };
716​
717 const environmentControl = (
718 <DraftEnvironmentControl
719 connectionState={connectionState}
720 label={selectedEnvironmentLabel}
721 machineKind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}
722 disabled={isComposerInteractionLocked}
723 onChooseEnvironment={() => openContextPicker("NewTaskEnvironment")}
724 />
725 );
726 const shareUnavailableNotice = isIncomingShareUnavailable ? (
727 <Text textRole="footnote" className="text-center text-foreground-muted">
728 The shared content is no longer in the inbox. You can continue editing this task draft.
729 </Text>
730 ) : null;
731 const hero = flow.isScratchDraft ? (
732 <View className="items-center gap-2 px-6" testID="new-task-hero">
733 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
734 What should we work on?
735 </Text>
736 <View className="flex-row flex-wrap items-center justify-center gap-x-1">
737 <ComposerInlineControl
738 accessibilityHint="Opens the project picker"
739 accessibilityLabel="No project"
740 chevronDirection="right"
741 disabled={isComposerInteractionLocked}
742 icon="folder"
743 label="No project"
744 onPress={chooseProject}
745 />
746 {environmentControl}
747 </View>
748 {shareUnavailableNotice}
749 </View>
750 ) : (
751 <View className="items-center gap-6 px-6" testID="new-task-hero">
752 <View className="w-full items-center gap-1.5">
753 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
754 What should we build
755 </Text>
756 <View className="max-w-full flex-row items-center justify-center">
757 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">in </Text>
758 <Pressable
759 accessibilityHint="Opens the project picker"
760 accessibilityLabel={selectedProjectLabel ?? selectedProject.title}
761 accessibilityRole="button"
762 disabled={isComposerInteractionLocked}
763 onPress={chooseProject}
764 className="min-w-0 max-w-[250px] border-b border-foreground-muted active:opacity-65"
765 >
766 <Text
767 className="text-2xl font-t3-medium tracking-tight text-foreground"
768 numberOfLines={1}
769 >
770 {selectedProjectLabel ?? selectedProject.title}
771 </Text>
772 </Pressable>
773 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">?</Text>
774 </View>
775 </View>
776​
777 {environmentControl}
778 {shareUnavailableNotice}
779 </View>
780 );
781 // The nested hero scroll view does not receive UIKit's automatic navigation inset in split columns.
782 const heroViewport = (headerInset: number, bottomInset: number, availableHeight: number) =>
783 availableHeight < 180 ? null : (
784 <NativeScrollEdgeEffectsContext
785 value={{ top: "hidden", bottom: "hidden", left: "hidden", right: "hidden" }}
786 >
787 <View
788 collapsable={false}
789 style={{
790 position: "absolute",
791 top: headerInset,
792 bottom: bottomInset,
793 left: 0,
794 right: 0,
795 overflow: "hidden",
796 }}
797 >
798 <ScrollView
799 alwaysBounceVertical={false}
800 className="flex-1"
801 contentInsetAdjustmentBehavior="never"
802 contentContainerClassName="grow items-center"
803 contentContainerStyle={{ paddingVertical: 24 }}
804 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
805 keyboardShouldPersistTaps="handled"
806 showsVerticalScrollIndicator={false}
807 style={{ flex: 1 }}
808 testID="new-task-hero-scroll"
809 >
810 <View style={{ flexGrow: 1 }} />
811 {hero}
812 <View style={{ flexGrow: 2 }} />
813 </ScrollView>
814 </View>
815 </NativeScrollEdgeEffectsContext>
816 );
817​
818 const workspaceControls = (
819 <View className="flex-row items-center gap-1 px-2">
820 <ComposerInlineControl
821 accessibilityHint={`Switches to ${flow.workspaceMode === "local" ? "a new worktree" : "the current checkout"}`}
822 accessibilityLabel={workspaceLabel}
823 disabled={isComposerInteractionLocked || !flow.isGitRepo}
824 renderIcon={(size) => (
825 <NewTaskWorkspaceIcon
826 workspaceMode={flow.workspaceMode}
827 worktreePath={flow.selectedWorktreePath}
828 size={size}
829 />
830 )}
831 label={workspaceLabel}
832 maxWidth="100%"
833 onPress={() => flow.setWorkspaceMode(flow.workspaceMode === "local" ? "worktree" : "local")}
834 showChevron={false}
835 />
836​
837 <View className="min-w-0 shrink">
838 <ComposerInlineControl
839 accessibilityLabel={`${flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}: ${selectedBranchLabel}`}
840 chevronDirection="right"
841 disabled={isComposerInteractionLocked || !flow.isGitRepo}
842 icon="arrow.triangle.branch"
843 label={showBranchLoading ? "Loading branches…" : selectedBranchLabel}
844 maxWidth="100%"
845 onPress={() => openContextPicker("NewTaskBranch")}
846 />
847 </View>
848 </View>
849 );
850​
851 if (!flow.selectedModel) {
852 return (
853 <ThreadScreenFallback header={<AppBar title="New thread" onBack={goBack} />}>
854 <View className="flex-1 justify-end gap-3 p-4">
855 {environmentControl}
856 <Text className="text-foreground-muted">
857 Your draft is saved on this device. Connect to an environment to choose its first model.
858 </Text>
859 <ComposerEditor
860 draftKey={flow.draftKey}
861 value={flow.prompt}
862 onChangeText={flow.setPrompt}
863 placeholder="Ask anything"
864 multiline
865 style={{ minHeight: 64 }}
866 />
867 </View>
868 </ThreadScreenFallback>
869 );
870 }
871 const thread = draftThreadShell({
872 environmentId: selectedProject.environmentId,
873 projectId: selectedProject.id,
874 threadId: ThreadId.make(creationMetadata.threadId),
875 modelSelection: flow.selectedModel,
876 runtimeMode: flow.runtimeMode,
877 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
878 branch: flow.selectedBranchName,
879 worktreePath: flow.selectedWorktreePath,
880 createdAt: creationMetadata.createdAt,
881 });
882 return (
883 <>
884 <ThreadScreenBinding
885 environmentId={selectedProject.environmentId}
886 header={
887 <DraftThreadHeader thread={thread} project={selectedProject} cwd={composerWorkspaceCwd} />
888 }
889 draftMode={{
890 content: heroViewport,
891 controls: (
892 <View className="pb-1">
893 {projectClone && projectClone.phase !== "done" && selectedProject ? (
894 <View className="px-1 pb-2">
895 <ProjectCloneBanner
896 clone={projectClone}
897 onCancel={() =>
898 void runCloneAction("Failed to cancel clone", () =>
899 cancelProjectClone({
900 environmentId: selectedProject.environmentId,
901 input: { projectId: selectedProject.id },
902 }),
903 )
904 }
905 onRetry={() =>
906 void runCloneAction("Failed to retry clone", () =>
907 retryProjectClone({
908 environmentId: selectedProject.environmentId,
909 input: { projectId: selectedProject.id },
910 }),
911 )
912 }
913 onRemove={() => void removeClonedProject()}
914 />
915 </View>
916 ) : null}
917 {flow.canChooseWorkspace ? workspaceControls : null}
918 </View>
919 ),
920 editorRef: promptInputRef,
921 sendBlockedReason: setupBlockReason,
922 interactionLocked: isComposerInteractionLocked,
923 }}
924 canOperateThread={canOperate}
925 selectedThread={thread}
926 selectedThreadDetailRef={null}
927 contentPresentation={{ kind: "ready" }}
928 screenTone={connectionTone(connectionState)}
929 connectionError={environmentRuntime?.connectionError ?? null}
930 environmentLabel={selectedEnvironmentLabel}
931 feedbackSubmissions={[]}
932 onDismissFeedback={() => {}}
933 selectedThreadFeed={[]}
934 activityRun={null}
935 activeWorkStartedAt={null}
936 isCompacting={false}
937 creationState={null}
938 activePendingApproval={null}
939 activePendingApprovals={[]}
940 respondingApprovalId={null}
941 activePendingUserInput={null}
942 activePendingUserInputDrafts={{}}
943 activePendingUserInputAnswers={null}
944 respondingUserInputId={null}
945 connectionStateLabel={connectionState}
946 activeThreadBusy={false}
947 canStopThread={false}
948 queuedRunEdit={null}
949 composerDraftKey={flow.draftKey}
950 followUpBehavior="queue"
951 canSteerActiveTurn={false}
952 isSavingQueuedEdit={false}
953 onCancelQueuedRunEdit={() => {}}
954 onRemoveQueuedEditAttachment={() => {}}
955 projectWorkspaceRoot={selectedProject.workspaceRoot}
956 threadCwd={composerWorkspaceCwd}
957 selectedThreadQueueCount={0}
958 queuedMessages={[]}
959 dispatchingMessageId={null}
960 serverConfig={selectedEnvironmentServerConfig}
961 usesAutomaticContentInsets
962 onOpenConnectionEditor={() => navigation.navigate("Connections")}
963 onChangeDraftMessage={flow.setPrompt}
964 onPickDraftMedia={handlePickMedia}
965 onPickDraftFiles={handlePickFiles}
966 onNativePasteImages={handleNativePasteImages}
967 onNativePasteText={handleNativePasteText}
968 onRemoveDraftImage={flow.removeAttachment}
969 onStopThread={() => {}}
970 onResumeQueue={null}
971 onSendMessage={handleStart}
972 offersSideChat={false}
973 onReconnectEnvironment={() => onReconnectEnvironment(selectedProject.environmentId)}
974 canSwitchThreadProvider
975 onRespondToApproval={async () => {}}
976 onSelectUserInputOption={() => {}}
977 onChangeUserInputCustomAnswer={() => {}}
978 onSubmitUserInput={async () => {}}
979 onDismissUserInput={async () => {}}
980 />
981 </>
982 );