Преглед изворни кода

feat(agent): 输入框支持 @ 引用已上传文件

- 新增 GET /chat/files:当前案件 file_info 根记录(按上传时间倒序),带 pickable 与原因;
  未保留原件的文档类明确置灰,不给看似可用的假选项
- 新增 POST /chat/attachments/from-file:把已上传文件复制到附件目录后,走与上传完全相同的
  提取流程(内联 / Python 直读 / RAG);复制而非引用原件,避免孤儿清理删掉案件上传文件
- ChatAttachmentService 抽出 register(),上传与引用共用同一套校验/提取/入库口径
- AttachmentVO.id 与消息徽标附件 id 改为字符串下发(雪花 ID 经 JS Number 会丢末位,
  重新生成消息时回传就变成「附件不存在」)
- 前端 ChatComposer:输入 @ 弹出候选面板(本地过滤、↑↓/Enter/Esc、输入法组合保护、
  点击外部关闭),选中即登记为附件 chip,同一文件不重复引用
cc пре 4 недеља
родитељ
комит
9edfebcfed

+ 36 - 1
ai-electron/frontend/src/ai/api/attachmentApi.ts

@@ -9,7 +9,8 @@
  */
 import { defHttp } from '@/core/utils/http/axios';
 import { resolveApiUrl } from '../utils/constants';
-import type { AttachmentVO } from './types';
+import { aiHttp } from './http';
+import type { AttachmentVO, ChatFileOption } from './types';
 
 /**
  * 上传附件。注意 defHttp.uploadFile 不走自动解包(见 governApi 的同类说明),
@@ -43,3 +44,37 @@ export async function uploadAttachment(
   );
   return (res?.data?.data ?? res?.data ?? res) as AttachmentVO;
 }
+
+/**
+ * 当前案件已上传的文件(输入框 @ 引用候选)。
+ * 后端返回 file_info 根记录(按上传时间倒序);pickable=false 的置灰展示,reason 说明原因。
+ */
+export function listChatFiles(keyword?: string): Promise<ChatFileOption[]> {
+  return aiHttp.getRaw<ChatFileOption[]>('/chat/files', {
+    limit: 200,
+    ...(keyword ? { keyword } : {}),
+  });
+}
+
+/**
+ * 把已上传文件引用为对话附件:服务端复制原件到附件目录后,走与上传完全相同的提取流程
+ * (内联 / Python 直读 / RAG),返回的 id 可直接作为发送时的 attachmentIds。
+ *
+ * 复制是必须的:附件孤儿清理会删除附件的 file_path,直接引用案件上传目录会把原件删掉。
+ * 表格扫描 / 大文档 OCR 都在这个请求内完成,因此与上传一样给 10 分钟超时。
+ */
+export function attachExistingFile(params: {
+  fileId: string;
+  workspaceId: string;
+  sessionId?: string | null;
+}): Promise<AttachmentVO> {
+  return aiHttp.postRaw<AttachmentVO>(
+    '/chat/attachments/from-file',
+    {
+      fileId: params.fileId,
+      workspaceId: params.workspaceId,
+      ...(params.sessionId ? { sessionId: params.sessionId } : {}),
+    },
+    { timeout: 10 * 60 * 1000 },
+  );
+}

+ 2 - 2
ai-electron/frontend/src/ai/api/http.ts

@@ -50,8 +50,8 @@ export const aiHttp = {
     return defHttp.get<T>({ url: withPrefix(url), params }, RAW);
   },
 
-  postRaw<T>(url: string, data?: Record<string, any>): Promise<T> {
-    return defHttp.postJson<T>({ url: withPrefix(url), data }, RAW);
+  postRaw<T>(url: string, data?: Record<string, any>, config?: AxiosRequestConfig): Promise<T> {
+    return defHttp.postJson<T>({ url: withPrefix(url), data, ...(config || {}) }, RAW);
   },
 
   /**

+ 19 - 1
ai-electron/frontend/src/ai/api/types.ts

@@ -266,7 +266,7 @@ export interface AttachmentVO {
   id: string;
   name: string;
   size: number;
-  /** DOCUMENT / TABLE */
+  /** DOCUMENT / TABLE / IMAGE / MEDIA */
   kind: string;
   /** 表格数据行数 */
   rows: number;
@@ -292,6 +292,24 @@ export interface AttachmentBadge {
   indexedChunks?: number;
 }
 
+/**
+ * 输入框 @ 可引用的已上传文件(当前案件 file_info 的根记录)。
+ *
+ * pickable=false 表示无法在对话中引用:非表格类文件上传时没有落盘,
+ * 只保留了 4000 字符的识别样本;前端置灰并展示 reason。
+ */
+export interface ChatFileOption {
+  /** file_info.id(雪花字符串,禁止 Number() 转换) */
+  id: string;
+  name: string;
+  /** 文件类型(后缀或 file_info.fileType) */
+  type: string;
+  size: number;
+  createTime?: string | null;
+  pickable: boolean;
+  reason?: string | null;
+}
+
 /* ------------------------------------------------------------------ *
  * 模型管理
  * ------------------------------------------------------------------ */

+ 308 - 5
ai-electron/frontend/src/ai/components/ChatComposer.vue

@@ -1,6 +1,6 @@
 <template>
   <div class="ai-composer">
-    <div class="ai-composer__box" :class="{ 'is-focus': focused }">
+    <div ref="boxRef" class="ai-composer__box" :class="{ 'is-focus': focused }">
       <a-textarea
         ref="inputRef"
         v-model:value="draft"
@@ -11,9 +11,39 @@
         placeholder="用自然语言描述要分析的内容,例如:查询近 30 天通话次数最多的 10 个号码"
         @focus="focused = true"
         @blur="focused = false"
+        @input="onDraftInput"
+        @compositionstart="composing = true"
+        @compositionend="composing = false"
         @keydown="onKeydown"
       />
 
+      <!-- @ 引用已上传文件:输入 @ 后的候选面板,选中即登记为附件 chip(走与上传相同的提取流程) -->
+      <div v-if="fileMenu.open" class="ai-composer__files">
+        <div class="ai-composer__files-head">
+          <Icon icon="mdi:paperclip" :size="13" />
+          <span>引用已上传文件</span>
+          <span v-if="fileMenu.query" class="ai-composer__files-query">@{{ fileMenu.query }}</span>
+        </div>
+        <div v-if="fileLoading" class="ai-composer__files-empty">加载中…</div>
+        <div v-else-if="fileError" class="ai-composer__files-empty">{{ fileError }}</div>
+        <div v-else-if="!visibleFiles.length" class="ai-composer__files-empty">当前案件没有匹配的已上传文件</div>
+        <ul v-else class="ai-composer__files-list">
+          <li
+            v-for="(f, i) in visibleFiles"
+            :key="f.id"
+            class="ai-file"
+            :class="{ 'is-active': i === fileMenu.index, 'is-disabled': !f.pickable }"
+            @mouseenter="onFileHover(i)"
+            @mousedown.prevent="pickFileOption(f)"
+          >
+            <Icon :icon="iconFor(f.name)" :size="13" />
+            <span class="ai-file__name">{{ f.name }}</span>
+            <span class="ai-file__meta">{{ (f.type || '').toUpperCase() }} · {{ formatSize(f.size) }}</span>
+            <span v-if="!f.pickable" class="ai-file__why">{{ f.reason }}</span>
+          </li>
+        </ul>
+      </div>
+
       <!-- 附件 chips:选择即上传,上传中显进度、失败可移除 -->
       <div v-if="attachments.length" class="ai-composer__atts">
         <span v-for="att in attachments" :key="att.localId" class="ai-att" :class="{ 'is-failed': att.failed }">
@@ -96,7 +126,7 @@
       </div>
     </div>
 
-    <p class="ai-composer__hint">Enter 发送 · Shift+Enter 换行</p>
+    <p class="ai-composer__hint">Enter 发送 · Shift+Enter 换行 · 输入 @ 引用已上传文件</p>
   </div>
 </template>
 
@@ -111,12 +141,12 @@
    * 弹性空白把模型 chip 与圆形发送按钮推到右侧贴邻,键位提示移到容器外下方 ——
    * 它属于"使用说明",不该挤占输入区的横向空间。
    */
-  import { computed, nextTick, ref, watch } from 'vue';
+  import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
   import { Dropdown, Menu, MenuItem, Textarea } from 'ant-design-vue';
   import Icon from '@/core/components/Icon/src/Icon.vue';
   import { useUserStore } from '@/core/store/modules/case';
-  import { uploadAttachment } from '../api/attachmentApi';
-  import type { AiModel, AttachmentBadge, AttachmentVO } from '../api/types';
+  import { attachExistingFile, listChatFiles, uploadAttachment } from '../api/attachmentApi';
+  import type { AiModel, AttachmentBadge, AttachmentVO, ChatFileOption } from '../api/types';
   import { useChatStreamStore } from '../store/chatStream';
 
   const ATextarea = Textarea;
@@ -151,6 +181,7 @@
   const focused = ref(false);
   const inputRef = ref<any>();
   const fileRef = ref<HTMLInputElement>();
+  const boxRef = ref<HTMLElement>();
   const userStore = useUserStore();
   const chatStore = useChatStreamStore();
 
@@ -160,6 +191,8 @@
     localId: number;
     /** 上传成功后的附件 id(雪花字符串,原样回传后端,禁止 Number() 转换) */
     id?: string;
+    /** @ 引用来源的 file_info.id:同一文件不重复引用 */
+    sourceFileId?: string;
     name: string;
     meta: string;
     icon: string;
@@ -220,6 +253,163 @@
     attachments.value = attachments.value.filter((a) => a.localId !== localId);
   }
 
+  /* ---------------- @ 引用已上传文件(案件 file_info) ---------------- */
+
+  interface FileMenuState {
+    open: boolean;
+    /** 触发位置的 @ 下标(选中后把「@query」从草稿里摘掉) */
+    start: number;
+    query: string;
+    /** 键盘高亮项 */
+    index: number;
+  }
+
+  const fileMenu = ref<FileMenuState>({ open: false, start: -1, query: '', index: 0 });
+  const fileOptions = ref<ChatFileOption[]>([]);
+  const fileLoading = ref(false);
+  const fileError = ref('');
+  const composing = ref(false);
+  /** 已为哪个案件拉过列表:切案件需要重新拉 */
+  let fileLoadedForCase: string | null = null;
+
+  const visibleFiles = computed(() => {
+    const q = fileMenu.value.query.trim().toLowerCase();
+    if (!q) return fileOptions.value;
+    return fileOptions.value.filter((f) => f.name.toLowerCase().includes(q));
+  });
+
+  async function loadFiles() {
+    const caseId = String(userStore.getCaseInfo?.id ?? '');
+    if (!caseId) {
+      fileError.value = '请先打开案件';
+      return;
+    }
+    if (fileLoadedForCase === caseId && fileOptions.value.length) return;
+    fileLoading.value = true;
+    fileError.value = '';
+    try {
+      fileOptions.value = (await listChatFiles()) || [];
+      fileLoadedForCase = caseId;
+    } catch (e: any) {
+      fileError.value = e?.message || '已上传文件加载失败';
+    } finally {
+      fileLoading.value = false;
+    }
+  }
+
+  function closeFileMenu() {
+    if (fileMenu.value.open) {
+      fileMenu.value = { ...fileMenu.value, open: false, index: 0 };
+    }
+  }
+
+  /**
+   * 输入 @ 触发候选面板。
+   *
+   * 判据:@ 前不能是邮箱用户名的字符(否则 a@b.com 会误触发),@ 到光标之间不能有空白;
+   * 中文句子里 @ 前通常没有空格,所以不能用「必须是空白」来判。输入法组合期间不触发。
+   */
+  function onDraftInput(e: Event) {
+    if (props.disabled || props.streaming || composing.value) return;
+    const el = e.target as HTMLTextAreaElement;
+    const caret = el.selectionStart ?? el.value.length;
+    const before = el.value.slice(0, caret);
+    const at = before.lastIndexOf('@');
+    if (at < 0) {
+      closeFileMenu();
+      return;
+    }
+    const prev = at === 0 ? '' : before[at - 1];
+    const query = before.slice(at + 1);
+    if (!/[A-Za-z0-9._%+-]/.test(prev) && !/\s/.test(query) && query.length <= 60) {
+      fileMenu.value = { open: true, start: at, query, index: 0 };
+      void loadFiles();
+    } else {
+      closeFileMenu();
+    }
+  }
+
+  function onFileHover(index: number) {
+    fileMenu.value = { ...fileMenu.value, index };
+  }
+
+  function moveFileActive(delta: number) {
+    const total = visibleFiles.value.length;
+    if (!total) return;
+    fileMenu.value = { ...fileMenu.value, index: (fileMenu.value.index + delta + total) % total };
+  }
+
+  /**
+   * 点击编辑区外部关闭候选面板。
+   *
+   * 用文档级 mousedown 而不是 textarea 的 blur:拖动面板滚动条时输入框会失焦,
+   * blur 方案会在滚动的瞬间把面板关掉。
+   */
+  function onDocumentMousedown(e: MouseEvent) {
+    if (!fileMenu.value.open) return;
+    if (boxRef.value?.contains(e.target as Node)) return;
+    closeFileMenu();
+  }
+
+  onMounted(() => document.addEventListener('mousedown', onDocumentMousedown));
+  onBeforeUnmount(() => document.removeEventListener('mousedown', onDocumentMousedown));
+
+  /** 选中文件:摘掉草稿里的「@query」,按现有附件流程登记为 chip */
+  async function pickFileOption(option: ChatFileOption) {
+    if (!option.pickable || props.disabled || props.streaming) return;
+    removeMentionText();
+    closeFileMenu();
+    if (attachments.value.some((a) => a.sourceFileId === option.id)) return;
+
+    const chip: AttChip = {
+      localId: ++attSeq,
+      sourceFileId: option.id,
+      name: option.name,
+      meta: `${formatSize(option.size)} · 解析中…`,
+      icon: iconFor(option.name),
+      uploading: true,
+      progress: 0,
+      failed: false,
+    };
+    attachments.value.push(chip);
+    try {
+      const vo = await attachExistingFile({
+        fileId: option.id,
+        workspaceId: String(userStore.getCaseInfo?.id ?? ''),
+        sessionId: chatStore.activeSessionId ?? undefined,
+      });
+      if (vo.status !== 'READY') {
+        throw new Error('附件处理失败,请重试');
+      }
+      chip.id = vo.id;
+      chip.vo = vo;
+      chip.uploading = false;
+      chip.meta = metaOf(vo);
+      chip.icon = iconFor(vo.name);
+    } catch (err: any) {
+      chip.uploading = false;
+      chip.failed = true;
+      chip.meta = err?.response?.data?.message || err?.message || '引用失败,点击 × 移除';
+    }
+  }
+
+  /** 从草稿里删掉触发用的「@query」,并把光标放回删除点 */
+  function removeMentionText() {
+    const { open, start, query } = fileMenu.value;
+    if (!open || start < 0) return;
+    const token = '@' + query;
+    const idx = draft.value.indexOf(token, start);
+    if (idx < 0) return;
+    draft.value = draft.value.slice(0, idx) + draft.value.slice(idx + token.length);
+    nextTick(() => {
+      const ta = (inputRef.value as any)?.resizableTextArea?.textArea as HTMLTextAreaElement | undefined;
+      if (ta) {
+        ta.focus();
+        ta.setSelectionRange(idx, idx);
+      }
+    });
+  }
+
   function metaOf(vo: AttachmentVO) {
     const base =
       vo.kind === 'TABLE' ? `${formatSize(vo.size)} · ${vo.rows} 行` : `${formatSize(vo.size)} · ${vo.chars} 字`;
@@ -274,6 +464,7 @@
   function submit() {
     const text = draft.value.trim();
     if (!text || props.disabled || props.streaming) return;
+    closeFileMenu();
     // 上传中的附件不随发(canSend 已拦截);失败的自动剔除,只发成功的
     const atts = attachments.value.filter((a) => !a.failed && !a.uploading && a.id != null && a.vo);
     draft.value = '';
@@ -293,6 +484,28 @@
    * 回车会沿用旧的组合中标记,被当成候选词确认而只换行、不发送。
    */
   function onKeydown(e: KeyboardEvent) {
+    // @ 候选面板打开时,方向键/回车/Esc 先交给面板,不触发发送
+    if (fileMenu.value.open) {
+      if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
+        e.preventDefault();
+        moveFileActive(e.key === 'ArrowDown' ? 1 : -1);
+        return;
+      }
+      if (e.key === 'Escape') {
+        e.preventDefault();
+        closeFileMenu();
+        return;
+      }
+      if (e.key === 'Enter' && !e.isComposing && e.keyCode !== 229) {
+        const option = visibleFiles.value[fileMenu.value.index];
+        // 高亮项不可引用时不吞回车,让用户照常发送
+        if (option?.pickable) {
+          e.preventDefault();
+          void pickFileOption(option);
+          return;
+        }
+      }
+    }
     if (e.key !== 'Enter') return;
     // 中文输入法组合中的回车是确认候选词,不能当发送
     if (e.isComposing || e.keyCode === 229) return;
@@ -337,6 +550,7 @@
    * 否则输入框会比正文宽出 48px,视觉上"左边不齐"。
    */
   .ai-composer__box {
+    position: relative;
     max-width: calc(var(--ai-content-max) - var(--ai-sp-5) * 2);
     margin: 0 auto;
     padding: 10px 12px 8px;
@@ -525,6 +739,95 @@
     display: none;
   }
 
+  /* @ 引用已上传文件:浮在输入框上方的候选面板 */
+  .ai-composer__files {
+    position: absolute;
+    right: 12px;
+    bottom: calc(100% + 6px);
+    left: 12px;
+    z-index: 20;
+    max-height: 268px;
+    overflow: auto;
+    background: #fff;
+    border: 1px solid var(--ai-border, #e7ebf3);
+    border-radius: 10px;
+    box-shadow: 0 8px 24px rgb(15 23 42 / 12%);
+
+    &-head {
+      display: flex;
+      align-items: center;
+      gap: 6px;
+      padding: 8px 10px 6px;
+      font-size: 12px;
+      color: var(--ai-text-2, #64748b);
+      border-bottom: 1px solid var(--ai-border, #eef2f7);
+    }
+
+    &-query {
+      max-width: 220px;
+      margin-left: auto;
+      overflow: hidden;
+      color: var(--ai-primary, #2a50ec);
+      text-overflow: ellipsis;
+      white-space: nowrap;
+    }
+
+    &-empty {
+      padding: 14px 12px;
+      font-size: 12px;
+      color: var(--ai-text-2, #94a3b8);
+      text-align: center;
+    }
+
+    &-list {
+      padding: 4px;
+      margin: 0;
+      list-style: none;
+    }
+  }
+
+  .ai-file {
+    display: flex;
+    align-items: center;
+    gap: 6px;
+    padding: 6px 8px;
+    font-size: 12.5px;
+    color: var(--ai-text, #0f172a);
+    cursor: pointer;
+    border-radius: 6px;
+
+    &.is-active:not(.is-disabled) {
+      background: rgb(42 80 236 / 8%);
+    }
+
+    &.is-disabled {
+      color: var(--ai-text-2, #94a3b8);
+      cursor: not-allowed;
+    }
+
+    &__name {
+      overflow: hidden;
+      white-space: nowrap;
+      text-overflow: ellipsis;
+    }
+
+    &__meta {
+      margin-left: auto;
+      color: var(--ai-text-2, #94a3b8);
+      white-space: nowrap;
+    }
+
+    &__why {
+      flex: 0 0 auto;
+      max-width: 40%;
+      overflow: hidden;
+      font-size: 11px;
+      color: #b45309;
+      text-overflow: ellipsis;
+      white-space: nowrap;
+    }
+  }
+
   .ai-composer__spacer {
     flex: 1 1 auto;
   }

+ 196 - 26
ai-server/src/main/java/com/zsjz/ai/module/agent/attachment/ChatAttachmentService.java

@@ -6,7 +6,10 @@ import cn.hutool.core.util.StrUtil;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.zsjz.ai.common.context.CaseContextHolder;
 import com.zsjz.ai.common.exception.ServerException;
+import com.zsjz.ai.common.model.dm.entity.FileInfo;
 import com.zsjz.ai.common.utils.Json;
+import com.zsjz.ai.common.utils.WorkspacePathGuard;
+import com.zsjz.ai.module.dm.mapper.FileInfoMapper;
 import com.zsjz.ai.module.document.ExtractionResult;
 import com.zsjz.ai.module.document.TextExtractor;
 import lombok.RequiredArgsConstructor;
@@ -17,11 +20,12 @@ import org.springframework.stereotype.Service;
 import org.springframework.web.multipart.MultipartFile;
 
 import java.io.File;
-import java.io.Writer;
+import java.io.IOException;
 import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
 import java.time.LocalDateTime;
 import java.util.ArrayList;
 import java.util.LinkedHashMap;
@@ -58,31 +62,36 @@ public class ChatAttachmentService {
 
     private final TextExtractor textExtractor;
 
+    /** 案件库(DuckDB)里的已上传文件表:@ 引用已上传文件的数据源 */
+    private final FileInfoMapper fileInfoMapper;
+
     private final ChatAttachmentProperties props;
 
     private final Tika tika = new Tika();
 
-    /** 上传响应 */
-    public record AttachmentVO(Long id, String name, long size, String kind,
+    /**
+     * 上传响应。id 用字符串回传:雪花 ID 超出 JS Number 安全整数,前端必须按字符串透传。
+     */
+    public record AttachmentVO(String id, String name, long size, String kind,
                                int rows, int chars, boolean truncated, int indexedChunks, String status) {
     }
 
+    /**
+     * 输入框 @ 可引用的已上传文件(当前案件 file_info 的根记录)。
+     *
+     * @param pickable 能否在对话中引用;false 时 {@code reason} 说明原因
+     */
+    public record ChatFileVO(String id, String name, String type, long size,
+                             String createTime, boolean pickable, String reason) {
+    }
+
     // ==================== 上传 ====================
 
     /**
      * 上传并按路由提取。UNSUPPORTED 直接 400(不落盘),FAILED 落盘登记但状态失败可重传。
      */
     public AttachmentVO upload(MultipartFile file, Long userId, Long caseId, Long sessionId) {
-        // caseId 来自请求参数,必须与当前打开案件一致;附件行/落盘目录/向量表名都以它为准
-        Long openCaseId = CaseContextHolder.currentCaseId();
-        if (openCaseId == null) {
-            throw new ServerException(400, "请先打开案件后再上传附件");
-        }
-        if (caseId == null) {
-            caseId = openCaseId;
-        } else if (!openCaseId.equals(caseId)) {
-            throw new ServerException(409, "案件上下文不一致,请重新打开案件后再上传附件");
-        }
+        Long openCaseId = requireOpenCase(caseId);
         if (!props.isEnabled()) {
             throw new ServerException(400, "附件功能未启用");
         }
@@ -90,17 +99,166 @@ public class ChatAttachmentService {
             throw new ServerException(400, "附件为空");
         }
         String safeName = sanitizeFileName(file.getOriginalFilename());
-        String suffix = AttachmentContentRouter.suffixOf(safeName);
-        if (!props.effectiveSuffixes().contains(suffix)) {
-            throw new ServerException(400, "不支持的文件类型: " + suffix
+        if (!props.effectiveSuffixes().contains(AttachmentContentRouter.suffixOf(safeName))) {
+            throw new ServerException(400, "不支持的文件类型: " + AttachmentContentRouter.suffixOf(safeName)
                     + "(支持文档、表格、图片与音视频,压缩包/加密文件不支持)");
         }
         long size = file.getSize();
         String mime = detectMime(file, safeName);
+        AttachmentContentRouter.Kind kind = requireKind(safeName, mime);
+        requireSize(kind, size, safeName);
+
+        // 落盘(三层隔离路径):{root}/chat-attachments/{userId}/{caseId}/{sessionId}/{雪花}_{safeName}
+        Path dir = baseDir(userId, openCaseId, sessionId);
+        Path target = allocate(dir, safeName);
+        try {
+            Files.createDirectories(dir);
+            file.transferTo(target);
+        } catch (Exception e) {
+            throw new ServerException(500, "附件保存失败: " + e.getMessage());
+        }
+        return register(userId, openCaseId, sessionId, target, safeName, mime, kind, size);
+    }
+
+    // ==================== @ 引用已上传文件 ====================
+
+    /**
+     * 列出当前案件已上传的文件({@code file_info} 根记录,按上传时间倒序),供输入框 @ 选择。
+     *
+     * <p>只有保留原件的文件可引用:非表格类文件上传时没有落盘(只留 file_ai_profile 的文本样本),
+     * 无法重新解析,这里标记 {@code pickable=false} 并给出原因,前端置灰展示。
+     */
+    public List<ChatFileVO> listCaseFiles(String keyword, int limit) {
+        Long caseId = CaseContextHolder.currentCaseId();
+        if (caseId == null) {
+            throw new ServerException(400, "请先打开案件后再查看已上传文件");
+        }
+        int size = Math.min(Math.max(limit, 1), 200);
+        List<FileInfo> rows = fileInfoMapper.selectList(Wrappers.<FileInfo>lambdaQuery()
+                .eq(FileInfo::getPid, 0L)
+                .like(StrUtil.isNotBlank(keyword), FileInfo::getFileName, StrUtil.trim(keyword))
+                .orderByDesc(FileInfo::getCreateDateTime)
+                .last("limit " + size));
+        List<ChatFileVO> out = new ArrayList<>(rows.size());
+        for (FileInfo row : rows) {
+            out.add(toChatFileVO(caseId, row));
+        }
+        return out;
+    }
+
+    /**
+     * 把已上传文件({@code file_info})登记为对话附件:复制原件到附件目录,然后走与上传完全相同的
+     * 提取流程(表格扫描 / 文档 OCR / 音视频转写 / 内联或 RAG)。
+     *
+     * <p><b>复制而不是引用原件</b>:附件孤儿清理会删除 {@code file_path} 指向的文件,
+     * 直接引用案件上传目录会在清理时把用户导入的原始表格一起删掉。
+     */
+    public AttachmentVO attachExisting(Long userId, Long caseId, Long sessionId, String fileId) {
+        Long openCaseId = requireOpenCase(caseId);
+        if (!props.isEnabled()) {
+            throw new ServerException(400, "附件功能未启用");
+        }
+        FileInfo info = loadFileInfo(fileId);
+        String safeName = sanitizeFileName(info.getFileName());
+        if (StrUtil.isBlank(info.getFilePath())) {
+            throw new ServerException(400, "该文件未保留原件,无法在对话中引用(只有表格类文件上传时会落盘): " + safeName);
+        }
+        Path source = WorkspacePathGuard.requireInsideWorkspace(openCaseId, info.getFilePath());
+        if (!Files.isRegularFile(source)) {
+            throw new ServerException(400, "文件原件已被清理: " + safeName);
+        }
+        if (!props.effectiveSuffixes().contains(AttachmentContentRouter.suffixOf(safeName))) {
+            throw new ServerException(400, "该文件类型不能在对话中引用: " + safeName);
+        }
+        String mime = detectMime(source);
+        AttachmentContentRouter.Kind kind = requireKind(safeName, mime);
+        long size;
+        try {
+            size = Files.size(source);
+        } catch (IOException e) {
+            throw new ServerException(500, "读取文件失败: " + e.getMessage());
+        }
+        requireSize(kind, size, safeName);
+
+        Path dir = baseDir(userId, openCaseId, sessionId);
+        Path target = allocate(dir, safeName);
+        try {
+            Files.createDirectories(dir);
+            Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
+        } catch (IOException e) {
+            throw new ServerException(500, "附件保存失败: " + e.getMessage());
+        }
+        return register(userId, openCaseId, sessionId, target, safeName, mime, kind, size);
+    }
+
+    private FileInfo loadFileInfo(String fileId) {
+        if (StrUtil.isBlank(fileId)) {
+            throw new ServerException(400, "缺少文件 ID");
+        }
+        long id;
+        try {
+            id = Long.parseLong(fileId.trim());
+        } catch (NumberFormatException e) {
+            throw new ServerException(400, "文件 ID 非法: " + fileId);
+        }
+        FileInfo info = fileInfoMapper.selectById(id);
+        if (info == null) {
+            throw new ServerException(404, "文件不存在或已删除: " + fileId);
+        }
+        return info;
+    }
+
+    private ChatFileVO toChatFileVO(Long caseId, FileInfo row) {
+        String name = StrUtil.blankToDefault(row.getFileName(), "未命名文件");
+        String type = StrUtil.blankToDefault(row.getFileType(), AttachmentContentRouter.suffixOf(name));
+        long size = row.getFileSize() == null ? 0 : row.getFileSize();
+        String reason;
+        if (StrUtil.isBlank(row.getFilePath())) {
+            reason = "未保留原件(仅表格类文件上传时落盘)";
+        } else if (!props.effectiveSuffixes().contains(AttachmentContentRouter.suffixOf(name))) {
+            reason = "该类型不能在对话中引用";
+        } else {
+            try {
+                Path path = WorkspacePathGuard.requireInsideWorkspace(caseId, row.getFilePath());
+                if (!Files.isRegularFile(path)) {
+                    reason = "原件已被清理";
+                } else {
+                    size = Files.size(path);
+                    reason = null;
+                }
+            } catch (Exception e) {
+                reason = "原件不可读或已被清理";
+            }
+        }
+        return new ChatFileVO(String.valueOf(row.getId()), name, type, size,
+                row.getCreateDateTime() == null ? null : row.getCreateDateTime().toString(),
+                reason == null, reason);
+    }
+
+    /** 当前案件必须已打开,且与请求里的 caseId 一致(附件行/落盘目录/向量表名都以它为准) */
+    private Long requireOpenCase(Long caseId) {
+        Long openCaseId = CaseContextHolder.currentCaseId();
+        if (openCaseId == null) {
+            throw new ServerException(400, "请先打开案件后再操作附件");
+        }
+        if (caseId == null) {
+            return openCaseId;
+        }
+        if (!openCaseId.equals(caseId)) {
+            throw new ServerException(409, "案件上下文不一致,请重新打开案件后再操作附件");
+        }
+        return openCaseId;
+    }
+
+    private AttachmentContentRouter.Kind requireKind(String safeName, String mime) {
         AttachmentContentRouter.Kind kind = AttachmentContentRouter.route(safeName, mime);
         if (kind == AttachmentContentRouter.Kind.UNSUPPORTED) {
             throw new ServerException(400, "该文件类型暂不支持解析: " + safeName + "(压缩包/加密文件不支持)");
         }
+        return kind;
+    }
+
+    private void requireSize(AttachmentContentRouter.Kind kind, long size, String safeName) {
         long limitMb = switch (kind) {
             case TABLE -> props.getMaxSheetMb();
             case IMAGE -> props.getMaxImageMb();
@@ -110,20 +268,21 @@ public class ChatAttachmentService {
         if (size > limitMb * 1024 * 1024) {
             throw new ServerException(400, "文件超过大小上限(" + limitMb + "MB): " + safeName);
         }
+    }
 
-        // 落盘(三层隔离路径):{root}/chat-attachments/{userId}/{caseId}/{sessionId}/{雪花}_{safeName}
-        Path dir = baseDir(userId, caseId, sessionId);
+    private Path allocate(Path dir, String safeName) {
         Path target = dir.resolve(IdUtil.getSnowflakeNextId() + "_" + safeName).normalize();
         if (!target.startsWith(dir)) {
             throw new ServerException(400, "非法文件名: " + safeName);
         }
-        try {
-            Files.createDirectories(dir);
-            file.transferTo(target);
-        } catch (Exception e) {
-            throw new ServerException(500, "附件保存失败: " + e.getMessage());
-        }
+        return target;
+    }
 
+    /**
+     * 落盘后的统一登记:建行 → 按类型提取 → 入库。上传与 @ 引用共用,保证两条入口口径一致。
+     */
+    private AttachmentVO register(Long userId, Long caseId, Long sessionId, Path target,
+                                  String safeName, String mime, AttachmentContentRouter.Kind kind, long size) {
         ChatAttachment att = new ChatAttachment();
         att.setId(IdUtil.getSnowflakeNextId());
         att.setUserId(userId);
@@ -400,7 +559,9 @@ public class ChatAttachmentService {
                 continue;
             }
             Map<String, Object> m = new LinkedHashMap<>();
-            m.put("id", att.getId());
+            // id 同样按字符串写进消息元数据:前端 regenerate 会把它原样回传为 attachmentIds,
+            // Long 经 JS Number 会被抹掉末位,回传后就变成「附件不存在」
+            m.put("id", String.valueOf(att.getId()));
             m.put("name", att.getFileName());
             m.put("size", att.getSizeBytes());
             m.put("kind", att.getKind());
@@ -486,7 +647,7 @@ public class ChatAttachmentService {
     // ==================== 内部 ====================
 
     private static AttachmentVO toVO(ChatAttachment att) {
-        return new AttachmentVO(att.getId(), att.getFileName(),
+        return new AttachmentVO(String.valueOf(att.getId()), att.getFileName(),
                 att.getSizeBytes() == null ? 0 : att.getSizeBytes(), att.getKind(),
                 att.getRowCount() == null ? 0 : att.getRowCount(),
                 att.getCharCount() == null ? 0 : att.getCharCount(),
@@ -522,6 +683,15 @@ public class ChatAttachmentService {
         }
     }
 
+    /** @ 引用已上传文件时按路径探测 MIME(原型是磁盘上的案件上传文件,不是 multipart) */
+    private String detectMime(Path file) {
+        try {
+            return tika.detect(file);
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
     /** 供 Controller 用的 VO 序列化(前端 chips 展示) */
     public static String toJson(AttachmentVO vo) {
         return Json.toStr(vo);

+ 22 - 0
ai-server/src/main/java/com/zsjz/ai/module/agent/controller/AgentChatController.java

@@ -4,6 +4,7 @@ import cn.dev33.satoken.stp.StpUtil;
 import com.zsjz.ai.common.config.Result;
 import com.zsjz.ai.common.exception.ServerException;
 import com.zsjz.ai.module.agent.attachment.ChatAttachmentService;
+import com.zsjz.ai.module.agent.dto.AttachFileDTO;
 import com.zsjz.ai.module.agent.dto.ChatRequestDTO;
 import com.zsjz.ai.module.agent.dto.CreateChatSessionDTO;
 import com.zsjz.ai.module.agent.dto.GraphRestoreDTO;
@@ -52,6 +53,27 @@ public class AgentChatController {
         return chatAttachmentService.upload(file, StpUtil.getLoginIdAsLong(), workspaceId, sessionId == null ? 0L : sessionId);
     }
 
+    /**
+     * 输入框 @ 可引用的已上传文件(当前案件的 file_info 根记录,按上传时间倒序)。
+     * 没有保留原件的类型也会返回,但 pickable=false 并带原因,前端置灰展示。
+     */
+    @GetMapping("/files")
+    public List<ChatAttachmentService.ChatFileVO> listFiles(
+            @RequestParam(required = false) String keyword,
+            @RequestParam(required = false, defaultValue = "200") int limit) {
+        return chatAttachmentService.listCaseFiles(keyword, limit);
+    }
+
+    /**
+     * 把已上传文件(file_info)引用为对话附件:服务端复制原件后走与上传相同的提取流程,
+     * 返回的附件 id 可直接作为发送消息的 attachmentIds。
+     */
+    @PostMapping("/attachments/from-file")
+    public ChatAttachmentService.AttachmentVO attachExisting(@RequestBody AttachFileDTO dto) {
+        return chatAttachmentService.attachExisting(StpUtil.getLoginIdAsLong(), dto.getWorkspaceId(),
+                dto.getSessionId() == null ? 0L : dto.getSessionId(), dto.getFileId());
+    }
+
     /**
      * 关系图谱会话复原:只按落库的查询条件重新取全量图谱,不持久化大 JSON。
      */

+ 21 - 0
ai-server/src/main/java/com/zsjz/ai/module/agent/dto/AttachFileDTO.java

@@ -0,0 +1,21 @@
+package com.zsjz.ai.module.agent.dto;
+
+import lombok.Data;
+
+/**
+ * 「@ 引用已上传文件」请求体:把当前案件 {@code file_info} 里的一条文件登记为对话附件。
+ *
+ * <p>fileId 用字符串传:雪花 ID 超出 JS 的 Number 安全整数,前端只能按字符串透传。
+ */
+@Data
+public class AttachFileDTO {
+
+    /** file_info.id(雪花,字符串形式) */
+    private String fileId;
+
+    /** 案件 ID(工作空间);为空时取当前打开的案件 */
+    private Long workspaceId;
+
+    /** 会话 ID;草稿态可为空,发送时再绑定 */
+    private Long sessionId;
+}

+ 122 - 1
ai-server/src/test/java/com/zsjz/ai/module/agent/attachment/ChatAttachmentServiceTest.java

@@ -1,17 +1,31 @@
 package com.zsjz.ai.module.agent.attachment;
 
+import cn.hutool.core.io.FileUtil;
+import com.zsjz.ai.common.constants.PathConst;
+import com.zsjz.ai.common.context.CaseContextHolder;
 import com.zsjz.ai.common.exception.ServerException;
+import com.zsjz.ai.common.model.dm.entity.FileInfo;
+import com.zsjz.ai.module.dm.mapper.FileInfoMapper;
+import com.zsjz.ai.module.document.ExtractionResult;
 import com.zsjz.ai.module.document.TextExtractor;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.DisplayName;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.mockito.ArgumentCaptor;
 
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.LocalDateTime;
 import java.util.List;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.anyLong;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.eq;
@@ -34,11 +48,16 @@ class ChatAttachmentServiceTest {
                 new org.apache.ibatis.builder.MapperBuilderAssistant(
                         new com.baomidou.mybatisplus.core.MybatisConfiguration(), ""),
                 ChatAttachment.class);
+        com.baomidou.mybatisplus.core.metadata.TableInfoHelper.initTableInfo(
+                new org.apache.ibatis.builder.MapperBuilderAssistant(
+                        new com.baomidou.mybatisplus.core.MybatisConfiguration(), ""),
+                FileInfo.class);
     }
 
     private ChatAttachmentMapper mapper;
     private AttachmentDocIndexer indexer;
     private TextExtractor textExtractor;
+    private FileInfoMapper fileInfoMapper;
     private ChatAttachmentService service;
 
     @BeforeEach
@@ -46,7 +65,9 @@ class ChatAttachmentServiceTest {
         mapper = mock(ChatAttachmentMapper.class);
         indexer = mock(AttachmentDocIndexer.class);
         textExtractor = mock(TextExtractor.class);
-        service = new ChatAttachmentService(mapper, indexer, textExtractor, new ChatAttachmentProperties());
+        fileInfoMapper = mock(FileInfoMapper.class);
+        service = new ChatAttachmentService(mapper, indexer, textExtractor, fileInfoMapper,
+                new ChatAttachmentProperties());
     }
 
     private static ChatAttachment att(long id, long userId, long caseId, long sessionId, String kind) {
@@ -161,6 +182,101 @@ class ChatAttachmentServiceTest {
         assertTrue(block.contains("音视频, 转写 30 字, 已截断"), block);
     }
 
+    @Test
+    @DisplayName("@ 文件列表:保留原件的可引用,未落盘的置灰并给出原因")
+    void listCaseFilesMarksPickable(@TempDir Path tempDir) throws Exception {
+        long caseId = 9_001L;
+        Path source = workspaceCaseDir(caseId).resolve("record.txt");
+        Files.createDirectories(source.getParent());
+        Files.writeString(source, "案件材料");
+
+        FileInfo pickable = new FileInfo();
+        pickable.setId(100L);
+        pickable.setPid(0L);
+        pickable.setFileName("话单.xls");
+        pickable.setFileType("xls");
+        pickable.setFileSize(12L);
+        pickable.setFilePath(source.toString());
+        pickable.setCreateDateTime(LocalDateTime.now());
+
+        FileInfo noOriginal = new FileInfo();
+        noOriginal.setId(101L);
+        noOriginal.setPid(0L);
+        noOriginal.setFileName("材料.pdf");
+        noOriginal.setFileType("pdf");
+        noOriginal.setFilePath(null);
+        noOriginal.setCreateDateTime(LocalDateTime.now().minusDays(1));
+
+        when(fileInfoMapper.selectList(any())).thenReturn(List.of(pickable, noOriginal));
+
+        List<ChatAttachmentService.ChatFileVO> files = CaseContextHolder.callWith(caseId, 1L,
+                () -> service.listCaseFiles(null, 50));
+
+        assertEquals(2, files.size());
+        assertTrue(files.get(0).pickable(), files.get(0).toString());
+        assertEquals("100", files.get(0).id());
+        assertEquals(Files.size(source), files.get(0).size(), "大小以磁盘原件为准");
+        assertFalse(files.get(1).pickable());
+        assertTrue(files.get(1).reason().contains("未保留原件"), files.get(1).reason());
+
+        FileUtil.del(PathConst.WORKSPACE.resolve(String.valueOf(caseId)).toFile());
+    }
+
+    @Test
+    @DisplayName("@ 引用已上传文件:复制原件登记附件,原件必须保留")
+    void attachExistingCopiesOriginal(@TempDir Path tempDir) throws Exception {
+        long caseId = 9_002L;
+        Path source = workspaceCaseDir(caseId).resolve("record.txt");
+        Files.createDirectories(source.getParent());
+        Files.writeString(source, "原文件内容");
+
+        FileInfo info = new FileInfo();
+        info.setId(200L);
+        info.setPid(0L);
+        info.setFileName("record.txt");
+        info.setFileType("txt");
+        info.setFilePath(source.toString());
+        info.setFileSize(Files.size(source));
+        when(fileInfoMapper.selectById(200L)).thenReturn(info);
+        when(textExtractor.extract(any(Path.class), eq("record.txt"), any(), anyInt()))
+                .thenReturn(ExtractionResult.of("原文件内容"));
+
+        ChatAttachmentService.AttachmentVO vo = CaseContextHolder.callWith(caseId, 1L,
+                () -> service.attachExisting(1L, caseId, 0L, "200"));
+
+        assertEquals("READY", vo.status());
+        assertEquals("record.txt", vo.name());
+        ArgumentCaptor<ChatAttachment> captor = ArgumentCaptor.forClass(ChatAttachment.class);
+        verify(mapper).insert(captor.capture());
+        ChatAttachment saved = captor.getValue();
+        assertNotEquals(source.toString(), saved.getFilePath(), "必须是副本,不能直接引用原件");
+        assertTrue(saved.getFilePath().contains("chat-attachments"), saved.getFilePath());
+        assertTrue(Files.exists(Path.of(saved.getFilePath())), "应复制出新附件");
+        assertTrue(Files.exists(source), "案件原件必须保留(孤儿清理会删附件文件)");
+        assertEquals(String.valueOf(saved.getId()), vo.id(), "附件 id 必须以字符串回传");
+
+        FileUtil.del(Path.of(saved.getFilePath()));
+        FileUtil.del(Path.of(saved.getSidecarPath()));
+        FileUtil.del(PathConst.WORKSPACE.resolve(String.valueOf(caseId)).toFile());
+    }
+
+    @Test
+    @DisplayName("@ 引用未落盘的文件:明确拒绝并说明原因")
+    void attachExistingRejectsMissingOriginal() {
+        FileInfo info = new FileInfo();
+        info.setId(300L);
+        info.setPid(0L);
+        info.setFileName("材料.pdf");
+        info.setFileType("pdf");
+        info.setFilePath(null);
+        when(fileInfoMapper.selectById(300L)).thenReturn(info);
+
+        ServerException e = assertThrows(ServerException.class,
+                () -> CaseContextHolder.callWith(9_003L, 1L,
+                        () -> service.attachExisting(1L, 9_003L, 0L, "300")));
+        assertTrue(e.getMessage().contains("未保留原件"), e.getMessage());
+    }
+
     @Test
     @DisplayName("处理失败的附件直接拒绝,不进消息")
     void failedAttachmentRejected() {
@@ -212,4 +328,9 @@ class ChatAttachmentServiceTest {
         assertTrue(service.buildBlocks(List.of(), 1L, 1L, 1L, "q").isEmpty());
         verify(mapper, never()).selectById(anyLong());
     }
+
+    /** 案件工作空间目录(@ 引用走 WorkspacePathGuard,文件必须真实落在 QingJian/workspace/{caseId} 下) */
+    private static Path workspaceCaseDir(long caseId) {
+        return PathConst.WORKSPACE.resolve(String.valueOf(caseId)).toAbsolutePath().normalize();
+    }
 }