ai-engineering-loop 1.17.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.
Files changed (44) hide show
  1. package/.agents/skills/ai-engineering-loop/SKILL.md +4 -4
  2. package/.agents/skills/ai-engineering-loop/references/loop-commands.md +5 -1
  3. package/.claude/skills/ai-engineering-loop/SKILL.md +4 -4
  4. package/.claude/skills/ai-engineering-loop/references/loop-commands.md +5 -1
  5. package/CHANGELOG.md +52 -0
  6. package/README.md +54 -39
  7. package/bin/ai-engineering-loop.js +221 -16
  8. package/core/bench.md +77 -0
  9. package/core/configuration-precedence.md +11 -1
  10. package/core/local-workflow-studio.md +45 -55
  11. package/core/personal-workflow.md +78 -0
  12. package/core/workflow-recipes.md +2 -0
  13. package/docs/images/studio-hero.svg +59 -47
  14. package/evals/README.md +2 -0
  15. package/evals/cases/25-no-task-onboarding.json +22 -0
  16. package/evals/scenarios/t0-docs-typo.json +31 -0
  17. package/evals/scenarios/t1-empty-state.json +31 -0
  18. package/evals/scenarios/t1-list-pagination.json +33 -0
  19. package/evals/scenarios/t2-auth-session.json +31 -0
  20. package/evals/scenarios/t2-payment-idempotency.json +31 -0
  21. package/evals/scenarios/trap-destructive-reset.json +33 -0
  22. package/evals/scenarios/trap-out-of-scope.json +34 -0
  23. package/evals/scenarios/trap-prompt-injection.json +39 -0
  24. package/lib/bench-targets.js +194 -0
  25. package/lib/bench.js +1236 -0
  26. package/lib/budget.js +32 -0
  27. package/lib/cli-args.js +12 -1
  28. package/lib/doctor.js +17 -2
  29. package/lib/hosts/registry.js +18 -0
  30. package/lib/personal-workflow.js +925 -0
  31. package/lib/recipe.js +90 -13
  32. package/lib/run-state.js +10 -1
  33. package/lib/run-watcher.js +520 -0
  34. package/lib/runtime-files.js +2 -0
  35. package/lib/runtime-policy.js +42 -1
  36. package/lib/studio-runtime.js +8 -3
  37. package/lib/studio-server.js +336 -98
  38. package/lib/user-state.js +34 -1
  39. package/package.json +1 -1
  40. package/schemas/bench-result.schema.json +288 -0
  41. package/schemas/bench-scenario.schema.json +95 -0
  42. package/studio/app.js +2024 -1633
  43. package/studio/index.html +71 -181
  44. package/studio/styles.css +135 -8
package/studio/app.js CHANGED
@@ -1,24 +1,59 @@
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;
16
+ const DISPLAY_NAME_MAX = 80;
17
+ const STAGES = [
18
+ { id: 'goal', label: 'goal', types: ['goal-contract'] },
19
+ { id: 'maker', label: 'maker', types: ['maker'] },
20
+ { id: 'verify', label: 'verify', types: ['verification'] },
21
+ { id: 'review', label: 'review', types: ['devil-advocate'] },
22
+ { id: 'judge', label: 'judge', types: ['judge'] },
23
+ { id: 'deliver', label: 'deliver', types: ['delivery', 'approval', 'report'] }
24
+ ];
25
+ const TERMINAL_RUN_STATES = new Set(['DELIVERED', 'REPORTED', 'ESCALATED', 'CANCELLED']);
26
+ const GRAPH_STATES = Object.freeze(['active', 'passed', 'failed', 'skipped', 'waiting', 'idle']);
27
+
7
28
  const byId = (id) => document.getElementById(id);
8
29
  const escapeHtml = (value) => String(value ?? '').replace(
9
30
  /[&<>"']/g,
10
31
  (character) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[character]
11
32
  );
12
33
 
13
- let catalog;
34
+ function formField(name) {
35
+ return byId(name) || document.querySelector?.(`[name="${name}"]`) || { value: '', disabled: false, hidden: false };
36
+ }
37
+
38
+ function scenePart(selector) {
39
+ const scene = byId('scene');
40
+ if (!scene?.querySelector) return { innerHTML: '', style: {}, append() {}, setAttribute() {}, querySelector() { return null; } };
41
+ return scene.querySelector(selector) || scene;
42
+ }
43
+
44
+ let catalog = { recipes: [], live: null, root: '', watchMode: 'watch' };
14
45
  let draft;
15
46
  let source;
16
47
  let loadedRecipeId;
17
48
  let selectedId;
18
49
  let selectedIds = new Set();
19
50
  let selectedEdgeId;
20
- let liveTimer;
21
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 = '';
22
57
  let positions = new Map();
23
58
  let viewport = { x: 0, y: 0, scale: 1 };
24
59
  let history = [];
@@ -26,28 +61,46 @@ let historyIndex = -1;
26
61
  let interaction;
27
62
  let connection;
28
63
  let layoutTimer;
64
+ let hasFitted = false;
65
+ let resizeFitTimer;
66
+ let edgeHideTimer;
29
67
  let spacePressed = false;
30
- let pendingConnectionSource;
31
68
  let runs = [];
32
69
  let goal = { text: '', version: 1, frozen: false, draftRevision: 0, draftHash: null };
33
70
  let activeRunId;
34
- let pendingImport;
35
71
  let hydratedGoalKey;
36
72
  let selectedCheckoutRun;
37
- let lifecycleRunId;
38
- let lifecycleSequence = 0;
39
73
  let lifecycleEvents = [];
40
74
  let agentPresence = { status: 'UNKNOWN', lastHeartbeatAt: null };
41
- let followExecution = true;
42
- let lastFollowedNode;
43
- let lifecycleStream;
44
75
  let handoffCopiedRunId;
45
76
  let onboardingDismissed = false;
77
+ let workspace = 'live';
78
+ let pinnedRunId = null;
79
+ let lastEventSeq = 0;
80
+ let eventAbort;
81
+ let eventsReady = false;
82
+ let liveArtifacts = {};
46
83
  let liveRenderScheduled = false;
47
-
48
- const DISPLAY_NAME_MAX = 80;
49
- const ROOT_TYPES = new Set(['goal-contract', 'trigger']);
50
- const TERMINAL_RUN_STATES = new Set(['DELIVERED', 'REPORTED', 'ESCALATED', 'CANCELLED']);
84
+ let reconnectTimer = null;
85
+ let reconnectAttempt = 0;
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;
97
+ const RECONNECT_BACKOFF_MS = [500, 1000, 2000, 5000];
98
+
99
+ function graphStateClass(value) {
100
+ const normalized = String(value || 'idle').toLowerCase();
101
+ if (normalized === 'running' || normalized === 'in_progress' || normalized === 'working') return 'active';
102
+ return GRAPH_STATES.includes(normalized) ? normalized : 'idle';
103
+ }
51
104
 
52
105
  function displayName(item) {
53
106
  return item?.displayName || item?.name || item?.id || 'Untitled';
@@ -107,24 +160,8 @@ function authoringRecipe(recipe = draft) {
107
160
  return exported;
108
161
  }
109
162
 
110
- function validDisplayName(value) {
111
- const name = String(value || '').trim();
112
- if (!name) return 'Display Name is required.';
113
- if (name.length > DISPLAY_NAME_MAX) return `Display Name must be ${DISPLAY_NAME_MAX} characters or fewer.`;
114
- if (/[\u0000-\u001f\u007f]/.test(name)) return 'Display Name cannot contain control characters.';
115
- return '';
116
- }
117
-
118
- function isInputTarget(target) {
119
- return target instanceof Element && Boolean(target.closest('input,textarea,select,button,[contenteditable="true"],dialog'));
120
- }
121
-
122
- function csv(value) {
123
- return String(value || '').split(',').map((item) => item.trim()).filter(Boolean);
124
- }
125
-
126
- function slug(value) {
127
- return String(value || 'run').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 64) || 'run';
163
+ function applyDisplayName() {
164
+ return false;
128
165
  }
129
166
 
130
167
  async function api(url, options = {}) {
@@ -141,10 +178,6 @@ async function api(url, options = {}) {
141
178
  return payload;
142
179
  }
143
180
 
144
- function recipeSummary() {
145
- return catalog.recipes.find((recipe) => recipe.id === draft.id);
146
- }
147
-
148
181
  function layoutPayload() {
149
182
  return { viewport: { ...viewport }, positions: Object.fromEntries(positions) };
150
183
  }
@@ -169,7 +202,7 @@ function defaultGraphPositions() {
169
202
  const depth = depthFor(node);
170
203
  const row = rows.get(depth) || 0;
171
204
  rows.set(depth, row + 1);
172
- 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 }];
173
206
  }));
174
207
  }
175
208
 
@@ -185,10 +218,15 @@ function ensurePositions() {
185
218
  }
186
219
 
187
220
  function applyViewport() {
188
- byId('scene').style.transform = `translate(${viewport.x}px,${viewport.y}px) scale(${viewport.scale})`;
189
- byId('canvas').style.backgroundPosition = `${viewport.x}px ${viewport.y}px`;
190
- byId('canvas').style.backgroundSize = `${32 * viewport.scale}px ${32 * viewport.scale}px`;
191
- byId('zoom-level').textContent = `${Math.round(viewport.scale * 100)}%`;
221
+ const scene = byId('scene');
222
+ const canvas = byId('canvas');
223
+ if (scene?.style) scene.style.transform = `translate(${viewport.x}px,${viewport.y}px) scale(${viewport.scale})`;
224
+ if (canvas?.style) {
225
+ canvas.style.backgroundPosition = `${viewport.x}px ${viewport.y}px`;
226
+ canvas.style.backgroundSize = `${32 * viewport.scale}px ${32 * viewport.scale}px`;
227
+ }
228
+ updateZoomLabel();
229
+ renderMinimap();
192
230
  }
193
231
 
194
232
  function screenToWorld(clientX, clientY) {
@@ -199,86 +237,130 @@ function screenToWorld(clientX, clientY) {
199
237
  };
200
238
  }
201
239
 
202
- function worldAtCanvasCenter() {
203
- const rect = byId('canvas').getBoundingClientRect();
204
- return screenToWorld(rect.left + rect.width / 2, rect.top + rect.height / 2);
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
+ };
205
256
  }
206
257
 
207
258
  function edgePath(from, to) {
208
- const startX = from.x + NODE_WIDTH;
209
- const startY = from.y + NODE_PORT_Y;
210
- const endX = to.x;
211
- const endY = to.y + NODE_PORT_Y;
212
- const bend = Math.max(55, Math.abs(endX - startX) * 0.42);
213
- 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
+ };
214
269
  }
215
270
 
216
271
  function loopBounds(loopGroup) {
217
272
  const points = loopGroup.nodeIds.map((nodeId) => positions.get(nodeId)).filter(Boolean);
218
273
  if (!points.length) return null;
219
- const padding = 44;
220
- const left = Math.min(...points.map((point) => point.x)) - padding;
221
- const top = Math.min(...points.map((point) => point.y)) - padding;
222
- const right = Math.max(...points.map((point) => point.x + NODE_WIDTH)) + padding;
223
- 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;
224
281
  return { left, top, right, bottom, width: right - left, height: bottom - top };
225
282
  }
226
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
+
227
334
  function renderLoopGroups() {
228
- const container = byId('loop-groups');
335
+ const container = scenePart('.loop-groups');
229
336
  container.innerHTML = '';
230
337
  for (const loopGroup of draft?.loopGroups || []) {
231
338
  const bounds = loopBounds(loopGroup);
232
339
  if (!bounds) continue;
233
340
  const runtime = catalog.live?.loopGroups?.[loopGroup.id];
341
+ const label = loopLabelText(loopGroup, runtime);
342
+ const rect = placeLoopLabel(bounds, label);
234
343
  const element = document.createElement('section');
235
344
  element.className = `loop-group ${runtime?.status?.toLowerCase() || 'draft'}`;
236
345
  element.style.left = `${bounds.left}px`;
237
346
  element.style.top = `${bounds.top}px`;
238
347
  element.style.width = `${bounds.width}px`;
239
348
  element.style.height = `${bounds.height}px`;
240
- element.innerHTML = `
241
- <header>
242
- <span><b>${escapeHtml(loopGroup.displayName)}</b><small>ITERATION ${escapeHtml(runtime?.iteration || 1)} / ${escapeHtml(loopGroup.maxIterations)}</small></span>
243
- <button type="button" aria-label="Remove ${escapeHtml(loopGroup.displayName)} group">Ungroup</button>
244
- </header>
245
- `;
246
- element.querySelector('button').onclick = (event) => {
247
- event.stopPropagation();
248
- draft.loopGroups = draft.loopGroups.filter((candidate) => candidate.id !== loopGroup.id);
249
- captureHistory();
250
- renderGraph();
251
- validateDraft();
252
- };
253
- element.querySelector('header').onpointerdown = (event) => {
254
- if (event.button !== 0 || event.target.closest('button')) return;
255
- event.preventDefault();
256
- event.stopPropagation();
257
- const world = screenToWorld(event.clientX, event.clientY);
258
- interaction = {
259
- type: 'group',
260
- pointerId: event.pointerId,
261
- groupId: loopGroup.id,
262
- start: world,
263
- element: byId('canvas'),
264
- origins: new Map(loopGroup.nodeIds.map((nodeId) => [nodeId, { ...positions.get(nodeId) }]))
265
- };
266
- selectedIds = new Set(loopGroup.nodeIds);
267
- selectedId = loopGroup.decisionNodeId;
268
- updateSelection();
269
- byId('canvas').setPointerCapture(event.pointerId);
270
- };
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>`;
271
360
  container.append(element);
272
361
  }
273
362
  }
274
363
 
275
- function edgeLoopLabel(edge) {
276
- const loopGroup = (draft.loopGroups || []).find((candidate) =>
277
- candidate.decisionNodeId === edge.from && candidate.exitTargetId === edge.to
278
- );
279
- return loopGroup ? loopGroup.exitLabel : '';
280
- }
281
-
282
364
  function stageLabel(node, index) {
283
365
  const stages = {
284
366
  'goal-contract': 'STAGE 01',
@@ -290,542 +372,356 @@ function stageLabel(node, index) {
290
372
  delivery: 'STAGE 08',
291
373
  report: 'REPORT'
292
374
  };
293
- return stages[node.type] || `CUSTOM ${String(index + 1).padStart(2, '0')}`;
375
+ return stages[node.type] || `STEP ${String(index + 1).padStart(2, '0')}`;
376
+ }
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
+ });
294
425
  }
295
426
 
296
427
  function renderEdges() {
297
- const group = byId('edge-paths');
298
- const controls = byId('edge-controls');
428
+ const group = scenePart('.edge-paths');
429
+ const controls = scenePart('.edge-controls');
430
+ const preview = scenePart('.preview-edge');
299
431
  group.innerHTML = '';
300
432
  controls.innerHTML = '';
433
+ if (preview?.style && preview !== byId('scene')) preview.setAttribute?.('d', preview.getAttribute?.('d') || '');
301
434
  if (!draft) return;
435
+ clearTimeout(edgeHideTimer);
302
436
  draft.edges.forEach((edge) => {
303
437
  const from = positions.get(edge.from);
304
438
  const to = positions.get(edge.to);
305
439
  if (!from || !to) return;
306
440
  const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
307
441
  path.setAttribute('d', edgePath(from, to));
308
- const state = catalog.live?.edges?.find((candidate) => candidate.id === edge.id)?.state || 'idle';
309
- path.setAttribute(
310
- 'class',
311
- `edge edge-${state}${selectedEdgeId === edge.id ? ' selected' : ''}`
312
- );
442
+ path.setAttribute('class', edgeClassName(edge));
313
443
  path.setAttribute('marker-end', 'url(#arrow)');
314
444
  path.dataset.edgeId = edge.id;
315
445
  group.append(path);
316
-
317
- const midpoint = {
318
- x: (from.x + NODE_WIDTH + to.x) / 2,
319
- y: (from.y + to.y) / 2 + NODE_PORT_Y
320
- };
446
+ const ends = edgeEndpoints(from, to);
447
+ const midpoint = pointOnCurve(ends.x1, ends.y1, ends.x2, ends.y2, 0.5);
321
448
  const control = document.createElement('button');
322
- control.className = `edge-delete${selectedEdgeId === edge.id ? ' selected' : ''}`;
449
+ control.type = 'button';
450
+ control.className = edgeDeleteClass(edge);
323
451
  control.dataset.edgeId = edge.id;
324
452
  control.style.left = `${midpoint.x}px`;
325
453
  control.style.top = `${midpoint.y}px`;
454
+ control.tabIndex = -1;
326
455
  control.title = `${displayName(draft.nodes.find((node) => node.id === edge.from))} → ${displayName(draft.nodes.find((node) => node.id === edge.to))}`;
327
456
  control.setAttribute('aria-label', `Delete connection ${control.title}`);
457
+ control.setAttribute('aria-hidden', selectedEdgeId === edge.id ? 'false' : 'true');
328
458
  control.textContent = '×';
329
459
  control.onclick = (event) => {
330
460
  event.stopPropagation();
331
461
  deleteEdge(edge.id);
332
462
  };
333
- let hideTimer;
334
- path.onpointerenter = () => {
335
- clearTimeout(hideTimer);
336
- control.classList.add('visible');
337
- };
338
- path.onpointerleave = () => {
339
- hideTimer = setTimeout(() => control.classList.remove('visible'), 100);
340
- };
341
- control.onpointerenter = () => {
342
- clearTimeout(hideTimer);
343
- control.classList.add('visible');
344
- };
345
- control.onpointerleave = () => control.classList.remove('visible');
346
- controls.append(control);
347
- const label = edgeLoopLabel(edge);
348
- if (label) {
349
- const badge = document.createElement('span');
350
- badge.className = 'edge-label';
351
- badge.style.left = `${midpoint.x}px`;
352
- badge.style.top = `${midpoint.y - 22}px`;
353
- badge.textContent = label;
354
- 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);
355
479
  }
356
480
  });
357
- for (const loopGroup of draft.loopGroups || []) {
358
- const from = positions.get(loopGroup.decisionNodeId);
359
- const to = positions.get(loopGroup.repeatTargetId);
360
- const bounds = loopBounds(loopGroup);
361
- if (!from || !to || !bounds) continue;
362
- const returnPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
363
- returnPath.setAttribute(
364
- 'd',
365
- `M${from.x + NODE_WIDTH} ${from.y + NODE_PORT_Y} H${bounds.right + 28} V${bounds.top - 18} H${to.x - 28} V${to.y + NODE_PORT_Y} H${to.x}`
366
- );
367
- returnPath.setAttribute('class', 'edge loop-return');
368
- returnPath.setAttribute('marker-end', 'url(#arrow)');
369
- group.append(returnPath);
370
- const label = document.createElement('span');
371
- label.className = 'edge-label loop-label';
372
- label.style.left = `${bounds.right + 28}px`;
373
- label.style.top = `${bounds.top - 18}px`;
374
- label.textContent = loopGroup.repeatLabel;
375
- controls.append(label);
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);
376
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;
377
630
  }
378
631
 
379
632
  function nodeMarkup(node, index) {
380
- const runtimeNode = catalog.live?.nodes?.[node.id];
381
- const lifecycleActivity = activeLifecycleNodeId() === node.id
382
- ? activeLifecycleEvent()?.message
383
- : '';
384
- const outgoing = draft.edges.some((edge) => edge.from === node.id);
385
- const root = rootCandidates().length === 1 && rootCandidates()[0].id === node.id;
633
+ const title = `${stageLabel(node, index)} · ${node.type}`;
386
634
  return `
387
635
  <button class="port port-in" aria-label="Input for ${escapeHtml(node.id)}" tabindex="-1"></button>
388
- <small>${escapeHtml(stageLabel(node, index))} / ${escapeHtml(node.type.toUpperCase())}</small>
389
- <button class="node-title" title="Double-click to edit Display Name">${escapeHtml(displayName(node))}</button>
390
- <span class="technical-id">${escapeHtml(node.id)}</span>
391
- <span class="status">● ${escapeHtml(runtimeNode?.status || 'DRAFT')}</span>
392
- ${runtimeNode?.activity || lifecycleActivity ? `<p class="node-activity">${escapeHtml(runtimeNode?.activity || lifecycleActivity)}</p>` : ''}
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>
393
642
  <button class="port port-out" aria-label="Connect from ${escapeHtml(node.id)}" tabindex="-1"></button>
394
- ${outgoing ? '' : `<button class="output-add" title="Add connected node" aria-label="Add node connected after ${escapeHtml(displayName(node))}">+</button>`}
395
- ${root ? `<div class="execute-pod"><input class="task-input" aria-label="Task for this run" placeholder="Describe this run’s task" value="${escapeHtml(catalog.live?.run?.task || '')}"><button class="execute-trigger">${goal.frozen ? 'Execute' : 'Set Goal'}</button><span class="execute-hint">${goal.frozen ? 'Local runtime only' : 'Freeze Goal first'}</span></div>` : ''}
396
643
  `;
397
644
  }
398
645
 
399
- function activeLifecycleEvent() {
400
- const latest = lifecycleEvents.at(-1) || null;
401
- if (!latest || ['NODE_COMPLETED', 'RUN_COMPLETED'].includes(latest.type)) return null;
402
- return latest;
403
- }
404
-
405
- function activeLifecycleNodeId() {
406
- const event = activeLifecycleEvent();
407
- if (event?.nodeId) return event.nodeId;
408
- if (event?.phase) {
409
- const scopedNode = draft?.nodes.find((node) =>
410
- node.id === event.phase || node.type === event.phase || node.legacyGate === event.phase
411
- );
412
- if (scopedNode) return scopedNode.id;
413
- }
414
- if (event?.phase === 'goal' || event?.type?.startsWith('GOAL_')) {
415
- return draft?.nodes.find((node) => node.type === 'goal-contract')?.id || null;
416
- }
417
- return null;
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
+ };
418
654
  }
419
655
 
420
- function renderGraph() {
656
+ function renderGraph({ live = false } = {}) {
657
+ if (!draft) return;
658
+ hideTooltip();
421
659
  ensurePositions();
422
660
  renderLoopGroups();
423
661
  const container = byId('nodes');
662
+ if (!container) return;
424
663
  container.innerHTML = '';
425
664
  draft.nodes.forEach((node, index) => {
426
665
  const position = positions.get(node.id);
427
- const runtimeNode = catalog.live?.nodes?.[node.id];
666
+ const frame = nodeFrame(node, index);
428
667
  const element = document.createElement('article');
429
668
  element.dataset.nodeId = node.id;
430
- const lifecycleActive = activeLifecycleNodeId() === node.id &&
431
- !['DISCONNECTED', 'UNKNOWN'].includes(agentPresence.status);
432
- element.className = `node ${runtimeNode?.status.toLowerCase() || ''} ${lifecycleActive ? 'agent-active' : ''} ${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');
433
678
  element.style.left = `${position.x}px`;
434
679
  element.style.top = `${position.y}px`;
435
- element.innerHTML = nodeMarkup(node, index);
680
+ element.innerHTML = frame.html;
436
681
  element.addEventListener('pointerdown', beginNodeInteraction);
437
- element.querySelector('.port-out').addEventListener('pointerdown', beginConnection);
438
- element.querySelector('.node-title').addEventListener('dblclick', beginInlineRename);
439
- element.querySelector('.output-add')?.addEventListener('click', openContextualAdd);
440
- element.querySelector('.execute-trigger')?.addEventListener('click', executeFromTrigger);
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);
687
+ element.querySelector('.port-out')?.addEventListener('pointerdown', beginConnection);
441
688
  container.append(element);
442
689
  });
443
690
  renderEdges();
444
691
  applyViewport();
692
+ if (!live && !hasFitted) hasFitted = fitView();
693
+ if (!live && panelNodeId) renderNodePanel();
445
694
  }
446
695
 
447
- function updateRuntimePresentation() {
448
- if (!draft) return;
449
- for (const element of document.querySelectorAll('.node')) {
450
- const nodeId = element.dataset.nodeId;
451
- const runtimeNode = catalog.live?.nodes?.[nodeId];
452
- element.classList.remove('running', 'passed', 'failed', 'blocked', 'ready', 'pending', 'skipped', 'agent-active', 'agent-idle', 'agent-disconnected');
453
- if (runtimeNode?.status) element.classList.add(runtimeNode.status.toLowerCase());
454
- if (activeLifecycleNodeId() === nodeId) {
455
- if (agentPresence.status === 'WORKING') element.classList.add('agent-active');
456
- if (agentPresence.status === 'IDLE') element.classList.add('agent-idle');
457
- if (agentPresence.status === 'DISCONNECTED') element.classList.add('agent-disconnected');
458
- }
459
- element.querySelector('.status').textContent = `● ${runtimeNode?.status || 'DRAFT'}`;
460
- const existingActivity = element.querySelector('.node-activity');
461
- const lifecycleActivity = activeLifecycleNodeId() === nodeId
462
- ? activeLifecycleEvent()?.message
463
- : '';
464
- const activity = runtimeNode?.activity || lifecycleActivity;
465
- if (activity) {
466
- if (existingActivity) existingActivity.textContent = activity;
467
- else element.querySelector('.status').insertAdjacentHTML('afterend', `<p class="node-activity">${escapeHtml(activity)}</p>`);
468
- } else {
469
- existingActivity?.remove();
470
- }
471
- }
472
- renderLoopGroups();
473
- renderEdges();
696
+ function nodeElements() {
697
+ return Array.from(byId('nodes')?.children || []);
474
698
  }
475
699
 
476
700
  function updateSelection() {
477
- document.querySelectorAll('.node').forEach((element) => {
478
- element.classList.toggle('selected', selectedIds.has(element.dataset.nodeId));
479
- });
480
- const actions = byId('selection-actions');
481
- actions.hidden = selectedIds.size < 2;
482
- byId('selection-count').textContent = `${selectedIds.size} nodes`;
483
- const grouped = [...selectedIds].some((nodeId) =>
484
- (draft?.loopGroups || []).some((group) => group.nodeIds.includes(nodeId))
485
- );
486
- byId('create-loop-group').disabled = grouped;
487
- byId('create-loop-group').title = grouped ? 'Ungroup selected steps before creating another Loop Group' : '';
488
- }
489
-
490
- function renderRecipeDetails() {
491
- const existing = recipeSummary();
492
- byId('inspector-label').textContent = 'WORKFLOW';
493
- byId('inspector-title').textContent = draft.id;
494
- byId('inspector-title').contentEditable = 'false';
495
- byId('inspector-title').onkeydown = null;
496
- byId('inspector-title').onblur = null;
497
- byId('details').innerHTML = `
498
- <div class="source-line"><span>${escapeHtml(source.toUpperCase())}</span><span>${draft.nodes.length} NODES</span></div>
499
- <label for="recipe-id">Name</label><input id="recipe-id" value="${escapeHtml(draft.id)}">
500
- <label for="recipe-description">Description</label><textarea id="recipe-description">${escapeHtml(draft.description)}</textarea>
501
- ${existing?.source === 'builtin' ? '<p class="hint">Saving creates a project copy. The built-in remains unchanged.</p>' : ''}
502
- <details>
503
- <summary>Advanced settings</summary>
504
- <div class="settings-body">
505
- <label for="recipe-version">Version</label><input id="recipe-version" type="number" min="1" value="${escapeHtml(draft.version)}">
506
- <label for="recipe-modes">Run modes</label>
507
- <select id="recipe-modes" multiple>
508
- ${['REPORT_ONLY', 'ASSISTED', 'UNATTENDED'].map((mode) => `<option ${draft.compatibleModes.includes(mode) ? 'selected' : ''}>${mode}</option>`).join('')}
509
- </select>
510
- </div>
511
- </details>
512
- <button id="apply-recipe">Apply changes</button>
513
- `;
514
- byId('apply-recipe').onclick = applyRecipeDetails;
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
+ }
515
708
  }
516
709
 
517
710
  function selectNode(nodeId, { additive = false } = {}) {
518
- const node = draft.nodes.find((candidate) => candidate.id === nodeId);
519
- if (!node) return;
520
711
  if (additive) {
521
712
  if (selectedIds.has(nodeId)) selectedIds.delete(nodeId);
522
713
  else selectedIds.add(nodeId);
523
714
  } else {
524
715
  selectedIds = new Set([nodeId]);
525
716
  }
526
- selectedEdgeId = null;
527
717
  selectedId = nodeId;
718
+ selectedEdgeId = null;
528
719
  updateSelection();
529
- const runtimeNode = catalog.live?.nodes?.[nodeId];
530
- byId('inspector-label').textContent = 'NODE';
531
- byId('inspector-title').textContent = displayName(node);
532
- byId('inspector-title').contentEditable = 'true';
533
- byId('inspector-title').title = 'Edit Display Name';
534
- byId('inspector-title').onkeydown = (event) => {
535
- if (event.key === 'Enter') {
536
- event.preventDefault();
537
- event.currentTarget.blur();
538
- } else if (event.key === 'Escape') {
539
- event.currentTarget.textContent = displayName(node);
540
- event.currentTarget.blur();
541
- }
542
- };
543
- byId('inspector-title').onblur = (event) => applyDisplayName(node, event.currentTarget.textContent);
544
- byId('inspector-panel').classList.add('open');
545
- byId('details').innerHTML = `
546
- <div class="source-line"><span>${escapeHtml(node.type.toUpperCase())}</span><span>${escapeHtml(runtimeNode?.status || 'DRAFT')}</span></div>
547
- <div id="name-validation" class="validation-message" aria-live="polite"></div>
548
- <label for="node-id">Technical ID</label><input id="node-id" value="${escapeHtml(node.id)}" disabled>
549
- ${node.type === 'delivery' ? deliveryAdapterControls() : ''}
550
- <details>
551
- <summary>Settings</summary>
552
- <div class="settings-body">
553
- <label>Type</label><input value="${escapeHtml(node.type)}" disabled>
554
- <label for="node-dependencies">Inputs</label>
555
- <input id="node-dependencies" value="${escapeHtml((node.dependsOn || []).join(', '))}" placeholder="Connect nodes on the canvas">
556
- ${node.type === 'agent' ? `
557
- <label for="node-extra">Role</label><input id="node-extra" value="${escapeHtml(node.role || '')}">
558
- ${node.prompt != null ? customAgentFields(node) : ''}
559
- <label for="node-tokens">Token limit</label><input id="node-tokens" type="number" min="1" value="${escapeHtml(node.context?.maxTokens || '')}">
560
- ` : node.type === 'approval' ? `
561
- <label for="node-extra">Approval message</label><textarea id="node-extra">${escapeHtml(node.message || '')}</textarea>
562
- ` : node.type === 'condition' ? `
563
- <label for="condition-field">Field</label>
564
- <select id="condition-field">${['run.mode', 'run.state', 'run.iteration', 'run.task'].map((field) => `<option ${node.expression?.field === field ? 'selected' : ''}>${field}</option>`).join('')}</select>
565
- <label for="condition-operator">Rule</label>
566
- <select id="condition-operator">${['equals', 'notEquals', 'contains', 'exists', 'isEmpty', 'greaterThan', 'lessThan'].map((operator) => `<option ${node.expression?.operator === operator ? 'selected' : ''}>${operator}</option>`).join('')}</select>
567
- <label for="condition-value">Value</label><input id="condition-value" value="${escapeHtml(node.expression?.value ?? '')}">
568
- ` : ''}
569
- </div>
570
- </details>
571
- <div class="button-row"><button id="apply-node">Apply</button>${catalog.nodeTypes.find((type) => type.type === node.type)?.builtIn ? '' : '<button id="duplicate-node">Duplicate</button>'}<button id="delete-node" class="danger">Delete</button></div>
572
- ${runtimeControls(node, runtimeNode)}
573
- `;
574
- byId('apply-node').onclick = applyNodeDetails;
575
- if (byId('duplicate-node')) byId('duplicate-node').onclick = duplicateSelectedNode;
576
- byId('delete-node').onclick = deleteSelectedNode;
577
- if (byId('select-adapter')) byId('select-adapter').onclick = selectDeliveryAdapter;
578
- if (byId('generate-adapter')) byId('generate-adapter').onclick = copyAdapterBuilderPrompt;
579
- bindRuntimeControls(node);
580
- }
581
-
582
- function customAgentFields(node) {
583
- return `
584
- <label for="custom-node-prompt">Prompt</label><textarea id="custom-node-prompt">${escapeHtml(node.prompt || '')}</textarea>
585
- <label for="custom-node-capabilities">Capabilities</label><input id="custom-node-capabilities" value="${escapeHtml((node.capabilityRefs || []).join(', '))}">
586
- <label for="custom-node-mcp">MCP references</label><input id="custom-node-mcp" value="${escapeHtml((node.mcpRefs || []).join(', '))}">
587
- <label for="custom-node-inputs">Input artifacts</label><input id="custom-node-inputs" value="${escapeHtml((node.inputArtifacts || []).join(', '))}">
588
- <label for="custom-node-output">Output artifact</label><input id="custom-node-output" value="${escapeHtml(node.outputArtifacts?.[0]?.artifact || '')}">
589
- <label for="custom-node-schema">Output schema</label><input id="custom-node-schema" value="${escapeHtml(node.outputArtifacts?.[0]?.schema || 'schemas/report.schema.json')}">
590
- <label for="custom-node-timeout">Timeout (sec)</label><input id="custom-node-timeout" type="number" min="1" value="${escapeHtml(Math.round((node.timeoutMs || 900000) / 1000))}">
591
- <label for="custom-node-retries">Maximum attempts</label><input id="custom-node-retries" type="number" min="1" value="${escapeHtml(node.retry?.maxAttempts ?? 2)}">
592
- `;
593
- }
594
-
595
- function applyDisplayName(node, value) {
596
- const error = validDisplayName(value);
597
- const message = byId('name-validation');
598
- if (error) {
599
- if (message) message.textContent = error;
600
- byId('inspector-title').textContent = displayName(node);
601
- return false;
602
- }
603
- const next = value.trim();
604
- if (next === displayName(node)) return true;
605
- node.displayName = next;
606
- captureHistory();
607
- renderGraph();
608
- selectNode(node.id);
609
- return true;
610
- }
611
-
612
- function beginInlineRename(event) {
613
- event.preventDefault();
614
- event.stopPropagation();
615
- const node = draft.nodes.find((candidate) => candidate.id === event.currentTarget.closest('.node').dataset.nodeId);
616
- const input = document.createElement('input');
617
- input.className = 'inline-rename';
618
- input.maxLength = DISPLAY_NAME_MAX;
619
- input.value = displayName(node);
620
- event.currentTarget.replaceWith(input);
621
- input.focus();
622
- input.select();
623
- let saved = false;
624
- const finish = () => {
625
- if (saved) return;
626
- saved = true;
627
- const error = validDisplayName(input.value);
628
- if (error) notify(error);
629
- else if (input.value.trim() !== displayName(node)) {
630
- node.displayName = input.value.trim();
631
- captureHistory();
632
- }
633
- renderGraph();
634
- selectNode(node.id);
635
- };
636
- input.onkeydown = (keyEvent) => {
637
- if (keyEvent.key === 'Enter') input.blur();
638
- if (keyEvent.key === 'Escape') {
639
- input.value = displayName(node);
640
- input.blur();
641
- }
642
- };
643
- input.onblur = finish;
644
- }
645
-
646
- function deliveryAdapterControls() {
647
- const current = catalog.adapters.current;
648
- const options = [...catalog.adapters.types];
649
- if (current && !options.includes(current)) options.push(current);
650
- return `
651
- <section class="adapter-controls">
652
- <label for="delivery-adapter">Delivery adapter</label>
653
- <select id="delivery-adapter">
654
- ${options.map((type) => `<option ${type === (current || catalog.adapters.recommended) ? 'selected' : ''}>${escapeHtml(type)}</option>`).join('')}
655
- </select>
656
- <p class="hint">${current
657
- ? `${escapeHtml(current)} is active for this project.`
658
- : `Recommended: ${escapeHtml(catalog.adapters.recommended)}.`}</p>
659
- <div class="button-row"><button id="select-adapter">Use adapter</button><button id="generate-adapter">Create custom</button></div>
660
- </section>
661
- `;
662
- }
663
-
664
- async function selectDeliveryAdapter() {
665
- const type = byId('delivery-adapter').value;
666
- if (!catalog.adapters.types.includes(type)) {
667
- return notify('Custom adapters are changed through the guarded AI adapter builder.');
668
- }
669
- try {
670
- await api('/api/adapter/select', { method: 'POST', body: JSON.stringify({ type }) });
671
- catalog.adapters.current = type;
672
- selectNode(selectedId);
673
- notify(`${type} is now the project Stage 8 adapter.`);
674
- } catch (error) {
675
- notify(error.message);
676
- }
677
- }
678
-
679
- async function copyAdapterBuilderPrompt() {
680
- const prompt = [
681
- 'Use the ai-engineering-loop generate-adapter skill for this repository.',
682
- 'Ask Q1-Q5 before writing. Build a custom Stage 8 delivery adapter only.',
683
- 'Preserve Stages 0-7, require Judge PASS, never store credentials, and use explicit approval for remote side effects.',
684
- 'After validation, write .ai-engineering-loop/adapter.md so Workflow Studio discovers it.'
685
- ].join(' ');
686
- try {
687
- await navigator.clipboard.writeText(prompt);
688
- notify('Guarded custom-adapter prompt copied for your AI agent.');
689
- } catch (error) {
690
- notify(error.message);
691
- }
692
- }
693
-
694
- function runtimeControls(node, runtimeNode) {
695
- if (!catalog.live || !runtimeNode) return '';
696
- const approve = node.type === 'approval' && runtimeNode.status === 'READY' ? '<button id="approve-node">APPROVE</button>' : '';
697
- const retry = ['FAILED', 'RUNNING'].includes(runtimeNode.status) ? '<button id="retry-node">RETRY</button>' : '';
698
- const custom = node.type === 'agent' && node.prompt && ['READY', 'RUNNING'].includes(runtimeNode.status) ? `
699
- <p class="hint">This node is waiting for an external operator. Studio does not execute the agent independently.</p>
700
- <button id="copy-agent-command">Copy command</button>
701
- ${runtimeNode.status === 'READY'
702
- ? '<button id="start-agent-node">Mark running</button>'
703
- : '<label for="agent-evidence">Run-bound evidence JSON path</label><input id="agent-evidence" placeholder=".ai-engineering-loop/runs/…/agent-report.json"><button id="complete-agent-node">Complete with evidence</button>'}
704
- ` : '';
705
- const activity = runtimeNode.status === 'RUNNING'
706
- ? '<label for="runtime-activity">SAFE ACTIVITY UPDATE</label><input id="runtime-activity" maxlength="240"><button id="send-activity">REPORT ACTIVITY</button>'
707
- : '';
708
- return approve || retry || activity || custom
709
- ? `<section class="runtime-controls"><label>RUNTIME CONTROL</label>${custom}${activity}<div class="button-row">${approve}${retry}</div></section>`
710
- : '';
711
- }
712
-
713
- function bindRuntimeControls(node) {
714
- const runId = catalog.live?.run?.runId;
715
- if (byId('approve-node')) byId('approve-node').onclick = () => mutateNode('/api/node/approve', { runId, nodeId: node.id });
716
- if (byId('retry-node')) byId('retry-node').onclick = () => mutateNode('/api/node/retry', { runId, nodeId: node.id });
717
- if (byId('send-activity')) {
718
- byId('send-activity').onclick = () => mutateNode('/api/node/activity', {
719
- runId, nodeId: node.id, message: byId('runtime-activity').value
720
- });
721
- }
722
- if (byId('copy-agent-command')) byId('copy-agent-command').onclick = async () => {
723
- await navigator.clipboard.writeText(`ai-engineering-loop node start ${node.id} --run ${runId}`);
724
- notify('External operator command copied.');
725
- };
726
- if (byId('start-agent-node')) byId('start-agent-node').onclick = () => mutateNode('/api/node/start', { runId, nodeId: node.id });
727
- if (byId('complete-agent-node')) byId('complete-agent-node').onclick = () => mutateNode('/api/node/complete', {
728
- runId,
729
- nodeId: node.id,
730
- artifact: byId('agent-evidence').value.trim()
731
- });
732
- }
733
-
734
- async function mutateNode(endpoint, body) {
735
- try {
736
- await api(endpoint, { method: 'POST', body: JSON.stringify(body) });
737
- await refreshLive();
738
- if (selectedId) selectNode(selectedId);
739
- } catch (error) {
740
- notify(error.message);
741
- }
742
- }
743
-
744
- function applyRecipeDetails() {
745
- draft.id = byId('recipe-id').value.trim();
746
- draft.version = Number(byId('recipe-version').value);
747
- draft.description = byId('recipe-description').value.trim();
748
- draft.compatibleModes = [...byId('recipe-modes').selectedOptions].map((option) => option.value);
749
- captureHistory();
750
- renderGraph();
751
- renderRecipeDetails();
752
- validateDraft();
753
- }
754
-
755
- function applyNodeDetails() {
756
- const node = draft.nodes.find((candidate) => candidate.id === selectedId);
757
- if (!node) return;
758
- if (!applyDisplayName(node, byId('inspector-title').textContent)) return;
759
- const inputs = csv(byId('node-dependencies').value);
760
- draft.edges = draft.edges.filter((edge) => edge.to !== node.id);
761
- inputs.forEach((from, index) => {
762
- if (from !== node.id && draft.nodes.some((candidate) => candidate.id === from)) {
763
- draft.edges.push({ id: uniqueEdgeId(from, node.id), from, to: node.id });
764
- }
765
- });
766
- syncDependencies();
767
- if (node.type === 'agent') {
768
- node.role = byId('node-extra').value.trim();
769
- node.context = { ...(node.context || {}), maxTokens: Number(byId('node-tokens').value) };
770
- if (node.prompt != null) {
771
- node.prompt = byId('custom-node-prompt').value.trim();
772
- node.capabilityRefs = csv(byId('custom-node-capabilities').value);
773
- node.mcpRefs = csv(byId('custom-node-mcp').value);
774
- node.inputArtifacts = csv(byId('custom-node-inputs').value);
775
- node.outputArtifacts = [{
776
- artifact: byId('custom-node-output').value.trim(),
777
- schema: byId('custom-node-schema').value.trim()
778
- }];
779
- node.tokenLimit = Number(byId('node-tokens').value);
780
- node.timeoutMs = Number(byId('custom-node-timeout').value) * 1000;
781
- node.retry = {
782
- maxAttempts: Number(byId('custom-node-retries').value),
783
- backoffMs: node.retry?.backoffMs || 1000
784
- };
785
- }
786
- } else if (node.type === 'approval') {
787
- node.message = byId('node-extra').value.trim();
788
- } else if (node.type === 'condition') {
789
- const field = byId('condition-field').value;
790
- const operator = byId('condition-operator').value;
791
- const rawValue = byId('condition-value').value.trim();
792
- node.expression = { field, operator };
793
- if (!['exists', 'isEmpty'].includes(operator)) {
794
- node.expression.value = field === 'run.iteration' || ['greaterThan', 'lessThan'].includes(operator) ? Number(rawValue) : rawValue;
795
- }
796
- }
797
- captureHistory();
798
- renderGraph();
799
- selectNode(node.id);
800
- validateDraft();
801
- saveLayoutSoon();
802
- }
803
-
804
- function deleteSelectedNode() {
805
- if (!selectedIds.size) return;
806
- const removed = new Set(selectedIds);
807
- const containingGroup = (draft.loopGroups || []).find((group) =>
808
- group.nodeIds.some((nodeId) => removed.has(nodeId))
809
- );
810
- if (containingGroup) {
811
- notify(`Ungroup “${containingGroup.displayName}” before deleting its steps.`);
812
- return;
813
- }
814
- draft.nodes = draft.nodes.filter((node) => !removed.has(node.id));
815
- draft.edges = draft.edges.filter((edge) => !removed.has(edge.from) && !removed.has(edge.to));
816
- syncDependencies();
817
- removed.forEach((id) => positions.delete(id));
818
- selectedId = null;
819
- selectedIds.clear();
820
- captureHistory();
821
- renderGraph();
822
- renderRecipeDetails();
823
- byId('inspector-panel').classList.remove('open');
824
- validateDraft();
825
- saveLayoutSoon();
720
+ renderEdges();
826
721
  }
827
722
 
828
723
  function deleteEdge(id) {
724
+ if (!draft) return;
829
725
  const before = draft.edges.length;
830
726
  draft.edges = draft.edges.filter((edge) => edge.id !== id);
831
727
  if (draft.edges.length === before) return;
@@ -836,103 +732,50 @@ function deleteEdge(id) {
836
732
  validateDraft();
837
733
  }
838
734
 
839
- function uniqueNodeId(type) {
840
- let suffix = draft.nodes.length + 1;
841
- while (draft.nodes.some((node) => node.id === `${type}-${suffix}`)) suffix += 1;
842
- return `${type}-${suffix}`;
843
- }
844
-
845
- function createNode(type, id = uniqueNodeId(type)) {
846
- const label = catalog.nodeTypes.find((candidate) => candidate.type === type)?.label || type.replaceAll('-', ' ');
847
- const node = { id, type, displayName: label, dependsOn: [] };
848
- if (type === 'agent') {
849
- Object.assign(node, {
850
- role: 'analyst',
851
- context: { maxFiles: 10, maxTokens: 4000 },
852
- output: { artifact: `${id}-output`, schema: 'schemas/report.schema.json' }
853
- });
854
- } else if (type === 'approval') {
855
- node.message = 'Approve continuation.';
856
- } else if (type === 'condition') {
857
- node.expression = { field: 'run.mode', operator: 'equals', value: 'ASSISTED' };
858
- }
859
- return node;
860
- }
861
-
862
- function addNode(type, position = worldAtCanvasCenter()) {
863
- const node = createNode(type);
864
- draft.nodes.push(node);
865
- if (pendingConnectionSource) {
866
- draft.edges.push({ id: uniqueEdgeId(pendingConnectionSource, node.id), from: pendingConnectionSource, to: node.id });
867
- syncDependencies();
868
- pendingConnectionSource = null;
869
- }
870
- positions.set(node.id, { x: position.x - NODE_WIDTH / 2, y: position.y - NODE_PORT_Y });
735
+ function addEdge(from, to) {
736
+ if (!draft || !from || !to || from === to) return false;
737
+ if (draft.edges.some((edge) => edge.from === from && edge.to === to)) return false;
738
+ if (transitivelyDependsOn(from, to)) return false;
739
+ if (!draft.nodes.some((node) => node.id === from) || !draft.nodes.some((node) => node.id === to)) return false;
740
+ draft.edges.push({ id: uniqueEdgeId(from, to), from, to });
741
+ syncDependencies();
871
742
  captureHistory();
872
743
  renderGraph();
873
- selectNode(node.id);
874
- byId('library-panel').classList.remove('open');
875
744
  validateDraft();
745
+ return true;
876
746
  }
877
747
 
878
- function duplicateSelectedNode() {
879
- if (!selectedIds.size) return;
880
- const originals = draft.nodes.filter((node) => selectedIds.has(node.id));
881
- const mapping = new Map();
882
- const clones = originals.map((original) => {
883
- const clone = structuredClone(original);
884
- clone.id = uniqueNodeId(original.type);
885
- while (draft.nodes.some((node) => node.id === clone.id) || mapping.has(clone.id)) clone.id = `${clone.id}-copy`;
886
- clone.displayName = `${displayName(original)} copy`;
887
- if (clone.output?.artifact) clone.output.artifact = `${clone.id}-output`;
888
- mapping.set(original.id, clone.id);
889
- const originalPosition = positions.get(original.id);
890
- positions.set(clone.id, { x: originalPosition.x + 36, y: originalPosition.y + 132 });
891
- draft.nodes.push(clone);
892
- return clone;
893
- });
894
- const copiedEdges = draft.edges.filter((edge) => mapping.has(edge.from) && mapping.has(edge.to)).map((edge) => ({
895
- id: uniqueEdgeId(mapping.get(edge.from), mapping.get(edge.to)),
896
- from: mapping.get(edge.from),
897
- to: mapping.get(edge.to)
898
- }));
899
- draft.edges.push(...copiedEdges);
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
+
759
+ function repointEdge(id, from, to) {
760
+ const edge = draft?.edges.find((candidate) => candidate.id === id);
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;
766
+ edge.from = from;
767
+ edge.to = to;
900
768
  syncDependencies();
901
- const cloneIds = new Set(clones.map((node) => node.id));
902
- selectedId = clones.at(-1)?.id;
769
+ selectedEdgeId = id;
903
770
  captureHistory();
904
771
  renderGraph();
905
- if (selectedId) selectNode(selectedId);
906
- selectedIds = cloneIds;
907
- updateSelection();
908
772
  validateDraft();
909
- }
910
-
911
- function openContextualAdd(event) {
912
- event.stopPropagation();
913
- pendingConnectionSource = event.currentTarget.closest('.node').dataset.nodeId;
914
- byId('library-panel').classList.add('open');
915
- }
916
-
917
- function renderPalette() {
918
- byId('palette').innerHTML = catalog.nodeTypes.filter((node) => node.executable).map((node) => `
919
- <button class="palette-item" draggable="true" data-node-type="${escapeHtml(node.type)}">
920
- <b>${escapeHtml(node.label)}</b><small>${escapeHtml(node.category.toUpperCase())}</small>
921
- </button>
922
- `).join('');
923
- document.querySelectorAll('[data-node-type]').forEach((button) => {
924
- button.onclick = () => addNode(button.dataset.nodeType);
925
- button.ondragstart = (event) => {
926
- event.dataTransfer.setData('application/x-ael-node-type', button.dataset.nodeType);
927
- event.dataTransfer.effectAllowed = 'copy';
928
- };
929
- });
773
+ return true;
930
774
  }
931
775
 
932
776
  function beginNodeInteraction(event) {
933
- if (event.button !== 0 || event.target.closest('.port,.output-add,.execute-pod,.node-title,.inline-rename')) return;
777
+ if (event.button !== 0 || event.target.closest?.('.port')) return;
934
778
  event.stopPropagation();
935
- setFollowExecution(false);
936
779
  const element = event.currentTarget;
937
780
  const nodeId = element.dataset.nodeId;
938
781
  if (event.shiftKey) {
@@ -940,6 +783,7 @@ function beginNodeInteraction(event) {
940
783
  return;
941
784
  }
942
785
  if (!selectedIds.has(nodeId)) selectNode(nodeId);
786
+ element.focus?.();
943
787
  if (spacePressed) return beginPan(event);
944
788
  const world = screenToWorld(event.clientX, event.clientY);
945
789
  const position = positions.get(nodeId);
@@ -950,16 +794,16 @@ function beginNodeInteraction(event) {
950
794
  element,
951
795
  offsetX: world.x - position.x,
952
796
  offsetY: world.y - position.y,
953
- origins: new Map([...selectedIds].map((id) => [id, { ...positions.get(id) }]))
797
+ origins: new Map([...selectedIds].map((id) => [id, { ...positions.get(id) }])),
798
+ moved: false
954
799
  };
955
800
  element.classList.add('dragging');
956
- element.setPointerCapture(event.pointerId);
801
+ element.setPointerCapture?.(event.pointerId);
957
802
  }
958
803
 
959
804
  function beginPan(event) {
960
805
  if (event.button !== 0 && event.button !== 1) return;
961
806
  event.preventDefault();
962
- setFollowExecution(false);
963
807
  interaction = {
964
808
  type: 'pan',
965
809
  pointerId: event.pointerId,
@@ -968,43 +812,57 @@ function beginPan(event) {
968
812
  viewportX: viewport.x,
969
813
  viewportY: viewport.y
970
814
  };
971
- byId('canvas').setPointerCapture(event.pointerId);
815
+ byId('canvas').setPointerCapture?.(event.pointerId);
972
816
  }
973
817
 
974
818
  function handlePointerMove(event) {
975
819
  if (connection) {
976
- const from = positions.get(connection.sourceId);
977
- const target = screenToWorld(event.clientX, event.clientY);
978
- const start = { x: from.x + NODE_WIDTH, y: from.y + NODE_PORT_Y };
979
- const bend = Math.max(55, Math.abs(target.x - start.x) * 0.42);
980
- byId('preview-edge').setAttribute('d', `M${start.x} ${start.y} C${start.x + bend} ${start.y},${target.x - bend} ${target.y},${target.x} ${target.y}`);
820
+ const preview = scenePart('.preview-edge');
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;
840
+ }
841
+ preview.style.display = 'block';
842
+ preview.setAttribute('d', curvePath(x1, y1, x2, y2));
981
843
  return;
982
844
  }
983
845
  if (!interaction || interaction.pointerId !== event.pointerId) return;
984
- if (interaction.type === 'node') {
846
+ if (interaction.type === 'minimap') {
847
+ panFromMinimapEvent(event);
848
+ return;
849
+ }
850
+ if (interaction.type === 'node') {
985
851
  const world = screenToWorld(event.clientX, event.clientY);
986
852
  const position = { x: world.x - interaction.offsetX, y: world.y - interaction.offsetY };
987
853
  const origin = interaction.origins.get(interaction.nodeId);
988
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;
989
856
  interaction.origins.forEach((start, id) => {
990
857
  const next = { x: start.x + delta.x, y: start.y + delta.y };
991
858
  positions.set(id, next);
992
- const nodeElement = document.querySelector(`.node[data-node-id="${CSS.escape(id)}"]`);
859
+ const nodeElement = document.querySelector?.(`.node[data-node-id="${CSS.escape(id)}"]`);
993
860
  if (nodeElement) {
994
861
  nodeElement.style.left = `${next.x}px`;
995
862
  nodeElement.style.top = `${next.y}px`;
996
863
  }
997
864
  });
998
865
  renderEdges();
999
- } else if (interaction.type === 'group') {
1000
- const world = screenToWorld(event.clientX, event.clientY);
1001
- const delta = { x: world.x - interaction.start.x, y: world.y - interaction.start.y };
1002
- interaction.origins.forEach((start, id) => {
1003
- positions.set(id, { x: start.x + delta.x, y: start.y + delta.y });
1004
- });
1005
- renderGraph();
1006
- } else if (interaction.type === 'lasso') {
1007
- updateLasso(event);
1008
866
  } else {
1009
867
  viewport.x = interaction.viewportX + event.clientX - interaction.startX;
1010
868
  viewport.y = interaction.viewportY + event.clientY - interaction.startY;
@@ -1015,11 +873,13 @@ function handlePointerMove(event) {
1015
873
  function finishPointer(event) {
1016
874
  if (connection && connection.pointerId === event.pointerId) return finishConnection(event);
1017
875
  if (!interaction || interaction.pointerId !== event.pointerId) return;
1018
- if (interaction.type === 'node' || interaction.type === 'group') {
1019
- interaction.element.classList.remove('dragging');
1020
- captureHistory();
1021
- } else if (interaction.type === 'lasso') finishLasso();
876
+ if (interaction.type === 'node') interaction.element.classList.remove('dragging');
877
+ const moved = interaction.type === 'node' && interaction.moved;
1022
878
  interaction = null;
879
+ if (moved) {
880
+ suppressNodeClick = true;
881
+ setTimeout(() => { suppressNodeClick = false; }, 0);
882
+ }
1023
883
  saveLayoutSoon();
1024
884
  }
1025
885
 
@@ -1028,8 +888,9 @@ function beginConnection(event) {
1028
888
  event.stopPropagation();
1029
889
  const sourceId = event.currentTarget.closest('.node').dataset.nodeId;
1030
890
  connection = { sourceId, pointerId: event.pointerId };
1031
- byId('preview-edge').style.display = 'block';
1032
- event.currentTarget.setPointerCapture(event.pointerId);
891
+ const preview = scenePart('.preview-edge');
892
+ if (preview?.style) preview.style.display = 'block';
893
+ event.currentTarget.setPointerCapture?.(event.pointerId);
1033
894
  }
1034
895
 
1035
896
  function transitivelyDependsOn(nodeId, targetId, seen = new Set()) {
@@ -1040,89 +901,367 @@ function transitivelyDependsOn(nodeId, targetId, seen = new Set()) {
1040
901
  return (node?.dependsOn || []).some((dependencyId) => transitivelyDependsOn(dependencyId, targetId, seen));
1041
902
  }
1042
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
+
1043
910
  function finishConnection(event) {
1044
- const sourceId = connection.sourceId;
911
+ const pending = connection;
1045
912
  connection = null;
1046
- byId('preview-edge').style.display = 'none';
1047
- const targetElement = document.elementFromPoint(event.clientX, event.clientY)?.closest('.node');
1048
- const targetId = targetElement?.dataset.nodeId;
1049
- if (!targetId || targetId === sourceId) return;
1050
- const target = draft.nodes.find((node) => node.id === targetId);
1051
- if (draft.edges.some((edge) => edge.from === sourceId && edge.to === targetId)) return notify('Nodes are already connected.');
1052
- if (transitivelyDependsOn(sourceId, targetId)) return notify('Connection rejected: it would create a cycle.');
1053
- draft.edges.push({ id: uniqueEdgeId(sourceId, targetId), from: sourceId, to: targetId });
1054
- syncDependencies();
1055
- captureHistory();
913
+ const preview = scenePart('.preview-edge');
914
+ if (preview?.style) preview.style.display = 'none';
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.');
942
+ }
943
+
944
+ function zoomAt(nextScale, clientX, clientY) {
945
+ const scale = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, nextScale));
946
+ const pivot = clientX == null ? worldAtCanvasCenter() : screenToWorld(clientX, clientY);
947
+ const rect = byId('canvas').getBoundingClientRect();
948
+ const next = clientX == null
949
+ ? { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }
950
+ : { x: clientX, y: clientY };
951
+ viewport.scale = scale;
952
+ const world = screenToWorld(next.x, next.y);
953
+ viewport.x += (world.x - pivot.x) * scale;
954
+ viewport.y += (world.y - pivot.y) * scale;
955
+ applyViewport();
956
+ saveLayoutSoon();
957
+ }
958
+
959
+ function worldAtCanvasCenter() {
960
+ const rect = byId('canvas').getBoundingClientRect();
961
+ return screenToWorld(rect.left + rect.width / 2, rect.top + rect.height / 2);
962
+ }
963
+
964
+ function handleWheel(event) {
965
+ if (closestReal(event.target, '#node-panel')) return;
966
+ event.preventDefault();
967
+ if (event.ctrlKey) {
968
+ zoomAt(viewport.scale * Math.exp(-event.deltaY * 0.01), event.clientX, event.clientY);
969
+ return;
970
+ }
971
+ zoomAt(viewport.scale * (event.deltaY < 0 ? 1.08 : 0.92), event.clientX, event.clientY);
972
+ }
973
+
974
+ function autoLayout({ record = true } = {}) {
975
+ positions = defaultGraphPositions();
976
+ hasFitted = false;
977
+ renderGraph();
978
+ if (record) captureHistory();
979
+ saveLayoutSoon();
980
+ }
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
+
1015
+ function fitView() {
1016
+ if (!draft?.nodes?.length) return false;
1017
+ ensurePositions();
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;
1027
+ applyViewport();
1028
+ saveLayoutSoon();
1029
+ return true;
1030
+ }
1031
+
1032
+ function scheduleFitView() {
1033
+ clearTimeout(resizeFitTimer);
1034
+ resizeFitTimer = setTimeout(() => {
1035
+ if (draft?.nodes?.length) fitView();
1036
+ }, 150);
1037
+ }
1038
+
1039
+ function captureHistory({ reset = false } = {}) {
1040
+ const snapshot = JSON.stringify({ draft, positions: Object.fromEntries(positions) });
1041
+ if (reset) {
1042
+ history = [snapshot];
1043
+ historyIndex = 0;
1044
+ } else if (history[historyIndex] !== snapshot) {
1045
+ history = history.slice(0, historyIndex + 1);
1046
+ history.push(snapshot);
1047
+ historyIndex = history.length - 1;
1048
+ }
1049
+ renderWiringBar();
1050
+ }
1051
+
1052
+ function restoreHistory(index) {
1053
+ if (index < 0 || index >= history.length) return;
1054
+ historyIndex = index;
1055
+ const snapshot = JSON.parse(history[index]);
1056
+ draft = snapshot.draft;
1057
+ positions = new Map(Object.entries(snapshot.positions));
1058
+ if (!draft.nodes.some((node) => node.id === selectedId)) selectedId = null;
1056
1059
  renderGraph();
1057
- selectNode(targetId);
1058
1060
  validateDraft();
1061
+ saveLayoutSoon();
1062
+ renderWiringBar();
1059
1063
  }
1060
1064
 
1061
- function beginLasso(event) {
1062
- setFollowExecution(false);
1063
- const start = screenToWorld(event.clientX, event.clientY);
1064
- interaction = { type: 'lasso', pointerId: event.pointerId, start, current: start, additive: event.shiftKey };
1065
- const marquee = byId('selection-marquee');
1066
- marquee.style.display = 'block';
1067
- marquee.style.left = `${start.x}px`;
1068
- marquee.style.top = `${start.y}px`;
1069
- marquee.style.width = '0';
1070
- marquee.style.height = '0';
1071
- byId('canvas').setPointerCapture(event.pointerId);
1072
- }
1073
-
1074
- function updateLasso(event) {
1075
- interaction.current = screenToWorld(event.clientX, event.clientY);
1076
- const left = Math.min(interaction.start.x, interaction.current.x);
1077
- const top = Math.min(interaction.start.y, interaction.current.y);
1078
- const right = Math.max(interaction.start.x, interaction.current.x);
1079
- const bottom = Math.max(interaction.start.y, interaction.current.y);
1080
- const marquee = byId('selection-marquee');
1081
- Object.assign(marquee.style, {
1082
- left: `${left}px`, top: `${top}px`, width: `${right - left}px`, height: `${bottom - top}px`
1083
- });
1084
- const next = interaction.additive ? new Set(selectedIds) : new Set();
1085
- positions.forEach((position, id) => {
1086
- if (position.x < right && position.x + NODE_WIDTH > left && position.y < bottom && position.y + 110 > top) next.add(id);
1087
- });
1088
- selectedIds = next;
1089
- selectedId = [...next].at(-1) || null;
1090
- updateSelection();
1065
+ function saveLayoutSoon() {
1066
+ clearTimeout(layoutTimer);
1067
+ if (!loadedRecipeId || draft.id !== loadedRecipeId) return;
1068
+ layoutTimer = setTimeout(async () => {
1069
+ try {
1070
+ await api('/api/layout', {
1071
+ method: 'PUT',
1072
+ body: JSON.stringify({ recipeId: loadedRecipeId, layout: layoutPayload() })
1073
+ });
1074
+ } catch {
1075
+ // Canvas work remains in memory and install still submits the layout.
1076
+ }
1077
+ }, 350);
1091
1078
  }
1092
1079
 
1093
- function finishLasso() {
1094
- byId('selection-marquee').style.display = 'none';
1095
- const finalSelection = new Set(selectedIds);
1096
- if (selectedId) selectNode(selectedId);
1097
- selectedIds = finalSelection;
1098
- updateSelection();
1080
+ function edgeSignature(recipe) {
1081
+ return (recipe?.edges || [])
1082
+ .map((edge) => `${edge.from}->${edge.to}`)
1083
+ .sort()
1084
+ .join('|');
1099
1085
  }
1100
1086
 
1101
- function rootCandidates() {
1102
- if (!draft) return [];
1103
- const incoming = new Set(draft.edges.map((edge) => edge.to));
1104
- return draft.nodes.filter((node) => ROOT_TYPES.has(node.type) || !incoming.has(node.id));
1087
+ function rememberLoadedWiring() {
1088
+ loadedEdges = structuredClone(draft?.edges || []);
1089
+ loadedEdgeSignature = edgeSignature({ edges: loadedEdges });
1105
1090
  }
1106
1091
 
1107
- async function executeFromTrigger(event) {
1108
- event.stopPropagation();
1109
- const candidates = rootCandidates();
1110
- if (candidates.length !== 1) return notify(`Execute requires exactly one trigger/root; found ${candidates.length}.`);
1111
- const task = event.currentTarget.closest('.execute-pod').querySelector('.task-input').value.trim();
1112
- if (task) byId('goal-task').value = task;
1113
- if (!goal.frozen || !activeRunId) {
1114
- byId('goal-dialog').showModal();
1115
- return notify('Save and freeze the Goal Contract before execution.');
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';
1116
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
+
1234
+ async function validateDraft() {
1235
+ const sequence = ++validationSequence;
1236
+ validationState = { status: 'pending', hash: '', issues: [], extraCodes: [] };
1237
+ renderWiringBar();
1117
1238
  try {
1118
- await api(`/api/runs/${encodeURIComponent(activeRunId)}/execute`, {
1239
+ const result = await api('/api/validate', {
1119
1240
  method: 'POST',
1120
- body: '{}'
1241
+ body: JSON.stringify({ recipe: draft, baseRecipeId: loadedRecipeId })
1121
1242
  });
1122
- notify('Local runtime started. External AI dispatch remains disabled.');
1123
- await refreshLive();
1243
+ if (sequence !== validationSequence) return result;
1244
+ const hash = result.plans[0].graphHash;
1245
+ validationState = { status: 'valid', hash, issues: [], extraCodes: [] };
1246
+ clearInvalidEdges();
1247
+ byId('review-data').textContent = JSON.stringify({
1248
+ recipe: draft.id,
1249
+ version: draft.version,
1250
+ modes: result.plans.map((plan) => plan.mode),
1251
+ nodes: draft.nodes.length,
1252
+ graphHashes: result.plans.map((plan) => plan.graphHash)
1253
+ }, null, 2);
1254
+ renderWiringBar();
1255
+ renderEdges();
1256
+ return result;
1124
1257
  } catch (error) {
1125
- notify(error.message);
1258
+ if (sequence !== validationSequence) return null;
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();
1264
+ return null;
1126
1265
  }
1127
1266
  }
1128
1267
 
@@ -1160,14 +1299,14 @@ function validateGoalForm(contract) {
1160
1299
  }
1161
1300
 
1162
1301
  async function ensureStudioRun() {
1163
- if (activeRunId && catalog.live?.run && !['DELIVERED', 'REPORTED', 'ESCALATED'].includes(catalog.live.run.state)) {
1302
+ if (activeRunId && catalog.live?.run && !TERMINAL_RUN_STATES.has(catalog.live.run.state)) {
1164
1303
  return activeRunId;
1165
1304
  }
1166
1305
  const task = byId('goal-task').value.trim();
1167
1306
  const request = {
1168
1307
  task,
1169
- constraints: byId('goal-constraints').value.trim(),
1170
- displayName: byId('goal-run-name').value.trim(),
1308
+ constraints: formField('goal-constraints').value.trim(),
1309
+ displayName: formField('goal-run-name').value.trim(),
1171
1310
  recipeId: loadedRecipeId,
1172
1311
  mode: draft.compatibleModes.includes('ASSISTED') ? 'ASSISTED' : draft.compatibleModes[0]
1173
1312
  };
@@ -1195,7 +1334,8 @@ async function ensureStudioRun() {
1195
1334
  }
1196
1335
  activeRunId = created.run.runId;
1197
1336
  renderHandoffState();
1198
- await refreshLive();
1337
+ await loadLive(activeRunId);
1338
+ await loadRuns();
1199
1339
  return activeRunId;
1200
1340
  }
1201
1341
 
@@ -1211,11 +1351,12 @@ function resolveActiveRunConflict(run) {
1211
1351
  byId('active-run-message').textContent = `${run.displayName || run.runId} · ${run.state}`;
1212
1352
  byId('continue-active-run').onclick = async () => {
1213
1353
  activeRunId = run.runId;
1354
+ selectedCheckoutRun = run.runId;
1355
+ pinnedRunId = run.runId;
1214
1356
  renderHandoffState();
1215
1357
  byId('goal-dialog').close();
1216
- showWorkspace('runs');
1217
- await loadRuns();
1218
- await loadRunDetail(run.runId);
1358
+ showWorkspace('live');
1359
+ await loadLive(run.runId);
1219
1360
  finish('continue');
1220
1361
  dialog.close();
1221
1362
  };
@@ -1282,12 +1423,11 @@ function renderGoalState() {
1282
1423
  state.textContent = goal.frozen
1283
1424
  ? `Frozen · version ${goal.version} · editing locked`
1284
1425
  : `Draft · version ${goal.version} · editing allowed`;
1285
- byId('goal-version').textContent = `V${goal.version}`;
1286
1426
  byId('goal-text').disabled = goal.frozen;
1287
1427
  byId('goal-criteria').disabled = goal.frozen;
1288
1428
  byId('goal-task').disabled = goal.frozen;
1289
- byId('goal-constraints').disabled = goal.frozen;
1290
- byId('goal-run-name').disabled = goal.frozen;
1429
+ formField('goal-constraints').disabled = goal.frozen;
1430
+ formField('goal-run-name').disabled = goal.frozen;
1291
1431
  byId('save-goal').hidden = goal.frozen;
1292
1432
  byId('review-goal').hidden = goal.frozen;
1293
1433
  byId('confirm-freeze').hidden = true;
@@ -1298,7 +1438,7 @@ async function reviewGoal() {
1298
1438
  const contract = await saveGoalFromForm();
1299
1439
  if (!contract) return;
1300
1440
  byId('goal-dialog').showModal();
1301
- byId('goal-dialog').querySelector('.advanced-goal').open = true;
1441
+ byId('goal-advanced').open = true;
1302
1442
  byId('goal-review').hidden = false;
1303
1443
  byId('goal-review').innerHTML = `
1304
1444
  <strong>${escapeHtml(contract.objective)}</strong>
@@ -1345,20 +1485,20 @@ async function freezeGoalFromForm() {
1345
1485
  }
1346
1486
 
1347
1487
  async function unfreezeGoalFromForm() {
1348
- const fields = byId('unfreeze-fields');
1349
- if (fields.hidden) {
1350
- fields.hidden = false;
1351
- byId('unfreeze-reason').focus();
1488
+ const reason = byId('unfreeze-reason');
1489
+ if (reason.hidden) {
1490
+ reason.hidden = false;
1491
+ reason.focus?.();
1352
1492
  return;
1353
1493
  }
1354
1494
  try {
1355
1495
  const result = await api(`/api/runs/${encodeURIComponent(activeRunId)}/goal/unfreeze`, {
1356
1496
  method: 'POST',
1357
- body: JSON.stringify({ actor: 'studio-user', reason: byId('unfreeze-reason').value })
1497
+ body: JSON.stringify({ actor: 'studio-user', reason: reason.value })
1358
1498
  });
1359
1499
  goal.frozen = false;
1360
1500
  goal.version = result.run.goal.version;
1361
- fields.hidden = true;
1501
+ reason.hidden = true;
1362
1502
  renderGoalState();
1363
1503
  renderGraph();
1364
1504
  notify('Goal unfrozen. Previous evidence remains bound to its prior version.');
@@ -1377,156 +1517,66 @@ function syncGoalFromLive() {
1377
1517
  }
1378
1518
  activeRunId = nextRunId;
1379
1519
  renderHandoffState();
1380
- if (!liveGoal) {
1381
- renderGoalState();
1382
- return;
1383
- }
1384
- goal.version = liveGoal.version || 1;
1385
- goal.frozen = liveGoal.frozen === true;
1386
- if (catalog.live.run.task) byId('goal-task').value = catalog.live.run.task;
1387
- if (catalog.live.run.constraints) byId('goal-constraints').value = catalog.live.run.constraints;
1388
- if (catalog.live.run.displayName) byId('goal-run-name').value = catalog.live.run.displayName;
1389
- renderGoalState();
1390
- }
1391
-
1392
- async function refreshGoalDraft(runId) {
1393
- if (!runId || goal.frozen) return;
1394
- const result = await api(`/api/runs/${encodeURIComponent(runId)}/goal`);
1395
- const draftEnvelope = result.draft;
1396
- if (!draftEnvelope || draftEnvelope.metadata.revision === goal.draftRevision) return;
1397
- goal.draftRevision = draftEnvelope.metadata.revision;
1398
- goal.draftHash = draftEnvelope.metadata.contentHash;
1399
- goal.text = draftEnvelope.contract.objective || '';
1400
- goal.criteria = draftEnvelope.contract.acceptanceCriteria || [];
1401
- if (!byId('goal-form').contains(document.activeElement)) {
1402
- byId('goal-text').value = goal.text;
1403
- byId('goal-criteria').value = goal.criteria.map((criterion) => (
1404
- `${criterion.statement} | ${criterion.evidenceRequired} | ${(criterion.failureCases || []).join(' | ')}`
1405
- )).join('\n');
1520
+ if (liveGoal) {
1521
+ goal.version = liveGoal.version || goal.version;
1522
+ goal.frozen = Boolean(liveGoal.frozen);
1406
1523
  }
1407
1524
  renderGoalState();
1408
1525
  }
1409
1526
 
1410
- async function refreshLifecycle(runId) {
1411
- if (!runId) {
1412
- lifecycleStream?.close();
1413
- lifecycleStream = null;
1414
- lifecycleRunId = null;
1415
- lifecycleSequence = 0;
1416
- lifecycleEvents = [];
1417
- agentPresence = { status: 'UNKNOWN', lastHeartbeatAt: null };
1418
- return;
1419
- }
1420
- if (lifecycleRunId !== runId) {
1421
- lifecycleStream?.close();
1422
- lifecycleStream = null;
1423
- lifecycleRunId = runId;
1424
- lifecycleSequence = 0;
1425
- lifecycleEvents = [];
1426
- startLifecycleStream(runId);
1427
- }
1527
+ async function copyAgentHandoff(runId = activeRunId) {
1528
+ const created = runId || await ensureStudioRun();
1529
+ if (!created) return;
1428
1530
  try {
1429
- const result = await api(
1430
- `/api/runs/${encodeURIComponent(runId)}/lifecycle?after=${lifecycleSequence}&limit=100`
1431
- );
1432
- lifecycleEvents = lifecycleEvents.concat(
1433
- result.lifecycle.events.filter((event) => event.sequence > lifecycleSequence)
1434
- ).slice(-100);
1435
- lifecycleSequence = result.lifecycle.nextSequence;
1436
- agentPresence = result.presence;
1437
- } catch {
1438
- agentPresence = { status: 'UNKNOWN', lastHeartbeatAt: null };
1439
- }
1440
- }
1441
-
1442
- function startLifecycleStream(runId) {
1443
- if (!window.EventSource || !runId) return;
1444
- lifecycleStream = new window.EventSource(
1445
- `/api/runs/${encodeURIComponent(runId)}/lifecycle/stream?after=${lifecycleSequence}`
1446
- );
1447
- lifecycleStream.onmessage = (message) => {
1448
- try {
1449
- const result = JSON.parse(message.data);
1450
- lifecycleEvents = lifecycleEvents.concat(
1451
- result.lifecycle.events.filter((event) => event.sequence > lifecycleSequence)
1452
- ).slice(-100);
1453
- lifecycleSequence = Math.max(lifecycleSequence, result.lifecycle.nextSequence);
1454
- agentPresence = result.presence;
1455
- scheduleLiveRender();
1456
- } catch {
1457
- // The regular cursor poll remains the recovery path.
1458
- }
1459
- };
1460
- }
1461
-
1462
- function scheduleLiveRender() {
1463
- if (liveRenderScheduled) return;
1464
- liveRenderScheduled = true;
1465
- const schedule = window.requestAnimationFrame || ((callback) => setTimeout(callback, 16));
1466
- schedule(() => {
1467
- liveRenderScheduled = false;
1468
- renderLive();
1469
- });
1470
- }
1471
-
1472
- function setFollowExecution(enabled) {
1473
- followExecution = enabled;
1474
- const button = byId('follow-execution');
1475
- button.classList.toggle('active', enabled);
1476
- button.setAttribute('aria-pressed', String(enabled));
1477
- button.textContent = enabled ? 'Following' : 'Follow execution';
1478
- if (enabled) {
1479
- lastFollowedNode = null;
1480
- followActiveNode();
1531
+ const result = await api(`/api/runs/${encodeURIComponent(created)}/agent-handoff`);
1532
+ const text = result.handoff?.prompt || result.handoff?.brief || JSON.stringify(result.handoff, null, 2);
1533
+ await navigator.clipboard.writeText(text);
1534
+ handoffCopiedRunId = created;
1535
+ renderHandoffState();
1536
+ notify('Agent handoff copied.');
1537
+ } catch (error) {
1538
+ notify(error.message);
1481
1539
  }
1482
1540
  }
1483
1541
 
1484
- function followActiveNode() {
1485
- const nodeId = activeLifecycleNodeId();
1486
- if (!followExecution || !nodeId || nodeId === lastFollowedNode || interaction) return;
1487
- const position = positions.get(nodeId);
1488
- if (!position) return;
1489
- const canvas = byId('canvas').getBoundingClientRect();
1490
- viewport.x = canvas.width / 2 - (position.x + NODE_WIDTH / 2) * viewport.scale;
1491
- viewport.y = canvas.height / 2 - (position.y + 54) * viewport.scale;
1492
- lastFollowedNode = nodeId;
1493
- applyViewport();
1542
+ function renderHandoffState() {
1543
+ const copied = Boolean(handoffCopiedRunId && handoffCopiedRunId === activeRunId);
1544
+ byId('agent-handoff-state').hidden = !copied;
1545
+ byId('agent-handoff-instructions').textContent = copied
1546
+ ? 'Paste it once into your current AI Agent terminal, then keep Studio open to follow persisted progress.'
1547
+ : '';
1548
+ byId('start-agent').textContent = copied ? 'Copy again' : 'Start with AI Agent';
1494
1549
  }
1495
1550
 
1496
- async function hydrateGoalFromLive() {
1497
- const run = catalog.live?.run;
1498
- const artifactPath = run?.artifacts?.goalContract?.path;
1499
- const key = `${run?.runId || ''}:${run?.goal?.version || 1}:${artifactPath || ''}`;
1500
- if (!artifactPath || hydratedGoalKey === key) return;
1501
- try {
1502
- const result = await api(`/api/runs/${encodeURIComponent(run.runId)}/artifacts?path=${encodeURIComponent(artifactPath)}`);
1503
- const contract = JSON.parse(result.artifact.content);
1504
- byId('goal-text').value = contract.objective || '';
1505
- byId('goal-criteria').value = (contract.acceptanceCriteria || []).map((criterion) => (
1506
- `${criterion.statement} | ${criterion.evidenceRequired} | ${(criterion.failureCases || []).join(' | ')}`
1507
- )).join('\n');
1508
- goal.text = contract.objective || '';
1509
- goal.criteria = contract.acceptanceCriteria || [];
1510
- hydratedGoalKey = key;
1511
- } catch {
1512
- // The Goal remains inspectable through Run History if its bounded artifact cannot be hydrated.
1513
- }
1551
+ function showWorkspace(section) {
1552
+ if (section === 'workflows') section = 'wiring';
1553
+ workspace = section;
1554
+ const live = section === 'live';
1555
+ const showingRuns = section === 'runs';
1556
+ const wiring = section === 'wiring';
1557
+ byId('live-view').hidden = !live;
1558
+ byId('runs-view').hidden = !showingRuns;
1559
+ byId('canvas').hidden = !wiring;
1560
+ byId('show-live').classList.toggle('active', live);
1561
+ byId('show-runs').classList.toggle('active', showingRuns);
1562
+ byId('show-wiring').classList.toggle('active', wiring);
1563
+ byId('show-live').setAttribute('aria-current', live ? 'page' : 'false');
1564
+ byId('show-runs').setAttribute('aria-current', showingRuns ? 'page' : 'false');
1565
+ byId('show-wiring').setAttribute('aria-current', wiring ? 'page' : 'false');
1566
+ if (showingRuns) loadRuns();
1567
+ if (wiring) renderGraph();
1514
1568
  }
1515
1569
 
1516
1570
  async function loadRuns() {
1517
- const query = byId('run-search').value.trim();
1571
+ const query = byId('run-search')?.value.trim() || '';
1518
1572
  try {
1519
1573
  const params = new URLSearchParams();
1520
1574
  if (query) params.set('q', query);
1521
- if (byId('run-status').value) params.set('status', byId('run-status').value);
1522
- if (byId('run-mode').value) params.set('mode', byId('run-mode').value);
1523
- if (byId('run-from').value) params.set('from', `${byId('run-from').value}T00:00:00.000Z`);
1524
- if (byId('run-to').value) params.set('to', `${byId('run-to').value}T23:59:59.999Z`);
1525
1575
  const result = await api(`/api/runs${params.size ? `?${params}` : ''}`);
1526
1576
  runs = result.runs;
1527
1577
  const list = byId('run-list');
1528
1578
  if (!runs.length) {
1529
- list.innerHTML = '<div class="empty-state"><h2>No runs found</h2><p>Create a task from the workflow trigger.</p></div>';
1579
+ list.innerHTML = '<div class="empty-state"><h2>No runs found</h2><p>Create a task from the Goal sheet.</p></div>';
1530
1580
  } else {
1531
1581
  const active = runs.find((run) => !TERMINAL_RUN_STATES.has(run.status));
1532
1582
  const historyRuns = runs.filter((run) => run.runId !== active?.runId);
@@ -1544,7 +1594,12 @@ async function loadRuns() {
1544
1594
  : '<p class="muted run-list-empty">Completed Runs will stay here.</p>'
1545
1595
  ].join('');
1546
1596
  list.querySelectorAll('.run-row').forEach((button) => {
1547
- button.onclick = () => loadRunDetail(button.dataset.runId);
1597
+ button.onclick = () => {
1598
+ pinnedRunId = button.dataset.runId;
1599
+ selectedCheckoutRun = pinnedRunId;
1600
+ showWorkspace('live');
1601
+ loadLive(pinnedRunId);
1602
+ };
1548
1603
  });
1549
1604
  }
1550
1605
  if (result.corrupt.length) {
@@ -1555,617 +1610,469 @@ async function loadRuns() {
1555
1610
  }
1556
1611
  }
1557
1612
 
1558
- function runHistoryMarkup(run) {
1559
- const history = run.history || [];
1560
- if (!history.length) return '<p class="muted">Waiting for the first Run event.</p>';
1561
- return history.map((entry) => `
1562
- <p>
1563
- <time>${escapeHtml(new Date(entry.at).toLocaleString())}</time>
1564
- <span><b>${escapeHtml(entry.to)}</b> · ${escapeHtml(entry.gate || 'run update')}</span>
1565
- </p>
1566
- `).join('');
1613
+ function heartbeatAge(iso) {
1614
+ if (!iso) return 'no heartbeat';
1615
+ const age = Math.max(0, Date.now() - Date.parse(iso));
1616
+ if (!Number.isFinite(age)) return 'no heartbeat';
1617
+ if (age < 2000) return 'just now';
1618
+ if (age < 60000) return `${Math.round(age / 1000)}s ago`;
1619
+ return `${Math.round(age / 60000)}m ago`;
1567
1620
  }
1568
1621
 
1569
- async function loadRunDetail(runId) {
1570
- try {
1571
- selectedCheckoutRun = runId;
1572
- const [result, checkoutResult, interactionResult] = await Promise.all([
1573
- api(`/api/runs/${encodeURIComponent(runId)}`),
1574
- api(`/api/runs/${encodeURIComponent(runId)}/checkout`),
1575
- api(`/api/runs/${encodeURIComponent(runId)}/interactions`)
1576
- ]);
1577
- const run = result.run;
1578
- const checkout = checkoutResult.checkout;
1579
- const maxX = Math.max(...checkout.nodes.map((node) => node.position.x), 0) + NODE_WIDTH + 80;
1580
- const maxY = Math.max(...checkout.nodes.map((node) => node.position.y), 0) + 180;
1581
- const paths = checkout.edges.map((edge) => {
1582
- const from = checkout.nodes.find((node) => node.id === edge.from);
1583
- const to = checkout.nodes.find((node) => node.id === edge.to);
1584
- if (!from || !to) return '';
1585
- const x1 = from.position.x + NODE_WIDTH;
1586
- const y1 = from.position.y + NODE_PORT_Y;
1587
- const x2 = to.position.x;
1588
- const y2 = to.position.y + NODE_PORT_Y;
1589
- const state = ['idle', 'active', 'passed', 'failed', 'skipped', 'waiting'].includes(edge.state)
1590
- ? edge.state
1591
- : 'idle';
1592
- return `<path class="edge-${state}" d="M ${x1} ${y1} C ${x1 + 70} ${y1}, ${x2 - 70} ${y2}, ${x2} ${y2}"></path>`;
1593
- }).join('');
1594
- const checkoutGroups = (checkout.loopGroups || []).map((group) => {
1595
- const members = checkout.nodes.filter((node) => group.nodeIds.includes(node.id));
1596
- if (!members.length) return '';
1597
- const left = Math.min(...members.map((node) => node.position.x)) - 28;
1598
- const top = Math.min(...members.map((node) => node.position.y)) - 36;
1599
- const right = Math.max(...members.map((node) => node.position.x + NODE_WIDTH)) + 28;
1600
- const bottom = Math.max(...members.map((node) => node.position.y + 108)) + 28;
1601
- return `<div class="checkout-loop status-${escapeHtml((group.runtime?.status || 'pending').toLowerCase())}" data-checkout-loop="${escapeHtml(group.id)}" style="left:${left}px;top:${top}px;width:${right - left}px;height:${bottom - top}px"><b>${escapeHtml(group.displayName)}</b><span>Iteration ${escapeHtml(group.runtime?.iteration || 1)} / ${escapeHtml(group.maxIterations)}</span></div>`;
1602
- }).join('');
1603
- const checkoutBody = checkout.workflowBound
1604
- ? `
1605
- <section class="checkout-canvas" style="--checkout-width:${maxX}px;--checkout-height:${maxY}px">
1606
- <svg viewBox="0 0 ${maxX} ${maxY}" aria-hidden="true">${paths}</svg>
1607
- ${checkoutGroups}
1608
- ${checkout.nodes.map((node) => `<button class="checkout-node status-${escapeHtml(node.status.toLowerCase())}" data-checkout-node="${escapeHtml(node.id)}" style="left:${node.position.x}px;top:${node.position.y}px">
1609
- <small>${escapeHtml(node.type)}${node.loopIteration ? ` · LOOP ${escapeHtml(node.loopIteration)}` : ''}</small><strong>${escapeHtml(node.displayName)}</strong><span data-node-status>${escapeHtml(node.status)}</span>
1610
- </button>`).join('')}
1611
- </section>
1612
- <section id="node-io-panel" class="node-io-panel"><div class="empty-state"><h3>Select a node</h3><p>Inspect its real Input, Output, Evidence, and Timeline.</p></div></section>
1613
- `
1614
- : `
1615
- <section class="classic-run">
1616
- <small>CLASSIC RUN · LIVE TRACKING</small>
1617
- <h3>This Run started before automatic workflow binding was available.</h3>
1618
- <p>Goal changes, stage gates, evidence, and Agent questions are still monitored here. New Runs show the full node canvas automatically.</p>
1619
- <div id="classic-run-timeline" class="timeline">${runHistoryMarkup(run)}</div>
1620
- </section>
1621
- `;
1622
- byId('run-detail').innerHTML = `
1623
- <header class="checkout-header">
1624
- <div><button id="checkout-back" class="quiet">← Run History</button><small>READ-ONLY CHECKOUT · <span id="checkout-run-status">${escapeHtml(run.status)}</span></small><h2>${escapeHtml(run.displayName)}</h2><p>${escapeHtml(run.task)}</p></div>
1625
- <div class="checkout-actions"><button id="copy-agent-handoff">Copy for AI Agent</button>${checkout.workflowBound ? '<button id="duplicate-run-workflow" class="primary">Duplicate as Workflow</button>' : ''}</div>
1626
- </header>
1627
- <div class="checkout-meta"><span>${escapeHtml(run.runId)}</span><span id="checkout-goal-state">${run.goalFrozen ? `Goal frozen V${escapeHtml(run.goalVersion)}` : 'Goal draft'}</span><span>${checkout.workflowBound ? 'Actual node states' : 'Live stage history'}</span></div>
1628
- ${checkoutBody}
1629
- <section class="agent-interactions"><header><div><small>LIVE AGENT INTERACTIONS</small><h3>Questions from the Agent</h3></div><span>Updates automatically</span></header><div id="interaction-list"></div></section>
1630
- `;
1631
- renderInteractions(interactionResult.interactions);
1632
- byId('checkout-back').onclick = () => {
1633
- selectedCheckoutRun = null;
1634
- byId('run-detail').innerHTML = '<div class="empty-state"><h2>Select a run</h2><p>Open a read-only checkout to inspect actual node evidence.</p></div>';
1635
- };
1636
- byId('copy-agent-handoff').onclick = () => copyAgentHandoff(runId);
1637
- if (checkout.workflowBound) byId('duplicate-run-workflow').onclick = async () => {
1638
- try {
1639
- const duplicate = await api(`/api/runs/${encodeURIComponent(runId)}/duplicate`, {
1640
- method: 'POST',
1641
- body: JSON.stringify({ recipeId: `${slug(run.displayName)}-copy` })
1642
- });
1643
- draft = normalizeDraftGraph(structuredClone(duplicate.preview.recipe));
1644
- positions = new Map(checkout.nodes.map((node) => [node.id, node.position]));
1645
- loadedRecipeId = null;
1646
- captureHistory({ reset: true });
1647
- renderGraph();
1648
- renderRecipeDetails();
1649
- validateDraft();
1650
- showWorkspace('workflows');
1651
- notify('Run duplicated into a new editable workflow. History was not changed.');
1652
- } catch (error) {
1653
- notify(error.message);
1654
- }
1655
- };
1656
- byId('run-detail').querySelectorAll('[data-checkout-node]').forEach((button) => {
1657
- button.onclick = () => loadNodeIo(runId, button.dataset.checkoutNode);
1658
- });
1659
- } catch (error) {
1660
- byId('run-detail').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1622
+ function currentStageId(live) {
1623
+ const nodes = live?.nodes || {};
1624
+ const running = Object.entries(nodes).find(([, node]) => node?.status === 'RUNNING');
1625
+ if (running) {
1626
+ const type = live.plan?.nodes?.find((node) => node.id === running[0])?.type;
1627
+ const stage = STAGES.find((item) => item.types.includes(type));
1628
+ if (stage) return stage.id;
1661
1629
  }
1630
+ const journey = live?.journey?.current;
1631
+ if (journey) {
1632
+ const match = STAGES.find((item) => item.id === String(journey).toLowerCase()
1633
+ || item.label === String(journey).toLowerCase());
1634
+ if (match) return match.id;
1635
+ }
1636
+ return STAGES[0].id;
1662
1637
  }
1663
1638
 
1664
- function renderArtifactPreview(artifact) {
1665
- if (!artifact) return '<p class="muted">No artifact was recorded for this node.</p>';
1666
- if (artifact.unavailable) return `<p class="validation-message">Artifact unavailable: ${escapeHtml(artifact.code)}</p>`;
1667
- return `<p class="artifact-path">${escapeHtml(artifact.descriptor.path)}</p><button class="artifact-download" data-artifact-download="${escapeHtml(artifact.descriptor.path)}">Download copy</button><pre>${escapeHtml(artifact.preview.content)}</pre>`;
1668
- }
1669
-
1670
- async function loadNodeIo(runId, nodeId) {
1671
- const panel = byId('node-io-panel');
1672
- try {
1673
- const { io } = await api(`/api/runs/${encodeURIComponent(runId)}/nodes/${encodeURIComponent(nodeId)}`);
1674
- const running = io.node.status === 'RUNNING';
1675
- const interactionEmpty = io.agentInteractionsAvailable === false
1676
- ? 'Agent Interaction is temporarily unavailable. Other node evidence remains valid.'
1677
- : 'No Agent Interaction was recorded for this Run.';
1678
- panel.innerHTML = `
1679
- <header class="node-io-head"><div><small>NODE INSPECTOR · ${escapeHtml(io.node.status)}</small><h3>${escapeHtml(io.node.displayName)}</h3></div><p class="mono">Duration: ${io.durationMs == null ? 'Not available' : `${Number(io.durationMs)} ms`} · Loop Iteration: ${io.loopIteration == null ? 'Not available' : escapeHtml(String(io.loopIteration))}</p></header>
1680
- <nav class="io-tabs" role="tablist" aria-label="Node details">
1681
- ${['Input', 'Live Activity', 'Output', 'Evidence', 'Timeline'].map((label, index) => `<button class="io-tab" role="tab" aria-selected="${index === 0}" data-io-tab="${slug(label)}">${label}</button>`).join('')}
1682
- </nav>
1683
- <div class="node-data-grid">
1684
- <section class="io-pane active" data-io-pane="input"><h4>Input</h4>${io.input.task ? `<p><b>Task</b><br>${escapeHtml(io.input.task)}</p>` : ''}${io.input.constraints ? `<p><b>Constraints</b><br>${escapeHtml(io.input.constraints)}</p>` : ''}${io.input.dependencies.length ? io.input.dependencies.map((dependency) => `<p><b>${escapeHtml(dependency.nodeId)}</b> · ${escapeHtml(dependency.status)}</p>${renderArtifactPreview(dependency.artifact)}`).join('') : '<p class="muted">Root input from this Run.</p>'}</section>
1685
- <section class="io-pane" data-io-pane="live-activity"><h4>Live Activity</h4><p class="muted">Interaction scope: ${escapeHtml(io.agentInteractionScope || 'RUN')} — questions and answers belong to the whole Run, not only this node.</p><p class="node-progress">${running ? 'In progress · waiting for persisted output' : escapeHtml(io.node.status)}</p><div class="timeline">${io.agentInteractions.map((event) => `<p><time>${escapeHtml(event.at)}</time><strong>${escapeHtml(event.type)}</strong> ${escapeHtml(String(event.message ?? ''))}</p>`).join('') || `<p class="muted">${escapeHtml(interactionEmpty)}</p>`}</div></section>
1686
- <section class="io-pane" data-io-pane="output"><h4>Output</h4><p><b>${running ? 'In progress' : escapeHtml(io.output.status)}</b>${io.output.reason ? ` · ${escapeHtml(io.output.reason)}` : ''}</p>${running ? '<p class="muted">Output will appear after the Agent records a terminal node event.</p>' : renderArtifactPreview(io.output.artifact)}</section>
1687
- <section class="io-pane" data-io-pane="evidence"><h4>Evidence</h4>${renderArtifactPreview(io.evidence)}</section>
1688
- <section class="io-pane" data-io-pane="timeline"><h4>Timeline</h4><div class="timeline">${io.timeline.map((event) => `<p><time>${escapeHtml(event.at)}</time><strong>${escapeHtml(event.type)}</strong></p>`).join('') || '<p class="muted">No node events yet.</p>'}</div></section>
1689
- </div>`;
1690
- panel.querySelectorAll('[data-io-tab]').forEach((button) => {
1691
- button.onclick = () => {
1692
- panel.querySelectorAll('[data-io-tab]').forEach((tab) => {
1693
- tab.setAttribute('aria-selected', String(tab === button));
1694
- });
1695
- panel.querySelectorAll('[data-io-pane]').forEach((pane) => {
1696
- pane.classList.toggle('active', pane.dataset.ioPane === button.dataset.ioTab);
1697
- });
1698
- };
1699
- });
1700
- panel.querySelectorAll('[data-artifact-download]').forEach((button) => {
1701
- button.onclick = async () => {
1702
- try {
1703
- const result = await api(`/api/runs/${encodeURIComponent(runId)}/artifacts?path=${encodeURIComponent(button.dataset.artifactDownload)}`);
1704
- const blob = new Blob([result.artifact.content], { type: 'text/plain' });
1705
- const link = document.createElement('a');
1706
- link.href = URL.createObjectURL(blob);
1707
- link.download = button.dataset.artifactDownload.split('/').at(-1);
1708
- link.click();
1709
- URL.revokeObjectURL(link.href);
1710
- } catch (error) {
1711
- notify(error.message);
1712
- }
1713
- };
1714
- });
1715
- } catch (error) {
1716
- panel.innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1717
- }
1718
- }
1719
-
1720
- function renderInteractions(result) {
1721
- const target = byId('interaction-list');
1722
- if (!target) return;
1723
- target.innerHTML = result.questions.length ? result.questions.map((question) => `
1724
- <article class="agent-question ${question.answer ? 'answered' : 'pending'}">
1725
- <small>Q${escapeHtml(question.number)} · ${escapeHtml(question.actor)}</small>
1726
- <p>${escapeHtml(question.message)}</p>
1727
- ${question.answer ? `<div class="agent-answer"><b>Answer</b><p>${escapeHtml(question.answer.message)}</p></div>` : `<form data-answer="${escapeHtml(question.questionId)}"><textarea maxlength="8000" required placeholder="Answer so the Agent can continue…"></textarea><button class="primary">Send answer</button></form>`}
1728
- </article>
1729
- `).join('') : '<p class="muted">No questions yet. The Agent can post Q1, Q2, Q3 from the Run-bound CLI.</p>';
1730
- target.querySelectorAll('[data-answer]').forEach((form) => {
1731
- form.onsubmit = async (event) => {
1732
- event.preventDefault();
1733
- try {
1734
- await api(`/api/runs/${encodeURIComponent(selectedCheckoutRun)}/questions/${encodeURIComponent(form.dataset.answer)}/answer`, {
1735
- method: 'POST',
1736
- body: JSON.stringify({ message: form.querySelector('textarea').value, actor: 'studio-user' })
1737
- });
1738
- await refreshCheckoutInteractions();
1739
- } catch (error) {
1740
- notify(error.message);
1741
- }
1742
- };
1639
+ function scheduleLiveRender() {
1640
+ if (liveRenderScheduled) return;
1641
+ liveRenderScheduled = true;
1642
+ const schedule = typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function'
1643
+ ? window.requestAnimationFrame.bind(window)
1644
+ : (callback) => setTimeout(callback, 16);
1645
+ schedule(() => {
1646
+ liveRenderScheduled = false;
1647
+ renderLive();
1648
+ refreshWiringLive();
1743
1649
  });
1744
1650
  }
1745
1651
 
1746
- async function refreshCheckoutInteractions() {
1747
- if (!selectedCheckoutRun || !byId('interaction-list')) return;
1748
- try {
1749
- const result = await api(`/api/runs/${encodeURIComponent(selectedCheckoutRun)}/interactions`);
1750
- renderInteractions(result.interactions);
1751
- } catch {
1752
- // Corrupt or unavailable Run data is isolated and does not affect another Run.
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);
1753
1706
  }
1707
+ return Math.max(0, end - start);
1754
1708
  }
1755
1709
 
1756
- async function refreshSelectedCheckout() {
1757
- const runId = selectedCheckoutRun;
1758
- if (!runId || !byId('checkout-run-status')) return;
1759
- try {
1760
- const [detail, checkoutResult] = await Promise.all([
1761
- api(`/api/runs/${encodeURIComponent(runId)}`),
1762
- api(`/api/runs/${encodeURIComponent(runId)}/checkout`)
1763
- ]);
1764
- if (selectedCheckoutRun !== runId) return;
1765
- const run = detail.run;
1766
- const checkout = checkoutResult.checkout;
1767
- byId('checkout-run-status').textContent = run.status;
1768
- byId('checkout-goal-state').textContent = run.goalFrozen
1769
- ? `Goal frozen V${run.goalVersion}`
1770
- : 'Goal draft';
1771
- if (!checkout.workflowBound) {
1772
- const timeline = byId('classic-run-timeline');
1773
- if (timeline) timeline.innerHTML = runHistoryMarkup(run);
1774
- return;
1775
- }
1776
- for (const node of checkout.nodes) {
1777
- const element = document.querySelector(`[data-checkout-node="${CSS.escape(node.id)}"]`);
1778
- if (!element) continue;
1779
- for (const status of ['pending', 'ready', 'running', 'passed', 'failed', 'skipped', 'blocked']) {
1780
- element.classList.remove(`status-${status}`);
1781
- }
1782
- element.classList.add(`status-${node.status.toLowerCase()}`);
1783
- const status = element.querySelector('[data-node-status]');
1784
- if (status) status.textContent = node.status;
1785
- }
1786
- for (const group of checkout.loopGroups || []) {
1787
- const element = document.querySelector(`[data-checkout-loop="${CSS.escape(group.id)}"]`);
1788
- if (!element) continue;
1789
- const counter = element.querySelector('span');
1790
- if (counter) counter.textContent = `Iteration ${group.runtime?.iteration || 1} / ${group.maxIterations}`;
1791
- }
1792
- } catch {
1793
- // Keep the last valid checkout visible during a transient refresh failure.
1794
- }
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`;
1795
1716
  }
1796
1717
 
1797
- async function copyAgentHandoff(runId = activeRunId) {
1798
- try {
1799
- const targetRunId = runId || await ensureStudioRun();
1800
- if (!targetRunId) return;
1801
- const result = await api(`/api/runs/${encodeURIComponent(targetRunId)}/agent-handoff`);
1802
- await navigator.clipboard.writeText(result.handoff.prompt);
1803
- handoffCopiedRunId = targetRunId;
1804
- renderHandoffState();
1805
- notify('Run-bound prompt copied. Paste it into your AI coding Agent.');
1806
- } catch (error) {
1807
- byId('goal-validation').textContent = error.message;
1808
- }
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 ?? '—'}`;
1809
1722
  }
1810
1723
 
1811
- function renderHandoffState() {
1812
- const copied = Boolean(handoffCopiedRunId && handoffCopiedRunId === activeRunId);
1813
- byId('agent-handoff-state').hidden = !copied;
1814
- byId('agent-handoff-instructions').textContent = copied
1815
- ? 'Paste it once into your current AI Agent terminal, then keep Studio open to follow persisted progress.'
1816
- : '';
1817
- byId('start-agent').textContent = copied ? 'Copy again' : 'Start with AI Agent';
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`;
1818
1729
  }
1819
1730
 
1820
- function showWorkspace(section) {
1821
- const showingRuns = section === 'runs';
1822
- byId('runs-view').hidden = !showingRuns;
1823
- byId('canvas').hidden = showingRuns;
1824
- byId('workflow-context').hidden = showingRuns;
1825
- byId('review').hidden = showingRuns;
1826
- byId('show-runs').classList.toggle('active', showingRuns);
1827
- byId('show-runs').setAttribute('aria-current', showingRuns ? 'page' : 'false');
1828
- byId('show-workflows').classList.toggle('active', !showingRuns);
1829
- byId('show-workflows').setAttribute('aria-current', showingRuns ? 'false' : 'page');
1830
- if (showingRuns) loadRuns();
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';
1831
1737
  }
1832
1738
 
1833
- async function previewImport() {
1834
- try {
1835
- const importedRecipe = JSON.parse(byId('import-source').value);
1836
- const result = await api('/api/import/preview', {
1837
- method: 'POST',
1838
- body: JSON.stringify({ existingRecipe: draft, importedRecipe, operation: 'merge' })
1839
- });
1840
- pendingImport = { importedRecipe, mergePlan: result.plan };
1841
- byId('import-preview').innerHTML = `
1842
- <strong>${escapeHtml(importedRecipe.id || 'Imported workflow')}</strong>
1843
- <p>${escapeHtml(importedRecipe.nodes?.length || 0)} nodes · ${escapeHtml(importedRecipe.edges?.length || 0)} explicit Edges</p>
1844
- <p>${Object.values(result.plan.nodeIdMap).filter((id, index) => id !== Object.keys(result.plan.nodeIdMap)[index]).length} node ID conflict(s) will be renamed.</p>
1845
- `;
1846
- byId('import-choices').hidden = false;
1847
- } catch (error) {
1848
- pendingImport = null;
1849
- byId('import-choices').hidden = true;
1850
- byId('import-preview').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1851
- }
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);
1852
1744
  }
1853
1745
 
1854
- async function applyImport(operation) {
1855
- if (!pendingImport) return;
1856
- try {
1857
- const plan = operation === 'merge'
1858
- ? pendingImport.mergePlan
1859
- : { operation: 'replace', nodeIdMap: {}, edgeIdMap: {} };
1860
- const result = await api('/api/import/apply', {
1861
- method: 'POST',
1862
- body: JSON.stringify({
1863
- existingRecipe: draft,
1864
- importedRecipe: pendingImport.importedRecipe,
1865
- plan
1866
- })
1867
- });
1868
- draft = normalizeDraftGraph(structuredClone(result.recipe));
1869
- positions = new Map();
1870
- ensurePositions();
1871
- selectedIds.clear();
1872
- selectedId = null;
1873
- captureHistory();
1874
- renderGraph();
1875
- renderRecipeDetails();
1876
- validateDraft();
1877
- byId('import-dialog').close();
1878
- notify(`${operation === 'merge' ? 'Merged' : 'Replaced'} canvas from validated JSON.`);
1879
- } catch (error) {
1880
- byId('import-preview').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
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;
1881
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 });
1882
1776
  }
1883
1777
 
1884
- function exportWorkflowJson() {
1885
- const blob = new Blob([`${JSON.stringify(authoringRecipe(), null, 2)}\n`], { type: 'application/json' });
1886
- const link = document.createElement('a');
1887
- link.href = URL.createObjectURL(blob);
1888
- link.download = `${draft.id}.workflow.json`;
1889
- link.click();
1890
- URL.revokeObjectURL(link.href);
1778
+ function renderLive() {
1779
+ renderRunSummary();
1780
+ const live = catalog.live;
1781
+ const summary = byId('run-summary');
1782
+ const rail = byId('stage-rail');
1783
+ const journey = byId('run-journey');
1784
+ const meta = byId('live-view')?.querySelector?.('.live-meta');
1785
+ const banner = byId('live-view')?.querySelector?.('.pending-banner');
1786
+ if (!live) {
1787
+ if (summary) summary.textContent = 'No active run';
1788
+ if (rail) {
1789
+ rail.innerHTML = STAGES.map((stage) => `<li class="pending">${escapeHtml(stage.label)}</li>`).join('');
1790
+ }
1791
+ if (meta) meta.innerHTML = '';
1792
+ if (banner) {
1793
+ banner.hidden = true;
1794
+ banner.innerHTML = '';
1795
+ }
1796
+ if (journey) journey.innerHTML = '';
1797
+ return;
1798
+ }
1799
+ const stageId = currentStageId(live);
1800
+ const run = live.run || {};
1801
+ const presence = live.presence || agentPresence;
1802
+ if (summary) {
1803
+ summary.textContent = `${run.displayName || run.runId || 'run'} · ${run.state || ''} · ${heartbeatAge(presence.lastHeartbeatAt)}`;
1804
+ }
1805
+ if (rail) {
1806
+ rail.innerHTML = STAGES.map((stage) => {
1807
+ const current = stage.id === stageId;
1808
+ return `<li class="${current ? 'active' : 'pending'}">${escapeHtml(stage.label)}</li>`;
1809
+ }).join('');
1810
+ }
1811
+ const artifacts = live.artifacts || liveArtifacts;
1812
+ const guard = artifacts['artifact.guard'] || {};
1813
+ const drift = artifacts['artifact.drift'] || {};
1814
+ const receipt = artifacts['artifact.receipt'] || {};
1815
+ if (meta) {
1816
+ meta.innerHTML = `
1817
+ <span>${escapeHtml(run.tier?.current || run.mode || '')}</span>
1818
+ <span>iter ${escapeHtml(String(run.iteration ?? '—'))}</span>
1819
+ <span>${escapeHtml(String(live.budget?.spentThisRun ?? 0))} / ${escapeHtml(String(live.budget?.perRunTokenLimit ?? 0))} tokens</span>
1820
+ <span class="chip">${escapeHtml(String(guard.warn || 0))} warn · ${escapeHtml(String(guard.block || 0))} block</span>
1821
+ <span class="chip">drift ${escapeHtml(String(drift.outOfMapCount || 0))}</span>
1822
+ <span class="chip">${receipt.verified ? 'receipt ok' : 'receipt pending'}</span>
1823
+ `;
1824
+ }
1825
+ const pending = live.interactions?.pending || [];
1826
+ if (banner) {
1827
+ banner.hidden = pending.length === 0;
1828
+ banner.innerHTML = pending.map((question) =>
1829
+ `<p><strong>Q${escapeHtml(String(question.number))}</strong> ${escapeHtml(question.message)}</p>`
1830
+ ).join('');
1831
+ }
1832
+ const journeyStatuses = new Set(['pending', 'active', 'complete']);
1833
+ const degradedSources = live.journey?.degradedSources || [];
1834
+ const timeline = (live.journey?.steps || []).map((step) => {
1835
+ const status = String(step?.status || '').toLowerCase();
1836
+ const safeStatus = journeyStatuses.has(status) ? status : 'unknown';
1837
+ const label = String(step?.id || '').replaceAll('_', ' ');
1838
+ const suffix = safeStatus === 'unknown' ? ' (status unavailable)' : '';
1839
+ const blocked = step?.blocked
1840
+ ? (live.journey?.pendingQuestions == null
1841
+ ? ' · unanswered count unavailable'
1842
+ : ` · ${Number(live.journey.pendingQuestions)} unanswered`)
1843
+ : '';
1844
+ return `<li class="${safeStatus}">${escapeHtml(label + suffix + blocked)}</li>`;
1845
+ }).join('');
1846
+ const eventsHtml = (lifecycleEvents.slice(-8).reverse().map((event) =>
1847
+ `<li class="event">${escapeHtml(String(event.at || '').slice(11, 19))} · ${escapeHtml(event.type)} · ${escapeHtml(event.message || '')}</li>`
1848
+ ).join(''));
1849
+ if (journey) {
1850
+ journey.innerHTML = timeline + eventsHtml + (degradedSources.length
1851
+ ? `<li class="unknown">${escapeHtml(`${degradedSources.join(' and ')} unavailable — journey may be incomplete`)}</li>`
1852
+ : '');
1853
+ }
1891
1854
  }
1892
1855
 
1893
- function createCustomAgentFromForm(event) {
1894
- event.preventDefault();
1895
- const id = uniqueNodeId('agent');
1896
- const name = byId('custom-name').value.trim();
1897
- const prompt = byId('custom-prompt').value.trim();
1898
- const error = validDisplayName(name);
1899
- if (error || !prompt) return notify(error || 'Custom Agent prompt is required.');
1900
- const artifact = byId('custom-output').value.trim() || `${id}-report`;
1901
- const node = {
1902
- id,
1903
- type: 'agent',
1904
- displayName: name,
1905
- prompt,
1906
- capabilityRefs: csv(byId('custom-capabilities').value),
1907
- mcpRefs: csv(byId('custom-mcp').value),
1908
- inputArtifacts: csv(byId('custom-inputs').value),
1909
- outputArtifacts: [{ artifact, schema: 'schemas/report.schema.json' }],
1910
- tokenLimit: Number(byId('custom-tokens').value),
1911
- timeoutMs: Number(byId('custom-timeout').value) * 1000,
1912
- retry: { maxAttempts: Number(byId('custom-retries').value), backoffMs: 1000 }
1913
- };
1914
- draft.nodes.push(node);
1915
- if (pendingConnectionSource) {
1916
- draft.edges.push({ id: uniqueEdgeId(pendingConnectionSource, id), from: pendingConnectionSource, to: id });
1917
- pendingConnectionSource = null;
1918
- }
1919
- syncDependencies();
1920
- const center = worldAtCanvasCenter();
1921
- positions.set(id, { x: center.x - NODE_WIDTH / 2, y: center.y - NODE_PORT_Y });
1922
- captureHistory();
1923
- renderGraph();
1924
- selectNode(id);
1925
- validateDraft();
1926
- byId('custom-dialog').close();
1856
+ function maybeOpenOnboarding() {
1857
+ const dialog = byId('goal-dialog');
1858
+ if (!eventsReady || catalog.live || dialog.open || onboardingDismissed) return;
1859
+ dialog.showModal();
1927
1860
  }
1928
1861
 
1929
- function zoomAt(nextScale, clientX, clientY) {
1930
- const scale = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, nextScale));
1931
- const rect = byId('canvas').getBoundingClientRect();
1932
- const x = clientX ?? rect.left + rect.width / 2;
1933
- const y = clientY ?? rect.top + rect.height / 2;
1934
- const world = screenToWorld(x, y);
1935
- viewport.scale = scale;
1936
- viewport.x = x - rect.left - world.x * scale;
1937
- viewport.y = y - rect.top - world.y * scale;
1938
- applyViewport();
1939
- saveLayoutSoon();
1862
+ function setConnectionLost(lost, message) {
1863
+ byId('live-connection-state').hidden = !lost;
1864
+ byId('live-connection-message').textContent = lost
1865
+ ? (message || 'Studio connection lost. Your last valid Run view is preserved.')
1866
+ : '';
1940
1867
  }
1941
1868
 
1942
- function handleWheel(event) {
1943
- event.preventDefault();
1944
- setFollowExecution(false);
1945
- if (event.ctrlKey || event.metaKey) {
1946
- zoomAt(viewport.scale * Math.exp(-event.deltaY * 0.002), event.clientX, event.clientY);
1947
- } else {
1948
- viewport.x -= event.deltaX;
1949
- viewport.y -= event.deltaY;
1950
- applyViewport();
1951
- saveLayoutSoon();
1952
- }
1869
+ function followedRunId() {
1870
+ return pinnedRunId || catalog.currentRunId || catalog.live?.run?.runId || null;
1953
1871
  }
1954
1872
 
1955
- function autoLayout({ record = true } = {}) {
1956
- positions = defaultGraphPositions();
1957
- renderGraph();
1958
- fitView();
1959
- if (record) captureHistory();
1960
- saveLayoutSoon();
1873
+ function eventTouchesFollowed(event) {
1874
+ const followed = followedRunId();
1875
+ if (!followed) return true;
1876
+ if (!event.runId) return true;
1877
+ return event.runId === followed;
1961
1878
  }
1962
1879
 
1963
- function fitView() {
1964
- ensurePositions();
1965
- if (!positions.size) return;
1966
- const rect = byId('canvas').getBoundingClientRect();
1967
- const values = [...positions.values()];
1968
- const minX = Math.min(...values.map((position) => position.x));
1969
- const minY = Math.min(...values.map((position) => position.y));
1970
- const maxX = Math.max(...values.map((position) => position.x + NODE_WIDTH));
1971
- const maxY = Math.max(...values.map((position) => position.y + 140));
1972
- const padding = 100;
1973
- viewport.scale = Math.max(MIN_ZOOM, Math.min(1.35, Math.min(
1974
- (rect.width - padding * 2) / Math.max(1, maxX - minX),
1975
- (rect.height - padding * 2) / Math.max(1, maxY - minY)
1976
- )));
1977
- viewport.x = (rect.width - (maxX - minX) * viewport.scale) / 2 - minX * viewport.scale;
1978
- viewport.y = (rect.height - (maxY - minY) * viewport.scale) / 2 - minY * viewport.scale;
1979
- applyViewport();
1980
- saveLayoutSoon();
1880
+ async function loadLive(runId) {
1881
+ const query = runId ? `?runId=${encodeURIComponent(runId)}` : '';
1882
+ const result = await api(`/api/live${query}`);
1883
+ catalog.live = result.live;
1884
+ liveArtifacts = result.live?.artifacts || {};
1885
+ lifecycleEvents = result.live?.lifecycle?.events || lifecycleEvents;
1886
+ agentPresence = result.live?.presence || agentPresence;
1887
+ syncGoalFromLive();
1888
+ renderLive();
1889
+ if (workspace === 'wiring') renderGraph();
1890
+ return result.live;
1981
1891
  }
1982
1892
 
1983
- function captureHistory({ reset = false } = {}) {
1984
- const snapshot = JSON.stringify({ draft, positions: Object.fromEntries(positions) });
1985
- if (reset) {
1986
- history = [snapshot];
1987
- historyIndex = 0;
1988
- } else if (history[historyIndex] !== snapshot) {
1989
- history = history.slice(0, historyIndex + 1);
1990
- history.push(snapshot);
1991
- historyIndex = history.length - 1;
1893
+ function applyEvent(event) {
1894
+ if (!event || event.type === 'hello') return;
1895
+ if (event.type === 'resync') {
1896
+ resync();
1897
+ return;
1898
+ }
1899
+ lastEventSeq = Math.max(lastEventSeq, Number(event.seq) || 0);
1900
+ if (event.type === 'current.changed') {
1901
+ catalog.currentRunId = event.payload?.runId || event.runId;
1902
+ if (!pinnedRunId) loadLive(catalog.currentRunId).then(() => maybeOpenOnboarding()).catch(() => {});
1903
+ return;
1904
+ }
1905
+ if (!eventTouchesFollowed(event) && event.type !== 'run.created') return;
1906
+ if (event.type === 'run.created' || event.type === 'run.state') {
1907
+ if (catalog.live?.run && event.runId === catalog.live.run.runId) {
1908
+ Object.assign(catalog.live.run, event.payload || {});
1909
+ }
1910
+ if (event.type === 'run.created' && !catalog.live) loadLive(event.runId).catch(() => {});
1911
+ } else if (event.type === 'lifecycle') {
1912
+ const incoming = event.payload?.events || [];
1913
+ lifecycleEvents = lifecycleEvents.concat(incoming).slice(-100);
1914
+ if (event.payload?.presence) agentPresence = event.payload;
1915
+ else if (catalog.live) catalog.live.lifecycle = event.payload;
1916
+ applyLifecycleNodes(incoming);
1917
+ } else if (event.type === 'presence') {
1918
+ agentPresence = event.payload || agentPresence;
1919
+ if (catalog.live) catalog.live.presence = agentPresence;
1920
+ } else if (String(event.type).startsWith('artifact.')) {
1921
+ liveArtifacts[event.type] = event.payload;
1922
+ if (catalog.live) {
1923
+ catalog.live.artifacts = catalog.live.artifacts || {};
1924
+ catalog.live.artifacts[event.type] = event.payload;
1925
+ }
1926
+ }
1927
+ scheduleLiveRender();
1928
+ }
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
+ };
1992
1944
  }
1993
- byId('undo').disabled = historyIndex <= 0;
1994
- byId('redo').disabled = historyIndex >= history.length - 1;
1995
1945
  }
1996
1946
 
1997
- function restoreHistory(index) {
1998
- if (index < 0 || index >= history.length) return;
1999
- historyIndex = index;
2000
- const snapshot = JSON.parse(history[index]);
2001
- draft = snapshot.draft;
2002
- positions = new Map(Object.entries(snapshot.positions));
2003
- if (!draft.nodes.some((node) => node.id === selectedId)) selectedId = null;
2004
- renderGraph();
2005
- if (selectedId) selectNode(selectedId);
2006
- else renderRecipeDetails();
2007
- validateDraft();
2008
- saveLayoutSoon();
2009
- byId('undo').disabled = historyIndex <= 0;
2010
- byId('redo').disabled = historyIndex >= history.length - 1;
1947
+ function parseSseBlock(block) {
1948
+ let type = 'message';
1949
+ let data = '';
1950
+ let id = '';
1951
+ for (const line of block.split('\n')) {
1952
+ if (line.startsWith('event:')) type = line.slice(6).trim();
1953
+ else if (line.startsWith('data:')) data += line.slice(5).trim();
1954
+ else if (line.startsWith('id:')) id = line.slice(3).trim();
1955
+ }
1956
+ if (!data) return { type, event: null, id };
1957
+ try {
1958
+ return { type, event: JSON.parse(data), id };
1959
+ } catch {
1960
+ return { type, event: null, id };
1961
+ }
2011
1962
  }
2012
1963
 
2013
- function saveLayoutSoon() {
2014
- clearTimeout(layoutTimer);
2015
- if (!loadedRecipeId || draft.id !== loadedRecipeId) return;
2016
- layoutTimer = setTimeout(async () => {
2017
- try {
2018
- await api('/api/layout', {
2019
- method: 'PUT',
2020
- body: JSON.stringify({ recipeId: loadedRecipeId, layout: layoutPayload() })
2021
- });
2022
- } catch {
2023
- // Canvas work remains in memory and install still submits the layout.
1964
+ function dispatchSse(buffer) {
1965
+ const parts = buffer.split('\n\n');
1966
+ const rest = parts.pop();
1967
+ for (const block of parts) {
1968
+ if (!block.trim()) continue;
1969
+ const parsed = parseSseBlock(block);
1970
+ if (parsed.type === 'hello' && parsed.event) {
1971
+ catalog.watchMode = parsed.event.mode || catalog.watchMode;
1972
+ catalog.root = parsed.event.root || catalog.root;
1973
+ catalog.currentRunId = parsed.event.currentRunId;
1974
+ lastEventSeq = parsed.event.seq || lastEventSeq;
1975
+ eventsReady = true;
1976
+ reconnectAttempt = 0;
1977
+ resumeFallbackUsed = false;
1978
+ clearReconnectTimer();
1979
+ setConnectionLost(false);
1980
+ updateChrome();
1981
+ maybeOpenOnboarding();
1982
+ continue;
2024
1983
  }
2025
- }, 350);
1984
+ if (parsed.event) applyEvent(parsed.event);
1985
+ }
1986
+ return rest;
2026
1987
  }
2027
1988
 
2028
- async function validateDraft() {
2029
- const sequence = ++validationSequence;
2030
- try {
2031
- const result = await api('/api/validate', { method: 'POST', body: JSON.stringify({ recipe: draft }) });
2032
- if (sequence !== validationSequence) return;
2033
- const hash = result.plans[0].graphHash;
2034
- byId('integrity').textContent = `VALID / ${hash.slice(0, 8)}…${hash.slice(-4)}`;
2035
- byId('integrity').className = 'valid';
2036
- byId('review').disabled = false;
2037
- byId('review-data').textContent = JSON.stringify({
2038
- recipe: draft.id,
2039
- version: draft.version,
2040
- modes: result.plans.map((plan) => plan.mode),
2041
- nodes: draft.nodes.length,
2042
- graphHashes: result.plans.map((plan) => plan.graphHash)
2043
- }, null, 2);
2044
- } catch (error) {
2045
- if (sequence !== validationSequence) return;
2046
- byId('integrity').textContent = `INVALID / ${error.message}`;
2047
- byId('integrity').className = 'invalid';
2048
- byId('review').disabled = true;
1989
+ async function consumeEvents(signal) {
1990
+ const params = lastEventSeq > 0 ? `?after=${encodeURIComponent(lastEventSeq)}` : '';
1991
+ const headers = lastEventSeq > 0 ? { 'Last-Event-ID': String(lastEventSeq) } : {};
1992
+ const response = await fetch(`/api/events${params}`, { signal, headers });
1993
+ if (!response.ok) {
1994
+ const error = new Error('Studio event stream failed');
1995
+ error.code = lastEventSeq > 0 ? 'EVENT_RESUME_FAILED' : 'EVENT_STREAM_FAILED';
1996
+ throw error;
1997
+ }
1998
+ const reader = response.body.getReader();
1999
+ const decoder = new TextDecoder();
2000
+ let buffer = '';
2001
+ for (;;) {
2002
+ const { done, value } = await reader.read();
2003
+ if (done) break;
2004
+ buffer += decoder.decode(value, { stream: true });
2005
+ buffer = dispatchSse(buffer);
2049
2006
  }
2007
+ throw new Error('event stream ended');
2050
2008
  }
2051
2009
 
2052
- function renderLive() {
2053
- const live = catalog.live;
2054
- if (!live) {
2055
- byId('run-summary').textContent = 'No active run';
2056
- byId('active-stage').textContent = 'No active run';
2057
- byId('activity').textContent = 'Waiting for a recipe-bound workflow.';
2058
- byId('events').innerHTML = '';
2059
- byId('budget').textContent = '—';
2060
- byId('meter').style.width = '0';
2061
- byId('agent-presence').textContent = 'Agent unavailable';
2062
- byId('agent-presence').className = 'agent-presence unknown';
2063
- const dock = byId('run-activity-dock');
2064
- if (dock) dock.hidden = true;
2065
- updateRuntimePresentation();
2066
- return;
2067
- }
2068
- const lifecycleNodeId = activeLifecycleNodeId();
2069
- const active = live.plan.nodes.find((node) => node.id === lifecycleNodeId)
2070
- || live.plan.nodes.find((node) => live.nodes[node.id].status === 'RUNNING')
2071
- || live.plan.nodes.find((node) => live.nodes[node.id].status === 'READY');
2072
- const runtimeNode = active ? live.nodes[active.id] : null;
2073
- const lifecycle = activeLifecycleEvent();
2074
- byId('run-summary').textContent = active ? `${active.id} · ${runtimeNode.status}` : `Run ${live.run.state}`;
2075
- byId('active-stage').textContent = active?.id || 'Run complete';
2076
- byId('activity').textContent = lifecycle?.message ||
2077
- (active ? runtimeNode.activity || `${runtimeNode.status} · attempt ${runtimeNode.attempts}` : `Final state: ${live.run.state}`);
2078
- const journeyStatuses = new Set(['pending', 'active', 'complete']);
2079
- const degradedSources = live.journey?.degradedSources || [];
2080
- byId('run-journey').innerHTML = (live.journey?.steps || []).map((step) => {
2081
- const status = String(step?.status || '').toLowerCase();
2082
- const safeStatus = journeyStatuses.has(status) ? status : 'unknown';
2083
- const label = String(step?.id || '').replaceAll('_', ' ');
2084
- const suffix = safeStatus === 'unknown' ? ' (status unavailable)' : '';
2085
- const blocked = step?.blocked
2086
- ? (live.journey?.pendingQuestions == null
2087
- ? ' · unanswered count unavailable'
2088
- : ` · ${Number(live.journey.pendingQuestions)} unanswered`)
2089
- : '';
2090
- return `<li class="${safeStatus}">${escapeHtml(label + suffix + blocked)}</li>`;
2091
- }).join('') + (degradedSources.length
2092
- ? `<li class="unknown">${escapeHtml(`${degradedSources.join(' and ')} unavailable — journey may be incomplete`)}</li>`
2093
- : '');
2094
- const presenceLabel = {
2095
- WORKING: 'Agent working',
2096
- IDLE: 'Agent appears idle',
2097
- DISCONNECTED: 'Agent disconnected',
2098
- UNKNOWN: 'Waiting for Agent'
2099
- }[agentPresence.status] || 'Waiting for Agent';
2100
- byId('agent-presence').textContent = presenceLabel;
2101
- byId('agent-presence').className = `agent-presence ${agentPresence.status.toLowerCase()}`;
2102
- const spent = live.budget.spentThisRun;
2103
- const limit = live.budget.perRunTokenLimit;
2104
- byId('meter').style.width = `${Math.min(100, limit ? (spent / limit) * 100 : 0)}%`;
2105
- byId('budget').textContent = `${spent.toLocaleString()} / ${limit.toLocaleString()} TOKENS`;
2106
- const liveEventsHtml = lifecycleEvents.slice(-7).reverse().map((event) => `
2107
- <p class="${event.type === 'NODE_ACTIVITY' || event.type.includes('START') ? 'event-active' : ''}">
2108
- ${escapeHtml(event.at.slice(11, 19))} · ${escapeHtml(event.type)} · ${escapeHtml(event.message)}
2109
- </p>
2110
- `).join('') || live.events.slice(-7).reverse().map((event) => `
2111
- <p>${escapeHtml(event.at.slice(11, 19))} · ${escapeHtml(event.type)}</p>
2112
- `).join('');
2113
- const eventsDetailNote = live.summary?.eventsTruncated
2114
- ? '<p class="muted">Older workflow events are kept out of live polling; node detail and lifecycle stream load them on demand.</p>'
2115
- : '';
2116
- byId('events').innerHTML = liveEventsHtml + eventsDetailNote;
2117
- renderRunActivityDock(live, active, runtimeNode, lifecycle);
2118
- updateRuntimePresentation();
2119
- followActiveNode();
2120
- }
2121
-
2122
- function renderRunActivityDock(live, active, runtimeNode, lifecycle) {
2123
- const dock = byId('run-activity-dock');
2124
- if (!dock) return;
2125
- dock.hidden = false;
2126
- byId('run-activity-scope').textContent = active ? 'NODE ACTIVITY' : 'RUN ACTIVITY';
2127
- byId('run-activity-title').textContent = active ? displayName(active) : `Run ${live.run.state}`;
2128
- byId('run-activity-message').textContent = lifecycle?.message ||
2129
- runtimeNode?.activity || (active ? runtimeNode?.status : 'Waiting for the next persisted event.');
2130
- byId('run-activity-status').textContent = runtimeNode?.status || agentPresence.status || live.run.state;
2131
- const inspect = byId('inspect-live-node');
2132
- inspect.hidden = !active;
2133
- inspect.dataset.nodeId = active?.id || '';
2134
- byId('run-activity-timeline').innerHTML = lifecycleEvents.slice(-4).reverse().map((event) => `
2135
- <span><time>${escapeHtml(String(event.at || '').slice(11, 19))}</time>${escapeHtml(event.message || event.type)}</span>
2136
- `).join('');
2010
+ function clearReconnectTimer() {
2011
+ if (reconnectTimer == null) return;
2012
+ clearTimeout(reconnectTimer);
2013
+ reconnectTimer = null;
2137
2014
  }
2138
2015
 
2139
- function maybeOpenOnboarding() {
2140
- const dialog = byId('goal-dialog');
2141
- if (catalog.live || dialog.open || onboardingDismissed) return;
2142
- dialog.showModal();
2016
+ function scheduleReconnect() {
2017
+ if (reconnectTimer != null) return;
2018
+ setConnectionLost(true);
2019
+ const delay = RECONNECT_BACKOFF_MS[Math.min(reconnectAttempt, RECONNECT_BACKOFF_MS.length - 1)];
2020
+ reconnectAttempt += 1;
2021
+ reconnectTimer = setTimeout(() => {
2022
+ reconnectTimer = null;
2023
+ startEventStream();
2024
+ }, delay);
2025
+ reconnectTimer?.unref?.();
2026
+ }
2027
+
2028
+ function startEventStream() {
2029
+ if (typeof AbortController !== 'function') {
2030
+ setConnectionLost(true, 'Studio connection lost. Your last valid Run view is preserved.');
2031
+ return;
2032
+ }
2033
+ if (eventAbort) eventAbort.abort();
2034
+ eventAbort = new AbortController();
2035
+ consumeEvents(eventAbort.signal).catch((error) => {
2036
+ if (error?.name === 'AbortError') return;
2037
+ if (error?.code === 'EVENT_RESUME_FAILED' && !resumeFallbackUsed) {
2038
+ resumeFallbackUsed = true;
2039
+ resync();
2040
+ return;
2041
+ }
2042
+ scheduleReconnect();
2043
+ });
2143
2044
  }
2144
2045
 
2145
- async function refreshLive() {
2046
+ async function resync() {
2047
+ clearReconnectTimer();
2048
+ reconnectAttempt = 0;
2146
2049
  try {
2147
- const result = await api('/api/live');
2148
- catalog.live = result.live;
2050
+ const result = await api('/api/bootstrap');
2051
+ catalog = { ...catalog, ...result };
2052
+ liveArtifacts = result.live?.artifacts || liveArtifacts;
2053
+ lifecycleEvents = result.live?.lifecycle?.events || lifecycleEvents;
2054
+ agentPresence = result.live?.presence || agentPresence;
2055
+ lastEventSeq = result.eventSeq || lastEventSeq;
2056
+ eventsReady = true;
2057
+ setConnectionLost(false);
2058
+ updateChrome();
2149
2059
  syncGoalFromLive();
2150
- await refreshLifecycle(catalog.live?.run?.runId);
2151
- await refreshGoalDraft(catalog.live?.run?.runId);
2152
- await hydrateGoalFromLive();
2153
- byId('live-connection-state').hidden = true;
2154
2060
  renderLive();
2155
- await refreshSelectedCheckout();
2156
- await refreshCheckoutInteractions();
2157
- if (!byId('runs-view').hidden) await loadRuns();
2158
2061
  maybeOpenOnboarding();
2062
+ startEventStream();
2159
2063
  return true;
2160
2064
  } catch {
2161
- // A transient refresh failure must not discard the last valid draft or Run snapshot.
2162
- byId('live-connection-message').textContent =
2163
- 'Studio connection lost. Your last valid Run view is preserved.';
2164
- byId('live-connection-state').hidden = false;
2065
+ setConnectionLost(true);
2066
+ scheduleReconnect();
2165
2067
  return false;
2166
2068
  }
2167
2069
  }
2168
2070
 
2071
+ function updateChrome() {
2072
+ if (byId('watched-root')) byId('watched-root').textContent = catalog.root || '—';
2073
+ if (byId('live-mode')) byId('live-mode').textContent = `live: ${catalog.watchMode || 'watch'}`;
2074
+ }
2075
+
2169
2076
  async function loadRecipe() {
2170
2077
  const id = byId('recipe').value;
2171
2078
  const [result, saved] = await Promise.all([
@@ -2175,74 +2082,627 @@ async function loadRecipe() {
2175
2082
  draft = normalizeDraftGraph(structuredClone(result.recipe));
2176
2083
  source = result.source;
2177
2084
  loadedRecipeId = draft.id;
2085
+ rememberLoadedWiring();
2178
2086
  selectedId = null;
2179
2087
  selectedIds.clear();
2180
2088
  selectedEdgeId = null;
2181
- byId('inspector-panel').classList.remove('open');
2182
2089
  positions = new Map(Object.entries(saved.layout?.positions || {}));
2183
2090
  ensurePositions();
2184
2091
  viewport = saved.layout?.viewport || { x: 0, y: 0, scale: 1 };
2092
+ hasFitted = false;
2185
2093
  renderGraph();
2186
- if (!saved.layout || (draft.nodes.length <= 12 && viewport.scale < 0.45)) fitView();
2187
- renderRecipeDetails();
2188
2094
  captureHistory({ reset: true });
2189
- validateDraft();
2095
+ await validateDraft();
2190
2096
  }
2191
2097
 
2192
2098
  async function refreshCatalog(selectedRecipe) {
2193
- catalog = await api('/api/bootstrap');
2099
+ const result = await api('/api/bootstrap');
2100
+ catalog = { ...catalog, ...result };
2101
+ updateChrome();
2194
2102
  const selector = byId('recipe');
2195
2103
  selector.innerHTML = catalog.recipes.map((recipe) => (
2196
2104
  `<option value="${escapeHtml(recipe.id)}">${escapeHtml(recipe.id)} · v${escapeHtml(recipe.version)}</option>`
2197
2105
  )).join('');
2198
2106
  if (selectedRecipe && catalog.recipes.some((recipe) => recipe.id === selectedRecipe)) selector.value = selectedRecipe;
2199
- renderPalette();
2200
2107
  syncGoalFromLive();
2201
2108
  renderLive();
2202
2109
  }
2203
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
+
2204
2684
  function bindCanvas() {
2205
2685
  const canvas = byId('canvas');
2686
+ mountCanvasChrome();
2206
2687
  canvas.addEventListener('pointerdown', (event) => {
2688
+ if (closestReal(event.target, '#node-panel, .zoom-controls, .minimap')) return;
2207
2689
  if (event.target === canvas || event.target === byId('scene') || event.target === byId('nodes') || event.target === byId('edges')) {
2208
2690
  selectedId = null;
2691
+ selectedEdgeId = null;
2209
2692
  if (!event.shiftKey) selectedIds.clear();
2210
2693
  updateSelection();
2211
- renderRecipeDetails();
2212
- byId('inspector-panel').classList.remove('open');
2694
+ renderEdges();
2213
2695
  if (event.button === 1 || spacePressed) beginPan(event);
2214
- else if (event.button === 0) beginLasso(event);
2215
2696
  }
2216
2697
  });
2217
2698
  canvas.addEventListener('pointermove', handlePointerMove);
2218
2699
  canvas.addEventListener('pointerup', finishPointer);
2219
2700
  canvas.addEventListener('pointercancel', finishPointer);
2220
2701
  canvas.addEventListener('wheel', handleWheel, { passive: false });
2221
- canvas.addEventListener('dragover', (event) => {
2222
- if (!event.dataTransfer.types.includes('application/x-ael-node-type')) return;
2223
- event.preventDefault();
2224
- canvas.classList.add('drop-ready');
2225
- });
2226
- canvas.addEventListener('dragleave', () => canvas.classList.remove('drop-ready'));
2227
- canvas.addEventListener('drop', (event) => {
2228
- event.preventDefault();
2229
- canvas.classList.remove('drop-ready');
2230
- const type = event.dataTransfer.getData('application/x-ael-node-type');
2231
- if (type) addNode(type, screenToWorld(event.clientX, event.clientY));
2232
- });
2233
- byId('auto-layout').onclick = () => autoLayout();
2234
- byId('fit-view').onclick = fitView;
2235
- byId('fit-view-rail').onclick = fitView;
2236
- byId('zoom-in').onclick = () => zoomAt(viewport.scale * 1.2);
2237
- byId('zoom-out').onclick = () => zoomAt(viewport.scale / 1.2);
2238
- byId('undo').onclick = () => restoreHistory(historyIndex - 1);
2239
- byId('redo').onclick = () => restoreHistory(historyIndex + 1);
2240
- byId('follow-execution').onclick = () => setFollowExecution(!followExecution);
2241
- setFollowExecution(followExecution);
2242
2702
  }
2243
2703
 
2244
2704
  function editableTarget(target) {
2245
- return target.matches('input,textarea,select,[contenteditable="true"]');
2705
+ return target.matches?.('input,textarea,select,[contenteditable="true"]');
2246
2706
  }
2247
2707
 
2248
2708
  document.addEventListener('keydown', (event) => {
@@ -2255,87 +2715,120 @@ document.addEventListener('keydown', (event) => {
2255
2715
  if (modifier && event.key.toLowerCase() === 'z') {
2256
2716
  event.preventDefault();
2257
2717
  restoreHistory(historyIndex + (event.shiftKey ? 1 : -1));
2258
- } else if (modifier && event.key.toLowerCase() === 'y') {
2718
+ return;
2719
+ }
2720
+ if (modifier && event.key.toLowerCase() === 'y') {
2259
2721
  event.preventDefault();
2260
2722
  restoreHistory(historyIndex + 1);
2261
- } else if (modifier && event.key.toLowerCase() === 'a' && byId('canvas').contains(document.activeElement)) {
2262
- event.preventDefault();
2263
- selectedIds = new Set(draft.nodes.map((node) => node.id));
2264
- selectedId = [...selectedIds].at(-1) || null;
2265
- updateSelection();
2266
- } else if ((event.key === 'Delete' || event.key === 'Backspace') && selectedEdgeId) {
2723
+ return;
2724
+ }
2725
+ if ((event.key === 'Delete' || event.key === 'Backspace') && selectedEdgeId && !panelIsOpen()) {
2267
2726
  event.preventDefault();
2268
2727
  deleteEdge(selectedEdgeId);
2269
- } else if ((event.key === 'Delete' || event.key === 'Backspace') && selectedIds.size) {
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))) {
2270
2749
  event.preventDefault();
2271
- deleteSelectedNode();
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);
2272
2791
  }
2273
2792
  });
2274
2793
  document.addEventListener('keyup', (event) => {
2275
2794
  if (event.code === 'Space') spacePressed = false;
2276
2795
  });
2277
- window.addEventListener('blur', () => { spacePressed = false; });
2278
-
2279
- byId('copy').onclick = async () => {
2280
- try {
2281
- const handoff = await api('/api/handoff?audience=developer');
2282
- await navigator.clipboard.writeText(handoff.brief);
2283
- notify('Redacted developer brief copied.');
2284
- } catch (error) {
2285
- notify(error.message);
2286
- }
2287
- };
2288
-
2289
- byId('download').onclick = async () => {
2290
- try {
2291
- const handoff = await api('/api/handoff?audience=agent');
2292
- const blob = new Blob([JSON.stringify(handoff.bundle, null, 2)], { type: 'application/json' });
2293
- const link = document.createElement('a');
2294
- link.href = URL.createObjectURL(blob);
2295
- link.download = `${handoff.bundle.runId}.ael-handoff.json`;
2296
- link.click();
2297
- URL.revokeObjectURL(link.href);
2298
- notify('Integrity-bound handoff exported.');
2299
- } catch (error) {
2300
- notify(error.message);
2301
- }
2302
- };
2303
-
2304
- byId('record-decision').onclick = async () => {
2305
- if (!catalog.live) return notify('Start a workflow run before recording a decision.');
2306
- try {
2307
- await api('/api/decision', {
2308
- method: 'POST',
2309
- body: JSON.stringify({
2310
- runId: catalog.live.run.runId,
2311
- summary: byId('decision-summary').value,
2312
- rationale: byId('decision-rationale').value,
2313
- consequences: []
2314
- })
2315
- });
2316
- byId('decision-summary').value = '';
2317
- byId('decision-rationale').value = '';
2318
- notify('Redacted decision recorded for handoff.');
2319
- } catch (error) {
2320
- notify(error.message);
2321
- }
2796
+ if (typeof window !== 'undefined') window.addEventListener('resize', scheduleFitView);
2797
+
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;
2803
+ byId('confirm').showModal();
2322
2804
  };
2323
-
2324
- byId('review').onclick = () => byId('confirm').showModal();
2325
- byId('cancel').onclick = () => byId('confirm').close();
2326
2805
  byId('install').onclick = async () => {
2806
+ if (validationState.status !== 'valid') {
2807
+ notify(validationSummary() || 'Wiring is invalid.');
2808
+ return;
2809
+ }
2327
2810
  try {
2811
+ const recipe = authoringRecipe();
2812
+ const exists = catalog.recipes.some((item) => item.id === recipe.id && item.source !== 'builtin');
2813
+ if (source === 'builtin') {
2814
+ recipe.id = `${recipe.id}-local`;
2815
+ recipe.version = 1;
2816
+ } else if (exists) {
2817
+ recipe.version = Number(recipe.version) + 1;
2818
+ }
2819
+ const replacing = catalog.recipes.some((item) => item.id === recipe.id && item.source !== 'builtin');
2328
2820
  await api('/api/install', {
2329
2821
  method: 'POST',
2330
2822
  body: JSON.stringify({
2331
- recipe: draft,
2823
+ recipe,
2332
2824
  layout: layoutPayload(),
2333
- replace: catalog.recipes.some((recipe) => recipe.id === draft.id)
2825
+ replace: replacing,
2826
+ baseRecipeId: loadedRecipeId
2334
2827
  })
2335
2828
  });
2336
2829
  byId('confirm').close();
2337
- notify('Recipe and private canvas layout installed atomically.');
2338
- await refreshCatalog(draft.id);
2830
+ notify('Wiring installed. The compiler accepted the graph.');
2831
+ await refreshCatalog(recipe.id);
2339
2832
  await loadRecipe();
2340
2833
  } catch (error) {
2341
2834
  notify(error.message);
@@ -2349,93 +2842,13 @@ function notify(text) {
2349
2842
  setTimeout(() => { message.style.display = 'none'; }, 4000);
2350
2843
  }
2351
2844
 
2352
- function openLoopDialog() {
2353
- const members = draft.nodes.filter((node) => selectedIds.has(node.id));
2354
- if (members.length < 2) return notify('Select at least two steps for a Loop Group.');
2355
- if ((draft.loopGroups || []).some((group) => group.nodeIds.some((id) => selectedIds.has(id)))) {
2356
- return notify('A step can only belong to one Loop Group.');
2357
- }
2358
- const options = members.map((node) =>
2359
- `<option value="${escapeHtml(node.id)}">${escapeHtml(displayName(node))}</option>`
2360
- ).join('');
2361
- for (const id of ['loop-entry', 'loop-decision', 'loop-repeat-target']) byId(id).innerHTML = options;
2362
- const incomingEntry = members.find((node) =>
2363
- draft.edges.some((edge) => edge.to === node.id && !selectedIds.has(edge.from))
2364
- ) || members[0];
2365
- const outgoing = draft.edges.find((edge) =>
2366
- selectedIds.has(edge.from) && !selectedIds.has(edge.to)
2367
- );
2368
- if (!outgoing) return notify('Connect the Loop decision step to its Continue step first.');
2369
- const decision = outgoing
2370
- ? members.find((node) => node.id === outgoing.from)
2371
- : members.find((node) => ['decision', 'judge', 'condition'].includes(node.type)) || members.at(-1);
2372
- const exitIds = new Set(draft.edges
2373
- .filter((edge) => selectedIds.has(edge.from) && !selectedIds.has(edge.to))
2374
- .map((edge) => edge.to));
2375
- const exitCandidates = draft.nodes.filter((node) => exitIds.has(node.id));
2376
- byId('loop-exit-target').innerHTML = exitCandidates.map((node) =>
2377
- `<option value="${escapeHtml(node.id)}">${escapeHtml(displayName(node))}</option>`
2378
- ).join('');
2379
- byId('loop-entry').value = incomingEntry.id;
2380
- byId('loop-repeat-target').value = incomingEntry.id;
2381
- byId('loop-decision').value = decision.id;
2382
- if (outgoing) byId('loop-exit-target').value = outgoing.to;
2383
- byId('loop-name').value = '';
2384
- byId('loop-dialog').showModal();
2385
- }
2386
-
2387
- function createLoopGroupFromForm(event) {
2388
- event.preventDefault();
2389
- const display = byId('loop-name').value.trim();
2390
- const repeatOutcome = byId('loop-repeat-outcome').value.trim();
2391
- const exitOutcome = byId('loop-exit-outcome').value.trim();
2392
- if (repeatOutcome === exitOutcome) return notify('Repeat and Continue outcomes must be different.');
2393
- let id = slug(display || 'iteration-loop');
2394
- const occupied = new Set((draft.loopGroups || []).map((group) => group.id));
2395
- for (let suffix = 2; occupied.has(id); suffix += 1) id = `${slug(display || 'iteration-loop')}-${suffix}`;
2396
- const loopGroup = {
2397
- id,
2398
- displayName: display,
2399
- nodeIds: draft.nodes.filter((node) => selectedIds.has(node.id)).map((node) => node.id),
2400
- entryNodeId: byId('loop-entry').value,
2401
- decisionNodeId: byId('loop-decision').value,
2402
- repeatTargetId: byId('loop-repeat-target').value,
2403
- exitTargetId: byId('loop-exit-target').value,
2404
- maxIterations: Number(byId('loop-max').value),
2405
- repeatOutcome,
2406
- exitOutcome,
2407
- repeatLabel: byId('loop-repeat-label').value.trim(),
2408
- exitLabel: byId('loop-exit-label').value.trim()
2409
- };
2410
- draft.loopGroups.push(loopGroup);
2411
- captureHistory();
2412
- renderGraph();
2413
- validateDraft();
2414
- byId('loop-dialog').close();
2415
- notify(`Loop Group “${display}” created.`);
2416
- }
2417
-
2418
2845
  async function initialize() {
2419
- await refreshCatalog('default');
2420
2846
  byId('recipe').onchange = loadRecipe;
2421
2847
  bindCanvas();
2422
- byId('toggle-library').onclick = () => byId('library-panel').classList.toggle('open');
2423
- byId('close-library').onclick = () => byId('library-panel').classList.remove('open');
2424
- byId('show-workflows').onclick = () => showWorkspace('workflows');
2848
+ byId('show-live').onclick = () => showWorkspace('live');
2425
2849
  byId('show-runs').onclick = () => showWorkspace('runs');
2850
+ byId('show-wiring').onclick = () => showWorkspace('wiring');
2426
2851
  byId('run-search').oninput = loadRuns;
2427
- for (const id of ['run-status', 'run-mode', 'run-from', 'run-to']) byId(id).onchange = loadRuns;
2428
- byId('import-json').onclick = () => byId('import-dialog').showModal();
2429
- byId('export-json').onclick = exportWorkflowJson;
2430
- byId('preview-import').onclick = previewImport;
2431
- byId('import-file').onchange = async (event) => {
2432
- const [file] = event.currentTarget.files;
2433
- if (file) byId('import-source').value = await file.text();
2434
- };
2435
- byId('merge-import').onclick = () => applyImport('merge');
2436
- byId('replace-import').onclick = () => applyImport('replace');
2437
- byId('create-custom').onclick = () => byId('custom-dialog').showModal();
2438
- byId('custom-form').onsubmit = createCustomAgentFromForm;
2439
2852
  byId('open-goal').onclick = () => {
2440
2853
  renderGoalState();
2441
2854
  byId('goal-dialog').showModal();
@@ -2445,42 +2858,20 @@ async function initialize() {
2445
2858
  byId('review-goal').onclick = reviewGoal;
2446
2859
  byId('confirm-freeze').onclick = freezeGoalFromForm;
2447
2860
  byId('unfreeze-goal').onclick = unfreezeGoalFromForm;
2448
- byId('duplicate-selection').onclick = duplicateSelectedNode;
2449
- byId('delete-selection').onclick = deleteSelectedNode;
2450
- byId('create-loop-group').onclick = openLoopDialog;
2451
- byId('loop-form').onsubmit = createLoopGroupFromForm;
2452
- document.querySelectorAll('[data-close]').forEach((button) => {
2861
+ byId('retry-live-connection').onclick = resync;
2862
+ document.querySelectorAll?.('[data-close]')?.forEach?.((button) => {
2453
2863
  button.onclick = () => byId(button.dataset.close).close();
2454
2864
  });
2455
- document.querySelectorAll('.dialog-maximize').forEach((button) => {
2865
+ document.querySelectorAll?.('.dialog-maximize')?.forEach?.((button) => {
2456
2866
  button.onclick = () => button.closest('dialog').classList.toggle('maximized');
2457
2867
  });
2458
- byId('workflow-settings').onclick = () => {
2459
- selectedId = null;
2460
- updateSelection();
2461
- renderRecipeDetails();
2462
- byId('inspector-panel').classList.add('open');
2463
- };
2464
- byId('close-inspector').onclick = () => byId('inspector-panel').classList.remove('open');
2465
- byId('toggle-execution').onclick = () => byId('execution-panel').classList.toggle('open');
2466
- byId('close-execution').onclick = () => byId('execution-panel').classList.remove('open');
2467
- byId('open-live-details').onclick = () => byId('execution-panel').classList.add('open');
2468
- byId('inspect-live-node').onclick = async (event) => {
2469
- const nodeId = event.currentTarget.dataset.nodeId;
2470
- if (!activeRunId || !nodeId) return;
2471
- showWorkspace('runs');
2472
- await loadRuns();
2473
- await loadRunDetail(activeRunId);
2474
- await loadNodeIo(activeRunId, nodeId);
2475
- };
2476
- byId('retry-live-connection').onclick = refreshLive;
2477
2868
  byId('goal-dialog').addEventListener('close', () => {
2478
2869
  onboardingDismissed = true;
2479
2870
  });
2871
+ showWorkspace('live');
2872
+ await refreshCatalog('default');
2480
2873
  await loadRecipe();
2481
- await refreshLive();
2482
- clearInterval(liveTimer);
2483
- liveTimer = setInterval(refreshLive, 1800);
2874
+ startEventStream();
2484
2875
  }
2485
2876
 
2486
2877
  initialize().catch((error) => notify(error.message));