cladogram 0.6.0-beta.5 → 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.
@@ -48,11 +48,21 @@ 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
+ MEMORY_SCRIBE_PRESET,
61
+ readAutomationsState,
62
+ saveAutomationRule,
63
+ setAutomationsPaused,
64
+ SYSTEM_EVENT_CATALOG,
65
+ } from '../agent/automations.js';
56
66
 
57
67
  const sessionIdSchema = z.string().regex(/^[a-zA-Z0-9_-]{4,80}$/);
58
68
  const canvasObjectSchema = z.object({
@@ -146,13 +156,8 @@ export function createAgentHandler({
146
156
  events = null,
147
157
  sessionFactory = null,
148
158
  remote = false,
159
+ autoStartScheduler = true,
149
160
  }) {
150
- const bridge = createPiBridge({
151
- workspaceService,
152
- events,
153
- sessionFactory,
154
- });
155
-
156
161
  const getRuntime = targetWorkspace => {
157
162
  const ws = targetWorkspace || (typeof workspace === 'function' ? workspace() : workspace);
158
163
  const info = resolveRuntimeInfo ? resolveRuntimeInfo(ws) : null;
@@ -164,8 +169,81 @@ export function createAgentHandler({
164
169
  };
165
170
  };
166
171
 
172
+ let bridge = null;
173
+
174
+ const automationEngine = createAutomationEngine({
175
+ resolveStateDir: ws => getRuntime(ws).stateDir,
176
+ listSessionsForStateDir: stateDir => listSessions(stateDir, { includeArchived: false, includeMessages: false }),
177
+ events,
178
+ autoStartTimer: autoStartScheduler,
179
+ onTrigger: async ({ workspace: ws, stateDir, rule, triggerMeta }) => {
180
+ if (!bridge) return;
181
+ const rt = getRuntime(ws);
182
+ const agentDir = resolvePiAgentDir();
183
+ const eventLines = Array.isArray(triggerMeta?.events) && triggerMeta.events.length
184
+ ? '\n\n触发事件摘要:\n' + triggerMeta.events.slice(-8).map(e => `- [${e.type}] ${JSON.stringify(e.payload || {}).slice(0, 220)}`).join('\n')
185
+ : (triggerMeta?.reason === 'schedule'
186
+ ? `\n\n触发方式:定时巡检(窗口:最近 ${triggerMeta.activeWindowMinutes || 20} 分钟${Array.isArray(triggerMeta.activeSessions) && triggerMeta.activeSessions.length ? `,活跃会话:${triggerMeta.activeSessions.map(s => `${s.title}(${s.id})`).join('、')}` : ''})`
187
+ : '');
188
+ const fullMessage = `${rule.target.prompt}${eventLines}`;
189
+ await bridge.sendCrossSessionMessage({
190
+ workspace: rt.workspace,
191
+ stateDir,
192
+ documentRoot: rt.documentRoot,
193
+ fromRoleName: `自动化 · ${rule.name}`,
194
+ targetSessionId: rule.target.sessionId || '',
195
+ targetRoleId: rule.target.roleId || 'archivist',
196
+ message: fullMessage,
197
+ wait: false,
198
+ automationRuleId: rule.id,
199
+ });
200
+ events?.emit(rt.workspace, 'agent.sessions', { action: 'automation_triggered', ruleId: rule.id });
201
+ },
202
+ });
203
+
204
+ const handleAutomationOp = async (ws, params = {}) => {
205
+ const rt = getRuntime(ws);
206
+ automationEngine.registerWorkspace(rt.workspace);
207
+ const act = String(params.action || 'list').trim();
208
+ if (act === 'events_catalog') {
209
+ return { ok: true, catalog: SYSTEM_EVENT_CATALOG, preset: MEMORY_SCRIBE_PRESET };
210
+ }
211
+ if (act === 'list') {
212
+ return { ok: true, ...readAutomationsState(rt.stateDir), preset: MEMORY_SCRIBE_PRESET };
213
+ }
214
+ if (act === 'save') {
215
+ const saved = saveAutomationRule(rt.stateDir, params.rule || params);
216
+ return { ok: true, ...saved };
217
+ }
218
+ if (act === 'delete') {
219
+ const removed = deleteAutomationRule(rt.stateDir, params.ruleId || params.id);
220
+ return { ok: true, ...removed };
221
+ }
222
+ if (act === 'pause' || act === 'resume') {
223
+ const state = setAutomationsPaused(rt.stateDir, act === 'pause');
224
+ return { ok: true, ...state };
225
+ }
226
+ if (act === 'run_now') {
227
+ return await automationEngine.runRuleNow(rt.workspace, params.ruleId || params.id);
228
+ }
229
+ throw new DocumentError(`不支持的自动化操作:${act}`, 400);
230
+ };
231
+
232
+ bridge = createPiBridge({
233
+ workspaceService,
234
+ events,
235
+ sessionFactory,
236
+ onSystemEvent: (ws, eventType, payload) => {
237
+ automationEngine.notifyEvent(ws, eventType, payload);
238
+ },
239
+ automationOps: {
240
+ handle: params => handleAutomationOp(params?.workspace || null, params),
241
+ },
242
+ });
243
+
167
244
  async function buildFullMeta(targetWorkspace) {
168
245
  const rt = getRuntime(targetWorkspace);
246
+ automationEngine.registerWorkspace(rt.workspace);
169
247
  const agentDir = resolvePiAgentDir();
170
248
  const [modelsInfo, ecosystem] = await Promise.all([
171
249
  listProvidersAndModels(rt.workspace, agentDir),
@@ -176,7 +254,8 @@ export function createAgentHandler({
176
254
  const memory = readAgentsMemory(rt.workspace);
177
255
  const platformDocs = ensureCladoPlatformDocs(agentDir);
178
256
  const canvasComponents = readCanvasComponentsConfig(agentDir);
179
- const sessions = listSessions(rt.stateDir, { includeArchived: true, agentDir });
257
+ const sessions = listSessions(rt.stateDir, { includeArchived: true, messageLimit: 30, agentDir });
258
+ const automations = readAutomationsState(rt.stateDir);
180
259
 
181
260
  return {
182
261
  engine: 'pi',
@@ -198,31 +277,132 @@ export function createAgentHandler({
198
277
  workspacePlugins: rt.pluginDescriptors,
199
278
  memory,
200
279
  platformDocs,
280
+ automations,
281
+ eventCatalog: SYSTEM_EVENT_CATALOG,
282
+ memoryScribePreset: MEMORY_SCRIBE_PRESET,
283
+ activeRuns: bridge.listActiveRuns(rt.workspace),
201
284
  sessions,
202
285
  };
203
286
  }
204
287
 
205
288
  return {
289
+ automationEngine,
290
+ notifySystemEvent(targetWorkspace, eventType, payload = {}) {
291
+ const rt = getRuntime(targetWorkspace);
292
+ automationEngine.notifyEvent(rt.workspace, eventType, payload);
293
+ },
294
+
295
+ async handleMcpSessions(args = {}) {
296
+ const rt = getRuntime(args.workspace);
297
+ automationEngine.registerWorkspace(rt.workspace);
298
+ const agentDir = resolvePiAgentDir();
299
+ const act = String(args.action || 'list').trim();
300
+ if (act === 'list') {
301
+ const list = listSessions(rt.stateDir, {
302
+ includeArchived: Boolean(args.includeArchived),
303
+ includeMessages: false,
304
+ sinceMinutes: Number(args.sinceMinutes) || 0,
305
+ agentDir,
306
+ });
307
+ return { ok: true, workspace: rt.workspace, count: list.length, sessions: list };
308
+ }
309
+ if (act === 'read') {
310
+ const transcript = bridge.readSessionTranscript(rt.stateDir, args.sessionId, {
311
+ limit: Number(args.limit) || 12,
312
+ agentDir,
313
+ });
314
+ if (!transcript) throw new DocumentError(`找不到会话:${args.sessionId}`, 404);
315
+ return { ok: true, workspace: rt.workspace, ...transcript };
316
+ }
317
+ if (act === 'open') {
318
+ const opened = bridge.openOrCreatePeerSession(rt.stateDir, {
319
+ roleId: args.roleId || 'architect',
320
+ title: args.title || '',
321
+ reuseLatest: args.reuseLatest !== false,
322
+ agentDir,
323
+ });
324
+ return { ok: true, workspace: rt.workspace, ...opened };
325
+ }
326
+ if (act === 'send') {
327
+ const res = await bridge.sendCrossSessionMessage({
328
+ workspace: rt.workspace,
329
+ stateDir: rt.stateDir,
330
+ documentRoot: rt.documentRoot,
331
+ fromSessionId: args.fromSessionId || '',
332
+ fromRoleName: args.fromRoleName || '外部 MCP',
333
+ targetSessionId: args.targetSessionId || '',
334
+ targetRoleId: args.targetRoleId || '',
335
+ message: args.message || '',
336
+ wait: Boolean(args.wait),
337
+ });
338
+ return { workspace: rt.workspace, ...res };
339
+ }
340
+ throw new DocumentError(`不支持的会话操作:${act}`, 400);
341
+ },
342
+
343
+ async handleMcpAutomations(args = {}) {
344
+ return await handleAutomationOp(args.workspace, args);
345
+ },
346
+
206
347
  async handleMeta(req, res, targetWorkspace) {
207
348
  if (req.method !== 'GET') throw new DocumentError('仅支持 GET。', 405);
208
349
  const data = await buildFullMeta(targetWorkspace);
209
350
  sendJson(res, 200, data);
210
351
  },
211
352
 
353
+ async handleAutomations(req, res, url, targetWorkspace) {
354
+ const rt = getRuntime(targetWorkspace);
355
+ automationEngine.registerWorkspace(rt.workspace);
356
+ if (req.method === 'GET') {
357
+ const state = readAutomationsState(rt.stateDir);
358
+ sendJson(res, 200, {
359
+ ok: true,
360
+ ...state,
361
+ eventCatalog: SYSTEM_EVENT_CATALOG,
362
+ preset: MEMORY_SCRIBE_PRESET,
363
+ });
364
+ return;
365
+ }
366
+ if (req.method === 'POST') {
367
+ assertSameOriginPost(req, remote);
368
+ const body = await readJsonBody(req);
369
+ const result = await handleAutomationOp(rt.workspace, body);
370
+ sendJson(res, 200, { ...result, automations: readAutomationsState(rt.stateDir) });
371
+ return;
372
+ }
373
+ throw new DocumentError('不支持的请求方法。', 405);
374
+ },
375
+
212
376
  async handleSessions(req, res, url, targetWorkspace) {
213
377
  const rt = getRuntime(targetWorkspace);
378
+ automationEngine.registerWorkspace(rt.workspace);
214
379
  const agentDir = resolvePiAgentDir();
215
380
 
216
381
  if (req.method === 'GET') {
217
382
  const id = url.searchParams.get('id');
218
383
  if (id) {
219
- const item = getSessionMeta(rt.stateDir, id, agentDir);
384
+ const limitParam = url.searchParams.get('limit');
385
+ const beforeParam = url.searchParams.get('before');
386
+ const limit = limitParam !== null ? Number(limitParam) : 30;
387
+ const item = getSessionMeta(rt.stateDir, id, agentDir, { messageLimit: limit });
220
388
  if (!item) throw new DocumentError('找不到该角色会话。', 404);
389
+ if (beforeParam !== null || limitParam !== null) {
390
+ const page = readSessionMessagesPage(rt.stateDir, id, {
391
+ limit,
392
+ before: beforeParam !== null ? Number(beforeParam) : null,
393
+ });
394
+ sendJson(res, 200, {
395
+ session: { ...item, messages: page.messages, totalMessages: page.totalMessages, oldestIndex: page.oldestIndex, hasMoreBefore: page.hasMoreBefore },
396
+ ...page,
397
+ });
398
+ return;
399
+ }
221
400
  sendJson(res, 200, { session: item });
222
401
  return;
223
402
  }
224
403
  const includeArchived = url.searchParams.get('archived') === '1';
225
- sendJson(res, 200, { sessions: listSessions(rt.stateDir, { includeArchived, agentDir }) });
404
+ const sinceMinutes = Number(url.searchParams.get('sinceMinutes') || 0);
405
+ sendJson(res, 200, { sessions: listSessions(rt.stateDir, { includeArchived, sinceMinutes, messageLimit: 30, agentDir }) });
226
406
  return;
227
407
  }
228
408
 
@@ -236,11 +416,13 @@ export function createAgentHandler({
236
416
  }
237
417
  if (body?.action === 'archive') {
238
418
  const updated = archiveSession(rt.stateDir, body.id, body.archived !== false, agentDir);
419
+ if (updated) automationEngine.notifyEvent(rt.workspace, 'session.archived', { originSessionId: updated.id, originRoleId: updated.roleId });
239
420
  sendJson(res, 200, { ok: Boolean(updated), session: updated });
240
421
  return;
241
422
  }
242
423
  if (body?.action === 'rollback') {
243
424
  const result = restoreCanvasSnapshot(rt.documentRoot, rt.stateDir, body.id, body.snapshotId || '', events, rt.workspace);
425
+ automationEngine.notifyEvent(rt.workspace, 'human.rollback', { file: result.file, sessionId: body.id });
244
426
  sendJson(res, 200, result);
245
427
  return;
246
428
  }
@@ -254,12 +436,34 @@ export function createAgentHandler({
254
436
  sendJson(res, 200, result);
255
437
  return;
256
438
  }
439
+ if (body?.action === 'abort_all') {
440
+ const stoppedCount = await bridge.abortAllRuns(rt.workspace);
441
+ sendJson(res, 200, { ok: true, stoppedCount });
442
+ return;
443
+ }
444
+ if (body?.action === 'send_peer') {
445
+ const result = await bridge.sendCrossSessionMessage({
446
+ workspace: rt.workspace,
447
+ stateDir: rt.stateDir,
448
+ documentRoot: rt.documentRoot,
449
+ fromSessionId: body.fromSessionId || '',
450
+ fromRoleId: body.fromRoleId || '',
451
+ fromRoleName: body.fromRoleName || '同伴角色',
452
+ targetSessionId: body.targetSessionId || '',
453
+ targetRoleId: body.targetRoleId || '',
454
+ message: body.message || '',
455
+ wait: Boolean(body.wait),
456
+ });
457
+ sendJson(res, 200, result);
458
+ return;
459
+ }
257
460
  const created = upsertSessionMeta(rt.stateDir, {
258
461
  id: body.id ? safeSessionId(body.id) : undefined,
259
462
  title: body.title,
260
463
  roleId: body.roleId || body.persona || 'architect',
261
464
  model: body.model || '',
262
465
  }, agentDir);
466
+ automationEngine.notifyEvent(rt.workspace, 'session.created', { originSessionId: created.id, originRoleId: created.roleId, title: created.title });
263
467
  sendJson(res, 200, { ok: true, session: created });
264
468
  return;
265
469
  }
@@ -375,6 +579,27 @@ export function createAgentHandler({
375
579
  }
376
580
  if (action === 'save_memory') {
377
581
  const result = saveAgentsMemory(rt.workspace, body.content);
582
+ automationEngine.notifyEvent(rt.workspace, 'memory.updated', { file: 'AGENTS.md', source: 'settings' });
583
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
584
+ return;
585
+ }
586
+ if (action === 'save_automation') {
587
+ const result = saveAutomationRule(rt.stateDir, body.rule || body);
588
+ sendJson(res, 200, { ok: true, ...result, meta: await buildFullMeta(targetWorkspace) });
589
+ return;
590
+ }
591
+ if (action === 'delete_automation') {
592
+ const result = deleteAutomationRule(rt.stateDir, body.ruleId || body.id);
593
+ sendJson(res, 200, { ok: true, ...result, meta: await buildFullMeta(targetWorkspace) });
594
+ return;
595
+ }
596
+ if (action === 'toggle_automations_pause') {
597
+ const result = setAutomationsPaused(rt.stateDir, Boolean(body.paused));
598
+ sendJson(res, 200, { ok: true, automations: result, meta: await buildFullMeta(targetWorkspace) });
599
+ return;
600
+ }
601
+ if (action === 'run_automation_now') {
602
+ const result = await automationEngine.runRuleNow(rt.workspace, body.ruleId || body.id);
378
603
  sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
379
604
  return;
380
605
  }
@@ -465,6 +690,13 @@ export function createAgentHandler({
465
690
  }
466
691
 
467
692
  // action === 'prompt'
693
+ if (input.canvas?.selection?.length || input.canvas?.textSnippet?.text) {
694
+ automationEngine.notifyEvent(rt.workspace, 'human.selection_sent', {
695
+ file: input.canvas?.file || '',
696
+ cards: (input.canvas?.selection || []).map(p => (Array.isArray(p) ? p[0] : String(p || ''))),
697
+ targetSessionId: input.session,
698
+ });
699
+ }
468
700
  await bridge.runTurn({
469
701
  workspace: rt.workspace,
470
702
  stateDir: rt.stateDir,
@@ -480,6 +712,7 @@ export function createAgentHandler({
480
712
  },
481
713
 
482
714
  close() {
715
+ automationEngine.dispose();
483
716
  return bridge.closeAll();
484
717
  },
485
718
  };
@@ -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 => {