kongdeqiang
2026-10-09 f55d84f8479f35f780c535d2d4f4836727363255
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
<template>
  <div class="files-page">
    <div class="files-header">
      <n-button quaternary size="small" @click="$router.push('/c')">← 返回对话</n-button>
      <h1 class="files-title">知识库管理</h1>
      <div class="files-header-right">
        <n-tag v-if="ragAvailable" type="success" size="small" :bordered="false">
          RAG 服务正常
        </n-tag>
        <n-tag v-else type="warning" size="small" :bordered="false">
          RAG 服务不可用
        </n-tag>
      </div>
    </div>
 
    <div class="files-body">
      <n-alert v-if="!ragEnabled" type="warning" :bordered="false" class="files-alert">
        后端配置中 RAG 功能已关闭(webui.rag.enabled=false)。
      </n-alert>
      <n-alert v-else-if="!ragAvailable" type="warning" :bordered="false" class="files-alert">
        RAG 服务不可用({{ ragBaseUrl }})。请启动 Python 服务:<br />
        <code>cd rag-service &amp;&amp; export HF_ENDPOINT=https://hf-mirror.com</code><br />
        <code>uvicorn main:app --host 0.0.0.0 --port 8000</code>
      </n-alert>
 
      <FileUpload :chat-id="null" @uploaded="handleUploaded" />
 
      <!-- ============ 分类管理 ============ -->
      <div class="files-list-header">
        <span class="files-list-title">
          我的分类({{ categories.length }})
          <span class="title-hint">对话时可按分类整体绑定</span>
        </span>
        <n-button size="tiny" quaternary @click="showCreateCategory = true">+ 新建分类</n-button>
      </div>
 
      <div v-if="categories.length === 0" class="empty-hint category-empty">
        还没有分类。建一个分类,把文档归进去,对话时就能一键绑定整类。
      </div>
      <div v-for="cat in categories" v-else :key="cat.id" class="category-row">
        <div class="category-row-main">
          <div class="category-name">
            {{ cat.name }}
            <span v-if="cat.isGlobal" class="global-badge">全局</span>
          </div>
          <div class="category-meta">
            {{ cat.ingestedCount }}/{{ cat.fileCount }} 篇已入库
            <span v-if="cat.description"> · {{ cat.description }}</span>
          </div>
        </div>
        <div class="category-row-actions">
          <n-button size="tiny" quaternary @click="startRenameCategory(cat)">重命名</n-button>
          <n-button size="tiny" type="error" quaternary @click="handleDeleteCategory(cat)">
            删除
          </n-button>
        </div>
      </div>
 
      <!-- ============ 文档列表(按分类分组)============ -->
      <div class="files-list-header">
        <span class="files-list-title">我的文档({{ files.length }})</span>
        <n-button size="tiny" quaternary :loading="loading" @click="load">刷新</n-button>
      </div>
 
      <n-spin v-if="loading" size="small" class="files-spin" />
 
      <div v-else-if="files.length === 0" class="empty-hint files-empty">
        还没有上传任何文档
      </div>
 
      <!--
        按分类分组展示,而不是一串平铺的卡片。
        用户最需要一眼看出「这篇在哪个分类里」,
        平铺列表上再挂个标签仍然要找;分组则是直接可见的结构。
      -->
      <template v-for="group in groupedFiles" v-else :key="group.key">
        <div class="group-header">
          <span class="group-name">
            {{ group.name }}
            <span v-if="group.isGlobal" class="global-badge">全局</span>
          </span>
          <span class="group-count">{{ group.files.length }} 篇</span>
        </div>
 
        <div v-for="file in group.files" :key="file.id" class="file-card">
          <div class="file-card-main">
            <div class="file-name">{{ file.filename }}</div>
            <div class="file-meta">
              <span>{{ formatSize(file.fileSize) }}</span>
              <span class="file-sep">·</span>
              <span>{{ formatDate(file.createdAt) }}</span>
              <span class="file-sep">·</span>
              <span v-if="file.ingested" class="status-ok">
                已入库 {{ file.chunkCount }} 个片段
              </span>
              <span v-else-if="ingestFailed(file)" class="status-fail">
                入库失败:{{ file.ingestMessage }}
              </span>
              <span v-else class="status-pending">未向量化</span>
            </div>
          </div>
 
          <div class="file-card-actions">
            <!-- 归类:最常见操作,放在最前面 -->
            <n-select
              :value="file.categoryId"
              size="tiny"
              class="category-select"
              :options="categoryOptions"
              placeholder="未分类"
              :consistent-menu-width="false"
              @update:value="(v) => handleAssign(file, v)"
            />
            <n-button
              v-if="!file.ingested"
              size="small"
              :loading="ingestingId === file.id"
              @click="handleIngest(file)"
            >
              向量化
            </n-button>
            <n-button v-else size="small" :loading="ingestingId === file.id" @click="handleIngest(file)">
              重新入库
            </n-button>
            <n-button size="small" type="error" quaternary @click="handleDelete(file)">
              删除
            </n-button>
          </div>
        </div>
      </template>
    </div>
 
    <!-- 新建分类 -->
    <n-modal v-model:show="showCreateCategory" preset="card" title="新建分类" class="cat-modal" :bordered="false">
      <n-form label-placement="top">
        <n-form-item label="分类名称">
          <n-input v-model:value="newCategoryName" placeholder="例如:对话文档、产品资料"
                   maxlength="64" show-count @keyup.enter="handleCreateCategory" />
        </n-form-item>
        <n-form-item label="说明(可选)">
          <n-input v-model:value="newCategoryDesc" placeholder="便于自己日后分辨这个分类装什么"
                   maxlength="255" />
        </n-form-item>
        <n-form-item v-if="isAdmin" label="可见范围">
          <n-radio-group v-model:value="newCategoryGlobal">
            <n-radio :value="false">仅自己</n-radio>
            <n-radio :value="true">所有用户(全局分类,需管理员)</n-radio>
          </n-radio-group>
        </n-form-item>
      </n-form>
      <template #footer>
        <div class="modal-footer">
          <n-button size="small" @click="showCreateCategory = false">取消</n-button>
          <n-button size="small" type="primary" :loading="creatingCategory" @click="handleCreateCategory">
            创建
          </n-button>
        </div>
      </template>
    </n-modal>
 
    <!-- 重命名分类 -->
    <n-modal v-model:show="showRenameCategory" preset="card" title="重命名分类" class="cat-modal" :bordered="false">
      <n-form label-placement="top">
        <n-form-item label="分类名称">
          <n-input v-model:value="renameValue" maxlength="64" @keyup.enter="handleRenameCategory" />
        </n-form-item>
      </n-form>
      <template #footer>
        <div class="modal-footer">
          <n-button size="small" @click="showRenameCategory = false">取消</n-button>
          <n-button size="small" type="primary" :loading="renaming" @click="handleRenameCategory">
            保存
          </n-button>
        </div>
      </template>
    </n-modal>
  </div>
</template>
 
<script setup>
import { computed, onMounted, ref } from 'vue'
import {
  NAlert,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NModal,
  NRadio,
  NRadioGroup,
  NSelect,
  NSpin,
  NTag,
  useDialog,
  useMessage
} from 'naive-ui'
import FileUpload from '@/components/FileUpload.vue'
import { deleteFile, ingestFile, listFiles, ragHealth } from '@/api/fileApi'
import {
  assignFileToCategory,
  createCategory,
  deleteCategory,
  listCategories,
  updateCategory
} from '@/api/categoryApi'
import { useAuthStore } from '@/stores/authStore'
 
const message = useMessage()
const dialog = useDialog()
const auth = useAuthStore()
 
const files = ref([])
const categories = ref([])
const loading = ref(false)
const ingestingId = ref(null)
const ragEnabled = ref(true)
const ragAvailable = ref(true)
const ragBaseUrl = ref('')
 
const isAdmin = computed(() => auth.isAdmin)
 
// ---------------- 分类弹窗状态 ----------------
const showCreateCategory = ref(false)
const newCategoryName = ref('')
const newCategoryDesc = ref('')
const newCategoryGlobal = ref(false)
const creatingCategory = ref(false)
 
const showRenameCategory = ref(false)
const renameTarget = ref(null)
const renameValue = ref('')
const renaming = ref(false)
 
const categoryOptions = computed(() => [
  { label: '未分类', value: null },
  ...categories.value.map((c) => ({
    label: c.isGlobal ? `${c.name}(全局)` : c.name,
    value: c.id
  }))
])
 
/**
 * 按分类把文档分组展示。
 *
 * 未分类的排在最后 —— 它是「待整理」状态,
 * 放最前面会挤掉用户已经整理好的内容。
 */
const groupedFiles = computed(() => {
  const groups = []
  const byCategory = new Map()
 
  // 按分类列表顺序建组,保证空分类也能显示出来(提示用户它还没内容)
  for (const cat of categories.value) {
    const g = { key: `c${cat.id}`, name: cat.name, isGlobal: cat.isGlobal, files: [] }
    byCategory.set(cat.id, g)
    groups.push(g)
  }
 
  const uncategorized = { key: 'none', name: '未分类', isGlobal: false, files: [] }
 
  for (const file of files.value) {
    const g = file.categoryId != null ? byCategory.get(file.categoryId) : null
    if (g) {
      g.files.push(file)
    } else {
      // 分类被删掉后文件会变回未分类,这里兜住
      uncategorized.files.push(file)
    }
  }
 
  // 空分类不显示分组标题(否则界面上会多出一堆「0 篇」的空壳)
  const visible = groups.filter((g) => g.files.length > 0)
  if (uncategorized.files.length > 0) {
    visible.push(uncategorized)
  }
  return visible
})
 
onMounted(load)
 
async function load() {
  loading.value = true
  try {
    const [health, list, cats] = await Promise.all([
      ragHealth(),
      listFiles(null),
      listCategories()
    ])
    ragEnabled.value = health.enabled !== false
    ragAvailable.value = health.available !== false
    ragBaseUrl.value = health.baseUrl || ''
    files.value = list || []
    categories.value = cats || []
  } catch (error) {
    message.error(error.message || '加载失败')
  } finally {
    loading.value = false
  }
}
 
function handleUploaded(uploaded) {
  files.value = [...uploaded, ...files.value]
}
 
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
  }
}
 
function handleDelete(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)
        message.success('已删除')
      } catch (error) {
        message.error(error.message || '删除失败')
      }
    }
  })
}
 
function ingestFailed(file) {
  return Boolean(file.ingestMessage) && !file.ingested
}
 
// ---------------- 分类操作 ----------------
 
async function handleCreateCategory() {
  const name = newCategoryName.value.trim()
  if (!name) {
    message.warning('请输入分类名称')
    return
  }
  creatingCategory.value = true
  try {
    const created = await createCategory(name, newCategoryDesc.value || null, newCategoryGlobal.value)
    categories.value = [...categories.value, created]
    message.success(`分类「${created.name}」已创建,可把文档归入其中`)
 
    showCreateCategory.value = false
    newCategoryName.value = ''
    newCategoryDesc.value = ''
    newCategoryGlobal.value = false
  } catch (error) {
    message.error(error.message || '创建失败')
  } finally {
    creatingCategory.value = false
  }
}
 
function startRenameCategory(cat) {
  renameTarget.value = cat
  renameValue.value = cat.name
  showRenameCategory.value = true
}
 
async function handleRenameCategory() {
  const name = renameValue.value.trim()
  if (!name) {
    message.warning('请输入分类名称')
    return
  }
  renaming.value = true
  try {
    const updated = await updateCategory(renameTarget.value.id, name, renameTarget.value.description)
    categories.value = categories.value.map((c) => (c.id === updated.id ? updated : c))
    // 文档列表里的分类名也要同步,否则分组标题会与分类列表不一致
    files.value = files.value.map((f) =>
      f.categoryId === updated.id ? { ...f, categoryName: updated.name } : f
    )
    message.success('已重命名')
    showRenameCategory.value = false
  } catch (error) {
    message.error(error.message || '重命名失败')
  } finally {
    renaming.value = false
  }
}
 
function handleDeleteCategory(cat) {
  dialog.warning({
    title: '删除分类',
    content:
      `确定删除分类「${cat.name}」吗?\n\n` +
      `分类内的 ${cat.fileCount} 篇文档**不会被删除**,只会变成「未分类」。`,
    positiveText: '删除分类',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await deleteCategory(cat.id)
        categories.value = categories.value.filter((c) => c.id !== cat.id)
        // 这些文档变回未分类
        files.value = files.value.map((f) =>
          f.categoryId === cat.id ? { ...f, categoryId: null, categoryName: null } : f
        )
        message.success('分类已删除,文档保留')
      } catch (error) {
        message.error(error.message || '删除失败')
      }
    }
  })
}
 
/** 把文档移入 / 移出分类 */
async function handleAssign(file, categoryId) {
  try {
    if (categoryId == null) {
      // 移出分类:借用当前分类的 assign=false
      if (file.categoryId != null) {
        await assignFileToCategory(file.categoryId, file.id, false)
      }
    } else {
      await assignFileToCategory(categoryId, file.id, true)
    }
 
    const target = categories.value.find((c) => c.id === categoryId)
    files.value = files.value.map((f) =>
      f.id === file.id
        ? { ...f, categoryId: categoryId ?? null, categoryName: target ? target.name : null }
        : f
    )
    // 分类的文档数变了,重新拉一次保证统计准确
    categories.value = (await listCategories()) || []
    message.success(categoryId == null ? '已移出分类' : `已归入「${target.name}」`)
  } catch (error) {
    message.error(error.message || '归类失败')
    await load()
  }
}
 
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`
}
 
function formatDate(value) {
  if (!value) return '-'
  try {
    return new Date(value).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch {
    return String(value)
  }
}
</script>
 
<style scoped>
.files-page {
  height: 100vh;
  overflow-y: auto;
  background: var(--bg-page);
}
 
.files-header {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 14px 24px;
  border-bottom: 1px solid var(--border-color);
  position: sticky;
  top: 0;
  background: var(--bg-page);
  z-index: 10;
}
 
.files-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}
 
.files-header-right {
  margin-left: auto;
}
 
.files-body {
  max-width: 860px;
  margin: 0 auto;
  padding: 24px;
}
 
.files-alert {
  margin-bottom: 16px;
  font-size: 12.5px;
  line-height: 1.8;
}
 
.title-hint {
  font-weight: 400;
  font-size: 11.5px;
  color: var(--text-muted);
  margin-left: 6px;
}
 
.category-empty {
  padding: 20px 0;
  line-height: 1.9;
}
 
.category-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 12px 14px;
  border: 1px solid var(--border-color);
  border-radius: 10px;
  margin-bottom: 8px;
  background: #fcfcfd;
}
 
.category-row-main {
  min-width: 0;
  flex: 1;
}
 
.category-name {
  font-size: 13.5px;
  font-weight: 500;
}
 
.category-meta {
  font-size: 11.5px;
  color: var(--text-muted);
  margin-top: 4px;
}
 
.category-row-actions {
  display: flex;
  gap: 4px;
  flex-shrink: 0;
}
 
/* 分组标题:让「这篇在哪个分类」一眼可见 */
.group-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 4px 2px 8px;
  margin-top: 14px;
  border-bottom: 1px solid var(--border-color);
}
 
.group-name {
  font-size: 12.5px;
  font-weight: 600;
  color: var(--text-secondary);
}
 
.group-count {
  font-size: 11.5px;
  color: var(--text-muted);
}
 
.category-select {
  width: 130px;
}
 
.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;
}
 
.cat-modal {
  width: 440px;
}
 
.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
 
.files-list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 26px 0 10px;
}
 
.files-list-title {
  font-size: 13px;
  font-weight: 600;
}
 
.files-spin {
  display: flex;
  justify-content: center;
  padding: 24px 0;
}
 
.files-empty {
  padding: 32px 0;
}
 
.file-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  padding: 14px 16px;
  border: 1px solid var(--border-color);
  border-radius: 10px;
  margin-bottom: 10px;
}
 
.file-card-main {
  min-width: 0;
  flex: 1;
}
 
.file-name {
  font-size: 13.5px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
 
.file-meta {
  font-size: 11.5px;
  color: var(--text-muted);
  margin-top: 5px;
}
 
.file-sep {
  margin: 0 6px;
}
 
.status-ok {
  color: #0f766e;
}
 
.status-fail {
  color: #dc2626;
}
 
.status-pending {
  color: #b45309;
}
 
.file-collection {
  font-size: 11.5px;
  color: var(--text-muted);
  margin-top: 5px;
}
 
.file-collection code {
  background: var(--code-bg);
  padding: 1px 5px;
  border-radius: 4px;
}
 
.file-card-actions {
  display: flex;
  gap: 6px;
  flex-shrink: 0;
}
</style>