kongdeqiang
2026-10-12 ed3c2513c35efa714f2a377aef55501dd15d1fec
fix: 修改对话模块
6个文件已修改
1287 ■■■■■ 已修改文件
src/api/axios.js 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/api/chatApi.js 51 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/components/ChatView.vue 18 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/components/Sidebar.vue 893 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/stores/chatStore.js 302 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/views/Chat.vue 16 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/api/axios.js
@@ -40,6 +40,13 @@
  (response) => {
    const body = response.data
    // 调用方显式要求「完整响应」时直接返回。
    // 典型场景是文件下载:建议文件名在 Content-Disposition 响应头里,
    // 而下面的解包逻辑只返回 body,会把响应头一起丢掉。
    if (response.config && response.config.__returnFullResponse) {
      return response
    }
    // 二进制响应(图片、文件下载)直接返回 Blob/ArrayBuffer。
    // 不能走下面的 Result 解包:它不是 {code,msg,data} 结构,
    // 且解包逻辑会把它当成普通对象处理。
src/api/chatApi.js
@@ -1,8 +1,15 @@
import http from './axios'
/** 会话列表 */
export function listChats() {
  return http.get('/chats')
/**
 * 会话列表。
 *
 * @param {boolean} archived false=主列表(未归档),true=归档列表
 *
 * 排序由**后端**决定(置顶优先,其次最近活跃),前端只按时间分组、
 * 不重新排序 —— 两边各排一次必然会出现顺序不一致。
 */
export function listChats(archived = false) {
  return http.get('/chats', { params: { archived } })
}
/**
@@ -11,9 +18,12 @@
 * 后端同时匹配标题与消息内容,返回的每一项带:
 *   - matchSnippet:命中处的上下文片段
 *   - matchType:title / message / both
 *
 * @param {boolean} archived 搜索范围,需与当前视图一致:
 *                           在主列表搜不该翻出已归档的对话
 */
export function searchChats(keyword, limit = 30) {
  return http.get('/chats/search', { params: { q: keyword, limit } })
export function searchChats(keyword, limit = 30, archived = false) {
  return http.get('/chats/search', { params: { q: keyword, limit, archived } })
}
/** 新建会话 */
@@ -22,8 +32,9 @@
}
/**
 * 修改会话标题或模型参数。
 * meta 是整体覆盖语义,请提交完整的参数对象。
 * 修改会话:标题 / 模型参数 / 置顶 / 归档。
 * meta 是整体覆盖语义,请提交完整的参数对象;
 * 其余字段是「传了才改」的局部更新语义。
 */
export function updateChat(chatId, payload) {
  return http.put(`/chats/${chatId}`, payload)
@@ -34,6 +45,32 @@
  return http.delete(`/chats/${chatId}`)
}
/**
 * 把会话移入 / 移出分组。
 *
 * 单独一个端点(而不是复用 updateChat):那边约定「字段为 null 表示不修改」,
 * 而「移出分组」正是要把 groupId 置为 null,同一个字段上语义会打架。
 *
 * @param {number|null} groupId 目标分组 id;null = 移出分组
 */
export function moveChatToGroup(chatId, groupId) {
  return http.put(`/chats/${chatId}/group`, { groupId })
}
/**
 * 导出会话为 json / txt / pdf。
 *
 * 用 __returnFullResponse 拿**完整响应**:下载文件名在
 * Content-Disposition 响应头里,而默认的响应拦截器只返回 body。
 */
export function exportChat(chatId, format) {
  return http.get(`/chats/${chatId}/export`, {
    params: { format },
    responseType: 'blob',
    __returnFullResponse: true
  })
}
/** 获取会话的消息树(根节点数组,节点内嵌 children) */
export function listMessages(chatId) {
  return http.get(`/chats/${chatId}/messages`)
src/components/ChatView.vue
@@ -120,15 +120,15 @@
          </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-->
<!--              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"
src/components/Sidebar.vue
@@ -25,84 +25,138 @@
    </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">
        <div v-else-if="chatStore.searchResults.length === 0" class="empty-hint sidebar-empty">
          没有找到匹配「{{ chatStore.searchKeyword }}」的对话<br />
          试试其他关键词
        </div>
        <div
          v-for="chat in visibleChats"
        <ChatListItem
          v-for="chat in chatStore.searchResults"
          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>
          :chat="chat"
          :active="chat.id === activeChatId"
          :options="menuFor(chat)"
          @select="(id) => $emit('select', id)"
          @menu="handleMenu"
        />
      </template>
      <!-- 普通态 -->
      <template v-else>
        <n-spin v-if="loading" size="small" class="sidebar-loading" />
        <!-- ============ 分组区块 ============ -->
        <div class="section">
          <div class="section-head" @click="toggleGroupSection()">
            <span class="chevron" :class="{ collapsed: groupSectionCollapsed }">▾</span>
            <span class="section-title">分组</span>
            <span class="section-count">{{ sections.groups.length || '' }}</span>
            <n-button
              text
              class="section-add"
              title="新建分组"
              @click.stop="openCreateGroup"
            >
              +
            </n-button>
          </div>
          <template v-if="!groupSectionCollapsed">
            <div v-if="sections.groups.length === 0" class="section-empty">
              还没有分组,点右上角「+」新建
            </div>
            <div v-for="group in sections.groups" :key="group.id" class="group-block">
              <div class="group-head" @click="toggleGroup(group.id)">
                <span class="chevron small" :class="{ collapsed: isGroupCollapsed(group.id) }">▾</span>
                <span class="group-name" :title="group.name">{{ group.name }}</span>
                <span class="group-count">{{ group.chats.length }}</span>
                <n-dropdown
                  trigger="click"
                  :options="groupMenuOptions"
                  placement="bottom-end"
                  @select="(key) => handleGroupMenu(key, group)"
                >
                  <n-button text class="group-more" @click.stop>⋯</n-button>
                </n-dropdown>
              </div>
              <template v-if="!isGroupCollapsed(group.id)">
                <div v-if="group.chats.length === 0" class="group-empty">
                  空分组 —— 用对话右上角的「⋯ → 移动到分组」放进来
                </div>
                <ChatListItem
                  v-for="chat in group.chats"
                  v-else
                  :key="chat.id"
                  :chat="chat"
                  :active="chat.id === activeChatId"
                  indented
                  :options="menuFor(chat)"
                  @select="(id) => $emit('select', id)"
                  @menu="handleMenu"
                />
              </template>
            </div>
          </template>
        </div>
        <!-- ============ 置顶(未分组的置顶会话)============ -->
        <div v-if="sections.pinned.length" class="section">
          <div class="section-head static">
            <span class="chevron">▾</span>
            <span class="section-title">置顶</span>
          </div>
          <ChatListItem
            v-for="chat in sections.pinned"
            :key="chat.id"
            :chat="chat"
            :active="chat.id === activeChatId"
            :options="menuFor(chat)"
            @select="(id) => $emit('select', id)"
            @menu="handleMenu"
          />
        </div>
        <!-- ============ 未分组的会话,按时间归类 ============ -->
        <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-for="group in sections.timeGroups" :key="group.key" class="chat-group">
          <div class="chat-group-title">{{ group.label }}</div>
          <ChatListItem
            v-for="chat in group.chats"
            :key="chat.id"
            :chat="chat"
            :active="chat.id === activeChatId"
            :options="menuFor(chat)"
            @select="(id) => $emit('select', id)"
            @menu="handleMenu"
          />
          <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-archive">
      <div class="archive-entry" @click="archiveVisible = true">
        <span class="archive-icon">🗄</span>
        <span class="archive-text">归档对话</span>
        <n-badge
          v-if="archivedCount > 0"
          :value="archivedCount"
          :max="99"
          type="info"
          class="archive-badge"
        />
      </div>
    </div>
    <div class="sidebar-footer">
@@ -117,14 +171,80 @@
        </div>
      </n-dropdown>
    </div>
    <!-- 新建 / 重命名分组共用同一个弹窗 -->
    <n-modal
      v-model:show="groupModal.show"
      preset="card"
      :title="groupModal.id ? '重命名分组' : '新建分组'"
      class="small-modal"
      :bordered="false"
    >
      <n-input
        v-model:value="groupModal.name"
        placeholder="分组名称,例如「工作」「学习资料」"
        maxlength="64"
        show-count
        @keyup.enter="confirmGroupModal"
      />
      <template #footer>
        <div class="modal-footer">
          <n-button size="small" @click="groupModal.show = false">取消</n-button>
          <n-button
            size="small"
            type="primary"
            :loading="groupModal.saving"
            @click="confirmGroupModal"
          >
            保存
          </n-button>
        </div>
      </template>
    </n-modal>
    <!-- 重命名对话 -->
    <n-modal
      v-model:show="renameModal.show"
      preset="card"
      title="重命名对话"
      class="small-modal"
      :bordered="false"
    >
      <n-input
        v-model:value="renameModal.title"
        placeholder="输入新的对话名称"
        maxlength="255"
        show-count
        @keyup.enter="confirmRenameModal"
      />
      <template #footer>
        <div class="modal-footer">
          <n-button size="small" @click="renameModal.show = false">取消</n-button>
          <n-button
            size="small"
            type="primary"
            :loading="renameModal.saving"
            @click="confirmRenameModal"
          >
            保存
          </n-button>
        </div>
      </template>
    </n-modal>
    <ArchivedChatDrawer v-model:show="archiveVisible" @select="handleArchivedSelect" />
  </div>
</template>
<script setup>
import { computed, nextTick, ref } from 'vue'
import { NButton, NDropdown, NInput, NSpin, useDialog, useMessage } from 'naive-ui'
import { computed, ref } from 'vue'
import { NBadge, NButton, NDropdown, NInput, NModal, NSpin, useDialog, useMessage } from 'naive-ui'
import ArchivedChatDrawer from '@/components/ArchivedChatDrawer.vue'
import ChatListItem from '@/components/ChatListItem.vue'
import { useAuthStore } from '@/stores/authStore'
import { useChatStore } from '@/stores/chatStore'
import { buildSidebarSections } from '@/utils/sidebarGroups'
import { usePersistentFlag, usePersistentMap } from '@/utils/uiPrefs'
const emit = defineEmits(['select', 'created', 'deleted', 'open-files', 'open-admin-knowledge'])
@@ -134,31 +254,311 @@
const dialog = useDialog()
const loading = ref(false)
const editingId = ref(null)
const editingTitle = ref('')
const renameInputRef = ref(null)
const archiveVisible = ref(false)
/** 搜索框的本地输入值(与 store 里的已提交关键词区分开) */
const keyword = ref('')
/**
 * 折叠状态:纯视图偏好,存 localStorage,不打扰后端。
 *
 * 「整个分组区块」的开关解构成顶层 ref —— Vue 只会自动解包
 * setup 顶层返回的 ref,如果把它留在对象里(flag.value),
 * 模板里就得写 flag.value.value,极易写错。
 */
const {
  collapsed: groupSectionCollapsed,
  toggle: toggleGroupSection
} = usePersistentFlag('group_section_collapsed', false)
const groupCollapse = usePersistentMap('group_collapsed')
const chats = computed(() => chatStore.chats)
const activeChatId = computed(() => chatStore.activeChatId)
/** 是否处于搜索态:只要关键词非空就显示搜索结果而非完整列表 */
const archivedCount = computed(() => chatStore.archivedChats.length)
const isSearching = computed(() => chatStore.searchKeyword.length > 0)
/** 搜索态显示结果列表,普通态显示全部会话 */
const visibleChats = computed(() =>
  isSearching.value ? chatStore.searchResults : chatStore.chats
/**
 * 侧边栏结构:分组 / 置顶 / 今天 / 昨天 / 更早。
 *
 * 纯计算属性 —— 编排规则都在 buildSidebarSections 里,
 * 组件只负责渲染,规则也能单独测。
 */
const sections = computed(() =>
  buildSidebarSections(chats.value, chatStore.chatGroups)
)
function isGroupCollapsed(id) {
  return groupCollapse.isCollapsed(id)
}
function toggleGroup(id) {
  groupCollapse.toggle(id)
}
const avatarText = computed(() => (auth.displayName || '?').charAt(0).toUpperCase())
// ---------------- 弹窗状态 ----------------
const groupModal = ref({ show: false, id: null, name: '', saving: false })
const renameModal = ref({ show: false, id: null, title: '', saving: false })
function openCreateGroup() {
  groupModal.value = { show: true, id: null, name: '', saving: false }
}
function openRenameGroup(group) {
  groupModal.value = { show: true, id: group.id, name: group.name, saving: false }
}
async function confirmGroupModal() {
  const name = groupModal.value.name.trim()
  if (!name) {
    message.warning('分组名不能为空')
    return
  }
  groupModal.value.saving = true
  try {
    if (groupModal.value.id) {
      await chatStore.renameChatGroup(groupModal.value.id, name)
      message.success('分组已重命名')
    } else {
      await chatStore.createChatGroup(name)
      message.success('分组已创建')
    }
    groupModal.value.show = false
  } catch (error) {
    // 重名等业务错误由后端给出人话提示,这里直接展示
    message.error(error.message || '操作失败')
  } finally {
    groupModal.value.saving = false
  }
}
// ---------------- 菜单 ----------------
/**
 * 输入防抖。
 * 每条会话的菜单。
 *
 * 「输入即查」若不防抖,每敲一个字都会打一次接口,
 * 而且中文输入法在拼音阶段也会频繁触发 input 事件。
 * 250ms 是打字停顿与响应速度之间的常见折中。
 * 「移动到分组」的子菜单列出「未分组 + 所有分组」,当前所在的那一项打勾 ——
 * 用户不必先记住它在哪个分组里。
 */
function menuFor(chat) {
  const moveChildren = [
    {
      label: chat.groupId == null ? '✓ 未分组' : '未分组',
      key: 'move-none'
    },
    ...chatStore.chatGroups.map((group) => ({
      label: (chat.groupId === group.id ? '✓ ' : '') + group.name,
      key: 'move-' + group.id
    }))
  ]
  return [
    { label: chat.pinned ? '取消置顶' : '置顶', key: 'pin' },
    { label: '重命名', key: 'rename' },
    { label: '移动到分组', key: 'move', children: moveChildren },
    {
      label: '下载',
      key: 'download',
      children: [
        { label: 'JSON(含全部分支)', key: 'download-json' },
        { label: 'TXT(纯文本)', key: 'download-txt' },
        { label: 'PDF(带页码排版)', key: 'download-pdf' }
      ]
    },
    { label: '归档', key: 'archive' },
    { type: 'divider', key: 'd1' },
    { label: '知识库设置', key: 'rag' },
    { label: '删除对话', key: 'delete', props: { style: 'color: #d03050;' } }
  ]
}
const groupMenuOptions = [
  { label: '重命名分组', key: 'rename' },
  { label: '删除分组', key: 'delete', props: { style: 'color: #d03050;' } }
]
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 handleMenu(key, chat) {
  if (key.startsWith('move-')) {
    const raw = key.slice('move-'.length)
    const groupId = raw === 'none' ? null : Number(raw)
    await moveChat(chat, groupId)
    return
  }
  switch (key) {
    case 'pin':
      await togglePin(chat)
      break
    case 'rename':
      renameModal.value = { show: true, id: chat.id, title: chat.title || '', saving: false }
      break
    case 'download-json':
      await download(chat, 'json')
      break
    case 'download-txt':
      await download(chat, 'txt')
      break
    case 'download-pdf':
      await download(chat, 'pdf')
      break
    case 'archive':
      archive(chat)
      break
    case 'rag':
      emit('select', chat.id)
      emit('open-files')
      break
    case 'delete':
      confirmDelete(chat)
      break
    default:
      break
  }
}
async function handleGroupMenu(key, group) {
  if (key === 'rename') {
    openRenameGroup(group)
    return
  }
  if (key === 'delete') {
    dialog.warning({
      title: '删除分组',
      content: `确定删除分组「${group.name}」吗?组内的 ${group.chats.length} 条对话`
        + '**不会被删除**,它们会回到「未分组」,继续按时间归类。',
      positiveText: '删除分组',
      negativeText: '取消',
      onPositiveClick: async () => {
        try {
          const moved = await chatStore.deleteChatGroup(group.id)
          message.success(moved > 0
            ? `分组已删除,${moved} 条对话已回到未分组`
            : '分组已删除')
        } catch (error) {
          message.error(error.message || '删除分组失败')
          return false
        }
        return true
      }
    })
  }
}
async function moveChat(chat, groupId) {
  if ((chat.groupId ?? null) === groupId) {
    return
  }
  try {
    await chatStore.moveChatToGroup(chat.id, groupId)
    const name = groupId == null
      ? '未分组'
      : chatStore.chatGroups.find((g) => g.id === groupId)?.name || '分组'
    message.success(`已移动到「${name}」`)
  } catch (error) {
    message.error(error.message || '移动失败')
  }
}
async function togglePin(chat) {
  try {
    await chatStore.setPinned(chat.id, !chat.pinned)
    message.success(chat.pinned ? '已取消置顶' : '已置顶')
  } catch (error) {
    message.error(error.message || '操作失败')
  }
}
const downloading = ref(false)
async function download(chat, format) {
  if (downloading.value) return
  downloading.value = true
  message.loading(`正在导出 ${format.toUpperCase()}…`, { duration: 1200 })
  try {
    const filename = await chatStore.exportChat(chat.id, format)
    message.success(`已导出 ${filename}`)
  } catch (error) {
    message.error(error.message || '导出失败')
  } finally {
    downloading.value = false
  }
}
function archive(chat) {
  dialog.create({
    title: '归档对话',
    content: `「${chat.title || '新对话'}」将从列表收起。消息与知识库绑定都会保留,`
      + '之后可以在「归档对话」里找到并恢复。',
    positiveText: '归档',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await chatStore.setArchived(chat.id, true)
        message.success('已归档,可在「归档对话」中查看')
      } catch (error) {
        message.error(error.message || '归档失败')
        return false
      }
      return true
    }
  })
}
function confirmDelete(chat) {
  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 || '删除失败')
        return false
      }
      return true
    }
  })
}
async function confirmRenameModal() {
  const title = renameModal.value.title.trim()
  if (!title) {
    message.warning('名称不能为空')
    return
  }
  renameModal.value.saving = true
  try {
    await chatStore.renameChat(renameModal.value.id, title)
    message.success('已重命名')
    renameModal.value.show = false
  } catch (error) {
    message.error(error.message || '重命名失败')
  } finally {
    renameModal.value.saving = false
  }
}
// ---------------- 搜索 ----------------
let searchTimer = null
const SEARCH_DEBOUNCE_MS = 250
@@ -169,7 +569,6 @@
  const value = keyword.value
  if (!value || !value.trim()) {
    // 清空时立即恢复完整列表,不必等防抖
    if (searchTimer) clearTimeout(searchTimer)
    chatStore.clearSearch()
    return
@@ -190,47 +589,9 @@
  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
  }
function handleArchivedSelect(id) {
  archiveVisible.value = false
  emit('select', id)
}
async function handleNewChat() {
@@ -242,65 +603,6 @@
  }
}
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')
@@ -309,6 +611,23 @@
  } else if (key === 'logout') {
    auth.logout()
    emit('deleted', null)
  }
}
/** 由父组件在挂载时调用,避免组件自己触发请求造成时序不确定 */
async function refresh() {
  loading.value = true
  try {
    handleClearSearch()
    await Promise.all([
      chatStore.loadChats(),
      chatStore.loadArchivedChats(),
      chatStore.loadChatGroups()
    ])
  } catch (error) {
    message.error(error.message || '加载会话列表失败')
  } finally {
    loading.value = false
  }
}
@@ -349,27 +668,147 @@
  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;
}
/* ---------- 分组区块 ---------- */
.section {
  margin-bottom: 6px;
}
.section-head {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 10px;
  border-radius: 6px;
  cursor: pointer;
  user-select: none;
}
.section-head:hover {
  background: var(--bg-hover);
}
.section-head.static {
  cursor: default;
}
.section-head.static:hover {
  background: transparent;
}
.section-title {
  font-size: 11.5px;
  font-weight: 600;
  letter-spacing: 0.3px;
  color: var(--text-muted);
}
.section-count {
  font-size: 11px;
  color: var(--text-muted);
}
.section-add {
  margin-left: auto;
  font-size: 15px;
  line-height: 1;
  padding: 0 4px;
  color: var(--text-secondary);
}
.section-add:hover {
  color: #2080f0;
}
.section-empty,
.group-empty {
  padding: 6px 10px 8px 26px;
  font-size: 11.5px;
  color: var(--text-muted);
  line-height: 1.7;
}
/* 折叠箭头:默认朝下,折叠时转 -90 度 */
.chevron {
  display: inline-block;
  width: 12px;
  font-size: 10px;
  color: var(--text-muted);
  transition: transform 0.15s ease;
}
.chevron.collapsed {
  transform: rotate(-90deg);
}
.chevron.small {
  font-size: 9px;
}
.group-block {
  margin-bottom: 2px;
}
.group-head {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 10px 6px 14px;
  border-radius: 6px;
  cursor: pointer;
  user-select: none;
}
.group-head:hover {
  background: var(--bg-hover);
}
.group-name {
  font-size: 12.5px;
  font-weight: 500;
  color: var(--text-primary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.group-count {
  font-size: 11px;
  color: var(--text-muted);
}
.group-more {
  margin-left: auto;
  font-size: 14px;
  line-height: 1;
  padding: 0 4px;
  color: var(--text-secondary);
  opacity: 0;
  transition: opacity 0.12s ease;
}
.group-head:hover .group-more {
  opacity: 1;
}
/* ---------- 时间分组 ---------- */
.chat-group-title {
  position: sticky;
  top: 0;
  z-index: 1;
  padding: 8px 10px 4px;
  font-size: 11px;
  font-weight: 600;
  letter-spacing: 0.3px;
  color: var(--text-muted);
  background: var(--bg-sidebar);
}
.sidebar-loading {
@@ -383,64 +822,36 @@
  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;
/* ---------- 归档入口 ---------- */
.sidebar-archive {
  padding: 4px 8px 0;
}
.chat-item:hover {
.archive-entry {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 10px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 12.5px;
  color: var(--text-secondary);
}
.archive-entry:hover {
  background: var(--bg-hover);
}
.chat-item.active {
  background: #e3e5e8;
.archive-icon {
  font-size: 13px;
}
.chat-item-main {
.archive-text {
  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);
@@ -495,4 +906,14 @@
.user-more {
  color: var(--text-muted);
}
.small-modal {
  width: 420px;
}
.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>
src/stores/chatStore.js
@@ -1,6 +1,8 @@
import { defineStore } from 'pinia'
import { computed, reactive, ref } from 'vue'
import * as chatApi from '@/api/chatApi'
import * as chatGroupApi from '@/api/chatGroupApi'
import { filenameFromDisposition, saveBlob } from '@/utils/download'
import { useAuthStore } from './authStore'
import { streamChat as openSseStream } from '@/utils/sse'
import {
@@ -31,6 +33,27 @@
 */
export const useChatStore = defineStore('chat', () => {
  const chats = ref([])
  /**
   * 已归档的会话。
   *
   * 单独一份而不是和 chats 混在一起靠字段过滤:
   * 主列表与归档列表是**两个视图**,各自有独立的加载时机与搜索关键词,
   * 混在一起后每次渲染都要过滤,很容易出现「归档了但主列表还显示」这类
   * 状态不一致。分开存放,归档动作就是把元素从一个数组搬到另一个。
   */
  const archivedChats = ref([])
  /** 归档列表是否已加载过 —— 用于区分「确实没有归档」和「还没查」 */
  const archiveLoaded = ref(false)
  /**
   * 用户自建的分组(文件夹)。
   *
   * 只存分组本身;「哪些会话在哪个分组里」由每条会话的 groupId 决定,
   * 前端按它分桶。这样移动会话只需要刷新会话列表,不必再拉一次分组。
   */
  const chatGroups = ref([])
  const activeChatId = ref(null)
  const tree = ref([])
@@ -49,7 +72,12 @@
  const path = computed(() => buildPath(tree.value, selections))
  const activeChat = computed(
    () => chats.value.find((chat) => chat.id === activeChatId.value) || null
    () =>
      chats.value.find((chat) => chat.id === activeChatId.value) ||
      // 归档的会话不在主列表里,但用户可能刚从「归档对话」里点开它 ——
      // 找不到就返回 null 会让标题栏、模型参数抽屉一起变空
      archivedChats.value.find((chat) => chat.id === activeChatId.value) ||
      null
  )
  // ============================================================
@@ -57,65 +85,145 @@
  // ============================================================
  async function loadChats() {
    chats.value = await chatApi.listChats()
    chats.value = await chatApi.listChats(false)
    return chats.value
  }
  /** 加载归档列表 */
  async function loadArchivedChats() {
    archivedChats.value = await chatApi.listChats(true)
    archiveLoaded.value = true
    return archivedChats.value
  }
  // ---------------- 自建分组 ----------------
  async function loadChatGroups() {
    chatGroups.value = await chatGroupApi.listChatGroups()
    return chatGroups.value
  }
  async function createChatGroup(name) {
    const group = await chatGroupApi.createChatGroup(name)
    chatGroups.value.push(group)
    return group
  }
  async function renameChatGroup(groupId, name) {
    const updated = await chatGroupApi.renameChatGroup(groupId, name)
    const index = chatGroups.value.findIndex((g) => g.id === groupId)
    if (index !== -1) {
      chatGroups.value[index] = updated
    }
    return updated
  }
  /**
   * 删除分组:组内会话回到「未分组」。
   *
   * 必须重新拉会话列表 —— 会话本身没变(还在原处、还是原来的时间),
   * 但它们的 groupId 已经被后端清空,不刷新的话它们会挂在一个
   * 已经不存在分组下而整个消失。
   */
  async function deleteChatGroup(groupId) {
    const result = await chatGroupApi.deleteChatGroup(groupId)
    chatGroups.value = chatGroups.value.filter((g) => g.id !== groupId)
    await loadChats()
    return result?.movedChats ?? 0
  }
  /** 把会话移入 / 移出分组(groupId 传 null 表示移出) */
  async function moveChatToGroup(chatId, groupId) {
    const updated = await chatApi.moveChatToGroup(chatId, groupId)
    replaceInLists(updated)
    // 分组数字要跟着变,同时刷新顺序(后端仍按置顶/活跃排序)
    await Promise.all([loadChats(), loadChatGroups()])
    return updated
  }
  // ---------------- 搜索历史对话 ----------------
  /** 搜索关键词;为空表示未处于搜索态 */
  const searchKeyword = ref('')
  /** 搜索结果(ChatDTO 数组,带 matchSnippet / matchType) */
  const searchResults = ref([])
  const searching = ref(false)
  /**
   * 请求序号。
   * 建一个独立的搜索器。
   *
   * 搜索是「输入即查」,慢的旧请求可能后于新请求返回,
   * 直接把旧结果写进去就会出现「输入了新词却显示旧结果」。
   * 每次发起递增并记住序号,回来时对不上就丢弃。
   * 主列表与归档列表要各有一份关键词与结果,所以做成工厂而不是两组变量:
   * 两组变量意味着「请求序号、竞态丢弃、loading 状态」这套逻辑要写两遍,
   * 而它恰恰是最容易写漏、写错的部分。
   */
  let searchSeq = 0
  function createSearcher(archived) {
    /** 搜索关键词;为空表示未处于搜索态 */
    const keyword = ref('')
    /** 搜索结果(ChatDTO 数组,带 matchSnippet / matchType) */
    const results = ref([])
    const loading = ref(false)
    /**
     * 请求序号。搜索是「输入即查」,慢的旧请求可能后于新请求返回,
     * 直接把旧结果写进去就会出现「输入了新词却显示旧结果」。
     */
    let seq = 0
  async function searchChats(keyword) {
    const kw = (keyword || '').trim()
    searchKeyword.value = kw
    async function run(raw) {
      const kw = (raw || '').trim()
      keyword.value = kw
    if (!kw) {
      searchResults.value = []
      searching.value = false
      return []
    }
    const seq = ++searchSeq
    searching.value = true
    try {
      const results = await chatApi.searchChats(kw)
      if (seq !== searchSeq) {
        // 已有更新的请求发出,丢弃这次的结果
        return searchResults.value
      if (!kw) {
        results.value = []
        loading.value = false
        return []
      }
      searchResults.value = Array.isArray(results) ? results : []
      return searchResults.value
    } catch (error) {
      if (seq === searchSeq) {
        searchResults.value = []
      }
      throw error
    } finally {
      if (seq === searchSeq) {
        searching.value = false
      const mine = ++seq
      loading.value = true
      try {
        const found = await chatApi.searchChats(kw, 30, archived)
        if (mine !== seq) {
          // 已有更新的请求发出,丢弃这次的结果
          return results.value
        }
        results.value = Array.isArray(found) ? found : []
        return results.value
      } catch (error) {
        if (mine === seq) {
          results.value = []
        }
        throw error
      } finally {
        if (mine === seq) {
          loading.value = false
        }
      }
    }
    function clear() {
      seq++   // 让在途请求失效
      keyword.value = ''
      results.value = []
      loading.value = false
    }
    return { keyword, results, loading, run, clear }
  }
  /** 退出搜索态,恢复显示完整会话列表 */
  function clearSearch() {
    searchSeq++   // 让在途请求失效
    searchKeyword.value = ''
    searchResults.value = []
    searching.value = false
  }
  const mainSearch = createSearcher(false)
  const archiveSearch = createSearcher(true)
  // 主列表搜索:保留扁平命名,侧边栏直接用这些。
  //
  // 注意 Pinia 只对 **顶层** 返回的 ref 做自动解包:这里以顶层成员暴露,
  // 组件里就能直接 `chatStore.searchKeyword`;如果把整个 searcher 对象
  // 暴露出去,里面每个 ref 都得写 `.value`,极易写错。
  const searchKeyword = mainSearch.keyword
  const searchResults = mainSearch.results
  const searching = mainSearch.loading
  const searchChats = mainSearch.run
  const clearSearch = mainSearch.clear
  // 归档列表的搜索:同样以顶层成员暴露
  const archiveKeyword = archiveSearch.keyword
  const archiveResults = archiveSearch.results
  const archiveSearching = archiveSearch.loading
  const searchArchive = archiveSearch.run
  const clearArchiveSearch = archiveSearch.clear
  async function createChat(payload = {}) {
    const chat = await chatApi.createChat(payload)
@@ -124,34 +232,93 @@
    return chat
  }
  async function renameChat(chatId, title) {
    const updated = await chatApi.updateChat(chatId, { title })
    const index = chats.value.findIndex((chat) => chat.id === chatId)
    if (index !== -1) {
      // 用替换而不是 Object.assign:保证所有字段都与后端一致
      chats.value[index] = updated
  /**
   * 用服务端返回的最新对象替换本地缓存里的同一条。
   *
   * 同时查两份列表:一条会话可能既不在主列表(已归档)也不在归档列表
   * (刚恢复),只查 chats 会让归档对话的重命名「看起来没生效」。
   */
  function replaceInLists(updated) {
    for (const list of [chats.value, archivedChats.value]) {
      const index = list.findIndex((chat) => chat.id === updated.id)
      if (index !== -1) {
        // 用替换而不是 Object.assign:保证所有字段都与后端一致
        list[index] = updated
      }
    }
    return updated
  }
  async function renameChat(chatId, title) {
    return replaceInLists(await chatApi.updateChat(chatId, { title }))
  }
  async function updateChatMeta(chatId, meta) {
    const updated = await chatApi.updateChat(chatId, { meta })
    const index = chats.value.findIndex((chat) => chat.id === chatId)
    if (index !== -1) {
      chats.value[index] = updated
    }
    return replaceInLists(await chatApi.updateChat(chatId, { meta }))
  }
  /**
   * 置顶 / 取消置顶。
   *
   * 操作完重新拉取主列表,而不是本地改一个字段了事:
   * 置顶会改变这条会话在列表中的**位置**(进入置顶区),
   * 而排序规则在后端(pinned DESC, pinned_at DESC, updated_at DESC)。
   * 本地自己排一遍就会出现「前端顺序和后端顺序不一致」,
   * 刷新一次又跳回去 —— 让唯一的排序权威留在后端,前端只负责分组。
   */
  async function setPinned(chatId, pinned) {
    const updated = await chatApi.updateChat(chatId, { pinned })
    replaceInLists(updated)
    await loadChats()
    return updated
  }
  /**
   * 归档 / 取消归档。
   *
   * 归档是一次「跨列表搬移」:主列表少一条、归档列表多一条。
   * 两份列表都重新拉,保证两边都一致(归档列表还要按归档时间倒序)。
   */
  async function setArchived(chatId, archived) {
    const updated = await chatApi.updateChat(chatId, { archived })
    await Promise.all([loadChats(), loadArchivedChats()])
    return updated
  }
  async function removeChat(chatId) {
    await chatApi.deleteChat(chatId)
    chats.value = chats.value.filter((chat) => chat.id !== chatId)
    archivedChats.value = archivedChats.value.filter((chat) => chat.id !== chatId)
    // 搜索结果里也可能残留这一条,一并清掉,避免点进去报 404
    mainSearch.results.value = mainSearch.results.value.filter((chat) => chat.id !== chatId)
    archiveSearch.results.value = archiveSearch.results.value.filter((chat) => chat.id !== chatId)
    if (activeChatId.value === chatId) {
      activeChatId.value = null
      tree.value = []
      clearSelections()
    }
  }
  /**
   * 下载会话为 json / txt / pdf。
   *
   * 文件名优先用服务端 Content-Disposition 里的建议名(它带了标题与时间戳),
   * 拿不到时才用本地拼的兜底名。
   *
   * @returns {Promise<string>} 实际保存的文件名
   */
  async function exportChat(chatId, format) {
    const response = await chatApi.exportChat(chatId, format)
    const blob = response.data
    const disposition = response.headers?.['content-disposition']
    const chat = chats.value.find((c) => c.id === chatId)
      || archivedChats.value.find((c) => c.id === chatId)
    const fallback = `${chat?.title || '对话'}_${chatId}.${format}`
    const filename = filenameFromDisposition(disposition) || fallback
    saveBlob(blob, filename)
    return filename
  }
  // ============================================================
@@ -483,6 +650,11 @@
              await loadMessages(chatId, true)
            }
            await loadChats()
            // 会话被归档时不在主列表里,标题等变化只体现在归档列表,
            // 不刷新就会出现「在归档对话里聊完,标题还是旧的」
            if (archivedChats.value.some((chat) => chat.id === chatId)) {
              await loadArchivedChats()
            }
          } catch {
            // 刷新失败不影响已渲染的内容,静默处理
          }
@@ -570,6 +742,9 @@
  return {
    // state
    chats,
    archivedChats,
    archiveLoaded,
    chatGroups,
    activeChatId,
    tree,
    streaming,
@@ -582,14 +757,29 @@
    activeChat,
    // actions
    loadChats,
    loadArchivedChats,
    loadChatGroups,
    createChatGroup,
    renameChatGroup,
    deleteChatGroup,
    moveChatToGroup,
    searchKeyword,
    searchResults,
    searching,
    searchChats,
    clearSearch,
    // 归档列表的搜索(独立的另一套状态)
    archiveKeyword,
    archiveResults,
    archiveSearching,
    searchArchive,
    clearArchiveSearch,
    createChat,
    renameChat,
    updateChatMeta,
    setPinned,
    setArchived,
    exportChat,
    removeChat,
    loadMessages,
    switchBranch,
src/views/Chat.vue
@@ -84,11 +84,19 @@
// 兜底:路由指向不存在的会话时提示并清理
watch(chatId, async (id) => {
  if (!id) return
  const exists = chatStore.chats.some((chat) => chat.id === id)
  if (!exists && chatStore.chats.length > 0) {
    message.warning('该对话不存在或已被删除')
    router.replace('/c')
  const inMain = chatStore.chats.some((chat) => chat.id === id)
  // 归档的会话不在主列表里,但仍然是有效会话 ——
  // 只看主列表会把「打开一个归档对话」误判成「对话已被删除」
  const inArchive = chatStore.archivedChats.some((chat) => chat.id === id)
  // 归档列表还没加载完时不做判定:宁可晚一点提示,也不要误报
  if (inMain || inArchive || !chatStore.archiveLoaded || chatStore.chats.length === 0) {
    return
  }
  message.warning('该对话不存在或已被删除')
  router.replace('/c')
})
</script>