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

NewTaskDraftScreen.tsx

589 lines20.0 KB

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