@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 1,786 lines 67.3 KB
Raw
1 import { msg, T, useGT, useLocale, useMessages, Var } from "gt-react-native";
2 import { managedCapabilityDenial } from "@t3tools/client-runtime/contract-labels";
3 import * as Dialog from "../../components/ui/Dialog";
4 import { useAtomValue } from "@effect/atom-react";
5 import {
6 AuthOrchestrationOperateScope,
7 clampManagedRuntimeMode,
8 resolveProjectProviderInstanceEnabled,
9 } from "@t3tools/contracts";
10 import { readEnvironmentScope } from "../../state/session";
11 import type {
12 EnvironmentId,
13 ProjectId,
14 ScheduledTask,
15 ScheduledTaskThreadMode,
16 ScheduledTaskUpsertInput,
17 } from "@t3tools/contracts";
18 import {
19 MAX_WEBHOOK_DELIVERY_AGE_MINUTES,
20 MAX_WEBHOOK_FILTERS,
21 resolveEnvironmentMachineKind,
22 scheduledTaskThreadMode,
23 } from "@t3tools/contracts";
24 import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail";
25 import type { MenuAction } from "@react-native-menu/menu";
26 import { DateTimePicker } from "@expo/ui/community/datetime-picker";
27 import {
28 isAtomCommandInterrupted,
29 squashAtomCommandFailure,
30 type AtomCommandResult,
31 } from "@t3tools/client-runtime/state/runtime";
32 import { resolvePastedPath } from "@t3tools/shared/path";
33 import {
34 DEFAULT_WEBHOOK_PROMPT,
35 emptyWebhookFilterDraft,
36 parseMaxDeliveryAge,
37 parseWebhookFilterDrafts,
38 removeWebhookFilterDraft,
39 WEBHOOK_FILTER_OPS,
40 type WebhookFilterDraft,
41 } from "@t3tools/client-runtime/scheduled-task-webhook";
42 import { scheduledTaskWorktreeBaseRef } from "@t3tools/client-runtime/scheduled-task-worktree";
43 import { scheduleTimeZoneLabel } from "@t3tools/client-runtime/scheduled-task-time-zone";
44 import type { MessageResolver } from "../../i18n/messages";
45 import { useRef, useState, type ReactNode } from "react";
46 import { useFocusEffect, useNavigation, usePreventRemove } from "@react-navigation/native";
47 import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
48 import { AppState, Platform, Pressable, TextInput as RNTextInput, View } from "react-native";
49 import { useSafeAreaInsets } from "react-native-safe-area-context";
50
51 import { Button } from "../../components/ui/Button";
52 import { AppText as Text } from "../../components/ui/AppText";
53 import { SymbolView } from "../../components/ui/AppSymbol";
54 import {
55 EnvironmentMachineSymbol,
56 ENVIRONMENT_MACHINE_SYMBOLS,
57 } from "../../components/EnvironmentMachineSymbol";
58 import { Menu } from "../../components/ui/Menu";
59 import type { ComposerEditorSelection } from "../../components/ComposerEditor";
60 import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
61 import { SegmentedControl } from "../../components/ui/SegmentedControl";
62 import { ThemedSwitch } from "../../components/ui/ThemedSwitch";
63 import { webhookAddress } from "@t3tools/client-runtime/webhook-address";
64 import { tryCopyTextWithHaptic } from "../../lib/copyTextWithHaptic";
65 import { usePreparedConnection } from "../../state/session";
66 import { buildModelOptions } from "../../lib/modelOptions";
67 import { withImplicitFastModeSelection } from "../../lib/providerOptions";
68 import { useProjects, useEnvironmentServerConfig } from "../../state/entities";
69 import { useEnvironmentQuery } from "../../state/query";
70 import { usePaginatedBranches } from "../../state/queries";
71 import { serverEnvironment } from "../../state/server";
72 import { useAtomCommand } from "../../state/use-atom-command";
73 import { resolveNewTaskBranchLabel } from "../threads/new-task-context-presentation";
74 import { useVoiceInputController } from "../voice-input/useVoiceInputController";
75 import { ScheduledTaskPromptField } from "./components/ScheduledTaskPromptField";
76 import { useSettingsEnvironmentMenu } from "./components/SettingsEnvironmentFilterHeader";
77 import { SettingsScreen } from "./components/SettingsScreen";
78 import { SettingsSection } from "./components/SettingsSection";
79 import { useSettingsEnvironmentFilter, type SettingsTarget } from "./settings-environment-filter";
80 import {
81 changeDraftProject,
82 editDraft,
83 parseIntervalMinutes,
84 scheduledTaskDefaultModel,
85 scheduleFromDraft,
86 unbindDraftFromThread,
87 type ScheduledTaskDraft as Draft,
88 } from "./scheduledTaskDraft";
89 import { settingsTargetsForProject } from "./settings-environment-filter.logic";
90 import {
91 useScheduledTaskDestinationLabel,
92 useScheduledTaskEditor,
93 useScheduledTaskThread,
94 } from "./scheduled-task-editor";
95 import {
96 discardScheduledTaskEditor,
97 markScheduledTaskEditorSaved,
98 } from "./scheduled-task-editor-state";
99 import {
100 formatNextScheduledTaskRun,
101 formatScheduledTaskInterval,
102 } from "./scheduledTaskPresentation";
103
104 type ScheduledTaskRoutes = {
105 SettingsScheduledTaskNew: undefined;
106 SettingsScheduledTaskEdit: undefined;
107 SettingsScheduledTaskModel: undefined;
108 SettingsScheduledTaskBranch: undefined;
109 SettingsScheduledTaskThread: undefined;
110 };
111
112 const DAYS = [1, 2, 3, 4, 5, 6, 0].map((index) => ({ index }));
113
114 // 2024-01-07 was a Sunday, so day index 0 to 6 maps onto Sunday to Saturday.
115 function weekdayLabel(index: number, locale: string): string {
116 return new Intl.DateTimeFormat(locale, { weekday: "short", timeZone: "UTC" }).format(
117 Date.UTC(2024, 0, 7 + index),
118 );
119 }
120
121 const THREAD_MODE_LABELS: Record<ScheduledTaskThreadMode, string> = {
122 new_thread: msg("New thread each run"),
123 continue: msg("One thread, same conversation"),
124 fresh_session: msg("One thread, fresh session"),
125 };
126
127 function describeSchedule(
128 task: ScheduledTask,
129 timeZone: string | undefined,
130 resolve: MessageResolver,
131 locale: string,
132 ): string {
133 if (task.schedule.type === "webhook") return resolve(msg("On webhook"));
134 if (task.schedule.type === "once") {
135 const runAt = new Date(task.schedule.runAt);
136 return resolve(
137 msg("Once, {date} at {time}", { date: formatRunAtDate(runAt), time: formatRunAtTime(runAt) }),
138 );
139 }
140 if (task.schedule.type === "interval")
141 return formatScheduledTaskInterval(task.schedule.everyMs, resolve);
142 const days = task.schedule.weekdays?.length
143 ? repeatLabel(task.schedule.weekdays, resolve, locale)
144 : resolve(msg("Every day"));
145 const zone = scheduleTimeZoneLabel(timeZone, task.nextRunAt);
146 const time = formatTime(task.schedule.timeOfDay);
147 return zone === undefined
148 ? resolve(msg("{days} at {time}", { days, time }))
149 : resolve(msg("{days} at {time} {zone}", { days, time, zone }));
150 }
151
152 function formatTime(value: string): string {
153 const [hours, minutes] = value.split(":").map(Number);
154 if (!Number.isInteger(hours) || !Number.isInteger(minutes)) return value;
155 const time = new Date();
156 time.setHours(hours ?? 9, minutes ?? 0, 0, 0);
157 return time.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
158 }
159
160 function formatRunAtDate(value: Date): string {
161 return value.toLocaleDateString([], { month: "short", day: "numeric", year: "numeric" });
162 }
163
164 function formatRunAtTime(value: Date): string {
165 return value.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
166 }
167
168 function timePickerValue(value: string): Date {
169 const [hours, minutes] = value.split(":").map(Number);
170 const time = new Date();
171 time.setHours(
172 Number.isInteger(hours) ? (hours ?? 9) : 9,
173 Number.isInteger(minutes) ? (minutes ?? 0) : 0,
174 0,
175 0,
176 );
177 return time;
178 }
179
180 function isWeekdays(weekdays: ReadonlyArray<number>): boolean {
181 const days = new Set(weekdays);
182 return days.size === 5 && [1, 2, 3, 4, 5].every((day) => days.has(day));
183 }
184
185 function repeatLabel(
186 weekdays: ReadonlyArray<number>,
187 resolve: MessageResolver,
188 locale: string,
189 ): string {
190 const days = new Set(weekdays);
191 if (days.size === 7) return resolve(msg("Every day"));
192 if (isWeekdays(weekdays)) return resolve(msg("Weekdays"));
193 return (
194 DAYS.filter((day) => days.has(day.index))
195 .map((day) => weekdayLabel(day.index, locale))
196 .join(", ") || resolve(msg("Choose days"))
197 );
198 }
199
200 function FormField(props: {
201 readonly label: string;
202 readonly value: string;
203 readonly onChange: (value: string) => void;
204 readonly keyboardType?: "decimal-pad" | "number-pad";
205 readonly disabled?: boolean;
206 readonly placeholder?: string;
207 readonly borderTop?: boolean;
208 }) {
209 return (
210 <View
211 className={
212 props.borderTop ? "gap-2 border-t border-border-subtle px-4 py-3" : "gap-2 px-4 py-3"
213 }
214 >
215 <Text className="text-sm text-foreground-muted">{props.label}</Text>
216 <RNTextInput
217 accessibilityLabel={props.label}
218 value={props.value}
219 readOnly={props.disabled}
220 onChangeText={props.onChange}
221 textAlignVertical="center"
222 keyboardType={props.keyboardType}
223 placeholder={props.placeholder}
224 placeholderTextColorClassName="accent-foreground-muted"
225 className="min-h-8 font-sans text-base text-foreground"
226 />
227 </View>
228 );
229 }
230
231 function SelectRow(props: {
232 readonly label: string;
233 readonly value: string;
234 readonly valueIcon?: ReactNode;
235 readonly actions: MenuAction[];
236 readonly onSelect: (id: string) => void;
237 readonly borderTop?: boolean;
238 }) {
239 const gt = useGT();
240 const value = (
241 <View className="min-w-0 flex-1 flex-row items-center justify-end gap-2">
242 {props.valueIcon}
243 <Text
244 textRole="footnote"
245 className="shrink text-right text-foreground-muted"
246 numberOfLines={1}
247 >
248 {props.value}
249 </Text>
250 </View>
251 );
252 if (props.actions.length === 0) {
253 return (
254 <View
255 className={
256 props.borderTop
257 ? "min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3"
258 : "min-h-14 flex-row items-center gap-3 px-4 py-3"
259 }
260 >
261 <Text textRole="body" className="text-foreground">
262 {props.label}
263 </Text>
264 {value}
265 </View>
266 );
267 }
268 return (
269 <Menu
270 actions={props.actions}
271 onPressAction={({ nativeEvent }) => props.onSelect(nativeEvent.event)}
272 >
273 <Pressable
274 accessibilityRole="button"
275 accessibilityLabel={gt("{label}, {value}", { label: props.label, value: props.value })}
276 className={
277 props.borderTop
278 ? "min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70"
279 : "min-h-14 flex-row items-center gap-3 px-4 py-3 active:opacity-70"
280 }
281 >
282 <Text textRole="body" className="text-foreground">
283 {props.label}
284 </Text>
285 {value}
286 <SymbolView
287 name="chevron.down"
288 size={14}
289 tintColorClassName="accent-chevron"
290 type="monochrome"
291 />
292 </Pressable>
293 </Menu>
294 );
295 }
296
297 function WebhookFilterRows(props: {
298 readonly filters: ReadonlyArray<WebhookFilterDraft>;
299 readonly disabled: boolean;
300 readonly onChange: (
301 update: (filters: ReadonlyArray<WebhookFilterDraft>) => ReadonlyArray<WebhookFilterDraft>,
302 ) => void;
303 }) {
304 const gt = useGT();
305 const m = useMessages();
306 const update = (id: WebhookFilterDraft["id"], patch: Partial<WebhookFilterDraft>) =>
307 props.onChange((filters) =>
308 filters.map((filter) => (filter.id === id ? { ...filter, ...patch } : filter)),
309 );
310 return (
311 <>
312 {props.filters.map((filter, index) => (
313 <View key={filter.id}>
314 <View className="flex-row items-center gap-3 border-t border-border-subtle px-4 pt-3">
315 <Text className="min-w-0 flex-1 text-sm text-foreground-muted">
316 <T>
317 Filter <Var>{index + 1}</Var>
318 </T>
319 </Text>
320 <Pressable
321 accessibilityRole="button"
322 accessibilityLabel={gt("Remove filter {number}", { number: index + 1 })}
323 disabled={props.disabled}
324 hitSlop={8}
325 onPress={() =>
326 props.onChange((filters) => removeWebhookFilterDraft(filters, filter.id))
327 }
328 className="active:opacity-70"
329 >
330 <SymbolView name="trash" size={16} tintColorClassName="accent-danger-foreground" />
331 </Pressable>
332 </View>
333 <FormField
334 label={gt("Path", { $context: "webhook payload field path" })}
335 value={filter.path}
336 placeholder="body.action"
337 disabled={props.disabled}
338 onChange={(path) => update(filter.id, { path })}
339 />
340 <SelectRow
341 label={gt("Test", { $context: "noun, the comparison a webhook filter applies" })}
342 value={m(WEBHOOK_FILTER_OPS.find((option) => option.op === filter.op)?.label ?? "")}
343 actions={WEBHOOK_FILTER_OPS.map((option) => ({
344 id: option.op,
345 title: m(option.label),
346 state: option.op === filter.op ? ("on" as const) : undefined,
347 }))}
348 onSelect={(id) => {
349 const known = WEBHOOK_FILTER_OPS.find((option) => option.op === id);
350 if (known) update(filter.id, { op: known.op });
351 }}
352 />
353 {filter.op === "exists" ? null : (
354 <FormField
355 label={filter.op === "in" ? gt("Values, comma-separated") : gt("Value")}
356 value={filter.value}
357 // oxlint-disable-next-line t3code/no-untranslated-copy -- webhook action values
358 placeholder={filter.op === "in" ? "opened, reopened" : "opened"}
359 disabled={props.disabled}
360 onChange={(value) => update(filter.id, { value })}
361 />
362 )}
363 </View>
364 ))}
365 {props.filters.length < MAX_WEBHOOK_FILTERS ? (
366 <Pressable
367 accessibilityRole="button"
368 disabled={props.disabled}
369 onPress={() =>
370 props.onChange((filters) =>
371 filters.length < MAX_WEBHOOK_FILTERS
372 ? [...filters, emptyWebhookFilterDraft()]
373 : filters,
374 )
375 }
376 className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70"
377 >
378 <Text textRole="body" className="min-w-0 flex-1 text-foreground">
379 <T>Add filter</T>
380 </Text>
381 <SymbolView name="plus" size={16} tintColorClassName="accent-icon" />
382 </Pressable>
383 ) : null}
384 {props.filters.length > 0 ? (
385 <Text className="px-4 pb-3 text-sm text-foreground-muted">
386 <T>
387 Runs only when every filter matches. Other requests are logged as filtered. Separate “is
388 one of” values with commas; a value can't contain a comma.
389 </T>
390 </Text>
391 ) : null}
392 </>
393 );
394 }
395
396 function PickerRow(props: {
397 readonly label: string;
398 readonly value: string;
399 readonly onPress: () => void;
400 readonly disabled?: boolean;
401 readonly borderTop?: boolean;
402 }) {
403 const gt = useGT();
404 return (
405 <Pressable
406 accessibilityRole="button"
407 accessibilityLabel={gt("{label}, {value}", { label: props.label, value: props.value })}
408 accessibilityState={{ disabled: props.disabled }}
409 disabled={props.disabled}
410 onPress={props.onPress}
411 className={
412 props.borderTop
413 ? "min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70 disabled:opacity-50"
414 : "min-h-14 flex-row items-center gap-3 px-4 py-3 active:opacity-70 disabled:opacity-50"
415 }
416 >
417 <Text textRole="body" className="text-foreground">
418 {props.label}
419 </Text>
420 <Text
421 textRole="footnote"
422 className="min-w-0 flex-1 text-right text-foreground-muted"
423 numberOfLines={1}
424 >
425 {props.value}
426 </Text>
427 <SymbolView
428 name="chevron.right"
429 size={14}
430 tintColorClassName="accent-chevron"
431 type="monochrome"
432 />
433 </Pressable>
434 );
435 }
436
437 export function SettingsScheduledTasksRouteScreen() {
438 const gt = useGT();
439 const [now, setNow] = useState(Date.now);
440 useFocusEffect(() => {
441 const updateNow = () => setNow(Date.now());
442 updateNow();
443 const timer = setInterval(updateNow, 60_000);
444 const subscription = AppState.addEventListener("change", (state) => {
445 if (state === "active") updateNow();
446 });
447 return () => {
448 clearInterval(timer);
449 subscription.remove();
450 };
451 });
452 const { availableTargets, selectedTargets, selectedProjectKey, projectGroups } =
453 useSettingsEnvironmentFilter();
454 const selectedGroup = projectGroups.find((group) => group.key === selectedProjectKey);
455 const visibleEnvironments = settingsTargetsForProject(
456 selectedTargets,
457 selectedProjectKey === null ? null : selectedGroup,
458 );
459 const { startEditor, resetEditor } = useScheduledTaskEditor();
460 const navigation = useNavigation<NativeStackNavigationProp<ScheduledTaskRoutes>>();
461 const insets = useSafeAreaInsets();
462 const environmentMenu = useSettingsEnvironmentMenu();
463 const newTask = () => {
464 if (visibleEnvironments.length === 0) return;
465 resetEditor();
466 navigation.navigate("SettingsScheduledTaskNew");
467 };
468
469 return (
470 <SettingsScreen
471 title={gt("Scheduled tasks")}
472 actions={[
473 {
474 accessibilityLabel: gt("New task"),
475 icon: "plus",
476 disabled: visibleEnvironments.length === 0,
477 onPress: newTask,
478 },
479 ]}
480 menus={[environmentMenu]}
481 >
482 <ScrollView
483 keyboardShouldPersistTaps="handled"
484 keyboardDismissMode="on-drag"
485 contentInsetAdjustmentBehavior="automatic"
486 showsVerticalScrollIndicator={false}
487 className="flex-1"
488 contentContainerClassName="gap-5 px-5 pt-4"
489 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
490 >
491 {visibleEnvironments.length > 0 ? (
492 visibleEnvironments.map((environment) => (
493 <EnvironmentTasks
494 key={environment.environmentId}
495 environment={environment}
496 now={now}
497 projectIds={
498 selectedProjectKey === null
499 ? null
500 : (selectedGroup?.members
501 .filter(
502 (member) => member.project.environmentId === environment.environmentId,
503 )
504 .map((member) => member.project.id) ?? [])
505 }
506 onEdit={(task) => {
507 startEditor({
508 environmentId: environment.environmentId,
509 environmentLabel: environment.label,
510 draft: editDraft(task),
511 });
512 navigation.navigate("SettingsScheduledTaskEdit");
513 }}
514 />
515 ))
516 ) : (
517 <Text className="px-2 text-base text-foreground-muted">
518 {availableTargets.length === 0
519 ? gt("Connect an environment to view and create scheduled tasks.")
520 : gt("No environments match these filters. Change the filter above.")}
521 </Text>
522 )}
523 </ScrollView>
524 </SettingsScreen>
525 );
526 }
527
528 // The "New task" action and takeScheduledTaskNewLink clear the editor before
529 // this screen opens, so it starts from the default target.
530 export function SettingsScheduledTaskNewRouteScreen() {
531 const gt = useGT();
532 return <SettingsScheduledTaskEditorScreen title={gt("New scheduled task")} />;
533 }
534
535 export function SettingsScheduledTaskEditRouteScreen() {
536 const gt = useGT();
537 return <SettingsScheduledTaskEditorScreen title={gt("Edit scheduled task")} />;
538 }
539
540 function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string }) {
541 const gt = useGT();
542 const {
543 editor,
544 voiceOwnerKey,
545 readEditor,
546 setEditor,
547 hasChanges,
548 saving,
549 setSaving,
550 draftForEnvironment,
551 } = useScheduledTaskEditor();
552 const { availableTargets } = useSettingsEnvironmentFilter();
553 const navigation = useNavigation();
554 const insets = useSafeAreaInsets();
555 // Set once the save lands, so the removal guard lets the editor close.
556 const saved = useRef(false);
557 const ownerKey = editor ? `${voiceOwnerKey}:${editor.environmentId}` : null;
558 const prompt = editor?.draft.prompt ?? "";
559 const [selectionState, setSelectionState] = useState<{
560 readonly ownerKey: string | null;
561 readonly selection: ComposerEditorSelection;
562 } | null>(null);
563 const selection =
564 selectionState?.ownerKey === ownerKey
565 ? selectionState.selection
566 : { start: prompt.length, end: prompt.length };
567 const setSelection = (next: ComposerEditorSelection) =>
568 setSelectionState({ ownerKey, selection: next });
569 const setPrompt = (next: string) =>
570 setEditor((current) =>
571 current
572 ? {
573 ...current,
574 draft: { ...current.draft, prompt: next },
575 }
576 : current,
577 );
578 const voiceInput = useVoiceInputController({
579 ownerKey,
580 label: editor?.draft.title.trim() || title,
581 selection,
582 readDraftMessage: () => {
583 const current = readEditor();
584 if (current?.environmentId !== editor?.environmentId) return null;
585 return current?.draft.prompt ?? null;
586 },
587 onChangeSelection: setSelection,
588 onChangeDraftMessage: (text) => {
589 if (readEditor()?.environmentId === editor?.environmentId) setPrompt(text);
590 },
591 disabled: saving,
592 });
593 const preventRemove = hasChanges || saving;
594 usePreventRemove(preventRemove, ({ data }) => {
595 if (saved.current) {
596 navigation.dispatch(data.action);
597 return;
598 }
599 if (saving) {
600 Dialog.alert(gt("Saving task"), gt("Wait for the task to finish saving before leaving."));
601 return;
602 }
603 Dialog.alert(gt("Discard changes?"), gt("Your unsaved changes will be lost."), [
604 { text: gt("Keep editing"), style: "cancel" },
605 {
606 text: gt("Discard changes"),
607 style: "destructive",
608 onPress: () => {
609 if (voiceInput.isBusy) voiceInput.cancel();
610 discardScheduledTaskEditor();
611 navigation.dispatch(data.action);
612 },
613 },
614 ]);
615 });
616 return (
617 <SettingsScreen
618 title={title}
619 // Native Back pops before removal guards; a bar action lets the guard run first.
620 guardBack={preventRemove}
621 >
622 <ScrollView
623 keyboardShouldPersistTaps="handled"
624 keyboardDismissMode="on-drag"
625 contentInsetAdjustmentBehavior="automatic"
626 showsVerticalScrollIndicator={false}
627 className="flex-1"
628 contentContainerClassName="gap-5 px-5 pt-4"
629 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
630 >
631 {editor ? (
632 <TaskForm
633 key={editor.environmentId}
634 environmentId={editor.environmentId}
635 environmentLabel={
636 availableTargets.find((target) => target.environmentId === editor.environmentId)
637 ?.label ?? editor.environmentLabel
638 }
639 availableTargets={availableTargets}
640 draft={editor.draft}
641 saving={saving}
642 setSaving={setSaving}
643 dictationPending={voiceInput.blocksSubmission}
644 promptField={
645 <ScheduledTaskPromptField
646 value={prompt}
647 onChange={setPrompt}
648 selection={selection}
649 onChangeSelection={setSelection}
650 disabled={saving}
651 voiceInput={voiceInput}
652 />
653 }
654 setDraft={(update) => {
655 if (!saving)
656 setEditor((current) =>
657 current ? { ...current, draft: update(current.draft) } : current,
658 );
659 }}
660 setEnvironmentDraft={(update) => {
661 if (!saving)
662 setEditor((current) =>
663 current && current.environmentId === editor.environmentId
664 ? { ...current, draft: update(current.draft) }
665 : current,
666 );
667 }}
668 onSaved={() => {
669 saved.current = true;
670 markScheduledTaskEditorSaved();
671 if (navigation.isFocused()) navigation.goBack();
672 }}
673 onChangeEnvironment={(target) => {
674 setEditor((current) =>
675 !current || target.environmentId === current.environmentId
676 ? current
677 : {
678 environmentId: target.environmentId,
679 environmentLabel: target.label,
680 draft: {
681 ...draftForEnvironment(target.environmentId),
682 title: current.draft.title,
683 prompt: current.draft.prompt,
684 schedule: current.draft.schedule,
685 enabled: current.draft.enabled,
686 },
687 },
688 );
689 }}
690 />
691 ) : (
692 <Text className="px-2 text-base text-foreground-muted">
693 {availableTargets.length === 0
694 ? gt("Connect an environment to create a scheduled task.")
695 : gt(
696 "No environments match the current filters. Change the filters to create a task.",
697 )}
698 </Text>
699 )}
700 </ScrollView>
701 </SettingsScreen>
702 );
703 }
704
705 function TaskForm({
706 environmentId,
707 environmentLabel,
708 availableTargets,
709 draft,
710 saving,
711 setSaving,
712 dictationPending,
713 promptField,
714 setDraft,
715 setEnvironmentDraft,
716 onSaved,
717 onChangeEnvironment,
718 }: {
719 readonly environmentId: EnvironmentId;
720 readonly environmentLabel: string;
721 readonly availableTargets: readonly SettingsTarget[];
722 readonly draft: Draft;
723 readonly saving: boolean;
724 readonly setSaving: (saving: boolean) => void;
725 readonly dictationPending: boolean;
726 readonly promptField: ReactNode;
727 readonly setDraft: (update: (current: Draft) => Draft) => void;
728 readonly setEnvironmentDraft: (update: (current: Draft) => Draft) => void;
729 readonly onSaved: () => void;
730 readonly onChangeEnvironment: (target: SettingsTarget) => void;
731 }) {
732 const gt = useGT();
733 const m = useMessages();
734 const locale = useLocale();
735 const { readEditor } = useScheduledTaskEditor();
736 const navigation = useNavigation<NativeStackNavigationProp<ScheduledTaskRoutes>>();
737 const tasks = useEnvironmentQuery(
738 serverEnvironment.scheduledTasksLive({ environmentId, input: {} }),
739 );
740 // Pinned first. The chosen project stays listed after it is archived.
741 const projects = useProjects()
742 .filter(
743 (project) =>
744 project.environmentId === environmentId &&
745 (project.archivedAt == null ||
746 project.id === draft.projectId ||
747 project.id === draft.task?.projectId),
748 )
749 .sort((left, right) => Number(right.pinnedAt != null) - Number(left.pinnedAt != null));
750 const automaticBaseRef = draft.workspace === "worktree" && !draft.baseRef.trim();
751 const automaticBaseRefCwd = automaticBaseRef
752 ? (projects.find((project) => project.id === draft.projectId)?.workspaceRoot ?? null)
753 : null;
754 const automaticBaseRefs = usePaginatedBranches({
755 environmentId,
756 cwd: automaticBaseRefCwd,
757 query: "",
758 });
759 const worktreeBaseRef = scheduledTaskWorktreeBaseRef(draft.baseRef, automaticBaseRefs.refs);
760 // Until the project's refs load, the automatic base would save as `main`. A failed lookup falls back to it.
761 const automaticBaseRefLoading =
762 automaticBaseRefCwd !== null &&
763 automaticBaseRefs.data === null &&
764 automaticBaseRefs.error === null;
765 const config = useEnvironmentServerConfig(environmentId);
766 const destinationLabel = useScheduledTaskDestinationLabel(environmentId, draft.threadId);
767 const boundThread = useScheduledTaskThread(environmentId, draft.threadId);
768 // Bound runs use the thread's current model, so the locked row shows that one.
769 const shownSelection =
770 draft.threadId === null ? draft.modelSelection : (boundThread?.modelSelection ?? null);
771 const modelOptions = buildModelOptions(config, null, undefined, draft.projectId);
772 // Existing webhook tasks keep the option so they can still switch to a timer.
773 const webhookDenial = managedCapabilityDenial(config?.managedPolicy, "webhookTasks", m);
774 const canOperate = useAtomValue(
775 serverEnvironment.upsertScheduledTask.permissionAtom(environmentId),
776 );
777 const upsert = useAtomCommand(serverEnvironment.upsertScheduledTask, {
778 label: "scheduled task upsert",
779 reportFailure: false,
780 });
781 const submissionPending = useRef(false);
782 const [timePickerOpen, setTimePickerOpen] = useState(false);
783 const [runAtPicker, setRunAtPicker] = useState<"date" | "time" | null>(null);
784 const taskMissing =
785 draft.task !== null &&
786 tasks.data !== null &&
787 !tasks.data.tasks.some((task) => task.id === draft.task?.id);
788 const runAtZone = scheduleTimeZoneLabel(tasks.data?.timeZone);
789 const environmentUnavailable = !availableTargets.some(
790 (target) => target.environmentId === environmentId,
791 );
792
793 const failure = (title: string, result: AtomCommandResult<unknown, unknown>) => {
794 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
795 Dialog.alert(title, String(squashAtomCommandFailure(result)));
796 }
797 };
798
799 const offersOnce =
800 config?.environment.capabilities.oneTimeSchedules === true ||
801 draft.task?.schedule.type === "once";
802 const offersThreadModes = config?.environment.capabilities.scheduledTaskThreadModes === true;
803 const save = async () => {
804 const current = readEditor();
805 if (!current || current.environmentId !== environmentId) return;
806 const draft = current.draft;
807 if (
808 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
809 submissionPending.current ||
810 saving ||
811 dictationPending ||
812 taskMissing ||
813 environmentUnavailable ||
814 automaticBaseRefLoading
815 )
816 return;
817 // Preserve signatures edited on other clients by sending the task's current value.
818 const liveTask = tasks.data?.tasks.find((task) => task.id === draft.task?.id);
819 const schedule = scheduleFromDraft(
820 draft.schedule.mode === "webhook" && liveTask?.schedule.type === "webhook"
821 ? { ...draft.schedule, signature: liveTask.schedule.signature }
822 : draft.schedule,
823 );
824 if (
825 draft.schedule.mode === "webhook" &&
826 parseMaxDeliveryAge(draft.schedule.maxDeliveryAgeMinutes) === undefined
827 ) {
828 Dialog.alert(
829 gt("Invalid age limit"),
830 gt("Enter whole minutes from 1 to {max}, or leave it blank.", {
831 max: MAX_WEBHOOK_DELIVERY_AGE_MINUTES,
832 }),
833 );
834 return;
835 }
836 if (draft.schedule.mode === "once" && !offersOnce) {
837 Dialog.alert(
838 gt("Once is not available here"),
839 gt(
840 "This environment runs an older {product}. Update it to schedule a one-time task, or pick another schedule.",
841 { product: "T3 Code" },
842 ),
843 );
844 return;
845 }
846 const parsedFilters = parseWebhookFilterDrafts(draft.schedule.filters, m);
847 if (draft.schedule.mode === "webhook" && "error" in parsedFilters) {
848 Dialog.alert(gt("Invalid filter"), parsedFilters.error);
849 return;
850 }
851 if (draft.schedule.mode === "webhook" && schedule === null) {
852 Dialog.alert(
853 gt("Invalid webhook settings"),
854 gt(
855 "Each dedupe key must contain a valid request placeholder. The coalesce window must be whole seconds from 10 to 3600, or blank.",
856 ),
857 );
858 return;
859 }
860 if (
861 !draft.title.trim() ||
862 !draft.prompt.trim() ||
863 !draft.projectId ||
864 !draft.modelSelection ||
865 !schedule ||
866 (draft.workspace === "existing_worktree" && !draft.checkoutPath.trim())
867 ) {
868 Dialog.alert(
869 gt("Incomplete task"),
870 gt("Add a name, prompt, project, model, valid schedule, and checkout path if needed."),
871 );
872 return;
873 }
874 if (!projects.some((project) => project.id === draft.projectId)) {
875 Dialog.alert(gt("Project unavailable"), gt("Choose a project in this environment."));
876 return;
877 }
878 const input: ScheduledTaskUpsertInput = {
879 ...(draft.task ? { id: draft.task.id, requireExisting: true } : {}),
880 title: draft.title.trim(),
881 prompt: draft.prompt.trim(),
882 projectId: draft.projectId,
883 modelSelection: withImplicitFastModeSelection(draft.modelSelection, config?.providers ?? []),
884 schedule,
885 enabled: draft.enabled,
886 threadId: draft.threadId,
887 ...(draft.threadId === null && draft.task?.threadId != null ? { unbindThread: true } : {}),
888 ...(offersThreadModes ? { threadMode: draft.threadMode } : {}),
889 workspaceStrategy:
890 draft.workspace === "root"
891 ? { type: "root" }
892 : draft.workspace === "existing_worktree"
893 ? { type: "existing_worktree", worktreePath: draft.checkoutPath.trim() }
894 : {
895 type: "worktree",
896 baseRef: worktreeBaseRef,
897 startFromOrigin: draft.startFromOrigin,
898 },
899 // Tasks have no mode picker; a mode above the administrator's ceiling is refused.
900 runtimeMode:
901 clampManagedRuntimeMode(config?.managedPolicy, draft.runtimeMode) ?? draft.runtimeMode,
902 interactionMode: draft.task?.interactionMode ?? "default",
903 creationSource: draft.task?.creationSource ?? "mobile",
904 };
905 submissionPending.current = true;
906 setSaving(true);
907 const result = await upsert({ environmentId, input });
908 setSaving(false);
909 if (result._tag === "Failure") {
910 submissionPending.current = false;
911 failure(gt("Could not save task"), result);
912 return;
913 }
914 onSaved();
915 };
916
917 return (
918 <View className="gap-5">
919 <View
920 className="gap-5"
921 pointerEvents={saving ? "none" : "auto"}
922 accessibilityElementsHidden={saving}
923 importantForAccessibility={saving ? "no-hide-descendants" : "auto"}
924 >
925 {taskMissing ? (
926 <Text className="px-1 text-base text-danger-foreground">
927 <T>This task no longer exists.</T>
928 </Text>
929 ) : null}
930
931 {environmentUnavailable ? (
932 <Text className="px-1 text-base text-danger-foreground">
933 <T>This environment is disconnected. Reconnect before saving.</T>
934 </Text>
935 ) : null}
936 <SettingsSection>
937 <SelectRow
938 label={gt("Runs on")}
939 value={environmentLabel}
940 valueIcon={
941 <EnvironmentMachineSymbol
942 kind={resolveEnvironmentMachineKind(config)}
943 size={18}
944 tintColorClassName="accent-foreground-muted"
945 />
946 }
947 actions={
948 draft.task || saving || dictationPending
949 ? []
950 : availableTargets.map((target) => ({
951 id: target.environmentId,
952 title: target.label,
953 image:
954 ENVIRONMENT_MACHINE_SYMBOLS[
955 resolveEnvironmentMachineKind(target.serverConfig)
956 ],
957 state: target.environmentId === environmentId ? "on" : undefined,
958 }))
959 }
960 onSelect={(id) => {
961 const target = availableTargets.find((entry) => entry.environmentId === id);
962 if (target) onChangeEnvironment(target);
963 }}
964 />
965 </SettingsSection>
966 <SettingsSection title={gt("Task", { $context: "section heading for a scheduled task" })}>
967 <FormField
968 label={gt("Name")}
969 disabled={saving}
970 value={draft.title}
971 placeholder={gt("Check for issues")}
972 onChange={(title) => setDraft((current) => ({ ...current, title }))}
973 />
974 {promptField}
975 </SettingsSection>
976
977 <SettingsSection title={gt("Context", { $context: "section heading: project and model" })}>
978 <SelectRow
979 label={gt("Project")}
980 value={
981 projects.find((project) => project.id === draft.projectId)?.title ??
982 (projects.length ? gt("Choose project") : gt("No projects available"))
983 }
984 actions={projects.map((project) => ({
985 id: project.id,
986 title: project.title,
987 state: project.id === draft.projectId ? "on" : undefined,
988 }))}
989 onSelect={(id) => {
990 const project = projects.find((item) => item.id === id);
991 if (!project) return;
992 setEnvironmentDraft((current) => {
993 const keepsExplicitModel =
994 current.modelSelectionIsExplicit &&
995 (current.modelSelection === null ||
996 !config?.settings ||
997 resolveProjectProviderInstanceEnabled(
998 config.settings,
999 project.id,
1000 current.modelSelection.instanceId,
1001 ));
1002 return {
1003 ...changeDraftProject(current, project.id),
1004 modelSelection: keepsExplicitModel
1005 ? current.modelSelection
1006 : scheduledTaskDefaultModel(config, project),
1007 modelSelectionIsExplicit: keepsExplicitModel,
1008 };
1009 });
1010 }}
1011 />
1012 <PickerRow
1013 label={gt("Model")}
1014 borderTop
1015 value={
1016 modelOptions.find(
1017 (option) =>
1018 option.selection.instanceId === shownSelection?.instanceId &&
1019 option.selection.model === shownSelection?.model,
1020 )?.label ??
1021 shownSelection?.model ??
1022 (modelOptions.length ? gt("Choose model") : gt("No models available"))
1023 }
1024 onPress={() => navigation.navigate("SettingsScheduledTaskModel")}
1025 // The saved selection only seeds new threads; bound runs ignore it.
1026 disabled={
1027 saving || dictationPending || environmentUnavailable || draft.threadId !== null
1028 }
1029 />
1030 </SettingsSection>
1031
1032 <SettingsSection
1033 title={gt("Destination")}
1034 footer={
1035 draft.threadMode === "new_thread"
1036 ? gt("Each run starts a new thread.")
1037 : draft.threadMode === "continue"
1038 ? draft.threadId === null
1039 ? gt(
1040 "Runs continue one conversation. The first run starts the thread. Deleting it also deletes this task.",
1041 )
1042 : gt("Runs continue one conversation. Deleting it also deletes this task.")
1043 : draft.threadId === null
1044 ? gt(
1045 "Runs share one thread, each in a fresh session without earlier runs' context. The first run starts the thread. Deleting it also deletes this task.",
1046 )
1047 : gt(
1048 "Runs share one thread, each in a fresh session without earlier runs' context. Deleting it also deletes this task.",
1049 )
1050 }
1051 >
1052 {offersThreadModes ? (
1053 <SelectRow
1054 label={gt("Runs go to")}
1055 value={m(THREAD_MODE_LABELS[draft.threadMode])}
1056 actions={(Object.keys(THREAD_MODE_LABELS) as ScheduledTaskThreadMode[]).map(
1057 (mode) => ({
1058 id: mode,
1059 title: m(THREAD_MODE_LABELS[mode]),
1060 state: draft.threadMode === mode ? "on" : undefined,
1061 }),
1062 )}
1063 onSelect={(id) => {
1064 if (id === "new_thread")
1065 setDraft((current) => ({ ...unbindDraftFromThread(current), threadMode: id }));
1066 else if (id === "continue" || id === "fresh_session")
1067 setDraft((current) => ({ ...current, threadMode: id }));
1068 }}
1069 />
1070 ) : null}
1071 {!offersThreadModes || draft.threadMode !== "new_thread" ? (
1072 <PickerRow
1073 label={gt("Thread")}
1074 borderTop={offersThreadModes}
1075 value={
1076 draft.threadId === null && draft.threadMode !== "new_thread"
1077 ? gt("Started by the first run")
1078 : destinationLabel
1079 }
1080 onPress={() => navigation.navigate("SettingsScheduledTaskThread")}
1081 disabled={!draft.projectId || saving || dictationPending || environmentUnavailable}
1082 />
1083 ) : null}
1084 </SettingsSection>
1085
1086 <SettingsSection title={gt("Workspace")}>
1087 <SelectRow
1088 label={gt("Run in")}
1089 value={
1090 draft.workspace === "worktree"
1091 ? gt("New worktree")
1092 : draft.workspace === "root"
1093 ? gt("Project checkout")
1094 : gt("Specific checkout")
1095 }
1096 actions={[
1097 {
1098 id: "worktree",
1099 title: gt("New worktree"),
1100 state: draft.workspace === "worktree" ? "on" : undefined,
1101 },
1102 {
1103 id: "root",
1104 title: gt("Project checkout"),
1105 state: draft.workspace === "root" ? "on" : undefined,
1106 },
1107 {
1108 id: "existing_worktree",
1109 title: gt("Specific checkout"),
1110 state: draft.workspace === "existing_worktree" ? "on" : undefined,
1111 },
1112 ]}
1113 onSelect={(id) => {
1114 if (id === "worktree" || id === "root" || id === "existing_worktree")
1115 setDraft((current) => ({ ...current, workspace: id }));
1116 }}
1117 />
1118 {draft.workspace === "worktree" ? (
1119 <PickerRow
1120 label={gt("Base branch")}
1121 value={resolveNewTaskBranchLabel(
1122 {
1123 branchName: automaticBaseRefLoading ? null : worktreeBaseRef,
1124 startFromOrigin: draft.startFromOrigin,
1125 workspaceMode: "worktree",
1126 },
1127 m,
1128 )}
1129 borderTop
1130 disabled={!draft.projectId || saving || dictationPending || environmentUnavailable}
1131 onPress={() => navigation.navigate("SettingsScheduledTaskBranch")}
1132 />
1133 ) : null}
1134 {draft.workspace === "existing_worktree" ? (
1135 <FormField
1136 label={gt("Checkout path")}
1137 disabled={saving}
1138 value={draft.checkoutPath}
1139 borderTop
1140 onChange={(checkoutPath) =>
1141 setEnvironmentDraft((current) => ({
1142 ...current,
1143 checkoutPath: resolvePastedPath(current.checkoutPath, checkoutPath),
1144 }))
1145 }
1146 />
1147 ) : null}
1148 </SettingsSection>
1149
1150 <SettingsSection title={gt("Schedule", { $context: "noun, section heading" })}>
1151 <View className="px-4 py-3">
1152 <SegmentedControl
1153 variant="card"
1154 options={[
1155 { value: "fixed_time", label: gt("At a time") },
1156 // Older servers reject one-time schedules on save.
1157 ...(offersOnce || draft.schedule.mode === "once"
1158 ? [
1159 {
1160 value: "once" as const,
1161 label: gt("Once", { $context: "one-time schedule option" }),
1162 },
1163 ]
1164 : []),
1165 { value: "interval", label: gt("Interval") },
1166 ...(webhookDenial === undefined || draft.schedule.mode === "webhook"
1167 ? [{ value: "webhook" as const, label: gt("On webhook") }]
1168 : []),
1169 ]}
1170 selected={draft.schedule.mode}
1171 onSelect={(mode) => {
1172 setTimePickerOpen(false);
1173 setRunAtPicker(null);
1174 setDraft((current) => ({
1175 ...current,
1176 prompt:
1177 mode === "webhook" && !current.prompt.trim()
1178 ? DEFAULT_WEBHOOK_PROMPT
1179 : current.prompt,
1180 schedule: {
1181 ...current.schedule,
1182 mode,
1183 runAt:
1184 mode === "once" && !current.schedule.runAt
1185 ? new Date(Math.ceil(Date.now() / 3_600_000) * 3_600_000).toISOString()
1186 : current.schedule.runAt,
1187 },
1188 }));
1189 }}
1190 />
1191 </View>
1192 {draft.schedule.mode === "fixed_time" ? (
1193 <>
1194 <Pressable
1195 accessibilityRole="button"
1196 accessibilityLabel={
1197 runAtZone
1198 ? gt("Time, {time} {zone}", {
1199 time: formatTime(draft.schedule.timeOfDay),
1200 zone: runAtZone,
1201 })
1202 : gt("Time, {time}", { time: formatTime(draft.schedule.timeOfDay) })
1203 }
1204 onPress={() => setTimePickerOpen((open) => !open)}
1205 className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70"
1206 >
1207 <Text textRole="body" className="text-foreground">
1208 {gt("Time", { $context: "time of day" })}
1209 </Text>
1210 <Text
1211 textRole="footnote"
1212 className="min-w-0 flex-1 text-right text-foreground-muted"
1213 >
1214 {formatTime(draft.schedule.timeOfDay)}
1215 {runAtZone ? ` ${runAtZone}` : ""}
1216 </Text>
1217 <SymbolView
1218 name="chevron.right"
1219 size={14}
1220 tintColorClassName="accent-chevron"
1221 type="monochrome"
1222 />
1223 </Pressable>
1224 {timePickerOpen ? (
1225 <DateTimePicker
1226 value={timePickerValue(draft.schedule.timeOfDay)}
1227 mode="time"
1228 display={Platform.OS === "ios" ? "spinner" : "default"}
1229 onDismiss={() => setTimePickerOpen(false)}
1230 onValueChange={(_, selected) => {
1231 const timeOfDay = `${String(selected.getHours()).padStart(2, "0")}:${String(selected.getMinutes()).padStart(2, "0")}`;
1232 setDraft((current) => ({
1233 ...current,
1234 schedule: { ...current.schedule, timeOfDay },
1235 }));
1236 }}
1237 />
1238 ) : null}
1239 <SelectRow
1240 label={gt("Repeat", { $context: "noun, which days a task repeats on" })}
1241 value={repeatLabel(draft.schedule.weekdays, m, locale)}
1242 borderTop
1243 actions={[
1244 {
1245 id: "every_day",
1246 title: gt("Every day"),
1247 state: draft.schedule.weekdays.length === 7 ? "on" : undefined,
1248 },
1249 {
1250 id: "weekdays",
1251 title: gt("Weekdays"),
1252 state: isWeekdays(draft.schedule.weekdays) ? "on" : undefined,
1253 },
1254 ...DAYS.map((day) => ({
1255 id: String(day.index),
1256 title: weekdayLabel(day.index, locale),
1257 attributes: { keepsMenuPresented: true },
1258 state: draft.schedule.weekdays.includes(day.index)
1259 ? ("on" as const)
1260 : undefined,
1261 })),
1262 ]}
1263 onSelect={(id) => {
1264 setDraft((current) => {
1265 const weekdays =
1266 id === "every_day"
1267 ? DAYS.map((day) => day.index)
1268 : id === "weekdays"
1269 ? [1, 2, 3, 4, 5]
1270 : (() => {
1271 const day = DAYS.find((item) => String(item.index) === id);
1272 if (!day) return current.schedule.weekdays;
1273 return current.schedule.weekdays.includes(day.index)
1274 ? current.schedule.weekdays.filter((index) => index !== day.index)
1275 : [...current.schedule.weekdays, day.index];
1276 })();
1277 return { ...current, schedule: { ...current.schedule, weekdays } };
1278 });
1279 }}
1280 />
1281 </>
1282 ) : draft.schedule.mode === "webhook" && webhookDenial !== undefined && draft.enabled ? (
1283 <Text className="border-t border-border-subtle px-4 py-3 text-sm text-foreground-muted">
1284 {gt("{reason} Switch the task to a timer, or turn it off, to save it.", {
1285 reason: webhookDenial,
1286 })}
1287 </Text>
1288 ) : draft.schedule.mode === "once" ? (
1289 (["date", "time"] as const).map((field) => {
1290 const runAt = new Date(draft.schedule.runAt);
1291 const label = field === "date" ? formatRunAtDate(runAt) : formatRunAtTime(runAt);
1292 return (
1293 <View key={field}>
1294 <Pressable
1295 accessibilityRole="button"
1296 accessibilityLabel={
1297 field === "date"
1298 ? gt("Date, {date}", { date: label })
1299 : gt("Time, {time}", { time: label })
1300 }
1301 onPress={() => setRunAtPicker((open) => (open === field ? null : field))}
1302 className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3 active:opacity-70"
1303 >
1304 <Text textRole="body" className="text-foreground">
1305 {field === "date" ? gt("Date") : gt("Time", { $context: "time of day" })}
1306 </Text>
1307 <Text
1308 textRole="footnote"
1309 className="min-w-0 flex-1 text-right text-foreground-muted"
1310 >
1311 {label}
1312 </Text>
1313 <SymbolView
1314 name="chevron.right"
1315 size={14}
1316 tintColorClassName="accent-chevron"
1317 type="monochrome"
1318 />
1319 </Pressable>
1320 {runAtPicker === field ? (
1321 <DateTimePicker
1322 value={runAt}
1323 mode={field}
1324 display={Platform.OS === "ios" ? "spinner" : "default"}
1325 onDismiss={() => setRunAtPicker(null)}
1326 onValueChange={(_, selected) => {
1327 // Android shows a dialog that closes on pick; iOS stays inline.
1328 if (Platform.OS === "android") setRunAtPicker(null);
1329 setDraft((current) => ({
1330 ...current,
1331 schedule: { ...current.schedule, runAt: selected.toISOString() },
1332 }));
1333 }}
1334 />
1335 ) : null}
1336 </View>
1337 );
1338 })
1339 ) : draft.schedule.mode === "webhook" ? (
1340 <>
1341 <WebhookScheduleDetails
1342 environmentId={environmentId}
1343 // Use the live row for rotated URLs; hide the URL once a loaded list no longer contains the task.
1344 task={
1345 tasks.data
1346 ? (tasks.data.tasks.find((task) => task.id === draft.task?.id) ?? null)
1347 : draft.task
1348 }
1349 signatureConfigured={draft.schedule.signature !== null}
1350 disabled={!canOperate || saving || environmentUnavailable}
1351 />
1352 <FormField
1353 label={gt("Skip requests older than (minutes)")}
1354 value={draft.schedule.maxDeliveryAgeMinutes}
1355 placeholder={gt("Run every request")}
1356 keyboardType="number-pad"
1357 disabled={saving}
1358 borderTop
1359 onChange={(maxDeliveryAgeMinutes) =>
1360 setDraft((current) => ({
1361 ...current,
1362 schedule: { ...current.schedule, maxDeliveryAgeMinutes },
1363 }))
1364 }
1365 />
1366 <WebhookFilterRows
1367 filters={draft.schedule.filters}
1368 disabled={saving}
1369 onChange={(update) =>
1370 setDraft((current) => ({
1371 ...current,
1372 schedule: { ...current.schedule, filters: update(current.schedule.filters) },
1373 }))
1374 }
1375 />
1376 <FormField
1377 label={gt("Duplicate request key")}
1378 value={draft.schedule.replayKey}
1379 placeholder="{{headers.delivery-id}}"
1380 disabled={saving}
1381 borderTop
1382 onChange={(replayKey) =>
1383 setDraft((current) => ({
1384 ...current,
1385 schedule: { ...current.schedule, replayKey },
1386 }))
1387 }
1388 />
1389 <Text className="px-4 pb-3 text-sm text-foreground-muted">
1390 <T>Requests with the same key run only once within 7 days.</T>
1391 </Text>
1392 <FormField
1393 label={gt("Coalesce key template")}
1394 value={draft.schedule.coalesceKey}
1395 placeholder="{{body.id}}"
1396 disabled={saving}
1397 borderTop
1398 onChange={(coalesceKey) =>
1399 setDraft((current) => ({
1400 ...current,
1401 schedule: { ...current.schedule, coalesceKey },
1402 }))
1403 }
1404 />
1405 <FormField
1406 label={gt("Coalesce window (seconds, 10–3600)")}
1407 value={draft.schedule.coalesceWindowSeconds}
1408 placeholder="120"
1409 keyboardType="number-pad"
1410 disabled={saving}
1411 borderTop
1412 onChange={(coalesceWindowSeconds) =>
1413 setDraft((current) => ({
1414 ...current,
1415 schedule: { ...current.schedule, coalesceWindowSeconds },
1416 }))
1417 }
1418 />
1419 <Text className="px-4 pb-3 text-sm text-foreground-muted">
1420 <T>
1421 Coalescing runs the latest payload when the window from the first delivery closes.
1422 Empty keys run normally.
1423 </T>
1424 </Text>
1425 </>
1426 ) : (
1427 <>
1428 <FormField
1429 label={gt("Minutes between runs")}
1430 value={draft.schedule.intervalMinutes}
1431 keyboardType="decimal-pad"
1432 disabled={saving}
1433 borderTop
1434 onChange={(intervalMinutes) =>
1435 setDraft((current) => ({
1436 ...current,
1437 schedule: { ...current.schedule, intervalMinutes },
1438 }))
1439 }
1440 />
1441 {!(parseIntervalMinutes(draft.schedule.intervalMinutes) >= 1) ? (
1442 <Text className="px-4 pb-3 text-sm text-danger-foreground">
1443 <T>Intervals must be at least 1 minute. Update this interval before saving.</T>
1444 </Text>
1445 ) : draft.task?.schedule.type === "interval" &&
1446 draft.task.schedule.everyMs < 60_000 ? (
1447 <Text className="px-4 pb-3 text-sm text-foreground-muted">
1448 <T>
1449 This task previously ran more than once per minute. Saving requires an interval
1450 of at least 1 minute.
1451 </T>
1452 </Text>
1453 ) : null}
1454 </>
1455 )}
1456 <View className="min-h-14 flex-row items-center gap-3 border-t border-border-subtle px-4 py-3">
1457 <Text textRole="body" className="min-w-0 flex-1 text-foreground">
1458 {gt("Enabled", { $context: "switch label, whether the task runs" })}
1459 </Text>
1460 <ThemedSwitch
1461 accessibilityLabel={gt("Task enabled")}
1462 value={draft.enabled}
1463 onValueChange={(enabled) => setDraft((current) => ({ ...current, enabled }))}
1464 />
1465 </View>
1466 </SettingsSection>
1467 {draft.schedule.mode === "fixed_time" ? (
1468 <Text className="px-2 text-sm text-foreground-muted">
1469 <T>Time uses the environment's time zone, which may differ from your phone's.</T>
1470 </Text>
1471 ) : null}
1472 </View>
1473 <Button
1474 tone="primary"
1475 fullWidth
1476 loading={saving}
1477 disabled={
1478 !canOperate ||
1479 dictationPending ||
1480 taskMissing ||
1481 environmentUnavailable ||
1482 automaticBaseRefLoading ||
1483 // The server refuses an enabled webhook task under this policy.
1484 (draft.enabled && draft.schedule.mode === "webhook" && webhookDenial !== undefined)
1485 }
1486 onPress={() => void save()}
1487 label={saving ? gt("Saving…") : draft.task ? gt("Save changes") : gt("Create task")}
1488 />
1489 </View>
1490 );
1491 }
1492
1493 function WebhookScheduleDetails({
1494 environmentId,
1495 task,
1496 signatureConfigured,
1497 disabled,
1498 }: {
1499 readonly environmentId: EnvironmentId;
1500 readonly task: ScheduledTask | null;
1501 readonly signatureConfigured: boolean;
1502 readonly disabled: boolean;
1503 }) {
1504 const gt = useGT();
1505 const m = useMessages();
1506 const [rotating, setRotating] = useState(false);
1507 const rotate = useAtomCommand(serverEnvironment.rotateScheduledTaskWebhookToken, {
1508 label: "scheduled task rotate webhook token",
1509 reportFailure: false,
1510 });
1511 const preparedConnection = usePreparedConnection(environmentId);
1512 const httpBaseUrl =
1513 preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : null;
1514 const webhook = task?.schedule.type === "webhook" ? task.webhook : undefined;
1515 const resolved = webhook ? webhookAddress(webhook, httpBaseUrl, m) : null;
1516 return (
1517 <View className="gap-2 border-t border-border-subtle px-4 py-3">
1518 <Text className="text-sm text-foreground-muted">
1519 {gt(
1520 "The prompt can use {body}, {headers}, {query}, {wholeBody} and {request}. The filled-in prompt is all the agent sees.",
1521 {
1522 body: "{{body.a.b}}",
1523 headers: "{{headers.name}}",
1524 query: "{{query.name}}",
1525 wholeBody: "{{body}}",
1526 request: "{{request}}",
1527 },
1528 )}
1529 </Text>
1530 {task === null || resolved === null ? (
1531 <Text className="text-sm text-foreground-muted">
1532 <T>Save the task to get its webhook URL.</T>
1533 </Text>
1534 ) : (
1535 <>
1536 <Pressable
1537 accessibilityRole="button"
1538 accessibilityLabel={gt("Copy webhook URL")}
1539 accessibilityHint={gt("Copies the URL to the clipboard")}
1540 disabled={!resolved.copyable}
1541 onPress={() => void tryCopyTextWithHaptic(resolved.address)}
1542 className="gap-1 active:opacity-70"
1543 >
1544 <Text textRole="body" className="text-foreground">
1545 {resolved.copyable ? gt("Webhook URL") : gt("Webhook path")}
1546 </Text>
1547 <Text className="text-sm text-foreground-muted" numberOfLines={2} selectable>
1548 {resolved.address}
1549 </Text>
1550 </Pressable>
1551 {resolved.note !== null ? (
1552 <Text className="text-sm text-foreground-muted">{resolved.note}</Text>
1553 ) : null}
1554 <Button
1555 label={rotating ? gt("Rotating…") : gt("Rotate URL")}
1556 tone="danger"
1557 disabled={disabled || rotating}
1558 onPress={() =>
1559 Dialog.alert(gt("Rotate URL?"), gt("The current URL stops working immediately."), [
1560 { text: gt("Cancel"), style: "cancel" },
1561 {
1562 text: gt("Rotate", { $context: "verb, replace the webhook URL" }),
1563 style: "destructive",
1564 onPress: () => {
1565 setRotating(true);
1566 void rotate({ environmentId, input: { id: task.id } }).then((result) => {
1567 setRotating(false);
1568 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1569 Dialog.alert(
1570 gt("Could not rotate URL"),
1571 String(squashAtomCommandFailure(result)),
1572 );
1573 }
1574 });
1575 },
1576 },
1577 ])
1578 }
1579 loading={rotating}
1580 />
1581 </>
1582 )}
1583 {signatureConfigured ? (
1584 <Text className="text-sm text-foreground-muted">
1585 <T>Signature check configured on desktop/web.</T>
1586 </Text>
1587 ) : null}
1588 </View>
1589 );
1590 }
1591
1592 function EnvironmentTasks({
1593 environment,
1594 now,
1595 projectIds,
1596 onEdit,
1597 }: {
1598 readonly environment: SettingsTarget;
1599 readonly now: number;
1600 readonly projectIds: readonly ProjectId[] | null;
1601 readonly onEdit: (task: ScheduledTask) => void;
1602 }) {
1603 const gt = useGT();
1604 const m = useMessages();
1605 const locale = useLocale();
1606 const environmentId = environment.environmentId;
1607 const tasks = useEnvironmentQuery(
1608 serverEnvironment.scheduledTasksLive({ environmentId, input: {} }),
1609 );
1610 const visibleTasks = tasks.data?.tasks.filter(
1611 (task) => projectIds === null || projectIds.includes(task.projectId),
1612 );
1613 const canOperate = useAtomValue(
1614 serverEnvironment.upsertScheduledTask.permissionAtom(environmentId),
1615 );
1616 const setEnabled = useAtomCommand(serverEnvironment.setScheduledTaskEnabled, {
1617 label: "scheduled task enabled",
1618 reportFailure: false,
1619 });
1620 const runNow = useAtomCommand(serverEnvironment.runScheduledTaskNow, {
1621 label: "scheduled task run",
1622 reportFailure: false,
1623 });
1624 const remove = useAtomCommand(serverEnvironment.deleteScheduledTask, {
1625 label: "scheduled task delete",
1626 reportFailure: false,
1627 });
1628 const selectDetail = useSelectWorkspaceDetail();
1629 const failure = (title: string, result: AtomCommandResult<unknown, unknown>) => {
1630 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1631 Dialog.alert(title, String(squashAtomCommandFailure(result)));
1632 }
1633 };
1634
1635 const act = async (task: ScheduledTask, action: "run" | "toggle" | "delete") => {
1636 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;
1637 const result =
1638 action === "run"
1639 ? await runNow({ environmentId, input: { id: task.id } })
1640 : action === "toggle"
1641 ? await setEnabled({ environmentId, input: { id: task.id, enabled: !task.enabled } })
1642 : await remove({ environmentId, input: { id: task.id } });
1643 failure(
1644 action === "run"
1645 ? gt("Could not run task")
1646 : action === "toggle"
1647 ? gt("Could not update task")
1648 : gt("Could not delete task"),
1649 result,
1650 );
1651 };
1652
1653 return (
1654 <SettingsSection
1655 title={environment.label}
1656 titleIcon={
1657 <EnvironmentMachineSymbol
1658 kind={resolveEnvironmentMachineKind(environment.serverConfig)}
1659 size={16}
1660 tintColorClassName={
1661 Platform.OS === "android" ? "accent-primary" : "accent-foreground-muted"
1662 }
1663 />
1664 }
1665 >
1666 {tasks.error ? (
1667 <Text className="p-4 text-base text-danger-foreground">{tasks.error}</Text>
1668 ) : !tasks.data ? (
1669 <Text className="p-4 text-base text-foreground-muted">
1670 <T>Loading tasks…</T>
1671 </Text>
1672 ) : visibleTasks?.length === 0 ? (
1673 <Text className="p-4 text-base text-foreground-muted">
1674 {projectIds === null ? gt("No scheduled tasks yet.") : gt("No tasks in this project.")}
1675 </Text>
1676 ) : (
1677 visibleTasks?.map((task, index) => (
1678 <View
1679 key={task.id}
1680 className={
1681 index === 0
1682 ? "flex-row items-start gap-1 px-4 py-3"
1683 : "flex-row items-start gap-1 border-t border-border-subtle px-4 py-3"
1684 }
1685 >
1686 <Pressable
1687 accessibilityRole="button"
1688 accessibilityLabel={gt("Edit {title}", { title: task.title })}
1689 onPress={() => {
1690 onEdit(task);
1691 }}
1692 className="min-w-0 flex-1 gap-1 active:opacity-70"
1693 >
1694 <Text textRole="body" className="text-foreground" numberOfLines={1}>
1695 {task.title}
1696 </Text>
1697 <Text className="text-sm text-foreground-muted" numberOfLines={2}>
1698 {!task.enabled
1699 ? gt("{schedule} · Paused", {
1700 schedule: describeSchedule(task, tasks.data?.timeZone, m, locale),
1701 })
1702 : task.nextRunAt
1703 ? gt("{schedule} · {nextRun}", {
1704 schedule: describeSchedule(task, tasks.data?.timeZone, m, locale),
1705 nextRun: formatNextScheduledTaskRun(task.nextRunAt, now, m),
1706 })
1707 : describeSchedule(task, tasks.data?.timeZone, m, locale)}
1708 </Text>
1709 {task.blockedByPolicy ? (
1710 <Text className="text-sm text-foreground-muted" numberOfLines={2}>
1711 {task.blockedByPolicy}
1712 </Text>
1713 ) : null}
1714 {task.lastRunError ? (
1715 <Text className="text-sm text-danger-foreground" numberOfLines={2}>
1716 <T>
1717 Last run failed: <Var>{task.lastRunError}</Var>
1718 </T>
1719 </Text>
1720 ) : null}
1721 </Pressable>
1722 <Menu
1723 actions={[
1724 { id: "edit", title: gt("Edit") },
1725 ...(task.threadId !== null && scheduledTaskThreadMode(task) !== "new_thread"
1726 ? [{ id: "thread", title: gt("Open thread") }]
1727 : []),
1728 {
1729 id: "toggle",
1730 title: task.enabled ? gt("Pause") : gt("Resume"),
1731 attributes: { disabled: !canOperate },
1732 },
1733 ...(task.schedule.type === "webhook"
1734 ? []
1735 : [{ id: "run", title: gt("Run now"), attributes: { disabled: !canOperate } }]),
1736 {
1737 id: "delete",
1738 title: gt("Delete"),
1739 attributes: { destructive: true, disabled: !canOperate },
1740 },
1741 ]}
1742 onPressAction={({ nativeEvent }) => {
1743 const action = nativeEvent.event;
1744 if (action === "edit") {
1745 onEdit(task);
1746 } else if (action === "thread" && task.threadId !== null) {
1747 selectDetail({
1748 name: "Thread",
1749 params: {
1750 environmentId: String(environmentId),
1751 threadId: String(task.threadId),
1752 },
1753 });
1754 } else if (action === "delete") {
1755 Dialog.alert(gt("Delete task?"), task.title, [
1756 { text: gt("Cancel"), style: "cancel" },
1757 {
1758 text: gt("Delete"),
1759 style: "destructive",
1760 onPress: () => void act(task, "delete"),
1761 },
1762 ]);
1763 } else if (action === "toggle" || action === "run") {
1764 void act(task, action);
1765 }
1766 }}
1767 >
1768 <Pressable
1769 accessibilityRole="button"
1770 accessibilityLabel={gt("Actions for {title}", { title: task.title })}
1771 className="h-11 w-11 items-center justify-center"
1772 >
1773 <SymbolView
1774 name="ellipsis"
1775 size={18}
1776 tintColorClassName="accent-icon"
1777 type="monochrome"
1778 />
1779 </Pressable>
1780 </Menu>
1781 </View>
1782 ))
1783 )}
1784 </SettingsSection>
1785 );
1786 }