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

SettingsScheduledTasksRouteScreen.tsx

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