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

NewTaskDraftScreen.tsx

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