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

NewTaskDraftScreen.tsx

1,160 lines44.4 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: PROVIDER_SEND_TURN_MAX_ATTACHMENTS }}.`,
673 );
674 return null;
675 }
676​
677 const contextBlockReason = composerContextSendBlockReason(draft.context);
678 if (contextBlockReason) {
679 Dialog.alert(gt`Too much context`, contextBlockReason);
680 return null;
681 }
682 const strandedThread = threadContextsOutsideEnvironment({
683 text: draft.text,
684 records: draft.context?.records ?? [],
685 environmentId: selectedProject.environmentId,
686 linkedEnvironments: flow.linkedEnvironments,
687 })[0];
688 if (strandedThread) {
689 const owner = flow.environments.find(
690 (environment) => environment.environmentId === strandedThread.environmentId,
691 )?.environmentLabel;
692 Dialog.alert(
693 gt`Attached thread unavailable`,
694 owner === undefined
695 ? gt`"${{ title: strandedThread.title }}" is on another machine. Switch back to its machine or remove it from the draft.`
696 : gt`"${{ title: strandedThread.title }}" is on another machine. Switch back to ${{ owner }} or remove it from the draft.`,
697 );
698 return null;
699 }
700​
701 const message = flow.buildPendingTaskMessage(creationMetadata, {
702 currentCheckoutBranch: queuesInsteadOfStarting ? null : flow.currentCheckoutBranchName,
703 });
704 if (!message) {
705 return null;
706 }
707 // Persist locally before clearing or leaving the draft; server setup runs on the thread.
708 flow.setSubmitting(true);
709 const queued = await settlePromise(() => enqueueThreadOutboxMessage(message));
710 flow.setSubmitting(false);
711 if (AsyncResult.isFailure(queued)) {
712 const error = squashAtomCommandFailure(queued);
713 Dialog.alert(
714 gt`Could not queue task`,
715 errorDisplayMessage(error, m) ?? gt`The task could not be saved to the outbox.`,
716 );
717 return null;
718 }
719 promptInputRef.current?.blur();
720 navigation.dispatch(
721 CommonActions.setParams(
722 submittedThreadParams(String(message.environmentId), String(message.threadId)),
723 ),
724 );
725 // The composer has moved to the submitted thread; a pick still converting
726 // would otherwise resurrect this draft.
727 abortComposerDraftOperations(draftKey);
728 const draftSnapshot = getComposerDraftSnapshot(draftKey);
729 // The queued message owns the attachments now, so the sweep is deferred
730 // until the write confirms it.
731 clearComposerDraftContent(draftKey, {
732 clearModelSelection: true,
733 clearWorkspaceSelection: true,
734 deferAttachmentCleanup: true,
735 });
736 scheduleUnusedComposerAttachmentCleanup(draftSnapshot.attachments);
737 return message.messageId;
738 }
739​
740 // Keep the current surface until the local draft selection is ready. Publishing
741 // an empty loading surface here flashes between two already-cached threads.
742 if (!selectedProject) return null;
743​
744 const setupBlockReason =
745 isIncomingShareReady && !isImportingShare
746 ? cloneBlocksStart
747 ? gt`Wait for the project clone to finish.`
748 : flow.submitting
749 ? gt`Starting the thread…`
750 : flow.workspaceMode === "worktree" &&
751 (!flow.isGitRepoKnown || (flow.isGitRepo && !flow.selectedBranchName))
752 ? gt`Choose a base branch before creating a worktree.`
753 : null
754 : gt`Wait for shared content to finish importing.`;
755 const chooseProject = () => {
756 if (isComposerInteractionLocked) {
757 return;
758 }
759 promptInputRef.current?.blur();
760 void KeyboardController.dismiss({ animated: true });
761 navigation.navigate("NewTaskProject", { incomingShareId: props.incomingShareId });
762 };
763 const openContextPicker = (
764 routeName: "NewTaskBranch" | "NewTaskEnvironment" | "NewTaskRepositories",
765 ) => {
766 if (isComposerInteractionLocked) {
767 return;
768 }
769 promptInputRef.current?.blur();
770 void KeyboardController.dismiss({ animated: true });
771 navigation.navigate(routeName);
772 };
773​
774 const environmentControl = (
775 <DraftEnvironmentControl
776 connectionState={connectionState}
777 label={selectedEnvironmentLabel}
778 machineKind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}
779 disabled={isComposerInteractionLocked}
780 onChooseEnvironment={() => openContextPicker("NewTaskEnvironment")}
781 />
782 );
783 const shareUnavailableNotice = isIncomingShareUnavailable ? (
784 <Text textRole="footnote" className="text-center text-foreground-muted">
785 <T>The shared content is no longer in the inbox. You can continue editing this task draft.</T>
786 </Text>
787 ) : null;
788 const headingParts = gt`What should we build in ${{ project: HEADING_PROJECT_SLOT }}?`.split(
789 HEADING_PROJECT_SLOT,
790 );
791 const headingBefore = headingParts[0] ?? "";
792 const headingAfter = headingParts[1] ?? "";
793 const headingBreak = headingBefore.trimEnd().lastIndexOf(" ");
794 const headingFirstLine = headingBreak < 0 ? headingBefore : headingBefore.slice(0, headingBreak);
795 const headingLead = headingBreak < 0 ? "" : headingBefore.slice(headingBreak + 1);
796 const hero = flow.isScratchDraft ? (
797 <View className="items-center gap-2 px-6" testID="new-task-hero">
798 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
799 <T>What should we work on?</T>
800 </Text>
801 <View className="flex-row flex-wrap items-center justify-center gap-x-1">
802 <ComposerInlineControl
803 accessibilityHint={gt`Opens the project picker`}
804 accessibilityLabel={gt`No project`}
805 chevronDirection="right"
806 disabled={isComposerInteractionLocked}
807 icon="folder"
808 label={gt`No project`}
809 onPress={chooseProject}
810 />
811 {environmentControl}
812 </View>
813 {shareUnavailableNotice}
814 </View>
815 ) : (
816 <View className="items-center gap-6 px-6" testID="new-task-hero">
817 <View className="w-full items-center gap-1.5">
818 <Text className="text-center text-2xl font-t3-medium tracking-tight text-foreground">
819 {headingFirstLine}
820 </Text>
821 <View className="max-w-full flex-row items-center justify-center">
822 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">
823 {headingLead}
824 </Text>
825 <Pressable
826 accessibilityHint={gt`Opens the project picker`}
827 accessibilityLabel={selectedProjectLabel ?? selectedProject.title}
828 accessibilityRole="button"
829 disabled={isComposerInteractionLocked}
830 onPress={chooseProject}
831 className="min-w-0 max-w-[250px] border-b border-foreground-muted active:opacity-65"
832 >
833 <Text
834 className="text-2xl font-t3-medium tracking-tight text-foreground"
835 numberOfLines={1}
836 >
837 {selectedProjectLabel ?? selectedProject.title}
838 </Text>
839 </Pressable>
840 <Text className="text-2xl font-t3-medium tracking-tight text-foreground">
841 {headingAfter}
842 </Text>
843 </View>
844 </View>
845​
846 {environmentControl}
847 {shareUnavailableNotice}
848 </View>
849 );
850 // The nested hero scroll view does not receive UIKit's automatic navigation inset in split columns.
851 const heroViewport = (headerInset: number, bottomInset: number, viewportHeight: number) =>
852 viewportHeight < SHORT_DRAFT_VIEWPORT_HEIGHT ? null : (
853 <NativeScrollEdgeEffectsContext
854 value={{ top: "hidden", bottom: "hidden", left: "hidden", right: "hidden" }}
855 >
856 <View
857 collapsable={false}
858 style={{
859 position: "absolute",
860 top: headerInset,
861 bottom: bottomInset,
862 left: 0,
863 right: 0,
864 overflow: "hidden",
865 }}
866 >
867 <ScrollView
868 alwaysBounceVertical={false}
869 className="flex-1"
870 contentInsetAdjustmentBehavior="never"
871 contentContainerClassName="grow items-center"
872 contentContainerStyle={{ paddingVertical: 24 }}
873 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
874 keyboardShouldPersistTaps="handled"
875 showsVerticalScrollIndicator={false}
876 style={{ flex: 1 }}
877 testID="new-task-hero-scroll"
878 >
879 <View style={{ flexGrow: 1 }} />
880 {hero}
881 <View style={{ flexGrow: 2 }} />
882 </ScrollView>
883 </View>
884 </NativeScrollEdgeEffectsContext>
885 );
886​
887 const contextProjectLabel = flow.isScratchDraft
888 ? gt`No project`
889 : (selectedProjectLabel ?? selectedProject.title);
890 const contextControls = (
891 <View className="flex-row items-center gap-1 px-2">
892 <View className="min-w-0 shrink">
893 <ComposerInlineControl
894 accessibilityHint={gt`Opens the project picker`}
895 accessibilityLabel={gt`Project: ${{ project: contextProjectLabel }}`}
896 chevronDirection="right"
897 disabled={isComposerInteractionLocked}
898 icon="folder"
899 label={contextProjectLabel}
900 maxWidth="100%"
901 onPress={chooseProject}
902 />
903 </View>
904 <View className="min-w-0 shrink">
905 <ComposerInlineControl
906 accessibilityLabel={
907 connectionState === "connected"
908 ? gt`Choose environment, ${{ label: selectedEnvironmentLabel }}, Connected`
909 : gt`Choose environment, ${{ label: selectedEnvironmentLabel }}, Offline`
910 }
911 chevronDirection="right"
912 disabled={isComposerInteractionLocked}
913 renderIcon={(size) => (
914 <EnvironmentMachineSymbol
915 kind={resolveEnvironmentMachineKind(selectedEnvironmentServerConfig)}
916 size={size}
917 tintColorClassName="accent-icon-muted"
918 />
919 )}
920 label={selectedEnvironmentLabel}
921 maxWidth="100%"
922 onPress={() => openContextPicker("NewTaskEnvironment")}
923 suffix={
924 connectionState === "connected" ? null : (
925 <ConnectionStatusDot state="error" pulse={false} size={6} />
926 )
927 }
928 />
929 </View>
930 </View>
931 );
932​
933 const startsNewWorktree = flow.workspaceMode === "worktree";
934 const offersRepositoryChoice =
935 startsNewWorktree && (flow.worktreeRepositoryChoices?.length ?? 0) > 0;
936 const workspaceControls = (
937 <View className="flex-row flex-wrap items-center gap-x-1 px-2">
938 <ComposerInlineControl
939 accessibilityHint={
940 flow.workspaceMode === "local"
941 ? gt`Switches to a new worktree`
942 : gt`Switches to the current checkout`
943 }
944 accessibilityLabel={workspaceLabel}
945 disabled={isComposerInteractionLocked || !(flow.isGitRepo || flow.tracksGitRepositories)}
946 renderIcon={(size) => (
947 <NewTaskWorkspaceIcon
948 workspaceMode={flow.workspaceMode}
949 worktreePath={flow.selectedWorktreePath}
950 size={size}
951 />
952 )}
953 label={workspaceLabel}
954 maxWidth="100%"
955 onPress={() => flow.setWorkspaceMode(flow.workspaceMode === "local" ? "worktree" : "local")}
956 showChevron={false}
957 />
958​
959 {offersRepositoryChoice ? (
960 <View className="min-w-0 shrink">
961 <ComposerInlineControl
962 accessibilityHint={gt`Chooses the repositories the new worktree holds`}
963 accessibilityLabel={gt`Repositories in the new worktree: ${{ selection: flow.worktreeRepositorySelection.label }}`}
964 chevronDirection="right"
965 disabled={isComposerInteractionLocked}
966 icon="folder.badge.plus"
967 label={flow.worktreeRepositorySelection.label}
968 maxWidth="100%"
969 onPress={() => {
970 flow.refreshWorktreeRepositoryChoices();
971 openContextPicker("NewTaskRepositories");
972 }}
973 {...(flow.worktreeRepositorySelection.needsChoice ? { tone: "warning" as const } : {})}
974 />
975 </View>
976 ) : null}
977 {startsNewWorktree && !flow.isGitRepo ? (
978 <View className="min-h-8 min-w-0 shrink justify-center px-2">
979 <Text className="text-sm text-foreground-muted" numberOfLines={1}>
980 <T>Each repository starts from its own default branch</T>
981 </Text>
982 </View>
983 ) : (
984 <View className="min-w-0 shrink">
985 <ComposerInlineControl
986 accessibilityLabel={
987 startsNewWorktree
988 ? gt`Base branch: ${{ branch: selectedBranchLabel }}`
989 : gt`Branch: ${{ branch: selectedBranchLabel }}`
990 }
991 chevronDirection="right"
992 disabled={isComposerInteractionLocked || !flow.isGitRepo}
993 icon="arrow.triangle.branch"
994 label={showBranchLoading ? gt`Loading branches…` : selectedBranchLabel}
995 maxWidth="100%"
996 onPress={() => openContextPicker("NewTaskBranch")}
997 />
998 </View>
999 )}
1000 </View>
1001 );
1002​
1003 const draftControls = (viewportHeight: number) => (
1004 <View className="pb-1">
1005 {projectClone && projectClone.phase !== "done" && selectedProject ? (
1006 <View className="px-1 pb-2">
1007 <ProjectCloneBanner
1008 clone={projectClone}
1009 onCancel={() =>
1010 void runCloneAction(gt`Failed to cancel clone`, () =>
1011 cancelProjectClone({
1012 environmentId: selectedProject.environmentId,
1013 input: { projectId: selectedProject.id },
1014 }),
1017 onRetry={() =>
1018 void runCloneAction(gt`Failed to retry clone`, () =>
1019 retryProjectClone({
1020 environmentId: selectedProject.environmentId,
1021 input: { projectId: selectedProject.id },
1022 }),
1025 onRemove={() => void removeClonedProject()}
1026 />
1027 </View>
1028 ) : null}
1029 {viewportHeight < SHORT_DRAFT_VIEWPORT_HEIGHT ? contextControls : null}
1030 {flow.canChooseWorkspace ? workspaceControls : null}
1031 </View>
1032 );
1033​
1034 if (!flow.selectedModel) {
1035 return (
1036 <ThreadScreenFallback header={<AppBar title={gt`New thread`} onBack={goBack} />}>
1037 <KeyboardStickyView pointerEvents="box-none" style={{ flex: 1 }}>
1038 <View pointerEvents="box-none" className="flex-1 justify-end gap-3 p-4">
1039 {environmentControl}
1040 <Text className="text-foreground-muted">
1041 {environmentConnected && selectedEnvironmentServerConfig ? (
1042 <T>
1043 Your draft is saved on this device. <Var>{selectedEnvironmentLabel}</Var> has no
1044 model available. Install or sign in to a provider there to choose one.
1045 </T>
1046 ) : (
1047 <T>
1048 Your draft is saved on this device. Connect to an environment to choose its first
1049 model.
1050 </T>
1051 )}
1052 </Text>
1053 <ComposerEditor
1054 draftKey={flow.draftKey}
1055 value={flow.prompt}
1056 onChangeText={flow.setPrompt}
1057 placeholder={gt`Ask anything`}
1058 multiline
1059 style={{ minHeight: 64 }}
1060 />
1061 </View>
1062 </KeyboardStickyView>
1063 </ThreadScreenFallback>
1064 );
1066 const thread = draftThreadShell(
1068 environmentId: selectedProject.environmentId,
1069 projectId: selectedProject.id,
1070 threadId: ThreadId.make(creationMetadata.threadId),
1071 modelSelection: flow.selectedModel,
1072 runtimeMode: flow.runtimeMode,
1073 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1074 branch: flow.selectedBranchName,
1075 worktreePath: flow.selectedWorktreePath,
1076 createdAt: creationMetadata.createdAt,
1077 },
1078 m,
1079 );
1080 return (
1081 <>
1082 <ThreadScreenBinding
1083 environmentId={selectedProject.environmentId}
1084 header={
1085 <DraftThreadHeader thread={thread} project={selectedProject} cwd={flow.workspaceCwd} />
1087 draftMode={{
1088 content: heroViewport,
1089 controls: draftControls,
1090 editorRef: promptInputRef,
1091 sendBlockedReason: setupBlockReason,
1092 interactionLocked: isComposerInteractionLocked,
1093 }}
1094 canOperateThread={canOperate}
1095 selectedThread={thread}
1096 selectedThreadDetailRef={null}
1097 contentPresentation={{ kind: "ready" }}
1098 screenTone={connectionTone(
1099 connectionState,
1100 environmentRuntime?.connectionAwaitingApproval === true,
1101 m,
1102 )}
1103 connectionError={
1104 environmentRuntime ? runtimeConnectionErrorText(environmentRuntime, m) : null
1106 environmentLabel={selectedEnvironmentLabel}
1107 feedbackSubmissions={[]}
1108 onDismissFeedback={() => {}}
1109 selectedThreadFeed={[]}
1110 activityRun={null}
1111 activeWorkStartedAt={null}
1112 isCompacting={false}
1113 creationState={null}
1114 activePendingApproval={null}
1115 activePendingApprovals={[]}
1116 respondingApprovalId={null}
1117 activePendingUserInput={null}
1118 activePendingUserInputDrafts={{}}
1119 activePendingUserInputAnswers={null}
1120 respondingUserInputId={null}
1121 connectionStateLabel={connectionState}
1122 activeThreadBusy={false}
1123 canStopThread={false}
1124 queuedRunEdit={null}
1125 composerDraftKey={flow.draftKey}
1126 followUpBehavior="queue"
1127 canSteerActiveTurn={false}
1128 isSavingQueuedEdit={false}
1129 onCancelQueuedRunEdit={() => {}}
1130 onRemoveQueuedEditAttachment={() => {}}
1131 projectWorkspaceRoot={selectedProject.workspaceRoot}
1132 threadCwd={flow.workspaceCwd}
1133 selectedThreadQueueCount={0}
1134 queuedMessages={[]}
1135 dispatchingMessageId={null}
1136 serverConfig={selectedEnvironmentServerConfig}
1137 usesAutomaticContentInsets
1138 onOpenConnectionEditor={() => navigation.navigate("Connections")}
1139 onChangeDraftMessage={flow.setPrompt}
1140 onPickDraftMedia={handlePickMedia}
1141 onPickDraftFiles={handlePickFiles}
1142 onNativePasteImages={handleNativePasteImages}
1143 onNativePasteText={handleNativePasteText}
1144 onRemoveDraftImage={flow.removeAttachment}
1145 onStopThread={() => {}}
1146 onResumeQueue={null}
1147 onSendMessage={handleStart}
1148 offersSideChat={false}
1149 onSendCommand={async () => null}
1150 onReconnectEnvironment={() => onReconnectEnvironment(selectedProject.environmentId)}
1151 canSwitchThreadProvider
1152 onRespondToApproval={async () => {}}
1153 onSelectUserInputOption={() => {}}
1154 onChangeUserInputCustomAnswer={() => {}}
1155 onSubmitUserInput={async () => {}}
1156 onDismissUserInput={async () => {}}
1157 />
1158 </>
1159 );