@aiyiran/myclaw 1.1.206 → 1.1.208

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.
package/index.js CHANGED
@@ -1718,6 +1718,17 @@ const MENU_ITEMS = [
1718
1718
  ];
1719
1719
 
1720
1720
  function runInteractiveMenu() {
1721
+ // 网页命令面板、管道和后台任务没有真实 TTY,stdin 因此不提供
1722
+ // setRawMode()。这类环境无法使用方向键菜单,直接给出可执行的命令提示,
1723
+ // 避免无参数调用 `myclaw` 时抛出 TypeError。
1724
+ if (!process.stdin.isTTY || typeof process.stdin.setRawMode !== 'function') {
1725
+ console.error('[' + colors.yellow + '提示' + colors.nc + '] 当前环境不是交互式终端,无法打开快捷菜单。');
1726
+ console.error('请直接输入完整命令,例如: mc up');
1727
+ showHelp();
1728
+ process.exitCode = 1;
1729
+ return;
1730
+ }
1731
+
1721
1732
  let cursor = 0;
1722
1733
  let handler = null;
1723
1734
  let resizeHandler = null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiyiran/myclaw",
3
- "version": "1.1.206",
3
+ "version": "1.1.208",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "bin": {
@@ -21,7 +21,7 @@ python3 scripts/extract_chat.py <my-workspace> "<urls>"
21
21
 
22
22
  **两步执行逻辑**:
23
23
  1. **始终先扫描**所有 agent → 生成 `作品扫描_<时间>.html`
24
- 2. 如果传了 `<urls>` → 再提取指定会话 → 生成 `index.js` + `index.html`
24
+ 2. 如果传了 `<urls>` → 再提取指定会话,并按 Workspace 合并 → 生成 `index.js` + `index.html`
25
25
 
26
26
  ## 输出文件
27
27
 
@@ -29,34 +29,39 @@ python3 scripts/extract_chat.py <my-workspace> "<urls>"
29
29
 
30
30
  | 文件 | 说明 |
31
31
  |---|---|
32
- | `index.js` | 唯一数据产物:`chatIndex`(会话元数据列表)+ `chatAll`(每个会话的完整对话) |
33
- | `index.html` | 查看器,复制自 `assets/chat-history-template.html`,只加载 `index.js` |
32
+ | `index.js` | 数据产物:Workspace 索引、合并时间线,以及原始 Session 数据 |
33
+ | `index.html` | 查看器;可按 Session 筛选、辨认来源并下载当前视图为 Markdown |
34
34
 
35
35
  `index.js` 结构:
36
36
 
37
37
  ```javascript
38
- // chatIndex:用于会话切换下拉框的元数据
38
+ // chatIndex:用于 Workspace 切换下拉框的元数据
39
39
  const chatIndex = [
40
- { "session_id": "agent:xxx:main", "workspace_name": "xxx", "session_name": "main",
41
- "total_pairs": 10, "first_time": "...", "last_time": "...", "work_url": "" },
40
+ { "workspace_name": "xxx", "workspace_label": "作品名称", "session_count": 2,
41
+ "total_pairs": 10, "first_time": "...", "last_time": "..." },
42
42
  ...
43
43
  ];
44
44
 
45
- // chatAll:按 session_id 索引的完整会话数据(HTML 渲染的真正数据源)
46
- const chatAll = {
47
- "agent:xxx:main": {
48
- "workspace_name": "xxx", "session_name": "main", "session_id": "agent:xxx:main",
49
- "total_pairs": 10, "first_time": "...", "last_time": "...", "work_url": "",
45
+ // chatWorkspaces:按 workspace_name 索引的合并时间线(HTML 的主要数据源)
46
+ const chatWorkspaces = {
47
+ "xxx": {
48
+ "workspace_name": "xxx", "workspace_label": "作品名称", "session_count": 2,
49
+ "total_pairs": 10, "first_time": "...", "last_time": "...",
50
50
  "conversations": [
51
- { "user": "...", "user_time": "...", "ai": "...", "ai_time": "..." },
51
+ { "user": "...", "user_time": "...", "user_timestamp": "...",
52
+ "ai": "...", "ai_time": "...", "ai_timestamp": "...",
53
+ "workspace_turn_index": 1, "source_session_id": "agent:xxx:main",
54
+ "source_session_label": "程序", "source_turn_index": 1 },
52
55
  ...
53
56
  ]
54
57
  },
55
58
  ...
56
59
  };
60
+
61
+ // chatSessionIndex / chatAll:保留原始 Session 索引和原始 Session 数据,兼容旧用途。
57
62
  ```
58
63
 
59
- > 单会话和批量模式产物一致,区别只是 `chatIndex` / `chatAll` 里的会话数量。
64
+ 同一 Workspace 下的多个 Session 会按**用户原始时间戳**稳定合并;展示时间只用于阅读,不参与排序。每轮仍保留来源 Session、来源标签和原轮次,便于追溯。
60
65
 
61
66
  ## 工作流
62
67
 
@@ -80,24 +85,36 @@ URL 示例:`https://claw1.kekouen.cn/chat?session=agent%3Ac108-v1-1811%3Amain`
80
85
  ### Step 3: 解析 JSONL,构建对话对
81
86
 
82
87
  1. 筛选 `type == "message"` 的事件
83
- 2. 每条用户消息与后续**所有连续的** AI 消息配对
84
- 3. 多条 AI 回复合并为一条
85
- 4. 跳过 `toolResult` 事件和空文本消息
88
+ 2. 高置信度识别模型切换时瞬间重新注入的历史回放块,整块过滤,避免重复对话
89
+ 3. 每条用户消息与后续**所有连续的** AI 消息配对
90
+ 4. 多条 AI 回复合并为一条
91
+ 5. 跳过 `toolResult` 事件和空文本消息
86
92
 
87
- ### Step 4: 生成 index.js
93
+ ### Step 4: 按 Workspace 合并并生成 index.js
88
94
 
89
- 所有会话的数据在内存中汇总,一次性写入唯一的 `index.js`(`chatIndex` + `chatAll`),不为单个会话单独落文件。
95
+ 所有 Session 先按 Workspace 分组,再按用户原始时间戳合并。一次性写入唯一的 `index.js`(`chatIndex` + `chatWorkspaces` + `chatSessionIndex` + `chatAll`),不为单个会话单独落文件。
90
96
 
91
97
  ### Step 5: 渲染
92
98
 
93
99
  将模板 `assets/chat-history-template.html` 复制到输出目录为 `index.html`。
94
- 模板只加载 `index.js`,通过 `chatIndex` 渲染会话切换下拉框、从 `chatAll` 取完整对话。
100
+ 模板只加载 `index.js`,通过 `chatIndex` 切换 Workspace、从 `chatWorkspaces` 读取合并时间线。页面以稳定的背景色和来源标签区分 Session,也可点击 Session 标签筛选当前视图。
95
101
 
96
102
  模板展示三种时间指标:
97
103
  - **课程流逝** — 距首条消息的时间
98
104
  - **回复耗时** — AI 响应时间
99
105
  - **间隔耗时** — 到下一条用户消息的间隔
100
106
 
107
+ ### Step 6: 下载当前视图为 Markdown
108
+
109
+ 页面顶部的“下载当前视图 MD”按钮会在浏览器本地即时生成文件,不需要服务端接口:
110
+
111
+ - 当前选择“全部会话”:导出整个 Workspace 的合并时间线
112
+ - 当前筛选某个 Session:只导出该 Session
113
+ - 文件顶部包含总体汇总、会话概览、每日对话分布、响应时间和内容规模
114
+ - 正文保留合并轮次、原 Session 轮次、Session 标签/ID、显示时间和原始时间戳
115
+ - 用户与 AI 原文使用 Markdown 引用块封装,适合直接交给 AI 分析
116
+ - 文件使用 UTF-8 BOM,降低中文在本地软件中打开时出现乱码的概率
117
+
101
118
  ## Agent 手动流程
102
119
 
103
120
  如果不使用脚本(如当前 agent 直接操作):
@@ -52,6 +52,21 @@
52
52
  border-color: #667eea;
53
53
  outline: none;
54
54
  }
55
+ .download-button {
56
+ border: 0;
57
+ border-radius: 8px;
58
+ padding: 9px 14px;
59
+ color: white;
60
+ background: #0f766e;
61
+ font-size: 13px;
62
+ font-weight: 700;
63
+ cursor: pointer;
64
+ white-space: nowrap;
65
+ box-shadow: 0 2px 6px rgba(15, 118, 110, .24);
66
+ }
67
+ .download-button:hover { background: #115e59; }
68
+ .download-button:focus-visible { outline: 3px solid #99f6e4; outline-offset: 2px; }
69
+ .download-button:disabled { cursor: not-allowed; opacity: .55; box-shadow: none; }
55
70
  .session-meta {
56
71
  font-size: 12px;
57
72
  color: #888;
@@ -196,6 +211,7 @@
196
211
  <label>🔍 切换工作空间:</label>
197
212
  <select id="sessionSelect"></select>
198
213
  <span class="session-meta" id="sessionMeta"></span>
214
+ <button type="button" class="download-button" id="downloadMarkdown">⬇ 下载当前视图 MD</button>
199
215
  </div>
200
216
 
201
217
  <div class="session-legend" id="sessionLegend" style="display:none;">
@@ -284,10 +300,289 @@
284
300
 
285
301
  function escapeHtml(text) {
286
302
  var div = document.createElement('div');
287
- div.textContent = text;
303
+ div.textContent = text || '';
288
304
  return div.innerHTML;
289
305
  }
290
306
 
307
+ function markdownCell(value) {
308
+ return String(value === null || value === undefined ? '' : value)
309
+ .replace(/\\/g, '\\\\')
310
+ .replace(/\|/g, '\\|')
311
+ .replace(/\r?\n/g, '<br>');
312
+ }
313
+
314
+ function markdownQuote(value) {
315
+ var text = String(value === null || value === undefined ? '' : value)
316
+ .replace(/\r\n?/g, '\n');
317
+ if (!text.trim()) return '> _无文本内容_';
318
+ return text.split('\n').map(function(line) {
319
+ return line ? '> ' + line : '>';
320
+ }).join('\n');
321
+ }
322
+
323
+ function formatLocalDateTime(date) {
324
+ function pad(value) { return String(value).padStart(2, '0'); }
325
+ return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) +
326
+ ' ' + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds());
327
+ }
328
+
329
+ function getSessionMeta(chatData, sessionId) {
330
+ var source = (chatData.session_sources || []).find(function(item) {
331
+ return item.session_id === sessionId;
332
+ });
333
+ var turn = (chatData.conversations || []).find(function(item) {
334
+ return item.source_session_id === sessionId;
335
+ });
336
+ var label = (turn && (turn.source_session_label || turn.source_session_name)) ||
337
+ (source && (source.session_label || source.session_name)) ||
338
+ (sessionId ? sessionId.split(':').pop() : '') || '未命名会话';
339
+ return { id: sessionId || '', label: label };
340
+ }
341
+
342
+ function getExportScope(chatData) {
343
+ if (!activeSessionFilter) return '全部会话';
344
+ return getSessionMeta(chatData, activeSessionFilter).label;
345
+ }
346
+
347
+ function getCurrentConversations() {
348
+ if (!currentChatData) return [];
349
+ var conversations = currentChatData.conversations || [];
350
+ if (!activeSessionFilter) return conversations.slice();
351
+ return conversations.filter(function(turn) {
352
+ return turn.source_session_id === activeSessionFilter;
353
+ });
354
+ }
355
+
356
+ function median(values) {
357
+ if (!values.length) return null;
358
+ var sorted = values.slice().sort(function(a, b) { return a - b; });
359
+ var middle = Math.floor(sorted.length / 2);
360
+ return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
361
+ }
362
+
363
+ function buildMarkdown(chatData, conversations) {
364
+ conversations = conversations || [];
365
+ var workspaceId = chatData.workspace_name || chatData.workspace_id || chatData.session_id || 'unknown';
366
+ var workspaceLabel = chatData.workspace_label || workspaceId;
367
+ var workspaceTitle = workspaceLabel === workspaceId ? workspaceLabel : workspaceLabel + '(' + workspaceId + ')';
368
+ var scope = getExportScope(chatData);
369
+ var replyCount = 0;
370
+ var userChars = 0;
371
+ var aiChars = 0;
372
+ var responseTimes = [];
373
+ var userDates = [];
374
+ var sessionStats = {};
375
+ var dailyStats = {};
376
+
377
+ (chatData.session_sources || []).forEach(function(source) {
378
+ var sessionId = source.session_id || '';
379
+ if (!sessionId || (activeSessionFilter && sessionId !== activeSessionFilter)) return;
380
+ var meta = getSessionMeta(chatData, sessionId);
381
+ sessionStats[sessionId] = {
382
+ id: sessionId, label: meta.label, turns: 0, replies: 0,
383
+ first: '', last: '', firstDate: null, lastDate: null
384
+ };
385
+ });
386
+
387
+ conversations.forEach(function(turn) {
388
+ var userText = String(turn.user || '');
389
+ var aiText = String(turn.ai || '');
390
+ var hasReply = Boolean(aiText.trim());
391
+ var userDate = parseConversationTime(turn, 'user');
392
+ var aiDate = parseConversationTime(turn, 'ai');
393
+ var displayTime = turn.user_time || '';
394
+ var day = displayTime.slice(0, 10) || (userDate ? formatLocalDateTime(userDate).slice(0, 10) : '未知日期');
395
+ var sessionId = turn.source_session_id || chatData.session_id || 'unknown';
396
+ var meta = getSessionMeta(chatData, sessionId);
397
+
398
+ userChars += userText.length;
399
+ aiChars += aiText.length;
400
+ if (hasReply) replyCount++;
401
+ if (userDate) userDates.push(userDate);
402
+ if (hasReply && userDate && aiDate) {
403
+ var responseMs = aiDate - userDate;
404
+ if (responseMs >= 0) responseTimes.push(responseMs);
405
+ }
406
+
407
+ if (!sessionStats[sessionId]) {
408
+ sessionStats[sessionId] = {
409
+ id: sessionId, label: meta.label, turns: 0, replies: 0,
410
+ first: '', last: '', firstDate: null, lastDate: null
411
+ };
412
+ }
413
+ var session = sessionStats[sessionId];
414
+ session.turns++;
415
+ if (hasReply) session.replies++;
416
+ if (userDate && (!session.firstDate || userDate < session.firstDate)) {
417
+ session.firstDate = userDate;
418
+ session.first = displayTime || formatLocalDateTime(userDate);
419
+ }
420
+ if (userDate && (!session.lastDate || userDate > session.lastDate)) {
421
+ session.lastDate = userDate;
422
+ session.last = displayTime || formatLocalDateTime(userDate);
423
+ }
424
+
425
+ if (!dailyStats[day]) {
426
+ dailyStats[day] = { turns: 0, replies: 0, sessions: {}, first: '', last: '' };
427
+ }
428
+ var daily = dailyStats[day];
429
+ daily.turns++;
430
+ if (hasReply) daily.replies++;
431
+ daily.sessions[sessionId] = true;
432
+ if (displayTime && (!daily.first || displayTime < daily.first)) daily.first = displayTime;
433
+ if (displayTime && (!daily.last || displayTime > daily.last)) daily.last = displayTime;
434
+ });
435
+
436
+ userDates.sort(function(a, b) { return a - b; });
437
+ var firstTime = conversations.length ? conversations[0].user_time || '' : '';
438
+ var lastTime = conversations.length ? conversations[conversations.length - 1].user_time || '' : '';
439
+ if (userDates.length) {
440
+ if (!firstTime) firstTime = formatLocalDateTime(userDates[0]);
441
+ if (!lastTime) lastTime = formatLocalDateTime(userDates[userDates.length - 1]);
442
+ }
443
+ var activeDays = Object.keys(dailyStats).filter(function(day) { return day !== '未知日期'; }).length;
444
+ var spanDays = userDates.length > 1 ? Math.floor((userDates[userDates.length - 1] - userDates[0]) / 86400000) + 1 : (userDates.length ? 1 : 0);
445
+ var sessions = Object.keys(sessionStats).map(function(id) { return sessionStats[id]; });
446
+ sessions.sort(function(a, b) {
447
+ if (!a.firstDate && !b.firstDate) return a.label.localeCompare(b.label);
448
+ if (!a.firstDate) return 1;
449
+ if (!b.firstDate) return -1;
450
+ return a.firstDate - b.firstDate;
451
+ });
452
+
453
+ var lines = [];
454
+ lines.push('# ' + workspaceTitle + '聊天记录');
455
+ lines.push('');
456
+ lines.push('> 本文件按用户消息时间合并排序,适合直接交给 AI 做内容分析。用户和 AI 原文均以引用块包裹,避免原文中的 Markdown 结构干扰文档层级。');
457
+ lines.push('');
458
+ lines.push('## 总体汇总');
459
+ lines.push('');
460
+ lines.push('| 指标 | 数值 |');
461
+ lines.push('| --- | --- |');
462
+ lines.push('| Workspace 名称 | ' + markdownCell(workspaceLabel) + ' |');
463
+ lines.push('| Workspace ID | `' + markdownCell(workspaceId) + '` |');
464
+ lines.push('| 导出范围 | ' + markdownCell(scope) + ' |');
465
+ lines.push('| Session 数 | ' + sessions.length + ' |');
466
+ lines.push('| 对话轮数 | ' + conversations.length + ' |');
467
+ lines.push('| AI 回复数 | ' + replyCount + ' |');
468
+ lines.push('| 未回复轮数 | ' + (conversations.length - replyCount) + ' |');
469
+ lines.push('| 首条用户消息 | ' + markdownCell(firstTime || '未知') + ' |');
470
+ lines.push('| 末条用户消息 | ' + markdownCell(lastTime || '未知') + ' |');
471
+ lines.push('| 活跃日期数 | ' + activeDays + ' |');
472
+ lines.push('| 日历跨度 | ' + spanDays + ' 天 |');
473
+ lines.push('| 导出时间 | ' + formatLocalDateTime(new Date()) + ' |');
474
+ lines.push('');
475
+ lines.push('## 会话概览');
476
+ lines.push('');
477
+ lines.push('| # | Session 名称 | Session ID | 对话数 | AI 回复 | 未回复 | 起始 | 最后 |');
478
+ lines.push('| ---: | --- | --- | ---: | ---: | ---: | --- | --- |');
479
+ sessions.forEach(function(session, index) {
480
+ lines.push('| ' + (index + 1) + ' | ' + markdownCell(session.label) + ' | `' + markdownCell(session.id) + '` | ' +
481
+ session.turns + ' | ' + session.replies + ' | ' + (session.turns - session.replies) + ' | ' +
482
+ markdownCell(session.first || '未知') + ' | ' + markdownCell(session.last || '未知') + ' |');
483
+ });
484
+ if (!sessions.length) lines.push('| - | 无数据 | - | 0 | 0 | 0 | - | - |');
485
+
486
+ lines.push('');
487
+ lines.push('## 每日对话分布');
488
+ lines.push('');
489
+ lines.push('| 日期 | 对话数 | AI 回复 | 未回复 | 活跃 Session | 当日首条 | 当日末条 |');
490
+ lines.push('| --- | ---: | ---: | ---: | ---: | --- | --- |');
491
+ Object.keys(dailyStats).sort().forEach(function(day) {
492
+ var daily = dailyStats[day];
493
+ lines.push('| ' + markdownCell(day) + ' | ' + daily.turns + ' | ' + daily.replies + ' | ' +
494
+ (daily.turns - daily.replies) + ' | ' + Object.keys(daily.sessions).length + ' | ' +
495
+ markdownCell(daily.first ? daily.first.slice(11) : '未知') + ' | ' +
496
+ markdownCell(daily.last ? daily.last.slice(11) : '未知') + ' |');
497
+ });
498
+ if (!Object.keys(dailyStats).length) lines.push('| - | 0 | 0 | 0 | 0 | - | - |');
499
+
500
+ lines.push('');
501
+ lines.push('## 响应时间汇总');
502
+ lines.push('');
503
+ lines.push('| 指标 | 数值 |');
504
+ lines.push('| --- | --- |');
505
+ lines.push('| 可计算样本 | ' + responseTimes.length + ' |');
506
+ lines.push('| 平均回复耗时 | ' + (responseTimes.length ? formatDuration(responseTimes.reduce(function(a, b) { return a + b; }, 0) / responseTimes.length) : '--') + ' |');
507
+ lines.push('| 中位回复耗时 | ' + (responseTimes.length ? formatDuration(median(responseTimes)) : '--') + ' |');
508
+ lines.push('| 最短回复耗时 | ' + (responseTimes.length ? formatDuration(Math.min.apply(null, responseTimes)) : '--') + ' |');
509
+ lines.push('| 最长回复耗时 | ' + (responseTimes.length ? formatDuration(Math.max.apply(null, responseTimes)) : '--') + ' |');
510
+
511
+ lines.push('');
512
+ lines.push('## 内容规模');
513
+ lines.push('');
514
+ lines.push('| 指标 | 数值 |');
515
+ lines.push('| --- | ---: |');
516
+ lines.push('| 用户总字符数 | ' + userChars + ' |');
517
+ lines.push('| AI 总字符数 | ' + aiChars + ' |');
518
+ lines.push('| 用户平均每轮字符数 | ' + (conversations.length ? Math.round(userChars / conversations.length) : 0) + ' |');
519
+ lines.push('| AI 平均每次回复字符数 | ' + (replyCount ? Math.round(aiChars / replyCount) : 0) + ' |');
520
+
521
+ lines.push('');
522
+ lines.push('# 对话正文');
523
+ lines.push('');
524
+ conversations.forEach(function(turn, index) {
525
+ var sessionId = turn.source_session_id || chatData.session_id || 'unknown';
526
+ var meta = getSessionMeta(chatData, sessionId);
527
+ var mergedIndex = turn.workspace_turn_index || (index + 1);
528
+ var originalIndex = turn.source_turn_index || mergedIndex;
529
+ lines.push('## 第 ' + mergedIndex + ' 轮 · ' + markdownCell(turn.user_time || '未知时间'));
530
+ lines.push('');
531
+ lines.push('- Session:' + markdownCell(meta.label));
532
+ lines.push('- Session ID:`' + markdownCell(sessionId) + '`');
533
+ lines.push('- 原 Session 轮次:第 ' + originalIndex + ' 轮');
534
+ if (turn.user_timestamp) lines.push('- 用户原始时间戳:`' + markdownCell(turn.user_timestamp) + '`');
535
+ lines.push('');
536
+ lines.push('### 用户');
537
+ lines.push('');
538
+ lines.push(markdownQuote(turn.user));
539
+ lines.push('');
540
+ lines.push('### AI' + (turn.ai_time ? ' · ' + markdownCell(turn.ai_time) : ''));
541
+ lines.push('');
542
+ lines.push(markdownQuote(turn.ai));
543
+ if (turn.ai_timestamp) {
544
+ lines.push('');
545
+ lines.push('_AI 原始时间戳:`' + markdownCell(turn.ai_timestamp) + '`_');
546
+ }
547
+ lines.push('');
548
+ lines.push('---');
549
+ lines.push('');
550
+ });
551
+ return lines.join('\n');
552
+ }
553
+
554
+ function sanitizeFilename(value) {
555
+ return String(value || '聊天记录')
556
+ .replace(/[\\/:*?"<>|]+/g, '_')
557
+ .replace(/\s+/g, '_')
558
+ .replace(/^_+|_+$/g, '')
559
+ .slice(0, 100) || '聊天记录';
560
+ }
561
+
562
+ function updateDownloadButton(chatData, conversations) {
563
+ var button = document.getElementById('downloadMarkdown');
564
+ if (!button) return;
565
+ button.disabled = !chatData;
566
+ button.textContent = '⬇ 下载' + getExportScope(chatData) + ' · ' + conversations.length + '轮 MD';
567
+ }
568
+
569
+ function downloadCurrentMarkdown() {
570
+ if (!currentChatData) return;
571
+ var conversations = getCurrentConversations();
572
+ var markdown = buildMarkdown(currentChatData, conversations);
573
+ var workspaceName = currentChatData.workspace_label || currentChatData.workspace_name || currentChatData.session_id || '聊天记录';
574
+ var filename = sanitizeFilename(workspaceName + '_' + getExportScope(currentChatData) + '_' + conversations.length + '轮') + '.md';
575
+ var blob = new Blob(['\uFEFF' + markdown], { type: 'text/markdown;charset=utf-8' });
576
+ var url = URL.createObjectURL(blob);
577
+ var anchor = document.createElement('a');
578
+ anchor.href = url;
579
+ anchor.download = filename;
580
+ document.body.appendChild(anchor);
581
+ anchor.click();
582
+ anchor.remove();
583
+ setTimeout(function() { URL.revokeObjectURL(url); }, 1000);
584
+ }
585
+
291
586
  function stableHash(text) {
292
587
  var hash = 2166136261;
293
588
  for (var i = 0; i < text.length; i++) {
@@ -382,12 +677,18 @@
382
677
  });
383
678
  Object.keys(sessionVisualMap).sort().forEach(function(sessionId) {
384
679
  var visual = sessionVisualMap[sessionId];
385
- var sessionName = '';
680
+ var sessionLabel = '';
386
681
  var sourceTurn = (chatData.conversations || []).find(function(turn) {
387
682
  return turn.source_session_id === sessionId;
388
683
  });
389
- if (sourceTurn) sessionName = sourceTurn.source_session_name || '';
390
- var label = visual.label + (sessionName ? ' · ' + sessionName : '') + ' · ' + visual.shortId;
684
+ if (sourceTurn) sessionLabel = sourceTurn.source_session_label || sourceTurn.source_session_name || '';
685
+ if (!sessionLabel) {
686
+ var sourceMeta = (chatData.session_sources || []).find(function(source) {
687
+ return source.session_id === sessionId;
688
+ });
689
+ if (sourceMeta) sessionLabel = sourceMeta.session_label || sourceMeta.session_name || '';
690
+ }
691
+ var label = visual.label + (sessionLabel ? ' · ' + sessionLabel : '') + ' · ' + visual.shortId;
391
692
  addButton(sessionId, label, counts[sessionId] || 0, visual);
392
693
  });
393
694
  }
@@ -407,9 +708,11 @@
407
708
  opt.value = workspaceMode ? item.workspace_id : item.session_id;
408
709
  var label;
409
710
  if (workspaceMode) {
410
- label = item.workspace_name + ' (' + item.session_count + '个会话 · ' + item.total_pairs + '对)';
711
+ var workspaceDisplay = item.workspace_label ? item.workspace_label + ' (' + item.workspace_name + ')' : item.workspace_name;
712
+ label = workspaceDisplay + ' · ' + item.session_count + '个会话 · ' + item.total_pairs + '对';
411
713
  } else {
412
- label = item.workspace_name + ' / ' + item.session_name + ' (' + item.total_pairs + '对)';
714
+ var sessionDisplay = item.session_label || item.session_name;
715
+ label = item.workspace_name + ' / ' + sessionDisplay + ' (' + item.total_pairs + '对)';
413
716
  }
414
717
  if (item.first_time) label += ' [' + item.first_time + ']';
415
718
  opt.textContent = label;
@@ -452,12 +755,13 @@
452
755
  var isWorkspace = chatData.session_count !== undefined;
453
756
  currentChatData = chatData;
454
757
  buildSessionLegend(chatData);
455
- document.getElementById('sessionId').textContent = chatData.workspace_name || chatData.session_id || '--';
758
+ var workspaceDisplay = chatData.workspace_label ? chatData.workspace_label + ' (' + chatData.workspace_name + ')' : (chatData.workspace_name || chatData.session_id || '--');
759
+ document.getElementById('sessionId').textContent = workspaceDisplay;
456
760
  if (isWorkspace) {
457
- var sessionNames = (chatData.session_names || []).join('、');
458
- document.getElementById('sessionName').textContent = chatData.session_count + ' 个' + (sessionNames ? '(' + sessionNames + ')' : '');
761
+ var sessionLabels = (chatData.session_labels || chatData.session_names || []).join('、');
762
+ document.getElementById('sessionName').textContent = chatData.session_count + ' 个' + (sessionLabels ? '(' + sessionLabels + ')' : '');
459
763
  } else {
460
- document.getElementById('sessionName').textContent = (chatData.workspace_name || '') + ' / ' + (chatData.session_name || '--');
764
+ document.getElementById('sessionName').textContent = chatData.session_label || chatData.session_name || '--';
461
765
  }
462
766
  document.getElementById('initiator').textContent = (chatData.first_time && chatData.last_time) ? chatData.first_time + ' ~ ' + chatData.last_time : '--';
463
767
 
@@ -470,6 +774,7 @@
470
774
  var conversations = activeSessionFilter ? allConversations.filter(function(turn) {
471
775
  return turn.source_session_id === activeSessionFilter;
472
776
  }) : allConversations;
777
+ updateDownloadButton(chatData, conversations);
473
778
  var timelineStart = allConversations.length > 0 ? parseConversationTime(allConversations[0], 'user') : null;
474
779
  document.getElementById('totalPairs').textContent = conversations.length;
475
780
  conversations.forEach(function(c, i) {
@@ -510,7 +815,8 @@
510
815
  if (c.source_session_id) {
511
816
  visual = sessionVisualMap[c.source_session_id] || visual;
512
817
  var originalTurn = c.source_turn_index || '?';
513
- var sourceLabel = visual.label + ' · 原第 ' + originalTurn + ' 轮';
818
+ var readableSessionName = c.source_session_label || c.source_session_name || '';
819
+ var sourceLabel = visual.label + (readableSessionName ? ' · ' + readableSessionName : '') + ' · 原第 ' + originalTurn + ' 轮';
514
820
  sourceBadge = '<span class="source-session" style="background:' + visual.soft + ';border-color:' + visual.border + ';color:' + visual.text + '" title="' + escapeHtml(c.source_session_id) + '">' + escapeHtml(sourceLabel) + '</span>';
515
821
  }
516
822
  pair.style.borderLeft = '6px solid ' + visual.border;
@@ -556,6 +862,9 @@
556
862
 
557
863
  // Init
558
864
  (function() {
865
+ var downloadButton = document.getElementById('downloadMarkdown');
866
+ if (downloadButton) downloadButton.addEventListener('click', downloadCurrentMarkdown);
867
+
559
868
  // Strategy 1: Use index.js workspace data (with old session fallback).
560
869
  if (typeof chatIndex !== 'undefined' && chatIndex && chatIndex.length > 0 &&
561
870
  ((typeof chatWorkspaces !== 'undefined' && chatWorkspaces) ||
@@ -20,6 +20,7 @@ import json
20
20
  import sys
21
21
  import os
22
22
  import glob
23
+ from html import escape as html_escape
23
24
  from urllib.parse import urlparse, parse_qs, quote
24
25
  from datetime import datetime, timezone, timedelta
25
26
  import time
@@ -90,7 +91,36 @@ def parse_input(input_str):
90
91
  return parts if len(parts) > 1 else [input_str]
91
92
 
92
93
 
93
- def find_session_file(session_key):
94
+ def load_workspace_labels():
95
+ """Return agent id -> human-readable workspace label from openclaw.json."""
96
+ config_path = f'{_base}/openclaw.json'
97
+ try:
98
+ with open(config_path, 'r', encoding='utf-8') as f:
99
+ config = json.load(f)
100
+ except Exception:
101
+ return {}
102
+
103
+ labels = {}
104
+ agents = (config.get('agents') or {}).get('list') or []
105
+ for agent in agents:
106
+ if not isinstance(agent, dict) or not agent.get('id'):
107
+ continue
108
+ agent_id = agent['id']
109
+ identity = agent.get('identity') or {}
110
+ label = identity.get('name') or agent.get('name') or ''
111
+ if label and label != agent_id:
112
+ labels[agent_id] = label
113
+ return labels
114
+
115
+
116
+ def get_workspace_label(agent_id, workspace_labels=None):
117
+ if workspace_labels is None:
118
+ workspace_labels = load_workspace_labels()
119
+ return workspace_labels.get(agent_id, '')
120
+
121
+
122
+ def find_session_metadata(session_key):
123
+ """Return normalized session metadata, including session file and label."""
94
124
  parts = session_key.split(':')
95
125
  if len(parts) < 2:
96
126
  return None
@@ -103,12 +133,25 @@ def find_session_file(session_key):
103
133
  with open(sessions_json_path, 'r') as f:
104
134
  sessions = json.load(f)
105
135
 
106
- if session_key in sessions:
107
- session_file = sessions[session_key].get('sessionFile')
108
- if session_file and not os.path.isabs(session_file):
109
- session_file = os.path.join(f'{_base}/agents/{agent_id}/sessions', session_file)
110
- return session_file
111
- return None
136
+ raw_meta = sessions.get(session_key)
137
+ if not isinstance(raw_meta, dict):
138
+ return None
139
+
140
+ session_file = raw_meta.get('sessionFile')
141
+ if session_file and not os.path.isabs(session_file):
142
+ session_file = os.path.join(f'{_base}/agents/{agent_id}/sessions', session_file)
143
+ session_name = parts[2] if len(parts) > 2 else 'main'
144
+ return {
145
+ 'session_file': session_file,
146
+ 'session_label': raw_meta.get('label') or session_name,
147
+ 'raw': raw_meta,
148
+ }
149
+
150
+
151
+ def find_session_file(session_key):
152
+ """Compatibility wrapper returning only the normalized session file path."""
153
+ metadata = find_session_metadata(session_key)
154
+ return metadata.get('session_file') if metadata else None
112
155
 
113
156
 
114
157
  def _parse_iso_timestamp(ts_str):
@@ -394,7 +437,14 @@ def count_conversations(jsonl_path, include_dedupe_report=False):
394
437
 
395
438
 
396
439
 
397
- def build_chat_data(conversations, session_key, first_ts, last_ts):
440
+ def build_chat_data(
441
+ conversations,
442
+ session_key,
443
+ first_ts,
444
+ last_ts,
445
+ workspace_label='',
446
+ session_label='',
447
+ ):
398
448
  """构建单个会话的完整数据对象(仅内存,不写盘)。
399
449
 
400
450
  数据最终全部汇入 index.js 的 chatAll,不再为每个会话单独落 js 文件。
@@ -402,18 +452,22 @@ def build_chat_data(conversations, session_key, first_ts, last_ts):
402
452
  parts = session_key.split(':')
403
453
  workspace_name = parts[1] if len(parts) > 1 else 'unknown'
404
454
  session_name = parts[2] if len(parts) > 2 else 'main'
455
+ session_label = session_label or session_name
405
456
 
406
457
  session_conversations = []
407
458
  for turn_index, conversation in enumerate(conversations, 1):
408
459
  turn = dict(conversation)
409
460
  turn['source_session_id'] = session_key
410
461
  turn['source_session_name'] = session_name
462
+ turn['source_session_label'] = session_label
411
463
  turn['source_turn_index'] = turn_index
412
464
  session_conversations.append(turn)
413
465
 
414
466
  return {
415
467
  'workspace_name': workspace_name,
468
+ 'workspace_label': workspace_label or '',
416
469
  'session_name': session_name,
470
+ 'session_label': session_label,
417
471
  'session_id': session_key,
418
472
  'first_time': parse_time(first_ts) if first_ts else '',
419
473
  'last_time': parse_time(last_ts) if last_ts else '',
@@ -454,7 +508,8 @@ def scan_all_agents():
454
508
  continue
455
509
  parts = session_key.split(':')
456
510
  session_name = parts[2] if len(parts) > 2 else 'main'
457
- results.append((session_key, agent_id, session_name, session_file))
511
+ session_label = meta.get('label') or session_name
512
+ results.append((session_key, agent_id, session_name, session_label, session_file))
458
513
  return results
459
514
 
460
515
 
@@ -467,8 +522,12 @@ def print_summary_table(entries, host=None):
467
522
  for e in entries:
468
523
  work = e.get('work_url') or '(待填)'
469
524
  url = session_key_to_url(e['session_key'], host)
470
- name = (e['session_name'] or '')[:26]
471
- agent = (e.get('agent_id') or '')[:16]
525
+ name = (e.get('session_label') or e.get('session_name') or '')[:26]
526
+ agent_id = e.get('agent_id') or ''
527
+ workspace_label = e.get('workspace_label') or ''
528
+ agent = (
529
+ f'{workspace_label} ({agent_id})' if workspace_label else agent_id
530
+ )[:16]
472
531
  first_t = (e.get('first_time') or '')[:19]
473
532
  last_t = (e.get('last_time') or '')[:19]
474
533
  print(f"{e['index']:>3} {agent:<16} {name:<28} {e['total_pairs']:>6} {first_t:<20} {last_t:<20} {work:<14} {url}")
@@ -497,21 +556,23 @@ def generate_html_table(entries, host, output_path):
497
556
  rows_html = []
498
557
  for e in entries:
499
558
  chat_url = session_key_to_url(e['session_key'], host)
500
- name = e.get('session_name', '') or ''
559
+ name = e.get('session_label') or e.get('session_name', '') or ''
501
560
  agent = e.get('agent_id', '') or ''
561
+ workspace_label = e.get('workspace_label') or ''
562
+ agent_display = f'{workspace_label} ({agent})' if workspace_label else agent
502
563
  chat_cell = '<a href="' + chat_url + '" target="_blank" class="link">💬 打开对话</a>'
503
564
  bg, border = agent_colors[agent]
504
565
  work_val = e.get('work_url', '') or ''
505
566
 
506
567
  row = '\n <tr style="background: ' + bg + '; border-left: 3px solid ' + border + ';">'
507
- row += '\n <td><input type="checkbox" class="row-check" data-session="' + e['session_key'] + '" data-agent="' + agent + '" data-name="' + name + '"></td>'
568
+ row += '\n <td><input type="checkbox" class="row-check" data-session="' + html_escape(e['session_key'], quote=True) + '" data-agent="' + html_escape(agent, quote=True) + '" data-name="' + html_escape(name, quote=True) + '"></td>'
508
569
  row += '\n <td class="num">' + str(e['index']) + '</td>'
509
- row += '\n <td>' + agent + '</td>'
510
- row += '\n <td>' + name + '</td>'
570
+ row += '\n <td>' + html_escape(agent_display) + '</td>'
571
+ row += '\n <td>' + html_escape(name) + '</td>'
511
572
  row += '\n <td class="num">' + str(e['total_pairs']) + '</td>'
512
573
  row += '\n <td>' + e.get('first_time', '') + '</td>'
513
574
  row += '\n <td>' + e.get('last_time', '') + '</td>'
514
- row += '\n <td><input type="text" class="work-input" placeholder="填入作品链接" value="' + work_val + '"></td>'
575
+ row += '\n <td><input type="text" class="work-input" placeholder="填入作品链接" value="' + html_escape(work_val, quote=True) + '"></td>'
515
576
  row += '\n <td>' + chat_cell + '</td>'
516
577
  row += '\n </tr>'
517
578
  rows_html.append(row)
@@ -519,7 +580,7 @@ def generate_html_table(entries, host, output_path):
519
580
  rows = '\n'.join(rows_html)
520
581
 
521
582
  legend_items = ''.join([
522
- '<span class="legend-item" style="background: ' + bg + '; border: 1px solid ' + bd + ';">' + agent + '</span>'
583
+ '<span class="legend-item" style="background: ' + bg + '; border: 1px solid ' + bd + ';">' + html_escape(agent) + '</span>'
523
584
  for agent, (bg, bd) in sorted(agent_colors.items())
524
585
  ])
525
586
 
@@ -552,10 +613,11 @@ def process_one(url_or_key, output_dir, index):
552
613
 
553
614
  print(f"\n[{index}] Session key: {session_key}")
554
615
 
555
- jsonl_path = find_session_file(session_key)
556
- if not jsonl_path:
616
+ session_metadata = find_session_metadata(session_key)
617
+ if not session_metadata or not session_metadata.get('session_file'):
557
618
  print(f"[{index}] ERROR: Could not find session file")
558
619
  return None
620
+ jsonl_path = session_metadata['session_file']
559
621
  if not os.path.exists(jsonl_path):
560
622
  print(f"[{index}] ERROR: JSONL not found: {jsonl_path}")
561
623
  return None
@@ -571,13 +633,24 @@ def process_one(url_or_key, output_dir, index):
571
633
  f"{report['dropped_messages']} message event(s)"
572
634
  )
573
635
 
574
- data = build_chat_data(conversations, session_key, first_ts, last_ts)
636
+ workspace_label = get_workspace_label(agent_id)
637
+ session_label = session_metadata.get('session_label') or session_name
638
+ data = build_chat_data(
639
+ conversations,
640
+ session_key,
641
+ first_ts,
642
+ last_ts,
643
+ workspace_label=workspace_label,
644
+ session_label=session_label,
645
+ )
575
646
 
576
647
  return {
577
648
  'index': index,
578
649
  'session_key': session_key,
579
650
  'session_name': session_name,
651
+ 'session_label': session_label,
580
652
  'agent_id': agent_id,
653
+ 'workspace_label': workspace_label,
581
654
  'total_pairs': data['total_pairs'],
582
655
  'first_time': data['first_time'],
583
656
  'last_time': data['last_time'],
@@ -618,7 +691,9 @@ def build_workspace_collections(results):
618
691
  all_data[sid] = data
619
692
  session_entries.append({
620
693
  'workspace_name': data.get('workspace_name', ''),
694
+ 'workspace_label': data.get('workspace_label', ''),
621
695
  'session_name': data.get('session_name', ''),
696
+ 'session_label': data.get('session_label', ''),
622
697
  'session_id': sid,
623
698
  'total_pairs': data.get('total_pairs', 0),
624
699
  'first_time': data.get('first_time', ''),
@@ -629,16 +704,30 @@ def build_workspace_collections(results):
629
704
  workspace_name = data.get('workspace_name') or 'unknown'
630
705
  workspace = grouped.setdefault(workspace_name, {
631
706
  'workspace_name': workspace_name,
707
+ 'workspace_label': data.get('workspace_label') or '',
632
708
  'workspace_id': workspace_name,
633
709
  'session_ids': [],
634
710
  'session_names': [],
711
+ 'session_labels': [],
712
+ 'session_sources': [],
635
713
  'work_urls': [],
636
714
  'conversations': [],
637
715
  })
716
+ if not workspace['workspace_label'] and data.get('workspace_label'):
717
+ workspace['workspace_label'] = data['workspace_label']
638
718
  workspace['session_ids'].append(sid)
639
719
  session_name = data.get('session_name') or 'main'
720
+ session_label = data.get('session_label') or session_name
640
721
  if session_name not in workspace['session_names']:
641
722
  workspace['session_names'].append(session_name)
723
+ if session_label not in workspace['session_labels']:
724
+ workspace['session_labels'].append(session_label)
725
+ workspace['session_sources'].append({
726
+ 'session_id': sid,
727
+ 'session_name': session_name,
728
+ 'session_label': session_label,
729
+ 'total_pairs': data.get('total_pairs', 0),
730
+ })
642
731
  work_url = data.get('work_url') or ''
643
732
  if work_url and work_url not in workspace['work_urls']:
644
733
  workspace['work_urls'].append(work_url)
@@ -647,6 +736,7 @@ def build_workspace_collections(results):
647
736
  turn = dict(conversation)
648
737
  turn.setdefault('source_session_id', sid)
649
738
  turn.setdefault('source_session_name', session_name)
739
+ turn.setdefault('source_session_label', session_label)
650
740
  turn.setdefault('source_turn_index', source_turn_index)
651
741
  turn['_source_session_order'] = session_order
652
742
  workspace['conversations'].append(turn)
@@ -682,6 +772,7 @@ def build_workspace_collections(results):
682
772
  workspace_data[workspace_name] = workspace
683
773
  workspace_entries.append({
684
774
  'workspace_name': workspace_name,
775
+ 'workspace_label': workspace['workspace_label'],
685
776
  'workspace_id': workspace_name,
686
777
  'session_count': workspace['session_count'],
687
778
  'session_ids': list(workspace['session_ids']),
@@ -724,17 +815,20 @@ def run_scan(output_dir=None, host=None):
724
815
  if host is None:
725
816
  host = detect_chat_host()
726
817
  all_sessions = scan_all_agents()
818
+ workspace_labels = load_workspace_labels()
727
819
  print("Found %d session(s) across all agents.\n" % len(all_sessions))
728
820
 
729
821
  entries = []
730
- for i, (session_key, agent_id, session_name, jsonl_path) in enumerate(all_sessions, 1):
822
+ for i, (session_key, agent_id, session_name, session_label, jsonl_path) in enumerate(all_sessions, 1):
731
823
  try:
732
824
  convs, first_ts, last_ts = count_conversations(jsonl_path)
733
825
  entries.append({
734
826
  'index': i,
735
827
  'session_key': session_key,
736
828
  'session_name': session_name,
829
+ 'session_label': session_label,
737
830
  'agent_id': agent_id,
831
+ 'workspace_label': get_workspace_label(agent_id, workspace_labels),
738
832
  'total_pairs': len(convs),
739
833
  'work_url': '',
740
834
  'first_time': parse_time(first_ts) if first_ts else '',