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 { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
30import { useFocusEffect, useNavigation, usePreventRemove } from "@react-navigation/native";
31import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
32import { AppState, Platform, Pressable, TextInput as RNTextInput, View } from "react-native";
33import { useSafeAreaInsets } from "react-native-safe-area-context";
34
35import { Button } from "../../components/ui/Button";
36import { AppText as Text } from "../../components/ui/AppText";
37import { SymbolView } from "../../components/ui/AppSymbol";
38import {
39 EnvironmentMachineSymbol,
40 ENVIRONMENT_MACHINE_SYMBOLS,
41} from "../../components/EnvironmentMachineSymbol";
42import { Menu } from "../../components/ui/Menu";
43import type { ComposerEditorSelection } from "../../components/ComposerEditor";
44import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
45import { SegmentedControl } from "../../components/ui/SegmentedControl";
46import { ThemedSwitch } from "../../components/ui/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 <Menu
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 </Menu>
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 const updateNow = () => setNow(Date.now());
263 updateNow();
264 const timer = setInterval(updateNow, 60_000);
265 const subscription = AppState.addEventListener("change", (state) => {
266 if (state === "active") updateNow();
267 });
268 return () => {
269 clearInterval(timer);
270 subscription.remove();
271 };
272 });
273 const { availableTargets, selectedTargets, selectedProjectKey, projectGroups } =
274 useSettingsEnvironmentFilter();
275 const selectedGroup = projectGroups.find((group) => group.key === selectedProjectKey);
276 const visibleEnvironments = settingsTargetsForProject(
277 selectedTargets,
278 selectedProjectKey === null ? null : selectedGroup,
279 );
280 const { startEditor, resetEditor } = useScheduledTaskEditor();
281 const navigation = useNavigation<NativeStackNavigationProp<ScheduledTaskRoutes>>();
282 const insets = useSafeAreaInsets();
283 const newTask = () => {
284 if (visibleEnvironments.length === 0) return;
285 resetEditor();
286 navigation.navigate("SettingsScheduledTaskNew");
287 };
288
289 return (
290 <>
291 <SettingsEnvironmentFilterHeader
292 trailingItems={[
293 withNativeGlassHeaderItem({
294 type: "button",
295 label: "",
296 accessibilityLabel: "New task",
297 icon: { type: "sfSymbol", name: "plus" } as const,
298 disabled: visibleEnvironments.length === 0,
299 onPress: newTask,
300 }),
301 ]}
302 />
303 <SettingsScreen
304 title="Scheduled Tasks"
305 trailing={
306 <View className="flex-row items-center">
307 <AndroidSettingsEnvironmentFilter />
308 <Pressable
309 accessibilityRole="button"
310 accessibilityLabel="New task"
311 accessibilityState={{ disabled: visibleEnvironments.length === 0 }}
312 disabled={visibleEnvironments.length === 0}
313 onPress={newTask}
314 className="size-11 items-center justify-center rounded-full disabled:opacity-50"
315 >
316 <SymbolView name="plus" size={22} tintColorClassName="accent-icon" />
317 </Pressable>
318 </View>
319 }
320 >
321 <ScrollView
322 keyboardShouldPersistTaps="handled"
323 keyboardDismissMode="on-drag"
324 contentInsetAdjustmentBehavior="automatic"
325 showsVerticalScrollIndicator={false}
326 className="flex-1"
327 contentContainerClassName="gap-5 px-5 pt-4"
328 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
329 >
330 {visibleEnvironments.length > 0 ? (
331 visibleEnvironments.map((environment) => (
332 <EnvironmentTasks
333 key={environment.environmentId}
334 environment={environment}
335 now={now}
336 projectIds={
337 selectedProjectKey === null
338 ? null
339 : (selectedGroup?.members
340 .filter(
341 (member) => member.project.environmentId === environment.environmentId,
342 )
343 .map((member) => member.project.id) ?? [])
344 }
345 onEdit={(task) => {
346 startEditor({
347 environmentId: environment.environmentId,
348 environmentLabel: environment.label,
349 draft: editDraft(task),
350 });
351 navigation.navigate("SettingsScheduledTaskEdit");
352 }}
353 />
354 ))
355 ) : (
356 <Text className="px-2 text-base text-foreground-muted">
357 {availableTargets.length === 0
358 ? "Connect an environment to view and create scheduled tasks."
359 : "No environments match these filters. Change the filter above."}
360 </Text>
361 )}
362 </ScrollView>
363 </SettingsScreen>
364 </>
365 );
366}
367
368export function SettingsScheduledTaskNewRouteScreen() {
369 const { resetEditor } = useScheduledTaskEditor();
370 const { availableTargets } = useSettingsEnvironmentFilter();
371 const initialized = useRef(false);
372 useLayoutEffect(() => {
373 if (initialized.current || availableTargets.length === 0) return;
374 initialized.current = true;
375 resetEditor();
376 }, [availableTargets.length, resetEditor]);
377 return <SettingsScheduledTaskEditorScreen title="New scheduled task" />;
378}
379
380export function SettingsScheduledTaskEditRouteScreen() {
381 return <SettingsScheduledTaskEditorScreen title="Edit scheduled task" />;
382}
383
384function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string }) {
385 const {
386 editor,
387 voiceOwnerKey,
388 readEditor,
389 setEditor,
390 startEditor,
391 hasChanges,
392 draftForEnvironment,
393 } = useScheduledTaskEditor();
394 const { availableTargets } = useSettingsEnvironmentFilter();
395 const navigation = useNavigation();
396 const insets = useSafeAreaInsets();
397 const [saving, setSaving] = useState(false);
398 const [saved, setSaved] = useState(false);
399 const ownerKey = editor ? `${voiceOwnerKey}:${editor.environmentId}` : null;
400 const prompt = editor?.draft.prompt ?? "";
401 const [selectionState, setSelectionState] = useState<{
402 readonly ownerKey: string | null;
403 readonly selection: ComposerEditorSelection;
404 } | null>(null);
405 const selection =
406 selectionState?.ownerKey === ownerKey
407 ? selectionState.selection
408 : { start: prompt.length, end: prompt.length };
409 const setSelection = (next: ComposerEditorSelection) =>
410 setSelectionState({ ownerKey, selection: next });
411 const setPrompt = (next: string) =>
412 setEditor((current) =>
413 current
414 ? {
415 ...current,
416 draft: { ...current.draft, prompt: next },
417 }
418 : current,
419 );
420 const voiceInput = useVoiceInputController({
421 ownerKey,
422 label: editor?.draft.title.trim() || title,
423 subscribeToDraftChanges: (onChange) =>
424 appAtomRegistry.subscribe(scheduledTaskEditorSessionAtom, onChange),
425 selection,
426 readDraftMessage: () => {
427 const current = readEditor();
428 if (current?.environmentId !== editor?.environmentId) return null;
429 return current?.draft.prompt ?? null;
430 },
431 onChangeSelection: setSelection,
432 onChangeDraftMessage: (text) => {
433 if (readEditor()?.environmentId === editor?.environmentId) setPrompt(text);
434 },
435 disabled: saving,
436 });
437 const preventRemove = !saved && (hasChanges || saving);
438 usePreventRemove(preventRemove, ({ data }) => {
439 if (saving) {
440 Dialog.alert("Saving task", "Wait for the task to finish saving before leaving.");
441 return;
442 }
443 Dialog.alert("Discard changes?", "Your unsaved changes will be lost.", [
444 { text: "Keep editing", style: "cancel" },
445 {
446 text: "Discard changes",
447 style: "destructive",
448 onPress: () => {
449 if (voiceInput.isBusy) voiceInput.cancel();
450 startEditor(null);
451 navigation.dispatch(data.action);
452 },
453 },
454 ]);
455 });
456 useEffect(() => {
457 if (!saved) return;
458 const frame = requestAnimationFrame(() => {
459 if (navigation.isFocused()) navigation.goBack();
460 });
461 return () => cancelAnimationFrame(frame);
462 }, [navigation, saved]);
463 return (
464 <SettingsScreen title={title}>
465 {Platform.OS === "ios" ? (
466 <NativeStackScreenOptions
467 options={{
468 headerBackVisible: false,
469 gestureEnabled: !preventRemove,
470 // The system back button begins its native pop before the removal
471 // guard runs. Dispatch from a bar action so the guard runs first.
472 unstable_headerLeftItems: () => [
473 withNativeGlassHeaderItem({
474 type: "button",
475 label: "",
476 accessibilityLabel: "Back",
477 icon: { type: "sfSymbol", name: "chevron.backward" },
478 onPress: () => navigation.goBack(),
479 }),
480 ],
481 }}
482 />
483 ) : null}
484 <ScrollView
485 keyboardShouldPersistTaps="handled"
486 keyboardDismissMode="on-drag"
487 contentInsetAdjustmentBehavior="automatic"
488 showsVerticalScrollIndicator={false}
489 className="flex-1"
490 contentContainerClassName="gap-5 px-5 pt-4"
491 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
492 >
493 {editor ? (
494 <TaskForm
495 key={editor.environmentId}
496 environmentId={editor.environmentId}
497 environmentLabel={
498 availableTargets.find((target) => target.environmentId === editor.environmentId)
499 ?.label ?? editor.environmentLabel
500 }
501 availableTargets={availableTargets}
502 draft={editor.draft}
503 saving={saving}
504 setSaving={setSaving}
505 dictationPending={voiceInput.blocksSubmission}
506 promptField={
507 <ScheduledTaskPromptField
508 value={prompt}
509 onChange={setPrompt}
510 selection={selection}
511 onChangeSelection={setSelection}
512 disabled={saving}
513 voiceInput={voiceInput}
514 />
515 }
516 setDraft={(draft) => {
517 if (!saving) setEditor({ ...editor, draft });
518 }}
519 onSaved={() => setSaved(true)}
520 onChangeEnvironment={(target) => {
521 if (target.environmentId === editor.environmentId) return;
522 setEditor({
523 environmentId: target.environmentId,
524 environmentLabel: target.label,
525 draft: {
526 ...draftForEnvironment(target.environmentId),
527 title: editor.draft.title,
528 prompt: editor.draft.prompt,
529 schedule: editor.draft.schedule,
530 enabled: editor.draft.enabled,
531 },
532 });
533 }}
534 />
535 ) : (
536 <Text className="px-2 text-base text-foreground-muted">
537 {availableTargets.length === 0
538 ? "Connect an environment to create a scheduled task."
539 : "No environments match the current filters. Change the filters to create a task."}
540 </Text>
541 )}
542 </ScrollView>
543 </SettingsScreen>
544 );
545}
546
547function TaskForm({
548 environmentId,
549 environmentLabel,
550 availableTargets,
551 draft,
552 saving,
553 setSaving,
554 dictationPending,
555 promptField,
556 setDraft,
557 onSaved,
558 onChangeEnvironment,
559}: {
560 readonly environmentId: EnvironmentId;
561 readonly environmentLabel: string;
562 readonly availableTargets: readonly SettingsTarget[];
563 readonly draft: Draft;
564 readonly saving: boolean;
565 readonly setSaving: (saving: boolean) => void;
566 readonly dictationPending: boolean;
567 readonly promptField: ReactNode;
568 readonly setDraft: (draft: Draft) => void;
569 readonly onSaved: () => void;
570 readonly onChangeEnvironment: (target: SettingsTarget) => void;
571}) {
572 const navigation = useNavigation<NativeStackNavigationProp<ScheduledTaskRoutes>>();
573 const tasks = useEnvironmentQuery(
574 serverEnvironment.scheduledTasksLive({ environmentId, input: {} }),
575 );
576 const projects = useProjects().filter((project) => project.environmentId === environmentId);
577 const config = useEnvironmentServerConfig(environmentId);
578 const modelOptions = buildModelOptions(config, null, undefined, draft.projectId);
579 const canOperate = useAtomValue(
580 serverEnvironment.upsertScheduledTask.permissionAtom(environmentId),
581 );
582 const upsert = useAtomCommand(serverEnvironment.upsertScheduledTask, {
583 label: "scheduled task upsert",
584 reportFailure: false,
585 });
586 const submissionPending = useRef(false);
587 const [timePickerOpen, setTimePickerOpen] = useState(false);
588 const taskMissing =
589 draft.task !== null &&
590 tasks.data !== null &&
591 !tasks.data.tasks.some((task) => task.id === draft.task?.id);
592 const environmentUnavailable = !availableTargets.some(
593 (target) => target.environmentId === environmentId,
594 );
595
596 const failure = (title: string, result: AtomCommandResult<unknown, unknown>) => {
597 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
598 Dialog.alert(title, String(squashAtomCommandFailure(result)));
599 }
600 };
601
602 const save = async () => {
603 if (
604 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
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 Dialog.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 Dialog.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 Dialog.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 submissionPending.current = true;
672 setSaving(true);
673 const result = await upsert({ environmentId, input });
674 setSaving(false);
675 if (result._tag === "Failure") {
676 submissionPending.current = false;
677 failure("Could not save task", result);
678 return;
679 }
680 onSaved();
681 };
682
683 return (
684 <View className="gap-5">
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[
719 resolveEnvironmentMachineKind(target.serverConfig)
720 ],
721 state: target.environmentId === environmentId ? "on" : undefined,
722 }))
723 }
724 onSelect={(id) => {
725 const target = availableTargets.find((entry) => entry.environmentId === id);
726 if (target) onChangeEnvironment(target);
727 }}
728 />
729 </SettingsSection>
730 <SettingsSection title="Task">
731 <FormField
732 label="Name"
733 disabled={saving}
734 value={draft.title}
735 placeholder="Check for issues"
736 onChange={(title) => setDraft({ ...draft, title })}
737 />
738 {promptField}
739 </SettingsSection>
740
741 <SettingsSection title="Context">
742 <SelectRow
743 label="Project"
744 value={
745 projects.find((project) => project.id === draft.projectId)?.title ??
746 (projects.length ? "Choose project" : "No projects available")
747 }
748 actions={projects.map((project) => ({
749 id: project.id,
750 title: project.title,
751 state: project.id === draft.projectId ? "on" : undefined,
752 }))}
753 onSelect={(id) => {
754 const project = projects.find((item) => item.id === id);
755 if (!project) return;
756 const keepsExplicitModel =
757 draft.modelSelectionIsExplicit &&
758 (draft.modelSelection === null ||
759 !config?.settings ||
760 resolveProjectProviderInstanceEnabled(
761 config.settings,
762 project.id,
763 draft.modelSelection.instanceId,
764 ));
765 setDraft({
766 ...draft,
767 projectId: project.id,
768 modelSelection: keepsExplicitModel
769 ? draft.modelSelection
770 : scheduledTaskDefaultModel(config, project),
771 modelSelectionIsExplicit: keepsExplicitModel,
772 });
773 }}
774 />
775 <PickerRow
776 label="Model"
777 borderTop
778 value={
779 modelOptions.find(
780 (option) =>
781 option.selection.instanceId === draft.modelSelection?.instanceId &&
782 option.selection.model === draft.modelSelection?.model,
783 )?.label ??
784 draft.modelSelection?.model ??
785 (modelOptions.length ? "Choose model" : "No models available")
786 }
787 onPress={() => navigation.navigate("SettingsScheduledTaskModel")}
788 disabled={saving || dictationPending || environmentUnavailable}
789 />
790 </SettingsSection>
791
792 <SettingsSection title="Workspace">
793 <SelectRow
794 label="Run in"
795 value={
796 draft.workspace === "worktree"
797 ? "New worktree"
798 : draft.workspace === "root"
799 ? "Project checkout"
800 : "Specific checkout"
801 }
802 actions={[
803 {
804 id: "worktree",
805 title: "New worktree",
806 state: draft.workspace === "worktree" ? "on" : undefined,
807 },
808 {
809 id: "root",
810 title: "Project checkout",
811 state: draft.workspace === "root" ? "on" : undefined,
812 },
813 {
814 id: "existing_worktree",
815 title: "Specific checkout",
816 state: draft.workspace === "existing_worktree" ? "on" : undefined,
817 },
818 ]}
819 onSelect={(id) => {
820 if (id === "worktree" || id === "root" || id === "existing_worktree")
821 setDraft({ ...draft, workspace: id });
822 }}
823 />
824 {draft.workspace === "worktree" ? (
825 <PickerRow
826 label="Base branch"
827 value={resolveNewTaskBranchLabel({
828 branchName: draft.baseRef,
829 startFromOrigin: draft.startFromOrigin,
830 workspaceMode: "worktree",
831 })}
832 borderTop
833 disabled={!draft.projectId || saving || dictationPending || environmentUnavailable}
834 onPress={() => navigation.navigate("SettingsScheduledTaskBranch")}
835 />
836 ) : null}
837 {draft.workspace === "existing_worktree" ? (
838 <FormField
839 label="Checkout path"
840 disabled={saving}
841 value={draft.checkoutPath}
842 borderTop
843 onChange={(checkoutPath) => setDraft({ ...draft, checkoutPath })}
844 />
845 ) : null}
846 </SettingsSection>
847
848 <SettingsSection title="Schedule">
849 <View className="px-4 py-3">
850 <SegmentedControl
851 options={[
852 { value: "fixed_time", label: "At a time" },
853 { value: "interval", label: "Interval" },
854 { value: "webhook", label: "On webhook" },
855 ]}
856 selected={draft.schedule.mode}
857 onSelect={(mode) => {
858 setTimePickerOpen(false);
859 setDraft({
860 ...draft,
861 prompt:
862 mode === "webhook" && !draft.prompt.trim()
863 ? DEFAULT_WEBHOOK_PROMPT
864 : draft.prompt,
865 schedule: { ...draft.schedule, mode },
866 });
867 }}
868 />
869 </View>
870 {draft.schedule.mode === "fixed_time" ? (
871 <>
872 <Pressable
873 accessibilityRole="button"
874 accessibilityLabel={`Time, ${formatTime(draft.schedule.timeOfDay)}`}
875 onPress={() => setTimePickerOpen((open) => !open)}
876 className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70"
877 >
878 <Text className="text-lg text-foreground">Time</Text>
879 <Text className="min-w-0 flex-1 text-right text-base text-foreground-muted">
880 {formatTime(draft.schedule.timeOfDay)}
881 </Text>
882 <SymbolView
883 name="chevron.right"
884 size={14}
885 tintColorClassName="accent-chevron"
886 type="monochrome"
887 />
888 </Pressable>
889 {timePickerOpen ? (
890 <DateTimePicker
891 value={timePickerValue(draft.schedule.timeOfDay)}
892 mode="time"
893 display={Platform.OS === "ios" ? "spinner" : "default"}
894 onDismiss={() => setTimePickerOpen(false)}
895 onValueChange={(_, selected) => {
896 const timeOfDay = `${String(selected.getHours()).padStart(2, "0")}:${String(selected.getMinutes()).padStart(2, "0")}`;
897 setDraft({ ...draft, schedule: { ...draft.schedule, timeOfDay } });
898 }}
899 />
900 ) : null}
901 <SelectRow
902 label="Repeat"
903 value={repeatLabel(draft.schedule.weekdays)}
904 borderTop
905 actions={[
906 {
907 id: "every_day",
908 title: "Every day",
909 state: draft.schedule.weekdays.length === 7 ? "on" : undefined,
910 },
911 {
912 id: "weekdays",
913 title: "Weekdays",
914 state: repeatLabel(draft.schedule.weekdays) === "Weekdays" ? "on" : undefined,
915 },
916 ...DAYS.map((day) => ({
917 id: String(day.index),
918 title: day.label,
919 attributes: { keepsMenuPresented: true },
920 state: draft.schedule.weekdays.includes(day.index)
921 ? ("on" as const)
922 : undefined,
923 })),
924 ]}
925 onSelect={(id) => {
926 const weekdays =
927 id === "every_day"
928 ? DAYS.map((day) => day.index)
929 : id === "weekdays"
930 ? [1, 2, 3, 4, 5]
931 : (() => {
932 const day = DAYS.find((item) => String(item.index) === id);
933 if (!day) return draft.schedule.weekdays;
934 return draft.schedule.weekdays.includes(day.index)
935 ? draft.schedule.weekdays.filter((index) => index !== day.index)
936 : [...draft.schedule.weekdays, day.index];
937 })();
938 setDraft({ ...draft, schedule: { ...draft.schedule, weekdays } });
939 }}
940 />
941 </>
942 ) : draft.schedule.mode === "webhook" ? (
943 <>
944 <WebhookScheduleDetails
945 environmentId={environmentId}
946 // The live row, so a rotated URL shows up without reopening the form.
947 // Once the list has loaded, a missing task is gone; don't keep showing its URL.
948 task={
949 tasks.data
950 ? (tasks.data.tasks.find((task) => task.id === draft.task?.id) ?? null)
951 : draft.task
952 }
953 signatureConfigured={draft.schedule.signature !== null}
954 disabled={!canOperate || saving || environmentUnavailable}
955 />
956 <FormField
957 label="Skip requests older than (minutes)"
958 value={draft.schedule.maxDeliveryAgeMinutes}
959 placeholder="Run every request"
960 keyboardType="number-pad"
961 disabled={saving}
962 borderTop
963 onChange={(maxDeliveryAgeMinutes) =>
964 setDraft({ ...draft, schedule: { ...draft.schedule, maxDeliveryAgeMinutes } })
965 }
966 />
967 </>
968 ) : (
969 <>
970 <FormField
971 label="Minutes between runs"
972 value={draft.schedule.intervalMinutes}
973 keyboardType="decimal-pad"
974 disabled={saving}
975 borderTop
976 onChange={(intervalMinutes) =>
977 setDraft({ ...draft, schedule: { ...draft.schedule, intervalMinutes } })
978 }
979 />
980 {Number(draft.schedule.intervalMinutes) < 1 ? (
981 <Text className="px-4 pb-3 text-sm text-danger-foreground">
982 Intervals must be at least 1 minute. Update this interval before saving.
983 </Text>
984 ) : draft.task?.schedule.type === "interval" &&
985 draft.task.schedule.everyMs < 60_000 ? (
986 <Text className="px-4 pb-3 text-sm text-foreground-muted">
987 This task previously ran more than once per minute. Saving requires an interval of
988 at least 1 minute.
989 </Text>
990 ) : null}
991 </>
992 )}
993 <View className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3">
994 <Text className="min-w-0 flex-1 text-lg text-foreground">Enabled</Text>
995 <ThemedSwitch
996 accessibilityLabel="Task enabled"
997 value={draft.enabled}
998 onValueChange={(enabled) => setDraft({ ...draft, enabled })}
999 />
1000 </View>
1001 </SettingsSection>
1002 {draft.schedule.mode === "fixed_time" ? (
1003 <Text className="px-2 text-sm text-foreground-muted">
1004 Time uses the environment's time zone, which may differ from your phone's.
1005 </Text>
1006 ) : null}
1007 </View>
1008 <Button
1009 tone="primary"
1010 fullWidth
1011 loading={saving}
1012 disabled={!canOperate || dictationPending || taskMissing || environmentUnavailable}
1013 onPress={() => void save()}
1014 label={saving ? "Saving…" : draft.task ? "Save changes" : "Create task"}
1015 />
1016 </View>
1017 );
1018}
1019
1020function WebhookScheduleDetails({
1021 environmentId,
1022 task,
1023 signatureConfigured,
1024 disabled,
1025}: {
1026 readonly environmentId: EnvironmentId;
1027 readonly task: ScheduledTask | null;
1028 readonly signatureConfigured: boolean;
1029 readonly disabled: boolean;
1030}) {
1031 const [rotating, setRotating] = useState(false);
1032 const rotate = useAtomCommand(serverEnvironment.rotateScheduledTaskWebhookToken, {
1033 label: "scheduled task rotate webhook token",
1034 reportFailure: false,
1035 });
1036 const preparedConnection = usePreparedConnection(environmentId);
1037 const httpBaseUrl =
1038 preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : null;
1039 const webhook = task?.schedule.type === "webhook" ? task.webhook : undefined;
1040 const resolved = webhook ? webhookAddress(webhook, httpBaseUrl) : null;
1041 return (
1042 <View className="gap-2 border-t border-border-subtle px-4 py-3">
1043 <Text className="text-sm text-foreground-muted">
1044 {
1045 "The prompt can use {{body.a.b}}, {{headers.name}}, {{query.name}}, {{body}} and {{request}}. The filled-in prompt is all the agent sees."
1046 }
1047 </Text>
1048 {task === null || resolved === null ? (
1049 <Text className="text-sm text-foreground-muted">Save the task to get its webhook URL.</Text>
1050 ) : (
1051 <>
1052 <Pressable
1053 accessibilityRole="button"
1054 accessibilityLabel="Copy webhook URL"
1055 accessibilityHint="Copies the URL to the clipboard"
1056 disabled={!resolved.copyable}
1057 onPress={() => void tryCopyTextWithHaptic(resolved.address)}
1058 className="gap-1 active:opacity-70"
1059 >
1060 <Text className="text-lg text-foreground">
1061 {resolved.copyable ? "Webhook URL" : "Webhook path"}
1062 </Text>
1063 <Text className="text-sm text-foreground-muted" numberOfLines={2} selectable>
1064 {resolved.address}
1065 </Text>
1066 </Pressable>
1067 {resolved.note !== null ? (
1068 <Text className="text-sm text-foreground-muted">{resolved.note}</Text>
1069 ) : null}
1070 <Pressable
1071 accessibilityRole="button"
1072 accessibilityState={{ disabled: disabled || rotating }}
1073 disabled={disabled || rotating}
1074 onPress={() =>
1075 Dialog.alert("Rotate URL?", "The current URL stops working immediately.", [
1076 { text: "Cancel", style: "cancel" },
1077 {
1078 text: "Rotate",
1079 style: "destructive",
1080 onPress: () => {
1081 setRotating(true);
1082 void rotate({ environmentId, input: { id: task.id } }).then((result) => {
1083 setRotating(false);
1084 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1085 Dialog.alert(
1086 "Could not rotate URL",
1087 String(squashAtomCommandFailure(result)),
1088 );
1089 }
1090 });
1091 },
1092 },
1093 ])
1094 }
1095 className="min-h-11 justify-center active:opacity-70 disabled:opacity-50"
1096 >
1097 <Text className="text-base text-danger-foreground">
1098 {rotating ? "Rotating…" : "Rotate URL"}
1099 </Text>
1100 </Pressable>
1101 </>
1102 )}
1103 {signatureConfigured ? (
1104 <Text className="text-sm text-foreground-muted">
1105 Signature check configured on desktop/web.
1106 </Text>
1107 ) : null}
1108 </View>
1109 );
1110}
1111
1112function EnvironmentTasks({
1113 environment,
1114 now,
1115 projectIds,
1116 onEdit,
1117}: {
1118 readonly environment: SettingsTarget;
1119 readonly now: number;
1120 readonly projectIds: readonly ProjectId[] | null;
1121 readonly onEdit: (task: ScheduledTask) => void;
1122}) {
1123 const environmentId = environment.environmentId;
1124 const tasks = useEnvironmentQuery(
1125 serverEnvironment.scheduledTasksLive({ environmentId, input: {} }),
1126 );
1127 const visibleTasks = tasks.data?.tasks.filter(
1128 (task) => projectIds === null || projectIds.includes(task.projectId),
1129 );
1130 const canOperate = useAtomValue(
1131 serverEnvironment.upsertScheduledTask.permissionAtom(environmentId),
1132 );
1133 const setEnabled = useAtomCommand(serverEnvironment.setScheduledTaskEnabled, {
1134 label: "scheduled task enabled",
1135 reportFailure: false,
1136 });
1137 const runNow = useAtomCommand(serverEnvironment.runScheduledTaskNow, {
1138 label: "scheduled task run",
1139 reportFailure: false,
1140 });
1141 const remove = useAtomCommand(serverEnvironment.deleteScheduledTask, {
1142 label: "scheduled task delete",
1143 reportFailure: false,
1144 });
1145 const failure = (title: string, result: AtomCommandResult<unknown, unknown>) => {
1146 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1147 Dialog.alert(title, String(squashAtomCommandFailure(result)));
1148 }
1149 };
1150
1151 const act = async (task: ScheduledTask, action: "run" | "toggle" | "delete") => {
1152 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;
1153 const result =
1154 action === "run"
1155 ? await runNow({ environmentId, input: { id: task.id } })
1156 : action === "toggle"
1157 ? await setEnabled({ environmentId, input: { id: task.id, enabled: !task.enabled } })
1158 : await remove({ environmentId, input: { id: task.id } });
1159 failure(`Could not ${action === "toggle" ? "update" : action} task`, result);
1160 };
1161
1162 return (
1163 <SettingsSection
1164 title={environment.label}
1165 titleIcon={
1166 <EnvironmentMachineSymbol
1167 kind={resolveEnvironmentMachineKind(environment.serverConfig)}
1168 size={16}
1169 tintColorClassName={
1170 Platform.OS === "android" ? "accent-primary" : "accent-foreground-muted"
1171 }
1172 />
1173 }
1174 >
1175 {tasks.error ? (
1176 <Text className="p-4 text-base text-danger-foreground">{tasks.error}</Text>
1177 ) : !tasks.data ? (
1178 <Text className="p-4 text-base text-foreground-muted">Loading tasks…</Text>
1179 ) : visibleTasks?.length === 0 ? (
1180 <Text className="p-4 text-base text-foreground-muted">
1181 {projectIds === null ? "No scheduled tasks yet." : "No tasks in this project."}
1182 </Text>
1183 ) : (
1184 visibleTasks?.map((task, index) => (
1185 <View
1186 key={task.id}
1187 className={
1188 index === 0
1189 ? "flex-row items-start gap-1 px-4 py-4"
1190 : "flex-row items-start gap-1 border-t border-border-subtle px-4 py-4"
1191 }
1192 >
1193 <Pressable
1194 accessibilityRole="button"
1195 accessibilityLabel={`Edit ${task.title}`}
1196 onPress={() => {
1197 onEdit(task);
1198 }}
1199 className="min-w-0 flex-1 gap-1 active:opacity-70"
1200 >
1201 <Text className="text-lg font-t3-medium text-foreground" numberOfLines={1}>
1202 {task.title}
1203 </Text>
1204 <Text className="text-sm text-foreground-muted" numberOfLines={2}>
1205 {describeSchedule(task)}
1206 {!task.enabled
1207 ? " · Paused"
1208 : task.nextRunAt
1209 ? ` · ${formatNextScheduledTaskRun(task.nextRunAt, now)}`
1210 : ""}
1211 </Text>
1212 {task.lastRunError ? (
1213 <Text className="text-sm text-danger-foreground" numberOfLines={2}>
1214 Last run failed: {task.lastRunError}
1215 </Text>
1216 ) : null}
1217 </Pressable>
1218 <Menu
1219 actions={[
1220 { id: "edit", title: "Edit" },
1221 {
1222 id: "toggle",
1223 title: task.enabled ? "Pause" : "Resume",
1224 attributes: { disabled: !canOperate },
1225 },
1226 ...(task.schedule.type === "webhook"
1227 ? []
1228 : [{ id: "run", title: "Run now", attributes: { disabled: !canOperate } }]),
1229 {
1230 id: "delete",
1231 title: "Delete",
1232 attributes: { destructive: true, disabled: !canOperate },
1233 },
1234 ]}
1235 onPressAction={({ nativeEvent }) => {
1236 const action = nativeEvent.event;
1237 if (action === "edit") {
1238 onEdit(task);
1239 } else if (action === "delete") {
1240 Dialog.alert("Delete task?", task.title, [
1241 { text: "Cancel", style: "cancel" },
1242 {
1243 text: "Delete",
1244 style: "destructive",
1245 onPress: () => void act(task, "delete"),
1246 },
1247 ]);
1248 } else if (action === "toggle" || action === "run") {
1249 void act(task, action);
1250 }
1251 }}
1252 >
1253 <Pressable
1254 accessibilityRole="button"
1255 accessibilityLabel={`Actions for ${task.title}`}
1256 className="h-11 w-11 items-center justify-center"
1257 >
1258 <SymbolView
1259 name="ellipsis"
1260 size={18}
1261 tintColorClassName="accent-icon"
1262 type="monochrome"
1263 />
1264 </Pressable>
1265 </Menu>
1266 </View>
1267 ))
1268 )}
1269 </SettingsSection>
1270 );
1271}