cladogram 0.6.0-beta.1 → 0.6.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +50 -47
  2. package/bin/clado.js +34 -2
  3. package/docs/agent-context.md +63 -0
  4. package/docs/agent-reference.md +219 -0
  5. package/docs/release.md +116 -0
  6. package/package.json +3 -1
  7. package/plugins/agent/index.js +2429 -723
  8. package/plugins/agent/settings.js +3592 -0
  9. package/plugins/agent/style.css +1327 -94
  10. package/plugins/view-controls/index.js +0 -11
  11. package/plugins/view-controls/style.css +7 -14
  12. package/skills/clado/SKILL.md +4 -2
  13. package/src/agent/automations.js +454 -0
  14. package/src/agent/clado-tools.js +597 -104
  15. package/src/agent/pi-bridge.js +2184 -112
  16. package/src/agent/pi-config.js +1889 -108
  17. package/src/agent/pi-hooks-perms.js +621 -0
  18. package/src/html/app-css.js +69 -1
  19. package/src/html/canvas-chain.js +32 -6
  20. package/src/html/canvas-focus.js +19 -13
  21. package/src/html/canvas-live-diff.js +1373 -0
  22. package/src/html/canvas-ui.css +503 -2
  23. package/src/html/canvas-wires.js +5 -1
  24. package/src/html/page.js +4 -2
  25. package/src/html/plugin-assets.js +5 -1
  26. package/src/html/plugin-ui.css +1 -1
  27. package/src/html/runtime-api.js +152 -10
  28. package/src/html/runtime.js +546 -37
  29. package/src/server/agent.js +594 -37
  30. package/src/server/assets/library-canvas.js +256 -9
  31. package/src/server/assets/library.css +567 -12
  32. package/src/server/assets/library.html +2 -0
  33. package/src/server/assets/library.js +1028 -32
  34. package/src/server/code-inspect.js +183 -0
  35. package/src/server/mcp.js +90 -22
  36. package/src/server/plugin-registry.js +664 -2
  37. package/src/server/workspace.js +551 -25
  38. package/src/workspace/graph-snapshot.js +695 -0
  39. package/src/workspace/service.js +201 -9
@@ -178,10 +178,10 @@
178
178
  saveView();
179
179
  syncChrome();
180
180
  frame.contentWindow.CladoPrototype?.setMode?.(next);
181
+ armPresenceAfterglowForFile(selected);
181
182
  },
182
183
  clearFocus: () => frame.contentWindow.CladoRuntime?.clearFocus(),
183
184
  showDiagnostics: () => frame.contentWindow.CladoCanvasControls?.showDiagnostics(),
184
- openHandoff: !offline && config.agent ? () => window.CladoVNext?.openHandoff?.() : null,
185
185
  });
186
186
  const directory = window.CladoDirectoryPlugin(host, {
187
187
  showFilename: settings['clado.directory']?.showFilename !== false,
@@ -574,6 +574,9 @@
574
574
  renderLobbyView(cachedHubData || {});
575
575
  }
576
576
 
577
+ let discoveredWorkspaces = [];
578
+ let emptyWorkspaceSignature = '';
579
+
577
580
  function renderEmptyOnboarding(profile = {}) {
578
581
  const emptyEl = $('#emptyState');
579
582
  if (!emptyEl) return;
@@ -627,6 +630,10 @@
627
630
  showToast('主架构师正在分析源码并绘制画布…');
628
631
  window.CladoVNext?.startCodeAnalysis?.(selectedTpl);
629
632
  };
633
+ if (discoveredWorkspaces.length) {
634
+ emptyWorkspaceSignature = '';
635
+ renderEmptyWorkspaces(discoveredWorkspaces);
636
+ }
630
637
  }
631
638
 
632
639
  if (config.canSwitchWorkspace && !offline) {
@@ -826,15 +833,119 @@
826
833
  addSep();
827
834
  addItem('删除此组件', () => deleteObject(obj.id), true);
828
835
  }
836
+ } else if (detail.kind === 'text-selection' && detail.node) {
837
+ addLabel(`选中文本 · ${detail.label || ''}`);
838
+ addItem('连接到其他卡片 / 锚点…', () => {
839
+ try {
840
+ frame.contentWindow.postMessage({
841
+ type: 'clado-workspace:start-link-pick',
842
+ source: {
843
+ kind: 'text-selection',
844
+ node: detail.node,
845
+ selectedText: detail.selectedText,
846
+ label: detail.label || detail.selectedText,
847
+ },
848
+ }, location.origin);
849
+ } catch {}
850
+ });
851
+ addItem('让 AI 修改这段', () => {
852
+ window.dispatchEvent(new CustomEvent('clado:agent-prefill', {
853
+ detail: { mode: 'edit', file: selected, node: detail.node, selectedText: detail.selectedText },
854
+ }));
855
+ });
856
+ addItem('问 AI 这段内容', () => {
857
+ window.dispatchEvent(new CustomEvent('clado:agent-prefill', {
858
+ detail: { mode: 'ask', file: selected, node: detail.node, selectedText: detail.selectedText },
859
+ }));
860
+ });
861
+ if (detail.codeRef) {
862
+ addSep();
863
+ addItem(`查看源码 · ${detail.codeRef}`, () => window.CladoCodeDrawer?.openRef?.(detail.codeRef));
864
+ }
865
+ } else if (detail.kind === 'code-line' && detail.node) {
866
+ addLabel(detail.label || `代码第 ${detail.line || 1} 行`);
867
+ addItem('从此代码行连接到…', () => {
868
+ try {
869
+ frame.contentWindow.postMessage({
870
+ type: 'clado-workspace:start-link-pick',
871
+ source: {
872
+ kind: 'code-line',
873
+ node: detail.node,
874
+ sourcePoint: detail.sourcePoint,
875
+ label: detail.label,
876
+ lineText: detail.lineText,
877
+ },
878
+ }, location.origin);
879
+ } catch {}
880
+ });
881
+ addItem('问 AI 这一行代码', () => {
882
+ window.dispatchEvent(new CustomEvent('clado:agent-prefill', {
883
+ detail: { mode: 'ask', file: selected, node: detail.node, selectedText: detail.lineText || detail.label },
884
+ }));
885
+ });
886
+ if (detail.codeRef) {
887
+ addSep();
888
+ addItem(`查看真实源码 · ${detail.codeRef}`, () => window.CladoCodeDrawer?.openRef?.(detail.codeRef));
889
+ }
890
+ } else if (detail.kind === 'mermaid-node' && detail.node) {
891
+ addLabel(detail.label || 'Mermaid 节点');
892
+ addItem('从此图节点连接到…', () => {
893
+ try {
894
+ frame.contentWindow.postMessage({
895
+ type: 'clado-workspace:start-link-pick',
896
+ source: {
897
+ kind: 'mermaid-node',
898
+ node: detail.node,
899
+ sourcePoint: detail.sourcePoint,
900
+ label: detail.label,
901
+ },
902
+ }, location.origin);
903
+ } catch {}
904
+ });
905
+ addItem('问 AI 这个图节点', () => {
906
+ window.dispatchEvent(new CustomEvent('clado:agent-prefill', {
907
+ detail: { mode: 'ask', file: selected, node: detail.node, selectedText: detail.nodeLabel || detail.nodeId },
908
+ }));
909
+ });
829
910
  } else if (detail.kind === 'card' && detail.node) {
911
+ const targetNode = detail.cardNode || detail.node;
830
912
  const nodes = [...(aiSelection?.nodes || [])];
831
- const at = nodes.findIndex(n => JSON.stringify(n) === JSON.stringify(detail.node));
913
+ const at = nodes.findIndex(n => JSON.stringify(n) === JSON.stringify(targetNode));
832
914
  addLabel(`卡片 · ${detail.title || detail.node[detail.node.length - 1]}`);
915
+ addItem('连接到其他卡片 / 锚点…', () => {
916
+ try {
917
+ frame.contentWindow.postMessage({
918
+ type: 'clado-workspace:start-link-pick',
919
+ source: {
920
+ kind: 'card',
921
+ node: detail.node,
922
+ title: detail.title,
923
+ label: detail.title || detail.node.join(' / '),
924
+ },
925
+ }, location.origin);
926
+ } catch {}
927
+ });
928
+ if (detail.codeRef) {
929
+ addItem(`查看真实源码 · ${detail.codeRef}`, () => window.CladoCodeDrawer?.openRef?.(detail.codeRef));
930
+ }
931
+ if (detail.isIsolated) {
932
+ addItem('让 AI 接入主调用链', () => {
933
+ window.dispatchEvent(new CustomEvent('clado:agent-prefill', {
934
+ detail: {
935
+ mode: 'custom',
936
+ file: selected,
937
+ node: targetNode,
938
+ prompt: `卡片「${detail.title}」目前未连入画布主拓扑,请结合真实调用关系将它合理连接到上下游卡片,完成后调用 clado_graph 验证无孤立卡。`,
939
+ },
940
+ }));
941
+ });
942
+ }
943
+ addSep();
833
944
  addItem(at >= 0 ? '取消选中此卡片' : '选中此卡片', () => {
834
945
  const nextNodes = [...(aiSelection?.nodes || [])];
835
- const idx = nextNodes.findIndex(n => JSON.stringify(n) === JSON.stringify(detail.node));
946
+ const idx = nextNodes.findIndex(n => JSON.stringify(n) === JSON.stringify(targetNode));
836
947
  if (idx >= 0) nextNodes.splice(idx, 1);
837
- else nextNodes.push(detail.node);
948
+ else nextNodes.push(targetNode);
838
949
  setSelection(nextNodes.length ? { file: selected, version, nodes: nextNodes } : null);
839
950
  });
840
951
  addItem('旁边贴一张便签', () => {
@@ -888,14 +999,10 @@
888
999
  selectionBarEl.innerHTML = `
889
1000
  <span class="clado-selection-dot"></span>
890
1001
  <span class="clado-selection-text" data-sel-summary>已选 0 项</span>
891
- <button type="button" class="clado-selection-send" data-sel-dev>交给开发落地</button>
892
- <button type="button" class="clado-selection-secondary" data-sel-qa>生成并跑测试</button>
1002
+ <button type="button" class="clado-selection-send" data-sel-send>发给当前会话</button>
893
1003
  <button type="button" class="clado-selection-clear" data-sel-clear>完成</button>`;
894
- selectionBarEl.querySelector('[data-sel-dev]').onclick = () => {
895
- window.CladoVNext?.triggerHandoff?.('developer');
896
- };
897
- selectionBarEl.querySelector('[data-sel-qa]').onclick = () => {
898
- window.CladoVNext?.triggerHandoff?.('tester');
1004
+ selectionBarEl.querySelector('[data-sel-send]').onclick = () => {
1005
+ window.CladoVNext?.focusComposer?.();
899
1006
  };
900
1007
  selectionBarEl.querySelector('[data-sel-clear]').onclick = () => {
901
1008
  objectSelection.clear();
@@ -954,11 +1061,363 @@
954
1061
  flushPendingTouch();
955
1062
  }
956
1063
  }
1064
+ function focusTag(tagId) {
1065
+ if (!tagId || readyCanvas?.frame !== frame) return;
1066
+ try { frame.contentWindow.postMessage({ type: 'clado-workspace:focus-tag', tagId: String(tagId) }, offline ? '*' : location.origin); } catch {}
1067
+ }
1068
+ function getCanvasEntities() {
1069
+ try {
1070
+ if (readyCanvas?.frame === frame) {
1071
+ return frame.contentWindow.CladoRuntime?.getCanvasEntities?.() || { cards: [], sections: [], tags: [] };
1072
+ }
1073
+ } catch {}
1074
+ return { cards: [], sections: [], tags: [] };
1075
+ }
1076
+
1077
+ // ============ Multi-Role Handoff Stage Banner ============
1078
+ let stageBannerTimer = null;
1079
+ function showStageBanner(payload) {
1080
+ const el = document.getElementById?.('clado-stage-banner');
1081
+ if (!el || !payload?.roleName) return;
1082
+ const phase = payload.phase ? `<span class="stage-phase">${escHtml(payload.phase)}</span>` : '';
1083
+ const fromTxt = payload.handoffFrom ? ` · 承接自「${escHtml(payload.handoffFrom)}」` : '';
1084
+ el.dataset.tone = payload.tone || 'sky';
1085
+ el.innerHTML = `<span class="stage-dot" aria-hidden="true"></span>${phase}<span>${escHtml(payload.roleName)}已接手${fromTxt}</span>`;
1086
+ el.hidden = false;
1087
+ requestAnimationFrame(() => el.classList.add('show'));
1088
+ clearTimeout(stageBannerTimer);
1089
+ stageBannerTimer = setTimeout(() => {
1090
+ el.classList.remove('show');
1091
+ setTimeout(() => { if (!el.classList.contains('show')) el.hidden = true; }, 240);
1092
+ }, 3400);
1093
+ }
1094
+
1095
+ // ============ Right-Side Live Code & Git Diff Drawer ============
1096
+ const codeDrawerEl = document.getElementById?.('clado-code-drawer') || null;
1097
+ const codeTabs = new Map();
1098
+ let activeCodePath = '';
1099
+ let codeViewMode = 'diff';
1100
+
1101
+ function computeCodeLineDiff(oldStr, newStr) {
1102
+ const a = oldStr == null ? [] : String(oldStr).replace(/\r\n?/g, '\n').split('\n');
1103
+ const b = newStr == null ? [] : String(newStr).replace(/\r\n?/g, '\n').split('\n');
1104
+ let start = 0;
1105
+ while (start < a.length && start < b.length && a[start] === b[start]) start++;
1106
+ let endA = a.length - 1, endB = b.length - 1;
1107
+ while (endA >= start && endB >= start && a[endA] === b[endB]) { endA--; endB--; }
1108
+ const ops = [];
1109
+ for (let i = 0; i < start; i++) ops.push({ type: 'eq', text: a[i], oldLn: i + 1, newLn: i + 1 });
1110
+ const midA = a.slice(start, endA + 1);
1111
+ const midB = b.slice(start, endB + 1);
1112
+ if (midA.length * midB.length > 90000 || !midA.length || !midB.length) {
1113
+ midA.forEach((line, idx) => ops.push({ type: 'del', text: line, oldLn: start + idx + 1, newLn: null }));
1114
+ midB.forEach((line, idx) => ops.push({ type: 'add', text: line, oldLn: null, newLn: start + idx + 1 }));
1115
+ } else {
1116
+ const m = midA.length, n = midB.length;
1117
+ const dp = Array.from({ length: m + 1 }, () => new Int32Array(n + 1));
1118
+ for (let x = m - 1; x >= 0; x--) {
1119
+ for (let y = n - 1; y >= 0; y--) {
1120
+ dp[x][y] = midA[x] === midB[y] ? dp[x + 1][y + 1] + 1 : Math.max(dp[x + 1][y], dp[x][y + 1]);
1121
+ }
1122
+ }
1123
+ let ix = 0, iy = 0;
1124
+ while (ix < m && iy < n) {
1125
+ if (midA[ix] === midB[iy]) {
1126
+ ops.push({ type: 'eq', text: midA[ix], oldLn: start + ix + 1, newLn: start + iy + 1 });
1127
+ ix++; iy++;
1128
+ } else if (dp[ix + 1][iy] >= dp[ix][iy + 1]) {
1129
+ ops.push({ type: 'del', text: midA[ix], oldLn: start + ix + 1, newLn: null });
1130
+ ix++;
1131
+ } else {
1132
+ ops.push({ type: 'add', text: midB[iy], oldLn: null, newLn: start + iy + 1 });
1133
+ iy++;
1134
+ }
1135
+ }
1136
+ while (ix < m) { ops.push({ type: 'del', text: midA[ix], oldLn: start + ix + 1, newLn: null }); ix++; }
1137
+ while (iy < n) { ops.push({ type: 'add', text: midB[iy], oldLn: null, newLn: start + iy + 1 }); iy++; }
1138
+ }
1139
+ const tailLen = a.length - (endA + 1);
1140
+ for (let k = 0; k < tailLen; k++) {
1141
+ ops.push({ type: 'eq', text: a[endA + 1 + k], oldLn: endA + 2 + k, newLn: endB + 2 + k });
1142
+ }
1143
+ let added = 0, removed = 0;
1144
+ for (const o of ops) { if (o.type === 'add') added++; else if (o.type === 'del') removed++; }
1145
+ return { ops, added, removed };
1146
+ }
1147
+
1148
+ function diffInlineTokens(oldLine, newLine) {
1149
+ const tok = s => String(s || '').match(/[A-Za-z0-9_]+|[\u4e00-\u9fff]|\s+|[^\sA-Za-z0-9_\u4e00-\u9fff]/g) || [];
1150
+ const a = tok(oldLine), b = tok(newLine);
1151
+ if (!a.length || !b.length || a.length * b.length > 10000) return { delHtml: escHtml(oldLine), addHtml: escHtml(newLine) };
1152
+ const m = a.length, n = b.length;
1153
+ const dp = Array.from({ length: m + 1 }, () => new Int32Array(n + 1));
1154
+ for (let x = m - 1; x >= 0; x--) {
1155
+ for (let y = n - 1; y >= 0; y--) {
1156
+ dp[x][y] = a[x] === b[y] ? dp[x + 1][y + 1] + 1 : Math.max(dp[x + 1][y], dp[x][y + 1]);
1157
+ }
1158
+ }
1159
+ const delSegs = [], addSegs = [];
1160
+ const pushSeg = (list, kind, t) => {
1161
+ const last = list[list.length - 1];
1162
+ if (last && last.kind === kind) last.text += t; else list.push({ kind, text: t });
1163
+ };
1164
+ let ix = 0, iy = 0;
1165
+ while (ix < m && iy < n) {
1166
+ if (a[ix] === b[iy]) { pushSeg(delSegs, 'eq', a[ix]); pushSeg(addSegs, 'eq', b[iy]); ix++; iy++; }
1167
+ else if (dp[ix + 1][iy] >= dp[ix][iy + 1]) pushSeg(delSegs, 'chg', a[ix++]);
1168
+ else pushSeg(addSegs, 'chg', b[iy++]);
1169
+ }
1170
+ while (ix < m) pushSeg(delSegs, 'chg', a[ix++]);
1171
+ while (iy < n) pushSeg(addSegs, 'chg', b[iy++]);
1172
+ const renderSegs = (segs, cls) => segs.map(s => s.kind === 'chg' ? `<mark class="${cls}">${escHtml(s.text)}</mark>` : escHtml(s.text)).join('');
1173
+ return { delHtml: renderSegs(delSegs, 'clado-cd-mark-del'), addHtml: renderSegs(addSegs, 'clado-cd-mark-add') };
1174
+ }
1175
+
1176
+ function renderCodeDrawer() {
1177
+ if (!codeDrawerEl) return;
1178
+ if (!activeCodePath || !codeTabs.has(activeCodePath)) {
1179
+ codeDrawerEl.hidden = true;
1180
+ return;
1181
+ }
1182
+ const tab = codeTabs.get(activeCodePath);
1183
+ const shortName = tab.path.split('/').pop() || tab.path;
1184
+ const hasDiff = tab.diff && (tab.diff.added > 0 || tab.diff.removed > 0);
1185
+ const effectiveMode = (codeViewMode === 'diff' && hasDiff) ? 'diff' : 'source';
1186
+ const statusLabel = tab.liveStatus || (hasDiff ? `+${tab.diff.added} / -${tab.diff.removed}` : `${(tab.content || '').split('\n').length} 行`);
1187
+
1188
+ const tabsHtml = [...codeTabs.values()].slice(-8).map(item => {
1189
+ const name = item.path.split('/').pop() || item.path;
1190
+ const a = item.diff?.added || 0;
1191
+ const d = item.diff?.removed || 0;
1192
+ return `<button type="button" class="clado-cd-tab${item.path === activeCodePath ? ' active' : ''}" data-cd-tab="${escHtml(item.path)}">`
1193
+ + `<span>${escHtml(name)}</span>`
1194
+ + (a ? `<span class="clado-cd-stat-add">+${a}</span>` : '')
1195
+ + (d ? `<span class="clado-cd-stat-del">-${d}</span>` : '')
1196
+ + `</button>`;
1197
+ }).join('');
1198
+
1199
+ let bodyHtml = '';
1200
+ if (tab.loading) {
1201
+ bodyHtml = '<div class="clado-cd-sep">正在读取工作区源码与 Git Diff…</div>';
1202
+ } else if (tab.error) {
1203
+ bodyHtml = `<div class="clado-cd-sep">${escHtml(tab.error)}</div>`;
1204
+ } else if (effectiveMode === 'diff' && tab.diff) {
1205
+ const ops = tab.diff.ops;
1206
+ const keep = new Array(ops.length).fill(false);
1207
+ for (let i = 0; i < ops.length; i++) {
1208
+ if (ops[i].type !== 'eq') {
1209
+ for (let j = Math.max(0, i - 3); j <= Math.min(ops.length - 1, i + 3); j++) keep[j] = true;
1210
+ }
1211
+ }
1212
+ const htmlOverride = new Array(ops.length);
1213
+ let idx = 0;
1214
+ while (idx < ops.length) {
1215
+ if (ops[idx].type === 'del') {
1216
+ const ds = idx; while (idx < ops.length && ops[idx].type === 'del') idx++;
1217
+ const as = idx; while (idx < ops.length && ops[idx].type === 'add') idx++;
1218
+ const pairs = Math.min(as - ds, idx - as);
1219
+ for (let p = 0; p < pairs; p++) {
1220
+ const pair = diffInlineTokens(ops[ds + p].text, ops[as + p].text);
1221
+ htmlOverride[ds + p] = pair.delHtml;
1222
+ htmlOverride[as + p] = pair.addHtml;
1223
+ }
1224
+ } else idx++;
1225
+ }
1226
+ const rows = [];
1227
+ let skipping = false;
1228
+ for (let i = 0; i < ops.length; i++) {
1229
+ if (!keep[i]) {
1230
+ if (!skipping && rows.length) { rows.push('<div class="clado-cd-sep">···</div>'); skipping = true; }
1231
+ continue;
1232
+ }
1233
+ skipping = false;
1234
+ const o = ops[i];
1235
+ const cls = o.type === 'add' ? ' is-add' : o.type === 'del' ? ' is-del' : '';
1236
+ const sign = o.type === 'add' ? '+' : o.type === 'del' ? '−' : ' ';
1237
+ const ln = o.newLn ?? o.oldLn ?? '';
1238
+ const codeHtml = htmlOverride[i] != null ? htmlOverride[i] : escHtml(o.text);
1239
+ rows.push(`<div class="clado-cd-line${cls}"><span class="clado-cd-ln">${ln}</span><span class="clado-cd-sign">${sign}</span><span class="clado-cd-code">${codeHtml || '&nbsp;'}</span></div>`);
1240
+ }
1241
+ bodyHtml = rows.join('') || '<div class="clado-cd-sep">与 Git HEAD 一致,无未提交改动</div>';
1242
+ } else {
1243
+ const lines = String(tab.content || '').replace(/\r\n?/g, '\n').split('\n');
1244
+ bodyHtml = lines.slice(0, 1200).map((line, i) => {
1245
+ const ln = i + 1;
1246
+ const isMatch = tab.matchedLine && ln === tab.matchedLine;
1247
+ return `<div class="clado-cd-line${isMatch ? ' is-match' : ''}" data-cd-ln="${ln}"><span class="clado-cd-ln">${ln}</span><span class="clado-cd-sign"> </span><span class="clado-cd-code">${escHtml(line) || '&nbsp;'}</span></div>`;
1248
+ }).join('');
1249
+ if (lines.length > 1200) bodyHtml += `<div class="clado-cd-sep">… 仅展示前 1200 行(共 ${lines.length} 行)</div>`;
1250
+ }
1251
+
1252
+ const cardsHtml = (tab.matchedCards || []).slice(0, 3).map(pathArr => {
1253
+ const title = Array.isArray(pathArr) ? pathArr[pathArr.length - 1] : String(pathArr);
1254
+ return `<button type="button" class="clado-cd-card-chip" data-cd-card="${escHtml(title)}">${escHtml(title)}</button>`;
1255
+ }).join('');
1256
+
1257
+ codeDrawerEl.innerHTML = `
1258
+ <div class="clado-cd-head">
1259
+ <div class="clado-cd-title-wrap">
1260
+ <span class="clado-cd-dot${tab.liveStatus ? ' live' : ''}" aria-hidden="true"></span>
1261
+ <span class="clado-cd-title">${escHtml(shortName)}</span>
1262
+ <span class="clado-cd-sub">${escHtml(statusLabel)}</span>
1263
+ </div>
1264
+ <div class="clado-cd-actions">
1265
+ ${hasDiff ? `<button type="button" class="clado-cd-btn${effectiveMode === 'diff' ? ' active' : ''}" data-cd-mode="diff">实时 Diff</button>` : ''}
1266
+ <button type="button" class="clado-cd-btn${effectiveMode === 'source' ? ' active' : ''}" data-cd-mode="source">完整源码</button>
1267
+ <button type="button" class="clado-cd-btn" data-cd-close title="关闭代码视图">关闭</button>
1268
+ </div>
1269
+ </div>
1270
+ ${codeTabs.size > 1 ? `<div class="clado-cd-tabs">${tabsHtml}</div>` : ''}
1271
+ <div class="clado-cd-pathbar">
1272
+ <span class="clado-cd-path" title="${escHtml(tab.path)}">${escHtml(tab.path)}</span>
1273
+ <button type="button" class="clado-cd-btn" data-cd-copy>复制路径</button>
1274
+ </div>
1275
+ <div class="clado-cd-body">${bodyHtml}</div>
1276
+ <div class="clado-cd-foot">
1277
+ <div class="clado-cd-cards">${cardsHtml ? `<span>关联卡片:</span>${cardsHtml}` : '<span>实时源码与 Git Diff</span>'}</div>
1278
+ <button type="button" class="clado-cd-btn" data-cd-sync>核对画布同步</button>
1279
+ </div>
1280
+ `;
1281
+ codeDrawerEl.hidden = false;
1282
+
1283
+ codeDrawerEl.querySelector('[data-cd-close]').onclick = () => { codeDrawerEl.hidden = true; };
1284
+ codeDrawerEl.querySelector('[data-cd-copy]').onclick = () => {
1285
+ navigator.clipboard?.writeText(tab.path).then(() => showToast('已复制路径:' + tab.path)).catch(() => {});
1286
+ };
1287
+ codeDrawerEl.querySelector('[data-cd-sync]').onclick = () => {
1288
+ window.dispatchEvent(new CustomEvent('clado:agent-prefill', {
1289
+ detail: {
1290
+ mode: 'custom',
1291
+ file: selected,
1292
+ prompt: `请核对源码 \`${tab.path}\` 的最新改动与当前画布 \`${selected || ''}\` 是否一致,如有出入请直接同步更新对应卡片并调用 clado_graph 复查。`,
1293
+ },
1294
+ }));
1295
+ };
1296
+ codeDrawerEl.querySelectorAll('[data-cd-mode]').forEach(btn => {
1297
+ btn.onclick = () => { codeViewMode = btn.dataset.cdMode; renderCodeDrawer(); };
1298
+ });
1299
+ codeDrawerEl.querySelectorAll('[data-cd-tab]').forEach(btn => {
1300
+ btn.onclick = () => { activeCodePath = btn.dataset.cdTab; renderCodeDrawer(); };
1301
+ });
1302
+ codeDrawerEl.querySelectorAll('[data-cd-card]').forEach(btn => {
1303
+ btn.onclick = () => focusTarget(selected, [btn.dataset.cdCard], btn.dataset.cdCard);
1304
+ });
1305
+ if (effectiveMode === 'source' && tab.matchedLine) {
1306
+ const targetRow = codeDrawerEl.querySelector(`[data-cd-ln="${tab.matchedLine}"]`);
1307
+ if (targetRow) targetRow.scrollIntoView({ block: 'center' });
1308
+ }
1309
+ }
1310
+
1311
+ async function openCodeDrawerFile(pathOrRef, opts = {}) {
1312
+ if (!codeDrawerEl || offline || !pathOrRef) return;
1313
+ const raw = String(pathOrRef).trim();
1314
+ const isSymbol = opts.isSymbol || (!raw.includes('/') && /[#.]/.test(raw) && !/\.(js|ts|tsx|jsx|mjs|cjs|py|go|rs|java|kt|cpp|c|h|rb|php|cs|vue|svelte|css|html|json|yaml|yml|toml|sql|md)$/i.test(raw));
1315
+ const key = raw;
1316
+ if (!codeTabs.has(key)) {
1317
+ codeTabs.set(key, { path: key, content: '', diff: null, loading: true, matchedCards: opts.matchedCards || [] });
1318
+ }
1319
+ activeCodePath = key;
1320
+ renderCodeDrawer();
1321
+ try {
1322
+ const qs = isSymbol ? ('symbol=' + encodeURIComponent(raw)) : ('path=' + encodeURIComponent(raw));
1323
+ const res = await fetch(withWorkspace('/library/code-file?' + qs), { cache: 'no-store' });
1324
+ const data = await res.json();
1325
+ if (!res.ok) throw new Error(data.error || '无法读取源码');
1326
+ const finalPath = data.path || raw;
1327
+ if (finalPath !== key) codeTabs.delete(key);
1328
+ const prevTab = codeTabs.get(finalPath);
1329
+ const diff = (data.changed && data.headContent != null)
1330
+ ? computeCodeLineDiff(data.headContent, data.content)
1331
+ : (prevTab?.diff || null);
1332
+ codeTabs.set(finalPath, {
1333
+ path: finalPath,
1334
+ content: data.content || '',
1335
+ matchedLine: data.matchedLine || null,
1336
+ diff,
1337
+ loading: false,
1338
+ error: '',
1339
+ liveStatus: '',
1340
+ matchedCards: opts.matchedCards || prevTab?.matchedCards || [],
1341
+ });
1342
+ activeCodePath = finalPath;
1343
+ if (diff && (diff.added || diff.removed)) codeViewMode = 'diff';
1344
+ else codeViewMode = 'source';
1345
+ renderCodeDrawer();
1346
+ } catch (err) {
1347
+ const cur = codeTabs.get(key);
1348
+ if (cur) {
1349
+ cur.loading = false;
1350
+ cur.error = err.message || '读取源码失败';
1351
+ renderCodeDrawer();
1352
+ }
1353
+ }
1354
+ }
1355
+
1356
+ function handleCodeActivityEvent(payload) {
1357
+ if (!payload?.path) return;
1358
+ if (Array.isArray(payload.matchedCards) && payload.matchedCards.length && readyCanvas?.frame === frame) {
1359
+ try {
1360
+ frame.contentWindow.postMessage({
1361
+ type: 'clado-workspace:ai-touch',
1362
+ kind: 'implementing',
1363
+ nodes: payload.matchedCards,
1364
+ label: `${payload.roleName || '开发'} · ${payload.phase === 'reading' ? '查看' : '正在改写'} ${payload.path}`,
1365
+ follow: false,
1366
+ }, location.origin);
1367
+ } catch {}
1368
+ }
1369
+ if (payload.phase === 'editing') {
1370
+ const existing = codeTabs.get(payload.path) || { path: payload.path, content: '', diff: null };
1371
+ existing.liveStatus = `${payload.roleName || 'AI'} 正在实时编辑…`;
1372
+ existing.matchedCards = payload.matchedCards || existing.matchedCards || [];
1373
+ codeTabs.set(payload.path, existing);
1374
+ activeCodePath = payload.path;
1375
+ renderCodeDrawer();
1376
+ }
1377
+ }
1378
+
1379
+ function handleCodeDiffEvent(payload) {
1380
+ if (!payload?.path || payload.after == null) return;
1381
+ const diff = computeCodeLineDiff(payload.before, payload.after);
1382
+ codeTabs.set(payload.path, {
1383
+ path: payload.path,
1384
+ content: payload.after,
1385
+ diff,
1386
+ loading: false,
1387
+ error: '',
1388
+ liveStatus: `${payload.roleName || 'AI'} 已更新 · +${diff.added} -${diff.removed}`,
1389
+ matchedCards: payload.matchedCards || [],
1390
+ });
1391
+ activeCodePath = payload.path;
1392
+ codeViewMode = 'diff';
1393
+ renderCodeDrawer();
1394
+ if (Array.isArray(payload.matchedCards) && payload.matchedCards.length && readyCanvas?.frame === frame) {
1395
+ try {
1396
+ frame.contentWindow.postMessage({
1397
+ type: 'clado-workspace:ai-touch',
1398
+ kind: 'implementing',
1399
+ nodes: payload.matchedCards,
1400
+ label: `已落地代码 ${payload.path} (+${diff.added} / -${diff.removed})`,
1401
+ follow: false,
1402
+ }, location.origin);
1403
+ } catch {}
1404
+ }
1405
+ }
1406
+
1407
+ window.CladoCodeDrawer = {
1408
+ openFile: (p, opts) => openCodeDrawerFile(p, opts),
1409
+ openRef: ref => openCodeDrawerFile(ref),
1410
+ close: () => { if (codeDrawerEl) codeDrawerEl.hidden = true; },
1411
+ };
1412
+
957
1413
  if (isEnabled('clado.agent')) window.CladoAgentPlugin(host, {
958
1414
  withWorkspace,
959
1415
  setTheme: applyTheme,
960
1416
  capture: captureShot,
961
1417
  focusCanvas: (file, heading) => focusTarget(file, heading ? [heading] : null, heading || ''),
1418
+ focusTag,
1419
+ getCanvasEntities,
1420
+ openCodeFile: p => openCodeDrawerFile(p),
962
1421
  readContext() {
963
1422
  const objSel = objectSelection.size ? [...objectSelection.values()] : undefined;
964
1423
  if (readyCanvas?.frame !== frame) return { file: selected || '', selection: [], ...(objSel ? { objectSelection: objSel } : {}) };
@@ -1036,35 +1495,64 @@
1036
1495
  if(!chainModal) { const force=deferredRefresh;deferredRefresh=false;scan(force); }
1037
1496
  }
1038
1497
  function renderDirectory() { directory.update(index, selected, history.length > 0); }
1039
- let emptyWorkspaceSignature = '';
1040
1498
  function renderEmptyWorkspaces(list) {
1041
- const others = list.filter(item => item.id !== workspaceId);
1499
+ discoveredWorkspaces = Array.isArray(list) ? list : [];
1500
+ const others = discoveredWorkspaces.filter(item => item.id !== workspaceId);
1042
1501
  const next = JSON.stringify(others.map(item => [item.id, item.name, item.documents]));
1043
- if (next === emptyWorkspaceSignature) return;
1502
+ if (next === emptyWorkspaceSignature && $('#emptyState .empty-workspaces')) return;
1044
1503
  emptyWorkspaceSignature = next;
1045
1504
  let container = $('#emptyState .empty-workspaces');
1046
1505
  if (!others.length) { container?.remove(); return; }
1506
+ const hostEl = $('#emptyState .clado-empty-card') || $('#emptyState .clado-launchpad-card') || $('#emptyState');
1047
1507
  if (!container) {
1048
1508
  container = document.createElement('div');
1049
1509
  container.className = 'empty-workspaces';
1050
- ($('#emptyState .clado-launchpad-card') || $('#emptyState')).append(container);
1510
+ hostEl.append(container);
1511
+ } else if (container.parentElement !== hostEl) {
1512
+ hostEl.append(container);
1051
1513
  }
1052
1514
  container.replaceChildren();
1515
+ const head = document.createElement('div');
1516
+ head.className = 'empty-workspaces-head';
1053
1517
  const title = document.createElement('div');
1054
1518
  title.className = 'empty-workspaces-title';
1055
- title.textContent = '已发现的子工作区(点击打开)';
1056
- container.append(title);
1519
+ title.textContent = '已发现的子工作区';
1520
+ const badge = document.createElement('span');
1521
+ badge.className = 'empty-workspaces-count';
1522
+ badge.textContent = `${others.length} 个工作区`;
1523
+ head.append(title, badge);
1524
+ container.append(head);
1525
+
1526
+ const grid = document.createElement('div');
1527
+ grid.className = 'empty-workspaces-grid';
1057
1528
  for (const item of others) {
1058
1529
  const link = document.createElement('a');
1059
1530
  link.className = 'empty-workspace-card';
1060
1531
  link.href = workspaceUrl(item.id);
1532
+ const label = item.id || (item.name + '(根目录)');
1533
+ link.title = label;
1534
+
1535
+ const ico = document.createElement('span');
1536
+ ico.className = 'empty-workspace-ico';
1537
+ ico.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>';
1538
+
1539
+ const meta = document.createElement('span');
1540
+ meta.className = 'empty-workspace-meta';
1061
1541
  const name = document.createElement('span');
1062
- name.textContent = item.id || (item.name + '(根目录)');
1542
+ name.className = 'empty-workspace-name';
1543
+ name.textContent = label;
1063
1544
  const count = document.createElement('small');
1064
1545
  count.textContent = (item.documents ?? 0) + ' 份画布';
1065
- link.append(name, count);
1066
- container.append(link);
1546
+ meta.append(name, count);
1547
+
1548
+ const arrow = document.createElement('span');
1549
+ arrow.className = 'empty-workspace-arrow';
1550
+ arrow.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18l6-6-6-6"/></svg>';
1551
+
1552
+ link.append(ico, meta, arrow);
1553
+ grid.append(link);
1067
1554
  }
1555
+ container.append(grid);
1068
1556
  }
1069
1557
  let renderRequest = 0;
1070
1558
  async function openFromCapability(file) {
@@ -1099,15 +1587,85 @@
1099
1587
  if (readyCanvas?.frame !== frame || readyCanvas?.file !== file) throw failure('NAVIGATION_FAILED', '目标画布已被另一次导航替换。');
1100
1588
  return { file, title: targetDocument.title, mode };
1101
1589
  }
1590
+ function capturePrevDocSnapshot(doc, filePath) {
1591
+ if (!doc || !Array.isArray(doc.cards)) return null;
1592
+ const snapNodes = list => (list || []).map(n => ({ title: n.title || '', md: n.md || '', kids: snapNodes(n.kids) }));
1593
+ return {
1594
+ file: filePath,
1595
+ title: doc.title || '',
1596
+ cards: doc.cards.map(c => ({ title: c.title || '', md: c.md || '', nodes: snapNodes(c.nodes) })),
1597
+ };
1598
+ }
1102
1599
  async function open(file, anchor = '', options = {}) {
1103
1600
  if(modalLocked()) { if(options.update)deferredRefresh=true;return; }
1104
1601
  pendingAnchor=anchor;
1105
1602
  const doc = index.documents.find(d => d.file === file);
1106
1603
  if (!doc) { directory.showMessage('这个 Markdown 暂未收录', file + ' 不在有效画布目录中。可以让 AI 检查文件路径和解析状态。'); return; }
1107
1604
  if (selected && file !== selected && !options.back) history.push(selected);
1108
- if (options.update && readyCanvas?.frame === frame && readyCanvas.file === file) { try { pendingView = frame.contentWindow.CladoPrototype?.captureView?.(); } catch {} }
1109
- else pendingView = null;
1605
+ const canHotPatch = Boolean(
1606
+ options.update
1607
+ && !offline
1608
+ && !anchor
1609
+ && readyCanvas?.frame === frame
1610
+ && readyCanvas.file === file
1611
+ && typeof frame.contentWindow?.CladoRuntime?.hotPatchDoc === 'function'
1612
+ );
1613
+ if (options.update && readyCanvas?.frame === frame && readyCanvas.file === file) {
1614
+ try { pendingView = frame.contentWindow.CladoPrototype?.captureView?.(); } catch {}
1615
+ try {
1616
+ const snap = capturePrevDocSnapshot(frame.contentWindow.__CLADO__, file);
1617
+ if (snap) pendingPrevDoc = { ...snap, ts: Date.now() };
1618
+ } catch {}
1619
+ } else {
1620
+ pendingView = null;
1621
+ if (pendingPrevDoc && pendingPrevDoc.file !== file) pendingPrevDoc = null;
1622
+ }
1110
1623
  const request = ++renderRequest, previousVersion = version, requestedMode = mode;
1624
+
1625
+ // 优先零闪烁原地热更新:拉取轻量化 doc.json 并在当前 iframe 内原位 patch DOM、执行实时红删绿增 Diff 与新增连线光束动画
1626
+ if (canHotPatch) {
1627
+ try {
1628
+ const patchRes = await fetch(withWorkspace('/library/doc.json?file=' + encodeURIComponent(file)), { cache: 'no-store' });
1629
+ if (patchRes.ok && request === renderRequest && !modalLocked() && mode === requestedMode) {
1630
+ const patchData = await patchRes.json();
1631
+ const hasFreshTouch = pendingTouch && (Date.now() - pendingTouch.ts <= 6000) && (!pendingTouch.file || pendingTouch.file === file);
1632
+ const touchPayload = hasFreshTouch ? pendingTouch : null;
1633
+ const follow = typeof touchPayload?.follow === 'boolean' ? touchPayload.follow : followAi;
1634
+ const patched = frame.contentWindow.CladoRuntime.hotPatchDoc(
1635
+ patchData.doc,
1636
+ patchData.diagnostics,
1637
+ patchData.version || doc.version,
1638
+ touchPayload,
1639
+ follow,
1640
+ );
1641
+ if (patched) {
1642
+ selected = file;
1643
+ version = patchData.version || doc.version;
1644
+ readyCanvas = { frame, file, revision: version };
1645
+ pendingView = null;
1646
+ pendingPrevDoc = null;
1647
+ if (hasFreshTouch) pendingTouch = null;
1648
+ if (selectionTab && aiSelection && aiSelection.version !== version) {
1649
+ const api = frame.contentWindow.CladoRuntime;
1650
+ const nodes = aiSelection.nodes.filter(node => api?.hasSelectionPath(node));
1651
+ setSelection(nodes.length ? { file: selected, version, nodes } : null, nodes.length > 0);
1652
+ }
1653
+ showSelection();
1654
+ syncFrameObjects();
1655
+ saveView();
1656
+ renderDirectory();
1657
+ syncChrome();
1658
+ $('#updateError').hidden = true;
1659
+ $('#emptyState').hidden = true;
1660
+ $('#canvasLoading').hidden = true;
1661
+ status('已同步 ' + new Date(doc.modified || Date.now()).toLocaleTimeString('zh-CN', { hour12: false }));
1662
+ return true;
1663
+ }
1664
+ }
1665
+ } catch {}
1666
+ if (request !== renderRequest) return;
1667
+ }
1668
+
1111
1669
  selected = file; version = doc.version; saveView(); renderDirectory(); syncChrome();
1112
1670
  $('#updateError').hidden = true; $('#emptyState').hidden = true; $('#canvasLoading').hidden = false;
1113
1671
  // Give each render its own browsing context. A late ready/message from the
@@ -1138,14 +1696,23 @@
1138
1696
  $('#updateError').textContent = '画布读取失败,保留上次画面并自动重试。'; $('#updateError').hidden = false; status('当前画布未更新', true);
1139
1697
  }
1140
1698
  }
1141
- let pendingRescan = false, pendingTouch = null;
1699
+ let pendingRescan = false, pendingTouch = null, pendingPrevDoc = null;
1142
1700
  function flushPendingTouch() {
1143
- if (!pendingTouch || Date.now() - pendingTouch.ts > 6000) { pendingTouch = null; return; }
1144
- if (pendingTouch.file && pendingTouch.file !== selected) return;
1145
1701
  if (readyCanvas?.frame !== frame || readyCanvas.file !== selected) return;
1146
- const payload = pendingTouch;
1147
- pendingTouch = null;
1148
- const follow = typeof payload.follow === 'boolean' ? payload.follow : followAi;
1702
+ const prevDoc = pendingPrevDoc && pendingPrevDoc.file === selected && (Date.now() - pendingPrevDoc.ts <= 8000)
1703
+ ? pendingPrevDoc : null;
1704
+ if (pendingPrevDoc && (!prevDoc || prevDoc.file === selected)) pendingPrevDoc = null;
1705
+
1706
+ const hasFreshTouch = pendingTouch && (Date.now() - pendingTouch.ts <= 6000) && (!pendingTouch.file || pendingTouch.file === selected);
1707
+ const payload = hasFreshTouch ? pendingTouch : null;
1708
+ if (pendingTouch && (hasFreshTouch || Date.now() - pendingTouch.ts > 6000)) pendingTouch = null;
1709
+
1710
+ const follow = typeof payload?.follow === 'boolean' ? payload.follow : followAi;
1711
+ if (prevDoc) {
1712
+ try { frame.contentWindow.postMessage({ type: 'clado-workspace:live-diff', prevDoc, touch: payload, follow }, offline ? '*' : location.origin); } catch {}
1713
+ return;
1714
+ }
1715
+ if (!payload) return;
1149
1716
  try { frame.contentWindow.postMessage({ type: 'clado-workspace:ai-touch', ...payload, follow }, offline ? '*' : location.origin); } catch {}
1150
1717
  }
1151
1718
  const status = (message, error) => directory.status(message, error);
@@ -1184,7 +1751,7 @@
1184
1751
  const doc = index.documents.find(d => d.file === selected);
1185
1752
  if (!doc && !version && index.documents.length) open(index.documents[0].file);
1186
1753
  else if (!doc) { $('#updateError').textContent = '当前 Markdown 已删除或暂时无法解析,保留上次画面。有效文档仍可从目录打开。'; $('#updateError').hidden = false; status('当前画布未更新', true); $('#canvasLoading').hidden = true; post('ready'); }
1187
- else { $('#updateError').hidden = true; if (force || doc.version !== version) { open(selected, version ? '' : pendingAnchor, { update: true }); } else { flushPendingTouch(); status('已同步 ' + new Date(doc.modified).toLocaleTimeString('zh-CN', { hour12: false })); } }
1754
+ else { $('#updateError').hidden = true; if (!version || doc.version !== version) { open(selected, version ? '' : pendingAnchor, { update: true }); } else { flushPendingTouch(); status('已同步 ' + new Date(doc.modified).toLocaleTimeString('zh-CN', { hour12: false })); } }
1188
1755
  }
1189
1756
  } catch { if (pageHidden) return; status('连接中断,正在重连', true); $('#updateError').textContent = '目录连接中断,保留当前画面。服务恢复后自动重连。'; $('#updateError').hidden = false; $('#canvasLoading').hidden = true; post('ready'); }
1190
1757
  finally {
@@ -1222,6 +1789,65 @@
1222
1789
  openCanvasCtxMenu((rect.left || 0) + (data.x || 0), (rect.top || 0) + (data.y || 0), data.detail);
1223
1790
  return;
1224
1791
  }
1792
+ if (!offline && data?.type === 'clado-library:complete-link' && data.source && data.target) {
1793
+ (async () => {
1794
+ try {
1795
+ const src = data.source;
1796
+ const tgt = data.target;
1797
+ const payload = {
1798
+ file: selected,
1799
+ sourceNode: src.node,
1800
+ anchor: src.selectedText || '',
1801
+ label: src.selectedText || tgt.label || (Array.isArray(tgt.targetNode) ? tgt.targetNode[tgt.targetNode.length - 1] : ''),
1802
+ sourcePoint: src.sourcePoint || null,
1803
+ targetNode: tgt.targetNode || null,
1804
+ targetTagId: tgt.targetTagId || '',
1805
+ targetPoint: tgt.targetPoint || null,
1806
+ };
1807
+ const res = await fetch(withWorkspace('/library/link'), {
1808
+ method: 'POST',
1809
+ headers: { 'content-type': 'application/json' },
1810
+ body: JSON.stringify(payload),
1811
+ });
1812
+ const result = await res.json();
1813
+ if (!res.ok) throw new Error(result.error || '创建连线失败');
1814
+ showToast('已连接到 ' + (tgt.label || tgt.targetTagId || '目标'));
1815
+ pendingTouch = { file: selected, nodes: [src.node, ...(tgt.targetNode ? [tgt.targetNode] : [])], kind: 'write', label: '已建立新连线', follow: false, ts: Date.now() };
1816
+ await scan(true);
1817
+ } catch (err) {
1818
+ showToast(err.message || '创建连线失败');
1819
+ }
1820
+ })();
1821
+ return;
1822
+ }
1823
+ if (data?.type === 'clado-library:selection-action' && data.selectedText) {
1824
+ window.dispatchEvent(new CustomEvent('clado:agent-prefill', {
1825
+ detail: {
1826
+ mode: data.mode || 'ask',
1827
+ file: selected,
1828
+ node: data.node || null,
1829
+ selectedText: data.selectedText,
1830
+ },
1831
+ }));
1832
+ return;
1833
+ }
1834
+ if (data?.type === 'clado-library:open-code-ref' && data.ref) {
1835
+ openCodeDrawerFile(data.ref);
1836
+ return;
1837
+ }
1838
+ if (data?.type === 'clado-library:presence-click') {
1839
+ if (data.sessionId || data.roleId) {
1840
+ window.dispatchEvent(new CustomEvent('clado:focus-session', {
1841
+ detail: { sessionId: data.sessionId || '', roleId: data.roleId || '' },
1842
+ }));
1843
+ }
1844
+ if (data.codePath) openCodeDrawerFile(data.codePath);
1845
+ return;
1846
+ }
1847
+ if (data?.type === 'clado-library:canvas-interacted') {
1848
+ armPresenceAfterglowForFile(selected);
1849
+ return;
1850
+ }
1225
1851
  if (data?.type === 'clado-library:chain-modal') { chainLock(data.value, data.mode); return; }
1226
1852
  if (data?.type === 'clado-library:lens-modal') {
1227
1853
  lensOpen = !!data.value;
@@ -1254,6 +1880,8 @@
1254
1880
  }
1255
1881
  showSelection();
1256
1882
  syncFrameObjects();
1883
+ syncPresenceConfigToCanvas();
1884
+ syncPresenceSnapshotToCanvas();
1257
1885
  if(offline){frame.contentWindow.postMessage({type:'clado-workspace:display',mode,theme:design.theme,anchor:pendingAnchor},'*');pendingAnchor='';}
1258
1886
  else if (mode !== data.mode) frame.contentWindow.CladoPrototype?.setMode?.(mode);
1259
1887
  saveView(); $('#canvasLoading').hidden = true; syncChrome();
@@ -1270,8 +1898,254 @@
1270
1898
  status('已同步 ' + new Date(index.documents.find(d => d.file === selected)?.modified || Date.now()).toLocaleTimeString('zh-CN', { hour12: false })); post('ready');
1271
1899
  }
1272
1900
  });
1901
+
1902
+ const PRESENCE_HARD_MAX_MS = 30 * 60 * 1000;
1903
+ const presenceByFile = new Map(); // file -> Map<cardKey, Map<sessionId, entry>>
1904
+ let presenceSweepTimer = 0;
1905
+
1906
+ function toAfterglowPresenceLabel(activeLabel, fallback) {
1907
+ const raw = String(activeLabel || '').trim();
1908
+ if (!raw) return fallback || '刚刚编辑了';
1909
+ if (raw.startsWith('刚刚')) return raw;
1910
+ if (/^正在(?:新建|创建)/.test(raw)) return '刚刚新建了';
1911
+ if (/^正在删除/.test(raw)) return '刚刚删除了';
1912
+ if (/^正在移除连线/.test(raw)) return '刚刚移除了连线';
1913
+ if (/^正在连线/.test(raw)) return '刚刚连线了';
1914
+ if (/^正在调整/.test(raw)) return '刚刚调整了';
1915
+ if (/^正在修改\s+(.+)$/.test(raw)) return raw.replace(/^正在修改\s+/, '刚刚修改了 ');
1916
+ if (/^正在查看\s+(.+)$/.test(raw)) return raw.replace(/^正在查看\s+/, '刚刚查看了 ');
1917
+ if (/^正在查看/.test(raw)) return '刚刚查看了';
1918
+ if (/^正在编辑/.test(raw)) return '刚刚编辑了';
1919
+ if (/^修改\s+(.+)$/.test(raw)) return raw.replace(/^修改\s+/, '刚刚修改了 ');
1920
+ if (/^查看\s+(.+)$/.test(raw)) return raw.replace(/^查看\s+/, '刚刚查看了 ');
1921
+ return fallback || '刚刚编辑了';
1922
+ }
1923
+
1924
+ function readPresenceAfterglowMs() {
1925
+ try {
1926
+ const raw = localStorage.getItem('clado-presence-ttl');
1927
+ if (raw !== null && raw !== '') {
1928
+ const sec = Number(raw);
1929
+ if (Number.isFinite(sec) && sec >= 0) return Math.round(sec * 1000);
1930
+ }
1931
+ } catch {}
1932
+ return 30000;
1933
+ }
1934
+
1935
+ function collectPresenceEntriesForFile(file) {
1936
+ if (!file) return [];
1937
+ const fileMap = presenceByFile.get(file);
1938
+ if (!fileMap) return [];
1939
+ const out = [];
1940
+ for (const cardMap of fileMap.values()) {
1941
+ for (const entry of cardMap.values()) out.push({ ...entry });
1942
+ }
1943
+ return out;
1944
+ }
1945
+
1946
+ function syncPresenceSnapshotToCanvas() {
1947
+ if (readyCanvas?.frame !== frame || !selected) return;
1948
+ try {
1949
+ frame.contentWindow.postMessage({
1950
+ type: 'clado-workspace:presence-sync',
1951
+ entries: collectPresenceEntriesForFile(selected),
1952
+ }, offline ? '*' : location.origin);
1953
+ } catch {}
1954
+ }
1955
+
1956
+ function ensurePresenceSweepTimer() {
1957
+ if (presenceByFile.size > 0 && !presenceSweepTimer) {
1958
+ presenceSweepTimer = setInterval(sweepPresenceRegistry, 1000);
1959
+ } else if (presenceByFile.size === 0 && presenceSweepTimer) {
1960
+ clearInterval(presenceSweepTimer);
1961
+ presenceSweepTimer = 0;
1962
+ }
1963
+ }
1964
+
1965
+ function sweepPresenceRegistry() {
1966
+ const now = Date.now();
1967
+ let selectedChanged = false;
1968
+ for (const [file, fileMap] of presenceByFile.entries()) {
1969
+ for (const [cardKey, cardMap] of fileMap.entries()) {
1970
+ for (const [sid, entry] of cardMap.entries()) {
1971
+ const hardCap = entry.hardExpiresAt || (entry.ts + PRESENCE_HARD_MAX_MS);
1972
+ const exp = entry.expiresAt || hardCap;
1973
+ if (now >= hardCap || (entry.phase === 'afterglow' && entry.armedAt && now >= exp)) {
1974
+ cardMap.delete(sid);
1975
+ if (file === selected) selectedChanged = true;
1976
+ }
1977
+ }
1978
+ if (!cardMap.size) fileMap.delete(cardKey);
1979
+ }
1980
+ if (!fileMap.size) presenceByFile.delete(file);
1981
+ }
1982
+ ensurePresenceSweepTimer();
1983
+ if (selectedChanged) syncPresenceSnapshotToCanvas();
1984
+ }
1985
+
1986
+ function armPresenceAfterglowForFile(file) {
1987
+ if (!file) return;
1988
+ const fileMap = presenceByFile.get(file);
1989
+ if (!fileMap) return;
1990
+ const now = Date.now();
1991
+ const afterglowMs = readPresenceAfterglowMs();
1992
+ let changed = false;
1993
+ for (const [cardKey, cardMap] of fileMap.entries()) {
1994
+ for (const [sid, entry] of cardMap.entries()) {
1995
+ if (entry.phase !== 'afterglow' || entry.armedAt) continue;
1996
+ if (afterglowMs <= 0) {
1997
+ cardMap.delete(sid);
1998
+ } else {
1999
+ entry.armedAt = now;
2000
+ const hardCap = entry.hardExpiresAt || (now + PRESENCE_HARD_MAX_MS);
2001
+ entry.expiresAt = Math.min(hardCap, now + afterglowMs);
2002
+ }
2003
+ changed = true;
2004
+ }
2005
+ if (!cardMap.size) fileMap.delete(cardKey);
2006
+ }
2007
+ if (!fileMap.size) presenceByFile.delete(file);
2008
+ ensurePresenceSweepTimer();
2009
+ if (changed && file === selected) syncPresenceSnapshotToCanvas();
2010
+ }
2011
+
2012
+ function applyPresenceEventToRegistry(payload) {
2013
+ if (!payload || typeof payload !== 'object') return;
2014
+ const sid = String(payload.sessionId || payload.roleId || 'agent');
2015
+ const phase = payload.phase || 'active';
2016
+ const now = Date.now();
2017
+ const afterglowMs = readPresenceAfterglowMs();
2018
+
2019
+ if (phase === 'clear') {
2020
+ const targetFile = String(payload.file || '').trim();
2021
+ const rawCards = (Array.isArray(payload.cards) ? payload.cards : [])
2022
+ .map(c => (Array.isArray(c) ? String(c[0] || '').trim() : String(c || '').trim()))
2023
+ .filter(Boolean);
2024
+ const files = targetFile ? [targetFile] : Array.from(presenceByFile.keys());
2025
+ for (const f of files) {
2026
+ const fileMap = presenceByFile.get(f);
2027
+ if (!fileMap) continue;
2028
+ const keys = rawCards.length ? rawCards : Array.from(fileMap.keys());
2029
+ for (const k of keys) {
2030
+ const cardMap = fileMap.get(k);
2031
+ if (!cardMap) continue;
2032
+ cardMap.delete(sid);
2033
+ if (!cardMap.size) fileMap.delete(k);
2034
+ }
2035
+ if (!fileMap.size) presenceByFile.delete(f);
2036
+ }
2037
+ ensurePresenceSweepTimer();
2038
+ syncPresenceSnapshotToCanvas();
2039
+ return;
2040
+ }
2041
+
2042
+ if (phase === 'afterglow') {
2043
+ // Transition ALL active entries of this session across ALL files into '刚刚编辑了' (unarmed until user interacts with that specific canvas)
2044
+ for (const [f, fileMap] of presenceByFile.entries()) {
2045
+ for (const [k, cardMap] of fileMap.entries()) {
2046
+ const existing = cardMap.get(sid);
2047
+ if (!existing || existing.phase !== 'active') continue;
2048
+ if (afterglowMs <= 0) {
2049
+ cardMap.delete(sid);
2050
+ } else {
2051
+ existing.phase = 'afterglow';
2052
+ existing.label = toAfterglowPresenceLabel(existing.label, payload.label || '刚刚编辑了');
2053
+ existing.ts = now;
2054
+ existing.armedAt = 0;
2055
+ existing.hardExpiresAt = now + PRESENCE_HARD_MAX_MS;
2056
+ existing.expiresAt = existing.hardExpiresAt;
2057
+ }
2058
+ if (!cardMap.size) fileMap.delete(k);
2059
+ }
2060
+ if (!fileMap.size) presenceByFile.delete(f);
2061
+ }
2062
+ ensurePresenceSweepTimer();
2063
+ syncPresenceSnapshotToCanvas();
2064
+ return;
2065
+ }
2066
+
2067
+ // phase === 'active': accumulate all cards touched in this turn on targetFile
2068
+ const targetFile = String(payload.file || selected || '').trim();
2069
+ const rawCards = (Array.isArray(payload.cards) ? payload.cards : [])
2070
+ .map(c => (Array.isArray(c) ? String(c[0] || '').trim() : String(c || '').trim()))
2071
+ .filter(Boolean);
2072
+ if (!targetFile || !rawCards.length) return;
2073
+
2074
+ // Refresh 30m hard cap on other still-active entries of this session
2075
+ for (const fileMap of presenceByFile.values()) {
2076
+ for (const cardMap of fileMap.values()) {
2077
+ const existing = cardMap.get(sid);
2078
+ if (existing && existing.phase === 'active') {
2079
+ existing.hardExpiresAt = now + PRESENCE_HARD_MAX_MS;
2080
+ existing.expiresAt = existing.hardExpiresAt;
2081
+ }
2082
+ }
2083
+ }
2084
+
2085
+ let fileMap = presenceByFile.get(targetFile);
2086
+ if (!fileMap) {
2087
+ fileMap = new Map();
2088
+ presenceByFile.set(targetFile, fileMap);
2089
+ }
2090
+ for (const cardKey of rawCards) {
2091
+ let cardMap = fileMap.get(cardKey);
2092
+ if (!cardMap) {
2093
+ cardMap = new Map();
2094
+ fileMap.set(cardKey, cardMap);
2095
+ }
2096
+ cardMap.set(sid, {
2097
+ file: targetFile,
2098
+ cardKey,
2099
+ sessionId: sid,
2100
+ roleId: String(payload.roleId || ''),
2101
+ roleName: String(payload.roleName || 'AI 角色'),
2102
+ tone: String(payload.tone || 'sky'),
2103
+ label: String(payload.label || '正在编辑'),
2104
+ codePath: String(payload.codePath || ''),
2105
+ phase: 'active',
2106
+ ts: now,
2107
+ armedAt: 0,
2108
+ hardExpiresAt: now + PRESENCE_HARD_MAX_MS,
2109
+ expiresAt: now + PRESENCE_HARD_MAX_MS,
2110
+ });
2111
+ }
2112
+ ensurePresenceSweepTimer();
2113
+ if (targetFile === selected) syncPresenceSnapshotToCanvas();
2114
+ }
2115
+
2116
+ function syncPresenceConfigToCanvas(overrideMs) {
2117
+ const afterglowMs = typeof overrideMs === 'number' && Number.isFinite(overrideMs) ? overrideMs : readPresenceAfterglowMs();
2118
+ const now = Date.now();
2119
+ for (const [f, fileMap] of presenceByFile.entries()) {
2120
+ for (const [k, cardMap] of fileMap.entries()) {
2121
+ for (const [sid, entry] of cardMap.entries()) {
2122
+ if (entry.phase !== 'afterglow') continue;
2123
+ if (afterglowMs <= 0) {
2124
+ cardMap.delete(sid);
2125
+ } else if (entry.armedAt) {
2126
+ const hardCap = entry.hardExpiresAt || (now + PRESENCE_HARD_MAX_MS);
2127
+ entry.expiresAt = Math.min(hardCap, entry.armedAt + afterglowMs);
2128
+ }
2129
+ }
2130
+ if (!cardMap.size) fileMap.delete(k);
2131
+ }
2132
+ if (!fileMap.size) presenceByFile.delete(f);
2133
+ }
2134
+ ensurePresenceSweepTimer();
2135
+ if (readyCanvas?.frame !== frame) return;
2136
+ try {
2137
+ frame.contentWindow.postMessage({
2138
+ type: 'clado-workspace:presence-config',
2139
+ config: { afterglowMs },
2140
+ }, offline ? '*' : location.origin);
2141
+ } catch {}
2142
+ syncPresenceSnapshotToCanvas();
2143
+ }
2144
+ addEventListener('clado:presence-config', ev => {
2145
+ syncPresenceConfigToCanvas(ev.detail?.afterglowMs);
2146
+ });
1273
2147
  function setDesign(next) { design = { ...design, ...next }; document.documentElement.dataset.theme = design.theme || 'light'; if (design.accent) document.documentElement.style.setProperty('--accent', design.accent); try { frame.contentWindow.CladoPrototype?.setDesign(design); } catch {} syncChrome(); }
1274
- window.CladoPrototype = { setDesign, fit: () => frame.contentWindow.CladoPrototype?.fit(), closeLens: () => frame.contentWindow.CladoPrototype?.closeLens() };
2148
+ window.CladoPrototype = { setDesign, fit: () => { armPresenceAfterglowForFile(selected); return frame.contentWindow.CladoPrototype?.fit(); }, closeLens: () => frame.contentWindow.CladoPrototype?.closeLens() };
1275
2149
  setDesign(design);
1276
2150
  scan();
1277
2151
  if (!offline) {
@@ -1283,7 +2157,13 @@
1283
2157
  es.addEventListener('doc.updated', event => {
1284
2158
  try {
1285
2159
  const payload = JSON.parse(event.data || '{}');
1286
- if (!payload.file || payload.file === selected) pendingTouch = { ...payload, ts: Date.now() };
2160
+ if (payload.action === 'create' && payload.file && (followAi || !selected)) {
2161
+ pendingOpen = payload.file;
2162
+ pendingPrevDoc = { file: payload.file, title: '', cards: [], ts: Date.now() };
2163
+ pendingTouch = { ...payload, ts: Date.now() };
2164
+ } else if (!payload.file || payload.file === selected) {
2165
+ pendingTouch = { ...payload, ts: Date.now() };
2166
+ }
1287
2167
  } catch {}
1288
2168
  scan(true);
1289
2169
  });
@@ -1298,12 +2178,44 @@
1298
2178
  }
1299
2179
  } catch {}
1300
2180
  });
2181
+ es.addEventListener('agent.presence', event => {
2182
+ try {
2183
+ const payload = JSON.parse(event.data || '{}');
2184
+ applyPresenceEventToRegistry(payload);
2185
+ } catch {}
2186
+ });
1301
2187
  es.addEventListener('agent.focus', event => {
1302
2188
  try {
1303
2189
  const payload = JSON.parse(event.data || '{}');
1304
2190
  focusTarget(payload.file || selected, payload.nodes?.[0] || null, payload.label || '');
1305
2191
  } catch {}
1306
2192
  });
2193
+ es.addEventListener('agent.stage', event => {
2194
+ try {
2195
+ const payload = JSON.parse(event.data || '{}');
2196
+ showStageBanner(payload);
2197
+ } catch {}
2198
+ });
2199
+ es.addEventListener('canvas.draft', event => {
2200
+ try {
2201
+ const payload = JSON.parse(event.data || '{}');
2202
+ if (readyCanvas?.frame === frame) {
2203
+ frame.contentWindow.postMessage({ type: 'clado-workspace:canvas-draft', draft: payload }, location.origin);
2204
+ }
2205
+ } catch {}
2206
+ });
2207
+ es.addEventListener('code.activity', event => {
2208
+ try {
2209
+ const payload = JSON.parse(event.data || '{}');
2210
+ handleCodeActivityEvent(payload);
2211
+ } catch {}
2212
+ });
2213
+ es.addEventListener('code.diff', event => {
2214
+ try {
2215
+ const payload = JSON.parse(event.data || '{}');
2216
+ handleCodeDiffEvent(payload);
2217
+ } catch {}
2218
+ });
1307
2219
  es.addEventListener('agent.sessions', event => {
1308
2220
  try {
1309
2221
  const payload = JSON.parse(event.data || '{}');
@@ -1312,7 +2224,18 @@
1312
2224
  }
1313
2225
  } catch {}
1314
2226
  });
1315
- es.onerror = () => { sseReady = false; };
2227
+ es.addEventListener('agent.stream', event => {
2228
+ try {
2229
+ const payload = JSON.parse(event.data || '{}');
2230
+ if (typeof CustomEvent === 'function') {
2231
+ dispatchEvent(new CustomEvent('clado:agent-stream', { detail: payload }));
2232
+ }
2233
+ } catch {}
2234
+ });
2235
+ es.onerror = () => { sseReady = false; pushDebugLog('sse', 'SSE 连接中断,正在重试'); };
2236
+ for (const evtName of ['ready', 'doc.updated', 'agent.activity', 'agent.presence', 'agent.stage', 'agent.sessions', 'canvas.draft', 'code.activity', 'code.diff']) {
2237
+ es.addEventListener(evtName, ev => pushDebugLog('sse', evtName + (ev.data ? ' ' + String(ev.data).slice(0, 140) : '')));
2238
+ }
1316
2239
  addEventListener('pagehide', () => es.close());
1317
2240
  } catch {}
1318
2241
  }
@@ -1325,4 +2248,77 @@
1325
2248
  }
1326
2249
  }, 1200);
1327
2250
  }
2251
+
2252
+ // ============ Mobile Debug Overlay (?debug=1) ============
2253
+ const debugEnabled = new URLSearchParams(location.search).get('debug') === '1';
2254
+ const debugLogs = [];
2255
+ let debugListEl = null;
2256
+ let debugBadgeEl = null;
2257
+ function pushDebugLog(level, msg) {
2258
+ if (!debugEnabled) return;
2259
+ const ts = new Date().toLocaleTimeString('zh-CN', { hour12: false });
2260
+ debugLogs.push({ ts, level, msg: String(msg || '') });
2261
+ if (debugLogs.length > 120) debugLogs.shift();
2262
+ if (debugBadgeEl) debugBadgeEl.textContent = String(debugLogs.length);
2263
+ if (debugListEl && !debugListEl.closest('[hidden]')) renderDebugLogs();
2264
+ }
2265
+ function renderDebugLogs() {
2266
+ if (!debugListEl) return;
2267
+ debugListEl.innerHTML = debugLogs.slice().reverse().map(item =>
2268
+ `<div class="clado-dbg-row is-${escHtml(item.level)}"><span class="clado-dbg-ts">${escHtml(item.ts)}</span><span class="clado-dbg-lv">${escHtml(item.level)}</span><span class="clado-dbg-msg">${escHtml(item.msg)}</span></div>`
2269
+ ).join('') || '<div class="clado-dbg-empty">暂无日志,操作画布或发起请求将实时记录。</div>';
2270
+ }
2271
+ if (debugEnabled && document.body) {
2272
+ const dbgBtn = document.createElement('button');
2273
+ dbgBtn.type = 'button';
2274
+ dbgBtn.id = 'clado-debug-toggle';
2275
+ dbgBtn.className = 'clado-debug-toggle';
2276
+ dbgBtn.innerHTML = '<span>Debug</span><span class="clado-dbg-count">0</span>';
2277
+ debugBadgeEl = dbgBtn.querySelector('.clado-dbg-count');
2278
+
2279
+ const dbgPanel = document.createElement('aside');
2280
+ dbgPanel.id = 'clado-debug-panel';
2281
+ dbgPanel.className = 'clado-debug-panel';
2282
+ dbgPanel.hidden = true;
2283
+ dbgPanel.innerHTML = `
2284
+ <div class="clado-dbg-head">
2285
+ <strong>移动端调试日志</strong>
2286
+ <div style="display:flex;gap:5px;">
2287
+ <button type="button" class="clado-cd-btn" data-dbg-copy>复制日志</button>
2288
+ <button type="button" class="clado-cd-btn" data-dbg-clear>清空</button>
2289
+ <button type="button" class="clado-cd-btn" data-dbg-close>收起</button>
2290
+ </div>
2291
+ </div>
2292
+ <div class="clado-dbg-list" data-dbg-list></div>
2293
+ `;
2294
+ debugListEl = dbgPanel.querySelector('[data-dbg-list]');
2295
+ document.body.append(dbgBtn, dbgPanel);
2296
+
2297
+ dbgBtn.onclick = () => { dbgPanel.hidden = !dbgPanel.hidden; if (!dbgPanel.hidden) renderDebugLogs(); };
2298
+ dbgPanel.querySelector('[data-dbg-close]').onclick = () => { dbgPanel.hidden = true; };
2299
+ dbgPanel.querySelector('[data-dbg-clear]').onclick = () => {
2300
+ debugLogs.length = 0;
2301
+ if (debugBadgeEl) debugBadgeEl.textContent = '0';
2302
+ renderDebugLogs();
2303
+ };
2304
+ dbgPanel.querySelector('[data-dbg-copy]').onclick = () => {
2305
+ const txt = debugLogs.map(x => `[${x.ts}] [${x.level}] ${x.msg}`).join('\n');
2306
+ navigator.clipboard?.writeText(txt).then(() => showToast('已复制调试日志')).catch(() => {});
2307
+ };
2308
+
2309
+ window.addEventListener('error', e => pushDebugLog('error', (e.message || 'Script error') + (e.filename ? ` (${e.filename}:${e.lineno})` : '')));
2310
+ window.addEventListener('unhandledrejection', e => pushDebugLog('error', 'Promise: ' + (e.reason?.message || String(e.reason || 'rejected'))));
2311
+ const origFetch = window.fetch.bind(window);
2312
+ window.fetch = async (...args) => {
2313
+ try {
2314
+ const res = await origFetch(...args);
2315
+ if (res.status >= 400) pushDebugLog('http', `${res.status} ${typeof args[0] === 'string' ? args[0] : (args[0]?.url || '')}`);
2316
+ return res;
2317
+ } catch (err) {
2318
+ pushDebugLog('error', `fetch failed: ${err?.message || err}`);
2319
+ throw err;
2320
+ }
2321
+ };
2322
+ pushDebugLog('info', `Clado Debug 已开启 · ${location.origin} · UA=${navigator.userAgent.slice(0, 60)}`);
2323
+ }
1328
2324
  })();