@aiyiran/myclaw 1.1.205 → 1.1.207

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.
@@ -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,22 +133,229 @@ 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
155
+
156
+
157
+ def _parse_iso_timestamp(ts_str):
158
+ """Parse an ISO-8601 timestamp as a timezone-aware datetime."""
159
+ if not ts_str:
160
+ return None
161
+ try:
162
+ return datetime.fromisoformat(ts_str.replace('Z', '+00:00'))
163
+ except (TypeError, ValueError):
164
+ return None
165
+
166
+
167
+ def _fingerprint_user_text(text):
168
+ """Return a lossless-enough fingerprint for replay detection.
169
+
170
+ Do not remove arbitrary bracketed prefixes or truncate long messages: both
171
+ can turn distinct, legitimate user messages into false duplicates. Line
172
+ endings are normalized only because they carry no conversational meaning.
173
+ """
174
+ return (text or '').replace('\r\n', '\n').replace('\r', '\n').strip()
175
+
176
+
177
+ def _model_snapshot_identity(event):
178
+ if event.get('type') != 'custom' or event.get('customType') != 'model-snapshot':
179
+ return None
180
+ data = event.get('data') or {}
181
+ return (
182
+ data.get('provider') or '',
183
+ data.get('modelApi') or '',
184
+ data.get('modelId') or '',
185
+ )
186
+
187
+
188
+ def _timestamps_form_burst(user_events, window_seconds):
189
+ """Require present, monotonic timestamps contained in a short window."""
190
+ timestamps = [_parse_iso_timestamp(ev.get('timestamp')) for ev in user_events]
191
+ if not timestamps or any(ts is None for ts in timestamps):
192
+ return False
193
+ if any(cur < prev for prev, cur in zip(timestamps, timestamps[1:])):
194
+ return False
195
+ return (timestamps[-1] - timestamps[0]).total_seconds() <= window_seconds
196
+
197
+
198
+ def _longest_history_prefix(history_users, replay_users):
199
+ """Find the longest prefix of replay_users occurring contiguously in history."""
200
+ best_start = None
201
+ best_length = 0
202
+ replay_keys = [ev['user_fingerprint'] for ev in replay_users]
203
+ history_keys = [ev['user_fingerprint'] for ev in history_users]
204
+
205
+ if not replay_keys or not replay_keys[0]:
206
+ return best_start, best_length
207
+
208
+ for history_start, history_key in enumerate(history_keys):
209
+ if history_key != replay_keys[0]:
210
+ continue
211
+ length = 0
212
+ while (
213
+ history_start + length < len(history_keys)
214
+ and length < len(replay_keys)
215
+ and history_keys[history_start + length] == replay_keys[length]
216
+ and replay_keys[length]
217
+ ):
218
+ length += 1
219
+ if length > best_length:
220
+ best_start = history_start
221
+ best_length = length
222
+
223
+ return best_start, best_length
224
+
225
+
226
+ def detect_history_replays(events, burst_window_seconds=3.0):
227
+ """Detect high-confidence history replay blocks after model snapshots.
228
+
229
+ A block is removed only when the first user messages after a model snapshot
230
+ reproduce a contiguous sequence of earlier user messages and the reproduced
231
+ messages have monotonic timestamps inside a very short burst. A model change
232
+ needs at least three matching user turns; a same-model snapshot needs five.
233
+
234
+ Returns ``(dropped_event_indices, reports)``. Indices refer to ``events`` and
235
+ only message events are included in the dropped set. The source JSONL is
236
+ never modified.
237
+ """
238
+ dropped = set()
239
+ reports = []
240
+ replay_ranges = []
241
+ last_snapshot_identity = None
242
+
243
+ for boundary_idx, boundary in enumerate(events):
244
+ snapshot_identity = _model_snapshot_identity(boundary)
245
+ if snapshot_identity is None:
246
+ continue
247
+
248
+ # Replayed custom events can contain old model snapshots too. They are
249
+ # evidence inside an already detected replay, not new live boundaries.
250
+ if any(start <= boundary_idx <= end for start, end in replay_ranges):
251
+ continue
252
+
253
+ previous_snapshot_identity = last_snapshot_identity
254
+ model_changed = (
255
+ previous_snapshot_identity is not None
256
+ and snapshot_identity != previous_snapshot_identity
257
+ )
258
+ last_snapshot_identity = snapshot_identity
259
+
260
+ history_users = [
261
+ ev for idx, ev in enumerate(events[:boundary_idx])
262
+ if ev.get('type') == 'message'
263
+ and ev.get('role') == 'user'
264
+ and idx not in dropped
265
+ ]
266
+ post_users = [
267
+ ev for idx, ev in enumerate(events[boundary_idx + 1:], boundary_idx + 1)
268
+ if ev.get('type') == 'message'
269
+ and ev.get('role') == 'user'
270
+ and idx not in dropped
271
+ ]
272
+ if not history_users or not post_users:
273
+ continue
274
+
275
+ history_start, match_length = _longest_history_prefix(history_users, post_users)
276
+ minimum_length = 3 if model_changed else 5
277
+ if history_start is None or match_length < minimum_length:
278
+ continue
279
+
280
+ matched_users = post_users[:match_length]
281
+ if not _timestamps_form_burst(matched_users, burst_window_seconds):
282
+ continue
283
+
284
+ first_replayed_user_idx = matched_users[0]['event_index']
285
+ replay_start_idx = first_replayed_user_idx
286
+
287
+ # A replay can begin with tool output and an assistant response belonging
288
+ # to a historical turn that precedes the first repeated user. Include that
289
+ # prefix only when every textual assistant there exactly matches an earlier
290
+ # assistant response. This removes the leaked reply seen in the supplied
291
+ # dashboard sample without swallowing a genuinely new model response.
292
+ prefix_messages = [
293
+ ev for ev in events[boundary_idx + 1:first_replayed_user_idx]
294
+ if ev.get('type') == 'message'
295
+ ]
296
+ prefix_assistants = [
297
+ ev for ev in prefix_messages
298
+ if ev.get('role') == 'assistant' and ev.get('text')
299
+ ]
300
+ prior_assistant_texts = {
301
+ ev.get('text') for ev in events[:boundary_idx]
302
+ if ev.get('type') == 'message'
303
+ and ev.get('role') == 'assistant'
304
+ and ev.get('text')
305
+ }
306
+ if (
307
+ prefix_messages
308
+ and prefix_assistants
309
+ and all(ev.get('text') in prior_assistant_texts for ev in prefix_assistants)
310
+ ):
311
+ replay_start_idx = boundary_idx + 1
312
+
313
+ next_user_idx = (
314
+ post_users[match_length]['event_index']
315
+ if match_length < len(post_users)
316
+ else len(events)
317
+ )
318
+ replay_end_idx = next_user_idx - 1
319
+
320
+ block_indices = {
321
+ idx for idx in range(replay_start_idx, replay_end_idx + 1)
322
+ if events[idx].get('type') == 'message'
323
+ }
324
+ if not block_indices:
325
+ continue
326
+ dropped.update(block_indices)
327
+ replay_ranges.append((replay_start_idx, replay_end_idx))
328
+
329
+ first_dropped_idx = min(block_indices)
330
+ last_dropped_idx = max(block_indices)
331
+
332
+ reports.append({
333
+ 'boundary_line': boundary.get('line_number'),
334
+ 'start_line': events[first_dropped_idx].get('line_number'),
335
+ 'end_line': events[last_dropped_idx].get('line_number'),
336
+ 'history_user_start': history_start + 1,
337
+ 'history_user_end': history_start + match_length,
338
+ 'replayed_users': match_length,
339
+ 'dropped_messages': len(block_indices),
340
+ 'model_changed': model_changed,
341
+ 'from_model': previous_snapshot_identity,
342
+ 'to_model': snapshot_identity,
343
+ })
344
+
345
+ return dropped, reports
112
346
 
113
347
 
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
348
+ def count_conversations(jsonl_path, include_dedupe_report=False):
349
+ """Parse JSONL and return conversations and timestamps.
350
+
351
+ High-confidence model-switch history replays are excluded from the exported
352
+ conversation, but the JSONL source file is never changed. Set
353
+ ``include_dedupe_report`` to receive a fourth return value with diagnostics.
354
+ """
355
+ events = []
119
356
 
120
357
  with open(jsonl_path, 'r', encoding='utf-8') as f:
121
- for line in f:
358
+ for line_number, line in enumerate(f, 1):
122
359
  line = line.strip()
123
360
  if not line:
124
361
  continue
@@ -128,24 +365,41 @@ def count_conversations(jsonl_path):
128
365
  content = obj['message'].get('content', [])
129
366
  timestamp = obj.get('timestamp', '')
130
367
 
131
- if timestamp:
132
- if first_timestamp is None:
133
- first_timestamp = timestamp
134
- last_timestamp = timestamp
135
-
136
368
  if isinstance(content, list):
137
369
  text = ''.join([c.get('text', '') for c in content if c.get('type') == 'text'])
138
370
  else:
139
371
  text = str(content)
140
372
 
141
- messages.append({
373
+ events.append({
374
+ 'type': 'message',
142
375
  'role': role,
143
376
  'text': text.strip(),
144
377
  'has_text': bool(text.strip()),
145
- 'timestamp': timestamp
378
+ 'timestamp': timestamp,
379
+ 'line_number': line_number,
380
+ })
381
+ events[-1]['event_index'] = len(events) - 1
382
+ if role == 'user':
383
+ events[-1]['user_fingerprint'] = _fingerprint_user_text(text)
384
+ else:
385
+ events.append({
386
+ 'type': obj.get('type'),
387
+ 'customType': obj.get('customType'),
388
+ 'data': obj.get('data'),
389
+ 'timestamp': obj.get('timestamp', ''),
390
+ 'line_number': line_number,
391
+ 'event_index': len(events),
146
392
  })
147
393
 
148
- # Count conversation pairs (user messages with at least one AI reply)
394
+ dropped, dedupe_reports = detect_history_replays(events)
395
+ messages = [
396
+ ev for idx, ev in enumerate(events)
397
+ if ev.get('type') == 'message' and idx not in dropped
398
+ ]
399
+ first_timestamp = messages[0].get('timestamp', '') if messages else None
400
+ last_timestamp = messages[-1].get('timestamp', '') if messages else None
401
+
402
+ # Build user turns and attach any assistant messages before the next user.
149
403
  conversations = []
150
404
  i = 0
151
405
  while i < len(messages):
@@ -159,24 +413,38 @@ def count_conversations(jsonl_path):
159
413
  ai_messages.append(messages[j])
160
414
  j += 1
161
415
  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 ''
416
+ user_timestamp = msg.get('timestamp', '') or ''
417
+ ai_timestamp = ai_messages[0].get('timestamp', '') if ai_messages else ''
418
+ user_time = parse_time(user_timestamp) or ''
419
+ ai_time = parse_time(ai_timestamp) if ai_timestamp else ''
164
420
  conversations.append({
165
421
  'user': user_text,
166
422
  'ai': ai_text,
167
423
  'user_time': user_time or '',
168
424
  'ai_time': ai_time or '',
425
+ 'user_timestamp': user_timestamp,
426
+ 'ai_timestamp': ai_timestamp or '',
169
427
  })
170
428
  i += 1
171
429
  else:
172
430
  i += 1
173
431
 
174
- return conversations, first_timestamp, last_timestamp
432
+ result = (conversations, first_timestamp, last_timestamp)
433
+ if include_dedupe_report:
434
+ return result + (dedupe_reports,)
435
+ return result
175
436
 
176
437
 
177
438
 
178
439
 
179
- 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
+ ):
180
448
  """构建单个会话的完整数据对象(仅内存,不写盘)。
181
449
 
182
450
  数据最终全部汇入 index.js 的 chatAll,不再为每个会话单独落 js 文件。
@@ -184,16 +452,28 @@ def build_chat_data(conversations, session_key, first_ts, last_ts):
184
452
  parts = session_key.split(':')
185
453
  workspace_name = parts[1] if len(parts) > 1 else 'unknown'
186
454
  session_name = parts[2] if len(parts) > 2 else 'main'
455
+ session_label = session_label or session_name
456
+
457
+ session_conversations = []
458
+ for turn_index, conversation in enumerate(conversations, 1):
459
+ turn = dict(conversation)
460
+ turn['source_session_id'] = session_key
461
+ turn['source_session_name'] = session_name
462
+ turn['source_session_label'] = session_label
463
+ turn['source_turn_index'] = turn_index
464
+ session_conversations.append(turn)
187
465
 
188
466
  return {
189
467
  'workspace_name': workspace_name,
468
+ 'workspace_label': workspace_label or '',
190
469
  'session_name': session_name,
470
+ 'session_label': session_label,
191
471
  'session_id': session_key,
192
472
  'first_time': parse_time(first_ts) if first_ts else '',
193
473
  'last_time': parse_time(last_ts) if last_ts else '',
194
- 'total_pairs': len(conversations),
474
+ 'total_pairs': len(session_conversations),
195
475
  'work_url': '',
196
- 'conversations': conversations
476
+ 'conversations': session_conversations
197
477
  }
198
478
 
199
479
 
@@ -228,7 +508,8 @@ def scan_all_agents():
228
508
  continue
229
509
  parts = session_key.split(':')
230
510
  session_name = parts[2] if len(parts) > 2 else 'main'
231
- 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))
232
513
  return results
233
514
 
234
515
 
@@ -241,8 +522,12 @@ def print_summary_table(entries, host=None):
241
522
  for e in entries:
242
523
  work = e.get('work_url') or '(待填)'
243
524
  url = session_key_to_url(e['session_key'], host)
244
- name = (e['session_name'] or '')[:26]
245
- 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]
246
531
  first_t = (e.get('first_time') or '')[:19]
247
532
  last_t = (e.get('last_time') or '')[:19]
248
533
  print(f"{e['index']:>3} {agent:<16} {name:<28} {e['total_pairs']:>6} {first_t:<20} {last_t:<20} {work:<14} {url}")
@@ -271,21 +556,23 @@ def generate_html_table(entries, host, output_path):
271
556
  rows_html = []
272
557
  for e in entries:
273
558
  chat_url = session_key_to_url(e['session_key'], host)
274
- name = e.get('session_name', '') or ''
559
+ name = e.get('session_label') or e.get('session_name', '') or ''
275
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
276
563
  chat_cell = '<a href="' + chat_url + '" target="_blank" class="link">💬 打开对话</a>'
277
564
  bg, border = agent_colors[agent]
278
565
  work_val = e.get('work_url', '') or ''
279
566
 
280
567
  row = '\n <tr style="background: ' + bg + '; border-left: 3px solid ' + border + ';">'
281
- 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>'
282
569
  row += '\n <td class="num">' + str(e['index']) + '</td>'
283
- row += '\n <td>' + agent + '</td>'
284
- row += '\n <td>' + name + '</td>'
570
+ row += '\n <td>' + html_escape(agent_display) + '</td>'
571
+ row += '\n <td>' + html_escape(name) + '</td>'
285
572
  row += '\n <td class="num">' + str(e['total_pairs']) + '</td>'
286
573
  row += '\n <td>' + e.get('first_time', '') + '</td>'
287
574
  row += '\n <td>' + e.get('last_time', '') + '</td>'
288
- 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>'
289
576
  row += '\n <td>' + chat_cell + '</td>'
290
577
  row += '\n </tr>'
291
578
  rows_html.append(row)
@@ -293,7 +580,7 @@ def generate_html_table(entries, host, output_path):
293
580
  rows = '\n'.join(rows_html)
294
581
 
295
582
  legend_items = ''.join([
296
- '<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>'
297
584
  for agent, (bg, bd) in sorted(agent_colors.items())
298
585
  ])
299
586
 
@@ -326,24 +613,44 @@ def process_one(url_or_key, output_dir, index):
326
613
 
327
614
  print(f"\n[{index}] Session key: {session_key}")
328
615
 
329
- jsonl_path = find_session_file(session_key)
330
- if not jsonl_path:
616
+ session_metadata = find_session_metadata(session_key)
617
+ if not session_metadata or not session_metadata.get('session_file'):
331
618
  print(f"[{index}] ERROR: Could not find session file")
332
619
  return None
620
+ jsonl_path = session_metadata['session_file']
333
621
  if not os.path.exists(jsonl_path):
334
622
  print(f"[{index}] ERROR: JSONL not found: {jsonl_path}")
335
623
  return None
336
624
 
337
- conversations, first_ts, last_ts = count_conversations(jsonl_path)
625
+ conversations, first_ts, last_ts, dedupe_reports = count_conversations(
626
+ jsonl_path, include_dedupe_report=True
627
+ )
338
628
  print(f"[{index}] {len(conversations)} pairs")
339
-
340
- data = build_chat_data(conversations, session_key, first_ts, last_ts)
629
+ for report in dedupe_reports:
630
+ print(
631
+ f"[{index}] replay filtered: lines {report['start_line']}-{report['end_line']}, "
632
+ f"{report['replayed_users']} duplicated user turn(s), "
633
+ f"{report['dropped_messages']} message event(s)"
634
+ )
635
+
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
+ )
341
646
 
342
647
  return {
343
648
  'index': index,
344
649
  'session_key': session_key,
345
650
  'session_name': session_name,
651
+ 'session_label': session_label,
346
652
  'agent_id': agent_id,
653
+ 'workspace_label': workspace_label,
347
654
  'total_pairs': data['total_pairs'],
348
655
  'first_time': data['first_time'],
349
656
  'last_time': data['last_time'],
@@ -352,22 +659,41 @@ def process_one(url_or_key, output_dir, index):
352
659
  }
353
660
 
354
661
 
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 = []
662
+ def _workspace_turn_sort_key(turn):
663
+ """Sort by raw user timestamp, with deterministic fallbacks."""
664
+ parsed = _parse_iso_timestamp(turn.get('user_timestamp'))
665
+ if parsed is not None:
666
+ return (
667
+ 0,
668
+ parsed.timestamp(),
669
+ turn.get('_source_session_order', 0),
670
+ turn.get('source_turn_index', 0),
671
+ turn.get('source_session_id', ''),
672
+ )
673
+ return (
674
+ 1,
675
+ 0,
676
+ turn.get('_source_session_order', 0),
677
+ turn.get('source_turn_index', 0),
678
+ turn.get('source_session_id', ''),
679
+ )
680
+
681
+
682
+ def build_workspace_collections(results):
683
+ """Build session data plus merged, user-time-ordered workspace timelines."""
684
+ session_entries = []
362
685
  all_data = {}
686
+ grouped = {}
363
687
 
364
- for r in results:
688
+ for session_order, r in enumerate(results):
365
689
  data = r['data']
366
690
  sid = data['session_id']
367
691
  all_data[sid] = data
368
- all_entries.append({
692
+ session_entries.append({
369
693
  'workspace_name': data.get('workspace_name', ''),
694
+ 'workspace_label': data.get('workspace_label', ''),
370
695
  'session_name': data.get('session_name', ''),
696
+ 'session_label': data.get('session_label', ''),
371
697
  'session_id': sid,
372
698
  'total_pairs': data.get('total_pairs', 0),
373
699
  'first_time': data.get('first_time', ''),
@@ -375,17 +701,113 @@ def generate_index_js(results, output_dir):
375
701
  'work_url': data.get('work_url', ''),
376
702
  })
377
703
 
704
+ workspace_name = data.get('workspace_name') or 'unknown'
705
+ workspace = grouped.setdefault(workspace_name, {
706
+ 'workspace_name': workspace_name,
707
+ 'workspace_label': data.get('workspace_label') or '',
708
+ 'workspace_id': workspace_name,
709
+ 'session_ids': [],
710
+ 'session_names': [],
711
+ 'session_labels': [],
712
+ 'session_sources': [],
713
+ 'work_urls': [],
714
+ 'conversations': [],
715
+ })
716
+ if not workspace['workspace_label'] and data.get('workspace_label'):
717
+ workspace['workspace_label'] = data['workspace_label']
718
+ workspace['session_ids'].append(sid)
719
+ session_name = data.get('session_name') or 'main'
720
+ session_label = data.get('session_label') or session_name
721
+ if session_name not in workspace['session_names']:
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
+ })
731
+ work_url = data.get('work_url') or ''
732
+ if work_url and work_url not in workspace['work_urls']:
733
+ workspace['work_urls'].append(work_url)
734
+
735
+ for source_turn_index, conversation in enumerate(data.get('conversations', []), 1):
736
+ turn = dict(conversation)
737
+ turn.setdefault('source_session_id', sid)
738
+ turn.setdefault('source_session_name', session_name)
739
+ turn.setdefault('source_session_label', session_label)
740
+ turn.setdefault('source_turn_index', source_turn_index)
741
+ turn['_source_session_order'] = session_order
742
+ workspace['conversations'].append(turn)
743
+
744
+ workspace_entries = []
745
+ workspace_data = {}
746
+ for workspace_name, workspace in grouped.items():
747
+ workspace['conversations'].sort(key=_workspace_turn_sort_key)
748
+ valid_turns = [
749
+ turn for turn in workspace['conversations']
750
+ if _parse_iso_timestamp(turn.get('user_timestamp')) is not None
751
+ ]
752
+ for workspace_turn_index, turn in enumerate(workspace['conversations'], 1):
753
+ turn['workspace_turn_index'] = workspace_turn_index
754
+ turn.pop('_source_session_order', None)
755
+
756
+ first_turn = valid_turns[0] if valid_turns else None
757
+ last_turn = valid_turns[-1] if valid_turns else None
758
+ workspace['session_count'] = len(workspace['session_ids'])
759
+ workspace['total_pairs'] = len(workspace['conversations'])
760
+ workspace['unknown_timestamp_turns'] = (
761
+ workspace['total_pairs'] - len(valid_turns)
762
+ )
763
+ workspace['first_time'] = first_turn.get('user_time', '') if first_turn else ''
764
+ workspace['last_time'] = last_turn.get('user_time', '') if last_turn else ''
765
+ workspace['first_user_timestamp'] = (
766
+ first_turn.get('user_timestamp', '') if first_turn else ''
767
+ )
768
+ workspace['last_user_timestamp'] = (
769
+ last_turn.get('user_timestamp', '') if last_turn else ''
770
+ )
771
+
772
+ workspace_data[workspace_name] = workspace
773
+ workspace_entries.append({
774
+ 'workspace_name': workspace_name,
775
+ 'workspace_label': workspace['workspace_label'],
776
+ 'workspace_id': workspace_name,
777
+ 'session_count': workspace['session_count'],
778
+ 'session_ids': list(workspace['session_ids']),
779
+ 'total_pairs': workspace['total_pairs'],
780
+ 'first_time': workspace['first_time'],
781
+ 'last_time': workspace['last_time'],
782
+ 'unknown_timestamp_turns': workspace['unknown_timestamp_turns'],
783
+ })
784
+
785
+ return workspace_entries, workspace_data, session_entries, all_data
786
+
787
+
788
+ def generate_index_js(results, output_dir):
789
+ """Generate workspace timelines while retaining original session data."""
790
+ workspace_entries, workspace_data, session_entries, all_data = (
791
+ build_workspace_collections(results)
792
+ )
793
+
378
794
  now_ts = int(time.time())
379
- idx = '// Chat History Index - %d session(s)\n' % len(all_entries)
795
+ idx = '// Chat History Index - %d workspace(s), %d session(s)\n' % (
796
+ len(workspace_entries), len(session_entries)
797
+ )
380
798
  idx += '// Generated by chat-history-extractor skill\n'
381
799
  idx += '// timestamp: %d\n\n' % now_ts
382
- idx += 'const chatIndex = %s;\n\n' % json.dumps(all_entries, ensure_ascii=False, indent=2)
800
+ idx += 'const chatIndex = %s;\n\n' % json.dumps(workspace_entries, ensure_ascii=False, indent=2)
801
+ idx += 'const chatWorkspaces = %s;\n\n' % json.dumps(workspace_data, ensure_ascii=False)
802
+ idx += 'const chatSessionIndex = %s;\n\n' % json.dumps(session_entries, ensure_ascii=False, indent=2)
383
803
  idx += 'const chatAll = %s;\n' % json.dumps(all_data, ensure_ascii=False)
384
804
 
385
805
  index_path = os.path.join(output_dir, 'index.js')
386
806
  with open(index_path, 'w', encoding='utf-8') as f:
387
807
  f.write(idx)
388
- print('\nIndex: %s (%d sessions, ts=%d)' % (index_path, len(all_entries), now_ts))
808
+ print('\nIndex: %s (%d workspaces, %d sessions, ts=%d)' % (
809
+ index_path, len(workspace_entries), len(session_entries), now_ts
810
+ ))
389
811
 
390
812
 
391
813
  def run_scan(output_dir=None, host=None):
@@ -393,17 +815,20 @@ def run_scan(output_dir=None, host=None):
393
815
  if host is None:
394
816
  host = detect_chat_host()
395
817
  all_sessions = scan_all_agents()
818
+ workspace_labels = load_workspace_labels()
396
819
  print("Found %d session(s) across all agents.\n" % len(all_sessions))
397
820
 
398
821
  entries = []
399
- 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):
400
823
  try:
401
824
  convs, first_ts, last_ts = count_conversations(jsonl_path)
402
825
  entries.append({
403
826
  'index': i,
404
827
  'session_key': session_key,
405
828
  'session_name': session_name,
829
+ 'session_label': session_label,
406
830
  'agent_id': agent_id,
831
+ 'workspace_label': get_workspace_label(agent_id, workspace_labels),
407
832
  'total_pairs': len(convs),
408
833
  'work_url': '',
409
834
  'first_time': parse_time(first_ts) if first_ts else '',