cladogram 0.6.0-beta.2 → 0.6.0-beta.4
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/bin/clado.js +34 -2
- package/docs/agent-context.md +62 -0
- package/docs/agent-reference.md +126 -0
- package/docs/release.md +15 -0
- package/package.json +3 -1
- package/plugins/agent/index.js +974 -124
- package/plugins/agent/style.css +502 -52
- package/src/agent/clado-tools.js +437 -103
- package/src/agent/pi-bridge.js +588 -43
- package/src/agent/pi-config.js +411 -35
- package/src/html/app-css.js +65 -1
- package/src/html/canvas-chain.js +26 -2
- package/src/html/canvas-focus.js +19 -13
- package/src/html/canvas-live-diff.js +1256 -0
- package/src/html/canvas-ui.css +508 -0
- package/src/html/canvas-wires.js +5 -1
- package/src/html/page.js +4 -2
- package/src/html/runtime-api.js +146 -10
- package/src/html/runtime.js +432 -29
- package/src/server/agent.js +55 -8
- package/src/server/assets/library-canvas.js +252 -9
- package/src/server/assets/library.css +416 -0
- package/src/server/assets/library.html +2 -0
- package/src/server/assets/library.js +744 -14
- package/src/server/code-inspect.js +183 -0
- package/src/server/mcp.js +4 -4
- package/src/server/workspace.js +266 -19
- package/src/workspace/graph-snapshot.js +695 -0
- package/src/workspace/service.js +11 -1
|
@@ -826,15 +826,119 @@
|
|
|
826
826
|
addSep();
|
|
827
827
|
addItem('删除此组件', () => deleteObject(obj.id), true);
|
|
828
828
|
}
|
|
829
|
+
} else if (detail.kind === 'text-selection' && detail.node) {
|
|
830
|
+
addLabel(`选中文本 · ${detail.label || ''}`);
|
|
831
|
+
addItem('连接到其他卡片 / 锚点…', () => {
|
|
832
|
+
try {
|
|
833
|
+
frame.contentWindow.postMessage({
|
|
834
|
+
type: 'clado-workspace:start-link-pick',
|
|
835
|
+
source: {
|
|
836
|
+
kind: 'text-selection',
|
|
837
|
+
node: detail.node,
|
|
838
|
+
selectedText: detail.selectedText,
|
|
839
|
+
label: detail.label || detail.selectedText,
|
|
840
|
+
},
|
|
841
|
+
}, location.origin);
|
|
842
|
+
} catch {}
|
|
843
|
+
});
|
|
844
|
+
addItem('让 AI 修改这段', () => {
|
|
845
|
+
window.dispatchEvent(new CustomEvent('clado:agent-prefill', {
|
|
846
|
+
detail: { mode: 'edit', file: selected, node: detail.node, selectedText: detail.selectedText },
|
|
847
|
+
}));
|
|
848
|
+
});
|
|
849
|
+
addItem('问 AI 这段内容', () => {
|
|
850
|
+
window.dispatchEvent(new CustomEvent('clado:agent-prefill', {
|
|
851
|
+
detail: { mode: 'ask', file: selected, node: detail.node, selectedText: detail.selectedText },
|
|
852
|
+
}));
|
|
853
|
+
});
|
|
854
|
+
if (detail.codeRef) {
|
|
855
|
+
addSep();
|
|
856
|
+
addItem(`查看源码 · ${detail.codeRef}`, () => window.CladoCodeDrawer?.openRef?.(detail.codeRef));
|
|
857
|
+
}
|
|
858
|
+
} else if (detail.kind === 'code-line' && detail.node) {
|
|
859
|
+
addLabel(detail.label || `代码第 ${detail.line || 1} 行`);
|
|
860
|
+
addItem('从此代码行连接到…', () => {
|
|
861
|
+
try {
|
|
862
|
+
frame.contentWindow.postMessage({
|
|
863
|
+
type: 'clado-workspace:start-link-pick',
|
|
864
|
+
source: {
|
|
865
|
+
kind: 'code-line',
|
|
866
|
+
node: detail.node,
|
|
867
|
+
sourcePoint: detail.sourcePoint,
|
|
868
|
+
label: detail.label,
|
|
869
|
+
lineText: detail.lineText,
|
|
870
|
+
},
|
|
871
|
+
}, location.origin);
|
|
872
|
+
} catch {}
|
|
873
|
+
});
|
|
874
|
+
addItem('问 AI 这一行代码', () => {
|
|
875
|
+
window.dispatchEvent(new CustomEvent('clado:agent-prefill', {
|
|
876
|
+
detail: { mode: 'ask', file: selected, node: detail.node, selectedText: detail.lineText || detail.label },
|
|
877
|
+
}));
|
|
878
|
+
});
|
|
879
|
+
if (detail.codeRef) {
|
|
880
|
+
addSep();
|
|
881
|
+
addItem(`查看真实源码 · ${detail.codeRef}`, () => window.CladoCodeDrawer?.openRef?.(detail.codeRef));
|
|
882
|
+
}
|
|
883
|
+
} else if (detail.kind === 'mermaid-node' && detail.node) {
|
|
884
|
+
addLabel(detail.label || 'Mermaid 节点');
|
|
885
|
+
addItem('从此图节点连接到…', () => {
|
|
886
|
+
try {
|
|
887
|
+
frame.contentWindow.postMessage({
|
|
888
|
+
type: 'clado-workspace:start-link-pick',
|
|
889
|
+
source: {
|
|
890
|
+
kind: 'mermaid-node',
|
|
891
|
+
node: detail.node,
|
|
892
|
+
sourcePoint: detail.sourcePoint,
|
|
893
|
+
label: detail.label,
|
|
894
|
+
},
|
|
895
|
+
}, location.origin);
|
|
896
|
+
} catch {}
|
|
897
|
+
});
|
|
898
|
+
addItem('问 AI 这个图节点', () => {
|
|
899
|
+
window.dispatchEvent(new CustomEvent('clado:agent-prefill', {
|
|
900
|
+
detail: { mode: 'ask', file: selected, node: detail.node, selectedText: detail.nodeLabel || detail.nodeId },
|
|
901
|
+
}));
|
|
902
|
+
});
|
|
829
903
|
} else if (detail.kind === 'card' && detail.node) {
|
|
904
|
+
const targetNode = detail.cardNode || detail.node;
|
|
830
905
|
const nodes = [...(aiSelection?.nodes || [])];
|
|
831
|
-
const at = nodes.findIndex(n => JSON.stringify(n) === JSON.stringify(
|
|
906
|
+
const at = nodes.findIndex(n => JSON.stringify(n) === JSON.stringify(targetNode));
|
|
832
907
|
addLabel(`卡片 · ${detail.title || detail.node[detail.node.length - 1]}`);
|
|
908
|
+
addItem('连接到其他卡片 / 锚点…', () => {
|
|
909
|
+
try {
|
|
910
|
+
frame.contentWindow.postMessage({
|
|
911
|
+
type: 'clado-workspace:start-link-pick',
|
|
912
|
+
source: {
|
|
913
|
+
kind: 'card',
|
|
914
|
+
node: detail.node,
|
|
915
|
+
title: detail.title,
|
|
916
|
+
label: detail.title || detail.node.join(' / '),
|
|
917
|
+
},
|
|
918
|
+
}, location.origin);
|
|
919
|
+
} catch {}
|
|
920
|
+
});
|
|
921
|
+
if (detail.codeRef) {
|
|
922
|
+
addItem(`查看真实源码 · ${detail.codeRef}`, () => window.CladoCodeDrawer?.openRef?.(detail.codeRef));
|
|
923
|
+
}
|
|
924
|
+
if (detail.isIsolated) {
|
|
925
|
+
addItem('让 AI 接入主调用链', () => {
|
|
926
|
+
window.dispatchEvent(new CustomEvent('clado:agent-prefill', {
|
|
927
|
+
detail: {
|
|
928
|
+
mode: 'custom',
|
|
929
|
+
file: selected,
|
|
930
|
+
node: targetNode,
|
|
931
|
+
prompt: `卡片「${detail.title}」目前未连入画布主拓扑,请结合真实调用关系将它合理连接到上下游卡片,完成后调用 clado_graph 验证无孤立卡。`,
|
|
932
|
+
},
|
|
933
|
+
}));
|
|
934
|
+
});
|
|
935
|
+
}
|
|
936
|
+
addSep();
|
|
833
937
|
addItem(at >= 0 ? '取消选中此卡片' : '选中此卡片', () => {
|
|
834
938
|
const nextNodes = [...(aiSelection?.nodes || [])];
|
|
835
|
-
const idx = nextNodes.findIndex(n => JSON.stringify(n) === JSON.stringify(
|
|
939
|
+
const idx = nextNodes.findIndex(n => JSON.stringify(n) === JSON.stringify(targetNode));
|
|
836
940
|
if (idx >= 0) nextNodes.splice(idx, 1);
|
|
837
|
-
else nextNodes.push(
|
|
941
|
+
else nextNodes.push(targetNode);
|
|
838
942
|
setSelection(nextNodes.length ? { file: selected, version, nodes: nextNodes } : null);
|
|
839
943
|
});
|
|
840
944
|
addItem('旁边贴一张便签', () => {
|
|
@@ -954,11 +1058,363 @@
|
|
|
954
1058
|
flushPendingTouch();
|
|
955
1059
|
}
|
|
956
1060
|
}
|
|
1061
|
+
function focusTag(tagId) {
|
|
1062
|
+
if (!tagId || readyCanvas?.frame !== frame) return;
|
|
1063
|
+
try { frame.contentWindow.postMessage({ type: 'clado-workspace:focus-tag', tagId: String(tagId) }, offline ? '*' : location.origin); } catch {}
|
|
1064
|
+
}
|
|
1065
|
+
function getCanvasEntities() {
|
|
1066
|
+
try {
|
|
1067
|
+
if (readyCanvas?.frame === frame) {
|
|
1068
|
+
return frame.contentWindow.CladoRuntime?.getCanvasEntities?.() || { cards: [], sections: [], tags: [] };
|
|
1069
|
+
}
|
|
1070
|
+
} catch {}
|
|
1071
|
+
return { cards: [], sections: [], tags: [] };
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
// ============ Multi-Role Handoff Stage Banner ============
|
|
1075
|
+
let stageBannerTimer = null;
|
|
1076
|
+
function showStageBanner(payload) {
|
|
1077
|
+
const el = document.getElementById?.('clado-stage-banner');
|
|
1078
|
+
if (!el || !payload?.roleName) return;
|
|
1079
|
+
const phase = payload.phase ? `<span class="stage-phase">${escHtml(payload.phase)}</span>` : '';
|
|
1080
|
+
const fromTxt = payload.handoffFrom ? ` · 承接自「${escHtml(payload.handoffFrom)}」` : '';
|
|
1081
|
+
el.dataset.tone = payload.tone || 'sky';
|
|
1082
|
+
el.innerHTML = `<span class="stage-dot" aria-hidden="true"></span>${phase}<span>${escHtml(payload.roleName)}已接手${fromTxt}</span>`;
|
|
1083
|
+
el.hidden = false;
|
|
1084
|
+
requestAnimationFrame(() => el.classList.add('show'));
|
|
1085
|
+
clearTimeout(stageBannerTimer);
|
|
1086
|
+
stageBannerTimer = setTimeout(() => {
|
|
1087
|
+
el.classList.remove('show');
|
|
1088
|
+
setTimeout(() => { if (!el.classList.contains('show')) el.hidden = true; }, 240);
|
|
1089
|
+
}, 3400);
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
// ============ Right-Side Live Code & Git Diff Drawer ============
|
|
1093
|
+
const codeDrawerEl = document.getElementById?.('clado-code-drawer') || null;
|
|
1094
|
+
const codeTabs = new Map();
|
|
1095
|
+
let activeCodePath = '';
|
|
1096
|
+
let codeViewMode = 'diff';
|
|
1097
|
+
|
|
1098
|
+
function computeCodeLineDiff(oldStr, newStr) {
|
|
1099
|
+
const a = oldStr == null ? [] : String(oldStr).replace(/\r\n?/g, '\n').split('\n');
|
|
1100
|
+
const b = newStr == null ? [] : String(newStr).replace(/\r\n?/g, '\n').split('\n');
|
|
1101
|
+
let start = 0;
|
|
1102
|
+
while (start < a.length && start < b.length && a[start] === b[start]) start++;
|
|
1103
|
+
let endA = a.length - 1, endB = b.length - 1;
|
|
1104
|
+
while (endA >= start && endB >= start && a[endA] === b[endB]) { endA--; endB--; }
|
|
1105
|
+
const ops = [];
|
|
1106
|
+
for (let i = 0; i < start; i++) ops.push({ type: 'eq', text: a[i], oldLn: i + 1, newLn: i + 1 });
|
|
1107
|
+
const midA = a.slice(start, endA + 1);
|
|
1108
|
+
const midB = b.slice(start, endB + 1);
|
|
1109
|
+
if (midA.length * midB.length > 90000 || !midA.length || !midB.length) {
|
|
1110
|
+
midA.forEach((line, idx) => ops.push({ type: 'del', text: line, oldLn: start + idx + 1, newLn: null }));
|
|
1111
|
+
midB.forEach((line, idx) => ops.push({ type: 'add', text: line, oldLn: null, newLn: start + idx + 1 }));
|
|
1112
|
+
} else {
|
|
1113
|
+
const m = midA.length, n = midB.length;
|
|
1114
|
+
const dp = Array.from({ length: m + 1 }, () => new Int32Array(n + 1));
|
|
1115
|
+
for (let x = m - 1; x >= 0; x--) {
|
|
1116
|
+
for (let y = n - 1; y >= 0; y--) {
|
|
1117
|
+
dp[x][y] = midA[x] === midB[y] ? dp[x + 1][y + 1] + 1 : Math.max(dp[x + 1][y], dp[x][y + 1]);
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
let ix = 0, iy = 0;
|
|
1121
|
+
while (ix < m && iy < n) {
|
|
1122
|
+
if (midA[ix] === midB[iy]) {
|
|
1123
|
+
ops.push({ type: 'eq', text: midA[ix], oldLn: start + ix + 1, newLn: start + iy + 1 });
|
|
1124
|
+
ix++; iy++;
|
|
1125
|
+
} else if (dp[ix + 1][iy] >= dp[ix][iy + 1]) {
|
|
1126
|
+
ops.push({ type: 'del', text: midA[ix], oldLn: start + ix + 1, newLn: null });
|
|
1127
|
+
ix++;
|
|
1128
|
+
} else {
|
|
1129
|
+
ops.push({ type: 'add', text: midB[iy], oldLn: null, newLn: start + iy + 1 });
|
|
1130
|
+
iy++;
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
while (ix < m) { ops.push({ type: 'del', text: midA[ix], oldLn: start + ix + 1, newLn: null }); ix++; }
|
|
1134
|
+
while (iy < n) { ops.push({ type: 'add', text: midB[iy], oldLn: null, newLn: start + iy + 1 }); iy++; }
|
|
1135
|
+
}
|
|
1136
|
+
const tailLen = a.length - (endA + 1);
|
|
1137
|
+
for (let k = 0; k < tailLen; k++) {
|
|
1138
|
+
ops.push({ type: 'eq', text: a[endA + 1 + k], oldLn: endA + 2 + k, newLn: endB + 2 + k });
|
|
1139
|
+
}
|
|
1140
|
+
let added = 0, removed = 0;
|
|
1141
|
+
for (const o of ops) { if (o.type === 'add') added++; else if (o.type === 'del') removed++; }
|
|
1142
|
+
return { ops, added, removed };
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
function diffInlineTokens(oldLine, newLine) {
|
|
1146
|
+
const tok = s => String(s || '').match(/[A-Za-z0-9_]+|[\u4e00-\u9fff]|\s+|[^\sA-Za-z0-9_\u4e00-\u9fff]/g) || [];
|
|
1147
|
+
const a = tok(oldLine), b = tok(newLine);
|
|
1148
|
+
if (!a.length || !b.length || a.length * b.length > 10000) return { delHtml: escHtml(oldLine), addHtml: escHtml(newLine) };
|
|
1149
|
+
const m = a.length, n = b.length;
|
|
1150
|
+
const dp = Array.from({ length: m + 1 }, () => new Int32Array(n + 1));
|
|
1151
|
+
for (let x = m - 1; x >= 0; x--) {
|
|
1152
|
+
for (let y = n - 1; y >= 0; y--) {
|
|
1153
|
+
dp[x][y] = a[x] === b[y] ? dp[x + 1][y + 1] + 1 : Math.max(dp[x + 1][y], dp[x][y + 1]);
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
const delSegs = [], addSegs = [];
|
|
1157
|
+
const pushSeg = (list, kind, t) => {
|
|
1158
|
+
const last = list[list.length - 1];
|
|
1159
|
+
if (last && last.kind === kind) last.text += t; else list.push({ kind, text: t });
|
|
1160
|
+
};
|
|
1161
|
+
let ix = 0, iy = 0;
|
|
1162
|
+
while (ix < m && iy < n) {
|
|
1163
|
+
if (a[ix] === b[iy]) { pushSeg(delSegs, 'eq', a[ix]); pushSeg(addSegs, 'eq', b[iy]); ix++; iy++; }
|
|
1164
|
+
else if (dp[ix + 1][iy] >= dp[ix][iy + 1]) pushSeg(delSegs, 'chg', a[ix++]);
|
|
1165
|
+
else pushSeg(addSegs, 'chg', b[iy++]);
|
|
1166
|
+
}
|
|
1167
|
+
while (ix < m) pushSeg(delSegs, 'chg', a[ix++]);
|
|
1168
|
+
while (iy < n) pushSeg(addSegs, 'chg', b[iy++]);
|
|
1169
|
+
const renderSegs = (segs, cls) => segs.map(s => s.kind === 'chg' ? `<mark class="${cls}">${escHtml(s.text)}</mark>` : escHtml(s.text)).join('');
|
|
1170
|
+
return { delHtml: renderSegs(delSegs, 'clado-cd-mark-del'), addHtml: renderSegs(addSegs, 'clado-cd-mark-add') };
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
function renderCodeDrawer() {
|
|
1174
|
+
if (!codeDrawerEl) return;
|
|
1175
|
+
if (!activeCodePath || !codeTabs.has(activeCodePath)) {
|
|
1176
|
+
codeDrawerEl.hidden = true;
|
|
1177
|
+
return;
|
|
1178
|
+
}
|
|
1179
|
+
const tab = codeTabs.get(activeCodePath);
|
|
1180
|
+
const shortName = tab.path.split('/').pop() || tab.path;
|
|
1181
|
+
const hasDiff = tab.diff && (tab.diff.added > 0 || tab.diff.removed > 0);
|
|
1182
|
+
const effectiveMode = (codeViewMode === 'diff' && hasDiff) ? 'diff' : 'source';
|
|
1183
|
+
const statusLabel = tab.liveStatus || (hasDiff ? `+${tab.diff.added} / -${tab.diff.removed}` : `${(tab.content || '').split('\n').length} 行`);
|
|
1184
|
+
|
|
1185
|
+
const tabsHtml = [...codeTabs.values()].slice(-8).map(item => {
|
|
1186
|
+
const name = item.path.split('/').pop() || item.path;
|
|
1187
|
+
const a = item.diff?.added || 0;
|
|
1188
|
+
const d = item.diff?.removed || 0;
|
|
1189
|
+
return `<button type="button" class="clado-cd-tab${item.path === activeCodePath ? ' active' : ''}" data-cd-tab="${escHtml(item.path)}">`
|
|
1190
|
+
+ `<span>${escHtml(name)}</span>`
|
|
1191
|
+
+ (a ? `<span class="clado-cd-stat-add">+${a}</span>` : '')
|
|
1192
|
+
+ (d ? `<span class="clado-cd-stat-del">-${d}</span>` : '')
|
|
1193
|
+
+ `</button>`;
|
|
1194
|
+
}).join('');
|
|
1195
|
+
|
|
1196
|
+
let bodyHtml = '';
|
|
1197
|
+
if (tab.loading) {
|
|
1198
|
+
bodyHtml = '<div class="clado-cd-sep">正在读取工作区源码与 Git Diff…</div>';
|
|
1199
|
+
} else if (tab.error) {
|
|
1200
|
+
bodyHtml = `<div class="clado-cd-sep">${escHtml(tab.error)}</div>`;
|
|
1201
|
+
} else if (effectiveMode === 'diff' && tab.diff) {
|
|
1202
|
+
const ops = tab.diff.ops;
|
|
1203
|
+
const keep = new Array(ops.length).fill(false);
|
|
1204
|
+
for (let i = 0; i < ops.length; i++) {
|
|
1205
|
+
if (ops[i].type !== 'eq') {
|
|
1206
|
+
for (let j = Math.max(0, i - 3); j <= Math.min(ops.length - 1, i + 3); j++) keep[j] = true;
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
const htmlOverride = new Array(ops.length);
|
|
1210
|
+
let idx = 0;
|
|
1211
|
+
while (idx < ops.length) {
|
|
1212
|
+
if (ops[idx].type === 'del') {
|
|
1213
|
+
const ds = idx; while (idx < ops.length && ops[idx].type === 'del') idx++;
|
|
1214
|
+
const as = idx; while (idx < ops.length && ops[idx].type === 'add') idx++;
|
|
1215
|
+
const pairs = Math.min(as - ds, idx - as);
|
|
1216
|
+
for (let p = 0; p < pairs; p++) {
|
|
1217
|
+
const pair = diffInlineTokens(ops[ds + p].text, ops[as + p].text);
|
|
1218
|
+
htmlOverride[ds + p] = pair.delHtml;
|
|
1219
|
+
htmlOverride[as + p] = pair.addHtml;
|
|
1220
|
+
}
|
|
1221
|
+
} else idx++;
|
|
1222
|
+
}
|
|
1223
|
+
const rows = [];
|
|
1224
|
+
let skipping = false;
|
|
1225
|
+
for (let i = 0; i < ops.length; i++) {
|
|
1226
|
+
if (!keep[i]) {
|
|
1227
|
+
if (!skipping && rows.length) { rows.push('<div class="clado-cd-sep">···</div>'); skipping = true; }
|
|
1228
|
+
continue;
|
|
1229
|
+
}
|
|
1230
|
+
skipping = false;
|
|
1231
|
+
const o = ops[i];
|
|
1232
|
+
const cls = o.type === 'add' ? ' is-add' : o.type === 'del' ? ' is-del' : '';
|
|
1233
|
+
const sign = o.type === 'add' ? '+' : o.type === 'del' ? '−' : ' ';
|
|
1234
|
+
const ln = o.newLn ?? o.oldLn ?? '';
|
|
1235
|
+
const codeHtml = htmlOverride[i] != null ? htmlOverride[i] : escHtml(o.text);
|
|
1236
|
+
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 || ' '}</span></div>`);
|
|
1237
|
+
}
|
|
1238
|
+
bodyHtml = rows.join('') || '<div class="clado-cd-sep">与 Git HEAD 一致,无未提交改动</div>';
|
|
1239
|
+
} else {
|
|
1240
|
+
const lines = String(tab.content || '').replace(/\r\n?/g, '\n').split('\n');
|
|
1241
|
+
bodyHtml = lines.slice(0, 1200).map((line, i) => {
|
|
1242
|
+
const ln = i + 1;
|
|
1243
|
+
const isMatch = tab.matchedLine && ln === tab.matchedLine;
|
|
1244
|
+
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) || ' '}</span></div>`;
|
|
1245
|
+
}).join('');
|
|
1246
|
+
if (lines.length > 1200) bodyHtml += `<div class="clado-cd-sep">… 仅展示前 1200 行(共 ${lines.length} 行)</div>`;
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
const cardsHtml = (tab.matchedCards || []).slice(0, 3).map(pathArr => {
|
|
1250
|
+
const title = Array.isArray(pathArr) ? pathArr[pathArr.length - 1] : String(pathArr);
|
|
1251
|
+
return `<button type="button" class="clado-cd-card-chip" data-cd-card="${escHtml(title)}">${escHtml(title)}</button>`;
|
|
1252
|
+
}).join('');
|
|
1253
|
+
|
|
1254
|
+
codeDrawerEl.innerHTML = `
|
|
1255
|
+
<div class="clado-cd-head">
|
|
1256
|
+
<div class="clado-cd-title-wrap">
|
|
1257
|
+
<span class="clado-cd-dot${tab.liveStatus ? ' live' : ''}" aria-hidden="true"></span>
|
|
1258
|
+
<span class="clado-cd-title">${escHtml(shortName)}</span>
|
|
1259
|
+
<span class="clado-cd-sub">${escHtml(statusLabel)}</span>
|
|
1260
|
+
</div>
|
|
1261
|
+
<div class="clado-cd-actions">
|
|
1262
|
+
${hasDiff ? `<button type="button" class="clado-cd-btn${effectiveMode === 'diff' ? ' active' : ''}" data-cd-mode="diff">实时 Diff</button>` : ''}
|
|
1263
|
+
<button type="button" class="clado-cd-btn${effectiveMode === 'source' ? ' active' : ''}" data-cd-mode="source">完整源码</button>
|
|
1264
|
+
<button type="button" class="clado-cd-btn" data-cd-close title="关闭代码视图">关闭</button>
|
|
1265
|
+
</div>
|
|
1266
|
+
</div>
|
|
1267
|
+
${codeTabs.size > 1 ? `<div class="clado-cd-tabs">${tabsHtml}</div>` : ''}
|
|
1268
|
+
<div class="clado-cd-pathbar">
|
|
1269
|
+
<span class="clado-cd-path" title="${escHtml(tab.path)}">${escHtml(tab.path)}</span>
|
|
1270
|
+
<button type="button" class="clado-cd-btn" data-cd-copy>复制路径</button>
|
|
1271
|
+
</div>
|
|
1272
|
+
<div class="clado-cd-body">${bodyHtml}</div>
|
|
1273
|
+
<div class="clado-cd-foot">
|
|
1274
|
+
<div class="clado-cd-cards">${cardsHtml ? `<span>关联卡片:</span>${cardsHtml}` : '<span>实时源码与 Git Diff</span>'}</div>
|
|
1275
|
+
<button type="button" class="clado-cd-btn" data-cd-sync>核对画布同步</button>
|
|
1276
|
+
</div>
|
|
1277
|
+
`;
|
|
1278
|
+
codeDrawerEl.hidden = false;
|
|
1279
|
+
|
|
1280
|
+
codeDrawerEl.querySelector('[data-cd-close]').onclick = () => { codeDrawerEl.hidden = true; };
|
|
1281
|
+
codeDrawerEl.querySelector('[data-cd-copy]').onclick = () => {
|
|
1282
|
+
navigator.clipboard?.writeText(tab.path).then(() => showToast('已复制路径:' + tab.path)).catch(() => {});
|
|
1283
|
+
};
|
|
1284
|
+
codeDrawerEl.querySelector('[data-cd-sync]').onclick = () => {
|
|
1285
|
+
window.dispatchEvent(new CustomEvent('clado:agent-prefill', {
|
|
1286
|
+
detail: {
|
|
1287
|
+
mode: 'custom',
|
|
1288
|
+
file: selected,
|
|
1289
|
+
prompt: `请核对源码 \`${tab.path}\` 的最新改动与当前画布 \`${selected || ''}\` 是否一致,如有出入请直接同步更新对应卡片并调用 clado_graph 复查。`,
|
|
1290
|
+
},
|
|
1291
|
+
}));
|
|
1292
|
+
};
|
|
1293
|
+
codeDrawerEl.querySelectorAll('[data-cd-mode]').forEach(btn => {
|
|
1294
|
+
btn.onclick = () => { codeViewMode = btn.dataset.cdMode; renderCodeDrawer(); };
|
|
1295
|
+
});
|
|
1296
|
+
codeDrawerEl.querySelectorAll('[data-cd-tab]').forEach(btn => {
|
|
1297
|
+
btn.onclick = () => { activeCodePath = btn.dataset.cdTab; renderCodeDrawer(); };
|
|
1298
|
+
});
|
|
1299
|
+
codeDrawerEl.querySelectorAll('[data-cd-card]').forEach(btn => {
|
|
1300
|
+
btn.onclick = () => focusTarget(selected, [btn.dataset.cdCard], btn.dataset.cdCard);
|
|
1301
|
+
});
|
|
1302
|
+
if (effectiveMode === 'source' && tab.matchedLine) {
|
|
1303
|
+
const targetRow = codeDrawerEl.querySelector(`[data-cd-ln="${tab.matchedLine}"]`);
|
|
1304
|
+
if (targetRow) targetRow.scrollIntoView({ block: 'center' });
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
async function openCodeDrawerFile(pathOrRef, opts = {}) {
|
|
1309
|
+
if (!codeDrawerEl || offline || !pathOrRef) return;
|
|
1310
|
+
const raw = String(pathOrRef).trim();
|
|
1311
|
+
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));
|
|
1312
|
+
const key = raw;
|
|
1313
|
+
if (!codeTabs.has(key)) {
|
|
1314
|
+
codeTabs.set(key, { path: key, content: '', diff: null, loading: true, matchedCards: opts.matchedCards || [] });
|
|
1315
|
+
}
|
|
1316
|
+
activeCodePath = key;
|
|
1317
|
+
renderCodeDrawer();
|
|
1318
|
+
try {
|
|
1319
|
+
const qs = isSymbol ? ('symbol=' + encodeURIComponent(raw)) : ('path=' + encodeURIComponent(raw));
|
|
1320
|
+
const res = await fetch(withWorkspace('/library/code-file?' + qs), { cache: 'no-store' });
|
|
1321
|
+
const data = await res.json();
|
|
1322
|
+
if (!res.ok) throw new Error(data.error || '无法读取源码');
|
|
1323
|
+
const finalPath = data.path || raw;
|
|
1324
|
+
if (finalPath !== key) codeTabs.delete(key);
|
|
1325
|
+
const prevTab = codeTabs.get(finalPath);
|
|
1326
|
+
const diff = (data.changed && data.headContent != null)
|
|
1327
|
+
? computeCodeLineDiff(data.headContent, data.content)
|
|
1328
|
+
: (prevTab?.diff || null);
|
|
1329
|
+
codeTabs.set(finalPath, {
|
|
1330
|
+
path: finalPath,
|
|
1331
|
+
content: data.content || '',
|
|
1332
|
+
matchedLine: data.matchedLine || null,
|
|
1333
|
+
diff,
|
|
1334
|
+
loading: false,
|
|
1335
|
+
error: '',
|
|
1336
|
+
liveStatus: '',
|
|
1337
|
+
matchedCards: opts.matchedCards || prevTab?.matchedCards || [],
|
|
1338
|
+
});
|
|
1339
|
+
activeCodePath = finalPath;
|
|
1340
|
+
if (diff && (diff.added || diff.removed)) codeViewMode = 'diff';
|
|
1341
|
+
else codeViewMode = 'source';
|
|
1342
|
+
renderCodeDrawer();
|
|
1343
|
+
} catch (err) {
|
|
1344
|
+
const cur = codeTabs.get(key);
|
|
1345
|
+
if (cur) {
|
|
1346
|
+
cur.loading = false;
|
|
1347
|
+
cur.error = err.message || '读取源码失败';
|
|
1348
|
+
renderCodeDrawer();
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
function handleCodeActivityEvent(payload) {
|
|
1354
|
+
if (!payload?.path) return;
|
|
1355
|
+
if (Array.isArray(payload.matchedCards) && payload.matchedCards.length && readyCanvas?.frame === frame) {
|
|
1356
|
+
try {
|
|
1357
|
+
frame.contentWindow.postMessage({
|
|
1358
|
+
type: 'clado-workspace:ai-touch',
|
|
1359
|
+
kind: 'implementing',
|
|
1360
|
+
nodes: payload.matchedCards,
|
|
1361
|
+
label: `${payload.roleName || '开发'} · ${payload.phase === 'reading' ? '查看' : '正在改写'} ${payload.path}`,
|
|
1362
|
+
follow: false,
|
|
1363
|
+
}, location.origin);
|
|
1364
|
+
} catch {}
|
|
1365
|
+
}
|
|
1366
|
+
if (payload.phase === 'editing') {
|
|
1367
|
+
const existing = codeTabs.get(payload.path) || { path: payload.path, content: '', diff: null };
|
|
1368
|
+
existing.liveStatus = `${payload.roleName || 'AI'} 正在实时编辑…`;
|
|
1369
|
+
existing.matchedCards = payload.matchedCards || existing.matchedCards || [];
|
|
1370
|
+
codeTabs.set(payload.path, existing);
|
|
1371
|
+
activeCodePath = payload.path;
|
|
1372
|
+
renderCodeDrawer();
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
function handleCodeDiffEvent(payload) {
|
|
1377
|
+
if (!payload?.path || payload.after == null) return;
|
|
1378
|
+
const diff = computeCodeLineDiff(payload.before, payload.after);
|
|
1379
|
+
codeTabs.set(payload.path, {
|
|
1380
|
+
path: payload.path,
|
|
1381
|
+
content: payload.after,
|
|
1382
|
+
diff,
|
|
1383
|
+
loading: false,
|
|
1384
|
+
error: '',
|
|
1385
|
+
liveStatus: `${payload.roleName || 'AI'} 已更新 · +${diff.added} -${diff.removed}`,
|
|
1386
|
+
matchedCards: payload.matchedCards || [],
|
|
1387
|
+
});
|
|
1388
|
+
activeCodePath = payload.path;
|
|
1389
|
+
codeViewMode = 'diff';
|
|
1390
|
+
renderCodeDrawer();
|
|
1391
|
+
if (Array.isArray(payload.matchedCards) && payload.matchedCards.length && readyCanvas?.frame === frame) {
|
|
1392
|
+
try {
|
|
1393
|
+
frame.contentWindow.postMessage({
|
|
1394
|
+
type: 'clado-workspace:ai-touch',
|
|
1395
|
+
kind: 'implementing',
|
|
1396
|
+
nodes: payload.matchedCards,
|
|
1397
|
+
label: `已落地代码 ${payload.path} (+${diff.added} / -${diff.removed})`,
|
|
1398
|
+
follow: false,
|
|
1399
|
+
}, location.origin);
|
|
1400
|
+
} catch {}
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
window.CladoCodeDrawer = {
|
|
1405
|
+
openFile: (p, opts) => openCodeDrawerFile(p, opts),
|
|
1406
|
+
openRef: ref => openCodeDrawerFile(ref),
|
|
1407
|
+
close: () => { if (codeDrawerEl) codeDrawerEl.hidden = true; },
|
|
1408
|
+
};
|
|
1409
|
+
|
|
957
1410
|
if (isEnabled('clado.agent')) window.CladoAgentPlugin(host, {
|
|
958
1411
|
withWorkspace,
|
|
959
1412
|
setTheme: applyTheme,
|
|
960
1413
|
capture: captureShot,
|
|
961
1414
|
focusCanvas: (file, heading) => focusTarget(file, heading ? [heading] : null, heading || ''),
|
|
1415
|
+
focusTag,
|
|
1416
|
+
getCanvasEntities,
|
|
1417
|
+
openCodeFile: p => openCodeDrawerFile(p),
|
|
962
1418
|
readContext() {
|
|
963
1419
|
const objSel = objectSelection.size ? [...objectSelection.values()] : undefined;
|
|
964
1420
|
if (readyCanvas?.frame !== frame) return { file: selected || '', selection: [], ...(objSel ? { objectSelection: objSel } : {}) };
|
|
@@ -1099,15 +1555,85 @@
|
|
|
1099
1555
|
if (readyCanvas?.frame !== frame || readyCanvas?.file !== file) throw failure('NAVIGATION_FAILED', '目标画布已被另一次导航替换。');
|
|
1100
1556
|
return { file, title: targetDocument.title, mode };
|
|
1101
1557
|
}
|
|
1558
|
+
function capturePrevDocSnapshot(doc, filePath) {
|
|
1559
|
+
if (!doc || !Array.isArray(doc.cards)) return null;
|
|
1560
|
+
const snapNodes = list => (list || []).map(n => ({ title: n.title || '', md: n.md || '', kids: snapNodes(n.kids) }));
|
|
1561
|
+
return {
|
|
1562
|
+
file: filePath,
|
|
1563
|
+
title: doc.title || '',
|
|
1564
|
+
cards: doc.cards.map(c => ({ title: c.title || '', md: c.md || '', nodes: snapNodes(c.nodes) })),
|
|
1565
|
+
};
|
|
1566
|
+
}
|
|
1102
1567
|
async function open(file, anchor = '', options = {}) {
|
|
1103
1568
|
if(modalLocked()) { if(options.update)deferredRefresh=true;return; }
|
|
1104
1569
|
pendingAnchor=anchor;
|
|
1105
1570
|
const doc = index.documents.find(d => d.file === file);
|
|
1106
1571
|
if (!doc) { directory.showMessage('这个 Markdown 暂未收录', file + ' 不在有效画布目录中。可以让 AI 检查文件路径和解析状态。'); return; }
|
|
1107
1572
|
if (selected && file !== selected && !options.back) history.push(selected);
|
|
1108
|
-
|
|
1109
|
-
|
|
1573
|
+
const canHotPatch = Boolean(
|
|
1574
|
+
options.update
|
|
1575
|
+
&& !offline
|
|
1576
|
+
&& !anchor
|
|
1577
|
+
&& readyCanvas?.frame === frame
|
|
1578
|
+
&& readyCanvas.file === file
|
|
1579
|
+
&& typeof frame.contentWindow?.CladoRuntime?.hotPatchDoc === 'function'
|
|
1580
|
+
);
|
|
1581
|
+
if (options.update && readyCanvas?.frame === frame && readyCanvas.file === file) {
|
|
1582
|
+
try { pendingView = frame.contentWindow.CladoPrototype?.captureView?.(); } catch {}
|
|
1583
|
+
try {
|
|
1584
|
+
const snap = capturePrevDocSnapshot(frame.contentWindow.__CLADO__, file);
|
|
1585
|
+
if (snap) pendingPrevDoc = { ...snap, ts: Date.now() };
|
|
1586
|
+
} catch {}
|
|
1587
|
+
} else {
|
|
1588
|
+
pendingView = null;
|
|
1589
|
+
if (pendingPrevDoc && pendingPrevDoc.file !== file) pendingPrevDoc = null;
|
|
1590
|
+
}
|
|
1110
1591
|
const request = ++renderRequest, previousVersion = version, requestedMode = mode;
|
|
1592
|
+
|
|
1593
|
+
// 优先零闪烁原地热更新:拉取轻量化 doc.json 并在当前 iframe 内原位 patch DOM、执行实时红删绿增 Diff 与新增连线光束动画
|
|
1594
|
+
if (canHotPatch) {
|
|
1595
|
+
try {
|
|
1596
|
+
const patchRes = await fetch(withWorkspace('/library/doc.json?file=' + encodeURIComponent(file)), { cache: 'no-store' });
|
|
1597
|
+
if (patchRes.ok && request === renderRequest && !modalLocked() && mode === requestedMode) {
|
|
1598
|
+
const patchData = await patchRes.json();
|
|
1599
|
+
const hasFreshTouch = pendingTouch && (Date.now() - pendingTouch.ts <= 6000) && (!pendingTouch.file || pendingTouch.file === file);
|
|
1600
|
+
const touchPayload = hasFreshTouch ? pendingTouch : null;
|
|
1601
|
+
const follow = typeof touchPayload?.follow === 'boolean' ? touchPayload.follow : followAi;
|
|
1602
|
+
const patched = frame.contentWindow.CladoRuntime.hotPatchDoc(
|
|
1603
|
+
patchData.doc,
|
|
1604
|
+
patchData.diagnostics,
|
|
1605
|
+
patchData.version || doc.version,
|
|
1606
|
+
touchPayload,
|
|
1607
|
+
follow,
|
|
1608
|
+
);
|
|
1609
|
+
if (patched) {
|
|
1610
|
+
selected = file;
|
|
1611
|
+
version = patchData.version || doc.version;
|
|
1612
|
+
readyCanvas = { frame, file, revision: version };
|
|
1613
|
+
pendingView = null;
|
|
1614
|
+
pendingPrevDoc = null;
|
|
1615
|
+
if (hasFreshTouch) pendingTouch = null;
|
|
1616
|
+
if (selectionTab && aiSelection && aiSelection.version !== version) {
|
|
1617
|
+
const api = frame.contentWindow.CladoRuntime;
|
|
1618
|
+
const nodes = aiSelection.nodes.filter(node => api?.hasSelectionPath(node));
|
|
1619
|
+
setSelection(nodes.length ? { file: selected, version, nodes } : null, nodes.length > 0);
|
|
1620
|
+
}
|
|
1621
|
+
showSelection();
|
|
1622
|
+
syncFrameObjects();
|
|
1623
|
+
saveView();
|
|
1624
|
+
renderDirectory();
|
|
1625
|
+
syncChrome();
|
|
1626
|
+
$('#updateError').hidden = true;
|
|
1627
|
+
$('#emptyState').hidden = true;
|
|
1628
|
+
$('#canvasLoading').hidden = true;
|
|
1629
|
+
status('已同步 ' + new Date(doc.modified || Date.now()).toLocaleTimeString('zh-CN', { hour12: false }));
|
|
1630
|
+
return true;
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
} catch {}
|
|
1634
|
+
if (request !== renderRequest) return;
|
|
1635
|
+
}
|
|
1636
|
+
|
|
1111
1637
|
selected = file; version = doc.version; saveView(); renderDirectory(); syncChrome();
|
|
1112
1638
|
$('#updateError').hidden = true; $('#emptyState').hidden = true; $('#canvasLoading').hidden = false;
|
|
1113
1639
|
// Give each render its own browsing context. A late ready/message from the
|
|
@@ -1138,14 +1664,23 @@
|
|
|
1138
1664
|
$('#updateError').textContent = '画布读取失败,保留上次画面并自动重试。'; $('#updateError').hidden = false; status('当前画布未更新', true);
|
|
1139
1665
|
}
|
|
1140
1666
|
}
|
|
1141
|
-
let pendingRescan = false, pendingTouch = null;
|
|
1667
|
+
let pendingRescan = false, pendingTouch = null, pendingPrevDoc = null;
|
|
1142
1668
|
function flushPendingTouch() {
|
|
1143
|
-
if (!pendingTouch || Date.now() - pendingTouch.ts > 6000) { pendingTouch = null; return; }
|
|
1144
|
-
if (pendingTouch.file && pendingTouch.file !== selected) return;
|
|
1145
1669
|
if (readyCanvas?.frame !== frame || readyCanvas.file !== selected) return;
|
|
1146
|
-
const
|
|
1147
|
-
|
|
1148
|
-
|
|
1670
|
+
const prevDoc = pendingPrevDoc && pendingPrevDoc.file === selected && (Date.now() - pendingPrevDoc.ts <= 8000)
|
|
1671
|
+
? pendingPrevDoc : null;
|
|
1672
|
+
if (pendingPrevDoc && (!prevDoc || prevDoc.file === selected)) pendingPrevDoc = null;
|
|
1673
|
+
|
|
1674
|
+
const hasFreshTouch = pendingTouch && (Date.now() - pendingTouch.ts <= 6000) && (!pendingTouch.file || pendingTouch.file === selected);
|
|
1675
|
+
const payload = hasFreshTouch ? pendingTouch : null;
|
|
1676
|
+
if (pendingTouch && (hasFreshTouch || Date.now() - pendingTouch.ts > 6000)) pendingTouch = null;
|
|
1677
|
+
|
|
1678
|
+
const follow = typeof payload?.follow === 'boolean' ? payload.follow : followAi;
|
|
1679
|
+
if (prevDoc) {
|
|
1680
|
+
try { frame.contentWindow.postMessage({ type: 'clado-workspace:live-diff', prevDoc, touch: payload, follow }, offline ? '*' : location.origin); } catch {}
|
|
1681
|
+
return;
|
|
1682
|
+
}
|
|
1683
|
+
if (!payload) return;
|
|
1149
1684
|
try { frame.contentWindow.postMessage({ type: 'clado-workspace:ai-touch', ...payload, follow }, offline ? '*' : location.origin); } catch {}
|
|
1150
1685
|
}
|
|
1151
1686
|
const status = (message, error) => directory.status(message, error);
|
|
@@ -1184,7 +1719,7 @@
|
|
|
1184
1719
|
const doc = index.documents.find(d => d.file === selected);
|
|
1185
1720
|
if (!doc && !version && index.documents.length) open(index.documents[0].file);
|
|
1186
1721
|
else if (!doc) { $('#updateError').textContent = '当前 Markdown 已删除或暂时无法解析,保留上次画面。有效文档仍可从目录打开。'; $('#updateError').hidden = false; status('当前画布未更新', true); $('#canvasLoading').hidden = true; post('ready'); }
|
|
1187
|
-
else { $('#updateError').hidden = true; if (
|
|
1722
|
+
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
1723
|
}
|
|
1189
1724
|
} catch { if (pageHidden) return; status('连接中断,正在重连', true); $('#updateError').textContent = '目录连接中断,保留当前画面。服务恢复后自动重连。'; $('#updateError').hidden = false; $('#canvasLoading').hidden = true; post('ready'); }
|
|
1190
1725
|
finally {
|
|
@@ -1222,6 +1757,61 @@
|
|
|
1222
1757
|
openCanvasCtxMenu((rect.left || 0) + (data.x || 0), (rect.top || 0) + (data.y || 0), data.detail);
|
|
1223
1758
|
return;
|
|
1224
1759
|
}
|
|
1760
|
+
if (!offline && data?.type === 'clado-library:complete-link' && data.source && data.target) {
|
|
1761
|
+
(async () => {
|
|
1762
|
+
try {
|
|
1763
|
+
const src = data.source;
|
|
1764
|
+
const tgt = data.target;
|
|
1765
|
+
const payload = {
|
|
1766
|
+
file: selected,
|
|
1767
|
+
sourceNode: src.node,
|
|
1768
|
+
anchor: src.selectedText || '',
|
|
1769
|
+
label: src.selectedText || tgt.label || (Array.isArray(tgt.targetNode) ? tgt.targetNode[tgt.targetNode.length - 1] : ''),
|
|
1770
|
+
sourcePoint: src.sourcePoint || null,
|
|
1771
|
+
targetNode: tgt.targetNode || null,
|
|
1772
|
+
targetTagId: tgt.targetTagId || '',
|
|
1773
|
+
targetPoint: tgt.targetPoint || null,
|
|
1774
|
+
};
|
|
1775
|
+
const res = await fetch(withWorkspace('/library/link'), {
|
|
1776
|
+
method: 'POST',
|
|
1777
|
+
headers: { 'content-type': 'application/json' },
|
|
1778
|
+
body: JSON.stringify(payload),
|
|
1779
|
+
});
|
|
1780
|
+
const result = await res.json();
|
|
1781
|
+
if (!res.ok) throw new Error(result.error || '创建连线失败');
|
|
1782
|
+
showToast('已连接到 ' + (tgt.label || tgt.targetTagId || '目标'));
|
|
1783
|
+
pendingTouch = { file: selected, nodes: [src.node, ...(tgt.targetNode ? [tgt.targetNode] : [])], kind: 'write', label: '已建立新连线', follow: false, ts: Date.now() };
|
|
1784
|
+
await scan(true);
|
|
1785
|
+
} catch (err) {
|
|
1786
|
+
showToast(err.message || '创建连线失败');
|
|
1787
|
+
}
|
|
1788
|
+
})();
|
|
1789
|
+
return;
|
|
1790
|
+
}
|
|
1791
|
+
if (data?.type === 'clado-library:selection-action' && data.selectedText) {
|
|
1792
|
+
window.dispatchEvent(new CustomEvent('clado:agent-prefill', {
|
|
1793
|
+
detail: {
|
|
1794
|
+
mode: data.mode || 'ask',
|
|
1795
|
+
file: selected,
|
|
1796
|
+
node: data.node || null,
|
|
1797
|
+
selectedText: data.selectedText,
|
|
1798
|
+
},
|
|
1799
|
+
}));
|
|
1800
|
+
return;
|
|
1801
|
+
}
|
|
1802
|
+
if (data?.type === 'clado-library:open-code-ref' && data.ref) {
|
|
1803
|
+
openCodeDrawerFile(data.ref);
|
|
1804
|
+
return;
|
|
1805
|
+
}
|
|
1806
|
+
if (data?.type === 'clado-library:presence-click') {
|
|
1807
|
+
if (data.sessionId || data.roleId) {
|
|
1808
|
+
window.dispatchEvent(new CustomEvent('clado:focus-session', {
|
|
1809
|
+
detail: { sessionId: data.sessionId || '', roleId: data.roleId || '' },
|
|
1810
|
+
}));
|
|
1811
|
+
}
|
|
1812
|
+
if (data.codePath) openCodeDrawerFile(data.codePath);
|
|
1813
|
+
return;
|
|
1814
|
+
}
|
|
1225
1815
|
if (data?.type === 'clado-library:chain-modal') { chainLock(data.value, data.mode); return; }
|
|
1226
1816
|
if (data?.type === 'clado-library:lens-modal') {
|
|
1227
1817
|
lensOpen = !!data.value;
|
|
@@ -1254,6 +1844,7 @@
|
|
|
1254
1844
|
}
|
|
1255
1845
|
showSelection();
|
|
1256
1846
|
syncFrameObjects();
|
|
1847
|
+
syncPresenceConfigToCanvas();
|
|
1257
1848
|
if(offline){frame.contentWindow.postMessage({type:'clado-workspace:display',mode,theme:design.theme,anchor:pendingAnchor},'*');pendingAnchor='';}
|
|
1258
1849
|
else if (mode !== data.mode) frame.contentWindow.CladoPrototype?.setMode?.(mode);
|
|
1259
1850
|
saveView(); $('#canvasLoading').hidden = true; syncChrome();
|
|
@@ -1270,6 +1861,29 @@
|
|
|
1270
1861
|
status('已同步 ' + new Date(index.documents.find(d => d.file === selected)?.modified || Date.now()).toLocaleTimeString('zh-CN', { hour12: false })); post('ready');
|
|
1271
1862
|
}
|
|
1272
1863
|
});
|
|
1864
|
+
function readPresenceAfterglowMs() {
|
|
1865
|
+
try {
|
|
1866
|
+
const raw = localStorage.getItem('clado-presence-ttl');
|
|
1867
|
+
if (raw !== null && raw !== '') {
|
|
1868
|
+
const sec = Number(raw);
|
|
1869
|
+
if (Number.isFinite(sec) && sec >= 0) return Math.round(sec * 1000);
|
|
1870
|
+
}
|
|
1871
|
+
} catch {}
|
|
1872
|
+
return 15000;
|
|
1873
|
+
}
|
|
1874
|
+
function syncPresenceConfigToCanvas(overrideMs) {
|
|
1875
|
+
if (readyCanvas?.frame !== frame) return;
|
|
1876
|
+
const afterglowMs = typeof overrideMs === 'number' && Number.isFinite(overrideMs) ? overrideMs : readPresenceAfterglowMs();
|
|
1877
|
+
try {
|
|
1878
|
+
frame.contentWindow.postMessage({
|
|
1879
|
+
type: 'clado-workspace:presence-config',
|
|
1880
|
+
config: { afterglowMs },
|
|
1881
|
+
}, offline ? '*' : location.origin);
|
|
1882
|
+
} catch {}
|
|
1883
|
+
}
|
|
1884
|
+
addEventListener('clado:presence-config', ev => {
|
|
1885
|
+
syncPresenceConfigToCanvas(ev.detail?.afterglowMs);
|
|
1886
|
+
});
|
|
1273
1887
|
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
1888
|
window.CladoPrototype = { setDesign, fit: () => frame.contentWindow.CladoPrototype?.fit(), closeLens: () => frame.contentWindow.CladoPrototype?.closeLens() };
|
|
1275
1889
|
setDesign(design);
|
|
@@ -1283,7 +1897,13 @@
|
|
|
1283
1897
|
es.addEventListener('doc.updated', event => {
|
|
1284
1898
|
try {
|
|
1285
1899
|
const payload = JSON.parse(event.data || '{}');
|
|
1286
|
-
if (
|
|
1900
|
+
if (payload.action === 'create' && payload.file && (followAi || !selected)) {
|
|
1901
|
+
pendingOpen = payload.file;
|
|
1902
|
+
pendingPrevDoc = { file: payload.file, title: '', cards: [], ts: Date.now() };
|
|
1903
|
+
pendingTouch = { ...payload, ts: Date.now() };
|
|
1904
|
+
} else if (!payload.file || payload.file === selected) {
|
|
1905
|
+
pendingTouch = { ...payload, ts: Date.now() };
|
|
1906
|
+
}
|
|
1287
1907
|
} catch {}
|
|
1288
1908
|
scan(true);
|
|
1289
1909
|
});
|
|
@@ -1298,12 +1918,46 @@
|
|
|
1298
1918
|
}
|
|
1299
1919
|
} catch {}
|
|
1300
1920
|
});
|
|
1921
|
+
es.addEventListener('agent.presence', event => {
|
|
1922
|
+
try {
|
|
1923
|
+
const payload = JSON.parse(event.data || '{}');
|
|
1924
|
+
if (readyCanvas?.frame === frame && (!payload.file || payload.file === selected || payload.phase === 'afterglow' || payload.phase === 'clear')) {
|
|
1925
|
+
frame.contentWindow.postMessage({ type: 'clado-workspace:presence', presence: payload }, location.origin);
|
|
1926
|
+
}
|
|
1927
|
+
} catch {}
|
|
1928
|
+
});
|
|
1301
1929
|
es.addEventListener('agent.focus', event => {
|
|
1302
1930
|
try {
|
|
1303
1931
|
const payload = JSON.parse(event.data || '{}');
|
|
1304
1932
|
focusTarget(payload.file || selected, payload.nodes?.[0] || null, payload.label || '');
|
|
1305
1933
|
} catch {}
|
|
1306
1934
|
});
|
|
1935
|
+
es.addEventListener('agent.stage', event => {
|
|
1936
|
+
try {
|
|
1937
|
+
const payload = JSON.parse(event.data || '{}');
|
|
1938
|
+
showStageBanner(payload);
|
|
1939
|
+
} catch {}
|
|
1940
|
+
});
|
|
1941
|
+
es.addEventListener('canvas.draft', event => {
|
|
1942
|
+
try {
|
|
1943
|
+
const payload = JSON.parse(event.data || '{}');
|
|
1944
|
+
if (readyCanvas?.frame === frame) {
|
|
1945
|
+
frame.contentWindow.postMessage({ type: 'clado-workspace:canvas-draft', draft: payload }, location.origin);
|
|
1946
|
+
}
|
|
1947
|
+
} catch {}
|
|
1948
|
+
});
|
|
1949
|
+
es.addEventListener('code.activity', event => {
|
|
1950
|
+
try {
|
|
1951
|
+
const payload = JSON.parse(event.data || '{}');
|
|
1952
|
+
handleCodeActivityEvent(payload);
|
|
1953
|
+
} catch {}
|
|
1954
|
+
});
|
|
1955
|
+
es.addEventListener('code.diff', event => {
|
|
1956
|
+
try {
|
|
1957
|
+
const payload = JSON.parse(event.data || '{}');
|
|
1958
|
+
handleCodeDiffEvent(payload);
|
|
1959
|
+
} catch {}
|
|
1960
|
+
});
|
|
1307
1961
|
es.addEventListener('agent.sessions', event => {
|
|
1308
1962
|
try {
|
|
1309
1963
|
const payload = JSON.parse(event.data || '{}');
|
|
@@ -1312,7 +1966,10 @@
|
|
|
1312
1966
|
}
|
|
1313
1967
|
} catch {}
|
|
1314
1968
|
});
|
|
1315
|
-
es.onerror = () => { sseReady = false; };
|
|
1969
|
+
es.onerror = () => { sseReady = false; pushDebugLog('sse', 'SSE 连接中断,正在重试'); };
|
|
1970
|
+
for (const evtName of ['ready', 'doc.updated', 'agent.activity', 'agent.presence', 'agent.stage', 'canvas.draft', 'code.activity', 'code.diff']) {
|
|
1971
|
+
es.addEventListener(evtName, ev => pushDebugLog('sse', evtName + (ev.data ? ' ' + String(ev.data).slice(0, 140) : '')));
|
|
1972
|
+
}
|
|
1316
1973
|
addEventListener('pagehide', () => es.close());
|
|
1317
1974
|
} catch {}
|
|
1318
1975
|
}
|
|
@@ -1325,4 +1982,77 @@
|
|
|
1325
1982
|
}
|
|
1326
1983
|
}, 1200);
|
|
1327
1984
|
}
|
|
1985
|
+
|
|
1986
|
+
// ============ Mobile Debug Overlay (?debug=1) ============
|
|
1987
|
+
const debugEnabled = new URLSearchParams(location.search).get('debug') === '1';
|
|
1988
|
+
const debugLogs = [];
|
|
1989
|
+
let debugListEl = null;
|
|
1990
|
+
let debugBadgeEl = null;
|
|
1991
|
+
function pushDebugLog(level, msg) {
|
|
1992
|
+
if (!debugEnabled) return;
|
|
1993
|
+
const ts = new Date().toLocaleTimeString('zh-CN', { hour12: false });
|
|
1994
|
+
debugLogs.push({ ts, level, msg: String(msg || '') });
|
|
1995
|
+
if (debugLogs.length > 120) debugLogs.shift();
|
|
1996
|
+
if (debugBadgeEl) debugBadgeEl.textContent = String(debugLogs.length);
|
|
1997
|
+
if (debugListEl && !debugListEl.closest('[hidden]')) renderDebugLogs();
|
|
1998
|
+
}
|
|
1999
|
+
function renderDebugLogs() {
|
|
2000
|
+
if (!debugListEl) return;
|
|
2001
|
+
debugListEl.innerHTML = debugLogs.slice().reverse().map(item =>
|
|
2002
|
+
`<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>`
|
|
2003
|
+
).join('') || '<div class="clado-dbg-empty">暂无日志,操作画布或发起请求将实时记录。</div>';
|
|
2004
|
+
}
|
|
2005
|
+
if (debugEnabled && document.body) {
|
|
2006
|
+
const dbgBtn = document.createElement('button');
|
|
2007
|
+
dbgBtn.type = 'button';
|
|
2008
|
+
dbgBtn.id = 'clado-debug-toggle';
|
|
2009
|
+
dbgBtn.className = 'clado-debug-toggle';
|
|
2010
|
+
dbgBtn.innerHTML = '<span>Debug</span><span class="clado-dbg-count">0</span>';
|
|
2011
|
+
debugBadgeEl = dbgBtn.querySelector('.clado-dbg-count');
|
|
2012
|
+
|
|
2013
|
+
const dbgPanel = document.createElement('aside');
|
|
2014
|
+
dbgPanel.id = 'clado-debug-panel';
|
|
2015
|
+
dbgPanel.className = 'clado-debug-panel';
|
|
2016
|
+
dbgPanel.hidden = true;
|
|
2017
|
+
dbgPanel.innerHTML = `
|
|
2018
|
+
<div class="clado-dbg-head">
|
|
2019
|
+
<strong>移动端调试日志</strong>
|
|
2020
|
+
<div style="display:flex;gap:5px;">
|
|
2021
|
+
<button type="button" class="clado-cd-btn" data-dbg-copy>复制日志</button>
|
|
2022
|
+
<button type="button" class="clado-cd-btn" data-dbg-clear>清空</button>
|
|
2023
|
+
<button type="button" class="clado-cd-btn" data-dbg-close>收起</button>
|
|
2024
|
+
</div>
|
|
2025
|
+
</div>
|
|
2026
|
+
<div class="clado-dbg-list" data-dbg-list></div>
|
|
2027
|
+
`;
|
|
2028
|
+
debugListEl = dbgPanel.querySelector('[data-dbg-list]');
|
|
2029
|
+
document.body.append(dbgBtn, dbgPanel);
|
|
2030
|
+
|
|
2031
|
+
dbgBtn.onclick = () => { dbgPanel.hidden = !dbgPanel.hidden; if (!dbgPanel.hidden) renderDebugLogs(); };
|
|
2032
|
+
dbgPanel.querySelector('[data-dbg-close]').onclick = () => { dbgPanel.hidden = true; };
|
|
2033
|
+
dbgPanel.querySelector('[data-dbg-clear]').onclick = () => {
|
|
2034
|
+
debugLogs.length = 0;
|
|
2035
|
+
if (debugBadgeEl) debugBadgeEl.textContent = '0';
|
|
2036
|
+
renderDebugLogs();
|
|
2037
|
+
};
|
|
2038
|
+
dbgPanel.querySelector('[data-dbg-copy]').onclick = () => {
|
|
2039
|
+
const txt = debugLogs.map(x => `[${x.ts}] [${x.level}] ${x.msg}`).join('\n');
|
|
2040
|
+
navigator.clipboard?.writeText(txt).then(() => showToast('已复制调试日志')).catch(() => {});
|
|
2041
|
+
};
|
|
2042
|
+
|
|
2043
|
+
window.addEventListener('error', e => pushDebugLog('error', (e.message || 'Script error') + (e.filename ? ` (${e.filename}:${e.lineno})` : '')));
|
|
2044
|
+
window.addEventListener('unhandledrejection', e => pushDebugLog('error', 'Promise: ' + (e.reason?.message || String(e.reason || 'rejected'))));
|
|
2045
|
+
const origFetch = window.fetch.bind(window);
|
|
2046
|
+
window.fetch = async (...args) => {
|
|
2047
|
+
try {
|
|
2048
|
+
const res = await origFetch(...args);
|
|
2049
|
+
if (res.status >= 400) pushDebugLog('http', `${res.status} ${typeof args[0] === 'string' ? args[0] : (args[0]?.url || '')}`);
|
|
2050
|
+
return res;
|
|
2051
|
+
} catch (err) {
|
|
2052
|
+
pushDebugLog('error', `fetch failed: ${err?.message || err}`);
|
|
2053
|
+
throw err;
|
|
2054
|
+
}
|
|
2055
|
+
};
|
|
2056
|
+
pushDebugLog('info', `Clado Debug 已开启 · ${location.origin} · UA=${navigator.userAgent.slice(0, 60)}`);
|
|
2057
|
+
}
|
|
1328
2058
|
})();
|