kongdeqiang
2026-10-12 97ddb98e522b2a15026e174be14a721219db4623
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
<template>
  <div class="chat-view">
    <!-- 顶部栏 -->
    <div class="chat-header">
      <div class="chat-header-left">
        <n-button quaternary size="small" class="header-btn" @click="$emit('toggle-sidebar')">
          ☰
        </n-button>
        <div class="chat-title-area">
          <div class="chat-title">{{ chat?.title || '新对话' }}</div>
          <div class="chat-subtitle">
            <span>{{ modelName }}</span>
            <span v-if="boundCollections.length" class="rag-badge">
              知识库 {{ boundCollections.length }}
            </span>
          </div>
        </div>
      </div>
 
      <div class="chat-header-right">
        <n-button quaternary size="small" class="header-btn" @click="showSettings = true">
          参数
        </n-button>
        <n-button quaternary size="small" class="header-btn" @click="showRag = true">
          知识库
        </n-button>
      </div>
    </div>
 
    <!-- 消息区 -->
    <div ref="scrollRef" class="message-list">
      <div v-if="!chatId" class="welcome">
        <div class="welcome-logo">CW</div>
        <h2 class="welcome-title">Custom-WebUI</h2>
        <p class="welcome-sub">
          选择左侧的对话,或点击「新对话」开始<br />
          支持流式输出、消息分支、以及知识库检索增强
        </p>
      </div>
 
      <template v-else>
        <div v-if="path.length === 0 && !streaming" class="welcome">
          <div class="welcome-logo">CW</div>
          <h2 class="welcome-title">开始新的对话</h2>
          <p class="welcome-sub">在下方输入你的问题,回复会以流式方式逐字显示</p>
        </div>
 
        <MessageItem
          v-for="msg in path"
          :key="msg.id"
          :message="msg"
          :is-streaming="msg.id === chatStore.streamingMessageId"
          :branch-info="chatStore.getBranchPosition(msg)"
          :user-initial="userInitial"
          @switch-branch="(delta) => chatStore.switchBranch(msg, delta)"
          @edit="(content) => handleEdit(msg, content)"
          @regenerate="() => handleRegenerate(msg)"
          @delete="() => handleDelete(msg)"
        />
      </template>
    </div>
 
    <!-- 错误提示 -->
    <div v-if="chatStore.streamError" class="stream-error">
      <span>{{ chatStore.streamError }}</span>
      <button class="error-close" @click="chatStore.streamError = ''">×</button>
    </div>
 
    <!-- 输入区 -->
    <div class="composer">
      <div class="composer-inner">
        <!-- 待发送的图片:显示缩略图与识别出的文字,发送前可删 -->
        <div v-if="pendingImages.length" class="pending-images">
          <div v-for="img in pendingImages" :key="img.key" class="pending-image">
            <img :src="img.previewUrl" class="pending-thumb" alt="待发送图片" />
            <div class="pending-info">
              <div class="pending-name">{{ img.filename }}</div>
              <div class="pending-status" :class="img.status">
                <template v-if="img.status === 'ocr'">识别中… {{ img.progress }}%</template>
                <template v-else-if="img.status === 'done'">
                  已识别 {{ img.text.length }} 字
                </template>
                <template v-else-if="img.status === 'empty'">
                  未识别到文字(仍可作为图片发送)
                </template>
                <template v-else>识别失败:{{ img.error }}</template>
              </div>
            </div>
            <button class="pending-remove" title="移除" @click="removePendingImage(img.key)">×</button>
          </div>
        </div>
 
        <n-input
          ref="inputRef"
          v-model:value="draft"
          type="textarea"
          :autosize="{ minRows: 1, maxRows: 8 }"
          :placeholder="composerPlaceholder"
          :disabled="!chatId"
          @keydown="handleKeydown"
          @paste="handlePaste"
        />
 
        <!-- 隐藏的文件选择框:accept 只列图片类型 -->
        <input
          ref="imageInputRef"
          type="file"
          class="hidden-image-input"
          multiple
          :accept="imageAccept"
          @change="handleImageSelect"
        />
 
        <div class="composer-actions">
          <label class="rag-toggle">
            <n-switch v-model:value="useRag" size="small" :disabled="!hasRag" />
            <span class="rag-toggle-label" :class="{ disabled: !hasRag }">
              {{ hasRag ? '启用知识库' : '未绑定知识库' }}
            </span>
          </label>
 
          <div class="composer-buttons">
<!--            <n-button-->
<!--              size="small"-->
<!--              :disabled="!chatId || chatStore.streaming"-->
<!--              :loading="pendingImages.some((i) => i.status === 'ocr')"-->
<!--              title="上传图片,识别其中文字后一并对话"-->
<!--              @click="pickImage"-->
<!--            >-->
<!--              图片-->
<!--            </n-button>-->
            <n-button
              v-if="chatStore.streaming"
              size="small"
              @click="chatStore.stopStreaming()"
            >
              停止生成
            </n-button>
            <n-button
              type="primary"
              size="small"
              :disabled="!canSend"
              :loading="chatStore.streaming"
              @click="handleSend"
            >
              发送
            </n-button>
          </div>
        </div>
      </div>
      <div class="composer-hint">
        Enter 发送,Shift + Enter 换行 · 可直接粘贴截图
      </div>
    </div>
 
    <!-- 模型参数抽屉 -->
    <n-drawer v-model:show="showSettings" :width="400" placement="right">
      <n-drawer-content title="模型参数" closable>
        <n-form label-placement="top">
          <n-form-item label="模型名称">
            <n-input v-model:value="metaForm.modelName" placeholder="留空使用后端默认模型" />
          </n-form-item>
          <n-form-item :label="`温度 temperature:${metaForm.temperature}`">
            <n-slider v-model:value="metaForm.temperature" :min="0" :max="2" :step="0.1" />
          </n-form-item>
          <n-form-item :label="`核采样 top_p:${metaForm.topP}`">
            <n-slider v-model:value="metaForm.topP" :min="0" :max="1" :step="0.05" />
          </n-form-item>
          <n-form-item label="上下文窗口 num_ctx">
            <n-input-number v-model:value="metaForm.numCtx" :min="512" :max="131072" :step="512" />
          </n-form-item>
          <n-form-item label="系统提示词">
            <n-input
              v-model:value="metaForm.systemPrompt"
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 10 }"
              placeholder="例如:你是一个严谨的技术助手,回答尽量简洁。"
            />
          </n-form-item>
        </n-form>
        <template #footer>
          <n-button type="primary" :loading="savingMeta" @click="saveMeta">保存参数</n-button>
        </template>
      </n-drawer-content>
    </n-drawer>
 
    <!-- 知识库抽屉 -->
    <n-drawer v-model:show="showRag" :width="520" placement="right">
      <n-drawer-content title="知识库设置" closable>
        <n-alert v-if="!ragEnabled" type="warning" :bordered="false" class="rag-alert">
          后端配置中 RAG 功能已关闭(webui.rag.enabled=false),检索不会生效。
        </n-alert>
        <n-alert v-else-if="!ragAvailable" type="warning" :bordered="false" class="rag-alert">
          RAG 服务当前不可用({{ ragBaseUrl }})。请启动 Python 服务:<br />
          <code>cd rag-service &amp;&amp; uvicorn main:app --host 0.0.0.0 --port 8000</code>
        </n-alert>
 
        <p class="rag-section-title">上传新文档</p>
        <FileUpload
          :chat-id="chatId"
          @uploaded="handleUploaded"
          @category-created="handleCategoryCreated"
        />
 
        <!--
          整类绑定区:把「绑定知识库」从逐个勾选变成一次点击。
          绑的是分类 id,后端检索时才展开 —— 之后往分类里新增文档,
          这个会话会自动检索到,不用回来重新绑定。
        -->
        <p class="rag-section-title">
          分类绑定
          <span class="section-hint">一次绑定整个分类</span>
          <n-button text size="tiny" class="section-refresh" @click="refreshRagState(props.chatId)">
            刷新
          </n-button>
        </p>
        <div v-if="categories.length === 0" class="empty-hint">
          还没有分类。上传文档时可选择或新建分类,之后即可整类绑定。
        </div>
        <div v-for="category in categories" v-else :key="category.id" class="category-row">
          <div class="category-row-main">
            <div class="category-name">
              {{ category.name }}
              <span v-if="category.isGlobal" class="global-badge">全局</span>
            </div>
            <div class="category-meta">
              {{ category.ingestedCount }}/{{ category.fileCount }} 篇已入库
              <span v-if="category.ingestedCount === 0" class="file-status pending">
                · 无已入库文档,绑定后检索不到内容
              </span>
            </div>
          </div>
          <n-button
            size="tiny"
            :disabled="category.ingestedCount === 0"
            :type="isCategoryBound(category.id) ? 'primary' : 'default'"
            :loading="categoryBindingId === category.id"
            @click="toggleCategoryBinding(category)"
          >
            {{ isCategoryBound(category.id) ? '已绑定' : '绑定整类' }}
          </n-button>
        </div>
 
        <p class="rag-section-title">
          我的知识库
          <span class="section-hint">也可单独绑定某篇</span>
        </p>
        <div v-if="files.length === 0" class="empty-hint">还没有上传任何文档</div>
        <div v-for="file in files" :key="file.id" class="file-row">
          <div class="file-row-main">
            <div class="file-name">
              {{ file.filename }}
              <!-- 全局知识库由管理员维护,普通用户只能绑定使用 -->
              <span v-if="file.isGlobal" class="global-badge">全局</span>
            </div>
            <div class="file-meta">
              {{ formatSize(file.fileSize) }}
              <span v-if="file.categoryName" class="file-category">· {{ file.categoryName }}</span>
              <span v-if="file.ingested" class="file-status ok">
                · 已入库 {{ file.chunkCount }} 块
              </span>
              <span v-else-if="file.ingestMessage" class="file-status fail">
                · {{ file.ingestMessage }}
              </span>
              <span v-else class="file-status pending">· 未向量化</span>
            </div>
          </div>
          <div class="file-row-actions">
            <n-button
              v-if="!file.ingested && file.canManage"
              size="tiny"
              :loading="ingestingId === file.id"
              @click="handleIngest(file)"
            >
              向量化
            </n-button>
            <n-button
              v-if="file.collectionName"
              size="tiny"
              :type="isCollectionActive(file.collectionName) ? 'primary' : 'default'"
              @click="toggleBinding(file.collectionName)"
            >
              {{ isCollectionActive(file.collectionName) ? '已绑定' : '绑定' }}
            </n-button>
            <n-button
              v-if="file.canManage"
              size="tiny"
              type="error"
              quaternary
              @click="handleDeleteFile(file)"
            >
              删除
            </n-button>
          </div>
        </div>
 
        <template #footer>
          <div class="rag-footer">
            <span class="text-secondary">
              已绑定 {{ boundCollections.length }} 个知识库,聊天时会自动检索
            </span>
          </div>
        </template>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>
 
<script setup>
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import {
  NAlert,
  NButton,
  NDrawer,
  NDrawerContent,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NSlider,
  NSwitch,
  useDialog,
  useMessage
} from 'naive-ui'
import MessageItem from './MessageItem.vue'
import FileUpload from './FileUpload.vue'
import {
  bindCategory,
  listCategories,
  listCategoryBindings
} from '@/api/categoryApi'
import { IMAGE_EXTENSIONS, recognizeImage, storeAttachmentText } from '@/api/fileApi'
import { useChatStore } from '@/stores/chatStore'
import { useAuthStore } from '@/stores/authStore'
import {
  bindCollections,
  deleteFile,
  ingestFile,
  listBindings,
  listFiles,
  ragHealth
} from '@/api/fileApi'
 
const emit = defineEmits(['toggle-sidebar'])
 
const props = defineProps({
  chatId: { type: Number, default: null }
})
 
const chatStore = useChatStore()
const auth = useAuthStore()
const message = useMessage()
const dialog = useDialog()
 
const draft = ref('')
const useRag = ref(true)
const scrollRef = ref(null)
const inputRef = ref(null)
 
const showSettings = ref(false)
const showRag = ref(false)
const savingMeta = ref(false)
 
const files = ref([])
const boundCollections = ref([])
const ingestingId = ref(null)
/** 可见分类(带 fileCount / ingestedCount / collectionNames) */
const categories = ref([])
/** 该会话已绑定的分类 id */
const boundCategoryIds = ref([])
/** 正在绑定/解绑的分类 id,用于按钮 loading */
const categoryBindingId = ref(null)
 
const ragEnabled = ref(true)
const ragAvailable = ref(true)
const ragBaseUrl = ref('')
 
const chat = computed(() => chatStore.activeChat)
const path = computed(() => chatStore.path)
const userInitial = computed(() => (auth.displayName || 'U').charAt(0).toUpperCase())
 
/**
 * 当前是否正在流式生成。
 *
 * 模板里用 `streaming` 而不是直接写 `chatStore.streaming`,
 * 一是可读性,二是将来若要加「已发送但首个 token 未到」这类派生状态,
 * 只需改这一处。
 *
 * 注意:这个 computed 是必须的 —— 之前模板引用了 `streaming` 却没定义,
 * Vue 只会在控制台打一条 warning,页面照常渲染但该条件恒为
 * undefined(falsy),表现为空会话时欢迎语与消息区同时出现。
 */
const streaming = computed(() => chatStore.streaming)
 
/**
 * 当前会话「实际生效」的全部集合 = 单篇绑定的集合 ∪ 已绑定分类展开出的集合。
 *
 * 这个计算属性是修一个严重 bug 的关键。之前状态是分散的:
 *   - hasRag 只看 boundCollections(单篇绑定)
 *   - 分类绑定只写在 boundCategoryIds 里
 * 于是「绑定整类」之后 hasRag 仍为 false →
 *   1) 底部显示「未绑定知识库」
 *   2) 发送消息时 useRag 被算成 false,后端**根本没做检索**,
 *      回答自然不引用知识库
 *
 * 根因是把「用户绑了什么」和「实际生效什么」混为一谈。
 * 现在统一由这里推导,两处绑定方式都覆盖,不再有遗漏。
 */
const effectiveBoundCollections = computed(() => {
  const set = new Set(boundCollections.value)
  for (const cat of categories.value) {
    if (!boundCategoryIds.value.includes(cat.id)) {
      continue
    }
    for (const name of cat.collectionNames || []) {
      set.add(name)
    }
  }
  return [...set]
})
 
// ---------------- 图片上传与 OCR ----------------
 
/**
 * 待发送的图片。
 *
 * 每项形如 { key, filename, previewUrl, status, progress, text, fileId, error }
 * status: ocr(识别中)/ done / empty(没识别到字)/ failed
 */
const pendingImages = ref([])
const imageInputRef = ref(null)
 
const imageAccept = IMAGE_EXTENSIONS.map((e) => `.${e}`).join(',')
 
function pickImage() {
  if (!props.chatId || chatStore.streaming) return
  imageInputRef.value?.click()
}
 
function handleImageSelect(event) {
  const files = Array.from(event.target.files || [])
  // 清空 value,否则连续选同一个文件不会触发 change
  event.target.value = ''
  uploadImages(files)
}
 
async function uploadImages(files) {
  if (files.length === 0) return
 
  for (const file of files) {
    const ext = file.name.split('.').pop()?.toLowerCase() || ''
    if (!IMAGE_EXTENSIONS.includes(ext)) {
      message.error(`${file.name}:不是支持的图片类型(${IMAGE_EXTENSIONS.join('/')})`)
      continue
    }
    if (file.size > 20 * 1024 * 1024) {
      message.error(`${file.name}:图片超过 20MB`)
      continue
    }
 
    // 本地预览:ObjectURL 不占内存,删除时记得 revoke
    const item = reactive({
      key: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
      filename: file.name,
      previewUrl: URL.createObjectURL(file),
      status: 'ocr',
      progress: 0,
      text: '',
      fileId: null,
      error: ''
    })
    pendingImages.value.push(item)
 
    try {
      const result = await recognizeImage(file, props.chatId, (percent) => {
        item.progress = percent
      })
      item.fileId = result.fileId
      item.text = result.text || ''
      item.status = item.text.trim() ? 'done' : 'empty'
 
      if (item.status === 'empty') {
        // 不是错误:用户可能就是想发张图。说清楚它不会被模型"看懂"即可
        message.info(`${file.name} 未识别到文字,图片仍会发出,但模型只能看到文件名`)
      }
    } catch (error) {
      item.status = 'failed'
      item.error = error.message || '识别失败'
      message.error(`${file.name}:${item.error}`)
    }
  }
}
 
/**
 * 从剪贴板事件中取出图片文件。
 *
 * 为什么要遍历 items 而不能只看 items[0]:
 * 从网页复制内容时,clipboardData 里往往同时有 text/html、text/plain
 * 和 image/png。只取第一项可能拿到 HTML 而不是图片,
 * 导致「明明复制的图片却粘出了源码」。
 */
function extractImageFiles(event) {
  const items = event.clipboardData?.items
  if (!items) return []
  const files = []
  for (const item of items) {
    if (item.kind === 'file' && item.type.startsWith('image/')) {
      const file = item.getAsFile()
      if (file) files.push(file)
    }
  }
  return files
}
 
/**
 * 粘贴处理。
 *
 * 只拦「剪贴板里确实有图片」的情况;纯文本粘贴交给浏览器默认行为,
 * 否则会破坏正常粘贴文字、以及带格式文本的粘贴。
 */
/**
 * 本次粘贴是否已被组件级处理。
 *
 * 用它而不是时间窗口去重:时间窗口会误伤「300ms 内连续粘贴两次图片」,
 * 而这种精确标记只吃掉同一个事件的重复投递,不会影响下一次真实粘贴。
 */
let pasteConsumedByComposer = false
 
function handlePaste(event) {
  const files = extractImageFiles(event)
  if (files.length === 0) {
    // 剪贴板里有文字也有图片时(从网页复制),文字照常插入,图片额外收下
    return
  }
 
  // 阻止默认行为,避免把图片的 html/文件名当文本塞进输入框
  event.preventDefault()
  // 标记本次粘贴已被处理,避免 document 层的兜底监听重复收一次
  pasteConsumedByComposer = true
 
  if (!props.chatId) {
    message.warning('请先选择或新建一个对话')
    return
  }
  if (chatStore.streaming) {
    message.warning('正在生成回复,请稍候再粘贴图片')
    return
  }
 
  // 剪贴板里的图片往往没有文件名(截图、复制的图),给个可读的默认名,
  // 否则「我的知识库」里会出现一堆无名的 png
  const named = files.map((f, i) =>
    f.name && f.name !== 'image.png'
      ? f
      : new File([f], `粘贴图片_${timestampName()}${files.length > 1 ? `_${i + 1}` : ''}.png`, {
          type: f.type || 'image/png'
        })
  )
 
  uploadImages(named)
}
 
/** 生成用于文件名的短时间戳,如 20261001_143012 */
function timestampName() {
  const d = new Date()
  const pad = (n) => String(n).padStart(2, '0')
  return (
    `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}` +
    `_${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`
  )
}
 
/**
 * 文档级粘贴兜底。
 *
 * 只在「粘贴发生的位置不在任何输入框里」时接管 —— 用户点了页面空白处再粘贴
 * 也能收到图,符合直觉。若焦点已在输入框内,由上面的 handlePaste 处理,
 * 这里直接跳过,否则会重复收图。
 */
function handleDocumentPaste(event) {
  // 同一个事件已由组件级处理过,消费掉标记并跳过
  if (pasteConsumedByComposer) {
    pasteConsumedByComposer = false
    return
  }
 
  // 焦点在输入类元素里时交给它们自己处理
  const el = document.activeElement
  const tag = el?.tagName?.toLowerCase()
  if (tag === 'input' || tag === 'textarea' || el?.isContentEditable) return
 
  const files = extractImageFiles(event)
  if (files.length === 0) return
  event.preventDefault()
  uploadImages(files.map((f) => new File([f], `粘贴图片_${timestampName()}.png`, { type: f.type || 'image/png' })))
}
 
function removePendingImage(key) {
  const idx = pendingImages.value.findIndex((i) => i.key === key)
  if (idx === -1) return
  // 释放 ObjectURL,否则长时间使用会持续占用内存
  URL.revokeObjectURL(pendingImages.value[idx].previewUrl)
  pendingImages.value.splice(idx, 1)
}
 
async function clearPendingImages() {
  for (const img of pendingImages.value) {
    URL.revokeObjectURL(img.previewUrl)
  }
  pendingImages.value = []
}
 
/** 是否有可用于检索的知识库(单篇或整类都算) */
const hasRag = computed(() => effectiveBoundCollections.value.length > 0)
 
/** 某篇文档(按集合名)当前是否处于已绑定/生效状态 */
function isCollectionActive(collectionName) {
  return effectiveBoundCollections.value.includes(collectionName)
}
const canSend = computed(() => {
  if (!props.chatId || streaming.value) return false
  // 允许「只发图片不打字」:上传了图就能发
  return draft.value.trim().length > 0 || pendingImages.value.length > 0
})
 
const modelName = computed(() => {
  const meta = chat.value?.meta
  return meta?.modelName || '默认模型'
})
 
const composerPlaceholder = computed(() =>
  props.chatId ? '输入消息…' : '请先新建或选择一个对话'
)
 
const metaForm = ref({
  modelName: '',
  temperature: 0.7,
  topP: 0.9,
  numCtx: 8192,
  systemPrompt: ''
})
 
// ---------------- 会话切换 ----------------
 
watch(
  () => props.chatId,
  async (chatId) => {
    if (!chatId) {
      chatStore.resetView()
      files.value = []
      boundCollections.value = []
      boundCategoryIds.value = []
      // 注意:**不能在这里 return**。
      // 没有选中会话时(用户刚进 /c,或删掉了当前会话),
      // 分类列表与文件列表仍然应该显示 —— 否则用户新建了分类、
      // 打开知识库却什么都看不到,会以为分类没建成功。
      // 只是此时没有「已绑定」状态可标记而已。
      await refreshRagState(null)
      return
    }
 
    // 切会话前先把可能还在跑的流中断掉。
    // 这是「发送按钮卡死」的兜底恢复手段:一旦 streaming 因任何竞态
    // 残留在 true,切一次会话即可恢复,不需要刷新页面。
    chatStore.stopStreaming()
 
    try {
      // 不保留上一个会话的分支选择,避免 id 复用导致的错乱
      await chatStore.loadMessages(chatId, false)
      syncMetaForm()
      await refreshRagState(chatId)
      scrollToBottom()
    } catch (error) {
      message.error(error.message || '加载消息失败')
    }
  },
  { immediate: true }
)
 
// 新内容到达时自动滚到底部
watch(
  () => path.value.map((item) => item.content).join('|'),
  () => scrollToBottom()
)
 
watch(
  () => chatStore.streaming,
  (streaming) => {
    if (!streaming) scrollToBottom()
  }
)
 
function syncMetaForm() {
  const meta = chat.value?.meta || {}
  metaForm.value = {
    modelName: meta.modelName || '',
    temperature: meta.temperature ?? 0.7,
    topP: meta.topP ?? 0.9,
    numCtx: meta.numCtx ?? 8192,
    systemPrompt: meta.systemPrompt || ''
  }
}
 
/**
 * 加载知识库相关状态。
 *
 * @param chatId 可为 null —— 未选中会话时,分类与文件列表仍需正常展示,
 *               只是无法标记「已绑定」状态。
 */
async function refreshRagState(chatId) {
  try {
    const health = await ragHealth()
    ragEnabled.value = health.enabled !== false
    ragAvailable.value = health.available !== false
    ragBaseUrl.value = health.baseUrl || ''
  } catch {
    // 健康检查失败不阻断页面,按「不可用」显示
    ragAvailable.value = false
  }
 
  try {
    // chatId 为空时跳过依赖会话的请求(会 400/404),但仍要拿分类与文件
    const [fileList, bindings, categoryList, categoryBindings] = await Promise.all([
      listFiles(null),
      chatId != null ? listBindings(chatId) : Promise.resolve([]),
      listCategories(chatId),
      chatId != null ? listCategoryBindings(chatId) : Promise.resolve([])
    ])
    files.value = fileList || []
    boundCollections.value = bindings || []
    categories.value = categoryList || []
    boundCategoryIds.value = categoryBindings || []
    // useRag 是「用户是否希望启用检索」的意图开关,
    // 是否真的有知识库可用由 hasRag 推导,不再手工同步,避免两处状态漂移
    if (hasRag.value) {
      useRag.value = true
    }
  } catch (error) {
    message.error(error.message || '加载知识库信息失败')
  }
}
 
/** 该分类是否已绑定到当前会话 */
function isCategoryBound(categoryId) {
  return boundCategoryIds.value.includes(categoryId)
}
 
/**
 * 整类绑定 / 解绑。
 *
 * 提交的是**分类 id**,检索时由后端展开成集合 ——
 * 因此之后往分类里新增文档会自动生效,不需要回到这里重新绑定。
 */
async function toggleCategoryBinding(category) {
  if (props.chatId == null) {
    message.warning('请先选择或新建一个对话,再绑定知识库分类')
    return
  }
  const bind = !isCategoryBound(category.id)
  categoryBindingId.value = category.id
  try {
    boundCategoryIds.value = (await bindCategory(props.chatId, category.id, bind)) || []
    // 绑定后自动打开检索开关:用户刚绑定知识库,意图显然是「要用它」
    if (hasRag.value) {
      useRag.value = true
    }
 
    if (bind) {
      // 提示里点明「新增文档会自动生效」,这是整类绑定相对逐个绑定的核心优势
      message.success(
        `已绑定分类「${category.name}」(${category.ingestedCount} 篇已入库),` +
          '以后往该分类新增文档会自动参与检索'
      )
    } else {
      message.success(`已解绑分类「${category.name}」`)
    }
  } catch (error) {
    message.error(error.message || '操作失败')
  } finally {
    categoryBindingId.value = null
  }
}
 
// ---------------- 发送 ----------------
 
function handleKeydown(event) {
  // Enter 发送,Shift+Enter 换行;输入法组合中的 Enter 不应触发发送
  if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
    event.preventDefault()
    handleSend()
  }
}
 
async function handleSend() {
  const content = draft.value.trim()
  const hasImages = pendingImages.value.length > 0
  if ((!content && !hasImages) || !props.chatId || chatStore.streaming) return
 
  // 先清空输入框与待发送图片,让用户能立即继续打字 / 继续选图
  draft.value = ''
 
  // 图片数据先取下快照:sendMessage 会立刻把消息乐观渲染进消息树,
  // 预览区就没必要继续占着了。
  //
  // 注意不能等 sendMessage 返回再清 —— 那要等整段回答生成完
  // (实测 9 秒以上),期间预览区一直挂着「待发送图片」,
  // 用户会以为没发出去而重复发送。
  const imageText = pendingImages.value
    .map((i) => i.text)
    .filter((t) => t && t.trim())
    .join('\n\n')
  const imageFileIds = pendingImages.value
    .map((i) => i.fileId)
    .filter((id) => id != null)
 
  await clearPendingImages()
 
  // 长文本先暂存换短 id:SSE 是 GET,参数只能走 query string,
  // 而中文 URL 编码约 9 字节/字,2000 字就 18KB,
  // 超过 Tomcat 默认 8KB 的请求行上限会得到 "Request header is too large"。
  // 阈值取 1000 字(约 9KB 编码后仍偏高),超过就走暂存。
  let imageTextId = null
  let inlineImageText = imageText
  if (imageText && imageText.length > 1000) {
    try {
      const stored = await storeAttachmentText(imageText)
      imageTextId = stored?.id || null
      if (imageTextId) {
        inlineImageText = null
      }
    } catch (error) {
      // 暂存失败就退回内联传递;内容不长时仍可用,
      // 过长时后端会给出明确提示而不是静默失败
      message.warning(`图片文字暂存失败,将尝试直接发送:${error.message || ''}`)
    }
  }
 
  try {
    await chatStore.sendMessage({
      chatId: props.chatId,
      content,
      useRag: useRag.value && hasRag.value,
      imageText: inlineImageText,
      imageTextId,
      imageFileIds
    })
  } catch (error) {
    message.error(error.message || '发送失败')
    // 发送失败把内容还回输入框,避免用户白打字。
    // 图片不还原:文件已在服务端落盘,重新识别一遍代价更高,
    // 用户重新选图即可(消息树里也没有产生垃圾消息)。
    draft.value = content
  } finally {
    inputRef.value?.focus?.()
  }
}
 
async function handleRegenerate(msg) {
  try {
    await chatStore.regenerate({
      chatId: props.chatId,
      userMessageId: msg.id,
      useRag: useRag.value && hasRag.value
    })
  } catch (error) {
    message.error(error.message || '重新生成失败')
  }
}
 
async function handleEdit(msg, content) {
  try {
    await chatStore.editMessage(props.chatId, msg.id, content)
    message.success('已保存')
  } catch (error) {
    message.error(error.message || '保存失败')
  }
}
 
function handleDelete(msg) {
  dialog.warning({
    title: '删除消息',
    content: '该消息及其之后的所有对话都会被删除,确定继续吗?',
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await chatStore.removeMessage(props.chatId, msg.id)
        message.success('已删除')
      } catch (error) {
        message.error(error.message || '删除失败')
      }
    }
  })
}
 
// ---------------- 参数 ----------------
 
async function saveMeta() {
  savingMeta.value = true
  try {
    await chatStore.updateChatMeta(props.chatId, {
      modelName: metaForm.value.modelName || null,
      temperature: metaForm.value.temperature,
      topP: metaForm.value.topP,
      numCtx: metaForm.value.numCtx || null,
      systemPrompt: metaForm.value.systemPrompt || null
    })
    message.success('参数已保存')
    showSettings.value = false
  } catch (error) {
    message.error(error.message || '保存失败')
  } finally {
    savingMeta.value = false
  }
}
 
// ---------------- 知识库 ----------------
 
async function handleUploaded(uploaded) {
  files.value = [...uploaded, ...files.value]
  // 上传时若选了分类,分类的文档数变了,连同文件列表一起刷新
  await refreshRagState(props.chatId)
}
 
/**
 * 在上传区现场新建了分类。
 *
 * 必须刷新分类列表 —— 否则用户刚建的分类不会出现在上方的
 * 「分类绑定」区里,看起来像没建成功。
 */
async function handleCategoryCreated() {
  await refreshRagState(props.chatId)
}
 
async function handleIngest(file) {
  ingestingId.value = file.id
  try {
    const updated = await ingestFile(file.id)
    const index = files.value.findIndex((item) => item.id === file.id)
    if (index !== -1) {
      files.value[index] = updated
    }
    message.success(`向量化完成,共 ${updated.chunkCount} 个片段`)
  } catch (error) {
    message.error(error.message || '向量化失败')
    // 重新拉取以显示后端的失败状态
    try {
      files.value = await listFiles(null)
    } catch {
      // 忽略
    }
  } finally {
    ingestingId.value = null
  }
}
 
async function toggleBinding(collectionName) {
  const next = boundCollections.value.includes(collectionName)
    ? boundCollections.value.filter((name) => name !== collectionName)
    : [...boundCollections.value, collectionName]
 
  try {
    // 后端是全量覆盖语义,因此提交完整列表。
    // 返回的是**实际绑定成功**的列表 —— 已失效的集合后端会忽略,
    // 所以这里必须用返回值覆盖本地状态,否则本地会一直残留
    // 那个已失效的集合名,导致每次绑定都重复提交它。
    const applied = (await bindCollections(props.chatId, next)) || []
    boundCollections.value = applied
    if (hasRag.value) {
      useRag.value = true
    }
 
    // 告知被剔除的项,避免用户觉得「点了没反应」
    const dropped = next.filter((name) => !applied.includes(name))
    if (dropped.length > 0) {
      message.warning(
        `${dropped.length} 个知识库已失效(文档可能已被删除或被取消全局),已自动移除:` +
          dropped.join('、')
      )
      // 拉一次文件列表,让失效文档从界面上消失
      await refreshRagState(props.chatId)
    } else {
      message.success(applied.length ? '绑定已更新' : '已解除全部绑定')
    }
  } catch (error) {
    message.error(error.message || '绑定失败')
  }
}
 
function handleDeleteFile(file) {
  dialog.warning({
    title: '删除文档',
    content: `确定删除「${file.filename}」吗?磁盘文件与已入库的向量都会一并清理。`,
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await deleteFile(file.id)
        files.value = files.value.filter((item) => item.id !== file.id)
        if (file.collectionName) {
          boundCollections.value = boundCollections.value.filter(
            (name) => name !== file.collectionName
          )
        }
        message.success('已删除')
      } catch (error) {
        message.error(error.message || '删除失败')
      }
    }
  })
}
 
function formatSize(bytes) {
  if (!bytes && bytes !== 0) return ''
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  return `${(bytes / 1024 / 1024).toFixed(1)} MB`
}
 
// ---------------- 生命周期 ----------------
 
onMounted(() => {
  document.addEventListener('paste', handleDocumentPaste)
})
 
onBeforeUnmount(() => {
  document.removeEventListener('paste', handleDocumentPaste)
  // 离开页面时释放未发送图片的 ObjectURL,避免泄漏
  clearPendingImages()
})
 
function scrollToBottom() {
  nextTick(() => {
    const el = scrollRef.value
    if (el) {
      el.scrollTop = el.scrollHeight
    }
  })
}
 
defineExpose({ refreshRagState })
</script>
 
<style scoped>
.chat-view {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
  height: 100vh;
  background: var(--bg-page);
}
 
.chat-header {
  height: 54px;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  flex-shrink: 0;
}
 
.chat-header-left,
.chat-header-right {
  display: flex;
  align-items: center;
  gap: 4px;
}
 
.header-btn {
  font-size: 15px;
}
 
.chat-title-area {
  margin-left: 8px;
  min-width: 0;
}
 
.chat-title {
  font-size: 14px;
  font-weight: 600;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 380px;
}
 
.chat-subtitle {
  font-size: 11.5px;
  color: var(--text-muted);
  margin-top: 1px;
}
 
.rag-badge {
  margin-left: 8px;
  color: #0f766e;
}
 
.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px 24px 24px;
  scroll-behavior: smooth;
}
 
.welcome {
  text-align: center;
  padding-top: 16vh;
}
 
.welcome-logo {
  width: 56px;
  height: 56px;
  margin: 0 auto 18px;
  border-radius: 15px;
  background: #374151;
  color: #fff;
  font-weight: 700;
  font-size: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}
 
.welcome-title {
  margin: 0 0 8px;
  font-size: 21px;
  font-weight: 600;
}
 
.welcome-sub {
  margin: 0;
  font-size: 13.5px;
  color: var(--text-secondary);
  line-height: 1.9;
}
 
.stream-error {
  margin: 0 24px 8px;
  padding: 9px 12px;
  background: #fef2f2;
  border: 1px solid #fecaca;
  border-radius: 8px;
  font-size: 13px;
  color: #b91c1c;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  max-width: 780px;
  align-self: center;
  width: calc(100% - 48px);
  box-sizing: border-box;
}
 
.error-close {
  background: none;
  border: none;
  font-size: 17px;
  line-height: 1;
  cursor: pointer;
  color: #b91c1c;
  padding: 0 2px;
}
 
.composer {
  padding: 8px 24px 16px;
  flex-shrink: 0;
}
 
.composer-inner {
  max-width: 780px;
  margin: 0 auto;
  border: 1px solid var(--border-color);
  border-radius: 12px;
  padding: 10px 12px 8px;
  box-shadow: 0 2px 10px rgba(15, 23, 42, 0.04);
  transition: border-color 0.15s ease;
}
 
.composer-inner:focus-within {
  border-color: #9ca3af;
}
 
.composer-inner :deep(.n-input) {
  --n-border: none !important;
  --n-border-hover: none !important;
  --n-border-focus: none !important;
  --n-box-shadow-focus: none !important;
}
 
.hidden-image-input {
  display: none;
}
 
.pending-images {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 8px;
}
 
.pending-image {
  position: relative;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 26px 6px 6px;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  background: #fafafa;
  max-width: 260px;
}
 
.pending-thumb {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 6px;
  flex-shrink: 0;
}
 
.pending-info {
  min-width: 0;
}
 
.pending-name {
  font-size: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
 
.pending-status {
  font-size: 11px;
  color: var(--text-muted);
  margin-top: 2px;
}
 
.pending-status.done {
  color: #0f766e;
}
 
.pending-status.failed {
  color: #dc2626;
}
 
.pending-remove {
  position: absolute;
  top: 2px;
  right: 4px;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 15px;
  line-height: 1;
  color: var(--text-muted);
  padding: 0 2px;
}
 
.pending-remove:hover {
  color: #dc2626;
}
 
.composer-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 8px;
}
 
.rag-toggle {
  display: flex;
  align-items: center;
  gap: 7px;
  cursor: pointer;
}
 
.rag-toggle-label {
  font-size: 12.5px;
  color: var(--text-secondary);
}
 
.rag-toggle-label.disabled {
  color: var(--text-muted);
}
 
.composer-buttons {
  display: flex;
  gap: 8px;
}
 
.composer-hint {
  text-align: center;
  font-size: 11.5px;
  color: var(--text-muted);
  margin-top: 8px;
}
 
/* ---------------- 抽屉内部 ---------------- */
.rag-alert {
  margin-bottom: 16px;
  font-size: 12.5px;
  line-height: 1.8;
}
 
.rag-section-title {
  font-size: 13px;
  font-weight: 600;
  margin: 20px 0 10px;
}
 
.rag-section-title:first-of-type {
  margin-top: 0;
}
 
.section-refresh {
  float: right;
  font-size: 11.5px;
  color: var(--text-secondary);
  margin-top: 1px;
}
 
.section-hint {
  font-weight: 400;
  color: var(--text-muted);
  font-size: 11.5px;
  margin-left: 6px;
}
 
.category-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  padding: 10px 12px;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  margin-bottom: 8px;
  background: #fcfcfd;
}
 
.category-row-main {
  min-width: 0;
  flex: 1;
}
 
.category-name {
  font-size: 13px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
 
.category-meta {
  font-size: 11.5px;
  color: var(--text-muted);
  margin-top: 3px;
}
 
.file-category {
  color: #0f766e;
}
 
.file-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  padding: 10px 0;
  border-bottom: 1px solid #f3f4f6;
}
 
.file-row-main {
  min-width: 0;
  flex: 1;
}
 
.file-name {
  font-size: 13px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
 
/* 全局知识库标记:提示这个文档是全员共用的公共知识库 */
.global-badge {
  display: inline-block;
  margin-left: 6px;
  padding: 0 5px;
  font-size: 11px;
  line-height: 16px;
  border-radius: 4px;
  color: #0f766e;
  background: #ecfdf5;
  vertical-align: middle;
}
 
.file-meta {
  font-size: 11.5px;
  color: var(--text-muted);
  margin-top: 3px;
}
 
.file-status.ok {
  color: #0f766e;
}
 
.file-status.fail {
  color: #dc2626;
}
 
.file-status.pending {
  color: #b45309;
}
 
.file-row-actions {
  display: flex;
  gap: 4px;
  flex-shrink: 0;
}
 
.rag-footer {
  font-size: 12.5px;
}
</style>