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

NewTaskDraftScreen.tsx

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