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

SettingsScheduledTasksRouteScreen.tsx

1,402 lines51.6 KB

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