-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaude_viewer.html
More file actions
1308 lines (1186 loc) · 50.2 KB
/
claude_viewer.html
File metadata and controls
1308 lines (1186 loc) · 50.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Claude / Codex 会话查看器</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dompurify/dist/purify.min.js"></script>
<style>
mark {
background-color: #fef08a;
padding: 0 2px;
border-radius: 2px;
}
.markdown-content h1 { font-size: 1.5em; font-weight: bold; margin: 0.5em 0; }
.markdown-content h2 { font-size: 1.3em; font-weight: bold; margin: 0.5em 0; }
.markdown-content h3 { font-size: 1.1em; font-weight: bold; margin: 0.5em 0; }
.markdown-content code { background: #f1f5f9; padding: 0.2em 0.4em; border-radius: 3px; font-family: monospace; white-space: pre-wrap; overflow-wrap: anywhere; word-break: break-word; }
.markdown-content pre { background: #f1f5f9; padding: 1em; border-radius: 6px; overflow-x: auto; }
.markdown-content pre code { background: none; padding: 0; }
.markdown-content ul { list-style: disc; margin-left: 1.5em; }
.markdown-content ol { list-style: decimal; margin-left: 1.5em; }
.markdown-content a { color: #3b82f6; text-decoration: underline; }
.markdown-content { overflow-wrap: anywhere; }
/* 改进 pre 标签的文本换行 */
pre {
white-space: pre-wrap;
word-wrap: break-word;
overflow-wrap: break-word;
}
/* 确保代码块不会超出容器 */
pre code {
display: block;
max-width: 100%;
}
</style>
</head>
<body class="bg-slate-50 text-slate-900">
<div class="flex h-screen">
<!-- 左侧边栏 -->
<aside class="w-80 shrink-0 border-r bg-white flex flex-col">
<div class="p-5 border-b">
<div class="text-lg font-semibold">Claude / Codex 会话查看器</div>
<div class="text-xs text-slate-500 mt-1">
本地会话历史浏览器
</div>
<label class="block text-xs text-slate-500 mt-4">项目</label>
<select
id="projectSelect"
class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
></select>
</div>
<div class="px-5 pt-4 text-xs uppercase text-slate-400 tracking-wider">
会话列表
</div>
<div id="sessionList" class="flex-1 overflow-y-scroll px-3 pb-4"></div>
</aside>
<!-- 主内容区 -->
<main class="flex-1 min-w-0 flex flex-col">
<!-- 固定顶部区域 -->
<div class="flex-shrink-0 bg-white">
<div class="border-b px-5 py-3">
<div id="indexStatus" class="text-xs text-slate-500"></div>
</div>
<!-- 会话元信息 -->
<div id="sessionMeta" class="border-b p-4 text-sm text-slate-500"></div>
</div>
<!-- 可滚动消息列表区域 -->
<div class="flex-1 min-w-0 overflow-y-auto p-6">
<div id="messageList" class="space-y-4"></div>
<!-- 加载更多按钮 -->
<button
id="loadMoreBtn"
class="mt-6 hidden rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
>
加载更多
</button>
</div>
</main>
</div>
<script>
// DOM 元素引用
const projectSelect = document.getElementById("projectSelect");
const sessionList = document.getElementById("sessionList");
const messageList = document.getElementById("messageList");
const sessionMeta = document.getElementById("sessionMeta");
const indexStatus = document.getElementById("indexStatus");
const loadMoreBtn = document.getElementById("loadMoreBtn");
// 应用状态
const state = {
projects: [],
currentProject: { source: "claude_code", project: "" },
currentProjectKey: "",
sessions: [],
currentSessionId: "",
sessionStartOffset: 0,
offset: 0,
limit: 200,
hasMore: false,
expandedSessions: new Set(), // 跟踪展开的主会话ID
roleFilters: { user: true, assistant: true, tool: true, other: true },
};
let suppressUrlSync = false;
function readUrlState() {
const params = new URLSearchParams(window.location.search || "");
const rolesParam = (params.get("roles") || "").trim();
const roles = rolesParam
? new Set(rolesParam.split(",").map((s) => s.trim()).filter(Boolean))
: null;
return {
source: params.get("src") || "",
project: params.get("project") || "",
sessionId: params.get("session") || "",
focus: params.get("focus") || "",
offset: params.get("offset") ? Number(params.get("offset")) : NaN,
roles,
};
}
function buildUrl(extra = {}) {
const params = new URLSearchParams();
const src = state.currentProject?.source || "claude_code";
const project = state.currentProject?.project || "";
if (src) params.set("src", src);
if (project) params.set("project", project);
if (state.currentSessionId) params.set("session", state.currentSessionId);
if (state.sessionStartOffset) params.set("offset", String(state.sessionStartOffset));
if (extra.focus) params.set("focus", String(extra.focus));
const rf = state.roleFilters || {};
const allOn = rf.user && rf.assistant && rf.tool && rf.other;
if (!allOn) {
const enabled = [];
if (rf.user) enabled.push("user");
if (rf.assistant) enabled.push("assistant");
if (rf.tool) enabled.push("tool");
if (rf.other) enabled.push("other");
params.set("roles", enabled.join(","));
}
return `${window.location.pathname}?${params.toString()}`;
}
function syncUrl(extra = {}) {
if (suppressUrlSync) return;
try {
window.history.replaceState(null, "", buildUrl(extra));
} catch {
// ignore
}
}
function pushUrl(extra = {}) {
if (suppressUrlSync) return;
try {
window.history.pushState(null, "", buildUrl(extra));
} catch {
// ignore
}
}
// 代码块复制:避免把大文本塞进 data-* 属性
let copySeq = 0;
const copyStore = new Map(); // id -> string
// 工具函数
function formatTimestamp(timestamp) {
if (!timestamp) return "";
try {
const date = new Date(timestamp);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
const seconds = String(date.getSeconds()).padStart(2, "0");
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
} catch {
return timestamp;
}
}
function escapeHtml(text) {
return String(text || "")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function escapeRegex(text) {
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function renderMarkdown(text) {
const source = String(text || "");
const renderer = new marked.Renderer();
renderer.image = (...args) => {
let href = "";
let alt = "";
if (args.length === 1 && args[0] && typeof args[0] === "object") {
href = String(args[0].href || "");
alt = String(args[0].text || "");
} else {
href = String(args[0] || "");
alt = String(args[2] || "");
}
const label = alt ? `![${alt}]` : "![image]";
const target = href ? ` <code>${escapeHtml(href)}</code>` : "";
return `<span class="inline-flex items-center gap-1 rounded bg-slate-100 px-2 py-0.5 text-xs text-slate-600">🖼️ ${escapeHtml(label)}${target}</span>`;
};
const raw = marked.parse(source, { renderer });
// DOMPurify may not be available (e.g. offline). Fallback: render as plain text.
if (typeof window.DOMPurify === "undefined") {
return escapeHtml(source).replace(/\n/g, "<br />");
}
return window.DOMPurify.sanitize(raw, { FORBID_TAGS: ["img"] });
}
function setIndexStatusText(text, isError = false) {
if (!indexStatus) return;
indexStatus.className = `mt-1 text-xs ${isError ? "text-red-600" : "text-slate-500"}`;
indexStatus.textContent = text || "";
}
function formatIndexStatus(s) {
const state = s?.state || "idle";
if (state === "running") {
const done = Number(s?.processed_files || 0);
const total = Number(s?.total_files || 0);
return total ? `索引构建中… ${done}/${total}` : "索引构建中…";
}
if (state === "error") {
return `索引失败:${s?.last_error || "unknown"}`;
}
if (state === "ready") {
return "";
}
return "";
}
async function fetchIndexStatus() {
const res = await fetch("/api/index/status");
if (!res.ok) return null;
const data = await res.json();
return data?.status || null;
}
async function waitForIndexReady({ timeoutMs = 300000 } = {}) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
const status = await fetchIndexStatus();
if (status) {
const text = formatIndexStatus(status);
if (text) setIndexStatusText(text, status.state === "error");
if (status.state === "ready") {
setIndexStatusText("");
return;
}
if (status.state === "error") {
throw new Error(status.last_error || "索引失败");
}
}
await new Promise((r) => setTimeout(r, 800));
}
throw new Error("等待索引完成超时");
}
async function api(path, { retryOnIndex = true } = {}) {
const res = await fetch(path);
if (res.status === 503 && retryOnIndex) {
// 后端在重建/刷新索引时会返回 503,前端轮询进度后自动重试一次
let payload = null;
try {
payload = await res.json();
} catch {
payload = null;
}
// FastAPI: {"detail": {...}}
const detail = payload && typeof payload === "object" && "detail" in payload ? payload.detail : payload;
const code = detail?.code || "indexing";
if (code === "indexing" || code === "index_error") {
setIndexStatusText(formatIndexStatus(detail?.status || { state: "running" }), code === "index_error");
await waitForIndexReady();
const out = await api(path, { retryOnIndex: false });
setIndexStatusText("");
return out;
}
}
if (!res.ok) {
throw new Error(`请求失败: ${res.status}`);
}
const data = await res.json();
// 防止“索引构建中…”文案残留
setIndexStatusText("");
return data;
}
async function copyToClipboard(text) {
const value = String(text || "");
if (!value) return false;
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(value);
return true;
}
} catch {
// ignore and fallback
}
// Fallback: execCommand
try {
const ta = document.createElement("textarea");
ta.value = value;
ta.style.position = "fixed";
ta.style.left = "-9999px";
ta.style.top = "0";
ta.setAttribute("readonly", "true");
document.body.appendChild(ta);
ta.select();
const ok = document.execCommand("copy");
document.body.removeChild(ta);
return Boolean(ok);
} catch {
return false;
}
}
function sourceLabel(source) {
return source === "codex" ? "[Codex]" : "[Claude Code]";
}
function makeProjectKey({ source, project }) {
return JSON.stringify({ source: source || "claude_code", project: project || "" });
}
function parseProjectKey(key) {
try {
const parsed = JSON.parse(key || "{}");
return {
source: parsed.source || "claude_code",
project: parsed.project || "",
};
} catch {
// Fallback for old format
return { source: "claude_code", project: key || "" };
}
}
// 渲染函数
function renderProjects() {
projectSelect.innerHTML = "";
if (!state.projects.length) {
const option = document.createElement("option");
option.value = "";
option.textContent = "未找到项目";
projectSelect.appendChild(option);
return;
}
for (const project of state.projects) {
const option = document.createElement("option");
const src = project.source || "claude_code";
option.value = makeProjectKey({ source: src, project: project.project });
option.textContent = `${sourceLabel(src)} ${project.project} (${project.session_count})`;
projectSelect.appendChild(option);
}
projectSelect.value = state.currentProjectKey;
}
/**
* 创建会话列表项
* 使用 data-* 属性而不是闭包,配合事件委托
* @param {Object} session - 会话对象
* @param {boolean} isActive - 是否为当前激活会话
* @param {boolean} isSubagent - 是否为子会话
* @param {boolean} hasSubagents - 是否有子会话
* @param {boolean} isExpanded - 子会话是否展开
*/
function createSessionListItem(session, isActive, isSubagent = false, hasSubagents = false, isExpanded = false) {
const wrapper = document.createElement("div");
// 基础样式
let wrapperClass = "rounded-lg border border-slate-200 bg-white mb-3 shadow-sm transition-colors";
// 子会话样式:缩进和不同的视觉效果
if (isSubagent) {
wrapperClass = "ml-6 rounded-lg border border-slate-200 bg-slate-50 mb-2 shadow-sm transition-colors";
}
wrapper.className = wrapperClass;
if (isActive) {
wrapper.classList.add("border-indigo-500", "shadow");
}
// 主会话区域(可点击打开会话)
const mainArea = document.createElement("div");
mainArea.className = "cursor-pointer p-3 hover:bg-slate-50 rounded-lg";
mainArea.dataset.action = "open-session";
mainArea.dataset.sessionId = session.session_id || "";
// 构建会话信息HTML
// 对于codex会话,显示更多信息以便区分
let sessionIdDisplay;
const fullSessionId = session.session_id || "";
if (fullSessionId.startsWith("rollout-")) {
// codex会话:显示时间戳部分 (rollout-2026-01-27T06-57-15)
const parts = fullSessionId.split("-");
if (parts.length >= 5) {
sessionIdDisplay = escapeHtml(parts.slice(0, 5).join("-"));
} else {
sessionIdDisplay = escapeHtml(fullSessionId.slice(0, 30));
}
} else {
// claude code会话:显示前8个字符
sessionIdDisplay = escapeHtml(fullSessionId.slice(0, 8));
}
const subagentIcon = isSubagent ? '<span class="text-slate-400 mr-1">↳</span>' : '';
// 只对主会话保留按钮槽位;子会话不需要
const toggleSlotHtml = isSubagent ? "" : `<div class="ml-2 w-6 h-6 flex items-center justify-center flex-shrink-0">${hasSubagents ? `<button type="button" class="w-6 h-6 hover:bg-slate-200 rounded transition-colors" data-action="toggle-subagents" data-session-id="${escapeHtml(session.session_id || "")}" aria-label="展开/折叠子会话"><span class="inline-block w-4 text-center text-slate-600 text-sm">${isExpanded ? '▼' : '▶'}</span></button>` : ""}</div>`;
mainArea.innerHTML = `
<div class="flex items-start">
<div class="flex-1 min-w-0">
<div class="text-sm font-semibold text-slate-700 flex items-center">
${subagentIcon}${sessionIdDisplay}
${isSubagent ? '<span class="ml-2 text-[10px] px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded">子会话</span>' : ''}
</div>
<div class="text-xs text-slate-500 mt-1" style="display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;">
${escapeHtml(session.summary || "无摘要")}
</div>
<div class="mt-2 text-[11px] text-slate-400 flex justify-between">
<span>${escapeHtml(session.updated_at || "")}</span>
<span>${session.message_count || 0} 条消息</span>
</div>
</div>
${toggleSlotHtml}
</div>
`;
wrapper.appendChild(mainArea);
return wrapper;
}
/**
* 构建会话树形结构
* @param {Array} sessions - 扁平的会话列表
* @returns {Array} 树形结构的会话列表
*/
function buildSessionTree(sessions) {
const tree = [];
const sessionMap = new Map();
// 第一遍:建立映射
for (const session of sessions) {
sessionMap.set(session.session_id, {
...session,
subagents: []
});
}
// 第二遍:构建树形结构
for (const session of sessions) {
const node = sessionMap.get(session.session_id);
if (session.parent_session_id) {
// 这是子会话,添加到父会话的 subagents 数组
const parent = sessionMap.get(session.parent_session_id);
if (parent) {
parent.subagents.push(node);
} else {
// 父会话不存在(可能被过滤掉了),作为顶层会话处理
tree.push(node);
}
} else {
// 这是主会话,添加到顶层
tree.push(node);
}
}
return tree;
}
function renderSessions() {
sessionList.innerHTML = "";
if (!state.sessions.length) {
sessionList.innerHTML =
'<div class="p-4 text-sm text-slate-400">未找到会话</div>';
return;
}
// 构建树形结构
const sessionTree = buildSessionTree(state.sessions);
// 使用 DocumentFragment 减少重排重绘
const fragment = document.createDocumentFragment();
for (const session of sessionTree) {
const isActive = session.session_id === state.currentSessionId;
const hasSubagents = session.subagents && session.subagents.length > 0;
const isExpanded = state.expandedSessions.has(session.session_id);
// 渲染主会话
fragment.appendChild(
createSessionListItem(session, isActive, false, hasSubagents, isExpanded)
);
// 如果有子会话且已展开,渲染子会话
if (hasSubagents && isExpanded) {
for (const subagent of session.subagents) {
const isSubActive = subagent.session_id === state.currentSessionId;
fragment.appendChild(
createSessionListItem(subagent, isSubActive, true, false, false)
);
}
}
}
sessionList.appendChild(fragment);
}
function renderSessionMeta() {
const session = state.sessions.find(
(s) => s.session_id === state.currentSessionId
);
if (!session) {
sessionMeta.innerHTML = "";
return;
}
const rf = state.roleFilters || { user: true, assistant: true, tool: true, other: true };
sessionMeta.innerHTML = `
<div class="flex flex-col gap-2">
<div class="flex items-center justify-between">
<div class="flex flex-wrap gap-3 text-xs text-slate-500">
<span class="font-semibold text-slate-700">${escapeHtml(
session.session_id
)}</span>
<span>${escapeHtml(sourceLabel(state.currentProject?.source))}</span>
<span>会话时间: ${formatTimestamp(session.started_at)} ~ ${formatTimestamp(session.updated_at)}</span>
<span>消息数: ${session.message_count || 0}</span>
<span>${escapeHtml(session.cwd || "")}</span>
<span>${escapeHtml(session.git_branch || "")}</span>
</div>
<div class="ml-4 flex items-center gap-2 flex-shrink-0">
<button
id="expandAllBtn"
class="px-3 py-1.5 text-xs font-medium text-slate-700 border border-slate-200 hover:bg-slate-50 rounded-lg transition-colors whitespace-nowrap"
title="展开当前视图里的所有折叠内容"
>
展开全部
</button>
<button
id="collapseAllBtn"
class="px-3 py-1.5 text-xs font-medium text-slate-700 border border-slate-200 hover:bg-slate-50 rounded-lg transition-colors whitespace-nowrap"
title="折叠当前视图里的所有折叠内容"
>
折叠全部
</button>
<button
id="refreshSessionBtn"
class="px-3 py-1.5 text-xs font-medium text-white bg-indigo-600 hover:bg-indigo-700 rounded-lg transition-colors whitespace-nowrap flex items-center gap-1.5"
title="刷新当前会话"
>
<span>🔄</span>
<span>刷新</span>
</button>
</div>
</div>
<div class="flex flex-wrap items-center gap-3 text-xs text-slate-600">
<span class="text-slate-400">显示</span>
<label class="inline-flex items-center gap-2 select-none">
<input type="checkbox" class="rounded" data-action="role-filter" data-role="user" ${rf.user ? "checked" : ""} />
<span>user</span>
</label>
<label class="inline-flex items-center gap-2 select-none">
<input type="checkbox" class="rounded" data-action="role-filter" data-role="assistant" ${rf.assistant ? "checked" : ""} />
<span>assistant</span>
</label>
<label class="inline-flex items-center gap-2 select-none">
<input type="checkbox" class="rounded" data-action="role-filter" data-role="tool" ${rf.tool ? "checked" : ""} />
<span>tool</span>
</label>
<label class="inline-flex items-center gap-2 select-none">
<input type="checkbox" class="rounded" data-action="role-filter" data-role="other" ${rf.other ? "checked" : ""} />
<span>other</span>
</label>
</div>
</div>
`;
}
function parseContent(content) {
if (!content) return [];
try {
const parsed = JSON.parse(content);
return Array.isArray(parsed) ? parsed : [{ type: "text", text: String(content) }];
} catch {
return [{ type: "text", text: String(content) }];
}
}
/**
* 解析旧格式的工具调用(Markdown 格式)
* 旧格式:**Tool:** `name`\n\n```json\n{...}\n```
*/
function parseLegacyToolCall(markdown) {
const text = String(markdown || "");
const nameMatch = text.match(/\*\*Tool:\*\*\s*`([^`]+)`/);
const name = (nameMatch && nameMatch[1]) ? nameMatch[1] : "工具调用";
// 提取 JSON 代码块(支持 \n 和 \r\n)
const jsonFence = text.match(/```json\s*[\r\n]+([\s\S]*?)[\r\n]+```/);
let input = {};
if (jsonFence && jsonFence[1]) {
const raw = jsonFence[1].trim();
if (raw) {
try {
input = JSON.parse(raw);
} catch {
input = { _raw: raw };
}
}
} else {
input = { _raw: text };
}
return { type: "tool_use", name, input };
}
/**
* 解析旧格式的工具输出(Markdown 格式)
* 旧格式:```json\n{...}\n``` 或 ```\n...\n```
*/
function parseLegacyToolOutput(markdown) {
const text = String(markdown || "");
// 优先尝试 JSON 代码块(支持 \n 和 \r\n)
const jsonFence = text.match(/```json\s*[\r\n]+([\s\S]*?)[\r\n]+```/);
if (jsonFence && jsonFence[1]) {
const raw = jsonFence[1].trim();
if (!raw) return { type: "tool_result", content: "" };
try {
return { type: "tool_result", content: JSON.parse(raw) };
} catch {
return { type: "tool_result", content: raw };
}
}
// 其次尝试普通代码块(支持 \n 和 \r\n)
const anyFence = text.match(/```\s*[\r\n]+([\s\S]*?)[\r\n]+```/);
if (anyFence && anyFence[1]) {
return { type: "tool_result", content: anyFence[1].trim() };
}
return { type: "tool_result", content: text };
}
/**
* 获取消息的内容块(统一新旧格式)
*
* 优先使用新的 blocks 字段,如果不存在则解析 content 字段。
* 同时处理旧的事件级类型(reasoning/tool_call/tool_output)。
*/
function getItemBlocks(item) {
// 优先使用新的 blocks 字段
if (item && Array.isArray(item.blocks)) {
return item.blocks;
}
// 解析 content 字段
const blocks = parseContent(item ? item.content : "");
// 向后兼容:将旧的事件级类型转换为统一的 blocks
if (item && item.type === "reasoning") {
// reasoning 类型:提取文本内容并转换为 thinking block
const thinking = blocks
.map((b) => (b && typeof b === "object" && b.type === "text" ? (b.text || "") : ""))
.filter(Boolean)
.join("\n")
.trim();
return thinking ? [{ type: "thinking", thinking }] : blocks;
}
if (item && item.type === "tool_call") {
// tool_call 类型:解析 Markdown 格式的工具调用
return [parseLegacyToolCall(item.content)];
}
if (item && item.type === "tool_output") {
// tool_output 类型:解析 Markdown 格式的工具输出
return [parseLegacyToolOutput(item.content)];
}
return blocks;
}
function formatJsonForDisplay(obj) {
return JSON.stringify(obj, null, 2);
}
function unescapeJsonString(str) {
return str.replace(/\\n/g, '\n').replace(/\\t/g, '\t');
}
function renderBox({ collapsible = false, bgClass, borderClass, titleClass = "", title = "", summary = "", bodyHtml }) {
const containerClass = `mt-2 rounded-lg ${bgClass} border ${borderClass} p-3`;
if (collapsible) {
return `
<details class="${containerClass}">
<summary class="cursor-pointer text-xs font-semibold ${titleClass} select-none">
${summary}
</summary>
${bodyHtml}
</details>
`;
}
const titleHtml = title
? `<div class="text-xs font-semibold ${titleClass}">${title}</div>`
: "";
return `
<div class="${containerClass}">
${titleHtml}
${bodyHtml}
</div>
`;
}
function renderCollapsible({ bgClass, borderClass, summaryClass, summary, bodyHtml }) {
return renderBox({
collapsible: true,
bgClass,
borderClass,
titleClass: summaryClass,
summary,
bodyHtml,
});
}
function renderPanel({ bgClass, borderClass, titleClass, title, bodyHtml }) {
return renderBox({ bgClass, borderClass, titleClass, title, bodyHtml });
}
function renderCodeBlock(content, extraClass = "") {
const copyId = `cb_${++copySeq}`;
copyStore.set(copyId, String(content || ""));
const classes = `mt-2 text-xs text-slate-600 overflow-x-auto whitespace-pre-wrap break-words ${extraClass}`.trim();
return `
<div class="relative group">
<button
type="button"
class="absolute top-2 right-2 hidden group-hover:inline-flex items-center rounded-md border border-slate-200 bg-white px-2 py-1 text-[11px] font-medium text-slate-700 hover:bg-slate-50"
data-action="copy-code"
data-copy-id="${escapeHtml(copyId)}"
title="复制代码块内容"
>
复制
</button>
<pre class="${classes}"><code>${escapeHtml(content)}</code></pre>
</div>
`;
}
function getRoleClasses(role, type) {
if (role === "user" || type === "user") {
return {
badgeClass: "bg-indigo-600 text-white",
bubbleClass: "bg-indigo-50 border-indigo-200",
};
}
if (role === "assistant" || type === "assistant") {
return {
badgeClass: "bg-emerald-600 text-white",
bubbleClass: "bg-emerald-50 border-emerald-200",
};
}
if (type === "tool_call") {
return {
badgeClass: "bg-purple-600 text-white",
bubbleClass: "bg-purple-50 border-purple-200",
};
}
if (type === "tool_output" || role === "tool") {
return {
badgeClass: "bg-amber-600 text-white",
bubbleClass: "bg-amber-50 border-amber-200",
};
}
if (type === "reasoning") {
return {
badgeClass: "bg-slate-600 text-white",
bubbleClass: "bg-slate-50 border-slate-200",
};
}
return {
badgeClass: "bg-slate-200 text-slate-600",
bubbleClass: "bg-white border-slate-200",
};
}
function renderTextBlock(text) {
const content = text || "";
const isSystemMessage = content.includes("<local-command-") || content.includes("<command-") || content.includes("<system-");
if (isSystemMessage) {
return renderCollapsible({
bgClass: "bg-slate-100",
borderClass: "border-slate-300",
summaryClass: "text-slate-600",
summary: `📋 系统消息 (${content.length} 字符)`,
bodyHtml: `<div class="mt-2 text-xs text-slate-600 whitespace-pre-wrap break-words">${escapeHtml(content)}</div>`,
});
}
if (content.length > 1500) {
return renderCollapsible({
bgClass: "bg-slate-50",
borderClass: "border-slate-200",
summaryClass: "text-slate-600",
summary: `📄 长文本 (${content.length} 字符,点击展开)`,
bodyHtml: `<div class="mt-2 text-sm text-slate-800 markdown-content">${renderMarkdown(content)}</div>`,
});
}
return `<div class="text-sm text-slate-800 markdown-content">${renderMarkdown(content)}</div>`;
}
function formatToolResultContent(block) {
// 使用 in 操作符检查 content 字段是否存在,而不是用 || 判断
// 这样可以正确处理空字符串、0、false 等 falsy 值
const content = "content" in block ? block.content : block;
if (typeof content === "string") {
try {
return formatJsonForDisplay(JSON.parse(content));
} catch {
return unescapeJsonString(content);
}
}
return formatJsonForDisplay(content);
}
function renderToolResult(block) {
const displayContent = formatToolResultContent(block);
const isLong = displayContent.length > 2000;
const bodyHtml = renderCodeBlock(displayContent, isLong ? "max-h-96" : "max-h-60");
// 统一使用 <details>/<summary> 折叠组件
// 短内容默认展开(open 属性),长内容默认折叠
const openAttr = isLong ? "" : " open";
return `
<details class="mt-2 rounded-lg bg-green-50 border border-green-200 p-3"${openAttr}>
<summary class="cursor-pointer text-xs font-semibold text-green-700 select-none">
✓ 工具结果 (${displayContent.length} 字符,点击${isLong ? "展开" : "折叠"})
</summary>
${bodyHtml}
</details>
`;
}
const contentRenderers = {
thinking: (block) => renderCollapsible({
bgClass: "bg-amber-50",
borderClass: "border-amber-200",
summaryClass: "text-amber-700",
summary: "💭 思考过程",
bodyHtml: `<div class="mt-2 text-sm text-slate-700 markdown-content">${renderMarkdown(block.thinking || "")}</div>`,
}),
image: (block) => {
const source = block.source || {};
const data = source.data || "";
if (!data) {
return `<div class="text-sm text-slate-500">图片数据缺失</div>`;
}
const mediaType = source.media_type || "image/png";
return renderPanel({
bgClass: "bg-white",
borderClass: "border-slate-200",
titleClass: "text-slate-600 mb-2",
title: "🖼️ 图片",
bodyHtml: `<img src="data:${mediaType};base64,${data}" class="max-w-full h-auto rounded" alt="消息图片" />`,
});
},
text: (block) => renderTextBlock(block.text),
tool_use: (block) => {
// 工具调用默认展开(因为通常内容不长)
const inputJson = formatJsonForDisplay(block.input || {});
const bodyHtml = renderCodeBlock(inputJson);
return `
<details class="mt-2 rounded-lg bg-blue-50 border border-blue-200 p-3" open>
<summary class="cursor-pointer text-xs font-semibold text-blue-700 select-none">
🔧 ${escapeHtml(block.name || "工具调用")}(点击折叠)
</summary>
${bodyHtml}
</details>
`;
},
tool_result: renderToolResult,
};
function renderContentBlock(block) {
if (!block || typeof block !== "object") {
return `<div class="text-sm text-slate-800">${escapeHtml(String(block))}</div>`;
}
const type = block.type || "unknown";
const renderer = Object.hasOwn(contentRenderers, type) ? contentRenderers[type] : null;
if (renderer) {
return renderer(block);
}
return `<pre class="text-xs text-slate-500 overflow-x-auto whitespace-pre-wrap break-words"><code>${escapeHtml(formatJsonForDisplay(block))}</code></pre>`;
}
function renderMessages(items) {
if (!items.length) {
messageList.innerHTML =
'<div class="text-sm text-slate-400">暂无消息</div>';
return;
}
const fragment = document.createDocumentFragment();
for (const item of items) {
const role = item.role || item.type || "event";
const roleCategory = roleCategoryForItem(item);
// 跳过不显示的事件类型
const skipTypes = ["summary", "file-history-snapshot", "progress"];
if (item.type === "progress" || (skipTypes.includes(item.type) && !item.content)) {
continue;
}
const { badgeClass, bubbleClass } = getRoleClasses(role, item.type);
const wrapper = document.createElement("div");
wrapper.className = `rounded-xl border ${bubbleClass} p-4 shadow-sm`;
if (item.timestamp) {
wrapper.dataset.timestamp = item.timestamp;
}
wrapper.dataset.roleCategory = roleCategory;
// 添加ID以支持锚点跳转:优先使用稳定 event_id
if (item.id) {
wrapper.id = `msg-${item.id}`;
} else if (item.timestamp) {
wrapper.id = `msg-${item.timestamp}`;
}
// 使用统一的 getItemBlocks() 获取内容块(支持新旧格式)
const contentBlocks = getItemBlocks(item);
const contentHtml = contentBlocks.map((block) => renderContentBlock(block)).join("");
// 确定显示标签
let displayLabel = role;
const linkId = item.id || "";
// 统一的卡片结构:所有折叠交互都由内容块的 <details>/<summary> 承担
wrapper.innerHTML = `
<div class="flex items-center justify-between">
<span class="rounded-full px-2 py-1 text-xs font-semibold ${badgeClass}">
${escapeHtml(displayLabel)}
</span>
<div class="flex items-center gap-2 text-xs text-slate-400">
${
linkId
? `<button type="button" class="text-[11px] font-medium text-slate-600 hover:text-slate-800" data-action="copy-permalink" data-event-id="${escapeHtml(linkId)}" title="复制此消息链接">🔗</button>`
: ""
}
<span>${formatTimestamp(item.timestamp)}</span>
</div>
</div>
<div class="mt-3 space-y-2">
${contentHtml}
</div>
`;
fragment.appendChild(wrapper);
}
messageList.appendChild(fragment);
applyMessageRoleFilter();
}
function toggleAllDetails(open) {
const details = messageList.querySelectorAll("details");
for (const el of details) {
el.open = Boolean(open);
}
}
function roleCategoryForItem(item) {
const role = String(item?.role || "").toLowerCase();
const type = String(item?.type || "").toLowerCase();
if (role === "user" || type === "user") return "user";
if (role === "assistant" || type === "assistant") return "assistant";