cladogram 0.6.0-beta.3 → 0.6.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -120,6 +120,260 @@
120
120
  });
121
121
  }
122
122
 
123
+ /* ══ ①-b 富媒体块渲染注册表(SVG 矢量/动画、UI 沙盒预览、可扩展插件入口) ═══ */
124
+
125
+ var CladoBlockRegistry = (function () {
126
+ var handlers = [];
127
+ return {
128
+ register: function (match, renderFn) {
129
+ if (typeof renderFn !== 'function') return;
130
+ handlers.push({ match: match, render: renderFn });
131
+ },
132
+ resolve: function (lang, codeText, ctx) {
133
+ for (var i = handlers.length - 1; i >= 0; i--) {
134
+ var h = handlers[i];
135
+ var ok = typeof h.match === 'function'
136
+ ? h.match(lang, codeText)
137
+ : Array.isArray(h.match)
138
+ ? h.match.indexOf(lang) >= 0
139
+ : h.match === lang;
140
+ if (ok) {
141
+ var out = h.render(codeText, lang, ctx);
142
+ if (out) return out;
143
+ }
144
+ }
145
+ return null;
146
+ },
147
+ list: function () { return handlers.slice(); },
148
+ };
149
+ })();
150
+ window.CladoBlockRegistry = CladoBlockRegistry;
151
+
152
+ var CLADO_SVG_TAGS = new Set(
153
+ 'svg g defs symbol use title desc path circle ellipse rect line polyline polygon text tspan textpath lineargradient radialgradient stop clippath mask pattern marker filter fegaussianblur fedropshadow feoffset femerge femergenode fecolormatrix feblend feflood fecomposite style animate animatetransform animatemotion mpath set'.split(' ')
154
+ );
155
+
156
+ function sanitizeSvgMarkup(raw) {
157
+ var src = String(raw || '').trim();
158
+ if (!src || src.indexOf('<svg') < 0) return null;
159
+ var svg = null;
160
+ try {
161
+ var parsed = new DOMParser().parseFromString(src, 'image/svg+xml');
162
+ if (parsed && !parsed.querySelector('parsererror') && parsed.documentElement && parsed.documentElement.localName === 'svg') {
163
+ svg = document.importNode(parsed.documentElement, true);
164
+ }
165
+ } catch (e) {}
166
+ if (!svg) {
167
+ var tpl = document.createElement('template');
168
+ tpl.innerHTML = src;
169
+ var found = tpl.content.querySelector('svg');
170
+ if (found) svg = found.cloneNode(true);
171
+ }
172
+ if (!svg) return null;
173
+
174
+ var cleanNode = function (el) {
175
+ var tag = String(el.localName || el.tagName || '').toLowerCase();
176
+ if (!CLADO_SVG_TAGS.has(tag)) {
177
+ el.remove();
178
+ return;
179
+ }
180
+ Array.from(el.attributes || []).forEach(function (attr) {
181
+ var name = String(attr.name || '').toLowerCase();
182
+ var val = String(attr.value || '');
183
+ if (/^on/.test(name)) { el.removeAttribute(attr.name); return; }
184
+ if (name === 'href' || name === 'xlink:href') {
185
+ if (!/^#[a-zA-Z0-9_.:-]+$/.test(val.trim())) el.removeAttribute(attr.name);
186
+ return;
187
+ }
188
+ if (name === 'style' && /(?:javascript:|expression\s*\(|@import|url\s*\(\s*['"]?\s*(?:https?:|data:|javascript:))/i.test(val)) {
189
+ el.removeAttribute(attr.name);
190
+ return;
191
+ }
192
+ if (/javascript:/i.test(val.replace(/[\x00-\x20]/g, ''))) {
193
+ el.removeAttribute(attr.name);
194
+ }
195
+ });
196
+ if (tag === 'style') {
197
+ el.textContent = String(el.textContent || '')
198
+ .replace(/@import[^;]*;?/gi, '')
199
+ .replace(/expression\s*\([^)]*\)/gi, '')
200
+ .replace(/javascript:/gi, '')
201
+ .replace(/-moz-binding\s*:[^;]*;?/gi, '')
202
+ .replace(/url\s*\(\s*['"]?\s*(?:https?:|data:|javascript:)[^)]*\)/gi, '');
203
+ return;
204
+ }
205
+ Array.from(el.children || []).forEach(cleanNode);
206
+ };
207
+ cleanNode(svg);
208
+
209
+ if (!svg.getAttribute('viewBox')) {
210
+ var w = parseFloat(svg.getAttribute('width') || '');
211
+ var h = parseFloat(svg.getAttribute('height') || '');
212
+ if (w > 0 && h > 0) svg.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
213
+ }
214
+ return svg;
215
+ }
216
+
217
+ var cladoUiFrameSeq = 0;
218
+ var cladoUiFrames = new Map();
219
+ window.addEventListener('message', function (ev) {
220
+ var d = ev.data;
221
+ if (!d || d.type !== 'clado-ui-height' || !d.id) return;
222
+ var fr = cladoUiFrames.get(String(d.id));
223
+ if (!fr || !fr.isConnected) { cladoUiFrames.delete(String(d.id)); return; }
224
+ var nextH = Math.max(180, Math.min(540, Math.ceil(Number(d.height) || 260)));
225
+ if (Math.abs((parseInt(fr.style.height, 10) || 260) - nextH) > 4) {
226
+ fr.style.height = nextH + 'px';
227
+ if (document.body.dataset.mode === 'cards') {
228
+ try { repinPorts(); drawWires(); } catch (e) {}
229
+ }
230
+ }
231
+ });
232
+
233
+ function buildUiSandboxDoc(rawCode, frameId) {
234
+ var src = String(rawCode || '');
235
+ var dark = document.documentElement.dataset.theme === 'dark';
236
+ var baseStyle =
237
+ '<style>'
238
+ + ':root{color-scheme:' + (dark ? 'dark' : 'light') + ';--bg:' + (dark ? '#0f172a' : '#f8fafc') + ';--surface:' + (dark ? '#1e293b' : '#ffffff') + ';--text:' + (dark ? '#f1f5f9' : '#0f172a') + ';--muted:' + (dark ? '#94a3b8' : '#64748b') + ';--border:' + (dark ? 'rgba(148,163,184,.22)' : 'rgba(15,23,42,.10)') + ';--accent:#0ea5e9;}'
239
+ + '*,*::before,*::after{box-sizing:border-box}'
240
+ + 'html,body{margin:0;padding:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Noto Sans SC",sans-serif;background:var(--bg);color:var(--text);font-size:13px;line-height:1.5;-webkit-font-smoothing:antialiased}'
241
+ + 'body{padding:12px}'
242
+ + 'button,input,select,textarea{font:inherit}'
243
+ + '</style>';
244
+ var resizeHook = frameId
245
+ ? ('\x3cscript>(function(){var id=' + JSON.stringify(frameId) + ';function send(){try{var h=Math.max(document.body?document.body.scrollHeight:0,document.documentElement?document.documentElement.scrollHeight:0);parent.postMessage({type:"clado-ui-height",id:id,height:h},"*");}catch(e){}}window.addEventListener("load",send);if(typeof ResizeObserver==="function"){new ResizeObserver(send).observe(document.documentElement);}setTimeout(send,60);setTimeout(send,240);})();\x3c/script>')
246
+ : '';
247
+ if (/^\s*<!doctype|^\s*<html\b/i.test(src)) {
248
+ if (/<\/head>/i.test(src)) src = src.replace(/<\/head>/i, baseStyle + '</head>');
249
+ if (resizeHook && /<\/body>/i.test(src)) src = src.replace(/<\/body>/i, resizeHook + '</body>');
250
+ else if (resizeHook) src += resizeHook;
251
+ return src;
252
+ }
253
+ return '<!DOCTYPE html><html lang="zh-CN" data-theme="' + (dark ? 'dark' : 'light') + '"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
254
+ + baseStyle + '</head><body>' + src + resizeHook + '</body></html>';
255
+ }
256
+
257
+ function createUiPreviewBlock(rawCode, preEl) {
258
+ var wrap = document.createElement('div');
259
+ wrap.className = 'zoomable zui';
260
+ wrap.dataset.label = 'UI 原型预览';
261
+
262
+ var bar = document.createElement('div');
263
+ bar.className = 'zblock-bar';
264
+ bar.innerHTML =
265
+ '<span class="zblock-title">UI 原型预览</span>'
266
+ + '<span class="zblock-actions">'
267
+ + '<button type="button" class="zblock-btn active" data-ui-vp="desktop">桌面</button>'
268
+ + '<button type="button" class="zblock-btn" data-ui-vp="mobile">手机</button>'
269
+ + '<button type="button" class="zblock-btn" data-ui-zoom>放大</button>'
270
+ + '<button type="button" class="zblock-btn" data-ui-mode>代码</button>'
271
+ + '</span>';
272
+
273
+ var stage = document.createElement('div');
274
+ stage.className = 'zui-stage';
275
+ var frameId = 'ui_' + (++cladoUiFrameSeq);
276
+ var iframe = document.createElement('iframe');
277
+ iframe.className = 'zui-frame';
278
+ iframe.setAttribute('sandbox', 'allow-scripts');
279
+ iframe.setAttribute('loading', 'lazy');
280
+ iframe.setAttribute('title', 'UI 原型预览');
281
+ iframe.dataset.uiFrameId = frameId;
282
+ iframe._cladoUiSource = rawCode;
283
+ iframe.srcdoc = buildUiSandboxDoc(rawCode, frameId);
284
+ cladoUiFrames.set(frameId, iframe);
285
+ stage.appendChild(iframe);
286
+
287
+ preEl.classList.add('zui-code');
288
+ wrap.appendChild(bar);
289
+ wrap.appendChild(stage);
290
+ wrap.appendChild(preEl);
291
+
292
+ var deskBtn = bar.querySelector('[data-ui-vp="desktop"]');
293
+ var mobBtn = bar.querySelector('[data-ui-vp="mobile"]');
294
+ var zoomBtn = bar.querySelector('[data-ui-zoom]');
295
+ var modeBtn = bar.querySelector('[data-ui-mode]');
296
+
297
+ deskBtn.addEventListener('click', function (ev) {
298
+ ev.stopPropagation();
299
+ wrap.classList.remove('is-mobile');
300
+ deskBtn.classList.add('active');
301
+ mobBtn.classList.remove('active');
302
+ });
303
+ mobBtn.addEventListener('click', function (ev) {
304
+ ev.stopPropagation();
305
+ wrap.classList.add('is-mobile');
306
+ mobBtn.classList.add('active');
307
+ deskBtn.classList.remove('active');
308
+ });
309
+ modeBtn.addEventListener('click', function (ev) {
310
+ ev.stopPropagation();
311
+ var showCode = wrap.classList.toggle('is-code');
312
+ modeBtn.textContent = showCode ? '预览' : '代码';
313
+ modeBtn.classList.toggle('active', showCode);
314
+ if (document.body.dataset.mode === 'cards') { try { repinPorts(); drawWires(); } catch (e) {} }
315
+ });
316
+ zoomBtn.addEventListener('click', function (ev) {
317
+ ev.stopPropagation();
318
+ var lensHtml = '<iframe class="zui-lens-frame" sandbox="allow-scripts" title="UI 原型全屏预览"></iframe>';
319
+ openLens(lensHtml, 'UI 原型预览', 'ui');
320
+ var lensFr = $('#lensInner .zui-lens-frame');
321
+ if (lensFr) lensFr.srcdoc = buildUiSandboxDoc(rawCode, '');
322
+ });
323
+ return wrap;
324
+ }
325
+
326
+ CladoBlockRegistry.register('svg', function (rawCode, lang, ctx) {
327
+ var cleanSvg = sanitizeSvgMarkup(rawCode);
328
+ if (!cleanSvg) return null;
329
+ var wrap = document.createElement('div');
330
+ wrap.className = 'zoomable zsvg';
331
+ wrap.dataset.label = 'SVG 矢量图';
332
+
333
+ var bar = document.createElement('div');
334
+ bar.className = 'zblock-bar';
335
+ bar.innerHTML =
336
+ '<span class="zblock-title">SVG 矢量图</span>'
337
+ + '<span class="zblock-actions">'
338
+ + '<button type="button" class="zblock-btn" data-svg-zoom>放大</button>'
339
+ + '<button type="button" class="zblock-btn" data-svg-mode>源码</button>'
340
+ + '</span>';
341
+
342
+ var stage = document.createElement('div');
343
+ stage.className = 'zsvg-stage';
344
+ stage.title = '点一下放大';
345
+ stage.appendChild(cleanSvg);
346
+
347
+ var preEl = ctx.pre;
348
+ if (window.hljs && ctx.code) { try { hljs.highlightElement(ctx.code); } catch (e) {} }
349
+ preEl.classList.add('zsvg-code');
350
+
351
+ wrap.appendChild(bar);
352
+ wrap.appendChild(stage);
353
+ wrap.appendChild(preEl);
354
+
355
+ var modeBtn = bar.querySelector('[data-svg-mode]');
356
+ var zoomBtn = bar.querySelector('[data-svg-zoom]');
357
+ modeBtn.addEventListener('click', function (ev) {
358
+ ev.stopPropagation();
359
+ var showCode = wrap.classList.toggle('is-code');
360
+ modeBtn.textContent = showCode ? '视图' : '源码';
361
+ modeBtn.classList.toggle('active', showCode);
362
+ if (document.body.dataset.mode === 'cards') { try { repinPorts(); drawWires(); } catch (e) {} }
363
+ });
364
+ zoomBtn.addEventListener('click', function (ev) {
365
+ ev.stopPropagation();
366
+ var svgEl = $('.zsvg-stage svg', wrap);
367
+ if (svgEl) openLens(svgEl.outerHTML, 'SVG 矢量图', 'media');
368
+ });
369
+ return wrap;
370
+ });
371
+
372
+ CladoBlockRegistry.register(['ui', 'html-preview'], function (rawCode, lang, ctx) {
373
+ if (window.hljs && ctx.code) { try { hljs.highlightElement(ctx.code); } catch (e) {} }
374
+ return createUiPreviewBlock(rawCode, ctx.pre);
375
+ });
376
+
123
377
  /**
124
378
  * 一段原文 Markdown → 一个 `.markdown-body` 元素。
125
379
  *
@@ -145,6 +399,46 @@
145
399
  });
146
400
  box.appendChild(template.content);
147
401
 
402
+ // 媒体交付件升级:![说明](demo.mp4/.webm/.mov) → 原生视频播放器;.mp3/.wav/.m4a → 原生音频播放器
403
+ $$('img[src]', box).forEach(function (img) {
404
+ var src = img.getAttribute('src') || '';
405
+ var alt = (img.getAttribute('alt') || '').trim();
406
+ if (/\.(?:mp4|webm|mov|ogv)(?:[?#].*)?$/i.test(src)) {
407
+ var vw = document.createElement('div');
408
+ vw.className = 'zvideo';
409
+ var video = document.createElement('video');
410
+ video.setAttribute('controls', '');
411
+ video.setAttribute('playsinline', '');
412
+ video.setAttribute('preload', 'metadata');
413
+ video.setAttribute('src', src);
414
+ vw.appendChild(video);
415
+ if (alt) {
416
+ var vcap = document.createElement('div');
417
+ vcap.className = 'zmedia-cap';
418
+ vcap.textContent = alt;
419
+ vw.appendChild(vcap);
420
+ }
421
+ img.parentNode.replaceChild(vw, img);
422
+ return;
423
+ }
424
+ if (/\.(?:mp3|wav|m4a|ogg|flac)(?:[?#].*)?$/i.test(src)) {
425
+ var aw = document.createElement('div');
426
+ aw.className = 'zaudio';
427
+ if (alt) {
428
+ var acap = document.createElement('div');
429
+ acap.className = 'zmedia-cap';
430
+ acap.textContent = alt;
431
+ aw.appendChild(acap);
432
+ }
433
+ var audio = document.createElement('audio');
434
+ audio.setAttribute('controls', '');
435
+ audio.setAttribute('preload', 'metadata');
436
+ audio.setAttribute('src', src);
437
+ aw.appendChild(audio);
438
+ img.parentNode.replaceChild(aw, img);
439
+ }
440
+ });
441
+
148
442
  // 表格:左右到顶、列多了自己左右滑、点一下能放大
149
443
  $$('table', box).forEach(function (t) {
150
444
  var shell = document.createElement('div');
@@ -158,11 +452,12 @@
158
452
  shell.appendChild(sc);
159
453
  });
160
454
 
161
- // 代码:先把 mermaid 挑出来(它交给 mermaid 渲染),其余交给 hljs 上色,都点得开
455
+ // 代码:依次经过 mermaid / CladoBlockRegistry(svg、ui、扩展块)/ hljs 代码块
162
456
  $$('pre > code', box).forEach(function (code) {
163
457
  var pre = code.parentNode;
164
458
  var m = /(?:^|\s)language-([\w+#.-]+)/.exec(code.className || '');
165
459
  var lang = m ? m[1].toLowerCase() : '';
460
+ var rawCode = code.textContent || '';
166
461
  if (lang === 'mermaid') {
167
462
  var wrap = document.createElement('div');
168
463
  wrap.className = 'zoomable';
@@ -170,11 +465,22 @@
170
465
  wrap.title = '点一下放大';
171
466
  var d = document.createElement('div');
172
467
  d.className = 'mermaid';
173
- d.dataset.src = code.textContent; // 浏览器已经把实体解回来了
468
+ d.dataset.src = rawCode; // 浏览器已经把实体解回来了
174
469
  wrap.appendChild(d);
175
470
  pre.parentNode.replaceChild(wrap, pre);
176
471
  return;
177
472
  }
473
+ var effectiveLang = (lang === 'html' && /^\s*<!--\s*(?:preview|ui)\s*-->/i.test(rawCode)) ? 'ui' : lang;
474
+ var origParent = pre.parentNode;
475
+ var origNext = pre.nextSibling;
476
+ var customBlock = CladoBlockRegistry.resolve(effectiveLang, rawCode, { pre: pre, code: code });
477
+ if (customBlock) {
478
+ if (origParent) {
479
+ origParent.insertBefore(customBlock, origNext);
480
+ if (pre.parentNode === origParent) origParent.removeChild(pre);
481
+ }
482
+ return;
483
+ }
178
484
  if (window.hljs) { try { hljs.highlightElement(code); } catch (e) { /* 高亮挂了也得能看 */ } }
179
485
  var z = document.createElement('div');
180
486
  z.className = 'zoomable zcode';
@@ -182,6 +488,20 @@
182
488
  z.title = '点一下放大';
183
489
  pre.parentNode.insertBefore(z, pre);
184
490
  z.appendChild(pre);
491
+ if (lang === 'html') {
492
+ var prevBtn = document.createElement('button');
493
+ prevBtn.type = 'button';
494
+ prevBtn.className = 'zcode-preview-btn';
495
+ prevBtn.textContent = '预览';
496
+ prevBtn.title = '在隔离沙盒中实时预览此 HTML';
497
+ prevBtn.addEventListener('click', function (ev) {
498
+ ev.stopPropagation();
499
+ var uiBlock = createUiPreviewBlock(rawCode, pre);
500
+ if (z.parentNode) z.parentNode.replaceChild(uiBlock, z);
501
+ if (document.body.dataset.mode === 'cards') { try { repinPorts(); drawWires(); } catch (e) {} }
502
+ });
503
+ z.appendChild(prevBtn);
504
+ }
185
505
  });
186
506
 
187
507
  $$('pre code', box).forEach(linkifyCode);
@@ -1360,7 +1680,18 @@
1360
1680
  var pointer = null, dragged = false, sx = 0, sy = 0, ox = 0, oy = 0;
1361
1681
  document.addEventListener('click', function (e) {
1362
1682
  var z = e.target.closest('.zoomable');
1363
- if (z && !e.target.closest('a.edge')) {
1683
+ if (z && !e.target.closest('a.edge,.zblock-bar,.zblock-btn,.zcode-preview-btn,iframe,video,audio')) {
1684
+ if (z.classList.contains('zui') && !z.classList.contains('is-code')) return;
1685
+ if (z.classList.contains('zsvg')) {
1686
+ if (z.classList.contains('is-code')) {
1687
+ var svgCode = $('pre', z);
1688
+ if (svgCode) openLens(svgCode.outerHTML, 'SVG 源码', 'code');
1689
+ } else {
1690
+ var svgNode = $('.zsvg-stage svg', z);
1691
+ if (svgNode) openLens(svgNode.outerHTML, z.dataset.label, 'media');
1692
+ }
1693
+ return;
1694
+ }
1364
1695
  var media = $('svg,img', z), code = $('pre', z), tbl = $('table', z);
1365
1696
  if (media) openLens(media.outerHTML, z.dataset.label, 'media');
1366
1697
  else if (code) openLens(code.outerHTML, z.dataset.label, 'code');
@@ -1478,6 +1809,11 @@
1478
1809
  function setTheme(t, save) {
1479
1810
  document.documentElement.dataset.theme = t;
1480
1811
  if (save !== false) { try { localStorage.setItem('clado-theme', t); } catch (e) {} }
1812
+ $$('.zui-frame').forEach(function (fr) {
1813
+ if (fr._cladoUiSource != null) {
1814
+ fr.srcdoc = buildUiSandboxDoc(fr._cladoUiSource, fr.dataset.uiFrameId || '');
1815
+ }
1816
+ });
1481
1817
  renderMermaid(true).then(afterMedia);
1482
1818
  document.dispatchEvent(new CustomEvent('clado:view-state'));
1483
1819
  }
@@ -17,6 +17,7 @@ import {
17
17
  deletePiSkill,
18
18
  deleteProviderConfig,
19
19
  deleteRole,
20
+ ensureCladoPlatformDocs,
20
21
  importPiMcpJson,
21
22
  inspectPiEcosystem,
22
23
  installPiPackage,
@@ -26,9 +27,11 @@ import {
26
27
  readCanvasComponentsConfig,
27
28
  readRuntimeSettings,
28
29
  removePiPackage,
30
+ resetCladoPlatformDocs,
29
31
  resolvePiAgentDir,
30
32
  resolveRole,
31
33
  saveAgentsMemory,
34
+ saveCladoPlatformContext,
32
35
  savePiMcpServer,
33
36
  savePiPrompt,
34
37
  savePiSkill,
@@ -171,6 +174,7 @@ export function createAgentHandler({
171
174
  const runtimeSettings = readRuntimeSettings(rt.workspace, agentDir, modelsInfo.activeContextWindow);
172
175
  const roles = listRoles(agentDir);
173
176
  const memory = readAgentsMemory(rt.workspace);
177
+ const platformDocs = ensureCladoPlatformDocs(agentDir);
174
178
  const canvasComponents = readCanvasComponentsConfig(agentDir);
175
179
  const sessions = listSessions(rt.stateDir, { includeArchived: true, agentDir });
176
180
 
@@ -193,6 +197,7 @@ export function createAgentHandler({
193
197
  canvasComponents,
194
198
  workspacePlugins: rt.pluginDescriptors,
195
199
  memory,
200
+ platformDocs,
196
201
  sessions,
197
202
  };
198
203
  }
@@ -373,6 +378,16 @@ export function createAgentHandler({
373
378
  sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
374
379
  return;
375
380
  }
381
+ if (action === 'save_platform_context') {
382
+ const result = saveCladoPlatformContext(body.content, agentDir);
383
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
384
+ return;
385
+ }
386
+ if (action === 'reset_platform_context') {
387
+ const result = resetCladoPlatformDocs(agentDir);
388
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
389
+ return;
390
+ }
376
391
  if (action === 'toggle_canvas_component') {
377
392
  const canvasComponents = toggleCanvasComponent(body.id, body.enabled, agentDir);
378
393
  sendJson(res, 200, { ok: true, canvasComponents, meta: await buildFullMeta(targetWorkspace) });
@@ -82,13 +82,13 @@
82
82
  return window.__CLADO_RESOURCES__?.[path] || (window.__CLADO_OFFLINE__ ? null : '/library/resource?file='+encodeURIComponent(path)+workspace);
83
83
  }
84
84
  function rewriteDocumentLinks() {
85
- document.querySelectorAll('img[src]:not([data-resource])').forEach(img=>{
86
- const src=img.getAttribute('src');if (!src || /^(?:[a-z][a-z0-9+.-]*:|\/\/|\/)/i.test(src))return;
87
- try { const url=resourceUrl(src);if(url){img.dataset.resource='1';img.src=url;} } catch {}
85
+ document.querySelectorAll('img[src]:not([data-resource]),video[src]:not([data-resource]),audio[src]:not([data-resource])').forEach(el=>{
86
+ const src=el.getAttribute('src');if (!src || /^(?:[a-z][a-z0-9+.-]*:|\/\/|\/)/i.test(src))return;
87
+ try { const url=resourceUrl(src);if(url){el.dataset.resource='1';el.src=url;} } catch {}
88
88
  });
89
89
  document.querySelectorAll('a[href]:not(.edge):not([data-resource])').forEach(a=>{
90
90
  const href=a.getAttribute('href');if (!href || /^(?:[a-z][a-z0-9+.-]*:|\/\/|\/|#)/i.test(href) || /\.mdc?(?:#|$)/i.test(href))return;
91
- if (!/\.(?:png|jpe?g|gif|webp|svg|pdf|txt|csv|json)(?:#|$)/i.test(href))return;
91
+ if (!/\.(?:png|jpe?g|gif|webp|svg|pdf|txt|csv|json|mp4|webm|mov|ogv|mp3|wav|m4a|ogg|flac)(?:#|$)/i.test(href))return;
92
92
  try { const url=resourceUrl(href);if(url){a.dataset.resource='1';a.href=url;} } catch {}
93
93
  });
94
94
  document.querySelectorAll('a[href]:not(.edge):not([data-canvas-file])').forEach(a => {
@@ -662,6 +662,14 @@
662
662
  runtime.highlightActivity?.(event.data);
663
663
  return;
664
664
  }
665
+ if (event.data?.type === 'clado-workspace:presence') {
666
+ runtime.setCardPresence?.(event.data.presence);
667
+ return;
668
+ }
669
+ if (event.data?.type === 'clado-workspace:presence-config') {
670
+ runtime.setPresenceConfig?.(event.data.config);
671
+ return;
672
+ }
665
673
  if (event.data?.type === 'clado-workspace:live-diff') {
666
674
  runtime.playLiveDiff?.(event.data.prevDoc, event.data.touch, event.data.follow);
667
675
  return;
@@ -1803,6 +1803,15 @@
1803
1803
  openCodeDrawerFile(data.ref);
1804
1804
  return;
1805
1805
  }
1806
+ if (data?.type === 'clado-library:presence-click') {
1807
+ if (data.sessionId || data.roleId) {
1808
+ window.dispatchEvent(new CustomEvent('clado:focus-session', {
1809
+ detail: { sessionId: data.sessionId || '', roleId: data.roleId || '' },
1810
+ }));
1811
+ }
1812
+ if (data.codePath) openCodeDrawerFile(data.codePath);
1813
+ return;
1814
+ }
1806
1815
  if (data?.type === 'clado-library:chain-modal') { chainLock(data.value, data.mode); return; }
1807
1816
  if (data?.type === 'clado-library:lens-modal') {
1808
1817
  lensOpen = !!data.value;
@@ -1835,6 +1844,7 @@
1835
1844
  }
1836
1845
  showSelection();
1837
1846
  syncFrameObjects();
1847
+ syncPresenceConfigToCanvas();
1838
1848
  if(offline){frame.contentWindow.postMessage({type:'clado-workspace:display',mode,theme:design.theme,anchor:pendingAnchor},'*');pendingAnchor='';}
1839
1849
  else if (mode !== data.mode) frame.contentWindow.CladoPrototype?.setMode?.(mode);
1840
1850
  saveView(); $('#canvasLoading').hidden = true; syncChrome();
@@ -1851,6 +1861,29 @@
1851
1861
  status('已同步 ' + new Date(index.documents.find(d => d.file === selected)?.modified || Date.now()).toLocaleTimeString('zh-CN', { hour12: false })); post('ready');
1852
1862
  }
1853
1863
  });
1864
+ function readPresenceAfterglowMs() {
1865
+ try {
1866
+ const raw = localStorage.getItem('clado-presence-ttl');
1867
+ if (raw !== null && raw !== '') {
1868
+ const sec = Number(raw);
1869
+ if (Number.isFinite(sec) && sec >= 0) return Math.round(sec * 1000);
1870
+ }
1871
+ } catch {}
1872
+ return 15000;
1873
+ }
1874
+ function syncPresenceConfigToCanvas(overrideMs) {
1875
+ if (readyCanvas?.frame !== frame) return;
1876
+ const afterglowMs = typeof overrideMs === 'number' && Number.isFinite(overrideMs) ? overrideMs : readPresenceAfterglowMs();
1877
+ try {
1878
+ frame.contentWindow.postMessage({
1879
+ type: 'clado-workspace:presence-config',
1880
+ config: { afterglowMs },
1881
+ }, offline ? '*' : location.origin);
1882
+ } catch {}
1883
+ }
1884
+ addEventListener('clado:presence-config', ev => {
1885
+ syncPresenceConfigToCanvas(ev.detail?.afterglowMs);
1886
+ });
1854
1887
  function setDesign(next) { design = { ...design, ...next }; document.documentElement.dataset.theme = design.theme || 'light'; if (design.accent) document.documentElement.style.setProperty('--accent', design.accent); try { frame.contentWindow.CladoPrototype?.setDesign(design); } catch {} syncChrome(); }
1855
1888
  window.CladoPrototype = { setDesign, fit: () => frame.contentWindow.CladoPrototype?.fit(), closeLens: () => frame.contentWindow.CladoPrototype?.closeLens() };
1856
1889
  setDesign(design);
@@ -1885,6 +1918,14 @@
1885
1918
  }
1886
1919
  } catch {}
1887
1920
  });
1921
+ es.addEventListener('agent.presence', event => {
1922
+ try {
1923
+ const payload = JSON.parse(event.data || '{}');
1924
+ if (readyCanvas?.frame === frame && (!payload.file || payload.file === selected || payload.phase === 'afterglow' || payload.phase === 'clear')) {
1925
+ frame.contentWindow.postMessage({ type: 'clado-workspace:presence', presence: payload }, location.origin);
1926
+ }
1927
+ } catch {}
1928
+ });
1888
1929
  es.addEventListener('agent.focus', event => {
1889
1930
  try {
1890
1931
  const payload = JSON.parse(event.data || '{}');
@@ -1926,7 +1967,7 @@
1926
1967
  } catch {}
1927
1968
  });
1928
1969
  es.onerror = () => { sseReady = false; pushDebugLog('sse', 'SSE 连接中断,正在重试'); };
1929
- for (const evtName of ['ready', 'doc.updated', 'agent.activity', 'agent.stage', 'canvas.draft', 'code.activity', 'code.diff']) {
1970
+ for (const evtName of ['ready', 'doc.updated', 'agent.activity', 'agent.presence', 'agent.stage', 'canvas.draft', 'code.activity', 'code.diff']) {
1930
1971
  es.addEventListener(evtName, ev => pushDebugLog('sse', evtName + (ev.data ? ' ' + String(ev.data).slice(0, 140) : '')));
1931
1972
  }
1932
1973
  addEventListener('pagehide', () => es.close());
@@ -31,7 +31,12 @@ import {
31
31
  import { readFileGitState, readWorkspaceCodeFile, resolveSymbolInWorkspace } from './code-inspect.js';
32
32
  import { z } from 'zod/v4';
33
33
  const assets = join(dirname(fileURLToPath(import.meta.url)), 'assets');
34
- const resourceTypes = {png:'image/png',jpg:'image/jpeg',jpeg:'image/jpeg',gif:'image/gif',webp:'image/webp',svg:'image/svg+xml',pdf:'application/pdf',txt:'text/plain',csv:'text/csv',json:'application/json'};
34
+ const resourceTypes = {
35
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml',
36
+ pdf: 'application/pdf', txt: 'text/plain', csv: 'text/csv', json: 'application/json',
37
+ mp4: 'video/mp4', webm: 'video/webm', mov: 'video/quicktime', ogv: 'video/ogg',
38
+ mp3: 'audio/mpeg', wav: 'audio/wav', m4a: 'audio/mp4', ogg: 'audio/ogg', flac: 'audio/flac',
39
+ };
35
40
  const types = { html: 'text/html', css: 'text/css', js: 'text/javascript', json: 'application/json', md: 'text/markdown' };
36
41
  const REMOTE_COOKIE = 'clado_remote_token';
37
42