@tangle-network/charts 2.0.12 → 2.0.14

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.
@@ -0,0 +1,1184 @@
1
+ import { D as statusMeta, O as createLucideIcon, T as RunStatusIcon } from "./flow-waterfall-model-DvrgPLGS.js";
2
+ import { a as LIVE_AGENT_CARD, c as AgentMark, d as Wrench, n as AGENT_CARD, o as buildAgentTopology, s as layoutAgents, t as LatestEvents } from "./latest-events-iiWwpIck.js";
3
+ import { C as fmtCost, E as fmtTokenTotal, T as fmtEventTime, _ as syncAmbient, b as useMotionAllowed, g as ambientStyle, h as agentQuietActivity, i as SELECTION_OUTLINE, n as RESTING_SHADOW, o as useColorMode, r as edgeColor, t as RESTING_BORDER, u as shortModel, v as tokenMilliseconds, x as useRunNow, y as useAttention } from "./graph-style-fealnLLn.js";
4
+ import { t as MOTION_CONTROL } from "./motion-DILryczn.js";
5
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6
+ import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
7
+ import { createPortal } from "react-dom";
8
+ import { Background, BaseEdge, Controls, EdgeLabelRenderer, Handle, MarkerType, MiniMap, Position, ReactFlow, useInternalNode } from "@xyflow/react";
9
+ //#region node_modules/lucide-react/dist/esm/icons/chevron-down.mjs
10
+ /**
11
+ * @license lucide-react v1.63.0 - ISC
12
+ *
13
+ * This source code is licensed under the ISC license.
14
+ * See the LICENSE file in the root directory of this source tree.
15
+ */
16
+ const __iconData = {
17
+ name: "chevron-down",
18
+ size: 24,
19
+ node: [["path", {
20
+ d: "m6 9 6 6 6-6",
21
+ key: "qrunsl"
22
+ }]]
23
+ };
24
+ __iconData.node;
25
+ const ChevronDown = createLucideIcon(__iconData);
26
+ //#endregion
27
+ //#region src/react/agent-graph/agent-graph-parts.tsx
28
+ /**
29
+ * What `AgentGraph` draws: an agent's card, the frame around a grid of leaf
30
+ * workers, and the curved edge a message or delegation travels along.
31
+ *
32
+ * The visual vocabulary is the workflow graph's own (`node-ui.tsx`): the same
33
+ * model brand mark, status colours, resting elevation and selection ring, so an
34
+ * agent run and a workflow run read as one system.
35
+ */
36
+ /** Workflow state adaptation stays at its boundary; agent states use ui directly. */
37
+ function agentStatus(status) {
38
+ const meta = statusMeta(status);
39
+ const flow = status === "needs-you" ? "waiting" : status === "waiting" || status === "idle" || status === "unknown" ? "queued" : status === "stopped" ? "succeeded" : status;
40
+ return {
41
+ ...meta,
42
+ color: `var(${meta.token})`,
43
+ flow
44
+ };
45
+ }
46
+ function StatusGlyph({ status, size }) {
47
+ return status === "running" ? /* @__PURE__ */ jsx("span", {
48
+ "aria-hidden": true,
49
+ "data-motion": "essential",
50
+ className: "ag-running-dot",
51
+ style: ambientStyle,
52
+ onAnimationStart: syncAmbient
53
+ }) : /* @__PURE__ */ jsx(RunStatusIcon, {
54
+ status,
55
+ size,
56
+ "aria-hidden": true
57
+ });
58
+ }
59
+ function cardBorder(status) {
60
+ if (status === "needs-you" || status === "failed") return {
61
+ borderColor: agentStatus(status).color,
62
+ borderWidth: status === "needs-you" ? 1.5 : 1
63
+ };
64
+ return { borderColor: RESTING_BORDER };
65
+ }
66
+ /** The words a reader without the picture receives for one agent. */
67
+ function agentDescription(agent) {
68
+ const cost = fmtCost(agent.costUsd ?? void 0);
69
+ const tokens = fmtTokenTotal(agent.tokens);
70
+ return [
71
+ agent.label,
72
+ agent.role,
73
+ agent.harness,
74
+ agent.model,
75
+ agentStatus(agent.status).label,
76
+ agent.turn,
77
+ agent.result,
78
+ cost,
79
+ tokens
80
+ ].filter(Boolean).join(", ");
81
+ }
82
+ /** Set on each card's React Flow wrapper — the element that takes keyboard
83
+ * focus — so the card inside can draw the focus ring. */
84
+ const AGENT_NODE_CLASS = "group/agent !outline-none";
85
+ const HANDLE_CLASS = "!h-1 !w-1 !min-w-0 !border-0 !bg-transparent opacity-0";
86
+ function Handles({ direction, source = true }) {
87
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Handle, {
88
+ type: "target",
89
+ position: direction === "LR" ? Position.Left : Position.Top,
90
+ isConnectable: false,
91
+ className: HANDLE_CLASS
92
+ }), source && /* @__PURE__ */ jsx(Handle, {
93
+ type: "source",
94
+ position: direction === "LR" ? Position.Right : Position.Bottom,
95
+ isConnectable: false,
96
+ className: HANDLE_CLASS
97
+ })] });
98
+ }
99
+ function AgentCardView({ agent, selected, direction, now: fixed, onOpen, parentLabel, handles = false }) {
100
+ const now = useRunNow(fixed);
101
+ const quiet = agentQuietActivity(agent, now);
102
+ const s = agentStatus(agent.status);
103
+ return /* @__PURE__ */ jsxs("div", {
104
+ "data-status": agent.status,
105
+ "data-activity": quiet ? "quiet" : void 0,
106
+ "data-selected": selected || void 0,
107
+ title: agentDescription(agent),
108
+ className: `ag-agent-card relative flex h-full w-full flex-col gap-0.5 rounded-[var(--radius-card)] border bg-card px-3 py-2 text-left ${MOTION_CONTROL}`,
109
+ style: {
110
+ boxShadow: RESTING_SHADOW,
111
+ ...cardBorder(agent.status),
112
+ ...selected ? SELECTION_OUTLINE : {}
113
+ },
114
+ children: [
115
+ handles && /* @__PURE__ */ jsx(Handles, { direction }),
116
+ /* @__PURE__ */ jsxs("div", {
117
+ className: "flex min-w-0 items-center gap-2",
118
+ children: [
119
+ /* @__PURE__ */ jsx("span", {
120
+ className: "grayscale hover:grayscale-0",
121
+ children: /* @__PURE__ */ jsx(AgentMark, {
122
+ agent,
123
+ layout: "tree",
124
+ size: 18
125
+ })
126
+ }),
127
+ /* @__PURE__ */ jsxs("span", {
128
+ className: "min-w-0 flex-1 truncate text-sm font-semibold leading-[18px]",
129
+ children: [parentLabel && /* @__PURE__ */ jsxs("span", {
130
+ className: "ag-parent-label",
131
+ children: [parentLabel, " / "]
132
+ }), agent.label]
133
+ }),
134
+ /* @__PURE__ */ jsx("span", {
135
+ className: "text-xs text-muted-foreground tabular-nums",
136
+ title: agent.costUsd == null ? "Cost not reported" : "Cost",
137
+ children: fmtCost(agent.costUsd ?? void 0) ?? "—"
138
+ })
139
+ ]
140
+ }),
141
+ /* @__PURE__ */ jsx("p", {
142
+ className: "m-0 line-clamp-2 min-h-4 text-xs text-foreground leading-4",
143
+ children: (agent.status === "failed" ? agent.result ?? agent.turn : agent.turn) || "—"
144
+ }),
145
+ /* @__PURE__ */ jsxs("div", {
146
+ className: "mt-auto flex items-center justify-between gap-1 text-xs",
147
+ style: { color: quiet ? "var(--surface-warning-text)" : s.color },
148
+ children: [/* @__PURE__ */ jsxs("span", {
149
+ className: "flex items-center gap-1",
150
+ children: [/* @__PURE__ */ jsx(StatusGlyph, {
151
+ status: agent.status,
152
+ size: 16
153
+ }), quiet?.label ?? s.label]
154
+ }), agent.status === "needs-you" && /* @__PURE__ */ jsx("button", {
155
+ type: "button",
156
+ className: "ag-live-respond nodrag nopan",
157
+ disabled: !onOpen,
158
+ onClick: (event) => {
159
+ event.stopPropagation();
160
+ onOpen?.();
161
+ },
162
+ children: "Respond"
163
+ })]
164
+ })
165
+ ]
166
+ });
167
+ }
168
+ function AgentCard({ data }) {
169
+ return /* @__PURE__ */ jsx(AgentCardView, {
170
+ ...data,
171
+ handles: true
172
+ });
173
+ }
174
+ function AgentFrameBox({ data }) {
175
+ const { frame, direction } = data;
176
+ return /* @__PURE__ */ jsxs("div", {
177
+ className: "relative h-full w-full rounded-2xl border",
178
+ style: {
179
+ background: "color-mix(in srgb, hsl(var(--muted-foreground)) 7%, transparent)",
180
+ borderColor: "hsl(var(--foreground) / 0.08)"
181
+ },
182
+ children: [/* @__PURE__ */ jsx(Handles, { direction }), /* @__PURE__ */ jsxs("button", {
183
+ type: "button",
184
+ className: "nodrag nopan absolute right-3 top-2 flex h-16 w-8 flex-col items-center justify-center gap-1 rounded text-sm text-muted-foreground hover:bg-muted focus-visible:outline",
185
+ "aria-label": `${frame.collapsed ? "Expand" : "Collapse"} ${data.label} team`,
186
+ "aria-expanded": !frame.collapsed,
187
+ title: `${data.label} · ${frame.group.memberIds.length} agents`,
188
+ onClick: (event) => {
189
+ event.stopPropagation();
190
+ data.onToggle();
191
+ },
192
+ children: [/* @__PURE__ */ jsx(ChevronDown, {
193
+ size: 16,
194
+ className: frame.collapsed ? "-rotate-90" : void 0
195
+ }), /* @__PURE__ */ jsx("span", { children: frame.group.memberIds.length })]
196
+ })]
197
+ });
198
+ }
199
+ /** Resting message and delegation edges stay neutral. */
200
+ const MESSAGE_EDGE_COLOR = {
201
+ message: "color-mix(in srgb, hsl(var(--muted-foreground)) 70%, transparent)",
202
+ delegation: "color-mix(in srgb, hsl(var(--muted-foreground)) 80%, transparent)"
203
+ };
204
+ function boxOf(node) {
205
+ return {
206
+ x: node.internals.positionAbsolute.x,
207
+ y: node.internals.positionAbsolute.y,
208
+ w: node.measured.width ?? node.width ?? 0,
209
+ h: node.measured.height ?? node.height ?? 0
210
+ };
211
+ }
212
+ /** Where the line from a box's centre toward `toward` leaves the box, `gap`px out. */
213
+ function exitPoint(b, toward, gap) {
214
+ const cx = b.x + b.w / 2;
215
+ const cy = b.y + b.h / 2;
216
+ const dx = toward.x - cx;
217
+ const dy = toward.y - cy;
218
+ const len = Math.hypot(dx, dy);
219
+ if (len === 0) return {
220
+ x: cx,
221
+ y: cy
222
+ };
223
+ const scale = Math.min(dx === 0 ? Number.POSITIVE_INFINITY : b.w / 2 / Math.abs(dx), dy === 0 ? Number.POSITIVE_INFINITY : b.h / 2 / Math.abs(dy));
224
+ return {
225
+ x: cx + dx * scale + dx / len * gap,
226
+ y: cy + dy * scale + dy / len * gap
227
+ };
228
+ }
229
+ /**
230
+ * A curve from one card's border to another's, bowed to the right of its
231
+ * direction of travel: two agents messaging each other both ways draw two
232
+ * separate arcs instead of one line over another, and a curve never hides
233
+ * under the straight spawn edges of the tree.
234
+ */
235
+ function messageCurve(a, b) {
236
+ const ac = {
237
+ x: a.x + a.w / 2,
238
+ y: a.y + a.h / 2
239
+ };
240
+ const bc = {
241
+ x: b.x + b.w / 2,
242
+ y: b.y + b.h / 2
243
+ };
244
+ const dx = bc.x - ac.x;
245
+ const dy = bc.y - ac.y;
246
+ const len = Math.hypot(dx, dy) || 1;
247
+ const bend = Math.min(90, Math.max(24, len * .22));
248
+ const control = {
249
+ x: (ac.x + bc.x) / 2 - dy / len * bend,
250
+ y: (ac.y + bc.y) / 2 + dx / len * bend
251
+ };
252
+ const start = exitPoint(a, control, 2);
253
+ const end = exitPoint(b, control, 4);
254
+ return {
255
+ path: `M${start.x},${start.y} Q${control.x},${control.y} ${end.x},${end.y}`,
256
+ mid: {
257
+ x: .25 * start.x + .5 * control.x + .25 * end.x,
258
+ y: .25 * start.y + .5 * control.y + .25 * end.y
259
+ }
260
+ };
261
+ }
262
+ function AgentMessageEdgeView({ id, source, target, data, markerEnd }) {
263
+ const from = useInternalNode(source);
264
+ const to = useInternalNode(target);
265
+ if (!from || !to || !data) return null;
266
+ const { path, mid } = messageCurve(boxOf(from), boxOf(to));
267
+ const color = MESSAGE_EDGE_COLOR[data.kind] ?? MESSAGE_EDGE_COLOR.message;
268
+ const count = data.count ?? 1;
269
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(BaseEdge, {
270
+ id,
271
+ path,
272
+ markerEnd,
273
+ interactionWidth: 10,
274
+ style: {
275
+ stroke: color,
276
+ strokeWidth: 1.25,
277
+ fill: "none"
278
+ }
279
+ }), count > 1 && /* @__PURE__ */ jsx(EdgeLabelRenderer, { children: /* @__PURE__ */ jsxs("div", {
280
+ title: data.label ? `${data.label} ×${count}` : `${count} ${data.kind}s`,
281
+ className: "nodrag nopan pointer-events-auto absolute rounded-full border bg-card px-1.5 font-medium text-[10px] text-muted-foreground tabular-nums leading-4 shadow-sm",
282
+ style: {
283
+ transform: `translate(-50%, -50%) translate(${mid.x}px, ${mid.y}px)`,
284
+ borderColor: color
285
+ },
286
+ children: ["×", count]
287
+ }) })] });
288
+ }
289
+ //#endregion
290
+ //#region src/react/agent-graph/agent-live-card.tsx
291
+ const SETTLED = /* @__PURE__ */ new Set(["succeeded", "stopped"]);
292
+ function middleLabel(label) {
293
+ return label.length <= 52 ? label : `${label.slice(0, 32)} … ${label.slice(-17)}`;
294
+ }
295
+ /** One shell survives settling. A failure retains its evidence and absolute event times. */
296
+ function LiveAgentCardView({ agent, selected, direction = "TB", now: fixed, handles = false, onOpen, parentLabel, renderEventIcon }) {
297
+ const now = useRunNow(fixed);
298
+ const ref = useRef(null);
299
+ useAttention(ref, agent.status);
300
+ const settled = SETTLED.has(agent.status);
301
+ const failed = agent.status === "failed";
302
+ const quiet = agentQuietActivity(agent, now);
303
+ const s = agentStatus(agent.status);
304
+ const meta = [agent.model ? shortModel(agent.model) : void 0, agent.effort].filter(Boolean).join(" · ");
305
+ const events = (agent.events ?? []).slice(-3);
306
+ const cost = Number.isFinite(agent.costUsd) ? fmtCost(agent.costUsd) : void 0;
307
+ const metrics = [
308
+ cost,
309
+ !failed && agent.startedAt != null ? `${fmtEventTime(agent.startedAt, now, false)} elapsed` : void 0,
310
+ Number.isFinite(agent.commits) ? `${agent.commits} ${agent.commits === 1 ? "commit" : "commits"}` : void 0
311
+ ].filter(Boolean).join(" · ") || "—";
312
+ return /* @__PURE__ */ jsxs("div", {
313
+ className: "ag-live-slot",
314
+ children: [handles && /* @__PURE__ */ jsx(Handles, { direction }), /* @__PURE__ */ jsxs("div", {
315
+ ref,
316
+ className: `ag-live-card${settled ? " ag-live-chip" : ""}`,
317
+ "data-status": agent.status,
318
+ "data-sparse": events.length === 0 || void 0,
319
+ "data-activity": quiet ? "quiet" : agent.activity ?? void 0,
320
+ "data-selected": selected || void 0,
321
+ title: agentDescription(agent),
322
+ style: {
323
+ boxShadow: RESTING_SHADOW,
324
+ ...cardBorder(agent.status),
325
+ ...selected ? SELECTION_OUTLINE : {},
326
+ ["--ag-status"]: s.color
327
+ },
328
+ children: [
329
+ settled && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(StatusGlyph, {
330
+ status: agent.status,
331
+ size: 16
332
+ }), /* @__PURE__ */ jsx("span", {
333
+ className: "ag-live-chip-status",
334
+ children: s.label
335
+ })] }),
336
+ /* @__PURE__ */ jsxs("div", {
337
+ className: "ag-live-head",
338
+ children: [
339
+ /* @__PURE__ */ jsx("span", {
340
+ className: "grayscale hover:grayscale-0",
341
+ children: /* @__PURE__ */ jsx(AgentMark, {
342
+ agent,
343
+ layout: "tree",
344
+ size: 18
345
+ })
346
+ }),
347
+ /* @__PURE__ */ jsxs("div", {
348
+ className: "ag-live-names",
349
+ children: [/* @__PURE__ */ jsxs("span", {
350
+ className: "ag-live-name",
351
+ children: [parentLabel && /* @__PURE__ */ jsxs("span", {
352
+ className: "ag-parent-label",
353
+ children: [parentLabel, " / "]
354
+ }), agent.label]
355
+ }), !settled && meta && /* @__PURE__ */ jsx("span", {
356
+ className: "ag-live-meta",
357
+ children: meta
358
+ })]
359
+ }),
360
+ /* @__PURE__ */ jsxs("div", {
361
+ className: "ag-live-stats",
362
+ children: [failed && onOpen ? /* @__PURE__ */ jsxs("button", {
363
+ type: "button",
364
+ className: "ag-live-pill ag-live-inspect nodrag nopan",
365
+ onClick: (event) => {
366
+ event.stopPropagation();
367
+ onOpen();
368
+ },
369
+ children: [
370
+ /* @__PURE__ */ jsx(StatusGlyph, {
371
+ status: agent.status,
372
+ size: 16
373
+ }),
374
+ s.label,
375
+ /* @__PURE__ */ jsx("span", { children: "Inspect" })
376
+ ]
377
+ }) : /* @__PURE__ */ jsxs("span", {
378
+ className: `ag-live-pill${quiet ? " ag-live-quiet" : ""}`,
379
+ children: [/* @__PURE__ */ jsx(StatusGlyph, {
380
+ status: agent.status,
381
+ size: 16
382
+ }), quiet?.label ?? s.label]
383
+ }), !settled && /* @__PURE__ */ jsx("span", {
384
+ className: "ag-live-accounting",
385
+ title: metrics,
386
+ children: metrics
387
+ })]
388
+ })
389
+ ]
390
+ }),
391
+ settled ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("span", {
392
+ className: "ag-live-chip-result",
393
+ children: agent.result ?? agent.turn ?? s.label
394
+ }), cost && /* @__PURE__ */ jsx("span", {
395
+ className: "ag-live-chip-cost",
396
+ title: "Cost",
397
+ children: cost
398
+ })] }) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("div", {
399
+ className: "ag-live-thinking-row",
400
+ children: [/* @__PURE__ */ jsx("p", {
401
+ className: `ag-live-thinking${failed ? " ag-live-failure" : ""}`,
402
+ children: failed ? agent.result ?? events.at(-1)?.label ?? agent.turn ?? s.label : agent.turn || "—"
403
+ }), agent.status === "needs-you" && /* @__PURE__ */ jsx("button", {
404
+ type: "button",
405
+ className: "ag-live-respond nodrag nopan",
406
+ disabled: !onOpen,
407
+ title: onOpen ? void 0 : "Responses unavailable in this view",
408
+ onClick: (event) => {
409
+ event.stopPropagation();
410
+ onOpen?.();
411
+ },
412
+ children: "Respond"
413
+ })]
414
+ }), events.length > 0 && /* @__PURE__ */ jsx("div", {
415
+ className: "ag-live-events-clip",
416
+ children: /* @__PURE__ */ jsx("ol", {
417
+ className: "ag-live-events",
418
+ "aria-label": "Latest events",
419
+ children: events.map((event) => /* @__PURE__ */ jsxs("li", {
420
+ title: event.label,
421
+ children: [
422
+ renderEventIcon?.(event) ?? /* @__PURE__ */ jsx(Wrench, {
423
+ size: 12,
424
+ strokeWidth: 1.75,
425
+ "aria-hidden": true
426
+ }),
427
+ /* @__PURE__ */ jsx("span", {
428
+ className: "ag-live-event-label",
429
+ children: middleLabel(event.label)
430
+ }),
431
+ /* @__PURE__ */ jsxs("time", {
432
+ className: "ag-live-event-at",
433
+ dateTime: Number.isFinite(event.at) ? new Date(event.at).toISOString() : void 0,
434
+ children: [failed && event.at != null ? "at " : "", fmtEventTime(event.at, now, failed)]
435
+ })
436
+ ]
437
+ }, event.id))
438
+ })
439
+ })] })
440
+ ]
441
+ })]
442
+ });
443
+ }
444
+ function LiveAgentCard({ data }) {
445
+ return /* @__PURE__ */ jsx(LiveAgentCardView, {
446
+ ...data,
447
+ handles: true
448
+ });
449
+ }
450
+ //#endregion
451
+ //#region src/react/agent-graph/AgentGraphCanvas.tsx
452
+ const NODE_TYPES = {
453
+ agent: AgentCard,
454
+ liveAgent: LiveAgentCard,
455
+ agentFrame: AgentFrameBox
456
+ };
457
+ const EDGE_TYPES = { agentMessage: AgentMessageEdgeView };
458
+ /** The fit's margin, in screen pixels. */
459
+ const FIT_PADDING = 16;
460
+ const PHONE_PAGE = 24;
461
+ /** The canvas's size, once it has one. */
462
+ function useCanvasSize() {
463
+ const [size, setSize] = useState(null);
464
+ const observer = useRef(null);
465
+ return [size, useCallback((el) => {
466
+ observer.current?.disconnect();
467
+ observer.current = null;
468
+ if (!el || typeof ResizeObserver === "undefined") return;
469
+ const viewport = el.querySelector(".ag-graph-viewport") ?? el;
470
+ const read = () => {
471
+ const r = viewport.getBoundingClientRect();
472
+ if (r.width === 0 || r.height === 0) return;
473
+ setSize((prev) => prev && Math.abs(prev.width - r.width) < 1 && Math.abs(prev.height - r.height) < 1 ? prev : {
474
+ width: r.width,
475
+ height: r.height
476
+ });
477
+ };
478
+ observer.current = new ResizeObserver(read);
479
+ observer.current.observe(viewport);
480
+ read();
481
+ }, [])];
482
+ }
483
+ /** Keep the selected card inside the actual viewport without resetting the reader's camera. */
484
+ function revealSelection(inst, wrapper, id) {
485
+ const node = inst.getInternalNode(id), box = wrapper?.querySelector(".ag-graph-viewport")?.getBoundingClientRect();
486
+ const width = node?.measured.width ?? node?.width, height = node?.measured.height ?? node?.height;
487
+ if (!node || !box || !width || !height) return;
488
+ const current = inst.getViewport(), position = node.internals.positionAbsolute;
489
+ const zoom = current.zoom;
490
+ const x = Math.max(FIT_PADDING - position.x * zoom, Math.min(box.width - FIT_PADDING - (position.x + width) * zoom, current.x));
491
+ const y = Math.max(FIT_PADDING - position.y * zoom, Math.min(box.height - FIT_PADDING - (position.y + height) * zoom, current.y));
492
+ if (x !== current.x || y !== current.y || zoom !== current.zoom) inst.setViewport({
493
+ x,
494
+ y,
495
+ zoom
496
+ });
497
+ }
498
+ function AgentGraphCanvas({ nodes, edges, selectedId, onSelect, direction = "TB", className, emptyState, live = false, renderEventIcon, showLatestEvents = true, now }) {
499
+ const card = live ? LIVE_AGENT_CARD : AGENT_CARD;
500
+ const clock = useRunNow(now);
501
+ const animateMotion = useMotionAllowed();
502
+ const detailsId = useId();
503
+ const hoverTimer = useRef(void 0);
504
+ const hoverTarget = useRef(null);
505
+ const returningFocus = useRef(false);
506
+ const keepDetails = () => clearTimeout(hoverTimer.current);
507
+ const hideDetails = () => {
508
+ keepDetails();
509
+ setHovered(null);
510
+ };
511
+ const leaveDetails = () => {
512
+ keepDetails();
513
+ hoverTimer.current = setTimeout(() => setHovered(null), tokenMilliseconds("--duration-fast", wrapperRef.current));
514
+ };
515
+ useEffect(() => () => clearTimeout(hoverTimer.current), []);
516
+ const [hovered, setHovered] = useState(null);
517
+ const [collapsed, setCollapsed] = useState(/* @__PURE__ */ new Set());
518
+ const [phonePage, setPhonePage] = useState(0);
519
+ const wrapperRef = useRef(null);
520
+ const [canvas, measureCanvas] = useCanvasSize();
521
+ const colorMode = useColorMode(wrapperRef, nodes.length > 0);
522
+ const narrow = canvas !== null && canvas.width < 600;
523
+ const nextTopology = buildAgentTopology(nodes, edges);
524
+ const topologyRef = useRef(nextTopology);
525
+ if (topologyRef.current.key !== nextTopology.key) topologyRef.current = nextTopology;
526
+ const topology = topologyRef.current;
527
+ const columnKey = `${direction}:${live}:${topology.key}`;
528
+ const columnRef = useRef(null);
529
+ if (canvas && !narrow && columnRef.current?.key !== columnKey) columnRef.current = {
530
+ key: columnKey,
531
+ columns: Math.max(1, Math.min(6, Math.floor((canvas.width - 32) / (card.width + 10))))
532
+ };
533
+ const columns = columnRef.current?.columns ?? 1;
534
+ const layoutKey = JSON.stringify([
535
+ direction,
536
+ live,
537
+ topology.key,
538
+ columns,
539
+ [...collapsed]
540
+ ]);
541
+ const [placed, setPlaced] = useState(null);
542
+ useEffect(() => {
543
+ if (narrow) return;
544
+ let active = true;
545
+ layoutAgents(topology, direction, columns, card, collapsed).then((layout) => {
546
+ if (active) setPlaced({
547
+ key: layoutKey,
548
+ layout
549
+ });
550
+ });
551
+ return () => {
552
+ active = false;
553
+ };
554
+ }, [layoutKey, narrow]);
555
+ const layout = placed?.key === layoutKey ? placed.layout : null;
556
+ useEffect(() => {
557
+ const group = selectedId && topology.groupOf.get(selectedId);
558
+ if (group) setCollapsed((current) => {
559
+ if (!current.has(group)) return current;
560
+ const next = new Set(current);
561
+ next.delete(group);
562
+ return next;
563
+ });
564
+ }, [selectedId, topology.key]);
565
+ const byId = useMemo(() => new Map(nodes.map((n) => [n.id, n])), [nodes]);
566
+ const rfRef = useRef(null);
567
+ const flowNodes = useMemo(() => {
568
+ if (!layout) return [];
569
+ const frames = layout.frames.map((frame) => ({
570
+ id: frame.group.id,
571
+ type: "agentFrame",
572
+ position: {
573
+ x: frame.x,
574
+ y: frame.y
575
+ },
576
+ width: frame.width,
577
+ height: frame.height,
578
+ measured: rfRef.current?.getInternalNode(frame.group.id)?.measured,
579
+ zIndex: -1,
580
+ selectable: false,
581
+ focusable: false,
582
+ draggable: false,
583
+ data: {
584
+ frame,
585
+ direction,
586
+ label: byId.get(frame.group.parentId)?.label ?? "Agent",
587
+ onToggle: () => {
588
+ if (!frame.collapsed && selectedId && frame.group.memberIds.includes(selectedId)) onSelect?.(frame.group.parentId);
589
+ setCollapsed((current) => {
590
+ const next = new Set(current);
591
+ next.has(frame.group.id) ? next.delete(frame.group.id) : next.add(frame.group.id);
592
+ return next;
593
+ });
594
+ }
595
+ }
596
+ }));
597
+ const cards = [];
598
+ for (const id of topology.agentIds) {
599
+ const agent = byId.get(id);
600
+ const position = layout.positions.get(id);
601
+ if (!agent || !position) continue;
602
+ const selected = selectedId === id, owned = layout.frames.find((frame) => frame.group.parentId === id);
603
+ const width = owned ? owned.width - 64 : card.width, height = owned ? 64 : card.height;
604
+ const measured = rfRef.current?.getInternalNode(id)?.measured;
605
+ cards.push({
606
+ id,
607
+ type: live ? "liveAgent" : "agent",
608
+ position,
609
+ width,
610
+ height,
611
+ measured: measured?.width === width && measured.height === height ? measured : void 0,
612
+ className: `${AGENT_NODE_CLASS}${owned ? " ag-frame-owner" : ""}`,
613
+ draggable: false,
614
+ ariaRole: "button",
615
+ ariaLabel: agentDescription(agent),
616
+ domAttributes: {
617
+ "aria-pressed": selected,
618
+ "aria-describedby": hovered?.id === id ? detailsId : void 0
619
+ },
620
+ data: {
621
+ agent,
622
+ selected,
623
+ direction,
624
+ now: clock,
625
+ onOpen: onSelect ? () => onSelect(agent.id) : void 0,
626
+ renderEventIcon
627
+ }
628
+ });
629
+ }
630
+ return [...frames, ...cards];
631
+ }, [
632
+ layout,
633
+ topology,
634
+ byId,
635
+ selectedId,
636
+ direction,
637
+ live,
638
+ card,
639
+ clock,
640
+ onSelect,
641
+ renderEventIcon,
642
+ hovered
643
+ ]);
644
+ const flowEdges = useMemo(() => {
645
+ if (!layout) return [];
646
+ const out = [];
647
+ const seen = /* @__PURE__ */ new Set();
648
+ for (const s of topology.spawns) {
649
+ const source = topology.groups.find((group) => group.parentId === s.from)?.id ?? s.from, target = topology.groupOf.get(s.to) ?? s.to;
650
+ if (source === target) continue;
651
+ const id = `spawn:${source}:${target}`;
652
+ if (seen.has(id)) continue;
653
+ seen.add(id);
654
+ out.push({
655
+ id,
656
+ source,
657
+ target,
658
+ type: "smoothstep",
659
+ pathOptions: { borderRadius: 14 },
660
+ selectable: false,
661
+ focusable: false,
662
+ style: {
663
+ stroke: edgeColor(void 0),
664
+ strokeWidth: 1.5
665
+ }
666
+ });
667
+ }
668
+ const ids = new Set(layout.positions.keys());
669
+ const messages = /* @__PURE__ */ new Map();
670
+ for (const e of edges) {
671
+ if (e.kind === "spawn" || e.from === e.to || !ids.has(e.from) || !ids.has(e.to)) continue;
672
+ if (![selectedId, hovered?.id].some((id) => id === e.from || id === e.to)) continue;
673
+ const id = `${e.kind}:${e.from}:${e.to}`;
674
+ const prior = messages.get(id);
675
+ const count = (prior?.data?.count ?? 0) + Math.max(1, e.count ?? 1);
676
+ const color = MESSAGE_EDGE_COLOR[e.kind] ?? MESSAGE_EDGE_COLOR.message;
677
+ messages.set(id, {
678
+ id,
679
+ source: e.from,
680
+ target: e.to,
681
+ type: "agentMessage",
682
+ selectable: false,
683
+ focusable: false,
684
+ zIndex: 0,
685
+ markerEnd: {
686
+ type: MarkerType.ArrowClosed,
687
+ width: 12,
688
+ height: 12,
689
+ color
690
+ },
691
+ ariaLabel: `${e.kind === "delegation" ? "Delegation" : "Message"} from ${byId.get(e.from)?.label ?? e.from} to ${byId.get(e.to)?.label ?? e.to}${count > 1 ? `, ${count} times` : ""}`,
692
+ data: {
693
+ kind: e.kind,
694
+ count,
695
+ label: e.label ?? prior?.data?.label
696
+ }
697
+ });
698
+ }
699
+ return [...out, ...messages.values()];
700
+ }, [
701
+ layout,
702
+ topology,
703
+ edges,
704
+ byId,
705
+ selectedId,
706
+ hovered
707
+ ]);
708
+ const [ready, setReady] = useState(false);
709
+ const [shown, setShown] = useState(false);
710
+ const selection = useRef(selectedId);
711
+ selection.current = selectedId;
712
+ const framed = useRef(null);
713
+ useEffect(() => {
714
+ if (narrow) {
715
+ rfRef.current = null;
716
+ setReady(false);
717
+ setShown(false);
718
+ framed.current = null;
719
+ }
720
+ }, [narrow]);
721
+ const layoutIdentity = layout ? `${layoutKey}:${layout.columns}` : null;
722
+ const cameraKey = `${direction}:${topology.key}`;
723
+ const minZoom = layout && canvas ? Math.max(.02, Math.min(.2, (canvas.width - 32) / layout.width, (canvas.height - 32) / layout.height)) : .2;
724
+ useEffect(() => {
725
+ const inst = rfRef.current;
726
+ if (!ready || !inst || !layoutIdentity || !canvas) return;
727
+ const relayout = framed.current !== cameraKey;
728
+ const preserveView = !relayout;
729
+ if (preserveView && !selection.current) return;
730
+ const animate = framed.current !== null && relayout && animateMotion;
731
+ framed.current = cameraKey;
732
+ const frame = requestAnimationFrame(() => {
733
+ if (preserveView) revealSelection(inst, wrapperRef.current, selection.current);
734
+ else {
735
+ const id = selection.current ?? topology.agentIds[0], position = layout?.positions.get(id), width = inst.getInternalNode(id)?.width ?? card.width;
736
+ const x = layout.width + 32 <= canvas.width ? (canvas.width - layout.width) / 2 : position ? Math.max(FIT_PADDING - position.x, canvas.width / 2 - position.x - width / 2) : FIT_PADDING;
737
+ const y = layout.height + 32 <= canvas.height ? FIT_PADDING : FIT_PADDING - (position?.y ?? 0);
738
+ inst.setViewport({
739
+ x,
740
+ y,
741
+ zoom: 1
742
+ }, { duration: animate ? tokenMilliseconds("--duration-base", wrapperRef.current) : 0 });
743
+ }
744
+ setShown(true);
745
+ });
746
+ return () => cancelAnimationFrame(frame);
747
+ }, [
748
+ ready,
749
+ layoutIdentity,
750
+ cameraKey,
751
+ canvas,
752
+ minZoom,
753
+ animateMotion,
754
+ selectedId
755
+ ]);
756
+ const select = useCallback((id) => {
757
+ if (byId.has(id)) {
758
+ onSelect?.(id);
759
+ wrapperRef.current?.querySelector(`[data-agent-id="${CSS.escape(id)}"]`)?.scrollIntoView({ block: "nearest" });
760
+ }
761
+ }, [byId, onSelect]);
762
+ const handleNodeClick = useCallback((_event, node) => select(node.id), [select]);
763
+ const handleKeyDown = useCallback((event) => {
764
+ if (!(event.target instanceof HTMLElement)) return;
765
+ const id = event.target.closest(".react-flow__node")?.getAttribute("data-id");
766
+ if (!id || !byId.has(id)) return;
767
+ if (event.key === "Escape") {
768
+ event.preventDefault();
769
+ event.stopPropagation();
770
+ wrapperRef.current?.focus();
771
+ return;
772
+ }
773
+ if (!event.target.classList.contains("react-flow__node")) return;
774
+ if (event.key === "Enter" || event.key === " ") {
775
+ event.preventDefault();
776
+ event.stopPropagation();
777
+ select(id);
778
+ return;
779
+ }
780
+ const origin = layout?.positions.get(id);
781
+ const vector = {
782
+ ArrowLeft: [-1, 0],
783
+ ArrowRight: [1, 0],
784
+ ArrowUp: [0, -1],
785
+ ArrowDown: [0, 1]
786
+ }[event.key];
787
+ const target = event.key === "Home" ? topology.agentIds[0] : origin && vector ? [...layout?.positions ?? []].filter(([key, p]) => byId.has(key) && key !== id && (p.x - origin.x) * vector[0] + (p.y - origin.y) * vector[1] > 0).sort((a, b) => Math.hypot(a[1].x - origin.x, a[1].y - origin.y) - Math.hypot(b[1].x - origin.x, b[1].y - origin.y))[0]?.[0] : null;
788
+ if (!target) return;
789
+ event.preventDefault();
790
+ event.stopPropagation();
791
+ const position = layout?.positions.get(target), size = rfRef.current?.getInternalNode(target)?.measured;
792
+ if (position) rfRef.current?.setCenter(position.x + (size?.width ?? card.width) / 2, position.y + (size?.height ?? card.height) / 2, { zoom: 1 });
793
+ const focus = () => wrapperRef.current?.querySelector(`.react-flow__node[data-id="${CSS.escape(target)}"]`);
794
+ const visible = focus();
795
+ if (visible) visible.focus();
796
+ else requestAnimationFrame(() => requestAnimationFrame(() => focus()?.focus()));
797
+ }, [
798
+ byId,
799
+ select,
800
+ layout,
801
+ topology,
802
+ card,
803
+ animateMotion
804
+ ]);
805
+ const activityRank = (agent) => agent.status === "needs-you" ? 0 : agent.status === "failed" ? 1 : agentQuietActivity(agent, clock) ? 2 : agent.status === "waiting" ? 3 : agent.status === "running" ? 4 : 5;
806
+ const parentOf = new Map(edges.filter((e) => e.kind === "spawn").map((e) => [e.to, e.from]));
807
+ const depthOf = (id) => {
808
+ const seen = /* @__PURE__ */ new Set([id]);
809
+ let depth = 0;
810
+ while (parentOf.has(id) && !seen.has(parentOf.get(id))) {
811
+ id = parentOf.get(id);
812
+ seen.add(id);
813
+ depth++;
814
+ }
815
+ return depth;
816
+ };
817
+ const readingOrder = useRef([]), known = new Set(readingOrder.current);
818
+ readingOrder.current = [...readingOrder.current.filter((id) => byId.has(id)), ...nodes.filter((agent) => !known.has(agent.id)).sort((a, b) => activityRank(a) - activityRank(b)).map((agent) => agent.id)];
819
+ const phoneNodes = readingOrder.current.map((id) => byId.get(id));
820
+ useEffect(() => {
821
+ const at = phoneNodes.findIndex((node) => node.id === selectedId);
822
+ if (at >= 0) setPhonePage(Math.floor(at / PHONE_PAGE));
823
+ }, [selectedId]);
824
+ useEffect(() => {
825
+ if (!narrow || !selectedId) return;
826
+ const frame = requestAnimationFrame(() => wrapperRef.current?.querySelector(`[data-agent-id="${CSS.escape(selectedId)}"]`)?.scrollIntoView({ block: "nearest" }));
827
+ return () => cancelAnimationFrame(frame);
828
+ }, [
829
+ selectedId,
830
+ phonePage,
831
+ narrow
832
+ ]);
833
+ const first = Math.min(phonePage * PHONE_PAGE, Math.max(0, Math.ceil(nodes.length / PHONE_PAGE) - 1) * PHONE_PAGE);
834
+ const counts = [
835
+ "needs-you",
836
+ "failed",
837
+ "quiet"
838
+ ].map((status) => {
839
+ const matches = nodes.filter((agent) => status === "quiet" ? agentQuietActivity(agent, clock) : agent.status === status);
840
+ return {
841
+ status,
842
+ matches,
843
+ current: matches.find((agent) => agent.id === selectedId) ?? matches[0]
844
+ };
845
+ });
846
+ const caption = /* @__PURE__ */ jsxs("div", {
847
+ className: "flex min-h-10 shrink-0 flex-wrap items-center gap-x-3 gap-y-1 px-3 py-1 text-xs text-muted-foreground",
848
+ "aria-label": "Run status",
849
+ children: [/* @__PURE__ */ jsxs("span", {
850
+ className: "shrink-0 whitespace-nowrap",
851
+ children: [nodes.length, " agents"]
852
+ }), counts.filter((group) => group.matches.length).map((group) => /* @__PURE__ */ jsxs("button", {
853
+ type: "button",
854
+ className: "ag-status-button rounded-full border border-border px-2 py-1",
855
+ style: { color: group.status === "quiet" ? "var(--surface-warning-text)" : agentStatus(group.status).color },
856
+ onClick: () => {
857
+ const index = group.matches.findIndex((agent) => agent.id === selectedId);
858
+ const next = group.matches[(index + 1) % group.matches.length];
859
+ select(next.id);
860
+ const p = layout?.positions.get(next.id), size = rfRef.current?.getInternalNode(next.id)?.measured;
861
+ if (p) rfRef.current?.setCenter(p.x + (size?.width ?? card.width) / 2, p.y + (size?.height ?? card.height) / 2, {
862
+ zoom: 1,
863
+ duration: animateMotion ? tokenMilliseconds("--duration-base", wrapperRef.current) : 0
864
+ });
865
+ },
866
+ children: [/* @__PURE__ */ jsxs("span", {
867
+ className: "shrink-0",
868
+ children: [
869
+ group.matches.length,
870
+ " ",
871
+ group.status === "needs-you" ? "needs you" : group.status
872
+ ]
873
+ }), /* @__PURE__ */ jsxs("span", {
874
+ className: "ag-caption-target",
875
+ children: [group.current.label, group.status === "failed" && /* @__PURE__ */ jsxs("span", {
876
+ className: "font-normal",
877
+ children: [" · ", group.current.result ?? group.current.turn ?? "Failure cause not recorded"]
878
+ })]
879
+ })]
880
+ }, group.status))]
881
+ });
882
+ if (nodes.length === 0) return /* @__PURE__ */ jsx("div", {
883
+ className: `agent-graph flex items-center justify-center rounded-lg border border-border border-dashed p-4 text-center text-muted-foreground text-xs ${className ?? ""}`,
884
+ children: emptyState ?? "No agents yet"
885
+ });
886
+ return /* @__PURE__ */ jsxs("div", {
887
+ ref: (el) => {
888
+ wrapperRef.current = el;
889
+ measureCanvas(el);
890
+ },
891
+ className: `agent-graph ag-live relative flex flex-col ${className ?? ""}`,
892
+ tabIndex: -1,
893
+ onKeyDownCapture: (event) => {
894
+ if (event.target instanceof HTMLElement && event.target.closest("[data-agent-metrics]")) return;
895
+ if (event.key === "Tab" && !event.shiftKey && hovered) {
896
+ event.preventDefault();
897
+ document.getElementById(detailsId)?.focus();
898
+ return;
899
+ }
900
+ if (event.key === "Escape") hideDetails();
901
+ handleKeyDown(event);
902
+ },
903
+ onFocusCapture: (event) => {
904
+ if (!(event.target instanceof HTMLElement) || returningFocus.current) return;
905
+ keepDetails();
906
+ if (event.target.closest("[data-agent-metrics]")) return;
907
+ if (!event.target.matches(":focus-visible")) {
908
+ hideDetails();
909
+ return;
910
+ }
911
+ const node = event.target.closest(".react-flow__node, [data-agent-id]");
912
+ const id = node?.dataset.id ?? node?.dataset.agentId;
913
+ hoverTarget.current = node ?? null;
914
+ setHovered(id && byId.has(id) ? {
915
+ id,
916
+ rect: node.getBoundingClientRect()
917
+ } : null);
918
+ },
919
+ onBlurCapture: (event) => {
920
+ if (!event.currentTarget.contains(event.relatedTarget) && event.relatedTarget?.id !== detailsId) hideDetails();
921
+ },
922
+ "data-layout": narrow ? "list" : layout && shown ? "ready" : "pending",
923
+ "data-columns": layout?.columns,
924
+ children: [
925
+ caption,
926
+ showLatestEvents && live && /* @__PURE__ */ jsx(LatestEvents, {
927
+ agents: nodes,
928
+ now,
929
+ live,
930
+ selectedId,
931
+ onSelect: onSelect ? select : void 0
932
+ }),
933
+ narrow ? /* @__PURE__ */ jsxs("ul", {
934
+ className: "ag-graph-viewport ag-phone-list overflow-auto",
935
+ "aria-label": "Agents by attention",
936
+ children: [phoneNodes.slice(first, first + PHONE_PAGE).map((agent) => /* @__PURE__ */ jsx("li", {
937
+ style: { ["--depth"]: depthOf(agent.id) },
938
+ children: /* @__PURE__ */ jsx("div", {
939
+ role: "button",
940
+ tabIndex: 0,
941
+ "aria-pressed": selectedId === agent.id,
942
+ "aria-label": agentDescription(agent),
943
+ "data-agent-id": agent.id,
944
+ className: "ag-phone-select",
945
+ onClick: () => select(agent.id),
946
+ onKeyDown: (e) => {
947
+ if ((e.key === "Enter" || e.key === " ") && e.target === e.currentTarget) {
948
+ e.preventDefault();
949
+ select(agent.id);
950
+ }
951
+ },
952
+ children: live || agent.status === "succeeded" || agent.status === "stopped" ? /* @__PURE__ */ jsx(LiveAgentCardView, {
953
+ agent,
954
+ parentLabel: byId.get(parentOf.get(agent.id) ?? "")?.label,
955
+ selected: selectedId === agent.id,
956
+ now: clock,
957
+ renderEventIcon,
958
+ onOpen: onSelect ? () => select(agent.id) : void 0
959
+ }) : /* @__PURE__ */ jsx(AgentCardView, {
960
+ agent,
961
+ parentLabel: byId.get(parentOf.get(agent.id) ?? "")?.label,
962
+ selected: selectedId === agent.id,
963
+ now: clock,
964
+ direction,
965
+ onOpen: onSelect ? () => select(agent.id) : void 0
966
+ })
967
+ })
968
+ }, agent.id)), nodes.length > PHONE_PAGE && /* @__PURE__ */ jsxs("li", {
969
+ className: "flex items-center justify-between gap-2 border-t border-border pt-3 text-sm",
970
+ "aria-label": "Agent pages",
971
+ children: [
972
+ /* @__PURE__ */ jsx("button", {
973
+ type: "button",
974
+ className: "rounded px-2 py-1 hover:bg-muted disabled:opacity-40 focus-visible:outline",
975
+ disabled: !first,
976
+ onClick: () => {
977
+ setPhonePage((page) => page - 1);
978
+ wrapperRef.current?.querySelector(".ag-phone-list")?.scrollTo({ top: 0 });
979
+ },
980
+ children: "Previous"
981
+ }),
982
+ /* @__PURE__ */ jsxs("span", { children: [
983
+ first + 1,
984
+ "–",
985
+ Math.min(nodes.length, first + PHONE_PAGE),
986
+ " of ",
987
+ nodes.length
988
+ ] }),
989
+ /* @__PURE__ */ jsx("button", {
990
+ type: "button",
991
+ className: "rounded px-2 py-1 hover:bg-muted disabled:opacity-40 focus-visible:outline",
992
+ disabled: first + PHONE_PAGE >= nodes.length,
993
+ onClick: () => {
994
+ setPhonePage((page) => page + 1);
995
+ wrapperRef.current?.querySelector(".ag-phone-list")?.scrollTo({ top: 0 });
996
+ },
997
+ children: "Next"
998
+ })
999
+ ]
1000
+ })]
1001
+ }) : /* @__PURE__ */ jsx("div", {
1002
+ className: "ag-graph-viewport min-h-0 flex-1",
1003
+ style: { opacity: shown ? 1 : 0 },
1004
+ children: /* @__PURE__ */ jsxs(ReactFlow, {
1005
+ nodes: flowNodes,
1006
+ edges: flowEdges,
1007
+ nodeTypes: NODE_TYPES,
1008
+ edgeTypes: EDGE_TYPES,
1009
+ colorMode,
1010
+ onInit: (inst) => {
1011
+ rfRef.current = inst;
1012
+ setReady(true);
1013
+ },
1014
+ onNodeClick: handleNodeClick,
1015
+ onNodeMouseEnter: (event, node) => {
1016
+ keepDetails();
1017
+ hoverTarget.current = event.target.closest(".react-flow__node");
1018
+ if (hoverTarget.current) setHovered({
1019
+ id: node.id,
1020
+ rect: hoverTarget.current.getBoundingClientRect()
1021
+ });
1022
+ },
1023
+ onNodeMouseLeave: leaveDetails,
1024
+ proOptions: { hideAttribution: true },
1025
+ onlyRenderVisibleElements: true,
1026
+ nodesDraggable: false,
1027
+ nodesConnectable: false,
1028
+ elementsSelectable: false,
1029
+ nodesFocusable: true,
1030
+ edgesFocusable: false,
1031
+ deleteKeyCode: null,
1032
+ panOnScroll: true,
1033
+ zoomOnScroll: false,
1034
+ zoomOnPinch: true,
1035
+ zoomOnDoubleClick: false,
1036
+ panOnDrag: true,
1037
+ minZoom,
1038
+ maxZoom: 1.75,
1039
+ "aria-label": "Agent topology",
1040
+ children: [
1041
+ /* @__PURE__ */ jsx(Background, {
1042
+ bgColor: "var(--bg-root)",
1043
+ gap: 16,
1044
+ size: 1,
1045
+ color: "hsl(var(--foreground) / 0.06)"
1046
+ }),
1047
+ layout && canvas && (layout.width > canvas.width || layout.height > canvas.height) && /* @__PURE__ */ jsx(MiniMap, {
1048
+ pannable: true,
1049
+ zoomable: true,
1050
+ position: "bottom-left",
1051
+ style: {
1052
+ width: 168,
1053
+ height: 104
1054
+ },
1055
+ className: "!hidden sm:!block",
1056
+ ariaLabel: "Agent topology overview"
1057
+ }),
1058
+ /* @__PURE__ */ jsx(Controls, {
1059
+ showInteractive: false,
1060
+ position: "bottom-right",
1061
+ fitViewOptions: {
1062
+ padding: `${FIT_PADDING}px`,
1063
+ maxZoom: 1
1064
+ }
1065
+ })
1066
+ ]
1067
+ })
1068
+ }),
1069
+ hovered && byId.has(hovered.id) && /* @__PURE__ */ jsx(AgentMetrics, {
1070
+ anchor: wrapperRef.current,
1071
+ mode: colorMode,
1072
+ id: detailsId,
1073
+ agent: byId.get(hovered.id),
1074
+ rect: hovered.rect,
1075
+ onEnter: keepDetails,
1076
+ onLeave: leaveDetails,
1077
+ onClose: () => {
1078
+ hideDetails();
1079
+ returningFocus.current = true;
1080
+ hoverTarget.current?.focus({ preventScroll: true });
1081
+ returningFocus.current = false;
1082
+ }
1083
+ })
1084
+ ]
1085
+ });
1086
+ }
1087
+ /** Metrics stay at reading size outside the zoomed canvas and its clipping container. */
1088
+ function AgentMetrics({ anchor, mode, id, agent, rect, onEnter, onLeave, onClose }) {
1089
+ const [theme, setTheme] = useState({});
1090
+ useLayoutEffect(() => {
1091
+ if (!anchor) return;
1092
+ const read = () => {
1093
+ const css = getComputedStyle(anchor);
1094
+ setTheme(Object.fromEntries(Array.from(css).filter((name) => name.startsWith("--") && !name.startsWith("--tw-")).map((name) => [name, css.getPropertyValue(name)])));
1095
+ };
1096
+ read();
1097
+ const observer = new MutationObserver(read);
1098
+ for (let el = anchor; el; el = el.parentElement) observer.observe(el, {
1099
+ attributes: true,
1100
+ attributeFilter: [
1101
+ "class",
1102
+ "style",
1103
+ "data-theme",
1104
+ "data-sandbox-theme"
1105
+ ]
1106
+ });
1107
+ return () => observer.disconnect();
1108
+ }, [anchor]);
1109
+ const facts = new Map([
1110
+ {
1111
+ label: "Tokens",
1112
+ value: fmtTokenTotal(agent.tokens) ?? "Not recorded"
1113
+ },
1114
+ {
1115
+ label: "Cost",
1116
+ value: fmtCost(agent.costUsd ?? void 0) ?? "Not recorded"
1117
+ },
1118
+ ...agent.facts ?? []
1119
+ ].map((fact) => [fact.label.toLowerCase(), fact]));
1120
+ const width = Math.min(420, window.innerWidth - 24), height = Math.min(560, window.innerHeight - 24);
1121
+ const left = Math.max(12, Math.min(rect.right + 12 + width <= window.innerWidth ? rect.right + 12 : rect.left - width - 12, window.innerWidth - width - 12));
1122
+ return createPortal(/* @__PURE__ */ jsxs("div", {
1123
+ id,
1124
+ "data-agent-metrics": true,
1125
+ "data-theme": anchor?.closest("[data-theme]")?.getAttribute("data-theme") ?? mode,
1126
+ role: "tooltip",
1127
+ tabIndex: 0,
1128
+ onMouseEnter: onEnter,
1129
+ onMouseLeave: onLeave,
1130
+ onWheel: (event) => event.stopPropagation(),
1131
+ onBlur: onLeave,
1132
+ onKeyDown: (event) => {
1133
+ if (event.key === "Escape") {
1134
+ event.preventDefault();
1135
+ onClose();
1136
+ }
1137
+ },
1138
+ className: `${mode} rounded-xl border border-border bg-card p-4 text-sm text-foreground shadow-xl`,
1139
+ style: {
1140
+ ...theme,
1141
+ colorScheme: mode,
1142
+ position: "fixed",
1143
+ zIndex: 1e3,
1144
+ width,
1145
+ maxHeight: height,
1146
+ overflow: "auto",
1147
+ left,
1148
+ top: Math.max(12, Math.min(rect.top, window.innerHeight - height - 12))
1149
+ },
1150
+ children: [
1151
+ /* @__PURE__ */ jsxs("div", {
1152
+ className: "mb-2 flex items-center justify-between gap-3",
1153
+ children: [/* @__PURE__ */ jsx("strong", { children: agent.label }), /* @__PURE__ */ jsx("span", { children: agentStatus(agent.status).label })]
1154
+ }),
1155
+ /* @__PURE__ */ jsx("p", {
1156
+ className: "mb-3 text-muted-foreground",
1157
+ children: [
1158
+ agent.model,
1159
+ agent.harness,
1160
+ agent.role
1161
+ ].filter(Boolean).join(" · ")
1162
+ }),
1163
+ /* @__PURE__ */ jsx("dl", {
1164
+ className: "grid grid-cols-[minmax(0,1fr)_auto] gap-x-5 gap-y-1.5",
1165
+ children: [...facts.values()].map((fact) => /* @__PURE__ */ jsxs("div", {
1166
+ className: "contents",
1167
+ children: [/* @__PURE__ */ jsx("dt", {
1168
+ className: "min-w-0 break-words text-muted-foreground",
1169
+ children: fact.label
1170
+ }), /* @__PURE__ */ jsx("dd", {
1171
+ className: "m-0 min-w-0 max-w-64 whitespace-normal break-words text-right tabular-nums",
1172
+ children: fact.value
1173
+ })]
1174
+ }, fact.label))
1175
+ }),
1176
+ agent.status === "failed" && /* @__PURE__ */ jsx("p", {
1177
+ className: "mt-3 whitespace-pre-wrap break-words text-[var(--surface-danger-text)]",
1178
+ children: agent.result ?? agent.turn ?? "Failure cause not recorded"
1179
+ })
1180
+ ]
1181
+ }), document.body);
1182
+ }
1183
+ //#endregion
1184
+ export { AgentGraphCanvas };