dsh-workflow-canvas 1.4.1 → 1.5.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/client.js CHANGED
@@ -51,6 +51,9 @@ window.__ModuleLoader__.load({
51
51
  const ROW_H = 18;
52
52
  const COND_ROW_H = 20;
53
53
  const BRANCH_COLORS = ['#3fb950', '#e5534b', '#2f81f7', '#d29922', '#a371f7', '#39c5cf', '#f778ba', '#f0883e'];
54
+ const LOOP_COLORS = ['#f0883e', '#39c5cf', '#f778ba', '#a371f7', '#d29922'];
55
+ const MAX_LOOP_ITERATIONS = 10;
56
+ const DEFAULT_LOOP_ITERATIONS = 3;
54
57
  const CONTENT_W = 2400;
55
58
  const CONTENT_H = 1600;
56
59
  /** World origin offset: keeps negative node coordinates inside the scroll area. */
@@ -187,7 +190,7 @@ window.__ModuleLoader__.load({
187
190
  helpBody: [
188
191
  '1. 在入口 Lead 里写「本次任务」,这是整张图的总目标。',
189
192
  '2. 点「+ 子代理 / + Lead / + 条件」加节点,从右侧输出口拖到另一个节点左侧输入口即可连线。',
190
- '3. 输出口决定连线类型:prompt(灰,纯文本)、structured(蓝,JSON)、session(紫,复用上游会话);条件节点支持多路分支(单选 switch/case 或多选并行,全不满足时跳过中间分支直达最近 Lead)。',
193
+ '3. 输出口决定连线类型:prompt(灰,纯文本)、structured(蓝,JSON)、session(紫,复用上游会话);条件节点支持多路分支,并可将分支连回上游(或多选节点右键「↺ 设为回环」)实现带反馈的受控重试(点 ↺ 徽章可调 1–10 次,超限自动交 Lead 熔断)。',
191
194
  '4. 节点左侧为统一通用输入口,可直接接收任意颜色的连线;拖已连接的左口可断开最近一条连线。',
192
195
  '5. 每个节点可设模型、推理强度、能力范围、备用模型、是否记忆;复杂任务/分工/条件可点 ⤢ 展开大框编辑。',
193
196
  '6. 连好后点「● 已启用」,然后对对话说「跑一次」,由我调用执行。',
@@ -256,6 +259,19 @@ window.__ModuleLoader__.load({
256
259
  ctxInsertAgent: '在此插入子代理',
257
260
  ctxInsertCond: '在此插入条件节点',
258
261
  ctxLangToggle: '界面语言',
262
+ ctxMakeLoop: '↺ 设为回环',
263
+ ctxMakeLoopAuto: '↺ 设为回环(自动补条件)',
264
+ ctxEditLoop: '↺ 修改回环次数',
265
+ ctxRemoveLoop: '取消回环',
266
+ loopCreated: '已创建回环(默认最多重试 3 次,点 ↺ 徽章可调)',
267
+ loopCreatedAutoCond: '已自动补条件节点并创建回环(点 ↺ 徽章可调次数)',
268
+ loopOverlap: '不支持交叉或重叠的回环',
269
+ loopModalTitle: '最大重试次数 (1–10)',
270
+ loopTipPill: '点击调整最大回环重试次数(1–10)或取消回环',
271
+ loopAutoCondLabel: '是否通过?',
272
+ loopAutoCondRole: '判断上游步骤是否执行成功并达到预期;全部达标走「是」,未达标或报错走「否」回环重做。',
273
+ loopRetryBranch: '重做',
274
+ loopPrunedNotice: '(内部连线断开,已清理失效回环)',
259
275
  shortcutsMenu: '⌨ 快捷键设置',
260
276
  shortcutsTitle: '快捷键设置',
261
277
  shortcutsHint: '点击右侧按键框后按下新组合键;按 Esc 取消录制,点 × 清除绑定。',
@@ -373,7 +389,7 @@ window.__ModuleLoader__.load({
373
389
  helpBody: [
374
390
  '1. Write the overall task in the entry Lead node.',
375
391
  '2. Add nodes with + Subagent / + Lead / + Condition, then drag from a right socket to a left socket.',
376
- '3. Output sockets choose channel type: prompt (grey text), structured (blue JSON), session (purple warm session), or multi-way condition branches (single switch/case or parallel multi-match; jumps to nearest Lead if none match).',
392
+ '3. Output sockets choose channel type: prompt (grey text), structured (blue JSON), session (purple warm session), or multi-way condition branches; wire a condition branch back upstream (or right-click selected nodes → ↺ Create loop) for bounded feedback retries (click the ↺ pill for 1–10 retries).',
377
393
  '4. Every node has one universal left input that accepts any incoming wire; drag a connected input away to detach the latest wire.',
378
394
  '5. Each node sets model, reasoning, capability scope, fallback model and memory; click ⤢ to expand a larger editor for long text.',
379
395
  '6. Press ● ON, then ask in chat to run the canvas.',
@@ -442,6 +458,19 @@ window.__ModuleLoader__.load({
442
458
  ctxInsertAgent: 'Insert Subagent here',
443
459
  ctxInsertCond: 'Insert Condition here',
444
460
  ctxLangToggle: 'Language',
461
+ ctxMakeLoop: '↺ Create loop',
462
+ ctxMakeLoopAuto: '↺ Create loop (+ Condition)',
463
+ ctxEditLoop: '↺ Edit loop retries',
464
+ ctxRemoveLoop: 'Remove loop',
465
+ loopCreated: 'Loop created (max 3 retries; click ↺ pill to edit)',
466
+ loopCreatedAutoCond: 'Added condition gate & created loop (click ↺ pill to edit)',
467
+ loopOverlap: 'Overlapping or crossing loops are not supported',
468
+ loopModalTitle: 'Max retries (1–10)',
469
+ loopTipPill: 'Click to adjust max loop retries (1–10) or remove loop',
470
+ loopAutoCondLabel: 'Checks Passed?',
471
+ loopAutoCondRole: 'Return pass=true if upstream succeeded and meets expectations; return pass=false to retry.',
472
+ loopRetryBranch: 'Retry',
473
+ loopPrunedNotice: ' (removed broken loop)',
445
474
  shortcutsMenu: '⌨ Shortcuts',
446
475
  shortcutsTitle: 'Keyboard Shortcuts',
447
476
  shortcutsHint: 'Click a key button then press a new combo. Press Esc to cancel, or × to clear.',
@@ -579,6 +608,39 @@ window.__ModuleLoader__.load({
579
608
  ctxDivider: {
580
609
  height: '1px', background: C.border, opacity: 0.65, margin: '3px 4px',
581
610
  },
611
+ loopPill: {
612
+ position: 'absolute', transform: 'translate(-50%, -50%)', zIndex: 18,
613
+ padding: '2px 7px', borderRadius: '999px',
614
+ background: C.elevated, color: C.text,
615
+ fontSize: '10px', fontWeight: 600, lineHeight: '14px',
616
+ cursor: 'pointer', whiteSpace: 'nowrap',
617
+ boxShadow: '0 2px 8px rgba(0,0,0,0.28)',
618
+ display: 'inline-flex', alignItems: 'center', gap: '3px',
619
+ },
620
+ loopPopover: {
621
+ position: 'absolute', left: '50%', top: 'calc(100% + 6px)', transform: 'translateX(-50%)',
622
+ zIndex: 60, minWidth: '154px', padding: '8px', borderRadius: '7px',
623
+ background: C.elevated, color: C.text, border: '1px solid ' + C.border,
624
+ boxShadow: '0 10px 26px rgba(0,0,0,0.34)',
625
+ },
626
+ loopStepBtn: {
627
+ width: '24px', height: '24px', padding: 0, borderRadius: '5px',
628
+ border: '1px solid ' + C.border, background: C.base, color: C.text,
629
+ fontSize: '13px', lineHeight: '22px', cursor: 'pointer', textAlign: 'center',
630
+ },
631
+ loopNumInput: {
632
+ width: '44px', height: '24px', boxSizing: 'border-box', textAlign: 'center',
633
+ borderRadius: '5px', border: '1px solid ' + C.border,
634
+ background: C.base, color: C.text, fontSize: '12px', fontWeight: 600,
635
+ outline: 'none', userSelect: 'text',
636
+ },
637
+ loopNodeTag: {
638
+ position: 'absolute', left: '10px', top: '-11px', zIndex: 9,
639
+ padding: '0 5px', height: '15px', lineHeight: '15px', borderRadius: '999px',
640
+ background: C.elevated, fontSize: '9px', fontWeight: 700,
641
+ pointerEvents: 'none', whiteSpace: 'nowrap',
642
+ boxShadow: '0 1px 4px rgba(0,0,0,0.26)',
643
+ },
582
644
  canvasWrap: {
583
645
  position: 'relative', flex: '1 1 auto', minHeight: '0',
584
646
  display: 'flex', flexDirection: 'column',
@@ -1227,6 +1289,257 @@ window.__ModuleLoader__.load({
1227
1289
  return doc;
1228
1290
  }
1229
1291
 
1292
+ function normalizeMaxIterationsUI(val) {
1293
+ const n = Number(val);
1294
+ if (!Number.isFinite(n)) return DEFAULT_LOOP_ITERATIONS;
1295
+ return Math.max(1, Math.min(MAX_LOOP_ITERATIONS, Math.floor(n)));
1296
+ }
1297
+
1298
+ function forwardEdgesUI(edges) {
1299
+ return (Array.isArray(edges) ? edges : []).filter((e) => e && !e.loop);
1300
+ }
1301
+
1302
+ /** Nodes strictly inside a loop edge (`descendants(to) ∩ ancestors(from)` over forward edges). */
1303
+ function loopMemberIdsUI(nodes, edges, loopEdge) {
1304
+ if (!loopEdge || !loopEdge.from || !loopEdge.to || loopEdge.to === 'lead') return new Set();
1305
+ const fwd = new Map();
1306
+ const rev = new Map();
1307
+ for (const e of forwardEdgesUI(edges)) {
1308
+ if (!e.from || !e.to) continue;
1309
+ if (!fwd.has(e.from)) fwd.set(e.from, []);
1310
+ fwd.get(e.from).push(e.to);
1311
+ if (!rev.has(e.to)) rev.set(e.to, []);
1312
+ rev.get(e.to).push(e.from);
1313
+ }
1314
+ const desc = new Set([loopEdge.to]);
1315
+ const q1 = [loopEdge.to];
1316
+ for (let i = 0; i < q1.length; i += 1) {
1317
+ for (const next of fwd.get(q1[i]) || []) {
1318
+ if (!desc.has(next)) { desc.add(next); q1.push(next); }
1319
+ }
1320
+ }
1321
+ if (!desc.has(loopEdge.from)) return new Set();
1322
+ const anc = new Set([loopEdge.from]);
1323
+ const q2 = [loopEdge.from];
1324
+ for (let i = 0; i < q2.length; i += 1) {
1325
+ for (const prev of rev.get(q2[i]) || []) {
1326
+ if (!anc.has(prev)) { anc.add(prev); q2.push(prev); }
1327
+ }
1328
+ }
1329
+ const members = new Set();
1330
+ for (const id of desc) {
1331
+ if (anc.has(id)) members.add(id);
1332
+ }
1333
+ return members;
1334
+ }
1335
+
1336
+ /** Compute loop visual groups (per-node color & per-edge metadata) from active loop edges. */
1337
+ function loopGroupsForUI(nodes, edges) {
1338
+ const byNode = new Map();
1339
+ const byEdge = new Map();
1340
+ let idx = 0;
1341
+ for (const e of edges || []) {
1342
+ if (!e || e.loop !== true) continue;
1343
+ const members = loopMemberIdsUI(nodes, edges, e);
1344
+ const color = LOOP_COLORS[idx % LOOP_COLORS.length];
1345
+ const info = {
1346
+ edge: e,
1347
+ color,
1348
+ index: idx + 1,
1349
+ members,
1350
+ maxIterations: normalizeMaxIterationsUI(e.maxIterations),
1351
+ };
1352
+ byEdge.set(e.id || (e.from + '->' + e.to), info);
1353
+ for (const nid of members) {
1354
+ if (!byNode.has(nid)) byNode.set(nid, info);
1355
+ }
1356
+ idx += 1;
1357
+ }
1358
+ return { byNode, byEdge };
1359
+ }
1360
+
1361
+ /** Remove any loop edge whose forward ancestor path was broken by an edge or node deletion. */
1362
+ function pruneInvalidLoopEdges(nodes, edges) {
1363
+ const list = Array.isArray(nodes) ? nodes : [];
1364
+ const all = Array.isArray(edges) ? edges : [];
1365
+ let removedCount = 0;
1366
+ const kept = all.filter((e) => {
1367
+ if (!e || e.loop !== true) return true;
1368
+ const ok = loopMemberIdsUI(list, all, e).size > 0;
1369
+ if (!ok) removedCount += 1;
1370
+ return ok;
1371
+ });
1372
+ return { edges: kept, removedCount };
1373
+ }
1374
+
1375
+ /** Check whether dragging from `fromId` to `toId` is a valid controlled loop back-edge. */
1376
+ function canLinkAsLoop(nodes, edges, fromId, toId) {
1377
+ const list = Array.isArray(nodes) ? nodes : [];
1378
+ const fromNode = list.find((n) => n && n.id === fromId);
1379
+ if (!fromNode || fromNode.kind !== 'condition') return { ok: false, reason: 'loopNotCondition' };
1380
+ if (!toId || toId === 'lead' || toId === fromId) return { ok: false, reason: 'loopToLead' };
1381
+ const members = loopMemberIdsUI(list, edges, { from: fromId, to: toId, loop: true });
1382
+ if (!members.size) return { ok: false, reason: 'loopNotAncestor' };
1383
+ const existing = loopGroupsForUI(list, edges);
1384
+ for (const mid of members) {
1385
+ if (existing.byNode.has(mid)) return { ok: false, reason: 'loopOverlap' };
1386
+ }
1387
+ return { ok: true, members };
1388
+ }
1389
+
1390
+ /**
1391
+ * Validate a multi-selected (or single non-condition) subgraph for one-click "Create loop".
1392
+ * Requires a single-entry, single-exit connected subgraph with no overlap with existing loops.
1393
+ */
1394
+ function analyzeLoopSelection(nodes, edges, selectedIds) {
1395
+ const list = Array.isArray(nodes) ? nodes : [];
1396
+ const byId = new Map(list.map((n) => [n.id, n]));
1397
+ const selIds = Array.from(new Set((selectedIds || []).filter((id) => id && id !== 'lead' && byId.has(id))));
1398
+ if (!selIds.length) return { ok: false, reason: 'loopNeedNodes' };
1399
+ const selSet = new Set(selIds);
1400
+ const existing = loopGroupsForUI(list, edges);
1401
+ for (const id of selIds) {
1402
+ if (existing.byNode.has(id)) return { ok: false, reason: 'loopOverlap' };
1403
+ }
1404
+ if (selIds.length === 1) {
1405
+ const only = byId.get(selIds[0]);
1406
+ if (only.kind === 'condition') return { ok: false, reason: 'loopCondAlone' };
1407
+ return { ok: true, entryId: only.id, exitId: only.id, needsAutoCondition: true };
1408
+ }
1409
+ const fwd = new Map(selIds.map((id) => [id, []]));
1410
+ const rev = new Map(selIds.map((id) => [id, []]));
1411
+ const undir = new Map(selIds.map((id) => [id, []]));
1412
+ for (const e of forwardEdgesUI(edges)) {
1413
+ if (!selSet.has(e.from) || !selSet.has(e.to)) continue;
1414
+ fwd.get(e.from).push(e.to);
1415
+ rev.get(e.to).push(e.from);
1416
+ undir.get(e.from).push(e.to);
1417
+ undir.get(e.to).push(e.from);
1418
+ }
1419
+ // Must be weakly connected
1420
+ const visited = new Set([selIds[0]]);
1421
+ const q = [selIds[0]];
1422
+ for (let i = 0; i < q.length; i += 1) {
1423
+ for (const nb of undir.get(q[i]) || []) {
1424
+ if (!visited.has(nb)) { visited.add(nb); q.push(nb); }
1425
+ }
1426
+ }
1427
+ if (visited.size !== selIds.length) return { ok: false, reason: 'loopDisconnected' };
1428
+ const entries = selIds.filter((id) => (rev.get(id) || []).length === 0);
1429
+ const exits = selIds.filter((id) => (fwd.get(id) || []).length === 0);
1430
+ if (entries.length !== 1 || exits.length !== 1) return { ok: false, reason: 'loopMultiEnds' };
1431
+ const entryId = entries[0];
1432
+ const exitId = exits[0];
1433
+ // Verify entry reaches exit
1434
+ const reach = new Set([entryId]);
1435
+ const rq = [entryId];
1436
+ for (let i = 0; i < rq.length; i += 1) {
1437
+ for (const nx of fwd.get(rq[i]) || []) {
1438
+ if (!reach.has(nx)) { reach.add(nx); rq.push(nx); }
1439
+ }
1440
+ }
1441
+ if (!reach.has(exitId)) return { ok: false, reason: 'loopDisconnected' };
1442
+ const exitNode = byId.get(exitId);
1443
+ return {
1444
+ ok: true,
1445
+ entryId,
1446
+ exitId,
1447
+ needsAutoCondition: exitNode.kind !== 'condition',
1448
+ };
1449
+ }
1450
+
1451
+ /**
1452
+ * Build a clean rounded bypass-rail SVG path for a controlled loop back-edge so it
1453
+ * routes outside all loop member cards instead of cutting across card bodies.
1454
+ */
1455
+ function loopEdgeArc(from, to, edge, direction, nodes, edges) {
1456
+ const type = (edge && edge.type) || 'prompt';
1457
+ const branch = (edge && edge.branch) || '';
1458
+ const p1 = outputSocketPos(from, type, branch, direction);
1459
+ const p2 = inputSocketPos(to, direction);
1460
+ const x1 = p1.x + WORLD_PAD;
1461
+ const y1 = p1.y + WORLD_PAD;
1462
+ const x2 = p2.x + WORLD_PAD;
1463
+ const y2 = p2.y + WORLD_PAD;
1464
+
1465
+ const list = Array.isArray(nodes) ? nodes : [from, to];
1466
+ const byId = new Map(list.map((n) => [n.id, n]));
1467
+ const memberIds = loopMemberIdsUI(list, edges || [], edge);
1468
+ const boxNodes = memberIds.size
1469
+ ? Array.from(memberIds).map((id) => byId.get(id)).filter(Boolean)
1470
+ : [from, to];
1471
+ let minX = Infinity;
1472
+ let maxX = -Infinity;
1473
+ let minY = Infinity;
1474
+ for (const n of boxNodes) {
1475
+ minX = Math.min(minX, n.x + WORLD_PAD);
1476
+ maxX = Math.max(maxX, n.x + WORLD_PAD + NODE_W);
1477
+ minY = Math.min(minY, n.y + WORLD_PAD);
1478
+ }
1479
+
1480
+ const buildRoundedPath = (pts, radius) => {
1481
+ if (pts.length < 2) return '';
1482
+ let d = 'M ' + pts[0].x + ' ' + pts[0].y;
1483
+ for (let i = 1; i < pts.length - 1; i += 1) {
1484
+ const prev = pts[i - 1];
1485
+ const cur = pts[i];
1486
+ const next = pts[i + 1];
1487
+ const d1 = Math.hypot(cur.x - prev.x, cur.y - prev.y);
1488
+ const d2 = Math.hypot(next.x - cur.x, next.y - cur.y);
1489
+ const r = Math.min(radius, d1 * 0.45, d2 * 0.45);
1490
+ if (r < 1) {
1491
+ d += ' L ' + cur.x + ' ' + cur.y;
1492
+ } else {
1493
+ const ax = cur.x - ((cur.x - prev.x) / d1) * r;
1494
+ const ay = cur.y - ((cur.y - prev.y) / d1) * r;
1495
+ const bx = cur.x + ((next.x - cur.x) / d2) * r;
1496
+ const by = cur.y + ((next.y - cur.y) / d2) * r;
1497
+ d += ' L ' + ax.toFixed(1) + ' ' + ay.toFixed(1)
1498
+ + ' Q ' + cur.x.toFixed(1) + ' ' + cur.y.toFixed(1) + ' ' + bx.toFixed(1) + ' ' + by.toFixed(1);
1499
+ }
1500
+ }
1501
+ const last = pts[pts.length - 1];
1502
+ d += ' L ' + last.x + ' ' + last.y;
1503
+ return d;
1504
+ };
1505
+
1506
+ if (direction === 'tb') {
1507
+ const onLeft = Boolean(from && from.tbSide === 'left');
1508
+ const railX = onLeft ? (Math.min(x1, minX) - 42) : (Math.max(x1, maxX) + 42);
1509
+ const topY = Math.min(y2, minY) - 34;
1510
+ const points = [
1511
+ { x: x1, y: y1 },
1512
+ { x: railX, y: y1 },
1513
+ { x: railX, y: topY },
1514
+ { x: x2, y: topY },
1515
+ { x: x2, y: y2 },
1516
+ ];
1517
+ return {
1518
+ path: buildRoundedPath(points, 16),
1519
+ points,
1520
+ midX: railX,
1521
+ midY: Math.round((y1 + topY) / 2),
1522
+ };
1523
+ }
1524
+ const rightX = Math.max(x1, maxX) + 34;
1525
+ const leftX = Math.min(x2, minX) - 34;
1526
+ const topY = Math.min(y1, y2, minY) - 38;
1527
+ const points = [
1528
+ { x: x1, y: y1 },
1529
+ { x: rightX, y: y1 },
1530
+ { x: rightX, y: topY },
1531
+ { x: leftX, y: topY },
1532
+ { x: leftX, y: y2 },
1533
+ { x: x2, y: y2 },
1534
+ ];
1535
+ return {
1536
+ path: buildRoundedPath(points, 16),
1537
+ points,
1538
+ midX: Math.round((rightX + leftX) / 2),
1539
+ midY: topY,
1540
+ };
1541
+ }
1542
+
1230
1543
  /** Control points of one link, in canvas coordinates. Supports horizontal (lr) and vertical (tb) flow. */
1231
1544
  function edgeCurve(from, to, typeOrEdge, direction) {
1232
1545
  const type = (typeOrEdge && typeof typeOrEdge === 'object') ? (typeOrEdge.type || 'prompt') : (typeOrEdge || 'prompt');
@@ -1265,13 +1578,24 @@ window.__ModuleLoader__.load({
1265
1578
  return { x1, y1, c1x: x1 + dx, c1y: y1, c2x: x2 - dx, c2y: y2, x2, y2 };
1266
1579
  }
1267
1580
 
1268
- function edgePath(from, to, typeOrEdge, direction) {
1581
+ function edgePath(from, to, typeOrEdge, direction, nodes, edges) {
1582
+ if (typeOrEdge && typeof typeOrEdge === 'object' && typeOrEdge.loop) {
1583
+ return loopEdgeArc(from, to, typeOrEdge, direction, nodes, edges).path;
1584
+ }
1269
1585
  const c = edgeCurve(from, to, typeOrEdge, direction);
1270
1586
  return 'M ' + c.x1 + ' ' + c.y1 + ' C ' + c.c1x + ' ' + c.c1y + ', ' + c.c2x + ' ' + c.c2y + ', ' + c.x2 + ' ' + c.y2;
1271
1587
  }
1272
1588
 
1273
- /** Shortest distance between a point and one link, sampled along the curve. */
1274
- function distanceToEdge(point, from, to, typeOrEdge, direction) {
1589
+ /** Shortest distance between a point and one link, sampled along the curve (or bypass rail for loops). */
1590
+ function distanceToEdge(point, from, to, typeOrEdge, direction, nodes, edges) {
1591
+ if (typeOrEdge && typeof typeOrEdge === 'object' && typeOrEdge.loop) {
1592
+ const pts = loopEdgeArc(from, to, typeOrEdge, direction, nodes, edges).points;
1593
+ let best = Infinity;
1594
+ for (let i = 1; i < pts.length; i += 1) {
1595
+ best = Math.min(best, distanceToSegment(point, pts[i - 1].x, pts[i - 1].y, pts[i].x, pts[i].y));
1596
+ }
1597
+ return best;
1598
+ }
1275
1599
  const c = edgeCurve(from, to, typeOrEdge, direction);
1276
1600
  let best = Infinity;
1277
1601
  let prevX = c.x1;
@@ -1301,7 +1625,7 @@ window.__ModuleLoader__.load({
1301
1625
  function topoOrder(nodes, edges) {
1302
1626
  const indeg = new Map(nodes.map((n) => [n.id, 0]));
1303
1627
  const adj = new Map(nodes.map((n) => [n.id, []]));
1304
- for (const e of edges) {
1628
+ for (const e of forwardEdgesUI(edges)) {
1305
1629
  if (!indeg.has(e.from) || !indeg.has(e.to)) continue;
1306
1630
  indeg.set(e.to, indeg.get(e.to) + 1);
1307
1631
  adj.get(e.from).push(e.to);
@@ -1319,10 +1643,10 @@ window.__ModuleLoader__.load({
1319
1643
  return out.length === nodes.length ? out : null;
1320
1644
  }
1321
1645
 
1322
- /** Ids reachable from the entry Lead via O(V + E) BFS; every other node is skipped at run time. */
1646
+ /** Ids reachable from the entry Lead via O(V + E) BFS over forward edges; every other node is skipped at run time. */
1323
1647
  function reachableFrom(nodes, edges) {
1324
1648
  const adj = new Map();
1325
- for (const e of edges || []) {
1649
+ for (const e of forwardEdgesUI(edges)) {
1326
1650
  if (!e || !e.from || !e.to) continue;
1327
1651
  if (!adj.has(e.from)) adj.set(e.from, []);
1328
1652
  adj.get(e.from).push(e.to);
@@ -1345,7 +1669,7 @@ window.__ModuleLoader__.load({
1345
1669
  */
1346
1670
  function soloLeadNodeIds(nodes, edges) {
1347
1671
  const list = Array.isArray(nodes) ? nodes : [];
1348
- const linkList = Array.isArray(edges) ? edges : [];
1672
+ const linkList = forwardEdgesUI(edges);
1349
1673
  const reachable = reachableFrom(list, linkList);
1350
1674
  const byId = new Map(list.map((n) => [n.id, n]));
1351
1675
  const out = new Set();
@@ -1370,13 +1694,14 @@ window.__ModuleLoader__.load({
1370
1694
  function deadEndNodeIds(nodes, edges) {
1371
1695
  const list = Array.isArray(nodes) ? nodes : [];
1372
1696
  const linkList = Array.isArray(edges) ? edges : [];
1373
- const reachable = reachableFrom(list, linkList);
1374
- const soloLeads = soloLeadNodeIds(list, linkList);
1697
+ const fwdLinks = forwardEdgesUI(linkList);
1698
+ const reachable = reachableFrom(list, fwdLinks);
1699
+ const soloLeads = soloLeadNodeIds(list, fwdLinks);
1375
1700
  const downstreamLeads = list.filter((n) => n.kind === 'lead' && n.id !== 'lead' && reachable.has(n.id) && !soloLeads.has(n.id));
1376
1701
  if (!downstreamLeads.length) return new Set();
1377
1702
  const hasOut = new Set(linkList.map((e) => e.from));
1378
1703
  const parents = new Map();
1379
- for (const e of linkList) {
1704
+ for (const e of fwdLinks) {
1380
1705
  if (!parents.has(e.to)) parents.set(e.to, []);
1381
1706
  parents.get(e.to).push(e.from);
1382
1707
  }
@@ -1400,11 +1725,11 @@ window.__ModuleLoader__.load({
1400
1725
  return out;
1401
1726
  }
1402
1727
 
1403
- /** True when adding `fromId -> toId` would create a cycle or point into entry Lead. */
1728
+ /** True when adding `fromId -> toId` would create a cycle over forward edges or point into entry Lead. */
1404
1729
  function wouldCycle(nodes, edges, fromId, toId) {
1405
1730
  if (!fromId || !toId || fromId === toId || toId === 'lead') return true;
1406
1731
  const adj = new Map();
1407
- for (const e of edges || []) {
1732
+ for (const e of forwardEdgesUI(edges)) {
1408
1733
  if (!adj.has(e.from)) adj.set(e.from, []);
1409
1734
  adj.get(e.from).push(e.to);
1410
1735
  }
@@ -1420,10 +1745,10 @@ window.__ModuleLoader__.load({
1420
1745
  return false;
1421
1746
  }
1422
1747
 
1423
- /** Tidy a DAG into symmetrical left-to-right columns by longest-path depth. */
1748
+ /** Tidy a DAG into symmetrical columns/rows by longest-path depth (ignoring loop back-edges). */
1424
1749
  function layoutGraph(nodes, edges, direction) {
1425
1750
  const list = Array.isArray(nodes) ? nodes : [];
1426
- const linkList = Array.isArray(edges) ? edges : [];
1751
+ const linkList = forwardEdgesUI(edges);
1427
1752
  if (!list.length) return [];
1428
1753
  const reachable = reachableFrom(list, linkList);
1429
1754
  const depth = new Map(list.map((n) => [n.id, n.id === 'lead' ? 0 : 1]));
@@ -1673,6 +1998,54 @@ window.__ModuleLoader__.load({
1673
1998
  { id: 'cd5', from: 'c_yes', to: 'c_final', type: 'prompt' },
1674
1999
  { id: 'cd6', from: 'c_no', to: 'c_final', type: 'prompt' },
1675
2000
  ];
2001
+ const loopNodes = [
2002
+ {
2003
+ id: 'lead', kind: 'lead', label: 'Lead', y: 0,
2004
+ task: en
2005
+ ? 'Implement the requested change and verify with tests: if checks fail, automatically loop back with feedback to fix (up to 3 retries), then hand off to me for final review.'
2006
+ : '实现目标功能并跑测试验证:若测试或检查不通过,自动带着失败原因回环修改(最多 3 次),全部通过后交我终审交付。',
2007
+ provider: '', model: '', role: '',
2008
+ },
2009
+ {
2010
+ id: 'lp_impl', kind: 'agent', y: 0,
2011
+ label: en ? 'Implement' : '编写实现',
2012
+ provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false,
2013
+ role: en
2014
+ ? 'Implement the requested change cleanly. When invoked on a retry round, focus directly on fixing the reported issues and list modified files.'
2015
+ : '按需求完成代码或文档实现;若处于回环修正轮次,针对打回理由直接定点修复并列出改动清单。',
2016
+ },
2017
+ {
2018
+ id: 'lp_test', kind: 'agent', y: 0,
2019
+ label: en ? 'Test & Verify' : '测试与检查',
2020
+ provider: '', model: '', reasoning: '', preset: 'standard', keepSession: false,
2021
+ role: en
2022
+ ? 'Run tests/lint/checks against the implementation and report exact pass/fail status, error logs, and remaining defects.'
2023
+ : '对实现结果运行单测、构建或逐项核验,如实汇报通过情况、具体报错日志与遗留缺陷。',
2024
+ },
2025
+ {
2026
+ id: 'lp_gate', kind: 'condition', y: 0,
2027
+ label: en ? 'Checks Passed?' : '是否通过?',
2028
+ provider: '', model: '', reasoning: '', preset: 'minimal', keepSession: false,
2029
+ role: en
2030
+ ? 'Return pass=true only if all tests/checks passed with no unresolved defects; otherwise return pass=false with a concise, actionable fix reason.'
2031
+ : '仅当测试与检查全部通过且无未解决缺陷时返回 true;否则返回 false,并在理由里写清下一轮需修复的具体问题。',
2032
+ },
2033
+ {
2034
+ id: 'lp_final', kind: 'lead', y: 0,
2035
+ label: en ? 'Lead Final Review' : 'Lead 终审',
2036
+ provider: '', model: '',
2037
+ role: en
2038
+ ? 'Review the verified result (or the round-by-round summary if retries exhausted) and decide whether to ship or intervene.'
2039
+ : '审阅最终通过的改动摘要(或回环达上限后的历次失败记录),确认交付或拍板下一步处理。',
2040
+ },
2041
+ ];
2042
+ const loopEdges = [
2043
+ { id: 'lp1', from: 'lead', to: 'lp_impl', type: 'prompt' },
2044
+ { id: 'lp2', from: 'lp_impl', to: 'lp_test', type: 'prompt' },
2045
+ { id: 'lp3', from: 'lp_test', to: 'lp_gate', type: 'prompt' },
2046
+ { id: 'lp4', from: 'lp_gate', to: 'lp_final', type: 'prompt', branch: 'true' },
2047
+ { id: 'lp5', from: 'lp_gate', to: 'lp_impl', type: 'prompt', branch: 'false', loop: true, maxIterations: 3 },
2048
+ ];
1676
2049
  return [
1677
2050
  {
1678
2051
  id: 'tpl-swe',
@@ -1698,6 +2071,12 @@ window.__ModuleLoader__.load({
1698
2071
  nodes: layoutGraph(condNodes, condEdges, direction),
1699
2072
  edges: condEdges,
1700
2073
  },
2074
+ {
2075
+ id: 'tpl-loop',
2076
+ name: en ? 'Retry Loop: Implement → Test ↺ Fix → Review' : '循环重试:实现 → 测试验收 ↺ 自动修复 → 终审',
2077
+ nodes: layoutGraph(loopNodes, loopEdges, direction),
2078
+ edges: loopEdges,
2079
+ },
1701
2080
  ];
1702
2081
  }
1703
2082
 
@@ -1722,12 +2101,17 @@ window.__ModuleLoader__.load({
1722
2101
  }
1723
2102
 
1724
2103
  const activeIds = new Set(active.map((n) => n.id));
1725
- const planEdges = edges
1726
- .filter((e) => (e.from === 'lead' || activeIds.has(e.from)) && activeIds.has(e.to))
2104
+ const candidateEdges = edges.filter((e) => (e.from === 'lead' || activeIds.has(e.from)) && activeIds.has(e.to));
2105
+ const { edges: validEdges } = pruneInvalidLoopEdges(active, candidateEdges);
2106
+ const planEdges = validEdges
1727
2107
  .map((e) => {
1728
2108
  const item = { from: e.from, to: e.to, type: e.type || 'prompt' };
1729
2109
  const b = typeof e.branch === 'string' ? e.branch.trim() : '';
1730
2110
  if (b) item.branch = b;
2111
+ if (e.loop === true) {
2112
+ item.loop = true;
2113
+ item.maxIterations = normalizeMaxIterationsUI(e.maxIterations);
2114
+ }
1731
2115
  return item;
1732
2116
  });
1733
2117
 
@@ -2100,6 +2484,8 @@ window.__ModuleLoader__.load({
2100
2484
  const lastMouseRef = useRef(null);
2101
2485
  const [addMenu, setAddMenu] = useState(null);
2102
2486
  const [ctxMenu, setCtxMenu] = useState(null);
2487
+ const [loopEditEdgeId, setLoopEditEdgeId] = useState(null);
2488
+ const [loopDraft, setLoopDraft] = useState('');
2103
2489
  const rightClickRef = useRef(null);
2104
2490
  const nodeDrag = useRef(null);
2105
2491
  const panDrag = useRef(null);
@@ -2500,6 +2886,7 @@ window.__ModuleLoader__.load({
2500
2886
  e.preventDefault();
2501
2887
  absorbScroll();
2502
2888
  setCtxMenu(null);
2889
+ setLoopEditEdgeId(null);
2503
2890
  const rect = el.getBoundingClientRect();
2504
2891
  const mx = e.clientX - rect.left;
2505
2892
  const my = e.clientY - rect.top;
@@ -2766,9 +3153,125 @@ window.__ModuleLoader__.load({
2766
3153
 
2767
3154
  const deleteEdgeById = (edgeId) => {
2768
3155
  pushSnapshot();
2769
- setEdges((es) => es.filter((e) => e.id !== edgeId));
3156
+ const remaining = edgesRef.current.filter((e) => e.id !== edgeId);
3157
+ const { edges: cleaned, removedCount } = pruneInvalidLoopEdges(nodesRef.current, remaining);
3158
+ setEdges(cleaned);
2770
3159
  setCtxMenu(null);
2771
- flash(t('linkCut') + ' ×1');
3160
+ setLoopEditEdgeId(null);
3161
+ flash(t('linkCut') + ' ×1' + (removedCount > 0 ? t('loopPrunedNotice') : ''));
3162
+ };
3163
+
3164
+ const openLoopEditor = (edge) => {
3165
+ if (!edge) { setLoopEditEdgeId(null); return; }
3166
+ setLoopDraft(String(normalizeMaxIterationsUI(edge.maxIterations)));
3167
+ setLoopEditEdgeId(edge.id);
3168
+ };
3169
+
3170
+ const updateLoopMaxIterations = (edgeId, nextVal) => {
3171
+ const clamped = normalizeMaxIterationsUI(nextVal);
3172
+ const cur = edgesRef.current.find((e) => e.id === edgeId);
3173
+ setLoopDraft(String(clamped));
3174
+ if (cur && cur.loop === true && normalizeMaxIterationsUI(cur.maxIterations) === clamped) return;
3175
+ pushSnapshot();
3176
+ setEdges((es) => es.map((e) => (e.id === edgeId ? { ...e, loop: true, maxIterations: clamped } : e)));
3177
+ };
3178
+
3179
+ const createLoopFromSelection = (selIds) => {
3180
+ const curNodes = nodesRef.current;
3181
+ const curEdges = edgesRef.current;
3182
+ const check = analyzeLoopSelection(curNodes, curEdges, selIds);
3183
+ if (!check.ok) {
3184
+ flash(check.reason === 'loopOverlap' ? t('loopOverlap') : t('cycleBlocked'));
3185
+ setCtxMenu(null);
3186
+ return;
3187
+ }
3188
+ pushSnapshot();
3189
+ const stamp = Date.now().toString(36);
3190
+ const exitNode = curNodes.find((n) => n.id === check.exitId);
3191
+ if (!exitNode) { setCtxMenu(null); return; }
3192
+
3193
+ if (check.needsAutoCondition) {
3194
+ const condId = 'n' + stamp + Math.random().toString(36).slice(2, 4);
3195
+ const isTB = directionRef.current === 'tb';
3196
+ const condX = isTB ? (exitNode.x || 0) : ((exitNode.x || 0) + 292);
3197
+ const condY = isTB ? ((exitNode.y || 0) + nodeHeight(exitNode) + 64) : (exitNode.y || 0);
3198
+ const prefs = lastNodePrefsRef.current || {};
3199
+ const condNode = {
3200
+ id: condId,
3201
+ kind: 'condition',
3202
+ x: condX,
3203
+ y: condY,
3204
+ label: t('loopAutoCondLabel'),
3205
+ provider: prefs.provider || '',
3206
+ model: prefs.model || '',
3207
+ reasoning: prefs.reasoning || '',
3208
+ preset: 'minimal',
3209
+ role: t('loopAutoCondRole'),
3210
+ };
3211
+ setNodes((ns) => ns.concat([condNode]));
3212
+ setEdges((es) => {
3213
+ const updated = [];
3214
+ let seq = 0;
3215
+ for (const e of es) {
3216
+ if (!e.loop && e.from === check.exitId) {
3217
+ if (e.type === 'session-ref') {
3218
+ // Preserve warm session-ref from exitNode as a condition-gated side channel,
3219
+ // and add a clean prompt wire from the new condition's `true` branch.
3220
+ updated.push(e);
3221
+ updated.push({ id: 'e' + stamp + 't' + (seq++), from: condId, to: e.to, type: 'prompt', branch: 'true' });
3222
+ } else {
3223
+ updated.push({ ...e, from: condId, type: 'prompt', branch: 'true' });
3224
+ }
3225
+ } else {
3226
+ updated.push(e);
3227
+ }
3228
+ }
3229
+ return updated.concat([
3230
+ { id: 'e' + stamp + 'f', from: check.exitId, to: condId, type: 'prompt' },
3231
+ {
3232
+ id: 'e' + stamp + 'l',
3233
+ from: condId,
3234
+ to: check.entryId,
3235
+ type: 'prompt',
3236
+ branch: 'false',
3237
+ loop: true,
3238
+ maxIterations: DEFAULT_LOOP_ITERATIONS,
3239
+ },
3240
+ ]);
3241
+ });
3242
+ setSelectedIds([condId]);
3243
+ setCtxMenu(null);
3244
+ flash(t('loopCreatedAutoCond'));
3245
+ return;
3246
+ }
3247
+
3248
+ const branches = conditionBranchesForUI(exitNode, lang);
3249
+ const usedBranchIds = new Set(curEdges.filter((e) => e.from === exitNode.id).map((e) => (e.branch || branches[0].id)));
3250
+ let chosenBranchId = '';
3251
+ if (!isCustomBranches(exitNode) && !usedBranchIds.has('false')) {
3252
+ chosenBranchId = 'false';
3253
+ } else {
3254
+ for (let i = branches.length - 1; i >= 0; i -= 1) {
3255
+ if (!usedBranchIds.has(branches[i].id)) { chosenBranchId = branches[i].id; break; }
3256
+ }
3257
+ }
3258
+ if (!chosenBranchId) {
3259
+ chosenBranchId = 'c' + stamp.slice(-4);
3260
+ const nextBranches = branches.map((b) => ({ id: b.id, label: b.label }))
3261
+ .concat([{ id: chosenBranchId, label: t('loopRetryBranch') }]);
3262
+ setNodes((ns) => ns.map((n) => (n.id === exitNode.id ? { ...n, branches: nextBranches } : n)));
3263
+ }
3264
+ setEdges((es) => es.concat([{
3265
+ id: 'e' + stamp + 'l',
3266
+ from: exitNode.id,
3267
+ to: check.entryId,
3268
+ type: 'prompt',
3269
+ branch: chosenBranchId,
3270
+ loop: true,
3271
+ maxIterations: DEFAULT_LOOP_ITERATIONS,
3272
+ }]));
3273
+ setCtxMenu(null);
3274
+ flash(t('loopCreated'));
2772
3275
  };
2773
3276
 
2774
3277
  const insertNodeOnEdge = (edgeId, kind, atWorld) => {
@@ -2839,9 +3342,13 @@ window.__ModuleLoader__.load({
2839
3342
  const deleteNode = (id) => {
2840
3343
  if (id === 'lead') { flash(t('leadLocked')); return; }
2841
3344
  pushSnapshot();
2842
- setNodes((ns) => ns.filter((n) => n.id !== id));
2843
- setEdges((es) => es.filter((e) => e.from !== id && e.to !== id));
3345
+ const nextNodes = nodesRef.current.filter((n) => n.id !== id);
3346
+ const remainingEdges = edgesRef.current.filter((e) => e.from !== id && e.to !== id);
3347
+ const { edges: cleaned } = pruneInvalidLoopEdges(nextNodes, remainingEdges);
3348
+ setNodes(nextNodes);
3349
+ setEdges(cleaned);
2844
3350
  setSelectedIds([]);
3351
+ setLoopEditEdgeId(null);
2845
3352
  flash(t('deletedNode'));
2846
3353
  };
2847
3354
 
@@ -2852,9 +3359,13 @@ window.__ModuleLoader__.load({
2852
3359
  if (!targets.length) { flash(t('leadLocked')); return; }
2853
3360
  const drop = new Set(targets);
2854
3361
  pushSnapshot();
2855
- setNodes((ns) => ns.filter((n) => !drop.has(n.id)));
2856
- setEdges((es) => es.filter((e) => !drop.has(e.from) && !drop.has(e.to)));
3362
+ const nextNodes = nodesRef.current.filter((n) => !drop.has(n.id));
3363
+ const remainingEdges = edgesRef.current.filter((e) => !drop.has(e.from) && !drop.has(e.to));
3364
+ const { edges: cleaned } = pruneInvalidLoopEdges(nextNodes, remainingEdges);
3365
+ setNodes(nextNodes);
3366
+ setEdges(cleaned);
2857
3367
  setSelectedIds([]);
3368
+ setLoopEditEdgeId(null);
2858
3369
  flash(targets.length === 1 ? t('deletedNode') : t('deletedNodes') + ' ×' + targets.length);
2859
3370
  };
2860
3371
 
@@ -2986,6 +3497,7 @@ window.__ModuleLoader__.load({
2986
3497
  setOpenModelFor(null);
2987
3498
  setAddMenu(null);
2988
3499
  setCtxMenu(null);
3500
+ setLoopEditEdgeId(null);
2989
3501
  e.preventDefault();
2990
3502
  e.stopPropagation();
2991
3503
  if (toggledOff) return;
@@ -3017,6 +3529,7 @@ window.__ModuleLoader__.load({
3017
3529
  setRoleEditFor(null);
3018
3530
  setDecisionViewFor(null);
3019
3531
  setRefsEditFor(null);
3532
+ setLoopEditEdgeId(null);
3020
3533
  };
3021
3534
 
3022
3535
  const addNodeRef = (node) => {
@@ -3093,38 +3606,62 @@ window.__ModuleLoader__.load({
3093
3606
  e.stopPropagation();
3094
3607
  };
3095
3608
 
3096
- /** Release over an output socket: completes a drag that started at the unified left input. */
3097
- const onOutputUp = (e, id, type, branch) => {
3098
- if (!pending || pending.dir !== 'in') return;
3099
- pendingHandledRef.current = true;
3100
- e.preventDefault();
3101
- e.stopPropagation();
3609
+ const tryAddEdge = (fromId, toId, type, branch, preferredMaxIter) => {
3610
+ if (!fromId || !toId || fromId === toId) return;
3102
3611
  const b = typeof branch === 'string' ? branch.trim() : '';
3103
- const toId = pending.toId;
3104
- if (toId && toId !== id) {
3105
- if (wouldCycle(nodesRef.current, edgesRef.current, id, toId)) {
3106
- flash(t('cycleBlocked'));
3107
- } else {
3612
+ if (wouldCycle(nodesRef.current, edgesRef.current, fromId, toId)) {
3613
+ const loopOk = canLinkAsLoop(nodesRef.current, edgesRef.current, fromId, toId);
3614
+ if (loopOk.ok) {
3108
3615
  pushSnapshot();
3616
+ const loopBranch = b || 'false';
3617
+ const maxIter = normalizeMaxIterationsUI(preferredMaxIter);
3109
3618
  setEdges((es) => {
3110
- if (es.some((x) => x.from === id && x.to === toId && x.type === type && (x.branch || '') === b)) return es;
3111
- const nextEdge = { id: 'e' + Date.now().toString(36), from: id, to: toId, type };
3112
- if (b) nextEdge.branch = b;
3113
- return [...es, nextEdge];
3619
+ if (es.some((x) => x.from === fromId && x.to === toId && (x.branch || '') === loopBranch)) return es;
3620
+ return [...es, {
3621
+ id: 'e' + Date.now().toString(36),
3622
+ from: fromId,
3623
+ to: toId,
3624
+ type: 'prompt',
3625
+ branch: loopBranch,
3626
+ loop: true,
3627
+ maxIterations: maxIter,
3628
+ }];
3114
3629
  });
3630
+ flash(t('loopCreated'));
3631
+ } else {
3632
+ flash(loopOk.reason === 'loopOverlap' ? t('loopOverlap') : t('cycleBlocked'));
3115
3633
  }
3634
+ return;
3116
3635
  }
3636
+ pushSnapshot();
3637
+ setEdges((es) => {
3638
+ if (es.some((x) => x.from === fromId && x.to === toId && x.type === type && (x.branch || '') === b)) return es;
3639
+ const nextEdge = { id: 'e' + Date.now().toString(36), from: fromId, to: toId, type };
3640
+ if (b) nextEdge.branch = b;
3641
+ return [...es, nextEdge];
3642
+ });
3643
+ };
3644
+
3645
+ /** Release over an output socket: completes a drag that started at the unified left input. */
3646
+ const onOutputUp = (e, id, type, branch) => {
3647
+ if (!pending || pending.dir !== 'in') return;
3648
+ pendingHandledRef.current = true;
3649
+ e.preventDefault();
3650
+ e.stopPropagation();
3651
+ tryAddEdge(id, pending.toId, type || 'prompt', branch, pending.maxIterations);
3117
3652
  setPending(null);
3118
3653
  setDragging(false);
3119
3654
  };
3120
3655
 
3121
- // Unified left input: dragging a connected input detaches the latest wire;
3656
+ // Unified left input: dragging a connected input detaches the latest forward wire
3657
+ // (preferring non-loop incoming links so loop back-edges aren't accidentally pulled);
3122
3658
  // dragging a free input starts a reverse wire that adopts whichever right output it drops onto.
3123
3659
  const onInputDown = (e, id) => {
3124
3660
  e.preventDefault();
3125
3661
  e.stopPropagation();
3126
3662
  const incoming = edges.filter((x) => x.to === id);
3127
- const link = incoming[incoming.length - 1];
3663
+ const forwardIncoming = incoming.filter((x) => !x.loop);
3664
+ const link = forwardIncoming.length ? forwardIncoming[forwardIncoming.length - 1] : incoming[incoming.length - 1];
3128
3665
  if (!link) {
3129
3666
  const node = nodes.find((n) => n.id === id);
3130
3667
  if (!node) return;
@@ -3136,7 +3673,9 @@ window.__ModuleLoader__.load({
3136
3673
  return;
3137
3674
  }
3138
3675
  pushSnapshot();
3139
- setEdges((es) => es.filter((x) => x.id !== link.id));
3676
+ const remaining = edgesRef.current.filter((x) => x.id !== link.id);
3677
+ const { edges: cleaned } = pruneInvalidLoopEdges(nodesRef.current, remaining);
3678
+ setEdges(cleaned);
3140
3679
  const from = nodes.find((n) => n.id === link.from);
3141
3680
  if (!from) return;
3142
3681
  const b = typeof link.branch === 'string' ? link.branch.trim() : '';
@@ -3145,7 +3684,18 @@ window.__ModuleLoader__.load({
3145
3684
  const sx = pos.x;
3146
3685
  const sy = pos.y;
3147
3686
  const color = edgeColorFor(from, link);
3148
- setPending({ dir: 'out', fromId: link.from, type: linkType, branch: b, color, sx, sy, x: sx, y: sy });
3687
+ setPending({
3688
+ dir: 'out',
3689
+ fromId: link.from,
3690
+ type: linkType,
3691
+ branch: b,
3692
+ maxIterations: link.loop ? normalizeMaxIterationsUI(link.maxIterations) : undefined,
3693
+ color,
3694
+ sx,
3695
+ sy,
3696
+ x: sx,
3697
+ y: sy,
3698
+ });
3149
3699
  setDragging(true);
3150
3700
  };
3151
3701
 
@@ -3154,22 +3704,7 @@ window.__ModuleLoader__.load({
3154
3704
  pendingHandledRef.current = true;
3155
3705
  e.preventDefault();
3156
3706
  e.stopPropagation();
3157
- if (pending.fromId !== id) {
3158
- const fromId = pending.fromId;
3159
- const type = pending.type || 'prompt';
3160
- const b = typeof pending.branch === 'string' ? pending.branch.trim() : '';
3161
- if (wouldCycle(nodesRef.current, edgesRef.current, fromId, id)) {
3162
- flash(t('cycleBlocked'));
3163
- } else {
3164
- pushSnapshot();
3165
- setEdges((es) => {
3166
- if (es.some((x) => x.from === fromId && x.to === id && x.type === type && (x.branch || '') === b)) return es;
3167
- const nextEdge = { id: 'e' + Date.now().toString(36), from: fromId, to: id, type };
3168
- if (b) nextEdge.branch = b;
3169
- return [...es, nextEdge];
3170
- });
3171
- }
3172
- }
3707
+ tryAddEdge(pending.fromId, id, pending.type || 'prompt', pending.branch, pending.maxIterations);
3173
3708
  setPending(null);
3174
3709
  setDragging(false);
3175
3710
  };
@@ -3234,8 +3769,8 @@ window.__ModuleLoader__.load({
3234
3769
  const keyActionsRef = useRef(null);
3235
3770
  keyActionsRef.current = {
3236
3771
  undo, redo, deleteSelected, duplicateSelected, openAddMenuAtCursor, addNode, fitView, autoLayout, toggleDirection, flash, t,
3237
- addMenu, ctxMenu, roleEditFor, openModelFor, menuOpen, presetOpen, helpOpen, shortcutsOpen, recordingAction, decisionViewFor, refsEditFor,
3238
- setAddMenu, setCtxMenu, setRoleEditFor, setOpenModelFor, setMenuOpen, setPresetOpen, setHelpOpen, setShortcutsOpen, setRecordingAction, setShortcuts, setDecisionViewFor, setRefsEditFor,
3772
+ addMenu, ctxMenu, loopEditEdgeId, roleEditFor, openModelFor, menuOpen, presetOpen, helpOpen, shortcutsOpen, recordingAction, decisionViewFor, refsEditFor,
3773
+ setAddMenu, setCtxMenu, setLoopEditEdgeId, setRoleEditFor, setOpenModelFor, setMenuOpen, setPresetOpen, setHelpOpen, setShortcutsOpen, setRecordingAction, setShortcuts, setDecisionViewFor, setRefsEditFor,
3239
3774
  };
3240
3775
  useEffect(() => {
3241
3776
  const isEditable = (target) => {
@@ -3264,10 +3799,11 @@ window.__ModuleLoader__.load({
3264
3799
  return;
3265
3800
  }
3266
3801
  if (ev.key === 'Escape') {
3267
- if (act.addMenu || act.ctxMenu || act.roleEditFor || act.openModelFor || act.menuOpen || act.presetOpen || act.helpOpen || act.shortcutsOpen || act.decisionViewFor || act.refsEditFor) {
3802
+ if (act.addMenu || act.ctxMenu || act.loopEditEdgeId || act.roleEditFor || act.openModelFor || act.menuOpen || act.presetOpen || act.helpOpen || act.shortcutsOpen || act.decisionViewFor || act.refsEditFor) {
3268
3803
  ev.preventDefault();
3269
3804
  act.setAddMenu(null);
3270
3805
  act.setCtxMenu(null);
3806
+ act.setLoopEditEdgeId(null);
3271
3807
  act.setRoleEditFor(null);
3272
3808
  act.setOpenModelFor(null);
3273
3809
  act.setMenuOpen(false);
@@ -3382,6 +3918,7 @@ window.__ModuleLoader__.load({
3382
3918
  if (menuOpen) setMenuOpen(false);
3383
3919
  if (addMenu) setAddMenu(null);
3384
3920
  if (ctxMenu) setCtxMenu(null);
3921
+ if (loopEditEdgeId) setLoopEditEdgeId(null);
3385
3922
  if (presetOpen) setPresetOpen(null);
3386
3923
  e.preventDefault();
3387
3924
  try { window.getSelection().removeAllRanges(); } catch (_sel) { /* ignore */ }
@@ -3439,7 +3976,7 @@ window.__ModuleLoader__.load({
3439
3976
  const source = nodeMap.get(edge.from);
3440
3977
  const target = nodeMap.get(edge.to);
3441
3978
  if (!source || !target) continue;
3442
- if (distanceToEdge(canvasSpot, source, target, edge, directionRef.current) <= threshold) {
3979
+ if (distanceToEdge(canvasSpot, source, target, edge, directionRef.current, nodes, edges) <= threshold) {
3443
3980
  cutHits.current.add(edge.id);
3444
3981
  }
3445
3982
  }
@@ -3478,7 +4015,7 @@ window.__ModuleLoader__.load({
3478
4015
  const source = nodeMap.get(edge.from);
3479
4016
  const target = nodeMap.get(edge.to);
3480
4017
  if (!source || !target) continue;
3481
- const dist = distanceToEdge(canvasSpot, source, target, edge, directionRef.current);
4018
+ const dist = distanceToEdge(canvasSpot, source, target, edge, directionRef.current, nodesRef.current, edgesRef.current);
3482
4019
  if (dist <= threshold && dist < bestDist) {
3483
4020
  bestDist = dist;
3484
4021
  hitEdge = edge;
@@ -3491,6 +4028,7 @@ window.__ModuleLoader__.load({
3491
4028
  setRoleEditFor(null);
3492
4029
  setDecisionViewFor(null);
3493
4030
  setRefsEditFor(null);
4031
+ setLoopEditEdgeId(null);
3494
4032
  if (hitEdge) {
3495
4033
  const pos = clampMenuPos(cx, cy, wrapRect.width, wrapRect.height, 180, 120);
3496
4034
  setCtxMenu({ kind: 'edge', edgeId: hitEdge.id, sx: pos.sx, sy: pos.sy, wx: rc.start.x, wy: rc.start.y });
@@ -3511,8 +4049,10 @@ window.__ModuleLoader__.load({
3511
4049
  cutHits.current = new Set();
3512
4050
  if (victims.length) {
3513
4051
  pushSnapshot();
3514
- setEdges((es) => es.filter((x) => !victimIds.has(x.id)));
3515
- flash(t('linkCut') + ' ×' + victims.length);
4052
+ const remaining = edgesRef.current.filter((x) => !victimIds.has(x.id));
4053
+ const { edges: cleaned, removedCount } = pruneInvalidLoopEdges(nodesRef.current, remaining);
4054
+ setEdges(cleaned);
4055
+ flash(t('linkCut') + ' ×' + victims.length + (removedCount > 0 ? t('loopPrunedNotice') : ''));
3516
4056
  }
3517
4057
  }
3518
4058
  if (cutPath.length) { setCutPath([]); setCutVictims([]); }
@@ -3659,6 +4199,10 @@ window.__ModuleLoader__.load({
3659
4199
  };
3660
4200
  const b = typeof e.branch === 'string' ? e.branch.trim() : '';
3661
4201
  if (b) item.branch = b;
4202
+ if (e.loop === true) {
4203
+ item.loop = true;
4204
+ item.maxIterations = normalizeMaxIterationsUI(e.maxIterations);
4205
+ }
3662
4206
  return item;
3663
4207
  });
3664
4208
  if (!merge) return incoming;
@@ -3668,8 +4212,20 @@ window.__ModuleLoader__.load({
3668
4212
  && String(r.to) === e.to
3669
4213
  && (!r.type || r.type === e.type)
3670
4214
  && (!r.branch || r.branch === e.branch));
3671
- const kept = existing.filter((e) => !matchesDrop(e) && !removedNodes.has(e.from) && !removedNodes.has(e.to));
3672
4215
  const keyOf = (e) => e.from + '>' + e.to + '|' + e.type + '|' + (e.branch || '');
4216
+ const incomingByKey = new Map(incoming.map((e) => [keyOf(e), e]));
4217
+ const kept = existing
4218
+ .filter((e) => !matchesDrop(e) && !removedNodes.has(e.from) && !removedNodes.has(e.to))
4219
+ .map((e) => {
4220
+ const inc = incomingByKey.get(keyOf(e));
4221
+ if (!inc) return e;
4222
+ if (inc.loop) return { ...e, loop: true, maxIterations: inc.maxIterations };
4223
+ if (e.loop && !inc.loop) {
4224
+ const { loop: _l, maxIterations: _m, ...rest } = e;
4225
+ return rest;
4226
+ }
4227
+ return e;
4228
+ });
3673
4229
  const seen = new Set(kept.map(keyOf));
3674
4230
  const added = incoming.filter((e) => !removedNodes.has(e.from) && !removedNodes.has(e.to) && !seen.has(keyOf(e)));
3675
4231
  return kept.concat(added);
@@ -4097,7 +4653,7 @@ window.__ModuleLoader__.load({
4097
4653
  const nodeById = new Map(nodes.map((n) => [n.id, n]));
4098
4654
  const inColorByNode = new Map();
4099
4655
  const inCountByNode = new Map();
4100
- const inPriority = (e) => (e.type === 'session-ref' ? 3 : (e.type === 'structured' ? 2 : (e.branch ? 1.5 : 1)));
4656
+ const inPriority = (e) => (e.loop ? 0.5 : (e.type === 'session-ref' ? 3 : (e.type === 'structured' ? 2 : (e.branch ? 1.5 : 1))));
4101
4657
  const inPrioByNode = new Map();
4102
4658
  const connectedOut = new Set();
4103
4659
  for (const e of edges) {
@@ -4165,16 +4721,39 @@ window.__ModuleLoader__.load({
4165
4721
  : {};
4166
4722
  const prunedSet = new Set(enabled && runState && Array.isArray(runState.pruned) ? runState.pruned : []);
4167
4723
  const blockedEdgeSet = new Set(enabled && runState && Array.isArray(runState.blockedEdges) ? runState.blockedEdges : []);
4724
+ const loopCountsMap = (enabled && runState && runState.loopCounts && typeof runState.loopCounts === 'object')
4725
+ ? runState.loopCounts
4726
+ : {};
4727
+ const nodeAttemptsMap = (enabled && runState && runState.nodeAttempts && typeof runState.nodeAttempts === 'object')
4728
+ ? runState.nodeAttempts
4729
+ : {};
4730
+ const loopGroups = loopGroupsForUI(nodes, edges);
4168
4731
  const edgeKeyForState = (e) => String(e.from) + '->' + String(e.to) + '|' + String(e.type || 'prompt') + '|' + String(e.branch || '');
4732
+ const loopPillItems = [];
4169
4733
 
4170
4734
  const edgeEls = edges.map((edge) => {
4171
4735
  const from = nodeById.get(edge.from);
4172
4736
  const to = nodeById.get(edge.to);
4173
4737
  if (!from || !to) return null;
4174
- const color = edgeColorFor(from, edge);
4175
- const d = edgePath(from, to, edge, direction);
4738
+ const isLoop = edge.loop === true;
4739
+ const loopInfo = isLoop ? loopGroups.byEdge.get(edge.id || (edge.from + '->' + edge.to)) : null;
4740
+ const color = isLoop ? ((loopInfo && loopInfo.color) || '#f0883e') : edgeColorFor(from, edge);
4741
+ const loopArc = isLoop ? loopEdgeArc(from, to, edge, direction, nodes, edges) : null;
4742
+ const d = loopArc ? loopArc.path : edgePath(from, to, edge, direction, nodes, edges);
4176
4743
  const highlighted = cutVictims.includes(edge.id);
4177
4744
  const isPrunedEdge = !highlighted && (blockedEdgeSet.has(edgeKeyForState(edge)) || prunedSet.has(edge.from) || prunedSet.has(edge.to));
4745
+ if (loopArc) {
4746
+ const live = loopCountsMap[edge.id] || loopCountsMap[edgeKeyForState(edge)] || null;
4747
+ loopPillItems.push({
4748
+ edge,
4749
+ color,
4750
+ midX: loopArc.midX,
4751
+ midY: loopArc.midY,
4752
+ maxIterations: normalizeMaxIterationsUI(edge.maxIterations),
4753
+ liveCount: live ? Number(live.count || 0) : 0,
4754
+ dimmed: isPrunedEdge,
4755
+ });
4756
+ }
4178
4757
  const hasSel = selectedSet.size > 0;
4179
4758
  const linkedToSel = hasSel && (selectedSet.has(edge.from) || selectedSet.has(edge.to));
4180
4759
  const toRunning = enabled && statusById[edge.to] === 'running';
@@ -4198,11 +4777,24 @@ window.__ModuleLoader__.load({
4198
4777
  const isCompletedLink = enabled && !highlighted && !isPrunedEdge && fromSettled && toSettled;
4199
4778
  const dimmed = isPrunedEdge || (hasSel && !linkedToSel && !highlighted && !isFlowing);
4200
4779
  const strokeColor = highlighted ? '#e5534b' : color;
4201
- const baseWidth = highlighted ? 3 : (linkedToSel || isFlowing ? 2.6 : 2);
4202
- const baseOpacity = isPrunedEdge ? 0.22 : (dimmed ? 0.26 : (isFlowing || linkedToSel ? 1 : (isCompletedLink ? 0.92 : 0.78)));
4780
+ const baseWidth = highlighted ? 3 : (linkedToSel || isFlowing || isLoop ? 2.4 : 2);
4781
+ const baseOpacity = isPrunedEdge ? 0.22 : (dimmed ? 0.26 : (isFlowing || linkedToSel || isLoop ? 0.96 : (isCompletedLink ? 0.92 : 0.78)));
4203
4782
  const useGlow = fxLevel === 'vivid' && !dimmed;
4204
4783
  const showDashFlow = isFlowing && fxLevel !== 'minimal';
4205
4784
  const showBead = isFlowing && fxLevel === 'vivid';
4785
+ // Arrowhead on loop entry point so the retry direction is unmistakable
4786
+ let loopArrow = null;
4787
+ if (loopArc && loopArc.points.length >= 2) {
4788
+ const endPt = loopArc.points[loopArc.points.length - 1];
4789
+ const prevPt = loopArc.points[loopArc.points.length - 2];
4790
+ const ang = Math.atan2(endPt.y - prevPt.y, endPt.x - prevPt.x);
4791
+ const sz = 7;
4792
+ const ax1 = endPt.x - sz * Math.cos(ang - 0.5);
4793
+ const ay1 = endPt.y - sz * Math.sin(ang - 0.5);
4794
+ const ax2 = endPt.x - sz * Math.cos(ang + 0.5);
4795
+ const ay2 = endPt.y - sz * Math.sin(ang + 0.5);
4796
+ loopArrow = endPt.x.toFixed(1) + ',' + endPt.y.toFixed(1) + ' ' + ax1.toFixed(1) + ',' + ay1.toFixed(1) + ' ' + ax2.toFixed(1) + ',' + ay2.toFixed(1);
4797
+ }
4206
4798
 
4207
4799
  return h('g', { key: edge.id, style: { pointerEvents: 'none' } },
4208
4800
  // Vector halo layers instead of an SVG objectBoundingBox <filter>, which
@@ -4228,9 +4820,14 @@ window.__ModuleLoader__.load({
4228
4820
  stroke: strokeColor,
4229
4821
  strokeWidth: baseWidth,
4230
4822
  strokeOpacity: showDashFlow ? 0.35 : baseOpacity,
4231
- strokeDasharray: isPrunedEdge ? '4 4' : undefined,
4823
+ strokeDasharray: isLoop ? '6 4' : (isPrunedEdge ? '4 4' : undefined),
4232
4824
  fill: 'none',
4233
4825
  }),
4826
+ loopArrow && h('polygon', {
4827
+ points: loopArrow,
4828
+ fill: strokeColor,
4829
+ fillOpacity: baseOpacity,
4830
+ }),
4234
4831
  showDashFlow && fxLevel === 'vivid' && h('path', {
4235
4832
  d,
4236
4833
  className: 'dsh-wc-edge-flow',
@@ -4958,11 +5555,14 @@ window.__ModuleLoader__.load({
4958
5555
  const target = nodeById.get(ctxMenu.nodeId);
4959
5556
  if (!target) return null;
4960
5557
  const multiSel = selectedIds.length > 1 && selectedSet.has(target.id);
4961
- const nonLeadCount = (multiSel ? selectedIds : [target.id]).filter((id) => id !== 'lead').length;
5558
+ const selList = multiSel ? selectedIds : [target.id];
5559
+ const nonLeadCount = selList.filter((id) => id !== 'lead').length;
4962
5560
  const suffix = nonLeadCount > 1 ? ' ×' + nonLeadCount : '';
4963
5561
  const latestRun = target.kind !== 'lead' ? runsById[target.id] : null;
5562
+ const existingLoop = loopGroups.byNode.get(target.id) || null;
5563
+ const loopCheck = !existingLoop ? analyzeLoopSelection(nodes, edges, selList) : { ok: false };
4964
5564
  return h('div', {
4965
- style: { ...S.addMenu, minWidth: '172px', left: ctxMenu.sx + 'px', top: ctxMenu.sy + 'px' },
5565
+ style: { ...S.addMenu, minWidth: '176px', left: ctxMenu.sx + 'px', top: ctxMenu.sy + 'px' },
4966
5566
  onMouseDown: (e) => e.stopPropagation(),
4967
5567
  onContextMenu: (e) => e.preventDefault(),
4968
5568
  },
@@ -4970,6 +5570,18 @@ window.__ModuleLoader__.load({
4970
5570
  menuRow('edit', t('ctxEditText'), () => { setCtxMenu(null); setRoleEditFor(target.id); }),
4971
5571
  menuRow('refs', t('ctxManageRefs'), () => { setCtxMenu(null); setRefsEditFor(target.id); }),
4972
5572
  latestRun && menuRow('chat', t('ctxOpenChat'), () => { setCtxMenu(null); openNodeSession(target); }),
5573
+ existingLoop && h('div', { style: S.ctxDivider }),
5574
+ existingLoop && menuRow('edit-loop', t('ctxEditLoop'), () => {
5575
+ setCtxMenu(null);
5576
+ openLoopEditor(existingLoop.edge);
5577
+ }),
5578
+ existingLoop && menuRow('rm-loop', t('ctxRemoveLoop'), () => deleteEdgeById(existingLoop.edge.id), { danger: true }),
5579
+ !existingLoop && loopCheck.ok && h('div', { style: S.ctxDivider }),
5580
+ !existingLoop && loopCheck.ok && menuRow(
5581
+ 'make-loop',
5582
+ loopCheck.needsAutoCondition ? t('ctxMakeLoopAuto') : t('ctxMakeLoop'),
5583
+ () => createLoopFromSelection(selList),
5584
+ ),
4973
5585
  nonLeadCount > 0 && h('div', { style: S.ctxDivider }),
4974
5586
  nonLeadCount > 0 && menuRow('dup', t('ctxDup') + suffix, () => { setCtxMenu(null); duplicateSelected(); }, { hint: shortcuts.duplicate || '' }),
4975
5587
  nonLeadCount > 0 && menuRow('del', t('ctxDelNode') + suffix, () => {
@@ -4988,10 +5600,21 @@ window.__ModuleLoader__.load({
4988
5600
  onContextMenu: (e) => e.preventDefault(),
4989
5601
  },
4990
5602
  h('div', { style: S.addMenuHead }, t('ctxEdgeTitle')),
4991
- menuRow('ins-agent', t('ctxInsertAgent'), () => insertNodeOnEdge(targetEdge.id, 'agent', { x: ctxMenu.wx, y: ctxMenu.wy })),
4992
- menuRow('ins-cond', t('ctxInsertCond'), () => insertNodeOnEdge(targetEdge.id, 'condition', { x: ctxMenu.wx, y: ctxMenu.wy })),
4993
- h('div', { style: S.ctxDivider }),
4994
- menuRow('del-edge', t('ctxDelEdge'), () => deleteEdgeById(targetEdge.id), { danger: true }),
5603
+ targetEdge.loop
5604
+ ? h(React.Fragment, null,
5605
+ menuRow('edit-loop', t('ctxEditLoop'), () => {
5606
+ setCtxMenu(null);
5607
+ openLoopEditor(targetEdge);
5608
+ }),
5609
+ h('div', { style: S.ctxDivider }),
5610
+ menuRow('rm-loop', t('ctxRemoveLoop'), () => deleteEdgeById(targetEdge.id), { danger: true }),
5611
+ )
5612
+ : h(React.Fragment, null,
5613
+ menuRow('ins-agent', t('ctxInsertAgent'), () => insertNodeOnEdge(targetEdge.id, 'agent', { x: ctxMenu.wx, y: ctxMenu.wy })),
5614
+ menuRow('ins-cond', t('ctxInsertCond'), () => insertNodeOnEdge(targetEdge.id, 'condition', { x: ctxMenu.wx, y: ctxMenu.wy })),
5615
+ h('div', { style: S.ctxDivider }),
5616
+ menuRow('del-edge', t('ctxDelEdge'), () => deleteEdgeById(targetEdge.id), { danger: true }),
5617
+ ),
4995
5618
  );
4996
5619
  }
4997
5620
  return h('div', {
@@ -5079,6 +5702,101 @@ window.__ModuleLoader__.load({
5079
5702
  return h('path', { d, stroke: color, strokeWidth: 2, strokeDasharray: '4 4', fill: 'none' });
5080
5703
  })(),
5081
5704
  ),
5705
+ loopPillItems.map((item) => {
5706
+ const isOpen = loopEditEdgeId === item.edge.id;
5707
+ const pillText = item.liveCount > 0
5708
+ ? ('↺ ' + item.liveCount + '/' + item.maxIterations)
5709
+ : ('↺ ×' + item.maxIterations);
5710
+ const commitLoopDraft = (closeAfter) => {
5711
+ const v = parseInt(String(loopDraft || '').trim(), 10);
5712
+ if (Number.isFinite(v)) updateLoopMaxIterations(item.edge.id, v);
5713
+ else setLoopDraft(String(item.maxIterations));
5714
+ if (closeAfter) setLoopEditEdgeId(null);
5715
+ };
5716
+ return h('div', {
5717
+ key: 'loop-pill-' + item.edge.id,
5718
+ style: {
5719
+ ...S.loopPill,
5720
+ left: item.midX + 'px',
5721
+ top: item.midY + 'px',
5722
+ border: '1.5px solid ' + item.color,
5723
+ color: item.color,
5724
+ opacity: item.dimmed && !isOpen ? 0.42 : 1,
5725
+ zIndex: isOpen ? 55 : 18,
5726
+ },
5727
+ title: t('loopTipPill'),
5728
+ onMouseDown: (e) => e.stopPropagation(),
5729
+ onContextMenu: (e) => {
5730
+ e.preventDefault();
5731
+ e.stopPropagation();
5732
+ if (isOpen) setLoopEditEdgeId(null);
5733
+ else openLoopEditor(item.edge);
5734
+ },
5735
+ onClick: (e) => {
5736
+ e.stopPropagation();
5737
+ setCtxMenu(null);
5738
+ if (isOpen) setLoopEditEdgeId(null);
5739
+ else openLoopEditor(item.edge);
5740
+ },
5741
+ },
5742
+ h('span', null, pillText),
5743
+ isOpen && h('div', {
5744
+ style: S.loopPopover,
5745
+ onMouseDown: (e) => e.stopPropagation(),
5746
+ onClick: (e) => e.stopPropagation(),
5747
+ },
5748
+ h('div', {
5749
+ style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px', fontSize: '10px', color: C.dim },
5750
+ },
5751
+ h('span', null, t('loopModalTitle')),
5752
+ h('button', {
5753
+ type: 'button',
5754
+ style: { background: 'transparent', border: 'none', color: C.dim, cursor: 'pointer', fontSize: '12px', padding: '0 2px' },
5755
+ onClick: () => setLoopEditEdgeId(null),
5756
+ }, '×'),
5757
+ ),
5758
+ h('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px', marginBottom: '7px' } },
5759
+ h('button', {
5760
+ type: 'button',
5761
+ style: S.loopStepBtn,
5762
+ disabled: item.maxIterations <= 1,
5763
+ onClick: () => updateLoopMaxIterations(item.edge.id, item.maxIterations - 1),
5764
+ }, '−'),
5765
+ h('input', {
5766
+ type: 'text',
5767
+ inputMode: 'numeric',
5768
+ style: S.loopNumInput,
5769
+ value: loopDraft,
5770
+ onChange: (e) => {
5771
+ const raw = e.target.value.replace(/[^\d]/g, '').slice(0, 2);
5772
+ setLoopDraft(raw);
5773
+ },
5774
+ onBlur: () => commitLoopDraft(false),
5775
+ onKeyDown: (e) => {
5776
+ if (e.key === 'Enter') {
5777
+ e.preventDefault();
5778
+ commitLoopDraft(true);
5779
+ } else if (e.key === 'Escape') {
5780
+ e.preventDefault();
5781
+ setLoopEditEdgeId(null);
5782
+ }
5783
+ },
5784
+ }),
5785
+ h('button', {
5786
+ type: 'button',
5787
+ style: S.loopStepBtn,
5788
+ disabled: item.maxIterations >= MAX_LOOP_ITERATIONS,
5789
+ onClick: () => updateLoopMaxIterations(item.edge.id, item.maxIterations + 1),
5790
+ }, '+'),
5791
+ ),
5792
+ h('button', {
5793
+ type: 'button',
5794
+ style: { ...S.btn, width: '100%', padding: '3px 6px', fontSize: '10px', color: '#e5534b', textAlign: 'center' },
5795
+ onClick: () => deleteEdgeById(item.edge.id),
5796
+ }, t('ctxRemoveLoop')),
5797
+ ),
5798
+ );
5799
+ }),
5082
5800
  nodes.map((node) => {
5083
5801
  const isEntry = node.id === 'lead';
5084
5802
  const isLeadKind = node.kind === 'lead';
@@ -5127,6 +5845,8 @@ window.__ModuleLoader__.load({
5127
5845
  : 'linear-gradient(90deg, #2f81f7 0%, #58d580 50%, #2f81f7 100%)'))
5128
5846
  : (isFailed ? '#e5534b' : (isLeadKind ? '#2f81f7' : (isCondKind ? '#d29922' : '#3fb950')));
5129
5847
  const isPruned = enabled && prunedSet.has(node.id);
5848
+ const nodeLoop = loopGroups.byNode.get(node.id) || null;
5849
+ const nodeAttempt = nodeAttemptsMap[node.id] || null;
5130
5850
  const condDecision = isCondKind ? (decisionsById[node.id] || null) : null;
5131
5851
  const verdictInfo = condDecision ? conditionVerdictSummary(condDecision, lang) : null;
5132
5852
  const hasOpenPopover = decisionViewFor === node.id
@@ -5145,12 +5865,22 @@ window.__ModuleLoader__.load({
5145
5865
  ...(isLeadKind ? S.leadNode : null),
5146
5866
  ...(isInactive || isPruned ? S.orphanNode : null),
5147
5867
  ...(stateStyle || null),
5868
+ ...(nodeLoop ? { outline: '1.5px dashed ' + nodeLoop.color, outlineOffset: '3px' } : null),
5148
5869
  ...(hasOpenPopover ? { zIndex: 40 } : null),
5149
5870
  },
5150
5871
  title: isPruned ? t('tipPruned') : (isOrphan ? t('orphanTip') : (isSoloLead ? t('tipSoloLead') : (isDeadEnd ? t('tipDeadEnd') : undefined))),
5151
5872
  onMouseDown: (e) => onNodeDown(e, node.id),
5152
5873
  onContextMenu: (e) => onNodeContextMenu(e, node),
5153
5874
  },
5875
+ nodeLoop && h('div', {
5876
+ style: {
5877
+ ...S.loopNodeTag,
5878
+ color: nodeLoop.color,
5879
+ border: '1px solid ' + nodeLoop.color,
5880
+ },
5881
+ }, nodeAttempt && nodeAttempt.retry > 0
5882
+ ? ('↺ ' + nodeAttempt.retry + '/' + nodeAttempt.max)
5883
+ : ('↺' + nodeLoop.index)),
5154
5884
  h('div', {
5155
5885
  className: (isRunning || isLeadReady) && fxLevel === 'vivid' ? 'dsh-wc-topbar-vivid' : undefined,
5156
5886
  style: {
@@ -5562,7 +6292,7 @@ window.__ModuleLoader__.load({
5562
6292
  try { console.error('[workflow-canvas] apply failed', error); } catch (_e) { /* ignore */ }
5563
6293
  }
5564
6294
  },
5565
- __test: { topoOrder, wouldCycle, soloLeadNodeIds, layoutGraph, builtinTemplates, deadEndNodeIds, nextEffectLevel, nextMaxParallel, dropdownAlign, zoomAroundPoint, scrubZoom, buildPlan, loadDoc, saveDoc, storageKey, socketCenterY, nodeHeight, conditionBranchesForUI, distanceToEdge, edgeCurve, compatibleTargetsForWire, conditionVerdictSummary, entryRunButtonState, outputSocketX, inputSocketPos, outputSocketPos, normalizeRefsUI, clampMenuPos, cloneSelection, nextSelectionOnNodeClick, DEFAULT_SHORTCUTS, normalizeShortcut, formatShortcutFromEvent, matchesShortcut, applyShortcutBinding },
6295
+ __test: { topoOrder, wouldCycle, soloLeadNodeIds, layoutGraph, builtinTemplates, deadEndNodeIds, nextEffectLevel, nextMaxParallel, dropdownAlign, zoomAroundPoint, scrubZoom, buildPlan, loadDoc, saveDoc, storageKey, socketCenterY, nodeHeight, conditionBranchesForUI, distanceToEdge, edgeCurve, compatibleTargetsForWire, conditionVerdictSummary, entryRunButtonState, outputSocketX, inputSocketPos, outputSocketPos, normalizeRefsUI, clampMenuPos, cloneSelection, nextSelectionOnNodeClick, DEFAULT_SHORTCUTS, normalizeShortcut, formatShortcutFromEvent, matchesShortcut, applyShortcutBinding, normalizeMaxIterationsUI, loopMemberIdsUI, loopGroupsForUI, pruneInvalidLoopEdges, canLinkAsLoop, analyzeLoopSelection, loopEdgeArc },
5566
6296
  };
5567
6297
  },
5568
6298
  });