Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SettingsScheduledTasksRouteScreen.tsx

1,271 lines45.9 KB

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