Open History to see the last commit
1import { useRouter } from "expo-router";
2import { TextInputWrapper } from "expo-paste-input";
3import { useCallback, useEffect, useMemo } from "react";
4import { View } from "react-native";
5import { KeyboardStickyView, useKeyboardState } from "react-native-keyboard-controller";
6import { useSafeAreaInsets } from "react-native-safe-area-context";
7import { useThemeColor } from "../../lib/useThemeColor";
8
9import { EnvironmentId, type ModelSelection } from "@t3tools/contracts";
10
11import { AppTextInput as TextInput } from "../../components/AppText";
12import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
13import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
14import { ProviderIcon } from "../../components/ProviderIcon";
15
16import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
17import { buildThreadRoutePath } from "../../lib/routes";
18import { useRemoteCatalog } from "../../state/use-remote-catalog";
19import { useNativePaste } from "../../lib/useNativePaste";
20import { CLAUDE_AGENT_EFFORT_OPTIONS } from "./claudeEffortOptions";
21import { NewTaskSheetHeader } from "./NewTaskSheetHeader";
22import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
23import { useProjectActions } from "./use-project-actions";
24
25function withModelSelectionOption(
26 selection: ModelSelection,
27 id: string,
28 value: string | boolean | undefined,
29): ModelSelection {
30 const options = (selection.options ?? []).filter((option) => option.id !== id);
31 return {
32 ...selection,
33 options: value === undefined ? options : [...options, { id, value }],
34 };
35}
36
37export function NewTaskDraftScreen(props: {
38 readonly initialProjectRef?: {
39 readonly environmentId?: string;
40 readonly projectId?: string;
41 };
42}) {
43 const { projects } = useRemoteCatalog();
44 const { onCreateThreadWithOptions } = useProjectActions();
45 const flow = useNewTaskFlow();
46 const router = useRouter();
47 const insets = useSafeAreaInsets();
48 const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
49 const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
50 const { logicalProjects, selectedProject, setProject } = flow;
51
52 const borderColor = useThemeColor("--color-border");
53
54 useEffect(() => {
55 if (props.initialProjectRef?.environmentId && props.initialProjectRef?.projectId) {
56 const directProject =
57 projects.find(
58 (project) =>
59 project.environmentId === props.initialProjectRef?.environmentId &&
60 project.id === props.initialProjectRef?.projectId,
61 ) ?? null;
62
63 if (directProject) {
64 setProject(directProject);
65 return;
66 }
67 }
68
69 if (selectedProject) {
70 return;
71 }
72
73 if (logicalProjects.length === 1) {
74 setProject(logicalProjects[0]!.project);
75 return;
76 }
77
78 router.replace("/new");
79 }, [
80 logicalProjects,
81 projects,
82 props.initialProjectRef?.environmentId,
83 props.initialProjectRef?.projectId,
84 router,
85 selectedProject,
86 setProject,
87 ]);
88
89 useEffect(() => {
90 if (!selectedProject) {
91 return;
92 }
93 void flow.loadBranches();
94 }, [flow, selectedProject]);
95
96 const environmentMenuActions = useMemo(
97 () =>
98 flow.environments.map((environment) => ({
99 id: `environment:${environment.environmentId}`,
100 title: environment.environmentLabel,
101 state:
102 flow.selectedEnvironmentId === environment.environmentId ? ("on" as const) : undefined,
103 })),
104 [flow.environments, flow.selectedEnvironmentId],
105 );
106
107 const modelMenuActions = useMemo(
108 () =>
109 flow.providerGroups.map((group) => ({
110 id: `provider:${group.providerKey}`,
111 title: group.providerLabel,
112 subtitle: group.models.find(
113 (model) =>
114 flow.selectedModel &&
115 model.selection.instanceId === flow.selectedModel.instanceId &&
116 model.selection.model === flow.selectedModel.model,
117 )?.label,
118 subactions: group.models.map((option) => ({
119 id: `model:${option.key}`,
120 title: option.label,
121 state:
122 flow.selectedModel &&
123 option.selection.instanceId === flow.selectedModel.instanceId &&
124 option.selection.model === flow.selectedModel.model
125 ? ("on" as const)
126 : undefined,
127 })),
128 })),
129 [flow.providerGroups, flow.selectedModel],
130 );
131
132 const optionsMenuActions = useMemo(
133 () => [
134 {
135 id: "options-effort",
136 title: "Effort",
137 subtitle: `${flow.effort.charAt(0).toUpperCase()}${flow.effort.slice(1)}`,
138 subactions: CLAUDE_AGENT_EFFORT_OPTIONS.map((level) => ({
139 id: `options:effort:${level}`,
140 title: `${level}${level === "high" ? " (default)" : ""}`,
141 state: flow.effort === level ? ("on" as const) : undefined,
142 })),
143 },
144 {
145 id: "options-fast-mode",
146 title: "Fast Mode",
147 subtitle: flow.fastMode ? "On" : "Off",
148 subactions: ([false, true] as const).map((value) => ({
149 id: `options:fast-mode:${value ? "on" : "off"}`,
150 title: value ? "On" : "Off",
151 state: flow.fastMode === value ? ("on" as const) : undefined,
152 })),
153 },
154 {
155 id: "options-context-window",
156 title: "Context Window",
157 subtitle: flow.contextWindow,
158 subactions: (["200k", "1M"] as const).map((value) => ({
159 id: `options:context-window:${value}`,
160 title: `${value}${value === "1M" ? " (default)" : ""}`,
161 state: flow.contextWindow === value ? ("on" as const) : undefined,
162 })),
163 },
164 {
165 id: "options-runtime",
166 title: "Runtime",
167 subtitle:
168 flow.runtimeMode === "approval-required"
169 ? "Approve actions"
170 : flow.runtimeMode === "auto-accept-edits"
171 ? "Auto-accept edits"
172 : "Full access",
173 subactions: [
174 { id: "options:runtime:approval-required", title: "Approve actions" },
175 { id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
176 { id: "options:runtime:full-access", title: "Full access" },
177 ].map((option) => {
178 const value = option.id.replace("options:runtime:", "");
179 return {
180 id: option.id,
181 title: option.title,
182 state: flow.runtimeMode === value ? ("on" as const) : undefined,
183 };
184 }),
185 },
186 {
187 id: "options-interaction",
188 title: "Interaction",
189 subtitle: flow.interactionMode === "plan" ? "Plan" : "Default",
190 subactions: [
191 { id: "options:interaction:default", title: "Default" },
192 { id: "options:interaction:plan", title: "Plan" },
193 ].map((option) => {
194 const value = option.id.replace("options:interaction:", "");
195 return {
196 id: option.id,
197 title: option.title,
198 state: flow.interactionMode === value ? ("on" as const) : undefined,
199 };
200 }),
201 },
202 ],
203 [flow.contextWindow, flow.effort, flow.fastMode, flow.interactionMode, flow.runtimeMode],
204 );
205
206 const workspaceMenuActions = useMemo(() => {
207 const branchActions =
208 flow.availableBranches.length === 0
209 ? [
210 {
211 id: "workspace:branch:none",
212 title: flow.branchesLoading ? "Loading branches…" : "No branches available",
213 attributes: { disabled: true },
214 },
215 ]
216 : flow.availableBranches.slice(0, 12).map((branch) => {
217 const badge = branchBadgeLabel({
218 branch,
219 project: flow.selectedProject,
220 });
221
222 return {
223 id: `workspace:branch:${branch.name}`,
224 title: branch.name,
225 subtitle: badge ? badge.toUpperCase() : undefined,
226 state: flow.selectedBranchName === branch.name ? ("on" as const) : undefined,
227 };
228 });
229
230 return [
231 {
232 id: "workspace:mode",
233 title: "Mode",
234 subtitle: flow.workspaceMode === "local" ? "Local" : "Worktree",
235 subactions: (["local", "worktree"] as const).map((value) => ({
236 id: `workspace:mode:${value}`,
237 title: value === "local" ? "Local" : "Worktree",
238 state: flow.workspaceMode === value ? ("on" as const) : undefined,
239 })),
240 },
241 {
242 id: "workspace:branch",
243 title: "Branch",
244 subtitle: flow.selectedBranchName ?? "Choose branch",
245 subactions: branchActions,
246 },
247 ];
248 }, [
249 flow.availableBranches,
250 flow.branchesLoading,
251 flow.selectedBranchName,
252 flow.selectedProject,
253 flow.workspaceMode,
254 ]);
255
256 function handleModelMenuAction(event: string) {
257 if (!event.startsWith("model:")) {
258 return;
259 }
260 // Defer state update so the native menu dismiss animation completes
261 // before re-rendering the menu actions (prevents submenu jump).
262 setTimeout(() => {
263 flow.setSelectedModelKey(event.slice("model:".length));
264 }, 150);
265 }
266
267 function handleEnvironmentMenuAction(event: string) {
268 if (!event.startsWith("environment:")) {
269 return;
270 }
271 flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));
272 }
273
274 function handleOptionsMenuAction(event: string) {
275 if (event.startsWith("options:effort:")) {
276 flow.setEffort(event.slice("options:effort:".length) as typeof flow.effort);
277 return;
278 }
279 if (event.startsWith("options:fast-mode:")) {
280 flow.setFastMode(event.endsWith(":on"));
281 return;
282 }
283 if (event.startsWith("options:context-window:")) {
284 flow.setContextWindow(event.slice("options:context-window:".length));
285 return;
286 }
287 if (event.startsWith("options:runtime:")) {
288 flow.setRuntimeMode(
289 event.slice("options:runtime:".length) as Parameters<typeof flow.setRuntimeMode>[0],
290 );
291 return;
292 }
293 if (event.startsWith("options:interaction:")) {
294 flow.setInteractionMode(
295 event.slice("options:interaction:".length) as Parameters<typeof flow.setInteractionMode>[0],
296 );
297 }
298 }
299
300 function handleWorkspaceMenuAction(event: string) {
301 if (event.startsWith("workspace:mode:")) {
302 flow.setWorkspaceMode(
303 event.slice("workspace:mode:".length) as Parameters<typeof flow.setWorkspaceMode>[0],
304 );
305 return;
306 }
307 if (event.startsWith("workspace:branch:")) {
308 const branchName = event.slice("workspace:branch:".length);
309 const branch = flow.availableBranches.find((candidate) => candidate.name === branchName);
310 if (branch) {
311 flow.selectBranch(branch);
312 }
313 }
314 }
315
316 async function handlePickImages(): Promise<void> {
317 const result = await pickComposerImages({ existingCount: flow.attachments.length });
318 if (result.images.length > 0) {
319 flow.appendAttachments(result.images);
320 }
321 }
322
323 const handleNativePasteImages = useCallback(
324 async (uris: ReadonlyArray<string>) => {
325 try {
326 const images = await convertPastedImagesToAttachments({
327 uris,
328 existingCount: flow.attachments.length,
329 });
330 if (images.length > 0) {
331 flow.appendAttachments(images);
332 }
333 } catch (error) {
334 console.error("[native paste] error converting images", error);
335 }
336 },
337 [flow],
338 );
339
340 const handleNativePaste = useNativePaste((uris) => {
341 void handleNativePasteImages(uris);
342 });
343
344 async function handleStart(): Promise<void> {
345 if (
346 !flow.selectedProject ||
347 !flow.selectedModel ||
348 flow.prompt.trim().length === 0 ||
349 flow.submitting ||
350 (flow.workspaceMode === "worktree" && !flow.selectedBranchName)
351 ) {
352 return;
353 }
354
355 flow.setSubmitting(true);
356 try {
357 const modelWithOptions: ModelSelection =
358 flow.selectedModelOption?.providerDriver === "claudeAgent"
359 ? withModelSelectionOption(
360 withModelSelectionOption(
361 withModelSelectionOption(flow.selectedModel, "effort", flow.effort),
362 "fastMode",
363 flow.fastMode || undefined,
364 ),
365 "contextWindow",
366 flow.contextWindow,
367 )
368 : flow.selectedModelOption?.providerDriver === "codex"
369 ? withModelSelectionOption(flow.selectedModel, "fastMode", flow.fastMode || undefined)
370 : flow.selectedModel;
371
372 const createdThread = await onCreateThreadWithOptions({
373 project: flow.selectedProject,
374 modelSelection: modelWithOptions,
375 envMode: flow.workspaceMode,
376 branch: flow.selectedBranchName,
377 worktreePath: flow.workspaceMode === "worktree" ? null : flow.selectedWorktreePath,
378 runtimeMode: flow.runtimeMode,
379 interactionMode: flow.interactionMode,
380 initialMessageText: flow.prompt.trim(),
381 initialAttachments: flow.attachments,
382 });
383
384 if (createdThread) {
385 router.replace(buildThreadRoutePath(createdThread));
386 }
387 } finally {
388 flow.setSubmitting(false);
389 }
390 }
391
392 if (!selectedProject) {
393 return (
394 <View className="flex-1 bg-sheet">
395 <NewTaskSheetHeader title="Loading task" />
396 </View>
397 );
398 }
399
400 return (
401 <View className="flex-1 bg-sheet">
402 <NewTaskSheetHeader
403 title={selectedProject.title}
404 control={
405 flow.logicalProjects.length > 1
406 ? { icon: "chevron.left", onPress: () => router.back() }
407 : undefined
408 }
409 />
410
411 <View style={{ flex: 1, paddingHorizontal: 20, paddingTop: 8 }}>
412 <TextInputWrapper
413 onPaste={(payload) => void handleNativePaste(payload)}
414 style={{ flex: 1 }}
415 >
416 <TextInput
417 multiline
418 value={flow.prompt}
419 onChangeText={flow.setPrompt}
420 placeholder={`Describe a coding task in ${selectedProject.title}`}
421 textAlignVertical="top"
422 className="h-full flex-1 border-0 bg-transparent text-[18px] leading-[28px]"
423 style={{ flex: 1 }}
424 />
425 </TextInputWrapper>
426 </View>
427
428 <KeyboardStickyView>
429 <View
430 style={{
431 borderTopWidth: 1,
432 borderTopColor: borderColor,
433 paddingBottom: controlsBottomPadding,
434 }}
435 >
436 {flow.attachments.length > 0 ? (
437 <View style={{ paddingHorizontal: 16, paddingTop: 12 }}>
438 <ComposerAttachmentStrip
439 attachments={flow.attachments}
440 onRemove={flow.removeAttachment}
441 imageSize={88}
442 imageBorderRadius={20}
443 />
444 </View>
445 ) : null}
446 <View className="flex-row items-center justify-between gap-2 px-4 pt-2">
447 <ControlPill icon="plus" onPress={() => void handlePickImages()} />
448 <ControlPillMenu
449 actions={modelMenuActions}
450 onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
451 >
452 <ControlPill
453 iconNode={
454 <ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />
455 }
456 />
457 </ControlPillMenu>
458 <ControlPillMenu
459 actions={optionsMenuActions}
460 onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
461 >
462 <ControlPill icon="slider.horizontal.3" />
463 </ControlPillMenu>
464 <ControlPillMenu
465 actions={environmentMenuActions}
466 onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
467 >
468 <ControlPill icon="desktopcomputer" />
469 </ControlPillMenu>
470 <ControlPillMenu
471 actions={workspaceMenuActions}
472 onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}
473 >
474 <ControlPill icon="point.topleft.down.curvedto.point.bottomright.up" />
475 </ControlPillMenu>
476 <ControlPill
477 icon="arrow.up"
478 label={flow.submitting ? "Starting" : "Start"}
479 onPress={() => void handleStart()}
480 variant="primary"
481 disabled={
482 !flow.selectedProject ||
483 !flow.selectedModel ||
484 flow.prompt.trim().length === 0 ||
485 flow.submitting ||
486 (flow.workspaceMode === "worktree" && !flow.selectedBranchName)
487 }
488 />
489 </View>
490 </View>
491 </KeyboardStickyView>
492 </View>
493 );
494}