Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 Clock3Icon,
4 MoreHorizontalIcon,
5 PencilIcon,
6 PlayIcon,
7 PlusIcon,
8 Trash2Icon,
9} from "lucide-react";
10import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
11import type {
12 EnvironmentId,
13 ModelSelection,
14 OrchestrationV2ThreadLaunchWorkspaceStrategy,
15 ProjectId,
16 ScheduledTask,
17 ScheduledTaskId,
18 ScheduledTaskSchedule,
19 ScheduledTaskUpsertInput,
20 ThreadId,
21} from "@t3tools/contracts";
22import {
23 MIN_SCHEDULED_TASK_INTERVAL_MS,
24 ProviderInstanceId,
25 resolveEnvironmentMachineKind,
26} from "@t3tools/contracts";
27import {
28 isAtomCommandInterrupted,
29 squashAtomCommandFailure,
30} from "@t3tools/client-runtime/state/runtime";
31
32import { formatRelativeTime } from "../../timestampFormat";
33import { useEnvironmentSettings } from "../../hooks/useSettings";
34import { getCustomModelOptionsByInstance } from "../../modelSelection";
35import {
36 applyProviderInstanceSettings,
37 deriveProviderInstanceEntries,
38 sortProviderInstanceEntries,
39} from "../../providerInstances";
40import { useEnvironment, type EnvironmentPresentation } from "../../state/environments";
41import { useProjects } from "../../state/entities";
42import { useEnvironmentQuery } from "../../state/query";
43import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";
44import { useAtomCommand } from "../../state/use-atom-command";
45import { WorktreeBaseBranchPicker } from "../WorktreeBaseBranchPicker";
46import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
47import { useSettingsScope } from "./SettingsScopeContext";
48import {
49 matchesScheduledTaskScope,
50 scheduledTaskDefaultModel,
51 taskToDraft,
52 type DraftState,
53 type WorkspaceMode,
54} from "./scheduledTasksSettings.logic";
55import { Label } from "../ui/label";
56import { Menu, MenuTrigger, MenuPopup, MenuItem, MenuSeparator } from "../ui/menu";
57import { ToggleGroup, Toggle } from "../ui/toggle-group";
58import { Empty, EmptyHeader, EmptyTitle, EmptyDescription, EmptyMedia } from "../ui/empty";
59import { ProviderModelPicker } from "../chat/ProviderModelPicker";
60import { Badge } from "../ui/badge";
61import { Button } from "../ui/button";
62import {
63 Dialog,
64 DialogClose,
65 DialogDescription,
66 DialogFooter,
67 DialogHeader,
68 DialogPanel,
69 DialogPopup,
70 DialogTitle,
71} from "../ui/dialog";
72import { Input } from "../ui/input";
73import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
74import { Switch } from "../ui/switch";
75import { Textarea } from "../ui/textarea";
76import { stackedThreadToast, toastManager } from "../ui/toast";
77import {
78 SettingsPageContainer,
79 SettingsRow,
80 SettingsSection,
81 SETTINGS_PICKER_TRIGGER_CLASSNAME,
82 useRelativeTimeTick,
83} from "./settingsLayout";
84
85/** JS day-of-week (0 = Sunday) rendered Monday-first, matching how people read a week. */
86const WEEKDAY_ORDER = [1, 2, 3, 4, 5, 6, 0] as const;
87const WEEKDAY_LABELS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] as const;
88const WEEKDAY_SHORT = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] as const;
89
90const WORKSPACE_MODE_LABELS: Record<WorkspaceMode, string> = {
91 worktree: "Create a new worktree",
92 root: "Use the project checkout",
93 existing_worktree: "Use a specific checkout",
94};
95
96const EMPTY_DRAFT: DraftState = {
97 editingId: null,
98 title: "",
99 prompt: "",
100 enabled: true,
101 scheduleMode: "fixed",
102 intervalMinutes: "15",
103 timeOfDay: "09:00",
104 weekdays: new Set([1, 2, 3, 4, 5]),
105 projectId: "",
106 threadId: "",
107 workspaceMode: "worktree",
108 baseRef: "main",
109 startFromOrigin: true,
110 existingWorktreePath: "",
111 modelKey: "",
112 runtimeMode: "full-access",
113 interactionMode: "default",
114 baseModelSelection: null,
115};
116
117/** Labelled field: a caption sitting above its control. */
118function Field({
119 label,
120 hint,
121 htmlFor,
122 children,
123}: {
124 label: string;
125 hint?: string;
126 htmlFor?: string;
127 children: ReactNode;
128}) {
129 return (
130 <div className="space-y-1.5">
131 <Label className="flex items-baseline justify-between" htmlFor={htmlFor}>
132 <span>{label}</span>
133 {hint ? (
134 <span className="font-normal text-2xs text-muted-foreground/80">{hint}</span>
135 ) : null}
136 </Label>
137 {children}
138 </div>
139 );
140}
141
142function splitModelKey(value: string): ModelSelection | null {
143 const index = value.indexOf(":");
144 if (index <= 0 || index === value.length - 1) return null;
145 return {
146 instanceId: ProviderInstanceId.make(value.slice(0, index)),
147 model: value.slice(index + 1),
148 };
149}
150
151function scheduleFromDraft(draft: DraftState): ScheduledTaskSchedule {
152 if (draft.scheduleMode === "interval") {
153 const everyMs = Math.round(Number(draft.intervalMinutes) * 60_000);
154 return { type: "interval", everyMs };
155 }
156 const selectedEveryDay = draft.weekdays.size === 0 || draft.weekdays.size === 7;
157 return {
158 type: "fixed_time",
159 timeOfDay: draft.timeOfDay || "09:00",
160 ...(selectedEveryDay ? {} : { weekdays: [...draft.weekdays].toSorted() }),
161 };
162}
163
164export function scheduleLabel(schedule: ScheduledTaskSchedule): string {
165 if (schedule.type === "interval") {
166 const minutes = schedule.everyMs / 60_000;
167 return Number.isInteger(minutes)
168 ? `Every ${minutes} min`
169 : `Every ${Math.round(schedule.everyMs / 1000)} sec`;
170 }
171 const weekdays = schedule.weekdays ?? [];
172 const days =
173 weekdays.length === 0
174 ? "Daily"
175 : weekdays.length === 5 && weekdays.every((day) => day >= 1 && day <= 5)
176 ? "Weekdays"
177 : weekdays.map((day) => WEEKDAY_LABELS[day]).join(", ");
178 return `${days} at ${schedule.timeOfDay}`;
179}
180
181/**
182 * Human label for a run timestamp. `formatRelativeTime` only handles the
183 * past, and `nextRunAt` is a future instant — render "in 5m" style labels
184 * for upcoming runs instead of a misleading "just now".
185 */
186export function relativeLabel(value: string | null): string {
187 if (!value) return "Not scheduled";
188 const diffMs = new Date(value).getTime() - Date.now();
189 if (diffMs <= 0) {
190 const relative = formatRelativeTime(value);
191 if (!relative) return "Not scheduled";
192 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
193 }
194 const minutes = Math.ceil(diffMs / 60_000);
195 if (minutes < 2) return "in under a minute";
196 if (minutes < 60) return `in ${minutes}m`;
197 const hours = Math.round(minutes / 60);
198 if (hours < 24) return `in ${hours}h`;
199 return `in ${Math.round(hours / 24)}d`;
200}
201
202function statusVariant(status: ScheduledTask["lastRunStatus"]) {
203 if (status === "failed") return "error";
204 if (status === "succeeded") return "success";
205 if (status === "running") return "info";
206 return "outline";
207}
208
209export function ScheduledTasksSettings(target: {
210 readonly environmentId?: EnvironmentId;
211 readonly taskId?: ScheduledTaskId | undefined;
212}) {
213 const { scope, environments, connectedEnvironments, environment } = useSettingsScope();
214 const [editor, setEditor] = useState<{
215 environmentId: EnvironmentId;
216 task: ScheduledTask | null;
217 } | null>(null);
218 const openForEdit = useCallback((environmentId: EnvironmentId, task: ScheduledTask) => {
219 setEditor({ environmentId, task });
220 }, []);
221 const defaultEnvironment = environment ?? connectedEnvironments[0];
222 return (
223 <SettingsPageContainer>
224 <SettingsSection
225 title="Scheduled tasks"
226 variant="plain"
227 headerAction={
228 <Button
229 size="xs"
230 variant="ghost-muted"
231 disabled={!defaultEnvironment}
232 onClick={() =>
233 defaultEnvironment &&
234 setEditor({ environmentId: defaultEnvironment.environmentId, task: null })
235 }
236 >
237 <PlusIcon className="size-3" />
238 New task
239 </Button>
240 }
241 >
242 {scope.kind === "unavailable" ? (
243 <SettingsSection title="Unavailable selection">
244 <SettingsRow title={scope.message} />
245 </SettingsSection>
246 ) : environments.length === 0 ? (
247 <Empty>
248 <EmptyHeader>
249 <EmptyMedia variant="icon">
250 <Clock3Icon />
251 </EmptyMedia>
252 <EmptyTitle>No environments available</EmptyTitle>
253 <EmptyDescription>Connect an environment to manage scheduled tasks.</EmptyDescription>
254 </EmptyHeader>
255 </Empty>
256 ) : (
257 <div className="space-y-8">
258 {environments.map((entry) => (
259 <ScheduledTaskEnvironmentSection
260 key={`${entry.environmentId}:${target.taskId ?? ""}`}
261 environment={entry}
262 showEnvironmentHeading={environments.length > 1}
263 taskId={
264 (target.environmentId ?? defaultEnvironment?.environmentId) ===
265 entry.environmentId
266 ? target.taskId
267 : undefined
268 }
269 onEdit={openForEdit}
270 />
271 ))}
272 </div>
273 )}
274 </SettingsSection>
275 {editor ? (
276 <ScheduledTaskEditorDialog
277 key={`${editor.environmentId}:${editor.task?.id ?? "new"}`}
278 initialEnvironmentId={editor.environmentId}
279 task={editor.task}
280 onClose={() => setEditor(null)}
281 />
282 ) : null}
283 </SettingsPageContainer>
284 );
285}
286
287function ScheduledTaskEnvironmentSection({
288 environment,
289 showEnvironmentHeading,
290 taskId,
291 onEdit,
292}: {
293 readonly environment: EnvironmentPresentation;
294 readonly showEnvironmentHeading: boolean;
295 readonly taskId?: ScheduledTaskId | undefined;
296 readonly onEdit: (environmentId: EnvironmentId, task: ScheduledTask) => void;
297}) {
298 const { scope } = useSettingsScope();
299 const connected =
300 environment.connection.phase === "connected" && environment.serverConfig !== null;
301 const tasksQuery = useEnvironmentQuery(
302 connected
303 ? serverEnvironment.scheduledTasksLive({
304 environmentId: environment.environmentId,
305 input: {},
306 })
307 : null,
308 );
309 const tasks = tasksQuery.data?.tasks.filter((task) =>
310 matchesScheduledTaskScope(scope, environment.environmentId, task.projectId),
311 );
312 const linkedTask = tasks?.find((task) => task.id === taskId);
313 const openedLink = useRef(false);
314 useEffect(() => {
315 if (!openedLink.current && linkedTask) {
316 openedLink.current = true;
317 onEdit(environment.environmentId, linkedTask);
318 }
319 }, [environment.environmentId, linkedTask, onEdit]);
320 useRelativeTimeTick(60_000);
321 return (
322 <SettingsSection
323 title={environment.label}
324 hideTitle={!showEnvironmentHeading}
325 icon={
326 <EnvironmentMachineIcon
327 kind={resolveEnvironmentMachineKind(environment.serverConfig)}
328 className="size-3.5"
329 />
330 }
331 >
332 {!connected ? (
333 <SettingsRow
334 title="Environment disconnected"
335 description={`Reconnect ${environment.label} to view its scheduled tasks.`}
336 />
337 ) : tasksQuery.error ? (
338 <SettingsRow title="Could not load scheduled tasks" description={tasksQuery.error} />
339 ) : !tasks ? (
340 <SettingsRow title="Loading scheduled tasks…" role="status" />
341 ) : (
342 <>
343 {taskId && !linkedTask ? (
344 <SettingsRow
345 title="Task unavailable"
346 description="This task no longer exists or is outside the selected project scope."
347 role="status"
348 />
349 ) : null}
350 {tasks.length === 0 ? (
351 <SettingsRow
352 title="No scheduled tasks"
353 description="No tasks match this environment and project selection."
354 />
355 ) : (
356 tasks.map((task) => (
357 <ScheduledTaskRow
358 key={task.id}
359 environmentId={environment.environmentId}
360 task={task}
361 onEdit={() => onEdit(environment.environmentId, task)}
362 />
363 ))
364 )}
365 </>
366 )}
367 </SettingsSection>
368 );
369}
370
371function ScheduledTaskRow({
372 environmentId,
373 task,
374 onEdit,
375}: {
376 readonly environmentId: EnvironmentId;
377 readonly task: ScheduledTask;
378 readonly onEdit: () => void;
379}) {
380 const [busy, setBusy] = useState(false);
381 const toggle = useAtomCommand(serverEnvironment.setScheduledTaskEnabled, {
382 label: "scheduled task enabled",
383 });
384 const run = useAtomCommand(serverEnvironment.runScheduledTaskNow, {
385 label: "scheduled task run now",
386 });
387 const remove = useAtomCommand(serverEnvironment.deleteScheduledTask, {
388 label: "scheduled task delete",
389 });
390 const act = async (action: "toggle" | "run" | "delete") => {
391 if (busy) return;
392 setBusy(true);
393 const result =
394 action === "toggle"
395 ? await toggle({ environmentId, input: { id: task.id, enabled: !task.enabled } })
396 : action === "run"
397 ? await run({ environmentId, input: { id: task.id } })
398 : await remove({ environmentId, input: { id: task.id } });
399 setBusy(false);
400 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
401 toastManager.add(
402 stackedThreadToast({
403 type: "error",
404 title: "Could not update scheduled task",
405 description: String(squashAtomCommandFailure(result)),
406 }),
407 );
408 }
409 };
410 return (
411 <SettingsRow
412 title={task.title}
413 description={<span className="line-clamp-2">{task.prompt}</span>}
414 status={
415 <div className="flex flex-wrap items-center gap-2">
416 <span>
417 {scheduleLabel(task.schedule)} ·{" "}
418 {task.enabled
419 ? task.nextRunAt
420 ? `Next run ${relativeLabel(task.nextRunAt)}`
421 : "Not scheduled"
422 : "Paused"}
423 </span>
424 {task.lastRunStatus !== "never" ? (
425 <Badge variant={statusVariant(task.lastRunStatus)}>{task.lastRunStatus}</Badge>
426 ) : null}
427 {task.lastRunError ? <span className="text-destructive">{task.lastRunError}</span> : null}
428 </div>
429 }
430 control={
431 <div className="flex items-center gap-2">
432 <Switch
433 checked={task.enabled}
434 disabled={busy}
435 aria-label={`Enable ${task.title}`}
436 onCheckedChange={() => void act("toggle")}
437 />
438 <Menu>
439 <MenuTrigger
440 render={
441 <Button
442 size="icon-sm"
443 variant="ghost"
444 disabled={busy}
445 aria-label={`Actions for ${task.title}`}
446 />
447 }
448 >
449 <MoreHorizontalIcon className="size-4" />
450 </MenuTrigger>
451 <MenuPopup align="end">
452 <MenuItem onClick={onEdit}>
453 <PencilIcon />
454 Edit
455 </MenuItem>
456 <MenuItem onClick={() => void act("run")}>
457 <PlayIcon />
458 Run now
459 </MenuItem>
460 <MenuSeparator />
461 <MenuItem onClick={() => void act("delete")}>
462 <Trash2Icon />
463 Delete
464 </MenuItem>
465 </MenuPopup>
466 </Menu>
467 </div>
468 }
469 />
470 );
471}
472
473function ScheduledTaskEditorDialog({
474 initialEnvironmentId,
475 task,
476 onClose,
477}: {
478 readonly initialEnvironmentId: EnvironmentId;
479 readonly task: ScheduledTask | null;
480 readonly onClose: () => void;
481}) {
482 const { scope, connectedEnvironments } = useSettingsScope();
483 const [environmentId, setEnvironmentId] = useState(initialEnvironmentId);
484 const environment = useEnvironment(environmentId);
485 const connected =
486 environment?.connection.phase === "connected" && environment.serverConfig !== null;
487 const tasksQuery = useEnvironmentQuery(
488 connected ? serverEnvironment.scheduledTasksLive({ environmentId, input: {} }) : null,
489 );
490 const allProjects = useProjects();
491 const projects = useMemo(
492 () =>
493 allProjects.filter(
494 (project) =>
495 project.environmentId === environmentId &&
496 matchesScheduledTaskScope(scope, environmentId, project.id),
497 ),
498 [allProjects, environmentId, scope],
499 );
500 const settings = useEnvironmentSettings(environmentId);
501 const providers =
502 useAtomValue(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS;
503 const upsertTask = useAtomCommand(serverEnvironment.upsertScheduledTask, {
504 label: "scheduled task upsert",
505 });
506 const instanceEntries = useMemo(
507 () =>
508 sortProviderInstanceEntries(
509 applyProviderInstanceSettings(deriveProviderInstanceEntries(providers), settings),
510 ),
511 [providers, settings],
512 );
513 const [draft, setDraft] = useState<DraftState>(() =>
514 task ? taskToDraft(task) : { ...EMPTY_DRAFT, projectId: projects[0]?.id ?? "" },
515 );
516 const [saving, setSaving] = useState(false);
517 const submissionPending = useRef(false);
518 const editingTaskMissing =
519 draft.editingId !== null &&
520 tasksQuery.data !== null &&
521 !tasksQuery.data.tasks.some((entry) => entry.id === draft.editingId);
522 const selectedProjectId = draft.projectId || projects[0]?.id || "";
523 const selectedProject = projects.find((project) => project.id === selectedProjectId);
524
525 // The real model picker is keyed by a `${instanceId}:${model}` string, which
526 // is exactly how the draft stores its selection.
527 const firstInstance = instanceEntries[0];
528 const activeSelection = draft.modelKey
529 ? splitModelKey(draft.modelKey)
530 : scheduledTaskDefaultModel(settings, selectedProject ?? null, instanceEntries);
531 const activeInstanceId =
532 activeSelection?.instanceId ?? firstInstance?.instanceId ?? ("" as ProviderInstanceId);
533 const activeModel = activeSelection?.model ?? "";
534 const modelOptionsByInstance = useMemo(
535 () => getCustomModelOptionsByInstance(settings, providers, activeInstanceId, activeModel),
536 [settings, providers, activeInstanceId, activeModel],
537 );
538
539 const reportFailure = (title: string, error: unknown) => {
540 toastManager.add(
541 stackedThreadToast({
542 type: "error",
543 title,
544 description: error instanceof Error ? error.message : String(error),
545 }),
546 );
547 };
548
549 const submit = async () => {
550 if (
551 submissionPending.current ||
552 saving ||
553 editingTaskMissing ||
554 !connected ||
555 tasksQuery.data === null
556 )
557 return;
558 const selection = activeSelection;
559 if (
560 !draft.title.trim() ||
561 !draft.prompt.trim() ||
562 !projects.some((project) => project.id === selectedProjectId) ||
563 selection === null
564 ) {
565 reportFailure("Scheduled task is incomplete", "Add a title, prompt, project, and model.");
566 return;
567 }
568 const schedule = scheduleFromDraft(draft);
569 if (
570 schedule.type === "interval" &&
571 (!Number.isSafeInteger(schedule.everyMs) || schedule.everyMs < MIN_SCHEDULED_TASK_INTERVAL_MS)
572 ) {
573 reportFailure("Invalid interval", "Enter an interval of at least one minute.");
574 return;
575 }
576 if (draft.workspaceMode === "existing_worktree" && !draft.existingWorktreePath.trim()) {
577 reportFailure("Checkout path is required", "Enter the path of the checkout to run in.");
578 return;
579 }
580 // Keep the original selection object (with provider options) when the
581 // picker still points at the same instance+model.
582 const modelSelection =
583 draft.baseModelSelection !== null &&
584 draft.baseModelSelection.instanceId === selection.instanceId &&
585 draft.baseModelSelection.model === selection.model
586 ? draft.baseModelSelection
587 : selection;
588 const workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy =
589 draft.workspaceMode === "root"
590 ? { type: "root" }
591 : draft.workspaceMode === "existing_worktree"
592 ? { type: "existing_worktree", worktreePath: draft.existingWorktreePath.trim() }
593 : {
594 type: "worktree",
595 baseRef: draft.baseRef.trim() || "main",
596 startFromOrigin: draft.startFromOrigin,
597 };
598 const input: ScheduledTaskUpsertInput = {
599 ...(draft.editingId ? { id: draft.editingId as ScheduledTaskId, requireExisting: true } : {}),
600 title: draft.title.trim(),
601 prompt: draft.prompt.trim(),
602 enabled: draft.enabled,
603 schedule,
604 projectId: selectedProjectId as ProjectId,
605 threadId: draft.threadId ? (draft.threadId as ThreadId) : null,
606 workspaceStrategy,
607 modelSelection,
608 runtimeMode: draft.runtimeMode,
609 interactionMode: draft.interactionMode,
610 creationSource: "web",
611 };
612 // Lock before React renders, and keep successful creates locked until the form closes.
613 submissionPending.current = true;
614 setSaving(true);
615 const result = await upsertTask({ environmentId, input });
616 setSaving(false);
617 if (result._tag === "Failure") {
618 submissionPending.current = false;
619 if (!isAtomCommandInterrupted(result)) {
620 reportFailure("Could not save scheduled task", squashAtomCommandFailure(result));
621 }
622 return;
623 }
624 onClose();
625 };
626
627 return (
628 <Dialog
629 open
630 onOpenChange={(open) => {
631 if (!open && !saving) onClose();
632 }}
633 >
634 <DialogPopup className="max-w-xl">
635 <DialogHeader>
636 <DialogTitle>{draft.editingId ? "Edit task" : "New task"}</DialogTitle>
637 <DialogDescription>
638 Run a prompt automatically — on an interval or at a fixed time.
639 </DialogDescription>
640 </DialogHeader>
641
642 <DialogPanel>
643 <fieldset disabled={saving} className="space-y-5">
644 {!connected ? (
645 <p className="text-sm text-destructive">Reconnect this environment before saving.</p>
646 ) : null}
647 <Field label="Runs on" htmlFor="scheduled-task-environment">
648 <Select
649 value={environmentId}
650 disabled={task !== null || saving}
651 onValueChange={(id) => {
652 const next = connectedEnvironments.find((entry) => entry.environmentId === id);
653 if (!next) return;
654 setEnvironmentId(next.environmentId);
655 setDraft((current) => ({
656 ...current,
657 projectId: "",
658 modelKey: "",
659 baseModelSelection: null,
660 baseRef: "main",
661 startFromOrigin: true,
662 existingWorktreePath: "",
663 }));
664 }}
665 >
666 <SelectTrigger id="scheduled-task-environment" size="sm">
667 <SelectValue>
668 <span className="flex items-center gap-2">
669 <EnvironmentMachineIcon
670 kind={resolveEnvironmentMachineKind(environment?.serverConfig ?? null)}
671 className="size-4"
672 />
673 {environment?.label ?? "Unavailable environment"}
674 </span>
675 </SelectValue>
676 </SelectTrigger>
677 <SelectPopup>
678 {connectedEnvironments.map((entry) => (
679 <SelectItem key={entry.environmentId} value={entry.environmentId}>
680 <EnvironmentMachineIcon
681 kind={resolveEnvironmentMachineKind(entry.serverConfig)}
682 className="size-4"
683 />
684 {entry.label}
685 </SelectItem>
686 ))}
687 </SelectPopup>
688 </Select>
689 </Field>
690 {tasksQuery.error ? (
691 <p className="text-sm text-destructive" role="status">
692 {tasksQuery.error}
693 </p>
694 ) : null}
695 {editingTaskMissing ? (
696 <p className="text-xs text-destructive" role="status">
697 This scheduled task no longer exists.
698 </p>
699 ) : null}
700 <Field label="Name" htmlFor="scheduled-task-title">
701 <Input
702 id="scheduled-task-title"
703 placeholder="e.g. Check for Sentry issues"
704 value={draft.title}
705 onChange={(event) =>
706 setDraft((current) => ({ ...current, title: event.target.value }))
707 }
708 />
709 </Field>
710
711 <div className="grid gap-3 sm:grid-cols-2">
712 <Field label="Project" htmlFor="scheduled-task-project">
713 <Select
714 value={selectedProjectId}
715 onValueChange={(projectId) =>
716 setDraft((current) => ({ ...current, projectId: projectId ?? "" }))
717 }
718 >
719 <SelectTrigger size="sm" id="scheduled-task-project">
720 <SelectValue placeholder="Select a project">
721 {selectedProject?.title}
722 </SelectValue>
723 </SelectTrigger>
724 <SelectPopup>
725 {projects.map((project) => (
726 <SelectItem key={project.id} value={project.id}>
727 {project.title}
728 </SelectItem>
729 ))}
730 </SelectPopup>
731 </Select>
732 </Field>
733
734 <Field label="Workspace" htmlFor="scheduled-task-workspace">
735 <Select
736 value={draft.workspaceMode}
737 onValueChange={(value) =>
738 setDraft((current) => ({ ...current, workspaceMode: value as WorkspaceMode }))
739 }
740 >
741 <SelectTrigger size="sm" id="scheduled-task-workspace">
742 <SelectValue>{WORKSPACE_MODE_LABELS[draft.workspaceMode]}</SelectValue>
743 </SelectTrigger>
744 <SelectPopup>
745 <SelectItem value="worktree">Create a new worktree</SelectItem>
746 <SelectItem value="root">Use the project checkout</SelectItem>
747 <SelectItem value="existing_worktree">Use a specific checkout</SelectItem>
748 </SelectPopup>
749 </Select>
750 </Field>
751 </div>
752
753 {draft.workspaceMode === "worktree" ? (
754 <Field label="Base branch" htmlFor="scheduled-task-base-ref">
755 <WorktreeBaseBranchPicker
756 key={`${environmentId}:${selectedProjectId}`}
757 id="scheduled-task-base-ref"
758 environmentId={environmentId}
759 cwd={selectedProject?.workspaceRoot ?? null}
760 value={draft.baseRef}
761 onValueChange={(baseRef) => setDraft((current) => ({ ...current, baseRef }))}
762 startFromOrigin={draft.startFromOrigin}
763 onStartFromOriginChange={(startFromOrigin) =>
764 setDraft((current) => ({ ...current, startFromOrigin }))
765 }
766 disabled={saving || !connected}
767 />
768 </Field>
769 ) : null}
770 {draft.workspaceMode === "existing_worktree" ? (
771 <Field label="Checkout path" htmlFor="scheduled-task-checkout">
772 <Input
773 id="scheduled-task-checkout"
774 value={draft.existingWorktreePath}
775 placeholder="/path/to/checkout"
776 onChange={(event) =>
777 setDraft((current) => ({
778 ...current,
779 existingWorktreePath: event.target.value,
780 }))
781 }
782 />
783 </Field>
784 ) : null}
785
786 <Field label="Prompt" htmlFor="scheduled-task-prompt">
787 <Textarea
788 id="scheduled-task-prompt"
789 className="max-h-64 overflow-y-auto"
790 placeholder="What should the agent do each time this runs?"
791 value={draft.prompt}
792 onChange={(event) =>
793 setDraft((current) => ({ ...current, prompt: event.target.value }))
794 }
795 />
796 </Field>
797
798 <Field label="Model">
799 <ProviderModelPicker
800 disabled={saving || !connected}
801 activeInstanceId={activeInstanceId}
802 model={activeModel}
803 lockedProvider={null}
804 instanceEntries={instanceEntries}
805 modelOptionsByInstance={modelOptionsByInstance}
806 isComposerOwned={false}
807 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
808 onInstanceModelChange={(instanceId, model) =>
809 setDraft((current) => ({ ...current, modelKey: `${instanceId}:${model}` }))
810 }
811 />
812 </Field>
813
814 <div className="space-y-3">
815 {task?.schedule.type === "interval" &&
816 task.schedule.everyMs < MIN_SCHEDULED_TASK_INTERVAL_MS ? (
817 <p className="text-sm text-muted-foreground" role="status">
818 This task uses a legacy interval below one minute. Saving updates it to at least
819 one minute.
820 </p>
821 ) : null}
822 <div className="flex items-center justify-between gap-2">
823 <Label>Schedule</Label>
824 <ToggleGroup
825 aria-label="Schedule type"
826 value={[draft.scheduleMode]}
827 onValueChange={(values) => {
828 const mode = values[0];
829 if (mode === "fixed" || mode === "interval")
830 setDraft((current) => ({ ...current, scheduleMode: mode }));
831 }}
832 >
833 <Toggle value="fixed">At a time</Toggle>
834 <Toggle value="interval">Every interval</Toggle>
835 </ToggleGroup>
836 </div>
837
838 {draft.scheduleMode === "fixed" ? (
839 <div className="flex flex-wrap items-center gap-3">
840 <div className="flex items-center gap-2">
841 <Label htmlFor="scheduled-task-time">Run at</Label>
842 <Input
843 type="time"
844 id="scheduled-task-time"
845 nativeInput
846 className="w-32"
847 value={draft.timeOfDay}
848 onChange={(event) =>
849 setDraft((current) => ({ ...current, timeOfDay: event.target.value }))
850 }
851 />
852 <span className="text-xs text-muted-foreground">on</span>
853 </div>
854 <ToggleGroup
855 multiple
856 variant="outline"
857 size="sm"
858 aria-label="Days to run"
859 value={[...draft.weekdays].map(String)}
860 onValueChange={(values) => {
861 if (values.length === 0) return;
862 setDraft((current) => ({
863 ...current,
864 weekdays: new Set(values.map(Number)),
865 }));
866 }}
867 >
868 {WEEKDAY_ORDER.map((day) => (
869 <Toggle key={day} value={String(day)} aria-label={WEEKDAY_LABELS[day]}>
870 {WEEKDAY_SHORT[day]}
871 </Toggle>
872 ))}
873 </ToggleGroup>
874 </div>
875 ) : (
876 <div className="flex items-center gap-2">
877 <Label htmlFor="scheduled-task-interval">Run every</Label>
878 <Input
879 type="number"
880 id="scheduled-task-interval"
881 nativeInput
882 min={1}
883 step="any"
884 className="w-24"
885 value={draft.intervalMinutes}
886 onChange={(event) =>
887 setDraft((current) => ({ ...current, intervalMinutes: event.target.value }))
888 }
889 />
890 <span className="text-xs text-muted-foreground">minutes</span>
891 </div>
892 )}
893 </div>
894
895 <div className="flex items-center justify-between gap-4">
896 <div className="min-w-0 space-y-1">
897 <Label htmlFor="scheduled-task-enabled">Enabled</Label>
898 <p
899 id="scheduled-task-enabled-description"
900 className="text-sm text-muted-foreground"
901 >
902 Disabled tasks stay saved but do not run.
903 </p>
904 </div>
905 <Switch
906 id="scheduled-task-enabled"
907 aria-describedby="scheduled-task-enabled-description"
908 checked={draft.enabled}
909 onCheckedChange={(enabled) => setDraft((current) => ({ ...current, enabled }))}
910 />
911 </div>
912 </fieldset>
913 </DialogPanel>
914
915 <DialogFooter>
916 <DialogClose render={<Button variant="outline" size="sm" disabled={saving} />}>
917 Cancel
918 </DialogClose>
919 <Button
920 size="sm"
921 disabled={saving || editingTaskMissing || !connected || !tasksQuery.data}
922 onClick={() => void submit()}
923 >
924 {draft.editingId ? "Save task" : "Create task"}
925 </Button>
926 </DialogFooter>
927 </DialogPopup>
928 </Dialog>
929 );
930}