Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
3import { ThreadDetailsControl } from "./ThreadDetailsControl";
4import { useNavigate } from "@tanstack/react-router";
5import { T, useGT, useMessages, Var } from "gt-react";
6import type { MessageResolver } from "~/i18n/messages";
7import { CalendarClockIcon, PencilIcon, PlayIcon, Settings2Icon } from "lucide-react";
8import { useState } from "react";
9import {
10 AuthOrchestrationOperateScope,
11 type EnvironmentId,
12 type ScheduledTask,
13 type ThreadId,
14} from "@t3tools/contracts";
15import type { TimestampFormat } from "@t3tools/contracts/settings";
16import {
17 isAtomCommandInterrupted,
18 squashAtomCommandFailure,
19} from "@t3tools/client-runtime/state/runtime";
20
21import { ThreadDetailsSection } from "./ThreadDetailsSection";
22import { useClientSettings } from "../../hooks/useSettings";
23import { cn } from "../../lib/utils";
24import { ScheduledRelativeLabel } from "../settings/ScheduledTasksSettings";
25import { scheduleLabel } from "../settings/scheduledTasksSettings.logic";
26import { useEnvironmentQuery } from "../../state/query";
27import { serverEnvironment } from "../../state/server";
28import { useAtomCommand } from "../../state/use-atom-command";
29
30import { readEnvironmentScope } from "../../state/session";
31import { Switch } from "../ui/switch";
32import { stackedThreadToast, toastManager } from "../ui/toast";
33import {
34 THREAD_DETAILS_PANEL_ICON_CLASS,
35 THREAD_DETAILS_PANEL_ROW_CONTENT_CLASS,
36} from "./threadDetailsPanelStyles";
37import { SharedTooltipTrigger } from "../ui/shared-tooltip";
38
39const STATUS_DOT_CLASS: Record<ScheduledTask["lastRunStatus"], string> = {
40 never: "bg-muted-foreground/40",
41 running: "bg-sky-500",
42 succeeded: "bg-emerald-500",
43 failed: "bg-destructive",
44};
45
46function taskScheduleLine(
47 task: ScheduledTask,
48 timestampFormat: TimestampFormat,
49 timeZone: string | undefined,
50 resolve: MessageResolver,
51) {
52 return (
53 <>
54 {scheduleLabel(task.schedule, timestampFormat, timeZone, task.nextRunAt, resolve)}
55 {task.blockedByPolicy !== undefined ? (
56 ` · ${task.blockedByPolicy}`
57 ) : task.enabled && task.nextRunAt !== null ? (
58 <>
59 {" · "}
60 <T>
61 next <ScheduledRelativeLabel value={task.nextRunAt} />
62 </T>
63 </>
64 ) : task.enabled ? (
65 ""
66 ) : (
67 <>
68 {" · "}
69 <T context="automation state">paused</T>
70 </>
71 )}
72 </>
73 );
74}
75
76export function ThreadAutomationsPanel(props: {
77 readonly environmentId: EnvironmentId;
78 readonly threadId: ThreadId;
79}) {
80 const canOperate = useAtomValue(
81 serverEnvironment.runScheduledTaskNow.permissionAtom(props.environmentId),
82 );
83 const tasksQuery = useEnvironmentQuery(
84 serverEnvironment.scheduledTasksLive({ environmentId: props.environmentId, input: {} }),
85 useMessages(),
86 );
87 const setTaskEnabled = useAtomCommand(serverEnvironment.setScheduledTaskEnabled, {
88 label: "thread automation toggle",
89 });
90 const runTaskNow = useAtomCommand(serverEnvironment.runScheduledTaskNow, {
91 label: "thread automation run now",
92 });
93 const timestampFormat = useClientSettings((settings) => settings.timestampFormat);
94 const navigate = useNavigate();
95 const gt = useGT();
96 const m = useMessages();
97 const [busyTaskId, setBusyTaskId] = useState<string | null>(null);
98
99 const boundTasks = (tasksQuery.data?.tasks ?? []).filter(
100 (task) => task.threadId === props.threadId,
101 );
102
103 if (tasksQuery.error === null && boundTasks.length === 0) return null;
104
105 const reportFailure = (title: string, error: unknown) => {
106 toastManager.add(
107 stackedThreadToast({
108 type: "error",
109 title,
110 description: thrownErrorMessage(error, m) ?? String(error),
111 }),
112 );
113 };
114
115 const toggleEnabled = async (task: ScheduledTask, enabled: boolean) => {
116 if (
117 busyTaskId !== null ||
118 !readEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope)
119 )
120 return;
121 setBusyTaskId(task.id);
122 const result = await setTaskEnabled({
123 environmentId: props.environmentId,
124 input: { id: task.id, enabled },
125 });
126 setBusyTaskId(null);
127 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
128 reportFailure(gt("Could not update automation"), squashAtomCommandFailure(result));
129 }
130 };
131
132 const runNow = async (task: ScheduledTask) => {
133 if (
134 busyTaskId !== null ||
135 !readEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope)
136 )
137 return;
138 setBusyTaskId(task.id);
139 const result = await runTaskNow({
140 environmentId: props.environmentId,
141 input: { id: task.id },
142 });
143 setBusyTaskId(null);
144 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
145 reportFailure(gt("Could not run automation"), squashAtomCommandFailure(result));
146 }
147 };
148
149 return (
150 <ThreadDetailsSection
151 headingId="thread-details-automations-heading"
152 title={gt("Automations")}
153 data-thread-automations-panel
154 actions={
155 <SharedTooltipTrigger
156 render={
157 <ThreadDetailsControl
158 size="icon-xs"
159 variant="ghost"
160 part="icon"
161 aria-label={gt("Manage scheduled tasks")}
162 onClick={() =>
163 void navigate({
164 to: "/settings/scheduled-tasks",
165 search: { environmentId: props.environmentId },
166 })
167 }
168 >
169 <Settings2Icon className="size-3.5" />
170 </ThreadDetailsControl>
171 }
172 label={
173 <>
174 <T>Manage scheduled tasks</T>
175 </>
176 }
177 />
178 }
179 >
180 <ul className="m-0 max-h-[13.5rem] list-none overflow-y-auto p-0">
181 {boundTasks.map((task) => (
182 <li
183 key={task.id}
184 className={cn(
185 "group flex items-center rounded-lg py-1.5",
186 THREAD_DETAILS_PANEL_ROW_CONTENT_CLASS,
187 )}
188 >
189 <span className="relative inline-flex size-4 shrink-0 items-center justify-center">
190 <CalendarClockIcon className={THREAD_DETAILS_PANEL_ICON_CLASS} />
191 <span
192 className={cn(
193 "absolute -right-1 -top-1 size-1.5 rounded-full",
194 STATUS_DOT_CLASS[task.lastRunStatus],
195 )}
196 aria-hidden
197 />
198 </span>
199 <SharedTooltipTrigger
200 render={<div className="min-w-0 flex-1" />}
201 label={
202 <>
203 <p className="font-medium">{task.title}</p>
204 <p className="text-muted-foreground">
205 {taskScheduleLine(task, timestampFormat, tasksQuery.data?.timeZone, m)}
206 </p>
207 </>
208 }
209 side="left"
210 >
211 <span className="block truncate text-sm font-medium text-foreground/80">
212 {task.title}
213 </span>
214 <p className="truncate text-2xs text-muted-foreground">
215 {taskScheduleLine(task, timestampFormat, tasksQuery.data?.timeZone, m)}
216 </p>
217 </SharedTooltipTrigger>
218 <SharedTooltipTrigger
219 render={
220 <ThreadDetailsControl
221 size="icon-xs"
222 variant="ghost"
223 part="icon"
224 aria-label={gt("Edit {title}", { title: task.title })}
225 onClick={() =>
226 void navigate({
227 to: "/settings/scheduled-tasks",
228 search: { environmentId: props.environmentId, taskId: task.id },
229 })
230 }
231 >
232 <PencilIcon className="size-3.5" />
233 </ThreadDetailsControl>
234 }
235 label={
236 <>
237 <T>Edit automation</T>
238 </>
239 }
240 />
241 {/* Webhook tasks need a request from their URL. */}
242 {task.schedule.type === "webhook" ? null : (
243 <SharedTooltipTrigger
244 render={
245 <ThreadDetailsControl
246 size="icon-xs"
247 variant="ghost"
248 part="icon"
249 aria-label={gt("Run {title} now", { title: task.title })}
250 disabled={
251 !canOperate || busyTaskId !== null || task.lastRunStatus === "running"
252 }
253 onClick={() => void runNow(task)}
254 >
255 <PlayIcon className="size-3.5" />
256 </ThreadDetailsControl>
257 }
258 label={
259 <>
260 <T>Run now</T>
261 </>
262 }
263 />
264 )}
265 <Switch
266 checked={task.enabled}
267 disabled={!canOperate || busyTaskId !== null}
268 aria-label={
269 task.enabled
270 ? gt("Pause {title}", { title: task.title })
271 : gt("Resume {title}", { title: task.title })
272 }
273 onCheckedChange={(enabled) => void toggleEnabled(task, enabled)}
274 />
275 </li>
276 ))}
277 </ul>
278 {/* Kept last: the details card treats a section whose last child is empty as empty. */}
279 {tasksQuery.error !== null ? (
280 <p className="px-2.5 py-1.5 text-2xs text-destructive">
281 <T>
282 Could not load automations: <Var>{tasksQuery.error}</Var>
283 </T>
284 </p>
285 ) : null}
286 </ThreadDetailsSection>
287 );
288}