-
Notifications
You must be signed in to change notification settings - Fork 517
Expand file tree
/
Copy pathAutomationDrawer.tsx
More file actions
453 lines (411 loc) · 17.3 KB
/
AutomationDrawer.tsx
File metadata and controls
453 lines (411 loc) · 17.3 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
import {createElement, useCallback, useEffect, useMemo, useState} from "react"
import {BookOpen} from "@phosphor-icons/react"
import {Button, Collapse, Form, Input, message, Select, Tabs, Tooltip, Typography} from "antd"
import {useAtom, useSetAtom} from "jotai"
import EnhancedDrawer from "@/oss/components/EnhancedUIs/Drawer"
import {
AutomationProvider,
WebhookSubscriptionCreateRequest,
WebhookSubscriptionEditRequest,
} from "@/oss/services/automations/types"
import {
createAutomationAtom,
testDraftAutomationAtom,
testAutomationAtom,
updateAutomationAtom,
} from "@/oss/state/automations/atoms"
import {
createdWebhookSecretAtom,
editingAutomationAtom,
isAutomationDrawerOpenAtom,
selectedProviderAtom,
} from "@/oss/state/automations/state"
import {AUTOMATION_SCHEMA, EVENT_OPTIONS} from "./assets/constants"
import {AutomationFieldRenderer} from "./AutomationFieldRenderer"
import AutomationLogsTab from "./AutomationLogsTab"
import {RequestPreview} from "./RequestPreview"
import {buildSubscription} from "./utils/buildSubscription"
import {AUTOMATION_TEST_FAILURE_MESSAGE, handleTestResult} from "./utils/handleTestResult"
const AutomationDrawer = ({onSuccess}: {onSuccess: () => void}) => {
const [form] = Form.useForm()
const [open, setOpen] = useAtom(isAutomationDrawerOpenAtom)
const [initialValues, setEditingWebhook] = useAtom(editingAutomationAtom)
const [activeTab, setActiveTab] = useState("configuration")
const [isTesting, setIsTesting] = useState(false)
const [isSubmitting, setIsSubmitting] = useState(false)
const setCreatedWebhookSecret = useSetAtom(createdWebhookSecretAtom)
const [selectedProvider, setSelectedProvider] = useAtom(selectedProviderAtom)
const createAutomation = useSetAtom(createAutomationAtom)
const testDraftAutomation = useSetAtom(testDraftAutomationAtom)
const testAutomation = useSetAtom(testAutomationAtom)
const updateAutomation = useSetAtom(updateAutomationAtom)
const isEdit = !!initialValues
const onCancel = useCallback(() => {
setOpen(false)
setEditingWebhook(undefined)
}, [setOpen, setEditingWebhook])
useEffect(() => {
if (!open) {
setActiveTab("configuration")
form.resetFields()
return
}
setActiveTab("configuration")
if (initialValues) {
// Determine provider via heuristic since no meta field is stored.
let isGitHub = false
try {
const parsedUrl = new URL(initialValues.data.url)
isGitHub = parsedUrl.hostname === "api.github.com"
} catch {
isGitHub = false
}
const provider: AutomationProvider = isGitHub ? "github" : "webhook"
setSelectedProvider(provider)
// Map the headers from Record<string, string> back to Antd Form.List [{key, value}]
let header_list: {key: string; value: string}[] = []
if (initialValues.data.headers && Object.keys(initialValues.data.headers).length > 0) {
const isSystemHeader = (k: string) =>
isGitHub &&
(k === "Accept" || k === "X-GitHub-Api-Version" || k === "Authorization")
header_list = Object.entries(initialValues.data.headers)
.filter(([k, _v]) => !isSystemHeader(k))
.map(([k, v]) => ({key: k, value: String(v)}))
}
// Derive GitHub properties if needed
let github_sub_type = "repository_dispatch"
let github_repo = ""
let github_workflow = ""
let github_branch = "main"
if (isGitHub) {
const repoMatch = initialValues.data.url.match(/repos\/([^\/]+\/[^\/]+)\//)
if (repoMatch) github_repo = repoMatch[1]
if (initialValues.data.url.includes("/actions/workflows/")) {
github_sub_type = "workflow_dispatch"
const workflowMatch = initialValues.data.url.match(
/workflows\/([^\/]+)\/dispatches/,
)
if (workflowMatch) github_workflow = workflowMatch[1]
if (initialValues.data.payload_fields?.ref) {
github_branch = initialValues.data.payload_fields.ref as string
}
}
}
form.setFieldsValue({
provider,
name: initialValues.name,
events: initialValues.data.event_types || [],
url: isGitHub ? undefined : initialValues.data.url,
header_list,
auth_mode: initialValues.data.auth_mode || "signature",
github_sub_type,
github_repo,
github_workflow,
github_branch,
})
} else {
form.resetFields()
setSelectedProvider("webhook")
form.setFieldsValue({
provider: "webhook",
events: ["environments.revisions.committed"],
auth_mode: "signature",
github_sub_type: "repository_dispatch",
})
}
}, [open, initialValues, form])
const buildPayloadFromForm = useCallback(async () => {
const rawValues = await form.validateFields()
let headersRecord: Record<string, string> | undefined = undefined
if (rawValues.header_list && rawValues.header_list.length > 0) {
headersRecord = {}
rawValues.header_list.forEach((h: {key: string; value: string}) => {
if (h.key && h.value && headersRecord) {
headersRecord[h.key] = h.value
}
})
}
const processedValues = {
...rawValues,
headers: headersRecord,
event_types: rawValues.events,
}
return {
rawValues,
payload: buildSubscription(processedValues, isEdit, initialValues?.id),
}
}, [form, initialValues?.id, isEdit])
const handleTestConnection = useCallback(async () => {
if (!open) return
try {
setIsTesting(true)
if (activeTab === "logs" && initialValues?.id) {
const response = await testAutomation(initialValues.id)
handleTestResult(response)
return
}
const {payload} = await buildPayloadFromForm()
const response = await testDraftAutomation(payload)
handleTestResult(response)
} catch (error) {
if ((error as {errorFields?: unknown}).errorFields) return
console.error(error)
message.error(AUTOMATION_TEST_FAILURE_MESSAGE, 10)
} finally {
setIsTesting(false)
}
}, [
activeTab,
buildPayloadFromForm,
initialValues?.id,
open,
testAutomation,
testDraftAutomation,
])
const handleOk = useCallback(async () => {
try {
setIsSubmitting(true)
const {rawValues, payload} = await buildPayloadFromForm()
let subscriptionId: string | undefined
if (isEdit && initialValues?.id) {
await updateAutomation({
webhookSubscriptionId: initialValues.id,
payload: payload as WebhookSubscriptionEditRequest,
})
subscriptionId = initialValues.id
message.success("Automation updated successfully")
} else {
const response = await createAutomation(payload as WebhookSubscriptionCreateRequest)
subscriptionId = response.subscription?.id
const webhookSecret =
response.subscription?.secret || response.subscription?.secret_id
const isSignatureWebhook =
selectedProvider === "webhook" && rawValues.auth_mode === "signature"
if (isSignatureWebhook && webhookSecret) {
setCreatedWebhookSecret(webhookSecret)
}
message.success("Automation created successfully")
}
onSuccess()
onCancel()
if (subscriptionId) {
try {
const response = await testAutomation(subscriptionId)
handleTestResult(response)
} catch (error) {
console.error(error)
message.warning(
"Automation saved, but the connection test could not complete. You can retry it from the drawer or table.",
10,
)
}
}
} catch (error) {
if ((error as {errorFields?: unknown}).errorFields) return
console.error(error)
message.error(isEdit ? "Failed to update automation" : "Failed to create automation")
} finally {
setIsSubmitting(false)
}
}, [
form,
isEdit,
initialValues,
onSuccess,
onCancel,
setCreatedWebhookSecret,
buildPayloadFromForm,
createAutomation,
testDraftAutomation,
testAutomation,
updateAutomation,
selectedProvider,
])
const providerOptions = useMemo(
() =>
AUTOMATION_SCHEMA.map((provider) => ({
label: (
<div className="flex items-center gap-2">
{createElement(provider.icon)}
<span>{provider.label}</span>
</div>
),
value: provider.provider,
})),
[],
)
const selectedProviderConfig = useMemo(
() => AUTOMATION_SCHEMA.find((s) => s.provider === selectedProvider),
[selectedProvider],
)
const docsUrl =
selectedProvider === "github"
? "https://agenta.ai/docs/prompt-engineering/integrating-prompts/github"
: "https://agenta.ai/docs/prompt-engineering/integrating-prompts/webhooks"
const drawerTabs = useMemo(
() => [
{
key: "configuration",
label: "Configuration",
children: (
<div className="flex flex-col gap-3">
<div className="mb-4 text-gray-500">
Set up an automation to trigger external services when specific events
occur within Agenta.
</div>
<Form
form={form}
layout="vertical"
requiredMark={false}
onValuesChange={(changedValues) => {
if (changedValues.provider) {
setSelectedProvider(changedValues.provider)
}
}}
>
<div className="flex flex-col gap-3">
<Form.Item
name="provider"
label="Webhook Type"
initialValue="webhook"
className="!mb-0"
>
<Select
disabled={isEdit}
options={providerOptions}
placeholder="Select webhook/github"
/>
</Form.Item>
<Form.Item
name="name"
label="Webhook Name"
className="!mb-0"
rules={[{required: true, message: "Please enter a name"}]}
>
<Input placeholder="Production deploy hook" />
</Form.Item>
<Form.Item
name="events"
label="Event Types"
className="!mb-0"
rules={[
{
required: true,
message: "Please select at least one event",
},
]}
>
<Select
mode="multiple"
placeholder="Select events"
options={EVENT_OPTIONS}
/>
</Form.Item>
{selectedProviderConfig && (
<>
<div className="mt-4 mb-2">
<Typography.Text
type="secondary"
className="font-medium"
>
{selectedProviderConfig.subtitle}
</Typography.Text>
</div>
<AutomationFieldRenderer
fields={selectedProviderConfig.fields}
isEditMode={isEdit}
/>
</>
)}
<Collapse
className="[&_.ant-collapse-content]:bg-transparent"
size="small"
>
<Collapse.Panel
header="Example Request"
key="preview"
forceRender
>
<RequestPreview form={form} />
</Collapse.Panel>
</Collapse>
</div>
</Form>
</div>
),
},
...(initialValues?.id
? [
{
key: "logs",
label: "Logs",
children:
activeTab === "logs" ? (
<AutomationLogsTab subscriptionId={initialValues.id} />
) : null,
},
]
: []),
],
[
activeTab,
form,
initialValues?.id,
isEdit,
providerOptions,
selectedProviderConfig,
setSelectedProvider,
],
)
return (
<>
<EnhancedDrawer
title={isEdit ? "Edit Automation" : "Add Automation"}
extra={
<Tooltip title="Documentation">
<Button
type="text"
size="small"
icon={<BookOpen size={16} />}
href={docsUrl}
target="_blank"
rel="noopener noreferrer"
aria-label="Open automation documentation"
/>
</Tooltip>
}
open={open}
onClose={onCancel}
width={840}
destroyOnHidden
footer={
<div className="flex items-center justify-between gap-2">
<Button onClick={onCancel}>Cancel</Button>
<div className="flex items-center gap-2">
<Button
onClick={handleTestConnection}
loading={isTesting}
disabled={isSubmitting}
>
Test Connection
</Button>
<Button type="primary" onClick={handleOk} loading={isSubmitting}>
{isEdit ? "Update Automation" : "Create Automation"}
</Button>
</div>
</div>
}
>
<div className="h-full min-h-0 [&_.ant-tabs-content]:h-full [&_.ant-tabs-content-holder]:h-full [&_.ant-tabs-tabpane]:h-full">
<Tabs
activeKey={activeTab}
onChange={setActiveTab}
items={drawerTabs}
className="h-full"
/>
</div>
</EnhancedDrawer>
</>
)
}
export default AutomationDrawer