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

ScheduledTasksSettings.tsx

740 lines28.4 KB

1import { useAtomValue } from "@effect/atom-react";
2import { Clock3Icon, PencilIcon, PlayIcon, PlusIcon, Trash2Icon } from "lucide-react";
3import { type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
4import type {
5 ModelSelection,
6 OrchestrationV2ThreadLaunchWorkspaceStrategy,
7 ProjectId,
8 ProviderInteractionMode,
9 RuntimeMode,
10 ScheduledTask,
11 ScheduledTaskId,
12 ScheduledTaskSchedule,
13 ScheduledTaskUpsertInput,
14 ThreadId,
15} from "@t3tools/contracts";
16import { ProviderInstanceId } from "@t3tools/contracts";
17import {
18 isAtomCommandInterrupted,
19 squashAtomCommandFailure,
20} from "@t3tools/client-runtime/state/runtime";
21​
22import { cn } from "../../lib/utils";
23import { formatRelativeTime } from "../../timestampFormat";
24import { usePrimarySettings } from "../../hooks/useSettings";
25import { getCustomModelOptionsByInstance } from "../../modelSelection";
26import {
27 applyProviderInstanceSettings,
28 deriveProviderInstanceEntries,
29 sortProviderInstanceEntries,
30} from "../../providerInstances";
31import { usePrimaryEnvironment } from "../../state/environments";
32import { useProjects } from "../../state/entities";
33import { useEnvironmentQuery } from "../../state/query";
34import { primaryServerProvidersAtom, serverEnvironment } from "../../state/server";
35import { useAtomCommand } from "../../state/use-atom-command";
36import { ProviderModelPicker } from "../chat/ProviderModelPicker";
37import { Badge } from "../ui/badge";
38import { Button } from "../ui/button";
39import {
40 Dialog,
41 DialogClose,
42 DialogDescription,
43 DialogFooter,
44 DialogHeader,
45 DialogPanel,
46 DialogPopup,
47 DialogTitle,
48} from "../ui/dialog";
49import { Input } from "../ui/input";
50import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
51import { Switch } from "../ui/switch";
52import { Textarea } from "../ui/textarea";
53import { stackedThreadToast, toastManager } from "../ui/toast";
54import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
55import { SettingsPageContainer, SettingsSection, useRelativeTimeTick } from "./settingsLayout";
56​
57type ScheduleMode = "fixed" | "interval";
58type WorkspaceMode = "root" | "worktree" | "existing_worktree";
59​
60interface DraftState {
61 readonly editingId: string | null;
62 readonly title: string;
63 readonly prompt: string;
64 readonly enabled: boolean;
65 readonly scheduleMode: ScheduleMode;
66 readonly intervalMinutes: string;
67 readonly timeOfDay: string;
68 readonly weekdays: ReadonlySet<number>;
69 readonly projectId: string;
70 readonly threadId: string;
71 readonly workspaceMode: WorkspaceMode;
72 readonly baseRef: string;
73 readonly existingWorktreePath: string;
74 readonly modelKey: string;
75 /** Not editable in the dialog, but preserved so editing an agent-created task keeps its modes. */
76 readonly runtimeMode: RuntimeMode;
77 readonly interactionMode: ProviderInteractionMode;
78 /**
79 * The task's original model selection. The picker only edits
80 * `instanceId:model`; keeping the source object preserves provider options
81 * (reasoning, temperature, …) when the model itself is left unchanged.
82 */
83 readonly baseModelSelection: ModelSelection | null;
85​
86/** JS day-of-week (0 = Sunday) rendered Monday-first, matching how people read a week. */
87const WEEKDAY_ORDER = [1, 2, 3, 4, 5, 6, 0] as const;
88const WEEKDAY_LABELS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] as const;
89const WEEKDAY_SHORT = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] as const;
90const ALL_WEEKDAYS: ReadonlySet<number> = new Set([0, 1, 2, 3, 4, 5, 6]);
91​
92const WORKSPACE_MODE_LABELS: Record<WorkspaceMode, string> = {
93 worktree: "Create a new worktree",
94 root: "Use the project checkout",
95 existing_worktree: "Use a specific checkout",
96};
97​
98const EMPTY_DRAFT: DraftState = {
99 editingId: null,
100 title: "",
101 prompt: "",
102 enabled: true,
103 scheduleMode: "fixed",
104 intervalMinutes: "15",
105 timeOfDay: "09:00",
106 weekdays: new Set([1, 2, 3, 4, 5]),
107 projectId: "",
108 threadId: "",
109 workspaceMode: "worktree",
110 baseRef: "main",
111 existingWorktreePath: "",
112 modelKey: "",
113 runtimeMode: "full-access",
114 interactionMode: "default",
115 baseModelSelection: null,
116};
117​
118/** Labelled field: a caption sitting above its control. */
119function Field({
120 label,
121 hint,
122 htmlFor,
123 children,
124}: {
125 label: string;
126 hint?: string;
127 htmlFor?: string;
128 children: ReactNode;
129}) {
130 return (
131 <div className="space-y-1.5">
132 <label
133 className="flex items-baseline justify-between gap-2 text-xs font-medium text-foreground"
134 htmlFor={htmlFor}
135 >
136 <span>{label}</span>
137 {hint ? (
138 <span className="font-normal text-[11px] text-muted-foreground/80">{hint}</span>
139 ) : null}
140 </label>
141 {children}
142 </div>
143 );
145​
146function modelKey(selection: ModelSelection): string {
147 return `${selection.instanceId}:${selection.model}`;
149​
150function splitModelKey(value: string): ModelSelection | null {
151 const index = value.indexOf(":");
152 if (index <= 0 || index === value.length - 1) return null;
153 return {
154 instanceId: ProviderInstanceId.make(value.slice(0, index)),
155 model: value.slice(index + 1),
156 };
158​
159function scheduleFromDraft(draft: DraftState): ScheduledTaskSchedule {
160 if (draft.scheduleMode === "interval") {
161 const minutes = Math.max(1, Number.parseInt(draft.intervalMinutes, 10) || 1);
162 return { type: "interval", everyMs: minutes * 60_000 };
163 }
164 const selectedEveryDay = draft.weekdays.size === 0 || draft.weekdays.size === 7;
165 return {
166 type: "fixed_time",
167 timeOfDay: draft.timeOfDay || "09:00",
168 ...(selectedEveryDay ? {} : { weekdays: [...draft.weekdays].toSorted() }),
169 };
171​
172export function scheduleLabel(schedule: ScheduledTaskSchedule): string {
173 if (schedule.type === "interval") {
174 const minutes = schedule.everyMs / 60_000;
175 return Number.isInteger(minutes)
176 ? `Every ${minutes} min`
177 : `Every ${Math.round(schedule.everyMs / 1000)} sec`;
178 }
179 const weekdays = schedule.weekdays ?? [];
180 const days =
181 weekdays.length === 0
182 ? "Daily"
183 : weekdays.length === 5 && weekdays.every((day) => day >= 1 && day <= 5)
184 ? "Weekdays"
185 : weekdays.map((day) => WEEKDAY_LABELS[day]).join(", ");
186 return `${days} at ${schedule.timeOfDay}`;
188​
189/**
190 * Human label for a run timestamp. `formatRelativeTime` only handles the
191 * past, and `nextRunAt` is a future instant — render "in 5m" style labels
192 * for upcoming runs instead of a misleading "just now".
193 */
194export function relativeLabel(value: string | null): string {
195 if (!value) return "Not scheduled";
196 const diffMs = new Date(value).getTime() - Date.now();
197 if (diffMs <= 0) {
198 const relative = formatRelativeTime(value);
199 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
200 }
201 const minutes = Math.ceil(diffMs / 60_000);
202 if (minutes < 2) return "in under a minute";
203 if (minutes < 60) return `in ${minutes}m`;
204 const hours = Math.round(minutes / 60);
205 if (hours < 24) return `in ${hours}h`;
206 return `in ${Math.round(hours / 24)}d`;
208​
209function taskToDraft(task: ScheduledTask): DraftState {
210 const schedule = task.schedule;
211 const weekdays =
212 schedule.type === "fixed_time" && schedule.weekdays && schedule.weekdays.length > 0
213 ? new Set(schedule.weekdays)
214 : new Set(ALL_WEEKDAYS);
215 return {
216 editingId: task.id,
217 title: task.title,
218 prompt: task.prompt,
219 enabled: task.enabled,
220 scheduleMode: schedule.type === "interval" ? "interval" : "fixed",
221 intervalMinutes:
222 schedule.type === "interval"
223 ? String(Math.max(1, Math.round(schedule.everyMs / 60_000)))
224 : "15",
225 timeOfDay: schedule.type === "fixed_time" ? schedule.timeOfDay : "09:00",
226 weekdays,
227 projectId: task.projectId,
228 threadId: task.threadId ?? "",
229 workspaceMode: task.workspaceStrategy.type,
230 baseRef: task.workspaceStrategy.type === "worktree" ? task.workspaceStrategy.baseRef : "main",
231 existingWorktreePath:
232 task.workspaceStrategy.type === "existing_worktree"
233 ? task.workspaceStrategy.worktreePath
234 : "",
235 modelKey: modelKey(task.modelSelection),
236 runtimeMode: task.runtimeMode,
237 interactionMode: task.interactionMode,
238 baseModelSelection: task.modelSelection,
239 };
241​
242function statusVariant(status: ScheduledTask["lastRunStatus"]) {
243 if (status === "failed") return "error";
244 if (status === "succeeded") return "success";
245 if (status === "running") return "info";
246 return "outline";
248​
249export function ScheduledTasksSettings() {
250 useRelativeTimeTick(15_000);
251 const environment = usePrimaryEnvironment();
252 const projects = useProjects();
253 const settings = usePrimarySettings();
254 const providers = useAtomValue(primaryServerProvidersAtom);
255 // Live subscription: the server pushes a fresh list after every change
256 // (CRUD, run transitions, reschedules), so no manual refresh is needed.
257 const tasksQuery = useEnvironmentQuery(
258 environment
259 ? serverEnvironment.scheduledTasksLive({
260 environmentId: environment.environmentId,
261 input: {},
262 })
263 : null,
264 );
265 const upsertTask = useAtomCommand(serverEnvironment.upsertScheduledTask, {
266 label: "scheduled task upsert",
267 });
268 const deleteTask = useAtomCommand(serverEnvironment.deleteScheduledTask, {
269 label: "scheduled task delete",
270 });
271 const runTaskNow = useAtomCommand(serverEnvironment.runScheduledTaskNow, {
272 label: "scheduled task run now",
273 });
274 const instanceEntries = useMemo(
275 () =>
276 sortProviderInstanceEntries(
277 applyProviderInstanceSettings(deriveProviderInstanceEntries(providers), settings),
278 ),
279 [providers, settings],
280 );
281 const [draft, setDraft] = useState<DraftState>(() => EMPTY_DRAFT);
282 const [dialogOpen, setDialogOpen] = useState(false);
283 const [saving, setSaving] = useState(false);
284 const tasks = tasksQuery.data?.tasks ?? [];
285 const selectedProjectTitle = projects.find((project) => project.id === draft.projectId)?.title;
286​
287 // The real model picker is keyed by a `${instanceId}:${model}` string, which
288 // is exactly how the draft stores its selection.
289 const firstInstance = instanceEntries[0];
290 const defaultModelKey =
291 firstInstance && firstInstance.models[0]
292 ? `${firstInstance.instanceId}:${firstInstance.models[0].slug}`
293 : "";
294 const activeSelection = splitModelKey(draft.modelKey || defaultModelKey);
295 const activeInstanceId =
296 activeSelection?.instanceId ?? firstInstance?.instanceId ?? ("" as ProviderInstanceId);
297 const activeModel = activeSelection?.model ?? "";
298 const modelOptionsByInstance = useMemo(
299 () => getCustomModelOptionsByInstance(settings, providers, activeInstanceId, activeModel),
300 [settings, providers, activeInstanceId, activeModel],
301 );
302​
303 const openForCreate = useCallback(() => {
304 setDraft({
305 ...EMPTY_DRAFT,
306 projectId: projects[0]?.id ?? "",
307 modelKey: defaultModelKey,
308 });
309 setDialogOpen(true);
310 }, [defaultModelKey, projects]);
311​
312 const openForEdit = useCallback((task: ScheduledTask) => {
313 setDraft(taskToDraft(task));
314 setDialogOpen(true);
315 }, []);
316​
317 const reportFailure = (title: string, error: unknown) => {
318 toastManager.add(
319 stackedThreadToast({
320 type: "error",
321 title,
322 description: error instanceof Error ? error.message : String(error),
323 }),
324 );
325 };
326​
327 const submit = useCallback(async () => {
328 if (!environment || saving) return;
329 const selection = splitModelKey(draft.modelKey || defaultModelKey);
330 if (!draft.title.trim() || !draft.prompt.trim() || !draft.projectId || selection === null) {
331 reportFailure("Schedule task is incomplete", "Add a title, prompt, project, and model.");
332 return;
333 }
334 // Keep the original selection object (with provider options) when the
335 // picker still points at the same instance+model.
336 const modelSelection =
337 draft.baseModelSelection !== null &&
338 draft.baseModelSelection.instanceId === selection.instanceId &&
339 draft.baseModelSelection.model === selection.model
340 ? draft.baseModelSelection
341 : selection;
342 const workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy =
343 draft.workspaceMode === "root"
344 ? { type: "root" }
345 : draft.workspaceMode === "existing_worktree"
346 ? { type: "existing_worktree", worktreePath: draft.existingWorktreePath.trim() }
347 : { type: "worktree", baseRef: draft.baseRef.trim() || "main", startFromOrigin: true };
348 const input: ScheduledTaskUpsertInput = {
349 ...(draft.editingId ? { id: draft.editingId as ScheduledTaskId } : {}),
350 title: draft.title.trim(),
351 prompt: draft.prompt.trim(),
352 enabled: draft.enabled,
353 schedule: scheduleFromDraft(draft),
354 projectId: draft.projectId as ProjectId,
355 threadId: draft.threadId ? (draft.threadId as ThreadId) : null,
356 workspaceStrategy,
357 modelSelection,
358 runtimeMode: draft.runtimeMode,
359 interactionMode: draft.interactionMode,
360 creationSource: "web",
361 };
362 setSaving(true);
363 const result = await upsertTask({ environmentId: environment.environmentId, input });
364 setSaving(false);
365 if (result._tag === "Failure") {
366 if (!isAtomCommandInterrupted(result)) {
367 reportFailure("Could not save schedule task", squashAtomCommandFailure(result));
368 }
369 return;
370 }
371 setDialogOpen(false);
372 }, [defaultModelKey, draft, environment, saving, upsertTask]);
373​
374 const handleDelete = useCallback(
375 async (task: ScheduledTask) => {
376 if (!environment) return;
377 const result = await deleteTask({
378 environmentId: environment.environmentId,
379 input: { id: task.id },
380 });
381 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
382 reportFailure("Could not delete schedule task", squashAtomCommandFailure(result));
383 }
384 },
385 [deleteTask, environment],
386 );
387​
388 const handleRunNow = useCallback(
389 async (task: ScheduledTask) => {
390 if (!environment) return;
391 const result = await runTaskNow({
392 environmentId: environment.environmentId,
393 input: { id: task.id },
394 });
395 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
396 reportFailure("Could not run schedule task", squashAtomCommandFailure(result));
397 }
398 },
399 [environment, runTaskNow],
400 );
401​
402 // Keep the draft pointed at a real project once projects load, so a freshly
403 // opened dialog is never stuck on an empty project select.
404 useEffect(() => {
405 if (draft.projectId || projects.length === 0) return;
406 setDraft((current) => ({
407 ...current,
408 projectId: projects[0]?.id ?? "",
409 modelKey: current.modelKey || defaultModelKey,
410 }));
411 }, [defaultModelKey, draft.projectId, projects]);
412​
413 return (
414 <SettingsPageContainer className="max-w-3xl">
415 <SettingsSection
416 title="Schedule Tasks"
417 icon={<Clock3Icon className="size-3.5" />}
418 headerAction={
419 <Button size="xs" variant="outline" onClick={openForCreate}>
420 <PlusIcon className="size-3.5" />
421 New
422 </Button>
423 }
424 >
425 {tasksQuery.error ? (
426 <div className="px-5 py-4 text-xs text-destructive">{tasksQuery.error}</div>
427 ) : tasks.length === 0 ? (
428 <div className="flex flex-col items-center gap-3 px-5 py-12 text-center">
429 <div className="grid size-10 place-items-center rounded-full border border-border/70 bg-muted/40 text-muted-foreground">
430 <Clock3Icon className="size-4.5" />
431 </div>
432 <div className="space-y-1">
433 <p className="text-sm font-medium text-foreground">No schedule tasks yet</p>
434 <p className="mx-auto max-w-xs text-xs text-muted-foreground">
435 Create one to run a prompt on a schedule — on an interval or at a fixed time.
436 </p>
437 </div>
438 <Button size="sm" onClick={openForCreate}>
439 <PlusIcon className="size-3.5" />
440 New task
441 </Button>
442 </div>
443 ) : (
444 <div className="divide-y divide-border/60">
445 {tasks.map((task) => (
446 <div key={task.id} className="grid gap-3 px-5 py-4 sm:grid-cols-[minmax(0,1fr)_auto]">
447 <div className="min-w-0 space-y-2">
448 <div className="flex min-w-0 flex-wrap items-center gap-2">
449 <h3 className="truncate text-sm font-semibold text-foreground">{task.title}</h3>
450 <Badge variant={task.enabled ? "success" : "outline"}>
451 {task.enabled ? "Enabled" : "Paused"}
452 </Badge>
453 <Badge variant={statusVariant(task.lastRunStatus)}>{task.lastRunStatus}</Badge>
454 </div>
455 <p className="line-clamp-2 text-xs text-muted-foreground">{task.prompt}</p>
456 <div className="flex flex-wrap gap-x-4 gap-y-1 text-[11px] text-muted-foreground/80">
457 <span>{scheduleLabel(task.schedule)}</span>
458 <span>Next: {relativeLabel(task.nextRunAt)}</span>
459 <span>Runs: {task.runCount}</span>
460 </div>
461 {task.lastRunError ? (
462 <p className="text-[11px] text-destructive">{task.lastRunError}</p>
463 ) : null}
464 </div>
465 <div className="flex items-start gap-1">
466 <Tooltip>
467 <TooltipTrigger
468 render={
469 <Button
470 size="icon-sm"
471 variant="ghost"
472 aria-label={`Run ${task.title}`}
473 onClick={() => void handleRunNow(task)}
474 >
475 <PlayIcon className="size-4" />
476 </Button>
477 }
478 />
479 <TooltipPopup>Run now</TooltipPopup>
480 </Tooltip>
481 <Button
482 size="icon-sm"
483 variant="ghost"
484 aria-label={`Edit ${task.title}`}
485 onClick={() => openForEdit(task)}
486 >
487 <PencilIcon className="size-4" />
488 </Button>
489 <Button
490 size="icon-sm"
491 variant="ghost"
492 aria-label={`Delete ${task.title}`}
493 onClick={() => void handleDelete(task)}
494 >
495 <Trash2Icon className="size-4" />
496 </Button>
497 </div>
498 </div>
499 ))}
500 </div>
501 )}
502 </SettingsSection>
503​
504 <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
505 <DialogPopup className="max-w-xl">
506 <DialogHeader>
507 <DialogTitle>{draft.editingId ? "Edit task" : "New task"}</DialogTitle>
508 <DialogDescription>
509 Run a prompt automatically — on an interval or at a fixed time.
510 </DialogDescription>
511 </DialogHeader>
512​
513 <DialogPanel className="space-y-5">
514 <Field label="Name" htmlFor="scheduled-task-title">
515 <Input
516 id="scheduled-task-title"
517 placeholder="e.g. Check for Sentry issues"
518 value={draft.title}
519 onChange={(event) =>
520 setDraft((current) => ({ ...current, title: event.target.value }))
521 }
522 />
523 </Field>
524​
525 <div className="grid gap-3 sm:grid-cols-2">
526 <Field label="Project">
527 <Select
528 value={draft.projectId}
529 onValueChange={(projectId) =>
530 setDraft((current) => ({ ...current, projectId: projectId ?? "" }))
531 }
532 >
533 <SelectTrigger size="sm">
534 <SelectValue placeholder="Select a project">{selectedProjectTitle}</SelectValue>
535 </SelectTrigger>
536 <SelectPopup>
537 {projects.map((project) => (
538 <SelectItem key={project.id} value={project.id}>
539 {project.title}
540 </SelectItem>
541 ))}
542 </SelectPopup>
543 </Select>
544 </Field>
545​
546 <Field label="Workspace">
547 <Select
548 value={draft.workspaceMode}
549 onValueChange={(value) =>
550 setDraft((current) => ({ ...current, workspaceMode: value as WorkspaceMode }))
551 }
552 >
553 <SelectTrigger size="sm">
554 <SelectValue>{WORKSPACE_MODE_LABELS[draft.workspaceMode]}</SelectValue>
555 </SelectTrigger>
556 <SelectPopup>
557 <SelectItem value="worktree">Create a new worktree</SelectItem>
558 <SelectItem value="root">Use the project checkout</SelectItem>
559 <SelectItem value="existing_worktree">Use a specific checkout</SelectItem>
560 </SelectPopup>
561 </Select>
562 </Field>
563 </div>
564​
565 {draft.workspaceMode === "worktree" ? (
566 <Field label="Base ref" htmlFor="scheduled-task-base-ref">
567 <Input
568 id="scheduled-task-base-ref"
569 value={draft.baseRef}
570 placeholder="main"
571 onChange={(event) =>
572 setDraft((current) => ({ ...current, baseRef: event.target.value }))
573 }
574 />
575 </Field>
576 ) : null}
577 {draft.workspaceMode === "existing_worktree" ? (
578 <Field label="Checkout path" htmlFor="scheduled-task-checkout">
579 <Input
580 id="scheduled-task-checkout"
581 value={draft.existingWorktreePath}
582 placeholder="/path/to/checkout"
583 onChange={(event) =>
584 setDraft((current) => ({
585 ...current,
586 existingWorktreePath: event.target.value,
587 }))
588 }
589 />
590 </Field>
591 ) : null}
592​
593 <Field label="Prompt" htmlFor="scheduled-task-prompt">
594 <Textarea
595 id="scheduled-task-prompt"
596 placeholder="What should the agent do each time this runs?"
597 value={draft.prompt}
598 onChange={(event) =>
599 setDraft((current) => ({ ...current, prompt: event.target.value }))
600 }
601 />
602 </Field>
603​
604 <Field label="Model">
605 <ProviderModelPicker
606 activeInstanceId={activeInstanceId}
607 model={activeModel}
608 lockedProvider={null}
609 instanceEntries={instanceEntries}
610 modelOptionsByInstance={modelOptionsByInstance}
611 triggerVariant="outline"
612 triggerClassName="w-full max-w-none justify-between text-foreground/90 hover:text-foreground"
613 onInstanceModelChange={(instanceId, model) =>
614 setDraft((current) => ({ ...current, modelKey: `${instanceId}:${model}` }))
615 }
616 />
617 </Field>
618​
619 <div className="space-y-3">
620 <div className="flex items-center justify-between gap-2">
621 <span className="text-xs font-medium text-foreground">Schedule</span>
622 <div className="inline-flex items-center gap-0.5 rounded-lg border border-border/70 bg-muted/40 p-0.5">
623 {(
624 [
625 ["fixed", "Daily"],
626 ["interval", "Interval"],
627 ] as const
628 ).map(([mode, label]) => (
629 <button
630 key={mode}
631 type="button"
632 aria-pressed={draft.scheduleMode === mode}
633 className={cn(
634 "rounded-md px-2.5 py-1 text-xs font-medium transition-colors",
635 draft.scheduleMode === mode
636 ? "bg-background text-foreground shadow-xs"
637 : "text-muted-foreground hover:text-foreground",
638 )}
639 onClick={() => setDraft((current) => ({ ...current, scheduleMode: mode }))}
640 >
641 {label}
642 </button>
643 ))}
644 </div>
645 </div>
646​
647 {draft.scheduleMode === "fixed" ? (
648 <div className="flex flex-wrap items-center gap-3">
649 <div className="flex items-center gap-2">
650 <span className="text-xs text-muted-foreground">Run at</span>
651 <Input
652 type="time"
653 nativeInput
654 className="w-32"
655 value={draft.timeOfDay}
656 onChange={(event) =>
657 setDraft((current) => ({ ...current, timeOfDay: event.target.value }))
658 }
659 />
660 <span className="text-xs text-muted-foreground">on</span>
661 </div>
662 <div className="flex flex-wrap gap-1.5">
663 {WEEKDAY_ORDER.map((day) => {
664 const selected = draft.weekdays.has(day);
665 return (
666 <button
667 key={day}
668 type="button"
669 aria-pressed={selected}
670 aria-label={WEEKDAY_LABELS[day]}
671 className={cn(
672 "grid size-8 place-items-center rounded-full border text-[11px] font-semibold transition-colors",
673 selected
674 ? "border-primary bg-primary text-primary-foreground shadow-xs"
675 : "border-border text-muted-foreground hover:bg-accent hover:text-foreground",
676 )}
677 onClick={() =>
678 setDraft((current) => {
679 const weekdays = new Set(current.weekdays);
680 if (weekdays.has(day)) {
681 // Keep at least one day selected: an empty set
682 // would silently persist as a daily schedule.
683 if (weekdays.size === 1) return current;
684 weekdays.delete(day);
685 } else {
686 weekdays.add(day);
687 }
688 return { ...current, weekdays };
689 })
690 }
691 >
692 {WEEKDAY_SHORT[day]}
693 </button>
694 );
695 })}
696 </div>
697 </div>
698 ) : (
699 <div className="flex items-center gap-2">
700 <span className="text-xs text-muted-foreground">Run every</span>
701 <Input
702 type="number"
703 nativeInput
704 min={1}
705 className="w-24"
706 value={draft.intervalMinutes}
707 onChange={(event) =>
708 setDraft((current) => ({ ...current, intervalMinutes: event.target.value }))
709 }
710 />
711 <span className="text-xs text-muted-foreground">minutes</span>
712 </div>
713 )}
714 </div>
715​
716 <div className="flex items-center justify-between gap-3 rounded-lg border border-border/60 bg-muted/20 px-3 py-2.5">
717 <div className="min-w-0">
718 <div className="text-xs font-medium">Enabled</div>
719 <div className="text-[11px] text-muted-foreground">
720 Disabled tasks stay saved but do not run.
721 </div>
722 </div>
723 <Switch
724 checked={draft.enabled}
725 onCheckedChange={(enabled) => setDraft((current) => ({ ...current, enabled }))}
726 />
727 </div>
728 </DialogPanel>
729​
730 <DialogFooter>
731 <DialogClose render={<Button variant="outline" size="sm" />}>Cancel</DialogClose>
732 <Button size="sm" disabled={saving} onClick={() => void submit()}>
733 {draft.editingId ? "Save task" : "Create task"}
734 </Button>
735 </DialogFooter>
736 </DialogPopup>
737 </Dialog>
738 </SettingsPageContainer>
739 );