@workflow/web-shared 5.1.0 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/README.md +8 -0
  2. package/dist/components/error-boundary.js +1 -1
  3. package/dist/components/event-list/event-details-panel.d.ts +25 -0
  4. package/dist/components/event-list/event-details-panel.d.ts.map +1 -0
  5. package/dist/components/event-list/event-details-panel.js +157 -0
  6. package/dist/components/event-list/event-list-toolbar.d.ts +6 -0
  7. package/dist/components/event-list/event-list-toolbar.d.ts.map +1 -0
  8. package/dist/components/event-list/event-list-toolbar.js +15 -0
  9. package/dist/components/event-list/event-row.d.ts +29 -0
  10. package/dist/components/event-list/event-row.d.ts.map +1 -0
  11. package/dist/components/event-list/event-row.js +102 -0
  12. package/dist/components/event-list/use-event-search.d.ts +14 -0
  13. package/dist/components/event-list/use-event-search.d.ts.map +1 -0
  14. package/dist/components/event-list/use-event-search.js +74 -0
  15. package/dist/components/event-list-view.d.ts +9 -66
  16. package/dist/components/event-list-view.d.ts.map +1 -1
  17. package/dist/components/event-list-view.js +112 -984
  18. package/dist/components/hook-actions.js +1 -1
  19. package/dist/components/index.js +1 -1
  20. package/dist/components/sidebar/attribute-panel.js +1 -1
  21. package/dist/components/sidebar/attributes-block.js +1 -1
  22. package/dist/components/sidebar/conversation-view.js +1 -1
  23. package/dist/components/sidebar/copyable-data-block.js +1 -1
  24. package/dist/components/sidebar/entity-detail-panel.js +1 -1
  25. package/dist/components/sidebar/events-list.js +1 -1
  26. package/dist/components/sidebar/resolve-hook-modal.js +1 -1
  27. package/dist/components/sidebar/sidebar-data-context.js +1 -1
  28. package/dist/components/sidebar/span-detail-merge.js +1 -1
  29. package/dist/components/sidebar/use-selected-span-detail.js +1 -1
  30. package/dist/components/stream-image-preview.d.ts +4 -0
  31. package/dist/components/stream-image-preview.d.ts.map +1 -0
  32. package/dist/components/stream-image-preview.js +21 -0
  33. package/dist/components/stream-viewer-skeleton.js +1 -1
  34. package/dist/components/stream-viewer.d.ts.map +1 -1
  35. package/dist/components/stream-viewer.js +7 -2
  36. package/dist/components/trace-viewer/components/copy-button.js +1 -1
  37. package/dist/components/trace-viewer/components/detail-panel-shell.d.ts +23 -0
  38. package/dist/components/trace-viewer/components/detail-panel-shell.d.ts.map +1 -0
  39. package/dist/components/trace-viewer/components/detail-panel-shell.js +49 -0
  40. package/dist/components/trace-viewer/components/detail-panel-width.js +1 -1
  41. package/dist/components/trace-viewer/components/detail-panel.d.ts +4 -4
  42. package/dist/components/trace-viewer/components/detail-panel.d.ts.map +1 -1
  43. package/dist/components/trace-viewer/components/detail-panel.js +11 -51
  44. package/dist/components/trace-viewer/components/draggable-border.js +1 -1
  45. package/dist/components/trace-viewer/components/event-list.d.ts +9 -0
  46. package/dist/components/trace-viewer/components/event-list.d.ts.map +1 -1
  47. package/dist/components/trace-viewer/components/event-list.js +10 -3
  48. package/dist/components/trace-viewer/components/middle-truncate/copy-selection.js +1 -1
  49. package/dist/components/trace-viewer/components/middle-truncate/measurement-batch.js +1 -1
  50. package/dist/components/trace-viewer/components/middle-truncate/middle-truncate.js +1 -1
  51. package/dist/components/trace-viewer/components/middle-truncate/truncate.js +1 -1
  52. package/dist/components/trace-viewer/components/middle-truncate/use-middle-truncate.js +1 -1
  53. package/dist/components/trace-viewer/components/minimap.js +1 -1
  54. package/dist/components/trace-viewer/components/pane-constants.js +1 -1
  55. package/dist/components/trace-viewer/components/span-markers.js +1 -1
  56. package/dist/components/trace-viewer/components/split-pane.js +1 -1
  57. package/dist/components/trace-viewer/components/timeline.js +1 -1
  58. package/dist/components/trace-viewer/components/trace-shortcut-helper.js +1 -1
  59. package/dist/components/trace-viewer/components/trace-viewer-skeleton.js +1 -1
  60. package/dist/components/trace-viewer/components/use-alt-held.d.ts +1 -0
  61. package/dist/components/trace-viewer/components/use-alt-held.d.ts.map +1 -1
  62. package/dist/components/trace-viewer/components/use-alt-held.js +2 -2
  63. package/dist/components/trace-viewer/components/use-detail-panel-width.d.ts +19 -0
  64. package/dist/components/trace-viewer/components/use-detail-panel-width.d.ts.map +1 -0
  65. package/dist/components/trace-viewer/components/use-detail-panel-width.js +26 -0
  66. package/dist/components/trace-viewer/components/use-element-width.js +1 -1
  67. package/dist/components/trace-viewer/components/use-row-window.js +1 -1
  68. package/dist/components/trace-viewer/context.d.ts +2 -1
  69. package/dist/components/trace-viewer/context.d.ts.map +1 -1
  70. package/dist/components/trace-viewer/context.js +3 -3
  71. package/dist/components/trace-viewer/icons.js +1 -1
  72. package/dist/components/trace-viewer/search.js +1 -1
  73. package/dist/components/trace-viewer/trace-viewer.d.ts +2 -1
  74. package/dist/components/trace-viewer/trace-viewer.d.ts.map +1 -1
  75. package/dist/components/trace-viewer/trace-viewer.js +9 -13
  76. package/dist/components/trace-viewer/types.js +1 -1
  77. package/dist/components/trace-viewer/util/timing.js +1 -1
  78. package/dist/components/trace-viewer/utils.js +1 -1
  79. package/dist/components/trace-viewer.d.ts +2 -1
  80. package/dist/components/trace-viewer.d.ts.map +1 -1
  81. package/dist/components/trace-viewer.js +3 -3
  82. package/dist/components/ui/alert.js +1 -1
  83. package/dist/components/ui/button.js +1 -1
  84. package/dist/components/ui/card.js +1 -1
  85. package/dist/components/ui/collapsible.d.ts +3 -1
  86. package/dist/components/ui/collapsible.d.ts.map +1 -1
  87. package/dist/components/ui/collapsible.js +3 -3
  88. package/dist/components/ui/context-card.js +1 -1
  89. package/dist/components/ui/data-inspector.js +1 -1
  90. package/dist/components/ui/data-inspector.styles.js +1 -1
  91. package/dist/components/ui/decrypt-button.js +2 -2
  92. package/dist/components/ui/duplicate-event-tooltip.js +1 -1
  93. package/dist/components/ui/error-card.js +2 -2
  94. package/dist/components/ui/error-stack-block.js +1 -1
  95. package/dist/components/ui/icon-button.d.ts +2 -2
  96. package/dist/components/ui/icon-button.js +1 -1
  97. package/dist/components/ui/kbd.d.ts +1 -1
  98. package/dist/components/ui/kbd.js +1 -1
  99. package/dist/components/ui/load-more-button.js +1 -1
  100. package/dist/components/ui/menu-dropdown.js +1 -1
  101. package/dist/components/ui/skeleton.js +1 -1
  102. package/dist/components/ui/spinner.js +1 -1
  103. package/dist/components/ui/timestamp-tooltip.js +1 -1
  104. package/dist/components/ui/tooltip.js +1 -1
  105. package/dist/components/workflow-traces/event-colors.js +1 -1
  106. package/dist/components/workflow-traces/trace-span-construction.js +1 -1
  107. package/dist/components/workflow-traces/trace-time-utils.js +1 -1
  108. package/dist/hooks/use-dark-mode.js +1 -1
  109. package/dist/hooks/use-intersection-observer.js +1 -1
  110. package/dist/hooks/use-load-more-on-scroll.js +1 -1
  111. package/dist/hooks/use-reduced-motion.js +1 -1
  112. package/dist/index.d.ts +1 -0
  113. package/dist/index.d.ts.map +1 -1
  114. package/dist/index.js +2 -1
  115. package/dist/lib/cn.js +1 -1
  116. package/dist/lib/duplicate-events.js +1 -1
  117. package/dist/lib/event-analysis.js +1 -1
  118. package/dist/lib/event-list-model.d.ts +179 -0
  119. package/dist/lib/event-list-model.d.ts.map +1 -0
  120. package/dist/lib/event-list-model.js +459 -0
  121. package/dist/lib/event-materialization.js +1 -1
  122. package/dist/lib/exact-event-search-id.js +1 -1
  123. package/dist/lib/hydration.js +1 -1
  124. package/dist/lib/run-limit-guidance.js +1 -1
  125. package/dist/lib/sealed-events.js +1 -1
  126. package/dist/lib/start-hook.js +1 -1
  127. package/dist/lib/state-hydration.js +1 -1
  128. package/dist/lib/stream-display.js +1 -1
  129. package/dist/lib/stream-image.d.ts +3 -0
  130. package/dist/lib/stream-image.d.ts.map +1 -0
  131. package/dist/lib/stream-image.js +23 -0
  132. package/dist/lib/toast.js +1 -1
  133. package/dist/lib/trace-builder.d.ts +1 -0
  134. package/dist/lib/trace-builder.d.ts.map +1 -1
  135. package/dist/lib/trace-builder.js +5 -1
  136. package/dist/lib/trace-types.js +1 -1
  137. package/dist/lib/utils.js +1 -1
  138. package/dist/lib/zstd-browser-decoder.js +1 -1
  139. package/dist/styles.css +19 -0
  140. package/package.json +8 -6
  141. package/src/components/event-list/event-details-panel.tsx +404 -0
  142. package/src/components/event-list/event-list-toolbar.tsx +47 -0
  143. package/src/components/event-list/event-row.tsx +348 -0
  144. package/src/components/event-list/use-event-search.ts +104 -0
  145. package/src/components/event-list-view.tsx +258 -1848
  146. package/src/components/stream-image-preview.tsx +54 -0
  147. package/src/components/stream-viewer.tsx +16 -6
  148. package/src/components/trace-viewer/components/detail-panel-shell.tsx +146 -0
  149. package/src/components/trace-viewer/components/detail-panel.tsx +37 -176
  150. package/src/components/trace-viewer/components/event-list.tsx +46 -27
  151. package/src/components/trace-viewer/components/use-alt-held.ts +1 -1
  152. package/src/components/trace-viewer/components/use-detail-panel-width.ts +53 -0
  153. package/src/components/trace-viewer/context.tsx +5 -1
  154. package/src/components/trace-viewer/trace-viewer.tsx +13 -11
  155. package/src/components/trace-viewer.tsx +3 -0
  156. package/src/components/ui/collapsible.tsx +11 -0
  157. package/src/components/ui/decrypt-button.tsx +1 -1
  158. package/src/components/ui/error-card.tsx +1 -1
  159. package/src/index.ts +1 -0
  160. package/src/lib/event-list-model.ts +684 -0
  161. package/src/lib/stream-image.ts +21 -0
  162. package/src/lib/trace-builder.ts +5 -0
  163. package/src/styles.css +19 -0
  164. package/src/components/event-list-view.test.ts +0 -51
  165. package/src/components/trace-viewer/components/detail-panel-width.test.ts +0 -123
  166. package/src/components/trace-viewer/utils.test.ts +0 -492
  167. package/src/components/workflow-traces/event-colors.test.ts +0 -14
  168. package/src/components/workflow-traces/trace-span-construction.test.ts +0 -202
  169. package/src/lib/duplicate-events.test.ts +0 -336
  170. package/src/lib/event-materialization.test.ts +0 -136
  171. package/src/lib/hydration.test.ts +0 -63
  172. package/src/lib/run-limit-guidance.test.ts +0 -90
  173. package/src/lib/start-hook.test.ts +0 -174
  174. package/src/lib/state-hydration.test.ts +0 -332
  175. package/src/lib/trace-builder.test.ts +0 -143
  176. package/src/lib/utils.test.ts +0 -33
@@ -0,0 +1,684 @@
1
+ /**
2
+ * Row model for the Events tab: which entity each event belongs to, what its
3
+ * row shows, how long it took, and how the list, its empty state and its
4
+ * footer read for a given search. Pure data in, data out.
5
+ */
6
+
7
+ import { parseStepName, parseWorkflowName } from '@workflow/utils/parse-name';
8
+ import {
9
+ type Event,
10
+ isHookLifecycleEventType,
11
+ isStepEventType,
12
+ isWaitEventType,
13
+ type WorkflowRun,
14
+ } from '@workflow/world';
15
+ import { DUPLICATE_EVENT_MESSAGE } from './duplicate-events';
16
+ import type { ExactWorkflowSearchId } from './exact-event-search-id';
17
+ import { isEncryptedMarker } from './hydration';
18
+ import { isSealedNoopEvent, SEALED_EVENT_MESSAGE } from './sealed-events';
19
+ import { formatDurationPrecise } from './utils';
20
+
21
+ // ──────────────────────────────────────────────────────────────────────────
22
+ // Time
23
+ // ──────────────────────────────────────────────────────────────────────────
24
+
25
+ export function parseEventDate(value: unknown): Date | null {
26
+ if (value == null) return null;
27
+
28
+ const date = value instanceof Date ? value : new Date(String(value));
29
+ return Number.isNaN(date.getTime()) ? null : date;
30
+ }
31
+
32
+ /** When the event happened: `occurredAt` when recorded, else `createdAt`. */
33
+ export function getEffectiveEventDate(
34
+ event: Pick<Event, 'createdAt' | 'occurredAt'>
35
+ ): Date {
36
+ return parseEventDate(event.occurredAt) ?? new Date(event.createdAt);
37
+ }
38
+
39
+ export function getEffectiveEventTime(
40
+ event: Pick<Event, 'createdAt' | 'occurredAt'>
41
+ ): number {
42
+ return getEffectiveEventDate(event).getTime();
43
+ }
44
+
45
+ const pad = (n: number, width = 2) => n.toString().padStart(width, '0');
46
+
47
+ /** Timestamp parts: dimmed `NOV 06`, clock, dimmed `.123`. */
48
+ export function formatTimestampParts(date: Date): {
49
+ day: string;
50
+ clock: string;
51
+ ms: string;
52
+ } {
53
+ const month = date.toLocaleString('en-US', { month: 'short' }).toUpperCase();
54
+ return {
55
+ day: `${month} ${pad(date.getDate())}`,
56
+ clock: `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`,
57
+ ms: `.${pad(date.getMilliseconds(), 3)}`,
58
+ };
59
+ }
60
+
61
+ function formatClock(value: unknown): string | null {
62
+ const date = parseEventDate(value);
63
+ return date ? formatTimestampParts(date).clock : null;
64
+ }
65
+
66
+ export function formatSinceStart(ms: number): string {
67
+ return ms <= 0 ? '0ms' : `+${formatDurationPrecise(ms)}`;
68
+ }
69
+
70
+ /** Sorts a copy of `events` by when each happened. */
71
+ export function sortEventsByTime(
72
+ events: readonly Event[],
73
+ order: 'asc' | 'desc'
74
+ ): Event[] {
75
+ const dir = order === 'desc' ? -1 : 1;
76
+ return [...events].sort(
77
+ (a, b) => dir * (getEffectiveEventTime(a) - getEffectiveEventTime(b))
78
+ );
79
+ }
80
+
81
+ /** Concatenates event lists, keeping the first copy of each eventId. */
82
+ export function mergeEventsById(...lists: readonly Event[][]): Event[] {
83
+ const seen = new Set<string>();
84
+ const merged: Event[] = [];
85
+ for (const list of lists) {
86
+ for (const event of list) {
87
+ if (seen.has(event.eventId)) continue;
88
+ seen.add(event.eventId);
89
+ merged.push(event);
90
+ }
91
+ }
92
+ return merged;
93
+ }
94
+
95
+ /** Whether a loaded eventData object contains any encrypted marker values. */
96
+ export function hasEncryptedValues(data: unknown): boolean {
97
+ if (!data || typeof data !== 'object') return false;
98
+ for (const val of Object.values(data as Record<string, unknown>)) {
99
+ if (isEncryptedMarker(val)) return true;
100
+ }
101
+ return false;
102
+ }
103
+
104
+ // ──────────────────────────────────────────────────────────────────────────
105
+ // Entity
106
+ // ──────────────────────────────────────────────────────────────────────────
107
+
108
+ export type EventEntityKind = 'run' | 'step' | 'hook' | 'wait';
109
+
110
+ export interface EventEntity {
111
+ kind: EventEntityKind;
112
+ /**
113
+ * Shared by every event of the same entity: {@link RUN_ENTITY_KEY} for the
114
+ * run, else the correlationId. Null for a child event without one.
115
+ */
116
+ key: string | null;
117
+ }
118
+
119
+ /** Entity key of the run itself. */
120
+ const RUN_ENTITY_KEY = '__run__';
121
+
122
+ function getEntityKind(eventType: string): EventEntityKind {
123
+ if (isStepEventType(eventType)) return 'step';
124
+ if (isWaitEventType(eventType)) return 'wait';
125
+ // hook_conflict is written instead of hook_created when the token is taken,
126
+ // and carries the correlationId of the hook it would have created.
127
+ if (isHookLifecycleEventType(eventType) || eventType === 'hook_conflict') {
128
+ return 'hook';
129
+ }
130
+ // Run lifecycle events, plus attr_set and noop, whose correlationId is a
131
+ // dedup or positional token rather than a child entity ID.
132
+ return 'run';
133
+ }
134
+
135
+ /** The step, hook, wait or run an event belongs to. */
136
+ export function getEventEntity(
137
+ event: Pick<Event, 'eventType' | 'correlationId'>
138
+ ): EventEntity {
139
+ const kind = getEntityKind(event.eventType);
140
+ if (kind === 'run') return { kind, key: RUN_ENTITY_KEY };
141
+ return { kind, key: event.correlationId ?? null };
142
+ }
143
+
144
+ /** The trace viewer's resource kind for an event, for its type icon. */
145
+ function getEventResource(event: Event, entity: EventEntity): string {
146
+ // A sealed-slot noop stands for no entity, so it keeps the generic icon.
147
+ if (event.eventType === 'noop') return 'event';
148
+ return entity.kind === 'wait' ? 'sleep' : entity.kind;
149
+ }
150
+
151
+ // ──────────────────────────────────────────────────────────────────────────
152
+ // Names
153
+ // ──────────────────────────────────────────────────────────────────────────
154
+
155
+ export interface EventNames {
156
+ /** Step correlationId → parsed step name. */
157
+ correlationNameMap: Map<string, string>;
158
+ /** Hook correlationId → token. */
159
+ hookNameMap: Map<string, string>;
160
+ workflowName: string | null;
161
+ }
162
+
163
+ /**
164
+ * Step names from step_created (or step_started, for a step whose creation
165
+ * the World recorded on its start alone), hook tokens from hook_created, and
166
+ * the workflow name from the run.
167
+ */
168
+ export function buildNameMaps(
169
+ events: readonly Event[] | null,
170
+ run: WorkflowRun | null
171
+ ): EventNames {
172
+ const correlationNameMap = new Map<string, string>();
173
+ const hookNameMap = new Map<string, string>();
174
+
175
+ for (const event of events ?? []) {
176
+ if (!event.correlationId) continue;
177
+ if (event.eventType === 'hook_created') {
178
+ // The token is never stripped from a list response.
179
+ const token = (event.eventData as { token?: unknown } | undefined)?.token;
180
+ if (typeof token === 'string')
181
+ hookNameMap.set(event.correlationId, token);
182
+ continue;
183
+ }
184
+ if (
185
+ event.eventType !== 'step_created' &&
186
+ event.eventType !== 'step_started'
187
+ ) {
188
+ continue;
189
+ }
190
+ const stepName = event.eventData?.stepName;
191
+ if (typeof stepName !== 'string') continue;
192
+ if (
193
+ event.eventType === 'step_started' &&
194
+ correlationNameMap.has(event.correlationId)
195
+ ) {
196
+ continue;
197
+ }
198
+ const parsed = parseStepName(stepName) ?? parseWorkflowName(stepName);
199
+ correlationNameMap.set(event.correlationId, parsed?.shortName ?? stepName);
200
+ }
201
+
202
+ const workflowName = run?.workflowName
203
+ ? (parseWorkflowName(run.workflowName)?.shortName ?? run.workflowName)
204
+ : null;
205
+
206
+ return { correlationNameMap, hookNameMap, workflowName };
207
+ }
208
+
209
+ function getEventName(entity: EventEntity, names: EventNames): string {
210
+ if (entity.kind === 'run') return names.workflowName ?? '';
211
+ if (entity.key === null) return '';
212
+ if (entity.kind === 'hook')
213
+ return names.hookNameMap.get(entity.key) ?? 'hook';
214
+ if (entity.kind === 'wait') return 'sleep';
215
+ return names.correlationNameMap.get(entity.key) ?? '';
216
+ }
217
+
218
+ // ──────────────────────────────────────────────────────────────────────────
219
+ // Timing
220
+ // ──────────────────────────────────────────────────────────────────────────
221
+
222
+ export type TimingSegment = {
223
+ kind: 'queued' | 'failed' | 'backoff' | 'ok';
224
+ label: string;
225
+ ms: number;
226
+ };
227
+
228
+ export interface EventTiming {
229
+ /**
230
+ * eventId → how long the attempt, wait or run that this event closes took.
231
+ * A retrying step gets one value per failed attempt, measured from the
232
+ * `step_started` that opened that attempt.
233
+ */
234
+ eventDurations: Map<string, number>;
235
+ /**
236
+ * Entity key → a step's queued, attempt and backoff segments of positive
237
+ * length; none for other entities. Queued runs from created to the first
238
+ * start, which retries do not move. Measured from the events on hand, so a
239
+ * partially loaded log may give a partial breakdown.
240
+ */
241
+ stepSegments: Map<string, TimingSegment[]>;
242
+ }
243
+
244
+ /** One entity's created time, open attempt, wait or run, and step segments. */
245
+ interface Clock {
246
+ createdAt?: number;
247
+ openedAt?: number;
248
+ backoffStart?: number;
249
+ attempt: number;
250
+ segments: TimingSegment[];
251
+ }
252
+
253
+ /** The outcome of the step attempt each of these event types closes. */
254
+ const ATTEMPT_OUTCOME: Record<string, 'ok' | 'failed'> = {
255
+ step_completed: 'ok',
256
+ step_failed: 'failed',
257
+ step_retrying: 'failed',
258
+ };
259
+
260
+ /**
261
+ * Measures every entity in one chronological pass, so the result does not
262
+ * depend on the caller's sort order.
263
+ *
264
+ * Events every replay reads past as repeats are excluded: a second
265
+ * `step_completed` written by a concurrent replay would otherwise stretch the
266
+ * step's measured runtime to whenever that replay happened to commit. The
267
+ * caller supplies them, because whether an event is a repeat is a property of
268
+ * the whole log and this function may be handed a page of it.
269
+ */
270
+ export function buildEventTiming(
271
+ events: readonly Event[],
272
+ duplicateEventIds: ReadonlySet<string> = new Set()
273
+ ): EventTiming {
274
+ const chronological = events
275
+ .filter((event) => !duplicateEventIds.has(event.eventId))
276
+ .sort((a, b) => getEffectiveEventTime(a) - getEffectiveEventTime(b));
277
+
278
+ const clocks = new Map<string, Clock>();
279
+ const eventDurations = new Map<string, number>();
280
+
281
+ for (const event of chronological) {
282
+ const { key } = getEventEntity(event);
283
+ if (key === null) continue;
284
+ const ts = getEffectiveEventTime(event);
285
+ const type = event.eventType;
286
+ let clock = clocks.get(key);
287
+ if (!clock) {
288
+ clock = { attempt: 0, segments: [] };
289
+ clocks.set(key, clock);
290
+ }
291
+
292
+ switch (type) {
293
+ case 'step_created':
294
+ case 'run_created':
295
+ clock.createdAt ??= ts;
296
+ break;
297
+ case 'step_started':
298
+ if (clock.attempt === 0 && clock.createdAt !== undefined) {
299
+ clock.segments.push({
300
+ kind: 'queued',
301
+ label: 'Queued',
302
+ ms: ts - clock.createdAt,
303
+ });
304
+ }
305
+ if (clock.backoffStart !== undefined) {
306
+ clock.segments.push({
307
+ kind: 'backoff',
308
+ label: 'Backoff',
309
+ ms: ts - clock.backoffStart,
310
+ });
311
+ clock.backoffStart = undefined;
312
+ }
313
+ clock.attempt += 1;
314
+ clock.openedAt = ts;
315
+ break;
316
+ case 'run_started':
317
+ case 'wait_created':
318
+ clock.openedAt = ts;
319
+ break;
320
+ case 'step_completed':
321
+ case 'step_failed':
322
+ case 'step_retrying':
323
+ case 'run_completed':
324
+ case 'run_failed':
325
+ case 'run_cancelled':
326
+ case 'wait_completed': {
327
+ if (type === 'step_retrying') clock.backoffStart = ts;
328
+ if (clock.openedAt === undefined) break;
329
+ const ms = ts - clock.openedAt;
330
+ clock.openedAt = undefined;
331
+ eventDurations.set(event.eventId, ms);
332
+ const outcome = ATTEMPT_OUTCOME[type];
333
+ if (outcome) {
334
+ clock.segments.push({
335
+ kind: outcome,
336
+ label: `Attempt ${clock.attempt} · ${outcome}`,
337
+ ms,
338
+ });
339
+ }
340
+ break;
341
+ }
342
+ }
343
+ }
344
+
345
+ const stepSegments = new Map<string, TimingSegment[]>();
346
+ for (const [key, clock] of clocks) {
347
+ stepSegments.set(
348
+ key,
349
+ clock.segments.filter((segment) => segment.ms > 0)
350
+ );
351
+ }
352
+
353
+ return { eventDurations, stepSegments };
354
+ }
355
+
356
+ // ──────────────────────────────────────────────────────────────────────────
357
+ // Level and message
358
+ // ──────────────────────────────────────────────────────────────────────────
359
+
360
+ export type EventLevel = 'default' | 'warning' | 'error' | 'muted';
361
+
362
+ /**
363
+ * Rows are tinted by level. Only events that need attention get color;
364
+ * everything else stays neutral.
365
+ */
366
+ function getEventLevel(event: Event): EventLevel {
367
+ switch (event.eventType) {
368
+ case 'step_failed':
369
+ case 'run_failed':
370
+ return 'error';
371
+ case 'step_retrying':
372
+ case 'hook_conflict':
373
+ return 'warning';
374
+ default:
375
+ return 'default';
376
+ }
377
+ }
378
+
379
+ /**
380
+ * One-line summary from what a list response carries inline. Payload fields
381
+ * (input, result, error, payload) are stripped by `resolveData: 'none'`, so
382
+ * the summary only uses the scalar fields every event keeps.
383
+ */
384
+ function getEventMessage(event: Event, queuedMs?: number): string {
385
+ const data = (event.eventData ?? {}) as Record<string, unknown>;
386
+ const attempt = typeof data.attempt === 'number' ? data.attempt : undefined;
387
+
388
+ switch (event.eventType) {
389
+ case 'step_started':
390
+ if (attempt && attempt > 1) return `attempt ${attempt}`;
391
+ return queuedMs ? `queued ${formatDurationPrecise(queuedMs)}` : '';
392
+ case 'step_retrying': {
393
+ const retryAt = formatClock(data.retryAfter);
394
+ const head = attempt ? `attempt ${attempt} failed` : 'attempt failed';
395
+ return retryAt ? `${head} · retry at ${retryAt}` : head;
396
+ }
397
+ case 'step_failed':
398
+ return attempt ? `failed on attempt ${attempt}` : 'failed';
399
+ case 'run_failed':
400
+ return typeof data.errorCode === 'string' ? data.errorCode : '';
401
+ case 'run_cancelled':
402
+ return typeof data.cancelReason === 'string' ? data.cancelReason : '';
403
+ case 'wait_created': {
404
+ const resumeAt = formatClock(data.resumeAt);
405
+ return resumeAt ? `resumes at ${resumeAt}` : '';
406
+ }
407
+ case 'hook_created':
408
+ return data.isWebhook ? 'webhook' : '';
409
+ case 'hook_conflict':
410
+ return typeof data.conflictingRunId === 'string'
411
+ ? `token held by ${data.conflictingRunId}`
412
+ : 'token already in use';
413
+ case 'attr_set': {
414
+ const changes = Array.isArray(data.changes) ? data.changes : [];
415
+ return changes
416
+ .map((change: { key?: unknown; value?: unknown }) =>
417
+ change.value === null
418
+ ? `${String(change.key)} removed`
419
+ : `${String(change.key)} = ${JSON.stringify(change.value)}`
420
+ )
421
+ .join(', ');
422
+ }
423
+ default:
424
+ return '';
425
+ }
426
+ }
427
+
428
+ // ──────────────────────────────────────────────────────────────────────────
429
+ // Rows
430
+ // ──────────────────────────────────────────────────────────────────────────
431
+
432
+ /** Everything an event's row, the text filter and the details panel read. */
433
+ export interface EventListLookups {
434
+ names: EventNames;
435
+ timing: EventTiming;
436
+ /** Epoch ms the "Since start" column is measured from. */
437
+ runStartMs?: number;
438
+ duplicateEventIds: ReadonlySet<string>;
439
+ }
440
+
441
+ /**
442
+ * "Since start" is measured from the run, falling back to the earliest event
443
+ * when the run record isn't available.
444
+ */
445
+ function getRunStartMs(
446
+ events: readonly Event[],
447
+ run: WorkflowRun | null
448
+ ): number | undefined {
449
+ const created = parseEventDate(run?.createdAt);
450
+ if (created) return created.getTime();
451
+ let min: number | undefined;
452
+ for (const event of events) {
453
+ const t = getEffectiveEventTime(event);
454
+ if (min === undefined || t < min) min = t;
455
+ }
456
+ return min;
457
+ }
458
+
459
+ /**
460
+ * Lookups over every event on hand. `duplicateEventIds` is classified by the
461
+ * caller, which knows whether `events` is the whole log.
462
+ */
463
+ export function buildEventLookups(
464
+ events: readonly Event[],
465
+ run: WorkflowRun | null,
466
+ duplicateEventIds: ReadonlySet<string>
467
+ ): EventListLookups {
468
+ return {
469
+ names: buildNameMaps(events, run),
470
+ timing: buildEventTiming(events, duplicateEventIds),
471
+ runStartMs: getRunStartMs(events, run),
472
+ duplicateEventIds,
473
+ };
474
+ }
475
+
476
+ export interface EventListRow {
477
+ event: Event;
478
+ entity: EventEntity;
479
+ level: EventLevel;
480
+ /** The trace viewer's resource kind, for the type icon. */
481
+ resource: string;
482
+ /** Step name, hook token, `sleep`, or the workflow name; may be empty. */
483
+ name: string;
484
+ message: string;
485
+ /** Why the row is struck through, when it is. */
486
+ notice?: string;
487
+ /** The step's queued, attempt and backoff breakdown; empty for other events. */
488
+ segments: TimingSegment[];
489
+ durationMs?: number;
490
+ sinceStartMs?: number;
491
+ }
492
+
493
+ export function buildEventRow(
494
+ event: Event,
495
+ lookups: EventListLookups
496
+ ): EventListRow {
497
+ const entity = getEventEntity(event);
498
+ const segments =
499
+ entity.key === null
500
+ ? []
501
+ : (lookups.timing.stepSegments.get(entity.key) ?? []);
502
+ // An event the runtime ignores is muted and struck through, and says why.
503
+ const ignored = lookups.duplicateEventIds.has(event.eventId)
504
+ ? {
505
+ message: 'duplicate, ignored on replay',
506
+ notice: DUPLICATE_EVENT_MESSAGE,
507
+ }
508
+ : isSealedNoopEvent(event)
509
+ ? {
510
+ message: 'sealed slot, never observed by the run',
511
+ notice: SEALED_EVENT_MESSAGE,
512
+ }
513
+ : null;
514
+ return {
515
+ event,
516
+ entity,
517
+ level: ignored ? 'muted' : getEventLevel(event),
518
+ resource: getEventResource(event, entity),
519
+ name: getEventName(entity, lookups.names),
520
+ message:
521
+ ignored?.message ??
522
+ getEventMessage(
523
+ event,
524
+ segments.find((segment) => segment.kind === 'queued')?.ms
525
+ ),
526
+ notice: ignored?.notice,
527
+ segments,
528
+ durationMs: lookups.timing.eventDurations.get(event.eventId),
529
+ sinceStartMs:
530
+ lookups.runStartMs === undefined
531
+ ? undefined
532
+ : getEffectiveEventTime(event) - lookups.runStartMs,
533
+ };
534
+ }
535
+
536
+ // ──────────────────────────────────────────────────────────────────────────
537
+ // Idle gaps
538
+ // ──────────────────────────────────────────────────────────────────────────
539
+
540
+ /** A pause this long between consecutive events gets a divider row. */
541
+ const IDLE_GAP_MS = 30_000;
542
+
543
+ export type EventListItem =
544
+ | { kind: 'event'; row: EventListRow; index: number }
545
+ | { kind: 'gap'; key: string; ms: number; reason: string };
546
+
547
+ function describeGap(later: Event, hookNameMap: Map<string, string>): string {
548
+ if (later.eventType === 'wait_completed') return 'waiting on sleep';
549
+ if (later.eventType === 'hook_received') {
550
+ const token = later.correlationId
551
+ ? hookNameMap.get(later.correlationId)
552
+ : undefined;
553
+ return token ? `waiting on hook ${token}` : 'waiting on hook';
554
+ }
555
+ return '';
556
+ }
557
+
558
+ /** Rows interleaved, when `showGaps`, with a divider at each idle pause. */
559
+ export function buildListItems(
560
+ rows: EventListRow[],
561
+ options: { showGaps: boolean; hookNameMap: Map<string, string> }
562
+ ): EventListItem[] {
563
+ const items: EventListItem[] = [];
564
+ rows.forEach((row, index) => {
565
+ if (options.showGaps && index > 0) {
566
+ const prev = rows[index - 1].event;
567
+ const event = row.event;
568
+ const a = getEffectiveEventTime(prev);
569
+ const b = getEffectiveEventTime(event);
570
+ const ms = Math.abs(b - a);
571
+ if (ms >= IDLE_GAP_MS) {
572
+ const later = b >= a ? event : prev;
573
+ items.push({
574
+ kind: 'gap',
575
+ key: `gap-${prev.eventId}-${event.eventId}`,
576
+ ms,
577
+ reason: describeGap(later, options.hookNameMap),
578
+ });
579
+ }
580
+ }
581
+ items.push({ kind: 'event', row, index });
582
+ });
583
+ return items;
584
+ }
585
+
586
+ // ──────────────────────────────────────────────────────────────────────────
587
+ // Search
588
+ // ──────────────────────────────────────────────────────────────────────────
589
+
590
+ /**
591
+ * What the search box is doing. `query` is the trimmed input. A complete
592
+ * ID is looked up on the server; anything else leaves the loaded events as
593
+ * they are, since a local filter would miss events on unloaded pages.
594
+ */
595
+ export type EventSearchState =
596
+ | { status: 'idle' }
597
+ | { status: 'incomplete'; query: string }
598
+ | { status: 'unavailable'; query: string }
599
+ | { status: 'loading'; query: string; id: ExactWorkflowSearchId }
600
+ | {
601
+ status: 'ok';
602
+ query: string;
603
+ id: ExactWorkflowSearchId;
604
+ events: Event[];
605
+ truncated: boolean;
606
+ }
607
+ | { status: 'not_found'; query: string; id: ExactWorkflowSearchId }
608
+ | {
609
+ status: 'error';
610
+ query: string;
611
+ id: ExactWorkflowSearchId;
612
+ message: string;
613
+ };
614
+
615
+ const NO_EVENTS: Event[] = [];
616
+
617
+ /**
618
+ * The events the list shows: the run's log, which pages in more as it
619
+ * scrolls, or the events a settled exact-ID search found in its place.
620
+ */
621
+ export function getListSource(
622
+ search: EventSearchState,
623
+ log: { events: Event[] | null; hasMore: boolean }
624
+ ): {
625
+ events: Event[];
626
+ hasMore: boolean;
627
+ /** The run's log, not a search result. */
628
+ isLog: boolean;
629
+ } {
630
+ switch (search.status) {
631
+ case 'ok':
632
+ return { events: search.events, hasMore: false, isLog: false };
633
+ case 'not_found':
634
+ case 'error':
635
+ return { events: NO_EVENTS, hasMore: false, isLog: false };
636
+ default:
637
+ return {
638
+ events: log.events ?? NO_EVENTS,
639
+ hasMore: log.hasMore,
640
+ isLog: true,
641
+ };
642
+ }
643
+ }
644
+
645
+ function countEvents(n: number): string {
646
+ return `${n} event${n !== 1 ? 's' : ''}`;
647
+ }
648
+
649
+ /** Shown in place of the list when it has no rows. */
650
+ export function getEmptyMessage(search: EventSearchState): string {
651
+ switch (search.status) {
652
+ case 'not_found':
653
+ return `No events found for ${search.query}`;
654
+ case 'error':
655
+ return search.message;
656
+ case 'unavailable':
657
+ return 'Exact ID search is unavailable in this view.';
658
+ default:
659
+ return 'No events found';
660
+ }
661
+ }
662
+
663
+ export function getFooterLabel(
664
+ search: EventSearchState,
665
+ counts: {
666
+ /** Events the list draws its rows from. */
667
+ total: number;
668
+ hasMoreEvents: boolean;
669
+ }
670
+ ): string {
671
+ const { total, hasMoreEvents } = counts;
672
+ switch (search.status) {
673
+ case 'ok':
674
+ return `${countEvents(total)} for ${search.query}${search.truncated ? ' (results may be truncated)' : ''}`;
675
+ case 'not_found':
676
+ return `No events found for ${search.query}`;
677
+ case 'error':
678
+ return search.message;
679
+ case 'incomplete':
680
+ return 'Enter a full step ID, wait ID, hook ID, or event ID';
681
+ default:
682
+ return `${countEvents(total)}${hasMoreEvents ? ' loaded' : ''}`;
683
+ }
684
+ }
@@ -0,0 +1,21 @@
1
+ const ascii = (text: string) => Array.from(text, (char) => char.charCodeAt(0));
2
+
3
+ const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
4
+ const JPEG = [0xff, 0xd8, 0xff];
5
+ const GIF87A = ascii('GIF87a');
6
+ const GIF89A = ascii('GIF89a');
7
+ const RIFF = ascii('RIFF');
8
+ const WEBP = ascii('WEBP');
9
+
10
+ /** Raster image signatures; stream names and caller-supplied types are untrusted. */
11
+ export function getStreamImageType(data: Uint8Array): string | null {
12
+ // Compare raw bytes: a WebP's RIFF size field (bytes 4-7) is binary and
13
+ // can form multi-byte UTF-8, so decoding the header as text misaligns it.
14
+ const matches = (signature: number[], offset = 0) =>
15
+ signature.every((byte, index) => data[offset + index] === byte);
16
+ if (matches(PNG)) return 'image/png';
17
+ if (matches(JPEG)) return 'image/jpeg';
18
+ if (matches(GIF87A) || matches(GIF89A)) return 'image/gif';
19
+ if (matches(RIFF) && matches(WEBP, 8)) return 'image/webp';
20
+ return null;
21
+ }