-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathClaudePowerestManager&Enhancer.user.js
More file actions
4465 lines (4009 loc) · 247 KB
/
ClaudePowerestManager&Enhancer.user.js
File metadata and controls
4465 lines (4009 loc) · 247 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
// ==UserScript==
// @name Claude Powerest Manager Enhancer | 导航 导出 管理 跳转 分支 对话 管理器 导出器 export navigate jump branch helper
// @name:zh-CN Claude神级拓展增强脚本 | (管理 增强 导出 导航 跳转 分支 分叉 管理器 增强器 导出器 导航器 助手) | (manage enhance export navigate jump branch fork manager enhancer exporter navigator helper)
// @namespace http://tampermonkey.net/
// @version 1.2.5
// @description 一站式搜索、筛选、批量管理所有对话。强大的JSON导出(原始/自定义/含附件)。为聊天框注入新功能,如从任意消息分支、跨分支全局导航、强制PDF深度解析、浮动线性导航面板等。关键词: 管理 增强 导出 导航 跳转 分支 分叉 管理器 增强器 导出器 导航器 助手 manage enhance export navigate jump branch fork manager enhancer exporter navigator helper
// @description:zh-CN [管理器] 右下角打开管理器面板开启一站式搜索、筛选、批量管理所有对话。强大的JSON导出(原始/自定义/含附件)。[增强器]为聊天框注入新功能,如从任意消息分支、跨分支全局导航、强制PDF深度解析、浮动线性导航面板等。
// @description:en [Manager] Opens a management panel in the bottom-right corner for one-stop searching, filtering, and batch management of all conversations. Powerful JSON export (raw/custom/with attachments). [Enhancer] Injects new features into the chat interface, such as branching from any message, cross-branch navigation, forced deep PDF parsing, floating linear navigation panel, and more.
// @author f14xuanlv
// @license MIT
// @homepageURL https://github.com/f14XuanLv/Claude-Powerest-Manager_Enhancer
// @supportURL https://github.com/f14XuanLv/Claude-Powerest-Manager_Enhancer/issues
// @match https://claude.ai/*
// @include /^https:\/\/.*\.fuclaude\.[a-z]{3}\/.*$/
// @icon https://www.google.com/s2/favicons?sz=64&domain=claude.ai
// @grant GM_addStyle
// @grant GM_setValue
// @grant GM_getValue
// @run-at document-idle
// ==/UserScript==
(function(window) {
'use strict';
const LOG_PREFIX = "[ClaudePowerestManager&Enhancer v1.2.5]:"
console.log(LOG_PREFIX, "脚本已加载。");
// 全局HTML转义函数 - 统一的转义实现
function escapeHTML(str) {
if (!str) return '';
return str.replace(/[&<>"']/g, function(match) {
return {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}[match];
});
}
// 全局字符串分割工具函数 - 避免原型污染
function rsplit(str, sep, maxsplit) {
const split = str.split(sep);
return maxsplit ? [split.slice(0, -maxsplit).join(sep)].concat(split.slice(-maxsplit)) : split;
}
// =========================================================================
// 0. 国际化配置和翻译函数
// =========================================================================
const I18N_CONFIG = {
currentLang: GM_getValue('language', 'zh'),
translations: {
zh: {
// Manager 相关
'manager.title': 'Manager',
'manager.refresh': '刷新列表',
'manager.selectAll': '全选',
'manager.selectNone': '全不选',
'manager.selectInvert': '反选',
'manager.batchStar': '批量收藏',
'manager.batchUnstar': '批量取消收藏',
'manager.batchRename': '批量自动重命名',
'manager.batchDelete': '批量删除',
'manager.loading': '正在加载会话列表...',
'manager.noResults': '没有符合条件的会话。',
'manager.ready': '准备就绪。',
'manager.refreshButtonTip': '点击刷新按钮 ( <svg class="cpm-svg-icon"><use href="#cpm-icon-refresh"></use></svg> ) 加载会话列表。',
// Settings 相关
'settings.title': '管理器设置',
'settings.theme': '外观设置',
'settings.themeMode': '脚本主题:',
'settings.themeAuto': '跟随网站',
'settings.themeLight': '锁定白天',
'settings.themeDark': '锁定黑夜',
'settings.batchOps': '批量操作设置',
'settings.exportDefaults': '自定义导出默认设置',
'settings.save': '保存设置',
'settings.saved': '设置已保存!',
'settings.backToMain': '返回主面板',
'settings.language': '语言设置',
'settings.interfaceLanguage': '界面语言:',
// Navigator 相关
'navigator.title': '对话节点延续&导航器',
'navigator.branchMode': '延续模式',
'navigator.navigateMode': '导航模式',
'navigator.branchSelected': '分支点已选定',
'navigator.loading': '正在加载对话历史...',
'navigator.branchFromRoot': '从根节点开始 (创建一个新的主分支)',
// Linear Navigator 相关
'linear.title': '线性导航',
'linear.refresh': '刷新对话列表',
'linear.close': '关闭线性导航',
'linear.top': '回到顶部',
'linear.bottom': '回到底部',
'linear.prev': '上一条',
'linear.next': '下一条',
'linear.empty': '暂无线性对话',
// Attachment 相关
'attachment.title': 'PDF深度解析暂存区',
'attachment.forceMode': 'Force PDF Deep Analysis',
'attachment.close': '关闭并清空所有暂存文件',
// Export 相关
'export.original': '原始JSON导出',
'export.custom': '自定义JSON导出',
'export.batchOriginal': '批量原始JSON导出',
'export.batchCustom': '批量自定义JSON导出',
'export.selectFolder': '正在请求文件夹权限...',
'export.complete': '导出完成!',
// Tree view 相关
'tree.preview': '对话树预览',
'tree.loading': '正在加载对话树...',
'tree.empty': '这是一个空对话',
'tree.emptyForBranching': ',无法选择节点',
// Common 相关
'common.confirm': '确定',
'common.cancel': '取消',
'common.close': '关闭',
'common.save': '保存',
'common.loading': '加载中...',
'common.error': '错误',
'common.success': '成功',
'common.failed': '失败',
// Sorting & Filtering
'sort.updatedDesc': '时间降序',
'sort.updatedAsc': '时间升序',
'sort.nameAsc': '名称 A-Z',
'sort.nameDesc': '名称 Z-A',
'filter.all': '显示全部',
'filter.starred': '仅显示收藏',
'filter.unstarred': '隐藏收藏',
'filter.asciiOnly': '仅显示纯ASCII标题',
'filter.nonAscii': '不显示纯ASCII标题',
// Button tooltips
'tooltip.managerButton': 'Tips: Ctrl + M 可以隐藏此按钮',
'tooltip.navigatorButton': '从对话历史的任意节点延续&导航至任意节点',
'tooltip.linearNavButton': '线性导航',
'tooltip.pdfButton': '打开PDF上传设置',
'tooltip.pdfHelp': '此功能为普通账户设计,可强制使用高级解析路径。Pro/Team账户原生支持,此开关对其无效。',
'tooltip.settingsButton': '设置',
'tooltip.githubLink': '查看 GitHub 仓库',
'tooltip.studioLink': '了解下一个项目: claude-dialog-tree-studio',
'pdf.forceModeText': 'Force PDF Deep Analysis',
// Toolbar labels
'toolbar.sort': '排序:',
'toolbar.filter': '筛选:',
'toolbar.searchPlaceholder': '搜索标题...',
// Batch operations detailed settings
'batchOps.starUnstar': '批量收藏/取消收藏',
'batchOps.refreshAfterStar': '操作后从服务器刷新列表 (否则仅更新当前视图)',
'batchOps.batchDelete': '批量删除',
'batchOps.refreshAfterDelete': '操作后从服务器刷新列表 (否则仅更新当前视图)',
'batchOps.autoRename': '批量自动重命名',
'batchOps.titleLanguage': '标题语言:',
'batchOps.titleLanguagePlaceholder': '例如:中文, English, 日本語',
'batchOps.maxRounds': '使用对话轮数 (最多):',
'batchOps.refreshAfterRename': '操作后从服务器刷新列表 (否则仅更新当前视图)',
// Export settings
'exportSettings.customOptions': '自定义导出选项',
'exportSettings.batchCustomOptions': '批量自定义导出选项',
'exportSettings.exportNow': '立即导出',
'exportSettings.batchExportNow': '开始批量导出',
'exportSettings.basicInfo': '基础信息',
'exportSettings.messageStructure': '消息结构',
'exportSettings.timestampInfo': '时间戳信息',
'exportSettings.coreContent': '核心内容',
'exportSettings.advancedContent': '高级内容',
'exportSettings.keepMetadata': '保留会话元数据',
'exportSettings.title': '标题 (name)',
'exportSettings.summary': '摘要 (summary)',
'exportSettings.sessionTimestamp': '会话创建/更新时间',
'exportSettings.sessionSettings': '会话设置 (settings)',
'exportSettings.sender': '发送者 (sender)',
'exportSettings.messageUuids': '消息/父级UUID (建议保留)',
'exportSettings.otherMeta': '其他元数据 (index, stop_reason等)',
'exportSettings.messageTimestamp': '消息节点时间戳 (created_at/updated_at)',
'exportSettings.contentTimestamp': '内容块流式时间戳 (start/stop)',
'exportSettings.attachmentTimestamp': '附件创建时间戳',
'exportSettings.textContent': '文本内容 (text块)',
'exportSettings.attachmentInfo': '附件信息:',
'exportSettings.attachmentFull': '完整信息 (含提取文本)',
'exportSettings.attachmentMetaOnly': '仅元数据 (文件名,大小等)',
'exportSettings.attachmentNone': '不保留附件',
'exportSettings.thinkingProcess': "'思考'过程 (thinking块)",
'exportSettings.toolRecords': '保留工具使用记录',
'exportSettings.webSearch': '网页搜索 (web_search)',
'exportSettings.codeAnalysis': '代码分析 (repl)',
'exportSettings.artifactCreation': '工件创建 (artifacts)',
'exportSettings.otherTools': '其他未知工具',
'exportSettings.successfulOnly': '仅保留成功的工具调用',
// Export status messages
'exportStatus.customComplete': '自定义导出完成!',
'exportStatus.customFailed': '自定义导出失败',
'exportStatus.batchPreparing': '准备批量自定义导出',
'exportStatus.batchComplete': '批量自定义导出完成',
'exportStatus.sessions': '个会话',
// Action button tooltips
'action.manualRename': '手动重命名',
'action.previewTree': '预览对话树',
'action.originalExport': '原始JSON导出',
'action.customExport': '自定义JSON导出',
// Status messages
'status.savingTitle': '正在保存新标题...',
'status.saveSuccess': '保存成功!',
'status.saveFailed': '保存失败',
'status.loadedSessions': '已加载',
'status.loadSessionsFailed': '加载会话失败',
'status.loadFailed': '加载失败',
// Error messages
'error.cannotLoadTree': '无法加载对话树',
// Tree view related
'treeView.prefix': '对话树: ',
'treeView.untitled': '无标题',
'treeView.loading': '加载中...',
'treeView.loadFailed': '无法加载对话树',
// Additional status and error messages
'error.invalidTitle': '生成了无效标题。',
'error.loadSessionsFailed': '加载会话失败',
'error.selectSessions': '请选择要执行"{0}"的会话。',
'error.selectExportSessions': '请选择要导出的会话。',
'error.browserNotSupported': '您的浏览器不支持 File System Access API。',
'status.refreshingFromServer': ' 正在从服务器刷新列表...',
'status.preparingExport': '准备导出...',
'status.exporting': '正在导出...',
'status.ready': '准备就绪。',
'navigator.loadingHistory': '正在加载对话历史...',
'navigator.notInChat': '不在具体聊天内,无法操作节点。',
'attachment.title': 'PDF深度解析暂存区',
'attachment.removeFile': '移除文件',
'attachment.clickPreview': '点击预览',
'attachment.openInNewTab': '点击在新标签页打开',
'navigator.clickToNavigate': '点击导航到此节点',
'navigator.clickToContinue': '点击从此节点继续对话',
'navigator.nextMessageFrom': '下条消息将从指定节点开始。',
'batchOps.confirmDelete': '确定永久删除 {0} 个会话吗?',
'status.batchProcessing': '正在批量{0} {1} 个会话...',
'status.batchItemProcessing': '正在{0} {1}/{2}...',
'status.batchItemFailed': '第{0}个失败',
'status.batchOperationComplete': '操作完成。成功{0} {1}/{2} 个会话。',
'status.batchOperationFailed': '批量{0}失败',
'status.batchExportPreparing': '准备批量导出 {0} 个会话...',
'status.batchExportFailed': '批量导出失败',
'status.exportFailed': '导出失败',
'status.checkingFile': '检查文件 {0} 出错',
'status.writingFile': '正在写入 {0}...',
'status.convertingData': '正在根据设置转换数据...',
// Export related messages
'export.foundAttachments': '发现 {0} 个附件,开始下载...',
'export.cannotGetOrgInfo': '无法获取组织信息以下载附件。',
'export.skipExistingFile': '({0}/{1}) 跳过 (文件已存在): {2}',
'export.downloading': '({0}/{1}) 正在下载: {2}',
'export.noDownloadUrl': '找不到附件的下载链接。',
'export.processAttachmentFailed': '处理附件 {0} 失败',
'export.requestingFolder': '正在请求文件夹权限...',
'export.userCancelled': '用户取消了文件夹选择。',
'export.orgInfoRequired': '缺少导出所需组织信息。',
'export.creatingDirectory': '正在创建目录...',
'export.originalComplete': '原始导出完成!',
'export.originalFailed': '原始导出失败',
'export.customFailed': '自定义导出失败',
'export.batchComplete': '批量导出完成: {0}/{1} 个会话成功导出。',
'export.exportFailed': '导出失败 ({0}/{1}): {2}',
'export.exportingProgress': '({0}/{1}) 正在导出: {2}',
'export.sessionFailed': '导出会话 {0} 失败',
// API error messages
'api.orgRequestFailed': '组织API请求失败: {0}',
'api.orgInfoNotFound': '在API响应中未找到组织信息。',
'api.getSessionsFailed': '获取会话列表失败: {0}',
'api.getHistoryFailed': '获取历史记录失败: {0}',
'api.deleteRequestFailed': '删除API请求失败: {0}',
'api.titleGenerationFailed': '标题生成API请求失败。',
'api.updateSessionFailed': '更新会话失败: {0}',
'api.fileDownloadFailed': '文件下载失败: {0} at {1}',
// Tree view and content messages
'tree.attachmentOrToolOnly': '[仅包含附件或工具使用]',
'tree.attachments': '附件',
'tree.dirtyData': '脏数据',
'error.checkingFile': '检查文件 {0} 时发生意外错误',
'error.noValidTextContent': '在指定轮次内未找到有效文本内容。',
'error.insufficientRounds': '对话轮次不足(可能为空对话),跳过重命名。',
'error.cannotGetConvoData': '无法获取对话数据',
// Operation names
'operation.rename': '重命名',
'operation.delete': '删除',
'operation.star': '收藏',
'operation.unstar': '取消收藏'
},
en: {
// Manager related
'manager.title': 'Manager',
'manager.refresh': 'Refresh List',
'manager.selectAll': 'Select All',
'manager.selectNone': 'Select None',
'manager.selectInvert': 'Invert Selection',
'manager.batchStar': 'Batch Star',
'manager.batchUnstar': 'Batch Unstar',
'manager.batchRename': 'Batch Auto Rename',
'manager.batchDelete': 'Batch Delete',
'manager.loading': 'Loading conversations...',
'manager.noResults': 'No conversations match the criteria.',
'manager.ready': 'Ready.',
'manager.refreshButtonTip': 'Click refresh button ( <svg class="cpm-svg-icon"><use href="#cpm-icon-refresh"></use></svg> ) to load conversation list.',
// Settings related
'settings.title': 'Manager Settings',
'settings.theme': 'Appearance Settings',
'settings.themeMode': 'Script Theme:',
'settings.themeAuto': 'Follow Website',
'settings.themeLight': 'Lock Light',
'settings.themeDark': 'Lock Dark',
'settings.batchOps': 'Batch Operations Settings',
'settings.exportDefaults': 'Custom Export Default Settings',
'settings.save': 'Save Settings',
'settings.saved': 'Settings saved!',
'settings.backToMain': 'Back to Main Panel',
'settings.language': 'Language Settings',
'settings.interfaceLanguage': 'Interface Language:',
// Navigator related
'navigator.title': 'Dialog Node Continuation & Navigator',
'navigator.branchMode': 'Branch Mode',
'navigator.navigateMode': 'Navigate Mode',
'navigator.branchSelected': 'Branch point selected',
'navigator.loading': 'Loading conversation history...',
'navigator.branchFromRoot': 'Start from root node (create a new main branch)',
// Linear Navigator related
'linear.title': 'Linear Navigation',
'linear.refresh': 'Refresh Dialog List',
'linear.close': 'Close Linear Navigation',
'linear.top': 'Go to Top',
'linear.bottom': 'Go to Bottom',
'linear.prev': 'Previous',
'linear.next': 'Next',
'linear.empty': 'No linear dialogs',
// Attachment related
'attachment.title': 'PDF Deep Analysis Staging Area',
'attachment.forceMode': 'Force PDF Deep Analysis',
'attachment.close': 'Close and clear all staged files',
// Export related
'export.original': 'Original JSON Export',
'export.custom': 'Custom JSON Export',
'export.batchOriginal': 'Batch Original JSON Export',
'export.batchCustom': 'Batch Custom JSON Export',
'export.selectFolder': 'Requesting folder permission...',
'export.complete': 'Export completed!',
// Tree view related
'tree.preview': 'Dialog Tree Preview',
'tree.loading': 'Loading dialog tree...',
'tree.empty': 'This is an empty conversation',
'tree.emptyForBranching': ', cannot select nodes',
// Common related
'common.confirm': 'Confirm',
'common.cancel': 'Cancel',
'common.close': 'Close',
'common.save': 'Save',
'common.loading': 'Loading...',
'common.error': 'Error',
'common.success': 'Success',
'common.failed': 'Failed',
// Sorting & Filtering
'sort.updatedDesc': 'Time Desc',
'sort.updatedAsc': 'Time Asc',
'sort.nameAsc': 'Name A-Z',
'sort.nameDesc': 'Name Z-A',
'filter.all': 'Show All',
'filter.starred': 'Show Starred Only',
'filter.unstarred': 'Hide Starred',
'filter.asciiOnly': 'ASCII Titles Only',
'filter.nonAscii': 'Non-ASCII Titles Only',
// Button tooltips
'tooltip.managerButton': 'Tips: Ctrl + M to hide this button',
'tooltip.navigatorButton': 'Branch from any message node & navigate to any node',
'tooltip.linearNavButton': 'Linear Navigation',
'tooltip.pdfButton': 'Open PDF upload settings',
'tooltip.pdfHelp': 'This feature is designed for regular accounts to force advanced parsing. Pro/Team accounts natively support this, so this toggle has no effect.',
'tooltip.settingsButton': 'Settings',
'tooltip.githubLink': 'View GitHub Repository',
'tooltip.studioLink': 'Learn about next project: claude-dialog-tree-studio',
'pdf.forceModeText': 'Force PDF Deep Analysis',
// Toolbar labels
'toolbar.sort': 'Sort:',
'toolbar.filter': 'Filter:',
'toolbar.searchPlaceholder': 'Search titles...',
// Batch operations detailed settings
'batchOps.starUnstar': 'Batch Star/Unstar',
'batchOps.refreshAfterStar': 'Refresh list from server after operation (otherwise only update current view)',
'batchOps.batchDelete': 'Batch Delete',
'batchOps.refreshAfterDelete': 'Refresh list from server after operation (otherwise only update current view)',
'batchOps.autoRename': 'Batch Auto Rename',
'batchOps.titleLanguage': 'Title Language:',
'batchOps.titleLanguagePlaceholder': 'e.g.: 中文, English, 日本語',
'batchOps.maxRounds': 'Max Conversation Rounds:',
'batchOps.refreshAfterRename': 'Refresh list from server after operation (otherwise only update current view)',
// Export settings
'exportSettings.customOptions': 'Custom Export Options',
'exportSettings.batchCustomOptions': 'Batch Custom Export Options',
'exportSettings.exportNow': 'Export Now',
'exportSettings.batchExportNow': 'Start Batch Export',
'exportSettings.basicInfo': 'Basic Information',
'exportSettings.messageStructure': 'Message Structure',
'exportSettings.timestampInfo': 'Timestamp Information',
'exportSettings.coreContent': 'Core Content',
'exportSettings.advancedContent': 'Advanced Content',
'exportSettings.keepMetadata': 'Keep conversation metadata',
'exportSettings.title': 'Title (name)',
'exportSettings.summary': 'Summary (summary)',
'exportSettings.sessionTimestamp': 'Session creation/update time',
'exportSettings.sessionSettings': 'Session settings (settings)',
'exportSettings.sender': 'Sender (sender)',
'exportSettings.messageUuids': 'Message/Parent UUIDs (recommended to keep)',
'exportSettings.otherMeta': 'Other metadata (index, stop_reason, etc.)',
'exportSettings.messageTimestamp': 'Message node timestamps (created_at/updated_at)',
'exportSettings.contentTimestamp': 'Content block streaming timestamps (start/stop)',
'exportSettings.attachmentTimestamp': 'Attachment creation timestamps',
'exportSettings.textContent': 'Text content (text blocks)',
'exportSettings.attachmentInfo': 'Attachment Information:',
'exportSettings.attachmentFull': 'Full information (including extracted text)',
'exportSettings.attachmentMetaOnly': 'Metadata only (filename, size, etc.)',
'exportSettings.attachmentNone': 'No attachments',
'exportSettings.thinkingProcess': "'Thinking' process (thinking blocks)",
'exportSettings.toolRecords': 'Keep tool usage records',
'exportSettings.webSearch': 'Web search (web_search)',
'exportSettings.codeAnalysis': 'Code analysis (repl)',
'exportSettings.artifactCreation': 'Artifact creation (artifacts)',
'exportSettings.otherTools': 'Other unknown tools',
'exportSettings.successfulOnly': 'Keep only successful tool calls',
// Export status messages
'exportStatus.customComplete': 'Custom export completed!',
'exportStatus.customFailed': 'Custom export failed',
'exportStatus.batchPreparing': 'Preparing batch custom export',
'exportStatus.batchComplete': 'Batch custom export completed',
'exportStatus.sessions': 'sessions',
// Action button tooltips
'action.manualRename': 'Manual Rename',
'action.previewTree': 'Preview Dialog Tree',
'action.originalExport': 'Original JSON Export',
'action.customExport': 'Custom JSON Export',
// Status messages
'status.savingTitle': 'Saving new title...',
'status.saveSuccess': 'Saved successfully!',
'status.saveFailed': 'Save failed',
'status.loadedSessions': 'Loaded',
'status.loadSessionsFailed': 'Failed to load conversations',
'status.loadFailed': 'Load failed',
// Error messages
'error.cannotLoadTree': 'Cannot load conversation tree',
// Tree view related
'treeView.prefix': 'Dialog Tree: ',
'treeView.untitled': 'Untitled',
'treeView.loading': 'Loading...',
'treeView.loadFailed': 'Failed to load dialog tree',
// Additional status and error messages
'error.invalidTitle': 'Generated invalid title.',
'error.loadSessionsFailed': 'Failed to load sessions',
'error.selectSessions': 'Please select sessions to execute "{0}".',
'error.selectExportSessions': 'Please select sessions to export.',
'error.browserNotSupported': 'Your browser does not support File System Access API.',
'status.refreshingFromServer': ' Refreshing from server...',
'status.preparingExport': 'Preparing export...',
'status.exporting': 'Exporting...',
'status.ready': 'Ready.',
'navigator.loadingHistory': 'Loading conversation history...',
'navigator.notInChat': 'Not in a specific chat, cannot operate on nodes.',
'attachment.title': 'PDF Deep Analysis Staging Area',
'attachment.removeFile': 'Remove file',
'attachment.clickPreview': 'Click to preview',
'attachment.openInNewTab': 'Click to open in new tab',
'navigator.clickToNavigate': 'Click to navigate to this node',
'navigator.clickToContinue': 'Click to continue from this node',
'navigator.nextMessageFrom': 'Next message will start from the specified node.',
'batchOps.confirmDelete': 'Are you sure to permanently delete {0} conversations?',
'status.batchProcessing': 'Batch {0} {1} conversations...',
'status.batchItemProcessing': '{0} {1}/{2}...',
'status.batchItemFailed': 'Item {0} failed',
'status.batchOperationComplete': 'Operation completed. Successfully {0} {1}/{2} conversations.',
'status.batchOperationFailed': 'Batch {0} failed',
'status.batchExportPreparing': 'Preparing batch export for {0} conversations...',
'status.batchExportFailed': 'Batch export failed',
'status.exportFailed': 'Export failed',
'status.checkingFile': 'Error checking file {0}',
'status.writingFile': 'Writing {0}...',
'status.convertingData': 'Converting data according to settings...',
// Export related messages
'export.foundAttachments': 'Found {0} attachments, starting download...',
'export.cannotGetOrgInfo': 'Cannot get organization info for downloading attachments.',
'export.skipExistingFile': '({0}/{1}) Skip (file exists): {2}',
'export.downloading': '({0}/{1}) Downloading: {2}',
'export.noDownloadUrl': 'Cannot find download link for attachment.',
'export.processAttachmentFailed': 'Failed to process attachment {0}',
'export.requestingFolder': 'Requesting folder permissions...',
'export.userCancelled': 'User cancelled folder selection.',
'export.orgInfoRequired': 'Organization info required for export.',
'export.creatingDirectory': 'Creating directory...',
'export.originalComplete': 'Original export completed!',
'export.originalFailed': 'Original export failed',
'export.customFailed': 'Custom export failed',
'export.batchComplete': 'Batch export completed: {0}/{1} conversations exported successfully.',
'export.exportFailed': 'Export failed ({0}/{1}): {2}',
'export.exportingProgress': '({0}/{1}) Exporting: {2}',
'export.sessionFailed': 'Failed to export session {0}',
// API error messages
'api.orgRequestFailed': 'Organization API request failed: {0}',
'api.orgInfoNotFound': 'Organization info not found in API response.',
'api.getSessionsFailed': 'Failed to get sessions: {0}',
'api.getHistoryFailed': 'Failed to get history: {0}',
'api.deleteRequestFailed': 'Delete API request failed: {0}',
'api.titleGenerationFailed': 'Title generation API request failed.',
'api.updateSessionFailed': 'Failed to update session: {0}',
'api.fileDownloadFailed': 'File download failed: {0} at {1}',
// Tree view and content messages
'tree.attachmentOrToolOnly': '[Contains only attachments or tool usage]',
'tree.attachments': 'Attachments',
'tree.dirtyData': 'Dirty Data',
'error.checkingFile': 'Unexpected error checking file {0}',
'error.noValidTextContent': 'No valid text content found within specified rounds.',
'error.insufficientRounds': 'Insufficient conversation rounds (possibly empty conversation), skipping rename.',
'error.cannotGetConvoData': 'Cannot get conversation data',
// Operation names
'operation.rename': 'rename',
'operation.delete': 'delete',
'operation.star': 'star',
'operation.unstar': 'unstar'
}
}
};
// 翻译函数
function t(key, fallback = key, ...params) {
const lang = I18N_CONFIG.currentLang;
const translations = I18N_CONFIG.translations[lang];
let text = translations && translations[key] ? translations[key] : (fallback || key);
// 支持参数替换 {0}, {1}, {2}...
if (params.length > 0) {
for (let i = 0; i < params.length; i++) {
text = text.replace(new RegExp(`\\{${i}\\}`, 'g'), params[i]);
}
}
return text;
}
// =========================================================================
// 1. 全局配置
// =========================================================================
const Config = {
INITIAL_PARENT_UUID: "00000000-0000-4000-8000-000000000000",
TOOLBAR_SELECTOR: 'div.relative.flex-1.flex.items-center.shrink.min-w-0',
EMPTY_AREA_SELECTOR: 'div.flex.flex-row.items-center.min-w-0',
FORCE_UPLOAD_TARGET_EXTENSIONS: [".pdf"],
SpecialContent: [".doc", ".pptx", ".zip"],
PdfHandler: [".pdf"],
OutOfContentFileHandler: [".csv", ".xls", ".xlsx", ".xlsb", ".xlm", ".xlsm", ".xlt", ".xltm", ".xltx", ".ods", ".zip"],
ContentExtractorHandler: [".docx", ".rtf", ".epub", ".odt", ".odp"],
ATTACHMENT_PANEL_ID: 'cpm-attachment-preview-panel',
EXPORT_MODAL_ID: 'cpm-export-modal',
URL_GITHUB_REPO: 'https://github.com/f14XuanLv/Claude-Powerest-Manager_Enhancer',
URL_STUDIO_REPO: 'https://github.com/f14XuanLv/claude-dialog-tree-studio',
maxPreviewLength: 16,
refreshInterval: 150,
topMargin: 200,
STORAGE_KEY: 'cpm-ln-panel-state'
};
// =========================================================================
// 1. 设置模块注册表
// =========================================================================
/**
* @typedef {object} ISettingModule - 设置模块接口定义
* @property {string} id - 模块的唯一ID。
* @property {string} title - 在设置面板中显示的标题。
* @property {function(): string} render - 返回该模块设置的HTML字符串。
* @property {function(HTMLElement): void} load - 从GM存储中加载设置并更新UI。
* @property {function(HTMLElement): void} save - 从UI读取设置并保存到GM存储。
* @property {function(HTMLElement): void} [addEventListeners] - (可选) 为模块的UI元素添加特定的事件监听器。
*/
const SettingsRegistry = {
/** @type {ISettingModule[]} */
modules: [],
/** @param {ISettingModule} module */
register(module) {
if (this.modules.find(m => m.id === module.id)) {
console.warn(LOG_PREFIX, `尝试重复注册设置模块: ${module.id}`);
return;
}
this.modules.push(module);
console.log(LOG_PREFIX, `设置模块已注册: ${module.id}`);
}
};
// =========================================================================
// 2. 各功能模块定义
// =========================================================================
// --- 2.1 主题设置模块 ---
const ThemeSettingsModule = {
id: 'theme',
title: t('settings.theme'),
render() {
return `
<div class="cpm-setting-group">
<div class="cpm-setting-item">
<label for="cpm-theme-mode" class="cpm-settings-label">${t('settings.themeMode')}</label>
<select id="cpm-theme-mode">
<option value="auto">${t('settings.themeAuto')}</option>
<option value="light">${t('settings.themeLight')}</option>
<option value="dark">${t('settings.themeDark')}</option>
</select>
</div>
</div>
`;
},
load(container) {
const themeSelect = container.querySelector('#cpm-theme-mode');
if (themeSelect) themeSelect.value = GM_getValue('themeMode', 'auto');
},
save(container) {
const themeSelect = container.querySelector('#cpm-theme-mode');
if (themeSelect) {
GM_setValue('themeMode', themeSelect.value);
ThemeManager.applyCurrentTheme();
}
}
};
// --- 2.2 批量操作设置模块 ---
const BatchOpsSettingsModule = {
id: 'batchOps',
title: t('settings.batchOps'),
render() {
return `
<div class="cpm-setting-group">
<h4>${t('batchOps.starUnstar')}</h4>
<div class="cpm-setting-item"><input type="checkbox" id="cpm-refresh-after-star"><label for="cpm-refresh-after-star">${t('batchOps.refreshAfterStar')}</label></div>
</div>
<div class="cpm-setting-group">
<h4>${t('batchOps.batchDelete')}</h4>
<div class="cpm-setting-item"><input type="checkbox" id="cpm-refresh-after-delete"><label for="cpm-refresh-after-delete">${t('batchOps.refreshAfterDelete')}</label></div>
</div>
<div class="cpm-setting-group">
<h4>${t('batchOps.autoRename')}</h4>
<div class="cpm-setting-item"><label for="cpm-rename-lang" class="cpm-settings-label">${t('batchOps.titleLanguage')}</label><input type="text" id="cpm-rename-lang" placeholder="${t('batchOps.titleLanguagePlaceholder')}"></div>
<div class="cpm-setting-item"><label for="cpm-rename-rounds" class="cpm-settings-label">${t('batchOps.maxRounds')}</label><input type="number" id="cpm-rename-rounds" min="1" max="10" step="1"></div>
<div class="cpm-setting-item"><input type="checkbox" id="cpm-refresh-after-rename"><label for="cpm-refresh-after-rename">${t('batchOps.refreshAfterRename')}</label></div>
</div>
`;
},
load(container) {
container.querySelector('#cpm-rename-lang').value = GM_getValue('renameLang', '中文');
container.querySelector('#cpm-rename-rounds').value = GM_getValue('renameRounds', '2');
container.querySelector('#cpm-refresh-after-rename').checked = GM_getValue('refreshAfterRename', false);
container.querySelector('#cpm-refresh-after-star').checked = GM_getValue('refreshAfterStar', false);
container.querySelector('#cpm-refresh-after-delete').checked = GM_getValue('refreshAfterDelete', false);
},
save(container) {
GM_setValue('renameLang', container.querySelector('#cpm-rename-lang').value);
GM_setValue('renameRounds', container.querySelector('#cpm-rename-rounds').value);
GM_setValue('refreshAfterRename', container.querySelector('#cpm-refresh-after-rename').checked);
GM_setValue('refreshAfterStar', container.querySelector('#cpm-refresh-after-star').checked);
GM_setValue('refreshAfterDelete', container.querySelector('#cpm-refresh-after-delete').checked);
}
};
// --- 2.3 导出设置模块 ---
const ExportSettingsModule = {
id: 'export',
title: t('settings.exportDefaults'),
render() {
return ManagerUI.createExportSettingsHTML(true);
},
load(container) {
ManagerUI.loadExportSettings(container);
},
save(container) {
ManagerUI.saveExportSettings(container);
},
addEventListeners(container) {
ManagerUI.setupSubOptionDisabling(container);
}
};
// --- 2.4 语言设置模块 ---
const LanguageSettingsModule = {
id: 'language',
title: t('settings.language'),
render() {
return `
<div class="cpm-setting-group">
<div class="cpm-setting-item">
<label for="cpm-language-select" class="cpm-settings-label">${t('settings.interfaceLanguage')}</label>
<select id="cpm-language-select">
<option value="zh">简体中文</option>
<option value="en">English</option>
</select>
</div>
</div>
`;
},
load(container) {
const langSelect = container.querySelector('#cpm-language-select');
if (langSelect) {
langSelect.value = I18N_CONFIG.currentLang;
}
},
save(container) {
const langSelect = container.querySelector('#cpm-language-select');
if (langSelect) {
const newLang = langSelect.value;
if (newLang !== I18N_CONFIG.currentLang) {
I18N_CONFIG.currentLang = newLang;
GM_setValue('language', newLang);
// 重新加载界面
setTimeout(() => {
location.reload();
}, 500);
}
}
}
};
// --- 2.5 注册所有设置模块 ---
SettingsRegistry.register(LanguageSettingsModule);
SettingsRegistry.register(ThemeSettingsModule);
SettingsRegistry.register(BatchOpsSettingsModule);
SettingsRegistry.register(ExportSettingsModule);
// =========================================================================
// 3. 主题管理器 (共享)
// =========================================================================
const ThemeManager = {
init() {
this.applyCurrentTheme();
this.observer = new MutationObserver(() => this.applyCurrentTheme());
this.observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-mode'] });
console.log(LOG_PREFIX, "主题管理器已初始化并开始监听。");
},
cleanup() {
if (this.observer) {
this.observer.disconnect();
this.observer = null;
}
},
applyCurrentTheme() {
const mode = GM_getValue('themeMode', 'auto');
let theme;
if (mode === 'light' || mode === 'dark') {
theme = mode;
} else {
theme = document.documentElement.getAttribute('data-mode') || 'light';
}
document.body.setAttribute('cpm-theme', theme);
},
};
// =========================================================================
// 4. 存储管理器和文本处理工具
// =========================================================================
const StorageManager = {
getPanelState() {
try {
const state = localStorage.getItem(Config.STORAGE_KEY);
return state === 'true';
} catch (e) {
return false;
}
},
setPanelState(isOpen) {
try {
localStorage.setItem(Config.STORAGE_KEY, String(isOpen));
} catch (e) {
// 忽略存储错误
}
}
};
const TextUtils = {
getPreview(element, maxLength = Config.maxPreviewLength) {
if (!element) return '';
const text = (element.innerText || element.textContent || '')
.replace(/\s+/g, ' ').trim();
if (!text) return '';
let width = 0, result = '';
for (let i = 0; i < text.length; i++) {
const char = text[i];
const charWidth = /[\u4e00-\u9fa5]/.test(char) ? 2 : 1;
if (width + charWidth > maxLength) {
result += '…';
break;
}
result += char;
width += charWidth;
}
return result || text.slice(0, maxLength);
}
};
// =========================================================================
// 5. API 层 (共享)
// =========================================================================
const ClaudeAPI = {
orgUuid: null,
orgInfo: null,
conversationTree: null,
currentLinearBranch: null,
currentConversationUuid: null,
isInitialized: false,
async getOrganizationInfo() {
if (this.orgInfo) return this.orgInfo;
try {
const response = await fetch('/api/organizations');
if (!response.ok) throw new Error(t('api.orgRequestFailed', 'api.orgRequestFailed', response.status));
const orgs = await response.json();
if (orgs && orgs.length > 0) {
this.orgInfo = orgs[0];
this.orgUuid = this.orgInfo.uuid;
return this.orgInfo;
}
throw new Error(t('api.orgInfoNotFound'));
} catch (error) {
console.error(LOG_PREFIX, "获取组织信息失败:", error);
throw error;
}
},
async getOrgUuid() {
if (this.orgUuid) return this.orgUuid;
const info = await this.getOrganizationInfo();
return info.uuid;
},
async getConversations() {
const orgId = await this.getOrgUuid();
const response = await fetch(`/api/organizations/${orgId}/chat_conversations`);
if (!response.ok) throw new Error(t('api.getSessionsFailed', 'api.getSessionsFailed', response.status));
return response.json();
},
async getConversationHistory(convUuid) {
const orgId = await this.getOrgUuid();
const url = `/api/organizations/${orgId}/chat_conversations/${convUuid}?tree=True&rendering_mode=messages&render_all_tools=true`;
const response = await fetch(url);
if (!response.ok) throw new Error(t('api.getHistoryFailed', 'api.getHistoryFailed', response.status));
const data = await response.json();
// 标记脏数据:标记没有 Claude 回复的孤儿用户节点 (在副本上操作)
const processedMessages = this.markDirtyMessages(data.chat_messages);
this.conversationTree = this.buildConversationTree(processedMessages);
this.updateCurrentLinearBranch();
return data; // 返回原始数据,保持不变
},
markDirtyMessages(messages) {
// 创建消息的深度副本,避免修改原始数据
const messagesCopy = messages.map(msg => JSON.parse(JSON.stringify(msg)));
// 按 index 排序消息以确保正确的时间顺序
const sortedMessages = [...messagesCopy].sort((a, b) => a.index - b.index);
let dirtyCount = 0;
console.log(`${LOG_PREFIX} 开始标记脏数据,原始消息数量: ${messages.length}`);
for (let i = 0; i < sortedMessages.length; i++) {
const currentMessage = sortedMessages[i];
// 如果是用户消息,检查下一个消息是否是 Claude 的回复
if (currentMessage.sender === 'human') {
const nextMessage = sortedMessages[i + 1];
// 如果没有下一个消息,或者下一个消息也是用户消息,说明是孤儿用户节点
if (!nextMessage || nextMessage.sender === 'human') {
console.log(`${LOG_PREFIX} 发现孤儿用户节点: ${currentMessage.uuid.slice(-8)}, index: ${currentMessage.index}, 内容: "${currentMessage.content?.[0]?.text?.slice(0, 50) || '空内容'}..."`);
// 在副本上标记为脏数据
currentMessage._isDirtyData = true;
dirtyCount++;
}
}
}
if (dirtyCount > 0) {
console.log(`${LOG_PREFIX} 标记完成,标记了 ${dirtyCount} 个孤儿用户节点为脏数据,总消息数量: ${messagesCopy.length}`);
}
return messagesCopy; // 返回包含脏数据标记的副本消息列表
},
buildConversationTree(messages) {
// 创建消息的深度副本,避免修改原始数据
const nodesCopy = {};
messages.forEach(msg => {
nodesCopy[msg.uuid] = JSON.parse(JSON.stringify(msg));
});
const childrenMap = {};
messages.forEach(msg => {
const parentUuid = msg.parent_message_uuid || Config.INITIAL_PARENT_UUID;
if (!childrenMap[parentUuid]) childrenMap[parentUuid] = [];
childrenMap[parentUuid].push(msg.uuid);
});
for (const parentUuid in childrenMap) {
childrenMap[parentUuid].sort((a, b) => new Date(nodesCopy[a].created_at) - new Date(nodesCopy[b].created_at));
}
function assignIdsRecursive(nodeUuid, prefix) {
if (!nodesCopy[nodeUuid]) return;
const node = nodesCopy[nodeUuid];
// 在副本上添加 tree_id
node.tree_id = prefix;
const children = childrenMap[nodeUuid] || [];
let normalIndex = 0;
let dirtyCount = 1;
children.forEach((childUuid) => {
const childNode = nodesCopy[childUuid];
if (!childNode) return;
// 检测脏数据:标记了 _isDirtyData 的节点
const isDirtyData = childNode._isDirtyData;
if (isDirtyData) {
assignIdsRecursive(childUuid, `${prefix}-F${dirtyCount}`);
dirtyCount++;
} else {
assignIdsRecursive(childUuid, `${prefix}-${normalIndex}`);
normalIndex++;
}
});
}
const rootNodes = childrenMap[Config.INITIAL_PARENT_UUID] || [];
rootNodes.forEach((rootUuid, index) => {
assignIdsRecursive(rootUuid, `root-${index}`);
});
return { nodes: nodesCopy, childrenMap, rootNodes };
},
async createTempConversation() {
const orgId = await this.getOrgUuid();
const tempConvUuid = crypto.randomUUID();
await fetch(`/api/organizations/${orgId}/chat_conversations`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ uuid: tempConvUuid, name: "" })
});
return tempConvUuid;
},
async deleteConversations(convUuids) {
const orgId = await this.getOrgUuid();
const isSingle = convUuids.length === 1;
const url = isSingle ? `/api/organizations/${orgId}/chat_conversations/${convUuids[0]}` : `/api/organizations/${orgId}/chat_conversations/delete_many`;