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 // Let the native removal guard turn off before popping the saved form.
470 const frame = requestAnimationFrame(() => {
471 if (navigation.isFocused()) navigation.goBack();
472 });
473 return () => cancelAnimationFrame(frame);
474 }, [navigation, saved]);
475 return (
476 <SettingsScreen title={title}>
477 {Platform.OS === "ios" ? (
478 <NativeStackScreenOptions
479 options={{
480 headerBackVisible: false,
481 gestureEnabled: !preventRemove,
482 // The system back button begins its native pop before the removal
483 // guard runs. Dispatch from a bar action so the guard runs first.
484 unstable_headerLeftItems: () => [
485 withNativeGlassHeaderItem({
486 type: "button",
487 label: "",
488 accessibilityLabel: "Back",
489 icon: { type: "sfSymbol", name: "chevron.backward" },
490 onPress: () => navigation.goBack(),
491 }),
492 ],
493 }}
494 />
495 ) : null}
496 <ScrollView
497 keyboardShouldPersistTaps="handled"
498 keyboardDismissMode="on-drag"
499 contentInsetAdjustmentBehavior="automatic"
500 showsVerticalScrollIndicator={false}
501 className="flex-1"
502 contentContainerClassName="gap-5 px-5 pt-4"
503 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
504 >
505 {editor ? (
506 <TaskForm
507 key={editor.environmentId}
508 environmentId={editor.environmentId}
509 environmentLabel={
510 availableTargets.find((target) => target.environmentId === editor.environmentId)
511 ?.label ?? editor.environmentLabel
512 }
513 availableTargets={availableTargets}
514 draft={editor.draft}
515 saving={saving}
516 setSaving={setSaving}
517 dictationPending={voiceInput.blocksSubmission}
518 promptField={
519 <ScheduledTaskPromptField
520 value={prompt}
521 onChange={setPrompt}
522 selection={selection}
523 onChangeSelection={setSelection}
524 disabled={saving}
525 voiceInput={voiceInput}
526 />
527 }
528 setDraft={(draft) => {
529 if (!saving) setEditor({ ...editor, draft });
530 }}
531 onSaved={() => setSaved(true)}
532 onChangeEnvironment={(target) => {
533 if (target.environmentId === editor.environmentId) return;
534 setEditor({
535 environmentId: target.environmentId,
536 environmentLabel: target.label,
537 draft: {
538 ...draftForEnvironment(target.environmentId),
539 title: editor.draft.title,
540 prompt: editor.draft.prompt,
541 schedule: editor.draft.schedule,
542 enabled: editor.draft.enabled,
543 },
544 });
545 }}
546 />
547 ) : (
548 <Text className="px-2 text-base text-foreground-muted">
549 {availableTargets.length === 0
550 ? "Connect an environment to create a scheduled task."
551 : "No environments match the current filters. Change the filters to create a task."}
552 </Text>
553 )}
554 </ScrollView>
555 </SettingsScreen>
556 );
557}
558
559function TaskForm({
560 environmentId,
561 environmentLabel,
562 availableTargets,
563 draft,
564 saving,
565 setSaving,
566 dictationPending,
567 promptField,
568 setDraft,
569 onSaved,
570 onChangeEnvironment,
571}: {
572 readonly environmentId: EnvironmentId;
573 readonly environmentLabel: string;
574 readonly availableTargets: readonly SettingsTarget[];
575 readonly draft: Draft;
576 readonly saving: boolean;
577 readonly setSaving: (saving: boolean) => void;
578 readonly dictationPending: boolean;
579 readonly promptField: ReactNode;
580 readonly setDraft: (draft: Draft) => void;
581 readonly onSaved: () => void;
582 readonly onChangeEnvironment: (target: SettingsTarget) => void;
583}) {
584 const navigation = useNavigation<NativeStackNavigationProp<ScheduledTaskRoutes>>();
585 const tasks = useEnvironmentQuery(
586 serverEnvironment.scheduledTasksLive({ environmentId, input: {} }),
587 );
588 const projects = useProjects().filter((project) => project.environmentId === environmentId);
589 const config = useEnvironmentServerConfig(environmentId);
590 const modelOptions = useMemo(
591 () => buildModelOptions(config, null, undefined, draft.projectId),
592 [config, draft.projectId],
593 );
594 const canOperate = useAtomValue(
595 serverEnvironment.upsertScheduledTask.permissionAtom(environmentId),
596 );
597 const upsert = useAtomCommand(serverEnvironment.upsertScheduledTask, {
598 label: "scheduled task upsert",
599 reportFailure: false,
600 });
601 const submissionPending = useRef(false);
602 const [timePickerOpen, setTimePickerOpen] = useState(false);
603 const taskMissing =
604 draft.task !== null &&
605 tasks.data !== null &&
606 !tasks.data.tasks.some((task) => task.id === draft.task?.id);
607 const environmentUnavailable = !availableTargets.some(
608 (target) => target.environmentId === environmentId,
609 );
610
611 const failure = (title: string, result: AtomCommandResult<unknown, unknown>) => {
612 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
613 Dialog.alert(title, String(squashAtomCommandFailure(result)));
614 }
615 };
616
617 const save = async () => {
618 if (
619 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
620 submissionPending.current ||
621 saving ||
622 dictationPending ||
623 taskMissing ||
624 environmentUnavailable
625 )
626 return;
627 // Signatures are edited on desktop and web; send the task's current one,
628 // not the copy taken when this form opened, so a newer edit survives.
629 const liveTask = tasks.data?.tasks.find((task) => task.id === draft.task?.id);
630 const schedule = scheduleFromDraft(
631 draft.schedule.mode === "webhook" && liveTask?.schedule.type === "webhook"
632 ? { ...draft.schedule, signature: liveTask.schedule.signature }
633 : draft.schedule,
634 );
635 if (
636 draft.schedule.mode === "webhook" &&
637 parseMaxDeliveryAge(draft.schedule.maxDeliveryAgeMinutes) === undefined
638 ) {
639 Dialog.alert(
640 "Invalid age limit",
641 `Enter whole minutes from 1 to ${MAX_WEBHOOK_DELIVERY_AGE_MINUTES}, or leave it blank.`,
642 );
643 return;
644 }
645 if (
646 !draft.title.trim() ||
647 !draft.prompt.trim() ||
648 !draft.projectId ||
649 !draft.modelSelection ||
650 !schedule ||
651 (draft.workspace === "existing_worktree" && !draft.checkoutPath.trim())
652 ) {
653 Dialog.alert(
654 "Incomplete task",
655 "Add a name, prompt, project, model, valid schedule, and checkout path if needed.",
656 );
657 return;
658 }
659 if (!projects.some((project) => project.id === draft.projectId)) {
660 Dialog.alert("Project unavailable", "Choose a project in this environment.");
661 return;
662 }
663 const input: ScheduledTaskUpsertInput = {
664 ...(draft.task ? { id: draft.task.id, requireExisting: true } : {}),
665 title: draft.title.trim(),
666 prompt: draft.prompt.trim(),
667 projectId: draft.projectId,
668 modelSelection: draft.modelSelection,
669 schedule,
670 enabled: draft.enabled,
671 threadId: draft.task?.threadId ?? null,
672 workspaceStrategy:
673 draft.workspace === "root"
674 ? { type: "root" }
675 : draft.workspace === "existing_worktree"
676 ? { type: "existing_worktree", worktreePath: draft.checkoutPath.trim() }
677 : {
678 type: "worktree",
679 baseRef: draft.baseRef.trim() || "main",
680 startFromOrigin: draft.startFromOrigin,
681 },
682 runtimeMode: draft.runtimeMode,
683 interactionMode: draft.task?.interactionMode ?? "default",
684 creationSource: draft.task?.creationSource ?? "mobile",
685 };
686 // Lock before React renders, and keep successful creates locked until the form closes.
687 submissionPending.current = true;
688 setSaving(true);
689 const result = await upsert({ environmentId, input });
690 setSaving(false);
691 if (result._tag === "Failure") {
692 submissionPending.current = false;
693 failure("Could not save task", result);
694 return;
695 }
696 onSaved();
697 };
698
699 return (
700 <View className="gap-5">
701 <View
702 className="gap-5"
703 pointerEvents={saving ? "none" : "auto"}
704 accessibilityElementsHidden={saving}
705 importantForAccessibility={saving ? "no-hide-descendants" : "auto"}
706 >
707 {taskMissing ? (
708 <Text className="px-1 text-base text-danger-foreground">This task no longer exists.</Text>
709 ) : null}
710
711 {environmentUnavailable ? (
712 <Text className="px-1 text-base text-danger-foreground">
713 This environment is disconnected. Reconnect before saving.
714 </Text>
715 ) : null}
716 <SettingsSection>
717 <SelectRow
718 label="Runs on"
719 value={environmentLabel}
720 valueIcon={
721 <EnvironmentMachineSymbol
722 kind={resolveEnvironmentMachineKind(config)}
723 size={18}
724 tintColorClassName="accent-foreground-muted"
725 />
726 }
727 actions={
728 draft.task || saving || dictationPending
729 ? []
730 : availableTargets.map((target) => ({
731 id: target.environmentId,
732 title: target.label,
733 image:
734 ENVIRONMENT_MACHINE_SYMBOLS[
735 resolveEnvironmentMachineKind(target.serverConfig)
736 ],
737 state: target.environmentId === environmentId ? "on" : undefined,
738 }))
739 }
740 onSelect={(id) => {
741 const target = availableTargets.find((entry) => entry.environmentId === id);
742 if (target) onChangeEnvironment(target);
743 }}
744 />
745 </SettingsSection>
746 <SettingsSection title="Task">
747 <FormField
748 label="Name"
749 disabled={saving}
750 value={draft.title}
751 placeholder="Check for issues"
752 onChange={(title) => setDraft({ ...draft, title })}
753 />
754 {promptField}
755 </SettingsSection>
756
757 <SettingsSection title="Context">
758 <SelectRow
759 label="Project"
760 value={
761 projects.find((project) => project.id === draft.projectId)?.title ??
762 (projects.length ? "Choose project" : "No projects available")
763 }
764 actions={projects.map((project) => ({
765 id: project.id,
766 title: project.title,
767 state: project.id === draft.projectId ? "on" : undefined,
768 }))}
769 onSelect={(id) => {
770 const project = projects.find((item) => item.id === id);
771 if (!project) return;
772 const keepsExplicitModel =
773 draft.modelSelectionIsExplicit &&
774 (draft.modelSelection === null ||
775 !config?.settings ||
776 resolveProjectProviderInstanceEnabled(
777 config.settings,
778 project.id,
779 draft.modelSelection.instanceId,
780 ));
781 setDraft({
782 ...draft,
783 projectId: project.id,
784 modelSelection: keepsExplicitModel
785 ? draft.modelSelection
786 : scheduledTaskDefaultModel(config, project),
787 modelSelectionIsExplicit: keepsExplicitModel,
788 });
789 }}
790 />
791 <PickerRow
792 label="Model"
793 borderTop
794 value={
795 modelOptions.find(
796 (option) =>
797 option.selection.instanceId === draft.modelSelection?.instanceId &&
798 option.selection.model === draft.modelSelection?.model,
799 )?.label ??
800 draft.modelSelection?.model ??
801 (modelOptions.length ? "Choose model" : "No models available")
802 }
803 onPress={() => navigation.navigate("SettingsScheduledTaskModel")}
804 disabled={saving || dictationPending || environmentUnavailable}
805 />
806 </SettingsSection>
807
808 <SettingsSection title="Workspace">
809 <SelectRow
810 label="Run in"
811 value={
812 draft.workspace === "worktree"
813 ? "New worktree"
814 : draft.workspace === "root"
815 ? "Project checkout"
816 : "Specific checkout"
817 }
818 actions={[
819 {
820 id: "worktree",
821 title: "New worktree",
822 state: draft.workspace === "worktree" ? "on" : undefined,
823 },
824 {
825 id: "root",
826 title: "Project checkout",
827 state: draft.workspace === "root" ? "on" : undefined,
828 },
829 {
830 id: "existing_worktree",
831 title: "Specific checkout",
832 state: draft.workspace === "existing_worktree" ? "on" : undefined,
833 },
834 ]}
835 onSelect={(id) => {
836 if (id === "worktree" || id === "root" || id === "existing_worktree")
837 setDraft({ ...draft, workspace: id });
838 }}
839 />
840 {draft.workspace === "worktree" ? (
841 <PickerRow
842 label="Base branch"
843 value={resolveNewTaskBranchLabel({
844 branchName: draft.baseRef,
845 startFromOrigin: draft.startFromOrigin,
846 workspaceMode: "worktree",
847 })}
848 borderTop
849 disabled={!draft.projectId || saving || dictationPending || environmentUnavailable}
850 onPress={() => navigation.navigate("SettingsScheduledTaskBranch")}
851 />
852 ) : null}
853 {draft.workspace === "existing_worktree" ? (
854 <FormField
855 label="Checkout path"
856 disabled={saving}
857 value={draft.checkoutPath}
858 borderTop
859 onChange={(checkoutPath) => setDraft({ ...draft, checkoutPath })}
860 />
861 ) : null}
862 </SettingsSection>
863
864 <SettingsSection title="Schedule">
865 <View className="px-4 py-3">
866 <SegmentedControl
867 options={[
868 { value: "fixed_time", label: "At a time" },
869 { value: "interval", label: "Interval" },
870 { value: "webhook", label: "On webhook" },
871 ]}
872 selected={draft.schedule.mode}
873 onSelect={(mode) => {
874 setTimePickerOpen(false);
875 setDraft({
876 ...draft,
877 prompt:
878 mode === "webhook" && !draft.prompt.trim()
879 ? DEFAULT_WEBHOOK_PROMPT
880 : draft.prompt,
881 schedule: { ...draft.schedule, mode },
882 });
883 }}
884 />
885 </View>
886 {draft.schedule.mode === "fixed_time" ? (
887 <>
888 <Pressable
889 accessibilityRole="button"
890 accessibilityLabel={`Time, ${formatTime(draft.schedule.timeOfDay)}`}
891 onPress={() => setTimePickerOpen((open) => !open)}
892 className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70"
893 >
894 <Text className="text-lg text-foreground">Time</Text>
895 <Text className="min-w-0 flex-1 text-right text-base text-foreground-muted">
896 {formatTime(draft.schedule.timeOfDay)}
897 </Text>
898 <SymbolView
899 name="chevron.right"
900 size={14}
901 tintColorClassName="accent-chevron"
902 type="monochrome"
903 />
904 </Pressable>
905 {timePickerOpen ? (
906 <DateTimePicker
907 value={timePickerValue(draft.schedule.timeOfDay)}
908 mode="time"
909 display={Platform.OS === "ios" ? "spinner" : "default"}
910 onDismiss={() => setTimePickerOpen(false)}
911 onValueChange={(_, selected) => {
912 const timeOfDay = `${String(selected.getHours()).padStart(2, "0")}:${String(selected.getMinutes()).padStart(2, "0")}`;
913 setDraft({ ...draft, schedule: { ...draft.schedule, timeOfDay } });
914 }}
915 />
916 ) : null}
917 <SelectRow
918 label="Repeat"
919 value={repeatLabel(draft.schedule.weekdays)}
920 borderTop
921 actions={[
922 {
923 id: "every_day",
924 title: "Every day",
925 state: draft.schedule.weekdays.length === 7 ? "on" : undefined,
926 },
927 {
928 id: "weekdays",
929 title: "Weekdays",
930 state: repeatLabel(draft.schedule.weekdays) === "Weekdays" ? "on" : undefined,
931 },
932 ...DAYS.map((day) => ({
933 id: String(day.index),
934 title: day.label,
935 attributes: { keepsMenuPresented: true },
936 state: draft.schedule.weekdays.includes(day.index)
937 ? ("on" as const)
938 : undefined,
939 })),
940 ]}
941 onSelect={(id) => {
942 const weekdays =
943 id === "every_day"
944 ? DAYS.map((day) => day.index)
945 : id === "weekdays"
946 ? [1, 2, 3, 4, 5]
947 : (() => {
948 const day = DAYS.find((item) => String(item.index) === id);
949 if (!day) return draft.schedule.weekdays;
950 return draft.schedule.weekdays.includes(day.index)
951 ? draft.schedule.weekdays.filter((index) => index !== day.index)
952 : [...draft.schedule.weekdays, day.index];
953 })();
954 setDraft({ ...draft, schedule: { ...draft.schedule, weekdays } });
955 }}
956 />
957 </>
958 ) : draft.schedule.mode === "webhook" ? (
959 <>
960 <WebhookScheduleDetails
961 environmentId={environmentId}
962 // The live row, so a rotated URL shows up without reopening the form.
963 // Once the list has loaded, a missing task is gone; don't keep showing its URL.
964 task={
965 tasks.data
966 ? (tasks.data.tasks.find((task) => task.id === draft.task?.id) ?? null)
967 : draft.task
968 }
969 signatureConfigured={draft.schedule.signature !== null}
970 disabled={!canOperate || saving || environmentUnavailable}
971 />
972 <FormField
973 label="Skip requests older than (minutes)"
974 value={draft.schedule.maxDeliveryAgeMinutes}
975 placeholder="Run every request"
976 keyboardType="number-pad"
977 disabled={saving}
978 borderTop
979 onChange={(maxDeliveryAgeMinutes) =>
980 setDraft({ ...draft, schedule: { ...draft.schedule, maxDeliveryAgeMinutes } })
981 }
982 />
983 </>
984 ) : (
985 <>
986 <FormField
987 label="Minutes between runs"
988 value={draft.schedule.intervalMinutes}
989 keyboardType="decimal-pad"
990 disabled={saving}
991 borderTop
992 onChange={(intervalMinutes) =>
993 setDraft({ ...draft, schedule: { ...draft.schedule, intervalMinutes } })
994 }
995 />
996 {Number(draft.schedule.intervalMinutes) < 1 ? (
997 <Text className="px-4 pb-3 text-sm text-danger-foreground">
998 Intervals must be at least 1 minute. Update this interval before saving.
999 </Text>
1000 ) : draft.task?.schedule.type === "interval" &&
1001 draft.task.schedule.everyMs < 60_000 ? (
1002 <Text className="px-4 pb-3 text-sm text-foreground-muted">
1003 This task previously ran more than once per minute. Saving requires an interval of
1004 at least 1 minute.
1005 </Text>
1006 ) : null}
1007 </>
1008 )}
1009 <View className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3">
1010 <Text className="min-w-0 flex-1 text-lg text-foreground">Enabled</Text>
1011 <ThemedSwitch
1012 accessibilityLabel="Task enabled"
1013 value={draft.enabled}
1014 onValueChange={(enabled) => setDraft({ ...draft, enabled })}
1015 />
1016 </View>
1017 </SettingsSection>
1018 {draft.schedule.mode === "fixed_time" ? (
1019 <Text className="px-2 text-sm text-foreground-muted">
1020 Time uses the environment's time zone, which may differ from your phone's.
1021 </Text>
1022 ) : null}
1023 </View>
1024 <Button
1025 tone="primary"
1026 fullWidth
1027 loading={saving}
1028 disabled={!canOperate || dictationPending || taskMissing || environmentUnavailable}
1029 onPress={() => void save()}
1030 label={saving ? "Saving…" : draft.task ? "Save changes" : "Create task"}
1031 />
1032 </View>
1033 );
1034}
1035
1036function WebhookScheduleDetails({
1037 environmentId,
1038 task,
1039 signatureConfigured,
1040 disabled,
1041}: {
1042 readonly environmentId: EnvironmentId;
1043 readonly task: ScheduledTask | null;
1044 readonly signatureConfigured: boolean;
1045 readonly disabled: boolean;
1046}) {
1047 const [rotating, setRotating] = useState(false);
1048 const rotate = useAtomCommand(serverEnvironment.rotateScheduledTaskWebhookToken, {
1049 label: "scheduled task rotate webhook token",
1050 reportFailure: false,
1051 });
1052 const preparedConnection = usePreparedConnection(environmentId);
1053 const httpBaseUrl =
1054 preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : null;
1055 const webhook = task?.schedule.type === "webhook" ? task.webhook : undefined;
1056 // Without T3 Connect, the path is resolved on the address this phone uses.
1057 const resolved = webhook ? webhookAddress(webhook, httpBaseUrl) : null;
1058 return (
1059 <View className="gap-2 border-t border-border-subtle px-4 py-3">
1060 <Text className="text-sm text-foreground-muted">
1061 {
1062 "The prompt can use {{body.a.b}}, {{headers.name}}, {{query.name}}, {{body}} and {{request}}. The filled-in prompt is all the agent sees."
1063 }
1064 </Text>
1065 {task === null || resolved === null ? (
1066 <Text className="text-sm text-foreground-muted">Save the task to get its webhook URL.</Text>
1067 ) : (
1068 <>
1069 <Pressable
1070 accessibilityRole="button"
1071 accessibilityLabel="Copy webhook URL"
1072 accessibilityHint="Copies the URL to the clipboard"
1073 // A bare path is not something a sender can call, so only full URLs copy.
1074 disabled={!resolved.copyable}
1075 onPress={() => void tryCopyTextWithHaptic(resolved.address)}
1076 className="gap-1 active:opacity-70"
1077 >
1078 <Text className="text-lg text-foreground">
1079 {resolved.copyable ? "Webhook URL" : "Webhook path"}
1080 </Text>
1081 <Text className="text-sm text-foreground-muted" numberOfLines={2} selectable>
1082 {resolved.address}
1083 </Text>
1084 </Pressable>
1085 {resolved.note !== null ? (
1086 <Text className="text-sm text-foreground-muted">{resolved.note}</Text>
1087 ) : null}
1088 <Pressable
1089 accessibilityRole="button"
1090 accessibilityState={{ disabled: disabled || rotating }}
1091 disabled={disabled || rotating}
1092 onPress={() =>
1093 Dialog.alert("Rotate URL?", "The current URL stops working immediately.", [
1094 { text: "Cancel", style: "cancel" },
1095 {
1096 text: "Rotate",
1097 style: "destructive",
1098 onPress: () => {
1099 setRotating(true);
1100 void rotate({ environmentId, input: { id: task.id } }).then((result) => {
1101 setRotating(false);
1102 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1103 Dialog.alert(
1104 "Could not rotate URL",
1105 String(squashAtomCommandFailure(result)),
1106 );
1107 }
1108 });
1109 },
1110 },
1111 ])
1112 }
1113 className="min-h-11 justify-center active:opacity-70 disabled:opacity-50"
1114 >
1115 <Text className="text-base text-danger-foreground">
1116 {rotating ? "Rotating…" : "Rotate URL"}
1117 </Text>
1118 </Pressable>
1119 </>
1120 )}
1121 {signatureConfigured ? (
1122 <Text className="text-sm text-foreground-muted">
1123 Signature check configured on desktop/web.
1124 </Text>
1125 ) : null}
1126 </View>
1127 );
1128}
1129
1130function EnvironmentTasks({
1131 environment,
1132 now,
1133 projectIds,
1134 onEdit,
1135}: {
1136 readonly environment: SettingsTarget;
1137 readonly now: number;
1138 readonly projectIds: readonly ProjectId[] | null;
1139 readonly onEdit: (task: ScheduledTask) => void;
1140}) {
1141 const environmentId = environment.environmentId;
1142 const tasks = useEnvironmentQuery(
1143 serverEnvironment.scheduledTasksLive({ environmentId, input: {} }),
1144 );
1145 const visibleTasks = tasks.data?.tasks.filter(
1146 (task) => projectIds === null || projectIds.includes(task.projectId),
1147 );
1148 const canOperate = useAtomValue(
1149 serverEnvironment.upsertScheduledTask.permissionAtom(environmentId),
1150 );
1151 const setEnabled = useAtomCommand(serverEnvironment.setScheduledTaskEnabled, {
1152 label: "scheduled task enabled",
1153 reportFailure: false,
1154 });
1155 const runNow = useAtomCommand(serverEnvironment.runScheduledTaskNow, {
1156 label: "scheduled task run",
1157 reportFailure: false,
1158 });
1159 const remove = useAtomCommand(serverEnvironment.deleteScheduledTask, {
1160 label: "scheduled task delete",
1161 reportFailure: false,
1162 });
1163 const failure = (title: string, result: AtomCommandResult<unknown, unknown>) => {
1164 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1165 Dialog.alert(title, String(squashAtomCommandFailure(result)));
1166 }
1167 };
1168
1169 const act = async (task: ScheduledTask, action: "run" | "toggle" | "delete") => {
1170 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;
1171 const result =
1172 action === "run"
1173 ? await runNow({ environmentId, input: { id: task.id } })
1174 : action === "toggle"
1175 ? await setEnabled({ environmentId, input: { id: task.id, enabled: !task.enabled } })
1176 : await remove({ environmentId, input: { id: task.id } });
1177 failure(`Could not ${action === "toggle" ? "update" : action} task`, result);
1178 };
1179
1180 return (
1181 <SettingsSection
1182 title={environment.label}
1183 titleIcon={
1184 <EnvironmentMachineSymbol
1185 kind={resolveEnvironmentMachineKind(environment.serverConfig)}
1186 size={16}
1187 tintColorClassName={
1188 Platform.OS === "android" ? "accent-primary" : "accent-foreground-muted"
1189 }
1190 />
1191 }
1192 >
1193 {tasks.error ? (
1194 <Text className="p-4 text-base text-danger-foreground">{tasks.error}</Text>
1195 ) : !tasks.data ? (
1196 <Text className="p-4 text-base text-foreground-muted">Loading tasks…</Text>
1197 ) : visibleTasks?.length === 0 ? (
1198 <Text className="p-4 text-base text-foreground-muted">
1199 {projectIds === null ? "No scheduled tasks yet." : "No tasks in this project."}
1200 </Text>
1201 ) : (
1202 visibleTasks?.map((task, index) => (
1203 <View
1204 key={task.id}
1205 className={
1206 index === 0
1207 ? "flex-row items-start gap-1 px-4 py-4"
1208 : "flex-row items-start gap-1 border-t border-border-subtle px-4 py-4"
1209 }
1210 >
1211 <Pressable
1212 accessibilityRole="button"
1213 accessibilityLabel={`Edit ${task.title}`}
1214 onPress={() => {
1215 onEdit(task);
1216 }}
1217 className="min-w-0 flex-1 gap-1 active:opacity-70"
1218 >
1219 <Text className="text-lg font-t3-medium text-foreground" numberOfLines={1}>
1220 {task.title}
1221 </Text>
1222 <Text className="text-sm text-foreground-muted" numberOfLines={2}>
1223 {describeSchedule(task)}
1224 {!task.enabled
1225 ? " · Paused"
1226 : task.nextRunAt
1227 ? ` · ${formatNextScheduledTaskRun(task.nextRunAt, now)}`
1228 : ""}
1229 </Text>
1230 {task.lastRunError ? (
1231 <Text className="text-sm text-danger-foreground" numberOfLines={2}>
1232 Last run failed: {task.lastRunError}
1233 </Text>
1234 ) : null}
1235 </Pressable>
1236 <Menu
1237 actions={[
1238 { id: "edit", title: "Edit" },
1239 {
1240 id: "toggle",
1241 title: task.enabled ? "Pause" : "Resume",
1242 attributes: { disabled: !canOperate },
1243 },
1244 ...(task.schedule.type === "webhook"
1245 ? []
1246 : [{ id: "run", title: "Run now", attributes: { disabled: !canOperate } }]),
1247 {
1248 id: "delete",
1249 title: "Delete",
1250 attributes: { destructive: true, disabled: !canOperate },
1251 },
1252 ]}
1253 onPressAction={({ nativeEvent }) => {
1254 const action = nativeEvent.event;
1255 if (action === "edit") {
1256 onEdit(task);
1257 } else if (action === "delete") {
1258 Dialog.alert("Delete task?", task.title, [
1259 { text: "Cancel", style: "cancel" },
1260 {
1261 text: "Delete",
1262 style: "destructive",
1263 onPress: () => void act(task, "delete"),
1264 },
1265 ]);
1266 } else if (action === "toggle" || action === "run") {
1267 void act(task, action);
1268 }
1269 }}
1270 >
1271 <Pressable
1272 accessibilityRole="button"
1273 accessibilityLabel={`Actions for ${task.title}`}
1274 className="h-11 w-11 items-center justify-center"
1275 >
1276 <SymbolView
1277 name="ellipsis"
1278 size={18}
1279 tintColorClassName="accent-icon"
1280 type="monochrome"
1281 />
1282 </Pressable>
1283 </Menu>
1284 </View>
1285 ))
1286 )}
1287 </SettingsSection>
1288 );
1289}