Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 Clock3Icon,
4 CopyIcon,
5 InboxIcon,
6 MoreHorizontalIcon,
7 PencilIcon,
8 PlayIcon,
9 PlusIcon,
10 Trash2Icon,
11} from "lucide-react";
12import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
13import type {
14 EnvironmentId,
15 ModelSelection,
16 OrchestrationV2ThreadLaunchWorkspaceStrategy,
17 ProjectId,
18 ScheduledTask,
19 ScheduledTaskId,
20 ScheduledTaskSchedule,
21 ScheduledTaskUpsertInput,
22 ScheduledTaskWebhookDeliveryOutcome,
23 ScheduledTaskWebhookDeliverySummary,
24 ThreadId,
25} from "@t3tools/contracts";
26import { DEFAULT_WEBHOOK_PROMPT } from "@t3tools/client-runtime/scheduled-task-webhook";
27import {
28 MAX_WEBHOOK_DELIVERY_AGE_MINUTES,
29 MIN_SCHEDULED_TASK_INTERVAL_MS,
30 ProviderInstanceId,
31 resolveEnvironmentMachineKind,
32} from "@t3tools/contracts";
33import {
34 isAtomCommandInterrupted,
35 squashAtomCommandFailure,
36} from "@t3tools/client-runtime/state/runtime";
37
38import { formatRelativeTime } from "../../timestampFormat";
39import { useEnvironmentSettings } from "../../hooks/useSettings";
40import { getCustomModelOptionsByInstance } from "../../modelSelection";
41import {
42 applyProviderInstanceSettings,
43 deriveProviderInstanceEntries,
44 sortProviderInstanceEntries,
45} from "../../providerInstances";
46import { usePrimaryCloudLinkState } from "../../cloud/primaryCloudLinkState";
47import { requestConfirmDialog } from "../../confirmDialog";
48import { webhookAddress } from "@t3tools/client-runtime/webhook-address";
49import { Link } from "@tanstack/react-router";
50import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
51import {
52 useEnvironment,
53 useEnvironmentHttpBaseUrl,
54 type EnvironmentPresentation,
55} from "../../state/environments";
56import { useProjects } from "../../state/entities";
57import { useEnvironmentQuery } from "../../state/query";
58import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";
59import { useAtomCommand } from "../../state/use-atom-command";
60import { WorktreeBaseBranchPicker } from "../WorktreeBaseBranchPicker";
61import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
62import { useSettingsScope } from "./SettingsScopeContext";
63import {
64 WEBHOOK_SIGNATURE_DEFAULTS,
65 matchesScheduledTaskScope,
66 scheduleFromDraft,
67 scheduledTaskDefaultModel,
68 taskToDraft,
69 type DraftState,
70 type ScheduleMode,
71 type WorkspaceMode,
72} from "./scheduledTasksSettings.logic";
73import { Label } from "../ui/label";
74import { Menu, MenuTrigger, MenuPopup, MenuItem, MenuSeparator } from "../ui/menu";
75import { ToggleGroup, Toggle } from "../ui/toggle-group";
76import { Empty, EmptyHeader, EmptyTitle, EmptyDescription, EmptyMedia } from "../ui/empty";
77import { ProviderModelPicker } from "../chat/ProviderModelPicker";
78import { Badge } from "../ui/badge";
79import { Button } from "../ui/button";
80import {
81 Dialog,
82 DialogClose,
83 DialogDescription,
84 DialogFooter,
85 DialogHeader,
86 DialogPanel,
87 DialogPopup,
88 DialogTitle,
89} from "../ui/dialog";
90import { Input } from "../ui/input";
91import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
92import { Switch } from "../ui/switch";
93import { Textarea } from "../ui/textarea";
94import { stackedThreadToast, toastManager } from "../ui/toast";
95import {
96 SettingsPageContainer,
97 SettingsRow,
98 SettingsSection,
99 SETTINGS_PICKER_TRIGGER_CLASSNAME,
100 useRelativeTimeTick,
101} from "./settingsLayout";
102
103/** JS day-of-week (0 = Sunday) rendered Monday-first, matching how people read a week. */
104const WEEKDAY_ORDER = [1, 2, 3, 4, 5, 6, 0] as const;
105const WEEKDAY_LABELS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] as const;
106const WEEKDAY_SHORT = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] as const;
107
108const WORKSPACE_MODE_LABELS: Record<WorkspaceMode, string> = {
109 worktree: "Create a new worktree",
110 root: "Use the project checkout",
111 existing_worktree: "Use a specific checkout",
112};
113
114const EMPTY_DRAFT: DraftState = {
115 editingId: null,
116 title: "",
117 prompt: "",
118 enabled: true,
119 scheduleMode: "fixed",
120 intervalMinutes: "15",
121 timeOfDay: "09:00",
122 weekdays: new Set([1, 2, 3, 4, 5]),
123 projectId: "",
124 threadId: "",
125 workspaceMode: "worktree",
126 baseRef: "main",
127 startFromOrigin: true,
128 existingWorktreePath: "",
129 modelKey: "",
130 runtimeMode: "full-access",
131 interactionMode: "default",
132 baseModelSelection: null,
133 signatureEnabled: false,
134 ...WEBHOOK_SIGNATURE_DEFAULTS,
135 signatureSecret: "",
136 maxDeliveryAgeMinutes: "",
137};
138
139/** Labelled field: a caption sitting above its control. */
140function Field({
141 label,
142 hint,
143 htmlFor,
144 children,
145}: {
146 label: string;
147 hint?: string;
148 htmlFor?: string;
149 children: ReactNode;
150}) {
151 return (
152 <div className="space-y-1.5">
153 <Label className="flex items-baseline justify-between" htmlFor={htmlFor}>
154 <span>{label}</span>
155 {hint ? (
156 <span className="font-normal text-2xs text-muted-foreground/80">{hint}</span>
157 ) : null}
158 </Label>
159 {children}
160 </div>
161 );
162}
163
164function splitModelKey(value: string): ModelSelection | null {
165 const index = value.indexOf(":");
166 if (index <= 0 || index === value.length - 1) return null;
167 return {
168 instanceId: ProviderInstanceId.make(value.slice(0, index)),
169 model: value.slice(index + 1),
170 };
171}
172
173export function scheduleLabel(schedule: ScheduledTaskSchedule): string {
174 if (schedule.type === "webhook") return "On webhook";
175 if (schedule.type === "interval") {
176 const minutes = schedule.everyMs / 60_000;
177 return Number.isInteger(minutes)
178 ? `Every ${minutes} min`
179 : `Every ${Math.round(schedule.everyMs / 1000)} sec`;
180 }
181 const weekdays = schedule.weekdays ?? [];
182 const days =
183 weekdays.length === 0
184 ? "Daily"
185 : weekdays.length === 5 && weekdays.every((day) => day >= 1 && day <= 5)
186 ? "Weekdays"
187 : weekdays.map((day) => WEEKDAY_LABELS[day]).join(", ");
188 return `${days} at ${schedule.timeOfDay}`;
189}
190
191/**
192 * Human label for a run timestamp. `formatRelativeTime` only handles the
193 * past, and `nextRunAt` is a future instant — render "in 5m" style labels
194 * for upcoming runs instead of a misleading "just now".
195 */
196export function relativeLabel(value: string | null): string {
197 if (!value) return "Not scheduled";
198 const diffMs = new Date(value).getTime() - Date.now();
199 if (diffMs <= 0) {
200 const relative = formatRelativeTime(value);
201 if (!relative) return "Not scheduled";
202 return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
203 }
204 const minutes = Math.ceil(diffMs / 60_000);
205 if (minutes < 2) return "in under a minute";
206 if (minutes < 60) return `in ${minutes}m`;
207 const hours = Math.round(minutes / 60);
208 if (hours < 24) return `in ${hours}h`;
209 return `in ${Math.round(hours / 24)}d`;
210}
211
212const DELIVERY_OUTCOME_LABELS: Record<ScheduledTaskWebhookDeliveryOutcome, string> = {
213 accepted: "Ran",
214 dispatch_failed: "Run failed",
215 rejected_signature: "Bad signature",
216 disabled: "Task paused",
217 rate_limited: "Rate limited",
218 expired: "Too old",
219};
220
221function deliveryOutcomeVariant(outcome: ScheduledTaskWebhookDeliveryOutcome) {
222 if (outcome === "accepted") return "success";
223 if (outcome === "disabled" || outcome === "rate_limited" || outcome === "expired") {
224 return "warning";
225 }
226 return "error";
227}
228
229function statusVariant(status: ScheduledTask["lastRunStatus"]) {
230 if (status === "failed") return "error";
231 if (status === "succeeded") return "success";
232 if (status === "running") return "info";
233 return "outline";
234}
235
236export function ScheduledTasksSettings(target: {
237 readonly environmentId?: EnvironmentId;
238 readonly taskId?: ScheduledTaskId | undefined;
239}) {
240 const { scope, environments, connectedEnvironments, environment } = useSettingsScope();
241 const [editor, setEditor] = useState<{
242 environmentId: EnvironmentId;
243 task: ScheduledTask | null;
244 } | null>(null);
245 const openForEdit = useCallback((environmentId: EnvironmentId, task: ScheduledTask) => {
246 setEditor({ environmentId, task });
247 }, []);
248 const defaultEnvironment = environment ?? connectedEnvironments[0];
249 return (
250 <SettingsPageContainer>
251 <SettingsSection
252 title="Scheduled tasks"
253 variant="plain"
254 headerAction={
255 <Button
256 size="xs"
257 variant="ghost-muted"
258 disabled={!defaultEnvironment}
259 onClick={() =>
260 defaultEnvironment &&
261 setEditor({ environmentId: defaultEnvironment.environmentId, task: null })
262 }
263 >
264 <PlusIcon className="size-3" />
265 New task
266 </Button>
267 }
268 >
269 {scope.kind === "unavailable" ? (
270 <SettingsSection title="Unavailable selection">
271 <SettingsRow title={scope.message} />
272 </SettingsSection>
273 ) : environments.length === 0 ? (
274 <Empty>
275 <EmptyHeader>
276 <EmptyMedia variant="icon">
277 <Clock3Icon />
278 </EmptyMedia>
279 <EmptyTitle>No environments available</EmptyTitle>
280 <EmptyDescription>Connect an environment to manage scheduled tasks.</EmptyDescription>
281 </EmptyHeader>
282 </Empty>
283 ) : (
284 <div className="space-y-8">
285 {environments.map((entry) => (
286 <ScheduledTaskEnvironmentSection
287 key={`${entry.environmentId}:${target.taskId ?? ""}`}
288 environment={entry}
289 showEnvironmentHeading={environments.length > 1}
290 taskId={
291 (target.environmentId ?? defaultEnvironment?.environmentId) ===
292 entry.environmentId
293 ? target.taskId
294 : undefined
295 }
296 onEdit={openForEdit}
297 />
298 ))}
299 </div>
300 )}
301 </SettingsSection>
302 {editor ? (
303 <ScheduledTaskEditorDialog
304 key={`${editor.environmentId}:${editor.task?.id ?? "new"}`}
305 initialEnvironmentId={editor.environmentId}
306 task={editor.task}
307 onClose={() => setEditor(null)}
308 />
309 ) : null}
310 </SettingsPageContainer>
311 );
312}
313
314function ScheduledTaskEnvironmentSection({
315 environment,
316 showEnvironmentHeading,
317 taskId,
318 onEdit,
319}: {
320 readonly environment: EnvironmentPresentation;
321 readonly showEnvironmentHeading: boolean;
322 readonly taskId?: ScheduledTaskId | undefined;
323 readonly onEdit: (environmentId: EnvironmentId, task: ScheduledTask) => void;
324}) {
325 const { scope } = useSettingsScope();
326 const connected =
327 environment.connection.phase === "connected" && environment.serverConfig !== null;
328 const tasksQuery = useEnvironmentQuery(
329 connected
330 ? serverEnvironment.scheduledTasksLive({
331 environmentId: environment.environmentId,
332 input: {},
333 })
334 : null,
335 );
336 const tasks = tasksQuery.data?.tasks.filter((task) =>
337 matchesScheduledTaskScope(scope, environment.environmentId, task.projectId),
338 );
339 const linkedTask = tasks?.find((task) => task.id === taskId);
340 const openedLink = useRef(false);
341 useEffect(() => {
342 if (!openedLink.current && linkedTask) {
343 openedLink.current = true;
344 onEdit(environment.environmentId, linkedTask);
345 }
346 }, [environment.environmentId, linkedTask, onEdit]);
347 useRelativeTimeTick(60_000);
348 return (
349 <SettingsSection
350 title={environment.label}
351 hideTitle={!showEnvironmentHeading}
352 icon={
353 <EnvironmentMachineIcon
354 kind={resolveEnvironmentMachineKind(environment.serverConfig)}
355 className="size-3.5"
356 />
357 }
358 >
359 {!connected ? (
360 <SettingsRow
361 title="Environment disconnected"
362 description={`Reconnect ${environment.label} to view its scheduled tasks.`}
363 />
364 ) : tasksQuery.error ? (
365 <SettingsRow title="Could not load scheduled tasks" description={tasksQuery.error} />
366 ) : !tasks ? (
367 <SettingsRow title="Loading scheduled tasks…" role="status" />
368 ) : (
369 <>
370 {taskId && !linkedTask ? (
371 <SettingsRow
372 title="Task unavailable"
373 description="This task no longer exists or is outside the selected project scope."
374 role="status"
375 />
376 ) : null}
377 {tasks.length === 0 ? (
378 <SettingsRow
379 title="No scheduled tasks"
380 description="No tasks match this environment and project selection."
381 />
382 ) : (
383 tasks.map((task) => (
384 <ScheduledTaskRow
385 key={task.id}
386 environmentId={environment.environmentId}
387 task={task}
388 onEdit={() => onEdit(environment.environmentId, task)}
389 />
390 ))
391 )}
392 </>
393 )}
394 </SettingsSection>
395 );
396}
397
398function ScheduledTaskRow({
399 environmentId,
400 task,
401 onEdit,
402}: {
403 readonly environmentId: EnvironmentId;
404 readonly task: ScheduledTask;
405 readonly onEdit: () => void;
406}) {
407 const [busy, setBusy] = useState(false);
408 const [deliveriesOpen, setDeliveriesOpen] = useState(false);
409 const isWebhook = task.schedule.type === "webhook";
410 const toggle = useAtomCommand(serverEnvironment.setScheduledTaskEnabled, {
411 label: "scheduled task enabled",
412 });
413 const run = useAtomCommand(serverEnvironment.runScheduledTaskNow, {
414 label: "scheduled task run now",
415 });
416 const remove = useAtomCommand(serverEnvironment.deleteScheduledTask, {
417 label: "scheduled task delete",
418 });
419 const act = async (action: "toggle" | "run" | "delete") => {
420 if (busy) return;
421 setBusy(true);
422 const result =
423 action === "toggle"
424 ? await toggle({ environmentId, input: { id: task.id, enabled: !task.enabled } })
425 : action === "run"
426 ? await run({ environmentId, input: { id: task.id } })
427 : await remove({ environmentId, input: { id: task.id } });
428 setBusy(false);
429 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
430 toastManager.add(
431 stackedThreadToast({
432 type: "error",
433 title: "Could not update scheduled task",
434 description: String(squashAtomCommandFailure(result)),
435 }),
436 );
437 }
438 };
439 return (
440 <SettingsRow
441 title={task.title}
442 description={<span className="line-clamp-2">{task.prompt}</span>}
443 status={
444 <div className="flex flex-wrap items-center gap-2">
445 <span>
446 {scheduleLabel(task.schedule)} ·{" "}
447 {!task.enabled
448 ? "Paused"
449 : isWebhook
450 ? "Listening"
451 : task.nextRunAt
452 ? `Next run ${relativeLabel(task.nextRunAt)}`
453 : "Not scheduled"}
454 </span>
455 {task.lastRunStatus !== "never" ? (
456 <Badge variant={statusVariant(task.lastRunStatus)}>{task.lastRunStatus}</Badge>
457 ) : null}
458 {task.lastRunError ? <span className="text-destructive">{task.lastRunError}</span> : null}
459 </div>
460 }
461 control={
462 <div className="flex items-center gap-2">
463 <Switch
464 checked={task.enabled}
465 disabled={busy}
466 aria-label={`Enable ${task.title}`}
467 onCheckedChange={() => void act("toggle")}
468 />
469 <Menu>
470 <MenuTrigger
471 render={
472 <Button
473 size="icon-sm"
474 variant="ghost"
475 disabled={busy}
476 aria-label={`Actions for ${task.title}`}
477 />
478 }
479 >
480 <MoreHorizontalIcon className="size-4" />
481 </MenuTrigger>
482 <MenuPopup align="end">
483 <MenuItem onClick={onEdit}>
484 <PencilIcon />
485 Edit
486 </MenuItem>
487 {isWebhook ? (
488 <MenuItem onClick={() => setDeliveriesOpen(true)}>
489 <InboxIcon />
490 Deliveries
491 </MenuItem>
492 ) : (
493 <MenuItem onClick={() => void act("run")}>
494 <PlayIcon />
495 Run now
496 </MenuItem>
497 )}
498 <MenuSeparator />
499 <MenuItem onClick={() => void act("delete")}>
500 <Trash2Icon />
501 Delete
502 </MenuItem>
503 </MenuPopup>
504 </Menu>
505 {deliveriesOpen ? (
506 <WebhookDeliveriesDialog
507 environmentId={environmentId}
508 task={task}
509 onClose={() => setDeliveriesOpen(false)}
510 />
511 ) : null}
512 </div>
513 }
514 />
515 );
516}
517
518function WebhookDeliveriesDialog({
519 environmentId,
520 task,
521 onClose,
522}: {
523 readonly environmentId: EnvironmentId;
524 readonly task: ScheduledTask;
525 readonly onClose: () => void;
526}) {
527 const deliveriesQuery = useEnvironmentQuery(
528 serverEnvironment.scheduledTaskWebhookDeliveries({ environmentId, input: { id: task.id } }),
529 );
530 const [selectedId, setSelectedId] = useState<ScheduledTaskWebhookDeliverySummary["id"] | null>(
531 null,
532 );
533 const selectedQuery = useEnvironmentQuery(
534 selectedId === null
535 ? null
536 : serverEnvironment.scheduledTaskWebhookDelivery({
537 environmentId,
538 input: { id: task.id, deliveryId: selectedId },
539 }),
540 );
541 const deliveries = deliveriesQuery.data?.deliveries ?? null;
542 const selected = selectedQuery.data?.delivery ?? null;
543 const error = selectedId === null ? deliveriesQuery.error : selectedQuery.error;
544
545 return (
546 <Dialog
547 open
548 onOpenChange={(next) => {
549 if (!next) onClose();
550 }}
551 >
552 <DialogPopup className="max-w-2xl">
553 <DialogHeader>
554 <DialogTitle>Deliveries · {task.title}</DialogTitle>
555 <DialogDescription>Recent requests to this task's webhook URL.</DialogDescription>
556 </DialogHeader>
557 <DialogPanel>
558 {error ? <p className="text-sm text-destructive">{error}</p> : null}
559 {selectedId !== null && selected === null && selectedQuery.error === null ? (
560 <p className="text-sm text-muted-foreground" role="status">
561 Loading delivery…
562 </p>
563 ) : selected ? (
564 <div className="space-y-4">
565 <div className="flex flex-wrap items-center gap-2 text-sm">
566 <Badge variant={deliveryOutcomeVariant(selected.outcome)}>
567 {DELIVERY_OUTCOME_LABELS[selected.outcome]}
568 </Badge>
569 <span>
570 {selected.method} · {relativeLabel(selected.receivedAt)}
571 </span>
572 {selected.signatureVerified ? (
573 <span className="text-muted-foreground">Signature verified</span>
574 ) : null}
575 </div>
576 {selected.error ? <p className="text-sm text-destructive">{selected.error}</p> : null}
577 <DeliveryBlock title="Prompt sent to the agent">
578 {selected.renderedPrompt ?? "No run was started for this request."}
579 </DeliveryBlock>
580 {selected.missingFields.length > 0 ? (
581 <p className="text-sm text-muted-foreground">
582 Empty placeholders: {selected.missingFields.join(", ")}
583 </p>
584 ) : null}
585 <DeliveryBlock title="Headers">
586 {Object.entries(selected.headers)
587 .map(([name, value]) => `${name}: ${value}`)
588 .join("\n")}
589 </DeliveryBlock>
590 {selected.query ? (
591 <DeliveryBlock title="Query">{selected.query}</DeliveryBlock>
592 ) : null}
593 <DeliveryBlock title={selected.bodyTruncated ? "Body (truncated)" : "Body"}>
594 {selected.body || "(empty)"}
595 </DeliveryBlock>
596 </div>
597 ) : selectedId !== null ? null : deliveries === null ? (
598 <p className="text-sm text-muted-foreground" role="status">
599 Loading deliveries…
600 </p>
601 ) : deliveries.length === 0 ? (
602 <p className="text-sm text-muted-foreground">No requests yet.</p>
603 ) : (
604 <ul className="divide-y divide-border">
605 {deliveries.map((delivery) => (
606 <li key={delivery.id}>
607 <button
608 type="button"
609 className="flex w-full flex-wrap items-center gap-2 py-2 text-left text-sm hover:bg-accent/40"
610 onClick={() => setSelectedId(delivery.id)}
611 >
612 <Badge variant={deliveryOutcomeVariant(delivery.outcome)}>
613 {DELIVERY_OUTCOME_LABELS[delivery.outcome]}
614 </Badge>
615 <span>{delivery.method}</span>
616 <span className="text-muted-foreground">
617 {relativeLabel(delivery.receivedAt)}
618 </span>
619 {delivery.missingFields.length > 0 ? (
620 <span className="text-muted-foreground">
621 {delivery.missingFields.length} empty placeholder
622 {delivery.missingFields.length === 1 ? "" : "s"}
623 </span>
624 ) : null}
625 </button>
626 </li>
627 ))}
628 </ul>
629 )}
630 </DialogPanel>
631 <DialogFooter>
632 {selectedId !== null ? (
633 <Button variant="outline" size="sm" onClick={() => setSelectedId(null)}>
634 Back
635 </Button>
636 ) : (
637 <Button
638 variant="outline"
639 size="sm"
640 disabled={deliveriesQuery.isPending}
641 onClick={deliveriesQuery.refresh}
642 >
643 Refresh
644 </Button>
645 )}
646 <DialogClose render={<Button size="sm" />}>Done</DialogClose>
647 </DialogFooter>
648 </DialogPopup>
649 </Dialog>
650 );
651}
652
653function DeliveryBlock({ title, children }: { title: string; children: ReactNode }) {
654 return (
655 <div className="space-y-1">
656 <Label>{title}</Label>
657 <pre className="max-h-64 overflow-auto rounded-md bg-muted p-2 text-xs whitespace-pre-wrap break-all">
658 {children}
659 </pre>
660 </div>
661 );
662}
663
664function WebhookEndpointField({
665 environmentId,
666 task,
667}: {
668 readonly environmentId: EnvironmentId;
669 readonly task: ScheduledTask | null;
670}) {
671 const httpBaseUrl = useEnvironmentHttpBaseUrl(environmentId);
672 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "webhook URL" });
673 const rotate = useAtomCommand(serverEnvironment.rotateScheduledTaskWebhookToken, {
674 label: "scheduled task rotate webhook token",
675 });
676 const [rotating, setRotating] = useState(false);
677 const endpoint = task?.webhook;
678 if (!task || !endpoint) {
679 return <p className="text-sm text-muted-foreground">The URL appears after you save.</p>;
680 }
681 const { address: url, copyable, note } = webhookAddress(endpoint, httpBaseUrl);
682 const rotateUrl = async () => {
683 const confirmed =
684 (await requestConfirmDialog("Rotate this webhook URL?\nThe current URL stops working.", {
685 variant: "destructive",
686 })) ??
687 // No themed dialog host is mounted; fall back to the native prompt
688 // rather than rotating unasked.
689 window.confirm("Rotate this webhook URL? The current URL stops working.");
690 if (!confirmed) return;
691 setRotating(true);
692 const result = await rotate({ environmentId, input: { id: task.id } });
693 setRotating(false);
694 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
695 toastManager.add(
696 stackedThreadToast({
697 type: "error",
698 title: "Could not rotate webhook URL",
699 description: String(squashAtomCommandFailure(result)),
700 }),
701 );
702 }
703 };
704 return (
705 <div className="space-y-1.5">
706 <div className="flex items-center gap-2">
707 <Input
708 readOnly
709 aria-label="Webhook URL"
710 value={url}
711 onFocus={(event) => event.currentTarget.select()}
712 />
713 <Button
714 size="sm"
715 variant="outline"
716 type="button"
717 // A bare path is not a URL a sender can call.
718 disabled={!copyable}
719 onClick={() => copyToClipboard(url, undefined)}
720 >
721 <CopyIcon />
722 {isCopied ? "Copied" : "Copy"}
723 </Button>
724 <Button
725 size="sm"
726 variant="outline"
727 type="button"
728 disabled={rotating}
729 onClick={() => void rotateUrl()}
730 >
731 Rotate
732 </Button>
733 </div>
734 {note !== null ? <p className="text-xs text-muted-foreground">{note}</p> : null}
735 {endpoint.url !== null ? <WebhookDeliveryMode environmentId={environmentId} /> : null}
736 </div>
737 );
738}
739
740/**
741 * Whether T3 Connect forwards requests live or holds them while the
742 * environment is offline. The setting is per environment and only readable
743 * for this machine's own environment, so other environments show nothing.
744 */
745function WebhookDeliveryMode({ environmentId }: { readonly environmentId: EnvironmentId }) {
746 const cloudLink = usePrimaryCloudLinkState();
747 if (cloudLink.target?.environmentId !== environmentId || cloudLink.data === null) return null;
748 return (
749 <p className="text-xs text-muted-foreground">
750 {cloudLink.data.holdWebhooksWhileOffline
751 ? "Held for up to 24 hours while this environment is offline. "
752 : "Forwarded live. Requests fail while this environment is offline. "}
753 <Link to="/settings/connections" className="underline underline-offset-2">
754 Change in Connections
755 </Link>
756 </p>
757 );
758}
759
760function ScheduledTaskEditorDialog({
761 initialEnvironmentId,
762 task,
763 onClose,
764}: {
765 readonly initialEnvironmentId: EnvironmentId;
766 readonly task: ScheduledTask | null;
767 readonly onClose: () => void;
768}) {
769 const { scope, connectedEnvironments } = useSettingsScope();
770 const [environmentId, setEnvironmentId] = useState(initialEnvironmentId);
771 const environment = useEnvironment(environmentId);
772 const connected =
773 environment?.connection.phase === "connected" && environment.serverConfig !== null;
774 const tasksQuery = useEnvironmentQuery(
775 connected ? serverEnvironment.scheduledTasksLive({ environmentId, input: {} }) : null,
776 );
777 const allProjects = useProjects();
778 const projects = useMemo(
779 () =>
780 allProjects.filter(
781 (project) =>
782 project.environmentId === environmentId &&
783 matchesScheduledTaskScope(scope, environmentId, project.id),
784 ),
785 [allProjects, environmentId, scope],
786 );
787 const settings = useEnvironmentSettings(environmentId);
788 const providers =
789 useAtomValue(serverEnvironment.providersValueAtom(environmentId)) ?? EMPTY_SERVER_PROVIDERS;
790 const upsertTask = useAtomCommand(serverEnvironment.upsertScheduledTask, {
791 label: "scheduled task upsert",
792 });
793 const instanceEntries = useMemo(
794 () =>
795 sortProviderInstanceEntries(
796 applyProviderInstanceSettings(deriveProviderInstanceEntries(providers), settings),
797 ),
798 [providers, settings],
799 );
800 const [draft, setDraft] = useState<DraftState>(() =>
801 task ? taskToDraft(task) : { ...EMPTY_DRAFT, projectId: projects[0]?.id ?? "" },
802 );
803 const [saving, setSaving] = useState(false);
804 const submissionPending = useRef(false);
805 const editingTaskMissing =
806 draft.editingId !== null &&
807 tasksQuery.data !== null &&
808 !tasksQuery.data.tasks.some((entry) => entry.id === draft.editingId);
809 // The live row, so a rotated URL shows up without reopening the dialog.
810 // Once the list has loaded, a missing task is gone; don't keep showing its URL.
811 const liveTask = tasksQuery.data
812 ? (tasksQuery.data.tasks.find((entry) => entry.id === draft.editingId) ?? null)
813 : task;
814 const selectedProjectId = draft.projectId || projects[0]?.id || "";
815 const selectedProject = projects.find((project) => project.id === selectedProjectId);
816
817 // The real model picker is keyed by a `${instanceId}:${model}` string, which
818 // is exactly how the draft stores its selection.
819 const firstInstance = instanceEntries[0];
820 const activeSelection = draft.modelKey
821 ? splitModelKey(draft.modelKey)
822 : scheduledTaskDefaultModel(settings, selectedProject ?? null, instanceEntries);
823 const activeInstanceId =
824 activeSelection?.instanceId ?? firstInstance?.instanceId ?? ("" as ProviderInstanceId);
825 const activeModel = activeSelection?.model ?? "";
826 const modelOptionsByInstance = useMemo(
827 () => getCustomModelOptionsByInstance(settings, providers, activeInstanceId, activeModel),
828 [settings, providers, activeInstanceId, activeModel],
829 );
830
831 const reportFailure = (title: string, error: unknown) => {
832 toastManager.add(
833 stackedThreadToast({
834 type: "error",
835 title,
836 description: error instanceof Error ? error.message : String(error),
837 }),
838 );
839 };
840
841 const submit = async () => {
842 if (
843 submissionPending.current ||
844 saving ||
845 editingTaskMissing ||
846 !connected ||
847 tasksQuery.data === null
848 )
849 return;
850 const selection = activeSelection;
851 if (
852 !draft.title.trim() ||
853 !draft.prompt.trim() ||
854 !projects.some((project) => project.id === selectedProjectId) ||
855 selection === null
856 ) {
857 reportFailure("Scheduled task is incomplete", "Add a title, prompt, project, and model.");
858 return;
859 }
860 const schedule = scheduleFromDraft(draft);
861 if (schedule === null) {
862 reportFailure(
863 "Invalid age limit",
864 `Enter whole minutes from 1 to ${MAX_WEBHOOK_DELIVERY_AGE_MINUTES}, or leave it blank.`,
865 );
866 return;
867 }
868 if (
869 schedule.type === "webhook" &&
870 schedule.signature &&
871 (!schedule.signature.header ||
872 (!schedule.signature.secret &&
873 !(liveTask?.schedule.type === "webhook" && liveTask.webhook?.hasSecret)))
874 ) {
875 reportFailure("Signing secret is required", "Enter the signature header and secret.");
876 return;
877 }
878 if (
879 schedule.type === "interval" &&
880 (!Number.isSafeInteger(schedule.everyMs) || schedule.everyMs < MIN_SCHEDULED_TASK_INTERVAL_MS)
881 ) {
882 reportFailure("Invalid interval", "Enter an interval of at least one minute.");
883 return;
884 }
885 if (draft.workspaceMode === "existing_worktree" && !draft.existingWorktreePath.trim()) {
886 reportFailure("Checkout path is required", "Enter the path of the checkout to run in.");
887 return;
888 }
889 // Keep the original selection object (with provider options) when the
890 // picker still points at the same instance+model.
891 const modelSelection =
892 draft.baseModelSelection !== null &&
893 draft.baseModelSelection.instanceId === selection.instanceId &&
894 draft.baseModelSelection.model === selection.model
895 ? draft.baseModelSelection
896 : selection;
897 const workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy =
898 draft.workspaceMode === "root"
899 ? { type: "root" }
900 : draft.workspaceMode === "existing_worktree"
901 ? { type: "existing_worktree", worktreePath: draft.existingWorktreePath.trim() }
902 : {
903 type: "worktree",
904 baseRef: draft.baseRef.trim() || "main",
905 startFromOrigin: draft.startFromOrigin,
906 };
907 const input: ScheduledTaskUpsertInput = {
908 ...(draft.editingId ? { id: draft.editingId as ScheduledTaskId, requireExisting: true } : {}),
909 title: draft.title.trim(),
910 prompt: draft.prompt.trim(),
911 enabled: draft.enabled,
912 schedule,
913 projectId: selectedProjectId as ProjectId,
914 threadId: draft.threadId ? (draft.threadId as ThreadId) : null,
915 workspaceStrategy,
916 modelSelection,
917 runtimeMode: draft.runtimeMode,
918 interactionMode: draft.interactionMode,
919 creationSource: "web",
920 };
921 // Lock before React renders, and keep successful creates locked until the form closes.
922 submissionPending.current = true;
923 setSaving(true);
924 const result = await upsertTask({ environmentId, input });
925 setSaving(false);
926 if (result._tag === "Failure") {
927 submissionPending.current = false;
928 if (!isAtomCommandInterrupted(result)) {
929 reportFailure("Could not save scheduled task", squashAtomCommandFailure(result));
930 }
931 return;
932 }
933 onClose();
934 };
935
936 return (
937 <Dialog
938 open
939 onOpenChange={(open) => {
940 if (!open && !saving) onClose();
941 }}
942 >
943 <DialogPopup className="max-w-xl">
944 <DialogHeader>
945 <DialogTitle>{draft.editingId ? "Edit task" : "New task"}</DialogTitle>
946 <DialogDescription>
947 Run a prompt automatically — on an interval, at a fixed time, or when a webhook is
948 called.
949 </DialogDescription>
950 </DialogHeader>
951
952 <DialogPanel>
953 <fieldset disabled={saving} className="space-y-5">
954 {!connected ? (
955 <p className="text-sm text-destructive">Reconnect this environment before saving.</p>
956 ) : null}
957 <Field label="Runs on" htmlFor="scheduled-task-environment">
958 <Select
959 value={environmentId}
960 disabled={task !== null || saving}
961 onValueChange={(id) => {
962 const next = connectedEnvironments.find((entry) => entry.environmentId === id);
963 if (!next) return;
964 setEnvironmentId(next.environmentId);
965 setDraft((current) => ({
966 ...current,
967 projectId: "",
968 modelKey: "",
969 baseModelSelection: null,
970 baseRef: "main",
971 startFromOrigin: true,
972 existingWorktreePath: "",
973 }));
974 }}
975 >
976 <SelectTrigger id="scheduled-task-environment" size="sm">
977 <SelectValue>
978 <span className="flex items-center gap-2">
979 <EnvironmentMachineIcon
980 kind={resolveEnvironmentMachineKind(environment?.serverConfig ?? null)}
981 className="size-4"
982 />
983 {environment?.label ?? "Unavailable environment"}
984 </span>
985 </SelectValue>
986 </SelectTrigger>
987 <SelectPopup>
988 {connectedEnvironments.map((entry) => (
989 <SelectItem key={entry.environmentId} value={entry.environmentId}>
990 <EnvironmentMachineIcon
991 kind={resolveEnvironmentMachineKind(entry.serverConfig)}
992 className="size-4"
993 />
994 {entry.label}
995 </SelectItem>
996 ))}
997 </SelectPopup>
998 </Select>
999 </Field>
1000 {tasksQuery.error ? (
1001 <p className="text-sm text-destructive" role="status">
1002 {tasksQuery.error}
1003 </p>
1004 ) : null}
1005 {editingTaskMissing ? (
1006 <p className="text-xs text-destructive" role="status">
1007 This scheduled task no longer exists.
1008 </p>
1009 ) : null}
1010 <Field label="Name" htmlFor="scheduled-task-title">
1011 <Input
1012 id="scheduled-task-title"
1013 placeholder="e.g. Check for Sentry issues"
1014 value={draft.title}
1015 onChange={(event) =>
1016 setDraft((current) => ({ ...current, title: event.target.value }))
1017 }
1018 />
1019 </Field>
1020
1021 <div className="grid gap-3 sm:grid-cols-2">
1022 <Field label="Project" htmlFor="scheduled-task-project">
1023 <Select
1024 value={selectedProjectId}
1025 onValueChange={(projectId) =>
1026 setDraft((current) => ({ ...current, projectId: projectId ?? "" }))
1027 }
1028 >
1029 <SelectTrigger size="sm" id="scheduled-task-project">
1030 <SelectValue placeholder="Select a project">
1031 {selectedProject?.title}
1032 </SelectValue>
1033 </SelectTrigger>
1034 <SelectPopup>
1035 {projects.map((project) => (
1036 <SelectItem key={project.id} value={project.id}>
1037 {project.title}
1038 </SelectItem>
1039 ))}
1040 </SelectPopup>
1041 </Select>
1042 </Field>
1043
1044 <Field label="Workspace" htmlFor="scheduled-task-workspace">
1045 <Select
1046 value={draft.workspaceMode}
1047 onValueChange={(value) =>
1048 setDraft((current) => ({ ...current, workspaceMode: value as WorkspaceMode }))
1049 }
1050 >
1051 <SelectTrigger size="sm" id="scheduled-task-workspace">
1052 <SelectValue>{WORKSPACE_MODE_LABELS[draft.workspaceMode]}</SelectValue>
1053 </SelectTrigger>
1054 <SelectPopup>
1055 <SelectItem value="worktree">Create a new worktree</SelectItem>
1056 <SelectItem value="root">Use the project checkout</SelectItem>
1057 <SelectItem value="existing_worktree">Use a specific checkout</SelectItem>
1058 </SelectPopup>
1059 </Select>
1060 </Field>
1061 </div>
1062
1063 {draft.workspaceMode === "worktree" ? (
1064 <Field label="Base branch" htmlFor="scheduled-task-base-ref">
1065 <WorktreeBaseBranchPicker
1066 key={`${environmentId}:${selectedProjectId}`}
1067 id="scheduled-task-base-ref"
1068 environmentId={environmentId}
1069 cwd={selectedProject?.workspaceRoot ?? null}
1070 value={draft.baseRef}
1071 onValueChange={(baseRef) => setDraft((current) => ({ ...current, baseRef }))}
1072 startFromOrigin={draft.startFromOrigin}
1073 onStartFromOriginChange={(startFromOrigin) =>
1074 setDraft((current) => ({ ...current, startFromOrigin }))
1075 }
1076 disabled={saving || !connected}
1077 />
1078 </Field>
1079 ) : null}
1080 {draft.workspaceMode === "existing_worktree" ? (
1081 <Field label="Checkout path" htmlFor="scheduled-task-checkout">
1082 <Input
1083 id="scheduled-task-checkout"
1084 value={draft.existingWorktreePath}
1085 placeholder="/path/to/checkout"
1086 onChange={(event) =>
1087 setDraft((current) => ({
1088 ...current,
1089 existingWorktreePath: event.target.value,
1090 }))
1091 }
1092 />
1093 </Field>
1094 ) : null}
1095
1096 <Field label="Prompt" htmlFor="scheduled-task-prompt">
1097 <Textarea
1098 id="scheduled-task-prompt"
1099 className="max-h-64 overflow-y-auto"
1100 placeholder="What should the agent do each time this runs?"
1101 value={draft.prompt}
1102 onChange={(event) =>
1103 setDraft((current) => ({ ...current, prompt: event.target.value }))
1104 }
1105 />
1106 </Field>
1107
1108 <Field label="Model">
1109 <ProviderModelPicker
1110 disabled={saving || !connected}
1111 activeInstanceId={activeInstanceId}
1112 model={activeModel}
1113 lockedProvider={null}
1114 instanceEntries={instanceEntries}
1115 modelOptionsByInstance={modelOptionsByInstance}
1116 isComposerOwned={false}
1117 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
1118 onInstanceModelChange={(instanceId, model) =>
1119 setDraft((current) => ({ ...current, modelKey: `${instanceId}:${model}` }))
1120 }
1121 />
1122 </Field>
1123
1124 <div className="space-y-3">
1125 {task?.schedule.type === "interval" &&
1126 task.schedule.everyMs < MIN_SCHEDULED_TASK_INTERVAL_MS ? (
1127 <p className="text-sm text-muted-foreground" role="status">
1128 This task uses a legacy interval below one minute. Saving updates it to at least
1129 one minute.
1130 </p>
1131 ) : null}
1132 <div className="flex items-center justify-between gap-2">
1133 <Label>Schedule</Label>
1134 <ToggleGroup
1135 aria-label="Schedule type"
1136 value={[draft.scheduleMode]}
1137 onValueChange={(values) => {
1138 const mode = values[0] as ScheduleMode | undefined;
1139 if (mode === "fixed" || mode === "interval" || mode === "webhook")
1140 setDraft((current) => ({
1141 ...current,
1142 scheduleMode: mode,
1143 prompt:
1144 mode === "webhook" && !current.prompt.trim()
1145 ? DEFAULT_WEBHOOK_PROMPT
1146 : current.prompt,
1147 }));
1148 }}
1149 >
1150 <Toggle value="fixed">At a time</Toggle>
1151 <Toggle value="interval">Every interval</Toggle>
1152 <Toggle value="webhook">On webhook</Toggle>
1153 </ToggleGroup>
1154 </div>
1155
1156 {draft.scheduleMode === "webhook" ? (
1157 <div className="space-y-4">
1158 <WebhookEndpointField environmentId={environmentId} task={liveTask} />
1159 <p className="text-xs text-muted-foreground">
1160 {
1161 "Each request runs the prompt. Use {{body.path}}, {{headers.name}}, {{query.name}}, {{body}} or {{request}} in the prompt; only what it names reaches the agent."
1162 }
1163 </p>
1164 <Field
1165 label="Skip requests older than"
1166 hint="minutes, optional"
1167 htmlFor="scheduled-task-max-age"
1168 >
1169 <Input
1170 id="scheduled-task-max-age"
1171 type="number"
1172 nativeInput
1173 min={1}
1174 max={MAX_WEBHOOK_DELIVERY_AGE_MINUTES}
1175 placeholder="Run every request"
1176 value={draft.maxDeliveryAgeMinutes}
1177 onChange={(event) =>
1178 setDraft((current) => ({
1179 ...current,
1180 maxDeliveryAgeMinutes: event.target.value,
1181 }))
1182 }
1183 />
1184 </Field>
1185 <div className="flex items-center justify-between gap-4">
1186 <div className="min-w-0 space-y-1">
1187 <Label htmlFor="scheduled-task-signature">Require signature</Label>
1188 <p className="text-sm text-muted-foreground">
1189 Reject requests without a valid HMAC-SHA256 signature of the body.
1190 </p>
1191 </div>
1192 <Switch
1193 id="scheduled-task-signature"
1194 checked={draft.signatureEnabled}
1195 onCheckedChange={(signatureEnabled) =>
1196 setDraft((current) => ({ ...current, signatureEnabled }))
1197 }
1198 />
1199 </div>
1200 {draft.signatureEnabled ? (
1201 <div className="grid gap-3 sm:grid-cols-2">
1202 <Field label="Header" htmlFor="scheduled-task-signature-header">
1203 <Input
1204 id="scheduled-task-signature-header"
1205 value={draft.signatureHeader}
1206 onChange={(event) =>
1207 setDraft((current) => ({
1208 ...current,
1209 signatureHeader: event.target.value,
1210 }))
1211 }
1212 />
1213 </Field>
1214 <Field label="Prefix" htmlFor="scheduled-task-signature-prefix">
1215 <Input
1216 id="scheduled-task-signature-prefix"
1217 value={draft.signaturePrefix}
1218 placeholder="None"
1219 onChange={(event) =>
1220 setDraft((current) => ({
1221 ...current,
1222 signaturePrefix: event.target.value,
1223 }))
1224 }
1225 />
1226 </Field>
1227 <Field label="Encoding" htmlFor="scheduled-task-signature-encoding">
1228 <Select
1229 value={draft.signatureEncoding}
1230 onValueChange={(value) =>
1231 setDraft((current) => ({
1232 ...current,
1233 signatureEncoding: value === "base64" ? "base64" : "hex",
1234 }))
1235 }
1236 >
1237 <SelectTrigger size="sm" id="scheduled-task-signature-encoding">
1238 <SelectValue>{draft.signatureEncoding}</SelectValue>
1239 </SelectTrigger>
1240 <SelectPopup>
1241 <SelectItem value="hex">hex</SelectItem>
1242 <SelectItem value="base64">base64</SelectItem>
1243 </SelectPopup>
1244 </Select>
1245 </Field>
1246 <Field label="Secret" htmlFor="scheduled-task-signature-secret">
1247 <Input
1248 id="scheduled-task-signature-secret"
1249 type="password"
1250 autoComplete="off"
1251 value={draft.signatureSecret}
1252 placeholder={
1253 liveTask?.schedule.type === "webhook" && liveTask.webhook?.hasSecret
1254 ? "Unchanged"
1255 : "Shared secret"
1256 }
1257 onChange={(event) =>
1258 setDraft((current) => ({
1259 ...current,
1260 signatureSecret: event.target.value,
1261 }))
1262 }
1263 />
1264 </Field>
1265 </div>
1266 ) : null}
1267 </div>
1268 ) : draft.scheduleMode === "fixed" ? (
1269 <div className="flex flex-wrap items-center gap-3">
1270 <div className="flex items-center gap-2">
1271 <Label htmlFor="scheduled-task-time">Run at</Label>
1272 <Input
1273 type="time"
1274 id="scheduled-task-time"
1275 nativeInput
1276 className="w-32"
1277 value={draft.timeOfDay}
1278 onChange={(event) =>
1279 setDraft((current) => ({ ...current, timeOfDay: event.target.value }))
1280 }
1281 />
1282 <span className="text-xs text-muted-foreground">on</span>
1283 </div>
1284 <ToggleGroup
1285 multiple
1286 variant="outline"
1287 size="sm"
1288 aria-label="Days to run"
1289 value={[...draft.weekdays].map(String)}
1290 onValueChange={(values) => {
1291 if (values.length === 0) return;
1292 setDraft((current) => ({
1293 ...current,
1294 weekdays: new Set(values.map(Number)),
1295 }));
1296 }}
1297 >
1298 {WEEKDAY_ORDER.map((day) => (
1299 <Toggle key={day} value={String(day)} aria-label={WEEKDAY_LABELS[day]}>
1300 {WEEKDAY_SHORT[day]}
1301 </Toggle>
1302 ))}
1303 </ToggleGroup>
1304 </div>
1305 ) : (
1306 <div className="flex items-center gap-2">
1307 <Label htmlFor="scheduled-task-interval">Run every</Label>
1308 <Input
1309 type="number"
1310 id="scheduled-task-interval"
1311 nativeInput
1312 min={1}
1313 step="any"
1314 className="w-24"
1315 value={draft.intervalMinutes}
1316 onChange={(event) =>
1317 setDraft((current) => ({ ...current, intervalMinutes: event.target.value }))
1318 }
1319 />
1320 <span className="text-xs text-muted-foreground">minutes</span>
1321 </div>
1322 )}
1323 </div>
1324
1325 <div className="flex items-center justify-between gap-4">
1326 <div className="min-w-0 space-y-1">
1327 <Label htmlFor="scheduled-task-enabled">Enabled</Label>
1328 <p
1329 id="scheduled-task-enabled-description"
1330 className="text-sm text-muted-foreground"
1331 >
1332 Disabled tasks stay saved but do not run.
1333 </p>
1334 </div>
1335 <Switch
1336 id="scheduled-task-enabled"
1337 aria-describedby="scheduled-task-enabled-description"
1338 checked={draft.enabled}
1339 onCheckedChange={(enabled) => setDraft((current) => ({ ...current, enabled }))}
1340 />
1341 </div>
1342 </fieldset>
1343 </DialogPanel>
1344
1345 <DialogFooter>
1346 <DialogClose render={<Button variant="outline" size="sm" disabled={saving} />}>
1347 Cancel
1348 </DialogClose>
1349 <Button
1350 size="sm"
1351 disabled={saving || editingTaskMissing || !connected || !tasksQuery.data}
1352 onClick={() => void submit()}
1353 >
1354 {draft.editingId ? "Save task" : "Create task"}
1355 </Button>
1356 </DialogFooter>
1357 </DialogPopup>
1358 </Dialog>
1359 );
1360}