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