Open History to see the last commit
1import type {
2 EnvironmentId,
3 ProjectId,
4 ScheduledTask,
5 ScheduledTaskUpsertInput,
6} from "@t3tools/contracts";
7import { resolveEnvironmentMachineKind } from "@t3tools/contracts";
8import type { MenuAction } from "@react-native-menu/menu";
9import { DateTimePicker } from "@expo/ui/community/datetime-picker";
10import {
11 isAtomCommandInterrupted,
12 squashAtomCommandFailure,
13 type AtomCommandResult,
14} from "@t3tools/client-runtime/state/runtime";
15import {
16 useCallback,
17 useEffect,
18 useId,
19 useLayoutEffect,
20 useMemo,
21 useRef,
22 useState,
23 type ReactNode,
24} from "react";
25import { useFocusEffect, useNavigation, usePreventRemove } from "@react-navigation/native";
26import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
27import { Alert, AppState, Platform, Pressable, TextInput as RNTextInput, View } from "react-native";
28import { useSafeAreaInsets } from "react-native-safe-area-context";
29
30import { AppText as Text } from "../../components/AppText";
31import { SymbolView } from "../../components/AppSymbol";
32import {
33 EnvironmentMachineSymbol,
34 ENVIRONMENT_MACHINE_SYMBOLS,
35} from "../../components/EnvironmentMachineSymbol";
36import { ControlPillMenu } from "../../components/ControlPill";
37import type { ComposerEditorSelection } from "../../components/ComposerEditor";
38import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";
39import { SegmentedControl } from "../../components/SegmentedControl";
40import { ThemedSwitch } from "../../components/ThemedSwitch";
41import { buildModelOptions } from "../../lib/modelOptions";
42import { NativeStackScreenOptions } from "../../native/StackHeader";
43import { useProjects, useEnvironmentServerConfig } from "../../state/entities";
44import { useEnvironmentQuery } from "../../state/query";
45import { serverEnvironment } from "../../state/server";
46import { useAtomCommand } from "../../state/use-atom-command";
47import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
48import { resolveNewTaskBranchLabel } from "../threads/new-task-context-presentation";
49import { useVoiceInputController } from "../voice-input/useVoiceInputController";
50import { ScheduledTaskPromptField } from "./components/ScheduledTaskPromptField";
51import {
52 AndroidSettingsEnvironmentFilter,
53 SettingsEnvironmentFilterHeader,
54} from "./components/SettingsEnvironmentFilterHeader";
55import { SettingsScreen } from "./components/SettingsScreen";
56import { SettingsSection } from "./components/SettingsSection";
57import { useSettingsEnvironmentFilter, type SettingsTarget } from "./settings-environment-filter";
58import {
59 editDraft,
60 scheduledTaskDefaultModel,
61 scheduleFromDraft,
62 type ScheduledTaskDraft as Draft,
63} from "./scheduledTaskDraft";
64import { settingsTargetsForProject } from "./settings-environment-filter.logic";
65import { useScheduledTaskEditor } from "./scheduled-task-editor";
66import {
67 formatNextScheduledTaskRun,
68 formatScheduledTaskInterval,
69} from "./scheduledTaskPresentation";
70
71type ScheduledTaskRoutes = {
72 SettingsScheduledTaskNew: undefined;
73 SettingsScheduledTaskEdit: undefined;
74 SettingsScheduledTaskModel: undefined;
75 SettingsScheduledTaskBranch: undefined;
76};
77
78const DAYS = [
79 { index: 1, label: "Mon" },
80 { index: 2, label: "Tue" },
81 { index: 3, label: "Wed" },
82 { index: 4, label: "Thu" },
83 { index: 5, label: "Fri" },
84 { index: 6, label: "Sat" },
85 { index: 0, label: "Sun" },
86] as const;
87
88function describeSchedule(task: ScheduledTask): string {
89 if (task.schedule.type === "interval") return formatScheduledTaskInterval(task.schedule.everyMs);
90 const days = task.schedule.weekdays?.length ? repeatLabel(task.schedule.weekdays) : "Every day";
91 return `${days} at ${formatTime(task.schedule.timeOfDay)}`;
92}
93
94function formatTime(value: string): string {
95 const [hours, minutes] = value.split(":").map(Number);
96 if (!Number.isInteger(hours) || !Number.isInteger(minutes)) return value;
97 const time = new Date();
98 time.setHours(hours ?? 9, minutes ?? 0, 0, 0);
99 return time.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
100}
101
102function timePickerValue(value: string): Date {
103 const [hours, minutes] = value.split(":").map(Number);
104 const time = new Date();
105 time.setHours(
106 Number.isInteger(hours) ? (hours ?? 9) : 9,
107 Number.isInteger(minutes) ? (minutes ?? 0) : 0,
108 0,
109 0,
110 );
111 return time;
112}
113
114function repeatLabel(weekdays: ReadonlyArray<number>): string {
115 const days = new Set(weekdays);
116 if (days.size === 7) return "Every day";
117 if (days.size === 5 && [1, 2, 3, 4, 5].every((day) => days.has(day))) return "Weekdays";
118 return (
119 DAYS.filter((day) => days.has(day.index))
120 .map((day) => day.label)
121 .join(", ") || "Choose days"
122 );
123}
124
125function FormField(props: {
126 readonly label: string;
127 readonly value: string;
128 readonly onChange: (value: string) => void;
129 readonly keyboardType?: "decimal-pad";
130 readonly disabled?: boolean;
131 readonly placeholder?: string;
132 readonly borderTop?: boolean;
133}) {
134 return (
135 <View
136 className={
137 props.borderTop ? "gap-2 border-t border-border-subtle px-4 py-3" : "gap-2 px-4 py-3"
138 }
139 >
140 <Text className="text-sm text-foreground-muted">{props.label}</Text>
141 <RNTextInput
142 accessibilityLabel={props.label}
143 value={props.value}
144 readOnly={props.disabled}
145 onChangeText={props.onChange}
146 textAlignVertical="center"
147 keyboardType={props.keyboardType}
148 placeholder={props.placeholder}
149 placeholderTextColorClassName="accent-foreground-muted"
150 className="min-h-8 font-sans text-base text-foreground"
151 />
152 </View>
153 );
154}
155
156function SelectRow(props: {
157 readonly label: string;
158 readonly value: string;
159 readonly valueIcon?: ReactNode;
160 readonly actions: MenuAction[];
161 readonly onSelect: (id: string) => void;
162 readonly borderTop?: boolean;
163}) {
164 const value = (
165 <View className="min-w-0 flex-1 flex-row items-center justify-end gap-2">
166 {props.valueIcon}
167 <Text className="shrink text-right text-base text-foreground-muted" numberOfLines={1}>
168 {props.value}
169 </Text>
170 </View>
171 );
172 if (props.actions.length === 0) {
173 return (
174 <View
175 className={
176 props.borderTop
177 ? "min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3"
178 : "min-h-14 flex-row items-center gap-3 px-4 py-3"
179 }
180 >
181 <Text className="text-lg text-foreground">{props.label}</Text>
182 {value}
183 </View>
184 );
185 }
186 return (
187 <ControlPillMenu
188 actions={props.actions}
189 onPressAction={({ nativeEvent }) => props.onSelect(nativeEvent.event)}
190 >
191 <Pressable
192 accessibilityRole="button"
193 accessibilityLabel={`${props.label}, ${props.value}`}
194 className={
195 props.borderTop
196 ? "min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70"
197 : "min-h-14 flex-row items-center gap-3 px-4 py-3 active:opacity-70"
198 }
199 >
200 <Text className="text-lg text-foreground">{props.label}</Text>
201 {value}
202 <SymbolView
203 name="chevron.down"
204 size={14}
205 tintColorClassName="accent-chevron"
206 type="monochrome"
207 />
208 </Pressable>
209 </ControlPillMenu>
210 );
211}
212
213function PickerRow(props: {
214 readonly label: string;
215 readonly value: string;
216 readonly onPress: () => void;
217 readonly disabled?: boolean;
218 readonly borderTop?: boolean;
219}) {
220 return (
221 <Pressable
222 accessibilityRole="button"
223 accessibilityLabel={`${props.label}, ${props.value}`}
224 accessibilityState={{ disabled: props.disabled }}
225 disabled={props.disabled}
226 onPress={props.onPress}
227 className={
228 props.borderTop
229 ? "min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70 disabled:opacity-50"
230 : "min-h-14 flex-row items-center gap-3 px-4 py-3 active:opacity-70 disabled:opacity-50"
231 }
232 >
233 <Text className="text-lg text-foreground">{props.label}</Text>
234 <Text className="min-w-0 flex-1 text-right text-base text-foreground-muted" numberOfLines={1}>
235 {props.value}
236 </Text>
237 <SymbolView
238 name="chevron.right"
239 size={14}
240 tintColorClassName="accent-chevron"
241 type="monochrome"
242 />
243 </Pressable>
244 );
245}
246
247export function SettingsScheduledTasksRouteScreen() {
248 const [now, setNow] = useState(Date.now);
249 useFocusEffect(
250 useCallback(() => {
251 const updateNow = () => setNow(Date.now());
252 updateNow();
253 const timer = setInterval(updateNow, 60_000);
254 const subscription = AppState.addEventListener("change", (state) => {
255 if (state === "active") updateNow();
256 });
257 return () => {
258 clearInterval(timer);
259 subscription.remove();
260 };
261 }, []),
262 );
263 const { availableTargets, selectedTargets, selectedProjectKey, projectGroups } =
264 useSettingsEnvironmentFilter();
265 const selectedGroup = projectGroups.find((group) => group.key === selectedProjectKey);
266 const visibleEnvironments = settingsTargetsForProject(
267 selectedTargets,
268 selectedProjectKey === null ? null : selectedGroup,
269 );
270 const { startEditor, resetEditor } = useScheduledTaskEditor();
271 const navigation = useNavigation<NativeStackNavigationProp<ScheduledTaskRoutes>>();
272 const insets = useSafeAreaInsets();
273 const newTask = () => {
274 if (visibleEnvironments.length === 0) return;
275 resetEditor();
276 navigation.navigate("SettingsScheduledTaskNew");
277 };
278
279 return (
280 <>
281 <SettingsEnvironmentFilterHeader
282 trailingItems={[
283 withNativeGlassHeaderItem({
284 type: "button",
285 label: "",
286 accessibilityLabel: "New task",
287 icon: { type: "sfSymbol", name: "plus" } as const,
288 disabled: visibleEnvironments.length === 0,
289 onPress: newTask,
290 }),
291 ]}
292 />
293 <SettingsScreen
294 title="Scheduled Tasks"
295 trailing={
296 <View className="flex-row items-center">
297 <AndroidSettingsEnvironmentFilter />
298 <Pressable
299 accessibilityRole="button"
300 accessibilityLabel="New task"
301 accessibilityState={{ disabled: visibleEnvironments.length === 0 }}
302 disabled={visibleEnvironments.length === 0}
303 onPress={newTask}
304 className="size-11 items-center justify-center rounded-full disabled:opacity-50"
305 >
306 <SymbolView name="plus" size={22} tintColorClassName="accent-icon" />
307 </Pressable>
308 </View>
309 }
310 >
311 <ScrollView
312 keyboardShouldPersistTaps="handled"
313 keyboardDismissMode="on-drag"
314 contentInsetAdjustmentBehavior="automatic"
315 showsVerticalScrollIndicator={false}
316 className="flex-1"
317 contentContainerClassName="gap-5 px-5 pt-4"
318 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
319 >
320 {visibleEnvironments.length > 0 ? (
321 visibleEnvironments.map((environment) => (
322 <EnvironmentTasks
323 key={environment.environmentId}
324 environment={environment}
325 now={now}
326 projectIds={
327 selectedProjectKey === null
328 ? null
329 : (selectedGroup?.members
330 .filter(
331 (member) => member.project.environmentId === environment.environmentId,
332 )
333 .map((member) => member.project.id) ?? [])
334 }
335 onEdit={(task) => {
336 startEditor({
337 environmentId: environment.environmentId,
338 environmentLabel: environment.label,
339 draft: editDraft(task),
340 });
341 navigation.navigate("SettingsScheduledTaskEdit");
342 }}
343 />
344 ))
345 ) : (
346 <Text className="px-2 text-base text-foreground-muted">
347 {availableTargets.length === 0
348 ? "Connect an environment to view and create scheduled tasks."
349 : "No environments match these filters. Change the filter above."}
350 </Text>
351 )}
352 </ScrollView>
353 </SettingsScreen>
354 </>
355 );
356}
357
358export function SettingsScheduledTaskNewRouteScreen() {
359 const { resetEditor } = useScheduledTaskEditor();
360 const { availableTargets } = useSettingsEnvironmentFilter();
361 const initialized = useRef(false);
362 useLayoutEffect(() => {
363 if (initialized.current || availableTargets.length === 0) return;
364 initialized.current = true;
365 resetEditor();
366 }, [availableTargets.length, resetEditor]);
367 return <SettingsScheduledTaskEditorScreen title="New scheduled task" />;
368}
369
370export function SettingsScheduledTaskEditRouteScreen() {
371 return <SettingsScheduledTaskEditorScreen title="Edit scheduled task" />;
372}
373
374function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string }) {
375 const { editor, setEditor, hasChanges, draftForEnvironment } = useScheduledTaskEditor();
376 const { availableTargets } = useSettingsEnvironmentFilter();
377 const navigation = useNavigation();
378 const insets = useSafeAreaInsets();
379 const [saving, setSaving] = useState(false);
380 const [saved, setSaved] = useState(false);
381 const voiceOwnerId = useId();
382 const ownerKey = editor ? `${voiceOwnerId}:${editor.environmentId}` : null;
383 const prompt = editor?.draft.prompt ?? "";
384 const [selectionState, setSelectionState] = useState<{
385 readonly ownerKey: string | null;
386 readonly selection: ComposerEditorSelection;
387 } | null>(null);
388 const selection =
389 selectionState?.ownerKey === ownerKey
390 ? selectionState.selection
391 : { start: prompt.length, end: prompt.length };
392 const setSelection = (next: ComposerEditorSelection) =>
393 setSelectionState({ ownerKey, selection: next });
394 const setPrompt = (next: string) =>
395 setEditor((current) =>
396 current
397 ? {
398 ...current,
399 draft: { ...current.draft, prompt: next },
400 }
401 : current,
402 );
403 const voiceInput = useVoiceInputController({
404 ownerKey,
405 draftMessage: prompt,
406 selection,
407 onChangeSelection: setSelection,
408 onChangeDraftMessage: setPrompt,
409 disabled: saving,
410 });
411 const preventRemove = !saved && (hasChanges || saving || voiceInput.isBusy);
412 usePreventRemove(preventRemove, ({ data }) => {
413 if (saving) {
414 Alert.alert("Saving task", "Wait for the task to finish saving before leaving.");
415 return;
416 }
417 Alert.alert(
418 "Discard changes?",
419 voiceInput.isBusy
420 ? "Your dictation and unsaved changes will be lost."
421 : "Your unsaved changes will be lost.",
422 [
423 { text: "Keep editing", style: "cancel" },
424 {
425 text: "Discard changes",
426 style: "destructive",
427 onPress: () => navigation.dispatch(data.action),
428 },
429 ],
430 );
431 });
432 useEffect(() => {
433 if (!saved) return;
434 // Let the native removal guard turn off before popping the saved form.
435 const frame = requestAnimationFrame(() => {
436 if (navigation.isFocused()) navigation.goBack();
437 });
438 return () => cancelAnimationFrame(frame);
439 }, [navigation, saved]);
440 return (
441 <SettingsScreen title={title}>
442 {Platform.OS === "ios" ? (
443 <NativeStackScreenOptions
444 options={{
445 headerBackVisible: false,
446 gestureEnabled: !preventRemove,
447 // The system back button begins its native pop before the removal
448 // guard runs. Dispatch from a bar action so the guard runs first.
449 unstable_headerLeftItems: () => [
450 withNativeGlassHeaderItem({
451 type: "button",
452 label: "",
453 accessibilityLabel: "Back",
454 icon: { type: "sfSymbol", name: "chevron.backward" },
455 onPress: () => navigation.goBack(),
456 }),
457 ],
458 }}
459 />
460 ) : null}
461 <ScrollView
462 keyboardShouldPersistTaps="handled"
463 keyboardDismissMode="on-drag"
464 contentInsetAdjustmentBehavior="automatic"
465 showsVerticalScrollIndicator={false}
466 className="flex-1"
467 contentContainerClassName="gap-5 px-5 pt-4"
468 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
469 >
470 {editor ? (
471 <TaskForm
472 key={editor.environmentId}
473 environmentId={editor.environmentId}
474 environmentLabel={
475 availableTargets.find((target) => target.environmentId === editor.environmentId)
476 ?.label ?? editor.environmentLabel
477 }
478 availableTargets={availableTargets}
479 draft={editor.draft}
480 saving={saving}
481 setSaving={setSaving}
482 dictationPending={voiceInput.blocksSubmission}
483 promptField={
484 <ScheduledTaskPromptField
485 value={prompt}
486 onChange={setPrompt}
487 selection={selection}
488 onChangeSelection={setSelection}
489 disabled={saving}
490 voiceInput={voiceInput}
491 />
492 }
493 setDraft={(draft) => {
494 if (!saving) setEditor({ ...editor, draft });
495 }}
496 onSaved={() => setSaved(true)}
497 onChangeEnvironment={(target) => {
498 if (target.environmentId === editor.environmentId) return;
499 setEditor({
500 environmentId: target.environmentId,
501 environmentLabel: target.label,
502 draft: {
503 ...draftForEnvironment(target.environmentId),
504 title: editor.draft.title,
505 prompt: editor.draft.prompt,
506 schedule: editor.draft.schedule,
507 enabled: editor.draft.enabled,
508 },
509 });
510 }}
511 />
512 ) : (
513 <Text className="px-2 text-base text-foreground-muted">
514 {availableTargets.length === 0
515 ? "Connect an environment to create a scheduled task."
516 : "No environments match the current filters. Change the filters to create a task."}
517 </Text>
518 )}
519 </ScrollView>
520 </SettingsScreen>
521 );
522}
523
524function TaskForm({
525 environmentId,
526 environmentLabel,
527 availableTargets,
528 draft,
529 saving,
530 setSaving,
531 dictationPending,
532 promptField,
533 setDraft,
534 onSaved,
535 onChangeEnvironment,
536}: {
537 readonly environmentId: EnvironmentId;
538 readonly environmentLabel: string;
539 readonly availableTargets: readonly SettingsTarget[];
540 readonly draft: Draft;
541 readonly saving: boolean;
542 readonly setSaving: (saving: boolean) => void;
543 readonly dictationPending: boolean;
544 readonly promptField: ReactNode;
545 readonly setDraft: (draft: Draft) => void;
546 readonly onSaved: () => void;
547 readonly onChangeEnvironment: (target: SettingsTarget) => void;
548}) {
549 const navigation = useNavigation<NativeStackNavigationProp<ScheduledTaskRoutes>>();
550 const tasks = useEnvironmentQuery(
551 serverEnvironment.scheduledTasksLive({ environmentId, input: {} }),
552 );
553 const projects = useProjects().filter((project) => project.environmentId === environmentId);
554 const config = useEnvironmentServerConfig(environmentId);
555 const modelOptions = useMemo(() => buildModelOptions(config, null), [config]);
556 const upsert = useAtomCommand(serverEnvironment.upsertScheduledTask, {
557 label: "scheduled task upsert",
558 reportFailure: false,
559 });
560 const submissionPending = useRef(false);
561 const [timePickerOpen, setTimePickerOpen] = useState(false);
562 const taskMissing =
563 draft.task !== null &&
564 tasks.data !== null &&
565 !tasks.data.tasks.some((task) => task.id === draft.task?.id);
566 const environmentUnavailable = !availableTargets.some(
567 (target) => target.environmentId === environmentId,
568 );
569
570 const failure = (title: string, result: AtomCommandResult<unknown, unknown>) => {
571 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
572 Alert.alert(title, String(squashAtomCommandFailure(result)));
573 }
574 };
575
576 const save = async () => {
577 if (
578 submissionPending.current ||
579 saving ||
580 dictationPending ||
581 taskMissing ||
582 environmentUnavailable
583 )
584 return;
585 const schedule = scheduleFromDraft(draft.schedule);
586 if (
587 !draft.title.trim() ||
588 !draft.prompt.trim() ||
589 !draft.projectId ||
590 !draft.modelSelection ||
591 !schedule ||
592 (draft.workspace === "existing_worktree" && !draft.checkoutPath.trim())
593 ) {
594 Alert.alert(
595 "Incomplete task",
596 "Add a name, prompt, project, model, valid schedule, and checkout path if needed.",
597 );
598 return;
599 }
600 if (!projects.some((project) => project.id === draft.projectId)) {
601 Alert.alert("Project unavailable", "Choose a project in this environment.");
602 return;
603 }
604 const input: ScheduledTaskUpsertInput = {
605 ...(draft.task ? { id: draft.task.id, requireExisting: true } : {}),
606 title: draft.title.trim(),
607 prompt: draft.prompt.trim(),
608 projectId: draft.projectId,
609 modelSelection: draft.modelSelection,
610 schedule,
611 enabled: draft.enabled,
612 threadId: draft.task?.threadId ?? null,
613 workspaceStrategy:
614 draft.workspace === "root"
615 ? { type: "root" }
616 : draft.workspace === "existing_worktree"
617 ? { type: "existing_worktree", worktreePath: draft.checkoutPath.trim() }
618 : {
619 type: "worktree",
620 baseRef: draft.baseRef.trim() || "main",
621 startFromOrigin: draft.startFromOrigin,
622 },
623 runtimeMode: draft.runtimeMode,
624 interactionMode: draft.task?.interactionMode ?? "default",
625 creationSource: draft.task?.creationSource ?? "mobile",
626 };
627 // Lock before React renders, and keep successful creates locked until the form closes.
628 submissionPending.current = true;
629 setSaving(true);
630 const result = await upsert({ environmentId, input });
631 setSaving(false);
632 if (result._tag === "Failure") {
633 submissionPending.current = false;
634 failure("Could not save task", result);
635 return;
636 }
637 onSaved();
638 };
639
640 return (
641 <View
642 className="gap-5"
643 pointerEvents={saving ? "none" : "auto"}
644 accessibilityElementsHidden={saving}
645 importantForAccessibility={saving ? "no-hide-descendants" : "auto"}
646 >
647 {taskMissing ? (
648 <Text className="px-1 text-base text-danger-foreground">This task no longer exists.</Text>
649 ) : null}
650
651 {environmentUnavailable ? (
652 <Text className="px-1 text-base text-danger-foreground">
653 This environment is disconnected. Reconnect before saving.
654 </Text>
655 ) : null}
656 <SettingsSection>
657 <SelectRow
658 label="Runs on"
659 value={environmentLabel}
660 valueIcon={
661 <EnvironmentMachineSymbol
662 kind={resolveEnvironmentMachineKind(config)}
663 size={18}
664 tintColorClassName="accent-foreground-muted"
665 />
666 }
667 actions={
668 draft.task || saving || dictationPending
669 ? []
670 : availableTargets.map((target) => ({
671 id: target.environmentId,
672 title: target.label,
673 image:
674 ENVIRONMENT_MACHINE_SYMBOLS[resolveEnvironmentMachineKind(target.serverConfig)],
675 state: target.environmentId === environmentId ? "on" : undefined,
676 }))
677 }
678 onSelect={(id) => {
679 const target = availableTargets.find((entry) => entry.environmentId === id);
680 if (target) onChangeEnvironment(target);
681 }}
682 />
683 </SettingsSection>
684 <SettingsSection title="Task">
685 <FormField
686 label="Name"
687 disabled={saving}
688 value={draft.title}
689 placeholder="Check for issues"
690 onChange={(title) => setDraft({ ...draft, title })}
691 />
692 {promptField}
693 </SettingsSection>
694
695 <SettingsSection title="Context">
696 <SelectRow
697 label="Project"
698 value={
699 projects.find((project) => project.id === draft.projectId)?.title ??
700 (projects.length ? "Choose project" : "No projects available")
701 }
702 actions={projects.map((project) => ({
703 id: project.id,
704 title: project.title,
705 state: project.id === draft.projectId ? "on" : undefined,
706 }))}
707 onSelect={(id) => {
708 const project = projects.find((item) => item.id === id);
709 if (project)
710 setDraft({
711 ...draft,
712 projectId: project.id,
713 modelSelection: draft.modelSelectionIsExplicit
714 ? draft.modelSelection
715 : scheduledTaskDefaultModel(config, project),
716 });
717 }}
718 />
719 <PickerRow
720 label="Model"
721 borderTop
722 value={
723 modelOptions.find(
724 (option) =>
725 option.selection.instanceId === draft.modelSelection?.instanceId &&
726 option.selection.model === draft.modelSelection?.model,
727 )?.label ??
728 draft.modelSelection?.model ??
729 (modelOptions.length ? "Choose model" : "No models available")
730 }
731 onPress={() => navigation.navigate("SettingsScheduledTaskModel")}
732 disabled={saving || dictationPending || environmentUnavailable}
733 />
734 </SettingsSection>
735
736 <SettingsSection title="Workspace">
737 <SelectRow
738 label="Run in"
739 value={
740 draft.workspace === "worktree"
741 ? "New worktree"
742 : draft.workspace === "root"
743 ? "Project checkout"
744 : "Specific checkout"
745 }
746 actions={[
747 {
748 id: "worktree",
749 title: "New worktree",
750 state: draft.workspace === "worktree" ? "on" : undefined,
751 },
752 {
753 id: "root",
754 title: "Project checkout",
755 state: draft.workspace === "root" ? "on" : undefined,
756 },
757 {
758 id: "existing_worktree",
759 title: "Specific checkout",
760 state: draft.workspace === "existing_worktree" ? "on" : undefined,
761 },
762 ]}
763 onSelect={(id) => {
764 if (id === "worktree" || id === "root" || id === "existing_worktree")
765 setDraft({ ...draft, workspace: id });
766 }}
767 />
768 {draft.workspace === "worktree" ? (
769 <PickerRow
770 label="Base branch"
771 value={resolveNewTaskBranchLabel({
772 branchName: draft.baseRef,
773 startFromOrigin: draft.startFromOrigin,
774 workspaceMode: "worktree",
775 })}
776 borderTop
777 disabled={!draft.projectId || saving || dictationPending || environmentUnavailable}
778 onPress={() => navigation.navigate("SettingsScheduledTaskBranch")}
779 />
780 ) : null}
781 {draft.workspace === "existing_worktree" ? (
782 <FormField
783 label="Checkout path"
784 disabled={saving}
785 value={draft.checkoutPath}
786 borderTop
787 onChange={(checkoutPath) => setDraft({ ...draft, checkoutPath })}
788 />
789 ) : null}
790 </SettingsSection>
791
792 <SettingsSection title="Schedule">
793 <View className="px-4 py-3">
794 <SegmentedControl
795 options={[
796 { value: "fixed_time", label: "At a time" },
797 { value: "interval", label: "Every interval" },
798 ]}
799 selected={draft.schedule.mode}
800 onSelect={(mode) => {
801 setTimePickerOpen(false);
802 setDraft({ ...draft, schedule: { ...draft.schedule, mode } });
803 }}
804 />
805 </View>
806 {draft.schedule.mode === "fixed_time" ? (
807 <>
808 <Pressable
809 accessibilityRole="button"
810 accessibilityLabel={`Time, ${formatTime(draft.schedule.timeOfDay)}`}
811 onPress={() => setTimePickerOpen((open) => !open)}
812 className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70"
813 >
814 <Text className="text-lg text-foreground">Time</Text>
815 <Text className="min-w-0 flex-1 text-right text-base text-foreground-muted">
816 {formatTime(draft.schedule.timeOfDay)}
817 </Text>
818 <SymbolView
819 name="chevron.right"
820 size={14}
821 tintColorClassName="accent-chevron"
822 type="monochrome"
823 />
824 </Pressable>
825 {timePickerOpen ? (
826 <DateTimePicker
827 value={timePickerValue(draft.schedule.timeOfDay)}
828 mode="time"
829 display={Platform.OS === "ios" ? "spinner" : "default"}
830 onDismiss={() => setTimePickerOpen(false)}
831 onValueChange={(_, selected) => {
832 const timeOfDay = `${String(selected.getHours()).padStart(2, "0")}:${String(selected.getMinutes()).padStart(2, "0")}`;
833 setDraft({ ...draft, schedule: { ...draft.schedule, timeOfDay } });
834 }}
835 />
836 ) : null}
837 <SelectRow
838 label="Repeat"
839 value={repeatLabel(draft.schedule.weekdays)}
840 borderTop
841 actions={[
842 {
843 id: "every_day",
844 title: "Every day",
845 state: draft.schedule.weekdays.length === 7 ? "on" : undefined,
846 },
847 {
848 id: "weekdays",
849 title: "Weekdays",
850 state: repeatLabel(draft.schedule.weekdays) === "Weekdays" ? "on" : undefined,
851 },
852 ...DAYS.map((day) => ({
853 id: String(day.index),
854 title: day.label,
855 attributes: { keepsMenuPresented: true },
856 state: draft.schedule.weekdays.includes(day.index) ? ("on" as const) : undefined,
857 })),
858 ]}
859 onSelect={(id) => {
860 const weekdays =
861 id === "every_day"
862 ? DAYS.map((day) => day.index)
863 : id === "weekdays"
864 ? [1, 2, 3, 4, 5]
865 : (() => {
866 const day = DAYS.find((item) => String(item.index) === id);
867 if (!day) return draft.schedule.weekdays;
868 return draft.schedule.weekdays.includes(day.index)
869 ? draft.schedule.weekdays.filter((index) => index !== day.index)
870 : [...draft.schedule.weekdays, day.index];
871 })();
872 setDraft({ ...draft, schedule: { ...draft.schedule, weekdays } });
873 }}
874 />
875 </>
876 ) : (
877 <>
878 <FormField
879 label="Minutes between runs"
880 value={draft.schedule.intervalMinutes}
881 keyboardType="decimal-pad"
882 disabled={saving}
883 borderTop
884 onChange={(intervalMinutes) =>
885 setDraft({ ...draft, schedule: { ...draft.schedule, intervalMinutes } })
886 }
887 />
888 {Number(draft.schedule.intervalMinutes) < 1 ? (
889 <Text className="px-4 pb-3 text-sm text-danger-foreground">
890 Intervals must be at least 1 minute. Update this interval before saving.
891 </Text>
892 ) : draft.task?.schedule.type === "interval" && draft.task.schedule.everyMs < 60_000 ? (
893 <Text className="px-4 pb-3 text-sm text-foreground-muted">
894 This task previously ran more than once per minute. Saving requires an interval of
895 at least 1 minute.
896 </Text>
897 ) : null}
898 </>
899 )}
900 <View className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3">
901 <Text className="min-w-0 flex-1 text-lg text-foreground">Enabled</Text>
902 <ThemedSwitch
903 accessibilityLabel="Task enabled"
904 value={draft.enabled}
905 onValueChange={(enabled) => setDraft({ ...draft, enabled })}
906 />
907 </View>
908 </SettingsSection>
909 {draft.schedule.mode === "fixed_time" ? (
910 <Text className="px-2 text-sm text-foreground-muted">
911 Time uses the environment's time zone, which may differ from your phone's.
912 </Text>
913 ) : null}
914 <Pressable
915 accessibilityRole="button"
916 accessibilityState={{
917 disabled: saving || dictationPending || taskMissing || environmentUnavailable,
918 }}
919 disabled={saving || dictationPending || taskMissing || environmentUnavailable}
920 onPress={() => void save()}
921 className="min-h-12 items-center justify-center rounded-[14px] bg-primary px-4 disabled:opacity-50"
922 >
923 <Text className="text-base font-t3-medium text-primary-foreground">
924 {saving ? "Saving…" : draft.task ? "Save changes" : "Create task"}
925 </Text>
926 </Pressable>
927 </View>
928 );
929}
930
931function EnvironmentTasks({
932 environment,
933 now,
934 projectIds,
935 onEdit,
936}: {
937 readonly environment: SettingsTarget;
938 readonly now: number;
939 readonly projectIds: readonly ProjectId[] | null;
940 readonly onEdit: (task: ScheduledTask) => void;
941}) {
942 const environmentId = environment.environmentId;
943 const tasks = useEnvironmentQuery(
944 serverEnvironment.scheduledTasksLive({ environmentId, input: {} }),
945 );
946 const visibleTasks = tasks.data?.tasks.filter(
947 (task) => projectIds === null || projectIds.includes(task.projectId),
948 );
949 const setEnabled = useAtomCommand(serverEnvironment.setScheduledTaskEnabled, {
950 label: "scheduled task enabled",
951 reportFailure: false,
952 });
953 const runNow = useAtomCommand(serverEnvironment.runScheduledTaskNow, {
954 label: "scheduled task run",
955 reportFailure: false,
956 });
957 const remove = useAtomCommand(serverEnvironment.deleteScheduledTask, {
958 label: "scheduled task delete",
959 reportFailure: false,
960 });
961 const failure = (title: string, result: AtomCommandResult<unknown, unknown>) => {
962 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
963 Alert.alert(title, String(squashAtomCommandFailure(result)));
964 }
965 };
966
967 const act = async (task: ScheduledTask, action: "run" | "toggle" | "delete") => {
968 const result =
969 action === "run"
970 ? await runNow({ environmentId, input: { id: task.id } })
971 : action === "toggle"
972 ? await setEnabled({ environmentId, input: { id: task.id, enabled: !task.enabled } })
973 : await remove({ environmentId, input: { id: task.id } });
974 failure(`Could not ${action === "toggle" ? "update" : action} task`, result);
975 };
976
977 return (
978 <SettingsSection
979 title={environment.label}
980 titleIcon={
981 <EnvironmentMachineSymbol
982 kind={resolveEnvironmentMachineKind(environment.serverConfig)}
983 size={16}
984 tintColorClassName={
985 Platform.OS === "android" ? "accent-primary" : "accent-foreground-muted"
986 }
987 />
988 }
989 >
990 {tasks.error ? (
991 <Text className="p-4 text-base text-danger-foreground">{tasks.error}</Text>
992 ) : !tasks.data ? (
993 <Text className="p-4 text-base text-foreground-muted">Loading tasks…</Text>
994 ) : visibleTasks?.length === 0 ? (
995 <Text className="p-4 text-base text-foreground-muted">
996 {projectIds === null ? "No scheduled tasks yet." : "No tasks in this project."}
997 </Text>
998 ) : (
999 visibleTasks?.map((task, index) => (
1000 <View
1001 key={task.id}
1002 className={
1003 index === 0
1004 ? "flex-row items-start gap-1 px-4 py-4"
1005 : "flex-row items-start gap-1 border-t border-border-subtle px-4 py-4"
1006 }
1007 >
1008 <Pressable
1009 accessibilityRole="button"
1010 accessibilityLabel={`Edit ${task.title}`}
1011 onPress={() => {
1012 onEdit(task);
1013 }}
1014 className="min-w-0 flex-1 gap-1 active:opacity-70"
1015 >
1016 <Text className="text-lg font-t3-medium text-foreground" numberOfLines={1}>
1017 {task.title}
1018 </Text>
1019 <Text className="text-sm text-foreground-muted" numberOfLines={2}>
1020 {describeSchedule(task)}
1021 {!task.enabled
1022 ? " · Paused"
1023 : task.nextRunAt
1024 ? ` · ${formatNextScheduledTaskRun(task.nextRunAt, now)}`
1025 : ""}
1026 </Text>
1027 {task.lastRunError ? (
1028 <Text className="text-sm text-danger-foreground" numberOfLines={2}>
1029 Last run failed: {task.lastRunError}
1030 </Text>
1031 ) : null}
1032 </Pressable>
1033 <ControlPillMenu
1034 actions={[
1035 { id: "edit", title: "Edit" },
1036 { id: "toggle", title: task.enabled ? "Pause" : "Resume" },
1037 { id: "run", title: "Run now" },
1038 { id: "delete", title: "Delete", attributes: { destructive: true } },
1039 ]}
1040 onPressAction={({ nativeEvent }) => {
1041 const action = nativeEvent.event;
1042 if (action === "edit") {
1043 onEdit(task);
1044 } else if (action === "delete") {
1045 Alert.alert("Delete task?", task.title, [
1046 { text: "Cancel", style: "cancel" },
1047 {
1048 text: "Delete",
1049 style: "destructive",
1050 onPress: () => void act(task, "delete"),
1051 },
1052 ]);
1053 } else if (action === "toggle" || action === "run") {
1054 void act(task, action);
1055 }
1056 }}
1057 >
1058 <Pressable
1059 accessibilityRole="button"
1060 accessibilityLabel={`Actions for ${task.title}`}
1061 className="h-11 w-11 items-center justify-center"
1062 >
1063 <SymbolView
1064 name="ellipsis"
1065 size={18}
1066 tintColorClassName="accent-icon"
1067 type="monochrome"
1068 />
1069 </Pressable>
1070 </ControlPillMenu>
1071 </View>
1072 ))
1073 )}
1074 </SettingsSection>
1075 );
1076}