-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathutils.ts
More file actions
452 lines (401 loc) · 13.1 KB
/
utils.ts
File metadata and controls
452 lines (401 loc) · 13.1 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
import React from 'react'
import { format } from 'date-fns'
import { Badge } from '@/components/emcn'
import { getIntegrationMetadata } from '@/lib/logs/get-trigger-options'
import { getBlock } from '@/blocks/registry'
import { CORE_TRIGGER_TYPES } from '@/stores/logs/filters/types'
/** Column configuration for logs table - shared between header and rows */
export const LOG_COLUMNS = {
date: { width: 'w-[8%]', minWidth: 'min-w-[70px]', label: 'Date' },
time: { width: 'w-[12%]', minWidth: 'min-w-[90px]', label: 'Time' },
status: { width: 'w-[12%]', minWidth: 'min-w-[100px]', label: 'Status' },
workflow: { width: 'w-[22%]', minWidth: 'min-w-[140px]', label: 'Workflow' },
cost: { width: 'w-[12%]', minWidth: 'min-w-[90px]', label: 'Cost' },
trigger: { width: 'w-[14%]', minWidth: 'min-w-[110px]', label: 'Trigger' },
duration: { width: 'w-[20%]', minWidth: 'min-w-[100px]', label: 'Duration' },
} as const
/** Type-safe column key derived from LOG_COLUMNS */
export type LogColumnKey = keyof typeof LOG_COLUMNS
/** Ordered list of column keys for rendering table headers */
export const LOG_COLUMN_ORDER: readonly LogColumnKey[] = [
'date',
'time',
'status',
'workflow',
'cost',
'trigger',
'duration',
] as const
/** Possible execution status values for workflow logs */
export type LogStatus = 'error' | 'pending' | 'running' | 'info' | 'cancelled'
/**
* Maps raw status string to LogStatus for display.
* @param status - Raw status from API
* @returns Normalized LogStatus value
*/
export function getDisplayStatus(status: string | null | undefined): LogStatus {
switch (status) {
case 'running':
return 'running'
case 'pending':
return 'pending'
case 'cancelled':
return 'cancelled'
case 'failed':
return 'error'
default:
return 'info'
}
}
/** Configuration mapping log status to Badge variant and display label */
const STATUS_VARIANT_MAP: Record<
LogStatus,
{ variant: React.ComponentProps<typeof Badge>['variant']; label: string }
> = {
error: { variant: 'red', label: 'Error' },
pending: { variant: 'amber', label: 'Pending' },
running: { variant: 'green', label: 'Running' },
cancelled: { variant: 'gray', label: 'Cancelled' },
info: { variant: 'gray', label: 'Info' },
}
/** Configuration mapping core trigger types to Badge color variants */
const TRIGGER_VARIANT_MAP: Record<string, React.ComponentProps<typeof Badge>['variant']> = {
manual: 'gray-secondary',
api: 'blue',
schedule: 'green',
chat: 'purple',
webhook: 'orange',
a2a: 'teal',
}
interface StatusBadgeProps {
/** The execution status to display */
status: LogStatus
}
/**
* Renders a colored badge indicating log execution status.
* @param props - Component props containing the status
* @returns A Badge with dot indicator and status label
*/
export const StatusBadge = React.memo(({ status }: StatusBadgeProps) => {
const config = STATUS_VARIANT_MAP[status]
return React.createElement(Badge, { variant: config.variant, dot: true }, config.label)
})
StatusBadge.displayName = 'StatusBadge'
interface TriggerBadgeProps {
/** The trigger type identifier (e.g., 'manual', 'api', or integration block type) */
trigger: string
}
/**
* Renders a colored badge indicating the workflow trigger type.
* Core triggers display with their designated colors; integrations show with icons.
* @param props - Component props containing the trigger type
* @returns A Badge with appropriate styling for the trigger type
*/
export const TriggerBadge = React.memo(({ trigger }: TriggerBadgeProps) => {
const metadata = getIntegrationMetadata(trigger)
const isIntegration = !(CORE_TRIGGER_TYPES as readonly string[]).includes(trigger)
const block = isIntegration ? getBlock(trigger) : null
const IconComponent = block?.icon
const coreVariant = TRIGGER_VARIANT_MAP[trigger]
if (coreVariant) {
return React.createElement(Badge, { variant: coreVariant }, metadata.label)
}
if (IconComponent) {
return React.createElement(
Badge,
{ variant: 'gray-secondary', icon: IconComponent },
metadata.label
)
}
return React.createElement(Badge, { variant: 'gray-secondary' }, metadata.label)
})
TriggerBadge.displayName = 'TriggerBadge'
interface LogWithDuration {
totalDurationMs?: number | string
duration?: number | string
}
/**
* Parse duration from various log data formats.
* Handles both numeric and string duration values.
* @param log - Log object containing duration information
* @returns Duration in milliseconds or null if not available
*/
export function parseDuration(log: LogWithDuration): number | null {
let durationCandidate: number | null = null
if (typeof log.totalDurationMs === 'number') {
durationCandidate = log.totalDurationMs
} else if (typeof log.duration === 'number') {
durationCandidate = log.duration
} else if (typeof log.totalDurationMs === 'string') {
durationCandidate = Number.parseInt(String(log.totalDurationMs).replace(/[^0-9]/g, ''), 10)
} else if (typeof log.duration === 'string') {
durationCandidate = Number.parseInt(String(log.duration).replace(/[^0-9]/g, ''), 10)
}
return Number.isFinite(durationCandidate) ? durationCandidate : null
}
interface TraceSpan {
output?: Record<string, unknown>
status?: string
error?: unknown
}
interface BlockExecution {
outputData?: unknown
errorMessage?: string
}
interface LogWithExecutionData {
executionData?: {
finalOutput?: unknown
traceSpans?: TraceSpan[]
blockExecutions?: BlockExecution[]
output?: unknown
}
output?: string
message?: string
}
/**
* Extract output from various sources in execution data.
* Checks multiple locations in priority order:
* 1. executionData.finalOutput
* 2. output (as string)
* 3. executionData.traceSpans (iterates through spans)
* 4. executionData.blockExecutions (last block)
* 5. message (fallback)
* @param log - Log object containing execution data
* @returns Extracted output value or null
*/
export function extractOutput(log: LogWithExecutionData): unknown {
let output: unknown = null
// Check finalOutput first
if (log.executionData?.finalOutput !== undefined) {
output = log.executionData.finalOutput
}
// Check direct output field
if (typeof log.output === 'string') {
output = log.output
} else if (log.executionData?.traceSpans && Array.isArray(log.executionData.traceSpans)) {
// Search through trace spans
const spans = log.executionData.traceSpans
for (let i = spans.length - 1; i >= 0; i--) {
const s = spans[i]
if (s?.output && Object.keys(s.output).length > 0) {
output = s.output
break
}
const outputWithError = s?.output as Record<string, unknown> | undefined
if (s?.status === 'error' && (outputWithError?.error || s?.error)) {
output = outputWithError?.error || s.error
break
}
}
// Fallback to executionData.output
if (!output && log.executionData?.output) {
output = log.executionData.output
}
}
// Check block executions
if (!output) {
const blockExecutions = log.executionData?.blockExecutions
if (Array.isArray(blockExecutions) && blockExecutions.length > 0) {
const lastBlock = blockExecutions[blockExecutions.length - 1]
output = lastBlock?.outputData || lastBlock?.errorMessage || null
}
}
// Final fallback to message
if (!output) {
output = log.message || null
}
return output
}
/** Execution log cost breakdown */
interface ExecutionCost {
input: number
output: number
total: number
}
/** Mapped execution log format for UI consumption */
export interface ExecutionLog {
id: string
executionId: string
startedAt: string
level: string
status: string
trigger: string
triggerUserId: string | null
triggerInputs?: unknown
outputs?: unknown
errorMessage: string | null
duration: number | null
cost: ExecutionCost | null
workflowName?: string
workflowColor?: string
hasPendingPause?: boolean
}
/** Raw API log response structure */
interface RawLogResponse extends LogWithDuration, LogWithExecutionData {
id: string
executionId: string
startedAt?: string
endedAt?: string
createdAt?: string
level?: string
status?: string
trigger?: string
triggerUserId?: string | null
error?: string
cost?: {
input?: number
output?: number
total?: number
}
workflowName?: string
workflowColor?: string
workflow?: {
name?: string
color?: string
}
hasPendingPause?: boolean
}
/**
* Convert raw API log response to ExecutionLog format.
* @param log - Raw log response from API
* @returns Formatted execution log
*/
export function mapToExecutionLog(log: RawLogResponse): ExecutionLog {
const started = log.startedAt
? new Date(log.startedAt)
: log.endedAt
? new Date(log.endedAt)
: null
const startedAt =
started && !Number.isNaN(started.getTime()) ? started.toISOString() : new Date().toISOString()
const duration = parseDuration(log)
const output = extractOutput(log)
return {
id: log.id,
executionId: log.executionId,
startedAt,
level: log.level || 'info',
status: log.status || 'completed',
trigger: log.trigger || 'manual',
triggerUserId: log.triggerUserId || null,
triggerInputs: undefined,
outputs: output || undefined,
errorMessage: log.error || null,
duration,
cost: log.cost
? {
input: log.cost.input || 0,
output: log.cost.output || 0,
total: log.cost.total || 0,
}
: null,
workflowName: log.workflowName || log.workflow?.name,
workflowColor: log.workflowColor || log.workflow?.color,
hasPendingPause: log.hasPendingPause === true,
}
}
/**
* Alternative version that uses createdAt as fallback for startedAt.
* Used in some API responses.
* @param log - Raw log response from API
* @returns Formatted execution log
*/
export function mapToExecutionLogAlt(log: RawLogResponse): ExecutionLog {
const duration = parseDuration(log)
const output = extractOutput(log)
return {
id: log.id,
executionId: log.executionId,
startedAt: log.createdAt || log.startedAt || new Date().toISOString(),
level: log.level || 'info',
status: log.status || 'completed',
trigger: log.trigger || 'manual',
triggerUserId: log.triggerUserId || null,
triggerInputs: undefined,
outputs: output || undefined,
errorMessage: log.error || null,
duration,
cost: log.cost
? {
input: log.cost.input || 0,
output: log.cost.output || 0,
total: log.cost.total || 0,
}
: null,
workflowName: log.workflow?.name,
workflowColor: log.workflow?.color,
hasPendingPause: log.hasPendingPause === true,
}
}
/**
* Format duration for display in logs UI
* If duration is under 1 second, displays as milliseconds (e.g., "500ms")
* If duration is 1 second or more, displays as seconds (e.g., "1.23s")
* @param duration - Duration string (e.g., "500ms") or null
* @returns Formatted duration string or null
*/
export function formatDuration(duration: string | null): string | null {
if (!duration) return null
// Extract numeric value from duration string (e.g., "500ms" -> 500)
const ms = Number.parseInt(duration.replace(/[^0-9]/g, ''), 10)
if (!Number.isFinite(ms)) return duration
if (ms < 1000) {
return `${ms}ms`
}
// Convert to seconds with up to 2 decimal places
const seconds = ms / 1000
return `${seconds.toFixed(2).replace(/\.?0+$/, '')}s`
}
/**
* Format latency value for display in dashboard UI
* If latency is under 1 second, displays as milliseconds (e.g., "500ms")
* If latency is 1 second or more, displays as seconds (e.g., "1.23s")
* @param ms - Latency in milliseconds (number)
* @returns Formatted latency string
*/
export function formatLatency(ms: number): string {
if (!Number.isFinite(ms) || ms <= 0) return '—'
if (ms < 1000) {
return `${Math.round(ms)}ms`
}
// Convert to seconds with up to 2 decimal places
const seconds = ms / 1000
return `${seconds.toFixed(2).replace(/\.?0+$/, '')}s`
}
export const formatDate = (dateString: string) => {
const date = new Date(dateString)
return {
full: date.toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
}),
time: date.toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
}),
formatted: format(date, 'HH:mm:ss'),
compact: format(date, 'MMM d HH:mm:ss'),
compactDate: format(date, 'MMM d').toUpperCase(),
compactTime: format(date, 'h:mm a'),
relative: (() => {
const now = new Date()
const diffMs = now.getTime() - date.getTime()
const diffMins = Math.floor(diffMs / 60000)
if (diffMins < 1) return 'just now'
if (diffMins < 60) return `${diffMins}m ago`
const diffHours = Math.floor(diffMins / 60)
if (diffHours < 24) return `${diffHours}h ago`
const diffDays = Math.floor(diffHours / 24)
if (diffDays === 1) return 'yesterday'
if (diffDays < 7) return `${diffDays}d ago`
return format(date, 'MMM d')
})(),
}
}