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.
@@ -48,11 +48,20 @@ import {
48
48
  deleteSession,
49
49
  getSessionMeta,
50
50
  listSessions,
51
+ readSessionMessagesPage,
51
52
  renameSession,
52
53
  restoreCanvasSnapshot,
53
54
  safeSessionId,
54
55
  upsertSessionMeta,
55
56
  } from '../agent/pi-bridge.js';
57
+ import {
58
+ createAutomationEngine,
59
+ deleteAutomationRule,
60
+ readAutomationsState,
61
+ saveAutomationRule,
62
+ setAutomationsPaused,
63
+ SYSTEM_EVENT_CATALOG,
64
+ } from '../agent/automations.js';
56
65
 
57
66
  const sessionIdSchema = z.string().regex(/^[a-zA-Z0-9_-]{4,80}$/);
58
67
  const canvasObjectSchema = z.object({
@@ -146,13 +155,8 @@ export function createAgentHandler({
146
155
  events = null,
147
156
  sessionFactory = null,
148
157
  remote = false,
158
+ autoStartScheduler = true,
149
159
  }) {
150
- const bridge = createPiBridge({
151
- workspaceService,
152
- events,
153
- sessionFactory,
154
- });
155
-
156
160
  const getRuntime = targetWorkspace => {
157
161
  const ws = targetWorkspace || (typeof workspace === 'function' ? workspace() : workspace);
158
162
  const info = resolveRuntimeInfo ? resolveRuntimeInfo(ws) : null;
@@ -164,8 +168,81 @@ export function createAgentHandler({
164
168
  };
165
169
  };
166
170
 
171
+ let bridge = null;
172
+
173
+ const automationEngine = createAutomationEngine({
174
+ resolveStateDir: ws => getRuntime(ws).stateDir,
175
+ listSessionsForStateDir: stateDir => listSessions(stateDir, { includeArchived: false, includeMessages: false }),
176
+ events,
177
+ autoStartTimer: autoStartScheduler,
178
+ onTrigger: async ({ workspace: ws, stateDir, rule, triggerMeta }) => {
179
+ if (!bridge) return;
180
+ const rt = getRuntime(ws);
181
+ const agentDir = resolvePiAgentDir();
182
+ const eventLines = Array.isArray(triggerMeta?.events) && triggerMeta.events.length
183
+ ? '\n\n触发事件摘要:\n' + triggerMeta.events.slice(-8).map(e => `- [${e.type}] ${JSON.stringify(e.payload || {}).slice(0, 220)}`).join('\n')
184
+ : (triggerMeta?.reason === 'schedule'
185
+ ? `\n\n触发方式:定时巡检(窗口:最近 ${triggerMeta.activeWindowMinutes || 20} 分钟${Array.isArray(triggerMeta.activeSessions) && triggerMeta.activeSessions.length ? `,活跃会话:${triggerMeta.activeSessions.map(s => `${s.title}(${s.id})`).join('、')}` : ''})`
186
+ : '');
187
+ const fullMessage = `${rule.target.prompt}${eventLines}`;
188
+ await bridge.sendCrossSessionMessage({
189
+ workspace: rt.workspace,
190
+ stateDir,
191
+ documentRoot: rt.documentRoot,
192
+ fromRoleName: `自动化 · ${rule.name}`,
193
+ targetSessionId: rule.target.sessionId || '',
194
+ targetRoleId: rule.target.roleId || 'archivist',
195
+ message: fullMessage,
196
+ wait: false,
197
+ automationRuleId: rule.id,
198
+ });
199
+ events?.emit(rt.workspace, 'agent.sessions', { action: 'automation_triggered', ruleId: rule.id });
200
+ },
201
+ });
202
+
203
+ const handleAutomationOp = async (ws, params = {}) => {
204
+ const rt = getRuntime(ws);
205
+ automationEngine.registerWorkspace(rt.workspace);
206
+ const act = String(params.action || 'list').trim();
207
+ if (act === 'events_catalog') {
208
+ return { ok: true, catalog: SYSTEM_EVENT_CATALOG };
209
+ }
210
+ if (act === 'list') {
211
+ return { ok: true, ...readAutomationsState(rt.stateDir) };
212
+ }
213
+ if (act === 'save') {
214
+ const saved = saveAutomationRule(rt.stateDir, params.rule || params);
215
+ return { ok: true, ...saved };
216
+ }
217
+ if (act === 'delete') {
218
+ const removed = deleteAutomationRule(rt.stateDir, params.ruleId || params.id);
219
+ return { ok: true, ...removed };
220
+ }
221
+ if (act === 'pause' || act === 'resume') {
222
+ const state = setAutomationsPaused(rt.stateDir, act === 'pause');
223
+ return { ok: true, ...state };
224
+ }
225
+ if (act === 'run_now') {
226
+ return await automationEngine.runRuleNow(rt.workspace, params.ruleId || params.id);
227
+ }
228
+ throw new DocumentError(`不支持的自动化操作:${act}`, 400);
229
+ };
230
+
231
+ bridge = createPiBridge({
232
+ workspaceService,
233
+ events,
234
+ sessionFactory,
235
+ onSystemEvent: (ws, eventType, payload) => {
236
+ automationEngine.notifyEvent(ws, eventType, payload);
237
+ },
238
+ automationOps: {
239
+ handle: params => handleAutomationOp(params?.workspace || null, params),
240
+ },
241
+ });
242
+
167
243
  async function buildFullMeta(targetWorkspace) {
168
244
  const rt = getRuntime(targetWorkspace);
245
+ automationEngine.registerWorkspace(rt.workspace);
169
246
  const agentDir = resolvePiAgentDir();
170
247
  const [modelsInfo, ecosystem] = await Promise.all([
171
248
  listProvidersAndModels(rt.workspace, agentDir),
@@ -176,7 +253,8 @@ export function createAgentHandler({
176
253
  const memory = readAgentsMemory(rt.workspace);
177
254
  const platformDocs = ensureCladoPlatformDocs(agentDir);
178
255
  const canvasComponents = readCanvasComponentsConfig(agentDir);
179
- const sessions = listSessions(rt.stateDir, { includeArchived: true, agentDir });
256
+ const sessions = listSessions(rt.stateDir, { includeArchived: true, messageLimit: 30, agentDir });
257
+ const automations = readAutomationsState(rt.stateDir);
180
258
 
181
259
  return {
182
260
  engine: 'pi',
@@ -198,31 +276,130 @@ export function createAgentHandler({
198
276
  workspacePlugins: rt.pluginDescriptors,
199
277
  memory,
200
278
  platformDocs,
279
+ automations,
280
+ eventCatalog: SYSTEM_EVENT_CATALOG,
281
+ activeRuns: bridge.listActiveRuns(rt.workspace),
201
282
  sessions,
202
283
  };
203
284
  }
204
285
 
205
286
  return {
287
+ automationEngine,
288
+ notifySystemEvent(targetWorkspace, eventType, payload = {}) {
289
+ const rt = getRuntime(targetWorkspace);
290
+ automationEngine.notifyEvent(rt.workspace, eventType, payload);
291
+ },
292
+
293
+ async handleMcpSessions(args = {}) {
294
+ const rt = getRuntime(args.workspace);
295
+ automationEngine.registerWorkspace(rt.workspace);
296
+ const agentDir = resolvePiAgentDir();
297
+ const act = String(args.action || 'list').trim();
298
+ if (act === 'list') {
299
+ const list = listSessions(rt.stateDir, {
300
+ includeArchived: Boolean(args.includeArchived),
301
+ includeMessages: false,
302
+ sinceMinutes: Number(args.sinceMinutes) || 0,
303
+ agentDir,
304
+ });
305
+ return { ok: true, workspace: rt.workspace, count: list.length, sessions: list };
306
+ }
307
+ if (act === 'read') {
308
+ const transcript = bridge.readSessionTranscript(rt.stateDir, args.sessionId, {
309
+ limit: Number(args.limit) || 12,
310
+ agentDir,
311
+ });
312
+ if (!transcript) throw new DocumentError(`找不到会话:${args.sessionId}`, 404);
313
+ return { ok: true, workspace: rt.workspace, ...transcript };
314
+ }
315
+ if (act === 'open') {
316
+ const opened = bridge.openOrCreatePeerSession(rt.stateDir, {
317
+ roleId: args.roleId || 'architect',
318
+ title: args.title || '',
319
+ reuseLatest: args.reuseLatest !== false,
320
+ agentDir,
321
+ });
322
+ return { ok: true, workspace: rt.workspace, ...opened };
323
+ }
324
+ if (act === 'send') {
325
+ const res = await bridge.sendCrossSessionMessage({
326
+ workspace: rt.workspace,
327
+ stateDir: rt.stateDir,
328
+ documentRoot: rt.documentRoot,
329
+ fromSessionId: args.fromSessionId || '',
330
+ fromRoleName: args.fromRoleName || '外部 MCP',
331
+ targetSessionId: args.targetSessionId || '',
332
+ targetRoleId: args.targetRoleId || '',
333
+ message: args.message || '',
334
+ wait: Boolean(args.wait),
335
+ });
336
+ return { workspace: rt.workspace, ...res };
337
+ }
338
+ throw new DocumentError(`不支持的会话操作:${act}`, 400);
339
+ },
340
+
341
+ async handleMcpAutomations(args = {}) {
342
+ return await handleAutomationOp(args.workspace, args);
343
+ },
344
+
206
345
  async handleMeta(req, res, targetWorkspace) {
207
346
  if (req.method !== 'GET') throw new DocumentError('仅支持 GET。', 405);
208
347
  const data = await buildFullMeta(targetWorkspace);
209
348
  sendJson(res, 200, data);
210
349
  },
211
350
 
351
+ async handleAutomations(req, res, url, targetWorkspace) {
352
+ const rt = getRuntime(targetWorkspace);
353
+ automationEngine.registerWorkspace(rt.workspace);
354
+ if (req.method === 'GET') {
355
+ const state = readAutomationsState(rt.stateDir);
356
+ sendJson(res, 200, {
357
+ ok: true,
358
+ ...state,
359
+ eventCatalog: SYSTEM_EVENT_CATALOG,
360
+ });
361
+ return;
362
+ }
363
+ if (req.method === 'POST') {
364
+ assertSameOriginPost(req, remote);
365
+ const body = await readJsonBody(req);
366
+ const result = await handleAutomationOp(rt.workspace, body);
367
+ sendJson(res, 200, { ...result, automations: readAutomationsState(rt.stateDir) });
368
+ return;
369
+ }
370
+ throw new DocumentError('不支持的请求方法。', 405);
371
+ },
372
+
212
373
  async handleSessions(req, res, url, targetWorkspace) {
213
374
  const rt = getRuntime(targetWorkspace);
375
+ automationEngine.registerWorkspace(rt.workspace);
214
376
  const agentDir = resolvePiAgentDir();
215
377
 
216
378
  if (req.method === 'GET') {
217
379
  const id = url.searchParams.get('id');
218
380
  if (id) {
219
- const item = getSessionMeta(rt.stateDir, id, agentDir);
381
+ const limitParam = url.searchParams.get('limit');
382
+ const beforeParam = url.searchParams.get('before');
383
+ const limit = limitParam !== null ? Number(limitParam) : 30;
384
+ const item = getSessionMeta(rt.stateDir, id, agentDir, { messageLimit: limit });
220
385
  if (!item) throw new DocumentError('找不到该角色会话。', 404);
386
+ if (beforeParam !== null || limitParam !== null) {
387
+ const page = readSessionMessagesPage(rt.stateDir, id, {
388
+ limit,
389
+ before: beforeParam !== null ? Number(beforeParam) : null,
390
+ });
391
+ sendJson(res, 200, {
392
+ session: { ...item, messages: page.messages, totalMessages: page.totalMessages, oldestIndex: page.oldestIndex, hasMoreBefore: page.hasMoreBefore },
393
+ ...page,
394
+ });
395
+ return;
396
+ }
221
397
  sendJson(res, 200, { session: item });
222
398
  return;
223
399
  }
224
400
  const includeArchived = url.searchParams.get('archived') === '1';
225
- sendJson(res, 200, { sessions: listSessions(rt.stateDir, { includeArchived, agentDir }) });
401
+ const sinceMinutes = Number(url.searchParams.get('sinceMinutes') || 0);
402
+ sendJson(res, 200, { sessions: listSessions(rt.stateDir, { includeArchived, sinceMinutes, messageLimit: 30, agentDir }) });
226
403
  return;
227
404
  }
228
405
 
@@ -236,11 +413,13 @@ export function createAgentHandler({
236
413
  }
237
414
  if (body?.action === 'archive') {
238
415
  const updated = archiveSession(rt.stateDir, body.id, body.archived !== false, agentDir);
416
+ if (updated) automationEngine.notifyEvent(rt.workspace, 'session.archived', { originSessionId: updated.id, originRoleId: updated.roleId });
239
417
  sendJson(res, 200, { ok: Boolean(updated), session: updated });
240
418
  return;
241
419
  }
242
420
  if (body?.action === 'rollback') {
243
421
  const result = restoreCanvasSnapshot(rt.documentRoot, rt.stateDir, body.id, body.snapshotId || '', events, rt.workspace);
422
+ automationEngine.notifyEvent(rt.workspace, 'human.rollback', { file: result.file, sessionId: body.id });
244
423
  sendJson(res, 200, result);
245
424
  return;
246
425
  }
@@ -254,12 +433,34 @@ export function createAgentHandler({
254
433
  sendJson(res, 200, result);
255
434
  return;
256
435
  }
436
+ if (body?.action === 'abort_all') {
437
+ const stoppedCount = await bridge.abortAllRuns(rt.workspace);
438
+ sendJson(res, 200, { ok: true, stoppedCount });
439
+ return;
440
+ }
441
+ if (body?.action === 'send_peer') {
442
+ const result = await bridge.sendCrossSessionMessage({
443
+ workspace: rt.workspace,
444
+ stateDir: rt.stateDir,
445
+ documentRoot: rt.documentRoot,
446
+ fromSessionId: body.fromSessionId || '',
447
+ fromRoleId: body.fromRoleId || '',
448
+ fromRoleName: body.fromRoleName || '同伴角色',
449
+ targetSessionId: body.targetSessionId || '',
450
+ targetRoleId: body.targetRoleId || '',
451
+ message: body.message || '',
452
+ wait: Boolean(body.wait),
453
+ });
454
+ sendJson(res, 200, result);
455
+ return;
456
+ }
257
457
  const created = upsertSessionMeta(rt.stateDir, {
258
458
  id: body.id ? safeSessionId(body.id) : undefined,
259
459
  title: body.title,
260
460
  roleId: body.roleId || body.persona || 'architect',
261
461
  model: body.model || '',
262
462
  }, agentDir);
463
+ automationEngine.notifyEvent(rt.workspace, 'session.created', { originSessionId: created.id, originRoleId: created.roleId, title: created.title });
263
464
  sendJson(res, 200, { ok: true, session: created });
264
465
  return;
265
466
  }
@@ -375,6 +576,27 @@ export function createAgentHandler({
375
576
  }
376
577
  if (action === 'save_memory') {
377
578
  const result = saveAgentsMemory(rt.workspace, body.content);
579
+ automationEngine.notifyEvent(rt.workspace, 'memory.updated', { file: 'AGENTS.md', source: 'settings' });
580
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
581
+ return;
582
+ }
583
+ if (action === 'save_automation') {
584
+ const result = saveAutomationRule(rt.stateDir, body.rule || body);
585
+ sendJson(res, 200, { ok: true, ...result, meta: await buildFullMeta(targetWorkspace) });
586
+ return;
587
+ }
588
+ if (action === 'delete_automation') {
589
+ const result = deleteAutomationRule(rt.stateDir, body.ruleId || body.id);
590
+ sendJson(res, 200, { ok: true, ...result, meta: await buildFullMeta(targetWorkspace) });
591
+ return;
592
+ }
593
+ if (action === 'toggle_automations_pause') {
594
+ const result = setAutomationsPaused(rt.stateDir, Boolean(body.paused));
595
+ sendJson(res, 200, { ok: true, automations: result, meta: await buildFullMeta(targetWorkspace) });
596
+ return;
597
+ }
598
+ if (action === 'run_automation_now') {
599
+ const result = await automationEngine.runRuleNow(rt.workspace, body.ruleId || body.id);
378
600
  sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
379
601
  return;
380
602
  }
@@ -465,6 +687,13 @@ export function createAgentHandler({
465
687
  }
466
688
 
467
689
  // action === 'prompt'
690
+ if (input.canvas?.selection?.length || input.canvas?.textSnippet?.text) {
691
+ automationEngine.notifyEvent(rt.workspace, 'human.selection_sent', {
692
+ file: input.canvas?.file || '',
693
+ cards: (input.canvas?.selection || []).map(p => (Array.isArray(p) ? p[0] : String(p || ''))),
694
+ targetSessionId: input.session,
695
+ });
696
+ }
468
697
  await bridge.runTurn({
469
698
  workspace: rt.workspace,
470
699
  stateDir: rt.stateDir,
@@ -480,6 +709,7 @@ export function createAgentHandler({
480
709
  },
481
710
 
482
711
  close() {
712
+ automationEngine.dispose();
483
713
  return bridge.closeAll();
484
714
  },
485
715
  };
@@ -666,6 +666,10 @@
666
666
  runtime.setCardPresence?.(event.data.presence);
667
667
  return;
668
668
  }
669
+ if (event.data?.type === 'clado-workspace:presence-sync') {
670
+ runtime.syncCardPresence?.(event.data.entries || []);
671
+ return;
672
+ }
669
673
  if (event.data?.type === 'clado-workspace:presence-config') {
670
674
  runtime.setPresenceConfig?.(event.data.config);
671
675
  return;
@@ -178,6 +178,7 @@
178
178
  saveView();
179
179
  syncChrome();
180
180
  frame.contentWindow.CladoPrototype?.setMode?.(next);
181
+ armPresenceAfterglowForFile(selected);
181
182
  },
182
183
  clearFocus: () => frame.contentWindow.CladoRuntime?.clearFocus(),
183
184
  showDiagnostics: () => frame.contentWindow.CladoCanvasControls?.showDiagnostics(),
@@ -1843,6 +1844,10 @@
1843
1844
  if (data.codePath) openCodeDrawerFile(data.codePath);
1844
1845
  return;
1845
1846
  }
1847
+ if (data?.type === 'clado-library:canvas-interacted') {
1848
+ armPresenceAfterglowForFile(selected);
1849
+ return;
1850
+ }
1846
1851
  if (data?.type === 'clado-library:chain-modal') { chainLock(data.value, data.mode); return; }
1847
1852
  if (data?.type === 'clado-library:lens-modal') {
1848
1853
  lensOpen = !!data.value;
@@ -1876,6 +1881,7 @@
1876
1881
  showSelection();
1877
1882
  syncFrameObjects();
1878
1883
  syncPresenceConfigToCanvas();
1884
+ syncPresenceSnapshotToCanvas();
1879
1885
  if(offline){frame.contentWindow.postMessage({type:'clado-workspace:display',mode,theme:design.theme,anchor:pendingAnchor},'*');pendingAnchor='';}
1880
1886
  else if (mode !== data.mode) frame.contentWindow.CladoPrototype?.setMode?.(mode);
1881
1887
  saveView(); $('#canvasLoading').hidden = true; syncChrome();
@@ -1892,6 +1898,29 @@
1892
1898
  status('已同步 ' + new Date(index.documents.find(d => d.file === selected)?.modified || Date.now()).toLocaleTimeString('zh-CN', { hour12: false })); post('ready');
1893
1899
  }
1894
1900
  });
1901
+
1902
+ const PRESENCE_HARD_MAX_MS = 30 * 60 * 1000;
1903
+ const presenceByFile = new Map(); // file -> Map<cardKey, Map<sessionId, entry>>
1904
+ let presenceSweepTimer = 0;
1905
+
1906
+ function toAfterglowPresenceLabel(activeLabel, fallback) {
1907
+ const raw = String(activeLabel || '').trim();
1908
+ if (!raw) return fallback || '刚刚编辑了';
1909
+ if (raw.startsWith('刚刚')) return raw;
1910
+ if (/^正在(?:新建|创建)/.test(raw)) return '刚刚新建了';
1911
+ if (/^正在删除/.test(raw)) return '刚刚删除了';
1912
+ if (/^正在移除连线/.test(raw)) return '刚刚移除了连线';
1913
+ if (/^正在连线/.test(raw)) return '刚刚连线了';
1914
+ if (/^正在调整/.test(raw)) return '刚刚调整了';
1915
+ if (/^正在修改\s+(.+)$/.test(raw)) return raw.replace(/^正在修改\s+/, '刚刚修改了 ');
1916
+ if (/^正在查看\s+(.+)$/.test(raw)) return raw.replace(/^正在查看\s+/, '刚刚查看了 ');
1917
+ if (/^正在查看/.test(raw)) return '刚刚查看了';
1918
+ if (/^正在编辑/.test(raw)) return '刚刚编辑了';
1919
+ if (/^修改\s+(.+)$/.test(raw)) return raw.replace(/^修改\s+/, '刚刚修改了 ');
1920
+ if (/^查看\s+(.+)$/.test(raw)) return raw.replace(/^查看\s+/, '刚刚查看了 ');
1921
+ return fallback || '刚刚编辑了';
1922
+ }
1923
+
1895
1924
  function readPresenceAfterglowMs() {
1896
1925
  try {
1897
1926
  const raw = localStorage.getItem('clado-presence-ttl');
@@ -1900,23 +1929,223 @@
1900
1929
  if (Number.isFinite(sec) && sec >= 0) return Math.round(sec * 1000);
1901
1930
  }
1902
1931
  } catch {}
1903
- return 15000;
1932
+ return 30000;
1933
+ }
1934
+
1935
+ function collectPresenceEntriesForFile(file) {
1936
+ if (!file) return [];
1937
+ const fileMap = presenceByFile.get(file);
1938
+ if (!fileMap) return [];
1939
+ const out = [];
1940
+ for (const cardMap of fileMap.values()) {
1941
+ for (const entry of cardMap.values()) out.push({ ...entry });
1942
+ }
1943
+ return out;
1944
+ }
1945
+
1946
+ function syncPresenceSnapshotToCanvas() {
1947
+ if (readyCanvas?.frame !== frame || !selected) return;
1948
+ try {
1949
+ frame.contentWindow.postMessage({
1950
+ type: 'clado-workspace:presence-sync',
1951
+ entries: collectPresenceEntriesForFile(selected),
1952
+ }, offline ? '*' : location.origin);
1953
+ } catch {}
1954
+ }
1955
+
1956
+ function ensurePresenceSweepTimer() {
1957
+ if (presenceByFile.size > 0 && !presenceSweepTimer) {
1958
+ presenceSweepTimer = setInterval(sweepPresenceRegistry, 1000);
1959
+ } else if (presenceByFile.size === 0 && presenceSweepTimer) {
1960
+ clearInterval(presenceSweepTimer);
1961
+ presenceSweepTimer = 0;
1962
+ }
1963
+ }
1964
+
1965
+ function sweepPresenceRegistry() {
1966
+ const now = Date.now();
1967
+ let selectedChanged = false;
1968
+ for (const [file, fileMap] of presenceByFile.entries()) {
1969
+ for (const [cardKey, cardMap] of fileMap.entries()) {
1970
+ for (const [sid, entry] of cardMap.entries()) {
1971
+ const hardCap = entry.hardExpiresAt || (entry.ts + PRESENCE_HARD_MAX_MS);
1972
+ const exp = entry.expiresAt || hardCap;
1973
+ if (now >= hardCap || (entry.phase === 'afterglow' && entry.armedAt && now >= exp)) {
1974
+ cardMap.delete(sid);
1975
+ if (file === selected) selectedChanged = true;
1976
+ }
1977
+ }
1978
+ if (!cardMap.size) fileMap.delete(cardKey);
1979
+ }
1980
+ if (!fileMap.size) presenceByFile.delete(file);
1981
+ }
1982
+ ensurePresenceSweepTimer();
1983
+ if (selectedChanged) syncPresenceSnapshotToCanvas();
1984
+ }
1985
+
1986
+ function armPresenceAfterglowForFile(file) {
1987
+ if (!file) return;
1988
+ const fileMap = presenceByFile.get(file);
1989
+ if (!fileMap) return;
1990
+ const now = Date.now();
1991
+ const afterglowMs = readPresenceAfterglowMs();
1992
+ let changed = false;
1993
+ for (const [cardKey, cardMap] of fileMap.entries()) {
1994
+ for (const [sid, entry] of cardMap.entries()) {
1995
+ if (entry.phase !== 'afterglow' || entry.armedAt) continue;
1996
+ if (afterglowMs <= 0) {
1997
+ cardMap.delete(sid);
1998
+ } else {
1999
+ entry.armedAt = now;
2000
+ const hardCap = entry.hardExpiresAt || (now + PRESENCE_HARD_MAX_MS);
2001
+ entry.expiresAt = Math.min(hardCap, now + afterglowMs);
2002
+ }
2003
+ changed = true;
2004
+ }
2005
+ if (!cardMap.size) fileMap.delete(cardKey);
2006
+ }
2007
+ if (!fileMap.size) presenceByFile.delete(file);
2008
+ ensurePresenceSweepTimer();
2009
+ if (changed && file === selected) syncPresenceSnapshotToCanvas();
1904
2010
  }
2011
+
2012
+ function applyPresenceEventToRegistry(payload) {
2013
+ if (!payload || typeof payload !== 'object') return;
2014
+ const sid = String(payload.sessionId || payload.roleId || 'agent');
2015
+ const phase = payload.phase || 'active';
2016
+ const now = Date.now();
2017
+ const afterglowMs = readPresenceAfterglowMs();
2018
+
2019
+ if (phase === 'clear') {
2020
+ const targetFile = String(payload.file || '').trim();
2021
+ const rawCards = (Array.isArray(payload.cards) ? payload.cards : [])
2022
+ .map(c => (Array.isArray(c) ? String(c[0] || '').trim() : String(c || '').trim()))
2023
+ .filter(Boolean);
2024
+ const files = targetFile ? [targetFile] : Array.from(presenceByFile.keys());
2025
+ for (const f of files) {
2026
+ const fileMap = presenceByFile.get(f);
2027
+ if (!fileMap) continue;
2028
+ const keys = rawCards.length ? rawCards : Array.from(fileMap.keys());
2029
+ for (const k of keys) {
2030
+ const cardMap = fileMap.get(k);
2031
+ if (!cardMap) continue;
2032
+ cardMap.delete(sid);
2033
+ if (!cardMap.size) fileMap.delete(k);
2034
+ }
2035
+ if (!fileMap.size) presenceByFile.delete(f);
2036
+ }
2037
+ ensurePresenceSweepTimer();
2038
+ syncPresenceSnapshotToCanvas();
2039
+ return;
2040
+ }
2041
+
2042
+ if (phase === 'afterglow') {
2043
+ // Transition ALL active entries of this session across ALL files into '刚刚编辑了' (unarmed until user interacts with that specific canvas)
2044
+ for (const [f, fileMap] of presenceByFile.entries()) {
2045
+ for (const [k, cardMap] of fileMap.entries()) {
2046
+ const existing = cardMap.get(sid);
2047
+ if (!existing || existing.phase !== 'active') continue;
2048
+ if (afterglowMs <= 0) {
2049
+ cardMap.delete(sid);
2050
+ } else {
2051
+ existing.phase = 'afterglow';
2052
+ existing.label = toAfterglowPresenceLabel(existing.label, payload.label || '刚刚编辑了');
2053
+ existing.ts = now;
2054
+ existing.armedAt = 0;
2055
+ existing.hardExpiresAt = now + PRESENCE_HARD_MAX_MS;
2056
+ existing.expiresAt = existing.hardExpiresAt;
2057
+ }
2058
+ if (!cardMap.size) fileMap.delete(k);
2059
+ }
2060
+ if (!fileMap.size) presenceByFile.delete(f);
2061
+ }
2062
+ ensurePresenceSweepTimer();
2063
+ syncPresenceSnapshotToCanvas();
2064
+ return;
2065
+ }
2066
+
2067
+ // phase === 'active': accumulate all cards touched in this turn on targetFile
2068
+ const targetFile = String(payload.file || selected || '').trim();
2069
+ const rawCards = (Array.isArray(payload.cards) ? payload.cards : [])
2070
+ .map(c => (Array.isArray(c) ? String(c[0] || '').trim() : String(c || '').trim()))
2071
+ .filter(Boolean);
2072
+ if (!targetFile || !rawCards.length) return;
2073
+
2074
+ // Refresh 30m hard cap on other still-active entries of this session
2075
+ for (const fileMap of presenceByFile.values()) {
2076
+ for (const cardMap of fileMap.values()) {
2077
+ const existing = cardMap.get(sid);
2078
+ if (existing && existing.phase === 'active') {
2079
+ existing.hardExpiresAt = now + PRESENCE_HARD_MAX_MS;
2080
+ existing.expiresAt = existing.hardExpiresAt;
2081
+ }
2082
+ }
2083
+ }
2084
+
2085
+ let fileMap = presenceByFile.get(targetFile);
2086
+ if (!fileMap) {
2087
+ fileMap = new Map();
2088
+ presenceByFile.set(targetFile, fileMap);
2089
+ }
2090
+ for (const cardKey of rawCards) {
2091
+ let cardMap = fileMap.get(cardKey);
2092
+ if (!cardMap) {
2093
+ cardMap = new Map();
2094
+ fileMap.set(cardKey, cardMap);
2095
+ }
2096
+ cardMap.set(sid, {
2097
+ file: targetFile,
2098
+ cardKey,
2099
+ sessionId: sid,
2100
+ roleId: String(payload.roleId || ''),
2101
+ roleName: String(payload.roleName || 'AI 角色'),
2102
+ tone: String(payload.tone || 'sky'),
2103
+ label: String(payload.label || '正在编辑'),
2104
+ codePath: String(payload.codePath || ''),
2105
+ phase: 'active',
2106
+ ts: now,
2107
+ armedAt: 0,
2108
+ hardExpiresAt: now + PRESENCE_HARD_MAX_MS,
2109
+ expiresAt: now + PRESENCE_HARD_MAX_MS,
2110
+ });
2111
+ }
2112
+ ensurePresenceSweepTimer();
2113
+ if (targetFile === selected) syncPresenceSnapshotToCanvas();
2114
+ }
2115
+
1905
2116
  function syncPresenceConfigToCanvas(overrideMs) {
1906
- if (readyCanvas?.frame !== frame) return;
1907
2117
  const afterglowMs = typeof overrideMs === 'number' && Number.isFinite(overrideMs) ? overrideMs : readPresenceAfterglowMs();
2118
+ const now = Date.now();
2119
+ for (const [f, fileMap] of presenceByFile.entries()) {
2120
+ for (const [k, cardMap] of fileMap.entries()) {
2121
+ for (const [sid, entry] of cardMap.entries()) {
2122
+ if (entry.phase !== 'afterglow') continue;
2123
+ if (afterglowMs <= 0) {
2124
+ cardMap.delete(sid);
2125
+ } else if (entry.armedAt) {
2126
+ const hardCap = entry.hardExpiresAt || (now + PRESENCE_HARD_MAX_MS);
2127
+ entry.expiresAt = Math.min(hardCap, entry.armedAt + afterglowMs);
2128
+ }
2129
+ }
2130
+ if (!cardMap.size) fileMap.delete(k);
2131
+ }
2132
+ if (!fileMap.size) presenceByFile.delete(f);
2133
+ }
2134
+ ensurePresenceSweepTimer();
2135
+ if (readyCanvas?.frame !== frame) return;
1908
2136
  try {
1909
2137
  frame.contentWindow.postMessage({
1910
2138
  type: 'clado-workspace:presence-config',
1911
2139
  config: { afterglowMs },
1912
2140
  }, offline ? '*' : location.origin);
1913
2141
  } catch {}
2142
+ syncPresenceSnapshotToCanvas();
1914
2143
  }
1915
2144
  addEventListener('clado:presence-config', ev => {
1916
2145
  syncPresenceConfigToCanvas(ev.detail?.afterglowMs);
1917
2146
  });
1918
2147
  function setDesign(next) { design = { ...design, ...next }; document.documentElement.dataset.theme = design.theme || 'light'; if (design.accent) document.documentElement.style.setProperty('--accent', design.accent); try { frame.contentWindow.CladoPrototype?.setDesign(design); } catch {} syncChrome(); }
1919
- window.CladoPrototype = { setDesign, fit: () => frame.contentWindow.CladoPrototype?.fit(), closeLens: () => frame.contentWindow.CladoPrototype?.closeLens() };
2148
+ window.CladoPrototype = { setDesign, fit: () => { armPresenceAfterglowForFile(selected); return frame.contentWindow.CladoPrototype?.fit(); }, closeLens: () => frame.contentWindow.CladoPrototype?.closeLens() };
1920
2149
  setDesign(design);
1921
2150
  scan();
1922
2151
  if (!offline) {
@@ -1952,9 +2181,7 @@
1952
2181
  es.addEventListener('agent.presence', event => {
1953
2182
  try {
1954
2183
  const payload = JSON.parse(event.data || '{}');
1955
- if (readyCanvas?.frame === frame && (!payload.file || payload.file === selected || payload.phase === 'afterglow' || payload.phase === 'clear')) {
1956
- frame.contentWindow.postMessage({ type: 'clado-workspace:presence', presence: payload }, location.origin);
1957
- }
2184
+ applyPresenceEventToRegistry(payload);
1958
2185
  } catch {}
1959
2186
  });
1960
2187
  es.addEventListener('agent.focus', event => {