dsh-workflow-canvas 1.4.0 → 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
@@ -37,11 +37,12 @@ window.__ModuleLoader__.load({
37
37
  duplicate: 'Shift+D',
38
38
  delete: 'Delete',
39
39
  undo: 'Ctrl+Z',
40
+ redo: 'Ctrl+Shift+Z',
40
41
  fitView: '',
41
42
  autoLayout: '',
42
43
  toggleDir: '',
43
44
  };
44
- const SHORTCUT_ORDER = ['addNode', 'duplicate', 'delete', 'undo', 'fitView', 'autoLayout', 'toggleDir'];
45
+ const SHORTCUT_ORDER = ['addNode', 'duplicate', 'delete', 'undo', 'redo', 'fitView', 'autoLayout', 'toggleDir'];
45
46
 
46
47
  const NODE_W = 216;
47
48
  const NODE_H = 234;
@@ -50,6 +51,9 @@ window.__ModuleLoader__.load({
50
51
  const ROW_H = 18;
51
52
  const COND_ROW_H = 20;
52
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;
53
57
  const CONTENT_W = 2400;
54
58
  const CONTENT_H = 1600;
55
59
  /** World origin offset: keeps negative node coordinates inside the scroll area. */
@@ -114,7 +118,7 @@ window.__ModuleLoader__.load({
114
118
  const LANG_KEY = STORAGE_PREFIX + 'lang';
115
119
  const I18N = {
116
120
  zh: {
117
- addAgent: '+ 子代理', addLead: '+ Lead', addCond: '+ 条件', undo: '↶ 撤销', sync: '↥ 同步',
121
+ addAgent: '+ 子代理', addLead: '+ Lead', addCond: '+ 条件', undo: '↶ 撤销', redo: '↷ 重做', sync: '↥ 同步',
118
122
  enabled: '● 已启用', disabled: '○ 已禁用', presetName: '预设名', save: '☆ 保存',
119
123
  presets: '☰ 预设', unsaved: '有未同步改动', synced: '已同步',
120
124
  pickModel: '选择模型', loadingModels: '加载中…', defaultEffort: '默认',
@@ -165,7 +169,7 @@ window.__ModuleLoader__.load({
165
169
  loadedPreset: '已载入预设', invalidPreset: '预设内容无效', deletedPreset: '已删除预设',
166
170
  syncFailed: '同步失败', upToDate: '已是最新', syncedToHost: '已同步到 Host',
167
171
  syncedWithStdWarn: '已同步(含可写/命令节点,请确认主对话权限已放开)',
168
- cannotOpen: '无法打开会话', undoDone: '已撤销', undoNone: '没有可撤销的操作',
172
+ cannotOpen: '无法打开会话', undoDone: '已撤销', undoNone: '没有可撤销的操作', redoDone: '已重做', redoNone: '没有可重做的操作',
169
173
  leadLocked: '入口 Lead 不能删除', modelsMissing: '模型列表未加载',
170
174
  tipLead: 'Lead 步骤在对话里执行,画布不追踪其状态',
171
175
  tipOrphan: '未连线:运行时会被跳过', tipStatus: '子代理节点的运行状态',
@@ -186,7 +190,7 @@ window.__ModuleLoader__.load({
186
190
  helpBody: [
187
191
  '1. 在入口 Lead 里写「本次任务」,这是整张图的总目标。',
188
192
  '2. 点「+ 子代理 / + Lead / + 条件」加节点,从右侧输出口拖到另一个节点左侧输入口即可连线。',
189
- '3. 输出口决定连线类型:prompt(灰,纯文本)、structured(蓝,JSON)、session(紫,复用上游会话);条件节点支持多路分支(单选 switch/case 或多选并行,全不满足时跳过中间分支直达最近 Lead)。',
193
+ '3. 输出口决定连线类型:prompt(灰,纯文本)、structured(蓝,JSON)、session(紫,复用上游会话);条件节点支持多路分支,并可将分支连回上游(或多选节点右键「↺ 设为回环」)实现带反馈的受控重试(点 ↺ 徽章可调 1–10 次,超限自动交 Lead 熔断)。',
190
194
  '4. 节点左侧为统一通用输入口,可直接接收任意颜色的连线;拖已连接的左口可断开最近一条连线。',
191
195
  '5. 每个节点可设模型、推理强度、能力范围、备用模型、是否记忆;复杂任务/分工/条件可点 ⤢ 展开大框编辑。',
192
196
  '6. 连好后点「● 已启用」,然后对对话说「跑一次」,由我调用执行。',
@@ -255,6 +259,19 @@ window.__ModuleLoader__.load({
255
259
  ctxInsertAgent: '在此插入子代理',
256
260
  ctxInsertCond: '在此插入条件节点',
257
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: '(内部连线断开,已清理失效回环)',
258
275
  shortcutsMenu: '⌨ 快捷键设置',
259
276
  shortcutsTitle: '快捷键设置',
260
277
  shortcutsHint: '点击右侧按键框后按下新组合键;按 Esc 取消录制,点 × 清除绑定。',
@@ -267,6 +284,7 @@ window.__ModuleLoader__.load({
267
284
  scDuplicate: '复制选中节点与连线',
268
285
  scDelete: '删除选中节点',
269
286
  scUndo: '撤销',
287
+ scRedo: '重做',
270
288
  scFitView: '全览居中',
271
289
  scAutoLayout: '自动排版',
272
290
  scToggleDir: '切换横排 / 竖排',
@@ -285,7 +303,7 @@ window.__ModuleLoader__.load({
285
303
  importNone: '剪贴板里没有可识别的画布数据',
286
304
  importBad: '画布数据格式不对',
287
305
  tipSync: '把当前画布同步给 Host(会在对话里留一条同步记录)',
288
- tipUndo: '撤销上一步结构改动', tipSave: '把当前画布保存为预设(可在新会话载入)',
306
+ tipUndo: '撤销上一步结构改动', tipRedo: '重做上一步撤销的改动(Ctrl+Shift+Z / Ctrl+Y)', tipSave: '把当前画布保存为预设(可在新会话载入)',
289
307
  tipPresets: '保存当前画布、跨会话复用,或载入内置模板', tipModel: '推理等级(默认 = 该模型声明的 defaultEffort)',
290
308
  tipMemory: '记忆:复用这个节点上一次的会话(跨运行及重启后可恢复)',
291
309
  memLatest: '最新',
@@ -299,7 +317,7 @@ window.__ModuleLoader__.load({
299
317
  lang: 'ZH',
300
318
  },
301
319
  en: {
302
- addAgent: '+ Subagent', addLead: '+ Lead', addCond: '+ Condition', undo: '↶ Undo', sync: '↥ Sync',
320
+ addAgent: '+ Subagent', addLead: '+ Lead', addCond: '+ Condition', undo: '↶ Undo', redo: '↷ Redo', sync: '↥ Sync',
303
321
  enabled: '● ON', disabled: '○ OFF', presetName: 'Preset name', save: '☆ Save',
304
322
  presets: '☰ Presets', unsaved: 'Unsaved changes', synced: 'Synced',
305
323
  pickModel: 'Pick a model', loadingModels: 'Loading…', defaultEffort: 'default',
@@ -350,7 +368,7 @@ window.__ModuleLoader__.load({
350
368
  loadedPreset: 'Loaded preset', invalidPreset: 'Preset content is invalid', deletedPreset: 'Deleted preset',
351
369
  syncFailed: 'Sync failed', upToDate: 'Already up to date', syncedToHost: 'Synced to host',
352
370
  syncedWithStdWarn: 'Synced (has write/tool nodes — check main chat permission mode)',
353
- cannotOpen: 'Cannot open the session', undoDone: 'Undone', undoNone: 'Nothing to undo',
371
+ cannotOpen: 'Cannot open the session', undoDone: 'Undone', undoNone: 'Nothing to undo', redoDone: 'Redone', redoNone: 'Nothing to redo',
354
372
  leadLocked: 'The entry Lead cannot be deleted', modelsMissing: 'Model list is not loaded',
355
373
  tipLead: 'Lead steps run in the chat; the canvas does not track them',
356
374
  tipOrphan: 'Unlinked: skipped when the canvas runs', tipStatus: 'Subagent run status',
@@ -371,7 +389,7 @@ window.__ModuleLoader__.load({
371
389
  helpBody: [
372
390
  '1. Write the overall task in the entry Lead node.',
373
391
  '2. Add nodes with + Subagent / + Lead / + Condition, then drag from a right socket to a left socket.',
374
- '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).',
375
393
  '4. Every node has one universal left input that accepts any incoming wire; drag a connected input away to detach the latest wire.',
376
394
  '5. Each node sets model, reasoning, capability scope, fallback model and memory; click ⤢ to expand a larger editor for long text.',
377
395
  '6. Press ● ON, then ask in chat to run the canvas.',
@@ -440,6 +458,19 @@ window.__ModuleLoader__.load({
440
458
  ctxInsertAgent: 'Insert Subagent here',
441
459
  ctxInsertCond: 'Insert Condition here',
442
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)',
443
474
  shortcutsMenu: '⌨ Shortcuts',
444
475
  shortcutsTitle: 'Keyboard Shortcuts',
445
476
  shortcutsHint: 'Click a key button then press a new combo. Press Esc to cancel, or × to clear.',
@@ -452,6 +483,7 @@ window.__ModuleLoader__.load({
452
483
  scDuplicate: 'Duplicate nodes & links',
453
484
  scDelete: 'Delete selected nodes',
454
485
  scUndo: 'Undo',
486
+ scRedo: 'Redo',
455
487
  scFitView: 'Fit all in view',
456
488
  scAutoLayout: 'Auto layout',
457
489
  scToggleDir: 'Toggle Horiz / Vert layout',
@@ -470,7 +502,7 @@ window.__ModuleLoader__.load({
470
502
  importNone: 'No canvas data found in the clipboard',
471
503
  importBad: 'Canvas data is malformed',
472
504
  tipSync: 'Publish this canvas to the host (leaves one sync record in the chat)',
473
- tipUndo: 'Undo the last structural change', tipSave: 'Save this canvas as a preset (reusable in new chats)',
505
+ tipUndo: 'Undo the last structural change', tipRedo: 'Redo the last undone change (Ctrl+Shift+Z / Ctrl+Y)', tipSave: 'Save this canvas as a preset (reusable in new chats)',
474
506
  tipPresets: 'Save this canvas for new chats, or load a preset / starter template', tipModel: 'Reasoning effort (default = the model\'s defaultEffort)',
475
507
  tipMemory: 'Memory: reuse this node\'s previous session (persisted across runs and restarts)',
476
508
  memLatest: 'Latest',
@@ -576,6 +608,39 @@ window.__ModuleLoader__.load({
576
608
  ctxDivider: {
577
609
  height: '1px', background: C.border, opacity: 0.65, margin: '3px 4px',
578
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
+ },
579
644
  canvasWrap: {
580
645
  position: 'relative', flex: '1 1 auto', minHeight: '0',
581
646
  display: 'flex', flexDirection: 'column',
@@ -989,6 +1054,16 @@ window.__ModuleLoader__.load({
989
1054
  return { clones, clonedEdges };
990
1055
  }
991
1056
 
1057
+ /** Compute the next node selection when clicking `id` (Shift/Ctrl toggles membership). */
1058
+ function nextSelectionOnNodeClick(selectedIds, id, additive) {
1059
+ const cur = Array.isArray(selectedIds) ? selectedIds : [];
1060
+ if (additive) {
1061
+ if (cur.includes(id)) return { next: cur.filter((x) => x !== id), toggledOff: true };
1062
+ return { next: cur.concat([id]), toggledOff: false };
1063
+ }
1064
+ return { next: cur.includes(id) ? cur : [id], toggledOff: false };
1065
+ }
1066
+
992
1067
  function socketCenterY(i) {
993
1068
  return SOCKET_BAND_TOP + i * ROW_H + ROW_H / 2;
994
1069
  }
@@ -1214,6 +1289,257 @@ window.__ModuleLoader__.load({
1214
1289
  return doc;
1215
1290
  }
1216
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
+
1217
1543
  /** Control points of one link, in canvas coordinates. Supports horizontal (lr) and vertical (tb) flow. */
1218
1544
  function edgeCurve(from, to, typeOrEdge, direction) {
1219
1545
  const type = (typeOrEdge && typeof typeOrEdge === 'object') ? (typeOrEdge.type || 'prompt') : (typeOrEdge || 'prompt');
@@ -1252,13 +1578,24 @@ window.__ModuleLoader__.load({
1252
1578
  return { x1, y1, c1x: x1 + dx, c1y: y1, c2x: x2 - dx, c2y: y2, x2, y2 };
1253
1579
  }
1254
1580
 
1255
- 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
+ }
1256
1585
  const c = edgeCurve(from, to, typeOrEdge, direction);
1257
1586
  return 'M ' + c.x1 + ' ' + c.y1 + ' C ' + c.c1x + ' ' + c.c1y + ', ' + c.c2x + ' ' + c.c2y + ', ' + c.x2 + ' ' + c.y2;
1258
1587
  }
1259
1588
 
1260
- /** Shortest distance between a point and one link, sampled along the curve. */
1261
- 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
+ }
1262
1599
  const c = edgeCurve(from, to, typeOrEdge, direction);
1263
1600
  let best = Infinity;
1264
1601
  let prevX = c.x1;
@@ -1288,7 +1625,7 @@ window.__ModuleLoader__.load({
1288
1625
  function topoOrder(nodes, edges) {
1289
1626
  const indeg = new Map(nodes.map((n) => [n.id, 0]));
1290
1627
  const adj = new Map(nodes.map((n) => [n.id, []]));
1291
- for (const e of edges) {
1628
+ for (const e of forwardEdgesUI(edges)) {
1292
1629
  if (!indeg.has(e.from) || !indeg.has(e.to)) continue;
1293
1630
  indeg.set(e.to, indeg.get(e.to) + 1);
1294
1631
  adj.get(e.from).push(e.to);
@@ -1306,10 +1643,10 @@ window.__ModuleLoader__.load({
1306
1643
  return out.length === nodes.length ? out : null;
1307
1644
  }
1308
1645
 
1309
- /** 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. */
1310
1647
  function reachableFrom(nodes, edges) {
1311
1648
  const adj = new Map();
1312
- for (const e of edges || []) {
1649
+ for (const e of forwardEdgesUI(edges)) {
1313
1650
  if (!e || !e.from || !e.to) continue;
1314
1651
  if (!adj.has(e.from)) adj.set(e.from, []);
1315
1652
  adj.get(e.from).push(e.to);
@@ -1332,7 +1669,7 @@ window.__ModuleLoader__.load({
1332
1669
  */
1333
1670
  function soloLeadNodeIds(nodes, edges) {
1334
1671
  const list = Array.isArray(nodes) ? nodes : [];
1335
- const linkList = Array.isArray(edges) ? edges : [];
1672
+ const linkList = forwardEdgesUI(edges);
1336
1673
  const reachable = reachableFrom(list, linkList);
1337
1674
  const byId = new Map(list.map((n) => [n.id, n]));
1338
1675
  const out = new Set();
@@ -1357,13 +1694,14 @@ window.__ModuleLoader__.load({
1357
1694
  function deadEndNodeIds(nodes, edges) {
1358
1695
  const list = Array.isArray(nodes) ? nodes : [];
1359
1696
  const linkList = Array.isArray(edges) ? edges : [];
1360
- const reachable = reachableFrom(list, linkList);
1361
- const soloLeads = soloLeadNodeIds(list, linkList);
1697
+ const fwdLinks = forwardEdgesUI(linkList);
1698
+ const reachable = reachableFrom(list, fwdLinks);
1699
+ const soloLeads = soloLeadNodeIds(list, fwdLinks);
1362
1700
  const downstreamLeads = list.filter((n) => n.kind === 'lead' && n.id !== 'lead' && reachable.has(n.id) && !soloLeads.has(n.id));
1363
1701
  if (!downstreamLeads.length) return new Set();
1364
1702
  const hasOut = new Set(linkList.map((e) => e.from));
1365
1703
  const parents = new Map();
1366
- for (const e of linkList) {
1704
+ for (const e of fwdLinks) {
1367
1705
  if (!parents.has(e.to)) parents.set(e.to, []);
1368
1706
  parents.get(e.to).push(e.from);
1369
1707
  }
@@ -1387,11 +1725,11 @@ window.__ModuleLoader__.load({
1387
1725
  return out;
1388
1726
  }
1389
1727
 
1390
- /** 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. */
1391
1729
  function wouldCycle(nodes, edges, fromId, toId) {
1392
1730
  if (!fromId || !toId || fromId === toId || toId === 'lead') return true;
1393
1731
  const adj = new Map();
1394
- for (const e of edges || []) {
1732
+ for (const e of forwardEdgesUI(edges)) {
1395
1733
  if (!adj.has(e.from)) adj.set(e.from, []);
1396
1734
  adj.get(e.from).push(e.to);
1397
1735
  }
@@ -1407,10 +1745,10 @@ window.__ModuleLoader__.load({
1407
1745
  return false;
1408
1746
  }
1409
1747
 
1410
- /** 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). */
1411
1749
  function layoutGraph(nodes, edges, direction) {
1412
1750
  const list = Array.isArray(nodes) ? nodes : [];
1413
- const linkList = Array.isArray(edges) ? edges : [];
1751
+ const linkList = forwardEdgesUI(edges);
1414
1752
  if (!list.length) return [];
1415
1753
  const reachable = reachableFrom(list, linkList);
1416
1754
  const depth = new Map(list.map((n) => [n.id, n.id === 'lead' ? 0 : 1]));
@@ -1660,6 +1998,54 @@ window.__ModuleLoader__.load({
1660
1998
  { id: 'cd5', from: 'c_yes', to: 'c_final', type: 'prompt' },
1661
1999
  { id: 'cd6', from: 'c_no', to: 'c_final', type: 'prompt' },
1662
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
+ ];
1663
2049
  return [
1664
2050
  {
1665
2051
  id: 'tpl-swe',
@@ -1685,6 +2071,12 @@ window.__ModuleLoader__.load({
1685
2071
  nodes: layoutGraph(condNodes, condEdges, direction),
1686
2072
  edges: condEdges,
1687
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
+ },
1688
2080
  ];
1689
2081
  }
1690
2082
 
@@ -1709,12 +2101,17 @@ window.__ModuleLoader__.load({
1709
2101
  }
1710
2102
 
1711
2103
  const activeIds = new Set(active.map((n) => n.id));
1712
- const planEdges = edges
1713
- .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
1714
2107
  .map((e) => {
1715
2108
  const item = { from: e.from, to: e.to, type: e.type || 'prompt' };
1716
2109
  const b = typeof e.branch === 'string' ? e.branch.trim() : '';
1717
2110
  if (b) item.branch = b;
2111
+ if (e.loop === true) {
2112
+ item.loop = true;
2113
+ item.maxIterations = normalizeMaxIterationsUI(e.maxIterations);
2114
+ }
1718
2115
  return item;
1719
2116
  });
1720
2117
 
@@ -2087,6 +2484,8 @@ window.__ModuleLoader__.load({
2087
2484
  const lastMouseRef = useRef(null);
2088
2485
  const [addMenu, setAddMenu] = useState(null);
2089
2486
  const [ctxMenu, setCtxMenu] = useState(null);
2487
+ const [loopEditEdgeId, setLoopEditEdgeId] = useState(null);
2488
+ const [loopDraft, setLoopDraft] = useState('');
2090
2489
  const rightClickRef = useRef(null);
2091
2490
  const nodeDrag = useRef(null);
2092
2491
  const panDrag = useRef(null);
@@ -2098,6 +2497,7 @@ window.__ModuleLoader__.load({
2098
2497
  const syncTimer = useRef(null);
2099
2498
  const lastSync = useRef('');
2100
2499
  const historyRef = useRef([]);
2500
+ const redoRef = useRef([]);
2101
2501
  const [dirty, setDirty] = useState(() => Boolean(initial && initial.enabled));
2102
2502
  const [view, setView] = useState({ k: 1, x: 0, y: 0 });
2103
2503
  const viewRef = useRef(view);
@@ -2486,6 +2886,7 @@ window.__ModuleLoader__.load({
2486
2886
  e.preventDefault();
2487
2887
  absorbScroll();
2488
2888
  setCtxMenu(null);
2889
+ setLoopEditEdgeId(null);
2489
2890
  const rect = el.getBoundingClientRect();
2490
2891
  const mx = e.clientX - rect.left;
2491
2892
  const my = e.clientY - rect.top;
@@ -2630,21 +3031,35 @@ window.__ModuleLoader__.load({
2630
3031
  };
2631
3032
  }, []);
2632
3033
 
2633
- // Snapshot before every structural change so a mis-click can be undone.
3034
+ // Snapshot before every structural change so a mis-click can be undone/redone.
2634
3035
  const pushSnapshot = () => {
2635
- historyRef.current.push({ nodes, edges });
3036
+ historyRef.current.push({ nodes: nodesRef.current, edges: edgesRef.current });
2636
3037
  if (historyRef.current.length > 50) historyRef.current.shift();
3038
+ redoRef.current = [];
2637
3039
  };
2638
3040
 
2639
3041
  const undo = () => {
2640
3042
  const prev = historyRef.current.pop();
2641
3043
  if (!prev) { flash(t('undoNone')); return; }
3044
+ redoRef.current.push({ nodes: nodesRef.current, edges: edgesRef.current });
3045
+ if (redoRef.current.length > 50) redoRef.current.shift();
2642
3046
  setNodes(prev.nodes);
2643
3047
  setEdges(prev.edges);
2644
3048
  setSelectedIds([]);
2645
3049
  flash(t('undoDone'));
2646
3050
  };
2647
3051
 
3052
+ const redo = () => {
3053
+ const next = redoRef.current.pop();
3054
+ if (!next) { flash(t('redoNone')); return; }
3055
+ historyRef.current.push({ nodes: nodesRef.current, edges: edgesRef.current });
3056
+ if (historyRef.current.length > 50) historyRef.current.shift();
3057
+ setNodes(next.nodes);
3058
+ setEdges(next.edges);
3059
+ setSelectedIds([]);
3060
+ flash(t('redoDone'));
3061
+ };
3062
+
2648
3063
  const openRun = (node, run) => {
2649
3064
  try {
2650
3065
  const sr = hostCtx && hostCtx.sidebarRight;
@@ -2738,9 +3153,125 @@ window.__ModuleLoader__.load({
2738
3153
 
2739
3154
  const deleteEdgeById = (edgeId) => {
2740
3155
  pushSnapshot();
2741
- 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);
2742
3159
  setCtxMenu(null);
2743
- 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'));
2744
3275
  };
2745
3276
 
2746
3277
  const insertNodeOnEdge = (edgeId, kind, atWorld) => {
@@ -2811,9 +3342,13 @@ window.__ModuleLoader__.load({
2811
3342
  const deleteNode = (id) => {
2812
3343
  if (id === 'lead') { flash(t('leadLocked')); return; }
2813
3344
  pushSnapshot();
2814
- setNodes((ns) => ns.filter((n) => n.id !== id));
2815
- 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);
2816
3350
  setSelectedIds([]);
3351
+ setLoopEditEdgeId(null);
2817
3352
  flash(t('deletedNode'));
2818
3353
  };
2819
3354
 
@@ -2824,9 +3359,13 @@ window.__ModuleLoader__.load({
2824
3359
  if (!targets.length) { flash(t('leadLocked')); return; }
2825
3360
  const drop = new Set(targets);
2826
3361
  pushSnapshot();
2827
- setNodes((ns) => ns.filter((n) => !drop.has(n.id)));
2828
- 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);
2829
3367
  setSelectedIds([]);
3368
+ setLoopEditEdgeId(null);
2830
3369
  flash(targets.length === 1 ? t('deletedNode') : t('deletedNodes') + ' ×' + targets.length);
2831
3370
  };
2832
3371
 
@@ -2952,19 +3491,22 @@ window.__ModuleLoader__.load({
2952
3491
  const node = nodes.find((n) => n.id === id);
2953
3492
  if (!node) return;
2954
3493
  const p = pointTo(e);
2955
- const group = selectedIds.includes(id) ? selectedIds : [id];
2956
- if (!selectedIds.includes(id)) setSelectedIds([id]);
3494
+ const additive = Boolean(e.shiftKey || e.ctrlKey || e.metaKey);
3495
+ const { next: group, toggledOff } = nextSelectionOnNodeClick(selectedIds, id, additive);
3496
+ setSelectedIds(group);
3497
+ setOpenModelFor(null);
3498
+ setAddMenu(null);
3499
+ setCtxMenu(null);
3500
+ setLoopEditEdgeId(null);
3501
+ e.preventDefault();
3502
+ e.stopPropagation();
3503
+ if (toggledOff) return;
2957
3504
  const origins = group
2958
3505
  .map((nid) => nodes.find((n) => n.id === nid))
2959
3506
  .filter(Boolean)
2960
3507
  .map((n) => ({ id: n.id, x: n.x, y: n.y }));
2961
3508
  nodeDrag.current = { origins, startX: p.x, startY: p.y, moved: false };
2962
3509
  setDragging(true);
2963
- setOpenModelFor(null);
2964
- setAddMenu(null);
2965
- setCtxMenu(null);
2966
- e.preventDefault();
2967
- e.stopPropagation();
2968
3510
  };
2969
3511
 
2970
3512
  const onNodeContextMenu = (e, node) => {
@@ -2987,6 +3529,7 @@ window.__ModuleLoader__.load({
2987
3529
  setRoleEditFor(null);
2988
3530
  setDecisionViewFor(null);
2989
3531
  setRefsEditFor(null);
3532
+ setLoopEditEdgeId(null);
2990
3533
  };
2991
3534
 
2992
3535
  const addNodeRef = (node) => {
@@ -3063,38 +3606,62 @@ window.__ModuleLoader__.load({
3063
3606
  e.stopPropagation();
3064
3607
  };
3065
3608
 
3066
- /** Release over an output socket: completes a drag that started at the unified left input. */
3067
- const onOutputUp = (e, id, type, branch) => {
3068
- if (!pending || pending.dir !== 'in') return;
3069
- pendingHandledRef.current = true;
3070
- e.preventDefault();
3071
- e.stopPropagation();
3609
+ const tryAddEdge = (fromId, toId, type, branch, preferredMaxIter) => {
3610
+ if (!fromId || !toId || fromId === toId) return;
3072
3611
  const b = typeof branch === 'string' ? branch.trim() : '';
3073
- const toId = pending.toId;
3074
- if (toId && toId !== id) {
3075
- if (wouldCycle(nodesRef.current, edgesRef.current, id, toId)) {
3076
- flash(t('cycleBlocked'));
3077
- } else {
3612
+ if (wouldCycle(nodesRef.current, edgesRef.current, fromId, toId)) {
3613
+ const loopOk = canLinkAsLoop(nodesRef.current, edgesRef.current, fromId, toId);
3614
+ if (loopOk.ok) {
3078
3615
  pushSnapshot();
3616
+ const loopBranch = b || 'false';
3617
+ const maxIter = normalizeMaxIterationsUI(preferredMaxIter);
3079
3618
  setEdges((es) => {
3080
- if (es.some((x) => x.from === id && x.to === toId && x.type === type && (x.branch || '') === b)) return es;
3081
- const nextEdge = { id: 'e' + Date.now().toString(36), from: id, to: toId, type };
3082
- if (b) nextEdge.branch = b;
3083
- 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
+ }];
3084
3629
  });
3630
+ flash(t('loopCreated'));
3631
+ } else {
3632
+ flash(loopOk.reason === 'loopOverlap' ? t('loopOverlap') : t('cycleBlocked'));
3085
3633
  }
3634
+ return;
3086
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);
3087
3652
  setPending(null);
3088
3653
  setDragging(false);
3089
3654
  };
3090
3655
 
3091
- // 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);
3092
3658
  // dragging a free input starts a reverse wire that adopts whichever right output it drops onto.
3093
3659
  const onInputDown = (e, id) => {
3094
3660
  e.preventDefault();
3095
3661
  e.stopPropagation();
3096
3662
  const incoming = edges.filter((x) => x.to === id);
3097
- 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];
3098
3665
  if (!link) {
3099
3666
  const node = nodes.find((n) => n.id === id);
3100
3667
  if (!node) return;
@@ -3106,7 +3673,9 @@ window.__ModuleLoader__.load({
3106
3673
  return;
3107
3674
  }
3108
3675
  pushSnapshot();
3109
- 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);
3110
3679
  const from = nodes.find((n) => n.id === link.from);
3111
3680
  if (!from) return;
3112
3681
  const b = typeof link.branch === 'string' ? link.branch.trim() : '';
@@ -3115,7 +3684,18 @@ window.__ModuleLoader__.load({
3115
3684
  const sx = pos.x;
3116
3685
  const sy = pos.y;
3117
3686
  const color = edgeColorFor(from, link);
3118
- 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
+ });
3119
3699
  setDragging(true);
3120
3700
  };
3121
3701
 
@@ -3124,22 +3704,7 @@ window.__ModuleLoader__.load({
3124
3704
  pendingHandledRef.current = true;
3125
3705
  e.preventDefault();
3126
3706
  e.stopPropagation();
3127
- if (pending.fromId !== id) {
3128
- const fromId = pending.fromId;
3129
- const type = pending.type || 'prompt';
3130
- const b = typeof pending.branch === 'string' ? pending.branch.trim() : '';
3131
- if (wouldCycle(nodesRef.current, edgesRef.current, fromId, id)) {
3132
- flash(t('cycleBlocked'));
3133
- } else {
3134
- pushSnapshot();
3135
- setEdges((es) => {
3136
- if (es.some((x) => x.from === fromId && x.to === id && x.type === type && (x.branch || '') === b)) return es;
3137
- const nextEdge = { id: 'e' + Date.now().toString(36), from: fromId, to: id, type };
3138
- if (b) nextEdge.branch = b;
3139
- return [...es, nextEdge];
3140
- });
3141
- }
3142
- }
3707
+ tryAddEdge(pending.fromId, id, pending.type || 'prompt', pending.branch, pending.maxIterations);
3143
3708
  setPending(null);
3144
3709
  setDragging(false);
3145
3710
  };
@@ -3203,9 +3768,9 @@ window.__ModuleLoader__.load({
3203
3768
  // Configurable canvas keyboard shortcuts (defaults: Shift+A, Shift+D, Delete, Ctrl+Z, Esc).
3204
3769
  const keyActionsRef = useRef(null);
3205
3770
  keyActionsRef.current = {
3206
- undo, deleteSelected, duplicateSelected, openAddMenuAtCursor, addNode, fitView, autoLayout, toggleDirection, flash, t,
3207
- addMenu, ctxMenu, roleEditFor, openModelFor, menuOpen, presetOpen, helpOpen, shortcutsOpen, recordingAction, decisionViewFor, refsEditFor,
3208
- setAddMenu, setCtxMenu, setRoleEditFor, setOpenModelFor, setMenuOpen, setPresetOpen, setHelpOpen, setShortcutsOpen, setRecordingAction, setShortcuts, setDecisionViewFor, setRefsEditFor,
3771
+ undo, redo, deleteSelected, duplicateSelected, openAddMenuAtCursor, addNode, fitView, autoLayout, toggleDirection, flash, t,
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,
3209
3774
  };
3210
3775
  useEffect(() => {
3211
3776
  const isEditable = (target) => {
@@ -3234,10 +3799,11 @@ window.__ModuleLoader__.load({
3234
3799
  return;
3235
3800
  }
3236
3801
  if (ev.key === 'Escape') {
3237
- 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) {
3238
3803
  ev.preventDefault();
3239
3804
  act.setAddMenu(null);
3240
3805
  act.setCtxMenu(null);
3806
+ act.setLoopEditEdgeId(null);
3241
3807
  act.setRoleEditFor(null);
3242
3808
  act.setOpenModelFor(null);
3243
3809
  act.setMenuOpen(false);
@@ -3279,11 +3845,18 @@ window.__ModuleLoader__.load({
3279
3845
  act.openAddMenuAtCursor();
3280
3846
  return;
3281
3847
  }
3848
+ const allBound = Object.values(sc).map(normalizeShortcut);
3282
3849
  if (matchesShortcut(ev, sc.undo)) {
3283
3850
  ev.preventDefault();
3284
3851
  act.undo();
3285
3852
  return;
3286
3853
  }
3854
+ if (matchesShortcut(ev, sc.redo)
3855
+ || (normalizeShortcut(sc.redo) === 'Ctrl+Shift+Z' && !allBound.includes('Ctrl+Y') && matchesShortcut(ev, 'Ctrl+Y'))) {
3856
+ ev.preventDefault();
3857
+ act.redo();
3858
+ return;
3859
+ }
3287
3860
  if (matchesShortcut(ev, sc.duplicate)) {
3288
3861
  ev.preventDefault();
3289
3862
  act.duplicateSelected();
@@ -3304,7 +3877,6 @@ window.__ModuleLoader__.load({
3304
3877
  act.toggleDirection();
3305
3878
  return;
3306
3879
  }
3307
- const allBound = Object.values(sc).map(normalizeShortcut);
3308
3880
  const delHit = matchesShortcut(ev, sc.delete)
3309
3881
  || (normalizeShortcut(sc.delete) === 'Delete' && !allBound.includes('Backspace') && matchesShortcut(ev, 'Backspace'));
3310
3882
  if (delHit) {
@@ -3346,6 +3918,7 @@ window.__ModuleLoader__.load({
3346
3918
  if (menuOpen) setMenuOpen(false);
3347
3919
  if (addMenu) setAddMenu(null);
3348
3920
  if (ctxMenu) setCtxMenu(null);
3921
+ if (loopEditEdgeId) setLoopEditEdgeId(null);
3349
3922
  if (presetOpen) setPresetOpen(null);
3350
3923
  e.preventDefault();
3351
3924
  try { window.getSelection().removeAllRanges(); } catch (_sel) { /* ignore */ }
@@ -3403,7 +3976,7 @@ window.__ModuleLoader__.load({
3403
3976
  const source = nodeMap.get(edge.from);
3404
3977
  const target = nodeMap.get(edge.to);
3405
3978
  if (!source || !target) continue;
3406
- if (distanceToEdge(canvasSpot, source, target, edge, directionRef.current) <= threshold) {
3979
+ if (distanceToEdge(canvasSpot, source, target, edge, directionRef.current, nodes, edges) <= threshold) {
3407
3980
  cutHits.current.add(edge.id);
3408
3981
  }
3409
3982
  }
@@ -3442,7 +4015,7 @@ window.__ModuleLoader__.load({
3442
4015
  const source = nodeMap.get(edge.from);
3443
4016
  const target = nodeMap.get(edge.to);
3444
4017
  if (!source || !target) continue;
3445
- const dist = distanceToEdge(canvasSpot, source, target, edge, directionRef.current);
4018
+ const dist = distanceToEdge(canvasSpot, source, target, edge, directionRef.current, nodesRef.current, edgesRef.current);
3446
4019
  if (dist <= threshold && dist < bestDist) {
3447
4020
  bestDist = dist;
3448
4021
  hitEdge = edge;
@@ -3455,11 +4028,12 @@ window.__ModuleLoader__.load({
3455
4028
  setRoleEditFor(null);
3456
4029
  setDecisionViewFor(null);
3457
4030
  setRefsEditFor(null);
4031
+ setLoopEditEdgeId(null);
3458
4032
  if (hitEdge) {
3459
4033
  const pos = clampMenuPos(cx, cy, wrapRect.width, wrapRect.height, 180, 120);
3460
4034
  setCtxMenu({ kind: 'edge', edgeId: hitEdge.id, sx: pos.sx, sy: pos.sy, wx: rc.start.x, wy: rc.start.y });
3461
4035
  } else {
3462
- const pos = clampMenuPos(cx, cy, wrapRect.width, wrapRect.height, 186, 296);
4036
+ const pos = clampMenuPos(cx, cy, wrapRect.width, wrapRect.height, 186, 322);
3463
4037
  setCtxMenu({ kind: 'canvas', sx: pos.sx, sy: pos.sy, wx: rc.start.x, wy: rc.start.y });
3464
4038
  }
3465
4039
  }
@@ -3475,8 +4049,10 @@ window.__ModuleLoader__.load({
3475
4049
  cutHits.current = new Set();
3476
4050
  if (victims.length) {
3477
4051
  pushSnapshot();
3478
- setEdges((es) => es.filter((x) => !victimIds.has(x.id)));
3479
- 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') : ''));
3480
4056
  }
3481
4057
  }
3482
4058
  if (cutPath.length) { setCutPath([]); setCutVictims([]); }
@@ -3623,6 +4199,10 @@ window.__ModuleLoader__.load({
3623
4199
  };
3624
4200
  const b = typeof e.branch === 'string' ? e.branch.trim() : '';
3625
4201
  if (b) item.branch = b;
4202
+ if (e.loop === true) {
4203
+ item.loop = true;
4204
+ item.maxIterations = normalizeMaxIterationsUI(e.maxIterations);
4205
+ }
3626
4206
  return item;
3627
4207
  });
3628
4208
  if (!merge) return incoming;
@@ -3632,8 +4212,20 @@ window.__ModuleLoader__.load({
3632
4212
  && String(r.to) === e.to
3633
4213
  && (!r.type || r.type === e.type)
3634
4214
  && (!r.branch || r.branch === e.branch));
3635
- const kept = existing.filter((e) => !matchesDrop(e) && !removedNodes.has(e.from) && !removedNodes.has(e.to));
3636
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
+ });
3637
4229
  const seen = new Set(kept.map(keyOf));
3638
4230
  const added = incoming.filter((e) => !removedNodes.has(e.from) && !removedNodes.has(e.to) && !seen.has(keyOf(e)));
3639
4231
  return kept.concat(added);
@@ -4061,7 +4653,7 @@ window.__ModuleLoader__.load({
4061
4653
  const nodeById = new Map(nodes.map((n) => [n.id, n]));
4062
4654
  const inColorByNode = new Map();
4063
4655
  const inCountByNode = new Map();
4064
- 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))));
4065
4657
  const inPrioByNode = new Map();
4066
4658
  const connectedOut = new Set();
4067
4659
  for (const e of edges) {
@@ -4129,16 +4721,39 @@ window.__ModuleLoader__.load({
4129
4721
  : {};
4130
4722
  const prunedSet = new Set(enabled && runState && Array.isArray(runState.pruned) ? runState.pruned : []);
4131
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);
4132
4731
  const edgeKeyForState = (e) => String(e.from) + '->' + String(e.to) + '|' + String(e.type || 'prompt') + '|' + String(e.branch || '');
4732
+ const loopPillItems = [];
4133
4733
 
4134
4734
  const edgeEls = edges.map((edge) => {
4135
4735
  const from = nodeById.get(edge.from);
4136
4736
  const to = nodeById.get(edge.to);
4137
4737
  if (!from || !to) return null;
4138
- const color = edgeColorFor(from, edge);
4139
- 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);
4140
4743
  const highlighted = cutVictims.includes(edge.id);
4141
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
+ }
4142
4757
  const hasSel = selectedSet.size > 0;
4143
4758
  const linkedToSel = hasSel && (selectedSet.has(edge.from) || selectedSet.has(edge.to));
4144
4759
  const toRunning = enabled && statusById[edge.to] === 'running';
@@ -4162,11 +4777,24 @@ window.__ModuleLoader__.load({
4162
4777
  const isCompletedLink = enabled && !highlighted && !isPrunedEdge && fromSettled && toSettled;
4163
4778
  const dimmed = isPrunedEdge || (hasSel && !linkedToSel && !highlighted && !isFlowing);
4164
4779
  const strokeColor = highlighted ? '#e5534b' : color;
4165
- const baseWidth = highlighted ? 3 : (linkedToSel || isFlowing ? 2.6 : 2);
4166
- 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)));
4167
4782
  const useGlow = fxLevel === 'vivid' && !dimmed;
4168
4783
  const showDashFlow = isFlowing && fxLevel !== 'minimal';
4169
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
+ }
4170
4798
 
4171
4799
  return h('g', { key: edge.id, style: { pointerEvents: 'none' } },
4172
4800
  // Vector halo layers instead of an SVG objectBoundingBox <filter>, which
@@ -4192,9 +4820,14 @@ window.__ModuleLoader__.load({
4192
4820
  stroke: strokeColor,
4193
4821
  strokeWidth: baseWidth,
4194
4822
  strokeOpacity: showDashFlow ? 0.35 : baseOpacity,
4195
- strokeDasharray: isPrunedEdge ? '4 4' : undefined,
4823
+ strokeDasharray: isLoop ? '6 4' : (isPrunedEdge ? '4 4' : undefined),
4196
4824
  fill: 'none',
4197
4825
  }),
4826
+ loopArrow && h('polygon', {
4827
+ points: loopArrow,
4828
+ fill: strokeColor,
4829
+ fillOpacity: baseOpacity,
4830
+ }),
4198
4831
  showDashFlow && fxLevel === 'vivid' && h('path', {
4199
4832
  d,
4200
4833
  className: 'dsh-wc-edge-flow',
@@ -4641,6 +5274,13 @@ window.__ModuleLoader__.load({
4641
5274
  onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
4642
5275
  onClick: () => { setMenuOpen(false); undo(); },
4643
5276
  }, t('undo')),
5277
+ h('div', {
5278
+ style: S.moreRow,
5279
+ title: t('tipRedo'),
5280
+ onMouseEnter: (e) => { e.currentTarget.style.background = C.hover; },
5281
+ onMouseLeave: (e) => { e.currentTarget.style.background = 'transparent'; },
5282
+ onClick: () => { setMenuOpen(false); redo(); },
5283
+ }, t('redo')),
4644
5284
  h('div', {
4645
5285
  style: S.moreRow,
4646
5286
  title: t('tipLocate'),
@@ -4761,6 +5401,7 @@ window.__ModuleLoader__.load({
4761
5401
  duplicate: t('scDuplicate'),
4762
5402
  delete: t('scDelete'),
4763
5403
  undo: t('scUndo'),
5404
+ redo: t('scRedo'),
4764
5405
  fitView: t('scFitView'),
4765
5406
  autoLayout: t('scAutoLayout'),
4766
5407
  toggleDir: t('scToggleDir'),
@@ -4914,11 +5555,14 @@ window.__ModuleLoader__.load({
4914
5555
  const target = nodeById.get(ctxMenu.nodeId);
4915
5556
  if (!target) return null;
4916
5557
  const multiSel = selectedIds.length > 1 && selectedSet.has(target.id);
4917
- 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;
4918
5560
  const suffix = nonLeadCount > 1 ? ' ×' + nonLeadCount : '';
4919
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 };
4920
5564
  return h('div', {
4921
- 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' },
4922
5566
  onMouseDown: (e) => e.stopPropagation(),
4923
5567
  onContextMenu: (e) => e.preventDefault(),
4924
5568
  },
@@ -4926,6 +5570,18 @@ window.__ModuleLoader__.load({
4926
5570
  menuRow('edit', t('ctxEditText'), () => { setCtxMenu(null); setRoleEditFor(target.id); }),
4927
5571
  menuRow('refs', t('ctxManageRefs'), () => { setCtxMenu(null); setRefsEditFor(target.id); }),
4928
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
+ ),
4929
5585
  nonLeadCount > 0 && h('div', { style: S.ctxDivider }),
4930
5586
  nonLeadCount > 0 && menuRow('dup', t('ctxDup') + suffix, () => { setCtxMenu(null); duplicateSelected(); }, { hint: shortcuts.duplicate || '' }),
4931
5587
  nonLeadCount > 0 && menuRow('del', t('ctxDelNode') + suffix, () => {
@@ -4944,10 +5600,21 @@ window.__ModuleLoader__.load({
4944
5600
  onContextMenu: (e) => e.preventDefault(),
4945
5601
  },
4946
5602
  h('div', { style: S.addMenuHead }, t('ctxEdgeTitle')),
4947
- menuRow('ins-agent', t('ctxInsertAgent'), () => insertNodeOnEdge(targetEdge.id, 'agent', { x: ctxMenu.wx, y: ctxMenu.wy })),
4948
- menuRow('ins-cond', t('ctxInsertCond'), () => insertNodeOnEdge(targetEdge.id, 'condition', { x: ctxMenu.wx, y: ctxMenu.wy })),
4949
- h('div', { style: S.ctxDivider }),
4950
- 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
+ ),
4951
5618
  );
4952
5619
  }
4953
5620
  return h('div', {
@@ -4961,6 +5628,7 @@ window.__ModuleLoader__.load({
4961
5628
  menuRow('add-cond', t('addCond'), () => addNode('condition', { x: ctxMenu.wx, y: ctxMenu.wy })),
4962
5629
  h('div', { style: S.ctxDivider }),
4963
5630
  menuRow('undo', t('undo'), () => { setCtxMenu(null); undo(); }, { hint: shortcuts.undo || '' }),
5631
+ menuRow('redo', t('redo'), () => { setCtxMenu(null); redo(); }, { hint: shortcuts.redo || '' }),
4964
5632
  menuRow('layout', t('autoLayoutBtn'), () => { setCtxMenu(null); autoLayout(); }, { hint: shortcuts.autoLayout || '' }),
4965
5633
  menuRow('dir', direction === 'tb' ? t('dirLR') : t('dirTB'), () => { setCtxMenu(null); toggleDirection(); }, { hint: shortcuts.toggleDir || '' }),
4966
5634
  menuRow('fit', t('locate'), () => { setCtxMenu(null); fitView(); }, { hint: shortcuts.fitView || '' }),
@@ -5034,6 +5702,101 @@ window.__ModuleLoader__.load({
5034
5702
  return h('path', { d, stroke: color, strokeWidth: 2, strokeDasharray: '4 4', fill: 'none' });
5035
5703
  })(),
5036
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
+ }),
5037
5800
  nodes.map((node) => {
5038
5801
  const isEntry = node.id === 'lead';
5039
5802
  const isLeadKind = node.kind === 'lead';
@@ -5082,6 +5845,8 @@ window.__ModuleLoader__.load({
5082
5845
  : 'linear-gradient(90deg, #2f81f7 0%, #58d580 50%, #2f81f7 100%)'))
5083
5846
  : (isFailed ? '#e5534b' : (isLeadKind ? '#2f81f7' : (isCondKind ? '#d29922' : '#3fb950')));
5084
5847
  const isPruned = enabled && prunedSet.has(node.id);
5848
+ const nodeLoop = loopGroups.byNode.get(node.id) || null;
5849
+ const nodeAttempt = nodeAttemptsMap[node.id] || null;
5085
5850
  const condDecision = isCondKind ? (decisionsById[node.id] || null) : null;
5086
5851
  const verdictInfo = condDecision ? conditionVerdictSummary(condDecision, lang) : null;
5087
5852
  const hasOpenPopover = decisionViewFor === node.id
@@ -5100,12 +5865,22 @@ window.__ModuleLoader__.load({
5100
5865
  ...(isLeadKind ? S.leadNode : null),
5101
5866
  ...(isInactive || isPruned ? S.orphanNode : null),
5102
5867
  ...(stateStyle || null),
5868
+ ...(nodeLoop ? { outline: '1.5px dashed ' + nodeLoop.color, outlineOffset: '3px' } : null),
5103
5869
  ...(hasOpenPopover ? { zIndex: 40 } : null),
5104
5870
  },
5105
5871
  title: isPruned ? t('tipPruned') : (isOrphan ? t('orphanTip') : (isSoloLead ? t('tipSoloLead') : (isDeadEnd ? t('tipDeadEnd') : undefined))),
5106
5872
  onMouseDown: (e) => onNodeDown(e, node.id),
5107
5873
  onContextMenu: (e) => onNodeContextMenu(e, node),
5108
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)),
5109
5884
  h('div', {
5110
5885
  className: (isRunning || isLeadReady) && fxLevel === 'vivid' ? 'dsh-wc-topbar-vivid' : undefined,
5111
5886
  style: {
@@ -5517,7 +6292,7 @@ window.__ModuleLoader__.load({
5517
6292
  try { console.error('[workflow-canvas] apply failed', error); } catch (_e) { /* ignore */ }
5518
6293
  }
5519
6294
  },
5520
- __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, 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 },
5521
6296
  };
5522
6297
  },
5523
6298
  });