cladogram 0.6.0-beta.5 → 0.6.0-beta.7

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.
@@ -416,11 +416,11 @@
416
416
  if (sendMode === 'ctrl-enter') {
417
417
  sendModeBtn.textContent = 'Ctrl↵ 发送';
418
418
  sendModeBtn.title = '当前:Enter 换行,Ctrl/⌘+Enter 发送(点击切换为 Enter 发送)';
419
- inputEl.placeholder = '输入需求、敲 / 调命令(Enter 换行,Ctrl+Enter 发送)…';
419
+ inputEl.placeholder = '输入需求,敲 / 调命令、@ 引用卡片或文件(Enter 换行,Ctrl+Enter 发送)…';
420
420
  } else {
421
421
  sendModeBtn.textContent = '↵ 发送';
422
422
  sendModeBtn.title = '当前:Enter 发送,Shift+Enter 换行(点击切换为 Ctrl+Enter 发送)';
423
- inputEl.placeholder = '输入需求、敲 / 调命令(Enter 发送,Shift+Enter 换行)…';
423
+ inputEl.placeholder = '输入需求,敲 / 调命令、@ 引用卡片或文件(Enter 发送,Shift+Enter 换行)…';
424
424
  }
425
425
  }
426
426
  syncSendModeUi();
@@ -824,6 +824,10 @@
824
824
  }
825
825
 
826
826
  let renderStreamTimer = 0;
827
+ let loadingHistoryFor = '';
828
+ let scrollTrimTimer = 0;
829
+ let suppressScrollAutoLoad = false;
830
+
827
831
  function scheduleRenderStream() {
828
832
  if (renderStreamTimer) return;
829
833
  renderStreamTimer = setTimeout(() => {
@@ -832,7 +836,62 @@
832
836
  }, 48);
833
837
  }
834
838
 
835
- 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 = {}) {
836
895
  if (renderStreamTimer) {
837
896
  clearTimeout(renderStreamTimer);
838
897
  renderStreamTimer = 0;
@@ -847,18 +906,32 @@
847
906
  modelChip.textContent = (modelLabel.includes('/') ? modelLabel.split('/').pop() : modelLabel) + ' ▾';
848
907
  renderContextMeter();
849
908
 
850
- const wasNearBottom = (streamEl.scrollHeight - streamEl.scrollTop - streamEl.clientHeight) < 60;
909
+ const wasNearBottom = opts.stickToBottom || (streamEl.scrollHeight - streamEl.scrollTop - streamEl.clientHeight) < 60;
851
910
 
852
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);
853
914
  streamEl.replaceChildren();
854
- if (!msgs.length) {
915
+ if (!msgs.length && !hasMoreBefore) {
855
916
  const empty = document.createElement('div');
856
917
  empty.className = 'clado-dock-empty';
857
- 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/>拖动顶部居中横条可调整窗口高度,点击标题可切换或新建会话。`;
858
919
  streamEl.append(empty);
859
920
  return;
860
921
  }
861
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
+
862
935
  const pendingDecisionCards = [];
863
936
 
864
937
  for (let idx = 0; idx < msgs.length; idx++) {
@@ -866,12 +939,17 @@
866
939
  const isLast = idx === msgs.length - 1;
867
940
  if (m.role === 'user') {
868
941
  const div = document.createElement('div');
869
- div.className = 'clado-msg-user' + (m.isSteer ? ' is-steer' : '');
870
- 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` : ''));
871
949
  div.textContent = prefix + (m.text || '');
872
950
  streamEl.append(div);
873
951
  } else {
874
- const msgKey = m.id || `${s.id}_${idx}`;
952
+ const msgKey = m.id || `${s.id}_${oldestIdx + idx}`;
875
953
  const isRunningMsg = isLast && s.status === 'running';
876
954
 
877
955
  // 1. Render ordered interleaved blocks (thinking -> text -> tools -> steer -> text -> ...)
@@ -945,11 +1023,33 @@
945
1023
  sendBtn.textContent = pendingDecisionCards.length ? '回复' : '插话';
946
1024
  }
947
1025
 
948
- 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) {
949
1031
  streamEl.scrollTop = streamEl.scrollHeight;
950
1032
  }
1033
+ requestAnimationFrame(() => { suppressScrollAutoLoad = false; });
951
1034
  }
952
1035
 
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
+
953
1053
  let chatPreviewMask = null;
954
1054
  function openChatCodePreview(lang, rawCode) {
955
1055
  if (!chatPreviewMask) {
@@ -1060,6 +1160,10 @@
1060
1160
  function renderSessionPop() {
1061
1161
  const activeCount = sessions.filter(s => !s.archived).length;
1062
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
+ );
1063
1167
  const list = sessions
1064
1168
  .filter(s => (sessionFilter === 'archived' ? s.archived : !s.archived))
1065
1169
  .slice()
@@ -1071,7 +1175,10 @@
1071
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>
1072
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>
1073
1177
  </div>
1074
- <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>
1075
1182
  </div>
1076
1183
  <div class="clado-session-list clado-scroll" data-sp-list></div>
1077
1184
  `;
@@ -1083,6 +1190,25 @@
1083
1190
  renderSessionPop();
1084
1191
  };
1085
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
+ }
1086
1212
  sessionPopEl.querySelector('[data-sp-new]').onclick = e => {
1087
1213
  e.stopPropagation();
1088
1214
  createNewSessionForCurrentRole();
@@ -1097,7 +1223,7 @@
1097
1223
  for (const item of list) {
1098
1224
  const row = document.createElement('div');
1099
1225
  row.className = 'clado-session-row' + (item.id === activeSessionId ? ' active' : '');
1100
- 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);
1101
1227
 
1102
1228
  if (renamingSessionId === item.id) {
1103
1229
  row.innerHTML = `
@@ -1373,36 +1499,399 @@
1373
1499
  popoverEl.hidden = false;
1374
1500
  }
1375
1501
 
1376
- function updateSlashPopover() {
1377
- const val = inputEl.value;
1378
- if (!val.startsWith('/') || val.includes('\n')) {
1379
- if (!popoverEl.hidden && popoverEl.dataset.kind === 'slash') closePopover();
1380
- 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;
1381
1646
  }
1382
- const q = val.slice(1).toLowerCase();
1383
- const prompts = (meta?.ecosystem?.prompts || []).filter(p => !q || p.name.toLowerCase().includes(q));
1384
- if (!prompts.length) {
1385
- 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();
1386
1660
  return;
1387
1661
  }
1388
- popoverEl.dataset.kind = 'slash';
1662
+ if (composerMenuIndex >= items.length || composerMenuIndex < 0) composerMenuIndex = 0;
1663
+ popoverEl.dataset.kind = kind;
1389
1664
  popoverEl.replaceChildren();
1390
- 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) => {
1391
1672
  const btn = document.createElement('button');
1392
1673
  btn.type = 'button';
1393
- btn.className = 'clado-pop-item';
1394
- 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>`;
1395
- btn.onclick = () => {
1396
- inputEl.value = '/' + p.name + ' ';
1397
- autoGrowInput();
1398
- closePopover();
1399
- 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);
1400
1690
  };
1401
1691
  popoverEl.append(btn);
1402
- }
1692
+ });
1403
1693
  popoverEl.hidden = false;
1404
1694
  }
1405
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
+
1406
1895
  // =========================================================================
1407
1896
  // 2. Streaming Pi Turn, Live Tool Calls & Safe Cancel (Preserving History!)
1408
1897
  // =========================================================================
@@ -1692,6 +2181,14 @@
1692
2181
  }
1693
2182
 
1694
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
+ }
1695
2192
  inputEl.value = '';
1696
2193
  autoGrowInput();
1697
2194
  closePopover();
@@ -1764,7 +2261,11 @@
1764
2261
  syncSendModeUi();
1765
2262
  showToast(sendMode === 'ctrl-enter' ? '已切换:Enter 换行,Ctrl+Enter 发送' : '已切换:Enter 发送,Shift+Enter 换行');
1766
2263
  };
1767
- inputEl.addEventListener('focus', () => renderContextChips());
2264
+ inputEl.addEventListener('focus', () => {
2265
+ renderContextChips();
2266
+ ensureMentionSources(false);
2267
+ });
2268
+ inputEl.addEventListener('click', () => updateSlashPopover());
1768
2269
  inputEl.addEventListener('input', () => {
1769
2270
  autoGrowInput();
1770
2271
  updateSlashPopover();
@@ -1775,6 +2276,23 @@
1775
2276
  closeSessionPop();
1776
2277
  return;
1777
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
+ }
1778
2296
  if (e.key === 'Enter' && !e.isComposing) {
1779
2297
  if (sendMode === 'ctrl-enter') {
1780
2298
  if (e.ctrlKey || e.metaKey) {
@@ -2336,6 +2854,7 @@
2336
2854
  }
2337
2855
 
2338
2856
  let memorySubTab = 'agents';
2857
+ let autoDraftTriggerType = 'schedule';
2339
2858
  function renderMemoryTab() {
2340
2859
  const content = meta.memory?.content || '';
2341
2860
  const pdocs = meta.platformDocs || {};
@@ -2343,24 +2862,34 @@
2343
2862
  const refPath = pdocs.referencePath || ((meta.agentDir || '~/.pi/agent') + '/clado-reference.md');
2344
2863
  const ctxContent = pdocs.contextContent || '';
2345
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 || '归档员';
2346
2870
 
2347
2871
  const isAgents = memorySubTab === 'agents';
2348
2872
  const isPlatform = memorySubTab === 'platform';
2349
2873
  const isReference = memorySubTab === 'reference';
2874
+ const isAutomations = memorySubTab === 'automations';
2350
2875
 
2351
2876
  sBody.innerHTML = `
2352
2877
  <div class="clado-setting-row">
2353
2878
  <div>
2354
2879
  <div style="font-size:18px;font-weight:630;">工作区与平台上下文</div>
2355
- <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>
2880
+ <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>
2356
2881
  </div>
2357
- <div style="display:flex;gap:6px;">
2882
+ <div style="display:flex;gap:6px;flex-wrap:wrap;">
2358
2883
  ${isAgents ? '<button type="button" class="clado-ui-button clado-ui-button-primary" data-save-mem>保存 AGENTS.md</button>' : ''}
2359
2884
  ${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>' : ''}
2885
+ ${isAutomations ? `
2886
+ <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>
2887
+ ` : ''}
2360
2888
  </div>
2361
2889
  </div>
2362
2890
  <div class="clado-ctx-pills" style="margin-bottom:2px;">
2363
2891
  <button type="button" class="clado-ctx-pill-btn ${isAgents ? 'active' : ''}" data-mtab="agents">项目记忆 (AGENTS.md)</button>
2892
+ <button type="button" class="clado-ctx-pill-btn ${isAutomations ? 'active' : ''}" data-mtab="automations">定时唤醒与事件订阅 (${autoRules.length})${autoState.paused ? ' · 已暂停' : ''}</button>
2364
2893
  <button type="button" class="clado-ctx-pill-btn ${isPlatform ? 'active' : ''}" data-mtab="platform">自动注入上下文 (clado-context.md)${pdocs.customized ? ' · 已自定义' : ''}</button>
2365
2894
  <button type="button" class="clado-ctx-pill-btn ${isReference ? 'active' : ''}" data-mtab="reference">完整参考手册 (clado-reference.md)</button>
2366
2895
  </div>
@@ -2369,6 +2898,125 @@
2369
2898
  <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>
2370
2899
  </div>
2371
2900
  <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>
2901
+ ` : isAutomations ? `
2902
+ <div class="clado-well-box" style="padding:10px 13px;font-size:11.5px;color:var(--clado-ui-muted);line-height:1.55;">
2903
+ 统一事件总线提供中立的 <strong style="color:var(--clado-ui-text);">周期定时唤醒</strong>(支持 <code>onlyIfActive</code> 无活跃会话时零 Token 自动跳过)与 <strong style="color:var(--clado-ui-text);">6 大类系统事件订阅</strong> 原语,内置防自触发、防抖合并与多会话进展熔断(Progress Guard)。规则持久化于 <code>.clado/automations.json</code>,由用户或插件按需自由配置。
2904
+ </div>
2905
+ <div style="display:flex;flex-direction:column;gap:8px;" data-auto-list>
2906
+ ${autoRules.length ? autoRules.map(rule => {
2907
+ const trig = rule.trigger || {};
2908
+ const trigDesc = trig.type === 'event'
2909
+ ? `事件订阅:${(trig.eventTypes || []).join(', ')}`
2910
+ : `每 ${trig.intervalMinutes || 10} 分钟${trig.onlyIfActive !== false ? ` · 活跃窗口 ${trig.activeWindowMinutes || 20} 分钟(无活跃跳过)` : ' · 固定触发'}`;
2911
+ const filterParts = [];
2912
+ if (trig.filter?.file) filterParts.push('文件:' + trig.filter.file);
2913
+ if (trig.filter?.card) filterParts.push('卡片:' + trig.filter.card);
2914
+ if (trig.filter?.tag) filterParts.push('Tag:' + trig.filter.tag);
2915
+ if (trig.filter?.roleId) filterParts.push('来源角色:' + roleNameOf(trig.filter.roleId));
2916
+ return `
2917
+ <div class="clado-well-box clado-auto-card" data-rule-id="${esc(rule.id)}">
2918
+ <div class="clado-setting-row">
2919
+ <div style="min-width:0;flex:1;">
2920
+ <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;">
2921
+ <span style="font-size:13px;font-weight:610;">${esc(rule.name)}</span>
2922
+ <span class="clado-chip ${trig.type === 'event' ? 'clado-chip-violet' : 'clado-chip-sky'}">${trig.type === 'event' ? '事件触发' : '定时巡检'}</span>
2923
+ <span class="clado-chip clado-chip-mint">唤醒:${esc(roleNameOf(rule.target?.roleId))}</span>
2924
+ </div>
2925
+ <div class="clado-auto-meta" style="margin-top:4px;">
2926
+ <span>${esc(trigDesc)}</span>
2927
+ ${filterParts.length ? `<span>· 过滤:${esc(filterParts.join(' / '))}</span>` : ''}
2928
+ <span>· 已运行 ${rule.runCount || 0} 次 · 空转跳过 ${rule.skipCount || 0} 次</span>
2929
+ ${rule.lastSkipReason ? `<span>· 最近跳过:${esc(rule.lastSkipReason)}</span>` : ''}
2930
+ </div>
2931
+ </div>
2932
+ <div style="display:flex;align-items:center;gap:8px;flex:none;">
2933
+ <button type="button" class="clado-dock-mini-btn" data-auto-run="${esc(rule.id)}">立即运行</button>
2934
+ <button type="button" class="clado-dock-mini-btn" data-auto-del="${esc(rule.id)}" style="color:#be123c;">删除</button>
2935
+ <div class="clado-switch ${rule.enabled ? 'on' : ''}" data-auto-tog="${esc(rule.id)}" title="${rule.enabled ? '点击禁用' : '点击启用'}"></div>
2936
+ </div>
2937
+ </div>
2938
+ <div class="clado-auto-prompt">${esc(rule.target?.prompt || '')}</div>
2939
+ </div>
2940
+ `;
2941
+ }).join('') : `
2942
+ <div class="clado-well-box" style="text-align:center;font-size:12px;color:var(--clado-ui-subtle);padding:16px;">
2943
+ 尚未配置定时唤醒或事件订阅规则,可在下方按需创建自定义规则。
2944
+ </div>
2945
+ `}
2946
+ </div>
2947
+ <div class="clado-well-box" style="display:flex;flex-direction:column;gap:10px;" data-auto-form>
2948
+ <div class="clado-setting-row">
2949
+ <div style="font-size:13px;font-weight:610;">新建自定义唤醒规则</div>
2950
+ <div class="clado-ctx-pills">
2951
+ <button type="button" class="clado-ctx-pill-btn ${autoDraftTriggerType === 'schedule' ? 'active' : ''}" data-auto-draft-type="schedule">定时周期唤醒</button>
2952
+ <button type="button" class="clado-ctx-pill-btn ${autoDraftTriggerType === 'event' ? 'active' : ''}" data-auto-draft-type="event">系统事件订阅</button>
2953
+ </div>
2954
+ </div>
2955
+ <div class="clado-rt-grid">
2956
+ <div class="clado-rt-field">
2957
+ <label class="clado-rt-label">规则名称</label>
2958
+ <input type="text" class="clado-field" data-af-name placeholder="例如:核心画布变更复核 / 定时状态检查" />
2959
+ </div>
2960
+ <div class="clado-rt-field">
2961
+ <label class="clado-rt-label">唤醒目标角色</label>
2962
+ <select class="clado-field" data-af-role>
2963
+ ${roles.map((r, i) => `<option value="${esc(r.id)}" ${i === 0 ? 'selected' : ''}>${esc(r.name)} (${esc(r.id)})</option>`).join('')}
2964
+ </select>
2965
+ </div>
2966
+ </div>
2967
+ ${autoDraftTriggerType === 'schedule' ? `
2968
+ <div class="clado-rt-grid">
2969
+ <div class="clado-rt-field">
2970
+ <label class="clado-rt-label">巡检间隔(分钟)</label>
2971
+ <input type="number" class="clado-field" data-af-interval min="1" max="1440" value="10" />
2972
+ </div>
2973
+ <div class="clado-rt-field">
2974
+ <label class="clado-rt-label">活跃会话扫描窗口(分钟)</label>
2975
+ <input type="number" class="clado-field" data-af-window min="1" max="1440" value="20" />
2976
+ </div>
2977
+ </div>
2978
+ <div class="clado-rt-checks">
2979
+ <label><input type="checkbox" data-af-only-active checked /> 仅在窗口内有其他会话活跃时唤醒(无活跃零 Token 自动跳过)</label>
2980
+ </div>
2981
+ ` : `
2982
+ <div class="clado-rt-field">
2983
+ <label class="clado-rt-label"><span>订阅的系统事件(6 大类统一事件总线)</span><span>可多选</span></label>
2984
+ <div class="clado-auto-events-grid clado-scroll">
2985
+ ${eventCatalog.map(group => `
2986
+ <div class="clado-auto-ev-group">
2987
+ <div class="clado-auto-ev-title">${esc(group.label)}</div>
2988
+ ${(group.events || []).map(ev => `
2989
+ <label class="clado-auto-ev-opt" title="${esc(ev.description)}">
2990
+ <input type="checkbox" data-af-event value="${esc(ev.type)}" ${ev.type === 'card.updated' ? 'checked' : ''} />
2991
+ <span><code>${esc(ev.type)}</code> · ${esc(ev.description)}</span>
2992
+ </label>
2993
+ `).join('')}
2994
+ </div>
2995
+ `).join('')}
2996
+ </div>
2997
+ </div>
2998
+ <div class="clado-rt-grid">
2999
+ <div class="clado-rt-field">
3000
+ <label class="clado-rt-label">过滤画布文件(可选)</label>
3001
+ <input type="text" class="clado-field" data-af-file placeholder="例如:architecture.md" />
3002
+ </div>
3003
+ <div class="clado-rt-field">
3004
+ <label class="clado-rt-label">过滤卡片名 / 语义 Tag(可选)</label>
3005
+ <div style="display:flex;gap:6px;">
3006
+ <input type="text" class="clado-field" data-af-card placeholder="卡片标题" />
3007
+ <input type="text" class="clado-field" data-af-tag placeholder="#tag" />
3008
+ </div>
3009
+ </div>
3010
+ </div>
3011
+ `}
3012
+ <div class="clado-rt-field">
3013
+ <label class="clado-rt-label">唤醒后下达的任务指令</label>
3014
+ <textarea class="clado-field clado-scroll" data-af-prompt rows="2" style="resize:vertical;line-height:1.5;" placeholder="填写唤醒目标角色后要执行的具体检查或协作指令…"></textarea>
3015
+ </div>
3016
+ <div style="display:flex;justify-content:flex-end;">
3017
+ <button type="button" class="clado-ui-button clado-ui-button-primary" data-af-save>保存唤醒规则</button>
3018
+ </div>
3019
+ </div>
2372
3020
  ` : isPlatform ? `
2373
3021
  <div class="clado-well-box clado-setting-row" style="padding:9px 12px;font-size:11.5px;color:var(--clado-ui-muted);gap:8px;">
2374
3022
  <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>
@@ -2425,6 +3073,101 @@
2425
3073
  } catch (e) { showToast(e.message); }
2426
3074
  };
2427
3075
  }
3076
+
3077
+ if (isAutomations) {
3078
+ const pauseBtn = sBody.querySelector('[data-auto-toggle-pause]');
3079
+ if (pauseBtn) {
3080
+ pauseBtn.onclick = async () => {
3081
+ try {
3082
+ await apiConfig({ action: 'toggle_automations_pause', paused: !autoState.paused });
3083
+ renderMemoryTab();
3084
+ showToast(!autoState.paused ? '已全局暂停全部自动化唤醒' : '已恢复自动化唤醒引擎');
3085
+ } catch (e) { showToast(e.message); }
3086
+ };
3087
+ }
3088
+ sBody.querySelectorAll('[data-auto-tog]').forEach(sw => {
3089
+ sw.onclick = async () => {
3090
+ const r = autoRules.find(x => x.id === sw.dataset.autoTog);
3091
+ if (!r) return;
3092
+ try {
3093
+ await apiConfig({ action: 'save_automation', rule: { ...r, enabled: !r.enabled } });
3094
+ renderMemoryTab();
3095
+ showToast(r.name + (!r.enabled ? ' 已启用' : ' 已禁用'));
3096
+ } catch (e) { showToast(e.message); }
3097
+ };
3098
+ });
3099
+ sBody.querySelectorAll('[data-auto-run]').forEach(btn => {
3100
+ btn.onclick = async () => {
3101
+ try {
3102
+ btn.disabled = true;
3103
+ await apiConfig({ action: 'run_automation_now', ruleId: btn.dataset.autoRun });
3104
+ renderMemoryTab();
3105
+ showToast('已立即唤醒目标角色执行任务');
3106
+ } catch (e) {
3107
+ btn.disabled = false;
3108
+ showToast(e.message);
3109
+ }
3110
+ };
3111
+ });
3112
+ sBody.querySelectorAll('[data-auto-del]').forEach(btn => {
3113
+ btn.onclick = async () => {
3114
+ try {
3115
+ await apiConfig({ action: 'delete_automation', ruleId: btn.dataset.autoDel });
3116
+ renderMemoryTab();
3117
+ showToast('已删除自动化规则');
3118
+ } catch (e) { showToast(e.message); }
3119
+ };
3120
+ });
3121
+ sBody.querySelectorAll('[data-auto-draft-type]').forEach(btn => {
3122
+ btn.onclick = () => {
3123
+ autoDraftTriggerType = btn.dataset.autoDraftType === 'event' ? 'event' : 'schedule';
3124
+ renderMemoryTab();
3125
+ };
3126
+ });
3127
+ const saveAutoBtn = sBody.querySelector('[data-af-save]');
3128
+ if (saveAutoBtn) {
3129
+ saveAutoBtn.onclick = async () => {
3130
+ const name = sBody.querySelector('[data-af-name]')?.value.trim() || (autoDraftTriggerType === 'schedule' ? '定时巡检规则' : '系统事件响应规则');
3131
+ const roleId = sBody.querySelector('[data-af-role]')?.value || 'archivist';
3132
+ const prompt = sBody.querySelector('[data-af-prompt]')?.value.trim() || '';
3133
+ if (!prompt) {
3134
+ showToast('请填写唤醒后要执行的任务指令');
3135
+ sBody.querySelector('[data-af-prompt]')?.focus();
3136
+ return;
3137
+ }
3138
+ const trigger = autoDraftTriggerType === 'schedule'
3139
+ ? {
3140
+ type: 'schedule',
3141
+ intervalMinutes: Number(sBody.querySelector('[data-af-interval]')?.value) || 10,
3142
+ activeWindowMinutes: Number(sBody.querySelector('[data-af-window]')?.value) || 20,
3143
+ onlyIfActive: Boolean(sBody.querySelector('[data-af-only-active]')?.checked),
3144
+ eventTypes: ['schedule.tick'],
3145
+ filter: {},
3146
+ }
3147
+ : {
3148
+ type: 'event',
3149
+ eventTypes: [...sBody.querySelectorAll('[data-af-event]:checked')].map(el => el.value),
3150
+ filter: {
3151
+ file: sBody.querySelector('[data-af-file]')?.value.trim() || '',
3152
+ card: sBody.querySelector('[data-af-card]')?.value.trim() || '',
3153
+ tag: sBody.querySelector('[data-af-tag]')?.value.trim().replace(/^#/, '') || '',
3154
+ },
3155
+ };
3156
+ if (trigger.type === 'event' && !trigger.eventTypes.length) {
3157
+ showToast('请至少选择一个订阅的系统事件');
3158
+ return;
3159
+ }
3160
+ try {
3161
+ await apiConfig({
3162
+ action: 'save_automation',
3163
+ rule: { name, enabled: true, trigger, target: { roleId, sessionId: '', prompt }, debounceMs: 4000 },
3164
+ });
3165
+ renderMemoryTab();
3166
+ showToast('已保存自动化唤醒规则');
3167
+ } catch (e) { showToast(e.message); }
3168
+ };
3169
+ }
3170
+ }
2428
3171
  }
2429
3172
 
2430
3173
  function readPresenceTtlSeconds() {
@@ -2435,7 +3178,7 @@
2435
3178
  if (Number.isFinite(n) && n >= 0) return Math.round(n);
2436
3179
  }
2437
3180
  } catch {}
2438
- return 15;
3181
+ return 30;
2439
3182
  }
2440
3183
 
2441
3184
  function renderAppearanceTab() {
@@ -2444,8 +3187,8 @@
2444
3187
  const ttlOptions = [
2445
3188
  [0, '立即关闭 (0s)'],
2446
3189
  [10, '10 秒'],
2447
- [15, '15 秒 (默认)'],
2448
- [30, '30 秒'],
3190
+ [15, '15 秒'],
3191
+ [30, '30 秒 (默认)'],
2449
3192
  [60, '60 秒'],
2450
3193
  ];
2451
3194
  sBody.innerHTML = `
@@ -2462,8 +3205,8 @@
2462
3205
  </div>
2463
3206
  <div class="clado-well-box" style="display:flex;flex-direction:column;gap:10px;">
2464
3207
  <div>
2465
- <div style="font-size:13.5px;font-weight:610;">卡片协同呼吸余韵</div>
2466
- <div style="font-size:12px;color:var(--clado-ui-muted);margin-top:2px;">AI 执行期间卡片底部呼吸自动常亮,回合结束/停止后自动释放并保留短暂余韵(无需手动解锁)。</div>
3208
+ <div style="font-size:13.5px;font-weight:610;">卡片「刚刚编辑了」消退时长</div>
3209
+ <div style="font-size:12px;color:var(--clado-ui-muted);margin-top:2px;">AI 操作的卡片会在本轮期间保持高亮;回合结束或手动停止后转为「刚刚编辑了」,在你下次操作该画布后按此时长自动消退(未操作则最长保留 30 分钟自动清空)。</div>
2467
3210
  </div>
2468
3211
  <div class="clado-ctx-pills" data-presence-ttl-group>
2469
3212
  ${ttlOptions.map(([sec, label]) => `<button type="button" class="clado-ctx-pill-btn ${curTtl === sec ? 'active' : ''}" data-presence-ttl="${sec}">${label}</button>`).join('')}
@@ -2573,6 +3316,19 @@
2573
3316
  renderMarkdown,
2574
3317
  };
2575
3318
 
3319
+ let sseSyncTimer = 0;
3320
+ window.addEventListener('clado:agent-sessions', () => {
3321
+ if (runningSessionId) return;
3322
+ clearTimeout(sseSyncTimer);
3323
+ sseSyncTimer = setTimeout(async () => {
3324
+ await refreshMeta();
3325
+ if (!settingsMask.hidden && settingsTab === 'memory' && memorySubTab === 'automations') {
3326
+ renderMemoryTab();
3327
+ }
3328
+ if (!sessionPopEl.hidden) renderSessionPop();
3329
+ }, 320);
3330
+ });
3331
+
2576
3332
  refreshMeta();
2577
3333
 
2578
3334
  return {