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

SettingsScheduledTasksRouteScreen.tsx

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