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