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

ScheduledTaskPickerScreens.tsx

286 lines9.9 KB

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