kongdeqiang
2026-10-12 ccf1a44c001e233c158bd168dc2d0d96721af929
fix: 修改后台
11个文件已修改
368 ■■■■■ 已修改文件
pom.xml 25 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/config/SecurityConfig.java 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/config/StartupDiagnostics.java 4 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/controller/ChatController.java 87 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/dto/req/ChatUpdateRequest.java 13 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/dto/resp/ChatDTO.java 23 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/entity/Chat.java 33 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/service/ChatService.java 37 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/custom/webui/service/impl/ChatServiceImpl.java 104 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/resources/application.yml 20 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/resources/db/h2-schema.sql 15 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
pom.xml
@@ -91,6 +91,31 @@
            <optional>true</optional>
        </dependency>
        <!--
          PDF 导出(Apache PDFBox,Apache-2.0)
          为什么是 PDFBox 而不是 iText / openhtmltopdf:
            - iText 是 AGPL,闭源分发要买商业授权,本项目不适合
            - openhtmltopdf 依赖链很长(自己也要拖 PDFBox),而我们只需要
              「标题 + 元信息 + 若干条消息」这一种版式,用不着 HTML/CSS 排版引擎
            - PDFBox 只多两个传递依赖(fontbox、pdfbox-io),且能直接嵌入
              系统中文字体并按子集裁剪,一个中文对话导出的 PDF 通常只有几十 KB
          commons-logging 为什么要显式钉版本:pdfbox-parent 里声明的是 1.3.3,
          而本项目离线仓库里只有 1.3.4 —— 不钉的话离线构建会解析失败。
          两者是同一主线的补丁版本,行为兼容。
        -->
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>3.0.3</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.3.4</version>
        </dependency>
        <!-- 测试 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
src/main/java/com/custom/webui/config/SecurityConfig.java
@@ -103,8 +103,11 @@
                "http://10.*.*.*:*"));
        config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
        config.setAllowedHeaders(List.of("*"));
        // SSE 不需要暴露额外头,保留 Content-Type 便于前端判断
        config.setExposedHeaders(List.of("Content-Type"));
        // 浏览器只允许前端脚本读取**显式暴露**的响应头。
        // 导出接口的建议文件名就放在 Content-Disposition 里:
        // 不暴露的话,即使响应里有这个头前端也读不到,
        // 只能退回本地拼的文件名 —— 中文标题与时间戳就丢了。
        config.setExposedHeaders(List.of("Content-Type", "Content-Disposition"));
        config.setAllowCredentials(true);
        config.setMaxAge(3600L);
src/main/java/com/custom/webui/config/StartupDiagnostics.java
@@ -84,6 +84,7 @@
    private final StorageProperties storageProperties;
    private final LlmProperties llmProperties;
    private final ObjectMapper objectMapper;
    private final com.custom.webui.util.PdfFontSupport pdfFontSupport;
    // ------------------------------------------------------------------
    // 一、存储位置
@@ -100,6 +101,9 @@
        log.info("  配置值       : {}", storageProperties.getLocation());
        log.info("  实际上传目录 : {}", uploadRoot);
        log.info("  目录状态     : {}", describe(uploadRoot));
        // 顺便报一下 PDF 导出的字体:找不到中文字体时 PDF 导出会失败,
        // 而这件事在启动时说一句,比等用户点了「下载 PDF」再报错友好得多
        log.info("  导出自检     : {}", pdfFontSupport.describe());
        log.info("=".repeat(66));
    }
src/main/java/com/custom/webui/controller/ChatController.java
@@ -1,13 +1,17 @@
package com.custom.webui.controller;
import com.custom.webui.dto.req.ChatCreateRequest;
import com.custom.webui.dto.req.ChatGroupMoveRequest;
import com.custom.webui.dto.req.ChatUpdateRequest;
import com.custom.webui.dto.resp.ChatDTO;
import com.custom.webui.dto.resp.Result;
import com.custom.webui.security.CurrentUser;
import com.custom.webui.service.ChatExportService;
import com.custom.webui.service.ChatService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@@ -18,6 +22,8 @@
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
/** 会话 CRUD 接口,对应侧边栏的对话列表。 */
@@ -27,11 +33,20 @@
public class ChatController {
    private final ChatService chatService;
    private final ChatExportService chatExportService;
    /** 当前用户的全部会话,按最近活跃排序 */
    /**
     * 当前用户的会话列表。
     *
     * <p>排序由后端固定为「置顶优先,其次最近活跃」—— 前端只负责按时间分组,
     * 不重新排序,避免两边规则不一致导致列表顺序跳动。
     *
     * @param archived false(默认)= 主列表;true = 归档列表
     */
    @GetMapping
    public Result<List<ChatDTO>> list() {
        return Result.success(chatService.listByUser(CurrentUser.requireUserId()));
    public Result<List<ChatDTO>> list(
            @RequestParam(value = "archived", defaultValue = "false") boolean archived) {
        return Result.success(chatService.listByUser(CurrentUser.requireUserId(), archived));
    }
    /**
@@ -40,13 +55,17 @@
     * <p>同时匹配会话标题与消息内容 —— 用户往往记得「聊过什么」却想不起原话,
     * 而标题只是首条提问的截断,只搜标题会漏掉大量结果。
     *
     * @param q     关键词;为空时返回空列表
     * @param limit 最多返回条数,默认 30,上限 100
     * @param q        关键词;为空时返回空列表
     * @param limit    最多返回条数,默认 30,上限 100
     * @param archived 搜索范围:默认只在未归档的对话里搜,
     *                 在「归档对话」界面里搜则传 true 只搜归档的
     */
    @GetMapping("/search")
    public Result<List<ChatDTO>> search(@RequestParam("q") String q,
                                       @RequestParam(value = "limit", defaultValue = "30") int limit) {
        return Result.success(chatService.search(CurrentUser.requireUserId(), q, limit));
    public Result<List<ChatDTO>> search(
            @RequestParam("q") String q,
            @RequestParam(value = "limit", defaultValue = "30") int limit,
            @RequestParam(value = "archived", defaultValue = "false") boolean archived) {
        return Result.success(chatService.search(CurrentUser.requireUserId(), q, limit, archived));
    }
    /** 新建会话 */
@@ -56,7 +75,12 @@
        return Result.success(chatService.create(CurrentUser.requireUserId(), request));
    }
    /** 修改会话标题或模型参数(temperature / top_p / systemPrompt / modelName) */
    /**
     * 修改会话:标题、模型参数、置顶、归档。
     *
     * <p>字段为 null 表示不改,因此「重命名」「置顶」「归档」都复用这一个接口,
     * 前端只提交需要变化的字段。
     */
    @PutMapping("/{id}")
    public Result<ChatDTO> update(@PathVariable Long id,
                                 @Valid @RequestBody ChatUpdateRequest request) {
@@ -69,4 +93,49 @@
        chatService.delete(CurrentUser.requireUserId(), id);
        return Result.success();
    }
    /**
     * 把会话移入 / 移出分组。
     *
     * <p>body 里 {@code groupId: null} 表示移出分组(回到未分组、继续按时间归类)。
     * 单独一个端点是因为 {@code PUT /api/chats/{id}} 的约定是
     * 「字段为 null = 不修改」,两者在同一个字段上会打架。
     */
    @PutMapping("/{id}/group")
    public Result<ChatDTO> moveToGroup(@PathVariable Long id,
                                       @RequestBody(required = false) ChatGroupMoveRequest request) {
        return Result.success(chatService.moveToGroup(
                CurrentUser.requireUserId(), id, request == null ? null : request.getGroupId()));
    }
    /**
     * 导出会话为 json / txt / pdf。
     *
     * <p>用 {@link ResponseEntity} 而不是统一的 {@code Result} 包装:
     * 导出要返回的是**文件本体**,套一层 JSON 就没法直接保存了
     * (这与 SSE 不走统一包装是同一个理由)。
     */
    @GetMapping("/{id}/export")
    public ResponseEntity<byte[]> export(
            @PathVariable Long id,
            @RequestParam(value = "format", defaultValue = "txt") String format) {
        ChatExportService.ExportFile file = chatExportService.export(
                CurrentUser.requireUserId(), id, ChatExportService.Format.parse(format));
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, file.contentType())
                // filename 用 ASCII 兜底,filename* 用 UTF-8 编码给支持的标准浏览器用。
                // 中文标题不这么处理会出现乱码或下载失败(RFC 5987)。
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"export." + extOf(file.filename()) + "\"; filename*=UTF-8''"
                                + URLEncoder.encode(file.filename(), StandardCharsets.UTF_8)
                                .replace("+", "%20"))
                .header(HttpHeaders.CACHE_CONTROL, "no-store")
                .body(file.data());
    }
    private String extOf(String filename) {
        int dot = filename.lastIndexOf('.');
        return dot >= 0 ? filename.substring(dot + 1) : "bin";
    }
}
src/main/java/com/custom/webui/dto/req/ChatUpdateRequest.java
@@ -5,7 +5,7 @@
import lombok.Data;
/**
 * 修改会话请求体,用于改标题和/或改模型参数。
 * 修改会话请求体,用于改标题、模型参数、置顶与归档。
 *
 * <p>字段为 null 表示「不修改」,因此前端做局部更新时只传需要改的字段即可。
 */
@@ -17,4 +17,15 @@
    @Valid
    private ChatMetaRequest meta;
    /**
     * 置顶开关。null = 不改。
     *
     * <p>注意:置顶**不会**刷新 {@code updatedAt} ——
     * 否则置顶一下就会被判定成「刚刚活跃」,在时间分组里从「更早」跳到「今天」。
     */
    private Boolean pinned;
    /** 归档开关。null = 不改。归档同样是软收起,不刷新 updatedAt */
    private Boolean archived;
}
src/main/java/com/custom/webui/dto/resp/ChatDTO.java
@@ -27,6 +27,29 @@
    private LocalDateTime updatedAt;
    /**
     * 是否置顶。
     *
     * <p>前端据此把会话放进最上方的「置顶」分组,并在标题前显示图钉。
     */
    private Boolean pinned;
    /** 置顶时间,置顶分组按它倒序(与活跃时间无关) */
    private LocalDateTime pinnedAt;
    /** 是否已归档;主列表只取 archived=false,归档列表只取 true */
    private Boolean archived;
    private LocalDateTime archivedAt;
    /**
     * 所属自建分组 id,{@code null} = 未分组。
     *
     * <p>前端就拿这个字段把会话挂到对应分组下,不需要再为「某个分组里有哪些会话」
     * 单独发请求 —— 会话列表本来就一次返回了全部。
     */
    private Long groupId;
    /** 会话内消息总数,用于侧边栏展示 */
    private Long messageCount;
src/main/java/com/custom/webui/entity/Chat.java
@@ -29,6 +29,39 @@
     */
    private String meta;
    /**
     * 是否置顶(1=置顶)。
     *
     * <p>用 {@code Boolean} 而不是 {@code boolean}:MyBatis-Plus 更新时
     * 只把非 null 字段写进 SQL,所以 partial update 场景下 null 才代表「不修改」。
     */
    private Boolean pinned;
    /**
     * 置顶时间,置顶区按它倒序。
     *
     * <p>不复用 {@code updatedAt}:置顶区内部要按「置顶的先后」排,
     * 而 updatedAt 会随新消息变化,导致置顶的老对话聊一句就跳到最前面。
     */
    private LocalDateTime pinnedAt;
    /** 是否归档(1=已归档,主列表不显示,但数据全部保留) */
    private Boolean archived;
    /** 归档时间,归档列表按它倒序 */
    private LocalDateTime archivedAt;
    /**
     * 所属自建分组 id,{@code null} 表示未分组。
     *
     * <p>未分组的会话继续按「今天 / 昨天 / 更早」自动归类;
     * 一旦放进分组,就只出现在该分组下(不再重复出现在时间分组里)。
     *
     * <p>用 NULL 而不是哨兵值表达「未分组」:哨兵值会让每个判断处
     * 都要记得特殊处理,迟早漏一处。
     */
    private Long groupId;
    private LocalDateTime createdAt;
    private LocalDateTime updatedAt;
src/main/java/com/custom/webui/service/ChatService.java
@@ -16,14 +16,25 @@
 */
public interface ChatService {
    /** 当前用户的会话列表,按更新时间倒序(最近活跃的在最上方) */
    List<ChatDTO> listByUser(Long userId);
    /**
     * 当前用户的会话列表。
     *
     * <p>排序固定为「置顶优先」:
     * <pre>
     *   ORDER BY pinned DESC, pinned_at DESC, updated_at DESC
     * </pre>
     * 置顶区内按置顶时间倒序(最近钉上去的在最前),
     * 非置顶区里 pinned_at 全为 NULL,于是自然退化为「按最近活跃倒序」。
     *
     * @param archived false = 主列表(未归档);true = 归档列表
     */
    List<ChatDTO> listByUser(Long userId, boolean archived);
    /** 新建会话,title 为空时使用默认「新对话」 */
    ChatDTO create(Long userId, ChatCreateRequest request);
    /**
     * 修改标题或模型参数,字段为 null 表示不修改。
     * 修改标题、模型参数、置顶或归档,字段为 null 表示不修改。
     *
     * @throws com.custom.webui.exception.BusinessException 会话不存在或不属于该用户(404/403)
     */
@@ -39,6 +50,19 @@
    /** 校验会话归属,返回实体;不属于该用户时抛 404(而非 403,避免探测他人会话是否存在) */
    Chat requireOwnedChat(Long userId, Long chatId);
    /**
     * 把会话移入 / 移出分组。
     *
     * <p>单独一个方法而不是塞进 {@link #update}:那里的约定是
     * 「字段为 null 表示不修改」,而「移出分组」正是要把 groupId 置为 null,
     * 同一个字段上无法同时表达这两种语义。
     *
     * @param groupId 目标分组 id;null 表示移出分组
     * @throws com.custom.webui.exception.BusinessException 会话不属于该用户(404),
     *         或目标分组不存在 / 不属于该用户(404)
     */
    ChatDTO moveToGroup(Long userId, Long chatId, Long groupId);
    /** 读取会话的模型参数,meta 为空或非法 JSON 时返回全 null 的对象 */
    ChatMetaRequest parseMeta(Chat chat);
@@ -53,9 +77,10 @@
     *
     * <p>排序:命中的会话按最近活跃时间倒序,最多返回 {@code limit} 条。
     *
     * @param keyword 关键词,空白则返回空列表(不返回全部,避免把搜索框
     *                当成「无过滤列表」误用)
     * @param keyword  关键词,空白则返回空列表(不返回全部,避免把搜索框
     *                 当成「无过滤列表」误用)
     * @param archived 搜索范围:false = 未归档(与主列表一致),true = 归档
     * @return 命中的会话,附带命中片段与命中类型
     */
    List<ChatDTO> search(Long userId, String keyword, int limit);
    List<ChatDTO> search(Long userId, String keyword, int limit, boolean archived);
}
src/main/java/com/custom/webui/service/impl/ChatServiceImpl.java
@@ -15,6 +15,7 @@
import com.custom.webui.mapper.MessageMapper;
import com.custom.webui.mapper.UploadFileMapper;
import com.custom.webui.service.ChatService;
import com.custom.webui.service.ChatGroupService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -50,13 +51,20 @@
    private final MessageMapper messageMapper;
    private final UploadFileMapper uploadFileMapper;
    private final ChatCollectionMapper chatCollectionMapper;
    private final ChatGroupService chatGroupService;
    private final ObjectMapper objectMapper;
    @Override
    public List<ChatDTO> listByUser(Long userId) {
    public List<ChatDTO> listByUser(Long userId, boolean archived) {
        List<Chat> chats = chatMapper.selectList(
                Wrappers.<Chat>lambdaQuery()
                        .eq(Chat::getUserId, userId)
                        .eq(Chat::getArchived, archived)
                        // 置顶优先,其次置顶时间倒序,最后活跃时间倒序。
                        // 非置顶行的 pinned_at 全为 NULL,第二排序键等同无效,
                        // 于是自然退化成「按最近活跃倒序」。
                        .orderByDesc(Chat::getPinned)
                        .orderByDesc(Chat::getPinnedAt)
                        .orderByDesc(Chat::getUpdatedAt));
        if (chats.isEmpty()) {
            return Collections.emptyList();
@@ -107,8 +115,22 @@
    public ChatDTO update(Long userId, Long chatId, ChatUpdateRequest request) {
        Chat existing = requireOwnedChat(userId, chatId);
        Chat update = new Chat();
        update.setId(chatId);
        /*
         * 这里刻意用 UpdateWrapper 逐列显式 SET,而不是 updateById(entity):
         *
         * 1) updateById 默认**忽略 null 字段**,而「取消置顶」恰恰要把
         *    pinned_at 写回 NULL,用实体传 null 表达不了这个意图。
         * 2) updated_at 这一列在 MySQL 里带 ON UPDATE CURRENT_TIMESTAMP,
         *    只要 UPDATE 语句不显式提到它,它就会被数据库自动刷新。
         *    而置顶/归档属于**视图整理**操作,不该被当成「刚刚活跃」——
         *    否则置顶一下,会话就会在时间分组里从「更早」跳到「今天」。
         *    显式 SET updated_at = 原值 是唯一能压住该自动行为的方式
         *    (MySQL 文档:被显式赋值的列不会再走 ON UPDATE)。
         */
        LocalDateTime now = LocalDateTime.now();
        var wrapper = Wrappers.<Chat>lambdaUpdate().eq(Chat::getId, chatId);
        boolean contentChanged = false;
        if (request.getTitle() != null) {
            String title = request.getTitle().trim();
@@ -116,16 +138,34 @@
                throw BusinessException.badRequest("标题不能为空");
            }
            // 防御超长标题:列宽 255,超出部分直接截断而不是报数据库错误
            update.setTitle(title.length() > 255 ? title.substring(0, 255) : title);
            wrapper.set(Chat::getTitle, title.length() > 255 ? title.substring(0, 255) : title);
            contentChanged = true;
        }
        if (request.getMeta() != null) {
            // meta 是整体覆盖语义:前端应提交完整的参数对象
            update.setMeta(writeMeta(request.getMeta()));
            wrapper.set(Chat::getMeta, writeMeta(request.getMeta()));
            contentChanged = true;
        }
        update.setUpdatedAt(LocalDateTime.now());
        chatMapper.updateById(update);
        // ---- 置顶 ----
        // 置顶时记录 pinned_at,置顶区因此按「钉上去的先后」排序;
        // 取消置顶则清回 NULL,不让旧时间残留下去影响后续排序。
        if (request.getPinned() != null) {
            boolean pinned = request.getPinned();
            wrapper.set(Chat::getPinned, pinned);
            wrapper.set(Chat::getPinnedAt, pinned ? now : null);
        }
        // ---- 归档 ----
        if (request.getArchived() != null) {
            boolean archived = request.getArchived();
            wrapper.set(Chat::getArchived, archived);
            wrapper.set(Chat::getArchivedAt, archived ? now : null);
        }
        wrapper.set(Chat::getUpdatedAt, contentChanged ? now : existing.getUpdatedAt());
        chatMapper.update(null, wrapper);
        Chat refreshed = chatMapper.selectById(chatId);
        Long messageCount = messageMapper.selectCount(
@@ -134,7 +174,9 @@
                        Wrappers.<ChatCollection>lambdaQuery().eq(ChatCollection::getChatId, chatId))
                .stream().map(ChatCollection::getCollectionName).toList();
        log.debug("更新会话 chatId={} 原meta={} 新meta={}", chatId, existing.getMeta(), refreshed.getMeta());
        log.debug("更新会话 chatId={} 原meta={} 新meta={} pinned={} archived={}",
                chatId, existing.getMeta(), refreshed.getMeta(),
                refreshed.getPinned(), refreshed.getArchived());
        return toDto(refreshed, messageCount, collections);
    }
@@ -163,6 +205,38 @@
        chatMapper.deleteById(chatId);
        log.info("删除会话 userId={} chatId={} 连带删除消息 {} 条、解绑文件 {} 个",
                userId, chatId, msgDeleted, boundFiles.size());
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChatDTO moveToGroup(Long userId, Long chatId, Long groupId) {
        Chat chat = requireOwnedChat(userId, chatId);
        if (groupId != null) {
            // 目标分组必须是自己的 —— 否则用户可以把会话「移进」别人的分组 id,
            // 虽然看不到对方的内容,但会在对方的列表里凭空多出一条不属于他的会话
            chatGroupService.requireOwnedGroup(userId, groupId);
        }
        // 一次 UPDATE 同时处理两件事:
        //   1. group_id 要能写成 NULL(移出分组),所以用 UpdateWrapper 显式 SET,
        //      实体里的 null 字段会被 MyBatis-Plus 忽略,表达不了「置空」
        //   2. updated_at 显式写回原值 —— 整理动作不该被当成「刚刚活跃」,
        //      否则会话会在时间分组里从「更早」跳到「今天」
        chatMapper.update(null,
                Wrappers.<Chat>lambdaUpdate()
                        .eq(Chat::getId, chatId)
                        .set(Chat::getGroupId, groupId)
                        .set(Chat::getUpdatedAt, chat.getUpdatedAt()));
        Long messageCount = messageMapper.selectCount(
                Wrappers.<Message>lambdaQuery().eq(Message::getChatId, chatId));
        List<String> collections = chatCollectionMapper.selectList(
                        Wrappers.<ChatCollection>lambdaQuery().eq(ChatCollection::getChatId, chatId))
                .stream().map(ChatCollection::getCollectionName).toList();
        log.info("会话移动分组 userId={} chatId={} groupId={}", userId, chatId, groupId);
        return toDto(chatMapper.selectById(chatId), messageCount, collections);
    }
    @Override
@@ -209,7 +283,7 @@
    }
    @Override
    public List<ChatDTO> search(Long userId, String keyword, int limit) {
    public List<ChatDTO> search(Long userId, String keyword, int limit, boolean archived) {
        if (keyword == null || keyword.isBlank()) {
            // 空关键词直接返回空,而不是返回全部会话 ——
            // 否则搜索框会退化成「无过滤列表」,和侧边栏本身重复
@@ -220,9 +294,14 @@
        // 先取该用户全部会话(个人会话量级通常在数百,一次查完再做内存匹配,
        // 比两次 LIKE 查询 + 合并更简单,也避免了 title/message 两次往返)。
        //
        // 搜索范围与当前视图一致:主列表搜索不把归档对话混进来,
        // 在「归档对话」里搜索则只搜归档的 —— 否则用户会搜到一堆
        // 自己刚归档起来、并不想看到的对话。
        List<Chat> chats = chatMapper.selectList(
                Wrappers.<Chat>lambdaQuery()
                        .eq(Chat::getUserId, userId)
                        .eq(Chat::getArchived, archived)
                        .orderByDesc(Chat::getUpdatedAt));
        if (chats.isEmpty()) {
            return Collections.emptyList();
@@ -346,6 +425,13 @@
        dto.setMeta(chat.getMeta() == null || chat.getMeta().isBlank() ? "{}" : chat.getMeta());
        dto.setCreatedAt(chat.getCreatedAt());
        dto.setUpdatedAt(chat.getUpdatedAt());
        // 置顶/归档列可能为 NULL(例如迁移前的老数据被显式查出),统一兜底成 false,
        // 免得前端拿到 null 还要到处判空
        dto.setPinned(Boolean.TRUE.equals(chat.getPinned()));
        dto.setPinnedAt(chat.getPinnedAt());
        dto.setArchived(Boolean.TRUE.equals(chat.getArchived()));
        dto.setArchivedAt(chat.getArchivedAt());
        dto.setGroupId(chat.getGroupId());
        dto.setMessageCount(messageCount == null ? 0L : messageCount);
        dto.setCollectionNames(collections == null ? new ArrayList<>() : collections);
        return dto;
src/main/resources/application.yml
@@ -91,6 +91,26 @@
    # 单文件最大字节数(50MB)
    max-file-size: 52428800
  # 会话导出(JSON / TXT / PDF)
  export:
    # PDF 用的中文字体文件;留空则自动探测系统字体。
    #
    # 为什么要显式嵌入字体:PDF 内置的 14 个标准字体只有 Latin-1,
    # 写中文会直接抛「No glyph for U+4E2D」;而引用系统 CJK 标准字体
    # 虽然省事,但对方机器没装就是一片空白 —— 导出文件是要发给别人的,
    # 不能赌他的环境。所以这里找一份真实字体**按子集嵌入**
    # (只带用到的字形,一个中文对话导出的 PDF 通常只有几十 KB)。
    #
    # macOS 无需配置(会自动用 /System/Library/Fonts/Supplemental/Arial Unicode.ttf);
    # Linux / Windows 若自动探测失败,用这里指定,例如:
    #   pdf-font-path: /usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc
    # 启动日志的「导出自检」会告诉你最终用了哪个字体。
    pdf-font-path: ${WEBUI_PDF_FONT:}
    # 单次导出的消息条数上限与单条消息字符上限:
    # 防止一条超长对话生成几十兆的文件把内存拖垮。超出会截断并**在文件里写明**。
    max-messages: 2000
    max-chars-per-message: 20000
  llm:
    # 可选值:ollama / openai-compat / mock
    #   ollama        —— Ollama 原生接口(/api/chat,NDJSON 流)
src/main/resources/db/h2-schema.sql
@@ -21,11 +21,26 @@
);
DROP TABLE IF EXISTS `chat`;
DROP TABLE IF EXISTS `chat_group`;
CREATE TABLE `chat_group` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `user_id` bigint NOT NULL,
  `name` varchar(64) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE (`user_id`, `name`)
);
CREATE TABLE `chat` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `user_id` bigint NOT NULL,
  `title` varchar(255) NOT NULL DEFAULT '新对话',
  `meta` varchar(4000) DEFAULT NULL,
  `pinned` tinyint NOT NULL DEFAULT 0,
  `pinned_at` timestamp DEFAULT NULL,
  `archived` tinyint NOT NULL DEFAULT 0,
  `archived_at` timestamp DEFAULT NULL,
  `group_id` bigint DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)