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

NewTaskDraftScreen.tsx

1,167 lines44.6 KB

1import { T, useGT, useMessages, Var } from "gt-react-native";
2import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3import { DraftEnvironmentControl } from "./DraftEnvironmentControl";
4import { NativeScrollEdgeEffectsContext } from "../../native/NativeScrollViewMarker";
5import { DraftThreadHeader } from "./DraftThreadHeader";
6import { useComposerAttachmentActions } from "../../state/use-composer-attachment-actions";
7import { useWorkspaceBackNavigation } from "../layout/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 { runtimeConnectionErrorText } from "../connection/environmentStatusText";
15import { AppBar } from "../../components/ui/AppBar";
16import { ThreadId } from "@t3tools/contracts";
17​
18import * as Dialog from "../../components/ui/Dialog";
19import { useAtomValue } from "@effect/atom-react";
20import * as Cause from "effect/Cause";
21import { AsyncResult } from "effect/reactivity";
22import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping";
23import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
24import {
25 CommonActions,
26 StackActions,
27 useIsFocused,
28 useNavigation,
29 usePreventRemove,
30 useRoute,
31} from "@react-navigation/native";
32import { useEffect, useRef, useState } from "react";
33import { Platform, Pressable, View } from "react-native";
34import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
35import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
36​
37import {
38 AuthOrchestrationOperateScope,
39 DEFAULT_PROVIDER_INTERACTION_MODE,
40 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
41 resolveEnvironmentMachineKind,
42} from "@t3tools/contracts";
43​
44import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
45import { composerContextImportsAtom } from "../../state/use-composer-drafts";
46import { abortComposerDraftOperations } from "../../state/composerDraftOperations";
47import { composerContextSendBlockReason } from "../../lib/composerContext";
48import { ComposerInlineControl } from "../../components/ComposerToolbar";
49​
50import {
51 composerAttachmentUploadBlockReason,
52 composerAttachmentsStillUploading,
53 composerAttachmentUploadsAtom,
54} from "../../state/composer-attachment-uploads";
55​
56import { SymbolView } from "../../components/ui/AppSymbol";
57import { AppText as Text } from "../../components/ui/AppText";
58import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences";
59​
60import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
61​
62import {
63 clearComposerDraftContent,
64 getComposerDraftSnapshot,
65 updateComposerDraftSettings,
66 scheduleUnusedComposerAttachmentCleanup,
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 {
96 handedShareIdAtom,
97 incomingShareImports,
98 noHandedShareIdAtom,
99 useIncomingShare,
100} from "../sharing/IncomingShareProvider";
101import { idleShareFlagAtom, idleShareImportPhaseAtom } from "./incomingShareImport";
102import { newTaskFlowKey } from "./new-task-flow-state";
103import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
104import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";
105import { appAtomRegistry } from "../../state/atom-registry";
106import { mobilePreferencesAtom } from "../../state/preferences";
107​
108import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
109​
110// Below this (keyboard up on iPad, phone landscape) the hero cannot fit above the composer,
111// so the project and environment pickers move into the composer controls instead.
112const SHORT_DRAFT_VIEWPORT_HEIGHT = 380;
113const HEADING_PROJECT_SLOT = "\uE000";
114​
115function NewTaskWorkspaceIcon(props: {
116 readonly workspaceMode: "local" | "worktree";
117 readonly worktreePath: string | null;
118 readonly size: number;
119}) {
120 if (props.workspaceMode === "local" && props.worktreePath === null) {
121 return (
122 <SymbolView
123 name="folder"
124 size={props.size}
125 tintColorClassName="accent-icon-muted"
126 type="monochrome"
127 />
128 );
129 }
130​
131 const boxSize = (14 * props.size) / 16;
132 return (
133 <View
134 className="size-4"
135 style={Platform.OS === "android" ? { width: boxSize, height: boxSize } : undefined}
136 >
137 <SymbolView
138 name="folder"
139 size={props.size}
140 tintColorClassName="accent-icon-muted"
141 type="monochrome"
142 />
143 <View
144 className="absolute -right-1 -bottom-1"
145 style={
146 Platform.OS === "android" ? { right: -boxSize / 4, bottom: -boxSize / 4 } : undefined
147 }
148 >
149 <SymbolView
150 name="arrow.triangle.branch"
151 size={Math.round((9 * props.size) / 16)}
152 tintColorClassName="accent-icon-muted"
153 type="monochrome"
154 />
155 </View>
156 </View>
157 );
159​
160export function NewTaskDraftScreen(props: {
161 readonly initialProjectRef?: {
162 readonly environmentId?: string;
163 readonly projectId?: string;
164 readonly branch?: string | null;
165 readonly worktreePath?: string | null;
166 readonly cloning?: boolean;
167 };
168 readonly draftId?: string;
169 readonly incomingShareId?: string;
170}) {
171 const gt = useGT();
172 const m = useMessages();
173 const [creationMetadata] = useState(makeTurnCommandMetadata);
174 const projects = useProjects();
175 const flow = useNewTaskFlow();
176 const navigation = useNavigation();
177 const isFocused = useIsFocused();
178 const goBack = useWorkspaceBackNavigation();
179 const currentRoute = useRoute();
180 const flowKey = newTaskFlowKey(currentRoute);
181 const { getShare, isLoading: isIncomingShareInboxLoading } = useIncomingShare();
182 const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
183 // selectedProject falls back to the environment's first project; remember only a chosen one.
184 useRememberThreadProject(
185 selectedProject &&
186 selectedProjectKey === scopedProjectKey(selectedProject.environmentId, selectedProject.id)
187 ? selectedProject
188 : null,
189 );
190 const selectedProjectLabel = (() => {
191 if (!selectedProject) return null;
192 const scope = projectScopes.find((candidate) =>
193 candidate.projectRefs.some(
194 (ref) =>
195 ref.environmentId === selectedProject.environmentId &&
196 ref.projectId === selectedProject.id,
197 ),
198 );
199 return scope?.title ?? selectedProject.title;
200 })();
201 const { onReconnectEnvironment } = useRemoteConnections();
202 const environmentRuntime = useRemoteEnvironmentRuntime(selectedProject?.environmentId ?? null);
203 const connectionState = environmentRuntime?.connectionState ?? "offline";
204 const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
205 selectedProject?.environmentId ?? null,
206 );
207 const environmentConnected = connectionState === "connected";
208 const canOperate = useEnvironmentScope(
209 selectedProject?.environmentId ?? null,
210 AuthOrchestrationOperateScope,
211 );
212 const projectCloneState = useProjectClone(
213 selectedProject
214 ? { environmentId: selectedProject.environmentId, projectId: selectedProject.id }
215 : null,
216 );
217 const projectClone = projectCloneState === "pending" ? null : projectCloneState;
218 const awaitingKnownClone =
219 projectCloneState === "pending" &&
220 props.initialProjectRef?.cloning === true &&
221 selectedProject !== null &&
222 selectedProject.id === props.initialProjectRef.projectId &&
223 selectedProject.environmentId === props.initialProjectRef.environmentId;
224 const cloneBlocksStart =
225 awaitingKnownClone || (projectClone !== null && projectClone.phase !== "done");
226 const cancelProjectClone = useAtomCommand(sourceControlEnvironment.cancelProjectClone, {
227 reportFailure: false,
228 });
229 const retryProjectClone = useAtomCommand(sourceControlEnvironment.retryProjectClone, {
230 reportFailure: false,
231 });
232 const runCloneAction = async (
233 title: string,
234 action: () => Promise<AsyncResult.AsyncResult<unknown, unknown>>,
235 ) => {
236 const result = await action();
237 if (AsyncResult.isFailure(result)) {
238 const error = Cause.squash(result.cause);
239 Dialog.alert(title, errorDisplayMessage(error, m) ?? gt("An error occurred."));
240 }
241 };
242 const deleteProject = useAtomCommand(projectEnvironment.delete, { reportFailure: false });
243 const removeClonedProject = async () => {
244 if (!selectedProject) return;
245 const removed = selectedProject;
246 const result = await deleteProject({
247 environmentId: removed.environmentId,
248 input: { projectId: removed.id },
249 });
250 if (AsyncResult.isFailure(result)) {
251 const error = Cause.squash(result.cause);
252 Dialog.alert(
253 gt("Failed to remove project"),
254 errorDisplayMessage(error, m) ?? gt("An error occurred."),
255 );
256 return;
257 }
258 if (flow.getSelectedProjectKey() === scopedProjectKey(removed.environmentId, removed.id)) {
259 navigation.dispatch(StackActions.replace("Home"));
260 }
261 };
262 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
263 const attachmentBlockReason = selectedProject
264 ? composerAttachmentUploadBlockReason(
265 {
266 environmentId: selectedProject.environmentId,
267 attachments: flow.attachments,
268 connected: environmentConnected,
269 serverConfig: selectedEnvironmentServerConfig,
270 states: uploadStates,
271 },
272 m,
273 )
274 : null;
275 const attachmentsUploading =
276 environmentConnected &&
277 selectedProject !== null &&
278 composerAttachmentsStillUploading({
279 environmentId: selectedProject.environmentId,
280 attachments: flow.attachments,
281 serverConfig: selectedEnvironmentServerConfig,
282 states: uploadStates,
283 });
284 const queuesInsteadOfStarting = !environmentConnected || attachmentsUploading;
285 const promptInputRef = useRef<ComposerEditorHandle>(null);
286 const loadedBranchesProjectKeyRef = useRef<string | null>(null);
287 const [isReturningToProjectPicker, setIsReturningToProjectPicker] = useState(false);
288 const incomingShare = props.incomingShareId ? getShare(props.incomingShareId) : null;
289 const requestedInitialProjectAvailable = Boolean(
290 props.initialProjectRef?.environmentId &&
291 props.initialProjectRef.projectId &&
292 projects.some(
293 (project) =>
294 project.environmentId === props.initialProjectRef?.environmentId &&
295 project.id === props.initialProjectRef?.projectId,
296 ),
297 );
298 // A route naming a draft that is gone, or whose project is gone, also
299 // returns to the picker; a draft that survives goes along with it.
300 const unopenableRouteDraftKind =
301 props.draftId !== undefined && flow.unopenableRouteDraft?.draftId === props.draftId
302 ? flow.unopenableRouteDraft.kind
303 : null;
304 const pickerDraftId = unopenableRouteDraftKind === "pickProject" ? props.draftId : undefined;
305 const isProjectPickerReturnActive =
306 (isReturningToProjectPicker && !requestedInitialProjectAvailable) ||
307 unopenableRouteDraftKind !== null;
308 const isIncomingShareAwaitingServerConfig = Boolean(
309 incomingShare?.attachments.some((attachment) => attachment.type === "file") &&
310 selectedEnvironmentServerConfig === null,
311 );
312 const routeImportedShare = useAtomValue(
313 flowKey !== undefined && props.incomingShareId
314 ? incomingShareImports.importedAtom(flowKey, props.incomingShareId)
315 : idleShareFlagAtom,
316 );
317 const hasImportedIncomingShare = Boolean(
318 props.incomingShareId &&
319 (routeImportedShare ||
320 (flow.draftKey &&
321 getComposerDraftSnapshot(flow.draftKey).importedShareIds?.includes(props.incomingShareId))),
322 );
323 const isIncomingShareUnavailable = Boolean(
324 props.incomingShareId &&
325 !isIncomingShareInboxLoading &&
326 !incomingShare &&
327 !hasImportedIncomingShare,
328 );
329 // The route's share was prepared for the draft's initial project; a handed share joins whichever project is selected.
330 const importTargetFor = (share: typeof incomingShare, requireInitialProject: boolean) => {
331 if (flowKey === undefined || !flow.draftKey || !selectedProject || !share) return null;
332 if (
333 share.attachments.some((attachment) => attachment.type === "file") &&
334 selectedEnvironmentServerConfig === null
335 ) {
336 return null;
337 }
338 const initialEnvironmentId = props.initialProjectRef?.environmentId;
339 const initialProjectId = props.initialProjectRef?.projectId;
340 if (
341 requireInitialProject &&
342 initialEnvironmentId &&
343 initialProjectId &&
344 (selectedProject.environmentId !== initialEnvironmentId ||
345 selectedProject.id !== initialProjectId)
346 ) {
347 return null;
348 }
349 return {
350 flowKey,
351 routeKey: currentRoute.key,
352 draftKey: flow.draftKey,
353 destination: {
354 environmentId: String(selectedProject.environmentId),
355 projectId: String(selectedProject.id),
356 },
357 shareId: share.id,
358 };
359 };
360 const shareImportTarget = props.incomingShareId ? importTargetFor(incomingShare, true) : null;
361 const handedShareId = useAtomValue(
362 flowKey === undefined ? noHandedShareIdAtom : handedShareIdAtom(flowKey),
363 );
364 // A share handed to this open draft merges in once the route's own share has finished. Not while
365 // submitting: the post-submit clear would drop content the queued message doesn't contain.
366 const handedShareImportTarget =
367 handedShareId && handedShareId !== props.incomingShareId && !incomingShare && !flow.submitting
368 ? importTargetFor(getShare(handedShareId), false)
369 : null;
370 useAtomValue(
371 handedShareImportTarget === null
372 ? idleShareImportPhaseAtom
373 : incomingShareImports.phaseAtom(handedShareImportTarget),
374 );
375 const shareImportPhase = useAtomValue(
376 shareImportTarget === null
377 ? idleShareImportPhaseAtom
378 : incomingShareImports.phaseAtom(shareImportTarget),
379 );
380 // Locks on the route, not the target: the target turns null when server config
381 // drops or the project stops matching, while the import keeps writing the draft.
382 const isImportingShare = useAtomValue(
383 flowKey === undefined ? idleShareFlagAtom : incomingShareImports.inFlightAtom(flowKey),
384 );
385 const isIncomingShareTransferPending = Boolean(
386 incomingShare && shareImportPhase !== "cancelled" && !isIncomingShareAwaitingServerConfig,
387 );
388 // A failed import waits in a modal alert, and a cancel finishes its undo even
389 // after the route leaves, so neither holds the route: the cancel can leave as
390 // soon as it is done.
391 const isIncomingShareHoldingRoute =
392 isIncomingShareTransferPending &&
393 shareImportPhase !== "failed" &&
394 shareImportPhase !== "cancelling";
395 const contextImports = useAtomValue(composerContextImportsAtom);
396 const isImportingContext = flow.draftKey ? contextImports[flow.draftKey] === true : false;
397 const isComposerInteractionLocked =
398 isIncomingShareTransferPending || flow.submitting || isImportingContext;
399 const { environments, selectedEnvironmentId, switchEnvironment, switchingToEnvironmentId } = flow;
400 const cycleEnvironment = () => {
401 if (isComposerInteractionLocked) return true;
402 const next = nextEnvironmentId(environments, switchingToEnvironmentId ?? selectedEnvironmentId);
403 if (next !== null) void switchEnvironment(next);
404 return true;
405 };
406 const cycleEnvironmentCommands = environments.length > 1 ? (["cycleHost"] as const) : [];
407 useHardwareKeyboardCommand(cycleEnvironmentCommands, cycleEnvironment);
408 const preventRemove =
409 (isIncomingShareHoldingRoute && !isProjectPickerReturnActive) || flow.submitting;
410 usePreventRemove(preventRemove, () => undefined);
411 const isIncomingShareReady =
412 !props.incomingShareId ||
413 (hasImportedIncomingShare && !incomingShare) ||
414 isIncomingShareUnavailable;
415 const appliedInitialProjectKeyRef = useRef<string | null>(null);
416 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- ends the picker return once the project arrives, else replaces the route with the picker next frame
417 useEffect(() => {
418 if (isReturningToProjectPicker && requestedInitialProjectAvailable) {
419 // oxlint-disable-next-line react/set-state-in-effect -- Ends the return-to-picker flow once the requested project arrives from the catalog.
420 setIsReturningToProjectPicker(false);
421 }
422 if (!isProjectPickerReturnActive) {
423 return;
424 }
425 // Wait for usePreventRemove to disable before replacing, or the transfer guard swallows the fallback.
426 const frame = requestAnimationFrame(() => {
427 navigation.dispatch(
428 StackActions.replace("NewTaskProject", {
429 incomingShareId: props.incomingShareId,
430 draftId: pickerDraftId,
431 }),
432 );
433 });
434 return () => cancelAnimationFrame(frame);
435 }, [
436 isProjectPickerReturnActive,
437 isReturningToProjectPicker,
438 navigation,
439 pickerDraftId,
440 props.incomingShareId,
441 requestedInitialProjectAvailable,
442 ]);
443​
444 const lastInitialProjectRefRef = useRef(props.initialProjectRef);
445 const initialPickerRef = useRef<"open" | "dismissed" | null>(null);
446​
447 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- applies the route or catalog project to the draft once projects load, or opens the picker in the navigator
448 useEffect(() => {
449 if (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 project once or picker changes would immediately revert.
467 const directProjectKey = `${directProject.environmentId}:${directProject.id}`;
468 if (appliedInitialProjectKeyRef.current === directProjectKey) {
469 return;
470 }
471 // setProject creates the draft, so it also runs when the fallback already shows this project.
472 const showsDirectProject =
473 flow.draftKey !== null &&
474 selectedProject?.environmentId === directProject.environmentId &&
475 selectedProject.id === directProject.id;
476 if (props.initialProjectRef?.branch) {
477 if (!showsDirectProject || !flow.draftKey) {
478 setProject(directProject);
479 return;
480 }
481 // Checkout completed before mount; local mode reuses it while worktree mode would create another.
482 updateComposerDraftSettings(flow.draftKey, {
483 workspaceSelection: {
484 mode: "local",
485 branch: props.initialProjectRef.branch,
486 worktreePath: props.initialProjectRef.worktreePath ?? null,
487 startFromOrigin: false,
488 },
489 });
490 }
491 appliedInitialProjectKeyRef.current = directProjectKey;
492 if (showsDirectProject) return;
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 preferences = appAtomRegistry.get(mobilePreferencesAtom);
505 const saved = AsyncResult.isSuccess(preferences) ? preferences.value : undefined;
506 const selection = resolveDraftProjectSelection(
507 selectedProjectKey,
508 projects,
509 pickableProjectGroups(projectScopes),
510 {
511 incomingShareId: props.incomingShareId,
512 pickerClosed: initialPickerRef.current === "open" && isFocused,
513 useLastProject: saved?.useLastProjectForNewThreads,
514 lastProject: saved?.lastThreadProject,
515 },
516 );
517 if (selection.kind === "preserve") {
518 initialPickerRef.current = null;
519 return;
520 }
521 if (selection.kind === "select") {
522 setProject(selection.project);
523 return;
524 }
525 if (selection.kind === "dismiss") {
526 initialPickerRef.current = "dismissed";
527 goBack();
528 return;
529 }
530 // Open the first picker once; catalog updates must not push it again over a cancelled draft.
531 if (initialPickerRef.current !== null) {
532 return;
533 }
534 initialPickerRef.current = "open";
535 navigation.dispatch(CommonActions.navigate("NewTaskProject"));
536 }, [
537 goBack,
538 isFocused,
539 projectScopes,
540 projects,
541 flow.draftKey,
542 props.initialProjectRef,
543 props.incomingShareId,
544 props.draftId,
545 navigation,
546 selectedProject,
547 selectedProjectKey,
548 setProject,
549 ]);
550​
551 const { loadBranches } = flow;
552 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- requests the selected project's branch list from the server once per project
553 useEffect(() => {
554 if (!selectedProject) {
555 loadedBranchesProjectKeyRef.current = null;
556 return;
557 }
558 const projectKey = `${selectedProject.environmentId}:${selectedProject.id}`;
559 if (loadedBranchesProjectKeyRef.current === projectKey) {
560 return;
561 }
562 loadedBranchesProjectKeyRef.current = projectKey;
563 loadBranches();
564 }, [loadBranches, selectedProject]);
565​
566 const selectedEnvironmentLabel =
567 flow.environments.find(
568 (environment) => environment.environmentId === flow.selectedEnvironmentId,
569 )?.environmentLabel ?? gt("Environment");
570 const availableCurrentBranchName =
571 flow.availableBranches.find((branch) => branch.current)?.name ??
572 flow.availableBranches.find((branch) => branch.isDefault)?.name ??
573 null;
574 const selectedBranchName = resolveProjectThreadCreationBranch({
575 workspaceMode: flow.workspaceMode,
576 selectedBranch:
577 flow.selectedBranchName ??
578 (flow.workspaceMode === "worktree" ? availableCurrentBranchName : null),
579 currentCheckoutBranch: flow.currentCheckoutBranchName,
580 });
581 const selectedBranchLabel = resolveNewTaskBranchLabel(
582 {
583 branchName: selectedBranchName,
584 startFromOrigin: flow.startFromOrigin,
585 workspaceMode: flow.workspaceMode,
586 pullRequestReference: flow.pullRequestReference,
587 },
588 m,
589 );
590 const workspaceLabel = resolveNewTaskWorkspaceLabel(
591 {
592 workspaceMode: flow.workspaceMode,
593 worktreePath: flow.selectedWorktreePath,
594 },
595 m,
596 );
597 const showBranchLoading =
598 environmentConnected && flow.branchesLoading && flow.availableBranches.length === 0;
599​
600 const {
601 onPickDraftMedia: handlePickMedia,
602 onPickDraftFiles: handlePickFiles,
603 onNativePasteImages: handleNativePasteImages,
604 onNativePasteText: handleNativePasteText,
605 } = useComposerAttachmentActions({
606 draftKey: flow.draftKey,
607 serverConfig: selectedEnvironmentServerConfig,
608 locked: isComposerInteractionLocked,
609 });
610​
611 async function handleStart(): Promise<import("@t3tools/contracts").MessageId | null> {
612 const selectedProject = flow.selectedProject;
613 const draftKey = flow.draftKey;
614 if (
615 !selectedProject ||
616 !draftKey ||
617 cloneBlocksStart ||
618 !isIncomingShareReady ||
619 isImportingShare ||
620 isComposerInteractionLocked
621 ) {
622 return null;
623 }
624 if (
625 environmentConnected &&
626 !readEnvironmentScope(selectedProject.environmentId, AuthOrchestrationOperateScope)
627 ) {
628 return null;
629 }
630 const draft = getComposerDraftSnapshot(draftKey);
631 if (appAtomRegistry.get(composerContextImportsAtom)[draftKey]) return null;
632 const modelSelection =
633 resolveSelectableModelSelection(
634 selectedEnvironmentServerConfig,
635 draft.modelSelection ?? null,
636 selectedProject.id,
637 ) ?? flow.selectedModel;
638 const workspaceSelection = flow.resolveWorkspaceSelection(draft.workspaceSelection);
639 const workspaceMode = workspaceSelection.mode;
640 const selectedBranchName = workspaceSelection.branch;
641 const initialMessageText = draft.text.trim();
642​
643 if (
644 attachmentBlockReason !== null ||
645 !modelSelection ||
646 (initialMessageText.length === 0 && draft.attachments.length === 0) ||
647 flow.submitting ||
648 (workspaceMode === "worktree" && flow.isGitRepo && !selectedBranchName)
649 ) {
650 return null;
651 }
652 if (
653 environmentConnected &&
654 isModelSelectionUnavailable(
655 selectedEnvironmentServerConfig,
656 modelSelection,
657 selectedProject.id,
658 )
659 ) {
660 const { title, detail } = describeUnavailableModelSelection(
661 selectedEnvironmentServerConfig,
662 modelSelection,
663 selectedProject.id,
664 );
665 Dialog.alert(title, detail);
666 return null;
667 }
668 // Recovery may retain over-cap attachments; block send before uploading a turn the server would reject.
669 if (draft.attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
670 Dialog.alert(
671 gt("Too many attachments"),
672 gt("Remove attachments until there are at most {max}.", {
673 max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
674 }),
675 );
676 return null;
677 }
678​
679 const contextBlockReason = composerContextSendBlockReason(draft.context);
680 if (contextBlockReason) {
681 Dialog.alert(gt("Too much context"), contextBlockReason);
682 return null;
683 }
684 const strandedThread = threadContextsOutsideEnvironment({
685 text: draft.text,
686 records: draft.context?.records ?? [],
687 environmentId: selectedProject.environmentId,
688 linkedEnvironments: flow.linkedEnvironments,
689 })[0];
690 if (strandedThread) {
691 const owner = flow.environments.find(
692 (environment) => environment.environmentId === strandedThread.environmentId,
693 )?.environmentLabel;
694 Dialog.alert(
695 gt("Attached thread unavailable"),
696 owner === undefined
697 ? gt(
698 '"{title}" is on another machine. Switch back to its machine or remove it from the draft.',
699 { title: strandedThread.title },
700 )
701 : gt(
702 '"{title}" is on another machine. Switch back to {owner} or remove it from the draft.',
703 { title: strandedThread.title, owner },
704 ),
705 );
706 return null;
707 }
708​
709 const message = flow.buildPendingTaskMessage(creationMetadata, {
710 currentCheckoutBranch: queuesInsteadOfStarting ? null : flow.currentCheckoutBranchName,
711 });
712 if (!message) {
713 return null;
714 }
715 // Persist locally before clearing or leaving the draft; server setup runs on the thread.
716 flow.setSubmitting(true);
717 const queued = await settlePromise(() => enqueueThreadOutboxMessage(message));
718 flow.setSubmitting(false);
719 if (AsyncResult.isFailure(queued)) {
720 const error = squashAtomCommandFailure(queued);
721 Dialog.alert(
722 gt("Could not queue task"),
723 errorDisplayMessage(error, m) ?? gt("The task could not be saved to the outbox."),
724 );
725 return null;
726 }
727 promptInputRef.current?.blur();
728 navigation.dispatch(
729 CommonActions.setParams(
730 submittedThreadParams(String(message.environmentId), String(message.threadId)),
731 ),
732 );
733 // The composer has moved to the submitted thread; a pick still converting
734 // would otherwise resurrect this draft.
735 abortComposerDraftOperations(draftKey);
736 const draftSnapshot = getComposerDraftSnapshot(draftKey);
737 // The queued message owns the attachments now, so the sweep is deferred
738 // until the write confirms it.
739 clearComposerDraftContent(draftKey, {
740 clearModelSelection: true,
741 clearWorkspaceSelection: true,
742 deferAttachmentCleanup: true,
743 });
744 scheduleUnusedComposerAttachmentCleanup(draftSnapshot.attachments);
745 return message.messageId;
746 }
747​
748 // Keep the current surface until the local draft selection is ready. Publishing
749 // an empty loading surface here flashes between two already-cached threads.
750 if (!selectedProject) return null;
751​
752 const setupBlockReason =
753 isIncomingShareReady && !isImportingShare
754 ? cloneBlocksStart
755 ? gt("Wait for the project clone to finish.")
756 : flow.submitting
757 ? gt("Starting the thread…")
758 : flow.workspaceMode === "worktree" &&
759 (!flow.isGitRepoKnown || (flow.isGitRepo && !flow.selectedBranchName))
760 ? gt("Choose a base branch before creating a worktree.")
761 : null
762 : gt("Wait for shared content to finish importing.");
763 const chooseProject = () => {
764 if (isComposerInteractionLocked) {
765 return;
766 }
767 promptInputRef.current?.blur();
768 void KeyboardController.dismiss({ animated: true });
769 navigation.navigate("NewTaskProject", { incomingShareId: props.incomingShareId });
770 };
771 const openContextPicker = (
772 routeName: "NewTaskBranch" | "NewTaskEnvironment" | "NewTaskRepositories",
773 ) => {
774 if (isComposerInteractionLocked) {
775 return;
776 }
777 promptInputRef.current?.blur();
778 void KeyboardController.dismiss({ animated: true });
779 navigation.navigate(routeName);
780 };
781​
782 const environmentControl = (
783 <DraftEnvironmentControl
784 connectionState={connectionState}
785 label={selectedEnvironmentLabel}
786 machineKind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}
787 disabled={isComposerInteractionLocked}
788 onChooseEnvironment={() => openContextPicker("NewTaskEnvironment")}
789 />
790 );
791 const shareUnavailableNotice = isIncomingShareUnavailable ? (
792 <Text textRole="footnote" className="text-center text-foreground-muted">
793 <T>The shared content is no longer in the inbox. You can continue editing this task draft.</T>
794 </Text>
795 ) : null;
796 const headingParts = gt("What should we build in {project}?", {
797 project: HEADING_PROJECT_SLOT,
798 }).split(HEADING_PROJECT_SLOT);
799 const headingBefore = headingParts[0] ?? "";
800 const headingAfter = headingParts[1] ?? "";
801 const headingBreak = headingBefore.trimEnd().lastIndexOf(" ");
802 const headingFirstLine = headingBreak < 0 ? headingBefore : headingBefore.slice(0, headingBreak);
803 const headingLead = headingBreak < 0 ? "" : headingBefore.slice(headingBreak + 1);
804 const hero = flow.isScratchDraft ? (
805 <View className="items-center gap-2 px-6" testID="new-task-hero">
806 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
807 <T>What should we work on?</T>
808 </Text>
809 <View className="flex-row flex-wrap items-center justify-center gap-x-1">
810 <ComposerInlineControl
811 accessibilityHint={gt("Opens the project picker")}
812 accessibilityLabel={gt("No project")}
813 chevronDirection="right"
814 disabled={isComposerInteractionLocked}
815 icon="folder"
816 label={gt("No project")}
817 onPress={chooseProject}
818 />
819 {environmentControl}
820 </View>
821 {shareUnavailableNotice}
822 </View>
823 ) : (
824 <View className="items-center gap-6 px-6" testID="new-task-hero">
825 <View className="w-full items-center gap-1.5">
826 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
827 {headingFirstLine}
828 </Text>
829 <View className="max-w-full flex-row items-center justify-center">
830 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">
831 {headingLead}
832 </Text>
833 <Pressable
834 accessibilityHint={gt("Opens the project picker")}
835 accessibilityLabel={selectedProjectLabel ?? selectedProject.title}
836 accessibilityRole="button"
837 disabled={isComposerInteractionLocked}
838 onPress={chooseProject}
839 className="min-w-0 max-w-[250px] border-b border-foreground-muted active:opacity-65"
840 >
841 <Text
842 className="text-2xl font-t3-medium tracking-tight text-foreground"
843 numberOfLines={1}
844 >
845 {selectedProjectLabel ?? selectedProject.title}
846 </Text>
847 </Pressable>
848 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">
849 {headingAfter}
850 </Text>
851 </View>
852 </View>
853​
854 {environmentControl}
855 {shareUnavailableNotice}
856 </View>
857 );
858 // The nested hero scroll view does not receive UIKit's automatic navigation inset in split columns.
859 const heroViewport = (headerInset: number, bottomInset: number, viewportHeight: number) =>
860 viewportHeight < SHORT_DRAFT_VIEWPORT_HEIGHT ? null : (
861 <NativeScrollEdgeEffectsContext
862 value={{ top: "hidden", bottom: "hidden", left: "hidden", right: "hidden" }}
863 >
864 <View
865 collapsable={false}
866 style={{
867 position: "absolute",
868 top: headerInset,
869 bottom: bottomInset,
870 left: 0,
871 right: 0,
872 overflow: "hidden",
873 }}
874 >
875 <ScrollView
876 alwaysBounceVertical={false}
877 className="flex-1"
878 contentInsetAdjustmentBehavior="never"
879 contentContainerClassName="grow items-center"
880 contentContainerStyle={{ paddingVertical: 24 }}
881 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
882 keyboardShouldPersistTaps="handled"
883 showsVerticalScrollIndicator={false}
884 style={{ flex: 1 }}
885 testID="new-task-hero-scroll"
886 >
887 <View style={{ flexGrow: 1 }} />
888 {hero}
889 <View style={{ flexGrow: 2 }} />
890 </ScrollView>
891 </View>
892 </NativeScrollEdgeEffectsContext>
893 );
894​
895 const contextProjectLabel = flow.isScratchDraft
896 ? gt("No project")
897 : (selectedProjectLabel ?? selectedProject.title);
898 const contextControls = (
899 <View className="flex-row items-center gap-1 px-2">
900 <View className="min-w-0 shrink">
901 <ComposerInlineControl
902 accessibilityHint={gt("Opens the project picker")}
903 accessibilityLabel={gt("Project: {project}", { project: contextProjectLabel })}
904 chevronDirection="right"
905 disabled={isComposerInteractionLocked}
906 icon="folder"
907 label={contextProjectLabel}
908 maxWidth="100%"
909 onPress={chooseProject}
910 />
911 </View>
912 <View className="min-w-0 shrink">
913 <ComposerInlineControl
914 accessibilityLabel={
915 connectionState === "connected"
916 ? gt("Choose environment, {label}, Connected", { label: selectedEnvironmentLabel })
917 : gt("Choose environment, {label}, Offline", { label: selectedEnvironmentLabel })
918 }
919 chevronDirection="right"
920 disabled={isComposerInteractionLocked}
921 renderIcon={(size) => (
922 <EnvironmentMachineSymbol
923 kind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}
924 size={size}
925 tintColorClassName="accent-icon-muted"
926 />
927 )}
928 label={selectedEnvironmentLabel}
929 maxWidth="100%"
930 onPress={() => openContextPicker("NewTaskEnvironment")}
931 suffix={
932 connectionState === "connected" ? null : (
933 <ConnectionStatusDot state="error" pulse={false} size={6} />
934 )
935 }
936 />
937 </View>
938 </View>
939 );
940​
941 const startsNewWorktree = flow.workspaceMode === "worktree";
942 const offersRepositoryChoice =
943 startsNewWorktree && (flow.worktreeRepositoryChoices?.length ?? 0) > 0;
944 const workspaceControls = (
945 <View className="flex-row flex-wrap items-center gap-x-1 px-2">
946 <ComposerInlineControl
947 accessibilityHint={
948 flow.workspaceMode === "local"
949 ? gt("Switches to a new worktree")
950 : gt("Switches to the current checkout")
951 }
952 accessibilityLabel={workspaceLabel}
953 disabled={isComposerInteractionLocked || !(flow.isGitRepo || flow.tracksGitRepositories)}
954 renderIcon={(size) => (
955 <NewTaskWorkspaceIcon
956 workspaceMode={flow.workspaceMode}
957 worktreePath={flow.selectedWorktreePath}
958 size={size}
959 />
960 )}
961 label={workspaceLabel}
962 maxWidth="100%"
963 onPress={() => flow.setWorkspaceMode(flow.workspaceMode === "local" ? "worktree" : "local")}
964 showChevron={false}
965 />
966​
967 {offersRepositoryChoice ? (
968 <View className="min-w-0 shrink">
969 <ComposerInlineControl
970 accessibilityHint={gt("Chooses the repositories the new worktree holds")}
971 accessibilityLabel={gt("Repositories in the new worktree: {selection}", {
972 selection: flow.worktreeRepositorySelection.label,
973 })}
974 chevronDirection="right"
975 disabled={isComposerInteractionLocked}
976 icon="folder.badge.plus"
977 label={flow.worktreeRepositorySelection.label}
978 maxWidth="100%"
979 onPress={() => openContextPicker("NewTaskRepositories")}
980 {...(flow.worktreeRepositorySelection.needsChoice ? { tone: "warning" as const } : {})}
981 />
982 </View>
983 ) : null}
984 {startsNewWorktree && !flow.isGitRepo ? (
985 <View className="min-h-8 min-w-0 shrink justify-center px-2">
986 <Text className="text-sm text-foreground-muted" numberOfLines={1}>
987 <T>Each repository starts from its own default branch</T>
988 </Text>
989 </View>
990 ) : (
991 <View className="min-w-0 shrink">
992 <ComposerInlineControl
993 accessibilityLabel={
994 startsNewWorktree
995 ? gt("Base branch: {branch}", { branch: selectedBranchLabel })
996 : gt("Branch: {branch}", { branch: selectedBranchLabel })
997 }
998 chevronDirection="right"
999 disabled={isComposerInteractionLocked || !flow.isGitRepo}
1000 icon="arrow.triangle.branch"
1001 label={showBranchLoading ? gt("Loading branches…") : selectedBranchLabel}
1002 maxWidth="100%"
1003 onPress={() => openContextPicker("NewTaskBranch")}
1004 />
1005 </View>
1006 )}
1007 </View>
1008 );
1009​
1010 const draftControls = (viewportHeight: number) => (
1011 <View className="pb-1">
1012 {projectClone && projectClone.phase !== "done" && selectedProject ? (
1013 <View className="px-1 pb-2">
1014 <ProjectCloneBanner
1015 clone={projectClone}
1016 onCancel={() =>
1017 void runCloneAction(gt("Failed to cancel clone"), () =>
1018 cancelProjectClone({
1019 environmentId: selectedProject.environmentId,
1020 input: { projectId: selectedProject.id },
1021 }),
1024 onRetry={() =>
1025 void runCloneAction(gt("Failed to retry clone"), () =>
1026 retryProjectClone({
1027 environmentId: selectedProject.environmentId,
1028 input: { projectId: selectedProject.id },
1029 }),
1032 onRemove={() => void removeClonedProject()}
1033 />
1034 </View>
1035 ) : null}
1036 {viewportHeight < SHORT_DRAFT_VIEWPORT_HEIGHT ? contextControls : null}
1037 {flow.canChooseWorkspace ? workspaceControls : null}
1038 </View>
1039 );
1040​
1041 if (!flow.selectedModel) {
1042 return (
1043 <ThreadScreenFallback header={<AppBar title={gt("New thread")} onBack={goBack} />}>
1044 <KeyboardStickyView pointerEvents="box-none" style={{ flex: 1 }}>
1045 <View pointerEvents="box-none" className="flex-1 justify-end gap-3 p-4">
1046 {environmentControl}
1047 <Text className="text-foreground-muted">
1048 {environmentConnected && selectedEnvironmentServerConfig ? (
1049 <T>
1050 Your draft is saved on this device. <Var>{selectedEnvironmentLabel}</Var> has no
1051 model available. Install or sign in to a provider there to choose one.
1052 </T>
1053 ) : (
1054 <T>
1055 Your draft is saved on this device. Connect to an environment to choose its first
1056 model.
1057 </T>
1058 )}
1059 </Text>
1060 <ComposerEditor
1061 draftKey={flow.draftKey}
1062 value={flow.prompt}
1063 onChangeText={flow.setPrompt}
1064 placeholder={gt("Ask anything")}
1065 multiline
1066 style={{ minHeight: 64 }}
1067 />
1068 </View>
1069 </KeyboardStickyView>
1070 </ThreadScreenFallback>
1071 );
1073 const thread = draftThreadShell(
1075 environmentId: selectedProject.environmentId,
1076 projectId: selectedProject.id,
1077 threadId: ThreadId.make(creationMetadata.threadId),
1078 modelSelection: flow.selectedModel,
1079 runtimeMode: flow.runtimeMode,
1080 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1081 branch: flow.selectedBranchName,
1082 worktreePath: flow.selectedWorktreePath,
1083 createdAt: creationMetadata.createdAt,
1084 },
1085 m,
1086 );
1087 return (
1088 <>
1089 <ThreadScreenBinding
1090 environmentId={selectedProject.environmentId}
1091 header={
1092 <DraftThreadHeader thread={thread} project={selectedProject} cwd={flow.workspaceCwd} />
1094 draftMode={{
1095 content: heroViewport,
1096 controls: draftControls,
1097 editorRef: promptInputRef,
1098 sendBlockedReason: setupBlockReason,
1099 interactionLocked: isComposerInteractionLocked,
1100 }}
1101 canOperateThread={canOperate}
1102 selectedThread={thread}
1103 selectedThreadDetailRef={null}
1104 contentPresentation={{ kind: "ready" }}
1105 screenTone={connectionTone(
1106 connectionState,
1107 environmentRuntime?.connectionAwaitingApproval === true,
1108 m,
1109 )}
1110 connectionError={
1111 environmentRuntime ? runtimeConnectionErrorText(environmentRuntime, m) : null
1113 environmentLabel={selectedEnvironmentLabel}
1114 feedbackSubmissions={[]}
1115 onDismissFeedback={() => {}}
1116 selectedThreadFeed={[]}
1117 activityRun={null}
1118 activeWorkStartedAt={null}
1119 isCompacting={false}
1120 creationState={null}
1121 activePendingApproval={null}
1122 activePendingApprovals={[]}
1123 respondingApprovalId={null}
1124 activePendingUserInput={null}
1125 activePendingUserInputDrafts={{}}
1126 activePendingUserInputAnswers={null}
1127 respondingUserInputId={null}
1128 connectionStateLabel={connectionState}
1129 activeThreadBusy={false}
1130 canStopThread={false}
1131 queuedRunEdit={null}
1132 composerDraftKey={flow.draftKey}
1133 followUpBehavior="queue"
1134 canSteerActiveTurn={false}
1135 isSavingQueuedEdit={false}
1136 onCancelQueuedRunEdit={() => {}}
1137 onRemoveQueuedEditAttachment={() => {}}
1138 projectWorkspaceRoot={selectedProject.workspaceRoot}
1139 threadCwd={flow.workspaceCwd}
1140 selectedThreadQueueCount={0}
1141 queuedMessages={[]}
1142 dispatchingMessageId={null}
1143 serverConfig={selectedEnvironmentServerConfig}
1144 usesAutomaticContentInsets
1145 onOpenConnectionEditor={() => navigation.navigate("Connections")}
1146 onChangeDraftMessage={flow.setPrompt}
1147 onPickDraftMedia={handlePickMedia}
1148 onPickDraftFiles={handlePickFiles}
1149 onNativePasteImages={handleNativePasteImages}
1150 onNativePasteText={handleNativePasteText}
1151 onRemoveDraftImage={flow.removeAttachment}
1152 onStopThread={() => {}}
1153 onResumeQueue={null}
1154 onSendMessage={handleStart}
1155 offersSideChat={false}
1156 onSendCommand={async () => null}
1157 onReconnectEnvironment={() => onReconnectEnvironment(selectedProject.environmentId)}
1158 canSwitchThreadProvider
1159 onRespondToApproval={async () => {}}
1160 onSelectUserInputOption={() => {}}
1161 onChangeUserInputCustomAnswer={() => {}}
1162 onSubmitUserInput={async () => {}}
1163 onDismissUserInput={async () => {}}
1164 />
1165 </>
1166 );