Open History to see the last commit
1import { Stack, useRouter } from "expo-router";
2import { useCallback, useEffect, useMemo, useRef } from "react";
3import { Alert, InteractionManager, View, useColorScheme } from "react-native";
4import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
5import { useSafeAreaInsets } from "react-native-safe-area-context";
6import { useThemeColor } from "../../lib/useThemeColor";
7
8import { EnvironmentId } from "@t3tools/contracts";
9import {
10 isAtomCommandInterrupted,
11 squashAtomCommandFailure,
12} from "@t3tools/client-runtime/state/runtime";
13
14import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
15import {
16 ComposerToolbarButton,
17 ComposerToolbarRow,
18 ComposerToolbarScroller,
19 ComposerToolbarTrigger,
20} from "../../components/ComposerToolbarTrigger";
21import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
22import { ControlPillMenu } from "../../components/ControlPill";
23import { ProviderIcon } from "../../components/ProviderIcon";
24
25import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
26import {
27 applyProviderOptionMenuEvent,
28 buildProviderOptionMenuActions,
29 providerOptionsConfigurationLabel,
30 resolveProviderOptionDescriptors,
31} from "../../lib/providerOptions";
32import { buildThreadRoutePath } from "../../lib/routes";
33import { scopedProjectKey } from "../../lib/scopedEntities";
34import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
35import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
36import { useProjects } from "../../state/entities";
37import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
38import { useCreateProjectThread } from "./use-project-actions";
39
40function formatWorkspaceLabel(input: {
41 readonly workspaceMode: string;
42 readonly currentBranchName: string | null;
43 readonly selectedBranchName: string | null;
44}): string {
45 const branchName = input.selectedBranchName ?? input.currentBranchName;
46 if (input.workspaceMode === "worktree") {
47 return branchName ? `New worktree · ${branchName}` : "New worktree";
48 }
49 return branchName ? `Current · ${branchName}` : "Current checkout";
50}
51
52export function NewTaskDraftScreen(props: {
53 readonly initialProjectRef?: {
54 readonly environmentId?: string;
55 readonly projectId?: string;
56 };
57}) {
58 const projects = useProjects();
59 const createProjectThread = useCreateProjectThread();
60 const flow = useNewTaskFlow();
61 const router = useRouter();
62 const insets = useSafeAreaInsets();
63 const colorScheme = useColorScheme();
64 const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
65 const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
66 const { logicalProjects, selectedProject, setProject } = flow;
67 const promptInputRef = useRef<ComposerEditorHandle>(null);
68 const loadedBranchesProjectKeyRef = useRef<string | null>(null);
69
70 const borderColor = useThemeColor("--color-border");
71 const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
72 const sheetFadeTransparent = colorScheme === "dark" ? "rgba(14,14,14,0)" : "rgba(242,242,247,0)";
73
74 useEffect(() => {
75 if (props.initialProjectRef?.environmentId && props.initialProjectRef?.projectId) {
76 const directProject =
77 projects.find(
78 (project) =>
79 project.environmentId === props.initialProjectRef?.environmentId &&
80 project.id === props.initialProjectRef?.projectId,
81 ) ?? null;
82
83 if (directProject) {
84 if (
85 selectedProject?.environmentId === directProject.environmentId &&
86 selectedProject.id === directProject.id
87 ) {
88 return;
89 }
90 setProject(directProject);
91 return;
92 }
93 }
94
95 if (selectedProject) {
96 return;
97 }
98
99 if (logicalProjects.length === 1) {
100 setProject(logicalProjects[0]!.project);
101 return;
102 }
103
104 router.replace("/new");
105 }, [
106 logicalProjects,
107 projects,
108 props.initialProjectRef?.environmentId,
109 props.initialProjectRef?.projectId,
110 router,
111 selectedProject,
112 setProject,
113 ]);
114
115 useEffect(() => {
116 if (!selectedProject) {
117 loadedBranchesProjectKeyRef.current = null;
118 return;
119 }
120 const projectKey = `${selectedProject.environmentId}:${selectedProject.id}`;
121 if (loadedBranchesProjectKeyRef.current === projectKey) {
122 return;
123 }
124 loadedBranchesProjectKeyRef.current = projectKey;
125 void flow.loadBranches();
126 }, [flow.loadBranches, selectedProject]);
127
128 useEffect(() => {
129 if (!selectedProject) {
130 return;
131 }
132
133 let focusFrame: ReturnType<typeof requestAnimationFrame> | null = null;
134 const interaction = InteractionManager.runAfterInteractions(() => {
135 focusFrame = requestAnimationFrame(() => promptInputRef.current?.focus());
136 });
137
138 return () => {
139 interaction.cancel();
140 if (focusFrame !== null) {
141 cancelAnimationFrame(focusFrame);
142 }
143 };
144 }, [selectedProject]);
145
146 const environmentMenuActions = useMemo(
147 () =>
148 flow.environments.map((environment) => ({
149 id: `environment:${environment.environmentId}`,
150 title: environment.environmentLabel,
151 state:
152 flow.selectedEnvironmentId === environment.environmentId ? ("on" as const) : undefined,
153 })),
154 [flow.environments, flow.selectedEnvironmentId],
155 );
156
157 const modelMenuActions = useMemo(
158 () =>
159 flow.providerGroups.map((group) => ({
160 id: `provider:${group.providerKey}`,
161 title: group.providerLabel,
162 subtitle: group.models.find(
163 (model) =>
164 flow.selectedModel &&
165 model.selection.instanceId === flow.selectedModel.instanceId &&
166 model.selection.model === flow.selectedModel.model,
167 )?.label,
168 subactions: group.models.map((option) => ({
169 id: `model:${option.key}`,
170 title: option.label,
171 state:
172 flow.selectedModel &&
173 option.selection.instanceId === flow.selectedModel.instanceId &&
174 option.selection.model === flow.selectedModel.model
175 ? ("on" as const)
176 : undefined,
177 })),
178 })),
179 [flow.providerGroups, flow.selectedModel],
180 );
181 const providerOptionDescriptors = useMemo(
182 () =>
183 resolveProviderOptionDescriptors({
184 capabilities: flow.selectedModelOption?.capabilities,
185 selections: flow.selectedModel?.options,
186 }),
187 [flow.selectedModel?.options, flow.selectedModelOption?.capabilities],
188 );
189
190 const optionsMenuActions = useMemo(
191 () => [
192 ...buildProviderOptionMenuActions(providerOptionDescriptors),
193 {
194 id: "options-runtime",
195 title: "Runtime",
196 subtitle:
197 flow.runtimeMode === "approval-required"
198 ? "Approve actions"
199 : flow.runtimeMode === "auto-accept-edits"
200 ? "Auto-accept edits"
201 : "Full access",
202 subactions: [
203 { id: "options:runtime:approval-required", title: "Approve actions" },
204 { id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
205 { id: "options:runtime:full-access", title: "Full access" },
206 ].map((option) => {
207 const value = option.id.replace("options:runtime:", "");
208 return {
209 id: option.id,
210 title: option.title,
211 state: flow.runtimeMode === value ? ("on" as const) : undefined,
212 };
213 }),
214 },
215 {
216 id: "options-interaction",
217 title: "Interaction",
218 subtitle: flow.interactionMode === "plan" ? "Plan" : "Default",
219 subactions: [
220 { id: "options:interaction:default", title: "Default" },
221 { id: "options:interaction:plan", title: "Plan" },
222 ].map((option) => {
223 const value = option.id.replace("options:interaction:", "");
224 return {
225 id: option.id,
226 title: option.title,
227 state: flow.interactionMode === value ? ("on" as const) : undefined,
228 };
229 }),
230 },
231 ],
232 [flow.interactionMode, flow.runtimeMode, providerOptionDescriptors],
233 );
234
235 const workspaceMenuActions = useMemo(() => {
236 const branchActions =
237 flow.availableBranches.length === 0
238 ? [
239 {
240 id: "workspace:branch:none",
241 title: flow.branchesLoading ? "Loading branches…" : "No branches available",
242 attributes: { disabled: true },
243 },
244 ]
245 : flow.availableBranches.slice(0, 12).map((branch) => {
246 const badge = branchBadgeLabel({
247 branch,
248 project: flow.selectedProject,
249 });
250
251 return {
252 id: `workspace:branch:${branch.name}`,
253 title: branch.name,
254 subtitle: badge ? badge.toUpperCase() : undefined,
255 state: flow.selectedBranchName === branch.name ? ("on" as const) : undefined,
256 };
257 });
258
259 return [
260 {
261 id: "workspace:mode",
262 title: "Mode",
263 subtitle: flow.workspaceMode === "local" ? "Current checkout" : "New worktree",
264 subactions: (["local", "worktree"] as const).map((value) => ({
265 id: `workspace:mode:${value}`,
266 title: value === "local" ? "Current checkout" : "New worktree",
267 state: flow.workspaceMode === value ? ("on" as const) : undefined,
268 })),
269 },
270 {
271 id: "workspace:branch",
272 title: "Branch",
273 subtitle: flow.selectedBranchName ?? "Choose branch",
274 subactions: branchActions,
275 },
276 ];
277 }, [
278 flow.availableBranches,
279 flow.branchesLoading,
280 flow.selectedBranchName,
281 flow.selectedProject,
282 flow.workspaceMode,
283 ]);
284
285 const selectedEnvironmentLabel =
286 flow.environments.find(
287 (environment) => environment.environmentId === flow.selectedEnvironmentId,
288 )?.environmentLabel ?? "Environment";
289 const currentBranchName =
290 flow.availableBranches.find((branch) => branch.current)?.name ??
291 flow.availableBranches.find((branch) => branch.isDefault)?.name ??
292 null;
293 const configurationLabel = useMemo(
294 () => providerOptionsConfigurationLabel(providerOptionDescriptors),
295 [providerOptionDescriptors],
296 );
297 const workspaceLabel = useMemo(
298 () =>
299 formatWorkspaceLabel({
300 currentBranchName,
301 selectedBranchName: flow.selectedBranchName,
302 workspaceMode: flow.workspaceMode,
303 }),
304 [currentBranchName, flow.selectedBranchName, flow.workspaceMode],
305 );
306 function handleModelMenuAction(event: string) {
307 if (!event.startsWith("model:")) {
308 return;
309 }
310 flow.setSelectedModelKey(event.slice("model:".length));
311 }
312
313 function handleEnvironmentMenuAction(event: string) {
314 if (!event.startsWith("environment:")) {
315 return;
316 }
317 flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));
318 }
319
320 function handleOptionsMenuAction(event: string) {
321 const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
322 if (providerOptions) {
323 flow.setSelectedModelOptions(providerOptions);
324 return;
325 }
326 if (event.startsWith("options:runtime:")) {
327 flow.setRuntimeMode(
328 event.slice("options:runtime:".length) as Parameters<typeof flow.setRuntimeMode>[0],
329 );
330 return;
331 }
332 if (event.startsWith("options:interaction:")) {
333 flow.setInteractionMode(
334 event.slice("options:interaction:".length) as Parameters<typeof flow.setInteractionMode>[0],
335 );
336 }
337 }
338
339 function handleWorkspaceMenuAction(event: string) {
340 if (event.startsWith("workspace:mode:")) {
341 flow.setWorkspaceMode(
342 event.slice("workspace:mode:".length) as Parameters<typeof flow.setWorkspaceMode>[0],
343 );
344 return;
345 }
346 if (event.startsWith("workspace:branch:")) {
347 const branchName = event.slice("workspace:branch:".length);
348 const branch = flow.availableBranches.find((candidate) => candidate.name === branchName);
349 if (branch) {
350 flow.selectBranch(branch);
351 }
352 }
353 }
354
355 async function handlePickImages(): Promise<void> {
356 const result = await pickComposerImages({ existingCount: flow.attachments.length });
357 if (result.images.length > 0) {
358 flow.appendAttachments(result.images);
359 }
360 }
361
362 const handleNativePasteImages = useCallback(
363 async (uris: ReadonlyArray<string>) => {
364 try {
365 const images = await convertPastedImagesToAttachments({
366 uris,
367 existingCount: flow.attachments.length,
368 });
369 if (images.length > 0) {
370 flow.appendAttachments(images);
371 }
372 } catch (error) {
373 console.error("[native paste] error converting images", error);
374 }
375 },
376 [flow],
377 );
378
379 async function handleStart(): Promise<void> {
380 const selectedProject = flow.selectedProject;
381 if (!selectedProject) {
382 return;
383 }
384 const draft = getComposerDraftSnapshot(
385 `new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`,
386 );
387 const modelSelection = draft.modelSelection ?? flow.selectedModel;
388 const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
389 const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
390 const selectedWorktreePath =
391 draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;
392 const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;
393 const interactionMode = draft.interactionMode ?? flow.interactionMode;
394 const initialMessageText = draft.text.trim();
395
396 if (
397 !modelSelection ||
398 initialMessageText.length === 0 ||
399 flow.submitting ||
400 (workspaceMode === "worktree" && !selectedBranchName)
401 ) {
402 return;
403 }
404
405 flow.setSubmitting(true);
406 const result = await createProjectThread({
407 project: selectedProject,
408 modelSelection,
409 envMode: workspaceMode,
410 branch: selectedBranchName,
411 worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
412 runtimeMode,
413 interactionMode,
414 initialMessageText,
415 initialAttachments: draft.attachments,
416 });
417 flow.setSubmitting(false);
418
419 if (result._tag === "Failure") {
420 if (!isAtomCommandInterrupted(result)) {
421 const error = squashAtomCommandFailure(result);
422 Alert.alert(
423 "Could not start task",
424 error instanceof Error ? error.message : "The task could not be started.",
425 );
426 }
427 return;
428 }
429
430 flow.setPrompt("");
431 flow.clearAttachments();
432 router.replace(buildThreadRoutePath(result.value));
433 }
434
435 if (!selectedProject) {
436 return (
437 <View className="flex-1 bg-sheet">
438 <Stack.Screen options={{ title: "Loading task" }} />
439 </View>
440 );
441 }
442
443 return (
444 <View className="flex-1 bg-sheet">
445 <Stack.Screen options={{ title: selectedProject.title }} />
446
447 <KeyboardAvoidingView automaticOffset behavior="padding" style={{ flex: 1 }}>
448 <View style={{ flex: 1, minHeight: 0, paddingHorizontal: 20, paddingTop: 8 }}>
449 <ComposerEditor
450 ref={promptInputRef}
451 autoFocus
452 multiline
453 scrollEnabled
454 value={flow.prompt}
455 skills={flow.selectedProviderSkills}
456 onChangeText={flow.setPrompt}
457 onPasteImages={(uris) => void handleNativePasteImages(uris)}
458 placeholder={`Describe a coding task in ${selectedProject.title}`}
459 style={{ flex: 1, minHeight: 0 }}
460 textStyle={MOBILE_TYPOGRAPHY.composer}
461 />
462 </View>
463
464 <View
465 style={{
466 borderTopWidth: 1,
467 borderTopColor: borderColor,
468 paddingBottom: controlsBottomPadding,
469 }}
470 >
471 {flow.attachments.length > 0 ? (
472 <View style={{ paddingHorizontal: 16, paddingTop: 12 }}>
473 <ComposerAttachmentStrip
474 attachments={flow.attachments}
475 onRemove={flow.removeAttachment}
476 imageSize={88}
477 imageBorderRadius={20}
478 />
479 </View>
480 ) : null}
481 <ComposerToolbarRow paddingBottom={controlsBottomPadding} paddingHorizontal={6}>
482 <ComposerToolbarScroller
483 fadeOpaque={sheetFadeOpaque}
484 fadeTransparent={sheetFadeTransparent}
485 >
486 <ComposerToolbarButton
487 icon="plus"
488 onPress={() => void handlePickImages()}
489 showChevron={false}
490 />
491 <ControlPillMenu
492 actions={modelMenuActions}
493 onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
494 >
495 <ComposerToolbarTrigger
496 accessibilityLabel="Model"
497 iconNode={
498 <ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />
499 }
500 label={flow.selectedModelOption?.label ?? "Model"}
501 />
502 </ControlPillMenu>
503 <ControlPillMenu
504 actions={optionsMenuActions}
505 onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
506 >
507 <ComposerToolbarTrigger
508 accessibilityLabel="Configuration"
509 icon="slider.horizontal.3"
510 label={configurationLabel}
511 />
512 </ControlPillMenu>
513 <ControlPillMenu
514 actions={environmentMenuActions}
515 onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
516 >
517 <ComposerToolbarTrigger
518 accessibilityLabel="Environment"
519 icon="desktopcomputer"
520 label={selectedEnvironmentLabel}
521 />
522 </ControlPillMenu>
523 <ControlPillMenu
524 actions={workspaceMenuActions}
525 onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}
526 >
527 <ComposerToolbarTrigger
528 accessibilityLabel="Workspace"
529 icon="point.topleft.down.curvedto.point.bottomright.up"
530 label={workspaceLabel}
531 />
532 </ControlPillMenu>
533 </ComposerToolbarScroller>
534 <ComposerToolbarButton
535 accessibilityLabel={flow.submitting ? "Starting task" : "Start task"}
536 icon="arrow.up"
537 onPress={() => void handleStart()}
538 variant="primary"
539 showChevron={false}
540 disabled={
541 !flow.selectedProject ||
542 !flow.selectedModel ||
543 flow.prompt.trim().length === 0 ||
544 flow.submitting ||
545 (flow.workspaceMode === "worktree" && !flow.selectedBranchName)
546 }
547 />
548 </ComposerToolbarRow>
549 </View>
550 </KeyboardAvoidingView>
551 </View>
552 );
553}