forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutomationsView.tsx
More file actions
5536 lines (5245 loc) · 173 KB
/
AutomationsView.tsx
File metadata and controls
5536 lines (5245 loc) · 173 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* AutomationsView — list/detail UI for tasks and n8n workflows.
*/
import {
Button,
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
FieldLabel,
Input,
PageLayout,
PagePanel,
SidebarCollapsedActionButton,
SidebarContent,
SidebarPanel,
SidebarScrollRegion,
StatusBadge,
StatusDot,
Textarea,
} from "@elizaos/ui";
import {
ArrowRight,
Calendar,
CheckCircle2,
ChevronDown,
ChevronRight,
Circle,
Clock3,
Copy,
Edit as EditIcon,
FileText,
GitBranch,
Grid3x3,
LayoutDashboard,
type LucideIcon,
Mail,
Pause,
Play,
Plus,
RefreshCw,
Rss,
Settings,
Share2,
Signal,
SquareTerminal,
Trash2,
Workflow,
Zap,
} from "lucide-react";
import {
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { client } from "../../api";
import {
type AutomationListResponse,
type AutomationNodeDescriptor,
type AutomationItem as CatalogAutomationItem,
type Conversation,
isMissingCredentialsResponse,
type N8nStatusResponse,
type N8nWorkflow,
type N8nWorkflowMissingCredential,
type N8nWorkflowWriteRequest,
type TriggerSummary,
type WorkbenchTask,
} from "../../api/client";
import { useWorkflowGenerationState } from "../../hooks/useWorkflowGenerationState";
import { useApp } from "../../state";
import { confirmDesktopAction } from "../../utils";
import { formatDateTime, formatDurationMs } from "../../utils/format";
// Direct sub-path import: `widgets/index.ts` re-exports `WidgetHost` while
// also pulling other widgets/* modules that depend back through the barrel.
// Going through the index from here drags Rollup into a chunk-level cycle
// (warning: "reexported through module ... while both modules are
// dependencies of each other"); the direct import skips it.
import { WidgetHost } from "../../widgets/WidgetHost";
import { AppPageSidebar } from "../shared/AppPageSidebar";
import {
AppWorkspaceChrome,
useAppWorkspaceChatChrome,
} from "../workspace/AppWorkspaceChrome";
import {
buildAutomationDraftConversationMetadata,
buildAutomationResponseRoutingMetadata,
buildCoordinatorConversationMetadata,
buildCoordinatorTriggerConversationMetadata,
buildWorkflowConversationMetadata,
buildWorkflowDraftConversationMetadata,
getAutomationBridgeConversationId,
resolveAutomationConversation,
} from "./automation-conversations";
import { HeartbeatForm } from "./HeartbeatForm";
import {
buildCreateRequest,
buildUpdateRequest,
emptyForm,
formFromTrigger,
type HeartbeatTemplate,
humanizeEventKind,
loadUserTemplates,
localizedExecutionStatus,
railMonogram,
saveUserTemplates,
scheduleLabel,
type TriggerFormState,
toneForLastStatus,
validateForm,
} from "./heartbeat-utils";
import { PageScopedChatPane } from "./PageScopedChatPane";
import { WorkflowGraphViewer } from "./WorkflowGraphViewer";
import {
VISUALIZE_WORKFLOW_EVENT,
type VisualizeWorkflowEventDetail,
} from "./workflow-graph-events";
type AutomationFilter = "all" | "coordinator" | "workflows" | "scheduled";
type AutomationSubpage = "list" | "node-catalog";
type SelectionKind = "trigger" | "task" | "workflow" | null;
type AutomationItem = CatalogAutomationItem;
interface ScheduledAutomationEntry {
item: AutomationItem;
schedule: TriggerSummary;
key: string;
}
const WORKFLOW_DRAFT_TITLE = "New Workflow Draft";
const WORKFLOW_SYSTEM_ADDENDUM =
"You are in a workflow-specific automation room. Focus only on this " +
"workflow. Use the linked terminal conversation only when it directly " +
"informs the workflow. Request keys and connector setup when needed, and " +
"prefer owner-scoped LifeOps integrations for personal services.";
const AUTOMATION_DRAFT_SYSTEM_ADDENDUM =
"You are in an automation-creation room. The user wants to create one " +
"automation. Decide whether it should be a task or a workflow and call " +
"the matching action exactly once:\n" +
'- Task: a simple prompt that runs on a schedule or from an event, for example "every morning summarize my inbox" or "when I get a GitHub notification, make a todo". Use CREATE_TRIGGER_TASK with a clear displayName, instructions, and any needed schedule.\n' +
'- Workflow: a multi-step n8n pipeline with deterministic steps and integrations, for example "when a Slack message matches X, post to Discord and log it". Create an n8n workflow via the n8n actions.\n' +
"Ask one short clarifying question only if the shape is genuinely " +
"ambiguous; otherwise create immediately. After creation, briefly " +
"confirm what you made and how it starts.";
const NODE_CLASS_ORDER = [
"agent",
"action",
"context",
"integration",
"trigger",
"flow-control",
] as const;
const PAGE_CHAT_PREFILL_EVENT = "milady:chat:prefill";
const DESCRIBE_WORKFLOW_PROMPT = "Describe your workflow";
const DESCRIBE_AUTOMATION_PROMPT = "What should happen?";
const WORKFLOW_PROMPT_PLACEHOLDER =
"Describe the trigger and steps, e.g. when a GitHub issue opens, summarize it and post to Discord";
const AUTOMATION_PROMPT_PLACEHOLDER =
"e.g. Every morning summarize my inbox, or when a GitHub issue opens, triage it";
const AUTOMATIONS_OVERVIEW_VISIBILITY_EVENT =
"milady:automations:overview-visibility";
interface AutomationsOverviewVisibilityDetail {
visible: boolean;
}
type AutomationsOverviewWindow = Window & {
__miladyAutomationsOverviewVisible?: boolean;
};
function createWorkflowDraftId(): string {
return globalThis.crypto.randomUUID();
}
function prefillPageChat(text: string, options?: { select?: boolean }): void {
if (typeof window === "undefined") return;
window.dispatchEvent(
new CustomEvent(PAGE_CHAT_PREFILL_EVENT, {
detail: {
text,
select: options?.select ?? true,
},
}),
);
}
/**
* Display name for an n8n credential type. Backend emits raw credential type
* IDs (e.g. `slackApi`, `gmailOAuth2`); the missing-credentials banner shows
* users a friendly service name. Falls back to the raw type if unmapped.
*/
const CRED_TYPE_LABELS: Record<string, string> = {
gmailOAuth2: "Gmail",
gmailOAuth2Api: "Gmail",
slackApi: "Slack",
slackOAuth2Api: "Slack",
discordApi: "Discord",
discordBotApi: "Discord",
discordWebhookApi: "Discord",
telegramApi: "Telegram",
};
function prettyCredName(credType: string): string {
return CRED_TYPE_LABELS[credType] ?? credType;
}
function buildWorkflowCopyRequest(
workflow: N8nWorkflow,
name: string,
): N8nWorkflowWriteRequest {
return {
name,
nodes:
workflow.nodes?.map((node) => ({
name: node.name,
type: node.type,
typeVersion: node.typeVersion ?? 1,
position: node.position ?? [0, 0],
parameters: node.parameters ?? {},
...(node.notes ? { notes: node.notes } : {}),
...(node.notesInFlow !== undefined
? { notesInFlow: node.notesInFlow }
: {}),
})) ?? [],
connections: workflow.connections ?? {},
settings: {},
};
}
function inferAutomationPromptKind(prompt: string): "task" | "workflow" {
const normalized = prompt.toLowerCase();
const looksScheduledTask =
/\b(every|daily|hourly|weekly|monthly|weekday|morning|evening|at \d{1,2})\b/.test(
normalized,
);
const looksWorkflow =
/\b(when|if|after|then|workflow|pipeline|webhook|event|triage|route|label|enrich|crm)\b/.test(
normalized,
) ||
(normalized.includes(" and ") &&
/\b(send|post|create|update|reply|notify|summarize)\b/.test(normalized));
if (looksScheduledTask && !normalized.includes("when ")) return "task";
return looksWorkflow ? "workflow" : "task";
}
function titleFromAutomationPrompt(prompt: string): string {
const cleaned = prompt
.replace(/[^\p{L}\p{N}\s-]/gu, " ")
.replace(/\s+/g, " ")
.trim();
if (!cleaned) return "New task";
const title = cleaned.split(" ").slice(0, 7).join(" ");
return title.charAt(0).toUpperCase() + title.slice(1);
}
// Reads `#automations.trigger=<id>` from the URL hash. The LifeOps chat-sidebar
// Automations widget writes this when a row is clicked, so /automations can
// focus the matching trigger card on navigation. Duplicated here (instead of
// cross-importing from @elizaos/app-lifeops) to keep the package dep graph
// one-way (app-lifeops → app-core).
const AUTOMATIONS_TRIGGER_HASH_KEY = "automations.trigger";
function readAutomationsTriggerFromHash(): string | null {
if (typeof window === "undefined") return null;
const raw = window.location.hash.startsWith("#")
? window.location.hash.slice(1)
: window.location.hash;
if (!raw) return null;
for (const chunk of raw.split("&")) {
if (!chunk) continue;
const eq = chunk.indexOf("=");
if (eq < 0) continue;
try {
const key = decodeURIComponent(chunk.slice(0, eq));
if (key !== AUTOMATIONS_TRIGGER_HASH_KEY) continue;
const value = decodeURIComponent(chunk.slice(eq + 1));
return value || null;
} catch {
// Skip malformed encodings.
}
}
return null;
}
function getNavigationPathFromWindow(): string {
if (typeof window === "undefined") return "/";
return window.location.protocol === "file:"
? window.location.hash.replace(/^#/, "") || "/"
: window.location.pathname || "/";
}
function normalizeAutomationPath(pathname: string): string {
if (!pathname) return "/";
const normalized = pathname.startsWith("/") ? pathname : `/${pathname}`;
return normalized.length > 1 ? normalized.replace(/\/+$/, "") : normalized;
}
function getAutomationSubpageFromPath(pathname: string): AutomationSubpage {
const normalized = normalizeAutomationPath(pathname);
if (
normalized === "/node-catalog" ||
normalized === "/automations/node-catalog"
) {
return "node-catalog";
}
return "list";
}
function getPathForAutomationSubpage(subpage: AutomationSubpage): string {
return subpage === "node-catalog"
? "/automations/node-catalog"
: "/automations";
}
function syncAutomationSubpagePath(
subpage: AutomationSubpage,
mode: "push" | "replace" = "push",
): void {
if (typeof window === "undefined") return;
const nextPath = getPathForAutomationSubpage(subpage);
const currentPath = normalizeAutomationPath(getNavigationPathFromWindow());
if (currentPath === nextPath) return;
if (window.location.protocol === "file:") {
window.location.hash = nextPath;
return;
}
window.history[mode === "replace" ? "replaceState" : "pushState"](
null,
"",
nextPath,
);
}
function getSelectionKind(item: AutomationItem | null): SelectionKind {
if (!item) return null;
if (item.type === "n8n_workflow") return "workflow";
if (item.task) return "task";
if (item.trigger) return "trigger";
return null;
}
function getAutomationDisplayTitle(item: AutomationItem): string {
return item.isDraft ? "Draft" : item.title;
}
function getOverviewDisplayTitle(item: AutomationItem): string {
if (!item.isDraft) {
return getAutomationDisplayTitle(item);
}
if (item.type === "automation_draft") {
return "Draft automation";
}
return `Draft ${getAutomationGroupLabel(item).toLowerCase()}`;
}
function getAutomationGroupLabel(item: AutomationItem): string {
if (item.type === "n8n_workflow") {
return "Workflow";
}
if (item.system) {
return "Agent owned";
}
return "Task";
}
function collectScheduledAutomationEntries(
items: AutomationItem[],
): ScheduledAutomationEntry[] {
return items.flatMap((item) =>
item.schedules.map((schedule) => ({
item,
schedule,
key: `${item.id}:${schedule.id}`,
})),
);
}
function isTimeBasedTrigger(trigger: TriggerSummary): boolean {
return trigger.triggerType !== "event";
}
function formatScheduleCount(count: number): string {
return count === 1 ? "1 schedule" : `${count} schedules`;
}
function getAutomationBridgeIdForItem(
item: AutomationItem | null | undefined,
activeConversationId: string | null | undefined,
conversations: Conversation[],
): string | undefined {
return (
item?.room?.terminalBridgeConversationId ??
item?.room?.sourceConversationId ??
getAutomationBridgeConversationId(activeConversationId, conversations)
);
}
function getWorkflowNodeCount(item: AutomationItem): number {
return item.workflow?.nodeCount ?? item.workflow?.nodes?.length ?? 0;
}
function getAutomationUpdatedAtMs(item: AutomationItem): number {
if (!item.updatedAt) {
return 0;
}
const ts = Date.parse(item.updatedAt);
return Number.isFinite(ts) ? ts : 0;
}
function sortAutomationsByUpdatedAtDesc(
items: AutomationItem[],
): AutomationItem[] {
return [...items].sort(
(left, right) =>
getAutomationUpdatedAtMs(right) - getAutomationUpdatedAtMs(left),
);
}
function getAutomationIndicatorTone(
item: AutomationItem,
): "accent" | undefined {
if (item.type === "n8n_workflow") {
return item.enabled ? "accent" : undefined;
}
if (item.task) {
return item.task.isCompleted ? undefined : "accent";
}
if (item.trigger) {
return item.trigger.enabled ? "accent" : undefined;
}
return undefined;
}
function getAutomationStatusTone(
item: AutomationItem,
): "success" | "warning" | "muted" | "danger" {
if (item.isDraft) return "warning";
if (item.type === "n8n_workflow") {
return item.enabled ? "success" : "muted";
}
if (item.trigger) {
const lastTone = toneForLastStatus(item.trigger.lastStatus);
if (lastTone === "danger") return "danger";
return item.trigger.enabled ? "success" : "muted";
}
if (item.task) {
return item.task.isCompleted ? "muted" : "success";
}
return "muted";
}
function getTriggerWakeModeLabel(trigger: TriggerSummary): string {
return trigger.wakeMode === "inject_now"
? "Interrupt and run now"
: "Queue for next cycle";
}
function getTriggerStartModeLabel(trigger: TriggerSummary): string {
if (trigger.triggerType === "once") return "One time";
if (trigger.triggerType === "cron") return "Cron schedule";
if (trigger.triggerType === "event") return "Event";
return "Repeating";
}
function buildTriggerSchedulePrompt(trigger: TriggerSummary): string {
if (trigger.triggerType === "interval") {
return `Schedule: interval every ${trigger.intervalMs ?? 0}ms.`;
}
if (trigger.triggerType === "once") {
return `Schedule: run once at ${trigger.scheduledAtIso ?? "an unspecified time"}.`;
}
if (trigger.triggerType === "cron") {
return `Schedule: cron ${trigger.cronExpression ?? ""}.`;
}
if (trigger.triggerType === "event") {
return `Event: ${trigger.eventKind ?? "event"}.`;
}
return `Schedule type: ${trigger.triggerType}.`;
}
function buildWorkflowCompilationPrompt(item: AutomationItem): string {
const lines = [
"Compile this coordinator automation into an n8n workflow.",
`Automation title: ${item.title}`,
`Description: ${item.description || "No additional description provided."}`,
"Keep the workflow in this dedicated automation room.",
"Use runtime actions and providers as workflow nodes when they fit the job.",
"Use owner-scoped LifeOps nodes for Gmail, Calendar, Signal, Telegram, Discord, and GitHub when they are set up. If not, request the required setup or keys.",
];
if (item.task) {
lines.push(
`Task description: ${item.task.description || "No task description."}`,
);
}
if (item.trigger) {
lines.push(`Coordinator instructions: ${item.trigger.instructions}`);
lines.push(buildTriggerSchedulePrompt(item.trigger));
}
if (item.schedules.length > 0) {
lines.push("Existing schedules:");
for (const schedule of item.schedules) {
lines.push(`- ${buildTriggerSchedulePrompt(schedule)}`);
}
}
lines.push(
"Ask follow-up questions only when workflow intent is genuinely ambiguous.",
);
return lines.join("\n");
}
function getNodeClassLabel(
className: AutomationNodeDescriptor["class"],
): string {
switch (className) {
case "agent":
return "Agent";
case "action":
return "Actions";
case "context":
return "Context";
case "integration":
return "Integrations";
case "trigger":
return "Triggers";
case "flow-control":
return "Flow Control";
default:
return className;
}
}
function getNodeIcon(node: AutomationNodeDescriptor) {
if (node.source === "lifeops_event") {
return <Zap className="h-3.5 w-3.5" />;
}
if (node.source === "lifeops") {
if (node.id === "lifeops:gmail") return <Mail className="h-3.5 w-3.5" />;
if (node.id === "lifeops:signal") return <Signal className="h-3.5 w-3.5" />;
if (node.id === "lifeops:github") {
return <GitBranch className="h-3.5 w-3.5" />;
}
}
if (node.class === "agent") {
return <SquareTerminal className="h-3.5 w-3.5" />;
}
if (node.class === "integration") {
return <Workflow className="h-3.5 w-3.5" />;
}
if (node.class === "context") {
return <Settings className="h-3.5 w-3.5" />;
}
if (node.class === "trigger") {
return <Clock3 className="h-3.5 w-3.5" />;
}
return <Zap className="h-3.5 w-3.5" />;
}
function useAutomationsViewController() {
const {
triggers = [],
triggersLoaded = false,
triggersLoading = false,
triggersSaving = false,
triggerRunsById = {},
triggerError = null,
loadTriggers = async () => {},
createTrigger = async () => null,
updateTrigger = async () => null,
deleteTrigger = async () => true,
runTriggerNow = async () => true,
loadTriggerRuns = async () => {},
loadTriggerHealth = async () => {},
ensureTriggersLoaded = async () => {
await loadTriggers(triggersLoaded ? { silent: true } : undefined);
},
t,
uiLanguage,
} = useApp();
const [taskError, setTaskError] = useState<string | null>(null);
const [taskSaving, setTaskSaving] = useState(false);
const [form, setForm] = useState<TriggerFormState>(emptyForm);
const [editingId, setEditingId] = useState<string | null>(null);
const [selectedItemId, setSelectedItemId] = useState<string | null>(null);
const [selectedItemKind, setSelectedItemKind] = useState<SelectionKind>(null);
const [formError, setFormError] = useState<string | null>(null);
const [editorOpen, setEditorOpen] = useState(false);
const [editorMode, setEditorMode] = useState<"trigger" | "task">("trigger");
const [userTemplates, setUserTemplates] =
useState<HeartbeatTemplate[]>(loadUserTemplates);
const [templateNotice, setTemplateNotice] = useState<string | null>(null);
const [taskFormName, setTaskFormName] = useState("");
const [taskFormDescription, setTaskFormDescription] = useState("");
const [editingTaskId, setEditingTaskId] = useState<string | null>(null);
const [filter, setFilter] = useState<AutomationFilter>("all");
const [automationItems, setAutomationItems] = useState<AutomationItem[]>([]);
const [automationNodes, setAutomationNodes] = useState<
AutomationNodeDescriptor[]
>([]);
const [automationsLoading, setAutomationsLoading] = useState(false);
const [automationsLoaded, setAutomationsLoaded] = useState(false);
const [automationsError, setAutomationsError] = useState<string | null>(null);
const [n8nStatus, setN8nStatus] = useState<N8nStatusResponse | null>(null);
const [workflowFetchError, setWorkflowFetchError] = useState<string | null>(
null,
);
const didBootstrapDataRef = useRef(false);
const lastSelectedIdRef = useRef<string | null>(null);
const refreshAutomations =
useCallback(async (): Promise<AutomationListResponse | null> => {
setAutomationsLoading(true);
try {
const [automationData, nodeCatalog] = await Promise.all([
client.listAutomations(),
client.getAutomationNodeCatalog(),
]);
setAutomationItems(automationData.automations ?? []);
setAutomationNodes(nodeCatalog.nodes ?? []);
setN8nStatus(automationData.n8nStatus ?? null);
setWorkflowFetchError(automationData.workflowFetchError ?? null);
setAutomationsError(null);
return automationData;
} catch (error) {
setAutomationsError(
error instanceof Error
? error.message
: t("automations.loadFailed", {
defaultValue: "Failed to load automations.",
}),
);
return null;
} finally {
setAutomationsLoaded(true);
setAutomationsLoading(false);
}
}, [t]);
const createWorkbenchTask = useCallback(
async (data: {
name: string;
description: string;
tags?: string[];
}): Promise<WorkbenchTask | null> => {
setTaskSaving(true);
try {
const res = await client.createWorkbenchTask(data);
setTaskError(null);
await refreshAutomations();
return res.task;
} catch (error) {
setTaskError(
error instanceof Error
? error.message
: t("automations.taskCreateFailed", {
defaultValue: "Failed to create task.",
}),
);
return null;
} finally {
setTaskSaving(false);
}
},
[refreshAutomations, t],
);
const updateWorkbenchTask = useCallback(
async (
id: string,
data: Partial<{
name: string;
description: string;
isCompleted: boolean;
}>,
): Promise<WorkbenchTask | null> => {
setTaskSaving(true);
try {
const res = await client.updateWorkbenchTask(id, data);
setTaskError(null);
await refreshAutomations();
return res.task;
} catch (error) {
setTaskError(
error instanceof Error
? error.message
: t("automations.taskUpdateFailed", {
defaultValue: "Failed to update task.",
}),
);
return null;
} finally {
setTaskSaving(false);
}
},
[refreshAutomations, t],
);
const deleteWorkbenchTask = useCallback(
async (id: string): Promise<boolean> => {
setTaskSaving(true);
try {
await client.deleteWorkbenchTask(id);
setTaskError(null);
await refreshAutomations();
return true;
} catch (error) {
setTaskError(
error instanceof Error
? error.message
: t("automations.taskDeleteFailed", {
defaultValue: "Failed to delete task.",
}),
);
return false;
} finally {
setTaskSaving(false);
}
},
[refreshAutomations, t],
);
const saveFormAsTemplate = useCallback(() => {
const name = form.displayName.trim();
if (!name) return;
const template: HeartbeatTemplate = {
id: `user_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
name,
instructions: form.instructions.trim(),
interval: form.durationValue || "1",
unit: form.durationUnit,
};
setUserTemplates((previous) => {
const next = [...previous, template];
saveUserTemplates(next);
return next;
});
}, [form]);
const deleteUserTemplate = useCallback((id: string) => {
setUserTemplates((previous) => {
const next = previous.filter((template) => template.id !== id);
saveUserTemplates(next);
return next;
});
}, []);
useEffect(() => {
if (didBootstrapDataRef.current) return;
didBootstrapDataRef.current = true;
void loadTriggerHealth();
void ensureTriggersLoaded();
void refreshAutomations();
}, [ensureTriggersLoaded, loadTriggerHealth, refreshAutomations]);
useEffect(() => {
const handler = (event: Event) => {
const detail = (event as CustomEvent<{ filter: AutomationFilter }>)
.detail;
if (detail?.filter) {
setFilter(detail.filter);
}
};
window.addEventListener("milady:automations:setFilter", handler);
return () =>
window.removeEventListener("milady:automations:setFilter", handler);
}, []);
const allItems = automationItems;
const filteredItems = useMemo(() => {
switch (filter) {
case "coordinator":
return allItems.filter((item) => item.type === "coordinator_text");
case "workflows":
return allItems.filter((item) => item.type === "n8n_workflow");
case "scheduled":
return allItems.filter((item) => item.schedules.length > 0);
default:
return allItems;
}
}, [allItems, filter]);
useEffect(() => {
if (!selectedItemId) return;
// Exempt in-flight workflow drafts — they're not in allItems until
// generateWorkflowFromPrompt finishes and refreshAutomations
// surfaces the real workflow. Without this exemption the draft
// selection gets cleared mid-generation, the auto-select effect
// below picks lastSelectedIdRef (typically a task like Heartbeat),
// and the user lands somewhere unexpected — defeating the
// WorkflowGenerationProgress UI we just added on the draft pane.
if (selectedItemId.startsWith("workflow-draft:")) return;
if (!allItems.some((item) => item.id === selectedItemId)) {
setSelectedItemId(null);
setSelectedItemKind(null);
}
}, [allItems, selectedItemId]);
useEffect(() => {
if (selectedItemId) {
lastSelectedIdRef.current = selectedItemId;
}
}, [selectedItemId]);
useEffect(() => {
if (
editorOpen ||
editingId ||
editingTaskId ||
selectedItemId ||
allItems.length === 0
) {
return;
}
const preferred = lastSelectedIdRef.current;
if (!preferred) return;
const item = allItems.find((candidate) => candidate.id === preferred);
if (!item) return;
setSelectedItemId(preferred);
setSelectedItemKind(getSelectionKind(item));
}, [allItems, editingId, editingTaskId, editorOpen, selectedItemId]);
useEffect(() => {
if (!editorOpen) return undefined;
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
setEditorOpen(false);
setEditingId(null);
setEditingTaskId(null);
setForm(emptyForm);
setFormError(null);
setTaskFormName("");
setTaskFormDescription("");
}
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [editorOpen]);
// When the LifeOps chat-sidebar Automations widget row is clicked, it
// writes `#automations.trigger=<id>` and `setTab("automations")`s over.
// Read the hash on mount and on any hashchange to focus that trigger.
useEffect(() => {
function applyHash(): void {
const hashTriggerId = readAutomationsTriggerFromHash();
if (!hashTriggerId) return;
const nextId = `trigger:${hashTriggerId}`;
setSelectedItemId((prev) => (prev === nextId ? prev : nextId));
setSelectedItemKind("trigger");
}
applyHash();
window.addEventListener("hashchange", applyHash);
return () => window.removeEventListener("hashchange", applyHash);
}, []);
const resetEditor = () => {
setForm(emptyForm);
setEditingId(null);
setEditingTaskId(null);
setFormError(null);
setTaskFormName("");
setTaskFormDescription("");
};
const closeEditor = () => {
setEditorOpen(false);
resetEditor();
};
const openCreateTrigger = () => {
resetEditor();
setEditorMode("trigger");
setEditorOpen(true);
};
const openCreateTask = () => {
openCreateTrigger();
};
const openEditTrigger = (trigger: TriggerSummary) => {
setEditingId(trigger.id);
setForm(formFromTrigger(trigger));
setFormError(null);
setSelectedItemId(`trigger:${trigger.id}`);
setSelectedItemKind("trigger");
setEditorMode("trigger");
setEditorOpen(true);
};
const openEditTask = (task: WorkbenchTask) => {
setEditingTaskId(task.id);
setTaskFormName(task.name);
setTaskFormDescription(task.description);
setSelectedItemId(`task:${task.id}`);
setSelectedItemKind("task");
setEditorMode("task");
setEditorOpen(true);
};
const setField = <K extends keyof TriggerFormState>(
key: K,
value: TriggerFormState[K],
) => setForm((previous) => ({ ...previous, [key]: value }));
const onSubmitTrigger = async () => {
const error = validateForm(form, t);
if (error) {
setFormError(error);
return;
}
setFormError(null);
if (editingId) {
const updated = await updateTrigger(editingId, buildUpdateRequest(form));
if (updated) {
if (updated.kind === "workflow" && updated.workflowId) {
setSelectedItemId(`workflow:${updated.workflowId}`);
setSelectedItemKind("workflow");
} else {
setSelectedItemId(`trigger:${updated.id}`);
setSelectedItemKind("trigger");
}
await refreshAutomations();
closeEditor();
}
return;
}
const created = await createTrigger(buildCreateRequest(form));
if (created) {
if (created.kind === "workflow" && created.workflowId) {
setSelectedItemId(`workflow:${created.workflowId}`);
setSelectedItemKind("workflow");
} else {
setSelectedItemId(`trigger:${created.id}`);
setSelectedItemKind("trigger");
}
void loadTriggerRuns(created.id);
await refreshAutomations();
closeEditor();
}
};
const onSubmitTask = async () => {
const name = taskFormName.trim();
if (!name) {
setFormError(
t("automations.nameRequired", {
defaultValue: "Name is required.",
}),
);
return;
}
setFormError(null);
if (editingTaskId) {
const updated = await updateWorkbenchTask(editingTaskId, {
name,
description: taskFormDescription.trim(),
});
if (updated) {
setSelectedItemId(`task:${updated.id}`);
setSelectedItemKind("task");
closeEditor();
}
return;
}
const created = await createWorkbenchTask({
name,
description: taskFormDescription.trim(),
});
if (created) {
setSelectedItemId(`task:${created.id}`);
setSelectedItemKind("task");
closeEditor();
}
};
const onDeleteTrigger = async () => {
if (!editingId) return;
const confirmed = await confirmDesktopAction({
title: t("heartbeatsview.deleteTitle"),