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

NewTaskDraftScreen.tsx

1,262 lines47.9 KB

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