@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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