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