ai-engineering-loop 1.8.1 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/studio/app.js CHANGED
@@ -33,6 +33,7 @@ let goal = { text: '', version: 1, frozen: false };
33
33
  let activeRunId;
34
34
  let pendingImport;
35
35
  let hydratedGoalKey;
36
+ let selectedCheckoutRun;
36
37
 
37
38
  const DISPLAY_NAME_MAX = 80;
38
39
  const ROOT_TYPES = new Set(['goal-contract', 'trigger']);
@@ -75,6 +76,7 @@ function normalizeDraftGraph(recipe) {
75
76
  used.add(id);
76
77
  return { ...edge, id };
77
78
  });
79
+ recipe.loopGroups = Array.isArray(recipe.loopGroups) ? recipe.loopGroups : [];
78
80
  syncDependencies(recipe);
79
81
  return recipe;
80
82
  }
@@ -200,6 +202,72 @@ function edgePath(from, to) {
200
202
  return `M${startX} ${startY} C${startX + bend} ${startY},${endX - bend} ${endY},${endX} ${endY}`;
201
203
  }
202
204
 
205
+ function loopBounds(loopGroup) {
206
+ const points = loopGroup.nodeIds.map((nodeId) => positions.get(nodeId)).filter(Boolean);
207
+ if (!points.length) return null;
208
+ const padding = 44;
209
+ const left = Math.min(...points.map((point) => point.x)) - padding;
210
+ const top = Math.min(...points.map((point) => point.y)) - padding;
211
+ const right = Math.max(...points.map((point) => point.x + NODE_WIDTH)) + padding;
212
+ const bottom = Math.max(...points.map((point) => point.y + 108)) + padding;
213
+ return { left, top, right, bottom, width: right - left, height: bottom - top };
214
+ }
215
+
216
+ function renderLoopGroups() {
217
+ const container = byId('loop-groups');
218
+ container.innerHTML = '';
219
+ for (const loopGroup of draft?.loopGroups || []) {
220
+ const bounds = loopBounds(loopGroup);
221
+ if (!bounds) continue;
222
+ const runtime = catalog.live?.loopGroups?.[loopGroup.id];
223
+ const element = document.createElement('section');
224
+ element.className = `loop-group ${runtime?.status?.toLowerCase() || 'draft'}`;
225
+ element.style.left = `${bounds.left}px`;
226
+ element.style.top = `${bounds.top}px`;
227
+ element.style.width = `${bounds.width}px`;
228
+ element.style.height = `${bounds.height}px`;
229
+ element.innerHTML = `
230
+ <header>
231
+ <span><b>${escapeHtml(loopGroup.displayName)}</b><small>ITERATION ${escapeHtml(runtime?.iteration || 1)} / ${escapeHtml(loopGroup.maxIterations)}</small></span>
232
+ <button type="button" aria-label="Remove ${escapeHtml(loopGroup.displayName)} group">Ungroup</button>
233
+ </header>
234
+ `;
235
+ element.querySelector('button').onclick = (event) => {
236
+ event.stopPropagation();
237
+ draft.loopGroups = draft.loopGroups.filter((candidate) => candidate.id !== loopGroup.id);
238
+ captureHistory();
239
+ renderGraph();
240
+ validateDraft();
241
+ };
242
+ element.querySelector('header').onpointerdown = (event) => {
243
+ if (event.button !== 0 || event.target.closest('button')) return;
244
+ event.preventDefault();
245
+ event.stopPropagation();
246
+ const world = screenToWorld(event.clientX, event.clientY);
247
+ interaction = {
248
+ type: 'group',
249
+ pointerId: event.pointerId,
250
+ groupId: loopGroup.id,
251
+ start: world,
252
+ element: byId('canvas'),
253
+ origins: new Map(loopGroup.nodeIds.map((nodeId) => [nodeId, { ...positions.get(nodeId) }]))
254
+ };
255
+ selectedIds = new Set(loopGroup.nodeIds);
256
+ selectedId = loopGroup.decisionNodeId;
257
+ updateSelection();
258
+ byId('canvas').setPointerCapture(event.pointerId);
259
+ };
260
+ container.append(element);
261
+ }
262
+ }
263
+
264
+ function edgeLoopLabel(edge) {
265
+ const loopGroup = (draft.loopGroups || []).find((candidate) =>
266
+ candidate.decisionNodeId === edge.from && candidate.exitTargetId === edge.to
267
+ );
268
+ return loopGroup ? loopGroup.exitLabel : '';
269
+ }
270
+
203
271
  function stageLabel(node, index) {
204
272
  const stages = {
205
273
  'goal-contract': 'STAGE 01',
@@ -261,7 +329,36 @@ function renderEdges() {
261
329
  };
262
330
  control.onpointerleave = () => control.classList.remove('visible');
263
331
  controls.append(control);
332
+ const label = edgeLoopLabel(edge);
333
+ if (label) {
334
+ const badge = document.createElement('span');
335
+ badge.className = 'edge-label';
336
+ badge.style.left = `${midpoint.x}px`;
337
+ badge.style.top = `${midpoint.y - 22}px`;
338
+ badge.textContent = label;
339
+ controls.append(badge);
340
+ }
264
341
  });
342
+ for (const loopGroup of draft.loopGroups || []) {
343
+ const from = positions.get(loopGroup.decisionNodeId);
344
+ const to = positions.get(loopGroup.repeatTargetId);
345
+ const bounds = loopBounds(loopGroup);
346
+ if (!from || !to || !bounds) continue;
347
+ const returnPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
348
+ returnPath.setAttribute(
349
+ 'd',
350
+ `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}`
351
+ );
352
+ returnPath.setAttribute('class', 'edge loop-return');
353
+ returnPath.setAttribute('marker-end', 'url(#arrow)');
354
+ group.append(returnPath);
355
+ const label = document.createElement('span');
356
+ label.className = 'edge-label loop-label';
357
+ label.style.left = `${bounds.right + 28}px`;
358
+ label.style.top = `${bounds.top - 18}px`;
359
+ label.textContent = loopGroup.repeatLabel;
360
+ controls.append(label);
361
+ }
265
362
  }
266
363
 
267
364
  function nodeMarkup(node, index) {
@@ -283,6 +380,7 @@ function nodeMarkup(node, index) {
283
380
 
284
381
  function renderGraph() {
285
382
  ensurePositions();
383
+ renderLoopGroups();
286
384
  const container = byId('nodes');
287
385
  container.innerHTML = '';
288
386
  draft.nodes.forEach((node, index) => {
@@ -331,6 +429,11 @@ function updateSelection() {
331
429
  const actions = byId('selection-actions');
332
430
  actions.hidden = selectedIds.size < 2;
333
431
  byId('selection-count').textContent = `${selectedIds.size} nodes`;
432
+ const grouped = [...selectedIds].some((nodeId) =>
433
+ (draft?.loopGroups || []).some((group) => group.nodeIds.includes(nodeId))
434
+ );
435
+ byId('create-loop-group').disabled = grouped;
436
+ byId('create-loop-group').title = grouped ? 'Ungroup selected steps before creating another Loop Group' : '';
334
437
  }
335
438
 
336
439
  function renderRecipeDetails() {
@@ -650,6 +753,13 @@ function applyNodeDetails() {
650
753
  function deleteSelectedNode() {
651
754
  if (!selectedIds.size) return;
652
755
  const removed = new Set(selectedIds);
756
+ const containingGroup = (draft.loopGroups || []).find((group) =>
757
+ group.nodeIds.some((nodeId) => removed.has(nodeId))
758
+ );
759
+ if (containingGroup) {
760
+ notify(`Ungroup “${containingGroup.displayName}” before deleting its steps.`);
761
+ return;
762
+ }
653
763
  draft.nodes = draft.nodes.filter((node) => !removed.has(node.id));
654
764
  draft.edges = draft.edges.filter((edge) => !removed.has(edge.from) && !removed.has(edge.to));
655
765
  syncDependencies();
@@ -833,6 +943,13 @@ function handlePointerMove(event) {
833
943
  }
834
944
  });
835
945
  renderEdges();
946
+ } else if (interaction.type === 'group') {
947
+ const world = screenToWorld(event.clientX, event.clientY);
948
+ const delta = { x: world.x - interaction.start.x, y: world.y - interaction.start.y };
949
+ interaction.origins.forEach((start, id) => {
950
+ positions.set(id, { x: start.x + delta.x, y: start.y + delta.y });
951
+ });
952
+ renderGraph();
836
953
  } else if (interaction.type === 'lasso') {
837
954
  updateLasso(event);
838
955
  } else {
@@ -845,7 +962,7 @@ function handlePointerMove(event) {
845
962
  function finishPointer(event) {
846
963
  if (connection && connection.pointerId === event.pointerId) return finishConnection(event);
847
964
  if (!interaction || interaction.pointerId !== event.pointerId) return;
848
- if (interaction.type === 'node') {
965
+ if (interaction.type === 'node' || interaction.type === 'group') {
849
966
  interaction.element.classList.remove('dragging');
850
967
  captureHistory();
851
968
  } else if (interaction.type === 'lasso') finishLasso();
@@ -997,6 +1114,7 @@ async function ensureStudioRun() {
997
1114
  method: 'POST',
998
1115
  body: JSON.stringify({
999
1116
  task,
1117
+ constraints: byId('goal-constraints').value.trim(),
1000
1118
  displayName: byId('goal-run-name').value.trim(),
1001
1119
  recipeId: loadedRecipeId,
1002
1120
  mode: draft.compatibleModes.includes('ASSISTED') ? 'ASSISTED' : draft.compatibleModes[0]
@@ -1009,6 +1127,14 @@ async function ensureStudioRun() {
1009
1127
 
1010
1128
  async function saveGoalFromForm() {
1011
1129
  try {
1130
+ const task = byId('goal-task').value.trim();
1131
+ if (!byId('goal-text').value.trim()) byId('goal-text').value = task;
1132
+ if (!byId('goal-criteria').value.trim()) {
1133
+ byId('goal-criteria').value = [
1134
+ 'Requested outcome works in its real workflow | Tests and Run-bound evidence demonstrate the result | The requested outcome is unavailable or misleading',
1135
+ 'Existing behavior remains reliable | Compatibility checks pass | A supported existing workflow regresses'
1136
+ ].join('\n');
1137
+ }
1012
1138
  const provisional = goalContractFromForm(activeRunId || 'pending');
1013
1139
  const error = validateGoalForm(provisional);
1014
1140
  if (error) {
@@ -1024,6 +1150,7 @@ async function saveGoalFromForm() {
1024
1150
  goal = { text: contract.objective, criteria: contract.acceptanceCriteria, version: goal.version, frozen: false };
1025
1151
  byId('goal-validation').textContent = '';
1026
1152
  notify('Goal draft saved. It is not frozen yet.');
1153
+ byId('goal-dialog').close();
1027
1154
  return contract;
1028
1155
  } catch (error) {
1029
1156
  byId('goal-validation').textContent = error.message;
@@ -1041,6 +1168,7 @@ function renderGoalState() {
1041
1168
  byId('goal-text').disabled = goal.frozen;
1042
1169
  byId('goal-criteria').disabled = goal.frozen;
1043
1170
  byId('goal-task').disabled = goal.frozen;
1171
+ byId('goal-constraints').disabled = goal.frozen;
1044
1172
  byId('goal-run-name').disabled = goal.frozen;
1045
1173
  byId('save-goal').hidden = goal.frozen;
1046
1174
  byId('review-goal').hidden = goal.frozen;
@@ -1051,6 +1179,8 @@ function renderGoalState() {
1051
1179
  async function reviewGoal() {
1052
1180
  const contract = await saveGoalFromForm();
1053
1181
  if (!contract) return;
1182
+ byId('goal-dialog').showModal();
1183
+ byId('goal-dialog').querySelector('.advanced-goal').open = true;
1054
1184
  byId('goal-review').hidden = false;
1055
1185
  byId('goal-review').innerHTML = `
1056
1186
  <strong>${escapeHtml(contract.objective)}</strong>
@@ -1076,6 +1206,7 @@ async function freezeGoalFromForm() {
1076
1206
  renderGoalState();
1077
1207
  renderGraph();
1078
1208
  notify('Goal frozen with an integrity-bound version.');
1209
+ byId('goal-dialog').close();
1079
1210
  } catch (error) {
1080
1211
  byId('goal-validation').textContent = error.message;
1081
1212
  }
@@ -1099,6 +1230,7 @@ async function unfreezeGoalFromForm() {
1099
1230
  renderGoalState();
1100
1231
  renderGraph();
1101
1232
  notify('Goal unfrozen. Previous evidence remains bound to its prior version.');
1233
+ byId('goal-dialog').close();
1102
1234
  } catch (error) {
1103
1235
  byId('goal-validation').textContent = error.message;
1104
1236
  }
@@ -1111,6 +1243,7 @@ function syncGoalFromLive() {
1111
1243
  goal.version = liveGoal.version || 1;
1112
1244
  goal.frozen = liveGoal.frozen === true;
1113
1245
  if (catalog.live.run.task) byId('goal-task').value = catalog.live.run.task;
1246
+ if (catalog.live.run.constraints) byId('goal-constraints').value = catalog.live.run.constraints;
1114
1247
  if (catalog.live.run.displayName) byId('goal-run-name').value = catalog.live.run.displayName;
1115
1248
  renderGoalState();
1116
1249
  }
@@ -1171,52 +1304,167 @@ async function loadRuns() {
1171
1304
 
1172
1305
  async function loadRunDetail(runId) {
1173
1306
  try {
1174
- const result = await api(`/api/runs/${encodeURIComponent(runId)}`);
1307
+ selectedCheckoutRun = runId;
1308
+ const [result, checkoutResult, interactionResult] = await Promise.all([
1309
+ api(`/api/runs/${encodeURIComponent(runId)}`),
1310
+ api(`/api/runs/${encodeURIComponent(runId)}/checkout`),
1311
+ api(`/api/runs/${encodeURIComponent(runId)}/interactions`)
1312
+ ]);
1175
1313
  const run = result.run;
1176
- const artifacts = Object.values(run.artifacts || {});
1314
+ const checkout = checkoutResult.checkout;
1315
+ const maxX = Math.max(...checkout.nodes.map((node) => node.position.x), 0) + NODE_WIDTH + 80;
1316
+ const maxY = Math.max(...checkout.nodes.map((node) => node.position.y), 0) + 180;
1317
+ const paths = checkout.edges.map((edge) => {
1318
+ const from = checkout.nodes.find((node) => node.id === edge.from);
1319
+ const to = checkout.nodes.find((node) => node.id === edge.to);
1320
+ if (!from || !to) return '';
1321
+ const x1 = from.position.x + NODE_WIDTH;
1322
+ const y1 = from.position.y + NODE_PORT_Y;
1323
+ const x2 = to.position.x;
1324
+ const y2 = to.position.y + NODE_PORT_Y;
1325
+ return `<path d="M ${x1} ${y1} C ${x1 + 70} ${y1}, ${x2 - 70} ${y2}, ${x2} ${y2}"></path>`;
1326
+ }).join('');
1327
+ const checkoutGroups = (checkout.loopGroups || []).map((group) => {
1328
+ const members = checkout.nodes.filter((node) => group.nodeIds.includes(node.id));
1329
+ if (!members.length) return '';
1330
+ const left = Math.min(...members.map((node) => node.position.x)) - 28;
1331
+ const top = Math.min(...members.map((node) => node.position.y)) - 36;
1332
+ const right = Math.max(...members.map((node) => node.position.x + NODE_WIDTH)) + 28;
1333
+ const bottom = Math.max(...members.map((node) => node.position.y + 108)) + 28;
1334
+ return `<div class="checkout-loop status-${escapeHtml((group.runtime?.status || 'pending').toLowerCase())}" 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>`;
1335
+ }).join('');
1177
1336
  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>
1337
+ <header class="checkout-header">
1338
+ <div><button id="checkout-back" class="quiet">← Run History</button><small>READ-ONLY CHECKOUT · ${escapeHtml(run.status)}</small><h2>${escapeHtml(run.displayName)}</h2><p>${escapeHtml(run.task)}</p></div>
1339
+ <div class="checkout-actions"><button id="copy-agent-handoff">Copy for AI Agent</button><button id="duplicate-run-workflow" class="primary">Duplicate as Workflow</button></div>
1340
+ </header>
1341
+ <div class="checkout-meta"><span>${escapeHtml(run.runId)}</span><span>${run.goalFrozen ? `Goal frozen V${escapeHtml(run.goalVersion)}` : 'Goal draft'}</span><span>Actual node states</span></div>
1342
+ <section class="checkout-canvas" style="--checkout-width:${maxX}px;--checkout-height:${maxY}px">
1343
+ <svg viewBox="0 0 ${maxX} ${maxY}" aria-hidden="true">${paths}</svg>
1344
+ ${checkoutGroups}
1345
+ ${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">
1346
+ <small>${escapeHtml(node.type)}${node.loopIteration ? ` · LOOP ${escapeHtml(node.loopIteration)}` : ''}</small><strong>${escapeHtml(node.displayName)}</strong><span>${escapeHtml(node.status)}</span>
1347
+ </button>`).join('')}
1348
+ </section>
1349
+ <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>
1350
+ <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>
1190
1351
  `;
1191
- byId('save-run-name').onclick = async () => {
1352
+ renderInteractions(interactionResult.interactions);
1353
+ byId('checkout-back').onclick = () => {
1354
+ selectedCheckoutRun = null;
1355
+ 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>';
1356
+ };
1357
+ byId('copy-agent-handoff').onclick = () => copyAgentHandoff(runId);
1358
+ byId('duplicate-run-workflow').onclick = async () => {
1192
1359
  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
- })
1360
+ const duplicate = await api(`/api/runs/${encodeURIComponent(runId)}/duplicate`, {
1361
+ method: 'POST',
1362
+ body: JSON.stringify({ recipeId: `${slug(run.displayName)}-copy` })
1200
1363
  });
1201
- await Promise.all([loadRuns(), loadRunDetail(runId)]);
1364
+ draft = normalizeDraftGraph(structuredClone(duplicate.preview.recipe));
1365
+ positions = new Map(checkout.nodes.map((node) => [node.id, node.position]));
1366
+ loadedRecipeId = null;
1367
+ captureHistory({ reset: true });
1368
+ renderGraph();
1369
+ renderRecipeDetails();
1370
+ validateDraft();
1371
+ showWorkspace('workflows');
1372
+ notify('Run duplicated into a new editable workflow. History was not changed.');
1202
1373
  } catch (error) {
1203
1374
  notify(error.message);
1204
1375
  }
1205
1376
  };
1206
- byId('run-detail').querySelectorAll('[data-artifact]').forEach((button) => {
1377
+ byId('run-detail').querySelectorAll('[data-checkout-node]').forEach((button) => {
1378
+ button.onclick = () => loadNodeIo(runId, button.dataset.checkoutNode);
1379
+ });
1380
+ } catch (error) {
1381
+ byId('run-detail').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1382
+ }
1383
+ }
1384
+
1385
+ function renderArtifactPreview(artifact) {
1386
+ if (!artifact) return '<p class="muted">No artifact was recorded for this node.</p>';
1387
+ if (artifact.unavailable) return `<p class="validation-message">Artifact unavailable: ${escapeHtml(artifact.code)}</p>`;
1388
+ 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>`;
1389
+ }
1390
+
1391
+ async function loadNodeIo(runId, nodeId) {
1392
+ const panel = byId('node-io-panel');
1393
+ try {
1394
+ const { io } = await api(`/api/runs/${encodeURIComponent(runId)}/nodes/${encodeURIComponent(nodeId)}`);
1395
+ panel.innerHTML = `
1396
+ <header><small>NODE I/O · ${escapeHtml(io.node.status)}</small><h3>${escapeHtml(io.node.displayName)}</h3></header>
1397
+ <div class="io-grid">
1398
+ <section><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>
1399
+ <section><h4>Output</h4><p><b>${escapeHtml(io.output.status)}</b>${io.output.reason ? ` · ${escapeHtml(io.output.reason)}` : ''}</p>${renderArtifactPreview(io.output.artifact)}</section>
1400
+ <section><h4>Evidence</h4>${renderArtifactPreview(io.evidence)}</section>
1401
+ <section><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>
1402
+ </div>`;
1403
+ panel.querySelectorAll('[data-artifact-download]').forEach((button) => {
1207
1404
  button.onclick = async () => {
1208
1405
  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;
1406
+ const result = await api(`/api/runs/${encodeURIComponent(runId)}/artifacts?path=${encodeURIComponent(button.dataset.artifactDownload)}`);
1407
+ const blob = new Blob([result.artifact.content], { type: 'text/plain' });
1408
+ const link = document.createElement('a');
1409
+ link.href = URL.createObjectURL(blob);
1410
+ link.download = button.dataset.artifactDownload.split('/').at(-1);
1411
+ link.click();
1412
+ URL.revokeObjectURL(link.href);
1213
1413
  } catch (error) {
1214
1414
  notify(error.message);
1215
1415
  }
1216
1416
  };
1217
1417
  });
1218
1418
  } catch (error) {
1219
- byId('run-detail').innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1419
+ panel.innerHTML = `<p class="validation-message">${escapeHtml(error.message)}</p>`;
1420
+ }
1421
+ }
1422
+
1423
+ function renderInteractions(result) {
1424
+ const target = byId('interaction-list');
1425
+ if (!target) return;
1426
+ target.innerHTML = result.questions.length ? result.questions.map((question) => `
1427
+ <article class="agent-question ${question.answer ? 'answered' : 'pending'}">
1428
+ <small>Q${escapeHtml(question.number)} · ${escapeHtml(question.actor)}</small>
1429
+ <p>${escapeHtml(question.message)}</p>
1430
+ ${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>`}
1431
+ </article>
1432
+ `).join('') : '<p class="muted">No questions yet. The Agent can post Q1, Q2, Q3 from the Run-bound CLI.</p>';
1433
+ target.querySelectorAll('[data-answer]').forEach((form) => {
1434
+ form.onsubmit = async (event) => {
1435
+ event.preventDefault();
1436
+ try {
1437
+ await api(`/api/runs/${encodeURIComponent(selectedCheckoutRun)}/questions/${encodeURIComponent(form.dataset.answer)}/answer`, {
1438
+ method: 'POST',
1439
+ body: JSON.stringify({ message: form.querySelector('textarea').value, actor: 'studio-user' })
1440
+ });
1441
+ await refreshCheckoutInteractions();
1442
+ } catch (error) {
1443
+ notify(error.message);
1444
+ }
1445
+ };
1446
+ });
1447
+ }
1448
+
1449
+ async function refreshCheckoutInteractions() {
1450
+ if (!selectedCheckoutRun || !byId('interaction-list')) return;
1451
+ try {
1452
+ const result = await api(`/api/runs/${encodeURIComponent(selectedCheckoutRun)}/interactions`);
1453
+ renderInteractions(result.interactions);
1454
+ } catch {
1455
+ // Corrupt or unavailable Run data is isolated and does not affect another Run.
1456
+ }
1457
+ }
1458
+
1459
+ async function copyAgentHandoff(runId = activeRunId) {
1460
+ try {
1461
+ if (!runId) await ensureStudioRun();
1462
+ const result = await api(`/api/runs/${encodeURIComponent(runId || activeRunId)}/agent-handoff`);
1463
+ await navigator.clipboard.writeText(result.handoff.prompt);
1464
+ byId('goal-dialog').close();
1465
+ notify('Run-bound prompt copied. Paste it into your AI coding Agent.');
1466
+ } catch (error) {
1467
+ byId('goal-validation').textContent = error.message;
1220
1468
  }
1221
1469
  }
1222
1470
 
@@ -1488,6 +1736,7 @@ async function refreshLive() {
1488
1736
  syncGoalFromLive();
1489
1737
  await hydrateGoalFromLive();
1490
1738
  renderLive();
1739
+ await refreshCheckoutInteractions();
1491
1740
  } catch {
1492
1741
  // A transient refresh failure must not discard the draft.
1493
1742
  }
@@ -1674,6 +1923,72 @@ function notify(text) {
1674
1923
  setTimeout(() => { message.style.display = 'none'; }, 4000);
1675
1924
  }
1676
1925
 
1926
+ function openLoopDialog() {
1927
+ const members = draft.nodes.filter((node) => selectedIds.has(node.id));
1928
+ if (members.length < 2) return notify('Select at least two steps for a Loop Group.');
1929
+ if ((draft.loopGroups || []).some((group) => group.nodeIds.some((id) => selectedIds.has(id)))) {
1930
+ return notify('A step can only belong to one Loop Group.');
1931
+ }
1932
+ const options = members.map((node) =>
1933
+ `<option value="${escapeHtml(node.id)}">${escapeHtml(displayName(node))}</option>`
1934
+ ).join('');
1935
+ for (const id of ['loop-entry', 'loop-decision', 'loop-repeat-target']) byId(id).innerHTML = options;
1936
+ const incomingEntry = members.find((node) =>
1937
+ draft.edges.some((edge) => edge.to === node.id && !selectedIds.has(edge.from))
1938
+ ) || members[0];
1939
+ const outgoing = draft.edges.find((edge) =>
1940
+ selectedIds.has(edge.from) && !selectedIds.has(edge.to)
1941
+ );
1942
+ if (!outgoing) return notify('Connect the Loop decision step to its Continue step first.');
1943
+ const decision = outgoing
1944
+ ? members.find((node) => node.id === outgoing.from)
1945
+ : members.find((node) => ['decision', 'judge', 'condition'].includes(node.type)) || members.at(-1);
1946
+ const exitIds = new Set(draft.edges
1947
+ .filter((edge) => selectedIds.has(edge.from) && !selectedIds.has(edge.to))
1948
+ .map((edge) => edge.to));
1949
+ const exitCandidates = draft.nodes.filter((node) => exitIds.has(node.id));
1950
+ byId('loop-exit-target').innerHTML = exitCandidates.map((node) =>
1951
+ `<option value="${escapeHtml(node.id)}">${escapeHtml(displayName(node))}</option>`
1952
+ ).join('');
1953
+ byId('loop-entry').value = incomingEntry.id;
1954
+ byId('loop-repeat-target').value = incomingEntry.id;
1955
+ byId('loop-decision').value = decision.id;
1956
+ if (outgoing) byId('loop-exit-target').value = outgoing.to;
1957
+ byId('loop-name').value = '';
1958
+ byId('loop-dialog').showModal();
1959
+ }
1960
+
1961
+ function createLoopGroupFromForm(event) {
1962
+ event.preventDefault();
1963
+ const display = byId('loop-name').value.trim();
1964
+ const repeatOutcome = byId('loop-repeat-outcome').value.trim();
1965
+ const exitOutcome = byId('loop-exit-outcome').value.trim();
1966
+ if (repeatOutcome === exitOutcome) return notify('Repeat and Continue outcomes must be different.');
1967
+ let id = slug(display || 'iteration-loop');
1968
+ const occupied = new Set((draft.loopGroups || []).map((group) => group.id));
1969
+ for (let suffix = 2; occupied.has(id); suffix += 1) id = `${slug(display || 'iteration-loop')}-${suffix}`;
1970
+ const loopGroup = {
1971
+ id,
1972
+ displayName: display,
1973
+ nodeIds: draft.nodes.filter((node) => selectedIds.has(node.id)).map((node) => node.id),
1974
+ entryNodeId: byId('loop-entry').value,
1975
+ decisionNodeId: byId('loop-decision').value,
1976
+ repeatTargetId: byId('loop-repeat-target').value,
1977
+ exitTargetId: byId('loop-exit-target').value,
1978
+ maxIterations: Number(byId('loop-max').value),
1979
+ repeatOutcome,
1980
+ exitOutcome,
1981
+ repeatLabel: byId('loop-repeat-label').value.trim(),
1982
+ exitLabel: byId('loop-exit-label').value.trim()
1983
+ };
1984
+ draft.loopGroups.push(loopGroup);
1985
+ captureHistory();
1986
+ renderGraph();
1987
+ validateDraft();
1988
+ byId('loop-dialog').close();
1989
+ notify(`Loop Group “${display}” created.`);
1990
+ }
1991
+
1677
1992
  async function initialize() {
1678
1993
  await refreshCatalog('default');
1679
1994
  byId('recipe').onchange = loadRecipe;
@@ -1700,14 +2015,20 @@ async function initialize() {
1700
2015
  byId('goal-dialog').showModal();
1701
2016
  };
1702
2017
  byId('save-goal').onclick = saveGoalFromForm;
2018
+ byId('start-agent').onclick = () => copyAgentHandoff();
1703
2019
  byId('review-goal').onclick = reviewGoal;
1704
2020
  byId('confirm-freeze').onclick = freezeGoalFromForm;
1705
2021
  byId('unfreeze-goal').onclick = unfreezeGoalFromForm;
1706
2022
  byId('duplicate-selection').onclick = duplicateSelectedNode;
1707
2023
  byId('delete-selection').onclick = deleteSelectedNode;
2024
+ byId('create-loop-group').onclick = openLoopDialog;
2025
+ byId('loop-form').onsubmit = createLoopGroupFromForm;
1708
2026
  document.querySelectorAll('[data-close]').forEach((button) => {
1709
2027
  button.onclick = () => byId(button.dataset.close).close();
1710
2028
  });
2029
+ document.querySelectorAll('.dialog-maximize').forEach((button) => {
2030
+ button.onclick = () => button.closest('dialog').classList.toggle('maximized');
2031
+ });
1711
2032
  byId('workflow-settings').onclick = () => {
1712
2033
  selectedId = null;
1713
2034
  updateSelection();