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

NewTaskDraftScreen.tsx

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