cladogram 0.6.0-beta.4 → 0.6.0-beta.6

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.
@@ -62,10 +62,14 @@
62
62
  let text = normalized.replace(/```([a-zA-Z0-9_+-]*)[ \t]*\n([\s\S]*?)(?:```|$)/g, (_, lang, code) => {
63
63
  const idx = fences.length;
64
64
  const cleanCode = code.replace(/\n$/, '');
65
+ const lowLang = String(lang || '').toLowerCase();
66
+ const canPreview = lowLang === 'svg' || lowLang === 'ui' || lowLang === 'html' || lowLang === 'html-preview';
65
67
  fences.push(
66
68
  `<div class="clado-md-pre">`
67
69
  + `<div class="clado-md-pre-head"><span>${esc(lang || 'code')}</span>`
68
- + `<button type="button" class="clado-dock-mini-btn" data-copy-code style="padding:1px 6px;font-size:10.5px;">复制</button></div>`
70
+ + `<span style="display:inline-flex;align-items:center;gap:4px;">`
71
+ + (canPreview ? `<button type="button" class="clado-dock-mini-btn" data-preview-code="${esc(lowLang)}" style="padding:1px 6px;font-size:10.5px;">预览放大</button>` : '')
72
+ + `<button type="button" class="clado-dock-mini-btn" data-copy-code style="padding:1px 6px;font-size:10.5px;">复制</button></span></div>`
69
73
  + `<pre class="clado-scroll"><code>${esc(cleanCode)}</code></pre></div>`
70
74
  );
71
75
  return `\n\u0000FENCE${idx}\u0000\n`;
@@ -233,13 +237,6 @@
233
237
  </div>
234
238
  <div class="clado-session-pop" data-session-pop hidden></div>
235
239
  <div class="clado-dock-stream clado-scroll" data-stream></div>
236
- <div class="clado-dock-handoff">
237
- <span style="color:var(--clado-ui-subtle);">流转至下一阶段</span>
238
- <div style="display:flex;align-items:center;gap:6px;">
239
- <button type="button" class="clado-dock-mini-btn" style="border-color:var(--clado-ui-well-border);background:var(--clado-ui-well);" data-quick-handoff="developer">交给开发落地</button>
240
- <button type="button" class="clado-dock-mini-btn" style="border-color:var(--clado-ui-well-border);background:var(--clado-ui-well);" data-quick-handoff="tester">交给测试验证</button>
241
- </div>
242
- </div>
243
240
  </div>
244
241
  </div>
245
242
 
@@ -419,11 +416,11 @@
419
416
  if (sendMode === 'ctrl-enter') {
420
417
  sendModeBtn.textContent = 'Ctrl↵ 发送';
421
418
  sendModeBtn.title = '当前:Enter 换行,Ctrl/⌘+Enter 发送(点击切换为 Enter 发送)';
422
- inputEl.placeholder = '输入需求、敲 / 调命令(Enter 换行,Ctrl+Enter 发送)…';
419
+ inputEl.placeholder = '输入需求,敲 / 调命令、@ 引用卡片或文件(Enter 换行,Ctrl+Enter 发送)…';
423
420
  } else {
424
421
  sendModeBtn.textContent = '↵ 发送';
425
422
  sendModeBtn.title = '当前:Enter 发送,Shift+Enter 换行(点击切换为 Ctrl+Enter 发送)';
426
- inputEl.placeholder = '输入需求、敲 / 调命令(Enter 发送,Shift+Enter 换行)…';
423
+ inputEl.placeholder = '输入需求,敲 / 调命令、@ 引用卡片或文件(Enter 发送,Shift+Enter 换行)…';
427
424
  }
428
425
  }
429
426
  syncSendModeUi();
@@ -827,6 +824,10 @@
827
824
  }
828
825
 
829
826
  let renderStreamTimer = 0;
827
+ let loadingHistoryFor = '';
828
+ let scrollTrimTimer = 0;
829
+ let suppressScrollAutoLoad = false;
830
+
830
831
  function scheduleRenderStream() {
831
832
  if (renderStreamTimer) return;
832
833
  renderStreamTimer = setTimeout(() => {
@@ -835,7 +836,62 @@
835
836
  }, 48);
836
837
  }
837
838
 
838
- function renderStream() {
839
+ async function loadOlderMessages(sessionId) {
840
+ const s = sessions.find(x => x.id === sessionId);
841
+ if (!s || !s.hasMoreBefore) return;
842
+ const before = typeof s.oldestIndex === 'number' ? s.oldestIndex : 0;
843
+ if (before <= 0 || loadingHistoryFor === sessionId) return;
844
+ loadingHistoryFor = sessionId;
845
+ const existingBtn = streamEl.querySelector('.clado-history-loader');
846
+ if (existingBtn) {
847
+ existingBtn.disabled = true;
848
+ existingBtn.textContent = '正在从磁盘按需加载更早记录…';
849
+ }
850
+ try {
851
+ const res = await fetch(withWs(`/library/agent/sessions?id=${encodeURIComponent(sessionId)}&limit=30&before=${before}`), { cache: 'no-store' });
852
+ if (!res.ok) return;
853
+ const data = await res.json();
854
+ const older = Array.isArray(data.messages) ? data.messages : [];
855
+ if (older.length) {
856
+ const prevScrollHeight = streamEl.scrollHeight;
857
+ const prevScrollTop = streamEl.scrollTop;
858
+ s.messages = older.concat(Array.isArray(s.messages) ? s.messages : []);
859
+ s.oldestIndex = typeof data.oldestIndex === 'number' ? data.oldestIndex : Math.max(0, before - older.length);
860
+ s.hasMoreBefore = Boolean(data.hasMoreBefore);
861
+ if (typeof data.totalMessages === 'number') s.totalMessages = data.totalMessages;
862
+ if (activeSessionId === sessionId) {
863
+ renderStream({ preserveScroll: { prevScrollHeight, prevScrollTop } });
864
+ }
865
+ } else {
866
+ s.hasMoreBefore = false;
867
+ s.oldestIndex = 0;
868
+ if (activeSessionId === sessionId) renderStream({ preserveScroll: { prevScrollHeight: streamEl.scrollHeight, prevScrollTop: streamEl.scrollTop } });
869
+ }
870
+ } catch {
871
+ showToast('加载更早历史失败,请重试');
872
+ } finally {
873
+ loadingHistoryFor = '';
874
+ const btn = streamEl.querySelector('.clado-history-loader');
875
+ if (btn && activeSessionId === sessionId) {
876
+ btn.disabled = false;
877
+ }
878
+ }
879
+ }
880
+
881
+ function trimOldMessagesInMemory() {
882
+ const s = currentSession();
883
+ if (!s || s.status === 'running' || loadingHistoryFor === s.id) return;
884
+ if (!Array.isArray(s.messages) || s.messages.length <= 60) return;
885
+ const distFromBottom = streamEl.scrollHeight - streamEl.scrollTop - streamEl.clientHeight;
886
+ if (distFromBottom > 80) return;
887
+ const dropped = s.messages.length - 40;
888
+ s.messages = s.messages.slice(-40);
889
+ s.oldestIndex = (typeof s.oldestIndex === 'number' ? s.oldestIndex : 0) + dropped;
890
+ s.hasMoreBefore = true;
891
+ renderStream({ stickToBottom: true });
892
+ }
893
+
894
+ function renderStream(opts = {}) {
839
895
  if (renderStreamTimer) {
840
896
  clearTimeout(renderStreamTimer);
841
897
  renderStreamTimer = 0;
@@ -850,18 +906,32 @@
850
906
  modelChip.textContent = (modelLabel.includes('/') ? modelLabel.split('/').pop() : modelLabel) + ' ▾';
851
907
  renderContextMeter();
852
908
 
853
- const wasNearBottom = (streamEl.scrollHeight - streamEl.scrollTop - streamEl.clientHeight) < 60;
909
+ const wasNearBottom = opts.stickToBottom || (streamEl.scrollHeight - streamEl.scrollTop - streamEl.clientHeight) < 60;
854
910
 
855
911
  const msgs = Array.isArray(s.messages) ? s.messages : [];
912
+ const oldestIdx = typeof s.oldestIndex === 'number' ? s.oldestIndex : 0;
913
+ const hasMoreBefore = Boolean(s.hasMoreBefore && oldestIdx > 0);
856
914
  streamEl.replaceChildren();
857
- if (!msgs.length) {
915
+ if (!msgs.length && !hasMoreBefore) {
858
916
  const empty = document.createElement('div');
859
917
  empty.className = 'clado-dock-empty';
860
- empty.innerHTML = `当前会话:<strong>${esc(s.title)}</strong>(Pi 1.0 引擎)<br/>可直接描述架构修改、输入 <code>/</code> 调命令,或在画布选中卡片派活交付。<br/>拖动顶部居中横条可调整窗口高度,点击标题可切换或新建会话。`;
918
+ empty.innerHTML = `当前会话:<strong>${esc(s.title)}</strong>(Pi 1.0 引擎)<br/>可直接描述需求、输入 <code>/</code> 调命令、<code>@</code> 引用卡片或文件,或在画布选中卡片发给当前会话。<br/>拖动顶部居中横条可调整窗口高度,点击标题可切换或新建会话。`;
861
919
  streamEl.append(empty);
862
920
  return;
863
921
  }
864
922
 
923
+ if (hasMoreBefore) {
924
+ const loader = document.createElement('button');
925
+ loader.type = 'button';
926
+ loader.className = 'clado-history-loader';
927
+ loader.disabled = loadingHistoryFor === s.id;
928
+ loader.textContent = loadingHistoryFor === s.id
929
+ ? '正在从磁盘按需加载更早记录…'
930
+ : `上滑或点击加载更早记录(还有 ${oldestIdx} 条已移出内存)`;
931
+ loader.onclick = () => loadOlderMessages(s.id);
932
+ streamEl.append(loader);
933
+ }
934
+
865
935
  const pendingDecisionCards = [];
866
936
 
867
937
  for (let idx = 0; idx < msgs.length; idx++) {
@@ -869,15 +939,20 @@
869
939
  const isLast = idx === msgs.length - 1;
870
940
  if (m.role === 'user') {
871
941
  const div = document.createElement('div');
872
- div.className = 'clado-msg-user' + (m.isSteer ? ' is-steer' : '');
873
- const prefix = m.isSteer ? '[中途纠偏] ' : (m.handoffFrom ? `[交接自 ${m.handoffFrom}]\n` : '');
942
+ const isPeer = Boolean(m.peerFrom) || String(m.text || '').startsWith('[来自「');
943
+ div.className = 'clado-msg-user' + (m.isSteer ? ' is-steer' : '') + (isPeer ? ' is-peer' : '');
944
+ const prefix = m.isSteer
945
+ ? '[中途插话] '
946
+ : (m.handoffFrom
947
+ ? `[交接自 ${m.handoffFrom}]\n`
948
+ : (m.peerFrom && !String(m.text || '').startsWith('[来自') ? `[来自 ${m.peerFrom}]\n` : ''));
874
949
  div.textContent = prefix + (m.text || '');
875
950
  streamEl.append(div);
876
951
  } else {
877
- const msgKey = m.id || `${s.id}_${idx}`;
952
+ const msgKey = m.id || `${s.id}_${oldestIdx + idx}`;
878
953
  const isRunningMsg = isLast && s.status === 'running';
879
954
 
880
- // 1. Render ordered interleaved blocks (thinking -> text -> tools -> text -> ...)
955
+ // 1. Render ordered interleaved blocks (thinking -> text -> tools -> steer -> text -> ...)
881
956
  if (Array.isArray(m.blocks) && m.blocks.length) {
882
957
  for (let bIdx = 0; bIdx < m.blocks.length; bIdx++) {
883
958
  const block = m.blocks[bIdx];
@@ -886,6 +961,11 @@
886
961
  streamEl.append(buildThinkingTrace(`${msgKey}_th${bIdx}`, block.text));
887
962
  } else if (block?.type === 'tools' && Array.isArray(block.tools) && block.tools.length) {
888
963
  streamEl.append(buildToolTrace(`${msgKey}_b${bIdx}`, block.tools, isRunningMsg && isLastBlock));
964
+ } else if (block?.type === 'steer' && block.text && block.text.trim()) {
965
+ const sdiv = document.createElement('div');
966
+ sdiv.className = 'clado-msg-user is-steer';
967
+ sdiv.textContent = '[中途插话] ' + block.text;
968
+ streamEl.append(sdiv);
889
969
  } else if (block?.type === 'text' && block.text && block.text.trim()) {
890
970
  const div = document.createElement('div');
891
971
  div.className = 'clado-msg-assistant clado-md';
@@ -943,12 +1023,84 @@
943
1023
  sendBtn.textContent = pendingDecisionCards.length ? '回复' : '插话';
944
1024
  }
945
1025
 
946
- if (wasNearBottom || s.status === 'running' || pendingDecisionCards.length) {
1026
+ suppressScrollAutoLoad = true;
1027
+ if (opts.preserveScroll) {
1028
+ const delta = streamEl.scrollHeight - opts.preserveScroll.prevScrollHeight;
1029
+ streamEl.scrollTop = Math.max(0, opts.preserveScroll.prevScrollTop + delta);
1030
+ } else if (wasNearBottom || s.status === 'running' || pendingDecisionCards.length) {
947
1031
  streamEl.scrollTop = streamEl.scrollHeight;
948
1032
  }
1033
+ requestAnimationFrame(() => { suppressScrollAutoLoad = false; });
949
1034
  }
950
1035
 
951
- // Copy code button & clickable card/tag chip delegation inside stream
1036
+ streamEl.addEventListener('scroll', () => {
1037
+ if (suppressScrollAutoLoad) return;
1038
+ const s = currentSession();
1039
+ if (!s) return;
1040
+ if (streamEl.scrollTop < 48 && s.hasMoreBefore && (s.oldestIndex || 0) > 0 && loadingHistoryFor !== s.id) {
1041
+ loadOlderMessages(s.id);
1042
+ return;
1043
+ }
1044
+ if (Array.isArray(s.messages) && s.messages.length > 60) {
1045
+ const distFromBottom = streamEl.scrollHeight - streamEl.scrollTop - streamEl.clientHeight;
1046
+ if (distFromBottom < 80) {
1047
+ clearTimeout(scrollTrimTimer);
1048
+ scrollTrimTimer = setTimeout(trimOldMessagesInMemory, 350);
1049
+ }
1050
+ }
1051
+ }, { passive: true });
1052
+
1053
+ let chatPreviewMask = null;
1054
+ function openChatCodePreview(lang, rawCode) {
1055
+ if (!chatPreviewMask) {
1056
+ chatPreviewMask = document.createElement('div');
1057
+ chatPreviewMask.id = 'clado-chat-preview-modal';
1058
+ chatPreviewMask.className = 'clado-vnext-mask';
1059
+ chatPreviewMask.hidden = true;
1060
+ stageRoot().append(chatPreviewMask);
1061
+ chatPreviewMask.addEventListener('click', ev => {
1062
+ if (ev.target === chatPreviewMask) chatPreviewMask.hidden = true;
1063
+ });
1064
+ }
1065
+ const isSvg = lang === 'svg';
1066
+ const isDark = document.documentElement.dataset.theme === 'dark';
1067
+ const bg = isDark ? '#0f172a' : '#f8fafc';
1068
+ const fg = isDark ? '#f1f5f9' : '#0f172a';
1069
+ let bodySrc = String(rawCode || '');
1070
+ if (isSvg) {
1071
+ let svgSrc = bodySrc.trim();
1072
+ if (!/\bxmlns\s*=/i.test(svgSrc)) svgSrc = svgSrc.replace(/<svg\b/i, '<svg xmlns="http://www.w3.org/2000/svg"');
1073
+ svgSrc = svgSrc.replace(/<script\b[\s\S]*?<\/script>/gi, '').replace(/\son[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, '');
1074
+ bodySrc = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"><style>html,body{margin:0;width:100%;height:100%;display:grid;place-items:center;background:${bg};overflow:auto;padding:20px;box-sizing:border-box}svg{max-width:100%;max-height:100%;width:auto;height:auto;transition:transform 140ms ease}</style></head><body>${svgSrc}</body></html>`;
1075
+ } else if (!/^\s*<!doctype|^\s*<html\b/i.test(bodySrc)) {
1076
+ bodySrc = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style>*,*::before,*::after{box-sizing:border-box}html,body{margin:0;padding:14px;background:${bg};color:${fg};font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC",sans-serif;font-size:13px;line-height:1.5}</style></head><body>${bodySrc}</body></html>`;
1077
+ }
1078
+ chatPreviewMask.innerHTML = `
1079
+ <div class="clado-well-box" style="width:min(1040px,calc(100% - 36px));height:min(760px,calc(100% - 36px));display:flex;flex-direction:column;gap:10px;padding:14px 16px;border-radius:18px;background:var(--clado-ui-popover);backdrop-filter:blur(26px) saturate(190%);-webkit-backdrop-filter:blur(26px) saturate(190%);border:1px solid var(--clado-ui-glass-outline);box-shadow:var(--clado-ui-glass-shadow);">
1080
+ <div style="display:flex;align-items:center;justify-content:space-between;gap:8px;">
1081
+ <strong style="font-size:13.5px;">${isSvg ? 'SVG 矢量放大预览' : 'HTML / UI 隔离沙盒预览'}</strong>
1082
+ <div style="display:inline-flex;align-items:center;gap:6px;">
1083
+ ${!isSvg ? '<button type="button" class="clado-dock-mini-btn" data-cp-vp="desktop">桌面</button><button type="button" class="clado-dock-mini-btn" data-cp-vp="mobile">手机 (375px)</button>' : ''}
1084
+ <button type="button" class="clado-dock-mini-btn" data-cp-close>关闭</button>
1085
+ </div>
1086
+ </div>
1087
+ <div style="flex:1;min-height:0;display:flex;justify-content:center;align-items:stretch;overflow:hidden;border-radius:12px;border:1px solid var(--clado-ui-edge);background:${bg};">
1088
+ <iframe data-cp-frame sandbox="allow-scripts" title="预览" style="border:0;width:100%;height:100%;background:${bg};transition:width 180ms ease;"></iframe>
1089
+ </div>
1090
+ </div>
1091
+ `;
1092
+ const fr = chatPreviewMask.querySelector('[data-cp-frame]');
1093
+ if (fr) fr.srcdoc = bodySrc;
1094
+ chatPreviewMask.querySelector('[data-cp-close]').onclick = () => { chatPreviewMask.hidden = true; };
1095
+ chatPreviewMask.querySelectorAll('[data-cp-vp]').forEach(b => {
1096
+ b.onclick = () => {
1097
+ if (fr) fr.style.width = b.dataset.cpVp === 'mobile' ? '375px' : '100%';
1098
+ };
1099
+ });
1100
+ chatPreviewMask.hidden = false;
1101
+ }
1102
+
1103
+ // Copy code, preview SVG/HTML & clickable card/tag chip delegation inside stream
952
1104
  streamEl.addEventListener('click', e => {
953
1105
  const refTag = e.target.closest?.('[data-ref-tag]');
954
1106
  if (refTag) {
@@ -960,6 +1112,12 @@
960
1112
  actions.focusCanvas?.(null, refCard.dataset.refCard);
961
1113
  return;
962
1114
  }
1115
+ const prevCodeBtn = e.target.closest?.('[data-preview-code]');
1116
+ if (prevCodeBtn) {
1117
+ const code = prevCodeBtn.closest('.clado-md-pre')?.querySelector('pre code')?.textContent || '';
1118
+ openChatCodePreview(prevCodeBtn.dataset.previewCode, code);
1119
+ return;
1120
+ }
963
1121
  const btn = e.target.closest?.('[data-copy-code]');
964
1122
  if (!btn) return;
965
1123
  const code = btn.closest('.clado-md-pre')?.querySelector('pre code')?.textContent || '';
@@ -1002,6 +1160,10 @@
1002
1160
  function renderSessionPop() {
1003
1161
  const activeCount = sessions.filter(s => !s.archived).length;
1004
1162
  const archivedCount = sessions.filter(s => s.archived).length;
1163
+ const runningCount = Math.max(
1164
+ sessions.filter(s => s.status === 'running').length,
1165
+ Array.isArray(meta?.activeRuns) ? meta.activeRuns.length : 0
1166
+ );
1005
1167
  const list = sessions
1006
1168
  .filter(s => (sessionFilter === 'archived' ? s.archived : !s.archived))
1007
1169
  .slice()
@@ -1013,7 +1175,10 @@
1013
1175
  <button type="button" class="clado-dock-mini-btn" data-sf="active" style="${sessionFilter === 'active' ? 'background:var(--clado-ui-prism-bg);border-color:var(--clado-ui-prism-border);color:var(--clado-ui-prism-text);' : ''}">进行中 (${activeCount})</button>
1014
1176
  <button type="button" class="clado-dock-mini-btn" data-sf="archived" style="${sessionFilter === 'archived' ? 'background:var(--clado-ui-prism-bg);border-color:var(--clado-ui-prism-border);color:var(--clado-ui-prism-text);' : ''}">已归档 (${archivedCount})</button>
1015
1177
  </div>
1016
- <button type="button" class="clado-ui-button clado-ui-button-primary" data-sp-new style="min-height:24px;padding:2px 9px;font-size:11px;">+ 新建会话</button>
1178
+ <div style="display:inline-flex;align-items:center;gap:4px;">
1179
+ ${runningCount > 0 ? `<button type="button" class="clado-dock-mini-btn" data-sp-abort-all style="color:#be123c;border-color:rgba(244,63,94,0.35);">全部停止 (${runningCount})</button>` : ''}
1180
+ <button type="button" class="clado-ui-button clado-ui-button-primary" data-sp-new style="min-height:24px;padding:2px 9px;font-size:11px;">+ 新建会话</button>
1181
+ </div>
1017
1182
  </div>
1018
1183
  <div class="clado-session-list clado-scroll" data-sp-list></div>
1019
1184
  `;
@@ -1025,6 +1190,25 @@
1025
1190
  renderSessionPop();
1026
1191
  };
1027
1192
  });
1193
+ const abortAllBtn = sessionPopEl.querySelector('[data-sp-abort-all]');
1194
+ if (abortAllBtn) {
1195
+ abortAllBtn.onclick = async e => {
1196
+ e.stopPropagation();
1197
+ try {
1198
+ const res = await fetch(withWs('/library/agent/sessions'), {
1199
+ method: 'POST',
1200
+ headers: { 'content-type': 'application/json' },
1201
+ body: JSON.stringify({ action: 'abort_all' }),
1202
+ });
1203
+ const data = await res.json().catch(() => ({}));
1204
+ showToast(`已发送全局停止指令(中止 ${data.stoppedCount || 0} 个会话)`);
1205
+ await refreshMeta();
1206
+ renderSessionPop();
1207
+ } catch {
1208
+ showToast('全局停止请求失败');
1209
+ }
1210
+ };
1211
+ }
1028
1212
  sessionPopEl.querySelector('[data-sp-new]').onclick = e => {
1029
1213
  e.stopPropagation();
1030
1214
  createNewSessionForCurrentRole();
@@ -1039,7 +1223,7 @@
1039
1223
  for (const item of list) {
1040
1224
  const row = document.createElement('div');
1041
1225
  row.className = 'clado-session-row' + (item.id === activeSessionId ? ' active' : '');
1042
- const msgCount = Array.isArray(item.messages) ? item.messages.length : 0;
1226
+ const msgCount = typeof item.totalMessages === 'number' ? item.totalMessages : (Array.isArray(item.messages) ? item.messages.length : 0);
1043
1227
 
1044
1228
  if (renamingSessionId === item.id) {
1045
1229
  row.innerHTML = `
@@ -1315,36 +1499,399 @@
1315
1499
  popoverEl.hidden = false;
1316
1500
  }
1317
1501
 
1318
- function updateSlashPopover() {
1319
- const val = inputEl.value;
1320
- if (!val.startsWith('/') || val.includes('\n')) {
1321
- if (!popoverEl.hidden && popoverEl.dataset.kind === 'slash') closePopover();
1322
- return;
1502
+ const BUILTIN_SLASH_COMMANDS = [
1503
+ { name: 'arch', badge: '画布', description: '梳理源码架构调用链并绘制画布', kind: 'prompt' },
1504
+ { name: 'review', badge: '评审', description: '深度评审当前画布或关联代码风险', kind: 'prompt' },
1505
+ { name: 'test', badge: '测试', description: '生成单元测试与边界异常验证矩阵', kind: 'prompt' },
1506
+ { name: 'diff', badge: '验收', description: '结合 Git Diff 验收代码并同步画布', kind: 'prompt' },
1507
+ { name: 'svg', badge: '图形', description: '绘制矢量架构图 / 流程图(SVG)', kind: 'prompt' },
1508
+ { name: 'ui', badge: '原型', description: '生成高保真交互式界面原型(UI)', kind: 'prompt' },
1509
+ { name: 'new', badge: '快捷', description: '为当前角色新建一段独立会话', kind: 'local' },
1510
+ { name: 'compact', badge: '快捷', description: '立即压缩当前会话长上下文', kind: 'local' },
1511
+ { name: 'model', badge: '快捷', description: '快速切换当前会话主力模型', kind: 'local' },
1512
+ { name: 'rollback', badge: '快捷', description: '回退当前画布至上一轮快照', kind: 'local' },
1513
+ { name: 'settings', badge: '快捷', description: '打开统一设置中心', kind: 'local' },
1514
+ ];
1515
+
1516
+ const mentionCache = {
1517
+ filesTs: 0,
1518
+ files: [],
1519
+ docsTs: 0,
1520
+ docs: [],
1521
+ cardsFile: '',
1522
+ cardsTs: 0,
1523
+ cards: [],
1524
+ fetching: false,
1525
+ };
1526
+
1527
+ let composerMenuItems = [];
1528
+ let composerMenuIndex = 0;
1529
+ let composerMenuRange = null; // { start, end, kind }
1530
+
1531
+ async function ensureMentionSources(force = false) {
1532
+ const now = Date.now();
1533
+ const ctx = actions.readContext ? (actions.readContext() || {}) : {};
1534
+ const curFile = String(ctx.file || '').trim();
1535
+ const tasks = [];
1536
+
1537
+ if (force || now - mentionCache.filesTs > 10000) {
1538
+ tasks.push(
1539
+ fetch(withWs('/library/workspace-files'), { cache: 'no-store' })
1540
+ .then(r => (r.ok ? r.json() : null))
1541
+ .then(d => {
1542
+ if (d && Array.isArray(d.files)) {
1543
+ mentionCache.files = d.files;
1544
+ mentionCache.filesTs = Date.now();
1545
+ }
1546
+ })
1547
+ .catch(() => {})
1548
+ );
1549
+ }
1550
+ if (force || now - mentionCache.docsTs > 10000) {
1551
+ tasks.push(
1552
+ fetch(withWs('/library/index.json'), { cache: 'no-store' })
1553
+ .then(r => (r.ok ? r.json() : null))
1554
+ .then(d => {
1555
+ if (d && Array.isArray(d.documents)) {
1556
+ mentionCache.docs = d.documents;
1557
+ mentionCache.docsTs = Date.now();
1558
+ }
1559
+ })
1560
+ .catch(() => {})
1561
+ );
1562
+ }
1563
+ if (curFile && (force || mentionCache.cardsFile !== curFile || now - mentionCache.cardsTs > 6000)) {
1564
+ const docUrl = withWs('/library/doc.json') + (withWs('/library/doc.json').includes('?') ? '&' : '?') + 'file=' + encodeURIComponent(curFile);
1565
+ tasks.push(
1566
+ fetch(docUrl, { cache: 'no-store' })
1567
+ .then(r => (r.ok ? r.json() : null))
1568
+ .then(d => {
1569
+ const cards = Array.isArray(d?.doc?.cards) ? d.doc.cards : [];
1570
+ mentionCache.cards = cards.map(c => String(c?.title || c?.id || '').trim()).filter(Boolean);
1571
+ mentionCache.cardsFile = curFile;
1572
+ mentionCache.cardsTs = Date.now();
1573
+ })
1574
+ .catch(() => {})
1575
+ );
1576
+ }
1577
+ if (tasks.length && !mentionCache.fetching) {
1578
+ mentionCache.fetching = true;
1579
+ try {
1580
+ await Promise.all(tasks);
1581
+ } finally {
1582
+ mentionCache.fetching = false;
1583
+ }
1584
+ return true;
1585
+ }
1586
+ return false;
1587
+ }
1588
+
1589
+ async function executeLocalSlashCommand(cmdName) {
1590
+ const cmd = String(cmdName || '').replace(/^\/+/, '').trim().toLowerCase();
1591
+ if (cmd === 'settings' || cmd === 'config') {
1592
+ openSettings('models');
1593
+ return true;
1594
+ }
1595
+ if (cmd === 'model' || cmd === 'models') {
1596
+ popoverEl.dataset.kind = 'model';
1597
+ openModelPopover();
1598
+ return true;
1599
+ }
1600
+ if (cmd === 'new' || cmd === 'clear') {
1601
+ const cur = currentSession();
1602
+ const roleId = cur?.roleId || 'architect';
1603
+ try {
1604
+ const res = await fetch(withWs('/library/agent/sessions'), {
1605
+ method: 'POST',
1606
+ headers: { 'content-type': 'application/json' },
1607
+ body: JSON.stringify({ action: 'create', roleId }),
1608
+ });
1609
+ const data = await res.json();
1610
+ if (res.ok && data.session) {
1611
+ await refreshMeta();
1612
+ selectSession(data.session.id, true);
1613
+ showToast('已为当前角色新建会话');
1614
+ }
1615
+ } catch {
1616
+ showToast('新建会话失败,请稍后重试');
1617
+ }
1618
+ return true;
1619
+ }
1620
+ if (cmd === 'compact') {
1621
+ const s = currentSession();
1622
+ if (!s) return true;
1623
+ if (runningSessionId) {
1624
+ showToast('当前回合正在运行,结束后再压缩上下文');
1625
+ return true;
1626
+ }
1627
+ showToast('正在压缩上下文…');
1628
+ try {
1629
+ const res = await fetch(withWs('/library/agent/sessions'), {
1630
+ method: 'POST',
1631
+ headers: { 'content-type': 'application/json' },
1632
+ body: JSON.stringify({ action: 'compact', id: s.id }),
1633
+ });
1634
+ const data = await res.json().catch(() => ({}));
1635
+ if (!res.ok) throw new Error(data.error || '压缩失败');
1636
+ await refreshMeta();
1637
+ showToast(data.skipped ? (data.reason || '当前无需压缩') : '上下文压缩完成');
1638
+ } catch (err) {
1639
+ showToast(err?.message || '上下文压缩失败');
1640
+ }
1641
+ return true;
1642
+ }
1643
+ if (cmd === 'rollback' || cmd === 'undo') {
1644
+ dock.querySelector('[data-rollback]')?.click();
1645
+ return true;
1323
1646
  }
1324
- const q = val.slice(1).toLowerCase();
1325
- const prompts = (meta?.ecosystem?.prompts || []).filter(p => !q || p.name.toLowerCase().includes(q));
1326
- if (!prompts.length) {
1327
- if (popoverEl.dataset.kind === 'slash') closePopover();
1647
+ return false;
1648
+ }
1649
+
1650
+ function tryMatchLocalSlashCommand(rawText) {
1651
+ const m = String(rawText || '').trim().match(/^\/(new|clear|compact|model|models|settings|config|rollback|undo)$/i);
1652
+ return m ? m[1].toLowerCase() : '';
1653
+ }
1654
+
1655
+ function renderComposerAutocomplete(kind, headerHint, items, range) {
1656
+ composerMenuItems = items;
1657
+ composerMenuRange = range;
1658
+ if (!items.length) {
1659
+ if (popoverEl.dataset.kind === 'slash' || popoverEl.dataset.kind === 'mention') closePopover();
1328
1660
  return;
1329
1661
  }
1330
- popoverEl.dataset.kind = 'slash';
1662
+ if (composerMenuIndex >= items.length || composerMenuIndex < 0) composerMenuIndex = 0;
1663
+ popoverEl.dataset.kind = kind;
1331
1664
  popoverEl.replaceChildren();
1332
- for (const p of prompts.slice(0, 8)) {
1665
+
1666
+ const head = document.createElement('div');
1667
+ head.className = 'clado-pop-head';
1668
+ head.innerHTML = `<span>${esc(headerHint)}</span><span>↑↓ 选择 · Tab / Enter 确认</span>`;
1669
+ popoverEl.append(head);
1670
+
1671
+ items.forEach((item, idx) => {
1333
1672
  const btn = document.createElement('button');
1334
1673
  btn.type = 'button';
1335
- btn.className = 'clado-pop-item';
1336
- btn.innerHTML = `<span style="font-family:ui-monospace,monospace;">/${esc(p.name)}</span><span style="color:var(--clado-ui-subtle);font-size:11px;">${esc(p.description || p.scope)}</span>`;
1337
- btn.onclick = () => {
1338
- inputEl.value = '/' + p.name + ' ';
1339
- autoGrowInput();
1340
- closePopover();
1341
- inputEl.focus();
1674
+ btn.className = 'clado-pop-item' + (idx === composerMenuIndex ? ' is-selected' : '');
1675
+ btn.dataset.menuIdx = String(idx);
1676
+ btn.innerHTML = `
1677
+ <span class="clado-pop-main">
1678
+ <span class="clado-pop-badge">${esc(item.badge || '')}</span>
1679
+ <span class="clado-pop-label">${esc(item.display)}</span>
1680
+ </span>
1681
+ <span class="clado-pop-desc">${esc(item.description || '')}</span>
1682
+ `;
1683
+ btn.onmouseenter = () => {
1684
+ composerMenuIndex = idx;
1685
+ popoverEl.querySelectorAll('.clado-pop-item').forEach((el, i) => el.classList.toggle('is-selected', i === idx));
1686
+ };
1687
+ btn.onmousedown = e => {
1688
+ e.preventDefault();
1689
+ applyComposerMenuItem(item);
1342
1690
  };
1343
1691
  popoverEl.append(btn);
1344
- }
1692
+ });
1345
1693
  popoverEl.hidden = false;
1346
1694
  }
1347
1695
 
1696
+ async function applyComposerMenuItem(item) {
1697
+ if (!item) return;
1698
+ const range = composerMenuRange;
1699
+ closePopover();
1700
+ composerMenuItems = [];
1701
+ composerMenuRange = null;
1702
+
1703
+ if (item.kind === 'local') {
1704
+ inputEl.value = '';
1705
+ autoGrowInput();
1706
+ await executeLocalSlashCommand(item.name);
1707
+ return;
1708
+ }
1709
+ const val = inputEl.value;
1710
+ const start = range ? range.start : 0;
1711
+ const end = range ? range.end : val.length;
1712
+ const insertText = item.insertText || '';
1713
+ inputEl.value = val.slice(0, start) + insertText + val.slice(end);
1714
+ const nextPos = start + insertText.length;
1715
+ autoGrowInput();
1716
+ inputEl.focus();
1717
+ try { inputEl.setSelectionRange(nextPos, nextPos); } catch {}
1718
+ }
1719
+
1720
+ function isComposerMenuOpen() {
1721
+ return !popoverEl.hidden && (popoverEl.dataset.kind === 'slash' || popoverEl.dataset.kind === 'mention') && composerMenuItems.length > 0;
1722
+ }
1723
+
1724
+ function moveComposerMenuSelection(delta) {
1725
+ if (!isComposerMenuOpen()) return false;
1726
+ const len = composerMenuItems.length;
1727
+ composerMenuIndex = (composerMenuIndex + delta + len) % len;
1728
+ const btns = popoverEl.querySelectorAll('.clado-pop-item');
1729
+ btns.forEach((el, i) => {
1730
+ const active = i === composerMenuIndex;
1731
+ el.classList.toggle('is-selected', active);
1732
+ if (active) el.scrollIntoView?.({ block: 'nearest' });
1733
+ });
1734
+ return true;
1735
+ }
1736
+
1737
+ function acceptComposerMenuSelection() {
1738
+ if (!isComposerMenuOpen()) return false;
1739
+ const item = composerMenuItems[composerMenuIndex] || composerMenuItems[0];
1740
+ if (!item) return false;
1741
+ applyComposerMenuItem(item);
1742
+ return true;
1743
+ }
1744
+
1745
+ function buildSlashItems(q) {
1746
+ const items = [];
1747
+ const seen = new Set();
1748
+ const pushUnique = it => {
1749
+ const key = it.display.toLowerCase();
1750
+ if (seen.has(key)) return;
1751
+ seen.add(key);
1752
+ items.push(it);
1753
+ };
1754
+
1755
+ // 1. User/Project Pi prompt templates (~/.pi/agent/prompts & .pi/prompts)
1756
+ for (const p of (meta?.ecosystem?.prompts || [])) {
1757
+ pushUnique({
1758
+ name: p.name,
1759
+ display: '/' + p.name,
1760
+ badge: p.scope === 'project' ? '项目' : '模板',
1761
+ description: p.description || 'Pi Prompt 模板',
1762
+ kind: 'prompt',
1763
+ insertText: '/' + p.name + ' ',
1764
+ });
1765
+ }
1766
+ // 2. Built-in Clado commands & quick actions
1767
+ for (const b of BUILTIN_SLASH_COMMANDS) {
1768
+ pushUnique({
1769
+ name: b.name,
1770
+ display: '/' + b.name,
1771
+ badge: b.badge,
1772
+ description: b.description,
1773
+ kind: b.kind,
1774
+ insertText: '/' + b.name + ' ',
1775
+ });
1776
+ }
1777
+ // 3. Discovered Pi skills (/skill:<name>)
1778
+ for (const sk of (meta?.ecosystem?.skills || [])) {
1779
+ pushUnique({
1780
+ name: 'skill:' + sk.name,
1781
+ display: '/skill:' + sk.name,
1782
+ badge: '技能',
1783
+ description: sk.description || '按需加载技能规范',
1784
+ kind: 'prompt',
1785
+ insertText: '/skill:' + sk.name + ' ',
1786
+ });
1787
+ }
1788
+
1789
+ if (!q) return items.slice(0, 12);
1790
+ return items
1791
+ .filter(it => it.display.toLowerCase().includes(q) || (it.description || '').toLowerCase().includes(q))
1792
+ .slice(0, 12);
1793
+ }
1794
+
1795
+ function buildMentionItems(q) {
1796
+ const items = [];
1797
+ const ql = q.toLowerCase();
1798
+ const matches = (label, desc) => !ql || label.toLowerCase().includes(ql) || (desc || '').toLowerCase().includes(ql);
1799
+
1800
+ // 1. Current canvas cards
1801
+ for (const title of mentionCache.cards) {
1802
+ if (!matches(title, '当前画布卡片')) continue;
1803
+ items.push({
1804
+ display: title,
1805
+ badge: '卡片',
1806
+ description: mentionCache.cardsFile || '当前画布',
1807
+ kind: 'mention',
1808
+ insertText: `@[卡片:${title}] `,
1809
+ });
1810
+ }
1811
+ // 2. Workspace canvases
1812
+ for (const doc of mentionCache.docs) {
1813
+ const f = String(doc.file || '');
1814
+ const t = String(doc.title || f);
1815
+ if (!f || !matches(f + ' ' + t, '画布')) continue;
1816
+ items.push({
1817
+ display: f,
1818
+ badge: '画布',
1819
+ description: t !== f ? t : '工作区画布',
1820
+ kind: 'mention',
1821
+ insertText: `@doc:${f} `,
1822
+ });
1823
+ }
1824
+ // 3. Workspace source files
1825
+ for (const f of mentionCache.files) {
1826
+ if (!matches(f, '源码文件')) continue;
1827
+ items.push({
1828
+ display: f,
1829
+ badge: '文件',
1830
+ description: '工作区文件',
1831
+ kind: 'mention',
1832
+ insertText: `@${f} `,
1833
+ });
1834
+ }
1835
+ // 4. Workspace roles
1836
+ for (const r of (meta?.roles || [])) {
1837
+ const rn = String(r.name || '');
1838
+ if (!rn || !matches(rn + ' ' + (r.id || ''), r.description || '')) continue;
1839
+ items.push({
1840
+ display: rn,
1841
+ badge: '角色',
1842
+ description: r.phase || r.description || '工作区角色',
1843
+ kind: 'mention',
1844
+ insertText: `@${rn} `,
1845
+ });
1846
+ }
1847
+ return items.slice(0, 14);
1848
+ }
1849
+
1850
+ function updateSlashPopover() {
1851
+ const val = inputEl.value;
1852
+ const caret = typeof inputEl.selectionStart === 'number' ? inputEl.selectionStart : val.length;
1853
+ const beforeCaret = val.slice(0, caret);
1854
+
1855
+ // Priority 1: '/' command at the very start of input (single token before first space/newline)
1856
+ const slashMatch = beforeCaret.match(/^\/([^\s\n]*)$/);
1857
+ if (slashMatch) {
1858
+ const q = slashMatch[1].toLowerCase();
1859
+ const items = buildSlashItems(q);
1860
+ composerMenuIndex = 0;
1861
+ renderComposerAutocomplete('slash', '斜杠命令 / 技能', items, { start: 0, end: caret, kind: 'slash' });
1862
+ return;
1863
+ }
1864
+
1865
+ // Priority 2: '@' mention anywhere before caret (preceded by start-of-string or whitespace/punctuation)
1866
+ const atMatch = beforeCaret.match(/(^|[\s((【,:;,;])@([^\s@\n]*)$/);
1867
+ if (atMatch) {
1868
+ const tokenStart = caret - atMatch[2].length - 1;
1869
+ const q = atMatch[2];
1870
+ const items = buildMentionItems(q);
1871
+ composerMenuIndex = 0;
1872
+ renderComposerAutocomplete('mention', '引用卡片 / 画布 / 文件 / 角色', items, { start: tokenStart, end: caret, kind: 'mention' });
1873
+ ensureMentionSources(false).then(updated => {
1874
+ if (!updated) return;
1875
+ // Re-render if user is still typing the same @ mention
1876
+ const curVal = inputEl.value;
1877
+ const curCaret = typeof inputEl.selectionStart === 'number' ? inputEl.selectionStart : curVal.length;
1878
+ const curMatch = curVal.slice(0, curCaret).match(/(^|[\s((【,:;,;])@([^\s@\n]*)$/);
1879
+ if (curMatch) {
1880
+ const nextItems = buildMentionItems(curMatch[2]);
1881
+ const nextStart = curCaret - curMatch[2].length - 1;
1882
+ renderComposerAutocomplete('mention', '引用卡片 / 画布 / 文件 / 角色', nextItems, { start: nextStart, end: curCaret, kind: 'mention' });
1883
+ }
1884
+ });
1885
+ return;
1886
+ }
1887
+
1888
+ if (!popoverEl.hidden && (popoverEl.dataset.kind === 'slash' || popoverEl.dataset.kind === 'mention')) {
1889
+ closePopover();
1890
+ composerMenuItems = [];
1891
+ composerMenuRange = null;
1892
+ }
1893
+ }
1894
+
1348
1895
  // =========================================================================
1349
1896
  // 2. Streaming Pi Turn, Live Tool Calls & Safe Cancel (Preserving History!)
1350
1897
  // =========================================================================
@@ -1465,6 +2012,14 @@
1465
2012
  renderStream();
1466
2013
  } else if (ev.type === 'focus') {
1467
2014
  actions.focusCanvas?.(ev.file, ev.heading);
2015
+ } else if (ev.type === 'steer' && ev.text) {
2016
+ if (!Array.isArray(liveAssistant.blocks)) liveAssistant.blocks = [];
2017
+ const lastBlk = liveAssistant.blocks[liveAssistant.blocks.length - 1];
2018
+ if (!lastBlk || lastBlk.type !== 'steer' || lastBlk.text !== ev.text) {
2019
+ liveAssistant.blocks.push({ type: 'steer', text: ev.text });
2020
+ }
2021
+ liveAssistant.activity = '已收到中途插话,正在调整方向…';
2022
+ renderStream();
1468
2023
  } else if (ev.type === 'status') {
1469
2024
  liveAssistant.activity = ev.text || liveAssistant.activity;
1470
2025
  showToast(ev.text);
@@ -1590,25 +2145,50 @@
1590
2145
  headers: { 'content-type': 'application/json' },
1591
2146
  body: JSON.stringify({ action: 'steer', session: targetId, text }),
1592
2147
  });
1593
- if (!res.ok) throw new Error('插话失败');
2148
+ const data = await res.json().catch(() => ({}));
2149
+ if (!res.ok || data.ok === false) throw new Error('插话失败');
1594
2150
  if (runningSession && Array.isArray(runningSession.messages)) {
1595
- const insertAt = Math.max(0, runningSession.messages.length - 1);
1596
- runningSession.messages.splice(insertAt, 0, {
1597
- id: 'local_steer_' + Date.now(),
1598
- role: 'user',
1599
- text,
1600
- isSteer: true,
1601
- });
1602
- renderStream();
2151
+ runningSession.updatedAt = new Date().toISOString();
2152
+ const liveMsg = runningSession.messages[runningSession.messages.length - 1];
2153
+ if (liveMsg && liveMsg.role === 'assistant') {
2154
+ if (!Array.isArray(liveMsg.blocks)) liveMsg.blocks = [];
2155
+ const lastBlk = liveMsg.blocks[liveMsg.blocks.length - 1];
2156
+ if (!lastBlk || lastBlk.type !== 'steer' || lastBlk.text !== text) {
2157
+ liveMsg.blocks.push({ type: 'steer', text });
2158
+ }
2159
+ liveMsg.activity = '已收到中途插话,正在调整方向…';
2160
+ } else {
2161
+ runningSession.messages.push({
2162
+ id: 'local_steer_' + Date.now(),
2163
+ role: 'user',
2164
+ text,
2165
+ isSteer: true,
2166
+ });
2167
+ }
2168
+ if (activeSessionId !== targetId) selectSession(targetId, true);
2169
+ else {
2170
+ renderStream();
2171
+ streamEl.scrollTop = streamEl.scrollHeight;
2172
+ }
1603
2173
  }
1604
- showToast('已发送中途纠偏指令');
2174
+ showToast('已发送中途插话');
1605
2175
  } catch {
1606
- showToast('当前回合暂不支持插话,可稍候或点击停止');
2176
+ inputEl.value = text;
2177
+ autoGrowInput();
2178
+ showToast('当前回合尚未就绪,稍候再试或点击停止');
1607
2179
  }
1608
2180
  return;
1609
2181
  }
1610
2182
 
1611
2183
  if (!text) return;
2184
+ const localCmd = tryMatchLocalSlashCommand(text);
2185
+ if (localCmd) {
2186
+ inputEl.value = '';
2187
+ autoGrowInput();
2188
+ closePopover();
2189
+ await executeLocalSlashCommand(localCmd);
2190
+ return;
2191
+ }
1612
2192
  inputEl.value = '';
1613
2193
  autoGrowInput();
1614
2194
  closePopover();
@@ -1631,33 +2211,6 @@
1631
2211
  }, s);
1632
2212
  }
1633
2213
 
1634
- async function triggerHandoff(targetRoleId, customNote = '') {
1635
- const from = currentSession();
1636
- const targetRole = (meta?.roles || []).find(r => r.id === targetRoleId) || { id: targetRoleId, name: targetRoleId };
1637
- let targetSession = sessions.find(s => !s.archived && s.roleId === targetRole.id);
1638
- if (!targetSession) {
1639
- const res = await fetch(withWs('/library/agent/sessions'), {
1640
- method: 'POST',
1641
- headers: { 'content-type': 'application/json' },
1642
- body: JSON.stringify({ roleId: targetRole.id, title: targetRole.name }),
1643
- });
1644
- const data = await res.json();
1645
- targetSession = data.session;
1646
- if (targetSession) sessions.push(targetSession);
1647
- }
1648
- const canvas = actions.readContext ? actions.readContext() : {};
1649
- showToast(`已交接给「${targetRole.name}」执行`);
1650
- await streamAgentRequest({
1651
- action: 'handoff',
1652
- fromSession: from?.id,
1653
- fromRoleName: from?.title || '画布定稿',
1654
- targetRoleId: targetRole.id,
1655
- targetSession: targetSession?.id,
1656
- text: customNote,
1657
- canvas,
1658
- }, targetSession);
1659
- }
1660
-
1661
2214
  // Bind dock events
1662
2215
  dock.querySelector('[data-toggle-drawer]').onclick = () => setDrawerOpen(!drawerOpen);
1663
2216
  dock.querySelector('[data-collapse]').onclick = () => setDrawerOpen(false);
@@ -1687,9 +2240,6 @@
1687
2240
  if (!res.ok) showToast(data.error || '暂无可回退快照');
1688
2241
  else showToast('已回退画布 ' + data.file);
1689
2242
  };
1690
- dock.querySelectorAll('[data-quick-handoff]').forEach(btn => {
1691
- btn.onclick = () => triggerHandoff(btn.dataset.quickHandoff);
1692
- });
1693
2243
  modelChip.onclick = e => {
1694
2244
  e.stopPropagation();
1695
2245
  closeSessionPop();
@@ -1711,7 +2261,11 @@
1711
2261
  syncSendModeUi();
1712
2262
  showToast(sendMode === 'ctrl-enter' ? '已切换:Enter 换行,Ctrl+Enter 发送' : '已切换:Enter 发送,Shift+Enter 换行');
1713
2263
  };
1714
- inputEl.addEventListener('focus', () => renderContextChips());
2264
+ inputEl.addEventListener('focus', () => {
2265
+ renderContextChips();
2266
+ ensureMentionSources(false);
2267
+ });
2268
+ inputEl.addEventListener('click', () => updateSlashPopover());
1715
2269
  inputEl.addEventListener('input', () => {
1716
2270
  autoGrowInput();
1717
2271
  updateSlashPopover();
@@ -1722,6 +2276,23 @@
1722
2276
  closeSessionPop();
1723
2277
  return;
1724
2278
  }
2279
+ if (!e.isComposing && isComposerMenuOpen()) {
2280
+ if (e.key === 'ArrowDown') {
2281
+ e.preventDefault();
2282
+ moveComposerMenuSelection(1);
2283
+ return;
2284
+ }
2285
+ if (e.key === 'ArrowUp') {
2286
+ e.preventDefault();
2287
+ moveComposerMenuSelection(-1);
2288
+ return;
2289
+ }
2290
+ if (e.key === 'Tab' || (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.metaKey)) {
2291
+ e.preventDefault();
2292
+ acceptComposerMenuSelection();
2293
+ return;
2294
+ }
2295
+ }
1725
2296
  if (e.key === 'Enter' && !e.isComposing) {
1726
2297
  if (sendMode === 'ctrl-enter') {
1727
2298
  if (e.ctrlKey || e.metaKey) {
@@ -2283,6 +2854,7 @@
2283
2854
  }
2284
2855
 
2285
2856
  let memorySubTab = 'agents';
2857
+ let autoDraftTriggerType = 'schedule';
2286
2858
  function renderMemoryTab() {
2287
2859
  const content = meta.memory?.content || '';
2288
2860
  const pdocs = meta.platformDocs || {};
@@ -2290,24 +2862,37 @@
2290
2862
  const refPath = pdocs.referencePath || ((meta.agentDir || '~/.pi/agent') + '/clado-reference.md');
2291
2863
  const ctxContent = pdocs.contextContent || '';
2292
2864
  const refContent = pdocs.referenceContent || '';
2865
+ const autoState = meta.automations || { paused: false, rules: [] };
2866
+ const autoRules = Array.isArray(autoState.rules) ? autoState.rules : [];
2867
+ const eventCatalog = Array.isArray(meta.eventCatalog) ? meta.eventCatalog : [];
2868
+ const roles = Array.isArray(meta.roles) ? meta.roles : [];
2869
+ const roleNameOf = id => roles.find(r => r.id === id)?.name || id || '归档员';
2293
2870
 
2294
2871
  const isAgents = memorySubTab === 'agents';
2295
2872
  const isPlatform = memorySubTab === 'platform';
2296
2873
  const isReference = memorySubTab === 'reference';
2874
+ const isAutomations = memorySubTab === 'automations';
2875
+
2876
+ const scribeExists = autoRules.some(r => r.id === 'auto_memory_scribe');
2297
2877
 
2298
2878
  sBody.innerHTML = `
2299
2879
  <div class="clado-setting-row">
2300
2880
  <div>
2301
2881
  <div style="font-size:18px;font-weight:630;">工作区与平台上下文</div>
2302
- <div style="font-size:12.5px;color:var(--clado-ui-muted);margin-top:4px;">项目记忆 <code style="font-family:ui-monospace,monospace;">AGENTS.md</code> 与自动注入所有角色的 Clado 平台文档。</div>
2882
+ <div style="font-size:12.5px;color:var(--clado-ui-muted);margin-top:4px;">项目记忆 <code style="font-family:ui-monospace,monospace;">AGENTS.md</code>、平台注入文档,以及定时巡检与系统事件自动唤醒。</div>
2303
2883
  </div>
2304
- <div style="display:flex;gap:6px;">
2884
+ <div style="display:flex;gap:6px;flex-wrap:wrap;">
2305
2885
  ${isAgents ? '<button type="button" class="clado-ui-button clado-ui-button-primary" data-save-mem>保存 AGENTS.md</button>' : ''}
2306
2886
  ${isPlatform ? '<button type="button" class="clado-ui-button" data-reset-pctx style="border-color:var(--clado-ui-well-border);background:var(--clado-ui-well);">恢复默认</button><button type="button" class="clado-ui-button clado-ui-button-primary" data-save-pctx>保存注入文档</button>' : ''}
2887
+ ${isAutomations ? `
2888
+ <button type="button" class="clado-ui-button" data-auto-toggle-pause style="border-color:${autoState.paused ? 'rgba(245,158,11,0.5)' : 'var(--clado-ui-well-border)'};background:var(--clado-ui-well);color:${autoState.paused ? '#d97706' : 'var(--clado-ui-text)'};">${autoState.paused ? '已全局暂停 · 点击恢复' : '全局暂停自动化'}</button>
2889
+ <button type="button" class="clado-ui-button clado-ui-button-primary" data-auto-add-scribe>${scribeExists ? '重置记忆记录专员' : '+ 记忆记录专员 (10m 巡检)'}</button>
2890
+ ` : ''}
2307
2891
  </div>
2308
2892
  </div>
2309
2893
  <div class="clado-ctx-pills" style="margin-bottom:2px;">
2310
2894
  <button type="button" class="clado-ctx-pill-btn ${isAgents ? 'active' : ''}" data-mtab="agents">项目记忆 (AGENTS.md)</button>
2895
+ <button type="button" class="clado-ctx-pill-btn ${isAutomations ? 'active' : ''}" data-mtab="automations">定时唤醒与事件订阅 (${autoRules.length})${autoState.paused ? ' · 已暂停' : ''}</button>
2311
2896
  <button type="button" class="clado-ctx-pill-btn ${isPlatform ? 'active' : ''}" data-mtab="platform">自动注入上下文 (clado-context.md)${pdocs.customized ? ' · 已自定义' : ''}</button>
2312
2897
  <button type="button" class="clado-ctx-pill-btn ${isReference ? 'active' : ''}" data-mtab="reference">完整参考手册 (clado-reference.md)</button>
2313
2898
  </div>
@@ -2316,6 +2901,125 @@
2316
2901
  <span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">文件路径:<code style="font-family:ui-monospace,monospace;color:var(--clado-ui-text);">${esc(meta.memory?.path || 'AGENTS.md')}</code></span>
2317
2902
  </div>
2318
2903
  <textarea class="clado-field clado-scroll" data-mem-text style="flex:1;min-height:320px;font-family:ui-monospace,monospace;line-height:1.65;resize:none;" placeholder="# AGENTS.md&#10;&#10;- 写下本项目的代码约定、测试命令与架构约束…">${esc(content)}</textarea>
2904
+ ` : isAutomations ? `
2905
+ <div class="clado-well-box" style="padding:10px 13px;font-size:11.5px;color:var(--clado-ui-muted);line-height:1.55;">
2906
+ 统一事件总线支持 <strong style="color:var(--clado-ui-text);">周期定时巡检</strong>(如每 10 分钟唤醒「记忆记录专员」扫描近 20 分钟活跃会话更新 <code>AGENTS.md</code>,无活跃会话时零 Token 自动跳过)与 <strong style="color:var(--clado-ui-text);">6 大类系统事件订阅</strong>,内置防自触发、防抖合并与多会话进展熔断(Progress Guard)。规则持久化于 <code>.clado/automations.json</code>。
2907
+ </div>
2908
+ <div style="display:flex;flex-direction:column;gap:8px;" data-auto-list>
2909
+ ${autoRules.length ? autoRules.map(rule => {
2910
+ const trig = rule.trigger || {};
2911
+ const trigDesc = trig.type === 'event'
2912
+ ? `事件订阅:${(trig.eventTypes || []).join(', ')}`
2913
+ : `每 ${trig.intervalMinutes || 10} 分钟${trig.onlyIfActive !== false ? ` · 活跃窗口 ${trig.activeWindowMinutes || 20} 分钟(无活跃跳过)` : ' · 固定触发'}`;
2914
+ const filterParts = [];
2915
+ if (trig.filter?.file) filterParts.push('文件:' + trig.filter.file);
2916
+ if (trig.filter?.card) filterParts.push('卡片:' + trig.filter.card);
2917
+ if (trig.filter?.tag) filterParts.push('Tag:' + trig.filter.tag);
2918
+ if (trig.filter?.roleId) filterParts.push('来源角色:' + roleNameOf(trig.filter.roleId));
2919
+ return `
2920
+ <div class="clado-well-box clado-auto-card" data-rule-id="${esc(rule.id)}">
2921
+ <div class="clado-setting-row">
2922
+ <div style="min-width:0;flex:1;">
2923
+ <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;">
2924
+ <span style="font-size:13px;font-weight:610;">${esc(rule.name)}</span>
2925
+ <span class="clado-chip ${trig.type === 'event' ? 'clado-chip-violet' : 'clado-chip-sky'}">${trig.type === 'event' ? '事件触发' : '定时巡检'}</span>
2926
+ <span class="clado-chip clado-chip-mint">唤醒:${esc(roleNameOf(rule.target?.roleId))}</span>
2927
+ </div>
2928
+ <div class="clado-auto-meta" style="margin-top:4px;">
2929
+ <span>${esc(trigDesc)}</span>
2930
+ ${filterParts.length ? `<span>· 过滤:${esc(filterParts.join(' / '))}</span>` : ''}
2931
+ <span>· 已运行 ${rule.runCount || 0} 次 · 空转跳过 ${rule.skipCount || 0} 次</span>
2932
+ ${rule.lastSkipReason ? `<span>· 最近跳过:${esc(rule.lastSkipReason)}</span>` : ''}
2933
+ </div>
2934
+ </div>
2935
+ <div style="display:flex;align-items:center;gap:8px;flex:none;">
2936
+ <button type="button" class="clado-dock-mini-btn" data-auto-run="${esc(rule.id)}">立即运行</button>
2937
+ <button type="button" class="clado-dock-mini-btn" data-auto-del="${esc(rule.id)}" style="color:#be123c;">删除</button>
2938
+ <div class="clado-switch ${rule.enabled ? 'on' : ''}" data-auto-tog="${esc(rule.id)}" title="${rule.enabled ? '点击禁用' : '点击启用'}"></div>
2939
+ </div>
2940
+ </div>
2941
+ <div class="clado-auto-prompt">${esc(rule.target?.prompt || '')}</div>
2942
+ </div>
2943
+ `;
2944
+ }).join('') : `
2945
+ <div class="clado-well-box" style="text-align:center;font-size:12px;color:var(--clado-ui-subtle);padding:16px;">
2946
+ 尚未配置定时巡检或事件订阅规则。可点击右上角「+ 记忆记录专员 (10m 巡检)」一键启用,或在下方创建自定义规则。
2947
+ </div>
2948
+ `}
2949
+ </div>
2950
+ <div class="clado-well-box" style="display:flex;flex-direction:column;gap:10px;" data-auto-form>
2951
+ <div class="clado-setting-row">
2952
+ <div style="font-size:13px;font-weight:610;">新建自定义唤醒规则</div>
2953
+ <div class="clado-ctx-pills">
2954
+ <button type="button" class="clado-ctx-pill-btn ${autoDraftTriggerType === 'schedule' ? 'active' : ''}" data-auto-draft-type="schedule">定时周期唤醒</button>
2955
+ <button type="button" class="clado-ctx-pill-btn ${autoDraftTriggerType === 'event' ? 'active' : ''}" data-auto-draft-type="event">系统事件订阅</button>
2956
+ </div>
2957
+ </div>
2958
+ <div class="clado-rt-grid">
2959
+ <div class="clado-rt-field">
2960
+ <label class="clado-rt-label">规则名称</label>
2961
+ <input type="text" class="clado-field" data-af-name placeholder="例如:架构变更有损复核 / 每 5 分钟巡检" />
2962
+ </div>
2963
+ <div class="clado-rt-field">
2964
+ <label class="clado-rt-label">唤醒目标角色</label>
2965
+ <select class="clado-field" data-af-role>
2966
+ ${roles.map(r => `<option value="${esc(r.id)}" ${r.id === 'archivist' ? 'selected' : ''}>${esc(r.name)} (${esc(r.id)})</option>`).join('')}
2967
+ </select>
2968
+ </div>
2969
+ </div>
2970
+ ${autoDraftTriggerType === 'schedule' ? `
2971
+ <div class="clado-rt-grid">
2972
+ <div class="clado-rt-field">
2973
+ <label class="clado-rt-label">巡检间隔(分钟)</label>
2974
+ <input type="number" class="clado-field" data-af-interval min="1" max="1440" value="10" />
2975
+ </div>
2976
+ <div class="clado-rt-field">
2977
+ <label class="clado-rt-label">活跃会话扫描窗口(分钟)</label>
2978
+ <input type="number" class="clado-field" data-af-window min="1" max="1440" value="20" />
2979
+ </div>
2980
+ </div>
2981
+ <div class="clado-rt-checks">
2982
+ <label><input type="checkbox" data-af-only-active checked /> 仅在窗口内有其他会话活跃时唤醒(无活跃零 Token 自动跳过)</label>
2983
+ </div>
2984
+ ` : `
2985
+ <div class="clado-rt-field">
2986
+ <label class="clado-rt-label"><span>订阅的系统事件(6 大类统一事件总线)</span><span>可多选</span></label>
2987
+ <div class="clado-auto-events-grid clado-scroll">
2988
+ ${eventCatalog.map(group => `
2989
+ <div class="clado-auto-ev-group">
2990
+ <div class="clado-auto-ev-title">${esc(group.label)}</div>
2991
+ ${(group.events || []).map(ev => `
2992
+ <label class="clado-auto-ev-opt" title="${esc(ev.description)}">
2993
+ <input type="checkbox" data-af-event value="${esc(ev.type)}" ${ev.type === 'card.updated' ? 'checked' : ''} />
2994
+ <span><code>${esc(ev.type)}</code> · ${esc(ev.description)}</span>
2995
+ </label>
2996
+ `).join('')}
2997
+ </div>
2998
+ `).join('')}
2999
+ </div>
3000
+ </div>
3001
+ <div class="clado-rt-grid">
3002
+ <div class="clado-rt-field">
3003
+ <label class="clado-rt-label">过滤画布文件(可选)</label>
3004
+ <input type="text" class="clado-field" data-af-file placeholder="例如:architecture.md" />
3005
+ </div>
3006
+ <div class="clado-rt-field">
3007
+ <label class="clado-rt-label">过滤卡片名 / 语义 Tag(可选)</label>
3008
+ <div style="display:flex;gap:6px;">
3009
+ <input type="text" class="clado-field" data-af-card placeholder="卡片标题" />
3010
+ <input type="text" class="clado-field" data-af-tag placeholder="#tag" />
3011
+ </div>
3012
+ </div>
3013
+ </div>
3014
+ `}
3015
+ <div class="clado-rt-field">
3016
+ <label class="clado-rt-label">唤醒后下达的任务指令</label>
3017
+ <textarea class="clado-field clado-scroll" data-af-prompt rows="2" style="resize:vertical;line-height:1.5;" placeholder="例如:请调用 clado_session_list(sinceMinutes: 20) 检查最新进展,并同步更新 AGENTS.md 或给目标卡片补充复核结论。"></textarea>
3018
+ </div>
3019
+ <div style="display:flex;justify-content:flex-end;">
3020
+ <button type="button" class="clado-ui-button clado-ui-button-primary" data-af-save>保存唤醒规则</button>
3021
+ </div>
3022
+ </div>
2319
3023
  ` : isPlatform ? `
2320
3024
  <div class="clado-well-box clado-setting-row" style="padding:9px 12px;font-size:11.5px;color:var(--clado-ui-muted);gap:8px;">
2321
3025
  <span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">自动注入所有内置/自定义角色:<code style="font-family:ui-monospace,monospace;color:var(--clado-ui-text);">${esc(ctxPath)}</code></span>
@@ -2372,6 +3076,119 @@
2372
3076
  } catch (e) { showToast(e.message); }
2373
3077
  };
2374
3078
  }
3079
+
3080
+ if (isAutomations) {
3081
+ const pauseBtn = sBody.querySelector('[data-auto-toggle-pause]');
3082
+ if (pauseBtn) {
3083
+ pauseBtn.onclick = async () => {
3084
+ try {
3085
+ await apiConfig({ action: 'toggle_automations_pause', paused: !autoState.paused });
3086
+ renderMemoryTab();
3087
+ showToast(!autoState.paused ? '已全局暂停全部自动化唤醒' : '已恢复自动化唤醒引擎');
3088
+ } catch (e) { showToast(e.message); }
3089
+ };
3090
+ }
3091
+ const scribeBtn = sBody.querySelector('[data-auto-add-scribe]');
3092
+ if (scribeBtn) {
3093
+ scribeBtn.onclick = async () => {
3094
+ try {
3095
+ const preset = meta.memoryScribePreset || {
3096
+ id: 'auto_memory_scribe',
3097
+ name: '记忆记录专员 · 定时沉淀工作区记忆',
3098
+ enabled: true,
3099
+ trigger: { type: 'schedule', intervalMinutes: 10, onlyIfActive: true, activeWindowMinutes: 20, eventTypes: ['schedule.tick'], filter: {} },
3100
+ target: { roleId: 'archivist', sessionId: '', prompt: '请调用 clado_session_list(sinceMinutes: 20) 扫描工作区最近 20 分钟活跃会话,提炼关键变更与决策并更新 AGENTS.md。' },
3101
+ debounceMs: 4000,
3102
+ };
3103
+ await apiConfig({ action: 'save_automation', rule: preset });
3104
+ renderMemoryTab();
3105
+ showToast('已启用「记忆记录专员」定时巡检规则');
3106
+ } catch (e) { showToast(e.message); }
3107
+ };
3108
+ }
3109
+ sBody.querySelectorAll('[data-auto-tog]').forEach(sw => {
3110
+ sw.onclick = async () => {
3111
+ const r = autoRules.find(x => x.id === sw.dataset.autoTog);
3112
+ if (!r) return;
3113
+ try {
3114
+ await apiConfig({ action: 'save_automation', rule: { ...r, enabled: !r.enabled } });
3115
+ renderMemoryTab();
3116
+ showToast(r.name + (!r.enabled ? ' 已启用' : ' 已禁用'));
3117
+ } catch (e) { showToast(e.message); }
3118
+ };
3119
+ });
3120
+ sBody.querySelectorAll('[data-auto-run]').forEach(btn => {
3121
+ btn.onclick = async () => {
3122
+ try {
3123
+ btn.disabled = true;
3124
+ await apiConfig({ action: 'run_automation_now', ruleId: btn.dataset.autoRun });
3125
+ renderMemoryTab();
3126
+ showToast('已立即唤醒目标角色执行任务');
3127
+ } catch (e) {
3128
+ btn.disabled = false;
3129
+ showToast(e.message);
3130
+ }
3131
+ };
3132
+ });
3133
+ sBody.querySelectorAll('[data-auto-del]').forEach(btn => {
3134
+ btn.onclick = async () => {
3135
+ try {
3136
+ await apiConfig({ action: 'delete_automation', ruleId: btn.dataset.autoDel });
3137
+ renderMemoryTab();
3138
+ showToast('已删除自动化规则');
3139
+ } catch (e) { showToast(e.message); }
3140
+ };
3141
+ });
3142
+ sBody.querySelectorAll('[data-auto-draft-type]').forEach(btn => {
3143
+ btn.onclick = () => {
3144
+ autoDraftTriggerType = btn.dataset.autoDraftType === 'event' ? 'event' : 'schedule';
3145
+ renderMemoryTab();
3146
+ };
3147
+ });
3148
+ const saveAutoBtn = sBody.querySelector('[data-af-save]');
3149
+ if (saveAutoBtn) {
3150
+ saveAutoBtn.onclick = async () => {
3151
+ const name = sBody.querySelector('[data-af-name]')?.value.trim() || (autoDraftTriggerType === 'schedule' ? '定时巡检规则' : '系统事件响应规则');
3152
+ const roleId = sBody.querySelector('[data-af-role]')?.value || 'archivist';
3153
+ const prompt = sBody.querySelector('[data-af-prompt]')?.value.trim() || '';
3154
+ if (!prompt) {
3155
+ showToast('请填写唤醒后要执行的任务指令');
3156
+ sBody.querySelector('[data-af-prompt]')?.focus();
3157
+ return;
3158
+ }
3159
+ const trigger = autoDraftTriggerType === 'schedule'
3160
+ ? {
3161
+ type: 'schedule',
3162
+ intervalMinutes: Number(sBody.querySelector('[data-af-interval]')?.value) || 10,
3163
+ activeWindowMinutes: Number(sBody.querySelector('[data-af-window]')?.value) || 20,
3164
+ onlyIfActive: Boolean(sBody.querySelector('[data-af-only-active]')?.checked),
3165
+ eventTypes: ['schedule.tick'],
3166
+ filter: {},
3167
+ }
3168
+ : {
3169
+ type: 'event',
3170
+ eventTypes: [...sBody.querySelectorAll('[data-af-event]:checked')].map(el => el.value),
3171
+ filter: {
3172
+ file: sBody.querySelector('[data-af-file]')?.value.trim() || '',
3173
+ card: sBody.querySelector('[data-af-card]')?.value.trim() || '',
3174
+ tag: sBody.querySelector('[data-af-tag]')?.value.trim().replace(/^#/, '') || '',
3175
+ },
3176
+ };
3177
+ if (trigger.type === 'event' && !trigger.eventTypes.length) {
3178
+ showToast('请至少选择一个订阅的系统事件');
3179
+ return;
3180
+ }
3181
+ try {
3182
+ await apiConfig({
3183
+ action: 'save_automation',
3184
+ rule: { name, enabled: true, trigger, target: { roleId, sessionId: '', prompt }, debounceMs: 4000 },
3185
+ });
3186
+ renderMemoryTab();
3187
+ showToast('已保存自动化唤醒规则');
3188
+ } catch (e) { showToast(e.message); }
3189
+ };
3190
+ }
3191
+ }
2375
3192
  }
2376
3193
 
2377
3194
  function readPresenceTtlSeconds() {
@@ -2382,7 +3199,7 @@
2382
3199
  if (Number.isFinite(n) && n >= 0) return Math.round(n);
2383
3200
  }
2384
3201
  } catch {}
2385
- return 15;
3202
+ return 30;
2386
3203
  }
2387
3204
 
2388
3205
  function renderAppearanceTab() {
@@ -2391,8 +3208,8 @@
2391
3208
  const ttlOptions = [
2392
3209
  [0, '立即关闭 (0s)'],
2393
3210
  [10, '10 秒'],
2394
- [15, '15 秒 (默认)'],
2395
- [30, '30 秒'],
3211
+ [15, '15 秒'],
3212
+ [30, '30 秒 (默认)'],
2396
3213
  [60, '60 秒'],
2397
3214
  ];
2398
3215
  sBody.innerHTML = `
@@ -2409,8 +3226,8 @@
2409
3226
  </div>
2410
3227
  <div class="clado-well-box" style="display:flex;flex-direction:column;gap:10px;">
2411
3228
  <div>
2412
- <div style="font-size:13.5px;font-weight:610;">卡片协同呼吸余韵</div>
2413
- <div style="font-size:12px;color:var(--clado-ui-muted);margin-top:2px;">AI 执行期间卡片底部呼吸自动常亮,回合结束/停止后自动释放并保留短暂余韵(无需手动解锁)。</div>
3229
+ <div style="font-size:13.5px;font-weight:610;">卡片「刚刚编辑了」消退时长</div>
3230
+ <div style="font-size:12px;color:var(--clado-ui-muted);margin-top:2px;">AI 操作的卡片会在本轮期间保持高亮;回合结束或手动停止后转为「刚刚编辑了」,在你下次操作该画布后按此时长自动消退(未操作则最长保留 30 分钟自动清空)。</div>
2414
3231
  </div>
2415
3232
  <div class="clado-ctx-pills" data-presence-ttl-group>
2416
3233
  ${ttlOptions.map(([sec, label]) => `<button type="button" class="clado-ctx-pill-btn ${curTtl === sec ? 'active' : ''}" data-presence-ttl="${sec}">${label}</button>`).join('')}
@@ -2456,57 +3273,7 @@
2456
3273
  }
2457
3274
 
2458
3275
  // =========================================================================
2459
- // 4. Design-to-Delivery Handoff Modal
2460
- // =========================================================================
2461
- const handoffMask = document.createElement('div');
2462
- handoffMask.className = 'clado-vnext-mask';
2463
- handoffMask.id = 'clado-handoff-modal';
2464
- handoffMask.hidden = true;
2465
- stageRoot().append(handoffMask);
2466
- handoffMask.addEventListener('click', e => { if (e.target === handoffMask) handoffMask.hidden = true; });
2467
-
2468
- function openHandoff() {
2469
- const ctx = actions.readContext ? actions.readContext() : {};
2470
- const selCount = ctx.selection?.length || 0;
2471
- const scopeText = selCount
2472
- ? `当前已选中 ${selCount} 项画布卡片(${ctx.file || '当前画布'}),将作为结构化设计契约交接给目标角色。`
2473
- : `将当前画布(${ctx.file || '当前工作区'})的完整设计交接给目标角色落地执行。`;
2474
- const roles = (meta?.roles || []).filter(r => r.id !== 'architect');
2475
- handoffMask.innerHTML = `
2476
- <div class="clado-handoff-card">
2477
- <div style="display:flex;align-items:center;justify-content:space-between;">
2478
- <div style="font-size:16.5px;font-weight:630;">将画布设计交付为实际产物</div>
2479
- <button type="button" class="clado-ui-button" data-close-ho style="width:28px;height:28px;padding:0;min-height:28px;">${ICONS.close}</button>
2480
- </div>
2481
- <p style="font-size:12.5px;color:var(--clado-ui-muted);margin:6px 0 14px;line-height:1.58;">${esc(scopeText)}</p>
2482
- <input class="clado-field" data-ho-note placeholder="补充交付要求(可选,例如:补齐并发重放单测)" style="margin-bottom:12px;" />
2483
- <div data-ho-list style="display:flex;flex-direction:column;gap:9px;"></div>
2484
- </div>
2485
- `;
2486
- handoffMask.querySelector('[data-close-ho]').onclick = () => { handoffMask.hidden = true; };
2487
- const list = handoffMask.querySelector('[data-ho-list]');
2488
- for (const r of roles) {
2489
- const row = document.createElement('div');
2490
- row.className = 'clado-well-box clado-setting-row clado-handoff-opt';
2491
- row.innerHTML = `
2492
- <div>
2493
- <div style="font-size:13px;font-weight:610;">交给「${esc(r.name)}」执行</div>
2494
- <div style="font-size:11.5px;color:var(--clado-ui-muted);margin-top:2px;">${esc(r.description)}</div>
2495
- </div>
2496
- <span class="clado-chip ${TONE_CHIP[r.tone] || 'clado-chip-mint'}">${esc(r.phase)}</span>
2497
- `;
2498
- row.onclick = () => {
2499
- const note = handoffMask.querySelector('[data-ho-note]').value.trim();
2500
- handoffMask.hidden = true;
2501
- triggerHandoff(r.id, note);
2502
- };
2503
- list.append(row);
2504
- }
2505
- handoffMask.hidden = false;
2506
- }
2507
-
2508
- // =========================================================================
2509
- // 5. Bootstrap & Public API
3276
+ // 4. Bootstrap & Public API
2510
3277
  // =========================================================================
2511
3278
  function applyMeta(data) {
2512
3279
  meta = data;
@@ -2550,34 +3317,46 @@
2550
3317
  return Boolean(comps.find(c => c.id === id)?.enabled);
2551
3318
  }
2552
3319
 
3320
+ function focusComposer(prefill = '') {
3321
+ setDrawerOpen(true);
3322
+ if (prefill) {
3323
+ inputEl.value = prefill;
3324
+ autoGrowInput();
3325
+ }
3326
+ inputEl.focus();
3327
+ }
3328
+
2553
3329
  window.CladoVNext = {
2554
3330
  openSettings,
2555
- openHandoff,
2556
- triggerHandoff,
2557
3331
  startCodeAnalysis,
2558
3332
  refreshMeta,
2559
3333
  getMeta: () => meta,
2560
3334
  isComponentEnabled,
2561
3335
  setDrawerOpen,
3336
+ focusComposer,
2562
3337
  renderMarkdown,
2563
3338
  };
2564
3339
 
3340
+ let sseSyncTimer = 0;
3341
+ window.addEventListener('clado:agent-sessions', () => {
3342
+ if (runningSessionId) return;
3343
+ clearTimeout(sseSyncTimer);
3344
+ sseSyncTimer = setTimeout(async () => {
3345
+ await refreshMeta();
3346
+ if (!settingsMask.hidden && settingsTab === 'memory' && memorySubTab === 'automations') {
3347
+ renderMemoryTab();
3348
+ }
3349
+ if (!sessionPopEl.hidden) renderSessionPop();
3350
+ }, 320);
3351
+ });
3352
+
2565
3353
  refreshMeta();
2566
3354
 
2567
3355
  return {
2568
3356
  openSettings,
2569
- openHandoff,
2570
- triggerHandoff,
2571
3357
  startCodeAnalysis,
2572
3358
  refreshMeta,
2573
- focusComposer(prefill = '') {
2574
- setDrawerOpen(true);
2575
- if (prefill) {
2576
- inputEl.value = prefill;
2577
- autoGrowInput();
2578
- }
2579
- inputEl.focus();
2580
- },
3359
+ focusComposer,
2581
3360
  };
2582
3361
  };
2583
3362
  })();