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

SettingsScheduledTasksRouteScreen.tsx

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