Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { ThreadDetailsControl } from "./ThreadDetailsControl";
3import { useNavigate } from "@tanstack/react-router";
4import { CalendarClockIcon, PencilIcon, PlayIcon, Settings2Icon } from "lucide-react";
5import { useState } from "react";
6import {
7 AuthOrchestrationOperateScope,
8 type EnvironmentId,
9 type ScheduledTask,
10 type ThreadId,
11} from "@t3tools/contracts";
12import {
13 isAtomCommandInterrupted,
14 squashAtomCommandFailure,
15} from "@t3tools/client-runtime/state/runtime";
16
17import { ThreadDetailsSection } from "./ThreadDetailsSection";
18import { cn } from "../../lib/utils";
19import { ScheduledRelativeLabel, scheduleLabel } from "../settings/ScheduledTasksSettings";
20import { useEnvironmentQuery } from "../../state/query";
21import { serverEnvironment } from "../../state/server";
22import { useAtomCommand } from "../../state/use-atom-command";
23
24import { readEnvironmentScope } from "../../state/session";
25import { Switch } from "../ui/switch";
26import { stackedThreadToast, toastManager } from "../ui/toast";
27import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
28import {
29 THREAD_DETAILS_PANEL_ICON_CLASS,
30 THREAD_DETAILS_PANEL_ROW_CONTENT_CLASS,
31} from "./threadDetailsPanelStyles";
32
33const STATUS_DOT_CLASS: Record<ScheduledTask["lastRunStatus"], string> = {
34 never: "bg-muted-foreground/40",
35 running: "bg-sky-500",
36 succeeded: "bg-emerald-500",
37 failed: "bg-destructive",
38};
39
40export function ThreadAutomationsPanel(props: {
41 readonly environmentId: EnvironmentId;
42 readonly threadId: ThreadId;
43}) {
44 const canOperate = useAtomValue(
45 serverEnvironment.runScheduledTaskNow.permissionAtom(props.environmentId),
46 );
47 const tasksQuery = useEnvironmentQuery(
48 serverEnvironment.scheduledTasksLive({ environmentId: props.environmentId, input: {} }),
49 );
50 const setTaskEnabled = useAtomCommand(serverEnvironment.setScheduledTaskEnabled, {
51 label: "thread automation toggle",
52 });
53 const runTaskNow = useAtomCommand(serverEnvironment.runScheduledTaskNow, {
54 label: "thread automation run now",
55 });
56 const navigate = useNavigate();
57 const [busyTaskId, setBusyTaskId] = useState<string | null>(null);
58
59 const boundTasks = (tasksQuery.data?.tasks ?? []).filter(
60 (task) => task.threadId === props.threadId,
61 );
62
63 if (tasksQuery.error === null && boundTasks.length === 0) return null;
64
65 const reportFailure = (title: string, error: unknown) => {
66 toastManager.add(
67 stackedThreadToast({
68 type: "error",
69 title,
70 description: error instanceof Error ? error.message : String(error),
71 }),
72 );
73 };
74
75 const toggleEnabled = async (task: ScheduledTask, enabled: boolean) => {
76 if (
77 busyTaskId !== null ||
78 !readEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope)
79 )
80 return;
81 setBusyTaskId(task.id);
82 // Partial update: only the enabled flag changes, so a toggle can never
83 // revert concurrent edits made to the task elsewhere.
84 const result = await setTaskEnabled({
85 environmentId: props.environmentId,
86 input: { id: task.id, enabled },
87 });
88 setBusyTaskId(null);
89 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
90 reportFailure("Could not update automation", squashAtomCommandFailure(result));
91 }
92 };
93
94 const runNow = async (task: ScheduledTask) => {
95 if (
96 busyTaskId !== null ||
97 !readEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope)
98 )
99 return;
100 setBusyTaskId(task.id);
101 const result = await runTaskNow({
102 environmentId: props.environmentId,
103 input: { id: task.id },
104 });
105 setBusyTaskId(null);
106 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
107 reportFailure("Could not run automation", squashAtomCommandFailure(result));
108 }
109 };
110
111 return (
112 <ThreadDetailsSection
113 headingId="thread-details-automations-heading"
114 title="Automations"
115 data-thread-automations-panel
116 actions={
117 <Tooltip>
118 <TooltipTrigger
119 render={
120 <ThreadDetailsControl
121 size="icon-xs"
122 variant="ghost"
123 part="icon"
124 aria-label="Manage scheduled tasks"
125 onClick={() =>
126 void navigate({
127 to: "/settings/scheduled-tasks",
128 search: { environmentId: props.environmentId },
129 })
130 }
131 >
132 <Settings2Icon className="size-3.5" />
133 </ThreadDetailsControl>
134 }
135 />
136 <TooltipPopup>Manage scheduled tasks</TooltipPopup>
137 </Tooltip>
138 }
139 >
140 {tasksQuery.error !== null ? (
141 <p className="px-2.5 py-1.5 text-2xs text-destructive">
142 Could not load automations: {tasksQuery.error}
143 </p>
144 ) : null}
145
146 <ul className="m-0 list-none p-0">
147 {boundTasks.map((task) => (
148 <li
149 key={task.id}
150 className={cn(
151 "group flex items-center rounded-lg py-1.5",
152 THREAD_DETAILS_PANEL_ROW_CONTENT_CLASS,
153 )}
154 >
155 <span className="relative inline-flex size-4 shrink-0 items-center justify-center">
156 <CalendarClockIcon className={THREAD_DETAILS_PANEL_ICON_CLASS} />
157 <span
158 className={cn(
159 "absolute -right-1 -top-1 size-1.5 rounded-full",
160 STATUS_DOT_CLASS[task.lastRunStatus],
161 )}
162 aria-hidden
163 />
164 </span>
165 <div className="min-w-0 flex-1">
166 <span className="block truncate text-sm font-medium text-foreground/80">
167 {task.title}
168 </span>
169 <p className="truncate text-2xs text-muted-foreground">
170 {scheduleLabel(task.schedule)}
171 {task.enabled && task.nextRunAt !== null ? (
172 <>
173 {" · next "}
174 <ScheduledRelativeLabel value={task.nextRunAt} />
175 </>
176 ) : task.enabled ? (
177 ""
178 ) : (
179 " · paused"
180 )}
181 </p>
182 </div>
183 <Tooltip>
184 <TooltipTrigger
185 render={
186 <ThreadDetailsControl
187 size="icon-xs"
188 variant="ghost"
189 part="icon"
190 aria-label={`Edit ${task.title}`}
191 onClick={() =>
192 void navigate({
193 to: "/settings/scheduled-tasks",
194 search: { environmentId: props.environmentId, taskId: task.id },
195 })
196 }
197 >
198 <PencilIcon className="size-3.5" />
199 </ThreadDetailsControl>
200 }
201 />
202 <TooltipPopup>Edit automation</TooltipPopup>
203 </Tooltip>
204 {/* A webhook task runs from its URL; there is no request to run it with. */}
205 {task.schedule.type === "webhook" ? null : (
206 <Tooltip>
207 <TooltipTrigger
208 render={
209 <ThreadDetailsControl
210 size="icon-xs"
211 variant="ghost"
212 part="icon"
213 aria-label={`Run ${task.title} now`}
214 disabled={
215 !canOperate || busyTaskId !== null || task.lastRunStatus === "running"
216 }
217 onClick={() => void runNow(task)}
218 >
219 <PlayIcon className="size-3.5" />
220 </ThreadDetailsControl>
221 }
222 />
223 <TooltipPopup>Run now</TooltipPopup>
224 </Tooltip>
225 )}
226 <Switch
227 checked={task.enabled}
228 disabled={!canOperate || busyTaskId !== null}
229 aria-label={task.enabled ? `Pause ${task.title}` : `Resume ${task.title}`}
230 onCheckedChange={(enabled) => void toggleEnabled(task, enabled)}
231 />
232 </li>
233 ))}
234 </ul>
235 </ThreadDetailsSection>
236 );
237}