ai-engineering-loop 1.7.0 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/studio/app.js CHANGED
@@ -15,6 +15,8 @@ let draft;
15
15
  let source;
16
16
  let loadedRecipeId;
17
17
  let selectedId;
18
+ let selectedIds = new Set();
19
+ let selectedEdgeId;
18
20
  let liveTimer;
19
21
  let validationSequence = 0;
20
22
  let positions = new Map();
@@ -25,6 +27,92 @@ let interaction;
25
27
  let connection;
26
28
  let layoutTimer;
27
29
  let spacePressed = false;
30
+ let pendingConnectionSource;
31
+ let runs = [];
32
+ let goal = { text: '', version: 1, frozen: false };
33
+ let activeRunId;
34
+ let pendingImport;
35
+ let hydratedGoalKey;
36
+
37
+ const DISPLAY_NAME_MAX = 80;
38
+ const ROOT_TYPES = new Set(['goal-contract', 'trigger']);
39
+
40
+ function displayName(item) {
41
+ return item?.displayName || item?.name || item?.id || 'Untitled';
42
+ }
43
+
44
+ function edgeId(from, to, index = 0) {
45
+ const suffix = index ? `-${index + 1}` : '';
46
+ const base = `edge-${from}-${to}`.toLowerCase().replace(/[^a-z0-9-]+/g, '-');
47
+ return `${base.slice(0, 64 - suffix.length)}${suffix}`;
48
+ }
49
+
50
+ function uniqueEdgeId(from, to) {
51
+ let index = 0;
52
+ let candidate = edgeId(from, to, index);
53
+ const occupied = new Set((draft?.edges || []).map((edge) => edge.id));
54
+ while (occupied.has(candidate)) candidate = edgeId(from, to, ++index);
55
+ return candidate;
56
+ }
57
+
58
+ function normalizeDraftGraph(recipe) {
59
+ recipe.nodes = (recipe.nodes || []).map((node) => ({
60
+ ...node,
61
+ displayName: displayName(node)
62
+ }));
63
+ if (!Array.isArray(recipe.edges)) {
64
+ recipe.edges = [];
65
+ recipe.nodes.forEach((node) => {
66
+ (node.dependsOn || []).forEach((from, index) => {
67
+ recipe.edges.push({ id: edgeId(from, node.id, index), from, to: node.id });
68
+ });
69
+ });
70
+ }
71
+ const used = new Set();
72
+ recipe.edges = recipe.edges.map((edge, index) => {
73
+ let id = edge.id || edgeId(edge.from, edge.to, index);
74
+ while (used.has(id)) id = `${id}-${index + 1}`;
75
+ used.add(id);
76
+ return { ...edge, id };
77
+ });
78
+ syncDependencies(recipe);
79
+ return recipe;
80
+ }
81
+
82
+ function syncDependencies(recipe = draft) {
83
+ if (!recipe) return;
84
+ recipe.nodes.forEach((node) => {
85
+ node.dependsOn = recipe.edges
86
+ .filter((edge) => edge.to === node.id)
87
+ .map((edge) => edge.from);
88
+ });
89
+ }
90
+
91
+ function authoringRecipe(recipe = draft) {
92
+ const exported = structuredClone(recipe);
93
+ exported.nodes.forEach((node) => delete node.dependsOn);
94
+ return exported;
95
+ }
96
+
97
+ function validDisplayName(value) {
98
+ const name = String(value || '').trim();
99
+ if (!name) return 'Display Name is required.';
100
+ if (name.length > DISPLAY_NAME_MAX) return `Display Name must be ${DISPLAY_NAME_MAX} characters or fewer.`;
101
+ if (/[\u0000-\u001f\u007f]/.test(name)) return 'Display Name cannot contain control characters.';
102
+ return '';
103
+ }
104
+
105
+ function isInputTarget(target) {
106
+ return target instanceof Element && Boolean(target.closest('input,textarea,select,button,[contenteditable="true"],dialog'));
107
+ }
108
+
109
+ function csv(value) {
110
+ return String(value || '').split(',').map((item) => item.trim()).filter(Boolean);
111
+ }
112
+
113
+ function slug(value) {
114
+ return String(value || 'run').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 64) || 'run';
115
+ }
28
116
 
29
117
  async function api(url, options = {}) {
30
118
  const response = await fetch(url, {
@@ -128,31 +216,68 @@ function stageLabel(node, index) {
128
216
 
129
217
  function renderEdges() {
130
218
  const group = byId('edge-paths');
219
+ const controls = byId('edge-controls');
131
220
  group.innerHTML = '';
221
+ controls.innerHTML = '';
132
222
  if (!draft) return;
133
- draft.nodes.forEach((node) => {
134
- for (const dependencyId of node.dependsOn || []) {
135
- const from = positions.get(dependencyId);
136
- const to = positions.get(node.id);
137
- if (!from || !to) continue;
138
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
139
- path.setAttribute('d', edgePath(from, to));
140
- path.setAttribute('class', catalog.live?.nodes?.[dependencyId]?.status === 'RUNNING' ? 'edge active' : 'edge');
141
- path.setAttribute('marker-end', 'url(#arrow)');
142
- group.append(path);
143
- }
223
+ draft.edges.forEach((edge) => {
224
+ const from = positions.get(edge.from);
225
+ const to = positions.get(edge.to);
226
+ if (!from || !to) return;
227
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
228
+ path.setAttribute('d', edgePath(from, to));
229
+ path.setAttribute('class', `${catalog.live?.nodes?.[edge.from]?.status === 'RUNNING' ? 'edge active' : 'edge'}${selectedEdgeId === edge.id ? ' selected' : ''}`);
230
+ path.setAttribute('marker-end', 'url(#arrow)');
231
+ path.dataset.edgeId = edge.id;
232
+ group.append(path);
233
+
234
+ const midpoint = {
235
+ x: (from.x + NODE_WIDTH + to.x) / 2,
236
+ y: (from.y + to.y) / 2 + NODE_PORT_Y
237
+ };
238
+ const control = document.createElement('button');
239
+ control.className = `edge-delete${selectedEdgeId === edge.id ? ' selected' : ''}`;
240
+ control.dataset.edgeId = edge.id;
241
+ control.style.left = `${midpoint.x}px`;
242
+ control.style.top = `${midpoint.y}px`;
243
+ control.title = `${displayName(draft.nodes.find((node) => node.id === edge.from))} → ${displayName(draft.nodes.find((node) => node.id === edge.to))}`;
244
+ control.setAttribute('aria-label', `Delete connection ${control.title}`);
245
+ control.textContent = '×';
246
+ control.onclick = (event) => {
247
+ event.stopPropagation();
248
+ deleteEdge(edge.id);
249
+ };
250
+ let hideTimer;
251
+ path.onpointerenter = () => {
252
+ clearTimeout(hideTimer);
253
+ control.classList.add('visible');
254
+ };
255
+ path.onpointerleave = () => {
256
+ hideTimer = setTimeout(() => control.classList.remove('visible'), 100);
257
+ };
258
+ control.onpointerenter = () => {
259
+ clearTimeout(hideTimer);
260
+ control.classList.add('visible');
261
+ };
262
+ control.onpointerleave = () => control.classList.remove('visible');
263
+ controls.append(control);
144
264
  });
145
265
  }
146
266
 
147
267
  function nodeMarkup(node, index) {
148
268
  const runtimeNode = catalog.live?.nodes?.[node.id];
269
+ const outgoing = draft.edges.some((edge) => edge.from === node.id);
270
+ const root = rootCandidates().length === 1 && rootCandidates()[0].id === node.id;
149
271
  return `
150
272
  <button class="port port-in" aria-label="Input for ${escapeHtml(node.id)}" tabindex="-1"></button>
151
273
  <small>${escapeHtml(stageLabel(node, index))} / ${escapeHtml(node.type.toUpperCase())}</small>
152
- <h3>${escapeHtml(node.id)}</h3>
274
+ <button class="node-title" title="Double-click to edit Display Name">${escapeHtml(displayName(node))}</button>
275
+ <span class="technical-id">${escapeHtml(node.id)}</span>
153
276
  <span class="status">● ${escapeHtml(runtimeNode?.status || 'DRAFT')}</span>
154
277
  ${runtimeNode?.activity ? `<p class="node-activity">${escapeHtml(runtimeNode.activity)}</p>` : ''}
155
278
  <button class="port port-out" aria-label="Connect from ${escapeHtml(node.id)}" tabindex="-1"></button>
279
+ ${outgoing ? '' : `<button class="output-add" title="Add connected node" aria-label="Add node connected after ${escapeHtml(displayName(node))}">+</button>`}
280
+ ${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>` : ''}
156
281
  `;
157
282
  }
158
283
 
@@ -165,12 +290,15 @@ function renderGraph() {
165
290
  const runtimeNode = catalog.live?.nodes?.[node.id];
166
291
  const element = document.createElement('article');
167
292
  element.dataset.nodeId = node.id;
168
- element.className = `node ${runtimeNode?.status.toLowerCase() || ''} ${selectedId === node.id ? 'selected' : ''}`;
293
+ element.className = `node ${runtimeNode?.status.toLowerCase() || ''} ${selectedIds.has(node.id) ? 'selected' : ''}`;
169
294
  element.style.left = `${position.x}px`;
170
295
  element.style.top = `${position.y}px`;
171
296
  element.innerHTML = nodeMarkup(node, index);
172
297
  element.addEventListener('pointerdown', beginNodeInteraction);
173
298
  element.querySelector('.port-out').addEventListener('pointerdown', beginConnection);
299
+ element.querySelector('.node-title').addEventListener('dblclick', beginInlineRename);
300
+ element.querySelector('.output-add')?.addEventListener('click', openContextualAdd);
301
+ element.querySelector('.execute-trigger')?.addEventListener('click', executeFromTrigger);
174
302
  container.append(element);
175
303
  });
176
304
  renderEdges();
@@ -198,14 +326,20 @@ function updateRuntimePresentation() {
198
326
 
199
327
  function updateSelection() {
200
328
  document.querySelectorAll('.node').forEach((element) => {
201
- element.classList.toggle('selected', element.dataset.nodeId === selectedId);
329
+ element.classList.toggle('selected', selectedIds.has(element.dataset.nodeId));
202
330
  });
331
+ const actions = byId('selection-actions');
332
+ actions.hidden = selectedIds.size < 2;
333
+ byId('selection-count').textContent = `${selectedIds.size} nodes`;
203
334
  }
204
335
 
205
336
  function renderRecipeDetails() {
206
337
  const existing = recipeSummary();
207
338
  byId('inspector-label').textContent = 'WORKFLOW';
208
339
  byId('inspector-title').textContent = draft.id;
340
+ byId('inspector-title').contentEditable = 'false';
341
+ byId('inspector-title').onkeydown = null;
342
+ byId('inspector-title').onblur = null;
209
343
  byId('details').innerHTML = `
210
344
  <div class="source-line"><span>${escapeHtml(source.toUpperCase())}</span><span>${draft.nodes.length} NODES</span></div>
211
345
  <label for="recipe-id">Name</label><input id="recipe-id" value="${escapeHtml(draft.id)}">
@@ -226,18 +360,38 @@ function renderRecipeDetails() {
226
360
  byId('apply-recipe').onclick = applyRecipeDetails;
227
361
  }
228
362
 
229
- function selectNode(nodeId) {
363
+ function selectNode(nodeId, { additive = false } = {}) {
230
364
  const node = draft.nodes.find((candidate) => candidate.id === nodeId);
231
365
  if (!node) return;
366
+ if (additive) {
367
+ if (selectedIds.has(nodeId)) selectedIds.delete(nodeId);
368
+ else selectedIds.add(nodeId);
369
+ } else {
370
+ selectedIds = new Set([nodeId]);
371
+ }
372
+ selectedEdgeId = null;
232
373
  selectedId = nodeId;
233
374
  updateSelection();
234
375
  const runtimeNode = catalog.live?.nodes?.[nodeId];
235
376
  byId('inspector-label').textContent = 'NODE';
236
- byId('inspector-title').textContent = node.id;
377
+ byId('inspector-title').textContent = displayName(node);
378
+ byId('inspector-title').contentEditable = 'true';
379
+ byId('inspector-title').title = 'Edit Display Name';
380
+ byId('inspector-title').onkeydown = (event) => {
381
+ if (event.key === 'Enter') {
382
+ event.preventDefault();
383
+ event.currentTarget.blur();
384
+ } else if (event.key === 'Escape') {
385
+ event.currentTarget.textContent = displayName(node);
386
+ event.currentTarget.blur();
387
+ }
388
+ };
389
+ byId('inspector-title').onblur = (event) => applyDisplayName(node, event.currentTarget.textContent);
237
390
  byId('inspector-panel').classList.add('open');
238
391
  byId('details').innerHTML = `
239
392
  <div class="source-line"><span>${escapeHtml(node.type.toUpperCase())}</span><span>${escapeHtml(runtimeNode?.status || 'DRAFT')}</span></div>
240
- <label for="node-id">Name</label><input id="node-id" value="${escapeHtml(node.id)}">
393
+ <div id="name-validation" class="validation-message" aria-live="polite"></div>
394
+ <label for="node-id">Technical ID</label><input id="node-id" value="${escapeHtml(node.id)}" disabled>
241
395
  ${node.type === 'delivery' ? deliveryAdapterControls() : ''}
242
396
  <details>
243
397
  <summary>Settings</summary>
@@ -247,6 +401,7 @@ function selectNode(nodeId) {
247
401
  <input id="node-dependencies" value="${escapeHtml((node.dependsOn || []).join(', '))}" placeholder="Connect nodes on the canvas">
248
402
  ${node.type === 'agent' ? `
249
403
  <label for="node-extra">Role</label><input id="node-extra" value="${escapeHtml(node.role || '')}">
404
+ ${node.prompt != null ? customAgentFields(node) : ''}
250
405
  <label for="node-tokens">Token limit</label><input id="node-tokens" type="number" min="1" value="${escapeHtml(node.context?.maxTokens || '')}">
251
406
  ` : node.type === 'approval' ? `
252
407
  <label for="node-extra">Approval message</label><textarea id="node-extra">${escapeHtml(node.message || '')}</textarea>
@@ -270,6 +425,70 @@ function selectNode(nodeId) {
270
425
  bindRuntimeControls(node);
271
426
  }
272
427
 
428
+ function customAgentFields(node) {
429
+ return `
430
+ <label for="custom-node-prompt">Prompt</label><textarea id="custom-node-prompt">${escapeHtml(node.prompt || '')}</textarea>
431
+ <label for="custom-node-capabilities">Capabilities</label><input id="custom-node-capabilities" value="${escapeHtml((node.capabilityRefs || []).join(', '))}">
432
+ <label for="custom-node-mcp">MCP references</label><input id="custom-node-mcp" value="${escapeHtml((node.mcpRefs || []).join(', '))}">
433
+ <label for="custom-node-inputs">Input artifacts</label><input id="custom-node-inputs" value="${escapeHtml((node.inputArtifacts || []).join(', '))}">
434
+ <label for="custom-node-output">Output artifact</label><input id="custom-node-output" value="${escapeHtml(node.outputArtifacts?.[0]?.artifact || '')}">
435
+ <label for="custom-node-schema">Output schema</label><input id="custom-node-schema" value="${escapeHtml(node.outputArtifacts?.[0]?.schema || 'schemas/report.schema.json')}">
436
+ <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))}">
437
+ <label for="custom-node-retries">Maximum attempts</label><input id="custom-node-retries" type="number" min="1" value="${escapeHtml(node.retry?.maxAttempts ?? 2)}">
438
+ `;
439
+ }
440
+
441
+ function applyDisplayName(node, value) {
442
+ const error = validDisplayName(value);
443
+ const message = byId('name-validation');
444
+ if (error) {
445
+ if (message) message.textContent = error;
446
+ byId('inspector-title').textContent = displayName(node);
447
+ return false;
448
+ }
449
+ const next = value.trim();
450
+ if (next === displayName(node)) return true;
451
+ node.displayName = next;
452
+ captureHistory();
453
+ renderGraph();
454
+ selectNode(node.id);
455
+ return true;
456
+ }
457
+
458
+ function beginInlineRename(event) {
459
+ event.preventDefault();
460
+ event.stopPropagation();
461
+ const node = draft.nodes.find((candidate) => candidate.id === event.currentTarget.closest('.node').dataset.nodeId);
462
+ const input = document.createElement('input');
463
+ input.className = 'inline-rename';
464
+ input.maxLength = DISPLAY_NAME_MAX;
465
+ input.value = displayName(node);
466
+ event.currentTarget.replaceWith(input);
467
+ input.focus();
468
+ input.select();
469
+ let saved = false;
470
+ const finish = () => {
471
+ if (saved) return;
472
+ saved = true;
473
+ const error = validDisplayName(input.value);
474
+ if (error) notify(error);
475
+ else if (input.value.trim() !== displayName(node)) {
476
+ node.displayName = input.value.trim();
477
+ captureHistory();
478
+ }
479
+ renderGraph();
480
+ selectNode(node.id);
481
+ };
482
+ input.onkeydown = (keyEvent) => {
483
+ if (keyEvent.key === 'Enter') input.blur();
484
+ if (keyEvent.key === 'Escape') {
485
+ input.value = displayName(node);
486
+ input.blur();
487
+ }
488
+ };
489
+ input.onblur = finish;
490
+ }
491
+
273
492
  function deliveryAdapterControls() {
274
493
  const current = catalog.adapters.current;
275
494
  const options = [...catalog.adapters.types];
@@ -322,11 +541,18 @@ function runtimeControls(node, runtimeNode) {
322
541
  if (!catalog.live || !runtimeNode) return '';
323
542
  const approve = node.type === 'approval' && runtimeNode.status === 'READY' ? '<button id="approve-node">APPROVE</button>' : '';
324
543
  const retry = ['FAILED', 'RUNNING'].includes(runtimeNode.status) ? '<button id="retry-node">RETRY</button>' : '';
544
+ const custom = node.type === 'agent' && node.prompt && ['READY', 'RUNNING'].includes(runtimeNode.status) ? `
545
+ <p class="hint">This node is waiting for an external operator. Studio does not execute the agent independently.</p>
546
+ <button id="copy-agent-command">Copy command</button>
547
+ ${runtimeNode.status === 'READY'
548
+ ? '<button id="start-agent-node">Mark running</button>'
549
+ : '<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>'}
550
+ ` : '';
325
551
  const activity = runtimeNode.status === 'RUNNING'
326
552
  ? '<label for="runtime-activity">SAFE ACTIVITY UPDATE</label><input id="runtime-activity" maxlength="240"><button id="send-activity">REPORT ACTIVITY</button>'
327
553
  : '';
328
- return approve || retry || activity
329
- ? `<section class="runtime-controls"><label>RUNTIME CONTROL</label>${activity}<div class="button-row">${approve}${retry}</div></section>`
554
+ return approve || retry || activity || custom
555
+ ? `<section class="runtime-controls"><label>RUNTIME CONTROL</label>${custom}${activity}<div class="button-row">${approve}${retry}</div></section>`
330
556
  : '';
331
557
  }
332
558
 
@@ -339,6 +565,16 @@ function bindRuntimeControls(node) {
339
565
  runId, nodeId: node.id, message: byId('runtime-activity').value
340
566
  });
341
567
  }
568
+ if (byId('copy-agent-command')) byId('copy-agent-command').onclick = async () => {
569
+ await navigator.clipboard.writeText(`ai-engineering-loop node start ${node.id} --run ${runId}`);
570
+ notify('External operator command copied.');
571
+ };
572
+ if (byId('start-agent-node')) byId('start-agent-node').onclick = () => mutateNode('/api/node/start', { runId, nodeId: node.id });
573
+ if (byId('complete-agent-node')) byId('complete-agent-node').onclick = () => mutateNode('/api/node/complete', {
574
+ runId,
575
+ nodeId: node.id,
576
+ artifact: byId('agent-evidence').value.trim()
577
+ });
342
578
  }
343
579
 
344
580
  async function mutateNode(endpoint, body) {
@@ -365,15 +601,34 @@ function applyRecipeDetails() {
365
601
  function applyNodeDetails() {
366
602
  const node = draft.nodes.find((candidate) => candidate.id === selectedId);
367
603
  if (!node) return;
368
- const previousId = node.id;
369
- node.id = byId('node-id').value.trim();
370
- node.dependsOn = byId('node-dependencies').value.split(',').map((value) => value.trim()).filter(Boolean);
371
- draft.nodes.forEach((candidate) => {
372
- candidate.dependsOn = (candidate.dependsOn || []).map((dependency) => dependency === previousId ? node.id : dependency);
604
+ if (!applyDisplayName(node, byId('inspector-title').textContent)) return;
605
+ const inputs = csv(byId('node-dependencies').value);
606
+ draft.edges = draft.edges.filter((edge) => edge.to !== node.id);
607
+ inputs.forEach((from, index) => {
608
+ if (from !== node.id && draft.nodes.some((candidate) => candidate.id === from)) {
609
+ draft.edges.push({ id: uniqueEdgeId(from, node.id), from, to: node.id });
610
+ }
373
611
  });
612
+ syncDependencies();
374
613
  if (node.type === 'agent') {
375
614
  node.role = byId('node-extra').value.trim();
376
615
  node.context = { ...(node.context || {}), maxTokens: Number(byId('node-tokens').value) };
616
+ if (node.prompt != null) {
617
+ node.prompt = byId('custom-node-prompt').value.trim();
618
+ node.capabilityRefs = csv(byId('custom-node-capabilities').value);
619
+ node.mcpRefs = csv(byId('custom-node-mcp').value);
620
+ node.inputArtifacts = csv(byId('custom-node-inputs').value);
621
+ node.outputArtifacts = [{
622
+ artifact: byId('custom-node-output').value.trim(),
623
+ schema: byId('custom-node-schema').value.trim()
624
+ }];
625
+ node.tokenLimit = Number(byId('node-tokens').value);
626
+ node.timeoutMs = Number(byId('custom-node-timeout').value) * 1000;
627
+ node.retry = {
628
+ maxAttempts: Number(byId('custom-node-retries').value),
629
+ backoffMs: node.retry?.backoffMs || 1000
630
+ };
631
+ }
377
632
  } else if (node.type === 'approval') {
378
633
  node.message = byId('node-extra').value.trim();
379
634
  } else if (node.type === 'condition') {
@@ -385,11 +640,6 @@ function applyNodeDetails() {
385
640
  node.expression.value = field === 'run.iteration' || ['greaterThan', 'lessThan'].includes(operator) ? Number(rawValue) : rawValue;
386
641
  }
387
642
  }
388
- if (previousId !== node.id && positions.has(previousId)) {
389
- positions.set(node.id, positions.get(previousId));
390
- positions.delete(previousId);
391
- }
392
- selectedId = node.id;
393
643
  captureHistory();
394
644
  renderGraph();
395
645
  selectNode(node.id);
@@ -398,14 +648,14 @@ function applyNodeDetails() {
398
648
  }
399
649
 
400
650
  function deleteSelectedNode() {
401
- if (!selectedId) return;
402
- const removedId = selectedId;
403
- draft.nodes = draft.nodes.filter((node) => node.id !== removedId);
404
- draft.nodes.forEach((node) => {
405
- node.dependsOn = (node.dependsOn || []).filter((dependency) => dependency !== removedId);
406
- });
407
- positions.delete(removedId);
651
+ if (!selectedIds.size) return;
652
+ const removed = new Set(selectedIds);
653
+ draft.nodes = draft.nodes.filter((node) => !removed.has(node.id));
654
+ draft.edges = draft.edges.filter((edge) => !removed.has(edge.from) && !removed.has(edge.to));
655
+ syncDependencies();
656
+ removed.forEach((id) => positions.delete(id));
408
657
  selectedId = null;
658
+ selectedIds.clear();
409
659
  captureHistory();
410
660
  renderGraph();
411
661
  renderRecipeDetails();
@@ -414,6 +664,17 @@ function deleteSelectedNode() {
414
664
  saveLayoutSoon();
415
665
  }
416
666
 
667
+ function deleteEdge(id) {
668
+ const before = draft.edges.length;
669
+ draft.edges = draft.edges.filter((edge) => edge.id !== id);
670
+ if (draft.edges.length === before) return;
671
+ syncDependencies();
672
+ selectedEdgeId = null;
673
+ captureHistory();
674
+ renderGraph();
675
+ validateDraft();
676
+ }
677
+
417
678
  function uniqueNodeId(type) {
418
679
  let suffix = draft.nodes.length + 1;
419
680
  while (draft.nodes.some((node) => node.id === `${type}-${suffix}`)) suffix += 1;
@@ -421,7 +682,8 @@ function uniqueNodeId(type) {
421
682
  }
422
683
 
423
684
  function createNode(type, id = uniqueNodeId(type)) {
424
- const node = { id, type, dependsOn: [] };
685
+ const label = catalog.nodeTypes.find((candidate) => candidate.type === type)?.label || type.replaceAll('-', ' ');
686
+ const node = { id, type, displayName: label, dependsOn: [] };
425
687
  if (type === 'agent') {
426
688
  Object.assign(node, {
427
689
  role: 'analyst',
@@ -439,6 +701,11 @@ function createNode(type, id = uniqueNodeId(type)) {
439
701
  function addNode(type, position = worldAtCanvasCenter()) {
440
702
  const node = createNode(type);
441
703
  draft.nodes.push(node);
704
+ if (pendingConnectionSource) {
705
+ draft.edges.push({ id: uniqueEdgeId(pendingConnectionSource, node.id), from: pendingConnectionSource, to: node.id });
706
+ syncDependencies();
707
+ pendingConnectionSource = null;
708
+ }
442
709
  positions.set(node.id, { x: position.x - NODE_WIDTH / 2, y: position.y - NODE_PORT_Y });
443
710
  captureHistory();
444
711
  renderGraph();
@@ -448,20 +715,44 @@ function addNode(type, position = worldAtCanvasCenter()) {
448
715
  }
449
716
 
450
717
  function duplicateSelectedNode() {
451
- const original = draft.nodes.find((node) => node.id === selectedId);
452
- if (!original) return;
453
- const clone = structuredClone(original);
454
- clone.id = uniqueNodeId(original.type);
455
- if (clone.output?.artifact) clone.output.artifact = `${clone.id}-output`;
456
- draft.nodes.push(clone);
457
- const originalPosition = positions.get(original.id);
458
- positions.set(clone.id, { x: originalPosition.x + 36, y: originalPosition.y + 132 });
718
+ if (!selectedIds.size) return;
719
+ const originals = draft.nodes.filter((node) => selectedIds.has(node.id));
720
+ const mapping = new Map();
721
+ const clones = originals.map((original) => {
722
+ const clone = structuredClone(original);
723
+ clone.id = uniqueNodeId(original.type);
724
+ while (draft.nodes.some((node) => node.id === clone.id) || mapping.has(clone.id)) clone.id = `${clone.id}-copy`;
725
+ clone.displayName = `${displayName(original)} copy`;
726
+ if (clone.output?.artifact) clone.output.artifact = `${clone.id}-output`;
727
+ mapping.set(original.id, clone.id);
728
+ const originalPosition = positions.get(original.id);
729
+ positions.set(clone.id, { x: originalPosition.x + 36, y: originalPosition.y + 132 });
730
+ draft.nodes.push(clone);
731
+ return clone;
732
+ });
733
+ const copiedEdges = draft.edges.filter((edge) => mapping.has(edge.from) && mapping.has(edge.to)).map((edge) => ({
734
+ id: uniqueEdgeId(mapping.get(edge.from), mapping.get(edge.to)),
735
+ from: mapping.get(edge.from),
736
+ to: mapping.get(edge.to)
737
+ }));
738
+ draft.edges.push(...copiedEdges);
739
+ syncDependencies();
740
+ const cloneIds = new Set(clones.map((node) => node.id));
741
+ selectedId = clones.at(-1)?.id;
459
742
  captureHistory();
460
743
  renderGraph();
461
- selectNode(clone.id);
744
+ if (selectedId) selectNode(selectedId);
745
+ selectedIds = cloneIds;
746
+ updateSelection();
462
747
  validateDraft();
463
748
  }
464
749
 
750
+ function openContextualAdd(event) {
751
+ event.stopPropagation();
752
+ pendingConnectionSource = event.currentTarget.closest('.node').dataset.nodeId;
753
+ byId('library-panel').classList.add('open');
754
+ }
755
+
465
756
  function renderPalette() {
466
757
  byId('palette').innerHTML = catalog.nodeTypes.filter((node) => node.executable).map((node) => `
467
758
  <button class="palette-item" draggable="true" data-node-type="${escapeHtml(node.type)}">
@@ -478,15 +769,27 @@ function renderPalette() {
478
769
  }
479
770
 
480
771
  function beginNodeInteraction(event) {
481
- if (event.button !== 0 || event.target.closest('.port')) return;
772
+ if (event.button !== 0 || event.target.closest('.port,.output-add,.execute-pod,.node-title,.inline-rename')) return;
482
773
  event.stopPropagation();
483
774
  const element = event.currentTarget;
484
775
  const nodeId = element.dataset.nodeId;
485
- selectNode(nodeId);
776
+ if (event.shiftKey) {
777
+ selectNode(nodeId, { additive: true });
778
+ return;
779
+ }
780
+ if (!selectedIds.has(nodeId)) selectNode(nodeId);
486
781
  if (spacePressed) return beginPan(event);
487
782
  const world = screenToWorld(event.clientX, event.clientY);
488
783
  const position = positions.get(nodeId);
489
- interaction = { type: 'node', pointerId: event.pointerId, nodeId, element, offsetX: world.x - position.x, offsetY: world.y - position.y };
784
+ interaction = {
785
+ type: 'node',
786
+ pointerId: event.pointerId,
787
+ nodeId,
788
+ element,
789
+ offsetX: world.x - position.x,
790
+ offsetY: world.y - position.y,
791
+ origins: new Map([...selectedIds].map((id) => [id, { ...positions.get(id) }]))
792
+ };
490
793
  element.classList.add('dragging');
491
794
  element.setPointerCapture(event.pointerId);
492
795
  }
@@ -518,10 +821,20 @@ function handlePointerMove(event) {
518
821
  if (interaction.type === 'node') {
519
822
  const world = screenToWorld(event.clientX, event.clientY);
520
823
  const position = { x: world.x - interaction.offsetX, y: world.y - interaction.offsetY };
521
- positions.set(interaction.nodeId, position);
522
- interaction.element.style.left = `${position.x}px`;
523
- interaction.element.style.top = `${position.y}px`;
824
+ const origin = interaction.origins.get(interaction.nodeId);
825
+ const delta = { x: position.x - origin.x, y: position.y - origin.y };
826
+ interaction.origins.forEach((start, id) => {
827
+ const next = { x: start.x + delta.x, y: start.y + delta.y };
828
+ positions.set(id, next);
829
+ const nodeElement = document.querySelector(`.node[data-node-id="${CSS.escape(id)}"]`);
830
+ if (nodeElement) {
831
+ nodeElement.style.left = `${next.x}px`;
832
+ nodeElement.style.top = `${next.y}px`;
833
+ }
834
+ });
524
835
  renderEdges();
836
+ } else if (interaction.type === 'lasso') {
837
+ updateLasso(event);
525
838
  } else {
526
839
  viewport.x = interaction.viewportX + event.clientX - interaction.startX;
527
840
  viewport.y = interaction.viewportY + event.clientY - interaction.startY;
@@ -535,7 +848,7 @@ function finishPointer(event) {
535
848
  if (interaction.type === 'node') {
536
849
  interaction.element.classList.remove('dragging');
537
850
  captureHistory();
538
- }
851
+ } else if (interaction.type === 'lasso') finishLasso();
539
852
  interaction = null;
540
853
  saveLayoutSoon();
541
854
  }
@@ -565,15 +878,457 @@ function finishConnection(event) {
565
878
  const targetId = targetElement?.dataset.nodeId;
566
879
  if (!targetId || targetId === sourceId) return;
567
880
  const target = draft.nodes.find((node) => node.id === targetId);
568
- if ((target.dependsOn || []).includes(sourceId)) return notify('Nodes are already connected.');
881
+ if (draft.edges.some((edge) => edge.from === sourceId && edge.to === targetId)) return notify('Nodes are already connected.');
569
882
  if (transitivelyDependsOn(sourceId, targetId)) return notify('Connection rejected: it would create a cycle.');
570
- target.dependsOn = [...(target.dependsOn || []), sourceId];
883
+ draft.edges.push({ id: uniqueEdgeId(sourceId, targetId), from: sourceId, to: targetId });
884
+ syncDependencies();
571
885
  captureHistory();
572
886
  renderGraph();
573
887
  selectNode(targetId);
574
888
  validateDraft();
575
889
  }
576
890
 
891
+ function beginLasso(event) {
892
+ const start = screenToWorld(event.clientX, event.clientY);
893
+ interaction = { type: 'lasso', pointerId: event.pointerId, start, current: start, additive: event.shiftKey };
894
+ const marquee = byId('selection-marquee');
895
+ marquee.style.display = 'block';
896
+ marquee.style.left = `${start.x}px`;
897
+ marquee.style.top = `${start.y}px`;
898
+ marquee.style.width = '0';
899
+ marquee.style.height = '0';
900
+ byId('canvas').setPointerCapture(event.pointerId);
901
+ }
902
+
903
+ function updateLasso(event) {
904
+ interaction.current = screenToWorld(event.clientX, event.clientY);
905
+ const left = Math.min(interaction.start.x, interaction.current.x);
906
+ const top = Math.min(interaction.start.y, interaction.current.y);
907
+ const right = Math.max(interaction.start.x, interaction.current.x);
908
+ const bottom = Math.max(interaction.start.y, interaction.current.y);
909
+ const marquee = byId('selection-marquee');
910
+ Object.assign(marquee.style, {
911
+ left: `${left}px`, top: `${top}px`, width: `${right - left}px`, height: `${bottom - top}px`
912
+ });
913
+ const next = interaction.additive ? new Set(selectedIds) : new Set();
914
+ positions.forEach((position, id) => {
915
+ if (position.x < right && position.x + NODE_WIDTH > left && position.y < bottom && position.y + 110 > top) next.add(id);
916
+ });
917
+ selectedIds = next;
918
+ selectedId = [...next].at(-1) || null;
919
+ updateSelection();
920
+ }
921
+
922
+ function finishLasso() {
923
+ byId('selection-marquee').style.display = 'none';
924
+ const finalSelection = new Set(selectedIds);
925
+ if (selectedId) selectNode(selectedId);
926
+ selectedIds = finalSelection;
927
+ updateSelection();
928
+ }
929
+
930
+ function rootCandidates() {
931
+ if (!draft) return [];
932
+ const incoming = new Set(draft.edges.map((edge) => edge.to));
933
+ return draft.nodes.filter((node) => ROOT_TYPES.has(node.type) || !incoming.has(node.id));
934
+ }
935
+
936
+ async function executeFromTrigger(event) {
937
+ event.stopPropagation();
938
+ const candidates = rootCandidates();
939
+ if (candidates.length !== 1) return notify(`Execute requires exactly one trigger/root; found ${candidates.length}.`);
940
+ const task = event.currentTarget.closest('.execute-pod').querySelector('.task-input').value.trim();
941
+ if (task) byId('goal-task').value = task;
942
+ if (!goal.frozen || !activeRunId) {
943
+ byId('goal-dialog').showModal();
944
+ return notify('Save and freeze the Goal Contract before execution.');
945
+ }
946
+ try {
947
+ await api(`/api/runs/${encodeURIComponent(activeRunId)}/execute`, {
948
+ method: 'POST',
949
+ body: '{}'
950
+ });
951
+ notify('Local runtime started. External AI dispatch remains disabled.');
952
+ await refreshLive();
953
+ } catch (error) {
954
+ notify(error.message);
955
+ }
956
+ }
957
+
958
+ function parseGoalCriteria(value) {
959
+ return String(value || '').split('\n').map((line) => line.trim()).filter(Boolean).map((line, index) => {
960
+ const [statement, evidenceRequired, ...failures] = line.split('|').map((part) => part.trim());
961
+ return {
962
+ id: `AC-${index + 1}`,
963
+ statement,
964
+ evidenceRequired,
965
+ failureCases: failures.filter(Boolean)
966
+ };
967
+ });
968
+ }
969
+
970
+ function goalContractFromForm(runId) {
971
+ return {
972
+ schemaVersion: 1,
973
+ runId,
974
+ objective: byId('goal-text').value.trim(),
975
+ acceptanceCriteria: parseGoalCriteria(byId('goal-criteria').value)
976
+ };
977
+ }
978
+
979
+ function validateGoalForm(contract) {
980
+ if (!byId('goal-task').value.trim()) return 'Task is required.';
981
+ if (!contract.objective) return 'Goal objective is required.';
982
+ if (!contract.acceptanceCriteria.length) return 'Add at least one acceptance failure-table row.';
983
+ for (const criterion of contract.acceptanceCriteria) {
984
+ if (!criterion.statement || !criterion.evidenceRequired || !criterion.failureCases.length) {
985
+ return `${criterion.id} must contain statement | evidence required | failure case.`;
986
+ }
987
+ }
988
+ return '';
989
+ }
990
+
991
+ async function ensureStudioRun() {
992
+ if (activeRunId && catalog.live?.run && !['DELIVERED', 'REPORTED', 'ESCALATED'].includes(catalog.live.run.state)) {
993
+ return activeRunId;
994
+ }
995
+ const task = byId('goal-task').value.trim();
996
+ const created = await api('/api/runs', {
997
+ method: 'POST',
998
+ body: JSON.stringify({
999
+ task,
1000
+ displayName: byId('goal-run-name').value.trim(),
1001
+ recipeId: loadedRecipeId,
1002
+ mode: draft.compatibleModes.includes('ASSISTED') ? 'ASSISTED' : draft.compatibleModes[0]
1003
+ })
1004
+ });
1005
+ activeRunId = created.run.runId;
1006
+ await refreshLive();
1007
+ return activeRunId;
1008
+ }
1009
+
1010
+ async function saveGoalFromForm() {
1011
+ try {
1012
+ const provisional = goalContractFromForm(activeRunId || 'pending');
1013
+ const error = validateGoalForm(provisional);
1014
+ if (error) {
1015
+ byId('goal-validation').textContent = error;
1016
+ return null;
1017
+ }
1018
+ const runId = await ensureStudioRun();
1019
+ const contract = goalContractFromForm(runId);
1020
+ await api(`/api/runs/${encodeURIComponent(runId)}/goal`, {
1021
+ method: 'PUT',
1022
+ body: JSON.stringify({ goal: contract })
1023
+ });
1024
+ goal = { text: contract.objective, criteria: contract.acceptanceCriteria, version: goal.version, frozen: false };
1025
+ byId('goal-validation').textContent = '';
1026
+ notify('Goal draft saved. It is not frozen yet.');
1027
+ return contract;
1028
+ } catch (error) {
1029
+ byId('goal-validation').textContent = error.message;
1030
+ return null;
1031
+ }
1032
+ }
1033
+
1034
+ function renderGoalState() {
1035
+ const state = byId('goal-state');
1036
+ state.className = `goal-state ${goal.frozen ? 'frozen' : 'draft'}`;
1037
+ state.textContent = goal.frozen
1038
+ ? `Frozen · version ${goal.version} · editing locked`
1039
+ : `Draft · version ${goal.version} · editing allowed`;
1040
+ byId('goal-version').textContent = `V${goal.version}`;
1041
+ byId('goal-text').disabled = goal.frozen;
1042
+ byId('goal-criteria').disabled = goal.frozen;
1043
+ byId('goal-task').disabled = goal.frozen;
1044
+ byId('goal-run-name').disabled = goal.frozen;
1045
+ byId('save-goal').hidden = goal.frozen;
1046
+ byId('review-goal').hidden = goal.frozen;
1047
+ byId('confirm-freeze').hidden = true;
1048
+ byId('unfreeze-goal').hidden = !goal.frozen;
1049
+ }
1050
+
1051
+ async function reviewGoal() {
1052
+ const contract = await saveGoalFromForm();
1053
+ if (!contract) return;
1054
+ byId('goal-review').hidden = false;
1055
+ byId('goal-review').innerHTML = `
1056
+ <strong>${escapeHtml(contract.objective)}</strong>
1057
+ <p>${contract.acceptanceCriteria.length} numbered acceptance failure rows are ready.</p>
1058
+ `;
1059
+ byId('confirm-freeze').hidden = false;
1060
+ }
1061
+
1062
+ async function freezeGoalFromForm() {
1063
+ try {
1064
+ const result = await api(`/api/runs/${encodeURIComponent(activeRunId)}/goal/freeze`, {
1065
+ method: 'POST',
1066
+ body: JSON.stringify({ actor: 'studio-user' })
1067
+ });
1068
+ catalog.live = catalog.live || {};
1069
+ catalog.live.run = result.run;
1070
+ goal = {
1071
+ text: byId('goal-text').value.trim(),
1072
+ criteria: parseGoalCriteria(byId('goal-criteria').value),
1073
+ version: result.run.goal.version,
1074
+ frozen: true
1075
+ };
1076
+ renderGoalState();
1077
+ renderGraph();
1078
+ notify('Goal frozen with an integrity-bound version.');
1079
+ } catch (error) {
1080
+ byId('goal-validation').textContent = error.message;
1081
+ }
1082
+ }
1083
+
1084
+ async function unfreezeGoalFromForm() {
1085
+ const fields = byId('unfreeze-fields');
1086
+ if (fields.hidden) {
1087
+ fields.hidden = false;
1088
+ byId('unfreeze-reason').focus();
1089
+ return;
1090
+ }
1091
+ try {
1092
+ const result = await api(`/api/runs/${encodeURIComponent(activeRunId)}/goal/unfreeze`, {
1093
+ method: 'POST',
1094
+ body: JSON.stringify({ actor: 'studio-user', reason: byId('unfreeze-reason').value })
1095
+ });
1096
+ goal.frozen = false;
1097
+ goal.version = result.run.goal.version;
1098
+ fields.hidden = true;
1099
+ renderGoalState();
1100
+ renderGraph();
1101
+ notify('Goal unfrozen. Previous evidence remains bound to its prior version.');
1102
+ } catch (error) {
1103
+ byId('goal-validation').textContent = error.message;
1104
+ }
1105
+ }
1106
+
1107
+ function syncGoalFromLive() {
1108
+ const liveGoal = catalog.live?.run?.goal;
1109
+ activeRunId = catalog.live?.run?.runId || null;
1110
+ if (!liveGoal) return;
1111
+ goal.version = liveGoal.version || 1;
1112
+ goal.frozen = liveGoal.frozen === true;
1113
+ if (catalog.live.run.task) byId('goal-task').value = catalog.live.run.task;
1114
+ if (catalog.live.run.displayName) byId('goal-run-name').value = catalog.live.run.displayName;
1115
+ renderGoalState();
1116
+ }
1117
+
1118
+ async function hydrateGoalFromLive() {
1119
+ const run = catalog.live?.run;
1120
+ const artifactPath = run?.artifacts?.goalContract?.path;
1121
+ const key = `${run?.runId || ''}:${run?.goal?.version || 1}:${artifactPath || ''}`;
1122
+ if (!artifactPath || hydratedGoalKey === key) return;
1123
+ try {
1124
+ const result = await api(`/api/runs/${encodeURIComponent(run.runId)}/artifacts?path=${encodeURIComponent(artifactPath)}`);
1125
+ const contract = JSON.parse(result.artifact.content);
1126
+ byId('goal-text').value = contract.objective || '';
1127
+ byId('goal-criteria').value = (contract.acceptanceCriteria || []).map((criterion) => (
1128
+ `${criterion.statement} | ${criterion.evidenceRequired} | ${(criterion.failureCases || []).join(' | ')}`
1129
+ )).join('\n');
1130
+ goal.text = contract.objective || '';
1131
+ goal.criteria = contract.acceptanceCriteria || [];
1132
+ hydratedGoalKey = key;
1133
+ } catch {
1134
+ // The Goal remains inspectable through Run History if its bounded artifact cannot be hydrated.
1135
+ }
1136
+ }
1137
+
1138
+ async function loadRuns() {
1139
+ const query = byId('run-search').value.trim();
1140
+ try {
1141
+ const params = new URLSearchParams();
1142
+ if (query) params.set('q', query);
1143
+ if (byId('run-status').value) params.set('status', byId('run-status').value);
1144
+ if (byId('run-mode').value) params.set('mode', byId('run-mode').value);
1145
+ if (byId('run-from').value) params.set('from', `${byId('run-from').value}T00:00:00.000Z`);
1146
+ if (byId('run-to').value) params.set('to', `${byId('run-to').value}T23:59:59.999Z`);
1147
+ const result = await api(`/api/runs${params.size ? `?${params}` : ''}`);
1148
+ runs = result.runs;
1149
+ const list = byId('run-list');
1150
+ if (!runs.length) {
1151
+ list.innerHTML = '<div class="empty-state"><h2>No runs found</h2><p>Create a task from the workflow trigger.</p></div>';
1152
+ } else {
1153
+ list.innerHTML = runs.map((run) => `
1154
+ <button class="run-row" data-run-id="${escapeHtml(run.runId)}">
1155
+ <strong>${escapeHtml(run.displayName)}</strong>
1156
+ <span>${escapeHtml(run.status)} · ${escapeHtml(new Date(run.updatedAt).toLocaleString())}</span>
1157
+ <small>${escapeHtml(run.task)}</small>
1158
+ </button>
1159
+ `).join('');
1160
+ list.querySelectorAll('.run-row').forEach((button) => {
1161
+ button.onclick = () => loadRunDetail(button.dataset.runId);
1162
+ });
1163
+ }
1164
+ if (result.corrupt.length) {
1165
+ list.insertAdjacentHTML('beforeend', `<p class="validation-message">${result.corrupt.length} corrupt run record(s) were isolated.</p>`);
1166
+ }
1167
+ } catch (error) {
1168
+ byId('run-list').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1169
+ }
1170
+ }
1171
+
1172
+ async function loadRunDetail(runId) {
1173
+ try {
1174
+ const result = await api(`/api/runs/${encodeURIComponent(runId)}`);
1175
+ const run = result.run;
1176
+ const artifacts = Object.values(run.artifacts || {});
1177
+ byId('run-detail').innerHTML = `
1178
+ <header><small>${escapeHtml(run.status)} · ${escapeHtml(run.mode)}</small><h2>${escapeHtml(run.displayName)}</h2><p>${escapeHtml(run.task)}</p></header>
1179
+ <div class="run-name-editor"><label for="run-name-edit">Display Name</label><input id="run-name-edit" maxlength="100" value="${escapeHtml(run.displayName)}"><button id="save-run-name">Rename</button></div>
1180
+ <dl><dt>Technical ID</dt><dd>${escapeHtml(run.runId)}</dd><dt>Goal</dt><dd>${run.goalFrozen ? `Frozen V${escapeHtml(run.goalVersion)}` : 'Not frozen'}</dd><dt>Evidence</dt><dd>${run.evidence.present ? 'Present' : 'Absent'}</dd></dl>
1181
+ <h3>Artifacts</h3>
1182
+ <div class="artifact-list">${artifacts.length ? artifacts.map((artifact) => (
1183
+ artifact?.path ? `<button data-artifact="${escapeHtml(artifact.path)}">${escapeHtml(artifact.path)}</button>` : ''
1184
+ )).join('') : '<p class="muted">No artifacts recorded.</p>'}</div>
1185
+ <h3>Decisions</h3>
1186
+ <div class="decision-list">${run.decisions?.length ? run.decisions.map((decision) => `<p><strong>${escapeHtml(decision.summary)}</strong><br><span class="muted">${escapeHtml(decision.rationale)}</span></p>`).join('') : '<p class="muted">No decisions recorded.</p>'}</div>
1187
+ <h3>Timeline</h3>
1188
+ <div class="timeline">${[...(run.history || []), ...(run.events || [])].sort((left, right) => String(right.at).localeCompare(String(left.at))).map((event) => `<p><time>${escapeHtml(event.at || '')}</time><strong>${escapeHtml(event.type || event.gate || event.to || 'event')}</strong>${escapeHtml(event.reason || event.changedNodes?.join(', ') || '')}</p>`).join('')}</div>
1189
+ <pre id="artifact-content" hidden></pre>
1190
+ `;
1191
+ byId('save-run-name').onclick = async () => {
1192
+ try {
1193
+ await api('/api/run/name', {
1194
+ method: 'PATCH',
1195
+ body: JSON.stringify({
1196
+ runId,
1197
+ displayName: byId('run-name-edit').value,
1198
+ actor: 'studio-user'
1199
+ })
1200
+ });
1201
+ await Promise.all([loadRuns(), loadRunDetail(runId)]);
1202
+ } catch (error) {
1203
+ notify(error.message);
1204
+ }
1205
+ };
1206
+ byId('run-detail').querySelectorAll('[data-artifact]').forEach((button) => {
1207
+ button.onclick = async () => {
1208
+ try {
1209
+ const artifactResult = await api(`/api/runs/${encodeURIComponent(runId)}/artifacts?path=${encodeURIComponent(button.dataset.artifact)}`);
1210
+ const output = byId('artifact-content');
1211
+ output.hidden = false;
1212
+ output.textContent = artifactResult.artifact.content;
1213
+ } catch (error) {
1214
+ notify(error.message);
1215
+ }
1216
+ };
1217
+ });
1218
+ } catch (error) {
1219
+ byId('run-detail').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1220
+ }
1221
+ }
1222
+
1223
+ function showWorkspace(section) {
1224
+ const showingRuns = section === 'runs';
1225
+ byId('runs-view').hidden = !showingRuns;
1226
+ byId('canvas').hidden = showingRuns;
1227
+ byId('workflow-context').hidden = showingRuns;
1228
+ byId('review').hidden = showingRuns;
1229
+ byId('show-runs').classList.toggle('active', showingRuns);
1230
+ byId('show-runs').setAttribute('aria-current', showingRuns ? 'page' : 'false');
1231
+ byId('show-workflows').classList.toggle('active', !showingRuns);
1232
+ byId('show-workflows').setAttribute('aria-current', showingRuns ? 'false' : 'page');
1233
+ if (showingRuns) loadRuns();
1234
+ }
1235
+
1236
+ async function previewImport() {
1237
+ try {
1238
+ const importedRecipe = JSON.parse(byId('import-source').value);
1239
+ const result = await api('/api/import/preview', {
1240
+ method: 'POST',
1241
+ body: JSON.stringify({ existingRecipe: draft, importedRecipe, operation: 'merge' })
1242
+ });
1243
+ pendingImport = { importedRecipe, mergePlan: result.plan };
1244
+ byId('import-preview').innerHTML = `
1245
+ <strong>${escapeHtml(importedRecipe.id || 'Imported workflow')}</strong>
1246
+ <p>${escapeHtml(importedRecipe.nodes?.length || 0)} nodes · ${escapeHtml(importedRecipe.edges?.length || 0)} explicit Edges</p>
1247
+ <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>
1248
+ `;
1249
+ byId('import-choices').hidden = false;
1250
+ } catch (error) {
1251
+ pendingImport = null;
1252
+ byId('import-choices').hidden = true;
1253
+ byId('import-preview').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1254
+ }
1255
+ }
1256
+
1257
+ async function applyImport(operation) {
1258
+ if (!pendingImport) return;
1259
+ try {
1260
+ const plan = operation === 'merge'
1261
+ ? pendingImport.mergePlan
1262
+ : { operation: 'replace', nodeIdMap: {}, edgeIdMap: {} };
1263
+ const result = await api('/api/import/apply', {
1264
+ method: 'POST',
1265
+ body: JSON.stringify({
1266
+ existingRecipe: draft,
1267
+ importedRecipe: pendingImport.importedRecipe,
1268
+ plan
1269
+ })
1270
+ });
1271
+ draft = normalizeDraftGraph(structuredClone(result.recipe));
1272
+ positions = new Map();
1273
+ ensurePositions();
1274
+ selectedIds.clear();
1275
+ selectedId = null;
1276
+ captureHistory();
1277
+ renderGraph();
1278
+ renderRecipeDetails();
1279
+ validateDraft();
1280
+ byId('import-dialog').close();
1281
+ notify(`${operation === 'merge' ? 'Merged' : 'Replaced'} canvas from validated JSON.`);
1282
+ } catch (error) {
1283
+ byId('import-preview').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1284
+ }
1285
+ }
1286
+
1287
+ function exportWorkflowJson() {
1288
+ const blob = new Blob([`${JSON.stringify(authoringRecipe(), null, 2)}\n`], { type: 'application/json' });
1289
+ const link = document.createElement('a');
1290
+ link.href = URL.createObjectURL(blob);
1291
+ link.download = `${draft.id}.workflow.json`;
1292
+ link.click();
1293
+ URL.revokeObjectURL(link.href);
1294
+ }
1295
+
1296
+ function createCustomAgentFromForm(event) {
1297
+ event.preventDefault();
1298
+ const id = uniqueNodeId('agent');
1299
+ const name = byId('custom-name').value.trim();
1300
+ const prompt = byId('custom-prompt').value.trim();
1301
+ const error = validDisplayName(name);
1302
+ if (error || !prompt) return notify(error || 'Custom Agent prompt is required.');
1303
+ const artifact = byId('custom-output').value.trim() || `${id}-report`;
1304
+ const node = {
1305
+ id,
1306
+ type: 'agent',
1307
+ displayName: name,
1308
+ prompt,
1309
+ capabilityRefs: csv(byId('custom-capabilities').value),
1310
+ mcpRefs: csv(byId('custom-mcp').value),
1311
+ inputArtifacts: csv(byId('custom-inputs').value),
1312
+ outputArtifacts: [{ artifact, schema: 'schemas/report.schema.json' }],
1313
+ tokenLimit: Number(byId('custom-tokens').value),
1314
+ timeoutMs: Number(byId('custom-timeout').value) * 1000,
1315
+ retry: { maxAttempts: Number(byId('custom-retries').value), backoffMs: 1000 }
1316
+ };
1317
+ draft.nodes.push(node);
1318
+ if (pendingConnectionSource) {
1319
+ draft.edges.push({ id: uniqueEdgeId(pendingConnectionSource, id), from: pendingConnectionSource, to: id });
1320
+ pendingConnectionSource = null;
1321
+ }
1322
+ syncDependencies();
1323
+ const center = worldAtCanvasCenter();
1324
+ positions.set(id, { x: center.x - NODE_WIDTH / 2, y: center.y - NODE_PORT_Y });
1325
+ captureHistory();
1326
+ renderGraph();
1327
+ selectNode(id);
1328
+ validateDraft();
1329
+ byId('custom-dialog').close();
1330
+ }
1331
+
577
1332
  function zoomAt(nextScale, clientX, clientY) {
578
1333
  const scale = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, nextScale));
579
1334
  const rect = byId('canvas').getBoundingClientRect();
@@ -730,6 +1485,8 @@ async function refreshLive() {
730
1485
  try {
731
1486
  const result = await api('/api/live');
732
1487
  catalog.live = result.live;
1488
+ syncGoalFromLive();
1489
+ await hydrateGoalFromLive();
733
1490
  renderLive();
734
1491
  } catch {
735
1492
  // A transient refresh failure must not discard the draft.
@@ -742,10 +1499,12 @@ async function loadRecipe() {
742
1499
  api(`/api/recipe?id=${encodeURIComponent(id)}`),
743
1500
  api(`/api/layout?id=${encodeURIComponent(id)}`)
744
1501
  ]);
745
- draft = structuredClone(result.recipe);
1502
+ draft = normalizeDraftGraph(structuredClone(result.recipe));
746
1503
  source = result.source;
747
1504
  loadedRecipeId = draft.id;
748
1505
  selectedId = null;
1506
+ selectedIds.clear();
1507
+ selectedEdgeId = null;
749
1508
  byId('inspector-panel').classList.remove('open');
750
1509
  positions = new Map(Object.entries(saved.layout?.positions || {}));
751
1510
  ensurePositions();
@@ -765,6 +1524,7 @@ async function refreshCatalog(selectedRecipe) {
765
1524
  )).join('');
766
1525
  if (selectedRecipe && catalog.recipes.some((recipe) => recipe.id === selectedRecipe)) selector.value = selectedRecipe;
767
1526
  renderPalette();
1527
+ syncGoalFromLive();
768
1528
  renderLive();
769
1529
  }
770
1530
 
@@ -773,10 +1533,12 @@ function bindCanvas() {
773
1533
  canvas.addEventListener('pointerdown', (event) => {
774
1534
  if (event.target === canvas || event.target === byId('scene') || event.target === byId('nodes') || event.target === byId('edges')) {
775
1535
  selectedId = null;
1536
+ if (!event.shiftKey) selectedIds.clear();
776
1537
  updateSelection();
777
1538
  renderRecipeDetails();
778
1539
  byId('inspector-panel').classList.remove('open');
779
- beginPan(event);
1540
+ if (event.button === 1 || spacePressed) beginPan(event);
1541
+ else if (event.button === 0) beginLasso(event);
780
1542
  }
781
1543
  });
782
1544
  canvas.addEventListener('pointermove', handlePointerMove);
@@ -821,7 +1583,15 @@ document.addEventListener('keydown', (event) => {
821
1583
  } else if (modifier && event.key.toLowerCase() === 'y') {
822
1584
  event.preventDefault();
823
1585
  restoreHistory(historyIndex + 1);
824
- } else if ((event.key === 'Delete' || event.key === 'Backspace') && selectedId) {
1586
+ } else if (modifier && event.key.toLowerCase() === 'a' && byId('canvas').contains(document.activeElement)) {
1587
+ event.preventDefault();
1588
+ selectedIds = new Set(draft.nodes.map((node) => node.id));
1589
+ selectedId = [...selectedIds].at(-1) || null;
1590
+ updateSelection();
1591
+ } else if ((event.key === 'Delete' || event.key === 'Backspace') && selectedEdgeId) {
1592
+ event.preventDefault();
1593
+ deleteEdge(selectedEdgeId);
1594
+ } else if ((event.key === 'Delete' || event.key === 'Backspace') && selectedIds.size) {
825
1595
  event.preventDefault();
826
1596
  deleteSelectedNode();
827
1597
  }
@@ -909,8 +1679,35 @@ async function initialize() {
909
1679
  byId('recipe').onchange = loadRecipe;
910
1680
  bindCanvas();
911
1681
  byId('toggle-library').onclick = () => byId('library-panel').classList.toggle('open');
912
- byId('quick-add').onclick = () => byId('library-panel').classList.add('open');
913
1682
  byId('close-library').onclick = () => byId('library-panel').classList.remove('open');
1683
+ byId('show-workflows').onclick = () => showWorkspace('workflows');
1684
+ byId('show-runs').onclick = () => showWorkspace('runs');
1685
+ byId('run-search').oninput = loadRuns;
1686
+ for (const id of ['run-status', 'run-mode', 'run-from', 'run-to']) byId(id).onchange = loadRuns;
1687
+ byId('import-json').onclick = () => byId('import-dialog').showModal();
1688
+ byId('export-json').onclick = exportWorkflowJson;
1689
+ byId('preview-import').onclick = previewImport;
1690
+ byId('import-file').onchange = async (event) => {
1691
+ const [file] = event.currentTarget.files;
1692
+ if (file) byId('import-source').value = await file.text();
1693
+ };
1694
+ byId('merge-import').onclick = () => applyImport('merge');
1695
+ byId('replace-import').onclick = () => applyImport('replace');
1696
+ byId('create-custom').onclick = () => byId('custom-dialog').showModal();
1697
+ byId('custom-form').onsubmit = createCustomAgentFromForm;
1698
+ byId('open-goal').onclick = () => {
1699
+ renderGoalState();
1700
+ byId('goal-dialog').showModal();
1701
+ };
1702
+ byId('save-goal').onclick = saveGoalFromForm;
1703
+ byId('review-goal').onclick = reviewGoal;
1704
+ byId('confirm-freeze').onclick = freezeGoalFromForm;
1705
+ byId('unfreeze-goal').onclick = unfreezeGoalFromForm;
1706
+ byId('duplicate-selection').onclick = duplicateSelectedNode;
1707
+ byId('delete-selection').onclick = deleteSelectedNode;
1708
+ document.querySelectorAll('[data-close]').forEach((button) => {
1709
+ button.onclick = () => byId(button.dataset.close).close();
1710
+ });
914
1711
  byId('workflow-settings').onclick = () => {
915
1712
  selectedId = null;
916
1713
  updateSelection();