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
<template>
  <div class="sidebar">
    <div class="sidebar-header">
      <n-button class="new-chat-btn" block @click="handleNewChat">
        <template #icon>
          <span class="plus-icon">+</span>
        </template>
        新对话
      </n-button>
    </div>
 
    <div class="sidebar-search">
      <n-input
        v-model:value="keyword"
        size="small"
        clearable
        placeholder="搜索历史对话"
        @input="handleSearchInput"
        @keyup.esc="handleClearSearch"
      >
        <template #prefix>
          <span class="search-icon">⌕</span>
        </template>
      </n-input>
    </div>
 
    <div class="sidebar-list">
      <!-- 搜索态:显示结果,命中内容时给出上下文片段 -->
      <template v-if="isSearching">
        <n-spin v-if="chatStore.searching" size="small" class="sidebar-loading" />
 
        <div v-else-if="visibleChats.length === 0" class="empty-hint sidebar-empty">
          没有找到匹配「{{ chatStore.searchKeyword }}」的对话<br />
          试试其他关键词
        </div>
 
        <div
          v-for="chat in visibleChats"
          v-else
          :key="chat.id"
          class="chat-item"
          :class="{ active: chat.id === activeChatId }"
          @click="$emit('select', chat.id)"
        >
          <div class="chat-item-main">
            <div class="chat-title">{{ chat.title || '新对话' }}</div>
            <!-- 命中消息内容时展示片段,方便确认是不是这次对话 -->
            <div v-if="chat.matchSnippet" class="chat-snippet">
              {{ chat.matchSnippet }}
            </div>
            <div class="chat-meta">
              <span>{{ chat.messageCount || 0 }} 条消息</span>
              <span class="match-badge">{{ matchLabel(chat.matchType) }}</span>
            </div>
          </div>
        </div>
      </template>
 
      <!-- 普通态 -->
      <template v-else>
        <n-spin v-if="loading" size="small" class="sidebar-loading" />
 
        <div v-if="!loading && chats.length === 0" class="empty-hint sidebar-empty">
          还没有对话<br />点击上方「新对话」开始
        </div>
 
        <div
          v-for="chat in chats"
          :key="chat.id"
          class="chat-item"
          :class="{ active: chat.id === activeChatId }"
          @click="$emit('select', chat.id)"
        >
        <div class="chat-item-main">
          <!-- 双击进入重命名,符合桌面端文件管理的直觉 -->
          <n-input
            v-if="editingId === chat.id"
            ref="renameInputRef"
            v-model:value="editingTitle"
            size="tiny"
            @blur="commitRename(chat)"
            @keyup.enter="commitRename(chat)"
            @keyup.esc="cancelRename"
            @click.stop
          />
          <div v-else class="chat-title" @dblclick.stop="startRename(chat)">
            {{ chat.title || '新对话' }}
          </div>
          <div class="chat-meta">
            <span>{{ chat.messageCount || 0 }} 条消息</span>
            <span v-if="chat.collectionNames?.length" class="chat-rag-tag">
              · {{ chat.collectionNames.length }} 个知识库
            </span>
          </div>
        </div>
 
          <n-dropdown
            trigger="click"
            :options="menuOptions"
            @select="(key) => handleMenu(key, chat)"
          >
            <n-button text class="chat-more" @click.stop>⋯</n-button>
          </n-dropdown>
        </div>
      </template>
    </div>
 
    <div class="sidebar-footer">
      <n-dropdown trigger="click" :options="userMenuOptions" @select="handleUserMenu">
        <div class="user-info">
          <div class="user-avatar">{{ avatarText }}</div>
          <div class="user-text">
            <div class="user-name">{{ auth.displayName }}</div>
            <div class="user-role">{{ auth.isAdmin ? '管理员' : '普通用户' }}</div>
          </div>
          <span class="user-more">⋯</span>
        </div>
      </n-dropdown>
    </div>
  </div>
</template>
 
<script setup>
import { computed, nextTick, ref } from 'vue'
import { NButton, NDropdown, NInput, NSpin, useDialog, useMessage } from 'naive-ui'
import { useAuthStore } from '@/stores/authStore'
import { useChatStore } from '@/stores/chatStore'
 
const emit = defineEmits(['select', 'created', 'deleted', 'open-files', 'open-admin-knowledge'])
 
const auth = useAuthStore()
const chatStore = useChatStore()
const message = useMessage()
const dialog = useDialog()
 
const loading = ref(false)
const editingId = ref(null)
const editingTitle = ref('')
const renameInputRef = ref(null)
 
/** 搜索框的本地输入值(与 store 里的已提交关键词区分开) */
const keyword = ref('')
 
const chats = computed(() => chatStore.chats)
const activeChatId = computed(() => chatStore.activeChatId)
 
/** 是否处于搜索态:只要关键词非空就显示搜索结果而非完整列表 */
const isSearching = computed(() => chatStore.searchKeyword.length > 0)
 
/** 搜索态显示结果列表,普通态显示全部会话 */
const visibleChats = computed(() =>
  isSearching.value ? chatStore.searchResults : chatStore.chats
)
 
/**
 * 输入防抖。
 *
 * 「输入即查」若不防抖,每敲一个字都会打一次接口,
 * 而且中文输入法在拼音阶段也会频繁触发 input 事件。
 * 250ms 是打字停顿与响应速度之间的常见折中。
 */
let searchTimer = null
const SEARCH_DEBOUNCE_MS = 250
 
function handleSearchInput() {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  const value = keyword.value
 
  if (!value || !value.trim()) {
    // 清空时立即恢复完整列表,不必等防抖
    if (searchTimer) clearTimeout(searchTimer)
    chatStore.clearSearch()
    return
  }
 
  searchTimer = setTimeout(async () => {
    try {
      await chatStore.searchChats(value)
    } catch (error) {
      message.error(error.message || '搜索失败')
    }
  }, SEARCH_DEBOUNCE_MS)
}
 
function handleClearSearch() {
  if (searchTimer) clearTimeout(searchTimer)
  keyword.value = ''
  chatStore.clearSearch()
}
 
/** 命中类型文案 */
function matchLabel(type) {
  if (type === 'title') return '标题命中'
  if (type === 'both') return '标题+内容'
  return '内容命中'
}
 
const avatarText = computed(() => (auth.displayName || '?').charAt(0).toUpperCase())
 
const menuOptions = [
  { label: '重命名', key: 'rename' },
  { label: '知识库设置', key: 'rag' },
  { type: 'divider', key: 'd1' },
  { label: '删除对话', key: 'delete' }
]
 
const userMenuOptions = computed(() => {
  const options = [{ label: '我的知识库', key: 'files' }]
  // 管理员额外提供全局知识库维护入口。
  // 后端对 /api/files/global/upload 等端点另有 403 校验,
  // 这里的隐藏只是避免普通用户看到无权限的菜单项。
  if (auth.isAdmin) {
    options.push({ label: '全局知识库(管理员)', key: 'admin-knowledge' })
  }
  options.push({ type: 'divider', key: 'd1' })
  options.push({ label: '退出登录', key: 'logout' })
  return options
})
 
/** 由父组件在挂载时调用,避免组件自己触发请求造成时序不确定 */
async function refresh() {
  loading.value = true
  try {
    // 刷新会话列表时退出搜索态,避免停留在旧结果上
    handleClearSearch()
    await chatStore.loadChats()
  } catch (error) {
    message.error(error.message || '加载会话列表失败')
  } finally {
    loading.value = false
  }
}
 
async function handleNewChat() {
  try {
    const chat = await chatStore.createChat({})
    emit('created', chat.id)
  } catch (error) {
    message.error(error.message || '创建会话失败')
  }
}
 
function startRename(chat) {
  editingId.value = chat.id
  editingTitle.value = chat.title
  nextTick(() => {
    // ref 在 v-for 中会是数组
    const input = Array.isArray(renameInputRef.value)
      ? renameInputRef.value[0]
      : renameInputRef.value
    input?.focus?.()
  })
}
 
function cancelRename() {
  editingId.value = null
  editingTitle.value = ''
}
 
async function commitRename(chat) {
  const title = editingTitle.value.trim()
  // 没改动或为空则放弃,避免产生空标题
  if (!title || title === chat.title) {
    cancelRename()
    return
  }
  try {
    await chatStore.renameChat(chat.id, title)
    message.success('已重命名')
  } catch (error) {
    message.error(error.message || '重命名失败')
  } finally {
    cancelRename()
  }
}
 
function handleMenu(key, chat) {
  if (key === 'rename') {
    startRename(chat)
  } else if (key === 'rag') {
    emit('select', chat.id)
    emit('open-files')
  } else if (key === 'delete') {
    dialog.warning({
      title: '删除对话',
      content: `确定删除「${chat.title}」吗?该会话的所有消息都会被一并删除,且无法恢复。`,
      positiveText: '删除',
      negativeText: '取消',
      onPositiveClick: async () => {
        try {
          await chatStore.removeChat(chat.id)
          message.success('已删除')
          emit('deleted', chat.id)
        } catch (error) {
          message.error(error.message || '删除失败')
        }
      }
    })
  }
}
 
function handleUserMenu(key) {
  if (key === 'files') {
    emit('open-files')
  } else if (key === 'admin-knowledge') {
    emit('open-admin-knowledge')
  } else if (key === 'logout') {
    auth.logout()
    emit('deleted', null)
  }
}
 
defineExpose({ refresh })
</script>
 
<style scoped>
.sidebar {
  width: var(--sidebar-width);
  height: 100vh;
  background: var(--bg-sidebar);
  border-right: 1px solid var(--border-color);
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
}
 
.sidebar-header {
  padding: 12px;
}
 
.new-chat-btn {
  justify-content: flex-start;
  font-weight: 500;
}
 
.plus-icon {
  font-size: 17px;
  line-height: 1;
}
 
.sidebar-search {
  padding: 0 12px 8px;
}
 
.search-icon {
  font-size: 14px;
  color: var(--text-muted);
}
 
.chat-snippet {
  font-size: 11.5px;
  color: var(--text-secondary);
  margin-top: 3px;
  /* 片段最多两行,超出用省略号截断 */
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.5;
}
 
.match-badge {
  color: #0f766e;
  margin-left: 6px;
}
 
.sidebar-list {
  flex: 1;
  overflow-y: auto;
  padding: 0 8px 8px;
}
 
.sidebar-loading {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}
 
.sidebar-empty {
  padding: 28px 12px;
  line-height: 1.9;
}
 
.chat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 9px 10px;
  border-radius: 8px;
  cursor: pointer;
  margin-bottom: 2px;
  transition: background 0.12s ease;
}
 
.chat-item:hover {
  background: var(--bg-hover);
}
 
.chat-item.active {
  background: #e3e5e8;
}
 
.chat-item-main {
  flex: 1;
  min-width: 0;
}
 
.chat-title {
  font-size: 13.5px;
  font-weight: 500;
  /* 单行截断,避免长标题把侧边栏撑开 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
 
.chat-meta {
  font-size: 11.5px;
  color: var(--text-muted);
  margin-top: 3px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
 
.chat-rag-tag {
  color: #6b7280;
}
 
.chat-more {
  opacity: 0;
  font-size: 16px;
  line-height: 1;
  padding: 0 4px;
  color: var(--text-secondary);
  transition: opacity 0.12s ease;
}
 
.chat-item:hover .chat-more {
  opacity: 1;
}
 
.sidebar-footer {
  border-top: 1px solid var(--border-color);
  padding: 8px;
}
 
.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px;
  border-radius: 8px;
  cursor: pointer;
}
 
.user-info:hover {
  background: var(--bg-hover);
}
 
.user-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #4b5563;
  color: #fff;
  font-size: 13px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}
 
.user-text {
  flex: 1;
  min-width: 0;
}
 
.user-name {
  font-size: 13px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
 
.user-role {
  font-size: 11px;
  color: var(--text-muted);
}
 
.user-more {
  color: var(--text-muted);
}
</style>