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

NewTaskDraftScreen.tsx

1,271 lines48.0 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 { 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 );
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 // The share this screen already moved into its draft. Sending clears the
287 // draft (and its importedShareIds receipt) a frame before the screen leaves,
288 // and the inbox entry is long gone by then; without this the re-render in
289 // between reads as "shared content vanished" and alerts on every send.
290 const [consumedIncomingShareId, setConsumedIncomingShareId] = useState<string | null>(null);
291 const incomingShare = props.incomingShareId ? getShare(props.incomingShareId) : null;
292 const requestedInitialProjectAvailable = Boolean(
293 props.initialProjectRef?.environmentId &&
294 props.initialProjectRef.projectId &&
295 projects.some(
296 (project) =>
297 project.environmentId === props.initialProjectRef?.environmentId &&
298 project.id === props.initialProjectRef?.projectId,
299 ),
300 );
301 const isProjectPickerReturnActive =
302 isReturningToProjectPicker && !requestedInitialProjectAvailable;
303 const isIncomingShareAwaitingServerConfig = Boolean(
304 incomingShare?.attachments.some((attachment) => attachment.type === "file") &&
305 selectedEnvironmentServerConfig === null,
306 );
307 const isIncomingShareTransferPending = Boolean(
308 incomingShare &&
309 cancelledIncomingShareId !== props.incomingShareId &&
310 !isIncomingShareAwaitingServerConfig,
311 );
312 const contextImports = useAtomValue(composerContextImportsAtom);
313 const isImportingContext = flow.draftKey ? contextImports[flow.draftKey] === true : false;
314 const isComposerInteractionLocked =
315 isIncomingShareTransferPending || flow.submitting || isImportingContext;
316 const { environments, selectedEnvironmentId, switchEnvironment, switchingToEnvironmentId } = flow;
317 const cycleEnvironment = () => {
318 if (isComposerInteractionLocked) return true;
319 const next = nextEnvironmentId(environments, switchingToEnvironmentId ?? selectedEnvironmentId);
320 if (next !== null) void switchEnvironment(next);
321 return true;
322 };
323 const cycleEnvironmentCommands = environments.length > 1 ? (["cycleHost"] as const) : [];
324 useHardwareKeyboardCommand(cycleEnvironmentCommands, cycleEnvironment);
325 const composerWorkspaceCwd =
326 (flow.workspaceMode === "worktree"
327 ? selectedProject?.workspaceRoot
328 : (flow.selectedWorktreePath ?? selectedProject?.workspaceRoot)) || null;
329 const preventRemove =
330 (isIncomingShareTransferPending && !isProjectPickerReturnActive) ||
331 isCancellingShareImport ||
332 flow.submitting;
333 usePreventRemove(preventRemove, () => undefined);
334 const hasImportedIncomingShare = Boolean(
335 props.incomingShareId &&
336 (consumedIncomingShareId === props.incomingShareId ||
337 (flow.draftKey &&
338 getComposerDraftSnapshot(flow.draftKey).importedShareIds?.includes(props.incomingShareId))),
339 );
340 const isIncomingShareUnavailable = Boolean(
341 props.incomingShareId &&
342 !isIncomingShareInboxLoading &&
343 !incomingShare &&
344 !hasImportedIncomingShare,
345 );
346 const isIncomingShareReady =
347 !props.incomingShareId ||
348 (hasImportedIncomingShare && !incomingShare) ||
349 isIncomingShareUnavailable;
350 const appliedInitialProjectKeyRef = useRef<string | null>(null);
351 useEffect(() => {
352 if (cancelledIncomingShareId === props.incomingShareId) {
353 navigation.goBack();
354 }
355 }, [cancelledIncomingShareId, navigation, props.incomingShareId]);
356 useEffect(() => {
357 if (!isReturningToProjectPicker) {
358 return;
359 }
360 if (requestedInitialProjectAvailable) {
361 setIsReturningToProjectPicker(false);
362 return;
363 }
364 // Let usePreventRemove commit its disabled state before replacing this
365 // route, otherwise the transfer guard can swallow the fallback action.
366 const frame = requestAnimationFrame(() => {
367 navigation.dispatch(
368 StackActions.replace("NewTaskProject", { incomingShareId: props.incomingShareId }),
369 );
370 });
371 return () => cancelAnimationFrame(frame);
372 }, [
373 isReturningToProjectPicker,
374 navigation,
375 props.incomingShareId,
376 requestedInitialProjectAvailable,
377 ]);
378 useEffect(() => {
379 if (!shareImportMountedRef.current) {
380 startedShareImportKeyRef.current = null;
381 }
382 shareImportMountedRef.current = true;
383 return () => {
384 appliedInitialProjectKeyRef.current = null;
385 shareImportMountedRef.current = false;
386 activeShareImportTokenRef.current = null;
387 cancellingShareImportKeyRef.current = null;
388 };
389 }, []);
390​
391 const { beginEditingPendingTask, cancelEditingPendingTask, editingPendingTask, openDraft } = flow;
392 // Drafts hydrate from disk and projects arrive with the shell snapshot, so on
393 // a cold launch the draft or its project can be missing for a moment; wait
394 // for hydration and retry while projects load.
395 const attemptedDraftIdRef = useRef<string | null>(null);
396 useEffect(() => {
397 if (!props.draftId || props.pendingTaskId) {
398 return;
399 }
400 const draftId = props.draftId;
401 if (attemptedDraftIdRef.current === draftId) {
402 return;
403 }
404 let cancelled = false;
405 void waitForComposerDraftsLoaded().then(() => {
406 if (cancelled || attemptedDraftIdRef.current === draftId) {
407 return;
408 }
409 if (openDraft(draftId)) {
410 attemptedDraftIdRef.current = draftId;
411 return;
412 }
413 if (getComposerDraftSnapshot(draftId).project !== undefined && projects.length === 0) {
414 return;
415 }
416 attemptedDraftIdRef.current = draftId;
417 navigation.dispatch(CommonActions.navigate("NewTaskProject"));
418 });
419 return () => {
420 cancelled = true;
421 };
422 }, [navigation, openDraft, projects, props.draftId, props.pendingTaskId]);
423​
424 const attemptedPendingTaskIdRef = useRef<string | null>(null);
425 useEffect(() => {
426 if (!props.pendingTaskId || editingPendingTask?.messageId === props.pendingTaskId) {
427 return;
428 }
429 if (attemptedPendingTaskIdRef.current === props.pendingTaskId) {
430 return;
431 }
432 attemptedPendingTaskIdRef.current = props.pendingTaskId;
433 if (!beginEditingPendingTask(props.pendingTaskId)) {
434 navigation.dispatch(CommonActions.navigate("NewTaskProject"));
435 }
436 }, [beginEditingPendingTask, editingPendingTask?.messageId, navigation, props.pendingTaskId]);
437​
438 useEffect(() => {
439 if (!props.pendingTaskId) return;
440 return () => {
441 attemptedPendingTaskIdRef.current = null;
442 cancelEditingPendingTask();
443 };
444 }, [props.pendingTaskId, cancelEditingPendingTask]);
445​
446 const lastInitialProjectRefRef = useRef(props.initialProjectRef);
447​
448 useEffect(() => {
449 if (props.pendingTaskId || props.draftId) {
450 return;
451 }
452 if (lastInitialProjectRefRef.current !== props.initialProjectRef) {
453 lastInitialProjectRefRef.current = props.initialProjectRef;
454 appliedInitialProjectKeyRef.current = null;
455 }
456 const initialEnvironmentId = props.initialProjectRef?.environmentId;
457 const initialProjectId = props.initialProjectRef?.projectId;
458 if (initialEnvironmentId && initialProjectId) {
459 const directProject =
460 projects.find(
461 (project) =>
462 project.environmentId === initialEnvironmentId && project.id === initialProjectId,
463 ) ?? null;
464​
465 if (directProject) {
466 // Apply the route's project once. Re-applying on every change would
467 // instantly revert environment/project switches made in the picker.
468 const directProjectKey = `${directProject.environmentId}:${directProject.id}`;
469 if (appliedInitialProjectKeyRef.current === directProjectKey) {
470 return;
471 }
472 if (props.initialProjectRef?.branch) {
473 if (
474 selectedProject?.environmentId !== directProject.environmentId ||
475 selectedProject.id !== directProject.id
476 ) {
477 setProject(directProject);
478 return;
479 }
480 if (!flow.draftKey) return;
481 // The route completes checkout before mounting this composer. Local
482 // mode reuses an existing worktree; worktree mode would create another.
483 updateComposerDraftSettings(flow.draftKey, {
484 workspaceSelection: {
485 mode: "local",
486 branch: props.initialProjectRef.branch,
487 worktreePath: props.initialProjectRef.worktreePath ?? null,
488 startFromOrigin: false,
489 },
490 });
491 }
492 appliedInitialProjectKeyRef.current = directProjectKey;
493 if (
494 selectedProject?.environmentId === directProject.environmentId &&
495 selectedProject.id === directProject.id
496 ) {
497 return;
498 }
499 setProject(directProject);
500 return;
501 }
502​
503 if (projects.length > 0) {
504 setIsReturningToProjectPicker(true);
505 }
506 return;
507 }
508​
509 const selection = resolveDraftProjectSelection(selectedProjectKey, projects, projectScopes);
510 if (selection.kind === "preserve") {
511 return;
512 }
513 if (selection.kind === "select") {
514 setProject(selection.project);
515 return;
516 }
517​
518 navigation.dispatch(CommonActions.navigate("NewTaskProject"));
519 }, [
520 projectScopes,
521 projects,
522 flow.draftKey,
523 props.initialProjectRef,
524 props.incomingShareId,
525 props.pendingTaskId,
526 props.draftId,
527 navigation,
528 selectedProject,
529 selectedProjectKey,
530 setProject,
531 ]);
532​
533 useEffect(() => {
534 if (!selectedProject) {
535 loadedBranchesProjectKeyRef.current = null;
536 return;
537 }
538 const projectKey = `${selectedProject.environmentId}:${selectedProject.id}`;
539 if (loadedBranchesProjectKeyRef.current === projectKey) {
540 return;
541 }
542 loadedBranchesProjectKeyRef.current = projectKey;
543 flow.loadBranches();
544 }, [flow.loadBranches, selectedProject]);
545​
546 useEffect(() => {
547 const shareId = props.incomingShareId;
548 const draftKey = flow.draftKey;
549 const destinationProject = selectedProject;
550 const initialEnvironmentId = props.initialProjectRef?.environmentId;
551 const initialProjectId = props.initialProjectRef?.projectId;
552 const selectedProjectMatchesRoute =
553 !initialEnvironmentId ||
554 !initialProjectId ||
555 (destinationProject?.environmentId === initialEnvironmentId &&
556 destinationProject.id === initialProjectId);
557 if (
558 !shareId ||
559 !draftKey ||
560 !destinationProject ||
561 !selectedProjectMatchesRoute ||
562 cancelledIncomingShareId === shareId
563 ) {
564 return;
565 }
566 const importKey = `${shareId}:${draftKey}`;
567 if (
568 startedShareImportKeyRef.current === importKey ||
569 cancellingShareImportKeyRef.current === importKey
570 ) {
571 return;
572 }
573​
574 if (!incomingShare) {
575 if (isIncomingShareUnavailable && alertedUnavailableIncomingShareIdRef.current !== shareId) {
576 alertedUnavailableIncomingShareIdRef.current = shareId;
577 Dialog.alert(
578 "Shared content unavailable",
579 "The shared content is no longer in the inbox. You can continue editing this task draft.",
580 );
581 }
582 return;
583 }
584​
585 if (
586 incomingShare.attachments.some((attachment) => attachment.type === "file") &&
587 selectedEnvironmentServerConfig === null
588 ) {
589 return;
590 }
591​
592 if (alertedUnavailableIncomingShareIdRef.current === shareId) {
593 alertedUnavailableIncomingShareIdRef.current = null;
594 }
595 startedShareImportKeyRef.current = importKey;
596 const draftBackup =
597 shareImportDraftBackupRef.current.get(importKey) ?? getComposerDraftSnapshot(draftKey);
598 shareImportDraftBackupRef.current.set(importKey, draftBackup);
599 const importToken = Symbol(importKey);
600 let didReserveShare = false;
601 let didConsumeShare = false;
602 let needsDraftRestore = false;
603 activeShareImportTokenRef.current = importToken;
604 setImportingShareKey(importKey);
605 void (async () => {
606 await reserveShare(shareId, {
607 environmentId: String(destinationProject.environmentId),
608 projectId: String(destinationProject.id),
609 });
610 didReserveShare = true;
611 if (
612 !shareImportMountedRef.current ||
613 activeShareImportTokenRef.current !== importToken ||
614 !isCurrentShareImport(draftKey, shareId)
615 ) {
616 return;
617 }
618 const selectedAttachments = selectIncomingShareAttachmentsForServer({
619 attachments: incomingShare.attachments,
620 serverConfig: appAtomRegistry.get(
621 serverEnvironment.configValueAtom(destinationProject.environmentId),
622 ),
623 });
624 if (selectedAttachments.status === "pending") {
625 throw new Error("Server attachment support is still loading.");
626 }
627 needsDraftRestore = true;
628 const { skippedAttachmentCount } = await mergeComposerDraftContent(draftKey, {
629 text: incomingShare.text,
630 attachments: selectedAttachments.attachments,
631 sourceShareId: shareId,
632 });
633 if (
634 !shareImportMountedRef.current ||
635 activeShareImportTokenRef.current !== importToken ||
636 !isCurrentShareImport(draftKey, shareId)
637 ) {
638 // The durable reservation makes an interrupted transfer resume only
639 // in this project instead of copying into a second project draft.
640 return;
641 }
642 await consumeShare(shareId);
643 didConsumeShare = true;
644 setConsumedIncomingShareId(shareId);
645 // The consumed inbox draft was the last owner of files that never made
646 // it into the composer draft (unsupported server, oversize, limit
647 // skips). Release them before any early return: an unmount or a
648 // superseding import must not leak them, and the sweep re-checks
649 // ownership so it cannot delete a file another draft picked up.
650 const retainedAttachmentIds = new Set(
651 getComposerDraftSnapshot(draftKey).attachments.map((attachment) => attachment.id),
652 );
653 scheduleUnusedComposerAttachmentCleanup(
654 incomingShare.attachments.filter((attachment) => !retainedAttachmentIds.has(attachment.id)),
655 );
656 if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {
657 return;
658 }
659 const warnings = [...incomingShare.warnings, ...selectedAttachments.warnings];
660 if (skippedAttachmentCount > 0) {
661 warnings.push(
662 `${skippedAttachmentCount} shared file${skippedAttachmentCount === 1 ? " was" : "s were"} skipped because this draft reached the attachment limit.`,
663 );
664 }
665 if (warnings.length > 0) {
666 Dialog.alert("Some shared content was skipped", warnings.join("\n"));
667 }
668 shareImportDraftBackupRef.current.delete(importKey);
669 })()
670 .catch((error) => {
671 if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {
672 return;
673 }
674 Dialog.alert(
675 "Could not import shared content",
676 error instanceof Error ? error.message : "The shared content could not be saved.",
677 [
678 {
679 text: "Cancel import",
680 style: "cancel",
681 onPress: () => {
682 const cancelImport = async (): Promise<void> => {
683 if (!shareImportMountedRef.current) {
684 return;
685 }
686 // Latch synchronously before restoring the draft. The
687 // restore publishes atom state and can re-run the import
688 // effect before React commits the cancelling state update.
689 cancellingShareImportKeyRef.current = importKey;
690 setIsCancellingShareImport(true);
691 try {
692 if (needsDraftRestore) {
693 // The restore drops the share's merged-in attachments
694 // from the draft. Sweep them only when the inbox entry
695 // was consumed: before that, the inbox still references
696 // these files and must keep them for a later import.
697 const mergedAttachments = getComposerDraftSnapshot(draftKey).attachments;
698 await restoreComposerDraftSnapshot(draftKey, draftBackup);
699 needsDraftRestore = false;
700 if (didConsumeShare) {
701 scheduleUnusedComposerAttachmentCleanup(mergedAttachments);
702 }
703 }
704 if (didReserveShare) {
705 await releaseShareReservation(shareId, {
706 environmentId: String(destinationProject.environmentId),
707 projectId: String(destinationProject.id),
708 });
709 }
710 shareImportDraftBackupRef.current.delete(importKey);
711 if (shareImportMountedRef.current) {
712 setIsCancellingShareImport(false);
713 setCancelledIncomingShareId(shareId);
714 }
715 } catch (cancelError) {
716 if (!shareImportMountedRef.current) {
717 return;
718 }
719 Dialog.alert(
720 "Could not cancel import",
721 cancelError instanceof Error
722 ? cancelError.message
723 : "The shared content could not be restored safely.",
724 [
725 {
726 text: "Retry import",
727 onPress: () => {
728 cancellingShareImportKeyRef.current = null;
729 setIsCancellingShareImport(false);
730 setShareImportAttempt((attempt) => attempt + 1);
731 },
732 },
733 {
734 text: "Retry cancel",
735 onPress: () => void cancelImport(),
736 },
737 ],
738 { cancelable: false },
739 );
740 }
741 };
742 void cancelImport();
743 },
744 },
745 {
746 text: "Retry",
747 onPress: () => setShareImportAttempt((attempt) => attempt + 1),
748 },
749 ],
750 { cancelable: false },
751 );
752 })
753 .finally(() => {
754 if (startedShareImportKeyRef.current === importKey) {
755 startedShareImportKeyRef.current = null;
756 }
757 if (shareImportMountedRef.current && activeShareImportTokenRef.current === importToken) {
758 activeShareImportTokenRef.current = null;
759 setImportingShareKey(null);
760 }
761 });
762 }, [
763 consumeShare,
764 cancelledIncomingShareId,
765 flow.draftKey,
766 hasImportedIncomingShare,
767 incomingShare,
768 isIncomingShareInboxLoading,
769 isIncomingShareUnavailable,
770 props.incomingShareId,
771 props.initialProjectRef?.environmentId,
772 props.initialProjectRef?.projectId,
773 releaseShareReservation,
774 reserveShare,
775 selectedEnvironmentServerConfig,
776 selectedProject,
777 shareImportAttempt,
778 ]);
779​
780 const selectedEnvironmentLabel =
781 flow.environments.find(
782 (environment) => environment.environmentId === flow.selectedEnvironmentId,
783 )?.environmentLabel ?? "Environment";
784 const availableCurrentBranchName =
785 flow.availableBranches.find((branch) => branch.current)?.name ??
786 flow.availableBranches.find((branch) => branch.isDefault)?.name ??
787 null;
788 const selectedBranchName = resolveProjectThreadCreationBranch({
789 workspaceMode: flow.workspaceMode,
790 selectedBranch:
791 flow.selectedBranchName ??
792 (flow.workspaceMode === "worktree" ? availableCurrentBranchName : null),
793 currentCheckoutBranch: flow.currentCheckoutBranchName,
794 });
795 const selectedBranchLabel = resolveNewTaskBranchLabel({
796 branchName: selectedBranchName,
797 startFromOrigin: flow.startFromOrigin,
798 workspaceMode: flow.workspaceMode,
799 pullRequestReference: flow.pullRequestReference,
800 });
801 const workspaceLabel = resolveNewTaskWorkspaceLabel({
802 workspaceMode: flow.workspaceMode,
803 worktreePath: flow.selectedWorktreePath,
804 });
805 const showBranchLoading =
806 environmentConnected && flow.branchesLoading && flow.availableBranches.length === 0;
807​
808 const {
809 onPickDraftMedia: handlePickMedia,
810 onPickDraftFiles: handlePickFiles,
811 onNativePasteImages: handleNativePasteImages,
812 onNativePasteText: handleNativePasteText,
813 } = useComposerAttachmentActions({
814 draftKey: flow.draftKey,
815 serverConfig: selectedEnvironmentServerConfig,
816 locked: isComposerInteractionLocked,
817 });
818​
819 async function handleStart(): Promise<import("@t3tools/contracts").MessageId | null> {
820 const selectedProject = flow.selectedProject;
821 const draftKey = flow.draftKey;
822 if (
823 !selectedProject ||
824 !draftKey ||
825 cloneBlocksStart ||
826 !isIncomingShareReady ||
827 isImportingShare ||
828 isComposerInteractionLocked
829 ) {
830 return null;
831 }
832 if (
833 environmentConnected &&
834 !readEnvironmentScope(selectedProject.environmentId, AuthOrchestrationOperateScope)
835 ) {
836 return null;
837 }
838 const draft = getComposerDraftSnapshot(draftKey);
839 if (appAtomRegistry.get(composerContextImportsAtom)[draftKey]) return null;
840 const modelSelection =
841 resolveSelectableModelSelection(
842 selectedEnvironmentServerConfig,
843 draft.modelSelection ?? null,
844 selectedProject.id,
845 ) ?? flow.selectedModel;
846 const workspaceSelection = resolveNewTaskWorkspaceSelection({
847 selection: draft.workspaceSelection,
848 fallback: {
849 mode: flow.workspaceMode,
850 branch: flow.selectedBranchName,
851 worktreePath: flow.selectedWorktreePath,
852 },
853 isGitRepo: flow.isGitRepo,
854 });
855 const workspaceMode = workspaceSelection.mode;
856 const selectedBranchName = workspaceSelection.branch;
857 const initialMessageText = draft.text.trim();
858​
859 if (
860 attachmentBlockReason !== null ||
861 !modelSelection ||
862 (initialMessageText.length === 0 && draft.attachments.length === 0) ||
863 flow.submitting ||
864 (workspaceMode === "worktree" && !selectedBranchName)
865 ) {
866 return null;
867 }
868 if (
869 environmentConnected &&
870 isModelSelectionUnavailable(
871 selectedEnvironmentServerConfig,
872 modelSelection,
873 selectedProject.id,
874 )
875 ) {
876 const { title, detail } = describeUnavailableModelSelection(
877 selectedEnvironmentServerConfig,
878 modelSelection,
879 selectedProject.id,
880 );
881 Dialog.alert(title, detail);
882 return null;
883 }
884 // A failed-send restore can leave the draft over the cap on purpose (it
885 // never drops the user's files); starting anyway would upload everything
886 // and have the server reject the turn.
887 if (draft.attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
888 Dialog.alert(
889 "Too many attachments",
890 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
891 );
892 return null;
893 }
894​
895 const contextBlockReason = composerContextSendBlockReason(draft.context);
896 if (contextBlockReason) {
897 Dialog.alert("Too much context", contextBlockReason);
898 return null;
899 }
900 const strandedThread = threadContextsOutsideEnvironment({
901 text: draft.text,
902 records: draft.context?.records ?? [],
903 environmentId: selectedProject.environmentId,
904 })[0];
905 if (strandedThread) {
906 const owner =
907 flow.environments.find(
908 (environment) => environment.environmentId === strandedThread.environmentId,
909 )?.environmentLabel ?? "its machine";
910 Dialog.alert(
911 "Attached thread unavailable",
912 `"${strandedThread.title}" is on another machine. Switch back to ${owner} or remove it from the draft.`,
913 );
914 return null;
915 }
916​
917 const editingPendingTask = flow.editingPendingTask;
918​
919 const metadata = editingPendingTask
920 ? {
921 threadId: editingPendingTask.threadId,
922 commandId: editingPendingTask.commandId,
923 messageId: editingPendingTask.messageId,
924 createdAt: editingPendingTask.createdAt,
925 }
926 : creationMetadata;
927 const message = flow.buildPendingTaskMessage(metadata, {
928 currentCheckoutBranch: queuesInsteadOfStarting ? null : flow.currentCheckoutBranchName,
929 });
930 if (!message) {
931 return null;
932 }
933 // Persist before clearing the draft or leaving its editor. This only waits
934 // for the local outbox write; server and worktree setup run on the thread.
935 flow.setSubmitting(true);
936 const queued = await settlePromise(() => enqueueThreadOutboxMessage(message));
937 flow.setSubmitting(false);
938 if (AsyncResult.isFailure(queued)) {
939 const error = squashAtomCommandFailure(queued);
940 Dialog.alert(
941 "Could not queue task",
942 error instanceof Error ? error.message : "The task could not be saved to the outbox.",
943 );
944 return null;
945 }
946 promptInputRef.current?.blur();
947 navigation.dispatch(
948 CommonActions.setParams(
949 submittedThreadParams(String(message.environmentId), String(message.threadId)),
950 ),
951 );
952 const draftSnapshot = getComposerDraftSnapshot(draftKey);
953 if (editingPendingTask) {
954 flow.finishEditingPendingTask();
955 } else {
956 // The queued message owns the attachments now, so the sweep is deferred
957 // until the write confirms it.
958 clearComposerDraftContent(draftKey, {
959 clearModelSelection: true,
960 clearWorkspaceSelection: true,
961 deferAttachmentCleanup: true,
962 });
963 }
964 scheduleUnusedComposerAttachmentCleanup(draftSnapshot.attachments);
965 return message.messageId;
966 }
967​
968 // Keep the current surface until the local draft selection is ready. Publishing
969 // an empty loading surface here flashes between two already-cached threads.
970 if (!selectedProject) return null;
971​
972 const setupBlockReason =
973 isIncomingShareReady && !isImportingShare
974 ? cloneBlocksStart
975 ? "Wait for the project clone to finish."
976 : flow.submitting
977 ? "Starting the thread…"
978 : flow.workspaceMode === "worktree" && (!flow.selectedBranchName || !flow.isGitRepoKnown)
979 ? "Choose a base branch before creating a worktree."
980 : null
981 : "Wait for shared content to finish importing.";
982 const chooseProject = () => {
983 if (isComposerInteractionLocked) {
984 return;
985 }
986 promptInputRef.current?.blur();
987 void KeyboardController.dismiss({ animated: true });
988 navigation.navigate("NewTaskProject", { incomingShareId: props.incomingShareId });
989 };
990 const openContextPicker = (routeName: "NewTaskBranch" | "NewTaskEnvironment") => {
991 if (isComposerInteractionLocked) {
992 return;
993 }
994 promptInputRef.current?.blur();
995 void KeyboardController.dismiss({ animated: true });
996 navigation.navigate(routeName);
997 };
998​
999 const environmentControl = (
1000 <DraftEnvironmentControl
1001 connectionState={connectionState}
1002 label={selectedEnvironmentLabel}
1003 machineKind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}
1004 disabled={isComposerInteractionLocked}
1005 onChooseEnvironment={() => openContextPicker("NewTaskEnvironment")}
1006 />
1007 );
1008 const hero = flow.isScratchDraft ? (
1009 <View className="items-center gap-2 px-6" testID="new-task-hero">
1010 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
1011 What should we work on?
1012 </Text>
1013 <View className="flex-row flex-wrap items-center justify-center gap-x-1">
1014 <ComposerInlineControl
1015 accessibilityHint="Opens the project picker"
1016 accessibilityLabel="No project"
1017 chevronDirection="right"
1018 disabled={isComposerInteractionLocked}
1019 icon="folder"
1020 label="No project"
1021 onPress={chooseProject}
1022 />
1023 {environmentControl}
1024 </View>
1025 </View>
1026 ) : (
1027 <View className="items-center gap-6 px-6" testID="new-task-hero">
1028 <View className="w-full items-center gap-1.5">
1029 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
1030 What should we build
1031 </Text>
1032 <View className="max-w-full flex-row items-center justify-center">
1033 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">in </Text>
1034 <Pressable
1035 accessibilityHint="Opens the project picker"
1036 accessibilityLabel={selectedProjectLabel ?? selectedProject.title}
1037 accessibilityRole="button"
1038 disabled={isComposerInteractionLocked}
1039 onPress={chooseProject}
1040 className="min-w-0 max-w-[250px] border-b border-foreground-muted active:opacity-65"
1042 <Text
1043 className="text-2xl font-t3-medium tracking-tight text-foreground"
1044 numberOfLines={1}
1046 {selectedProjectLabel ?? selectedProject.title}
1047 </Text>
1048 </Pressable>
1049 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">?</Text>
1050 </View>
1051 </View>
1052​
1053 {environmentControl}
1054 </View>
1055 );
1056 // The nested hero scroll view does not receive UIKit's automatic navigation inset in split columns.
1057 const heroViewport = (headerInset: number, bottomInset: number, availableHeight: number) =>
1058 availableHeight < 180 ? null : (
1059 <NativeScrollEdgeEffectsContext
1060 value={{ top: "hidden", bottom: "hidden", left: "hidden", right: "hidden" }}
1062 <View
1063 collapsable={false}
1064 style={{
1065 position: "absolute",
1066 top: headerInset,
1067 bottom: bottomInset,
1068 left: 0,
1069 right: 0,
1070 overflow: "hidden",
1071 }}
1073 <ScrollView
1074 alwaysBounceVertical={false}
1075 className="flex-1"
1076 contentInsetAdjustmentBehavior="never"
1077 contentContainerClassName="grow items-center"
1078 contentContainerStyle={{ paddingVertical: 24 }}
1079 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
1080 keyboardShouldPersistTaps="handled"
1081 showsVerticalScrollIndicator={false}
1082 style={{ flex: 1 }}
1083 testID="new-task-hero-scroll"
1085 <View style={{ flexGrow: 1 }} />
1086 {hero}
1087 <View style={{ flexGrow: 2 }} />
1088 </ScrollView>
1089 </View>
1090 </NativeScrollEdgeEffectsContext>
1091 );
1092​
1093 const workspaceControls = (
1094 <View className="flex-row items-center gap-1 px-2">
1095 <ComposerInlineControl
1096 accessibilityHint={`Switches to ${flow.workspaceMode === "local" ? "a new worktree" : "the current checkout"}`}
1097 accessibilityLabel={workspaceLabel}
1098 disabled={isComposerInteractionLocked || !flow.isGitRepo}
1099 renderIcon={(size) => (
1100 <NewTaskWorkspaceIcon
1101 workspaceMode={flow.workspaceMode}
1102 worktreePath={flow.selectedWorktreePath}
1103 size={size}
1104 />
1105 )}
1106 label={workspaceLabel}
1107 maxWidth={flow.workspaceMode === "local" ? 220 : 148}
1108 onPress={() => flow.setWorkspaceMode(flow.workspaceMode === "local" ? "worktree" : "local")}
1109 showChevron={false}
1110 />
1111​
1112 <ComposerInlineControl
1113 accessibilityLabel={`${flow.workspaceMode === "worktree" ? "Base branch" : "Branch"}: ${selectedBranchLabel}`}
1114 chevronDirection="right"
1115 disabled={isComposerInteractionLocked || !flow.isGitRepo}
1116 icon="arrow.triangle.branch"
1117 label={showBranchLoading ? "Loading branches…" : selectedBranchLabel}
1118 maxWidth={190}
1119 onPress={() => openContextPicker("NewTaskBranch")}
1120 />
1121 </View>
1122 );
1123​
1124 if (!flow.selectedModel) {
1125 return (
1126 <ThreadScreenFallback>
1127 <AppBar
1128 title="New thread"
1129 sidebar={false}
1130 onBack={goBack}
1131 options={{
1132 ...threadHeaderAppearance(NATIVE_LIQUID_GLASS_SUPPORTED),
1133 unstable_headerSubtitle: undefined,
1134 unstable_headerRightItems: () => [],
1135 unstable_headerToolbarItems: () => [],
1136 }}
1137 />
1138 <View className="flex-1 justify-end gap-3 p-4">
1139 {environmentControl}
1140 <Text className="text-foreground-muted">
1141 Your draft is saved on this device. Connect to an environment to choose its first model.
1142 </Text>
1143 <ComposerEditor
1144 draftKey={flow.draftKey}
1145 value={flow.prompt}
1146 onChangeText={flow.setPrompt}
1147 placeholder="Ask the repo agent, or run a command…"
1148 multiline
1149 style={{ minHeight: 64 }}
1150 />
1151 </View>
1152 </ThreadScreenFallback>
1153 );
1155 const thread = draftThreadShell({
1156 environmentId: selectedProject.environmentId,
1157 projectId: selectedProject.id,
1158 threadId: ThreadId.make(flow.editingPendingTask?.threadId ?? creationMetadata.threadId),
1159 modelSelection: flow.selectedModel,
1160 runtimeMode: flow.runtimeMode,
1161 interactionMode: flow.interactionMode,
1162 branch: flow.selectedBranchName,
1163 worktreePath: flow.selectedWorktreePath,
1164 createdAt: creationMetadata.createdAt,
1165 });
1166 return (
1167 <>
1168 <ThreadScreenBinding
1169 environmentId={selectedProject.environmentId}
1170 header={
1171 <DraftThreadHeader thread={thread} project={selectedProject} cwd={composerWorkspaceCwd} />
1173 draftMode={{
1174 content: heroViewport,
1175 controls: (
1176 <View className="px-3 pb-1">
1177 {projectClone && projectClone.phase !== "done" && selectedProject ? (
1178 <View className="px-1 pb-2">
1179 <ProjectCloneBanner
1180 clone={projectClone}
1181 onCancel={() =>
1182 void runCloneAction("Failed to cancel clone", () =>
1183 cancelProjectClone({
1184 environmentId: selectedProject.environmentId,
1185 input: { projectId: selectedProject.id },
1186 }),
1189 onRetry={() =>
1190 void runCloneAction("Failed to retry clone", () =>
1191 retryProjectClone({
1192 environmentId: selectedProject.environmentId,
1193 input: { projectId: selectedProject.id },
1194 }),
1197 onRemove={() => void removeClonedProject()}
1198 />
1199 </View>
1200 ) : null}
1201 {flow.canChooseWorkspace ? workspaceControls : null}
1202 </View>
1203 ),
1204 editorRef: promptInputRef,
1205 sendBlockedReason: setupBlockReason,
1206 interactionLocked: isComposerInteractionLocked,
1207 }}
1208 canOperateThread={canOperate}
1209 selectedThread={thread}
1210 selectedThreadDetailRef={null}
1211 contentPresentation={{ kind: "ready" }}
1212 screenTone={connectionTone(connectionState)}
1213 connectionError={environmentRuntime?.connectionError ?? null}
1214 environmentLabel={selectedEnvironmentLabel}
1215 feedbackSubmissions={[]}
1216 onDismissFeedback={() => {}}
1217 selectedThreadFeed={[]}
1218 activityRun={null}
1219 activeWorkStartedAt={null}
1220 isCompacting={false}
1221 creationState={null}
1222 activePendingApproval={null}
1223 activePendingApprovals={[]}
1224 respondingApprovalId={null}
1225 activePendingUserInput={null}
1226 activePendingUserInputDrafts={{}}
1227 activePendingUserInputAnswers={null}
1228 respondingUserInputId={null}
1229 connectionStateLabel={connectionState}
1230 activeThreadBusy={false}
1231 canStopThread={false}
1232 queuedRunEdit={null}
1233 composerDraftKey={flow.draftKey}
1234 followUpBehavior="queue"
1235 canSteerActiveTurn={false}
1236 isSavingQueuedEdit={false}
1237 onCancelQueuedRunEdit={() => {}}
1238 onRemoveQueuedEditAttachment={() => {}}
1239 projectWorkspaceRoot={selectedProject.workspaceRoot}
1240 threadCwd={composerWorkspaceCwd}
1241 selectedThreadQueueCount={0}
1242 queuedMessages={[]}
1243 dispatchingMessageId={null}
1244 serverConfig={selectedEnvironmentServerConfig}
1245 usesAutomaticContentInsets
1246 onOpenConnectionEditor={() => navigation.navigate("Connections")}
1247 onChangeDraftMessage={flow.setPrompt}
1248 onPickDraftMedia={handlePickMedia}
1249 onPickDraftFiles={handlePickFiles}
1250 onNativePasteImages={handleNativePasteImages}
1251 onNativePasteText={handleNativePasteText}
1252 onRemoveDraftImage={flow.removeAttachment}
1253 onStopThread={() => {}}
1254 onResumeQueue={null}
1255 onSendMessage={handleStart}
1256 onReconnectEnvironment={() => onReconnectEnvironment(selectedProject.environmentId)}
1257 canSwitchThreadProvider
1258 onUpdateThreadModelSelection={(selection) =>
1259 flow.setSelectedModelKey(`${selection.instanceId}:${selection.model}`, selection.options)
1261 onUpdateThreadRuntimeMode={flow.setRuntimeMode}
1262 onUpdateThreadInteractionMode={flow.planModeEnabled ? flow.setInteractionMode : undefined}
1263 onRespondToApproval={async () => {}}
1264 onSelectUserInputOption={() => {}}
1265 onChangeUserInputCustomAnswer={() => {}}
1266 onSubmitUserInput={async () => {}}
1267 onDismissUserInput={async () => {}}
1268 />
1269 </>
1270 );