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

ScheduledTaskPickerScreens.tsx

293 lines10.2 KB

1import { NativeScrollView } from "../../native/NativeScrollViewMarker";
2import { LegendList } from "@legendapp/list/react-native";
3import { useNavigation } from "@react-navigation/native";
4import { isListedThreadLineage } from "@t3tools/contracts";
5import * as Haptics from "expo-haptics";
6import { useMemo, useState } from "react";
7import { Platform } from "react-native";
8import { useSafeAreaInsets } from "react-native-safe-area-context";
9​
10import { AppText as Text } from "../../components/ui/AppText";
11import { SelectionRow } from "../../components/ui/SelectionRow";
12import { useSearchToolbarInset } from "../../components/ui/useBarInset";
13import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
14import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
15import {
16 useEnvironmentServerConfig,
17 useProjects,
18 useVisibleThreadShells,
19} from "../../state/entities";
20import { useDebouncedValue, usePaginatedBranches, useThreadSearch } from "../../state/queries";
21import { BranchPickerScreen } from "../threads/NewTaskContextPickerScreens";
22import { ThreadSettingsPickerScreen } from "../threads/ThreadSettingsSheet";
23import { SettingsScreen } from "./components/SettingsScreen";
24import {
25 NEW_THREAD_DESTINATION_LABEL,
26 useScheduledTaskDestinationLabel,
27 useScheduledTaskEditor,
28} from "./scheduled-task-editor";
29import { moveDraftToThread, unbindDraftFromThread } from "./scheduledTaskDraft";
30​
31function MissingTaskDraft() {
32 return (
33 <SettingsScreen title="Scheduled task">
34 <Text className="p-5 text-base text-foreground-muted">Open a scheduled task form first.</Text>
35 </SettingsScreen>
36 );
38​
39export function ScheduledTaskModelPickerRouteScreen() {
40 const navigation = useNavigation();
41 const { editor, setEditor } = useScheduledTaskEditor();
42 const config = useEnvironmentServerConfig(editor?.environmentId ?? null);
43 const selectedModel = editor?.draft.modelSelection ?? null;
44 const projectId = editor?.draft.projectId ?? null;
45 const models = useMemo(
46 () => buildModelOptions(config, selectedModel, undefined, projectId),
47 [config, selectedModel, projectId],
48 );
49 const providerGroups = useMemo(() => groupByProvider(models), [models]);
50 const selectedOption = models.find(
51 (option) =>
52 option.selection.instanceId === selectedModel?.instanceId &&
53 option.selection.model === selectedModel.model,
54 );
55 const optionDescriptors = useMemo(
56 () =>
57 resolveProviderOptionDescriptors({
58 capabilities: selectedOption?.capabilities,
59 selections: selectedModel?.options,
60 }),
61 [selectedOption?.capabilities, selectedModel?.options],
62 );
63​
64 if (!editor) return <MissingTaskDraft />;
65​
66 return (
67 <ThreadSettingsPickerScreen
68 environmentId={editor.environmentId}
69 projectId={projectId}
70 cwd={null}
71 providerGroups={providerGroups}
72 selectedModel={selectedModel}
73 prompt={editor.draft.prompt}
74 onPromptChange={(prompt) =>
75 setEditor((current) =>
76 current ? { ...current, draft: { ...current.draft, prompt } } : current,
77 )
78 }
79 onSelectModel={(option) =>
80 setEditor((current) =>
81 current
82 ? {
83 ...current,
84 draft: {
85 ...current.draft,
86 modelSelection: option.selection,
87 modelSelectionIsExplicit: true,
88 },
89 }
90 : current,
91 )
92 }
93 optionDescriptors={optionDescriptors}
94 onUpdateOptionSelections={(options) =>
95 setEditor((current) =>
96 current?.draft.modelSelection
97 ? {
98 ...current,
99 draft: {
100 ...current.draft,
101 modelSelection: { ...current.draft.modelSelection, options },
102 modelSelectionIsExplicit: true,
103 },
104 }
105 : current,
106 )
107 }
108 runtimeMode={editor.draft.runtimeMode}
109 onUpdateRuntimeMode={(runtimeMode) =>
110 setEditor((current) =>
111 current
112 ? {
113 ...current,
114 draft: { ...current.draft, runtimeMode },
115 }
116 : current,
117 )
118 }
119 onClose={() => navigation.goBack()}
120 />
121 );
123​
124export function ScheduledTaskBranchPickerRouteScreen() {
125 const navigation = useNavigation();
126 const { editor, setEditor } = useScheduledTaskEditor();
127 const projects = useProjects();
128 const project =
129 projects.find(
130 (entry) =>
131 entry.environmentId === editor?.environmentId && entry.id === editor.draft.projectId,
132 ) ?? null;
133 const [query, setQuery] = useState("");
134 const debouncedQuery = useDebouncedValue(query, 150);
135 const branches = usePaginatedBranches({
136 environmentId: editor?.environmentId ?? null,
137 cwd: project?.workspaceRoot ?? null,
138 query: debouncedQuery,
139 });
140 const visibleBranches = branches.refs.filter(
141 (branch) => !branch.isRemote && branch.name.toLowerCase().includes(query.trim().toLowerCase()),
142 );
143​
144 if (!editor) return <MissingTaskDraft />;
145​
146 return (
147 <BranchPickerScreen
148 title="Base branch"
149 project={project}
150 branches={visibleBranches}
151 selectedBranchName={editor.draft.baseRef}
152 query={query}
153 onQueryChange={setQuery}
154 loading={
155 query.trim() !== debouncedQuery.trim() || (branches.isPending && branches.data === null)
156 }
157 error={project ? branches.error : "This project is no longer available."}
158 refreshing={branches.isFetchingNextPage}
159 hasMore={branches.data?.nextCursor != null}
160 onRefresh={branches.refresh}
161 onLoadMore={branches.loadNext}
162 onSelect={(branch) => {
163 void Haptics.selectionAsync();
164 setEditor((current) =>
165 current ? { ...current, draft: { ...current.draft, baseRef: branch.name } } : current,
166 );
167 navigation.goBack();
168 }}
169 worktree={{
170 startFromOrigin: editor.draft.startFromOrigin,
171 onChangeStartFromOrigin: (startFromOrigin) =>
172 setEditor((current) =>
173 current
174 ? {
175 ...current,
176 draft: { ...current.draft, startFromOrigin },
177 }
178 : current,
179 ),
180 }}
181 />
182 );
184​
185const THREAD_SEARCH_PLACEHOLDER = "Search threads, including older ones";
186​
187export function ScheduledTaskThreadPickerRouteScreen() {
188 const navigation = useNavigation();
189 const insets = useSafeAreaInsets();
190 const { editor, setEditor } = useScheduledTaskEditor();
191 const environmentId = editor?.environmentId ?? null;
192 const projectId = editor?.draft.projectId ?? null;
193 const threadId = editor?.draft.threadId ?? null;
194 const currentLabel = useScheduledTaskDestinationLabel(environmentId, threadId);
195 const shells = useVisibleThreadShells();
196 const [query, setQuery] = useState("");
197 const search = {
198 value: query,
199 onChangeText: setQuery,
200 placeholder: THREAD_SEARCH_PLACEHOLDER,
201 accessibilityLabel: "Search threads",
202 clearAccessibilityLabel: "Clear thread search",
203 mode: "inline" as const,
204 compactToolbar: true,
205 };
206 const searchToolbarInset = useSearchToolbarInset(search);
207 // Mounts older settled threads matching the query, which shells may leave out.
208 useThreadSearch(
209 environmentId !== null && projectId !== null ? [environmentId] : [],
210 query,
211 projectId === null ? { titlesOnly: true } : { titlesOnly: true, projectIds: [projectId] },
212 );
213​
214 if (!editor) return <MissingTaskDraft />;
215​
216 const needle = query.trim().toLocaleLowerCase();
217 const rows = [
218 ...(needle ? [] : [{ key: "new-thread", title: NEW_THREAD_DESTINATION_LABEL, thread: null }]),
219 ...(threadId !== null && currentLabel.toLocaleLowerCase().includes(needle)
220 ? [{ key: threadId, title: currentLabel, thread: null }]
221 : []),
222 ...shells
223 .filter(
224 (thread) =>
225 thread.environmentId === environmentId &&
226 thread.projectId === projectId &&
227 thread.id !== threadId &&
228 thread.archivedAt === null &&
229 isListedThreadLineage(thread.lineage) &&
230 thread.title.toLocaleLowerCase().includes(needle),
231 )
232 .sort((left, right) => right.updatedAt.localeCompare(left.updatedAt))
233 .map((thread) => ({
234 key: thread.id,
235 title: thread.title.trim() || "Untitled thread",
236 thread,
237 })),
238 ];
239 const selectedKey = threadId ?? (editor.draft.threadMode === "new_thread" ? "new-thread" : null);
240​
241 return (
242 <SettingsScreen title="Destination" search={search}>
243 <LegendList
244 renderScrollComponent={NativeScrollView}
245 data={rows}
246 keyExtractor={(row) => row.key}
247 extraData={selectedKey}
248 estimatedItemSize={56}
249 recycleItems
250 className="flex-1"
251 contentInsetAdjustmentBehavior="automatic"
252 automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}
253 keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
254 keyboardShouldPersistTaps="handled"
255 showsVerticalScrollIndicator={false}
256 contentContainerStyle={{
257 paddingHorizontal: 16,
258 paddingTop: 16,
259 paddingBottom: searchToolbarInset
260 ? searchToolbarInset + 16
261 : Math.max(insets.bottom, 16) + 16,
262 }}
263 ListEmptyComponent={
264 <Text className="p-5 text-center text-sm text-foreground-muted">No matching threads</Text>
265 }
266 renderItem={({ item, index }) => (
267 <SelectionRow
268 title={item.title}
269 selected={item.key === selectedKey}
270 isFirst={index === 0}
271 isLast={index === rows.length - 1}
272 onPress={() => {
273 void Haptics.selectionAsync();
274 if (item.key !== selectedKey) {
275 setEditor((current) =>
276 current
277 ? {
278 ...current,
279 draft: item.thread
280 ? moveDraftToThread(current.draft, item.thread)
281 : { ...unbindDraftFromThread(current.draft), threadMode: "new_thread" },
282 }
283 : current,
284 );
285 }
286 navigation.goBack();
287 }}
288 />
289 )}
290 />
291 </SettingsScreen>
292 );