@aiyiran/myclaw 1.1.205 → 1.1.206

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiyiran/myclaw",
3
- "version": "1.1.205",
3
+ "version": "1.1.206",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "bin": {
@@ -56,6 +56,39 @@
56
56
  font-size: 12px;
57
57
  color: #888;
58
58
  }
59
+ .session-legend {
60
+ background: white;
61
+ border-radius: 12px;
62
+ padding: 14px 18px;
63
+ margin-bottom: 20px;
64
+ box-shadow: 0 2px 8px rgba(0,0,0,0.08);
65
+ }
66
+ .legend-title {
67
+ font-size: 13px;
68
+ font-weight: 700;
69
+ color: #394150;
70
+ margin-bottom: 10px;
71
+ }
72
+ .legend-buttons { display: flex; gap: 8px; flex-wrap: wrap; }
73
+ .legend-button {
74
+ appearance: none;
75
+ border: 1px solid #d8dee8;
76
+ background: #fff;
77
+ color: #4c5667;
78
+ border-radius: 999px;
79
+ padding: 7px 12px;
80
+ font-size: 12px;
81
+ font-weight: 650;
82
+ cursor: pointer;
83
+ display: inline-flex;
84
+ align-items: center;
85
+ gap: 7px;
86
+ transition: box-shadow .15s ease, transform .15s ease, border-color .15s ease;
87
+ }
88
+ .legend-button:hover { transform: translateY(-1px); box-shadow: 0 3px 8px rgba(0,0,0,.1); }
89
+ .legend-button.active { border-width: 2px; padding: 6px 11px; box-shadow: 0 0 0 2px rgba(0,0,0,.04); }
90
+ .legend-dot { width: 10px; height: 10px; border-radius: 50%; flex: 0 0 auto; }
91
+ .legend-count { opacity: .7; font-weight: 500; }
59
92
  .info-box {
60
93
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
61
94
  color: white;
@@ -97,7 +130,7 @@
97
130
  flex-wrap: wrap;
98
131
  gap: 10px;
99
132
  }
100
- .pair-left { display: flex; align-items: center; gap: 12px; }
133
+ .pair-left { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
101
134
  .pair-num {
102
135
  background: #4CAF50;
103
136
  color: white;
@@ -106,6 +139,15 @@
106
139
  font-weight: bold;
107
140
  font-size: 13px;
108
141
  }
142
+ .source-session {
143
+ background: #eef1f5;
144
+ color: #5f6b7a;
145
+ border: 1px solid #d8dee8;
146
+ padding: 4px 10px;
147
+ border-radius: 20px;
148
+ font-size: 12px;
149
+ font-weight: 600;
150
+ }
109
151
  .pair-duration {
110
152
  padding: 6px 14px;
111
153
  border-radius: 20px;
@@ -151,15 +193,20 @@
151
193
  <h1>📋 聊天记录</h1>
152
194
 
153
195
  <div class="session-selector" id="sessionSelector" style="display:none;">
154
- <label>🔍 切换会话:</label>
196
+ <label>🔍 切换工作空间:</label>
155
197
  <select id="sessionSelect"></select>
156
198
  <span class="session-meta" id="sessionMeta"></span>
157
199
  </div>
158
200
 
201
+ <div class="session-legend" id="sessionLegend" style="display:none;">
202
+ <div class="legend-title">会话来源(点击可筛选)</div>
203
+ <div class="legend-buttons" id="legendButtons"></div>
204
+ </div>
205
+
159
206
  <div class="info-box">
160
- <p><strong>会话ID:</strong> <span id="sessionId">--</span></p>
161
- <p><strong>会话名称:</strong> <span id="sessionName">--</span></p>
162
- <p><strong>发起人:</strong> <span id="initiator">--</span></p>
207
+ <p><strong>工作空间:</strong> <span id="sessionId">--</span></p>
208
+ <p><strong>包含会话:</strong> <span id="sessionName">--</span></p>
209
+ <p><strong>用户时间范围:</strong> <span id="initiator">--</span></p>
163
210
  <div class="stats">
164
211
  <div class="stat-item">
165
212
  <div class="stat-num" id="totalPairs">--</div>
@@ -183,10 +230,24 @@
183
230
  <div id="conversationList"></div>
184
231
  </div>
185
232
 
186
- <!-- Load index.js (contains chatIndex + chatAll) -->
233
+ <!-- Load index.js (contains workspace timelines and original session data) -->
187
234
  <script src="index.js"></script>
188
235
  <script>
189
236
  var currentSession = null;
237
+ var currentChatData = null;
238
+ var activeSessionFilter = null;
239
+ var sessionVisualMap = {};
240
+
241
+ var SESSION_PALETTE = [
242
+ { border: '#2563eb', soft: '#eff6ff', text: '#1e40af' },
243
+ { border: '#16a34a', soft: '#f0fdf4', text: '#166534' },
244
+ { border: '#9333ea', soft: '#faf5ff', text: '#6b21a8' },
245
+ { border: '#ea580c', soft: '#fff7ed', text: '#9a3412' },
246
+ { border: '#0891b2', soft: '#ecfeff', text: '#155e75' },
247
+ { border: '#db2777', soft: '#fdf2f8', text: '#9d174d' },
248
+ { border: '#4f46e5', soft: '#eef2ff', text: '#3730a3' },
249
+ { border: '#ca8a04', soft: '#fefce8', text: '#854d0e' }
250
+ ];
190
251
 
191
252
  // parseTime, formatDuration, escapeHtml
192
253
  function parseTime(timeStr) {
@@ -198,6 +259,15 @@
198
259
  return null;
199
260
  }
200
261
 
262
+ function parseConversationTime(conversation, prefix) {
263
+ var raw = conversation[prefix + '_timestamp'];
264
+ if (raw) {
265
+ var parsed = new Date(raw);
266
+ if (!isNaN(parsed.getTime())) return parsed;
267
+ }
268
+ return parseTime(conversation[prefix + '_time']);
269
+ }
270
+
201
271
  function formatDuration(ms) {
202
272
  if (ms === null || ms === undefined || ms < 0) return '--';
203
273
  var seconds = Math.floor(ms / 1000);
@@ -218,7 +288,111 @@
218
288
  return div.innerHTML;
219
289
  }
220
290
 
221
- // Build dropdown from chatIndex
291
+ function stableHash(text) {
292
+ var hash = 2166136261;
293
+ for (var i = 0; i < text.length; i++) {
294
+ hash ^= text.charCodeAt(i);
295
+ hash = Math.imul(hash, 16777619);
296
+ }
297
+ return hash >>> 0;
298
+ }
299
+
300
+ function buildSessionVisualMap(chatData) {
301
+ var ids = (chatData.session_ids || []).slice().sort();
302
+ if (ids.length === 0) {
303
+ (chatData.conversations || []).forEach(function(turn) {
304
+ if (turn.source_session_id && ids.indexOf(turn.source_session_id) === -1) {
305
+ ids.push(turn.source_session_id);
306
+ }
307
+ });
308
+ ids.sort();
309
+ }
310
+
311
+ var visualMap = {};
312
+ var usedColors = {};
313
+ ids.forEach(function(sessionId, index) {
314
+ var colorIndex = stableHash(sessionId) % SESSION_PALETTE.length;
315
+ if (ids.length <= SESSION_PALETTE.length) {
316
+ while (usedColors[colorIndex]) {
317
+ colorIndex = (colorIndex + 1) % SESSION_PALETTE.length;
318
+ }
319
+ }
320
+ usedColors[colorIndex] = true;
321
+ var palette = SESSION_PALETTE[colorIndex];
322
+ var shortId = sessionId.split(':').pop().slice(0, 8);
323
+ visualMap[sessionId] = {
324
+ label: '会话 ' + String.fromCharCode(65 + (index % 26)),
325
+ shortId: shortId,
326
+ border: palette.border,
327
+ soft: palette.soft,
328
+ text: palette.text
329
+ };
330
+ });
331
+ return visualMap;
332
+ }
333
+
334
+ function buildSessionLegend(chatData) {
335
+ var legend = document.getElementById('sessionLegend');
336
+ var buttons = document.getElementById('legendButtons');
337
+ var isWorkspace = chatData.session_count !== undefined;
338
+ if (!isWorkspace) {
339
+ legend.style.display = 'none';
340
+ buttons.innerHTML = '';
341
+ return;
342
+ }
343
+
344
+ sessionVisualMap = buildSessionVisualMap(chatData);
345
+ var counts = {};
346
+ (chatData.conversations || []).forEach(function(turn) {
347
+ var sourceId = turn.source_session_id || '';
348
+ counts[sourceId] = (counts[sourceId] || 0) + 1;
349
+ });
350
+ buttons.innerHTML = '';
351
+ legend.style.display = 'block';
352
+
353
+ function addButton(sessionId, label, count, visual) {
354
+ var button = document.createElement('button');
355
+ button.type = 'button';
356
+ button.className = 'legend-button' + (activeSessionFilter === sessionId ? ' active' : '');
357
+ button.style.borderColor = visual.border;
358
+ button.style.background = activeSessionFilter === sessionId ? visual.soft : '#fff';
359
+ button.style.color = visual.text;
360
+ button.title = sessionId || '显示全部会话';
361
+
362
+ var dot = document.createElement('span');
363
+ dot.className = 'legend-dot';
364
+ dot.style.background = visual.border;
365
+ var text = document.createElement('span');
366
+ text.textContent = label;
367
+ var countEl = document.createElement('span');
368
+ countEl.className = 'legend-count';
369
+ countEl.textContent = count + '轮';
370
+ button.appendChild(dot);
371
+ button.appendChild(text);
372
+ button.appendChild(countEl);
373
+ button.addEventListener('click', function() {
374
+ activeSessionFilter = sessionId;
375
+ renderSession(currentChatData);
376
+ });
377
+ buttons.appendChild(button);
378
+ }
379
+
380
+ addButton(null, '全部会话', (chatData.conversations || []).length, {
381
+ border: '#64748b', soft: '#f8fafc', text: '#334155'
382
+ });
383
+ Object.keys(sessionVisualMap).sort().forEach(function(sessionId) {
384
+ var visual = sessionVisualMap[sessionId];
385
+ var sessionName = '';
386
+ var sourceTurn = (chatData.conversations || []).find(function(turn) {
387
+ return turn.source_session_id === sessionId;
388
+ });
389
+ if (sourceTurn) sessionName = sourceTurn.source_session_name || '';
390
+ var label = visual.label + (sessionName ? ' · ' + sessionName : '') + ' · ' + visual.shortId;
391
+ addButton(sessionId, label, counts[sessionId] || 0, visual);
392
+ });
393
+ }
394
+
395
+ // Build dropdown from the workspace index (with old session-index fallback).
222
396
  function buildSelector() {
223
397
  if (typeof chatIndex === 'undefined' || !chatIndex || chatIndex.length === 0) {
224
398
  return; // No index data, hide selector
@@ -229,8 +403,14 @@
229
403
 
230
404
  chatIndex.forEach(function(item, i) {
231
405
  var opt = document.createElement('option');
232
- opt.value = item.session_id;
233
- var label = item.workspace_name + ' / ' + item.session_name + ' (' + item.total_pairs + '对)';
406
+ var workspaceMode = typeof chatWorkspaces !== 'undefined' && chatWorkspaces;
407
+ opt.value = workspaceMode ? item.workspace_id : item.session_id;
408
+ var label;
409
+ if (workspaceMode) {
410
+ label = item.workspace_name + ' (' + item.session_count + '个会话 · ' + item.total_pairs + '对)';
411
+ } else {
412
+ label = item.workspace_name + ' / ' + item.session_name + ' (' + item.total_pairs + '对)';
413
+ }
234
414
  if (item.first_time) label += ' [' + item.first_time + ']';
235
415
  opt.textContent = label;
236
416
  select.appendChild(opt);
@@ -241,17 +421,23 @@
241
421
  });
242
422
  }
243
423
 
244
- // Switch to a specific session
245
- function switchTo(sessionId) {
246
- if (typeof chatAll === 'undefined' || !chatAll) return;
247
-
248
- var data = chatAll[sessionId];
424
+ // Switch to a workspace timeline, or to a session for old-format data.
425
+ function switchTo(dataId) {
426
+ var data = null;
427
+ if (typeof chatWorkspaces !== 'undefined' && chatWorkspaces) {
428
+ data = chatWorkspaces[dataId];
429
+ }
430
+ if (!data && typeof chatAll !== 'undefined' && chatAll) {
431
+ data = chatAll[dataId];
432
+ }
249
433
  if (!data) {
250
- document.getElementById('conversationList').innerHTML = '<p style="text-align:center;color:#999;">该会话数据未找到</p>';
434
+ document.getElementById('conversationList').innerHTML = '<p style="text-align:center;color:#999;">该工作空间数据未找到</p>';
251
435
  return;
252
436
  }
253
437
 
254
- currentSession = sessionId;
438
+ currentSession = dataId;
439
+ currentChatData = data;
440
+ activeSessionFilter = null;
255
441
  renderSession(data);
256
442
 
257
443
  // Update meta
@@ -261,28 +447,39 @@
261
447
  }
262
448
  }
263
449
 
264
- // Render a session's conversations
450
+ // Render a workspace's merged timeline (also supports old session data).
265
451
  function renderSession(chatData) {
266
- document.getElementById('sessionId').textContent = chatData.session_id || '--';
267
- document.getElementById('sessionName').textContent = (chatData.workspace_name || '') + ' / ' + (chatData.session_name || '--');
268
- document.getElementById('initiator').textContent = chatData.initiator || '--';
269
- document.getElementById('totalPairs').textContent = chatData.total_pairs || 0;
452
+ var isWorkspace = chatData.session_count !== undefined;
453
+ currentChatData = chatData;
454
+ buildSessionLegend(chatData);
455
+ document.getElementById('sessionId').textContent = chatData.workspace_name || chatData.session_id || '--';
456
+ if (isWorkspace) {
457
+ var sessionNames = (chatData.session_names || []).join('、');
458
+ document.getElementById('sessionName').textContent = chatData.session_count + ' 个' + (sessionNames ? '(' + sessionNames + ')' : '');
459
+ } else {
460
+ document.getElementById('sessionName').textContent = (chatData.workspace_name || '') + ' / ' + (chatData.session_name || '--');
461
+ }
462
+ document.getElementById('initiator').textContent = (chatData.first_time && chatData.last_time) ? chatData.first_time + ' ~ ' + chatData.last_time : '--';
270
463
 
271
- var userCount = 0;
272
464
  var aiCount = 0;
273
465
  var totalDuration = 0;
274
466
  var list = document.getElementById('conversationList');
275
467
  list.innerHTML = '';
276
468
 
277
- var conversations = chatData.conversations || [];
469
+ var allConversations = chatData.conversations || [];
470
+ var conversations = activeSessionFilter ? allConversations.filter(function(turn) {
471
+ return turn.source_session_id === activeSessionFilter;
472
+ }) : allConversations;
473
+ var timelineStart = allConversations.length > 0 ? parseConversationTime(allConversations[0], 'user') : null;
474
+ document.getElementById('totalPairs').textContent = conversations.length;
278
475
  conversations.forEach(function(c, i) {
279
476
  var hasReply = c.ai && c.ai.trim();
280
477
  if (hasReply) aiCount++;
281
478
 
282
479
  var responseDuration = null;
283
480
  if (hasReply) {
284
- var userTime = parseTime(c.user_time);
285
- var aiTime = parseTime(c.ai_time);
481
+ var userTime = parseConversationTime(c, 'user');
482
+ var aiTime = parseConversationTime(c, 'ai');
286
483
  if (userTime && aiTime) {
287
484
  responseDuration = aiTime - userTime;
288
485
  if (responseDuration > 0) totalDuration += responseDuration;
@@ -291,28 +488,39 @@
291
488
 
292
489
  var intervalDuration = null;
293
490
  if (i < conversations.length - 1) {
294
- var nextUserTime = parseTime(conversations[i + 1].user_time);
295
- var currentUserTime = parseTime(c.user_time);
491
+ var nextUserTime = parseConversationTime(conversations[i + 1], 'user');
492
+ var currentUserTime = parseConversationTime(c, 'user');
296
493
  if (currentUserTime && nextUserTime) {
297
494
  intervalDuration = nextUserTime - currentUserTime;
298
495
  }
299
496
  }
300
497
 
301
498
  var elapsedDuration = null;
302
- if (i > 0) {
303
- var firstUserTime = parseTime(conversations[0].user_time);
304
- var currentUserTime2 = parseTime(c.user_time);
305
- if (firstUserTime && currentUserTime2) {
306
- elapsedDuration = currentUserTime2 - firstUserTime;
499
+ if (timelineStart) {
500
+ var currentUserTime2 = parseConversationTime(c, 'user');
501
+ if (currentUserTime2) {
502
+ elapsedDuration = currentUserTime2 - timelineStart;
307
503
  }
308
504
  }
309
505
 
310
506
  var pair = document.createElement('div');
311
507
  pair.className = 'pair';
508
+ var sourceBadge = '';
509
+ var visual = { border: '#94a3b8', soft: '#f8fafc', text: '#475569', label: '会话', shortId: '' };
510
+ if (c.source_session_id) {
511
+ visual = sessionVisualMap[c.source_session_id] || visual;
512
+ var originalTurn = c.source_turn_index || '?';
513
+ var sourceLabel = visual.label + ' · 原第 ' + originalTurn + ' 轮';
514
+ 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
+ }
516
+ pair.style.borderLeft = '6px solid ' + visual.border;
517
+ var displayedTurn = c.workspace_turn_index || (i + 1);
518
+ var turnLabel = isWorkspace ? '合并第 ' + displayedTurn + ' 轮' : '第 ' + displayedTurn + ' 轮';
312
519
  pair.innerHTML =
313
- '<div class="pair-header">' +
520
+ '<div class="pair-header" style="background:' + visual.soft + '">' +
314
521
  '<div class="pair-left">' +
315
- '<span class="pair-num">第 ' + (i + 1) + ' 轮</span>' +
522
+ '<span class="pair-num">' + turnLabel + '</span>' +
523
+ sourceBadge +
316
524
  (elapsedDuration !== null ? '<span class="pair-duration elapsed">⏰ 课程流逝: ' + formatDuration(elapsedDuration) + '</span>' : '<span class="pair-duration elapsed">⏰ 课程流逝: 0分</span>') +
317
525
  (intervalDuration !== null ? '<span class="pair-duration interval">⏸️ 间隔耗时: ' + formatDuration(intervalDuration) + '</span>' : '') +
318
526
  '</div>' +
@@ -348,13 +556,14 @@
348
556
 
349
557
  // Init
350
558
  (function() {
351
- // Strategy 1: Use index.js with chatIndex + chatAll
559
+ // Strategy 1: Use index.js workspace data (with old session fallback).
352
560
  if (typeof chatIndex !== 'undefined' && chatIndex && chatIndex.length > 0 &&
353
- typeof chatAll !== 'undefined' && chatAll) {
561
+ ((typeof chatWorkspaces !== 'undefined' && chatWorkspaces) ||
562
+ (typeof chatAll !== 'undefined' && chatAll))) {
354
563
  buildSelector();
355
- // Select first session
356
- document.getElementById('sessionSelect').value = chatIndex[0].session_id;
357
- switchTo(chatIndex[0].session_id);
564
+ var firstId = (typeof chatWorkspaces !== 'undefined' && chatWorkspaces) ? chatIndex[0].workspace_id : chatIndex[0].session_id;
565
+ document.getElementById('sessionSelect').value = firstId;
566
+ switchTo(firstId);
358
567
  return;
359
568
  }
360
569
 
@@ -111,14 +111,208 @@ def find_session_file(session_key):
111
111
  return None
112
112
 
113
113
 
114
- def count_conversations(jsonl_path):
115
- """Parse JSONL and return (conversation_count, first_ts, last_ts)."""
116
- messages = []
117
- first_timestamp = None
118
- last_timestamp = None
114
+ def _parse_iso_timestamp(ts_str):
115
+ """Parse an ISO-8601 timestamp as a timezone-aware datetime."""
116
+ if not ts_str:
117
+ return None
118
+ try:
119
+ return datetime.fromisoformat(ts_str.replace('Z', '+00:00'))
120
+ except (TypeError, ValueError):
121
+ return None
122
+
123
+
124
+ def _fingerprint_user_text(text):
125
+ """Return a lossless-enough fingerprint for replay detection.
126
+
127
+ Do not remove arbitrary bracketed prefixes or truncate long messages: both
128
+ can turn distinct, legitimate user messages into false duplicates. Line
129
+ endings are normalized only because they carry no conversational meaning.
130
+ """
131
+ return (text or '').replace('\r\n', '\n').replace('\r', '\n').strip()
132
+
133
+
134
+ def _model_snapshot_identity(event):
135
+ if event.get('type') != 'custom' or event.get('customType') != 'model-snapshot':
136
+ return None
137
+ data = event.get('data') or {}
138
+ return (
139
+ data.get('provider') or '',
140
+ data.get('modelApi') or '',
141
+ data.get('modelId') or '',
142
+ )
143
+
144
+
145
+ def _timestamps_form_burst(user_events, window_seconds):
146
+ """Require present, monotonic timestamps contained in a short window."""
147
+ timestamps = [_parse_iso_timestamp(ev.get('timestamp')) for ev in user_events]
148
+ if not timestamps or any(ts is None for ts in timestamps):
149
+ return False
150
+ if any(cur < prev for prev, cur in zip(timestamps, timestamps[1:])):
151
+ return False
152
+ return (timestamps[-1] - timestamps[0]).total_seconds() <= window_seconds
153
+
154
+
155
+ def _longest_history_prefix(history_users, replay_users):
156
+ """Find the longest prefix of replay_users occurring contiguously in history."""
157
+ best_start = None
158
+ best_length = 0
159
+ replay_keys = [ev['user_fingerprint'] for ev in replay_users]
160
+ history_keys = [ev['user_fingerprint'] for ev in history_users]
161
+
162
+ if not replay_keys or not replay_keys[0]:
163
+ return best_start, best_length
164
+
165
+ for history_start, history_key in enumerate(history_keys):
166
+ if history_key != replay_keys[0]:
167
+ continue
168
+ length = 0
169
+ while (
170
+ history_start + length < len(history_keys)
171
+ and length < len(replay_keys)
172
+ and history_keys[history_start + length] == replay_keys[length]
173
+ and replay_keys[length]
174
+ ):
175
+ length += 1
176
+ if length > best_length:
177
+ best_start = history_start
178
+ best_length = length
179
+
180
+ return best_start, best_length
181
+
182
+
183
+ def detect_history_replays(events, burst_window_seconds=3.0):
184
+ """Detect high-confidence history replay blocks after model snapshots.
185
+
186
+ A block is removed only when the first user messages after a model snapshot
187
+ reproduce a contiguous sequence of earlier user messages and the reproduced
188
+ messages have monotonic timestamps inside a very short burst. A model change
189
+ needs at least three matching user turns; a same-model snapshot needs five.
190
+
191
+ Returns ``(dropped_event_indices, reports)``. Indices refer to ``events`` and
192
+ only message events are included in the dropped set. The source JSONL is
193
+ never modified.
194
+ """
195
+ dropped = set()
196
+ reports = []
197
+ replay_ranges = []
198
+ last_snapshot_identity = None
199
+
200
+ for boundary_idx, boundary in enumerate(events):
201
+ snapshot_identity = _model_snapshot_identity(boundary)
202
+ if snapshot_identity is None:
203
+ continue
204
+
205
+ # Replayed custom events can contain old model snapshots too. They are
206
+ # evidence inside an already detected replay, not new live boundaries.
207
+ if any(start <= boundary_idx <= end for start, end in replay_ranges):
208
+ continue
209
+
210
+ previous_snapshot_identity = last_snapshot_identity
211
+ model_changed = (
212
+ previous_snapshot_identity is not None
213
+ and snapshot_identity != previous_snapshot_identity
214
+ )
215
+ last_snapshot_identity = snapshot_identity
216
+
217
+ history_users = [
218
+ ev for idx, ev in enumerate(events[:boundary_idx])
219
+ if ev.get('type') == 'message'
220
+ and ev.get('role') == 'user'
221
+ and idx not in dropped
222
+ ]
223
+ post_users = [
224
+ ev for idx, ev in enumerate(events[boundary_idx + 1:], boundary_idx + 1)
225
+ if ev.get('type') == 'message'
226
+ and ev.get('role') == 'user'
227
+ and idx not in dropped
228
+ ]
229
+ if not history_users or not post_users:
230
+ continue
231
+
232
+ history_start, match_length = _longest_history_prefix(history_users, post_users)
233
+ minimum_length = 3 if model_changed else 5
234
+ if history_start is None or match_length < minimum_length:
235
+ continue
236
+
237
+ matched_users = post_users[:match_length]
238
+ if not _timestamps_form_burst(matched_users, burst_window_seconds):
239
+ continue
240
+
241
+ first_replayed_user_idx = matched_users[0]['event_index']
242
+ replay_start_idx = first_replayed_user_idx
243
+
244
+ # A replay can begin with tool output and an assistant response belonging
245
+ # to a historical turn that precedes the first repeated user. Include that
246
+ # prefix only when every textual assistant there exactly matches an earlier
247
+ # assistant response. This removes the leaked reply seen in the supplied
248
+ # dashboard sample without swallowing a genuinely new model response.
249
+ prefix_messages = [
250
+ ev for ev in events[boundary_idx + 1:first_replayed_user_idx]
251
+ if ev.get('type') == 'message'
252
+ ]
253
+ prefix_assistants = [
254
+ ev for ev in prefix_messages
255
+ if ev.get('role') == 'assistant' and ev.get('text')
256
+ ]
257
+ prior_assistant_texts = {
258
+ ev.get('text') for ev in events[:boundary_idx]
259
+ if ev.get('type') == 'message'
260
+ and ev.get('role') == 'assistant'
261
+ and ev.get('text')
262
+ }
263
+ if (
264
+ prefix_messages
265
+ and prefix_assistants
266
+ and all(ev.get('text') in prior_assistant_texts for ev in prefix_assistants)
267
+ ):
268
+ replay_start_idx = boundary_idx + 1
269
+
270
+ next_user_idx = (
271
+ post_users[match_length]['event_index']
272
+ if match_length < len(post_users)
273
+ else len(events)
274
+ )
275
+ replay_end_idx = next_user_idx - 1
276
+
277
+ block_indices = {
278
+ idx for idx in range(replay_start_idx, replay_end_idx + 1)
279
+ if events[idx].get('type') == 'message'
280
+ }
281
+ if not block_indices:
282
+ continue
283
+ dropped.update(block_indices)
284
+ replay_ranges.append((replay_start_idx, replay_end_idx))
285
+
286
+ first_dropped_idx = min(block_indices)
287
+ last_dropped_idx = max(block_indices)
288
+
289
+ reports.append({
290
+ 'boundary_line': boundary.get('line_number'),
291
+ 'start_line': events[first_dropped_idx].get('line_number'),
292
+ 'end_line': events[last_dropped_idx].get('line_number'),
293
+ 'history_user_start': history_start + 1,
294
+ 'history_user_end': history_start + match_length,
295
+ 'replayed_users': match_length,
296
+ 'dropped_messages': len(block_indices),
297
+ 'model_changed': model_changed,
298
+ 'from_model': previous_snapshot_identity,
299
+ 'to_model': snapshot_identity,
300
+ })
301
+
302
+ return dropped, reports
303
+
304
+
305
+ def count_conversations(jsonl_path, include_dedupe_report=False):
306
+ """Parse JSONL and return conversations and timestamps.
307
+
308
+ High-confidence model-switch history replays are excluded from the exported
309
+ conversation, but the JSONL source file is never changed. Set
310
+ ``include_dedupe_report`` to receive a fourth return value with diagnostics.
311
+ """
312
+ events = []
119
313
 
120
314
  with open(jsonl_path, 'r', encoding='utf-8') as f:
121
- for line in f:
315
+ for line_number, line in enumerate(f, 1):
122
316
  line = line.strip()
123
317
  if not line:
124
318
  continue
@@ -128,24 +322,41 @@ def count_conversations(jsonl_path):
128
322
  content = obj['message'].get('content', [])
129
323
  timestamp = obj.get('timestamp', '')
130
324
 
131
- if timestamp:
132
- if first_timestamp is None:
133
- first_timestamp = timestamp
134
- last_timestamp = timestamp
135
-
136
325
  if isinstance(content, list):
137
326
  text = ''.join([c.get('text', '') for c in content if c.get('type') == 'text'])
138
327
  else:
139
328
  text = str(content)
140
329
 
141
- messages.append({
330
+ events.append({
331
+ 'type': 'message',
142
332
  'role': role,
143
333
  'text': text.strip(),
144
334
  'has_text': bool(text.strip()),
145
- 'timestamp': timestamp
335
+ 'timestamp': timestamp,
336
+ 'line_number': line_number,
337
+ })
338
+ events[-1]['event_index'] = len(events) - 1
339
+ if role == 'user':
340
+ events[-1]['user_fingerprint'] = _fingerprint_user_text(text)
341
+ else:
342
+ events.append({
343
+ 'type': obj.get('type'),
344
+ 'customType': obj.get('customType'),
345
+ 'data': obj.get('data'),
346
+ 'timestamp': obj.get('timestamp', ''),
347
+ 'line_number': line_number,
348
+ 'event_index': len(events),
146
349
  })
147
350
 
148
- # Count conversation pairs (user messages with at least one AI reply)
351
+ dropped, dedupe_reports = detect_history_replays(events)
352
+ messages = [
353
+ ev for idx, ev in enumerate(events)
354
+ if ev.get('type') == 'message' and idx not in dropped
355
+ ]
356
+ first_timestamp = messages[0].get('timestamp', '') if messages else None
357
+ last_timestamp = messages[-1].get('timestamp', '') if messages else None
358
+
359
+ # Build user turns and attach any assistant messages before the next user.
149
360
  conversations = []
150
361
  i = 0
151
362
  while i < len(messages):
@@ -159,19 +370,26 @@ def count_conversations(jsonl_path):
159
370
  ai_messages.append(messages[j])
160
371
  j += 1
161
372
  ai_text = '\n\n'.join([m['text'] for m in ai_messages if m['has_text']])
162
- user_time = parse_time(msg.get('timestamp', '')) or ''
163
- ai_time = parse_time(ai_messages[0].get('timestamp', '')) if ai_messages else ''
373
+ user_timestamp = msg.get('timestamp', '') or ''
374
+ ai_timestamp = ai_messages[0].get('timestamp', '') if ai_messages else ''
375
+ user_time = parse_time(user_timestamp) or ''
376
+ ai_time = parse_time(ai_timestamp) if ai_timestamp else ''
164
377
  conversations.append({
165
378
  'user': user_text,
166
379
  'ai': ai_text,
167
380
  'user_time': user_time or '',
168
381
  'ai_time': ai_time or '',
382
+ 'user_timestamp': user_timestamp,
383
+ 'ai_timestamp': ai_timestamp or '',
169
384
  })
170
385
  i += 1
171
386
  else:
172
387
  i += 1
173
388
 
174
- return conversations, first_timestamp, last_timestamp
389
+ result = (conversations, first_timestamp, last_timestamp)
390
+ if include_dedupe_report:
391
+ return result + (dedupe_reports,)
392
+ return result
175
393
 
176
394
 
177
395
 
@@ -185,15 +403,23 @@ def build_chat_data(conversations, session_key, first_ts, last_ts):
185
403
  workspace_name = parts[1] if len(parts) > 1 else 'unknown'
186
404
  session_name = parts[2] if len(parts) > 2 else 'main'
187
405
 
406
+ session_conversations = []
407
+ for turn_index, conversation in enumerate(conversations, 1):
408
+ turn = dict(conversation)
409
+ turn['source_session_id'] = session_key
410
+ turn['source_session_name'] = session_name
411
+ turn['source_turn_index'] = turn_index
412
+ session_conversations.append(turn)
413
+
188
414
  return {
189
415
  'workspace_name': workspace_name,
190
416
  'session_name': session_name,
191
417
  'session_id': session_key,
192
418
  'first_time': parse_time(first_ts) if first_ts else '',
193
419
  'last_time': parse_time(last_ts) if last_ts else '',
194
- 'total_pairs': len(conversations),
420
+ 'total_pairs': len(session_conversations),
195
421
  'work_url': '',
196
- 'conversations': conversations
422
+ 'conversations': session_conversations
197
423
  }
198
424
 
199
425
 
@@ -334,8 +560,16 @@ def process_one(url_or_key, output_dir, index):
334
560
  print(f"[{index}] ERROR: JSONL not found: {jsonl_path}")
335
561
  return None
336
562
 
337
- conversations, first_ts, last_ts = count_conversations(jsonl_path)
563
+ conversations, first_ts, last_ts, dedupe_reports = count_conversations(
564
+ jsonl_path, include_dedupe_report=True
565
+ )
338
566
  print(f"[{index}] {len(conversations)} pairs")
567
+ for report in dedupe_reports:
568
+ print(
569
+ f"[{index}] replay filtered: lines {report['start_line']}-{report['end_line']}, "
570
+ f"{report['replayed_users']} duplicated user turn(s), "
571
+ f"{report['dropped_messages']} message event(s)"
572
+ )
339
573
 
340
574
  data = build_chat_data(conversations, session_key, first_ts, last_ts)
341
575
 
@@ -352,20 +586,37 @@ def process_one(url_or_key, output_dir, index):
352
586
  }
353
587
 
354
588
 
355
- def generate_index_js(results, output_dir):
356
- """直接用内存中的 results 拼出唯一产物 index.js(chatIndex + chatAll)。
357
-
358
- 不再为每个会话单独落 js 文件——每个会话的完整对话都进 chatAll,
359
- HTML 只加载 index.js 即可渲染全部会话。
360
- """
361
- all_entries = []
589
+ def _workspace_turn_sort_key(turn):
590
+ """Sort by raw user timestamp, with deterministic fallbacks."""
591
+ parsed = _parse_iso_timestamp(turn.get('user_timestamp'))
592
+ if parsed is not None:
593
+ return (
594
+ 0,
595
+ parsed.timestamp(),
596
+ turn.get('_source_session_order', 0),
597
+ turn.get('source_turn_index', 0),
598
+ turn.get('source_session_id', ''),
599
+ )
600
+ return (
601
+ 1,
602
+ 0,
603
+ turn.get('_source_session_order', 0),
604
+ turn.get('source_turn_index', 0),
605
+ turn.get('source_session_id', ''),
606
+ )
607
+
608
+
609
+ def build_workspace_collections(results):
610
+ """Build session data plus merged, user-time-ordered workspace timelines."""
611
+ session_entries = []
362
612
  all_data = {}
613
+ grouped = {}
363
614
 
364
- for r in results:
615
+ for session_order, r in enumerate(results):
365
616
  data = r['data']
366
617
  sid = data['session_id']
367
618
  all_data[sid] = data
368
- all_entries.append({
619
+ session_entries.append({
369
620
  'workspace_name': data.get('workspace_name', ''),
370
621
  'session_name': data.get('session_name', ''),
371
622
  'session_id': sid,
@@ -375,17 +626,97 @@ def generate_index_js(results, output_dir):
375
626
  'work_url': data.get('work_url', ''),
376
627
  })
377
628
 
629
+ workspace_name = data.get('workspace_name') or 'unknown'
630
+ workspace = grouped.setdefault(workspace_name, {
631
+ 'workspace_name': workspace_name,
632
+ 'workspace_id': workspace_name,
633
+ 'session_ids': [],
634
+ 'session_names': [],
635
+ 'work_urls': [],
636
+ 'conversations': [],
637
+ })
638
+ workspace['session_ids'].append(sid)
639
+ session_name = data.get('session_name') or 'main'
640
+ if session_name not in workspace['session_names']:
641
+ workspace['session_names'].append(session_name)
642
+ work_url = data.get('work_url') or ''
643
+ if work_url and work_url not in workspace['work_urls']:
644
+ workspace['work_urls'].append(work_url)
645
+
646
+ for source_turn_index, conversation in enumerate(data.get('conversations', []), 1):
647
+ turn = dict(conversation)
648
+ turn.setdefault('source_session_id', sid)
649
+ turn.setdefault('source_session_name', session_name)
650
+ turn.setdefault('source_turn_index', source_turn_index)
651
+ turn['_source_session_order'] = session_order
652
+ workspace['conversations'].append(turn)
653
+
654
+ workspace_entries = []
655
+ workspace_data = {}
656
+ for workspace_name, workspace in grouped.items():
657
+ workspace['conversations'].sort(key=_workspace_turn_sort_key)
658
+ valid_turns = [
659
+ turn for turn in workspace['conversations']
660
+ if _parse_iso_timestamp(turn.get('user_timestamp')) is not None
661
+ ]
662
+ for workspace_turn_index, turn in enumerate(workspace['conversations'], 1):
663
+ turn['workspace_turn_index'] = workspace_turn_index
664
+ turn.pop('_source_session_order', None)
665
+
666
+ first_turn = valid_turns[0] if valid_turns else None
667
+ last_turn = valid_turns[-1] if valid_turns else None
668
+ workspace['session_count'] = len(workspace['session_ids'])
669
+ workspace['total_pairs'] = len(workspace['conversations'])
670
+ workspace['unknown_timestamp_turns'] = (
671
+ workspace['total_pairs'] - len(valid_turns)
672
+ )
673
+ workspace['first_time'] = first_turn.get('user_time', '') if first_turn else ''
674
+ workspace['last_time'] = last_turn.get('user_time', '') if last_turn else ''
675
+ workspace['first_user_timestamp'] = (
676
+ first_turn.get('user_timestamp', '') if first_turn else ''
677
+ )
678
+ workspace['last_user_timestamp'] = (
679
+ last_turn.get('user_timestamp', '') if last_turn else ''
680
+ )
681
+
682
+ workspace_data[workspace_name] = workspace
683
+ workspace_entries.append({
684
+ 'workspace_name': workspace_name,
685
+ 'workspace_id': workspace_name,
686
+ 'session_count': workspace['session_count'],
687
+ 'session_ids': list(workspace['session_ids']),
688
+ 'total_pairs': workspace['total_pairs'],
689
+ 'first_time': workspace['first_time'],
690
+ 'last_time': workspace['last_time'],
691
+ 'unknown_timestamp_turns': workspace['unknown_timestamp_turns'],
692
+ })
693
+
694
+ return workspace_entries, workspace_data, session_entries, all_data
695
+
696
+
697
+ def generate_index_js(results, output_dir):
698
+ """Generate workspace timelines while retaining original session data."""
699
+ workspace_entries, workspace_data, session_entries, all_data = (
700
+ build_workspace_collections(results)
701
+ )
702
+
378
703
  now_ts = int(time.time())
379
- idx = '// Chat History Index - %d session(s)\n' % len(all_entries)
704
+ idx = '// Chat History Index - %d workspace(s), %d session(s)\n' % (
705
+ len(workspace_entries), len(session_entries)
706
+ )
380
707
  idx += '// Generated by chat-history-extractor skill\n'
381
708
  idx += '// timestamp: %d\n\n' % now_ts
382
- idx += 'const chatIndex = %s;\n\n' % json.dumps(all_entries, ensure_ascii=False, indent=2)
709
+ idx += 'const chatIndex = %s;\n\n' % json.dumps(workspace_entries, ensure_ascii=False, indent=2)
710
+ idx += 'const chatWorkspaces = %s;\n\n' % json.dumps(workspace_data, ensure_ascii=False)
711
+ idx += 'const chatSessionIndex = %s;\n\n' % json.dumps(session_entries, ensure_ascii=False, indent=2)
383
712
  idx += 'const chatAll = %s;\n' % json.dumps(all_data, ensure_ascii=False)
384
713
 
385
714
  index_path = os.path.join(output_dir, 'index.js')
386
715
  with open(index_path, 'w', encoding='utf-8') as f:
387
716
  f.write(idx)
388
- print('\nIndex: %s (%d sessions, ts=%d)' % (index_path, len(all_entries), now_ts))
717
+ print('\nIndex: %s (%d workspaces, %d sessions, ts=%d)' % (
718
+ index_path, len(workspace_entries), len(session_entries), now_ts
719
+ ))
389
720
 
390
721
 
391
722
  def run_scan(output_dir=None, host=None):