cladogram 0.5.5-beta.9 → 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 (56) hide show
  1. package/README.md +106 -80
  2. package/bin/clado.js +35 -3
  3. package/docs/agent-context.md +63 -0
  4. package/docs/agent-reference.md +219 -0
  5. package/docs/release.md +123 -0
  6. package/package.json +5 -3
  7. package/plugins/agent/index.js +2485 -2982
  8. package/plugins/agent/settings.js +3592 -0
  9. package/plugins/agent/style.css +1441 -1315
  10. package/plugins/brand/index.js +84 -466
  11. package/plugins/brand/style.css +39 -172
  12. package/plugins/directory/index.js +10 -10
  13. package/plugins/view-controls/index.js +6 -1
  14. package/plugins/view-controls/style.css +41 -30
  15. package/skills/clado/SKILL.md +4 -2
  16. package/src/agent/automations.js +454 -0
  17. package/src/agent/clado-tools.js +792 -0
  18. package/src/agent/pi-bridge.js +2559 -0
  19. package/src/agent/pi-config.js +2411 -0
  20. package/src/agent/pi-hooks-perms.js +621 -0
  21. package/src/html/app-css.js +69 -1
  22. package/src/html/canvas-chain.js +32 -6
  23. package/src/html/canvas-focus.js +19 -13
  24. package/src/html/canvas-live-diff.js +1373 -0
  25. package/src/html/canvas-ui.css +503 -2
  26. package/src/html/canvas-wires.js +5 -1
  27. package/src/html/page.js +4 -2
  28. package/src/html/plugin-assets.js +5 -1
  29. package/src/html/plugin-ui.css +159 -134
  30. package/src/html/plugin-ui.js +3 -2
  31. package/src/html/runtime-api.js +152 -10
  32. package/src/html/runtime.js +546 -37
  33. package/src/server/agent.js +862 -1566
  34. package/src/server/assets/library-canvas.js +256 -9
  35. package/src/server/assets/library.css +951 -11
  36. package/src/server/assets/library.html +39 -4
  37. package/src/server/assets/library.js +1445 -224
  38. package/src/server/code-inspect.js +183 -0
  39. package/src/server/mcp.js +90 -22
  40. package/src/server/plugin-registry.js +671 -9
  41. package/src/server/plugins.js +1 -1
  42. package/src/server/workspace-hub.js +50 -0
  43. package/src/server/workspace.js +554 -39
  44. package/src/workspace/graph-snapshot.js +695 -0
  45. package/src/workspace/service.js +201 -9
  46. package/src/agent/commands.js +0 -204
  47. package/src/agent/context.js +0 -445
  48. package/src/agent/executors.js +0 -213
  49. package/src/agent/mcp-client.js +0 -308
  50. package/src/agent/probe.js +0 -234
  51. package/src/agent/providers/anthropic.js +0 -220
  52. package/src/agent/providers/index.js +0 -235
  53. package/src/agent/providers/openai.js +0 -146
  54. package/src/agent/runtime.js +0 -995
  55. package/src/agent/sessions.js +0 -336
  56. package/src/agent/skills.js +0 -190
@@ -45,65 +45,131 @@
45
45
  if (write) reloadWithMode(id !== 'clado.view-controls');
46
46
  return result;
47
47
  }
48
- const brand = ui.mountBrand(host, {
49
- plugins: {
50
- items, isEnabled,
51
- edit: config.hasPluginSettings ? editPluginSettings : null,
52
- install: config.canInstallPlugins && (async files => {
53
- const response = await fetch(withWorkspace('/library/install-plugin'), {
54
- method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ files }),
55
- });
56
- const result = await response.json();
57
- if (!response.ok) throw new Error(result.error);
58
- return result;
59
- }),
60
- refresh: () => reloadWithMode(true),
61
- save(disabled) {
62
- const next = new Set(disabledPlugins);
63
- for (const plugin of items) {
64
- if (plugin.reason) continue;
65
- if (disabled.includes(plugin.id)) next.add(plugin.id);
66
- else next.delete(plugin.id);
48
+ const stageEl = document.getElementById?.('clado-stage') || document.body;
49
+ const viewportEl = document.getElementById?.('clado-viewport') || null;
50
+
51
+ // ============ Toast Notification ============
52
+ let toastTimer = null;
53
+ function showToast(msg) {
54
+ const el = document.getElementById?.('clado-toast');
55
+ if (!el || !msg) return;
56
+ el.innerHTML = '<span class="clado-dot-sky"></span><span></span>';
57
+ el.querySelector('span:last-child').textContent = String(msg);
58
+ el.classList.add('show');
59
+ clearTimeout(toastTimer);
60
+ toastTimer = setTimeout(() => el.classList.remove('show'), 2400);
61
+ }
62
+ window.addEventListener?.('clado:toast', ev => showToast(ev.detail?.message));
63
+
64
+ // ============ Mobile Proportional Scale-to-Fit Stage (Zero Squish!) ============
65
+ if (viewportEl && stageEl && stageEl.id === 'clado-stage') {
66
+ const STAGE_W = 1280, STAGE_H = 820;
67
+ const mzLabel = document.querySelector('[data-mz-fit]');
68
+ let isScaled = false, fitScale = 1, curScale = 1, panX = 0, panY = 0;
69
+
70
+ const applyStageTransform = () => {
71
+ if (!isScaled) { stageEl.style.transform = ''; return; }
72
+ stageEl.style.transform = `translate3d(${panX.toFixed(1)}px, ${panY.toFixed(1)}px, 0) scale(${curScale.toFixed(4)})`;
73
+ if (mzLabel) mzLabel.textContent = Math.round(curScale * 100) + '%';
74
+ };
75
+
76
+ const resetMobileFit = () => {
77
+ const vw = window.innerWidth, vh = window.innerHeight;
78
+ if (vw >= 1160) {
79
+ isScaled = false;
80
+ viewportEl.classList.remove('scaled-mode');
81
+ stageEl.style.transform = '';
82
+ return;
83
+ }
84
+ isScaled = true;
85
+ viewportEl.classList.add('scaled-mode');
86
+ const padX = 12, padTop = 14, padBottom = 58;
87
+ fitScale = Math.min((vw - padX * 2) / STAGE_W, (vh - padTop - padBottom) / STAGE_H);
88
+ curScale = fitScale;
89
+ panX = (vw - STAGE_W * curScale) / 2;
90
+ panY = padTop + Math.max(0, (vh - padTop - padBottom - STAGE_H * curScale) / 2);
91
+ applyStageTransform();
92
+ };
93
+
94
+ const stepZoom = delta => {
95
+ if (!isScaled) return;
96
+ const vw = window.innerWidth, vh = window.innerHeight;
97
+ const next = Math.max(fitScale * 0.85, Math.min(1.6, curScale + delta));
98
+ const ratio = next / curScale;
99
+ panX = vw / 2 - (vw / 2 - panX) * ratio;
100
+ panY = vh / 2 - (vh / 2 - panY) * ratio;
101
+ curScale = next;
102
+ applyStageTransform();
103
+ };
104
+
105
+ document.querySelector('[data-mz-out]')?.addEventListener('click', () => stepZoom(-0.15));
106
+ document.querySelector('[data-mz-in]')?.addEventListener('click', () => stepZoom(0.15));
107
+ mzLabel?.addEventListener('click', resetMobileFit);
108
+
109
+ const ptrs = new Map();
110
+ let lastDist = null, lastDrag = null;
111
+ viewportEl.addEventListener('pointerdown', e => {
112
+ if (!isScaled || e.target.closest('#clado-mobile-zoom-hud')) return;
113
+ ptrs.set(e.pointerId, { x: e.clientX, y: e.clientY });
114
+ if (ptrs.size === 1) lastDrag = { x: e.clientX, y: e.clientY };
115
+ else if (ptrs.size === 2) {
116
+ const p = [...ptrs.values()];
117
+ lastDist = Math.hypot(p[0].x - p[1].x, p[0].y - p[1].y);
118
+ }
119
+ });
120
+ viewportEl.addEventListener('pointermove', e => {
121
+ if (!isScaled || !ptrs.has(e.pointerId)) return;
122
+ ptrs.set(e.pointerId, { x: e.clientX, y: e.clientY });
123
+ if (ptrs.size === 2) {
124
+ const p = [...ptrs.values()];
125
+ const dist = Math.hypot(p[0].x - p[1].x, p[0].y - p[1].y);
126
+ const mx = (p[0].x + p[1].x) / 2, my = (p[0].y + p[1].y) / 2;
127
+ if (lastDist && dist > 10) {
128
+ const next = Math.max(fitScale * 0.85, Math.min(1.8, curScale * (dist / lastDist)));
129
+ const ratio = next / curScale;
130
+ panX = mx - (mx - panX) * ratio;
131
+ panY = my - (my - panY) * ratio;
132
+ curScale = next;
133
+ applyStageTransform();
67
134
  }
68
- localStorage.setItem(pluginKey, JSON.stringify([...next]));
69
- reloadWithMode(true);
70
- },
71
- },
72
- market: config.canInstallPlugins ? {
73
- load: async () => {
74
- const response = await fetch(withWorkspace('/library/plugin-registry'), { cache: 'no-store' });
75
- const result = await response.json();
76
- if (!response.ok) throw new Error(result.error || '加载插件市场失败');
77
- return result;
78
- },
79
- install: async id => {
80
- const response = await fetch(withWorkspace('/library/plugin-registry'), {
81
- method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id }),
82
- });
83
- const result = await response.json();
84
- if (!response.ok) throw new Error(result.error || '安装失败');
85
- return result;
86
- },
87
- uninstall: async id => {
88
- const response = await fetch(withWorkspace('/library/install-plugin?id=' + encodeURIComponent(id)), {
89
- method: 'DELETE',
90
- });
91
- const result = await response.json();
92
- if (!response.ok) throw new Error(result.error || '卸载失败');
93
- return result;
94
- },
95
- } : null,
96
- openWorkspacePicker: config.canSwitchWorkspace && !offline ? () => openWorkspacePicker() : null,
97
- setTheme: theme => {
98
- if (modalLocked()) return;
99
- try { localStorage.setItem('clado-theme', theme); } catch {}
100
- setDesign({ theme });
101
- post('theme', { theme });
102
- },
103
- capture: screenshot && settings['clado.brand']?.showScreenshot !== false && (async () => {
104
- try { await screenshot.download(await screenshot.capture({}, readScreenshotCanvas)); }
105
- catch (error) { directory.showMessage('截图失败', error.message); }
106
- }),
135
+ lastDist = dist;
136
+ } else if (ptrs.size === 1 && lastDrag && curScale > fitScale * 1.05) {
137
+ const dx = e.clientX - lastDrag.x, dy = e.clientY - lastDrag.y;
138
+ if (Math.hypot(dx, dy) > 2) {
139
+ panX += dx; panY += dy;
140
+ lastDrag = { x: e.clientX, y: e.clientY };
141
+ applyStageTransform();
142
+ }
143
+ }
144
+ });
145
+ const dropPtr = e => {
146
+ ptrs.delete(e.pointerId);
147
+ if (ptrs.size < 2) lastDist = null;
148
+ if (ptrs.size === 0) lastDrag = null;
149
+ };
150
+ viewportEl.addEventListener('pointerup', dropPtr);
151
+ viewportEl.addEventListener('pointercancel', dropPtr);
152
+ window.addEventListener('resize', resetMobileFit);
153
+ resetMobileFit();
154
+ }
155
+
156
+ const applyTheme = theme => {
157
+ if (modalLocked()) return;
158
+ try { localStorage.setItem('clado-theme', theme); } catch {}
159
+ setDesign({ theme });
160
+ post('theme', { theme });
161
+ };
162
+ const captureShot = screenshot && settings['clado.brand']?.showScreenshot !== false ? (async () => {
163
+ try { await screenshot.download(await screenshot.capture({}, readScreenshotCanvas)); }
164
+ catch (error) { directory.showMessage('截图失败', error.message); }
165
+ }) : null;
166
+
167
+ const brand = ui.mountBrand(host, {
168
+ workspaceName: config.workspaceName || 'clado',
169
+ openLobby: config.canSwitchWorkspace && !offline ? () => openLobby() : null,
170
+ openSettings: !offline && config.agent ? () => window.CladoVNext?.openSettings?.('extensions') : null,
171
+ setTheme: applyTheme,
172
+ capture: captureShot,
107
173
  });
108
174
  const updateControls = ui.mountViewControls(host, {
109
175
  setMode: next => {
@@ -112,6 +178,7 @@
112
178
  saveView();
113
179
  syncChrome();
114
180
  frame.contentWindow.CladoPrototype?.setMode?.(next);
181
+ armPresenceAfterglowForFile(selected);
115
182
  },
116
183
  clearFocus: () => frame.contentWindow.CladoRuntime?.clearFocus(),
117
184
  showDiagnostics: () => frame.contentWindow.CladoCanvasControls?.showDiagnostics(),
@@ -122,7 +189,7 @@
122
189
  openFromCapability,
123
190
  workspaceUrl,
124
191
  switchWorkspace: id => { location.href = workspaceUrl(id); },
125
- openWorkspacePicker: config.canSwitchWorkspace && !offline ? () => openWorkspacePicker() : null,
192
+ openWorkspacePicker: config.canSwitchWorkspace && !offline ? () => openLobby() : null,
126
193
  createCanvas: config.canSwitchWorkspace && !offline ? () => createCanvasFlow() : null,
127
194
  renameCanvas: config.canSwitchWorkspace && !offline ? doc => renameCanvasFlow(doc) : null,
128
195
  deleteCanvas: config.canSwitchWorkspace && !offline ? doc => deleteCanvasFlow(doc) : null,
@@ -232,65 +299,59 @@
232
299
  location.href = '/';
233
300
  }
234
301
 
302
+ const escHtml = s => String(s ?? '').replace(/[&<>"']/g, m => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[m]));
303
+ const lobbyEl = document.getElementById?.('clado-lobby') || null;
304
+ let lobbySearchQuery = '';
305
+ let cachedHubData = null;
306
+
235
307
  function ensureWorkspacePicker() {
236
- if (wsPickerOverlay || !document.body) return wsPickerOverlay;
308
+ if (wsPickerOverlay || !stageEl) return wsPickerOverlay;
237
309
  wsPickerOverlay = document.createElement('div');
238
310
  wsPickerOverlay.id = 'clado-workspace-picker';
239
- wsPickerOverlay.className = 'clado-market-overlay';
311
+ wsPickerOverlay.className = 'clado-vnext-mask';
312
+ wsPickerOverlay.hidden = true;
240
313
  wsPickerOverlay.innerHTML = `
241
- <div class="clado-market-sheet" style="max-width:500px;">
242
- <div class="clado-market-well" style="padding:12px 14px;display:flex;align-items:center;justify-content:space-between;gap:8px;">
314
+ <div class="clado-folder-sheet">
315
+ <div style="display:flex;align-items:center;justify-content:space-between;gap:8px;">
243
316
  <div>
244
- <strong style="font-size:15px;">选择或新建工作区</strong>
245
- <div data-ws-cur style="font-size:11px;color:var(--clado-ui-muted);margin-top:2px;"></div>
317
+ <div style="font-size:15.5px;font-weight:630;">打开本地目录或新建工作区</div>
318
+ <div data-ws-cur style="font-size:11.5px;color:var(--clado-ui-muted);margin-top:2px;font-family:ui-monospace,monospace;"></div>
246
319
  </div>
247
- <button type="button" class="clado-market-tab active" data-ws-close style="padding:5px 11px;">关闭</button>
320
+ <button type="button" class="clado-ui-button" data-ws-close style="border-color:var(--clado-ui-well-border);background:var(--clado-ui-well);">关闭</button>
248
321
  </div>
249
322
 
250
- <div class="clado-market-well" data-ws-recents-wrap style="padding:11px 12px;display:none;flex-direction:column;gap:5px;">
251
- <div style="font-size:11px;font-weight:650;color:var(--clado-ui-muted);">最近打开的项目</div>
252
- <div data-ws-recents style="display:flex;flex-direction:column;gap:3px;"></div>
253
- </div>
254
-
255
- <div class="clado-market-well" style="padding:11px 12px;display:flex;flex-direction:column;gap:8px;">
323
+ <div class="clado-well-box" style="padding:11px 12px;display:flex;flex-direction:column;gap:8px;">
256
324
  <div style="display:flex;align-items:center;justify-content:space-between;gap:6px;">
257
- <span style="font-size:11.5px;font-weight:650;color:var(--clado-ui-muted);">浏览本机目录</span>
258
- <div style="display:flex;gap:4px;">
259
- <button type="button" class="clado-market-tab active" data-ws-up style="font-size:11px;padding:3px 8px;">↑ 上级</button>
260
- <button type="button" class="clado-market-tab active" data-ws-home style="font-size:11px;padding:3px 8px;">⌂ 主目录</button>
325
+ <span style="font-size:11.5px;font-weight:610;color:var(--clado-ui-muted);">浏览本机文件夹</span>
326
+ <div style="display:flex;gap:5px;">
327
+ <button type="button" class="clado-ui-button" data-ws-up style="min-height:26px;font-size:11.5px;padding:3px 9px;border-color:var(--clado-ui-well-border);background:var(--clado-ui-well);">上级</button>
328
+ <button type="button" class="clado-ui-button" data-ws-home style="min-height:26px;font-size:11.5px;padding:3px 9px;border-color:var(--clado-ui-well-border);background:var(--clado-ui-well);">主目录</button>
261
329
  </div>
262
330
  </div>
263
- <div data-ws-browse-list style="max-height:190px;overflow-y:auto;display:flex;flex-direction:column;gap:2px;"></div>
331
+ <div data-ws-browse-list style="max-height:210px;overflow-y:auto;display:flex;flex-direction:column;gap:2px;"></div>
264
332
  </div>
265
333
 
266
- <div class="clado-market-well" style="padding:12px;display:flex;flex-direction:column;gap:8px;">
267
- <div style="font-size:11.5px;color:var(--clado-ui-muted);">目标工作区路径(回车浏览目录,或直接输入新目录路径自动创建)</div>
334
+ <div class="clado-well-box" style="padding:12px;display:flex;flex-direction:column;gap:8px;">
335
+ <div style="font-size:11.5px;color:var(--clado-ui-muted);">输入或选择项目路径(若目录不存在将自动新建)</div>
268
336
  <div style="display:flex;gap:6px;">
269
- <input type="text" data-ws-input style="flex:1;height:35px;padding:0 11px;border-radius:10px;border:1px solid var(--clado-ui-well-border);background:var(--clado-ui-well);color:var(--clado-ui-text);font:inherit;font-size:12.5px;outline:none;" placeholder="/path/to/your-project" />
270
- <button type="button" class="clado-market-tab active" data-ws-go style="height:35px;padding:0 11px;font-size:12px;">浏览</button>
337
+ <input type="text" class="clado-field" data-ws-input placeholder="/path/to/your-project" />
338
+ <button type="button" class="clado-ui-button" data-ws-go style="border-color:var(--clado-ui-well-border);background:var(--clado-ui-well);">定位</button>
271
339
  </div>
272
- <div data-ws-err style="font-size:11.5px;color:#e11d48;display:none;"></div>
273
- <div style="display:flex;gap:8px;flex-wrap:wrap;">
274
- <button type="button" class="clado-market-tab active" data-ws-open style="flex:1;height:35px;font-size:12.5px;">打开此目录</button>
275
- <button type="button" data-ws-init style="flex:1.2;height:35px;border:0;border-radius:10px;background:var(--clado-ui-brand);color:#fff;font:inherit;font-size:12.5px;font-weight:600;cursor:pointer;">在此新建工作区并建首张画布</button>
340
+ <div data-ws-err style="font-size:11.5px;color:#be123c;display:none;"></div>
341
+ <div style="display:flex;gap:8px;margin-top:2px;">
342
+ <button type="button" class="clado-ui-button" data-ws-open style="flex:1;border-color:var(--clado-ui-well-border);background:var(--clado-ui-well);">打开此目录</button>
343
+ <button type="button" class="clado-ui-button clado-ui-button-primary" data-ws-init style="flex:1.2;">打开并新建首张画布</button>
276
344
  </div>
277
345
  </div>
278
346
  </div>`;
279
- document.body.append(wsPickerOverlay);
347
+ stageEl.append(wsPickerOverlay);
280
348
 
281
- let parentDir = '';
282
- let homeDir = '';
349
+ let parentDir = '', homeDir = '';
283
350
  const curEl = wsPickerOverlay.querySelector('[data-ws-cur]');
284
- const recentsWrap = wsPickerOverlay.querySelector('[data-ws-recents-wrap]');
285
- const recentsList = wsPickerOverlay.querySelector('[data-ws-recents]');
286
351
  const browseList = wsPickerOverlay.querySelector('[data-ws-browse-list]');
287
352
  const pathInput = wsPickerOverlay.querySelector('[data-ws-input]');
288
353
  const errEl = wsPickerOverlay.querySelector('[data-ws-err]');
289
-
290
- const showErr = msg => {
291
- errEl.textContent = msg || '';
292
- errEl.style.display = msg ? 'block' : 'none';
293
- };
354
+ const showErr = msg => { errEl.textContent = msg || ''; errEl.style.display = msg ? 'block' : 'none'; };
294
355
 
295
356
  const loadDir = async (dir = '') => {
296
357
  showErr('');
@@ -299,69 +360,43 @@
299
360
  const res = await fetch('/library/fs-workspaces' + qs, { cache: 'no-store' });
300
361
  const data = await res.json();
301
362
  if (!res.ok) throw new Error(data.error || '读取目录失败');
363
+ cachedHubData = data;
302
364
  parentDir = data.parentDir || '';
303
365
  homeDir = data.homeDir || '';
304
- curEl.textContent = data.hubMode ? '请选择一个项目目录开始协作' : `当前:${data.currentWorkspace}`;
366
+ curEl.textContent = data.currentDir || data.currentWorkspace || '';
305
367
  pathInput.value = data.currentDir || data.currentWorkspace || '';
306
368
 
307
- const recents = Array.isArray(data.recentWorkspaces) ? data.recentWorkspaces : [];
308
- if (recents.length) {
309
- recentsWrap.style.display = 'flex';
310
- recentsList.replaceChildren();
311
- for (const r of recents.slice(0, 5)) {
312
- const row = document.createElement('button');
313
- row.type = 'button';
314
- row.className = 'clado-folder-row';
315
- row.innerHTML = `<span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><strong>${r.name}</strong> <small style="color:var(--clado-ui-muted);">${r.path}</small></span><span style="font-size:11px;color:var(--clado-ui-brand);flex:none;">${r.documents ?? 0} 画布</span>`;
316
- row.onclick = () => applyWorkspaceSwitch(r.path, { createIfMissing: false }).catch(e => showErr(e.message));
317
- recentsList.append(row);
318
- }
319
- } else {
320
- recentsWrap.style.display = 'none';
321
- }
322
-
323
369
  browseList.replaceChildren();
324
370
  const entries = Array.isArray(data.entries) ? data.entries : [];
325
371
  if (!entries.length) {
326
372
  const empty = document.createElement('div');
327
- empty.style.cssText = 'padding:12px;text-align:center;color:var(--clado-ui-muted);font-size:12px;';
328
- empty.textContent = '当前文件夹下暂无子目录,可直接打开此目录或下方输入新子目录名新建。';
373
+ empty.style.cssText = 'padding:14px;text-align:center;color:var(--clado-ui-muted);font-size:12px;';
374
+ empty.textContent = '当前目录下无子文件夹,可直接打开此目录或输入新目录名。';
329
375
  browseList.append(empty);
330
376
  } else {
331
377
  for (const item of entries) {
332
378
  const row = document.createElement('button');
333
379
  row.type = 'button';
334
380
  row.className = 'clado-folder-row';
335
- row.dataset.folderPath = item.path;
336
381
  const badges = [
337
- item.hasClado ? '<span style="color:#059669;font-weight:600;">Clado</span>' : '',
338
- item.isGit ? '<span style="color:var(--clado-ui-muted);">Git</span>' : '',
339
- item.mdCount ? `<span>${item.mdCount} md</span>` : '',
340
- ].filter(Boolean).join(' · ');
341
- row.innerHTML = `<span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">📁 ${item.name}</span><small style="color:var(--clado-ui-subtle);flex:none;">${badges || '进入 ›'}</small>`;
382
+ item.hasClado ? '<span class="clado-chip clado-chip-sky">Clado</span>' : '',
383
+ item.isGit ? '<span class="clado-chip clado-chip-neutral">Git</span>' : '',
384
+ ].filter(Boolean).join(' ');
385
+ row.innerHTML = `<span style="display:inline-flex;align-items:center;gap:7px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><svg class="clado-svg-ico" style="color:var(--clado-ui-muted)" viewBox="0 0 24 24"><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>${escHtml(item.name)}</span><span style="display:inline-flex;gap:4px;flex:none;">${badges}</span>`;
342
386
  row.onclick = () => loadDir(item.path);
343
387
  browseList.append(row);
344
388
  }
345
389
  }
346
- } catch (err) {
347
- showErr(err.message || '读取目录失败');
348
- }
390
+ } catch (err) { showErr(err.message || '读取目录失败'); }
349
391
  };
350
392
 
351
393
  wsPickerOverlay.addEventListener('click', ev => {
352
- if (ev.target === wsPickerOverlay || ev.target.closest('[data-ws-close]')) {
353
- wsPickerOverlay.classList.remove('show');
354
- }
394
+ if (ev.target === wsPickerOverlay || ev.target.closest('[data-ws-close]')) wsPickerOverlay.hidden = true;
355
395
  });
356
396
  pathInput.addEventListener('keydown', ev => {
357
- if (ev.key === 'Enter') {
358
- ev.preventDefault();
359
- if (pathInput.value.trim()) loadDir(pathInput.value.trim());
360
- }
397
+ if (ev.key === 'Enter') { ev.preventDefault(); if (pathInput.value.trim()) loadDir(pathInput.value.trim()); }
361
398
  });
362
- wsPickerOverlay.querySelector('[data-ws-go]').onclick = () => {
363
- if (pathInput.value.trim()) loadDir(pathInput.value.trim());
364
- };
399
+ wsPickerOverlay.querySelector('[data-ws-go]').onclick = () => { if (pathInput.value.trim()) loadDir(pathInput.value.trim()); };
365
400
  wsPickerOverlay.querySelector('[data-ws-up]').onclick = () => { if (parentDir) loadDir(parentDir); };
366
401
  wsPickerOverlay.querySelector('[data-ws-home]').onclick = () => { if (homeDir) loadDir(homeDir); };
367
402
  wsPickerOverlay.querySelector('[data-ws-open]').onclick = () => {
@@ -375,53 +410,248 @@
375
410
  }
376
411
 
377
412
  function openWorkspacePicker(initialDir = '') {
378
- if (!config.canSwitchWorkspace || offline || !document.body) return;
413
+ if (!config.canSwitchWorkspace || offline) return;
379
414
  const modal = ensureWorkspacePicker();
380
415
  if (!modal) return;
381
- modal.classList.add('show');
416
+ modal.hidden = false;
382
417
  modal._loadDir(initialDir);
383
418
  }
384
419
 
385
- if (config.canSwitchWorkspace && !offline && document.body) {
386
- window.addEventListener('clado:open-workspace-picker', () => openWorkspacePicker());
387
- const emptyEl = $('#emptyState');
388
- if (emptyEl) {
389
- const wsTitle = config.hubMode ? '欢迎使用 Clado · 请先选择工作区' : `当前工作区:${config.workspaceName || '未命名项目'}`;
390
- const wsSub = config.hubMode
391
- ? '选择一个已有代码仓库或新建空白工作区,配置好模型供应商即可开始与多角色分身协作设计。'
392
- : `路径:${config.workspacePath || '.'} · 当前目录尚无画布文档,你可以一键新建首张画布或直接在右下角向 Agent 提问。`;
393
- emptyEl.style.padding = '0';
394
- emptyEl.innerHTML = `
395
- <div class="clado-launchpad-wrap">
396
- <div class="clado-launchpad-card">
420
+ function closeLobby() {
421
+ if (lobbyEl) lobbyEl.hidden = true;
422
+ }
423
+
424
+ function renderLobbyView(hubData) {
425
+ if (!lobbyEl) return;
426
+ const meta = window.CladoVNext?.getMeta?.() || {};
427
+ const recents = Array.isArray(hubData?.recentWorkspaces) ? hubData.recentWorkspaces : [];
428
+ const currentInRecents = recents.some(r => r.path === hubData?.currentWorkspace);
429
+ const allWorkspaces = [...recents];
430
+ if (!config.hubMode && hubData?.currentWorkspace && !currentInRecents) {
431
+ allWorkspaces.unshift({
432
+ path: hubData.currentWorkspace,
433
+ name: hubData.currentName || config.workspaceName || '当前项目',
434
+ gitBranch: hubData.currentProfile?.gitBranch || '',
435
+ codeFiles: hubData.currentProfile?.codeFiles || 0,
436
+ primaryLang: hubData.currentProfile?.primaryLang || '',
437
+ documents: index.documents.length,
438
+ });
439
+ }
440
+ const q = lobbySearchQuery.trim().toLowerCase();
441
+ const filtered = allWorkspaces.filter(w => !q || (w.name + ' ' + w.path).toLowerCase().includes(q));
442
+ const eco = meta.ecosystem || {};
443
+ const extCount = (eco.packages?.length || 0) + (eco.skills?.length || 0) + 1;
444
+ const mcpCount = eco.mcpServers?.length || 0;
445
+ const roleCount = meta.roles?.length || 4;
446
+ const activeModel = meta.activeModelLabel || '点击设置模型';
447
+
448
+ lobbyEl.innerHTML = `
449
+ <div class="clado-lobby-inner">
450
+ <header class="clado-lobby-head">
451
+ <div style="display:flex;align-items:center;gap:13px;">
452
+ <div class="clado-brand-gem">
453
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round">
454
+ <path d="M17 7.5A6.5 6.5 0 1 0 17 16.5"/>
455
+ <circle cx="17.5" cy="12" r="1.4" fill="currentColor" stroke="none"/>
456
+ </svg>
457
+ </div>
397
458
  <div>
398
- <div style="font-size:16px;font-weight:700;color:var(--clado-ui-text);">${wsTitle}</div>
399
- <div style="font-size:12px;line-height:1.55;color:var(--clado-ui-muted);margin-top:5px;">${wsSub}</div>
459
+ <div style="display:flex;align-items:center;gap:8px;">
460
+ <span style="font-size:19px;font-weight:640;letter-spacing:-0.02em;">clado</span>
461
+ <span class="clado-chip clado-chip-sky">Pi Engine</span>
462
+ </div>
463
+ <div style="font-size:12px;color:var(--clado-ui-muted);margin-top:2px;">空间画布设计 · 多角色编排 · 代码与测试交付</div>
464
+ </div>
465
+ </div>
466
+
467
+ <div style="display:flex;align-items:center;gap:10px;">
468
+ <div class="clado-ui-glass" style="display:flex;align-items:center;gap:8px;padding:7px 14px;border-radius:999px;width:230px;">
469
+ <svg class="clado-svg-ico" style="color:var(--clado-ui-subtle)" viewBox="0 0 24 24"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
470
+ <input type="text" data-lobby-search value="${escHtml(lobbySearchQuery)}" placeholder="搜索项目工作区…" style="border:0;outline:0;background:transparent;width:100%;font-size:12.5px;color:var(--clado-ui-text);" />
471
+ </div>
472
+ <div class="clado-ui-glass" style="display:flex;align-items:center;gap:8px;padding:5px 7px 5px 13px;border-radius:999px;">
473
+ <span class="clado-dot-ok"></span>
474
+ <span style="font-family:ui-monospace,monospace;font-size:11.5px;color:var(--clado-ui-text-soft);">${escHtml(activeModel)}</span>
475
+ <span class="clado-top-pill-sep"></span>
476
+ <button type="button" class="clado-ui-button" data-lobby-settings style="min-height:28px;padding:4px 10px;font-size:12px;">设置</button>
400
477
  </div>
401
- <div class="clado-launchpad-actions">
402
- <button type="button" class="clado-launchpad-btn primary" data-lp-pick>
403
- <span><strong>📂 选择或切换本机工作区</strong><br/><small style="color:var(--clado-ui-muted);">浏览电脑目录、打开已有仓库或新建项目</small></span>
404
- <span style="color:var(--clado-ui-brand);font-weight:700;">›</span>
405
- </button>
406
- <button type="button" class="clado-launchpad-btn" data-lp-new-canvas>
407
- <span><strong>✨ 在当前工作区新建首张画布</strong><br/><small style="color:var(--clado-ui-muted);">立即创建初始架构画布进入三视图协作</small></span>
408
- <span style="opacity:.5;">+</span>
409
- </button>
410
- <button type="button" class="clado-launchpad-btn" data-lp-llm>
411
- <span><strong>⚙ 配置供应商与主力模型</strong><br/><small style="color:var(--clado-ui-muted);">支持 OpenAI / Anthropic / DeepSeek / OpenRouter / Ollama</small></span>
412
- <span style="opacity:.5;">›</span>
413
- </button>
478
+ </div>
479
+ </header>
480
+
481
+ <div style="display:flex;align-items:flex-end;justify-content:space-between;gap:14px;">
482
+ <div>
483
+ <div style="font-size:24px;font-weight:640;letter-spacing:-0.025em;">工作区</div>
484
+ <div style="font-size:13px;color:var(--clado-ui-muted);margin-top:5px;">选择已有项目进入空间画布,或打开本地代码仓库一键梳理架构。</div>
485
+ </div>
486
+ <div style="display:flex;align-items:center;gap:10px;">
487
+ ${!config.hubMode ? '<button type="button" class="clado-ui-button" data-lobby-back style="border-color:var(--clado-ui-well-border);background:var(--clado-ui-well);padding:8px 14px;border-radius:13px;">返回当前画布</button>' : ''}
488
+ <button type="button" class="clado-ui-button" data-lobby-open style="border-color:var(--clado-ui-well-border);background:var(--clado-ui-well);padding:8px 15px;border-radius:13px;">打开本地目录</button>
489
+ <button type="button" class="clado-ui-button clado-ui-button-primary" data-lobby-new style="padding:8px 16px;border-radius:13px;">+ 新建工作区</button>
490
+ </div>
491
+ </div>
492
+
493
+ <div class="clado-lobby-grid" data-lobby-cards></div>
494
+
495
+ <div class="clado-ui-glass" style="margin-top:26px;border-radius:18px;padding:13px 20px;display:flex;align-items:center;justify-content:space-between;font-size:12.5px;">
496
+ <div style="display:flex;align-items:center;gap:14px;">
497
+ <span style="display:inline-flex;align-items:center;gap:7px;font-weight:540;color:var(--clado-ui-text-soft);"><span class="clado-dot-ok"></span>Pi 1.0 运行时就绪</span>
498
+ <span style="font-family:ui-monospace,monospace;font-size:11.5px;color:var(--clado-ui-subtle);">${escHtml(meta.agentDir || '~/.pi/agent')}</span>
499
+ <span class="clado-top-pill-sep"></span>
500
+ <span style="color:var(--clado-ui-muted);">${extCount} 个扩展 · ${mcpCount} 个 MCP · ${roleCount} 套角色</span>
501
+ </div>
502
+ <button type="button" class="clado-ui-button" data-lobby-ext style="min-height:28px;font-size:12px;">管理扩展与能力 →</button>
503
+ </div>
504
+ </div>
505
+ `;
506
+
507
+ const cardsWrap = lobbyEl.querySelector('[data-lobby-cards]');
508
+ if (!filtered.length) {
509
+ cardsWrap.innerHTML = `<div class="clado-well-box" style="grid-column:1/-1;padding:28px;text-align:center;color:var(--clado-ui-muted);">暂无最近工作区,点击右上角「打开本地目录」或「+ 新建工作区」立即开始。</div>`;
510
+ } else {
511
+ for (const w of filtered.slice(0, 9)) {
512
+ const card = document.createElement('button');
513
+ card.type = 'button';
514
+ card.className = 'clado-ws-card';
515
+ const initials = (w.name || 'WS').replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '').slice(0, 2).toUpperCase() || 'WS';
516
+ const needsAnalysis = (w.documents || 0) === 0 && (w.codeFiles || 0) > 0;
517
+ const badgeHtml = needsAnalysis
518
+ ? '<span class="clado-chip clado-chip-amber">待分析</span>'
519
+ : w.gitBranch
520
+ ? `<span class="clado-chip clado-chip-sky">${escHtml(w.gitBranch)}</span>`
521
+ : '<span class="clado-chip clado-chip-mint">工作区</span>';
522
+ const desc = needsAnalysis
523
+ ? `已检测到 ${escHtml(w.primaryLang || '本地')} 源码仓库(${w.codeFiles} 个文件),尚未生成架构画布,可一键分析出图。`
524
+ : (w.documents || 0) > 0
525
+ ? `包含 ${w.documents} 张空间画布${w.primaryLang ? ` · ${w.primaryLang} 工程` : ''},可继续梳理架构或交接交付。`
526
+ : '空白工作区,进入后可直接起稿画布或让角色协助拆解设计。';
527
+ card.innerHTML = `
528
+ <div>
529
+ <div style="display:flex;align-items:center;justify-content:space-between;gap:8px;">
530
+ <div style="display:flex;align-items:center;gap:11px;min-width:0;">
531
+ <div class="clado-ws-mono">${escHtml(initials)}</div>
532
+ <div style="min-width:0;">
533
+ <div style="font-size:14.5px;font-weight:620;color:var(--clado-ui-text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${escHtml(w.name)}</div>
534
+ <div style="font-family:ui-monospace,monospace;font-size:11px;color:var(--clado-ui-subtle);margin-top:1px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${escHtml(w.path)}</div>
535
+ </div>
536
+ </div>
537
+ ${badgeHtml}
414
538
  </div>
539
+ <p style="font-size:12.5px;line-height:1.62;color:var(--clado-ui-muted);margin:15px 0 0;">${desc}</p>
540
+ </div>
541
+ <div style="display:flex;align-items:center;justify-content:space-between;padding-top:13px;border-top:1px solid var(--clado-ui-edge);font-size:12px;">
542
+ <span style="color:var(--clado-ui-subtle);">${w.documents || 0} 张画布</span>
543
+ <span style="font-weight:560;color:var(--clado-ui-text-soft);">${needsAnalysis ? '分析并进入 →' : '进入 →'}</span>
415
544
  </div>
416
- </div>`;
417
- emptyEl.querySelector('[data-lp-pick]').onclick = () => openWorkspacePicker();
418
- emptyEl.querySelector('[data-lp-new-canvas]').onclick = () => createCanvasFlow('系统架构概览');
419
- emptyEl.querySelector('[data-lp-llm]').onclick = () => window.dispatchEvent(new CustomEvent('clado:open-llm-settings'));
545
+ `;
546
+ card.onclick = () => {
547
+ if (w.path === hubData?.currentWorkspace && !config.hubMode) {
548
+ closeLobby();
549
+ return;
550
+ }
551
+ applyWorkspaceSwitch(w.path, { createIfMissing: false }).catch(e => showToast(e.message));
552
+ };
553
+ cardsWrap.append(card);
554
+ }
420
555
  }
421
- if (config.hubMode) {
422
- setTimeout(() => openWorkspacePicker(), 60);
556
+
557
+ const searchInput = lobbyEl.querySelector('[data-lobby-search]');
558
+ searchInput.addEventListener('input', () => { lobbySearchQuery = searchInput.value; renderLobbyView(hubData); });
559
+ lobbyEl.querySelector('[data-lobby-settings]').onclick = () => window.CladoVNext?.openSettings?.('models');
560
+ lobbyEl.querySelector('[data-lobby-ext]').onclick = () => window.CladoVNext?.openSettings?.('extensions');
561
+ lobbyEl.querySelector('[data-lobby-open]').onclick = () => openWorkspacePicker();
562
+ lobbyEl.querySelector('[data-lobby-new]').onclick = () => openWorkspacePicker();
563
+ const backBtn = lobbyEl.querySelector('[data-lobby-back]');
564
+ if (backBtn) backBtn.onclick = () => closeLobby();
565
+ }
566
+
567
+ async function openLobby() {
568
+ if (!config.canSwitchWorkspace || offline || !lobbyEl) return;
569
+ lobbyEl.hidden = false;
570
+ try {
571
+ const res = await fetch('/library/fs-workspaces', { cache: 'no-store' });
572
+ if (res.ok) cachedHubData = await res.json();
573
+ } catch {}
574
+ renderLobbyView(cachedHubData || {});
575
+ }
576
+
577
+ let discoveredWorkspaces = [];
578
+ let emptyWorkspaceSignature = '';
579
+
580
+ function renderEmptyOnboarding(profile = {}) {
581
+ const emptyEl = $('#emptyState');
582
+ if (!emptyEl) return;
583
+ let selectedTpl = 'arch';
584
+ const hasCode = (profile.codeFiles || 0) > 0;
585
+ const chipLabel = hasCode
586
+ ? `已识别本地仓库 · ${profile.codeFiles} 个 ${profile.primaryLang || '源码'} 文件`
587
+ : `当前工作区 · ${config.workspaceName || '新建项目'}`;
588
+ emptyEl.innerHTML = `
589
+ <div class="clado-empty-card">
590
+ <div class="clado-prism-aura-under"></div>
591
+ <div style="display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;">
592
+ <span class="clado-chip clado-chip-sky" style="padding:4px 11px;"><span class="clado-dot-sky" style="width:6px;height:6px;"></span>${escHtml(chipLabel)}</span>
593
+ <span style="font-family:ui-monospace,monospace;font-size:11.5px;color:var(--clado-ui-subtle);">${escHtml(config.workspacePath || '')}</span>
594
+ </div>
595
+ <div style="font-size:22px;font-weight:630;letter-spacing:-0.02em;margin-top:16px;">想怎样开始这张画布?</div>
596
+ <p style="font-size:13px;color:var(--clado-ui-muted);margin:6px 0 0;line-height:1.6;">
597
+ 选择一个分析模板让「主架构师」快速读取源码并生成人可读的架构图,或直接从空白画布自由起稿。
598
+ </p>
599
+ <div class="clado-tpl-grid">
600
+ <button type="button" class="clado-tpl-btn selected" data-tpl="arch">
601
+ <svg class="clado-svg-ico" style="width:17px;height:17px;color:#0284c7;" viewBox="0 0 24 24"><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="8.5" y="14" width="7" height="7" rx="1.5"/><path d="M6.5 10v2h11v-2M12 12v2"/></svg>
602
+ <div style="font-size:13.5px;font-weight:610;margin-top:2px;">老代码架构梳理</div>
603
+ <div style="font-size:11.5px;color:var(--clado-ui-muted);line-height:1.55;">扫描模块边界、调用链与核心入口,自动铺出清晰卡片图。</div>
604
+ </button>
605
+ <button type="button" class="clado-tpl-btn" data-tpl="req">
606
+ <svg class="clado-svg-ico" style="width:17px;height:17px;color:#059669;" viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6M8 13h8M8 17h5"/></svg>
607
+ <div style="font-size:13.5px;font-weight:610;margin-top:2px;">新需求拆解设计</div>
608
+ <div style="font-size:11.5px;color:var(--clado-ui-muted);line-height:1.55;">把需求拆为数据契约、状态流转与风险清单,边改边定稿。</div>
609
+ </button>
610
+ <button type="button" class="clado-tpl-btn" data-tpl="qa">
611
+ <svg class="clado-svg-ico" style="width:17px;height:17px;color:#7c3aed;" viewBox="0 0 24 24"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
612
+ <div style="font-size:13.5px;font-weight:610;margin-top:2px;">测试与压测矩阵</div>
613
+ <div style="font-size:11.5px;color:var(--clado-ui-muted);line-height:1.55;">提炼主链路与异常分支,准备一键交付给测试角色跑通。</div>
614
+ </button>
615
+ </div>
616
+ <div style="display:flex;align-items:center;justify-content:space-between;margin-top:22px;padding-top:18px;border-top:1px solid var(--clado-ui-edge);">
617
+ <button type="button" class="clado-ui-button" data-empty-skip>跳过引导,新建空白画布</button>
618
+ <button type="button" class="clado-ui-button clado-ui-button-primary" data-empty-start style="padding:9px 20px;">开始分析并生成画布 →</button>
619
+ </div>
620
+ </div>
621
+ `;
622
+ emptyEl.querySelectorAll('[data-tpl]').forEach(btn => {
623
+ btn.onclick = () => {
624
+ selectedTpl = btn.dataset.tpl;
625
+ emptyEl.querySelectorAll('[data-tpl]').forEach(b => b.classList.toggle('selected', b === btn));
626
+ };
627
+ });
628
+ emptyEl.querySelector('[data-empty-skip]').onclick = () => createCanvasFlow('系统架构概览');
629
+ emptyEl.querySelector('[data-empty-start]').onclick = () => {
630
+ showToast('主架构师正在分析源码并绘制画布…');
631
+ window.CladoVNext?.startCodeAnalysis?.(selectedTpl);
632
+ };
633
+ if (discoveredWorkspaces.length) {
634
+ emptyWorkspaceSignature = '';
635
+ renderEmptyWorkspaces(discoveredWorkspaces);
423
636
  }
424
637
  }
638
+
639
+ if (config.canSwitchWorkspace && !offline) {
640
+ window.addEventListener('clado:open-workspace-picker', () => openLobby());
641
+ window.addEventListener('clado:meta-updated', () => {
642
+ if (lobbyEl && !lobbyEl.hidden) renderLobbyView(cachedHubData || {});
643
+ });
644
+ renderEmptyOnboarding({});
645
+ fetch('/library/fs-workspaces', { cache: 'no-store' })
646
+ .then(r => r.ok ? r.json() : null)
647
+ .then(data => {
648
+ if (!data) return;
649
+ cachedHubData = data;
650
+ renderEmptyOnboarding(data.currentProfile || {});
651
+ if (config.hubMode) openLobby();
652
+ })
653
+ .catch(() => { if (config.hubMode) openLobby(); });
654
+ }
425
655
  const liveObjectsEnabled = Boolean(config.selection && !offline && document.body);
426
656
  let canvasObjectsList = [];
427
657
  const objectSelection = new Map();
@@ -603,15 +833,119 @@
603
833
  addSep();
604
834
  addItem('删除此组件', () => deleteObject(obj.id), true);
605
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
+ });
606
910
  } else if (detail.kind === 'card' && detail.node) {
911
+ const targetNode = detail.cardNode || detail.node;
607
912
  const nodes = [...(aiSelection?.nodes || [])];
608
- const at = nodes.findIndex(n => JSON.stringify(n) === JSON.stringify(detail.node));
913
+ const at = nodes.findIndex(n => JSON.stringify(n) === JSON.stringify(targetNode));
609
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();
610
944
  addItem(at >= 0 ? '取消选中此卡片' : '选中此卡片', () => {
611
945
  const nextNodes = [...(aiSelection?.nodes || [])];
612
- const idx = nextNodes.findIndex(n => JSON.stringify(n) === JSON.stringify(detail.node));
946
+ const idx = nextNodes.findIndex(n => JSON.stringify(n) === JSON.stringify(targetNode));
613
947
  if (idx >= 0) nextNodes.splice(idx, 1);
614
- else nextNodes.push(detail.node);
948
+ else nextNodes.push(targetNode);
615
949
  setSelection(nextNodes.length ? { file: selected, version, nodes: nextNodes } : null);
616
950
  });
617
951
  addItem('旁边贴一张便签', () => {
@@ -619,28 +953,30 @@
619
953
  });
620
954
  } else {
621
955
  addLabel('画布空白处');
622
- addItem('+ 在此处新建便签', () => {
623
- saveObject({ kind: 'sticky', title: '灵感便签', pluginId: 'starter.sticky-notes', x: detail.wx, y: detail.wy, tint: 'amber', text: '记录一条新想法…' });
956
+ addItem('+ 在此处新建便签', () => {
957
+ saveObject({ kind: 'sticky', title: '设计便签', pluginId: 'starter.sticky-notes', x: detail.wx, y: detail.wy, tint: 'amber', text: '记录一条新想法…' });
624
958
  });
625
- addItem('+ 添加专注播放器组件', () => {
626
- saveObject({
627
- kind: 'music',
628
- title: 'Lo-Fi 专注播放器',
629
- pluginId: 'starter.lofi-player',
630
- x: detail.wx,
631
- y: detail.wy,
632
- width: 326,
633
- data: {
634
- expanded: false,
635
- selRenderMode: 'custom',
636
- tracks: [
637
- { id: 't1', title: 'Midnight Rain · 深夜雨声', duration: '03:24', liked: true },
638
- { id: 't2', title: 'Glass Horizon · 玻璃天际线', duration: '02:58', liked: false },
639
- { id: 't3', title: 'Soft Focus · 柔焦白噪音', duration: '04:12', liked: false },
640
- ],
641
- },
959
+ if (window.CladoVNext?.isComponentEnabled?.('lofi-studio-widget')) {
960
+ addItem('+ 添加 Lo-Fi 专注播放器', () => {
961
+ saveObject({
962
+ kind: 'music',
963
+ title: 'Lo-Fi 专注播放器',
964
+ pluginId: 'starter.lofi-player',
965
+ x: detail.wx,
966
+ y: detail.wy,
967
+ width: 326,
968
+ data: {
969
+ expanded: false,
970
+ selRenderMode: 'custom',
971
+ tracks: [
972
+ { id: 't1', title: 'Midnight Rain · 深夜雨声', duration: '03:24', liked: true },
973
+ { id: 't2', title: 'Glass Horizon · 玻璃天际线', duration: '02:58', liked: false },
974
+ { id: 't3', title: 'Soft Focus · 柔焦白噪音', duration: '04:12', liked: false },
975
+ ],
976
+ },
977
+ });
642
978
  });
643
- });
979
+ }
644
980
  addSep();
645
981
  addItem('居中复位画布', () => frame.contentWindow.CladoPrototype?.fit());
646
982
  }
@@ -666,8 +1002,7 @@
666
1002
  <button type="button" class="clado-selection-send" data-sel-send>发给当前会话</button>
667
1003
  <button type="button" class="clado-selection-clear" data-sel-clear>完成</button>`;
668
1004
  selectionBarEl.querySelector('[data-sel-send]').onclick = () => {
669
- const names = collectSelectionLabels().join('、');
670
- window.dispatchEvent(new CustomEvent('clado:send-selection', { detail: { names } }));
1005
+ window.CladoVNext?.focusComposer?.();
671
1006
  };
672
1007
  selectionBarEl.querySelector('[data-sel-clear]').onclick = () => {
673
1008
  objectSelection.clear();
@@ -675,7 +1010,7 @@
675
1010
  syncFrameObjects();
676
1011
  renderSelectionSummary();
677
1012
  };
678
- document.body.append(selectionBarEl);
1013
+ stageEl.append(selectionBarEl);
679
1014
 
680
1015
  canvasCtxMenuEl = document.createElement('div');
681
1016
  canvasCtxMenuEl.id = 'clado-canvas-ctx-menu';
@@ -726,21 +1061,370 @@
726
1061
  flushPendingTouch();
727
1062
  }
728
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
+
729
1413
  if (isEnabled('clado.agent')) window.CladoAgentPlugin(host, {
730
- placeholder: settings['clado.agent']?.placeholder,
731
- agentName: config.agentProfile === 'codex' ? 'Codex' : settings['clado.agent']?.name,
732
- endpoint: withWorkspace('/library/agent'),
733
- followAi,
734
- setFollowAi,
735
- focusTarget,
736
- readCanvas() {
1414
+ withWorkspace,
1415
+ setTheme: applyTheme,
1416
+ capture: captureShot,
1417
+ focusCanvas: (file, heading) => focusTarget(file, heading ? [heading] : null, heading || ''),
1418
+ focusTag,
1419
+ getCanvasEntities,
1420
+ openCodeFile: p => openCodeDrawerFile(p),
1421
+ readContext() {
737
1422
  const objSel = objectSelection.size ? [...objectSelection.values()] : undefined;
738
- if (readyCanvas?.frame !== frame) return objSel ? { objectSelection: objSel } : undefined;
1423
+ if (readyCanvas?.frame !== frame) return { file: selected || '', selection: [], ...(objSel ? { objectSelection: objSel } : {}) };
739
1424
  const { file, revision } = readyCanvas;
740
1425
  const selection = aiSelection?.file === file && aiSelection.version === revision ? aiSelection.nodes : [];
741
1426
  return { file, revision, selection, ...(objSel ? { objectSelection: objSel } : {}) };
742
1427
  },
743
- viewId: capabilities?.viewId,
744
1428
  });
745
1429
  if (!['light', 'dark'].includes(design.theme)) design.theme = 'light';
746
1430
  try { const savedTheme = localStorage.getItem('clado-theme'); if (['light', 'dark'].includes(savedTheme)) design.theme = savedTheme; } catch {}
@@ -811,35 +1495,64 @@
811
1495
  if(!chainModal) { const force=deferredRefresh;deferredRefresh=false;scan(force); }
812
1496
  }
813
1497
  function renderDirectory() { directory.update(index, selected, history.length > 0); }
814
- let emptyWorkspaceSignature = '';
815
1498
  function renderEmptyWorkspaces(list) {
816
- const others = list.filter(item => item.id !== workspaceId);
1499
+ discoveredWorkspaces = Array.isArray(list) ? list : [];
1500
+ const others = discoveredWorkspaces.filter(item => item.id !== workspaceId);
817
1501
  const next = JSON.stringify(others.map(item => [item.id, item.name, item.documents]));
818
- if (next === emptyWorkspaceSignature) return;
1502
+ if (next === emptyWorkspaceSignature && $('#emptyState .empty-workspaces')) return;
819
1503
  emptyWorkspaceSignature = next;
820
1504
  let container = $('#emptyState .empty-workspaces');
821
1505
  if (!others.length) { container?.remove(); return; }
1506
+ const hostEl = $('#emptyState .clado-empty-card') || $('#emptyState .clado-launchpad-card') || $('#emptyState');
822
1507
  if (!container) {
823
1508
  container = document.createElement('div');
824
1509
  container.className = 'empty-workspaces';
825
- ($('#emptyState .clado-launchpad-card') || $('#emptyState')).append(container);
1510
+ hostEl.append(container);
1511
+ } else if (container.parentElement !== hostEl) {
1512
+ hostEl.append(container);
826
1513
  }
827
1514
  container.replaceChildren();
1515
+ const head = document.createElement('div');
1516
+ head.className = 'empty-workspaces-head';
828
1517
  const title = document.createElement('div');
829
1518
  title.className = 'empty-workspaces-title';
830
- title.textContent = '已发现的子工作区(点击打开)';
831
- 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';
832
1528
  for (const item of others) {
833
1529
  const link = document.createElement('a');
834
1530
  link.className = 'empty-workspace-card';
835
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';
836
1541
  const name = document.createElement('span');
837
- name.textContent = item.id || (item.name + '(根目录)');
1542
+ name.className = 'empty-workspace-name';
1543
+ name.textContent = label;
838
1544
  const count = document.createElement('small');
839
1545
  count.textContent = (item.documents ?? 0) + ' 份画布';
840
- link.append(name, count);
841
- 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);
842
1554
  }
1555
+ container.append(grid);
843
1556
  }
844
1557
  let renderRequest = 0;
845
1558
  async function openFromCapability(file) {
@@ -874,15 +1587,85 @@
874
1587
  if (readyCanvas?.frame !== frame || readyCanvas?.file !== file) throw failure('NAVIGATION_FAILED', '目标画布已被另一次导航替换。');
875
1588
  return { file, title: targetDocument.title, mode };
876
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
+ }
877
1599
  async function open(file, anchor = '', options = {}) {
878
1600
  if(modalLocked()) { if(options.update)deferredRefresh=true;return; }
879
1601
  pendingAnchor=anchor;
880
1602
  const doc = index.documents.find(d => d.file === file);
881
1603
  if (!doc) { directory.showMessage('这个 Markdown 暂未收录', file + ' 不在有效画布目录中。可以让 AI 检查文件路径和解析状态。'); return; }
882
1604
  if (selected && file !== selected && !options.back) history.push(selected);
883
- if (options.update && readyCanvas?.frame === frame && readyCanvas.file === file) { try { pendingView = frame.contentWindow.CladoPrototype?.captureView?.(); } catch {} }
884
- 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
+ }
885
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
+
886
1669
  selected = file; version = doc.version; saveView(); renderDirectory(); syncChrome();
887
1670
  $('#updateError').hidden = true; $('#emptyState').hidden = true; $('#canvasLoading').hidden = false;
888
1671
  // Give each render its own browsing context. A late ready/message from the
@@ -913,14 +1696,23 @@
913
1696
  $('#updateError').textContent = '画布读取失败,保留上次画面并自动重试。'; $('#updateError').hidden = false; status('当前画布未更新', true);
914
1697
  }
915
1698
  }
916
- let pendingRescan = false, pendingTouch = null;
1699
+ let pendingRescan = false, pendingTouch = null, pendingPrevDoc = null;
917
1700
  function flushPendingTouch() {
918
- if (!pendingTouch || Date.now() - pendingTouch.ts > 6000) { pendingTouch = null; return; }
919
- if (pendingTouch.file && pendingTouch.file !== selected) return;
920
1701
  if (readyCanvas?.frame !== frame || readyCanvas.file !== selected) return;
921
- const payload = pendingTouch;
922
- pendingTouch = null;
923
- 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;
924
1716
  try { frame.contentWindow.postMessage({ type: 'clado-workspace:ai-touch', ...payload, follow }, offline ? '*' : location.origin); } catch {}
925
1717
  }
926
1718
  const status = (message, error) => directory.status(message, error);
@@ -959,7 +1751,7 @@
959
1751
  const doc = index.documents.find(d => d.file === selected);
960
1752
  if (!doc && !version && index.documents.length) open(index.documents[0].file);
961
1753
  else if (!doc) { $('#updateError').textContent = '当前 Markdown 已删除或暂时无法解析,保留上次画面。有效文档仍可从目录打开。'; $('#updateError').hidden = false; status('当前画布未更新', true); $('#canvasLoading').hidden = true; post('ready'); }
962
- 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 })); } }
963
1755
  }
964
1756
  } catch { if (pageHidden) return; status('连接中断,正在重连', true); $('#updateError').textContent = '目录连接中断,保留当前画面。服务恢复后自动重连。'; $('#updateError').hidden = false; $('#canvasLoading').hidden = true; post('ready'); }
965
1757
  finally {
@@ -997,6 +1789,65 @@
997
1789
  openCanvasCtxMenu((rect.left || 0) + (data.x || 0), (rect.top || 0) + (data.y || 0), data.detail);
998
1790
  return;
999
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
+ }
1000
1851
  if (data?.type === 'clado-library:chain-modal') { chainLock(data.value, data.mode); return; }
1001
1852
  if (data?.type === 'clado-library:lens-modal') {
1002
1853
  lensOpen = !!data.value;
@@ -1029,6 +1880,8 @@
1029
1880
  }
1030
1881
  showSelection();
1031
1882
  syncFrameObjects();
1883
+ syncPresenceConfigToCanvas();
1884
+ syncPresenceSnapshotToCanvas();
1032
1885
  if(offline){frame.contentWindow.postMessage({type:'clado-workspace:display',mode,theme:design.theme,anchor:pendingAnchor},'*');pendingAnchor='';}
1033
1886
  else if (mode !== data.mode) frame.contentWindow.CladoPrototype?.setMode?.(mode);
1034
1887
  saveView(); $('#canvasLoading').hidden = true; syncChrome();
@@ -1045,8 +1898,254 @@
1045
1898
  status('已同步 ' + new Date(index.documents.find(d => d.file === selected)?.modified || Date.now()).toLocaleTimeString('zh-CN', { hour12: false })); post('ready');
1046
1899
  }
1047
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
+ });
1048
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(); }
1049
- 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() };
1050
2149
  setDesign(design);
1051
2150
  scan();
1052
2151
  if (!offline) {
@@ -1058,7 +2157,13 @@
1058
2157
  es.addEventListener('doc.updated', event => {
1059
2158
  try {
1060
2159
  const payload = JSON.parse(event.data || '{}');
1061
- 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
+ }
1062
2167
  } catch {}
1063
2168
  scan(true);
1064
2169
  });
@@ -1073,12 +2178,44 @@
1073
2178
  }
1074
2179
  } catch {}
1075
2180
  });
2181
+ es.addEventListener('agent.presence', event => {
2182
+ try {
2183
+ const payload = JSON.parse(event.data || '{}');
2184
+ applyPresenceEventToRegistry(payload);
2185
+ } catch {}
2186
+ });
1076
2187
  es.addEventListener('agent.focus', event => {
1077
2188
  try {
1078
2189
  const payload = JSON.parse(event.data || '{}');
1079
2190
  focusTarget(payload.file || selected, payload.nodes?.[0] || null, payload.label || '');
1080
2191
  } catch {}
1081
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
+ });
1082
2219
  es.addEventListener('agent.sessions', event => {
1083
2220
  try {
1084
2221
  const payload = JSON.parse(event.data || '{}');
@@ -1087,7 +2224,18 @@
1087
2224
  }
1088
2225
  } catch {}
1089
2226
  });
1090
- 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
+ }
1091
2239
  addEventListener('pagehide', () => es.close());
1092
2240
  } catch {}
1093
2241
  }
@@ -1100,4 +2248,77 @@
1100
2248
  }
1101
2249
  }, 1200);
1102
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
+ }
1103
2324
  })();