Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadAutomationsPanel.tsx

189 lines6.9 KB

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