ai-engineering-loop 2.0.0 → 2.1.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,18 @@
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 = 400;
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 COLUMN_PITCH = 188;
15
+ const ROW_PITCH = 200;
7
16
  const DISPLAY_NAME_MAX = 80;
8
17
  const STAGES = [
9
18
  { id: 'goal', label: 'goal', types: ['goal-contract'] },
@@ -40,6 +49,11 @@ let selectedId;
40
49
  let selectedIds = new Set();
41
50
  let selectedEdgeId;
42
51
  let validationSequence = 0;
52
+ let validationState = { status: 'pending', hash: '', issues: [], extraCodes: [] };
53
+ let invalidEdgeIds = new Set();
54
+ let edgeIssues = new Map();
55
+ let loadedEdges = [];
56
+ let loadedEdgeSignature = '';
43
57
  let positions = new Map();
44
58
  let viewport = { x: 0, y: 0, scale: 1 };
45
59
  let history = [];
@@ -47,6 +61,9 @@ let historyIndex = -1;
47
61
  let interaction;
48
62
  let connection;
49
63
  let layoutTimer;
64
+ let hasFitted = false;
65
+ let resizeFitTimer;
66
+ let edgeHideTimer;
50
67
  let spacePressed = false;
51
68
  let runs = [];
52
69
  let goal = { text: '', version: 1, frozen: false, draftRevision: 0, draftHash: null };
@@ -67,6 +84,16 @@ let liveRenderScheduled = false;
67
84
  let reconnectTimer = null;
68
85
  let reconnectAttempt = 0;
69
86
  let resumeFallbackUsed = false;
87
+ let panelNodeId = null;
88
+ let panelTab = 'input';
89
+ let panelRequest = 0;
90
+ let panelView = { status: 'empty' };
91
+ let tooltipTimer = null;
92
+ let suppressNodeClick = false;
93
+ let zoomInButton = null;
94
+ let zoomLevelOutput = null;
95
+ let nodeTooltip = null;
96
+ let minimap = null;
70
97
  const RECONNECT_BACKOFF_MS = [500, 1000, 2000, 5000];
71
98
 
72
99
  function graphStateClass(value) {
@@ -175,7 +202,7 @@ function defaultGraphPositions() {
175
202
  const depth = depthFor(node);
176
203
  const row = rows.get(depth) || 0;
177
204
  rows.set(depth, row + 1);
178
- return [node.id, { x: 80 + depth * 270, y: 110 + row * 150 }];
205
+ return [node.id, { x: 48 + depth * COLUMN_PITCH, y: 56 + row * ROW_PITCH }];
179
206
  }));
180
207
  }
181
208
 
@@ -198,6 +225,8 @@ function applyViewport() {
198
225
  canvas.style.backgroundPosition = `${viewport.x}px ${viewport.y}px`;
199
226
  canvas.style.backgroundSize = `${32 * viewport.scale}px ${32 * viewport.scale}px`;
200
227
  }
228
+ updateZoomLabel();
229
+ renderMinimap();
201
230
  }
202
231
 
203
232
  function screenToWorld(clientX, clientY) {
@@ -208,26 +237,100 @@ function screenToWorld(clientX, clientY) {
208
237
  };
209
238
  }
210
239
 
240
+ function curveBend(x1, x2) {
241
+ return Math.max(48, Math.abs(x2 - x1) * 0.45);
242
+ }
243
+
244
+ function curvePath(x1, y1, x2, y2) {
245
+ const bend = curveBend(x1, x2);
246
+ return `M${x1} ${y1} C${x1 + bend} ${y1},${x2 - bend} ${y2},${x2} ${y2}`;
247
+ }
248
+
249
+ function pointOnCurve(x1, y1, x2, y2, t) {
250
+ const bend = curveBend(x1, x2);
251
+ const u = 1 - t;
252
+ return {
253
+ x: u * u * u * x1 + 3 * u * u * t * (x1 + bend) + 3 * u * t * t * (x2 - bend) + t * t * t * x2,
254
+ y: u * u * u * y1 + 3 * u * u * t * y1 + 3 * u * t * t * y2 + t * t * t * y2
255
+ };
256
+ }
257
+
211
258
  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}`;
259
+ return curvePath(from.x + NODE_WIDTH, from.y + NODE_PORT_Y, to.x, to.y + NODE_PORT_Y);
260
+ }
261
+
262
+ function edgeEndpoints(from, to) {
263
+ return {
264
+ x1: from.x + NODE_WIDTH,
265
+ y1: from.y + NODE_PORT_Y,
266
+ x2: to.x,
267
+ y2: to.y + NODE_PORT_Y
268
+ };
218
269
  }
219
270
 
220
271
  function loopBounds(loopGroup) {
221
272
  const points = loopGroup.nodeIds.map((nodeId) => positions.get(nodeId)).filter(Boolean);
222
273
  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;
274
+ const padX = 46;
275
+ const padTop = 58;
276
+ const padBottom = 28;
277
+ const left = Math.min(...points.map((point) => point.x)) - padX;
278
+ const top = Math.min(...points.map((point) => point.y)) - padTop;
279
+ const right = Math.max(...points.map((point) => point.x + NODE_WIDTH)) + padX;
280
+ const bottom = Math.max(...points.map((point) => point.y + NODE_BLOCK_HEIGHT)) + padBottom;
228
281
  return { left, top, right, bottom, width: right - left, height: bottom - top };
229
282
  }
230
283
 
284
+ function loopLabelText(loopGroup, runtime) {
285
+ const iteration = runtime?.iteration ?? 1;
286
+ return `${loopGroup.displayName} · iteration ${iteration} / ${loopGroup.maxIterations}`;
287
+ }
288
+
289
+ function loopLabelOverlapsEdge(rect) {
290
+ for (const edge of draft?.edges || []) {
291
+ const from = positions.get(edge.from);
292
+ const to = positions.get(edge.to);
293
+ if (!from || !to) continue;
294
+ const { x1, y1, x2, y2 } = edgeEndpoints(from, to);
295
+ for (let step = 0; step <= 8; step += 1) {
296
+ const point = pointOnCurve(x1, y1, x2, y2, step / 8);
297
+ if (point.x >= rect.left && point.x <= rect.right && point.y >= rect.top && point.y <= rect.bottom) {
298
+ return true;
299
+ }
300
+ }
301
+ }
302
+ return false;
303
+ }
304
+
305
+ function placeLoopLabel(bounds, label) {
306
+ const height = 26;
307
+ const width = Math.min(Math.max(bounds.width - 24, 80), 16 + String(label).length * 7.1);
308
+ const centerLeft = bounds.left + (bounds.width - width) / 2;
309
+ const candidates = [
310
+ { left: centerLeft, top: bounds.top - height / 2 },
311
+ { left: centerLeft, top: bounds.top - height - 10 },
312
+ { left: bounds.left + 12, top: bounds.top - height - 10 },
313
+ { left: bounds.right - width - 12, top: bounds.top - height - 10 },
314
+ { left: centerLeft, top: bounds.bottom + 10 }
315
+ ];
316
+ for (const candidate of candidates) {
317
+ const rect = {
318
+ left: candidate.left,
319
+ top: candidate.top,
320
+ right: candidate.left + width,
321
+ bottom: candidate.top + height
322
+ };
323
+ if (!loopLabelOverlapsEdge(rect)) return rect;
324
+ }
325
+ const fallback = candidates[1];
326
+ return {
327
+ left: fallback.left,
328
+ top: fallback.top,
329
+ right: fallback.left + width,
330
+ bottom: fallback.top + height
331
+ };
332
+ }
333
+
231
334
  function renderLoopGroups() {
232
335
  const container = scenePart('.loop-groups');
233
336
  container.innerHTML = '';
@@ -235,28 +338,29 @@ function renderLoopGroups() {
235
338
  const bounds = loopBounds(loopGroup);
236
339
  if (!bounds) continue;
237
340
  const runtime = catalog.live?.loopGroups?.[loopGroup.id];
341
+ const label = loopLabelText(loopGroup, runtime);
342
+ const rect = placeLoopLabel(bounds, label);
238
343
  const element = document.createElement('section');
239
344
  element.className = `loop-group ${runtime?.status?.toLowerCase() || 'draft'}`;
240
345
  element.style.left = `${bounds.left}px`;
241
346
  element.style.top = `${bounds.top}px`;
242
347
  element.style.width = `${bounds.width}px`;
243
348
  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
- `;
349
+ // CSP style-src 'self' blocks inline style attributes; position the pill through the CSSOM.
350
+ const pill = document.createElement('header');
351
+ pill.className = 'loop-pill';
352
+ pill.textContent = label;
353
+ if (pill.style) {
354
+ pill.style.left = `${rect.left - bounds.left}px`;
355
+ pill.style.top = `${rect.top - bounds.top}px`;
356
+ pill.style.width = `${Math.max(0, rect.right - rect.left)}px`;
357
+ }
358
+ element.replaceChildren?.(pill);
359
+ if (!element.replaceChildren) element.innerHTML = `<header class="loop-pill">${escapeHtml(label)}</header>`;
249
360
  container.append(element);
250
361
  }
251
362
  }
252
363
 
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
364
  function stageLabel(node, index) {
261
365
  const stages = {
262
366
  'goal-contract': 'STAGE 01',
@@ -271,6 +375,55 @@ function stageLabel(node, index) {
271
375
  return stages[node.type] || `STEP ${String(index + 1).padStart(2, '0')}`;
272
376
  }
273
377
 
378
+ function edgeClassName(edge) {
379
+ const state = graphStateClass(catalog.live?.edges?.find((candidate) => candidate.id === edge.id)?.state);
380
+ const intoRunning = graphStateClass(catalog.live?.nodes?.[edge.to]?.status) === 'active';
381
+ const active = state === 'active' || intoRunning;
382
+ const invalid = invalidEdgeIds.has(edge.id) ? ' edge-invalid' : '';
383
+ return `edge edge-${state}${active ? ' edge-active' : ''}${selectedEdgeId === edge.id ? ' selected' : ''}${invalid}`;
384
+ }
385
+
386
+ function edgeDeleteClass(edge) {
387
+ return `edge-delete${selectedEdgeId === edge.id ? ' selected' : ''}`;
388
+ }
389
+
390
+ function bindEdgeAffordance(path, control, handles, edgeId) {
391
+ const show = () => {
392
+ clearTimeout(edgeHideTimer);
393
+ control.classList.add('visible');
394
+ control.setAttribute('aria-hidden', 'false');
395
+ handles.forEach((handle) => handle.classList.add('visible'));
396
+ };
397
+ const scheduleHide = () => {
398
+ clearTimeout(edgeHideTimer);
399
+ edgeHideTimer = setTimeout(() => {
400
+ if (selectedEdgeId !== edgeId) {
401
+ control.classList.remove('visible');
402
+ control.setAttribute('aria-hidden', 'true');
403
+ handles.forEach((handle) => handle.classList.remove('visible'));
404
+ }
405
+ }, 160);
406
+ };
407
+ path.addEventListener('pointerenter', show);
408
+ path.addEventListener('pointerleave', scheduleHide);
409
+ control.addEventListener('pointerenter', show);
410
+ control.addEventListener('pointerleave', scheduleHide);
411
+ handles.forEach((handle) => {
412
+ handle.addEventListener('pointerenter', show);
413
+ handle.addEventListener('pointerleave', scheduleHide);
414
+ });
415
+ path.addEventListener('pointerdown', (event) => {
416
+ if (event.button !== 0) return;
417
+ event.stopPropagation();
418
+ event.preventDefault();
419
+ selectedEdgeId = edgeId;
420
+ selectedId = null;
421
+ selectedIds = new Set();
422
+ updateSelection();
423
+ renderEdges();
424
+ });
425
+ }
426
+
274
427
  function renderEdges() {
275
428
  const group = scenePart('.edge-paths');
276
429
  const controls = scenePart('.edge-controls');
@@ -279,63 +432,230 @@ function renderEdges() {
279
432
  controls.innerHTML = '';
280
433
  if (preview?.style && preview !== byId('scene')) preview.setAttribute?.('d', preview.getAttribute?.('d') || '');
281
434
  if (!draft) return;
435
+ clearTimeout(edgeHideTimer);
282
436
  draft.edges.forEach((edge) => {
283
437
  const from = positions.get(edge.from);
284
438
  const to = positions.get(edge.to);
285
439
  if (!from || !to) return;
286
440
  const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
287
441
  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
- );
442
+ path.setAttribute('class', edgeClassName(edge));
293
443
  path.setAttribute('marker-end', 'url(#arrow)');
294
444
  path.dataset.edgeId = edge.id;
295
445
  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
- };
446
+ const ends = edgeEndpoints(from, to);
447
+ const midpoint = pointOnCurve(ends.x1, ends.y1, ends.x2, ends.y2, 0.5);
300
448
  const control = document.createElement('button');
301
- control.className = `edge-delete${selectedEdgeId === edge.id ? ' selected' : ''}`;
449
+ control.type = 'button';
450
+ control.className = edgeDeleteClass(edge);
302
451
  control.dataset.edgeId = edge.id;
303
452
  control.style.left = `${midpoint.x}px`;
304
453
  control.style.top = `${midpoint.y}px`;
454
+ control.tabIndex = -1;
305
455
  control.title = `${displayName(draft.nodes.find((node) => node.id === edge.from))} → ${displayName(draft.nodes.find((node) => node.id === edge.to))}`;
306
456
  control.setAttribute('aria-label', `Delete connection ${control.title}`);
457
+ control.setAttribute('aria-hidden', selectedEdgeId === edge.id ? 'false' : 'true');
307
458
  control.textContent = '×';
308
459
  control.onclick = (event) => {
309
460
  event.stopPropagation();
310
461
  deleteEdge(edge.id);
311
462
  };
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);
463
+ const handles = [
464
+ edgeHandle(edge, 'from', ends.x1, ends.y1),
465
+ edgeHandle(edge, 'to', ends.x2, ends.y2)
466
+ ];
467
+ bindEdgeAffordance(path, control, handles, edge.id);
468
+ controls.append(control, ...handles);
469
+ const issue = edgeIssueText(edge.id);
470
+ if (issue) {
471
+ const note = document.createElement('p');
472
+ note.className = 'edge-error';
473
+ note.textContent = issue;
474
+ if (note.style) {
475
+ note.style.left = `${midpoint.x}px`;
476
+ note.style.top = `${midpoint.y}px`;
477
+ }
478
+ controls.append(note);
321
479
  }
322
480
  });
481
+ renderMinimap();
482
+ }
483
+
484
+ function edgeHandle(edge, end, x, y) {
485
+ const handle = document.createElement('button');
486
+ handle.type = 'button';
487
+ handle.className = `edge-end edge-end-${end}${selectedEdgeId === edge.id ? ' visible' : ''}`;
488
+ handle.dataset.edgeId = edge.id;
489
+ handle.dataset.end = end;
490
+ handle.tabIndex = -1;
491
+ handle.setAttribute('aria-label', end === 'to'
492
+ ? `Reposition end of ${edge.from} to ${edge.to}`
493
+ : `Reposition start of ${edge.from} to ${edge.to}`);
494
+ if (handle.style) {
495
+ handle.style.left = `${x}px`;
496
+ handle.style.top = `${y}px`;
497
+ }
498
+ handle.addEventListener('pointerdown', (event) => {
499
+ if (event.button !== 0) return;
500
+ event.preventDefault();
501
+ event.stopPropagation();
502
+ selectedEdgeId = edge.id;
503
+ selectedId = null;
504
+ selectedIds = new Set();
505
+ connection = {
506
+ pointerId: event.pointerId,
507
+ edgeId: edge.id,
508
+ end,
509
+ sourceId: end === 'to' ? edge.from : null,
510
+ fixedId: end === 'to' ? edge.from : edge.to
511
+ };
512
+ const preview = scenePart('.preview-edge');
513
+ if (preview?.style) preview.style.display = 'block';
514
+ handle.setPointerCapture?.(event.pointerId);
515
+ });
516
+ return handle;
517
+ }
518
+
519
+ function edgeIssueText(edgeId) {
520
+ return (edgeIssues.get(edgeId) || []).map(issueText).filter(Boolean).join('; ');
521
+ }
522
+
523
+ const NODE_ICONS = {
524
+ '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"/>',
525
+ 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"/>',
526
+ 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"/>',
527
+ '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"/>',
528
+ 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"/>',
529
+ 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"/>',
530
+ 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"/>',
531
+ 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"/>',
532
+ 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"/>',
533
+ 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"/>',
534
+ 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"/>'
535
+ };
536
+
537
+ function nodeIcon(type) {
538
+ const body = NODE_ICONS[type] || NODE_ICONS.generic;
539
+ return `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">${body}</svg>`;
540
+ }
541
+
542
+ function formatDuration(ms) {
543
+ if (!Number.isFinite(ms) || ms < 0) return '';
544
+ const totalSeconds = Math.round(ms / 1000);
545
+ const hours = Math.floor(totalSeconds / 3600);
546
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
547
+ const seconds = totalSeconds % 60;
548
+ if (hours > 0) return minutes ? `${hours}h ${minutes}m` : `${hours}h`;
549
+ if (minutes > 0) return `${minutes}m ${String(seconds).padStart(2, '0')}s`;
550
+ return `${seconds}s`;
551
+ }
552
+
553
+ function legacyDurationMs(runtime) {
554
+ if (!runtime || typeof runtime !== 'object') return null;
555
+ if (runtime.durationMs != null && runtime.durationMs !== '') {
556
+ const explicit = Number(runtime.durationMs);
557
+ if (Number.isFinite(explicit) && explicit >= 0) return explicit;
558
+ }
559
+ const started = Date.parse(runtime.startedAt);
560
+ if (!Number.isFinite(started)) return null;
561
+ const completed = Date.parse(runtime.completedAt);
562
+ if (Number.isFinite(completed)) return Math.max(0, completed - started);
563
+ if (graphStateClass(runtime.status) === 'active') return Math.max(0, Date.now() - started);
564
+ return null;
565
+ }
566
+
567
+ function dependencyIds(nodeId, recipe) {
568
+ const ids = new Set();
569
+ for (const edge of recipe?.edges || []) {
570
+ if (edge?.to === nodeId && edge.from) ids.add(edge.from);
571
+ }
572
+ const node = (recipe?.nodes || []).find((item) => item?.id === nodeId);
573
+ for (const id of node?.dependsOn || []) {
574
+ if (id) ids.add(id);
575
+ }
576
+ return [...ids];
577
+ }
578
+
579
+ function nodeDurationMs(nodeId, live, recipe) {
580
+ if (!nodeId || !live || !recipe) return null;
581
+ const runtime = live.nodes?.[nodeId];
582
+ if (!runtime) return null;
583
+ const status = String(runtime.status || '').toUpperCase();
584
+ const finished = status === 'PASSED' || status === 'FAILED';
585
+ const running = status === 'RUNNING' || status === 'IN_PROGRESS' || status === 'WORKING';
586
+ if (!finished && !running) return null;
587
+ const dependencies = dependencyIds(nodeId, recipe);
588
+ let start = NaN;
589
+ if (!dependencies.length) {
590
+ start = Date.parse(live.run?.createdAt);
591
+ } else {
592
+ const times = dependencies
593
+ .map((id) => Date.parse(live.nodes?.[id]?.updatedAt))
594
+ .filter(Number.isFinite);
595
+ if (times.length) start = Math.max(...times);
596
+ }
597
+ if (!Number.isFinite(start)) return null;
598
+ const end = finished ? Date.parse(runtime.updatedAt) : Date.now();
599
+ if (!Number.isFinite(end)) return null;
600
+ return Math.max(0, end - start);
601
+ }
602
+
603
+ function statusWord(status) {
604
+ if (status == null || status === '') return 'Pending';
605
+ const normalized = String(status).toLowerCase();
606
+ if (normalized === 'blocked') return 'Blocked';
607
+ const state = graphStateClass(status);
608
+ if (state === 'active') return 'Running';
609
+ if (state === 'passed') return 'Passed';
610
+ if (state === 'failed') return 'Failed';
611
+ if (state === 'skipped') return 'Skipped';
612
+ if (state === 'waiting') return 'Waiting';
613
+ if (normalized === 'ready') return 'Ready';
614
+ if (normalized === 'idle' || normalized === 'pending') return 'Pending';
615
+ return normalized.charAt(0).toUpperCase() + normalized.slice(1);
616
+ }
617
+
618
+ function nodeStatusLine(runtime) {
619
+ const word = statusWord(runtime?.status);
620
+ const duration = formatDuration(legacyDurationMs(runtime));
621
+ return duration ? `${word} · ${duration}` : word;
622
+ }
623
+
624
+ function liveStatusText(node) {
625
+ if (!node) return 'Pending';
626
+ const runtime = runtimeFor(node);
627
+ const word = statusWord(runtime?.status);
628
+ const duration = formatDuration(nodeDurationMs(node.id, catalog.live, draft));
629
+ return duration ? `${word} · ${duration}` : word;
323
630
  }
324
631
 
325
632
  function nodeMarkup(node, index) {
326
- const runtimeNode = catalog.live?.nodes?.[node.id];
633
+ const title = `${stageLabel(node, index)} · ${node.type}`;
327
634
  return `
328
635
  <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>
636
+ <div class="node-tile" title="${escapeHtml(title)}">
637
+ <span class="node-icon">${nodeIcon(node.type)}</span>
638
+ <span class="node-mark" aria-hidden="true"></span>
639
+ </div>
640
+ <span class="node-name">${escapeHtml(displayName(node))}</span>
641
+ <span class="node-status">${escapeHtml(liveStatusText(node))}</span>
333
642
  <button class="port port-out" aria-label="Connect from ${escapeHtml(node.id)}" tabindex="-1"></button>
334
643
  `;
335
644
  }
336
645
 
337
- function renderGraph() {
646
+ function nodeFrame(node, index) {
647
+ const runtime = catalog.live?.nodes?.[node.id];
648
+ return {
649
+ status: graphStateClass(runtime?.status),
650
+ nodeType: node.type,
651
+ title: `${stageLabel(node, index)} · ${node.type}`,
652
+ html: nodeMarkup(node, index)
653
+ };
654
+ }
655
+
656
+ function renderGraph({ live = false } = {}) {
338
657
  if (!draft) return;
658
+ hideTooltip();
339
659
  ensurePositions();
340
660
  renderLoopGroups();
341
661
  const container = byId('nodes');
@@ -343,25 +663,48 @@ function renderGraph() {
343
663
  container.innerHTML = '';
344
664
  draft.nodes.forEach((node, index) => {
345
665
  const position = positions.get(node.id);
346
- const runtimeNode = catalog.live?.nodes?.[node.id];
666
+ const frame = nodeFrame(node, index);
347
667
  const element = document.createElement('article');
348
668
  element.dataset.nodeId = node.id;
349
- element.className = `node ${graphStateClass(runtimeNode?.status)} ${selectedIds.has(node.id) ? 'selected' : ''}`;
669
+ element.dataset.status = frame.status;
670
+ element.dataset.nodeType = frame.nodeType;
671
+ element.title = frame.title;
672
+ element.className = `node${selectedIds.has(node.id) ? ' selected' : ''}`;
673
+ element.tabIndex = 0;
674
+ element.setAttribute('role', 'button');
675
+ element.setAttribute('tabindex', '0');
676
+ element.setAttribute('aria-label', `${displayName(node)}, ${statusWord(runtimeFor(node)?.status)}`);
677
+ element.setAttribute('aria-describedby', 'node-tooltip');
350
678
  element.style.left = `${position.x}px`;
351
679
  element.style.top = `${position.y}px`;
352
- element.innerHTML = nodeMarkup(node, index);
680
+ element.innerHTML = frame.html;
353
681
  element.addEventListener('pointerdown', beginNodeInteraction);
682
+ element.addEventListener('pointerenter', () => scheduleTooltip(element));
683
+ element.addEventListener('pointerleave', hideTooltip);
684
+ element.addEventListener('focus', () => scheduleTooltip(element));
685
+ element.addEventListener('blur', hideTooltip);
686
+ element.addEventListener('click', onNodeClick);
354
687
  element.querySelector('.port-out')?.addEventListener('pointerdown', beginConnection);
355
688
  container.append(element);
356
689
  });
357
690
  renderEdges();
358
691
  applyViewport();
692
+ if (!live && !hasFitted) hasFitted = fitView();
693
+ if (!live && panelNodeId) renderNodePanel();
694
+ }
695
+
696
+ function nodeElements() {
697
+ return Array.from(byId('nodes')?.children || []);
359
698
  }
360
699
 
361
700
  function updateSelection() {
362
- document.querySelectorAll?.('.node')?.forEach?.((element) => {
363
- element.classList.toggle('selected', selectedIds.has(element.dataset.nodeId));
364
- });
701
+ for (const element of nodeElements()) {
702
+ const selected = selectedIds.has(element.dataset.nodeId);
703
+ element.classList.toggle('selected', selected);
704
+ const names = String(element.className || '').split(/\s+/).filter((name) => name && name !== 'selected');
705
+ if (selected) names.push('selected');
706
+ element.className = names.join(' ');
707
+ }
365
708
  }
366
709
 
367
710
  function selectNode(nodeId, { additive = false } = {}) {
@@ -374,6 +717,7 @@ function selectNode(nodeId, { additive = false } = {}) {
374
717
  selectedId = nodeId;
375
718
  selectedEdgeId = null;
376
719
  updateSelection();
720
+ renderEdges();
377
721
  }
378
722
 
379
723
  function deleteEdge(id) {
@@ -389,7 +733,7 @@ function deleteEdge(id) {
389
733
  }
390
734
 
391
735
  function addEdge(from, to) {
392
- if (!draft || from === to) return false;
736
+ if (!draft || !from || !to || from === to) return false;
393
737
  if (draft.edges.some((edge) => edge.from === from && edge.to === to)) return false;
394
738
  if (transitivelyDependsOn(from, to)) return false;
395
739
  if (!draft.nodes.some((node) => node.id === from) || !draft.nodes.some((node) => node.id === to)) return false;
@@ -401,12 +745,28 @@ function addEdge(from, to) {
401
745
  return true;
402
746
  }
403
747
 
748
+ function dependsOnTarget(nodeId, targetId, ignoreEdgeId, seen = new Set()) {
749
+ if (!nodeId || !targetId) return false;
750
+ if (nodeId === targetId) return true;
751
+ if (seen.has(nodeId)) return false;
752
+ seen.add(nodeId);
753
+ const upstream = (draft?.edges || [])
754
+ .filter((edge) => edge.to === nodeId && edge.id !== ignoreEdgeId)
755
+ .map((edge) => edge.from);
756
+ return upstream.some((from) => dependsOnTarget(from, targetId, ignoreEdgeId, seen));
757
+ }
758
+
404
759
  function repointEdge(id, from, to) {
405
760
  const edge = draft?.edges.find((candidate) => candidate.id === id);
406
- if (!edge) return false;
761
+ if (!edge || !from || !to || from === to) return false;
762
+ if (edge.from === from && edge.to === to) return true;
763
+ if (!draft.nodes.some((node) => node.id === from) || !draft.nodes.some((node) => node.id === to)) return false;
764
+ if (draft.edges.some((candidate) => candidate.id !== id && candidate.from === from && candidate.to === to)) return false;
765
+ if (dependsOnTarget(from, to, id)) return false;
407
766
  edge.from = from;
408
767
  edge.to = to;
409
768
  syncDependencies();
769
+ selectedEdgeId = id;
410
770
  captureHistory();
411
771
  renderGraph();
412
772
  validateDraft();
@@ -423,6 +783,7 @@ function beginNodeInteraction(event) {
423
783
  return;
424
784
  }
425
785
  if (!selectedIds.has(nodeId)) selectNode(nodeId);
786
+ element.focus?.();
426
787
  if (spacePressed) return beginPan(event);
427
788
  const world = screenToWorld(event.clientX, event.clientY);
428
789
  const position = positions.get(nodeId);
@@ -433,7 +794,8 @@ function beginNodeInteraction(event) {
433
794
  element,
434
795
  offsetX: world.x - position.x,
435
796
  offsetY: world.y - position.y,
436
- origins: new Map([...selectedIds].map((id) => [id, { ...positions.get(id) }]))
797
+ origins: new Map([...selectedIds].map((id) => [id, { ...positions.get(id) }])),
798
+ moved: false
437
799
  };
438
800
  element.classList.add('dragging');
439
801
  element.setPointerCapture?.(event.pointerId);
@@ -455,23 +817,42 @@ function beginPan(event) {
455
817
 
456
818
  function handlePointerMove(event) {
457
819
  if (connection) {
458
- const from = positions.get(connection.sourceId);
459
820
  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}`);
821
+ const cursor = screenToWorld(event.clientX, event.clientY);
822
+ let x1;
823
+ let y1;
824
+ let x2;
825
+ let y2;
826
+ if (connection.edgeId && connection.end === 'from') {
827
+ const target = positions.get(connection.fixedId);
828
+ if (!target || !preview?.setAttribute) return;
829
+ x1 = cursor.x;
830
+ y1 = cursor.y;
831
+ x2 = target.x;
832
+ y2 = target.y + NODE_PORT_Y;
833
+ } else {
834
+ const source = positions.get(connection.sourceId || connection.fixedId);
835
+ if (!source || !preview?.setAttribute) return;
836
+ x1 = source.x + NODE_WIDTH;
837
+ y1 = source.y + NODE_PORT_Y;
838
+ x2 = cursor.x;
839
+ y2 = cursor.y;
466
840
  }
841
+ preview.style.display = 'block';
842
+ preview.setAttribute('d', curvePath(x1, y1, x2, y2));
467
843
  return;
468
844
  }
469
845
  if (!interaction || interaction.pointerId !== event.pointerId) return;
846
+ if (interaction.type === 'minimap') {
847
+ panFromMinimapEvent(event);
848
+ return;
849
+ }
470
850
  if (interaction.type === 'node') {
471
851
  const world = screenToWorld(event.clientX, event.clientY);
472
852
  const position = { x: world.x - interaction.offsetX, y: world.y - interaction.offsetY };
473
853
  const origin = interaction.origins.get(interaction.nodeId);
474
854
  const delta = { x: position.x - origin.x, y: position.y - origin.y };
855
+ if (Math.hypot(delta.x, delta.y) > 3) interaction.moved = true;
475
856
  interaction.origins.forEach((start, id) => {
476
857
  const next = { x: start.x + delta.x, y: start.y + delta.y };
477
858
  positions.set(id, next);
@@ -493,7 +874,12 @@ function finishPointer(event) {
493
874
  if (connection && connection.pointerId === event.pointerId) return finishConnection(event);
494
875
  if (!interaction || interaction.pointerId !== event.pointerId) return;
495
876
  if (interaction.type === 'node') interaction.element.classList.remove('dragging');
877
+ const moved = interaction.type === 'node' && interaction.moved;
496
878
  interaction = null;
879
+ if (moved) {
880
+ suppressNodeClick = true;
881
+ setTimeout(() => { suppressNodeClick = false; }, 0);
882
+ }
497
883
  saveLayoutSoon();
498
884
  }
499
885
 
@@ -515,17 +901,44 @@ function transitivelyDependsOn(nodeId, targetId, seen = new Set()) {
515
901
  return (node?.dependsOn || []).some((dependencyId) => transitivelyDependsOn(dependencyId, targetId, seen));
516
902
  }
517
903
 
904
+ function nodeIdFromPort(hit, selector) {
905
+ const port = hit?.closest?.(selector);
906
+ const node = port?.closest?.('.node');
907
+ return node?.dataset?.nodeId || null;
908
+ }
909
+
518
910
  function finishConnection(event) {
519
- const sourceId = connection.sourceId;
911
+ const pending = connection;
520
912
  connection = null;
521
913
  const preview = scenePart('.preview-edge');
522
914
  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);
915
+ if (!pending || !draft) return;
916
+ const hit = document.elementFromPoint?.(event.clientX, event.clientY);
917
+ if (pending.edgeId) {
918
+ const edge = draft.edges.find((item) => item.id === pending.edgeId);
919
+ if (!edge) return;
920
+ if (pending.end === 'from') {
921
+ const sourceId = nodeIdFromPort(hit, '.port-out');
922
+ if (!sourceId) return;
923
+ if (!repointEdge(edge.id, sourceId, edge.to)) notify('Connection rejected.');
924
+ return;
925
+ }
926
+ const targetId = nodeIdFromPort(hit, '.port-in');
927
+ if (!targetId) return;
928
+ if (!repointEdge(edge.id, edge.from, targetId)) notify('Connection rejected.');
929
+ return;
930
+ }
931
+ const targetId = nodeIdFromPort(hit, '.port-in');
932
+ if (!targetId || targetId === pending.sourceId) {
933
+ if (targetId && targetId === pending.sourceId) notify('A node cannot connect to itself.');
934
+ return;
935
+ }
936
+ if (addEdge(pending.sourceId, targetId)) return;
937
+ if (draft.edges.some((edge) => edge.from === pending.sourceId && edge.to === targetId)) {
938
+ notify('Nodes are already connected.');
939
+ return;
940
+ }
941
+ notify('Connection rejected: it would create a cycle.');
529
942
  }
530
943
 
531
944
  function zoomAt(nextScale, clientX, clientY) {
@@ -549,30 +962,78 @@ function worldAtCanvasCenter() {
549
962
  }
550
963
 
551
964
  function handleWheel(event) {
965
+ if (closestReal(event.target, '#node-panel')) return;
552
966
  event.preventDefault();
967
+ if (event.ctrlKey) {
968
+ zoomAt(viewport.scale * Math.exp(-event.deltaY * 0.01), event.clientX, event.clientY);
969
+ return;
970
+ }
553
971
  zoomAt(viewport.scale * (event.deltaY < 0 ? 1.08 : 0.92), event.clientX, event.clientY);
554
972
  }
555
973
 
556
974
  function autoLayout({ record = true } = {}) {
557
975
  positions = defaultGraphPositions();
976
+ hasFitted = false;
558
977
  renderGraph();
559
978
  if (record) captureHistory();
560
979
  saveLayoutSoon();
561
980
  }
562
981
 
982
+ function graphBounds() {
983
+ const points = (draft?.nodes || []).map((node) => positions.get(node.id)).filter(Boolean);
984
+ if (!points.length) return null;
985
+ const minX = Math.min(...points.map((point) => point.x)) - LABEL_BLEED;
986
+ const minY = Math.min(...points.map((point) => point.y));
987
+ const maxX = Math.max(...points.map((point) => point.x + NODE_WIDTH)) + LABEL_BLEED;
988
+ const maxY = Math.max(...points.map((point) => point.y + NODE_BLOCK_HEIGHT));
989
+ return { minX, minY, maxX, maxY, width: maxX - minX, height: maxY - minY };
990
+ }
991
+
992
+ function computeFit(bounds, canvasWidth, canvasHeight, padding = FIT_PADDING) {
993
+ const availableW = Math.max(1, canvasWidth - padding * 2);
994
+ const availableH = Math.max(1, canvasHeight - padding * 2);
995
+ const scale = Math.min(
996
+ MAX_ZOOM,
997
+ Math.max(MIN_ZOOM, Math.min(availableW / Math.max(bounds.width, 1), availableH / Math.max(bounds.height, 1)))
998
+ );
999
+ return {
1000
+ scale,
1001
+ x: padding + (availableW - bounds.width * scale) / 2 - bounds.minX * scale,
1002
+ y: padding + (availableH - bounds.height * scale) / 2 - bounds.minY * scale
1003
+ };
1004
+ }
1005
+
1006
+ function panelInset() {
1007
+ const panel = byId('node-panel');
1008
+ if (!panel || panel.hidden) return 0;
1009
+ const width = panel.getBoundingClientRect?.().width || 0;
1010
+ const canvasWidth = byId('canvas')?.getBoundingClientRect?.().width || 0;
1011
+ if (width >= 2 && canvasWidth >= 2 && width < canvasWidth - 1) return width;
1012
+ return PANEL_WIDTH;
1013
+ }
1014
+
563
1015
  function fitView() {
564
- if (!draft?.nodes.length) return;
1016
+ if (!draft?.nodes?.length) return false;
565
1017
  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;
1018
+ const rect = byId('canvas')?.getBoundingClientRect?.() || { width: 0, height: 0 };
1019
+ const width = Math.max(0, rect.width - panelInset());
1020
+ if (width < 2 || rect.height < 2) return false;
1021
+ const bounds = graphBounds();
1022
+ if (!bounds) return false;
1023
+ const next = computeFit(bounds, width, rect.height);
1024
+ viewport.scale = next.scale;
1025
+ viewport.x = next.x;
1026
+ viewport.y = next.y;
574
1027
  applyViewport();
575
1028
  saveLayoutSoon();
1029
+ return true;
1030
+ }
1031
+
1032
+ function scheduleFitView() {
1033
+ clearTimeout(resizeFitTimer);
1034
+ resizeFitTimer = setTimeout(() => {
1035
+ if (draft?.nodes?.length) fitView();
1036
+ }, 150);
576
1037
  }
577
1038
 
578
1039
  function captureHistory({ reset = false } = {}) {
@@ -585,8 +1046,7 @@ function captureHistory({ reset = false } = {}) {
585
1046
  history.push(snapshot);
586
1047
  historyIndex = history.length - 1;
587
1048
  }
588
- if (byId('undo')) byId('undo').disabled = historyIndex <= 0;
589
- if (byId('redo')) byId('redo').disabled = historyIndex >= history.length - 1;
1049
+ renderWiringBar();
590
1050
  }
591
1051
 
592
1052
  function restoreHistory(index) {
@@ -599,8 +1059,7 @@ function restoreHistory(index) {
599
1059
  renderGraph();
600
1060
  validateDraft();
601
1061
  saveLayoutSoon();
602
- if (byId('undo')) byId('undo').disabled = historyIndex <= 0;
603
- if (byId('redo')) byId('redo').disabled = historyIndex >= history.length - 1;
1062
+ renderWiringBar();
604
1063
  }
605
1064
 
606
1065
  function saveLayoutSoon() {
@@ -618,8 +1077,164 @@ function saveLayoutSoon() {
618
1077
  }, 350);
619
1078
  }
620
1079
 
1080
+ function edgeSignature(recipe) {
1081
+ return (recipe?.edges || [])
1082
+ .map((edge) => `${edge.from}->${edge.to}`)
1083
+ .sort()
1084
+ .join('|');
1085
+ }
1086
+
1087
+ function rememberLoadedWiring() {
1088
+ loadedEdges = structuredClone(draft?.edges || []);
1089
+ loadedEdgeSignature = edgeSignature({ edges: loadedEdges });
1090
+ }
1091
+
1092
+ function wiringChangeCount() {
1093
+ const loaded = new Set(loadedEdgeSignature ? loadedEdgeSignature.split('|').filter(Boolean) : []);
1094
+ const current = new Set((draft?.edges || []).map((edge) => `${edge.from}->${edge.to}`));
1095
+ let count = 0;
1096
+ for (const edge of current) if (!loaded.has(edge)) count += 1;
1097
+ for (const edge of loaded) if (!current.has(edge)) count += 1;
1098
+ return count;
1099
+ }
1100
+
1101
+ function issueText(issue) {
1102
+ const code = issue?.code ? String(issue.code) : '';
1103
+ const message = issue?.message ? String(issue.message) : '';
1104
+ if (code && message) return `${code}: ${message}`;
1105
+ return code || message;
1106
+ }
1107
+
1108
+ function validationSummary(state = validationState) {
1109
+ const parts = (state.issues || []).map(issueText).filter(Boolean);
1110
+ for (const code of state.extraCodes || []) {
1111
+ if (code && !parts.some((part) => part.includes(code))) parts.push(code);
1112
+ }
1113
+ return parts.join('; ');
1114
+ }
1115
+
1116
+ function issuesFromPayload(payload) {
1117
+ const validation = payload?.validation;
1118
+ const messages = Array.isArray(validation?.errors) ? validation.errors.map(String) : [];
1119
+ const codes = Array.isArray(validation?.codes) ? validation.codes.filter(Boolean).map(String) : [];
1120
+ if (!messages.length) {
1121
+ if (payload?.error || payload?.code) {
1122
+ return {
1123
+ issues: [{ message: String(payload.error || ''), code: String(payload.code || '') }],
1124
+ extraCodes: []
1125
+ };
1126
+ }
1127
+ return { issues: [{ message: 'Validation failed', code: '' }], extraCodes: [] };
1128
+ }
1129
+ if (codes.length === messages.length) {
1130
+ return {
1131
+ issues: messages.map((message, index) => ({ message, code: codes[index] || '' })),
1132
+ extraCodes: []
1133
+ };
1134
+ }
1135
+ return { issues: messages.map((message) => ({ message, code: '' })), extraCodes: codes };
1136
+ }
1137
+
1138
+ function assignInvalidEdges(issues) {
1139
+ edgeIssues = new Map();
1140
+ const loaded = new Set(loadedEdgeSignature ? loadedEdgeSignature.split('|').filter(Boolean) : []);
1141
+ const dirtyIds = (draft?.edges || [])
1142
+ .filter((edge) => !loaded.has(`${edge.from}->${edge.to}`))
1143
+ .map((edge) => edge.id);
1144
+ const remember = (edgeId, issue) => {
1145
+ if (!edgeId) return;
1146
+ if (!edgeIssues.has(edgeId)) edgeIssues.set(edgeId, []);
1147
+ const list = edgeIssues.get(edgeId);
1148
+ if (!list.some((item) => item.code === issue.code && item.message === issue.message)) list.push(issue);
1149
+ };
1150
+ for (const issue of issues) {
1151
+ const message = issue.message || '';
1152
+ let matched = false;
1153
+ for (const edge of draft?.edges || []) {
1154
+ if ((edge.id && message.includes(edge.id)) || message.includes(`${edge.from} -> ${edge.to}`)) {
1155
+ remember(edge.id, issue);
1156
+ matched = true;
1157
+ }
1158
+ }
1159
+ const typed = message.match(/^([a-z0-9-]+) must depend on ([a-z0-9-]+)/);
1160
+ if (typed) {
1161
+ const dependents = new Set((draft?.nodes || []).filter((node) => node.type === typed[1]).map((node) => node.id));
1162
+ const dependencies = new Set((draft?.nodes || []).filter((node) => node.type === typed[2]).map((node) => node.id));
1163
+ for (const edgeId of dirtyIds) {
1164
+ const edge = draft.edges.find((item) => item.id === edgeId);
1165
+ if (!edge) continue;
1166
+ if (dependents.has(edge.to) || dependents.has(edge.from) || dependencies.has(edge.to) || dependencies.has(edge.from)) {
1167
+ remember(edge.id, issue);
1168
+ matched = true;
1169
+ }
1170
+ }
1171
+ }
1172
+ if (/must be a terminal node/.test(message)) {
1173
+ const token = message.split(' ')[0];
1174
+ const ids = new Set((draft?.nodes || []).filter((node) => node.type === token || node.id === token).map((node) => node.id));
1175
+ for (const edge of draft?.edges || []) {
1176
+ if (ids.has(edge.from)) {
1177
+ remember(edge.id, issue);
1178
+ matched = true;
1179
+ }
1180
+ }
1181
+ }
1182
+ if (!matched && dirtyIds.length === 1) remember(dirtyIds[0], issue);
1183
+ }
1184
+ invalidEdgeIds = new Set(edgeIssues.keys());
1185
+ }
1186
+
1187
+ function renderWiringBar() {
1188
+ const changes = draft ? wiringChangeCount() : 0;
1189
+ const bar = byId('wiring-bar');
1190
+ if (bar) bar.hidden = changes === 0;
1191
+ const count = byId('wiring-count');
1192
+ if (count) count.textContent = `${changes} wiring change${changes === 1 ? '' : 's'}`;
1193
+ const pill = byId('wiring-pill');
1194
+ if (pill) {
1195
+ const short = validationState.hash ? String(validationState.hash).slice(0, 8) : '';
1196
+ const status = validationState.status;
1197
+ pill.className = `wiring-pill ${status === 'valid' ? 'valid' : status === 'invalid' ? 'invalid' : 'pending'}`;
1198
+ if (status === 'valid') pill.textContent = short ? `Valid ${short}` : 'Valid';
1199
+ else if (status === 'invalid') pill.textContent = short ? `Invalid ${short}` : 'Invalid';
1200
+ else pill.textContent = 'Checking';
1201
+ }
1202
+ const error = byId('wiring-error');
1203
+ if (error) {
1204
+ // CSS clamps this to two lines; the full compiler output stays in the tooltip.
1205
+ const full = validationState.status === 'invalid' ? validationSummary() : '';
1206
+ error.textContent = full;
1207
+ if (error.setAttribute) error.setAttribute('title', full);
1208
+ }
1209
+ const save = byId('save-wiring');
1210
+ if (save) save.disabled = changes === 0 || validationState.status !== 'valid';
1211
+ const undo = byId('undo');
1212
+ const redo = byId('redo');
1213
+ if (undo) undo.disabled = historyIndex <= 0;
1214
+ if (redo) redo.disabled = historyIndex >= history.length - 1;
1215
+ }
1216
+
1217
+ function discardWiring() {
1218
+ if (!draft) return;
1219
+ draft.edges = structuredClone(loadedEdges);
1220
+ syncDependencies();
1221
+ selectedEdgeId = null;
1222
+ invalidEdgeIds = new Set();
1223
+ edgeIssues = new Map();
1224
+ captureHistory();
1225
+ renderGraph();
1226
+ validateDraft();
1227
+ }
1228
+
1229
+ function clearInvalidEdges() {
1230
+ invalidEdgeIds = new Set();
1231
+ edgeIssues = new Map();
1232
+ }
1233
+
621
1234
  async function validateDraft() {
622
1235
  const sequence = ++validationSequence;
1236
+ validationState = { status: 'pending', hash: '', issues: [], extraCodes: [] };
1237
+ renderWiringBar();
623
1238
  try {
624
1239
  const result = await api('/api/validate', {
625
1240
  method: 'POST',
@@ -627,9 +1242,8 @@ async function validateDraft() {
627
1242
  });
628
1243
  if (sequence !== validationSequence) return result;
629
1244
  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;
1245
+ validationState = { status: 'valid', hash, issues: [], extraCodes: [] };
1246
+ clearInvalidEdges();
633
1247
  byId('review-data').textContent = JSON.stringify({
634
1248
  recipe: draft.id,
635
1249
  version: draft.version,
@@ -637,12 +1251,16 @@ async function validateDraft() {
637
1251
  nodes: draft.nodes.length,
638
1252
  graphHashes: result.plans.map((plan) => plan.graphHash)
639
1253
  }, null, 2);
1254
+ renderWiringBar();
1255
+ renderEdges();
640
1256
  return result;
641
1257
  } catch (error) {
642
1258
  if (sequence !== validationSequence) return null;
643
- byId('integrity').textContent = `INVALID / ${error.message}`;
644
- byId('integrity').className = 'invalid';
645
- byId('review').disabled = true;
1259
+ const parsed = issuesFromPayload(error.payload);
1260
+ validationState = { status: 'invalid', hash: '', issues: parsed.issues, extraCodes: parsed.extraCodes };
1261
+ assignInvalidEdges(parsed.issues);
1262
+ renderWiringBar();
1263
+ renderEdges();
646
1264
  return null;
647
1265
  }
648
1266
  }
@@ -1027,10 +1645,138 @@ function scheduleLiveRender() {
1027
1645
  schedule(() => {
1028
1646
  liveRenderScheduled = false;
1029
1647
  renderLive();
1648
+ refreshWiringLive();
1030
1649
  });
1031
1650
  }
1032
1651
 
1652
+ function textOrNull(value) {
1653
+ if (value == null) return null;
1654
+ const text = String(value).trim();
1655
+ return text || null;
1656
+ }
1657
+
1658
+ function shown(value) {
1659
+ return value == null || value === '' ? '—' : String(value);
1660
+ }
1661
+
1662
+ function summaryFact(label, value) {
1663
+ return `<div class="summary-fact"><span>${escapeHtml(label)}</span><strong>${escapeHtml(shown(value))}</strong></div>`;
1664
+ }
1665
+
1666
+ function deliveryDestination(live) {
1667
+ const artifacts = live?.artifacts || {};
1668
+ const delivery = (live?.plan?.nodes || []).find((node) => node.type === 'delivery');
1669
+ const runtime = delivery ? live.nodes?.[delivery.id] : null;
1670
+ return textOrNull(live?.run?.destination)
1671
+ || textOrNull(live?.run?.delivery?.destination)
1672
+ || textOrNull(artifacts['artifact.delivery']?.destination)
1673
+ || textOrNull(runtime?.destination)
1674
+ || textOrNull(runtime?.output?.destination);
1675
+ }
1676
+
1677
+ function approverName(live) {
1678
+ const artifacts = live?.artifacts || {};
1679
+ const approval = (live?.plan?.nodes || []).find((node) => node.type === 'approval');
1680
+ const runtime = approval ? live.nodes?.[approval.id] : null;
1681
+ return textOrNull(runtime?.approvedBy)
1682
+ || textOrNull(live?.run?.approvedBy)
1683
+ || textOrNull(live?.run?.approver)
1684
+ || textOrNull(artifacts['artifact.delivery']?.approvedBy)
1685
+ || textOrNull(artifacts['artifact.verdict']?.approvedBy);
1686
+ }
1687
+
1688
+ function completedRunDurationMs(live) {
1689
+ const start = Date.parse(live?.run?.createdAt);
1690
+ if (!Number.isFinite(start)) return null;
1691
+ const nodeTimes = Object.values(live?.nodes || {})
1692
+ .map((node) => Date.parse(node?.updatedAt))
1693
+ .filter(Number.isFinite);
1694
+ const lastNode = nodeTimes.length ? Math.max(...nodeTimes) : NaN;
1695
+ const delivery = [
1696
+ live?.run?.deliveredAt,
1697
+ live?.run?.deliveryAt,
1698
+ live?.run?.delivery?.at,
1699
+ live?.artifacts?.['artifact.delivery']?.at
1700
+ ].map((value) => Date.parse(value)).find(Number.isFinite);
1701
+ const end = Number.isFinite(delivery) ? delivery : lastNode;
1702
+ if (!Number.isFinite(end)) {
1703
+ const updated = Date.parse(live?.run?.updatedAt);
1704
+ if (!Number.isFinite(updated)) return null;
1705
+ return Math.max(0, updated - start);
1706
+ }
1707
+ return Math.max(0, end - start);
1708
+ }
1709
+
1710
+ function verificationLabel(summary) {
1711
+ if (!summary || typeof summary !== 'object') return null;
1712
+ const failed = Number(summary.failed);
1713
+ const total = Number(summary.commandCount);
1714
+ if (!Number.isFinite(failed) || !Number.isFinite(total)) return null;
1715
+ return `${Math.max(0, total - failed)} passed / ${failed} failed`;
1716
+ }
1717
+
1718
+ function findingsLabel(summary) {
1719
+ if (!summary || typeof summary !== 'object') return null;
1720
+ if (summary.count == null && summary.blocking == null) return null;
1721
+ return `${summary.count ?? '—'} / ${summary.blocking ?? '—'}`;
1722
+ }
1723
+
1724
+ function driftLabel(summary) {
1725
+ if (!summary || typeof summary !== 'object' || summary.outOfMapCount == null) return null;
1726
+ const count = Number(summary.outOfMapCount);
1727
+ if (!Number.isFinite(count)) return null;
1728
+ return count === 0 ? 'none' : `${count} out of map`;
1729
+ }
1730
+
1731
+ function receiptLabel(summary) {
1732
+ if (!summary || summary.present === false) return 'missing';
1733
+ if (summary.verified === true && !(summary.problems || []).length) return 'verified';
1734
+ if (Array.isArray(summary.problems) && summary.problems.length) return 'problems';
1735
+ if (summary.verified === false) return 'problems';
1736
+ return 'missing';
1737
+ }
1738
+
1739
+ function tokenLabel(live) {
1740
+ const raw = live?.budget?.totalTokens ?? live?.budget?.spentThisRun ?? live?.run?.totalTokens ?? live?.run?.tokens;
1741
+ const value = Number(raw);
1742
+ if (!Number.isFinite(value) || value <= 0) return 'unknown';
1743
+ return String(value);
1744
+ }
1745
+
1746
+ function renderRunSummary() {
1747
+ const card = byId('run-summary-card');
1748
+ if (!card) return;
1749
+ const live = catalog.live;
1750
+ const state = live?.run?.state;
1751
+ if (!live?.run || !TERMINAL_RUN_STATES.has(state)) {
1752
+ card.hidden = true;
1753
+ card.innerHTML = '';
1754
+ return;
1755
+ }
1756
+ const artifacts = live.artifacts || liveArtifacts || {};
1757
+ const duration = formatDuration(completedRunDurationMs(live));
1758
+ card.hidden = false;
1759
+ card.innerHTML = `<div class="summary-facts">${[
1760
+ summaryFact('State', state),
1761
+ summaryFact('Destination', deliveryDestination(live)),
1762
+ summaryFact('Verdict', textOrNull(artifacts['artifact.verdict']?.verdict) || textOrNull(live.run?.verdict)),
1763
+ summaryFact('Approver', approverName(live)),
1764
+ summaryFact('Duration', duration || null),
1765
+ summaryFact('Tests', verificationLabel(artifacts['artifact.verification'])),
1766
+ summaryFact('Findings', findingsLabel(artifacts['artifact.findings'])),
1767
+ summaryFact('Drift', driftLabel(artifacts['artifact.drift'])),
1768
+ summaryFact('Receipt', receiptLabel(artifacts['artifact.receipt'])),
1769
+ summaryFact('Tokens', tokenLabel(live))
1770
+ ].join('')}</div>`;
1771
+ }
1772
+
1773
+ function refreshWiringLive() {
1774
+ if (workspace !== 'wiring' || !draft || interaction || connection) return;
1775
+ renderGraph({ live: true });
1776
+ }
1777
+
1033
1778
  function renderLive() {
1779
+ renderRunSummary();
1034
1780
  const live = catalog.live;
1035
1781
  const summary = byId('run-summary');
1036
1782
  const rail = byId('stage-rail');
@@ -1167,6 +1913,7 @@ function applyEvent(event) {
1167
1913
  lifecycleEvents = lifecycleEvents.concat(incoming).slice(-100);
1168
1914
  if (event.payload?.presence) agentPresence = event.payload;
1169
1915
  else if (catalog.live) catalog.live.lifecycle = event.payload;
1916
+ applyLifecycleNodes(incoming);
1170
1917
  } else if (event.type === 'presence') {
1171
1918
  agentPresence = event.payload || agentPresence;
1172
1919
  if (catalog.live) catalog.live.presence = agentPresence;
@@ -1180,6 +1927,23 @@ function applyEvent(event) {
1180
1927
  scheduleLiveRender();
1181
1928
  }
1182
1929
 
1930
+ const LIVE_NODE_STATUSES = new Set(['PENDING', 'READY', 'RUNNING', 'PASSED', 'FAILED', 'SKIPPED', 'BLOCKED', 'WAITING']);
1931
+
1932
+ function applyLifecycleNodes(events) {
1933
+ if (!catalog.live) return;
1934
+ catalog.live.nodes = catalog.live.nodes || {};
1935
+ for (const item of events || []) {
1936
+ const status = String(item?.status || '').toUpperCase();
1937
+ if (!item?.nodeId || !LIVE_NODE_STATUSES.has(status)) continue;
1938
+ const current = catalog.live.nodes[item.nodeId] || {};
1939
+ catalog.live.nodes[item.nodeId] = {
1940
+ ...current,
1941
+ status,
1942
+ ...(item.at ? { updatedAt: item.at } : {})
1943
+ };
1944
+ }
1945
+ }
1946
+
1183
1947
  function parseSseBlock(block) {
1184
1948
  let type = 'message';
1185
1949
  let data = '';
@@ -1318,14 +2082,15 @@ async function loadRecipe() {
1318
2082
  draft = normalizeDraftGraph(structuredClone(result.recipe));
1319
2083
  source = result.source;
1320
2084
  loadedRecipeId = draft.id;
2085
+ rememberLoadedWiring();
1321
2086
  selectedId = null;
1322
2087
  selectedIds.clear();
1323
2088
  selectedEdgeId = null;
1324
2089
  positions = new Map(Object.entries(saved.layout?.positions || {}));
1325
2090
  ensurePositions();
1326
2091
  viewport = saved.layout?.viewport || { x: 0, y: 0, scale: 1 };
2092
+ hasFitted = false;
1327
2093
  renderGraph();
1328
- if (!saved.layout || (draft.nodes.length <= 12 && viewport.scale < 0.45)) fitView();
1329
2094
  captureHistory({ reset: true });
1330
2095
  await validateDraft();
1331
2096
  }
@@ -1343,13 +2108,590 @@ async function refreshCatalog(selectedRecipe) {
1343
2108
  renderLive();
1344
2109
  }
1345
2110
 
2111
+ function closestReal(element, selector) {
2112
+ const node = element?.closest ? element : element?.parentElement;
2113
+ if (typeof node?.closest !== 'function') return null;
2114
+ const found = node.closest(selector);
2115
+ if (!found || typeof found.matches !== 'function' || !found.matches(selector)) return null;
2116
+ return found;
2117
+ }
2118
+
2119
+ function runtimeFor(node) {
2120
+ if (!node) return null;
2121
+ return catalog.live?.nodes?.[node.id] || null;
2122
+ }
2123
+
2124
+ function nodeSummary(node) {
2125
+ const runtime = runtimeFor(node) || {};
2126
+ const raw = runtime.activity || runtime.summary || node.summary || node.description || '';
2127
+ const line = String(raw).replace(/\s+/g, ' ').trim();
2128
+ if (!line) return '';
2129
+ return line.length > 160 ? `${line.slice(0, 159)}…` : line;
2130
+ }
2131
+
2132
+ function nodeDepths() {
2133
+ const depths = new Map();
2134
+ const visiting = new Set();
2135
+ const depthFor = (node) => {
2136
+ if (!node) return 0;
2137
+ if (depths.has(node.id)) return depths.get(node.id);
2138
+ if (visiting.has(node.id)) return 0;
2139
+ visiting.add(node.id);
2140
+ const depth = (node.dependsOn || []).reduce((maximum, dependencyId) => {
2141
+ const dependency = draft.nodes.find((candidate) => candidate.id === dependencyId);
2142
+ return Math.max(maximum, dependency ? depthFor(dependency) + 1 : 0);
2143
+ }, 0);
2144
+ visiting.delete(node.id);
2145
+ depths.set(node.id, depth);
2146
+ return depth;
2147
+ };
2148
+ for (const node of draft?.nodes || []) depthFor(node);
2149
+ return depths;
2150
+ }
2151
+
2152
+ function columnsByDepth() {
2153
+ const depths = nodeDepths();
2154
+ const columns = new Map();
2155
+ for (const node of draft?.nodes || []) {
2156
+ const depth = depths.get(node.id) || 0;
2157
+ if (!columns.has(depth)) columns.set(depth, []);
2158
+ columns.get(depth).push(node.id);
2159
+ }
2160
+ for (const column of columns.values()) {
2161
+ column.sort((left, right) => (positions.get(left)?.y ?? 0) - (positions.get(right)?.y ?? 0)
2162
+ || String(left).localeCompare(String(right)));
2163
+ }
2164
+ return columns;
2165
+ }
2166
+
2167
+ function focusNode(nodeId) {
2168
+ nodeElements().find((element) => element.dataset.nodeId === nodeId)?.focus?.();
2169
+ }
2170
+
2171
+ function clearSelection() {
2172
+ selectedId = null;
2173
+ selectedIds = new Set();
2174
+ selectedEdgeId = null;
2175
+ updateSelection();
2176
+ renderEdges();
2177
+ }
2178
+
2179
+ function moveSelection(direction) {
2180
+ if (!draft?.nodes?.length) return null;
2181
+ const columns = columnsByDepth();
2182
+ const depths = [...columns.keys()].sort((left, right) => left - right);
2183
+ if (!depths.length) return null;
2184
+ const known = selectedId && draft.nodes.some((node) => node.id === selectedId);
2185
+ if (!known) {
2186
+ const first = columns.get(depths[0])[0];
2187
+ selectNode(first);
2188
+ focusNode(first);
2189
+ return first;
2190
+ }
2191
+ const depth = nodeDepths().get(selectedId) || 0;
2192
+ const column = columns.get(depth) || [];
2193
+ const row = Math.max(0, column.indexOf(selectedId));
2194
+ let next = null;
2195
+ if (direction === 'up') next = column[row - 1] || null;
2196
+ else if (direction === 'down') next = column[row + 1] || null;
2197
+ else {
2198
+ const depthIndex = depths.indexOf(depth);
2199
+ const neighborDepth = depths[depthIndex + (direction === 'right' ? 1 : -1)];
2200
+ if (neighborDepth == null) return selectedId;
2201
+ const neighbor = columns.get(neighborDepth) || [];
2202
+ next = neighbor[Math.min(row, neighbor.length - 1)] || null;
2203
+ }
2204
+ if (!next || next === selectedId) return selectedId;
2205
+ selectNode(next);
2206
+ focusNode(next);
2207
+ return next;
2208
+ }
2209
+
2210
+ function scheduleTooltip(element) {
2211
+ clearTimeout(tooltipTimer);
2212
+ const nodeId = element?.dataset?.nodeId;
2213
+ tooltipTimer = setTimeout(() => {
2214
+ tooltipTimer = null;
2215
+ if (!nodeId || !draft?.nodes?.some((node) => node.id === nodeId)) return;
2216
+ const current = nodeElements().find((item) => item.dataset.nodeId === nodeId) || element;
2217
+ showTooltip(current);
2218
+ }, TOOLTIP_DELAY_MS);
2219
+ }
2220
+
2221
+ function hideTooltip() {
2222
+ clearTimeout(tooltipTimer);
2223
+ tooltipTimer = null;
2224
+ if (nodeTooltip) nodeTooltip.hidden = true;
2225
+ }
2226
+
2227
+ function showTooltip(element) {
2228
+ const node = draft?.nodes?.find((item) => item.id === element?.dataset?.nodeId);
2229
+ if (!node || !nodeTooltip) return;
2230
+ const index = draft.nodes.indexOf(node);
2231
+ const summary = nodeSummary(node);
2232
+ const lines = [
2233
+ `<strong>${escapeHtml(displayName(node))}</strong>`,
2234
+ `<span class="tooltip-type">${escapeHtml(node.type)} · ${escapeHtml(stageLabel(node, index))}</span>`,
2235
+ `<span class="tooltip-status">${escapeHtml(liveStatusText(node))}</span>`
2236
+ ];
2237
+ if (summary) lines.push(`<span class="tooltip-summary">${escapeHtml(summary)}</span>`);
2238
+ nodeTooltip.innerHTML = lines.join('');
2239
+ const canvasRect = byId('canvas')?.getBoundingClientRect?.() || { left: 0, top: 0, width: 0 };
2240
+ const rect = element.getBoundingClientRect?.() || { left: 0, bottom: 0 };
2241
+ const width = 240;
2242
+ const left = Math.max(8, Math.min(rect.left - canvasRect.left, Math.max(8, canvasRect.width - width - 8)));
2243
+ nodeTooltip.style.left = `${left}px`;
2244
+ nodeTooltip.style.top = `${rect.bottom - canvasRect.top + 8}px`;
2245
+ nodeTooltip.hidden = false;
2246
+ }
2247
+
2248
+ function onNodeClick(event) {
2249
+ if (closestReal(event.target, '.port')) return;
2250
+ if (event.shiftKey || spacePressed || suppressNodeClick) {
2251
+ suppressNodeClick = false;
2252
+ return;
2253
+ }
2254
+ openNodePanel(event.currentTarget?.dataset?.nodeId);
2255
+ }
2256
+
2257
+ function headerDuration(node, io) {
2258
+ const derived = formatDuration(nodeDurationMs(node?.id, catalog.live, draft));
2259
+ if (derived) return derived;
2260
+ // Pending/ready nodes have no meaningful duration; never show "0s" for them.
2261
+ const state = graphStateClass(runtimeFor(node)?.status);
2262
+ if (state !== 'passed' && state !== 'failed' && state !== 'active') return '';
2263
+ const explicit = Number(io?.durationMs);
2264
+ if (Number.isFinite(explicit) && explicit >= 0) return formatDuration(explicit);
2265
+ return formatDuration(legacyDurationMs(runtimeFor(node)));
2266
+ }
2267
+
2268
+ function tabButton(id, label) {
2269
+ const selected = panelTab === id;
2270
+ 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}</button>`;
2271
+ }
2272
+
2273
+ function jsonBlock(value) {
2274
+ if (value == null || value === '') return '<p class="muted">None</p>';
2275
+ const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
2276
+ return `<pre>${escapeHtml(text)}</pre>`;
2277
+ }
2278
+
2279
+ function artifactBlock(artifact) {
2280
+ if (!artifact) return '<p class="muted">No artifact.</p>';
2281
+ if (artifact.unavailable) {
2282
+ return `<p class="muted">Artifact unavailable (${escapeHtml(artifact.code || 'unknown')}).</p>`;
2283
+ }
2284
+ const preview = artifact.preview || artifact;
2285
+ const path = preview.path || artifact.descriptor?.path || '';
2286
+ return `
2287
+ ${path ? `<p class="artifact-path">${escapeHtml(path)}</p>` : ''}
2288
+ ${preview.content ? `<pre>${escapeHtml(preview.content)}</pre>` : '<p class="muted">No preview.</p>'}
2289
+ `;
2290
+ }
2291
+
2292
+ function inputPane(io) {
2293
+ const input = io?.input || {};
2294
+ const dependencies = (input.dependencies || []).map((item) =>
2295
+ `<li><strong>${escapeHtml(item.nodeId)}</strong> <span class="muted">${escapeHtml(item.status || '')}</span></li>`
2296
+ ).join('');
2297
+ return `
2298
+ ${input.task ? `<h3>Task</h3><p>${escapeHtml(input.task)}</p>` : '<p class="muted">This node reads its input from upstream nodes.</p>'}
2299
+ ${input.constraints ? `<h3>Constraints</h3><p>${escapeHtml(input.constraints)}</p>` : ''}
2300
+ ${input.goal ? `<h3>Goal</h3>${jsonBlock(input.goal)}` : ''}
2301
+ <h3>Upstream</h3>
2302
+ ${dependencies ? `<ul>${dependencies}</ul>` : '<p class="muted">No upstream nodes.</p>'}
2303
+ `;
2304
+ }
2305
+
2306
+ function outputPane(io) {
2307
+ const output = io?.output || {};
2308
+ return `
2309
+ <h3>Status</h3>
2310
+ <p>${escapeHtml(output.status || 'Unknown')}</p>
2311
+ ${output.reason ? `<h3>Reason</h3><p>${escapeHtml(output.reason)}</p>` : ''}
2312
+ ${output.loopGroupId ? `<p class="muted">Loop ${escapeHtml(output.loopGroupId)} · iteration ${escapeHtml(String(output.loopIteration ?? '—'))}</p>` : ''}
2313
+ <h3>Artifact</h3>
2314
+ ${artifactBlock(output.artifact)}
2315
+ `;
2316
+ }
2317
+
2318
+ function evidencePane(view) {
2319
+ const fetched = view.artifacts || [];
2320
+ if (fetched.length) {
2321
+ return fetched.map((artifact) => artifact.error
2322
+ ? `<p class="validation-message">${escapeHtml(artifact.path || 'Artifact')}: ${escapeHtml(artifact.error)}</p>`
2323
+ : `<article class="evidence-card"><p class="artifact-path">${escapeHtml(artifact.path || '')}</p><pre>${escapeHtml(artifact.content || '')}</pre></article>`
2324
+ ).join('');
2325
+ }
2326
+ if (view.io?.evidence) return artifactBlock(view.io.evidence);
2327
+ return '<p class="muted">No evidence recorded for this node.</p>';
2328
+ }
2329
+
2330
+ function formatEventTime(value) {
2331
+ const text = String(value || '');
2332
+ return text ? text.replace('T', ' ').slice(0, 19) : '—';
2333
+ }
2334
+
2335
+ function eventForNode(event, nodeId) {
2336
+ if (!event || !nodeId) return false;
2337
+ if (event.nodeId === nodeId) return true;
2338
+ if (Array.isArray(event.changedNodes) && event.changedNodes.includes(nodeId)) return true;
2339
+ if (Array.isArray(event.changes) && event.changes.some((change) => change.nodeId === nodeId)) return true;
2340
+ return false;
2341
+ }
2342
+
2343
+ function timelinePane(view) {
2344
+ const events = (view.events || []).filter((event) => eventForNode(event, panelNodeId));
2345
+ if (!events.length) return '<p class="muted">No lifecycle events for this node yet.</p>';
2346
+ return `<ol class="panel-timeline">${events.map((event) => `
2347
+ <li>
2348
+ <time>${escapeHtml(formatEventTime(event.at))}</time>
2349
+ <strong>${escapeHtml(event.type || 'event')}</strong>
2350
+ <span>${escapeHtml(event.message || '')}</span>
2351
+ </li>`).join('')}</ol>`;
2352
+ }
2353
+
2354
+ function paneBody(view) {
2355
+ if (view.status === 'empty') {
2356
+ 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>';
2357
+ }
2358
+ if (view.status === 'loading') return '<p class="muted">Loading node details…</p>';
2359
+ if (view.status === 'error') return `<p class="validation-message">${escapeHtml(view.message || 'Could not load this node.')}</p>`;
2360
+ if (panelTab === 'output') return outputPane(view.io);
2361
+ if (panelTab === 'evidence') return evidencePane(view);
2362
+ if (panelTab === 'timeline') return timelinePane(view);
2363
+ return inputPane(view.io);
2364
+ }
2365
+
2366
+ function renderNodePanel(next) {
2367
+ if (next) panelView = next;
2368
+ const panel = byId('node-panel');
2369
+ const node = draft?.nodes?.find((item) => item.id === panelNodeId);
2370
+ if (!panel || !node) return;
2371
+ const index = draft.nodes.indexOf(node);
2372
+ const runtime = runtimeFor(node);
2373
+ const duration = headerDuration(node, panelView.io);
2374
+ const state = graphStateClass(runtime?.status || panelView.io?.output?.status);
2375
+ const word = statusWord(runtime?.status || panelView.io?.output?.status);
2376
+ panel.innerHTML = `
2377
+ <div class="node-panel-frame">
2378
+ <header class="node-panel-head">
2379
+ <span class="node-icon panel-type-icon">${nodeIcon(node.type)}</span>
2380
+ <div class="node-panel-titles">
2381
+ <h2>${escapeHtml(displayName(node))}</h2>
2382
+ <p>${escapeHtml(node.type)} · ${escapeHtml(stageLabel(node, index))}</p>
2383
+ </div>
2384
+ <div class="node-panel-meta">
2385
+ <span class="status-pill status-${state}">${escapeHtml(word)}</span>
2386
+ ${duration ? `<span class="status-duration">${escapeHtml(duration)}</span>` : ''}
2387
+ </div>
2388
+ <button type="button" class="node-panel-close" aria-label="Close node panel">×</button>
2389
+ </header>
2390
+ <div class="io-tabs" role="tablist" aria-label="Node details">
2391
+ ${tabButton('input', 'Input')}
2392
+ ${tabButton('output', 'Output')}
2393
+ ${tabButton('evidence', 'Evidence')}
2394
+ ${tabButton('timeline', 'Timeline')}
2395
+ </div>
2396
+ <div class="node-panel-body" role="tabpanel" id="node-pane-${panelTab}" aria-labelledby="node-tab-${panelTab}">
2397
+ ${paneBody(panelView)}
2398
+ </div>
2399
+ </div>
2400
+ `;
2401
+ }
2402
+
2403
+ function collectArtifactPaths(io) {
2404
+ const paths = [];
2405
+ const push = (artifact) => {
2406
+ if (!artifact || artifact.unavailable) return;
2407
+ const path = artifact.preview?.path || artifact.descriptor?.path || artifact.path;
2408
+ if (path && !paths.includes(path)) paths.push(path);
2409
+ };
2410
+ push(io?.evidence);
2411
+ push(io?.output?.artifact);
2412
+ return paths.slice(0, 6);
2413
+ }
2414
+
2415
+ async function loadPanel(nodeId) {
2416
+ const request = ++panelRequest;
2417
+ const runId = followedRunId();
2418
+ if (!runId) {
2419
+ renderNodePanel({ status: 'empty' });
2420
+ return;
2421
+ }
2422
+ try {
2423
+ const [ioResult, lifeResult] = await Promise.all([
2424
+ api(`/api/runs/${encodeURIComponent(runId)}/nodes/${encodeURIComponent(nodeId)}`),
2425
+ api(`/api/runs/${encodeURIComponent(runId)}/lifecycle?after=0&limit=100`)
2426
+ ]);
2427
+ if (request !== panelRequest || panelNodeId !== nodeId) return;
2428
+ const io = ioResult.io;
2429
+ const artifacts = [];
2430
+ for (const path of collectArtifactPaths(io)) {
2431
+ try {
2432
+ const result = await api(`/api/runs/${encodeURIComponent(runId)}/artifacts?path=${encodeURIComponent(path)}`);
2433
+ artifacts.push(result.artifact);
2434
+ } catch (error) {
2435
+ artifacts.push({ path, error: error.message });
2436
+ }
2437
+ }
2438
+ if (request !== panelRequest || panelNodeId !== nodeId) return;
2439
+ renderNodePanel({
2440
+ status: 'ready',
2441
+ io,
2442
+ events: lifeResult.lifecycle?.events || [],
2443
+ artifacts
2444
+ });
2445
+ } catch (error) {
2446
+ if (request !== panelRequest || panelNodeId !== nodeId) return;
2447
+ renderNodePanel({ status: 'error', message: error.message });
2448
+ }
2449
+ }
2450
+
2451
+ function openNodePanel(nodeId) {
2452
+ if (!nodeId || !draft?.nodes?.some((node) => node.id === nodeId)) return;
2453
+ const alreadyOpen = panelIsOpen();
2454
+ if (panelNodeId !== nodeId) panelTab = 'input';
2455
+ panelNodeId = nodeId;
2456
+ selectNode(nodeId);
2457
+ focusNode(nodeId);
2458
+ const panel = byId('node-panel');
2459
+ if (!panel) return;
2460
+ panel.hidden = false;
2461
+ byId('canvas')?.classList.add('panel-open');
2462
+ const runId = followedRunId();
2463
+ renderNodePanel(runId ? { status: 'loading' } : { status: 'empty' });
2464
+ if (!alreadyOpen) fitView();
2465
+ if (runId) loadPanel(nodeId);
2466
+ }
2467
+
2468
+ function closeNodePanel() {
2469
+ panelNodeId = null;
2470
+ panelRequest += 1;
2471
+ panelView = { status: 'empty' };
2472
+ const panel = byId('node-panel');
2473
+ if (panel) {
2474
+ panel.hidden = true;
2475
+ panel.innerHTML = '';
2476
+ }
2477
+ byId('canvas')?.classList.remove('panel-open');
2478
+ hideTooltip();
2479
+ if (workspace === 'wiring' && draft?.nodes?.length) fitView();
2480
+ }
2481
+
2482
+ function panelIsOpen() {
2483
+ const panel = byId('node-panel');
2484
+ return Boolean(panelNodeId && panel && !panel.hidden);
2485
+ }
2486
+
2487
+ function onPanelClick(event) {
2488
+ if (closestReal(event.target, '.node-panel-close')) {
2489
+ closeNodePanel();
2490
+ return;
2491
+ }
2492
+ const tab = closestReal(event.target, '[role="tab"]');
2493
+ if (!tab?.dataset?.tab) return;
2494
+ panelTab = tab.dataset.tab;
2495
+ renderNodePanel();
2496
+ byId('node-panel')?.querySelector?.(`[data-tab="${panelTab}"]`)?.focus?.();
2497
+ }
2498
+
2499
+ function onPanelKeydown(event) {
2500
+ const tab = closestReal(event.target, '[role="tab"]');
2501
+ if (!tab) return;
2502
+ const tabs = Array.from(byId('node-panel')?.querySelectorAll?.('[role="tab"]') || []);
2503
+ const index = tabs.indexOf(tab);
2504
+ if (index < 0) return;
2505
+ let next = index;
2506
+ if (event.key === 'ArrowRight' || event.key === 'ArrowDown') next = (index + 1) % tabs.length;
2507
+ else if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') next = (index - 1 + tabs.length) % tabs.length;
2508
+ else if (event.key === 'Home') next = 0;
2509
+ else if (event.key === 'End') next = tabs.length - 1;
2510
+ else return;
2511
+ event.preventDefault();
2512
+ event.stopPropagation();
2513
+ panelTab = tabs[next].dataset.tab;
2514
+ renderNodePanel();
2515
+ byId('node-panel')?.querySelector?.(`[data-tab="${panelTab}"]`)?.focus?.();
2516
+ }
2517
+
2518
+ function updateZoomLabel() {
2519
+ if (!zoomLevelOutput) return;
2520
+ zoomLevelOutput.textContent = `${Math.round(viewport.scale * 100)}%`;
2521
+ }
2522
+
2523
+ const ZOOM_ICONS = {
2524
+ 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>',
2525
+ 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>',
2526
+ 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>',
2527
+ 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>'
2528
+ };
2529
+
2530
+ function zoomButton(label, icon, action) {
2531
+ const button = document.createElement('button');
2532
+ button.type = 'button';
2533
+ button.className = 'zoom-button';
2534
+ button.title = label;
2535
+ button.setAttribute('aria-label', label);
2536
+ button.innerHTML = icon;
2537
+ button.onclick = (event) => {
2538
+ event?.preventDefault?.();
2539
+ event?.stopPropagation?.();
2540
+ action();
2541
+ };
2542
+ return button;
2543
+ }
2544
+
2545
+ function mountCanvasChrome() {
2546
+ const canvas = byId('canvas');
2547
+ if (!canvas || zoomInButton) return;
2548
+ const bar = document.createElement('div');
2549
+ bar.className = 'zoom-controls';
2550
+ zoomInButton = zoomButton('Zoom in', ZOOM_ICONS.in, () => zoomAt(viewport.scale * 1.08));
2551
+ const zoomOutButton = zoomButton('Zoom out', ZOOM_ICONS.out, () => zoomAt(viewport.scale * 0.92));
2552
+ const zoomFitButton = zoomButton('Fit to view', ZOOM_ICONS.fit, () => fitView());
2553
+ const zoomLayoutButton = zoomButton('Auto-layout', ZOOM_ICONS.layout, () => autoLayout());
2554
+ zoomLevelOutput = document.createElement('output');
2555
+ zoomLevelOutput.className = 'zoom-level';
2556
+ zoomLevelOutput.setAttribute('aria-label', 'Zoom level');
2557
+ const sep = () => {
2558
+ const element = document.createElement('span');
2559
+ element.className = 'zoom-sep';
2560
+ element.setAttribute('aria-hidden', 'true');
2561
+ return element;
2562
+ };
2563
+ bar.append(zoomInButton, sep(), zoomOutButton, sep(), zoomFitButton, sep(), zoomLayoutButton, zoomLevelOutput);
2564
+ canvas.append(bar);
2565
+
2566
+ nodeTooltip = document.createElement('div');
2567
+ nodeTooltip.id = 'node-tooltip';
2568
+ nodeTooltip.className = 'node-tooltip';
2569
+ nodeTooltip.setAttribute('role', 'tooltip');
2570
+ nodeTooltip.hidden = true;
2571
+ canvas.append(nodeTooltip);
2572
+
2573
+ minimap = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
2574
+ minimap.setAttribute('class', 'minimap');
2575
+ minimap.setAttribute('aria-label', 'Workflow minimap');
2576
+ minimap.setAttribute('viewBox', `0 0 ${MINIMAP_WIDTH} ${MINIMAP_HEIGHT}`);
2577
+ minimap.setAttribute('width', String(MINIMAP_WIDTH));
2578
+ minimap.setAttribute('height', String(MINIMAP_HEIGHT));
2579
+ minimap.addEventListener('pointerdown', onMinimapPointerDown);
2580
+ canvas.append(minimap);
2581
+
2582
+ const panel = byId('node-panel');
2583
+ if (panel) {
2584
+ panel.hidden = true;
2585
+ panel.addEventListener('click', onPanelClick);
2586
+ panel.addEventListener('keydown', onPanelKeydown);
2587
+ }
2588
+ updateZoomLabel();
2589
+ }
2590
+
2591
+ function minimapMetrics() {
2592
+ const bounds = graphBounds();
2593
+ if (!bounds) return null;
2594
+ const pad = 10;
2595
+ const innerW = MINIMAP_WIDTH - pad * 2;
2596
+ const innerH = MINIMAP_HEIGHT - pad * 2;
2597
+ const scale = Math.min(innerW / Math.max(bounds.width, 1), innerH / Math.max(bounds.height, 1));
2598
+ return {
2599
+ bounds,
2600
+ scale,
2601
+ offsetX: pad + (innerW - bounds.width * scale) / 2,
2602
+ offsetY: pad + (innerH - bounds.height * scale) / 2,
2603
+ width: MINIMAP_WIDTH,
2604
+ height: MINIMAP_HEIGHT
2605
+ };
2606
+ }
2607
+
2608
+ function renderMinimap() {
2609
+ if (!minimap) return;
2610
+ minimap.innerHTML = '';
2611
+ const metrics = minimapMetrics();
2612
+ if (!metrics || !draft?.nodes?.length) return;
2613
+ for (const node of draft.nodes) {
2614
+ const position = positions.get(node.id);
2615
+ if (!position) continue;
2616
+ const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
2617
+ const status = graphStateClass(runtimeFor(node)?.status);
2618
+ rect.setAttribute('class', `minimap-node minimap-${status}`);
2619
+ rect.setAttribute('x', String(metrics.offsetX + (position.x - metrics.bounds.minX) * metrics.scale));
2620
+ rect.setAttribute('y', String(metrics.offsetY + (position.y - metrics.bounds.minY) * metrics.scale));
2621
+ rect.setAttribute('width', String(Math.max(3, NODE_WIDTH * metrics.scale)));
2622
+ rect.setAttribute('height', String(Math.max(3, NODE_BLOCK_HEIGHT * metrics.scale)));
2623
+ rect.setAttribute('rx', '2');
2624
+ minimap.append(rect);
2625
+ }
2626
+ const canvasRect = byId('canvas')?.getBoundingClientRect?.() || { left: 0, top: 0, width: 1, height: 1 };
2627
+ const viewW = Math.max(1, canvasRect.width - panelInset());
2628
+ const viewH = Math.max(1, canvasRect.height);
2629
+ const origin = screenToWorld(canvasRect.left, canvasRect.top);
2630
+ const viewportRect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
2631
+ viewportRect.setAttribute('class', 'minimap-viewport');
2632
+ viewportRect.setAttribute('x', String(metrics.offsetX + (origin.x - metrics.bounds.minX) * metrics.scale));
2633
+ viewportRect.setAttribute('y', String(metrics.offsetY + (origin.y - metrics.bounds.minY) * metrics.scale));
2634
+ viewportRect.setAttribute('width', String(Math.max(4, (viewW / viewport.scale) * metrics.scale)));
2635
+ viewportRect.setAttribute('height', String(Math.max(4, (viewH / viewport.scale) * metrics.scale)));
2636
+ viewportRect.setAttribute('rx', '3');
2637
+ minimap.append(viewportRect);
2638
+ }
2639
+
2640
+ function centerOnWorld(worldX, worldY) {
2641
+ const rect = byId('canvas')?.getBoundingClientRect?.() || { left: 0, top: 0, width: 0, height: 0 };
2642
+ const inset = panelInset();
2643
+ viewport.x = (rect.width - inset) / 2 - worldX * viewport.scale;
2644
+ viewport.y = rect.height / 2 - worldY * viewport.scale;
2645
+ applyViewport();
2646
+ saveLayoutSoon();
2647
+ }
2648
+
2649
+ function panFromMinimapEvent(event) {
2650
+ const metrics = minimapMetrics();
2651
+ if (!metrics || !minimap?.getBoundingClientRect) return;
2652
+ const rect = minimap.getBoundingClientRect();
2653
+ const localX = ((event.clientX - rect.left) / Math.max(rect.width, 1)) * metrics.width;
2654
+ const localY = ((event.clientY - rect.top) / Math.max(rect.height, 1)) * metrics.height;
2655
+ const worldX = metrics.bounds.minX + (localX - metrics.offsetX) / metrics.scale;
2656
+ const worldY = metrics.bounds.minY + (localY - metrics.offsetY) / metrics.scale;
2657
+ centerOnWorld(worldX, worldY);
2658
+ }
2659
+
2660
+ function onMinimapPointerDown(event) {
2661
+ if (event.button !== 0) return;
2662
+ event.preventDefault();
2663
+ event.stopPropagation();
2664
+ interaction = { type: 'minimap', pointerId: event.pointerId };
2665
+ panFromMinimapEvent(event);
2666
+ minimap?.setPointerCapture?.(event.pointerId);
2667
+ }
2668
+
2669
+ function canvasShortcutTarget(target) {
2670
+ if (!target || editableTarget(target)) return false;
2671
+ if (workspace !== 'wiring' || byId('canvas')?.hidden) return false;
2672
+ if (target.id === 'canvas' || target === byId('canvas')) return true;
2673
+ if (target.dataset?.nodeId) return true;
2674
+ return String(target.className || '').split(/\s+/).includes('node');
2675
+ }
2676
+
2677
+ function toggleShortcutSheet() {
2678
+ const dialog = byId('shortcut-sheet');
2679
+ if (!dialog) return;
2680
+ if (dialog.open) dialog.close();
2681
+ else dialog.showModal();
2682
+ }
2683
+
1346
2684
  function bindCanvas() {
1347
2685
  const canvas = byId('canvas');
2686
+ mountCanvasChrome();
1348
2687
  canvas.addEventListener('pointerdown', (event) => {
2688
+ if (closestReal(event.target, '#node-panel, .zoom-controls, .minimap')) return;
1349
2689
  if (event.target === canvas || event.target === byId('scene') || event.target === byId('nodes') || event.target === byId('edges')) {
1350
2690
  selectedId = null;
2691
+ selectedEdgeId = null;
1351
2692
  if (!event.shiftKey) selectedIds.clear();
1352
2693
  updateSelection();
2694
+ renderEdges();
1353
2695
  if (event.button === 1 || spacePressed) beginPan(event);
1354
2696
  }
1355
2697
  });
@@ -1357,10 +2699,6 @@ function bindCanvas() {
1357
2699
  canvas.addEventListener('pointerup', finishPointer);
1358
2700
  canvas.addEventListener('pointercancel', finishPointer);
1359
2701
  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);
1364
2702
  }
1365
2703
 
1366
2704
  function editableTarget(target) {
@@ -1377,23 +2715,98 @@ document.addEventListener('keydown', (event) => {
1377
2715
  if (modifier && event.key.toLowerCase() === 'z') {
1378
2716
  event.preventDefault();
1379
2717
  restoreHistory(historyIndex + (event.shiftKey ? 1 : -1));
1380
- } else if (modifier && event.key.toLowerCase() === 'y') {
2718
+ return;
2719
+ }
2720
+ if (modifier && event.key.toLowerCase() === 'y') {
1381
2721
  event.preventDefault();
1382
2722
  restoreHistory(historyIndex + 1);
1383
- } else if ((event.key === 'Delete' || event.key === 'Backspace') && selectedEdgeId) {
2723
+ return;
2724
+ }
2725
+ if ((event.key === 'Delete' || event.key === 'Backspace') && selectedEdgeId && !panelIsOpen()) {
1384
2726
  event.preventDefault();
1385
2727
  deleteEdge(selectedEdgeId);
2728
+ return;
2729
+ }
2730
+ if (event.key === 'Escape') {
2731
+ if (byId('shortcut-sheet')?.open) {
2732
+ event.preventDefault();
2733
+ byId('shortcut-sheet').close();
2734
+ return;
2735
+ }
2736
+ if (panelIsOpen()) {
2737
+ event.preventDefault();
2738
+ closeNodePanel();
2739
+ return;
2740
+ }
2741
+ if (canvasShortcutTarget(event.target)) {
2742
+ event.preventDefault();
2743
+ clearSelection();
2744
+ }
2745
+ return;
2746
+ }
2747
+ const shortcutQuestion = event.key === '?' || (event.key === '/' && event.shiftKey);
2748
+ if (shortcutQuestion && (byId('shortcut-sheet')?.open || canvasShortcutTarget(event.target))) {
2749
+ event.preventDefault();
2750
+ toggleShortcutSheet();
2751
+ return;
2752
+ }
2753
+ if (!canvasShortcutTarget(event.target)) return;
2754
+ if (modifier || event.altKey) return;
2755
+ const key = event.key;
2756
+ if (key === '+' || key === '=') {
2757
+ event.preventDefault();
2758
+ zoomAt(viewport.scale * 1.08);
2759
+ return;
2760
+ }
2761
+ if (key === '-' || key === '_') {
2762
+ event.preventDefault();
2763
+ zoomAt(viewport.scale * 0.92);
2764
+ return;
2765
+ }
2766
+ if (event.shiftKey) return;
2767
+ if (key === 'f' || key === 'F') {
2768
+ event.preventDefault();
2769
+ fitView();
2770
+ } else if (key === 'l' || key === 'L') {
2771
+ event.preventDefault();
2772
+ autoLayout();
2773
+ } else if (key === '0') {
2774
+ event.preventDefault();
2775
+ zoomAt(1);
2776
+ } else if (key === 'ArrowLeft') {
2777
+ event.preventDefault();
2778
+ moveSelection('left');
2779
+ } else if (key === 'ArrowRight') {
2780
+ event.preventDefault();
2781
+ moveSelection('right');
2782
+ } else if (key === 'ArrowUp') {
2783
+ event.preventDefault();
2784
+ moveSelection('up');
2785
+ } else if (key === 'ArrowDown') {
2786
+ event.preventDefault();
2787
+ moveSelection('down');
2788
+ } else if (key === 'Enter' && selectedId) {
2789
+ event.preventDefault();
2790
+ openNodePanel(selectedId);
1386
2791
  }
1387
2792
  });
1388
2793
  document.addEventListener('keyup', (event) => {
1389
2794
  if (event.code === 'Space') spacePressed = false;
1390
2795
  });
2796
+ if (typeof window !== 'undefined') window.addEventListener('resize', scheduleFitView);
1391
2797
 
1392
- byId('review').onclick = () => {
1393
- if (byId('review').disabled) return;
2798
+ byId('undo').onclick = () => restoreHistory(historyIndex - 1);
2799
+ byId('redo').onclick = () => restoreHistory(historyIndex + 1);
2800
+ byId('discard-wiring').onclick = discardWiring;
2801
+ byId('save-wiring').onclick = () => {
2802
+ if (byId('save-wiring').disabled) return;
1394
2803
  byId('confirm').showModal();
1395
2804
  };
1396
2805
  byId('install').onclick = async () => {
2806
+ if (validationState.status !== 'valid') {
2807
+ notify(validationSummary() || 'Wiring is invalid.');
2808
+ return;
2809
+ }
1397
2810
  try {
1398
2811
  const recipe = authoringRecipe();
1399
2812
  const exists = catalog.recipes.some((item) => item.id === recipe.id && item.source !== 'builtin');