ai-engineering-loop 2.0.0 → 2.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.
package/studio/app.js CHANGED
@@ -1,9 +1,22 @@
1
1
  'use strict';
2
2
 
3
- const NODE_WIDTH = 224;
4
- const NODE_PORT_Y = 54;
3
+ const NODE_WIDTH = 104;
4
+ const NODE_PORT_Y = 52;
5
+ const NODE_BLOCK_HEIGHT = 152;
6
+ const FIT_PADDING = 48;
7
+ const PANEL_WIDTH = 480;
8
+ const TOOLTIP_DELAY_MS = 250;
9
+ const MINIMAP_WIDTH = 180;
10
+ const MINIMAP_HEIGHT = 110;
11
+ const LABEL_BLEED = 36;
5
12
  const MIN_ZOOM = 0.2;
6
13
  const MAX_ZOOM = 2.5;
14
+ const WHEEL_LINE_PX = 16;
15
+ const WHEEL_PAGE_PX = 800;
16
+ const WHEEL_SPIKE_PX = 240;
17
+ const PAN_THRESHOLD_PX = 4;
18
+ const COLUMN_PITCH = 188;
19
+ const ROW_PITCH = 200;
7
20
  const DISPLAY_NAME_MAX = 80;
8
21
  const STAGES = [
9
22
  { id: 'goal', label: 'goal', types: ['goal-contract'] },
@@ -40,6 +53,11 @@ let selectedId;
40
53
  let selectedIds = new Set();
41
54
  let selectedEdgeId;
42
55
  let validationSequence = 0;
56
+ let validationState = { status: 'pending', hash: '', issues: [], extraCodes: [] };
57
+ let invalidEdgeIds = new Set();
58
+ let edgeIssues = new Map();
59
+ let loadedEdges = [];
60
+ let loadedEdgeSignature = '';
43
61
  let positions = new Map();
44
62
  let viewport = { x: 0, y: 0, scale: 1 };
45
63
  let history = [];
@@ -47,6 +65,9 @@ let historyIndex = -1;
47
65
  let interaction;
48
66
  let connection;
49
67
  let layoutTimer;
68
+ let hasFitted = false;
69
+ let resizeFitTimer;
70
+ let edgeHideTimer;
50
71
  let spacePressed = false;
51
72
  let runs = [];
52
73
  let goal = { text: '', version: 1, frozen: false, draftRevision: 0, draftHash: null };
@@ -67,6 +88,20 @@ let liveRenderScheduled = false;
67
88
  let reconnectTimer = null;
68
89
  let reconnectAttempt = 0;
69
90
  let resumeFallbackUsed = false;
91
+ let panelNodeId = null;
92
+ let panelTab = 'overview';
93
+ let panelRequest = 0;
94
+ let panelView = { status: 'empty' };
95
+ let tooltipTimer = null;
96
+ let suppressNodeClick = false;
97
+ let wheelFrame = null;
98
+ let wheelPending = null;
99
+ let marquee = null;
100
+ let gestureZoom = null;
101
+ let zoomInButton = null;
102
+ let zoomLevelOutput = null;
103
+ let nodeTooltip = null;
104
+ let minimap = null;
70
105
  const RECONNECT_BACKOFF_MS = [500, 1000, 2000, 5000];
71
106
 
72
107
  function graphStateClass(value) {
@@ -175,7 +210,7 @@ function defaultGraphPositions() {
175
210
  const depth = depthFor(node);
176
211
  const row = rows.get(depth) || 0;
177
212
  rows.set(depth, row + 1);
178
- return [node.id, { x: 80 + depth * 270, y: 110 + row * 150 }];
213
+ return [node.id, { x: 48 + depth * COLUMN_PITCH, y: 56 + row * ROW_PITCH }];
179
214
  }));
180
215
  }
181
216
 
@@ -198,6 +233,8 @@ function applyViewport() {
198
233
  canvas.style.backgroundPosition = `${viewport.x}px ${viewport.y}px`;
199
234
  canvas.style.backgroundSize = `${32 * viewport.scale}px ${32 * viewport.scale}px`;
200
235
  }
236
+ updateZoomLabel();
237
+ renderMinimap();
201
238
  }
202
239
 
203
240
  function screenToWorld(clientX, clientY) {
@@ -208,26 +245,100 @@ function screenToWorld(clientX, clientY) {
208
245
  };
209
246
  }
210
247
 
248
+ function curveBend(x1, x2) {
249
+ return Math.max(48, Math.abs(x2 - x1) * 0.45);
250
+ }
251
+
252
+ function curvePath(x1, y1, x2, y2) {
253
+ const bend = curveBend(x1, x2);
254
+ return `M${x1} ${y1} C${x1 + bend} ${y1},${x2 - bend} ${y2},${x2} ${y2}`;
255
+ }
256
+
257
+ function pointOnCurve(x1, y1, x2, y2, t) {
258
+ const bend = curveBend(x1, x2);
259
+ const u = 1 - t;
260
+ return {
261
+ x: u * u * u * x1 + 3 * u * u * t * (x1 + bend) + 3 * u * t * t * (x2 - bend) + t * t * t * x2,
262
+ y: u * u * u * y1 + 3 * u * u * t * y1 + 3 * u * t * t * y2 + t * t * t * y2
263
+ };
264
+ }
265
+
211
266
  function edgePath(from, to) {
212
- const startX = from.x + NODE_WIDTH;
213
- const startY = from.y + NODE_PORT_Y;
214
- const endX = to.x;
215
- const endY = to.y + NODE_PORT_Y;
216
- const bend = Math.max(55, Math.abs(endX - startX) * 0.42);
217
- return `M${startX} ${startY} C${startX + bend} ${startY},${endX - bend} ${endY},${endX} ${endY}`;
267
+ return curvePath(from.x + NODE_WIDTH, from.y + NODE_PORT_Y, to.x, to.y + NODE_PORT_Y);
268
+ }
269
+
270
+ function edgeEndpoints(from, to) {
271
+ return {
272
+ x1: from.x + NODE_WIDTH,
273
+ y1: from.y + NODE_PORT_Y,
274
+ x2: to.x,
275
+ y2: to.y + NODE_PORT_Y
276
+ };
218
277
  }
219
278
 
220
279
  function loopBounds(loopGroup) {
221
280
  const points = loopGroup.nodeIds.map((nodeId) => positions.get(nodeId)).filter(Boolean);
222
281
  if (!points.length) return null;
223
- const padding = 44;
224
- const left = Math.min(...points.map((point) => point.x)) - padding;
225
- const top = Math.min(...points.map((point) => point.y)) - padding;
226
- const right = Math.max(...points.map((point) => point.x + NODE_WIDTH)) + padding;
227
- const bottom = Math.max(...points.map((point) => point.y + 108)) + padding;
282
+ const padX = 46;
283
+ const padTop = 58;
284
+ const padBottom = 28;
285
+ const left = Math.min(...points.map((point) => point.x)) - padX;
286
+ const top = Math.min(...points.map((point) => point.y)) - padTop;
287
+ const right = Math.max(...points.map((point) => point.x + NODE_WIDTH)) + padX;
288
+ const bottom = Math.max(...points.map((point) => point.y + NODE_BLOCK_HEIGHT)) + padBottom;
228
289
  return { left, top, right, bottom, width: right - left, height: bottom - top };
229
290
  }
230
291
 
292
+ function loopLabelText(loopGroup, runtime) {
293
+ const iteration = runtime?.iteration ?? 1;
294
+ return `${loopGroup.displayName} · iteration ${iteration} / ${loopGroup.maxIterations}`;
295
+ }
296
+
297
+ function loopLabelOverlapsEdge(rect) {
298
+ for (const edge of draft?.edges || []) {
299
+ const from = positions.get(edge.from);
300
+ const to = positions.get(edge.to);
301
+ if (!from || !to) continue;
302
+ const { x1, y1, x2, y2 } = edgeEndpoints(from, to);
303
+ for (let step = 0; step <= 8; step += 1) {
304
+ const point = pointOnCurve(x1, y1, x2, y2, step / 8);
305
+ if (point.x >= rect.left && point.x <= rect.right && point.y >= rect.top && point.y <= rect.bottom) {
306
+ return true;
307
+ }
308
+ }
309
+ }
310
+ return false;
311
+ }
312
+
313
+ function placeLoopLabel(bounds, label) {
314
+ const height = 26;
315
+ const width = Math.min(Math.max(bounds.width - 24, 80), 16 + String(label).length * 7.1);
316
+ const centerLeft = bounds.left + (bounds.width - width) / 2;
317
+ const candidates = [
318
+ { left: centerLeft, top: bounds.top - height / 2 },
319
+ { left: centerLeft, top: bounds.top - height - 10 },
320
+ { left: bounds.left + 12, top: bounds.top - height - 10 },
321
+ { left: bounds.right - width - 12, top: bounds.top - height - 10 },
322
+ { left: centerLeft, top: bounds.bottom + 10 }
323
+ ];
324
+ for (const candidate of candidates) {
325
+ const rect = {
326
+ left: candidate.left,
327
+ top: candidate.top,
328
+ right: candidate.left + width,
329
+ bottom: candidate.top + height
330
+ };
331
+ if (!loopLabelOverlapsEdge(rect)) return rect;
332
+ }
333
+ const fallback = candidates[1];
334
+ return {
335
+ left: fallback.left,
336
+ top: fallback.top,
337
+ right: fallback.left + width,
338
+ bottom: fallback.top + height
339
+ };
340
+ }
341
+
231
342
  function renderLoopGroups() {
232
343
  const container = scenePart('.loop-groups');
233
344
  container.innerHTML = '';
@@ -235,28 +346,29 @@ function renderLoopGroups() {
235
346
  const bounds = loopBounds(loopGroup);
236
347
  if (!bounds) continue;
237
348
  const runtime = catalog.live?.loopGroups?.[loopGroup.id];
349
+ const label = loopLabelText(loopGroup, runtime);
350
+ const rect = placeLoopLabel(bounds, label);
238
351
  const element = document.createElement('section');
239
352
  element.className = `loop-group ${runtime?.status?.toLowerCase() || 'draft'}`;
240
353
  element.style.left = `${bounds.left}px`;
241
354
  element.style.top = `${bounds.top}px`;
242
355
  element.style.width = `${bounds.width}px`;
243
356
  element.style.height = `${bounds.height}px`;
244
- element.innerHTML = `
245
- <header>
246
- <span><b>${escapeHtml(loopGroup.displayName)}</b><small>ITERATION ${escapeHtml(runtime?.iteration || 1)} / ${escapeHtml(loopGroup.maxIterations)}</small></span>
247
- </header>
248
- `;
357
+ // CSP style-src 'self' blocks inline style attributes; position the pill through the CSSOM.
358
+ const pill = document.createElement('header');
359
+ pill.className = 'loop-pill';
360
+ pill.textContent = label;
361
+ if (pill.style) {
362
+ pill.style.left = `${rect.left - bounds.left}px`;
363
+ pill.style.top = `${rect.top - bounds.top}px`;
364
+ pill.style.width = `${Math.max(0, rect.right - rect.left)}px`;
365
+ }
366
+ element.replaceChildren?.(pill);
367
+ if (!element.replaceChildren) element.innerHTML = `<header class="loop-pill">${escapeHtml(label)}</header>`;
249
368
  container.append(element);
250
369
  }
251
370
  }
252
371
 
253
- function edgeLoopLabel(edge) {
254
- const loopGroup = (draft.loopGroups || []).find((candidate) =>
255
- candidate.decisionNodeId === edge.from && candidate.exitTargetId === edge.to
256
- );
257
- return loopGroup ? loopGroup.exitLabel : '';
258
- }
259
-
260
372
  function stageLabel(node, index) {
261
373
  const stages = {
262
374
  'goal-contract': 'STAGE 01',
@@ -271,6 +383,55 @@ function stageLabel(node, index) {
271
383
  return stages[node.type] || `STEP ${String(index + 1).padStart(2, '0')}`;
272
384
  }
273
385
 
386
+ function edgeClassName(edge) {
387
+ const state = graphStateClass(catalog.live?.edges?.find((candidate) => candidate.id === edge.id)?.state);
388
+ const intoRunning = graphStateClass(catalog.live?.nodes?.[edge.to]?.status) === 'active';
389
+ const active = state === 'active' || intoRunning;
390
+ const invalid = invalidEdgeIds.has(edge.id) ? ' edge-invalid' : '';
391
+ return `edge edge-${state}${active ? ' edge-active' : ''}${selectedEdgeId === edge.id ? ' selected' : ''}${invalid}`;
392
+ }
393
+
394
+ function edgeDeleteClass(edge) {
395
+ return `edge-delete${selectedEdgeId === edge.id ? ' selected' : ''}`;
396
+ }
397
+
398
+ function bindEdgeAffordance(path, control, handles, edgeId) {
399
+ const show = () => {
400
+ clearTimeout(edgeHideTimer);
401
+ control.classList.add('visible');
402
+ control.setAttribute('aria-hidden', 'false');
403
+ handles.forEach((handle) => handle.classList.add('visible'));
404
+ };
405
+ const scheduleHide = () => {
406
+ clearTimeout(edgeHideTimer);
407
+ edgeHideTimer = setTimeout(() => {
408
+ if (selectedEdgeId !== edgeId) {
409
+ control.classList.remove('visible');
410
+ control.setAttribute('aria-hidden', 'true');
411
+ handles.forEach((handle) => handle.classList.remove('visible'));
412
+ }
413
+ }, 160);
414
+ };
415
+ path.addEventListener('pointerenter', show);
416
+ path.addEventListener('pointerleave', scheduleHide);
417
+ control.addEventListener('pointerenter', show);
418
+ control.addEventListener('pointerleave', scheduleHide);
419
+ handles.forEach((handle) => {
420
+ handle.addEventListener('pointerenter', show);
421
+ handle.addEventListener('pointerleave', scheduleHide);
422
+ });
423
+ path.addEventListener('pointerdown', (event) => {
424
+ if (event.button !== 0) return;
425
+ event.stopPropagation();
426
+ event.preventDefault();
427
+ selectedEdgeId = edgeId;
428
+ selectedId = null;
429
+ selectedIds = new Set();
430
+ updateSelection();
431
+ renderEdges();
432
+ });
433
+ }
434
+
274
435
  function renderEdges() {
275
436
  const group = scenePart('.edge-paths');
276
437
  const controls = scenePart('.edge-controls');
@@ -279,63 +440,322 @@ function renderEdges() {
279
440
  controls.innerHTML = '';
280
441
  if (preview?.style && preview !== byId('scene')) preview.setAttribute?.('d', preview.getAttribute?.('d') || '');
281
442
  if (!draft) return;
443
+ clearTimeout(edgeHideTimer);
282
444
  draft.edges.forEach((edge) => {
283
445
  const from = positions.get(edge.from);
284
446
  const to = positions.get(edge.to);
285
447
  if (!from || !to) return;
286
448
  const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
287
449
  path.setAttribute('d', edgePath(from, to));
288
- const state = graphStateClass(catalog.live?.edges?.find((candidate) => candidate.id === edge.id)?.state);
289
- path.setAttribute(
290
- 'class',
291
- `edge edge-${state}${selectedEdgeId === edge.id ? ' selected' : ''}`
292
- );
450
+ path.setAttribute('class', edgeClassName(edge));
293
451
  path.setAttribute('marker-end', 'url(#arrow)');
294
452
  path.dataset.edgeId = edge.id;
295
453
  group.append(path);
296
- const midpoint = {
297
- x: (from.x + NODE_WIDTH + to.x) / 2,
298
- y: (from.y + to.y) / 2 + NODE_PORT_Y
299
- };
454
+ const ends = edgeEndpoints(from, to);
455
+ const midpoint = pointOnCurve(ends.x1, ends.y1, ends.x2, ends.y2, 0.5);
300
456
  const control = document.createElement('button');
301
- control.className = `edge-delete${selectedEdgeId === edge.id ? ' selected' : ''}`;
457
+ control.type = 'button';
458
+ control.className = edgeDeleteClass(edge);
302
459
  control.dataset.edgeId = edge.id;
303
460
  control.style.left = `${midpoint.x}px`;
304
461
  control.style.top = `${midpoint.y}px`;
462
+ control.tabIndex = -1;
305
463
  control.title = `${displayName(draft.nodes.find((node) => node.id === edge.from))} → ${displayName(draft.nodes.find((node) => node.id === edge.to))}`;
306
464
  control.setAttribute('aria-label', `Delete connection ${control.title}`);
465
+ control.setAttribute('aria-hidden', selectedEdgeId === edge.id ? 'false' : 'true');
307
466
  control.textContent = '×';
308
467
  control.onclick = (event) => {
309
468
  event.stopPropagation();
310
469
  deleteEdge(edge.id);
311
470
  };
312
- controls.append(control);
313
- const label = edgeLoopLabel(edge);
314
- if (label) {
315
- const badge = document.createElement('span');
316
- badge.className = 'edge-label';
317
- badge.style.left = `${midpoint.x}px`;
318
- badge.style.top = `${midpoint.y - 22}px`;
319
- badge.textContent = label;
320
- controls.append(badge);
471
+ const handles = [
472
+ edgeHandle(edge, 'from', ends.x1, ends.y1),
473
+ edgeHandle(edge, 'to', ends.x2, ends.y2)
474
+ ];
475
+ bindEdgeAffordance(path, control, handles, edge.id);
476
+ controls.append(control, ...handles);
477
+ const issue = edgeIssueText(edge.id);
478
+ if (issue) {
479
+ const note = document.createElement('p');
480
+ note.className = 'edge-error';
481
+ note.textContent = issue;
482
+ if (note.style) {
483
+ note.style.left = `${midpoint.x}px`;
484
+ note.style.top = `${midpoint.y}px`;
485
+ }
486
+ controls.append(note);
321
487
  }
322
488
  });
489
+ renderMinimap();
490
+ }
491
+
492
+ function edgeHandle(edge, end, x, y) {
493
+ const handle = document.createElement('button');
494
+ handle.type = 'button';
495
+ handle.className = `edge-end edge-end-${end}${selectedEdgeId === edge.id ? ' visible' : ''}`;
496
+ handle.dataset.edgeId = edge.id;
497
+ handle.dataset.end = end;
498
+ handle.tabIndex = -1;
499
+ handle.setAttribute('aria-label', end === 'to'
500
+ ? `Reposition end of ${edge.from} to ${edge.to}`
501
+ : `Reposition start of ${edge.from} to ${edge.to}`);
502
+ if (handle.style) {
503
+ handle.style.left = `${x}px`;
504
+ handle.style.top = `${y}px`;
505
+ }
506
+ handle.addEventListener('pointerdown', (event) => {
507
+ if (event.button !== 0) return;
508
+ event.preventDefault();
509
+ event.stopPropagation();
510
+ selectedEdgeId = edge.id;
511
+ selectedId = null;
512
+ selectedIds = new Set();
513
+ connection = {
514
+ pointerId: event.pointerId,
515
+ edgeId: edge.id,
516
+ end,
517
+ sourceId: end === 'to' ? edge.from : null,
518
+ fixedId: end === 'to' ? edge.from : edge.to
519
+ };
520
+ const preview = scenePart('.preview-edge');
521
+ if (preview?.style) preview.style.display = 'block';
522
+ handle.setPointerCapture?.(event.pointerId);
523
+ });
524
+ return handle;
525
+ }
526
+
527
+ function edgeIssueText(edgeId) {
528
+ return (edgeIssues.get(edgeId) || []).map(issueText).filter(Boolean).join('; ');
529
+ }
530
+
531
+ const NODE_ICONS = {
532
+ 'goal-contract': '<circle cx="12" cy="12" r="7.2" fill="none" stroke="currentColor" stroke-width="1.8"/><circle cx="12" cy="12" r="3.1" fill="none" stroke="currentColor" stroke-width="1.8"/><circle cx="12" cy="12" r="1.2" fill="currentColor"/>',
533
+ maker: '<path d="M9 7 4 12l5 5M15 7l5 5-5 5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>',
534
+ verification: '<rect x="6" y="3.8" width="12" height="16.4" rx="2" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M9 12.2 11.2 14.4 15.2 10.2" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>',
535
+ 'devil-advocate': '<path d="M12 3.2 19.2 6v5.4c0 4.3-2.9 7.2-7.2 8.8-4.3-1.6-7.2-4.5-7.2-8.8V6Z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/><path d="M12 8.2v4.4M12 15.4v.4" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>',
536
+ judge: '<path d="M12 3.5v16.5M6.5 20h11M3.5 8h17" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/><path d="M3.5 8 1.8 14h4.2ZM20.5 8l1.7 6h-4.2" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>',
537
+ approval: '<circle cx="12" cy="8" r="3.1" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M5.2 19.2c.9-3.5 3.2-5.2 6.8-5.2s5.9 1.7 6.8 5.2" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>',
538
+ delivery: '<path d="M12 4v10.2M8 10.2 12 14.4l4-4.2M5 19.8h14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>',
539
+ report: '<path d="M7 3.2h7.2L18.2 7.2V20.8H7Z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/><path d="M14 3.2V7.4h4.2M9.2 12h6M9.2 15.8h6" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/>',
540
+ agent: '<rect x="4.8" y="7" width="14.4" height="10.6" rx="3" fill="none" stroke="currentColor" stroke-width="1.8"/><circle cx="9.4" cy="12.2" r="1.1" fill="currentColor"/><circle cx="14.6" cy="12.2" r="1.1" fill="currentColor"/><path d="M12 7V4.2M8 17.6v1.6M16 17.6v1.6" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>',
541
+ command: '<rect x="3.2" y="4.6" width="17.6" height="14.2" rx="2" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M7 9.6 9.8 12.2 7 14.8M12 14.8h5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>',
542
+ generic: '<rect x="5" y="5" width="14" height="14" rx="3.5" fill="none" stroke="currentColor" stroke-width="1.8"/><circle cx="12" cy="12" r="2.2" fill="currentColor"/>'
543
+ };
544
+
545
+ function nodeIcon(type) {
546
+ const body = NODE_ICONS[type] || NODE_ICONS.generic;
547
+ return `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">${body}</svg>`;
548
+ }
549
+
550
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
551
+
552
+ function formatDuration(ms) {
553
+ if (!Number.isFinite(ms) || ms <= 0) return '';
554
+ const totalSeconds = Math.round(ms / 1000);
555
+ if (totalSeconds <= 0) return '';
556
+ const hours = Math.floor(totalSeconds / 3600);
557
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
558
+ const seconds = totalSeconds % 60;
559
+ if (hours > 0) return `${hours}h ${String(minutes).padStart(2, '0')}m`;
560
+ if (minutes > 0) return `${minutes}m ${String(seconds).padStart(2, '0')}s`;
561
+ return `${seconds}s`;
562
+ }
563
+
564
+ function parsedTime(value) {
565
+ const ms = Date.parse(value || '');
566
+ return Number.isFinite(ms) ? ms : null;
567
+ }
568
+
569
+ function padTime(value) {
570
+ return String(value).padStart(2, '0');
571
+ }
572
+
573
+ function clockTime(date, withSeconds = false) {
574
+ const clock = `${padTime(date.getHours())}:${padTime(date.getMinutes())}`;
575
+ return withSeconds ? `${clock}:${padTime(date.getSeconds())}` : clock;
576
+ }
577
+
578
+ function monthDay(date, withYear) {
579
+ const base = `${MONTHS[date.getMonth()]} ${date.getDate()}`;
580
+ return withYear ? `${base}, ${date.getFullYear()}` : base;
581
+ }
582
+
583
+ function calendarDayStart(ms) {
584
+ const date = new Date(ms);
585
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
586
+ }
587
+
588
+ function timeZoneName(date) {
589
+ try {
590
+ if (typeof Intl === 'undefined' || typeof Intl.DateTimeFormat !== 'function') return '';
591
+ const parts = new Intl.DateTimeFormat('en-US', { timeZoneName: 'short' }).formatToParts(date);
592
+ return parts.find((part) => part.type === 'timeZoneName')?.value || '';
593
+ } catch {
594
+ return '';
595
+ }
596
+ }
597
+
598
+ function humanizeTime(value, now = Date.now()) {
599
+ const ms = parsedTime(value);
600
+ if (ms == null) return '';
601
+ const age = Math.max(0, now - ms);
602
+ const date = new Date(ms);
603
+ if (age < 5000) return 'just now';
604
+ if (age < 60000) return `${Math.round(age / 1000)}s ago`;
605
+ if (age < 3600000) return `${Math.round(age / 60000)} min ago`;
606
+ const dayDiff = Math.round((calendarDayStart(now) - calendarDayStart(ms)) / 86400000);
607
+ const hours = Math.floor(age / 3600000);
608
+ if (dayDiff <= 0 && hours < 24) return `${Math.max(hours, 1)} h ago`;
609
+ const absolute = `${monthDay(date, date.getFullYear() !== new Date(now).getFullYear())}, ${clockTime(date)}`;
610
+ if (dayDiff === 1) return `yesterday · ${monthDay(date, false)}, ${clockTime(date)}`;
611
+ if (dayDiff > 1 && dayDiff < 7) return `${dayDiff} days ago · ${monthDay(date, false)}, ${clockTime(date)}`;
612
+ return absolute;
613
+ }
614
+
615
+ function exactTimeLabel(value) {
616
+ const ms = parsedTime(value);
617
+ if (ms == null) return '';
618
+ const date = new Date(ms);
619
+ const zone = timeZoneName(date);
620
+ return `${monthDay(date, true)} ${clockTime(date, true)}${zone ? ` ${zone}` : ''}`;
621
+ }
622
+
623
+ function datetimeAttr(value) {
624
+ const ms = parsedTime(value);
625
+ if (ms == null) return '';
626
+ const date = new Date(ms);
627
+ const offset = -date.getTimezoneOffset();
628
+ const sign = offset >= 0 ? '+' : '-';
629
+ const abs = Math.abs(offset);
630
+ return `${date.getFullYear()}-${padTime(date.getMonth() + 1)}-${padTime(date.getDate())}T${clockTime(date, true)}${sign}${padTime(Math.floor(abs / 60))}:${padTime(abs % 60)}`;
631
+ }
632
+
633
+ function clockTimeLabel(value, now = Date.now()) {
634
+ const ms = parsedTime(value);
635
+ if (ms == null) return '';
636
+ const date = new Date(ms);
637
+ const dayDiff = Math.round((calendarDayStart(now) - calendarDayStart(ms)) / 86400000);
638
+ if (dayDiff <= 0) return clockTime(date);
639
+ if (dayDiff === 1) return `yesterday ${clockTime(date)}`;
640
+ return humanizeTime(value, now);
641
+ }
642
+
643
+ function timeTag(value, now = Date.now(), mode = 'relative') {
644
+ const label = mode === 'clock' ? clockTimeLabel(value, now) : humanizeTime(value, now);
645
+ if (!label) return '';
646
+ return `<time datetime="${escapeHtml(datetimeAttr(value))}" title="${escapeHtml(exactTimeLabel(value))}">${escapeHtml(label)}</time>`;
647
+ }
648
+
649
+ function looksLikeIso(value) {
650
+ return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(String(value || ''));
651
+ }
652
+
653
+ function legacyDurationMs(runtime) {
654
+ if (!runtime || typeof runtime !== 'object') return null;
655
+ if (runtime.durationMs != null && runtime.durationMs !== '') {
656
+ const explicit = Number(runtime.durationMs);
657
+ if (Number.isFinite(explicit) && explicit >= 0) return explicit;
658
+ }
659
+ const started = Date.parse(runtime.startedAt);
660
+ if (!Number.isFinite(started)) return null;
661
+ const completed = Date.parse(runtime.completedAt);
662
+ if (Number.isFinite(completed)) return Math.max(0, completed - started);
663
+ if (graphStateClass(runtime.status) === 'active') return Math.max(0, Date.now() - started);
664
+ return null;
665
+ }
666
+
667
+ function dependencyIds(nodeId, recipe) {
668
+ const ids = new Set();
669
+ for (const edge of recipe?.edges || []) {
670
+ if (edge?.to === nodeId && edge.from) ids.add(edge.from);
671
+ }
672
+ const node = (recipe?.nodes || []).find((item) => item?.id === nodeId);
673
+ for (const id of node?.dependsOn || []) {
674
+ if (id) ids.add(id);
675
+ }
676
+ return [...ids];
677
+ }
678
+
679
+ function nodeDurationMs(nodeId, live, recipe) {
680
+ if (!nodeId || !live || !recipe) return null;
681
+ const runtime = live.nodes?.[nodeId];
682
+ if (!runtime) return null;
683
+ const status = String(runtime.status || '').toUpperCase();
684
+ const finished = status === 'PASSED' || status === 'FAILED';
685
+ const running = status === 'RUNNING' || status === 'IN_PROGRESS' || status === 'WORKING';
686
+ if (!finished && !running) return null;
687
+ const dependencies = dependencyIds(nodeId, recipe);
688
+ let start = NaN;
689
+ if (!dependencies.length) {
690
+ start = Date.parse(live.run?.createdAt);
691
+ } else {
692
+ const times = dependencies
693
+ .map((id) => Date.parse(live.nodes?.[id]?.updatedAt))
694
+ .filter(Number.isFinite);
695
+ if (times.length) start = Math.max(...times);
696
+ }
697
+ if (!Number.isFinite(start)) return null;
698
+ const end = finished ? Date.parse(runtime.updatedAt) : Date.now();
699
+ if (!Number.isFinite(end)) return null;
700
+ return Math.max(0, end - start);
701
+ }
702
+
703
+ function statusWord(status) {
704
+ if (status == null || status === '') return 'Pending';
705
+ const normalized = String(status).toLowerCase();
706
+ if (normalized === 'blocked') return 'Blocked';
707
+ const state = graphStateClass(status);
708
+ if (state === 'active') return 'Running';
709
+ if (state === 'passed') return 'Passed';
710
+ if (state === 'failed') return 'Failed';
711
+ if (state === 'skipped') return 'Skipped';
712
+ if (state === 'waiting') return 'Waiting';
713
+ if (normalized === 'ready') return 'Ready';
714
+ if (normalized === 'idle' || normalized === 'pending') return 'Pending';
715
+ return normalized.charAt(0).toUpperCase() + normalized.slice(1);
716
+ }
717
+
718
+ function nodeStatusLine(runtime) {
719
+ const word = statusWord(runtime?.status);
720
+ const duration = formatDuration(legacyDurationMs(runtime));
721
+ return duration ? `${word} · ${duration}` : word;
722
+ }
723
+
724
+ function liveStatusText(node) {
725
+ if (!node) return 'Pending';
726
+ const runtime = runtimeFor(node);
727
+ const word = statusWord(runtime?.status);
728
+ const duration = formatDuration(nodeDurationMs(node.id, catalog.live, draft));
729
+ return duration ? `${word} · ${duration}` : word;
323
730
  }
324
731
 
325
732
  function nodeMarkup(node, index) {
326
- const runtimeNode = catalog.live?.nodes?.[node.id];
733
+ const title = `${stageLabel(node, index)} · ${node.type}`;
327
734
  return `
328
735
  <button class="port port-in" aria-label="Input for ${escapeHtml(node.id)}" tabindex="-1"></button>
329
- <small>${escapeHtml(stageLabel(node, index))} / ${escapeHtml(node.type.toUpperCase())}</small>
330
- <span class="node-title">${escapeHtml(displayName(node))}</span>
331
- <span class="technical-id">${escapeHtml(node.id)}</span>
332
- <span class="status">● ${escapeHtml(runtimeNode?.status || 'READY')}</span>
736
+ <div class="node-tile" title="${escapeHtml(title)}">
737
+ <span class="node-icon">${nodeIcon(node.type)}</span>
738
+ <span class="node-mark" aria-hidden="true"></span>
739
+ </div>
740
+ <span class="node-name">${escapeHtml(displayName(node))}</span>
741
+ <span class="node-status">${escapeHtml(liveStatusText(node))}</span>
333
742
  <button class="port port-out" aria-label="Connect from ${escapeHtml(node.id)}" tabindex="-1"></button>
334
743
  `;
335
744
  }
336
745
 
337
- function renderGraph() {
746
+ function nodeFrame(node, index) {
747
+ const runtime = catalog.live?.nodes?.[node.id];
748
+ return {
749
+ status: graphStateClass(runtime?.status),
750
+ nodeType: node.type,
751
+ title: `${stageLabel(node, index)} · ${node.type}`,
752
+ html: nodeMarkup(node, index)
753
+ };
754
+ }
755
+
756
+ function renderGraph({ live = false } = {}) {
338
757
  if (!draft) return;
758
+ hideTooltip();
339
759
  ensurePositions();
340
760
  renderLoopGroups();
341
761
  const container = byId('nodes');
@@ -343,25 +763,48 @@ function renderGraph() {
343
763
  container.innerHTML = '';
344
764
  draft.nodes.forEach((node, index) => {
345
765
  const position = positions.get(node.id);
346
- const runtimeNode = catalog.live?.nodes?.[node.id];
766
+ const frame = nodeFrame(node, index);
347
767
  const element = document.createElement('article');
348
768
  element.dataset.nodeId = node.id;
349
- element.className = `node ${graphStateClass(runtimeNode?.status)} ${selectedIds.has(node.id) ? 'selected' : ''}`;
769
+ element.dataset.status = frame.status;
770
+ element.dataset.nodeType = frame.nodeType;
771
+ element.title = frame.title;
772
+ element.className = `node${selectedIds.has(node.id) ? ' selected' : ''}`;
773
+ element.tabIndex = 0;
774
+ element.setAttribute('role', 'button');
775
+ element.setAttribute('tabindex', '0');
776
+ element.setAttribute('aria-label', `${displayName(node)}, ${statusWord(runtimeFor(node)?.status)}`);
777
+ element.setAttribute('aria-describedby', 'node-tooltip');
350
778
  element.style.left = `${position.x}px`;
351
779
  element.style.top = `${position.y}px`;
352
- element.innerHTML = nodeMarkup(node, index);
780
+ element.innerHTML = frame.html;
353
781
  element.addEventListener('pointerdown', beginNodeInteraction);
782
+ element.addEventListener('pointerenter', () => scheduleTooltip(element));
783
+ element.addEventListener('pointerleave', hideTooltip);
784
+ element.addEventListener('focus', () => scheduleTooltip(element));
785
+ element.addEventListener('blur', hideTooltip);
786
+ element.addEventListener('click', onNodeClick);
354
787
  element.querySelector('.port-out')?.addEventListener('pointerdown', beginConnection);
355
788
  container.append(element);
356
789
  });
357
790
  renderEdges();
358
791
  applyViewport();
792
+ if (!live && !hasFitted) hasFitted = fitView();
793
+ if (!live && panelNodeId) renderNodePanel();
794
+ }
795
+
796
+ function nodeElements() {
797
+ return Array.from(byId('nodes')?.children || []);
359
798
  }
360
799
 
361
800
  function updateSelection() {
362
- document.querySelectorAll?.('.node')?.forEach?.((element) => {
363
- element.classList.toggle('selected', selectedIds.has(element.dataset.nodeId));
364
- });
801
+ for (const element of nodeElements()) {
802
+ const selected = selectedIds.has(element.dataset.nodeId);
803
+ element.classList.toggle('selected', selected);
804
+ const names = String(element.className || '').split(/\s+/).filter((name) => name && name !== 'selected');
805
+ if (selected) names.push('selected');
806
+ element.className = names.join(' ');
807
+ }
365
808
  }
366
809
 
367
810
  function selectNode(nodeId, { additive = false } = {}) {
@@ -374,6 +817,7 @@ function selectNode(nodeId, { additive = false } = {}) {
374
817
  selectedId = nodeId;
375
818
  selectedEdgeId = null;
376
819
  updateSelection();
820
+ renderEdges();
377
821
  }
378
822
 
379
823
  function deleteEdge(id) {
@@ -389,7 +833,7 @@ function deleteEdge(id) {
389
833
  }
390
834
 
391
835
  function addEdge(from, to) {
392
- if (!draft || from === to) return false;
836
+ if (!draft || !from || !to || from === to) return false;
393
837
  if (draft.edges.some((edge) => edge.from === from && edge.to === to)) return false;
394
838
  if (transitivelyDependsOn(from, to)) return false;
395
839
  if (!draft.nodes.some((node) => node.id === from) || !draft.nodes.some((node) => node.id === to)) return false;
@@ -401,12 +845,28 @@ function addEdge(from, to) {
401
845
  return true;
402
846
  }
403
847
 
848
+ function dependsOnTarget(nodeId, targetId, ignoreEdgeId, seen = new Set()) {
849
+ if (!nodeId || !targetId) return false;
850
+ if (nodeId === targetId) return true;
851
+ if (seen.has(nodeId)) return false;
852
+ seen.add(nodeId);
853
+ const upstream = (draft?.edges || [])
854
+ .filter((edge) => edge.to === nodeId && edge.id !== ignoreEdgeId)
855
+ .map((edge) => edge.from);
856
+ return upstream.some((from) => dependsOnTarget(from, targetId, ignoreEdgeId, seen));
857
+ }
858
+
404
859
  function repointEdge(id, from, to) {
405
860
  const edge = draft?.edges.find((candidate) => candidate.id === id);
406
- if (!edge) return false;
861
+ if (!edge || !from || !to || from === to) return false;
862
+ if (edge.from === from && edge.to === to) return true;
863
+ if (!draft.nodes.some((node) => node.id === from) || !draft.nodes.some((node) => node.id === to)) return false;
864
+ if (draft.edges.some((candidate) => candidate.id !== id && candidate.from === from && candidate.to === to)) return false;
865
+ if (dependsOnTarget(from, to, id)) return false;
407
866
  edge.from = from;
408
867
  edge.to = to;
409
868
  syncDependencies();
869
+ selectedEdgeId = id;
410
870
  captureHistory();
411
871
  renderGraph();
412
872
  validateDraft();
@@ -423,6 +883,7 @@ function beginNodeInteraction(event) {
423
883
  return;
424
884
  }
425
885
  if (!selectedIds.has(nodeId)) selectNode(nodeId);
886
+ element.focus?.();
426
887
  if (spacePressed) return beginPan(event);
427
888
  const world = screenToWorld(event.clientX, event.clientY);
428
889
  const position = positions.get(nodeId);
@@ -433,7 +894,8 @@ function beginNodeInteraction(event) {
433
894
  element,
434
895
  offsetX: world.x - position.x,
435
896
  offsetY: world.y - position.y,
436
- origins: new Map([...selectedIds].map((id) => [id, { ...positions.get(id) }]))
897
+ origins: new Map([...selectedIds].map((id) => [id, { ...positions.get(id) }])),
898
+ moved: false
437
899
  };
438
900
  element.classList.add('dragging');
439
901
  element.setPointerCapture?.(event.pointerId);
@@ -448,30 +910,107 @@ function beginPan(event) {
448
910
  startX: event.clientX,
449
911
  startY: event.clientY,
450
912
  viewportX: viewport.x,
451
- viewportY: viewport.y
913
+ viewportY: viewport.y,
914
+ panning: false
452
915
  };
453
916
  byId('canvas').setPointerCapture?.(event.pointerId);
454
917
  }
455
918
 
919
+ function ensureMarquee() {
920
+ if (marquee) return marquee;
921
+ marquee = document.createElement('div');
922
+ marquee.id = 'selection-marquee';
923
+ byId('canvas')?.append(marquee);
924
+ return marquee;
925
+ }
926
+
927
+ function beginMarquee(event) {
928
+ event.preventDefault?.();
929
+ ensureMarquee();
930
+ interaction = {
931
+ type: 'marquee',
932
+ pointerId: event.pointerId,
933
+ startX: event.clientX,
934
+ startY: event.clientY,
935
+ clientX: event.clientX,
936
+ clientY: event.clientY,
937
+ armed: false
938
+ };
939
+ byId('canvas').setPointerCapture?.(event.pointerId);
940
+ }
941
+
942
+ function paintMarquee() {
943
+ const box = ensureMarquee();
944
+ const rect = byId('canvas').getBoundingClientRect();
945
+ const left = Math.min(interaction.startX, interaction.clientX) - rect.left;
946
+ const top = Math.min(interaction.startY, interaction.clientY) - rect.top;
947
+ box.style.display = 'block';
948
+ box.style.left = `${left}px`;
949
+ box.style.top = `${top}px`;
950
+ box.style.width = `${Math.abs(interaction.clientX - interaction.startX)}px`;
951
+ box.style.height = `${Math.abs(interaction.clientY - interaction.startY)}px`;
952
+ }
953
+
954
+ function finishMarquee() {
955
+ const box = marquee;
956
+ if (box?.style) box.style.display = 'none';
957
+ if (!interaction?.armed || !draft) return;
958
+ const start = screenToWorld(interaction.startX, interaction.startY);
959
+ const end = screenToWorld(interaction.clientX, interaction.clientY);
960
+ const minX = Math.min(start.x, end.x);
961
+ const maxX = Math.max(start.x, end.x);
962
+ const minY = Math.min(start.y, end.y);
963
+ const maxY = Math.max(start.y, end.y);
964
+ const hits = draft.nodes.filter((node) => {
965
+ const pos = positions.get(node.id);
966
+ if (!pos) return false;
967
+ return pos.x < maxX && pos.x + NODE_WIDTH > minX && pos.y < maxY && pos.y + NODE_BLOCK_HEIGHT > minY;
968
+ }).map((node) => node.id);
969
+ selectedIds = new Set(hits);
970
+ selectedId = hits[0] || null;
971
+ selectedEdgeId = null;
972
+ updateSelection();
973
+ renderEdges();
974
+ }
975
+
456
976
  function handlePointerMove(event) {
457
977
  if (connection) {
458
- const from = positions.get(connection.sourceId);
459
978
  const preview = scenePart('.preview-edge');
460
- if (from && preview?.setAttribute) {
461
- const target = screenToWorld(event.clientX, event.clientY);
462
- const start = { x: from.x + NODE_WIDTH, y: from.y + NODE_PORT_Y };
463
- const bend = Math.max(55, Math.abs(target.x - start.x) * 0.42);
464
- preview.style.display = 'block';
465
- preview.setAttribute('d', `M${start.x} ${start.y} C${start.x + bend} ${start.y},${target.x - bend} ${target.y},${target.x} ${target.y}`);
979
+ const cursor = screenToWorld(event.clientX, event.clientY);
980
+ let x1;
981
+ let y1;
982
+ let x2;
983
+ let y2;
984
+ if (connection.edgeId && connection.end === 'from') {
985
+ const target = positions.get(connection.fixedId);
986
+ if (!target || !preview?.setAttribute) return;
987
+ x1 = cursor.x;
988
+ y1 = cursor.y;
989
+ x2 = target.x;
990
+ y2 = target.y + NODE_PORT_Y;
991
+ } else {
992
+ const source = positions.get(connection.sourceId || connection.fixedId);
993
+ if (!source || !preview?.setAttribute) return;
994
+ x1 = source.x + NODE_WIDTH;
995
+ y1 = source.y + NODE_PORT_Y;
996
+ x2 = cursor.x;
997
+ y2 = cursor.y;
466
998
  }
999
+ preview.style.display = 'block';
1000
+ preview.setAttribute('d', curvePath(x1, y1, x2, y2));
467
1001
  return;
468
1002
  }
469
1003
  if (!interaction || interaction.pointerId !== event.pointerId) return;
1004
+ if (interaction.type === 'minimap') {
1005
+ panFromMinimapEvent(event);
1006
+ return;
1007
+ }
470
1008
  if (interaction.type === 'node') {
471
1009
  const world = screenToWorld(event.clientX, event.clientY);
472
1010
  const position = { x: world.x - interaction.offsetX, y: world.y - interaction.offsetY };
473
1011
  const origin = interaction.origins.get(interaction.nodeId);
474
1012
  const delta = { x: position.x - origin.x, y: position.y - origin.y };
1013
+ if (Math.hypot(delta.x, delta.y) > 3) interaction.moved = true;
475
1014
  interaction.origins.forEach((start, id) => {
476
1015
  const next = { x: start.x + delta.x, y: start.y + delta.y };
477
1016
  positions.set(id, next);
@@ -482,9 +1021,24 @@ function handlePointerMove(event) {
482
1021
  }
483
1022
  });
484
1023
  renderEdges();
485
- } else {
486
- viewport.x = interaction.viewportX + event.clientX - interaction.startX;
487
- viewport.y = interaction.viewportY + event.clientY - interaction.startY;
1024
+ return;
1025
+ }
1026
+ if (interaction.type === 'marquee') {
1027
+ interaction.clientX = event.clientX;
1028
+ interaction.clientY = event.clientY;
1029
+ const distance = Math.hypot(event.clientX - interaction.startX, event.clientY - interaction.startY);
1030
+ if (distance < PAN_THRESHOLD_PX) return;
1031
+ interaction.armed = true;
1032
+ paintMarquee();
1033
+ return;
1034
+ }
1035
+ if (interaction.type === 'pan') {
1036
+ const dx = event.clientX - interaction.startX;
1037
+ const dy = event.clientY - interaction.startY;
1038
+ if (!interaction.panning && Math.hypot(dx, dy) < PAN_THRESHOLD_PX) return;
1039
+ interaction.panning = true;
1040
+ viewport.x = interaction.viewportX + dx;
1041
+ viewport.y = interaction.viewportY + dy;
488
1042
  applyViewport();
489
1043
  }
490
1044
  }
@@ -493,7 +1047,16 @@ function finishPointer(event) {
493
1047
  if (connection && connection.pointerId === event.pointerId) return finishConnection(event);
494
1048
  if (!interaction || interaction.pointerId !== event.pointerId) return;
495
1049
  if (interaction.type === 'node') interaction.element.classList.remove('dragging');
1050
+ const moved = interaction.type === 'node' && interaction.moved;
1051
+ const kind = interaction.type;
1052
+ const panned = kind === 'pan' && interaction.panning;
1053
+ if (kind === 'marquee') finishMarquee();
496
1054
  interaction = null;
1055
+ if (moved) {
1056
+ suppressNodeClick = true;
1057
+ setTimeout(() => { suppressNodeClick = false; }, 0);
1058
+ }
1059
+ if (kind === 'marquee' || (kind === 'pan' && !panned)) return;
497
1060
  saveLayoutSoon();
498
1061
  }
499
1062
 
@@ -515,17 +1078,44 @@ function transitivelyDependsOn(nodeId, targetId, seen = new Set()) {
515
1078
  return (node?.dependsOn || []).some((dependencyId) => transitivelyDependsOn(dependencyId, targetId, seen));
516
1079
  }
517
1080
 
1081
+ function nodeIdFromPort(hit, selector) {
1082
+ const port = hit?.closest?.(selector);
1083
+ const node = port?.closest?.('.node');
1084
+ return node?.dataset?.nodeId || null;
1085
+ }
1086
+
518
1087
  function finishConnection(event) {
519
- const sourceId = connection.sourceId;
1088
+ const pending = connection;
520
1089
  connection = null;
521
1090
  const preview = scenePart('.preview-edge');
522
1091
  if (preview?.style) preview.style.display = 'none';
523
- const targetElement = document.elementFromPoint?.(event.clientX, event.clientY)?.closest?.('.node');
524
- const targetId = targetElement?.dataset.nodeId;
525
- if (!targetId || targetId === sourceId) return;
526
- if (draft.edges.some((edge) => edge.from === sourceId && edge.to === targetId)) return notify('Nodes are already connected.');
527
- if (transitivelyDependsOn(sourceId, targetId)) return notify('Connection rejected: it would create a cycle.');
528
- addEdge(sourceId, targetId);
1092
+ if (!pending || !draft) return;
1093
+ const hit = document.elementFromPoint?.(event.clientX, event.clientY);
1094
+ if (pending.edgeId) {
1095
+ const edge = draft.edges.find((item) => item.id === pending.edgeId);
1096
+ if (!edge) return;
1097
+ if (pending.end === 'from') {
1098
+ const sourceId = nodeIdFromPort(hit, '.port-out');
1099
+ if (!sourceId) return;
1100
+ if (!repointEdge(edge.id, sourceId, edge.to)) notify('Connection rejected.');
1101
+ return;
1102
+ }
1103
+ const targetId = nodeIdFromPort(hit, '.port-in');
1104
+ if (!targetId) return;
1105
+ if (!repointEdge(edge.id, edge.from, targetId)) notify('Connection rejected.');
1106
+ return;
1107
+ }
1108
+ const targetId = nodeIdFromPort(hit, '.port-in');
1109
+ if (!targetId || targetId === pending.sourceId) {
1110
+ if (targetId && targetId === pending.sourceId) notify('A node cannot connect to itself.');
1111
+ return;
1112
+ }
1113
+ if (addEdge(pending.sourceId, targetId)) return;
1114
+ if (draft.edges.some((edge) => edge.from === pending.sourceId && edge.to === targetId)) {
1115
+ notify('Nodes are already connected.');
1116
+ return;
1117
+ }
1118
+ notify('Connection rejected: it would create a cycle.');
529
1119
  }
530
1120
 
531
1121
  function zoomAt(nextScale, clientX, clientY) {
@@ -548,31 +1138,121 @@ function worldAtCanvasCenter() {
548
1138
  return screenToWorld(rect.left + rect.width / 2, rect.top + rect.height / 2);
549
1139
  }
550
1140
 
1141
+ function wheelPixels(delta, mode) {
1142
+ const unit = mode === 1 ? WHEEL_LINE_PX : mode === 2 ? WHEEL_PAGE_PX : 1;
1143
+ const pixels = Number(delta) * unit;
1144
+ if (!Number.isFinite(pixels)) return 0;
1145
+ return Math.max(-WHEEL_SPIKE_PX, Math.min(WHEEL_SPIKE_PX, pixels));
1146
+ }
1147
+
1148
+ function canvasGestureIgnored(event) {
1149
+ return Boolean(closestReal(event?.target, '#node-panel, .zoom-controls, .minimap, .canvas-toolbar'));
1150
+ }
1151
+
1152
+ function flushWheel() {
1153
+ const pending = wheelPending;
1154
+ wheelPending = null;
1155
+ if (!pending) return;
1156
+ if (pending.ctrlKey) {
1157
+ zoomAt(viewport.scale * Math.exp(-pending.deltaY * 0.01), pending.clientX, pending.clientY);
1158
+ return;
1159
+ }
1160
+ viewport.x -= pending.deltaX;
1161
+ viewport.y -= pending.deltaY;
1162
+ applyViewport();
1163
+ }
1164
+
551
1165
  function handleWheel(event) {
1166
+ if (canvasGestureIgnored(event)) return;
552
1167
  event.preventDefault();
553
- zoomAt(viewport.scale * (event.deltaY < 0 ? 1.08 : 0.92), event.clientX, event.clientY);
1168
+ const sample = {
1169
+ ctrlKey: Boolean(event.ctrlKey),
1170
+ deltaX: wheelPixels(event.deltaX, event.deltaMode),
1171
+ deltaY: wheelPixels(event.deltaY, event.deltaMode),
1172
+ clientX: event.clientX,
1173
+ clientY: event.clientY
1174
+ };
1175
+ if (wheelPending && wheelPending.ctrlKey !== sample.ctrlKey) flushWheel();
1176
+ if (!wheelPending) {
1177
+ wheelPending = { ctrlKey: sample.ctrlKey, deltaX: 0, deltaY: 0, clientX: sample.clientX, clientY: sample.clientY };
1178
+ }
1179
+ wheelPending.deltaX += sample.deltaX;
1180
+ wheelPending.deltaY += sample.deltaY;
1181
+ wheelPending.clientX = sample.clientX;
1182
+ wheelPending.clientY = sample.clientY;
1183
+ if (wheelFrame != null) return;
1184
+ const schedule = typeof requestAnimationFrame === 'function'
1185
+ ? requestAnimationFrame
1186
+ : (callback) => setTimeout(callback, 16);
1187
+ wheelFrame = schedule(() => {
1188
+ wheelFrame = null;
1189
+ flushWheel();
1190
+ });
554
1191
  }
555
1192
 
556
1193
  function autoLayout({ record = true } = {}) {
557
1194
  positions = defaultGraphPositions();
1195
+ hasFitted = false;
558
1196
  renderGraph();
559
1197
  if (record) captureHistory();
560
1198
  saveLayoutSoon();
561
1199
  }
562
1200
 
1201
+ function graphBounds() {
1202
+ const points = (draft?.nodes || []).map((node) => positions.get(node.id)).filter(Boolean);
1203
+ if (!points.length) return null;
1204
+ const minX = Math.min(...points.map((point) => point.x)) - LABEL_BLEED;
1205
+ const minY = Math.min(...points.map((point) => point.y));
1206
+ const maxX = Math.max(...points.map((point) => point.x + NODE_WIDTH)) + LABEL_BLEED;
1207
+ const maxY = Math.max(...points.map((point) => point.y + NODE_BLOCK_HEIGHT));
1208
+ return { minX, minY, maxX, maxY, width: maxX - minX, height: maxY - minY };
1209
+ }
1210
+
1211
+ function computeFit(bounds, canvasWidth, canvasHeight, padding = FIT_PADDING) {
1212
+ const availableW = Math.max(1, canvasWidth - padding * 2);
1213
+ const availableH = Math.max(1, canvasHeight - padding * 2);
1214
+ const scale = Math.min(
1215
+ MAX_ZOOM,
1216
+ Math.max(MIN_ZOOM, Math.min(availableW / Math.max(bounds.width, 1), availableH / Math.max(bounds.height, 1)))
1217
+ );
1218
+ return {
1219
+ scale,
1220
+ x: padding + (availableW - bounds.width * scale) / 2 - bounds.minX * scale,
1221
+ y: padding + (availableH - bounds.height * scale) / 2 - bounds.minY * scale
1222
+ };
1223
+ }
1224
+
1225
+ function panelInset() {
1226
+ const panel = byId('node-panel');
1227
+ if (!panel || panel.hidden) return 0;
1228
+ const width = panel.getBoundingClientRect?.().width || 0;
1229
+ const canvasWidth = byId('canvas')?.getBoundingClientRect?.().width || 0;
1230
+ if (width >= 2 && canvasWidth >= 2 && width < canvasWidth - 1) return width;
1231
+ return PANEL_WIDTH;
1232
+ }
1233
+
563
1234
  function fitView() {
564
- if (!draft?.nodes.length) return;
1235
+ if (!draft?.nodes?.length) return false;
565
1236
  ensurePositions();
566
- const canvas = byId('canvas').getBoundingClientRect();
567
- const xs = draft.nodes.map((node) => positions.get(node.id).x);
568
- const ys = draft.nodes.map((node) => positions.get(node.id).y);
569
- const width = Math.max(...xs) - Math.min(...xs) + NODE_WIDTH + 160;
570
- const height = Math.max(...ys) - Math.min(...ys) + 200;
571
- viewport.scale = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, Math.min(canvas.width / width, canvas.height / height)));
572
- viewport.x = (canvas.width - width * viewport.scale) / 2 - Math.min(...xs) * viewport.scale + 40;
573
- viewport.y = (canvas.height - height * viewport.scale) / 2 - Math.min(...ys) * viewport.scale + 40;
1237
+ const rect = byId('canvas')?.getBoundingClientRect?.() || { width: 0, height: 0 };
1238
+ const width = Math.max(0, rect.width - panelInset());
1239
+ if (width < 2 || rect.height < 2) return false;
1240
+ const bounds = graphBounds();
1241
+ if (!bounds) return false;
1242
+ const next = computeFit(bounds, width, rect.height);
1243
+ viewport.scale = next.scale;
1244
+ viewport.x = next.x;
1245
+ viewport.y = next.y;
574
1246
  applyViewport();
575
1247
  saveLayoutSoon();
1248
+ return true;
1249
+ }
1250
+
1251
+ function scheduleFitView() {
1252
+ clearTimeout(resizeFitTimer);
1253
+ resizeFitTimer = setTimeout(() => {
1254
+ if (draft?.nodes?.length) fitView();
1255
+ }, 150);
576
1256
  }
577
1257
 
578
1258
  function captureHistory({ reset = false } = {}) {
@@ -585,8 +1265,7 @@ function captureHistory({ reset = false } = {}) {
585
1265
  history.push(snapshot);
586
1266
  historyIndex = history.length - 1;
587
1267
  }
588
- if (byId('undo')) byId('undo').disabled = historyIndex <= 0;
589
- if (byId('redo')) byId('redo').disabled = historyIndex >= history.length - 1;
1268
+ renderWiringBar();
590
1269
  }
591
1270
 
592
1271
  function restoreHistory(index) {
@@ -599,8 +1278,7 @@ function restoreHistory(index) {
599
1278
  renderGraph();
600
1279
  validateDraft();
601
1280
  saveLayoutSoon();
602
- if (byId('undo')) byId('undo').disabled = historyIndex <= 0;
603
- if (byId('redo')) byId('redo').disabled = historyIndex >= history.length - 1;
1281
+ renderWiringBar();
604
1282
  }
605
1283
 
606
1284
  function saveLayoutSoon() {
@@ -618,8 +1296,164 @@ function saveLayoutSoon() {
618
1296
  }, 350);
619
1297
  }
620
1298
 
1299
+ function edgeSignature(recipe) {
1300
+ return (recipe?.edges || [])
1301
+ .map((edge) => `${edge.from}->${edge.to}`)
1302
+ .sort()
1303
+ .join('|');
1304
+ }
1305
+
1306
+ function rememberLoadedWiring() {
1307
+ loadedEdges = structuredClone(draft?.edges || []);
1308
+ loadedEdgeSignature = edgeSignature({ edges: loadedEdges });
1309
+ }
1310
+
1311
+ function wiringChangeCount() {
1312
+ const loaded = new Set(loadedEdgeSignature ? loadedEdgeSignature.split('|').filter(Boolean) : []);
1313
+ const current = new Set((draft?.edges || []).map((edge) => `${edge.from}->${edge.to}`));
1314
+ let count = 0;
1315
+ for (const edge of current) if (!loaded.has(edge)) count += 1;
1316
+ for (const edge of loaded) if (!current.has(edge)) count += 1;
1317
+ return count;
1318
+ }
1319
+
1320
+ function issueText(issue) {
1321
+ const code = issue?.code ? String(issue.code) : '';
1322
+ const message = issue?.message ? String(issue.message) : '';
1323
+ if (code && message) return `${code}: ${message}`;
1324
+ return code || message;
1325
+ }
1326
+
1327
+ function validationSummary(state = validationState) {
1328
+ const parts = (state.issues || []).map(issueText).filter(Boolean);
1329
+ for (const code of state.extraCodes || []) {
1330
+ if (code && !parts.some((part) => part.includes(code))) parts.push(code);
1331
+ }
1332
+ return parts.join('; ');
1333
+ }
1334
+
1335
+ function issuesFromPayload(payload) {
1336
+ const validation = payload?.validation;
1337
+ const messages = Array.isArray(validation?.errors) ? validation.errors.map(String) : [];
1338
+ const codes = Array.isArray(validation?.codes) ? validation.codes.filter(Boolean).map(String) : [];
1339
+ if (!messages.length) {
1340
+ if (payload?.error || payload?.code) {
1341
+ return {
1342
+ issues: [{ message: String(payload.error || ''), code: String(payload.code || '') }],
1343
+ extraCodes: []
1344
+ };
1345
+ }
1346
+ return { issues: [{ message: 'Validation failed', code: '' }], extraCodes: [] };
1347
+ }
1348
+ if (codes.length === messages.length) {
1349
+ return {
1350
+ issues: messages.map((message, index) => ({ message, code: codes[index] || '' })),
1351
+ extraCodes: []
1352
+ };
1353
+ }
1354
+ return { issues: messages.map((message) => ({ message, code: '' })), extraCodes: codes };
1355
+ }
1356
+
1357
+ function assignInvalidEdges(issues) {
1358
+ edgeIssues = new Map();
1359
+ const loaded = new Set(loadedEdgeSignature ? loadedEdgeSignature.split('|').filter(Boolean) : []);
1360
+ const dirtyIds = (draft?.edges || [])
1361
+ .filter((edge) => !loaded.has(`${edge.from}->${edge.to}`))
1362
+ .map((edge) => edge.id);
1363
+ const remember = (edgeId, issue) => {
1364
+ if (!edgeId) return;
1365
+ if (!edgeIssues.has(edgeId)) edgeIssues.set(edgeId, []);
1366
+ const list = edgeIssues.get(edgeId);
1367
+ if (!list.some((item) => item.code === issue.code && item.message === issue.message)) list.push(issue);
1368
+ };
1369
+ for (const issue of issues) {
1370
+ const message = issue.message || '';
1371
+ let matched = false;
1372
+ for (const edge of draft?.edges || []) {
1373
+ if ((edge.id && message.includes(edge.id)) || message.includes(`${edge.from} -> ${edge.to}`)) {
1374
+ remember(edge.id, issue);
1375
+ matched = true;
1376
+ }
1377
+ }
1378
+ const typed = message.match(/^([a-z0-9-]+) must depend on ([a-z0-9-]+)/);
1379
+ if (typed) {
1380
+ const dependents = new Set((draft?.nodes || []).filter((node) => node.type === typed[1]).map((node) => node.id));
1381
+ const dependencies = new Set((draft?.nodes || []).filter((node) => node.type === typed[2]).map((node) => node.id));
1382
+ for (const edgeId of dirtyIds) {
1383
+ const edge = draft.edges.find((item) => item.id === edgeId);
1384
+ if (!edge) continue;
1385
+ if (dependents.has(edge.to) || dependents.has(edge.from) || dependencies.has(edge.to) || dependencies.has(edge.from)) {
1386
+ remember(edge.id, issue);
1387
+ matched = true;
1388
+ }
1389
+ }
1390
+ }
1391
+ if (/must be a terminal node/.test(message)) {
1392
+ const token = message.split(' ')[0];
1393
+ const ids = new Set((draft?.nodes || []).filter((node) => node.type === token || node.id === token).map((node) => node.id));
1394
+ for (const edge of draft?.edges || []) {
1395
+ if (ids.has(edge.from)) {
1396
+ remember(edge.id, issue);
1397
+ matched = true;
1398
+ }
1399
+ }
1400
+ }
1401
+ if (!matched && dirtyIds.length === 1) remember(dirtyIds[0], issue);
1402
+ }
1403
+ invalidEdgeIds = new Set(edgeIssues.keys());
1404
+ }
1405
+
1406
+ function renderWiringBar() {
1407
+ const changes = draft ? wiringChangeCount() : 0;
1408
+ const bar = byId('wiring-bar');
1409
+ if (bar) bar.hidden = changes === 0;
1410
+ const count = byId('wiring-count');
1411
+ if (count) count.textContent = `${changes} wiring change${changes === 1 ? '' : 's'}`;
1412
+ const pill = byId('wiring-pill');
1413
+ if (pill) {
1414
+ const short = validationState.hash ? String(validationState.hash).slice(0, 8) : '';
1415
+ const status = validationState.status;
1416
+ pill.className = `wiring-pill ${status === 'valid' ? 'valid' : status === 'invalid' ? 'invalid' : 'pending'}`;
1417
+ if (status === 'valid') pill.textContent = short ? `Valid ${short}` : 'Valid';
1418
+ else if (status === 'invalid') pill.textContent = short ? `Invalid ${short}` : 'Invalid';
1419
+ else pill.textContent = 'Checking';
1420
+ }
1421
+ const error = byId('wiring-error');
1422
+ if (error) {
1423
+ // CSS clamps this to two lines; the full compiler output stays in the tooltip.
1424
+ const full = validationState.status === 'invalid' ? validationSummary() : '';
1425
+ error.textContent = full;
1426
+ if (error.setAttribute) error.setAttribute('title', full);
1427
+ }
1428
+ const save = byId('save-wiring');
1429
+ if (save) save.disabled = changes === 0 || validationState.status !== 'valid';
1430
+ const undo = byId('undo');
1431
+ const redo = byId('redo');
1432
+ if (undo) undo.disabled = historyIndex <= 0;
1433
+ if (redo) redo.disabled = historyIndex >= history.length - 1;
1434
+ }
1435
+
1436
+ function discardWiring() {
1437
+ if (!draft) return;
1438
+ draft.edges = structuredClone(loadedEdges);
1439
+ syncDependencies();
1440
+ selectedEdgeId = null;
1441
+ invalidEdgeIds = new Set();
1442
+ edgeIssues = new Map();
1443
+ captureHistory();
1444
+ renderGraph();
1445
+ validateDraft();
1446
+ }
1447
+
1448
+ function clearInvalidEdges() {
1449
+ invalidEdgeIds = new Set();
1450
+ edgeIssues = new Map();
1451
+ }
1452
+
621
1453
  async function validateDraft() {
622
1454
  const sequence = ++validationSequence;
1455
+ validationState = { status: 'pending', hash: '', issues: [], extraCodes: [] };
1456
+ renderWiringBar();
623
1457
  try {
624
1458
  const result = await api('/api/validate', {
625
1459
  method: 'POST',
@@ -627,9 +1461,8 @@ async function validateDraft() {
627
1461
  });
628
1462
  if (sequence !== validationSequence) return result;
629
1463
  const hash = result.plans[0].graphHash;
630
- byId('integrity').textContent = `VALID / ${hash.slice(0, 8)}…${hash.slice(-4)}`;
631
- byId('integrity').className = 'valid';
632
- byId('review').disabled = false;
1464
+ validationState = { status: 'valid', hash, issues: [], extraCodes: [] };
1465
+ clearInvalidEdges();
633
1466
  byId('review-data').textContent = JSON.stringify({
634
1467
  recipe: draft.id,
635
1468
  version: draft.version,
@@ -637,12 +1470,16 @@ async function validateDraft() {
637
1470
  nodes: draft.nodes.length,
638
1471
  graphHashes: result.plans.map((plan) => plan.graphHash)
639
1472
  }, null, 2);
1473
+ renderWiringBar();
1474
+ renderEdges();
640
1475
  return result;
641
1476
  } catch (error) {
642
1477
  if (sequence !== validationSequence) return null;
643
- byId('integrity').textContent = `INVALID / ${error.message}`;
644
- byId('integrity').className = 'invalid';
645
- byId('review').disabled = true;
1478
+ const parsed = issuesFromPayload(error.payload);
1479
+ validationState = { status: 'invalid', hash: '', issues: parsed.issues, extraCodes: parsed.extraCodes };
1480
+ assignInvalidEdges(parsed.issues);
1481
+ renderWiringBar();
1482
+ renderEdges();
646
1483
  return null;
647
1484
  }
648
1485
  }
@@ -965,7 +1802,7 @@ async function loadRuns() {
965
1802
  const row = (run, isActive = false) => `
966
1803
  <button class="run-row${isActive ? ' active-run-row' : ''}" data-run-id="${escapeHtml(run.runId)}">
967
1804
  <strong>${escapeHtml(run.displayName)}</strong>
968
- <span>${escapeHtml(run.status)} · ${escapeHtml(new Date(run.updatedAt).toLocaleString())}</span>
1805
+ <span>${escapeHtml(run.status)} · ${timeTag(run.updatedAt) || '—'}</span>
969
1806
  <small>${escapeHtml(run.task)}</small>
970
1807
  </button>`;
971
1808
  list.innerHTML = [
@@ -992,13 +1829,9 @@ async function loadRuns() {
992
1829
  }
993
1830
  }
994
1831
 
995
- function heartbeatAge(iso) {
1832
+ function heartbeatAge(iso, now = Date.now()) {
996
1833
  if (!iso) return 'no heartbeat';
997
- const age = Math.max(0, Date.now() - Date.parse(iso));
998
- if (!Number.isFinite(age)) return 'no heartbeat';
999
- if (age < 2000) return 'just now';
1000
- if (age < 60000) return `${Math.round(age / 1000)}s ago`;
1001
- return `${Math.round(age / 60000)}m ago`;
1834
+ return humanizeTime(iso, now) || 'no heartbeat';
1002
1835
  }
1003
1836
 
1004
1837
  function currentStageId(live) {
@@ -1027,22 +1860,396 @@ function scheduleLiveRender() {
1027
1860
  schedule(() => {
1028
1861
  liveRenderScheduled = false;
1029
1862
  renderLive();
1863
+ refreshWiringLive();
1030
1864
  });
1031
1865
  }
1032
1866
 
1867
+ function textOrNull(value) {
1868
+ if (value == null) return null;
1869
+ const text = String(value).trim();
1870
+ return text || null;
1871
+ }
1872
+
1873
+ function shown(value) {
1874
+ return value == null || value === '' ? '—' : String(value);
1875
+ }
1876
+
1877
+ function summaryFact(label, value) {
1878
+ return `<div class="summary-fact"><span>${escapeHtml(label)}</span><strong>${escapeHtml(shown(value))}</strong></div>`;
1879
+ }
1880
+
1881
+ function deliveryDestination(live) {
1882
+ const artifacts = live?.artifacts || {};
1883
+ const delivery = (live?.plan?.nodes || []).find((node) => node.type === 'delivery');
1884
+ const runtime = delivery ? live.nodes?.[delivery.id] : null;
1885
+ return textOrNull(live?.run?.destination)
1886
+ || textOrNull(live?.run?.delivery?.destination)
1887
+ || textOrNull(artifacts['artifact.delivery']?.destination)
1888
+ || textOrNull(runtime?.destination)
1889
+ || textOrNull(runtime?.output?.destination);
1890
+ }
1891
+
1892
+ function approverName(live) {
1893
+ const artifacts = live?.artifacts || {};
1894
+ const approval = (live?.plan?.nodes || []).find((node) => node.type === 'approval');
1895
+ const runtime = approval ? live.nodes?.[approval.id] : null;
1896
+ return textOrNull(runtime?.approvedBy)
1897
+ || textOrNull(live?.run?.approvedBy)
1898
+ || textOrNull(live?.run?.approver)
1899
+ || textOrNull(artifacts['artifact.delivery']?.approvedBy)
1900
+ || textOrNull(artifacts['artifact.verdict']?.approvedBy);
1901
+ }
1902
+
1903
+ function completedRunDurationMs(live) {
1904
+ const start = Date.parse(live?.run?.createdAt);
1905
+ if (!Number.isFinite(start)) return null;
1906
+ const nodeTimes = Object.values(live?.nodes || {})
1907
+ .map((node) => Date.parse(node?.updatedAt))
1908
+ .filter(Number.isFinite);
1909
+ const lastNode = nodeTimes.length ? Math.max(...nodeTimes) : NaN;
1910
+ const delivery = [
1911
+ live?.run?.deliveredAt,
1912
+ live?.run?.deliveryAt,
1913
+ live?.run?.delivery?.at,
1914
+ live?.artifacts?.['artifact.delivery']?.at
1915
+ ].map((value) => Date.parse(value)).find(Number.isFinite);
1916
+ const end = Number.isFinite(delivery) ? delivery : lastNode;
1917
+ if (!Number.isFinite(end)) {
1918
+ const updated = Date.parse(live?.run?.updatedAt);
1919
+ if (!Number.isFinite(updated)) return null;
1920
+ return Math.max(0, updated - start);
1921
+ }
1922
+ return Math.max(0, end - start);
1923
+ }
1924
+
1925
+ function verificationLabel(summary) {
1926
+ if (!summary || typeof summary !== 'object') return null;
1927
+ const failed = Number(summary.failed);
1928
+ const total = Number(summary.commandCount);
1929
+ if (!Number.isFinite(failed) || !Number.isFinite(total)) return null;
1930
+ return `${Math.max(0, total - failed)} passed / ${failed} failed`;
1931
+ }
1932
+
1933
+ function findingsLabel(summary) {
1934
+ if (!summary || typeof summary !== 'object') return null;
1935
+ if (summary.count == null && summary.blocking == null) return null;
1936
+ return `${summary.count ?? '—'} / ${summary.blocking ?? '—'}`;
1937
+ }
1938
+
1939
+ function driftLabel(summary) {
1940
+ if (!summary || typeof summary !== 'object' || summary.outOfMapCount == null) return null;
1941
+ const count = Number(summary.outOfMapCount);
1942
+ if (!Number.isFinite(count)) return null;
1943
+ return count === 0 ? 'none' : `${count} out of map`;
1944
+ }
1945
+
1946
+ function receiptLabel(summary) {
1947
+ if (!summary || summary.present === false) return 'missing';
1948
+ if (summary.verified === true && !(summary.problems || []).length) return 'verified';
1949
+ if (Array.isArray(summary.problems) && summary.problems.length) return 'problems';
1950
+ if (summary.verified === false) return 'problems';
1951
+ return 'missing';
1952
+ }
1953
+
1954
+ function tokenLabel(live) {
1955
+ const raw = live?.budget?.totalTokens ?? live?.budget?.spentThisRun ?? live?.run?.totalTokens ?? live?.run?.tokens;
1956
+ const value = Number(raw);
1957
+ if (!Number.isFinite(value) || value <= 0) return 'unknown';
1958
+ return String(value);
1959
+ }
1960
+
1961
+ function tokenBudgetLabel(live) {
1962
+ const tokens = tokenLabel(live);
1963
+ const limit = Number(live?.budget?.perRunTokenLimit);
1964
+ if (Number.isFinite(limit) && limit > 0) return `${tokens} / ${limit}`;
1965
+ return tokens;
1966
+ }
1967
+
1968
+ function guardChipValue(summary) {
1969
+ if (!summary || typeof summary !== 'object') return 'unknown';
1970
+ if (summary.warn == null && summary.block == null) return 'unknown';
1971
+ return `${summary.warn || 0} warn · ${summary.block || 0} block`;
1972
+ }
1973
+
1974
+ function receiptChipValue(live) {
1975
+ const receipt = live?.artifacts?.['artifact.receipt'];
1976
+ const terminal = live?.run?.state === 'DELIVERED' || live?.run?.state === 'REPORTED';
1977
+ if (receipt?.verified === true && !(receipt.problems || []).length) {
1978
+ return { value: 'verified', title: 'receipt recorded' };
1979
+ }
1980
+ if (receipt && Array.isArray(receipt.problems) && receipt.problems.length) {
1981
+ return { value: 'problems', title: receipt.problems.join(', ') };
1982
+ }
1983
+ if (terminal && (!receipt || receipt.present === false)) {
1984
+ return { value: 'missing', title: 'no receipt: run predates receipts' };
1985
+ }
1986
+ return { value: 'pending', title: 'receipt pending' };
1987
+ }
1988
+
1989
+ function labeledChip(label, value, title) {
1990
+ const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
1991
+ return `<span class="chip"${titleAttr}><span>${escapeHtml(label)}</span><strong>${escapeHtml(String(value))}</strong></span>`;
1992
+ }
1993
+
1994
+ function liveMetaHtml(live) {
1995
+ const run = live?.run || {};
1996
+ const artifacts = live?.artifacts || {};
1997
+ const tokens = tokenLabel(live);
1998
+ const receipt = receiptChipValue(live);
1999
+ const chips = [
2000
+ labeledChip('Mode', run.mode || '—'),
2001
+ labeledChip('Tier', run.tier?.current || run.mode || '—'),
2002
+ labeledChip('Iteration', run.iteration ?? '—'),
2003
+ labeledChip('Tokens', tokenBudgetLabel(live), tokens === 'unknown' ? 'host reports no usage' : ''),
2004
+ labeledChip('Guard', guardChipValue(artifacts['artifact.guard'])),
2005
+ labeledChip('Drift', driftLabel(artifacts['artifact.drift']) || 'unknown'),
2006
+ labeledChip('Receipt', receipt.value, receipt.title)
2007
+ ].join('');
2008
+ return `<section class="compliance-card"><h2 class="live-card-title">Compliance &amp; budget</h2><div class="chip-row">${chips}</div>${budgetRow(live)}</section><section class="events-card"><h2 class="live-card-title">Latest events</h2>${latestEventsHtml(live)}</section>`;
2009
+ }
2010
+
2011
+ function budgetRow(live) {
2012
+ const tokens = tokenLabel(live);
2013
+ const note = tokens === 'unknown' ? 'host reports no usage' : tokenBudgetLabel(live);
2014
+ return `<div class="budget-row"><span>Budget</span><span class="meter" aria-hidden="true"><i></i></span><span>${escapeHtml(note)}</span></div>`;
2015
+ }
2016
+
2017
+ function paintBudget(live) {
2018
+ const bar = byId('live-meta')?.querySelector?.('.meter i');
2019
+ if (!bar?.style) return;
2020
+ const spent = Number(live?.budget?.totalTokens ?? live?.budget?.spentThisRun);
2021
+ const limit = Number(live?.budget?.perRunTokenLimit);
2022
+ const ratio = Number.isFinite(spent) && spent > 0 && Number.isFinite(limit) && limit > 0
2023
+ ? Math.max(0, Math.min(1, spent / limit))
2024
+ : 0;
2025
+ bar.style.width = `${Math.round(ratio * 100)}%`;
2026
+ }
2027
+
2028
+ function liveEventLabel(event) {
2029
+ if (event?.message) return event.message;
2030
+ const gate = event?.gate;
2031
+ if (event?.type === 'GATE_PASSED') {
2032
+ if (gate === 'goal') return 'Goal frozen';
2033
+ if (gate === 'maker') return 'Maker gate passed';
2034
+ if (gate === 'verification') return 'Verification gate passed';
2035
+ if (gate === 'review') return 'Review gate passed';
2036
+ if (gate === 'judge') return 'Judge gate passed';
2037
+ if (gate === 'delivery') return 'Delivery gate passed';
2038
+ return 'Gate passed';
2039
+ }
2040
+ if (event?.type === 'NODE_APPROVED') return `Approved by ${event.approvedBy || 'human'}`;
2041
+ return String(event?.type || 'event').replaceAll('_', ' ').toLowerCase();
2042
+ }
2043
+
2044
+ function eventActor(event, live) {
2045
+ const plan = live?.plan?.nodes || [];
2046
+ const node = plan.find((item) => item.id === event?.nodeId)
2047
+ || plan.find((item) => item.legacyGate === event?.gate || item.id === event?.gate);
2048
+ return node?.id || event?.gate || event?.phase || 'run';
2049
+ }
2050
+
2051
+ function recentEvents(live) {
2052
+ const workflow = Array.isArray(live?.events) ? live.events : [];
2053
+ const source = workflow.length ? workflow : lifecycleEvents;
2054
+ return source.slice(-4).reverse();
2055
+ }
2056
+
2057
+ function latestEventsHtml(live) {
2058
+ const events = recentEvents(live);
2059
+ if (!events.length) return '<p class="muted">No events yet.</p>';
2060
+ return events.map((event) => `
2061
+ <p class="event-row">${timeTag(event.at, Date.now(), 'clock') || '—'} <span class="who">${escapeHtml(eventActor(event, live))}</span> <span>${escapeHtml(liveEventLabel(event))}</span></p>
2062
+ `).join('');
2063
+ }
2064
+
2065
+ function stageNodes(stage, live) {
2066
+ return (live?.plan?.nodes || []).filter((node) => stage.types.includes(node.type));
2067
+ }
2068
+
2069
+ function stageState(stage, live) {
2070
+ const statuses = stageNodes(stage, live).map((node) => String(live?.nodes?.[node.id]?.status || '').toUpperCase());
2071
+ if (statuses.includes('RUNNING')) return 'active';
2072
+ if (statuses.includes('FAILED') || statuses.includes('BLOCKED')) return 'failed';
2073
+ if (statuses.length && statuses.every((status) => status === 'PASSED' || status === 'SKIPPED')) return 'passed';
2074
+ return 'pending';
2075
+ }
2076
+
2077
+ function stageDurationLabel(stage, live) {
2078
+ const recipe = draft || live?.plan;
2079
+ let total = 0;
2080
+ for (const node of stageNodes(stage, live)) {
2081
+ const ms = nodeDurationMs(node.id, live, recipe);
2082
+ if (ms > 0) total += ms;
2083
+ }
2084
+ return formatDuration(total) || '—';
2085
+ }
2086
+
2087
+ function progressRailHtml(live) {
2088
+ return STAGES.map((stage) => {
2089
+ const state = live ? stageState(stage, live) : 'pending';
2090
+ const duration = live ? stageDurationLabel(stage, live) : '—';
2091
+ return `<li class="${state}"><strong>${escapeHtml(stage.label)}</strong><span>${escapeHtml(duration)}</span></li>`;
2092
+ }).join('');
2093
+ }
2094
+
2095
+ function focusNodeRecord(live) {
2096
+ const plan = live?.plan?.nodes || [];
2097
+ const nodes = live?.nodes || {};
2098
+ const statusOf = (node) => String(nodes[node.id]?.status || '').toUpperCase();
2099
+ return plan.find((node) => statusOf(node) === 'RUNNING')
2100
+ || plan.find((node) => {
2101
+ const stage = STAGES.find((item) => item.id === currentStageId(live));
2102
+ return stage?.types.includes(node.type) && !['PASSED', 'SKIPPED', ''].includes(statusOf(node));
2103
+ })
2104
+ || [...plan].reverse().find((node) => statusOf(node) === 'PASSED')
2105
+ || null;
2106
+ }
2107
+
2108
+ function iterationText(node, live) {
2109
+ const group = (draft?.loopGroups || []).find((item) => (item.nodeIds || []).includes(node?.id));
2110
+ if (!group) return '';
2111
+ const iteration = live?.loopGroups?.[group.id]?.iteration ?? live?.run?.iteration ?? '—';
2112
+ return `iteration ${iteration} / ${group.maxIterations ?? '—'}`;
2113
+ }
2114
+
2115
+ function stepEvidenceHtml(live) {
2116
+ const artifacts = live?.artifacts || {};
2117
+ const chips = [];
2118
+ const findings = findingsLabel(artifacts['artifact.findings']);
2119
+ if (findings) chips.push(labeledChip('Findings', findings));
2120
+ const tests = verificationLabel(artifacts['artifact.verification']);
2121
+ if (tests) chips.push(labeledChip('Tests', tests));
2122
+ const drift = driftLabel(artifacts['artifact.drift']);
2123
+ if (drift) chips.push(labeledChip('Scope', drift === 'none' ? 'in map' : drift));
2124
+ return chips.join('');
2125
+ }
2126
+
2127
+ function currentStepHtml(live) {
2128
+ const node = focusNodeRecord(live);
2129
+ if (!node) return '<p class="muted">No step is running.</p>';
2130
+ const plan = live.plan?.nodes || [];
2131
+ const index = Math.max(0, plan.indexOf(node));
2132
+ const runtime = live.nodes?.[node.id] || {};
2133
+ const running = String(runtime.status || '').toUpperCase() === 'RUNNING';
2134
+ const duration = formatDuration(nodeDurationMs(node.id, live, draft || live.plan));
2135
+ const timing = running
2136
+ ? (duration ? `running ${duration}` : 'running')
2137
+ : (duration || statusWord(runtime.status));
2138
+ const loop = iterationText(node, live);
2139
+ const activity = runtime.activity || runtime.reason || runtime.summary || 'Waiting for the next persisted event.';
2140
+ const next = plan.slice(index + 1, index + 4).map((item) => displayName(item));
2141
+ return `
2142
+ <h2 class="live-card-title">Current step</h2>
2143
+ <div class="current-head">
2144
+ <span class="node-icon">${nodeIcon(node.type)}</span>
2145
+ <div>
2146
+ <h2>${escapeHtml(displayName(node))} · ${escapeHtml(node.type)}</h2>
2147
+ <p>${escapeHtml([panelSubtitle(node, index).split(' · ').slice(0, 1).join(''), loop, timing].filter(Boolean).join(' · '))}</p>
2148
+ </div>
2149
+ </div>
2150
+ <p class="current-activity"><span class="chip-label">Latest activity</span> ${escapeHtml(activity)}</p>
2151
+ <div class="chip-row">${stepEvidenceHtml(live)}</div>
2152
+ <div class="current-actions">
2153
+ <button type="button" data-open-node="${escapeHtml(node.id)}">Open node details</button>
2154
+ <button type="button" class="primary" data-start-agent>Start with AI Agent</button>
2155
+ </div>
2156
+ ${next.length ? `<p class="current-next">Next: ${escapeHtml(next.join(' → '))}</p>` : ''}
2157
+ `;
2158
+ }
2159
+
2160
+ function questionBannerHtml(questions) {
2161
+ return (questions || []).map((question) => `
2162
+ <form class="answer-form" data-question-id="${escapeHtml(question.questionId || '')}">
2163
+ <p><span class="chip-label">Question</span> ${escapeHtml(question.message || '')}</p>
2164
+ <textarea name="answer" maxlength="4000" aria-label="Answer" placeholder="Write the answer"></textarea>
2165
+ <button type="submit" class="primary">Answer in Studio</button>
2166
+ </form>
2167
+ `).join('');
2168
+ }
2169
+
2170
+ function journeyStepsHtml(live) {
2171
+ const journeyStatuses = new Set(['pending', 'active', 'complete']);
2172
+ return (live?.journey?.steps || []).map((step) => {
2173
+ const status = String(step?.status || '').toLowerCase();
2174
+ const safeStatus = journeyStatuses.has(status) ? status : 'unknown';
2175
+ const label = String(step?.id || '').replaceAll('_', ' ');
2176
+ const suffix = safeStatus === 'unknown' ? ' (status unavailable)' : '';
2177
+ const blocked = step?.blocked
2178
+ ? (live.journey?.pendingQuestions == null
2179
+ ? ' · unanswered count unavailable'
2180
+ : ` · ${Number(live.journey.pendingQuestions)} unanswered`)
2181
+ : '';
2182
+ return `<li class="${safeStatus}">${escapeHtml(label + suffix + blocked)}</li>`;
2183
+ }).join('');
2184
+ }
2185
+
2186
+ function groupedTimelineHtml(live) {
2187
+ const workflow = Array.isArray(live?.events) ? live.events : [];
2188
+ const source = workflow.length ? workflow : lifecycleEvents;
2189
+ const groups = [];
2190
+ const seen = new Map();
2191
+ for (const event of source) {
2192
+ const key = eventActor(event, live);
2193
+ if (!seen.has(key)) {
2194
+ seen.set(key, groups.length);
2195
+ groups.push({ key, events: [] });
2196
+ }
2197
+ groups[seen.get(key)].events.push(event);
2198
+ }
2199
+ if (!groups.length) return '';
2200
+ return `<li class="timeline-groups"><div class="timeline-columns">${groups.map((group) => `
2201
+ <section class="step-group">
2202
+ <h3>${escapeHtml(group.key)}</h3>
2203
+ <ul>${group.events.map((event) => `<li>${timeTag(event.at, Date.now(), 'clock') || '—'} ${escapeHtml(liveEventLabel(event))}</li>`).join('')}</ul>
2204
+ </section>`).join('')}</div></li>`;
2205
+ }
2206
+
2207
+ function renderRunSummary() {
2208
+ const card = byId('run-summary-card');
2209
+ if (!card) return;
2210
+ const live = catalog.live;
2211
+ const state = live?.run?.state;
2212
+ if (!live?.run || !TERMINAL_RUN_STATES.has(state)) {
2213
+ card.hidden = true;
2214
+ card.innerHTML = '';
2215
+ return;
2216
+ }
2217
+ const artifacts = live.artifacts || liveArtifacts || {};
2218
+ const duration = formatDuration(completedRunDurationMs(live));
2219
+ card.hidden = false;
2220
+ card.innerHTML = `<div class="summary-facts">${[
2221
+ summaryFact('State', state),
2222
+ summaryFact('Destination', deliveryDestination(live)),
2223
+ summaryFact('Verdict', textOrNull(artifacts['artifact.verdict']?.verdict) || textOrNull(live.run?.verdict)),
2224
+ summaryFact('Approver', approverName(live)),
2225
+ summaryFact('Duration', duration || null),
2226
+ summaryFact('Tests', verificationLabel(artifacts['artifact.verification'])),
2227
+ summaryFact('Findings', findingsLabel(artifacts['artifact.findings'])),
2228
+ summaryFact('Drift', driftLabel(artifacts['artifact.drift'])),
2229
+ summaryFact('Receipt', receiptLabel(artifacts['artifact.receipt'])),
2230
+ summaryFact('Tokens', tokenLabel(live))
2231
+ ].join('')}</div>`;
2232
+ }
2233
+
2234
+ function refreshWiringLive() {
2235
+ if (workspace !== 'wiring' || !draft || interaction || connection) return;
2236
+ renderGraph({ live: true });
2237
+ }
2238
+
1033
2239
  function renderLive() {
2240
+ renderRunSummary();
1034
2241
  const live = catalog.live;
1035
2242
  const summary = byId('run-summary');
1036
2243
  const rail = byId('stage-rail');
1037
2244
  const journey = byId('run-journey');
1038
- const meta = byId('live-view')?.querySelector?.('.live-meta');
1039
- const banner = byId('live-view')?.querySelector?.('.pending-banner');
2245
+ const meta = byId('live-meta');
2246
+ const current = byId('live-current');
2247
+ const banner = byId('question-banner');
1040
2248
  if (!live) {
1041
2249
  if (summary) summary.textContent = 'No active run';
1042
- if (rail) {
1043
- rail.innerHTML = STAGES.map((stage) => `<li class="pending">${escapeHtml(stage.label)}</li>`).join('');
1044
- }
2250
+ if (rail) rail.innerHTML = progressRailHtml(null);
1045
2251
  if (meta) meta.innerHTML = '';
2252
+ if (current) current.innerHTML = '';
1046
2253
  if (banner) {
1047
2254
  banner.hidden = true;
1048
2255
  banner.innerHTML = '';
@@ -1050,63 +2257,66 @@ function renderLive() {
1050
2257
  if (journey) journey.innerHTML = '';
1051
2258
  return;
1052
2259
  }
1053
- const stageId = currentStageId(live);
1054
2260
  const run = live.run || {};
1055
2261
  const presence = live.presence || agentPresence;
1056
2262
  if (summary) {
1057
- summary.textContent = `${run.displayName || run.runId || 'run'} · ${run.state || ''} · ${heartbeatAge(presence.lastHeartbeatAt)}`;
1058
- }
1059
- if (rail) {
1060
- rail.innerHTML = STAGES.map((stage) => {
1061
- const current = stage.id === stageId;
1062
- return `<li class="${current ? 'active' : 'pending'}">${escapeHtml(stage.label)}</li>`;
1063
- }).join('');
1064
- }
1065
- const artifacts = live.artifacts || liveArtifacts;
1066
- const guard = artifacts['artifact.guard'] || {};
1067
- const drift = artifacts['artifact.drift'] || {};
1068
- const receipt = artifacts['artifact.receipt'] || {};
2263
+ const started = run.createdAt ? `started ${timeTag(run.createdAt)}` : '';
2264
+ const beatAge = heartbeatAge(presence.lastHeartbeatAt);
2265
+ const beat = presence?.lastHeartbeatAt ? `heartbeat ${timeTag(presence.lastHeartbeatAt)}` : escapeHtml(beatAge);
2266
+ summary.innerHTML = `${escapeHtml(run.displayName || run.runId || 'run')} · ${escapeHtml(run.state || '')}${started ? ` · ${started}` : ''} · ${beat}`;
2267
+ }
2268
+ if (rail) rail.innerHTML = progressRailHtml(live);
1069
2269
  if (meta) {
1070
- meta.innerHTML = `
1071
- <span>${escapeHtml(run.tier?.current || run.mode || '')}</span>
1072
- <span>iter ${escapeHtml(String(run.iteration ?? '—'))}</span>
1073
- <span>${escapeHtml(String(live.budget?.spentThisRun ?? 0))} / ${escapeHtml(String(live.budget?.perRunTokenLimit ?? 0))} tokens</span>
1074
- <span class="chip">${escapeHtml(String(guard.warn || 0))} warn · ${escapeHtml(String(guard.block || 0))} block</span>
1075
- <span class="chip">drift ${escapeHtml(String(drift.outOfMapCount || 0))}</span>
1076
- <span class="chip">${receipt.verified ? 'receipt ok' : 'receipt pending'}</span>
1077
- `;
2270
+ meta.innerHTML = liveMetaHtml(live);
2271
+ paintBudget(live);
1078
2272
  }
2273
+ if (current) current.innerHTML = currentStepHtml(live);
1079
2274
  const pending = live.interactions?.pending || [];
1080
2275
  if (banner) {
1081
2276
  banner.hidden = pending.length === 0;
1082
- banner.innerHTML = pending.map((question) =>
1083
- `<p><strong>Q${escapeHtml(String(question.number))}</strong> ${escapeHtml(question.message)}</p>`
1084
- ).join('');
2277
+ banner.innerHTML = questionBannerHtml(pending);
1085
2278
  }
1086
- const journeyStatuses = new Set(['pending', 'active', 'complete']);
1087
2279
  const degradedSources = live.journey?.degradedSources || [];
1088
- const timeline = (live.journey?.steps || []).map((step) => {
1089
- const status = String(step?.status || '').toLowerCase();
1090
- const safeStatus = journeyStatuses.has(status) ? status : 'unknown';
1091
- const label = String(step?.id || '').replaceAll('_', ' ');
1092
- const suffix = safeStatus === 'unknown' ? ' (status unavailable)' : '';
1093
- const blocked = step?.blocked
1094
- ? (live.journey?.pendingQuestions == null
1095
- ? ' · unanswered count unavailable'
1096
- : ` · ${Number(live.journey.pendingQuestions)} unanswered`)
1097
- : '';
1098
- return `<li class="${safeStatus}">${escapeHtml(label + suffix + blocked)}</li>`;
1099
- }).join('');
1100
- const eventsHtml = (lifecycleEvents.slice(-8).reverse().map((event) =>
1101
- `<li class="event">${escapeHtml(String(event.at || '').slice(11, 19))} · ${escapeHtml(event.type)} · ${escapeHtml(event.message || '')}</li>`
1102
- ).join(''));
1103
2280
  if (journey) {
1104
- journey.innerHTML = timeline + eventsHtml + (degradedSources.length
2281
+ journey.innerHTML = journeyStepsHtml(live) + groupedTimelineHtml(live) + (degradedSources.length
1105
2282
  ? `<li class="unknown">${escapeHtml(`${degradedSources.join(' and ')} unavailable — journey may be incomplete`)}</li>`
1106
2283
  : '');
1107
2284
  }
1108
2285
  }
1109
2286
 
2287
+ async function submitAnswer(questionId, message) {
2288
+ const runId = followedRunId();
2289
+ const text = String(message || '').trim();
2290
+ if (!runId || !questionId || !text) {
2291
+ notify('Write an answer first.');
2292
+ return;
2293
+ }
2294
+ await api(`/api/runs/${encodeURIComponent(runId)}/questions/${encodeURIComponent(questionId)}/answer`, {
2295
+ method: 'POST',
2296
+ body: JSON.stringify({ message: text, actor: 'human' })
2297
+ });
2298
+ notify('Answer recorded.');
2299
+ await loadLive(runId);
2300
+ }
2301
+
2302
+ function onLiveClick(event) {
2303
+ const open = closestReal(event.target, '[data-open-node]');
2304
+ if (open?.dataset?.openNode) {
2305
+ showWorkspace('wiring');
2306
+ openNodePanel(open.dataset.openNode);
2307
+ return;
2308
+ }
2309
+ if (closestReal(event.target, '[data-start-agent]')) copyAgentHandoff(followedRunId() || undefined);
2310
+ }
2311
+
2312
+ function onLiveSubmit(event) {
2313
+ const form = event.target;
2314
+ if (!form?.dataset?.questionId) return;
2315
+ event.preventDefault?.();
2316
+ const field = form.querySelector?.('[name="answer"]');
2317
+ submitAnswer(form.dataset.questionId, field?.value || '');
2318
+ }
2319
+
1110
2320
  function maybeOpenOnboarding() {
1111
2321
  const dialog = byId('goal-dialog');
1112
2322
  if (!eventsReady || catalog.live || dialog.open || onboardingDismissed) return;
@@ -1167,6 +2377,7 @@ function applyEvent(event) {
1167
2377
  lifecycleEvents = lifecycleEvents.concat(incoming).slice(-100);
1168
2378
  if (event.payload?.presence) agentPresence = event.payload;
1169
2379
  else if (catalog.live) catalog.live.lifecycle = event.payload;
2380
+ applyLifecycleNodes(incoming);
1170
2381
  } else if (event.type === 'presence') {
1171
2382
  agentPresence = event.payload || agentPresence;
1172
2383
  if (catalog.live) catalog.live.presence = agentPresence;
@@ -1180,6 +2391,23 @@ function applyEvent(event) {
1180
2391
  scheduleLiveRender();
1181
2392
  }
1182
2393
 
2394
+ const LIVE_NODE_STATUSES = new Set(['PENDING', 'READY', 'RUNNING', 'PASSED', 'FAILED', 'SKIPPED', 'BLOCKED', 'WAITING']);
2395
+
2396
+ function applyLifecycleNodes(events) {
2397
+ if (!catalog.live) return;
2398
+ catalog.live.nodes = catalog.live.nodes || {};
2399
+ for (const item of events || []) {
2400
+ const status = String(item?.status || '').toUpperCase();
2401
+ if (!item?.nodeId || !LIVE_NODE_STATUSES.has(status)) continue;
2402
+ const current = catalog.live.nodes[item.nodeId] || {};
2403
+ catalog.live.nodes[item.nodeId] = {
2404
+ ...current,
2405
+ status,
2406
+ ...(item.at ? { updatedAt: item.at } : {})
2407
+ };
2408
+ }
2409
+ }
2410
+
1183
2411
  function parseSseBlock(block) {
1184
2412
  let type = 'message';
1185
2413
  let data = '';
@@ -1318,14 +2546,15 @@ async function loadRecipe() {
1318
2546
  draft = normalizeDraftGraph(structuredClone(result.recipe));
1319
2547
  source = result.source;
1320
2548
  loadedRecipeId = draft.id;
2549
+ rememberLoadedWiring();
1321
2550
  selectedId = null;
1322
2551
  selectedIds.clear();
1323
2552
  selectedEdgeId = null;
1324
2553
  positions = new Map(Object.entries(saved.layout?.positions || {}));
1325
2554
  ensurePositions();
1326
2555
  viewport = saved.layout?.viewport || { x: 0, y: 0, scale: 1 };
2556
+ hasFitted = false;
1327
2557
  renderGraph();
1328
- if (!saved.layout || (draft.nodes.length <= 12 && viewport.scale < 0.45)) fitView();
1329
2558
  captureHistory({ reset: true });
1330
2559
  await validateDraft();
1331
2560
  }
@@ -1343,24 +2572,733 @@ async function refreshCatalog(selectedRecipe) {
1343
2572
  renderLive();
1344
2573
  }
1345
2574
 
2575
+ function closestReal(element, selector) {
2576
+ const node = element?.closest ? element : element?.parentElement;
2577
+ if (typeof node?.closest !== 'function') return null;
2578
+ const found = node.closest(selector);
2579
+ if (!found || typeof found.matches !== 'function' || !found.matches(selector)) return null;
2580
+ return found;
2581
+ }
2582
+
2583
+ function runtimeFor(node) {
2584
+ if (!node) return null;
2585
+ return catalog.live?.nodes?.[node.id] || null;
2586
+ }
2587
+
2588
+ function nodeSummary(node) {
2589
+ const runtime = runtimeFor(node) || {};
2590
+ const raw = runtime.activity || runtime.summary || node.summary || node.description || '';
2591
+ const line = String(raw).replace(/\s+/g, ' ').trim();
2592
+ if (!line) return '';
2593
+ return line.length > 160 ? `${line.slice(0, 159)}…` : line;
2594
+ }
2595
+
2596
+ function nodeDepths() {
2597
+ const depths = new Map();
2598
+ const visiting = new Set();
2599
+ const depthFor = (node) => {
2600
+ if (!node) return 0;
2601
+ if (depths.has(node.id)) return depths.get(node.id);
2602
+ if (visiting.has(node.id)) return 0;
2603
+ visiting.add(node.id);
2604
+ const depth = (node.dependsOn || []).reduce((maximum, dependencyId) => {
2605
+ const dependency = draft.nodes.find((candidate) => candidate.id === dependencyId);
2606
+ return Math.max(maximum, dependency ? depthFor(dependency) + 1 : 0);
2607
+ }, 0);
2608
+ visiting.delete(node.id);
2609
+ depths.set(node.id, depth);
2610
+ return depth;
2611
+ };
2612
+ for (const node of draft?.nodes || []) depthFor(node);
2613
+ return depths;
2614
+ }
2615
+
2616
+ function columnsByDepth() {
2617
+ const depths = nodeDepths();
2618
+ const columns = new Map();
2619
+ for (const node of draft?.nodes || []) {
2620
+ const depth = depths.get(node.id) || 0;
2621
+ if (!columns.has(depth)) columns.set(depth, []);
2622
+ columns.get(depth).push(node.id);
2623
+ }
2624
+ for (const column of columns.values()) {
2625
+ column.sort((left, right) => (positions.get(left)?.y ?? 0) - (positions.get(right)?.y ?? 0)
2626
+ || String(left).localeCompare(String(right)));
2627
+ }
2628
+ return columns;
2629
+ }
2630
+
2631
+ function focusNode(nodeId) {
2632
+ nodeElements().find((element) => element.dataset.nodeId === nodeId)?.focus?.();
2633
+ }
2634
+
2635
+ function clearSelection() {
2636
+ selectedId = null;
2637
+ selectedIds = new Set();
2638
+ selectedEdgeId = null;
2639
+ updateSelection();
2640
+ renderEdges();
2641
+ }
2642
+
2643
+ function moveSelection(direction) {
2644
+ if (!draft?.nodes?.length) return null;
2645
+ const columns = columnsByDepth();
2646
+ const depths = [...columns.keys()].sort((left, right) => left - right);
2647
+ if (!depths.length) return null;
2648
+ const known = selectedId && draft.nodes.some((node) => node.id === selectedId);
2649
+ if (!known) {
2650
+ const first = columns.get(depths[0])[0];
2651
+ selectNode(first);
2652
+ focusNode(first);
2653
+ return first;
2654
+ }
2655
+ const depth = nodeDepths().get(selectedId) || 0;
2656
+ const column = columns.get(depth) || [];
2657
+ const row = Math.max(0, column.indexOf(selectedId));
2658
+ let next = null;
2659
+ if (direction === 'up') next = column[row - 1] || null;
2660
+ else if (direction === 'down') next = column[row + 1] || null;
2661
+ else {
2662
+ const depthIndex = depths.indexOf(depth);
2663
+ const neighborDepth = depths[depthIndex + (direction === 'right' ? 1 : -1)];
2664
+ if (neighborDepth == null) return selectedId;
2665
+ const neighbor = columns.get(neighborDepth) || [];
2666
+ next = neighbor[Math.min(row, neighbor.length - 1)] || null;
2667
+ }
2668
+ if (!next || next === selectedId) return selectedId;
2669
+ selectNode(next);
2670
+ focusNode(next);
2671
+ return next;
2672
+ }
2673
+
2674
+ function scheduleTooltip(element) {
2675
+ clearTimeout(tooltipTimer);
2676
+ const nodeId = element?.dataset?.nodeId;
2677
+ tooltipTimer = setTimeout(() => {
2678
+ tooltipTimer = null;
2679
+ if (!nodeId || !draft?.nodes?.some((node) => node.id === nodeId)) return;
2680
+ const current = nodeElements().find((item) => item.dataset.nodeId === nodeId) || element;
2681
+ showTooltip(current);
2682
+ }, TOOLTIP_DELAY_MS);
2683
+ }
2684
+
2685
+ function hideTooltip() {
2686
+ clearTimeout(tooltipTimer);
2687
+ tooltipTimer = null;
2688
+ if (nodeTooltip) nodeTooltip.hidden = true;
2689
+ }
2690
+
2691
+ function showTooltip(element) {
2692
+ const node = draft?.nodes?.find((item) => item.id === element?.dataset?.nodeId);
2693
+ if (!node || !nodeTooltip) return;
2694
+ const index = draft.nodes.indexOf(node);
2695
+ const summary = nodeSummary(node);
2696
+ const lines = [
2697
+ `<strong>${escapeHtml(displayName(node))}</strong>`,
2698
+ `<span class="tooltip-type">${escapeHtml(node.type)} · ${escapeHtml(stageLabel(node, index))}</span>`,
2699
+ `<span class="tooltip-status">${escapeHtml(liveStatusText(node))}</span>`
2700
+ ];
2701
+ if (summary) lines.push(`<span class="tooltip-summary">${escapeHtml(summary)}</span>`);
2702
+ nodeTooltip.innerHTML = lines.join('');
2703
+ const canvasRect = byId('canvas')?.getBoundingClientRect?.() || { left: 0, top: 0, width: 0 };
2704
+ const rect = element.getBoundingClientRect?.() || { left: 0, bottom: 0 };
2705
+ const width = 240;
2706
+ const left = Math.max(8, Math.min(rect.left - canvasRect.left, Math.max(8, canvasRect.width - width - 8)));
2707
+ nodeTooltip.style.left = `${left}px`;
2708
+ nodeTooltip.style.top = `${rect.bottom - canvasRect.top + 8}px`;
2709
+ nodeTooltip.hidden = false;
2710
+ }
2711
+
2712
+ function onNodeClick(event) {
2713
+ if (closestReal(event.target, '.port')) return;
2714
+ if (event.shiftKey || spacePressed || suppressNodeClick) {
2715
+ suppressNodeClick = false;
2716
+ return;
2717
+ }
2718
+ openNodePanel(event.currentTarget?.dataset?.nodeId);
2719
+ }
2720
+
2721
+ function headerDuration(node, io) {
2722
+ if (io?.durationMs != null && io.durationMs !== '') {
2723
+ const formatted = formatDuration(Number(io.durationMs));
2724
+ if (formatted) return formatted;
2725
+ }
2726
+ const derived = formatDuration(nodeDurationMs(node?.id, catalog.live, draft));
2727
+ if (derived) return derived;
2728
+ const state = graphStateClass(runtimeFor(node)?.status);
2729
+ if (state !== 'passed' && state !== 'failed' && state !== 'active') return '';
2730
+ return formatDuration(legacyDurationMs(runtimeFor(node)));
2731
+ }
2732
+
2733
+ function tabButton(id, label, badge = 0) {
2734
+ const selected = panelTab === id;
2735
+ const count = Number(badge) > 0 ? `<span class="tab-count">${escapeHtml(String(badge))}</span>` : '';
2736
+ return `<button type="button" role="tab" id="node-tab-${id}" class="io-tab" data-tab="${id}" aria-selected="${selected ? 'true' : 'false'}" aria-controls="node-pane-${id}" tabindex="${selected ? '0' : '-1'}">${label}${count}</button>`;
2737
+ }
2738
+
2739
+ function evidenceCount(view) {
2740
+ const recorded = Number(view?.io?.nodeEvidence?.count);
2741
+ if (Number.isFinite(recorded) && recorded > 0) return recorded;
2742
+ const cards = view?.io?.nodeEvidence?.cards;
2743
+ return Array.isArray(cards) ? cards.length : 0;
2744
+ }
2745
+
2746
+ function nodeLoopGroup(node) {
2747
+ if (!node) return null;
2748
+ return (draft?.loopGroups || []).find((group) =>
2749
+ (group?.nodeIds || []).includes(node.id)
2750
+ || group?.entryNodeId === node.id
2751
+ || group?.decisionNodeId === node.id
2752
+ ) || null;
2753
+ }
2754
+
2755
+ function loopChipValue(node, io) {
2756
+ const group = nodeLoopGroup(node);
2757
+ const groupId = io?.output?.loopGroupId || group?.id;
2758
+ if (!groupId) return '';
2759
+ const iteration = io?.output?.loopIteration ?? io?.loopIteration;
2760
+ const max = group?.maxIterations;
2761
+ if (iteration == null && max == null) return groupId;
2762
+ const step = iteration == null ? '—' : String(iteration);
2763
+ return max ? `${groupId} · ${step}/${max}` : `${groupId} · ${step}`;
2764
+ }
2765
+
2766
+ function attemptCount(io) {
2767
+ const groups = io?.timelineGroups;
2768
+ if (!Array.isArray(groups) || !groups.length) return null;
2769
+ return Math.max(...groups.map((group) => Number(group.attempt) || 1));
2770
+ }
2771
+
2772
+ function nodeChip(label, valueHtml) {
2773
+ return `<span class="node-chip"><span class="chip-label">${escapeHtml(label)}</span><strong>${valueHtml}</strong></span>`;
2774
+ }
2775
+
2776
+ function panelSubtitle(node, index) {
2777
+ const stage = stageLabel(node, index).toLowerCase().replace(/(^|\s)\w/g, (letter) => letter.toUpperCase());
2778
+ const recipe = draft?.id ? `${draft.id}${draft.version != null ? ` v${draft.version}` : ''}` : '';
2779
+ return [stage, node.type, recipe].filter(Boolean).join(' · ');
2780
+ }
2781
+
2782
+ function nodeChipRow(node, io, runtime) {
2783
+ const status = runtime?.status || io?.output?.status;
2784
+ const state = graphStateClass(status);
2785
+ const chips = [nodeChip('Status', `<span class="status-text status-${state}">${escapeHtml(statusWord(status))}</span>`)];
2786
+ const duration = headerDuration(node, io);
2787
+ if (duration) chips.push(nodeChip('Duration', escapeHtml(duration)));
2788
+ if (io?.finishedAt) {
2789
+ const finished = timeTag(io.finishedAt);
2790
+ if (finished) chips.push(nodeChip('Finished', finished));
2791
+ }
2792
+ const loop = loopChipValue(node, io);
2793
+ if (loop) chips.push(nodeChip('Loop', escapeHtml(loop)));
2794
+ const attempts = attemptCount(io);
2795
+ if (attempts) chips.push(nodeChip('Attempts', escapeHtml(String(attempts))));
2796
+ const reason = io?.output?.reason || runtime?.reason;
2797
+ if (reason && (state === 'failed' || String(status || '').toLowerCase() === 'blocked')) {
2798
+ chips.push(nodeChip('Reason', escapeHtml(reason)));
2799
+ }
2800
+ return `<div class="node-chip-row">${chips.join('')}</div>`;
2801
+ }
2802
+
2803
+ function jsonBlock(value) {
2804
+ if (value == null || value === '') return '<p class="muted">None</p>';
2805
+ const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
2806
+ return `<pre>${escapeHtml(text)}</pre>`;
2807
+ }
2808
+
2809
+ function artifactPreview(artifact) {
2810
+ if (!artifact || artifact.unavailable) return '';
2811
+ const preview = artifact.preview || artifact;
2812
+ if (!preview.content) return '';
2813
+ const path = preview.path || artifact.descriptor?.path || '';
2814
+ return `${path ? `<p class="artifact-path">${escapeHtml(path)}</p>` : ''}<pre>${escapeHtml(preview.content)}</pre>`;
2815
+ }
2816
+
2817
+ function fileChipRow(files) {
2818
+ const list = (files || []).filter((file) => file && (file.name || file.path));
2819
+ if (!list.length) return '';
2820
+ return `<div class="artifact-chips">${list.map((file) => {
2821
+ const name = escapeHtml(file.name || file.path);
2822
+ if (!file.path || file.state === 'rejected') return `<span class="artifact-chip">${name}</span>`;
2823
+ return `<button type="button" class="artifact-chip" data-artifact-path="${escapeHtml(file.path)}">${name}</button>`;
2824
+ }).join('')}</div>`;
2825
+ }
2826
+
2827
+ function previewBlock(preview) {
2828
+ if (!preview) return '';
2829
+ if (preview.error) {
2830
+ return `<p class="validation-message">${escapeHtml(preview.path || 'Artifact')}: ${escapeHtml(preview.error)}</p>`;
2831
+ }
2832
+ const content = preview.content || '';
2833
+ if (!content && !preview.path) return '';
2834
+ return `<article class="evidence-card"><p class="artifact-path">${escapeHtml(preview.path || '')}</p>${content ? `<pre>${escapeHtml(content)}</pre>` : '<p class="muted">No preview.</p>'}</article>`;
2835
+ }
2836
+
2837
+ function renderEvidenceCard(card) {
2838
+ const lines = (card.lines || []).map((line) => {
2839
+ const raw = line.value == null ? '' : String(line.value);
2840
+ const value = looksLikeIso(raw) ? (timeTag(raw) || escapeHtml(raw)) : escapeHtml(raw);
2841
+ const duration = formatDuration(Number(line.durationMs));
2842
+ const extra = [line.detail, duration].filter(Boolean).join(' · ');
2843
+ return `<li class="evidence-line"><span class="evidence-label">${escapeHtml(line.label || '')}</span><span class="evidence-value">${value}</span>${extra ? `<span class="evidence-detail">${escapeHtml(extra)}</span>` : ''}</li>`;
2844
+ }).join('');
2845
+ return `<article class="evidence-card"><h3>${escapeHtml(card.title || 'Evidence')}</h3>${lines ? `<ul class="evidence-lines">${lines}</ul>` : ''}${card.note ? `<p class="evidence-note">${escapeHtml(card.note)}</p>` : ''}</article>`;
2846
+ }
2847
+
2848
+ function evidenceBody(evidence) {
2849
+ const changed = evidence?.status === 'changed' || evidence?.status === 'rejected';
2850
+ const cards = evidence?.cards || [];
2851
+ if (!evidence || (!changed && !cards.length)) {
2852
+ return `<p class="muted">${escapeHtml(evidence?.summary || 'No evidence recorded for this node yet.')}</p>${fileChipRow(evidence?.files)}`;
2853
+ }
2854
+ const banner = changed
2855
+ ? `<p class="validation-message">${escapeHtml(evidence.message || 'artifact changed')}</p>`
2856
+ : '';
2857
+ return banner + cards.map(renderEvidenceCard).join('') + fileChipRow(evidence.files);
2858
+ }
2859
+
2860
+ function inputPane(io) {
2861
+ const input = io?.input || {};
2862
+ const dependencies = (input.dependencies || []).map((item) =>
2863
+ `<li><strong>${escapeHtml(item.nodeId)}</strong> <span class="muted">${escapeHtml(item.status || '')}</span></li>`
2864
+ ).join('');
2865
+ return `
2866
+ ${input.task ? `<h3>Task</h3><p>${escapeHtml(input.task)}</p>` : '<p class="muted">This node reads its input from upstream nodes.</p>'}
2867
+ ${input.constraints ? `<h3>Constraints</h3><p>${escapeHtml(input.constraints)}</p>` : ''}
2868
+ ${input.goal ? `<h3>Goal</h3>${jsonBlock(input.goal)}` : ''}
2869
+ <h3>Upstream</h3>
2870
+ ${dependencies ? `<ul>${dependencies}</ul>` : '<p class="muted">No upstream nodes.</p>'}
2871
+ `;
2872
+ }
2873
+
2874
+ function outputPane(view) {
2875
+ const io = view?.io || {};
2876
+ const summary = io.nodeEvidence?.summary || io.output?.summary || 'No evidence recorded for this node yet.';
2877
+ return `<p class="node-summary">${escapeHtml(summary)}</p>${fileChipRow(io.nodeEvidence?.files)}${artifactPreview(io.output?.artifact)}${previewBlock(view?.preview)}`;
2878
+ }
2879
+
2880
+ function evidencePane(view) {
2881
+ if (view.io?.nodeEvidence) return evidenceBody(view.io.nodeEvidence) + previewBlock(view.preview);
2882
+ const fetched = view.artifacts || [];
2883
+ if (fetched.length) {
2884
+ return fetched.map((artifact) => artifact.error
2885
+ ? `<p class="validation-message">${escapeHtml(artifact.path || 'Artifact')}: ${escapeHtml(artifact.error)}</p>`
2886
+ : `<article class="evidence-card"><p class="artifact-path">${escapeHtml(artifact.path || '')}</p><pre>${escapeHtml(artifact.content || '')}</pre></article>`
2887
+ ).join('') + previewBlock(view.preview);
2888
+ }
2889
+ return `<p class="muted">No evidence recorded for this node yet.</p>${previewBlock(view.preview)}`;
2890
+ }
2891
+
2892
+ function renderTimelineGroups(groups) {
2893
+ if (!groups.length) return '<p class="muted">No lifecycle events for this node yet.</p>';
2894
+ return groups.map((group) => `
2895
+ <section class="timeline-group">
2896
+ <h3>${escapeHtml(group.label || 'Step')}</h3>
2897
+ <ul class="panel-timeline">${(group.events || []).map((event) => `
2898
+ <li>
2899
+ ${timeTag(event.at) || '<span class="muted">—</span>'}
2900
+ <strong>${escapeHtml(event.label || event.type || 'event')}</strong>
2901
+ </li>`).join('')}</ul>
2902
+ </section>`).join('');
2903
+ }
2904
+
2905
+ function timelinePane(view) {
2906
+ if (Array.isArray(view.io?.timelineGroups)) return renderTimelineGroups(view.io.timelineGroups);
2907
+ const node = draft?.nodes?.find((item) => item.id === panelNodeId);
2908
+ const gate = node?.legacyGate;
2909
+ const events = (view.events || []).filter((event) => event?.nodeId === panelNodeId || (gate && event?.gate === gate));
2910
+ return renderTimelineGroups(events.length ? [{
2911
+ label: 'This node',
2912
+ events: events.map((event) => ({
2913
+ at: event.at,
2914
+ label: event.message || String(event.type || 'event').replaceAll('_', ' ').toLowerCase()
2915
+ }))
2916
+ }] : []);
2917
+ }
2918
+
2919
+ function paneBody(view) {
2920
+ if (view.status === 'empty') {
2921
+ return '<div class="empty-state"><h3>No run to inspect</h3><p>Start a run from the Goal sheet, or open a past run, to see this node\'s input, output, evidence, and timeline.</p></div>';
2922
+ }
2923
+ if (view.status === 'loading') return '<p class="muted">Loading node details…</p>';
2924
+ if (view.status === 'error') return `<p class="validation-message">${escapeHtml(view.message || 'Could not load this node.')}</p>`;
2925
+ if (panelTab === 'output') return outputPane(view);
2926
+ if (panelTab === 'evidence') return evidencePane(view);
2927
+ if (panelTab === 'timeline') return timelinePane(view);
2928
+ return inputPane(view.io);
2929
+ }
2930
+
2931
+ function renderNodePanel(next) {
2932
+ if (next) panelView = next;
2933
+ const panel = byId('node-panel');
2934
+ const node = draft?.nodes?.find((item) => item.id === panelNodeId);
2935
+ if (!panel || !node) return;
2936
+ const index = draft.nodes.indexOf(node);
2937
+ const runtime = runtimeFor(node);
2938
+ panel.innerHTML = `
2939
+ <div class="node-panel-frame">
2940
+ <header class="node-panel-head">
2941
+ <span class="node-icon panel-type-icon">${nodeIcon(node.type)}</span>
2942
+ <div class="node-panel-titles">
2943
+ <h2>${escapeHtml(displayName(node))}</h2>
2944
+ <p>${escapeHtml(panelSubtitle(node, index))}</p>
2945
+ </div>
2946
+ <button type="button" class="node-panel-close" aria-label="Close node panel">×</button>
2947
+ </header>
2948
+ ${nodeChipRow(node, panelView.io, runtime)}
2949
+ <div class="io-tabs" role="tablist" aria-label="Node details">
2950
+ ${tabButton('overview', 'Overview')}
2951
+ ${tabButton('output', 'Output')}
2952
+ ${tabButton('evidence', 'Evidence', evidenceCount(panelView))}
2953
+ ${tabButton('timeline', 'Timeline')}
2954
+ </div>
2955
+ <div class="node-panel-body" role="tabpanel" id="node-pane-${panelTab}" aria-labelledby="node-tab-${panelTab}">
2956
+ ${paneBody(panelView)}
2957
+ </div>
2958
+ </div>
2959
+ `;
2960
+ }
2961
+
2962
+ function collectArtifactPaths(io) {
2963
+ const paths = [];
2964
+ const push = (artifact) => {
2965
+ if (!artifact || artifact.unavailable) return;
2966
+ const path = artifact.preview?.path || artifact.descriptor?.path || artifact.path;
2967
+ if (path && !paths.includes(path)) paths.push(path);
2968
+ };
2969
+ push(io?.evidence);
2970
+ push(io?.output?.artifact);
2971
+ return paths.slice(0, 6);
2972
+ }
2973
+
2974
+ async function loadPanel(nodeId) {
2975
+ const request = ++panelRequest;
2976
+ const runId = followedRunId();
2977
+ if (!runId) {
2978
+ renderNodePanel({ status: 'empty' });
2979
+ return;
2980
+ }
2981
+ try {
2982
+ const [ioResult, lifeResult] = await Promise.all([
2983
+ api(`/api/runs/${encodeURIComponent(runId)}/nodes/${encodeURIComponent(nodeId)}`),
2984
+ api(`/api/runs/${encodeURIComponent(runId)}/lifecycle?after=0&limit=100`)
2985
+ ]);
2986
+ if (request !== panelRequest || panelNodeId !== nodeId) return;
2987
+ const io = ioResult.io;
2988
+ const artifacts = [];
2989
+ for (const path of collectArtifactPaths(io)) {
2990
+ try {
2991
+ const result = await api(`/api/runs/${encodeURIComponent(runId)}/artifacts?path=${encodeURIComponent(path)}`);
2992
+ artifacts.push(result.artifact);
2993
+ } catch (error) {
2994
+ artifacts.push({ path, error: error.message });
2995
+ }
2996
+ }
2997
+ if (request !== panelRequest || panelNodeId !== nodeId) return;
2998
+ renderNodePanel({
2999
+ status: 'ready',
3000
+ io,
3001
+ events: lifeResult.lifecycle?.events || [],
3002
+ artifacts
3003
+ });
3004
+ } catch (error) {
3005
+ if (request !== panelRequest || panelNodeId !== nodeId) return;
3006
+ renderNodePanel({ status: 'error', message: error.message });
3007
+ }
3008
+ }
3009
+
3010
+ function openNodePanel(nodeId) {
3011
+ if (!nodeId || !draft?.nodes?.some((node) => node.id === nodeId)) return;
3012
+ const alreadyOpen = panelIsOpen();
3013
+ if (panelNodeId !== nodeId) panelTab = 'overview';
3014
+ panelNodeId = nodeId;
3015
+ selectNode(nodeId);
3016
+ focusNode(nodeId);
3017
+ const panel = byId('node-panel');
3018
+ if (!panel) return;
3019
+ panel.hidden = false;
3020
+ byId('canvas')?.classList.add('panel-open');
3021
+ const runId = followedRunId();
3022
+ renderNodePanel(runId ? { status: 'loading' } : { status: 'empty' });
3023
+ if (!alreadyOpen) fitView();
3024
+ if (runId) loadPanel(nodeId);
3025
+ }
3026
+
3027
+ function closeNodePanel() {
3028
+ panelNodeId = null;
3029
+ panelRequest += 1;
3030
+ panelView = { status: 'empty' };
3031
+ const panel = byId('node-panel');
3032
+ if (panel) {
3033
+ panel.hidden = true;
3034
+ panel.innerHTML = '';
3035
+ }
3036
+ byId('canvas')?.classList.remove('panel-open');
3037
+ hideTooltip();
3038
+ if (workspace === 'wiring' && draft?.nodes?.length) fitView();
3039
+ }
3040
+
3041
+ function panelIsOpen() {
3042
+ const panel = byId('node-panel');
3043
+ return Boolean(panelNodeId && panel && !panel.hidden);
3044
+ }
3045
+
3046
+ async function loadArtifactPreview(artifactPath) {
3047
+ const runId = followedRunId();
3048
+ if (!runId || !artifactPath) return;
3049
+ const request = panelRequest;
3050
+ try {
3051
+ const result = await api(`/api/runs/${encodeURIComponent(runId)}/artifacts?path=${encodeURIComponent(artifactPath)}`);
3052
+ if (request !== panelRequest) return;
3053
+ panelView = { ...panelView, preview: result.artifact };
3054
+ } catch (error) {
3055
+ if (request !== panelRequest) return;
3056
+ panelView = { ...panelView, preview: { path: artifactPath, error: error.message } };
3057
+ }
3058
+ renderNodePanel();
3059
+ }
3060
+
3061
+ function onPanelClick(event) {
3062
+ if (closestReal(event.target, '.node-panel-close')) {
3063
+ closeNodePanel();
3064
+ return;
3065
+ }
3066
+ const artifact = closestReal(event.target, '[data-artifact-path]');
3067
+ if (artifact?.dataset?.artifactPath) {
3068
+ loadArtifactPreview(artifact.dataset.artifactPath);
3069
+ return;
3070
+ }
3071
+ const tab = closestReal(event.target, '[role="tab"]');
3072
+ if (!tab?.dataset?.tab) return;
3073
+ panelTab = tab.dataset.tab;
3074
+ renderNodePanel();
3075
+ byId('node-panel')?.querySelector?.(`[data-tab="${panelTab}"]`)?.focus?.();
3076
+ }
3077
+
3078
+ function onPanelKeydown(event) {
3079
+ const tab = closestReal(event.target, '[role="tab"]');
3080
+ if (!tab) return;
3081
+ const tabs = Array.from(byId('node-panel')?.querySelectorAll?.('[role="tab"]') || []);
3082
+ const index = tabs.indexOf(tab);
3083
+ if (index < 0) return;
3084
+ let next = index;
3085
+ if (event.key === 'ArrowRight' || event.key === 'ArrowDown') next = (index + 1) % tabs.length;
3086
+ else if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') next = (index - 1 + tabs.length) % tabs.length;
3087
+ else if (event.key === 'Home') next = 0;
3088
+ else if (event.key === 'End') next = tabs.length - 1;
3089
+ else return;
3090
+ event.preventDefault();
3091
+ event.stopPropagation();
3092
+ panelTab = tabs[next].dataset.tab;
3093
+ renderNodePanel();
3094
+ byId('node-panel')?.querySelector?.(`[data-tab="${panelTab}"]`)?.focus?.();
3095
+ }
3096
+
3097
+ function updateZoomLabel() {
3098
+ if (!zoomLevelOutput) return;
3099
+ zoomLevelOutput.textContent = `${Math.round(viewport.scale * 100)}%`;
3100
+ }
3101
+
3102
+ const ZOOM_ICONS = {
3103
+ in: '<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M6 12h12M12 6v12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',
3104
+ out: '<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M6 12h12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',
3105
+ fit: '<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M8 4H4v4M16 4h4v4M8 20H4v-4M16 20h4v-4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',
3106
+ layout: '<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="4" y="5" width="6" height="6" rx="1.2" fill="none" stroke="currentColor" stroke-width="1.8"/><rect x="14" y="13" width="6" height="6" rx="1.2" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M10 8h3v8h3" fill="none" stroke="currentColor" stroke-width="1.6"/></svg>'
3107
+ };
3108
+
3109
+ function zoomButton(label, icon, action) {
3110
+ const button = document.createElement('button');
3111
+ button.type = 'button';
3112
+ button.className = 'zoom-button';
3113
+ button.title = label;
3114
+ button.setAttribute('aria-label', label);
3115
+ button.innerHTML = icon;
3116
+ button.onclick = (event) => {
3117
+ event?.preventDefault?.();
3118
+ event?.stopPropagation?.();
3119
+ action();
3120
+ };
3121
+ return button;
3122
+ }
3123
+
3124
+ function mountCanvasChrome() {
3125
+ const canvas = byId('canvas');
3126
+ if (!canvas || zoomInButton) return;
3127
+ const bar = document.createElement('div');
3128
+ bar.className = 'zoom-controls';
3129
+ zoomInButton = zoomButton('Zoom in', ZOOM_ICONS.in, () => zoomAt(viewport.scale * 1.08));
3130
+ const zoomOutButton = zoomButton('Zoom out', ZOOM_ICONS.out, () => zoomAt(viewport.scale * 0.92));
3131
+ const zoomFitButton = zoomButton('Fit to view', ZOOM_ICONS.fit, () => fitView());
3132
+ const zoomLayoutButton = zoomButton('Auto-layout', ZOOM_ICONS.layout, () => autoLayout());
3133
+ zoomLevelOutput = document.createElement('output');
3134
+ zoomLevelOutput.className = 'zoom-level';
3135
+ zoomLevelOutput.setAttribute('aria-label', 'Zoom level');
3136
+ const sep = () => {
3137
+ const element = document.createElement('span');
3138
+ element.className = 'zoom-sep';
3139
+ element.setAttribute('aria-hidden', 'true');
3140
+ return element;
3141
+ };
3142
+ bar.append(zoomInButton, sep(), zoomOutButton, sep(), zoomFitButton, sep(), zoomLayoutButton, zoomLevelOutput);
3143
+ canvas.append(bar);
3144
+
3145
+ nodeTooltip = document.createElement('div');
3146
+ nodeTooltip.id = 'node-tooltip';
3147
+ nodeTooltip.className = 'node-tooltip';
3148
+ nodeTooltip.setAttribute('role', 'tooltip');
3149
+ nodeTooltip.hidden = true;
3150
+ canvas.append(nodeTooltip);
3151
+
3152
+ minimap = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
3153
+ minimap.setAttribute('class', 'minimap');
3154
+ minimap.setAttribute('aria-label', 'Workflow minimap');
3155
+ minimap.setAttribute('viewBox', `0 0 ${MINIMAP_WIDTH} ${MINIMAP_HEIGHT}`);
3156
+ minimap.setAttribute('width', String(MINIMAP_WIDTH));
3157
+ minimap.setAttribute('height', String(MINIMAP_HEIGHT));
3158
+ minimap.addEventListener('pointerdown', onMinimapPointerDown);
3159
+ canvas.append(minimap);
3160
+
3161
+ const panel = byId('node-panel');
3162
+ if (panel) {
3163
+ panel.hidden = true;
3164
+ panel.addEventListener('click', onPanelClick);
3165
+ panel.addEventListener('keydown', onPanelKeydown);
3166
+ }
3167
+ updateZoomLabel();
3168
+ }
3169
+
3170
+ function minimapMetrics() {
3171
+ const bounds = graphBounds();
3172
+ if (!bounds) return null;
3173
+ const pad = 10;
3174
+ const innerW = MINIMAP_WIDTH - pad * 2;
3175
+ const innerH = MINIMAP_HEIGHT - pad * 2;
3176
+ const scale = Math.min(innerW / Math.max(bounds.width, 1), innerH / Math.max(bounds.height, 1));
3177
+ return {
3178
+ bounds,
3179
+ scale,
3180
+ offsetX: pad + (innerW - bounds.width * scale) / 2,
3181
+ offsetY: pad + (innerH - bounds.height * scale) / 2,
3182
+ width: MINIMAP_WIDTH,
3183
+ height: MINIMAP_HEIGHT
3184
+ };
3185
+ }
3186
+
3187
+ function renderMinimap() {
3188
+ if (!minimap) return;
3189
+ minimap.innerHTML = '';
3190
+ const metrics = minimapMetrics();
3191
+ if (!metrics || !draft?.nodes?.length) return;
3192
+ for (const node of draft.nodes) {
3193
+ const position = positions.get(node.id);
3194
+ if (!position) continue;
3195
+ const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
3196
+ const status = graphStateClass(runtimeFor(node)?.status);
3197
+ rect.setAttribute('class', `minimap-node minimap-${status}`);
3198
+ rect.setAttribute('x', String(metrics.offsetX + (position.x - metrics.bounds.minX) * metrics.scale));
3199
+ rect.setAttribute('y', String(metrics.offsetY + (position.y - metrics.bounds.minY) * metrics.scale));
3200
+ rect.setAttribute('width', String(Math.max(3, NODE_WIDTH * metrics.scale)));
3201
+ rect.setAttribute('height', String(Math.max(3, NODE_BLOCK_HEIGHT * metrics.scale)));
3202
+ rect.setAttribute('rx', '2');
3203
+ minimap.append(rect);
3204
+ }
3205
+ const canvasRect = byId('canvas')?.getBoundingClientRect?.() || { left: 0, top: 0, width: 1, height: 1 };
3206
+ const viewW = Math.max(1, canvasRect.width - panelInset());
3207
+ const viewH = Math.max(1, canvasRect.height);
3208
+ const origin = screenToWorld(canvasRect.left, canvasRect.top);
3209
+ const viewportRect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
3210
+ viewportRect.setAttribute('class', 'minimap-viewport');
3211
+ viewportRect.setAttribute('x', String(metrics.offsetX + (origin.x - metrics.bounds.minX) * metrics.scale));
3212
+ viewportRect.setAttribute('y', String(metrics.offsetY + (origin.y - metrics.bounds.minY) * metrics.scale));
3213
+ viewportRect.setAttribute('width', String(Math.max(4, (viewW / viewport.scale) * metrics.scale)));
3214
+ viewportRect.setAttribute('height', String(Math.max(4, (viewH / viewport.scale) * metrics.scale)));
3215
+ viewportRect.setAttribute('rx', '3');
3216
+ minimap.append(viewportRect);
3217
+ }
3218
+
3219
+ function centerOnWorld(worldX, worldY) {
3220
+ const rect = byId('canvas')?.getBoundingClientRect?.() || { left: 0, top: 0, width: 0, height: 0 };
3221
+ const inset = panelInset();
3222
+ viewport.x = (rect.width - inset) / 2 - worldX * viewport.scale;
3223
+ viewport.y = rect.height / 2 - worldY * viewport.scale;
3224
+ applyViewport();
3225
+ saveLayoutSoon();
3226
+ }
3227
+
3228
+ function panFromMinimapEvent(event) {
3229
+ const metrics = minimapMetrics();
3230
+ if (!metrics || !minimap?.getBoundingClientRect) return;
3231
+ const rect = minimap.getBoundingClientRect();
3232
+ const localX = ((event.clientX - rect.left) / Math.max(rect.width, 1)) * metrics.width;
3233
+ const localY = ((event.clientY - rect.top) / Math.max(rect.height, 1)) * metrics.height;
3234
+ const worldX = metrics.bounds.minX + (localX - metrics.offsetX) / metrics.scale;
3235
+ const worldY = metrics.bounds.minY + (localY - metrics.offsetY) / metrics.scale;
3236
+ centerOnWorld(worldX, worldY);
3237
+ }
3238
+
3239
+ function onMinimapPointerDown(event) {
3240
+ if (event.button !== 0) return;
3241
+ event.preventDefault();
3242
+ event.stopPropagation();
3243
+ interaction = { type: 'minimap', pointerId: event.pointerId };
3244
+ panFromMinimapEvent(event);
3245
+ minimap?.setPointerCapture?.(event.pointerId);
3246
+ }
3247
+
3248
+ function canvasShortcutTarget(target) {
3249
+ if (!target || editableTarget(target)) return false;
3250
+ if (workspace !== 'wiring' || byId('canvas')?.hidden) return false;
3251
+ if (target.id === 'canvas' || target === byId('canvas')) return true;
3252
+ if (target.dataset?.nodeId) return true;
3253
+ return String(target.className || '').split(/\s+/).includes('node');
3254
+ }
3255
+
3256
+ function toggleShortcutSheet() {
3257
+ const dialog = byId('shortcut-sheet');
3258
+ if (!dialog) return;
3259
+ if (dialog.open) dialog.close();
3260
+ else dialog.showModal();
3261
+ }
3262
+
1346
3263
  function bindCanvas() {
1347
3264
  const canvas = byId('canvas');
3265
+ mountCanvasChrome();
1348
3266
  canvas.addEventListener('pointerdown', (event) => {
1349
- if (event.target === canvas || event.target === byId('scene') || event.target === byId('nodes') || event.target === byId('edges')) {
1350
- selectedId = null;
1351
- if (!event.shiftKey) selectedIds.clear();
1352
- updateSelection();
1353
- if (event.button === 1 || spacePressed) beginPan(event);
3267
+ if (closestReal(event.target, '#node-panel, .zoom-controls, .minimap')) return;
3268
+ const empty = event.target === canvas || event.target === byId('scene')
3269
+ || event.target === byId('nodes') || event.target === byId('edges');
3270
+ if (!empty) return;
3271
+ if (event.button === 0 && event.shiftKey) {
3272
+ beginMarquee(event);
3273
+ return;
1354
3274
  }
3275
+ selectedId = null;
3276
+ selectedEdgeId = null;
3277
+ if (!event.shiftKey) selectedIds.clear();
3278
+ updateSelection();
3279
+ renderEdges();
3280
+ if (event.button === 0 || event.button === 1 || spacePressed) beginPan(event);
1355
3281
  });
1356
3282
  canvas.addEventListener('pointermove', handlePointerMove);
1357
3283
  canvas.addEventListener('pointerup', finishPointer);
1358
3284
  canvas.addEventListener('pointercancel', finishPointer);
1359
3285
  canvas.addEventListener('wheel', handleWheel, { passive: false });
1360
- byId('auto-layout').onclick = () => autoLayout();
1361
- byId('fit-view').onclick = fitView;
1362
- byId('undo').onclick = () => restoreHistory(historyIndex - 1);
1363
- byId('redo').onclick = () => restoreHistory(historyIndex + 1);
3286
+ canvas.addEventListener('gesturestart', (event) => {
3287
+ if (canvasGestureIgnored(event)) return;
3288
+ event.preventDefault();
3289
+ gestureZoom = viewport.scale;
3290
+ }, { passive: false });
3291
+ canvas.addEventListener('gesturechange', (event) => {
3292
+ if (canvasGestureIgnored(event)) return;
3293
+ event.preventDefault();
3294
+ const scale = Number(event.scale);
3295
+ if (!Number.isFinite(scale) || scale <= 0) return;
3296
+ zoomAt((gestureZoom || viewport.scale) * scale, event.clientX, event.clientY);
3297
+ }, { passive: false });
3298
+ canvas.addEventListener('gestureend', (event) => {
3299
+ event.preventDefault?.();
3300
+ gestureZoom = null;
3301
+ }, { passive: false });
1364
3302
  }
1365
3303
 
1366
3304
  function editableTarget(target) {
@@ -1377,23 +3315,98 @@ document.addEventListener('keydown', (event) => {
1377
3315
  if (modifier && event.key.toLowerCase() === 'z') {
1378
3316
  event.preventDefault();
1379
3317
  restoreHistory(historyIndex + (event.shiftKey ? 1 : -1));
1380
- } else if (modifier && event.key.toLowerCase() === 'y') {
3318
+ return;
3319
+ }
3320
+ if (modifier && event.key.toLowerCase() === 'y') {
1381
3321
  event.preventDefault();
1382
3322
  restoreHistory(historyIndex + 1);
1383
- } else if ((event.key === 'Delete' || event.key === 'Backspace') && selectedEdgeId) {
3323
+ return;
3324
+ }
3325
+ if ((event.key === 'Delete' || event.key === 'Backspace') && selectedEdgeId && !panelIsOpen()) {
1384
3326
  event.preventDefault();
1385
3327
  deleteEdge(selectedEdgeId);
3328
+ return;
3329
+ }
3330
+ if (event.key === 'Escape') {
3331
+ if (byId('shortcut-sheet')?.open) {
3332
+ event.preventDefault();
3333
+ byId('shortcut-sheet').close();
3334
+ return;
3335
+ }
3336
+ if (panelIsOpen()) {
3337
+ event.preventDefault();
3338
+ closeNodePanel();
3339
+ return;
3340
+ }
3341
+ if (canvasShortcutTarget(event.target)) {
3342
+ event.preventDefault();
3343
+ clearSelection();
3344
+ }
3345
+ return;
3346
+ }
3347
+ const shortcutQuestion = event.key === '?' || (event.key === '/' && event.shiftKey);
3348
+ if (shortcutQuestion && (byId('shortcut-sheet')?.open || canvasShortcutTarget(event.target))) {
3349
+ event.preventDefault();
3350
+ toggleShortcutSheet();
3351
+ return;
3352
+ }
3353
+ if (!canvasShortcutTarget(event.target)) return;
3354
+ if (modifier || event.altKey) return;
3355
+ const key = event.key;
3356
+ if (key === '+' || key === '=') {
3357
+ event.preventDefault();
3358
+ zoomAt(viewport.scale * 1.08);
3359
+ return;
3360
+ }
3361
+ if (key === '-' || key === '_') {
3362
+ event.preventDefault();
3363
+ zoomAt(viewport.scale * 0.92);
3364
+ return;
3365
+ }
3366
+ if (event.shiftKey) return;
3367
+ if (key === 'f' || key === 'F') {
3368
+ event.preventDefault();
3369
+ fitView();
3370
+ } else if (key === 'l' || key === 'L') {
3371
+ event.preventDefault();
3372
+ autoLayout();
3373
+ } else if (key === '0') {
3374
+ event.preventDefault();
3375
+ zoomAt(1);
3376
+ } else if (key === 'ArrowLeft') {
3377
+ event.preventDefault();
3378
+ moveSelection('left');
3379
+ } else if (key === 'ArrowRight') {
3380
+ event.preventDefault();
3381
+ moveSelection('right');
3382
+ } else if (key === 'ArrowUp') {
3383
+ event.preventDefault();
3384
+ moveSelection('up');
3385
+ } else if (key === 'ArrowDown') {
3386
+ event.preventDefault();
3387
+ moveSelection('down');
3388
+ } else if (key === 'Enter' && selectedId) {
3389
+ event.preventDefault();
3390
+ openNodePanel(selectedId);
1386
3391
  }
1387
3392
  });
1388
3393
  document.addEventListener('keyup', (event) => {
1389
3394
  if (event.code === 'Space') spacePressed = false;
1390
3395
  });
3396
+ if (typeof window !== 'undefined') window.addEventListener('resize', scheduleFitView);
1391
3397
 
1392
- byId('review').onclick = () => {
1393
- if (byId('review').disabled) return;
3398
+ byId('undo').onclick = () => restoreHistory(historyIndex - 1);
3399
+ byId('redo').onclick = () => restoreHistory(historyIndex + 1);
3400
+ byId('discard-wiring').onclick = discardWiring;
3401
+ byId('save-wiring').onclick = () => {
3402
+ if (byId('save-wiring').disabled) return;
1394
3403
  byId('confirm').showModal();
1395
3404
  };
1396
3405
  byId('install').onclick = async () => {
3406
+ if (validationState.status !== 'valid') {
3407
+ notify(validationSummary() || 'Wiring is invalid.');
3408
+ return;
3409
+ }
1397
3410
  try {
1398
3411
  const recipe = authoringRecipe();
1399
3412
  const exists = catalog.recipes.some((item) => item.id === recipe.id && item.source !== 'builtin');
@@ -1446,6 +3459,8 @@ async function initialize() {
1446
3459
  byId('confirm-freeze').onclick = freezeGoalFromForm;
1447
3460
  byId('unfreeze-goal').onclick = unfreezeGoalFromForm;
1448
3461
  byId('retry-live-connection').onclick = resync;
3462
+ byId('live-view').addEventListener('click', onLiveClick);
3463
+ byId('live-view').addEventListener('submit', onLiveSubmit);
1449
3464
  document.querySelectorAll?.('[data-close]')?.forEach?.((button) => {
1450
3465
  button.onclick = () => byId(button.dataset.close).close();
1451
3466
  });