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

NewTaskDraftScreen.tsx

1,240 lines46.9 KB

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