Open History to see the last commit
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 { 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 { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
20import {
21 CommonActions,
22 StackActions,
23 useNavigation,
24 usePreventRemove,
25} from "@react-navigation/native";
26import { useEffect, useEffectEvent, useRef, useState } from "react";
27import { Platform, Pressable, View } from "react-native";
28import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
29import { KeyboardController } from "react-native-keyboard-controller";
30
31import {
32 AuthOrchestrationOperateScope,
33 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
34 resolveEnvironmentMachineKind,
35} from "@t3tools/contracts";
36
37import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
38import { composerContextImportsAtom } from "../../state/use-composer-drafts";
39import { abortComposerDraftOperations } from "../../state/composerDraftOperations";
40import { composerContextSendBlockReason } from "../../lib/composerContext";
41import { ComposerInlineControl } from "../../components/ComposerToolbar";
42
43import {
44 composerAttachmentUploadBlockReason,
45 composerAttachmentsStillUploading,
46 composerAttachmentUploadsAtom,
47} from "../../state/composer-attachment-uploads";
48
49import { SymbolView } from "../../components/ui/AppSymbol";
50import { AppText as Text } from "../../components/ui/AppText";
51import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences";
52
53import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
54
55import {
56 clearComposerDraftContent,
57 getComposerDraftSnapshot,
58 mergeComposerDraftContent,
59 restoreComposerDraftSnapshot,
60 updateComposerDraftSettings,
61 scheduleUnusedComposerAttachmentCleanup,
62 type ComposerDraft,
63 waitForComposerDraftsLoaded,
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 { useIncomingShare } from "../sharing/IncomingShareProvider";
93import { selectIncomingShareAttachmentsForServer } from "../sharing/incoming-share-model";
94import { appAtomRegistry } from "../../state/atom-registry";
95import { serverEnvironment } from "../../state/server";
96
97import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
98
99function NewTaskWorkspaceIcon(props: {
100 readonly workspaceMode: "local" | "worktree";
101 readonly worktreePath: string | null;
102 readonly size: number;
103}) {
104 if (props.workspaceMode === "local" && props.worktreePath === null) {
105 return (
106 <SymbolView
107 name="folder"
108 size={props.size}
109 tintColorClassName="accent-icon-muted"
110 type="monochrome"
111 />
112 );
113 }
114
115 const boxSize = (14 * props.size) / 16;
116 return (
117 <View
118 className="size-4"
119 style={Platform.OS === "android" ? { width: boxSize, height: boxSize } : undefined}
120 >
121 <SymbolView
122 name="folder"
123 size={props.size}
124 tintColorClassName="accent-icon-muted"
125 type="monochrome"
126 />
127 <View
128 className="absolute -right-1 -bottom-1"
129 style={
130 Platform.OS === "android" ? { right: -boxSize / 4, bottom: -boxSize / 4 } : undefined
131 }
132 >
133 <SymbolView
134 name="arrow.triangle.branch"
135 size={Math.round((9 * props.size) / 16)}
136 tintColorClassName="accent-icon-muted"
137 type="monochrome"
138 />
139 </View>
140 </View>
141 );
142}
143
144export function NewTaskDraftScreen(props: {
145 readonly initialProjectRef?: {
146 readonly environmentId?: string;
147 readonly projectId?: string;
148 readonly branch?: string | null;
149 readonly worktreePath?: string | null;
150 readonly cloning?: boolean;
151 };
152 readonly draftId?: string;
153 readonly incomingShareId?: string;
154}) {
155 const [creationMetadata] = useState(makeTurnCommandMetadata);
156 const projects = useProjects();
157 const flow = useNewTaskFlow();
158 const navigation = useNavigation();
159 const goBack = useWorkspaceBackNavigation("threads");
160 const {
161 consumeShare,
162 getShare,
163 isLoading: isIncomingShareInboxLoading,
164 releaseShareReservation,
165 reserveShare,
166 } = useIncomingShare();
167 const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
168 const selectedProjectLabel = (() => {
169 if (!selectedProject) return null;
170 const scope = projectScopes.find((candidate) =>
171 candidate.projectRefs.some(
172 (ref) =>
173 ref.environmentId === selectedProject.environmentId &&
174 ref.projectId === selectedProject.id,
175 ),
176 );
177 return scope?.title ?? selectedProject.title;
178 })();
179 const { onReconnectEnvironment } = useRemoteConnections();
180 const environmentRuntime = useRemoteEnvironmentRuntime(selectedProject?.environmentId ?? null);
181 const connectionState = environmentRuntime?.connectionState ?? "offline";
182 const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
183 selectedProject?.environmentId ?? null,
184 );
185 const environmentConnected = connectionState === "connected";
186 const canOperate = useEnvironmentScope(
187 selectedProject?.environmentId ?? null,
188 AuthOrchestrationOperateScope,
189 );
190 const projectCloneState = useProjectClone(
191 selectedProject
192 ? { environmentId: selectedProject.environmentId, projectId: selectedProject.id }
193 : null,
194 );
195 const projectClone = projectCloneState === "pending" ? null : projectCloneState;
196 const awaitingKnownClone =
197 projectCloneState === "pending" &&
198 props.initialProjectRef?.cloning === true &&
199 selectedProject !== null &&
200 selectedProject.id === props.initialProjectRef.projectId &&
201 selectedProject.environmentId === props.initialProjectRef.environmentId;
202 const cloneBlocksStart =
203 awaitingKnownClone || (projectClone !== null && projectClone.phase !== "done");
204 const cancelProjectClone = useAtomCommand(sourceControlEnvironment.cancelProjectClone, {
205 reportFailure: false,
206 });
207 const retryProjectClone = useAtomCommand(sourceControlEnvironment.retryProjectClone, {
208 reportFailure: false,
209 });
210 const runCloneAction = async (
211 title: string,
212 action: () => Promise<AsyncResult.AsyncResult<unknown, unknown>>,
213 ) => {
214 const result = await action();
215 if (AsyncResult.isFailure(result)) {
216 const error = Cause.squash(result.cause);
217 Dialog.alert(title, error instanceof Error ? error.message : "An error occurred.");
218 }
219 };
220 const deleteProject = useAtomCommand(projectEnvironment.delete, { reportFailure: false });
221 const selectedProjectRef = useRef(selectedProject);
222 useEffect(() => {
223 selectedProjectRef.current = selectedProject;
224 }, [selectedProject]);
225 const removeClonedProject = async () => {
226 if (!selectedProject) return;
227 const removed = selectedProject;
228 const result = await deleteProject({
229 environmentId: removed.environmentId,
230 input: { projectId: removed.id },
231 });
232 if (AsyncResult.isFailure(result)) {
233 const error = Cause.squash(result.cause);
234 Dialog.alert(
235 "Failed to remove project",
236 error instanceof Error ? error.message : "An error occurred.",
237 );
238 return;
239 }
240 const current = selectedProjectRef.current;
241 if (current?.id === removed.id && current.environmentId === removed.environmentId) {
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 [importingShareKey, setImportingShareKey] = useState<string | null>(null);
268 const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);
269 const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);
270 const [isReturningToProjectPicker, setIsReturningToProjectPicker] = useState(false);
271 const [shareImportAttempt, setShareImportAttempt] = useState(0);
272 const startedShareImportKeyRef = useRef<string | null>(null);
273 const cancellingShareImportKeyRef = useRef<string | null>(null);
274 const shareImportDraftBackupRef = useRef(new Map<string, ComposerDraft>());
275 const activeShareImportTokenRef = useRef<symbol | null>(null);
276 const shareImportMountedRef = useRef(true);
277 // The share import resumes after awaits; this reads the screen's current
278 // draft and share at that point without re-running the import effect.
279 const isCurrentShareImport = useEffectEvent(
280 (draftKey: string, shareId: string) =>
281 flow.draftKey === draftKey && props.incomingShareId === shareId,
282 );
283 const isImportingShare = importingShareKey !== null;
284 const alertedUnavailableIncomingShareIdRef = useRef<string | null>(null);
285 // Remember consumed shares locally: send clears the receipt before navigation and can trigger a missing-content render.
286 const [consumedIncomingShareId, setConsumedIncomingShareId] = useState<string | null>(null);
287 const incomingShare = props.incomingShareId ? getShare(props.incomingShareId) : null;
288 const requestedInitialProjectAvailable = Boolean(
289 props.initialProjectRef?.environmentId &&
290 props.initialProjectRef.projectId &&
291 projects.some(
292 (project) =>
293 project.environmentId === props.initialProjectRef?.environmentId &&
294 project.id === props.initialProjectRef?.projectId,
295 ),
296 );
297 const isProjectPickerReturnActive =
298 isReturningToProjectPicker && !requestedInitialProjectAvailable;
299 const isIncomingShareAwaitingServerConfig = Boolean(
300 incomingShare?.attachments.some((attachment) => attachment.type === "file") &&
301 selectedEnvironmentServerConfig === null,
302 );
303 const isIncomingShareTransferPending = Boolean(
304 incomingShare &&
305 cancelledIncomingShareId !== props.incomingShareId &&
306 !isIncomingShareAwaitingServerConfig,
307 );
308 const contextImports = useAtomValue(composerContextImportsAtom);
309 const isImportingContext = flow.draftKey ? contextImports[flow.draftKey] === true : false;
310 const isComposerInteractionLocked =
311 isIncomingShareTransferPending || flow.submitting || isImportingContext;
312 const { environments, selectedEnvironmentId, switchEnvironment, switchingToEnvironmentId } = flow;
313 const cycleEnvironment = () => {
314 if (isComposerInteractionLocked) return true;
315 const next = nextEnvironmentId(environments, switchingToEnvironmentId ?? selectedEnvironmentId);
316 if (next !== null) void switchEnvironment(next);
317 return true;
318 };
319 const cycleEnvironmentCommands = environments.length > 1 ? (["cycleHost"] as const) : [];
320 useHardwareKeyboardCommand(cycleEnvironmentCommands, cycleEnvironment);
321 const composerWorkspaceCwd =
322 (flow.workspaceMode === "worktree"
323 ? selectedProject?.workspaceRoot
324 : (flow.selectedWorktreePath ?? selectedProject?.workspaceRoot)) || null;
325 const preventRemove =
326 (isIncomingShareTransferPending && !isProjectPickerReturnActive) ||
327 isCancellingShareImport ||
328 flow.submitting;
329 usePreventRemove(preventRemove, () => undefined);
330 const hasImportedIncomingShare = Boolean(
331 props.incomingShareId &&
332 (consumedIncomingShareId === props.incomingShareId ||
333 (flow.draftKey &&
334 getComposerDraftSnapshot(flow.draftKey).importedShareIds?.includes(props.incomingShareId))),
335 );
336 const isIncomingShareUnavailable = Boolean(
337 props.incomingShareId &&
338 !isIncomingShareInboxLoading &&
339 !incomingShare &&
340 !hasImportedIncomingShare,
341 );
342 const isIncomingShareReady =
343 !props.incomingShareId ||
344 (hasImportedIncomingShare && !incomingShare) ||
345 isIncomingShareUnavailable;
346 const appliedInitialProjectKeyRef = useRef<string | null>(null);
347 useEffect(() => {
348 if (cancelledIncomingShareId === props.incomingShareId) {
349 navigation.goBack();
350 }
351 }, [cancelledIncomingShareId, navigation, props.incomingShareId]);
352 useEffect(() => {
353 if (!isReturningToProjectPicker) {
354 return;
355 }
356 if (requestedInitialProjectAvailable) {
357 // oxlint-disable-next-line react/set-state-in-effect -- Ends the return-to-picker flow once the requested project arrives from the catalog.
358 setIsReturningToProjectPicker(false);
359 return;
360 }
361 // Wait for usePreventRemove to disable before replacing, or the transfer guard swallows the fallback.
362 const frame = requestAnimationFrame(() => {
363 navigation.dispatch(
364 StackActions.replace("NewTaskProject", { incomingShareId: props.incomingShareId }),
365 );
366 });
367 return () => cancelAnimationFrame(frame);
368 }, [
369 isReturningToProjectPicker,
370 navigation,
371 props.incomingShareId,
372 requestedInitialProjectAvailable,
373 ]);
374 useEffect(() => {
375 if (!shareImportMountedRef.current) {
376 startedShareImportKeyRef.current = null;
377 }
378 shareImportMountedRef.current = true;
379 return () => {
380 appliedInitialProjectKeyRef.current = null;
381 shareImportMountedRef.current = false;
382 activeShareImportTokenRef.current = null;
383 cancellingShareImportKeyRef.current = null;
384 };
385 }, []);
386
387 const { openDraft } = flow;
388 // Cold launches load drafts and projects separately; wait for hydration and retry while shells load.
389 const attemptedDraftIdRef = useRef<string | null>(null);
390 useEffect(() => {
391 if (!props.draftId) {
392 return;
393 }
394 const draftId = props.draftId;
395 if (attemptedDraftIdRef.current === draftId) {
396 return;
397 }
398 let cancelled = false;
399 void waitForComposerDraftsLoaded().then(() => {
400 if (cancelled || attemptedDraftIdRef.current === draftId) {
401 return;
402 }
403 if (openDraft(draftId)) {
404 attemptedDraftIdRef.current = draftId;
405 return;
406 }
407 if (getComposerDraftSnapshot(draftId).project !== undefined && projects.length === 0) {
408 return;
409 }
410 attemptedDraftIdRef.current = draftId;
411 navigation.dispatch(CommonActions.navigate("NewTaskProject"));
412 });
413 return () => {
414 cancelled = true;
415 };
416 }, [navigation, openDraft, projects, props.draftId]);
417
418 const lastInitialProjectRefRef = useRef(props.initialProjectRef);
419
420 useEffect(() => {
421 if (props.draftId) {
422 return;
423 }
424 if (lastInitialProjectRefRef.current !== props.initialProjectRef) {
425 lastInitialProjectRefRef.current = props.initialProjectRef;
426 appliedInitialProjectKeyRef.current = null;
427 }
428 const initialEnvironmentId = props.initialProjectRef?.environmentId;
429 const initialProjectId = props.initialProjectRef?.projectId;
430 if (initialEnvironmentId && initialProjectId) {
431 const directProject =
432 projects.find(
433 (project) =>
434 project.environmentId === initialEnvironmentId && project.id === initialProjectId,
435 ) ?? null;
436
437 if (directProject) {
438 // Apply the route project once or picker changes would immediately revert.
439 const directProjectKey = `${directProject.environmentId}:${directProject.id}`;
440 if (appliedInitialProjectKeyRef.current === directProjectKey) {
441 return;
442 }
443 if (props.initialProjectRef?.branch) {
444 if (
445 selectedProject?.environmentId !== directProject.environmentId ||
446 selectedProject.id !== directProject.id
447 ) {
448 setProject(directProject);
449 return;
450 }
451 if (!flow.draftKey) return;
452 // Checkout completed before mount; local mode reuses it while worktree mode would create another.
453 updateComposerDraftSettings(flow.draftKey, {
454 workspaceSelection: {
455 mode: "local",
456 branch: props.initialProjectRef.branch,
457 worktreePath: props.initialProjectRef.worktreePath ?? null,
458 startFromOrigin: false,
459 },
460 });
461 }
462 appliedInitialProjectKeyRef.current = directProjectKey;
463 if (
464 selectedProject?.environmentId === directProject.environmentId &&
465 selectedProject.id === directProject.id
466 ) {
467 return;
468 }
469 setProject(directProject);
470 return;
471 }
472
473 if (projects.length > 0) {
474 // oxlint-disable-next-line react/set-state-in-effect -- Route-driven project resolution starts the return-to-picker flow when no project matches.
475 setIsReturningToProjectPicker(true);
476 }
477 return;
478 }
479
480 const selection = resolveDraftProjectSelection(selectedProjectKey, projects, projectScopes);
481 if (selection.kind === "preserve") {
482 return;
483 }
484 if (selection.kind === "select") {
485 setProject(selection.project);
486 return;
487 }
488
489 navigation.dispatch(CommonActions.navigate("NewTaskProject"));
490 }, [
491 projectScopes,
492 projects,
493 flow.draftKey,
494 props.initialProjectRef,
495 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Opening a draft from a share or draft id re-resolves its project.
496 props.incomingShareId,
497 props.draftId,
498 navigation,
499 selectedProject,
500 selectedProjectKey,
501 setProject,
502 ]);
503
504 const { loadBranches } = flow;
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 useEffect(() => {
519 const shareId = props.incomingShareId;
520 const draftKey = flow.draftKey;
521 const destinationProject = selectedProject;
522 const initialEnvironmentId = props.initialProjectRef?.environmentId;
523 const initialProjectId = props.initialProjectRef?.projectId;
524 const selectedProjectMatchesRoute =
525 !initialEnvironmentId ||
526 !initialProjectId ||
527 (destinationProject?.environmentId === initialEnvironmentId &&
528 destinationProject.id === initialProjectId);
529 if (
530 !shareId ||
531 !draftKey ||
532 !destinationProject ||
533 !selectedProjectMatchesRoute ||
534 cancelledIncomingShareId === shareId
535 ) {
536 return;
537 }
538 const importKey = `${shareId}:${draftKey}`;
539 if (
540 startedShareImportKeyRef.current === importKey ||
541 cancellingShareImportKeyRef.current === importKey
542 ) {
543 return;
544 }
545
546 if (!incomingShare) {
547 if (isIncomingShareUnavailable && alertedUnavailableIncomingShareIdRef.current !== shareId) {
548 alertedUnavailableIncomingShareIdRef.current = shareId;
549 Dialog.alert(
550 "Shared content unavailable",
551 "The shared content is no longer in the inbox. You can continue editing this task draft.",
552 );
553 }
554 return;
555 }
556
557 if (
558 incomingShare.attachments.some((attachment) => attachment.type === "file") &&
559 selectedEnvironmentServerConfig === null
560 ) {
561 return;
562 }
563
564 if (alertedUnavailableIncomingShareIdRef.current === shareId) {
565 alertedUnavailableIncomingShareIdRef.current = null;
566 }
567 startedShareImportKeyRef.current = importKey;
568 const draftBackup =
569 shareImportDraftBackupRef.current.get(importKey) ?? getComposerDraftSnapshot(draftKey);
570 shareImportDraftBackupRef.current.set(importKey, draftBackup);
571 const importToken = Symbol(importKey);
572 let didReserveShare = false;
573 let didConsumeShare = false;
574 let needsDraftRestore = false;
575 activeShareImportTokenRef.current = importToken;
576 // oxlint-disable-next-line react/set-state-in-effect -- Publishes the share import started by this effect before its async work runs.
577 setImportingShareKey(importKey);
578 void (async () => {
579 await reserveShare(shareId, {
580 environmentId: String(destinationProject.environmentId),
581 projectId: String(destinationProject.id),
582 });
583 didReserveShare = true;
584 if (
585 !shareImportMountedRef.current ||
586 activeShareImportTokenRef.current !== importToken ||
587 !isCurrentShareImport(draftKey, shareId)
588 ) {
589 return;
590 }
591 const selectedAttachments = selectIncomingShareAttachmentsForServer({
592 attachments: incomingShare.attachments,
593 serverConfig: appAtomRegistry.get(
594 serverEnvironment.configValueAtom(destinationProject.environmentId),
595 ),
596 });
597 if (selectedAttachments.status === "pending") {
598 throw new Error("Server attachment support is still loading.");
599 }
600 needsDraftRestore = true;
601 const { skippedAttachmentCount } = await mergeComposerDraftContent(draftKey, {
602 text: incomingShare.text,
603 attachments: selectedAttachments.attachments,
604 sourceShareId: shareId,
605 });
606 if (
607 !shareImportMountedRef.current ||
608 activeShareImportTokenRef.current !== importToken ||
609 !isCurrentShareImport(draftKey, shareId)
610 ) {
611 // Durable reservations resume interrupted transfers only in this project, avoiding duplicate draft copies.
612 return;
613 }
614 await consumeShare(shareId);
615 didConsumeShare = true;
616 setConsumedIncomingShareId(shareId);
617 // Release skipped files after consumption even on unmount; sweeping re-checks new owners.
618 const retainedAttachmentIds = new Set(
619 getComposerDraftSnapshot(draftKey).attachments.map((attachment) => attachment.id),
620 );
621 scheduleUnusedComposerAttachmentCleanup(
622 incomingShare.attachments.filter((attachment) => !retainedAttachmentIds.has(attachment.id)),
623 );
624 if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {
625 return;
626 }
627 const warnings = [...incomingShare.warnings, ...selectedAttachments.warnings];
628 if (skippedAttachmentCount > 0) {
629 warnings.push(
630 `${skippedAttachmentCount} shared file${skippedAttachmentCount === 1 ? " was" : "s were"} skipped because this draft reached the attachment limit.`,
631 );
632 }
633 if (warnings.length > 0) {
634 Dialog.alert("Some shared content was skipped", warnings.join("\n"));
635 }
636 shareImportDraftBackupRef.current.delete(importKey);
637 })()
638 .catch((error) => {
639 if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {
640 return;
641 }
642 Dialog.alert(
643 "Could not import shared content",
644 error instanceof Error ? error.message : "The shared content could not be saved.",
645 [
646 {
647 text: "Cancel import",
648 style: "cancel",
649 onPress: () => {
650 const cancelImport = async (): Promise<void> => {
651 if (!shareImportMountedRef.current) {
652 return;
653 }
654 // Latch before restoring: atom publication can re-run import before React commits cancellation.
655 cancellingShareImportKeyRef.current = importKey;
656 setIsCancellingShareImport(true);
657 try {
658 if (needsDraftRestore) {
659 // Sweep restored attachments only after inbox consumption; unconsumed inbox entries still own them.
660 const mergedAttachments = getComposerDraftSnapshot(draftKey).attachments;
661 await restoreComposerDraftSnapshot(draftKey, draftBackup);
662 needsDraftRestore = false;
663 if (didConsumeShare) {
664 scheduleUnusedComposerAttachmentCleanup(mergedAttachments);
665 }
666 }
667 if (didReserveShare) {
668 await releaseShareReservation(shareId, {
669 environmentId: String(destinationProject.environmentId),
670 projectId: String(destinationProject.id),
671 });
672 }
673 shareImportDraftBackupRef.current.delete(importKey);
674 if (shareImportMountedRef.current) {
675 setIsCancellingShareImport(false);
676 setCancelledIncomingShareId(shareId);
677 }
678 } catch (cancelError) {
679 if (!shareImportMountedRef.current) {
680 return;
681 }
682 Dialog.alert(
683 "Could not cancel import",
684 cancelError instanceof Error
685 ? cancelError.message
686 : "The shared content could not be restored safely.",
687 [
688 {
689 text: "Retry import",
690 onPress: () => {
691 cancellingShareImportKeyRef.current = null;
692 setIsCancellingShareImport(false);
693 setShareImportAttempt((attempt) => attempt + 1);
694 },
695 },
696 {
697 text: "Retry cancel",
698 onPress: () => void cancelImport(),
699 },
700 ],
701 { cancelable: false },
702 );
703 }
704 };
705 void cancelImport();
706 },
707 },
708 {
709 text: "Retry",
710 onPress: () => setShareImportAttempt((attempt) => attempt + 1),
711 },
712 ],
713 { cancelable: false },
714 );
715 })
716 .finally(() => {
717 if (startedShareImportKeyRef.current === importKey) {
718 startedShareImportKeyRef.current = null;
719 }
720 if (shareImportMountedRef.current && activeShareImportTokenRef.current === importToken) {
721 activeShareImportTokenRef.current = null;
722 setImportingShareKey(null);
723 }
724 });
725 }, [
726 consumeShare,
727 cancelledIncomingShareId,
728 flow.draftKey,
729 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- hasImportedIncomingShare reflects the draft store; a change re-checks whether the share still needs importing.
730 hasImportedIncomingShare,
731 incomingShare,
732 isIncomingShareInboxLoading,
733 isIncomingShareUnavailable,
734 props.incomingShareId,
735 props.initialProjectRef?.environmentId,
736 props.initialProjectRef?.projectId,
737 releaseShareReservation,
738 reserveShare,
739 selectedEnvironmentServerConfig,
740 selectedProject,
741 shareImportAttempt,
742 ]);
743
744 const selectedEnvironmentLabel =
745 flow.environments.find(
746 (environment) => environment.environmentId === flow.selectedEnvironmentId,
747 )?.environmentLabel ?? "Environment";
748 const availableCurrentBranchName =
749 flow.availableBranches.find((branch) => branch.current)?.name ??
750 flow.availableBranches.find((branch) => branch.isDefault)?.name ??
751 null;
752 const selectedBranchName = resolveProjectThreadCreationBranch({
753 workspaceMode: flow.workspaceMode,
754 selectedBranch:
755 flow.selectedBranchName ??
756 (flow.workspaceMode === "worktree" ? availableCurrentBranchName : null),
757 currentCheckoutBranch: flow.currentCheckoutBranchName,
758 });
759 const selectedBranchLabel = resolveNewTaskBranchLabel({
760 branchName: selectedBranchName,
761 startFromOrigin: flow.startFromOrigin,
762 workspaceMode: flow.workspaceMode,
763 pullRequestReference: flow.pullRequestReference,
764 });
765 const workspaceLabel = resolveNewTaskWorkspaceLabel({
766 workspaceMode: flow.workspaceMode,
767 worktreePath: flow.selectedWorktreePath,
768 });
769 const showBranchLoading =
770 environmentConnected && flow.branchesLoading && flow.availableBranches.length === 0;
771
772 const {
773 onPickDraftMedia: handlePickMedia,
774 onPickDraftFiles: handlePickFiles,
775 onNativePasteImages: handleNativePasteImages,
776 onNativePasteText: handleNativePasteText,
777 } = useComposerAttachmentActions({
778 draftKey: flow.draftKey,
779 serverConfig: selectedEnvironmentServerConfig,
780 locked: isComposerInteractionLocked,
781 });
782
783 async function handleStart(): Promise<import("@t3tools/contracts").MessageId | null> {
784 const selectedProject = flow.selectedProject;
785 const draftKey = flow.draftKey;
786 if (
787 !selectedProject ||
788 !draftKey ||
789 cloneBlocksStart ||
790 !isIncomingShareReady ||
791 isImportingShare ||
792 isComposerInteractionLocked
793 ) {
794 return null;
795 }
796 if (
797 environmentConnected &&
798 !readEnvironmentScope(selectedProject.environmentId, AuthOrchestrationOperateScope)
799 ) {
800 return null;
801 }
802 const draft = getComposerDraftSnapshot(draftKey);
803 if (appAtomRegistry.get(composerContextImportsAtom)[draftKey]) return null;
804 const modelSelection =
805 resolveSelectableModelSelection(
806 selectedEnvironmentServerConfig,
807 draft.modelSelection ?? null,
808 selectedProject.id,
809 ) ?? flow.selectedModel;
810 const workspaceSelection = flow.resolveWorkspaceSelection(draft.workspaceSelection);
811 const workspaceMode = workspaceSelection.mode;
812 const selectedBranchName = workspaceSelection.branch;
813 const initialMessageText = draft.text.trim();
814
815 if (
816 attachmentBlockReason !== null ||
817 !modelSelection ||
818 (initialMessageText.length === 0 && draft.attachments.length === 0) ||
819 flow.submitting ||
820 (workspaceMode === "worktree" && !selectedBranchName)
821 ) {
822 return null;
823 }
824 if (
825 environmentConnected &&
826 isModelSelectionUnavailable(
827 selectedEnvironmentServerConfig,
828 modelSelection,
829 selectedProject.id,
830 )
831 ) {
832 const { title, detail } = describeUnavailableModelSelection(
833 selectedEnvironmentServerConfig,
834 modelSelection,
835 selectedProject.id,
836 );
837 Dialog.alert(title, detail);
838 return null;
839 }
840 // Recovery may retain over-cap attachments; block send before uploading a turn the server would reject.
841 if (draft.attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
842 Dialog.alert(
843 "Too many attachments",
844 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
845 );
846 return null;
847 }
848
849 const contextBlockReason = composerContextSendBlockReason(draft.context);
850 if (contextBlockReason) {
851 Dialog.alert("Too much context", contextBlockReason);
852 return null;
853 }
854 const strandedThread = threadContextsOutsideEnvironment({
855 text: draft.text,
856 records: draft.context?.records ?? [],
857 environmentId: selectedProject.environmentId,
858 })[0];
859 if (strandedThread) {
860 const owner =
861 flow.environments.find(
862 (environment) => environment.environmentId === strandedThread.environmentId,
863 )?.environmentLabel ?? "its machine";
864 Dialog.alert(
865 "Attached thread unavailable",
866 `"${strandedThread.title}" is on another machine. Switch back to ${owner} or remove it from the draft.`,
867 );
868 return null;
869 }
870
871 const message = flow.buildPendingTaskMessage(creationMetadata, {
872 currentCheckoutBranch: queuesInsteadOfStarting ? null : flow.currentCheckoutBranchName,
873 });
874 if (!message) {
875 return null;
876 }
877 // Persist locally before clearing or leaving the draft; server setup runs on the thread.
878 flow.setSubmitting(true);
879 const queued = await settlePromise(() => enqueueThreadOutboxMessage(message));
880 flow.setSubmitting(false);
881 if (AsyncResult.isFailure(queued)) {
882 const error = squashAtomCommandFailure(queued);
883 Dialog.alert(
884 "Could not queue task",
885 error instanceof Error ? error.message : "The task could not be saved to the outbox.",
886 );
887 return null;
888 }
889 promptInputRef.current?.blur();
890 navigation.dispatch(
891 CommonActions.setParams(
892 submittedThreadParams(String(message.environmentId), String(message.threadId)),
893 ),
894 );
895 // The composer has moved to the submitted thread; a pick still converting
896 // would otherwise resurrect this draft.
897 abortComposerDraftOperations(draftKey);
898 const draftSnapshot = getComposerDraftSnapshot(draftKey);
899 // The queued message owns the attachments now, so the sweep is deferred
900 // until the write confirms it.
901 clearComposerDraftContent(draftKey, {
902 clearModelSelection: true,
903 clearWorkspaceSelection: true,
904 deferAttachmentCleanup: true,
905 });
906 scheduleUnusedComposerAttachmentCleanup(draftSnapshot.attachments);
907 return message.messageId;
908 }
909
910 // Keep the current surface until the local draft selection is ready. Publishing
911 // an empty loading surface here flashes between two already-cached threads.
912 if (!selectedProject) return null;
913
914 const setupBlockReason =
915 isIncomingShareReady && !isImportingShare
916 ? cloneBlocksStart
917 ? "Wait for the project clone to finish."
918 : flow.submitting
919 ? "Starting the thread…"
920 : flow.workspaceMode === "worktree" && (!flow.selectedBranchName || !flow.isGitRepoKnown)
921 ? "Choose a base branch before creating a worktree."
922 : null
923 : "Wait for shared content to finish importing.";
924 const chooseProject = () => {
925 if (isComposerInteractionLocked) {
926 return;
927 }
928 promptInputRef.current?.blur();
929 void KeyboardController.dismiss({ animated: true });
930 navigation.navigate("NewTaskProject", { incomingShareId: props.incomingShareId });
931 };
932 const openContextPicker = (routeName: "NewTaskBranch" | "NewTaskEnvironment") => {
933 if (isComposerInteractionLocked) {
934 return;
935 }
936 promptInputRef.current?.blur();
937 void KeyboardController.dismiss({ animated: true });
938 navigation.navigate(routeName);
939 };
940
941 const environmentControl = (
942 <DraftEnvironmentControl
943 connectionState={connectionState}
944 label={selectedEnvironmentLabel}
945 machineKind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}
946 disabled={isComposerInteractionLocked}
947 onChooseEnvironment={() => openContextPicker("NewTaskEnvironment")}
948 />
949 );
950 const hero = flow.isScratchDraft ? (
951 <View className="items-center gap-2 px-6" testID="new-task-hero">
952 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
953 What should we work on?
954 </Text>
955 <View className="flex-row flex-wrap items-center justify-center gap-x-1">
956 <ComposerInlineControl
957 accessibilityHint="Opens the project picker"
958 accessibilityLabel="No project"
959 chevronDirection="right"
960 disabled={isComposerInteractionLocked}
961 icon="folder"
962 label="No project"
963 onPress={chooseProject}
964 />
965 {environmentControl}
966 </View>
967 </View>
968 ) : (
969 <View className="items-center gap-6 px-6" testID="new-task-hero">
970 <View className="w-full items-center gap-1.5">
971 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
972 What should we build
973 </Text>
974 <View className="max-w-full flex-row items-center justify-center">
975 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">in </Text>
976 <Pressable
977 accessibilityHint="Opens the project picker"
978 accessibilityLabel={selectedProjectLabel ?? selectedProject.title}
979 accessibilityRole="button"
980 disabled={isComposerInteractionLocked}
981 onPress={chooseProject}
982 className="min-w-0 max-w-[250px] border-b border-foreground-muted active:opacity-65"
983 >
984 <Text
985 className="text-2xl font-t3-medium tracking-tight text-foreground"
986 numberOfLines={1}
987 >
988 {selectedProjectLabel ?? selectedProject.title}
989 </Text>
990 </Pressable>
991 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">?</Text>
992 </View>
993 </View>
994
995 {environmentControl}
996 </View>
997 );
998 // The nested hero scroll view does not receive UIKit's automatic navigation inset in split columns.
999 const heroViewport = (headerInset: number, bottomInset: number, availableHeight: number) =>
1000 availableHeight < 180 ? null : (
1001 <NativeScrollEdgeEffectsContext
1002 value={{ top: "hidden", bottom: "hidden", left: "hidden", right: "hidden" }}
1003 >
1004 <View
1005 collapsable={false}
1006 style={{
1007 position: "absolute",
1008 top: headerInset,
1009 bottom: bottomInset,
1010 left: 0,
1011 right: 0,
1012 overflow: "hidden",
1013 }}
1014 >
1015 <ScrollView
1016 alwaysBounceVertical={false}
1017 className="flex-1"
1018 contentInsetAdjustmentBehavior="never"
1019 contentContainerClassName="grow items-center"
1020 contentContainerStyle={{ paddingVertical: 24 }}
1021 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
1022 keyboardShouldPersistTaps="handled"
1023 showsVerticalScrollIndicator={false}
1024 style={{ flex: 1 }}
1025 testID="new-task-hero-scroll"
1026 >
1027 <View style={{ flexGrow: 1 }} />
1028 {hero}
1029 <View style={{ flexGrow: 2 }} />
1030 </ScrollView>
1031 </View>
1032 </NativeScrollEdgeEffectsContext>
1033 );
1034
1035 const workspaceControls = (
1036 <View className="flex-row items-center gap-1 px-2">
1037 <ComposerInlineControl
1038 accessibilityHint={`Switches to ${flow.workspaceMode === "local" ? "a new worktree" : "the current checkout"}`}
1039 accessibilityLabel={workspaceLabel}
1040 disabled={isComposerInteractionLocked || !flow.isGitRepo}
1041 renderIcon={(size) => (
1042 <NewTaskWorkspaceIcon
1043 workspaceMode={flow.workspaceMode}
1044 worktreePath={flow.selectedWorktreePath}
1045 size={size}
1046 />
1047 )}
1048 label={workspaceLabel}
1049 maxWidth="100%"
1050 onPress={() => flow.setWorkspaceMode(flow.workspaceMode === "local" ? "worktree" : "local")}
1051 showChevron={false}
1052 />
1053
1054 <View className="min-w-0 shrink">
1055 <ComposerInlineControl
1056 accessibilityLabel={`${flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}: ${selectedBranchLabel}`}
1057 chevronDirection="right"
1058 disabled={isComposerInteractionLocked || !flow.isGitRepo}
1059 icon="arrow.triangle.branch"
1060 label={showBranchLoading ? "Loading branches…" : selectedBranchLabel}
1061 maxWidth="100%"
1062 onPress={() => openContextPicker("NewTaskBranch")}
1063 />
1064 </View>
1065 </View>
1066 );
1067
1068 if (!flow.selectedModel) {
1069 return (
1070 <ThreadScreenFallback
1071 header={
1072 <AppBar
1073 title="New thread"
1074 sidebar={false}
1075 onBack={goBack}
1076 options={{
1077 ...threadHeaderAppearance(NATIVE_LIQUID_GLASS_SUPPORTED),
1078 unstable_headerSubtitle: undefined,
1079 unstable_headerRightItems: () => [],
1080 unstable_headerToolbarItems: () => [],
1081 }}
1082 />
1083 }
1084 >
1085 <View className="flex-1 justify-end gap-3 p-4">
1086 {environmentControl}
1087 <Text className="text-foreground-muted">
1088 Your draft is saved on this device. Connect to an environment to choose its first model.
1089 </Text>
1090 <ComposerEditor
1091 draftKey={flow.draftKey}
1092 value={flow.prompt}
1093 onChangeText={flow.setPrompt}
1094 placeholder="Ask anything"
1095 multiline
1096 style={{ minHeight: 64 }}
1097 />
1098 </View>
1099 </ThreadScreenFallback>
1100 );
1101 }
1102 const thread = draftThreadShell({
1103 environmentId: selectedProject.environmentId,
1104 projectId: selectedProject.id,
1105 threadId: ThreadId.make(creationMetadata.threadId),
1106 modelSelection: flow.selectedModel,
1107 runtimeMode: flow.runtimeMode,
1108 interactionMode: flow.interactionMode,
1109 branch: flow.selectedBranchName,
1110 worktreePath: flow.selectedWorktreePath,
1111 createdAt: creationMetadata.createdAt,
1112 });
1113 return (
1114 <>
1115 <ThreadScreenBinding
1116 environmentId={selectedProject.environmentId}
1117 header={
1118 <DraftThreadHeader thread={thread} project={selectedProject} cwd={composerWorkspaceCwd} />
1119 }
1120 draftMode={{
1121 content: heroViewport,
1122 controls: (
1123 <View className="pb-1">
1124 {projectClone && projectClone.phase !== "done" && selectedProject ? (
1125 <View className="px-1 pb-2">
1126 <ProjectCloneBanner
1127 clone={projectClone}
1128 onCancel={() =>
1129 void runCloneAction("Failed to cancel clone", () =>
1130 cancelProjectClone({
1131 environmentId: selectedProject.environmentId,
1132 input: { projectId: selectedProject.id },
1133 }),
1134 )
1135 }
1136 onRetry={() =>
1137 void runCloneAction("Failed to retry clone", () =>
1138 retryProjectClone({
1139 environmentId: selectedProject.environmentId,
1140 input: { projectId: selectedProject.id },
1141 }),
1142 )
1143 }
1144 onRemove={() => void removeClonedProject()}
1145 />
1146 </View>
1147 ) : null}
1148 {flow.canChooseWorkspace ? workspaceControls : null}
1149 </View>
1150 ),
1151 editorRef: promptInputRef,
1152 sendBlockedReason: setupBlockReason,
1153 interactionLocked: isComposerInteractionLocked,
1154 }}
1155 canOperateThread={canOperate}
1156 selectedThread={thread}
1157 selectedThreadDetailRef={null}
1158 contentPresentation={{ kind: "ready" }}
1159 screenTone={connectionTone(connectionState)}
1160 connectionError={environmentRuntime?.connectionError ?? null}
1161 environmentLabel={selectedEnvironmentLabel}
1162 feedbackSubmissions={[]}
1163 onDismissFeedback={() => {}}
1164 selectedThreadFeed={[]}
1165 activityRun={null}
1166 activeWorkStartedAt={null}
1167 isCompacting={false}
1168 creationState={null}
1169 activePendingApproval={null}
1170 activePendingApprovals={[]}
1171 respondingApprovalId={null}
1172 activePendingUserInput={null}
1173 activePendingUserInputDrafts={{}}
1174 activePendingUserInputAnswers={null}
1175 respondingUserInputId={null}
1176 connectionStateLabel={connectionState}
1177 activeThreadBusy={false}
1178 canStopThread={false}
1179 queuedRunEdit={null}
1180 composerDraftKey={flow.draftKey}
1181 followUpBehavior="queue"
1182 canSteerActiveTurn={false}
1183 isSavingQueuedEdit={false}
1184 onCancelQueuedRunEdit={() => {}}
1185 onRemoveQueuedEditAttachment={() => {}}
1186 projectWorkspaceRoot={selectedProject.workspaceRoot}
1187 threadCwd={composerWorkspaceCwd}
1188 selectedThreadQueueCount={0}
1189 queuedMessages={[]}
1190 dispatchingMessageId={null}
1191 serverConfig={selectedEnvironmentServerConfig}
1192 usesAutomaticContentInsets
1193 onOpenConnectionEditor={() => navigation.navigate("Connections")}
1194 onChangeDraftMessage={flow.setPrompt}
1195 onPickDraftMedia={handlePickMedia}
1196 onPickDraftFiles={handlePickFiles}
1197 onNativePasteImages={handleNativePasteImages}
1198 onNativePasteText={handleNativePasteText}
1199 onRemoveDraftImage={flow.removeAttachment}
1200 onStopThread={() => {}}
1201 onResumeQueue={null}
1202 onSendMessage={handleStart}
1203 onReconnectEnvironment={() => onReconnectEnvironment(selectedProject.environmentId)}
1204 canSwitchThreadProvider
1205 onUpdateThreadInteractionMode={flow.planModeEnabled ? flow.setInteractionMode : undefined}
1206 onRespondToApproval={async () => {}}
1207 onSelectUserInputOption={() => {}}
1208 onChangeUserInputCustomAnswer={() => {}}
1209 onSubmitUserInput={async () => {}}
1210 onDismissUserInput={async () => {}}
1211 />
1212 </>
1213 );
1214}