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

ThreadAutomationsPanel.tsx

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