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