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

ScheduledTasksSettings.tsx

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