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