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

feat(ai): 新增会话产物面板与任务删除清理

- 新增产物列表/预览/下载接口,直接扫描 workbench 会话工作区;支持文本、HTML、CSV、图片、PDF 预览
- 聊天页增加右侧产物面板与标题栏入口,工具完成后自动刷新;预览使用 BasicModal,支持全屏/还原
- 下载接入 Electron 下载管理器;浏览器 fallback 识别 JSON 错误体,避免把错误响应当文件下载
- 任务管理删除 workbench 会话时清理独立产物目录,chat 共享工作区不受影响;修正来源列展示
- 补充产物功能测试报告
cc пре 5 дана
родитељ
комит
177d81ade8

+ 17 - 0
ai-electron/electron/service/download/downloadService.js

@@ -239,6 +239,23 @@ class DownloadService {
         throw new Error(message);
       }
 
+      // 鉴权 / 业务异常在 HTTP 200 下返回 JSON(Sa-Token 口径):没有 Content-Disposition
+      // 且响应是 JSON 时按失败处理,避免把 {code:401,message:...} 存成文件。
+      // 真正的 JSON 产物由下载接口带 Content-Disposition,仍按文件正常保存。
+      const contentType = (response.headers.get('content-type') || '').toLowerCase();
+      const hasDisposition = Boolean(response.headers.get('content-disposition'));
+      if (!hasDisposition && contentType.includes('application/json')) {
+        let message = '下载失败:服务端返回错误';
+        try {
+          const text = await response.text();
+          const parsed = JSON.parse(text);
+          message = parsed?.message || parsed?.msg || message;
+        } catch {
+          // 非 JSON 文本按通用错误处理
+        }
+        throw new Error(message);
+      }
+
       const total = Number(response.headers.get('content-length') || 0);
       this.patchItem(item.id, { total, mime: response.headers.get('content-type') || item.mime });
 

+ 170 - 0
ai-electron/frontend/src/workbench/api/artifact.ts

@@ -0,0 +1,170 @@
+import { defHttp } from '@/core/utils/http/axios';
+import { useGlobSetting } from '@/core/hooks/setting';
+import { useMessage } from '@/core/hooks/web/useMessage';
+import { getToken } from '@/core/utils/auth';
+import { isDesktopDownloadAvailable, onDownloadProgress, startDownload } from '@/core/utils/desktop/downloader';
+import { downloadByData } from '@/core/utils/file/download';
+import { aiGet, aiUrl } from './http';
+
+export type Id = string | number;
+
+/** 产物类别(由后端按扩展名推导) */
+export type ArtifactKind =
+  | 'text'
+  | 'markdown'
+  | 'csv'
+  | 'json'
+  | 'image'
+  | 'pdf'
+  | 'html'
+  | 'office'
+  | 'archive'
+  | 'other';
+
+export interface ArtifactItem {
+  /** 相对会话工作区根目录的 POSIX 路径 */
+  path: string;
+  name: string;
+  kind: ArtifactKind;
+  mime?: string;
+  size?: number;
+  lastModified?: string;
+  previewable?: boolean;
+  downloadable?: boolean;
+}
+
+export interface ArtifactListVO {
+  sessionId: Id;
+  items: ArtifactItem[];
+  total: number;
+  truncated: boolean;
+}
+
+export interface ArtifactContentVO {
+  path: string;
+  name: string;
+  kind: ArtifactKind;
+  mime?: string;
+  size?: number;
+  lastModified?: string;
+  text: string;
+  truncated: boolean;
+}
+
+const artifactBase = (sessionId: Id) => `/ai/chat/session/${encodeURIComponent(String(sessionId))}/artifacts`;
+
+/** 产物列表(直接扫描会话工作区磁盘) */
+export function listArtifacts(sessionId: Id): Promise<ArtifactListVO> {
+  return aiGet<ArtifactListVO>(artifactBase(sessionId));
+}
+
+/** 文本类产物内容(HTML 返回源码,由前端 iframe 同源渲染) */
+export function getArtifactContent(sessionId: Id, path: string): Promise<ArtifactContentVO> {
+  return aiGet<ArtifactContentVO>(`${artifactBase(sessionId)}/content`, { path });
+}
+
+/** 下载接口绝对地址(主进程下载需要完整 URL) */
+export function buildArtifactDownloadUrl(sessionId: Id, path: string, inline = false): string {
+  const { apiUrl, urlPrefix, adminPath } = useGlobSetting();
+  const prefix = `${apiUrl || ''}${urlPrefix || ''}${adminPath || ''}`.replace(/\/+$/, '');
+  const query = new URLSearchParams({ path });
+  if (inline) {
+    query.set('inline', 'true');
+  }
+  return `${prefix}${artifactBase(sessionId)}/download?${query.toString()}`;
+}
+
+/** 预览图片 / PDF:带 x-token 拉取 blob(走与 aiGet 相同的 URL 拼接,兼容 Electron/浏览器) */
+export async function fetchArtifactBlob(sessionId: Id, path: string): Promise<Blob> {
+  const res: any = await defHttp.request(
+    {
+      url: aiUrl(`${artifactBase(sessionId)}/download`),
+      method: 'GET',
+      params: { path, inline: true },
+      responseType: 'blob',
+    },
+    {
+      isReturnNativeResponse: true,
+      isTransformResponse: false,
+      skipErrorMessage: true,
+    },
+  );
+  const data = res?.data ?? res;
+  return data instanceof Blob ? data : new Blob([data]);
+}
+
+/**
+ * 下载产物:桌面端交给现有下载管理器(进度/记录在顶栏),浏览器端走 blob 另存。
+ */
+export async function downloadArtifact(sessionId: Id, item: ArtifactItem): Promise<void> {
+  const { createMessage } = useMessage();
+  if (isDesktopDownloadAvailable()) {
+    const token = getToken();
+    const record = await startDownload({
+      url: buildArtifactDownloadUrl(sessionId, item.path),
+      fileName: item.name,
+      mime: item.mime,
+      headers: token ? { 'x-token': String(token) } : undefined,
+      source: 'AI 产物',
+    });
+    createMessage.success(`已开始下载:${record.fileName}`);
+    // 主进程异步下载:完成/失败通过进度通道回传;只关心本次记录
+    const stop = onDownloadProgress((next) => {
+      if (next.id !== record.id) {
+        return;
+      }
+      if (next.status === 'done') {
+        createMessage.success(`已下载:${next.fileName}`);
+        stop();
+      } else if (next.status === 'failed') {
+        createMessage.error(next.message || '产物下载失败');
+        stop();
+      }
+    });
+    return;
+  }
+  await downloadArtifactInBrowser(sessionId, item);
+}
+
+/**
+ * 浏览器 fallback 下载:先取 blob 并识别 JSON 错误,再触发另存。
+ *
+ * <p>后端业务异常会返回 HTTP 200 + JSON(无 Content-Disposition),不能直接当文件下载;
+ * 合法 JSON 产物带有 Content-Disposition,仍按文件正常保存。</p>
+ */
+async function downloadArtifactInBrowser(sessionId: Id, item: ArtifactItem): Promise<void> {
+  const res: any = await defHttp.request(
+    {
+      url: aiUrl(`${artifactBase(sessionId)}/download`),
+      method: 'GET',
+      params: { path: item.path },
+      responseType: 'blob',
+    },
+    {
+      isReturnNativeResponse: true,
+      isTransformResponse: false,
+      skipErrorMessage: true,
+    },
+  );
+  const headers = res?.headers;
+  const disposition =
+    typeof headers?.get === 'function' ? headers.get('content-disposition') : headers?.['content-disposition'];
+  const data = res?.data ?? res;
+  const blob = data instanceof Blob ? data : new Blob([data], { type: item.mime });
+  if (!disposition && blob.type.includes('json')) {
+    const message = await readArtifactErrorMessage(blob);
+    throw new Error(message || '产物下载失败');
+  }
+  downloadByData(blob, item.name);
+}
+
+/** 读取后端 JSON 错误体中的可读消息 */
+async function readArtifactErrorMessage(blob: Blob): Promise<string> {
+  try {
+    const text = await blob.text();
+    const parsed = JSON.parse(text);
+    return String(parsed?.message || parsed?.msg || '').trim();
+  } catch {
+    return '';
+  }
+}

+ 8 - 10
ai-electron/frontend/src/workbench/views/agent/session/index.vue

@@ -67,12 +67,8 @@
           </div>
           <div class="session-card-actions">
             <span class="session-card-count">共 {{ total }} 条</span>
-            <a-button class="wb-btn-warning" :disabled="multiple" @click="handleClose()">
-              终止
-            </a-button>
-            <a-button danger :disabled="multiple" @click="handleDelete()">
-              删除
-            </a-button>
+            <a-button class="wb-btn-warning" :disabled="multiple" @click="handleClose()"> 终止 </a-button>
+            <a-button danger :disabled="multiple" @click="handleDelete()"> 删除 </a-button>
             <a-button @click="handleExport"> 导出 </a-button>
             <a-button @click="getList">刷新</a-button>
           </div>
@@ -419,7 +415,9 @@
     if (!targetIds.length) {
       return;
     }
-    const ok = await confirmAction(`是否确认删除选中的 ${targetIds.length} 个任务?删除后消息记录不再展示。`);
+    const ok = await confirmAction(
+      `是否确认删除选中的 ${targetIds.length} 个任务?删除后消息记录不再展示,智能工作台会话的产物文件将一并清理。`,
+    );
     if (!ok) {
       return;
     }
@@ -476,14 +474,14 @@
     return 'default';
   };
 
-  /** 会话来源展示名(chat 手动对话) */
+  /** 会话来源展示名(workbench 智能工作台 / chat 手动对话) */
   const sourceLabel = (source?: string) => {
-    return '手动对话';
+    return source === 'workbench' ? '智能工作台' : '手动对话';
   };
 
   /** 会话来源标签样式 */
   const sourceTagColor = (source?: string) => {
-    return 'processing';
+    return source === 'workbench' ? 'blue' : 'processing';
   };
 
   onMounted(() => {

+ 767 - 4
ai-electron/frontend/src/workbench/views/chat/index.vue

@@ -47,8 +47,21 @@
           {{ sidebarCollapsed ? '显示任务列表' : '隐藏任务列表' }}
         </a-button>
       </div>
-      <div v-if="messages.length" class="chat-context-bar">
+      <div v-if="currentSessionId" class="chat-context-bar">
         <span class="chat-context-bar__title" :title="currentSessionTitle">{{ currentSessionTitle }}</span>
+        <button
+          v-if="artifactSupported"
+          type="button"
+          class="chat-context-bar__artifact-toggle"
+          :class="{ 'is-active': artifactPanelOpen }"
+          :aria-expanded="artifactPanelOpen"
+          aria-label="产物"
+          title="产物"
+          @click="toggleArtifactPanel()"
+        >
+          <Icon icon="i-mdi:folder-open-outline" />
+          <span v-if="artifacts.length" class="chat-context-bar__artifact-count">{{ artifacts.length }}</span>
+        </button>
       </div>
       <div ref="messageContainerRef" class="message-area" :class="{ 'message-area--empty': !messages.length }">
         <template v-for="msg in messages" :key="String(msg.id)">
@@ -580,6 +593,140 @@
       </div>
     </section>
 
+    <!-- 右侧产物面板:直接扫描本会话工作区磁盘,按会话隔离 -->
+    <aside v-if="currentSessionId && artifactSupported && artifactPanelOpen" class="chat-artifact-panel">
+      <div class="chat-artifact-panel__header">
+        <div class="chat-artifact-panel__heading">
+          <span class="chat-artifact-panel__title">产物</span>
+          <span class="chat-artifact-panel__count">{{ artifacts.length }}</span>
+        </div>
+        <div class="chat-artifact-panel__actions">
+          <a-tooltip title="刷新">
+            <button
+              type="button"
+              class="chat-artifact-panel__icon-btn"
+              aria-label="刷新产物"
+              :disabled="artifactLoading"
+              @click="loadArtifacts()"
+            >
+              <Icon icon="i-mdi:refresh" :class="{ 'is-spinning': artifactLoading }" />
+            </button>
+          </a-tooltip>
+          <a-tooltip title="收起">
+            <button
+              type="button"
+              class="chat-artifact-panel__icon-btn"
+              aria-label="收起产物"
+              @click="toggleArtifactPanel(false)"
+            >
+              <Icon icon="i-mdi:chevron-right" />
+            </button>
+          </a-tooltip>
+        </div>
+      </div>
+      <div class="chat-artifact-panel__body">
+        <a-spin :spinning="artifactLoading">
+          <div v-if="artifactError" class="chat-artifact-panel__error">
+            <span>{{ artifactError }}</span>
+            <a-button type="link" size="small" @click="loadArtifacts()">重试</a-button>
+          </div>
+          <a-empty v-else-if="!artifacts.length" description="本会话暂无产物" />
+          <template v-else>
+            <div v-for="item in artifacts" :key="item.path" class="chat-artifact-item">
+              <span class="chat-artifact-item__icon"><Icon :icon="artifactIcon(item)" /></span>
+              <div class="chat-artifact-item__main">
+                <div class="chat-artifact-item__name" :title="item.path">{{ item.name }}</div>
+                <div class="chat-artifact-item__meta">
+                  <span>{{ formatArtifactSize(item.size) }}</span>
+                  <span>{{ formatArtifactTime(item.lastModified) }}</span>
+                </div>
+                <div v-if="item.path !== item.name" class="chat-artifact-item__path">{{ item.path }}</div>
+              </div>
+              <div class="chat-artifact-item__actions">
+                <a-tooltip v-if="item.previewable" title="预览">
+                  <button
+                    type="button"
+                    class="chat-artifact-item__action"
+                    :aria-label="`预览 ${item.name}`"
+                    @click="previewArtifact(item)"
+                  >
+                    <Icon icon="i-mdi:eye-outline" />
+                  </button>
+                </a-tooltip>
+                <a-tooltip title="下载">
+                  <button
+                    type="button"
+                    class="chat-artifact-item__action"
+                    :aria-label="`下载 ${item.name}`"
+                    @click="handleDownloadArtifact(item)"
+                  >
+                    <Icon icon="i-mdi:download-outline" />
+                  </button>
+                </a-tooltip>
+              </div>
+            </div>
+            <div v-if="artifactTruncated" class="chat-artifact-panel__truncated">
+              文件较多,仅显示最近 {{ artifacts.length }} 个
+            </div>
+          </template>
+        </a-spin>
+      </div>
+    </aside>
+
+    <!-- 产物预览:文本 / Markdown / CSV / 图片 / PDF / HTML(同源 iframe) -->
+    <BasicModal
+      v-model:open="artifactPreview.visible"
+      :title="artifactPreview.item?.name || '产物预览'"
+      :footer="null"
+      :width="920"
+      :min-height="320"
+      :can-fullscreen="true"
+      :destroy-on-close="true"
+      wrap-class-name="artifact-preview-modal"
+      @cancel="closeArtifactPreview"
+    >
+      <div class="artifact-preview">
+        <a-spin v-if="artifactPreview.loading" class="artifact-preview__loading" />
+        <div v-else-if="artifactPreview.error" class="artifact-preview__error">{{ artifactPreview.error }}</div>
+        <template v-else-if="artifactPreview.item">
+          <iframe
+            v-if="artifactPreview.item.kind === 'html'"
+            class="artifact-preview__html"
+            :srcdoc="artifactPreview.content"
+          ></iframe>
+          <img
+            v-else-if="artifactPreview.item.kind === 'image'"
+            class="artifact-preview__image"
+            :src="artifactPreview.objectUrl"
+            :alt="artifactPreview.item.name"
+            @error="handleArtifactImageError"
+          />
+          <iframe
+            v-else-if="artifactPreview.item.kind === 'pdf'"
+            class="artifact-preview__pdf"
+            :src="artifactPreview.objectUrl"
+          ></iframe>
+          <div v-else-if="artifactPreview.item.kind === 'csv'" class="artifact-preview__table-wrap">
+            <table v-if="artifactPreview.csvRows.length" class="artifact-preview__table">
+              <thead>
+                <tr>
+                  <th v-for="(cell, index) in artifactPreview.csvHeader" :key="index">{{ cell }}</th>
+                </tr>
+              </thead>
+              <tbody>
+                <tr v-for="(row, rowIndex) in artifactPreview.csvRows" :key="rowIndex">
+                  <td v-for="(cell, cellIndex) in row" :key="cellIndex">{{ cell }}</td>
+                </tr>
+              </tbody>
+            </table>
+            <pre v-else class="artifact-preview__text">{{ artifactPreview.content }}</pre>
+          </div>
+          <pre v-else class="artifact-preview__text">{{ artifactPreview.content }}</pre>
+          <div v-if="artifactPreview.truncated" class="artifact-preview__hint"> 内容较大,仅预览前一部分。 </div>
+        </template>
+      </div>
+    </BasicModal>
+
     <!-- 原图预览:点击附件时先换一个新签地址再打开,避免预签名 URL 过期后 403 -->
     <a-modal
       v-if="previewVisible"
@@ -724,8 +871,17 @@
   import { getDocumentChunkContext, getDocumentContent } from '@/workbench/api/kb';
   import { getOnboardingChecklist } from '@/workbench/api/audit';
   import { aiUpload } from '@/workbench/api/http';
+  import {
+    downloadArtifact,
+    fetchArtifactBlob,
+    getArtifactContent,
+    listArtifacts,
+    type ArtifactItem,
+  } from '@/workbench/api/artifact';
+  import { formatSize } from '@/core/components/Upload/src/helper';
   import { scenarioPackMcpOptions, scenarioPackOptions } from '@/workbench/api/pack';
   import { visibleSkillOptions } from '@/workbench/api/skill';
+  import { BasicModal } from '@/core/components/Modal';
   import { useAccountStore } from '@/core/store/modules/account';
   import { useUserStore } from '@/core/store/modules/case';
   import { Icon } from '@/core/components/Icon';
@@ -1025,12 +1181,250 @@
   /** 工作台内联样式(仅在实测到高度时生效) */
   const workbenchStyle = computed(() => (workbenchHeight.value ? { height: workbenchHeight.value } : {}));
 
+  /** 当前会话(用于标题栏与产物面板判断) */
+  const currentSession = computed(() =>
+    sessions.value.find((item) => String(item.id) === String(currentSessionId.value)),
+  );
+
   /** 当前会话标题(用于聊天区顶部上下文栏) */
-  const currentSessionTitle = computed(() => {
-    const current = sessions.value.find((item) => String(item.id) === String(currentSessionId.value));
-    return current?.sessionTitle || '当前会话';
+  const currentSessionTitle = computed(() => currentSession.value?.sessionTitle || '当前会话');
+
+  /** 产物面板只支持智能工作台会话(source=workbench,按会话隔离工作区) */
+  const artifactSupported = computed(() => currentSession.value?.source === 'workbench');
+
+  // ==================== 产物面板(直接扫描会话工作区磁盘) ====================
+
+  /** 面板开关(持久化;默认收起) */
+  const artifactPanelOpen = ref(localStorage.getItem('chat.artifactPanelOpen') === '1');
+  const artifacts = ref<ArtifactItem[]>([]);
+  const artifactLoading = ref(false);
+  const artifactError = ref('');
+  const artifactTruncated = ref(false);
+  let artifactRefreshTimer: ReturnType<typeof setTimeout> | undefined;
+
+  /** 产物预览弹窗状态 */
+  const artifactPreview = reactive<{
+    visible: boolean;
+    loading: boolean;
+    error: string;
+    item: ArtifactItem | null;
+    content: string;
+    truncated: boolean;
+    objectUrl: string;
+    csvHeader: string[];
+    csvRows: string[][];
+  }>({
+    visible: false,
+    loading: false,
+    error: '',
+    item: null,
+    content: '',
+    truncated: false,
+    objectUrl: '',
+    csvHeader: [],
+    csvRows: [],
   });
 
+  /** 展开 / 收起产物面板 */
+  const toggleArtifactPanel = (open?: boolean) => {
+    const next = typeof open === 'boolean' ? open : !artifactPanelOpen.value;
+    artifactPanelOpen.value = next;
+    localStorage.setItem('chat.artifactPanelOpen', next ? '1' : '0');
+    if (next && artifactSupported.value) {
+      void loadArtifacts();
+    }
+  };
+
+  /** 加载当前会话产物列表 */
+  const loadArtifacts = async () => {
+    const sessionId = currentSessionId.value;
+    if (!sessionId || !artifactSupported.value) {
+      artifacts.value = [];
+      artifactTruncated.value = false;
+      return;
+    }
+    artifactLoading.value = true;
+    artifactError.value = '';
+    try {
+      const res = await listArtifacts(sessionId);
+      if (String(currentSessionId.value) !== String(sessionId)) {
+        return;
+      }
+      artifacts.value = res?.items ?? [];
+      artifactTruncated.value = !!res?.truncated;
+    } catch (error) {
+      if (String(currentSessionId.value) === String(sessionId)) {
+        artifactError.value = (error as Error)?.message || '产物加载失败';
+      }
+    } finally {
+      if (String(currentSessionId.value) === String(sessionId)) {
+        artifactLoading.value = false;
+      }
+    }
+  };
+
+  /** 工具完成后防抖刷新(write_file / edit_file / execute 等) */
+  const scheduleArtifactRefresh = () => {
+    if (!currentSessionId.value) {
+      return;
+    }
+    if (artifactRefreshTimer) {
+      clearTimeout(artifactRefreshTimer);
+    }
+    artifactRefreshTimer = setTimeout(() => {
+      artifactRefreshTimer = undefined;
+      if (artifactPanelOpen.value) {
+        void loadArtifacts();
+      }
+    }, 500);
+  };
+
+  /** 产物文件图标(全部使用已 safelist 的 mdi 图标) */
+  const artifactIcon = (item: ArtifactItem) => {
+    if (item.kind === 'image') {
+      return 'i-mdi:image-outline';
+    }
+    if (item.kind === 'pdf') {
+      return 'i-mdi:file-pdf-box';
+    }
+    if (item.kind === 'csv') {
+      return 'i-mdi:file-delimited-outline';
+    }
+    return 'i-mdi:file-document-outline';
+  };
+
+  /** 文件大小展示 */
+  const formatArtifactSize = (size?: number) => {
+    if (size === undefined || size === null) {
+      return '-';
+    }
+    return size <= 0 ? '0B' : formatSize(size);
+  };
+
+  /** 修改时间展示 */
+  const formatArtifactTime = (value?: string) => {
+    if (!value) {
+      return '-';
+    }
+    const date = new Date(value);
+    if (Number.isNaN(date.getTime())) {
+      return value;
+    }
+    const pad = (num: number) => String(num).padStart(2, '0');
+    return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
+  };
+
+  /** 简单 CSV 解析(支持引号与逗号转义;仅用于预览) */
+  const parseArtifactCsv = (text: string): string[][] => {
+    const rows: string[][] = [];
+    let row: string[] = [];
+    let cell = '';
+    let quoted = false;
+    for (let i = 0; i < text.length; i += 1) {
+      const ch = text[i];
+      if (quoted) {
+        if (ch === '"' && text[i + 1] === '"') {
+          cell += '"';
+          i += 1;
+        } else if (ch === '"') {
+          quoted = false;
+        } else {
+          cell += ch;
+        }
+      } else if (ch === '"') {
+        quoted = true;
+      } else if (ch === ',') {
+        row.push(cell);
+        cell = '';
+      } else if (ch === '\n') {
+        row.push(cell.replace(/\r$/, ''));
+        rows.push(row);
+        row = [];
+        cell = '';
+      } else {
+        cell += ch;
+      }
+    }
+    if (cell || row.length) {
+      row.push(cell.replace(/\r$/, ''));
+      rows.push(row);
+    }
+    return rows;
+  };
+
+  /** 预览产物 */
+  const previewArtifact = async (item: ArtifactItem) => {
+    const sessionId = currentSessionId.value;
+    if (!sessionId) {
+      return;
+    }
+    closeArtifactPreview();
+    artifactPreview.visible = true;
+    artifactPreview.item = item;
+    artifactPreview.loading = true;
+    try {
+      if (item.kind === 'image' || item.kind === 'pdf') {
+        let blob = await fetchArtifactBlob(sessionId, item.path);
+        // 部分运行环境返回的 blob 不带 type:按列表元信息补上,图片/PDF 才能正确解码
+        if (!blob.type && item.mime) {
+          blob = new Blob([blob], { type: item.mime });
+        }
+        artifactPreview.objectUrl = URL.createObjectURL(blob);
+      } else {
+        const res = await getArtifactContent(sessionId, item.path);
+        artifactPreview.content = res?.text ?? '';
+        artifactPreview.truncated = !!res?.truncated;
+        if (item.kind === 'csv') {
+          const rows = parseArtifactCsv(artifactPreview.content);
+          artifactPreview.csvHeader = rows[0] ?? [];
+          artifactPreview.csvRows = rows.slice(1, 201);
+          if (rows.length > 201) {
+            artifactPreview.truncated = true;
+          }
+        }
+      }
+    } catch (error) {
+      artifactPreview.error = (error as Error)?.message || '预览加载失败';
+    } finally {
+      artifactPreview.loading = false;
+    }
+  };
+
+  /** 图片解码失败:给出可读原因并保留下载入口(如 HEIC/损坏文件) */
+  const handleArtifactImageError = () => {
+    artifactPreview.error = '图片加载失败:文件可能已损坏或当前浏览器不支持该图片格式,请下载后查看。';
+  };
+
+  /** 关闭预览并释放 blob URL */
+  const closeArtifactPreview = () => {
+    if (artifactPreview.objectUrl) {
+      URL.revokeObjectURL(artifactPreview.objectUrl);
+      artifactPreview.objectUrl = '';
+    }
+    artifactPreview.visible = false;
+    artifactPreview.loading = false;
+    artifactPreview.error = '';
+    artifactPreview.item = null;
+    artifactPreview.content = '';
+    artifactPreview.truncated = false;
+    artifactPreview.csvHeader = [];
+    artifactPreview.csvRows = [];
+  };
+
+  /** 下载产物:桌面端走现有下载管理器,浏览器端走 blob 另存 */
+  const handleDownloadArtifact = async (item: ArtifactItem) => {
+    const sessionId = currentSessionId.value;
+    if (!sessionId) {
+      antMessage.warning('请先选择会话');
+      return;
+    }
+    try {
+      await downloadArtifact(sessionId, item);
+    } catch (error) {
+      antMessage.error((error as Error)?.message || '产物下载失败');
+    }
+  };
+
   /**
    * 按父容器实测可用高度:视口高度 − 容器顶部偏移 − 父容器底部内边距。
    *
@@ -1088,6 +1482,11 @@
   onBeforeUnmount(() => {
     workbenchTimers.forEach((timer) => window.clearTimeout(timer));
     workbenchTimers = [];
+    if (artifactRefreshTimer) {
+      clearTimeout(artifactRefreshTimer);
+      artifactRefreshTimer = undefined;
+    }
+    closeArtifactPreview();
     window.removeEventListener('resize', syncWorkbenchHeight);
     workbenchResizeObserver?.disconnect();
     workbenchResizeObserver = undefined;
@@ -1957,6 +2356,10 @@
     currentSessionId.value = undefined;
     messages.value = [];
     expandedToolKeys.value = [];
+    artifacts.value = [];
+    artifactError.value = '';
+    artifactTruncated.value = false;
+    closeArtifactPreview();
     inputText.value = '';
     regenerateCheck.value = null;
     regenerateCheckMessageId.value = undefined;
@@ -2075,6 +2478,14 @@
     // 最后一轮的重新生成可用性由后端预检决定(写操作轮次置灰)
     void refreshRegenerateCheck();
     scrollToBottomSoon();
+    // 产物面板按会话隔离:切换会话时清空旧列表,面板打开则立即加载新会话产物
+    artifacts.value = [];
+    artifactError.value = '';
+    artifactTruncated.value = false;
+    closeArtifactPreview();
+    if (artifactPanelOpen.value && artifactSupported.value) {
+      void loadArtifacts();
+    }
   };
 
   /** 会话「更多操作」:置顶 / 重命名 / 结束任务 */
@@ -2347,6 +2758,8 @@
       msg.status = '3';
     }
     finishStream();
+    // 中止时已落盘的部分产物也要展示
+    scheduleArtifactRefresh();
   };
 
   /** 处置待确认的工具调用:写入结果后建立恢复流继续生成 */
@@ -2466,6 +2879,10 @@
             part.toolName = event.toolName;
           }
         }
+        if (event.state === 'SUCCESS') {
+          // write_file / edit_file / execute 等工具完成后刷新产物列表(防抖)
+          scheduleArtifactRefresh();
+        }
         break;
       }
       case 'tool_confirm': {
@@ -2561,6 +2978,8 @@
         // done 载荷与 references 事件同结构:兜底回填(防 references 事件丢失)
         mergeMessageSources(msg, event.references);
         finishStream();
+        // 本轮产物兜底刷新(tool_result 事件可能被截断或丢失)
+        scheduleArtifactRefresh();
         // 重新生成成功:旧回答快照已无意义,刷新预检(新一轮回答可能含写操作)
         regenerateBackup = null;
         void refreshRegenerateCheck();
@@ -2579,6 +2998,7 @@
         msg.durationMs = event.durationMs ?? msg.durationMs;
         msg.status = '3';
         finishStream();
+        scheduleArtifactRefresh();
         regenerateBackup = null;
         void refreshRegenerateCheck();
         break;
@@ -2596,6 +3016,7 @@
         msg.errorMsg = event.message || '对话失败';
         antMessage.error(msg.errorMsg);
         finishStream();
+        scheduleArtifactRefresh();
         regenerateBackup = null;
         break;
       }
@@ -2648,6 +3069,10 @@
       );
     }
     await getSessions();
+    // 新会话创建完成后按需加载产物(面板打开时立即显示空态/已有文件)
+    if (artifactPanelOpen.value && artifactSupported.value) {
+      void loadArtifacts();
+    }
     return session.id;
   };
 
@@ -2907,6 +3332,10 @@
     finishStream();
     currentSessionId.value = undefined;
     messages.value = [];
+    artifacts.value = [];
+    artifactError.value = '';
+    artifactTruncated.value = false;
+    closeArtifactPreview();
     sessionResources.value = [];
     pinnedExpert.value = undefined;
     planModeEnabled.value = false;
@@ -4747,6 +5176,329 @@
     margin-top: 6px;
   }
 
+  /* ==================== 产物面板 ==================== */
+
+  .chat-context-bar__artifact-toggle {
+    position: relative;
+    display: inline-flex;
+    align-items: center;
+    justify-content: center;
+    width: 28px;
+    height: 28px;
+    padding: 0;
+    color: var(--wb-text-2, #667085);
+    font-size: 18px;
+    cursor: pointer;
+    background: transparent;
+    border: 0;
+    border-radius: 6px;
+    transition:
+      background-color 0.15s,
+      color 0.15s;
+  }
+
+  .chat-context-bar__artifact-toggle:hover,
+  .chat-context-bar__artifact-toggle.is-active {
+    color: #2448c9;
+    background: #e8eeff;
+  }
+
+  .chat-context-bar__artifact-count {
+    position: absolute;
+    top: -2px;
+    right: -4px;
+    min-width: 14px;
+    height: 14px;
+    padding: 0 4px;
+    color: #fff;
+    font-size: 9px;
+    line-height: 14px;
+    text-align: center;
+    background: #2448c9;
+    border-radius: 999px;
+  }
+
+  .chat-artifact-panel {
+    display: flex;
+    flex: 0 0 320px;
+    flex-direction: column;
+    min-width: 260px;
+    max-width: 380px;
+    overflow: hidden;
+    background: #fff;
+    border: 1px solid var(--wb-border, #e7ebf3);
+    border-radius: 12px;
+    box-shadow: 0 2px 8px rgb(15 23 42 / 3%);
+  }
+
+  .chat-artifact-panel__header {
+    display: flex;
+    align-items: center;
+    justify-content: space-between;
+    padding: 12px 14px;
+    border-bottom: 1px solid var(--wb-border, #e7ebf3);
+  }
+
+  .chat-artifact-panel__heading {
+    display: flex;
+    gap: 8px;
+    align-items: center;
+  }
+
+  .chat-artifact-panel__title {
+    color: var(--wb-text, #111827);
+    font-size: 14px;
+    font-weight: 600;
+  }
+
+  .chat-artifact-panel__count {
+    min-width: 20px;
+    padding: 0 6px;
+    color: #2448c9;
+    font-size: 11px;
+    line-height: 18px;
+    text-align: center;
+    background: #e8eeff;
+    border-radius: 999px;
+  }
+
+  .chat-artifact-panel__actions {
+    display: flex;
+    gap: 2px;
+    align-items: center;
+  }
+
+  .chat-artifact-panel__icon-btn {
+    display: inline-flex;
+    align-items: center;
+    justify-content: center;
+    width: 26px;
+    height: 26px;
+    padding: 0;
+    color: var(--wb-text-2, #667085);
+    font-size: 16px;
+    cursor: pointer;
+    background: transparent;
+    border: 0;
+    border-radius: 6px;
+  }
+
+  .chat-artifact-panel__icon-btn:hover {
+    color: #2448c9;
+    background: #e8eeff;
+  }
+
+  .chat-artifact-panel__icon-btn:disabled {
+    cursor: not-allowed;
+    opacity: 0.5;
+  }
+
+  .chat-artifact-panel__body {
+    flex: 1;
+    min-height: 0;
+    padding: 8px;
+    overflow-y: auto;
+  }
+
+  .chat-artifact-panel__error {
+    display: flex;
+    flex-direction: column;
+    gap: 4px;
+    padding: 16px 8px;
+    color: #d92d20;
+    font-size: 12px;
+    text-align: center;
+  }
+
+  .chat-artifact-panel__truncated {
+    padding: 8px;
+    color: var(--wb-text-2, #667085);
+    font-size: 11px;
+    text-align: center;
+  }
+
+  .chat-artifact-item {
+    display: flex;
+    gap: 8px;
+    align-items: flex-start;
+    padding: 8px;
+    border-radius: 8px;
+  }
+
+  .chat-artifact-item:hover {
+    background: #f6f8fc;
+  }
+
+  .chat-artifact-item__icon {
+    display: inline-flex;
+    flex: 0 0 28px;
+    align-items: center;
+    justify-content: center;
+    width: 28px;
+    height: 28px;
+    color: #2448c9;
+    font-size: 18px;
+    background: #eef3ff;
+    border-radius: 6px;
+  }
+
+  .chat-artifact-item__main {
+    flex: 1;
+    min-width: 0;
+  }
+
+  .chat-artifact-item__name {
+    overflow: hidden;
+    color: var(--wb-text, #111827);
+    font-size: 13px;
+    line-height: 18px;
+    text-overflow: ellipsis;
+    white-space: nowrap;
+  }
+
+  .chat-artifact-item__meta {
+    display: flex;
+    gap: 8px;
+    margin-top: 2px;
+    color: var(--wb-text-2, #667085);
+    font-size: 11px;
+  }
+
+  .chat-artifact-item__path {
+    margin-top: 2px;
+    overflow: hidden;
+    color: var(--wb-text-2, #98a2b3);
+    font-size: 11px;
+    text-overflow: ellipsis;
+    white-space: nowrap;
+  }
+
+  .chat-artifact-item__actions {
+    display: flex;
+    flex: 0 0 auto;
+    gap: 2px;
+    opacity: 0;
+    transition: opacity 0.15s;
+  }
+
+  .chat-artifact-item:hover .chat-artifact-item__actions,
+  .chat-artifact-item__actions:focus-within {
+    opacity: 1;
+  }
+
+  .chat-artifact-item__action {
+    display: inline-flex;
+    align-items: center;
+    justify-content: center;
+    width: 26px;
+    height: 26px;
+    padding: 0;
+    color: var(--wb-text-2, #667085);
+    font-size: 16px;
+    cursor: pointer;
+    background: transparent;
+    border: 0;
+    border-radius: 6px;
+  }
+
+  .chat-artifact-item__action:hover {
+    color: #2448c9;
+    background: #e8eeff;
+  }
+
+  .is-spinning {
+    animation: artifact-spin 1s linear infinite;
+  }
+
+  @keyframes artifact-spin {
+    to {
+      transform: rotate(360deg);
+    }
+  }
+
+  .artifact-preview__loading {
+    display: flex;
+    justify-content: center;
+    padding: 40px 0;
+  }
+
+  .artifact-preview__error {
+    padding: 24px;
+    color: #d92d20;
+    text-align: center;
+  }
+
+  .artifact-preview__html {
+    width: 100%;
+    height: 60vh;
+    background: #fff;
+    border: 1px solid var(--wb-border, #e7ebf3);
+    border-radius: 8px;
+  }
+
+  .artifact-preview__image {
+    display: block;
+    max-width: 100%;
+    max-height: 65vh;
+    margin: 0 auto;
+  }
+
+  .artifact-preview__pdf {
+    width: 100%;
+    height: 65vh;
+    border: 1px solid var(--wb-border, #e7ebf3);
+    border-radius: 8px;
+  }
+
+  .artifact-preview__table-wrap {
+    max-height: 60vh;
+    overflow: auto;
+    border: 1px solid var(--wb-border, #e7ebf3);
+    border-radius: 8px;
+  }
+
+  .artifact-preview__table {
+    width: 100%;
+    border-collapse: collapse;
+    font-size: 12px;
+  }
+
+  .artifact-preview__table th,
+  .artifact-preview__table td {
+    padding: 6px 8px;
+    text-align: left;
+    white-space: nowrap;
+    border-bottom: 1px solid #eef1f6;
+  }
+
+  .artifact-preview__table th {
+    position: sticky;
+    top: 0;
+    font-weight: 600;
+    background: #f8fafc;
+  }
+
+  .artifact-preview__text {
+    max-height: 60vh;
+    margin: 0;
+    padding: 12px;
+    overflow: auto;
+    font-family: 'JetBrains Mono', 'Fira Code', Consolas, monospace;
+    font-size: 12px;
+    line-height: 1.6;
+    white-space: pre-wrap;
+    word-break: break-word;
+    background: #f8fafc;
+    border: 1px solid var(--wb-border, #e7ebf3);
+    border-radius: 8px;
+  }
+
+  .artifact-preview__hint {
+    margin-top: 8px;
+    color: var(--wb-text-2, #667085);
+    font-size: 12px;
+  }
+
   @media (max-width: 900px) {
     .chat-workbench {
       gap: 8px;
@@ -4776,5 +5528,16 @@
     .message-area {
       padding: 16px;
     }
+
+    .chat-artifact-panel {
+      position: fixed;
+      top: 8px;
+      right: 8px;
+      bottom: 8px;
+      z-index: 1100;
+      width: min(360px, calc(100vw - 16px));
+      max-width: none;
+      box-shadow: 0 12px 32px rgb(15 23 42 / 18%);
+    }
   }
 </style>

+ 21 - 0
ai-server/src/main/java/com/zsjz/ai/common/storage/StorageLayout.java

@@ -320,6 +320,27 @@ public class StorageLayout {
         return caseAiRoot(caseId).resolve(CASE_AI_WORKBENCH_DIR);
     }
 
+    /**
+     * 智能工作台会话工作区:{@code cases/{caseId}/ai/workbench/{sessionId}}。
+     *
+     * <p>会话产物(模型通过文件工具写入的文件)与框架运行目录都在这个目录下;
+     * 产物列表只展示排除系统目录后的普通文件。</p>
+     */
+    public Path caseWorkbenchSessionDir(long caseId, long sessionId) {
+        return caseWorkbenchDir(caseId).resolve(Long.toString(sessionId));
+    }
+
+    /**
+     * 删除智能工作台会话工作区(含会话产物)。
+     *
+     * <p>只允许删除 {@code workbench/{sessionId}} 这一会话独立目录;
+     * 普通 chat 会话共享 {@code agents/{agentId}/{userId}} 用户工作区,
+     * 不能因删除单个会话而清空其他会话仍在使用的文件。</p>
+     */
+    public void deleteWorkbenchSessionDir(long caseId, long sessionId) {
+        FileUtil.del(caseWorkbenchSessionDir(caseId, sessionId).toFile());
+    }
+
     /** 智能工作台共享副本目录:{@code cases/{caseId}/ai/workbench/shared}。 */
     public Path workbenchSharedDir(long caseId) {
         return caseWorkbenchDir(caseId).resolve(WORKBENCH_SHARED_DIR);

+ 111 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/controller/AiArtifactController.java

@@ -0,0 +1,111 @@
+package com.zsjz.ai.module.ai.controller;
+
+import com.zsjz.ai.common.compat.R;
+import com.zsjz.ai.module.ai.domain.vo.AiArtifactContentVo;
+import com.zsjz.ai.module.ai.domain.vo.AiArtifactListVo;
+import com.zsjz.ai.module.ai.service.IAiArtifactService;
+import lombok.RequiredArgsConstructor;
+import org.springframework.core.io.FileSystemResource;
+import org.springframework.core.io.Resource;
+import org.springframework.http.CacheControl;
+import org.springframework.http.ContentDisposition;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.InvalidMediaTypeException;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.validation.annotation.Validated;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.nio.charset.StandardCharsets;
+
+/**
+ * AI 会话产物 Controller。
+ *
+ * <p>产物直接来自智能工作台会话工作区磁盘,不落库。所有接口先校验
+ * 「当前用户 + 当前案件 + workbench 会话」,文件路径只接受会话内相对路径。</p>
+ *
+ * @author cc
+ */
+@Validated
+@RequiredArgsConstructor
+@RestController
+@RequestMapping("/ai/chat/session/{sessionId}/artifacts")
+public class AiArtifactController {
+
+    private final IAiArtifactService artifactService;
+
+    /**
+     * 查询会话产物列表。
+     *
+     * @param sessionId 会话主键
+     */
+    @GetMapping
+    public R<AiArtifactListVo> list(@PathVariable("sessionId") Long sessionId) {
+        return R.ok(artifactService.list(sessionId));
+    }
+
+    /**
+     * 读取文本类产物内容(HTML 返回源码,由前端同源 iframe 渲染)。
+     *
+     * @param sessionId 会话主键
+     * @param path      相对会话工作区根目录的路径
+     */
+    @GetMapping("/content")
+    public R<AiArtifactContentVo> content(@PathVariable("sessionId") Long sessionId,
+                                          @RequestParam("path") String path) {
+        return R.ok(artifactService.content(sessionId, path));
+    }
+
+    /**
+     * 下载 / 内联预览产物文件。
+     *
+     * @param sessionId 会话主键
+     * @param path      相对会话工作区根目录的路径
+     * @param inline    是否内联(仅图片 / PDF 生效)
+     */
+    @GetMapping("/download")
+    public ResponseEntity<Resource> download(@PathVariable("sessionId") Long sessionId,
+                                             @RequestParam("path") String path,
+                                             @RequestParam(value = "inline", defaultValue = "false") boolean inline) {
+        IAiArtifactService.ArtifactFile file = artifactService.download(sessionId, path, inline);
+        boolean inlineSafe = inline && isInlineSafe(file.kind());
+        ContentDisposition disposition = (inlineSafe
+                ? ContentDisposition.inline()
+                : ContentDisposition.attachment())
+                .filename(file.fileName(), StandardCharsets.UTF_8)
+                .build();
+        return ResponseEntity.ok()
+                .contentType(resolveMediaType(file, inlineSafe))
+                .contentLength(file.size())
+                .cacheControl(CacheControl.noStore())
+                .header(HttpHeaders.CONTENT_DISPOSITION, disposition.toString())
+                .header("X-Content-Type-Options", "nosniff")
+                .body(new FileSystemResource(file.path()));
+    }
+
+    /**
+     * 内联预览仅开放图片与 PDF;HTML/SVG 等可执行内容强制下载。
+     */
+    private static boolean isInlineSafe(String kind) {
+        return "image".equals(kind) || "pdf".equals(kind);
+    }
+
+    /**
+     * 解析响应 Content-Type:下载 HTML/SVG 时强制二进制,避免浏览器直接当页面打开。
+     */
+    private static MediaType resolveMediaType(IAiArtifactService.ArtifactFile file, boolean inlineSafe) {
+        if (!inlineSafe && ("html".equals(file.kind())
+                || "image/svg+xml".equalsIgnoreCase(file.mime()))) {
+            return MediaType.APPLICATION_OCTET_STREAM;
+        }
+        try {
+            return MediaType.parseMediaType(file.mime());
+        } catch (InvalidMediaTypeException e) {
+            return MediaType.APPLICATION_OCTET_STREAM;
+        }
+    }
+}

+ 59 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiArtifactContentVo.java

@@ -0,0 +1,59 @@
+package com.zsjz.ai.module.ai.domain.vo;
+
+import lombok.Data;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.time.LocalDateTime;
+
+/**
+ * AI 会话产物文本预览视图(HTML 也以源码文本返回,由前端同源 iframe 渲染)。
+ *
+ * @author cc
+ */
+@Data
+public class AiArtifactContentVo implements Serializable {
+
+    @Serial
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 相对会话工作区根目录的 POSIX 路径
+     */
+    private String path;
+
+    /**
+     * 文件名
+     */
+    private String name;
+
+    /**
+     * 文件类别
+     */
+    private String kind;
+
+    /**
+     * MIME 类型
+     */
+    private String mime;
+
+    /**
+     * 文件大小(字节)
+     */
+    private Long size;
+
+    /**
+     * 最后修改时间
+     */
+    private LocalDateTime lastModified;
+
+    /**
+     * 文本内容(可能被预览上限截断)
+     */
+    private String text;
+
+    /**
+     * 内容是否被预览上限截断
+     */
+    private Boolean truncated;
+}

+ 39 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiArtifactListVo.java

@@ -0,0 +1,39 @@
+package com.zsjz.ai.module.ai.domain.vo;
+
+import lombok.Data;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.util.List;
+
+/**
+ * AI 会话产物列表视图。
+ *
+ * @author cc
+ */
+@Data
+public class AiArtifactListVo implements Serializable {
+
+    @Serial
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 会话主键
+     */
+    private Long sessionId;
+
+    /**
+     * 产物文件(按最后修改时间倒序)
+     */
+    private List<AiArtifactVo> items;
+
+    /**
+     * 本次返回的文件数
+     */
+    private Integer total;
+
+    /**
+     * 是否因数量/深度上限被截断
+     */
+    private Boolean truncated;
+}

+ 59 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiArtifactVo.java

@@ -0,0 +1,59 @@
+package com.zsjz.ai.module.ai.domain.vo;
+
+import lombok.Data;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.time.LocalDateTime;
+
+/**
+ * AI 会话产物文件视图(会话工作区内的普通文件)。
+ *
+ * @author cc
+ */
+@Data
+public class AiArtifactVo implements Serializable {
+
+    @Serial
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 相对会话工作区根目录的 POSIX 路径(含文件名)
+     */
+    private String path;
+
+    /**
+     * 文件名
+     */
+    private String name;
+
+    /**
+     * 文件类别:text / markdown / csv / json / image / pdf / html / office / archive / other
+     */
+    private String kind;
+
+    /**
+     * MIME 类型
+     */
+    private String mime;
+
+    /**
+     * 文件大小(字节)
+     */
+    private Long size;
+
+    /**
+     * 最后修改时间
+     */
+    private LocalDateTime lastModified;
+
+    /**
+     * 是否支持在线预览
+     */
+    private Boolean previewable;
+
+    /**
+     * 是否支持下载(当前所有普通文件均为 true)
+     */
+    private Boolean downloadable;
+}

+ 57 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/service/IAiArtifactService.java

@@ -0,0 +1,57 @@
+package com.zsjz.ai.module.ai.service;
+
+import com.zsjz.ai.module.ai.domain.vo.AiArtifactContentVo;
+import com.zsjz.ai.module.ai.domain.vo.AiArtifactListVo;
+
+import java.nio.file.Path;
+
+/**
+ * AI 会话产物服务:直接扫描智能工作台会话工作区磁盘目录。
+ *
+ * <p>产物不落库:文件即事实,覆盖 {@code write_file} / {@code edit_file} / {@code execute}
+ * 等所有工具产生的文件。仅支持 {@code ai_session.source = workbench} 的会话。</p>
+ *
+ * @author cc
+ */
+public interface IAiArtifactService {
+
+    /**
+     * 列出会话产物。
+     *
+     * @param sessionId 会话主键
+     * @return 产物列表(无产物时 items 为空)
+     */
+    AiArtifactListVo list(Long sessionId);
+
+    /**
+     * 读取文本类产物内容(含 HTML 源码)。
+     *
+     * @param sessionId 会话主键
+     * @param path      相对会话工作区根目录的路径
+     * @return 文本内容(可能被预览上限截断)
+     */
+    AiArtifactContentVo content(Long sessionId, String path);
+
+    /**
+     * 解析可下载的产物文件。
+     *
+     * @param sessionId 会话主键
+     * @param path      相对会话工作区根目录的路径
+     * @param inline    是否用于内联预览
+     * @return 文件元信息
+     */
+    ArtifactFile download(Long sessionId, String path, boolean inline);
+
+    /**
+     * 可下载产物文件。
+     *
+     * @param path     已校验的真实文件路径
+     * @param fileName 文件名
+     * @param kind     文件类别
+     * @param mime     MIME 类型
+     * @param size     文件大小
+     * @param inline   是否内联预览
+     */
+    record ArtifactFile(Path path, String fileName, String kind, String mime, long size, boolean inline) {
+    }
+}

+ 438 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiArtifactServiceImpl.java

@@ -0,0 +1,438 @@
+package com.zsjz.ai.module.ai.service.impl;
+
+import com.zsjz.ai.common.compat.ServiceException;
+import com.zsjz.ai.common.compat.StringUtils;
+import com.zsjz.ai.common.storage.StorageLayout;
+import com.zsjz.ai.module.ai.domain.AiSession;
+import com.zsjz.ai.module.ai.domain.vo.AiArtifactContentVo;
+import com.zsjz.ai.module.ai.domain.vo.AiArtifactListVo;
+import com.zsjz.ai.module.ai.domain.vo.AiArtifactVo;
+import com.zsjz.ai.module.ai.service.IAiArtifactService;
+import com.zsjz.ai.module.ai.service.IAiSessionService;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.FileVisitOption;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.InvalidPathException;
+import java.nio.file.Path;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * AI 会话产物服务实现:直接扫描智能工作台会话工作区。
+ *
+ * <p>不落库、不复制副本:文件是唯一事实来源。扫描时排除框架运行目录与共享输入副本,
+ * 只返回会话根下的普通文件(含 {@code outputs/} 等业务目录)。</p>
+ *
+ * @author cc
+ */
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class AiArtifactServiceImpl implements IAiArtifactService {
+
+    /**
+     * 扫描最大深度(相对会话根)
+     */
+    private static final int MAX_DEPTH = 8;
+
+    /**
+     * 单次最多返回的文件数
+     */
+    private static final int MAX_FILES = 500;
+
+    /**
+     * 文本预览最多读取的字节数
+     */
+    private static final int MAX_PREVIEW_BYTES = 1024 * 1024;
+
+    /**
+     * 文本预览最多返回的字符数
+     */
+    private static final int MAX_PREVIEW_CHARS = 200_000;
+
+    /**
+     * 框架运行目录 / 共享输入副本:不作为产物展示,也不允许通过下载接口访问
+     */
+    private static final Set<String> RESERVED_DIRS = Set.of(
+            "agents", "default", "memory", ".skills-cache", ".agentscope-runtime",
+            "large_tool_results", "sessions", "events", "logs", "tmp", ".project", "shared");
+
+    /**
+     * 支持文本预览的类别
+     */
+    private static final Set<String> TEXT_KINDS = Set.of("text", "markdown", "csv", "json", "html");
+
+    /**
+     * 支持在线预览的类别
+     */
+    private static final Set<String> PREVIEWABLE_KINDS = Set.of(
+            "text", "markdown", "csv", "json", "image", "pdf", "html");
+
+    /**
+     * 后缀 → MIME(覆盖常见模型产物;未知类型回退 probeContentType / octet-stream)
+     */
+    private static final Map<String, String> MIME_BY_SUFFIX = Map.ofEntries(
+            Map.entry("txt", "text/plain"),
+            Map.entry("log", "text/plain"),
+            Map.entry("md", "text/markdown"),
+            Map.entry("markdown", "text/markdown"),
+            Map.entry("csv", "text/csv"),
+            Map.entry("json", "application/json"),
+            Map.entry("yaml", "text/yaml"),
+            Map.entry("yml", "text/yaml"),
+            Map.entry("xml", "application/xml"),
+            Map.entry("html", "text/html"),
+            Map.entry("htm", "text/html"),
+            Map.entry("css", "text/css"),
+            Map.entry("js", "text/javascript"),
+            Map.entry("ts", "text/plain"),
+            Map.entry("py", "text/plain"),
+            Map.entry("sql", "text/plain"),
+            Map.entry("sh", "text/plain"),
+            Map.entry("bat", "text/plain"),
+            Map.entry("ps1", "text/plain"),
+            Map.entry("java", "text/plain"),
+            Map.entry("kt", "text/plain"),
+            Map.entry("properties", "text/plain"),
+            Map.entry("ini", "text/plain"),
+            Map.entry("conf", "text/plain"),
+            Map.entry("toml", "text/plain"),
+            Map.entry("png", "image/png"),
+            Map.entry("jpg", "image/jpeg"),
+            Map.entry("jpeg", "image/jpeg"),
+            Map.entry("gif", "image/gif"),
+            Map.entry("webp", "image/webp"),
+            Map.entry("bmp", "image/bmp"),
+            Map.entry("svg", "image/svg+xml"),
+            Map.entry("heic", "image/heic"),
+            Map.entry("heif", "image/heif"),
+            Map.entry("pdf", "application/pdf"),
+            Map.entry("doc", "application/msword"),
+            Map.entry("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
+            Map.entry("xls", "application/vnd.ms-excel"),
+            Map.entry("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
+            Map.entry("ppt", "application/vnd.ms-powerpoint"),
+            Map.entry("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"),
+            Map.entry("odt", "application/vnd.oasis.opendocument.text"),
+            Map.entry("ods", "application/vnd.oasis.opendocument.spreadsheet"),
+            Map.entry("odp", "application/vnd.oasis.opendocument.presentation"),
+            Map.entry("zip", "application/zip"),
+            Map.entry("rar", "application/vnd.rar"),
+            Map.entry("7z", "application/x-7z-compressed"),
+            Map.entry("tar", "application/x-tar"),
+            Map.entry("gz", "application/gzip"),
+            Map.entry("tgz", "application/gzip"),
+            Map.entry("bz2", "application/x-bzip2"),
+            Map.entry("xz", "application/x-xz"));
+
+    private final IAiSessionService aiSessionService;
+
+    private final StorageLayout storageLayout;
+
+    @Override
+    public AiArtifactListVo list(Long sessionId) {
+        AiSession session = requireWorkbenchSession(sessionId);
+        Path root = workspaceRoot(session);
+        List<AiArtifactVo> items = new ArrayList<>();
+        boolean[] truncated = {false};
+        if (Files.isDirectory(root)) {
+            ArtifactCollector collector = new ArtifactCollector(root, items, truncated);
+            try {
+                Files.walkFileTree(root, EnumSet.noneOf(FileVisitOption.class), MAX_DEPTH, collector);
+            } catch (IOException e) {
+                log.warn("扫描会话产物失败:sessionId={}, root={}, err={}", sessionId, root, e.getMessage());
+            }
+        }
+        items.sort(Comparator.comparing(AiArtifactVo::getLastModified,
+                        Comparator.nullsLast(Comparator.reverseOrder()))
+                .thenComparing(AiArtifactVo::getName, String.CASE_INSENSITIVE_ORDER));
+        AiArtifactListVo vo = new AiArtifactListVo();
+        vo.setSessionId(sessionId);
+        vo.setItems(items);
+        vo.setTotal(items.size());
+        vo.setTruncated(truncated[0]);
+        return vo;
+    }
+
+    @Override
+    public AiArtifactContentVo content(Long sessionId, String path) {
+        AiSession session = requireWorkbenchSession(sessionId);
+        Path file = resolveArtifact(session, path);
+        String name = file.getFileName().toString();
+        String kind = kindOf(name);
+        if (!TEXT_KINDS.contains(kind)) {
+            throw new ServiceException("该类型不支持在线预览,请下载后查看");
+        }
+        long size;
+        try {
+            size = Files.size(file);
+        } catch (IOException e) {
+            throw new ServiceException("产物文件不存在");
+        }
+        String text;
+        boolean truncated = false;
+        try (InputStream in = Files.newInputStream(file)) {
+            byte[] bytes = in.readNBytes(MAX_PREVIEW_BYTES);
+            truncated = size > bytes.length;
+            text = new String(bytes, StandardCharsets.UTF_8);
+        } catch (IOException e) {
+            log.warn("读取产物内容失败:path={}, err={}", file, e.getMessage());
+            throw new ServiceException("读取产物内容失败");
+        }
+        if (!text.isEmpty() && text.charAt(0) == '\uFEFF') {
+            text = text.substring(1);
+        }
+        if (text.length() > MAX_PREVIEW_CHARS) {
+            text = text.substring(0, MAX_PREVIEW_CHARS);
+            truncated = true;
+        }
+        AiArtifactContentVo vo = new AiArtifactContentVo();
+        vo.setPath(relativePath(workspaceRoot(session), file));
+        vo.setName(name);
+        vo.setKind(kind);
+        vo.setMime(mimeOf(file, name));
+        vo.setSize(size);
+        vo.setLastModified(lastModified(file));
+        vo.setText(text);
+        vo.setTruncated(truncated);
+        return vo;
+    }
+
+    @Override
+    public ArtifactFile download(Long sessionId, String path, boolean inline) {
+        AiSession session = requireWorkbenchSession(sessionId);
+        Path file = resolveArtifact(session, path);
+        long size;
+        try {
+            size = Files.size(file);
+        } catch (IOException e) {
+            throw new ServiceException("产物文件不存在");
+        }
+        String name = file.getFileName().toString();
+        return new ArtifactFile(file, name, kindOf(name), mimeOf(file, name), size, inline);
+    }
+
+    /**
+     * 校验会话:必须是当前用户、当前案件下的智能工作台会话。
+     */
+    private AiSession requireWorkbenchSession(Long sessionId) {
+        AiSession session = aiSessionService.assertSessionInCurrentCase(sessionId);
+        if (!AiSession.SOURCE_WORKBENCH.equals(session.getSource())) {
+            throw new ServiceException("仅智能工作台会话支持产物列表");
+        }
+        return session;
+    }
+
+    /**
+     * 会话工作区根目录(绝对化 + 规范化)。
+     */
+    private Path workspaceRoot(AiSession session) {
+        return storageLayout.caseWorkbenchSessionDir(session.getCaseId(), session.getId())
+                .toAbsolutePath().normalize();
+    }
+
+    /**
+     * 解析并校验产物文件:只允许会话根下的普通文件,拒绝绝对路径、穿越、保留目录与符号链接。
+     */
+    private Path resolveArtifact(AiSession session, String rawPath) {
+        if (StringUtils.isBlank(rawPath)) {
+            throw new ServiceException("产物路径不能为空");
+        }
+        Path root = workspaceRoot(session);
+        if (!Files.isDirectory(root)) {
+            throw new ServiceException("会话工作区不存在");
+        }
+        Path relative;
+        try {
+            relative = Path.of(rawPath.trim()).normalize();
+        } catch (InvalidPathException e) {
+            throw new ServiceException("产物路径不合法");
+        }
+        if (relative.isAbsolute() || relative.getNameCount() == 0) {
+            throw new ServiceException("产物路径不合法");
+        }
+        for (Path segment : relative) {
+            String name = segment.toString();
+            if (name.isBlank() || "..".equals(name) || ".".equals(name) || isReservedName(name)) {
+                throw new ServiceException("产物路径不合法");
+            }
+        }
+        Path target = root.resolve(relative).normalize();
+        if (!target.startsWith(root) || Files.isSymbolicLink(target)) {
+            throw new ServiceException("产物路径不合法");
+        }
+        Path realRoot;
+        Path realTarget;
+        try {
+            realRoot = root.toRealPath();
+            realTarget = target.toRealPath();
+        } catch (IOException e) {
+            throw new ServiceException("产物文件不存在");
+        }
+        if (!realTarget.startsWith(realRoot)) {
+            throw new ServiceException("产物路径不合法");
+        }
+        if (!Files.isRegularFile(realTarget)) {
+            throw new ServiceException("产物不是文件");
+        }
+        return realTarget;
+    }
+
+    /**
+     * 扫描器:跳过保留目录、隐藏文件、符号链接与非普通文件,超过上限即终止。
+     */
+    private final class ArtifactCollector extends SimpleFileVisitor<Path> {
+
+        private final Path root;
+
+        private final List<AiArtifactVo> items;
+
+        private final boolean[] truncated;
+
+        private ArtifactCollector(Path root, List<AiArtifactVo> items, boolean[] truncated) {
+            this.root = root;
+            this.items = items;
+            this.truncated = truncated;
+        }
+
+        @Override
+        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
+            if (!dir.equals(root)) {
+                String name = dir.getFileName() == null ? "" : dir.getFileName().toString();
+                if (isReservedName(name)) {
+                    return FileVisitResult.SKIP_SUBTREE;
+                }
+            }
+            return FileVisitResult.CONTINUE;
+        }
+
+        @Override
+        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
+            if (!attrs.isRegularFile() || Files.isSymbolicLink(file)) {
+                return FileVisitResult.CONTINUE;
+            }
+            String name = file.getFileName() == null ? "" : file.getFileName().toString();
+            if (name.isBlank() || name.startsWith(".")) {
+                return FileVisitResult.CONTINUE;
+            }
+            if (items.size() >= MAX_FILES) {
+                truncated[0] = true;
+                return FileVisitResult.TERMINATE;
+            }
+            items.add(toVo(file, name, attrs));
+            return FileVisitResult.CONTINUE;
+        }
+
+        @Override
+        public FileVisitResult visitFileFailed(Path file, IOException exc) {
+            return FileVisitResult.CONTINUE;
+        }
+
+        private AiArtifactVo toVo(Path file, String name, BasicFileAttributes attrs) {
+            String kind = kindOf(name);
+            AiArtifactVo vo = new AiArtifactVo();
+            vo.setPath(relativePath(root, file));
+            vo.setName(name);
+            vo.setKind(kind);
+            vo.setMime(mimeOf(file, name));
+            vo.setSize(attrs.size());
+            vo.setLastModified(LocalDateTime.ofInstant(attrs.lastModifiedTime().toInstant(),
+                    ZoneId.systemDefault()));
+            vo.setPreviewable(PREVIEWABLE_KINDS.contains(kind));
+            vo.setDownloadable(true);
+            return vo;
+        }
+    }
+
+    /**
+     * 保留目录 / 隐藏文件判断。
+     */
+    private static boolean isReservedName(String name) {
+        return name.startsWith(".") || RESERVED_DIRS.contains(name);
+    }
+
+    /**
+     * 相对会话根目录的 POSIX 路径。
+     */
+    private static String relativePath(Path root, Path file) {
+        return root.relativize(file).toString().replace('\\', '/');
+    }
+
+    /**
+     * 文件类别。
+     */
+    private static String kindOf(String name) {
+        return switch (suffixOf(name)) {
+            case "md", "markdown" -> "markdown";
+            case "csv" -> "csv";
+            case "json" -> "json";
+            case "html", "htm" -> "html";
+            case "txt", "log", "yaml", "yml", "xml", "css", "js", "ts", "py", "sql", "sh",
+                 "bat", "ps1", "java", "kt", "properties", "ini", "conf", "toml" -> "text";
+            case "png", "jpg", "jpeg", "gif", "webp", "bmp", "svg", "heic", "heif" -> "image";
+            case "pdf" -> "pdf";
+            case "doc", "docx", "xls", "xlsx", "ppt", "pptx", "odt", "ods", "odp" -> "office";
+            case "zip", "rar", "7z", "tar", "gz", "tgz", "bz2", "xz" -> "archive";
+            default -> "other";
+        };
+    }
+
+    /**
+     * 小写后缀(不含点)。
+     */
+    private static String suffixOf(String name) {
+        if (name == null) {
+            return "";
+        }
+        int index = name.lastIndexOf('.');
+        return index < 0 || index == name.length() - 1
+                ? "" : name.substring(index + 1).toLowerCase(Locale.ROOT);
+    }
+
+    /**
+     * MIME:优先按后缀映射,其次 probeContentType,最后 octet-stream。
+     */
+    private static String mimeOf(Path file, String name) {
+        String mapped = MIME_BY_SUFFIX.get(suffixOf(name));
+        if (mapped != null) {
+            return mapped;
+        }
+        try {
+            String probed = Files.probeContentType(file);
+            if (StringUtils.isNotBlank(probed)) {
+                return probed;
+            }
+        } catch (IOException ignored) {
+            // 探测失败按未知类型处理
+        }
+        return "application/octet-stream";
+    }
+
+    /**
+     * 文件最后修改时间。
+     */
+    private static LocalDateTime lastModified(Path file) {
+        try {
+            return LocalDateTime.ofInstant(Files.getLastModifiedTime(file).toInstant(),
+                    ZoneId.systemDefault());
+        } catch (IOException e) {
+            return null;
+        }
+    }
+}

+ 29 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiSessionServiceImpl.java

@@ -37,6 +37,7 @@ import com.zsjz.ai.module.ai.service.IAiChatAttachmentService;
 import com.zsjz.ai.module.ai.service.IAiScenarioPackService;
 import com.zsjz.ai.module.ai.service.IAiSessionService;
 import com.zsjz.ai.common.context.CaseContextHolder;
+import com.zsjz.ai.common.storage.StorageLayout;
 import com.zsjz.ai.common.compat.PageResult;
 import com.zsjz.ai.common.compat.ServiceException;
 import com.zsjz.ai.common.compat.StringUtils;
@@ -185,6 +186,11 @@ public class AiSessionServiceImpl implements IAiSessionService {
      */
     private final AiAttachmentReclaimer attachmentReclaimer;
 
+    /**
+     * 业务存储布局:删除智能工作台会话时清理其独立产物目录
+     */
+    private final StorageLayout storageLayout;
+
     @Override
     @Transactional(rollbackFor = Exception.class)
     public AiSessionVo createSession(Long agentId, Long scenarioPackId, String title, Long pinnedExpertId,
@@ -1045,6 +1051,8 @@ public class AiSessionServiceImpl implements IAiSessionService {
             lqw.in(AiMessage::getSessionId, ids);
             messageMapper.delete(lqw);
             list.forEach(this::clearSessionState);
+            // 仅清理 workbench 会话的独立产物目录;chat 会话共享用户工作区,不能动
+            list.forEach(this::deleteWorkbenchArtifacts);
         }
         return flag;
     }
@@ -1173,6 +1181,27 @@ public class AiSessionServiceImpl implements IAiSessionService {
         }
     }
 
+    /**
+     * 删除智能工作台会话的独立产物目录。
+     *
+     * <p>只有 workbench 会话有 {@code workbench/{sessionId}} 独立目录;
+     * 普通 chat 会话共享 {@code agents/{entryAgentId}/{userId}} 用户工作区,
+     * 删除单个会话时不能清空该目录,否则会误删其他会话仍在使用或需要保留的文件。</p>
+     *
+     * @param session 会话实体
+     */
+    private void deleteWorkbenchArtifacts(AiSession session) {
+        if (!AiSession.SOURCE_WORKBENCH.equals(session.getSource()) || session.getCaseId() == null) {
+            return;
+        }
+        try {
+            storageLayout.deleteWorkbenchSessionDir(session.getCaseId(), session.getId());
+        } catch (Exception e) {
+            // 文件清理失败不阻断会话删除;残留目录可由运维后续清理
+            log.warn("清理会话产物目录失败,sessionId={}:{}", session.getId(), e.getMessage());
+        }
+    }
+
     /**
      * 格式化导出用时间。
      *

+ 282 - 0
test-reports-20261117/产物功能测试报告.md

@@ -0,0 +1,282 @@
+# AI 产物功能测试报告
+
+- **测试日期**:2026-11-17 16:35–16:55
+- **测试方式**:ZCode 内置浏览器模拟真实用户操作(非接口单测)
+- **前端**:http://127.0.0.1:3100/workbench/chat(Vite dev)
+- **后端**:http://127.0.0.1:8980/js/a(2026-11-17 16:34 重新打包启动)
+- **测试账号**:admin
+- **测试案件**:Ces(caseId `2121846987260764162`)
+- **主测试会话**:`2122551737895714817`(智能工作台会话,source=workbench)
+- **浏览器视口**:桌面 1294×890;窄屏 800×900
+- **代码改动**:本次测试**未修改任何业务代码**
+
+---
+
+## 一、测试结论
+
+核心链路整体可用:
+
+- 产物列表按智能工作台会话隔离,能扫描会话工作区磁盘文件
+- 标题栏入口、数量角标、展开/收起、空态、长文件名、大量文件截断、窄屏浮层均正常
+- 文本 / HTML / CSV / 图片 / PDF / Office / 损坏图片 / 大文本预览均按预期工作
+- 会话隔离、工作台与普通 chat 隔离、跨案件隔离、路径穿越/保留目录拦截均通过
+- 下载接口响应头正确,浏览器 fallback 能触发下载
+
+**发现 1 个中等级别 Bug**:
+
+> **浏览器 fallback 下载时,如果文件已在磁盘上被删除,会把后端返回的 JSON 错误体当成产物文件下载,且没有任何错误提示。**
+
+Electron 下载管理器路径有 JSON 错误识别,但浏览器 fallback 没有;由于本项目主要运行在 Electron,影响范围有限,但 Web 调试/浏览器模式会踩到。
+
+---
+
+## 二、测试数据说明
+
+为覆盖边界场景,在测试会话工作区创建了以下测试文件(非业务数据):
+
+| 文件 | 用途 |
+|---|---|
+| `artifact-test.txt` | 最初 AI 生成的文本产物 |
+| `auto-refresh-test.txt` | AI 生成后验证自动刷新 |
+| `preview-test.html` | HTML 同源 iframe + 脚本执行 |
+| `preview-test.csv` | CSV 表格预览 |
+| `preview-test.png` | 1×1 PNG |
+| `preview-photo.png` | 512×512 真实 PNG |
+| `preview-test.pdf` | 手工构造的最小 PDF |
+| `preview-office.xlsx` | Office 类型(不可预览) |
+| `broken.png` | 伪装成 PNG 的文本(损坏图片兜底) |
+| `broken.heic` | 伪装成 HEIC 的文本(不支持格式兜底) |
+| `large-text.txt` | 约 1.2MB 文本(预览截断) |
+| `中文 报告.txt` | 中文文件名 |
+| `this-is-a-very-long-...txt` | 超长文件名 |
+| `outputs/subdir/nested.txt` | 嵌套目录路径展示 |
+| `preview-test.json` | 合法 JSON 产物 |
+| `.hidden.txt` / `.hidden-dir/file.txt` | 隐藏文件/目录排除 |
+| `many/f000.txt … f504.txt` | 505 个文件,验证 500 条上限(测试后已删除) |
+
+另创建了两个测试会话:
+
+- 会话 B:AI 生成 `session-b-artifact.txt`(验证会话隔离)
+- 会话 C:只问时间、不生成文件(验证空态)
+
+---
+
+## 三、测试结果
+
+### 1. UI 入口与面板
+
+| 编号 | 用例 | 预期 | 实际 | 结果 |
+|---|---|---|---|---|
+| UI-01 | 打开智能工作台会话 | 标题栏出现「产物」图标,角标=产物数 | 图标出现,角标 14,与列表 14 一致 | PASS |
+| UI-02 | 点击图标展开/收起 | 面板显隐切换 | 收起后面板 0 个,展开后 1 个 | PASS |
+| UI-03 | 新建任务 | 清空当前会话、产物面板和角标 | contextBar/panel/toggle 均为 0 | PASS |
+| UI-04 | 空产物新会话 | 面板显示空态 | 显示「本会话暂无产物」,数量 0,无角标 | PASS |
+| UI-05 | 数量同步 | 标题角标 / 面板头 / 列表行数一致 | 14 / 14 / 14 | PASS |
+| UI-06 | 长文件名 | 名称单行省略,路径可提示 | `clientWidth=188`、`scrollWidth=511`、`text-overflow: ellipsis` | PASS |
+| UI-07 | 505 个文件 | 最多 500 条 + 截断提示 + 面板可滚动 | 500 条;提示「文件较多,仅显示最近 500 个」;scrollHeight 36253 / clientHeight 781 | PASS |
+| UI-08 | 窄屏 800px | 面板改为右侧浮层 | `position: fixed`,360×884,右侧 8px | PASS |
+| UI-09 | 弹框放大/还原 | 系统 BasicModal 全屏按钮可用 | 920×645 ↔ 1387×886 | PASS |
+| UI-10 | 普通 chat 会话 | 不显示产物入口/面板 | panel=0,toggle=0 | PASS |
+
+### 2. 数据隔离与安全
+
+| 编号 | 用例 | 预期 | 实际 | 结果 |
+|---|---|---|---|---|
+| ISO-01 | 会话 A/B 产物隔离 | 各会话只显示自己的文件 | A 显示 6/14 个文件,无 `session-b-artifact.txt`;B 只显示 1 个 | PASS |
+| ISO-02 | 工作台 vs 普通 chat | 普通 chat 不显示产物 | 隐藏入口与面板 | PASS |
+| ISO-03 | 跨案件访问 | 用案件 B 的上下文访问案件 A 会话被拒 | 返回「该会话不属于当前案件,请切换到对应案件后再操作」;恢复案件 A 后正常 | PASS |
+| ISO-04 | 系统目录排除 | 不出现 `agents/`、`default/`、`memory/` 等 | 列表无这些目录 | PASS |
+| ISO-05 | 隐藏文件/目录排除 | `.hidden.txt`、`.hidden-dir/` 不出现 | 未出现 | PASS |
+| ISO-06 | 路径穿越 | `../artifact-test.txt` 被拒 | `code=500`,`产物路径不合法` | PASS |
+| ISO-07 | 保留目录下载 | `agents/...` 被拒 | `code=500`,`产物路径不合法` | PASS |
+| ISO-08 | 隐藏路径下载 | `.hidden...` 被拒 | `code=500`,`产物路径不合法` | PASS |
+| ISO-09 | 未登录/失效 token | 401,不返回文件 | 返回 `{"code":401,...}`,无文件流 | PASS |
+| ISO-10 | 跨用户隔离 | 他人会话不可访问 | 单账号环境未测(代码有 userId 校验) | NOT TESTED |
+| ISO-11 | 符号链接逃逸 | 符号链接不被列表/下载 | Windows 创建符号链接受限,未测 | NOT TESTED |
+
+### 3. 预览
+
+| 编号 | 用例 | 预期 | 实际 | 结果 |
+|---|---|---|---|---|
+| PRE-01 | 文本预览 | 显示文本内容 | `hello artifact` | PASS |
+| PRE-02 | HTML 预览 | 同源 iframe 渲染,脚本执行 | iframe 内 `h1=HTML 产物预览测试`,脚本输出 `脚本已执行:16:37:35` | PASS |
+| PRE-03 | CSV 预览 | 表格渲染 | 4 行 × 3 列表格正确 | PASS |
+| PRE-04 | 图片预览 | 512×512 PNG 正常显示 | `naturalWidth=512`,Blob URL 加载 | PASS |
+| PRE-05 | PDF 预览 | iframe 加载 PDF | iframe 存在,`blob:` src,无错误;视觉渲染未截图确认(截图工具超时) | PARTIAL |
+| PRE-06 | Office 预览 | 不提供预览,只下载 | `预览` 按钮 0 个,`下载` 1 个 | PASS |
+| PRE-07 | 损坏图片 | 可读错误 + 下载入口 | 显示「图片加载失败…」+「下载查看」 | PASS |
+| PRE-08 | HEIC/HEIF | 不支持时给出兜底 | 有预览按钮,点击后显示错误 + 下载查看 | PASS(体验可优化) |
+| PRE-09 | 大文本截断 | 最多 20 万字符 + 提示 | 文本长度 200000,显示「内容较大,仅预览前一部分…」 | PASS |
+| PRE-10 | Markdown | 可预览 | 以 `<pre>` 源码显示,未渲染标题/加粗 | 观察项 |
+| PRE-11 | 中文文件名 | 正常列出/预览 | 列表显示「中文 报告.txt」,内容正确 | PASS |
+
+### 4. 下载
+
+| 编号 | 用例 | 预期 | 实际 | 结果 |
+|---|---|---|---|---|
+| DL-01 | 正常文本文件下载 | 触发浏览器下载,无错误 | Playwright download 事件 fired | PASS |
+| DL-02 | 中文文件名下载 | 触发下载,文件名正确 | download 事件 fired;IAB 未暴露 suggestedFilename,无法核对落盘名 | PASS(部分) |
+| DL-03 | JSON 产物下载 | 不被 JSON 错误识别逻辑误杀 | 响应 `application/json` + `Content-Disposition: attachment`,可下载 | PASS |
+| DL-04 | HTML 下载 | 强制 attachment + 二进制 | `application/octet-stream` + attachment + nosniff | PASS |
+| DL-05 | 图片内联预览 | `image/png` + inline | 响应头正确 | PASS |
+| DL-06 | 文件已被删除后点击下载 | 提示错误,不生成文件 | **download 事件仍 fired;后端返回 HTTP 200 JSON 错误体;无错误提示** | **FAIL** |
+| DL-07 | Electron 下载管理器 | 进度/记录/失败提示 | IAB 无 Electron IPC,未实测;代码走 `startDownload`,主进程有 JSON 错误识别 | NOT TESTED |
+
+---
+
+## 四、Bug 记录
+
+### BUG-01(中):浏览器 fallback 下载已删除文件时,把 JSON 错误体当成产物下载
+
+**复现步骤**
+
+1. 在产物列表中看到一个存在的文件(如 `delete-me.txt`),列表已加载。
+2. 在服务器磁盘上删除该文件(模拟文件被清理、或会话工作区被外部改动)。
+3. 不刷新列表,直接点击该行的「下载」。
+
+**预期**
+
+- 提示「产物文件不存在」之类的错误。
+- 不产生任何下载文件。
+
+**实际**
+
+- 浏览器触发了一次 download 事件。
+- 后端实际返回:
+
+```http
+HTTP/1.1 200
+Content-Type: application/json
+```
+
+```json
+{"code":500,"message":"产物文件不存在","data":null}
+```
+
+- 浏览器 fallback 把这段 JSON 当作文件保存成 `delete-me.txt`,页面无错误提示。
+
+**根因**
+
+- 后端业务异常通过全局异常处理器返回 **HTTP 200 + JSON `code=500`**,没有 `Content-Disposition`。
+- Electron 主进程 `downloadService.run()` 已增加判断:`application/json` 且无 `Content-Disposition` 时按失败处理。
+- 浏览器 fallback 走 `workbench/api/http.ts` 的 `aiDownload()`,只关注 HTTP 状态和 blob,不解析 JSON 错误体,因此把错误体当文件下载。
+
+**影响**
+
+- Electron 桌面端基本不受影响(走主进程下载)。
+- Web/浏览器调试模式、或 Electron IPC 不可用时的 fallback 会受影响。
+- 用户会得到一个内容为 JSON 的“假产物”,且不知道下载失败。
+
+**建议修复(本次未改代码)**
+
+- 在 `aiDownload()` 或产物浏览器下载分支中,若 `Blob.type` 包含 `application/json`,读取并解析 `code/message`,抛出错误并提示;或统一复用 `saveBlobResponse` 的 JSON 错误识别逻辑。
+- 或让文件下载接口对“文件不存在/路径非法”返回非 2xx HTTP 状态码。
+- 同时把浏览器 fallback 的错误提示从「导出失败」改为「下载失败」,与业务语义一致。
+
+---
+
+### BUG-02(低 / 体验):Markdown 以源码形式预览
+
+**现象**:`preview-test.md` 的预览内容是 `<pre>` 中的原文(`# 标题`、`**Markdown**`),没有渲染为标题/加粗。
+
+**判断**:当前方案文档允许「`<pre>` 或 AiMarkdown」二选一,因此不算功能错误;若产品要求 Markdown 富文本预览,需要后续接入 `AiMarkdown`。
+
+---
+
+### BUG-03(低 / 体验):HEIC/HEIF 仍显示预览按钮
+
+**现象**:`.heic` 文件在列表中 `previewable=true`,点击后浏览器无法解码,走错误兜底 + 下载按钮。
+
+**判断**:兜底体验可接受;如希望列表层就提示“不支持预览”,可在后端将 HEIC/HEIF 标记为不可预览,或前端按扩展名禁用预览。
+
+---
+
+### BUG-04(低 / 观察):产物列表错误提示可能包含请求 URL
+
+**现象**:在非工作台会话被允许加载产物时,面板错误文案曾显示:
+
+```
+仅智能工作台会话支持产物列表(http://127.0.0.1:8980/js/a/ai/chat/session/.../artifacts?...)
+```
+
+**现状**:已通过前端 `artifactSupported` 隐藏非工作台入口,正常用户不会看到;但若工作台会话产物接口真实失败,错误文案仍可能带长 URL。建议后续在 `artifactError` 展示前取后端 `message`,不要把 axios 的完整 URL 暴露给用户。
+
+---
+
+## 五、未覆盖/环境限制
+
+1. **Electron 下载管理器实际落盘/进度/失败提示**:IAB 没有 Electron IPC,无法在本次环境实测。代码路径复用现有 `startDownload`,主进程已有 `downloadCtl:progress` 和 JSON 错误识别。
+2. **跨用户隔离**:当前只有 admin 一个账号,未创建第二个用户验证 `userId` 隔离;代码层有 `getOwnedSession` 校验。
+3. **符号链接逃逸**:Windows 创建符号链接需要额外权限,未实测。
+4. **PDF 视觉渲染**:iframe Blob 加载成功,但截图工具准备超时,未确认 PDF 内容是否实际绘制;建议人工点开确认。
+5. **会话删除后的产物清理**:已实现并在任务管理页验证(详见第八节)。
+6. **`execute` 写到会话工作区之外的文件**:不会出现在产物面板(命令工具在宿主机执行),属于已知边界。
+
+---
+
+## 六、建议
+
+1. 修复 BUG-01:浏览器 fallback 增加 JSON 错误识别,避免把错误体当产物下载。
+2. 在 Electron 客户端补一次下载管理器实测(正常文件 + 文件不存在 + token 失效三种场景)。
+3. 若产品需要 Markdown 富文本预览,接入 `AiMarkdown`。
+4. 后续可考虑在列表层对 HEIC/HEIF 禁用预览,或增加服务端转码。
+5. 本次测试创建了会话 B/C 和若干测试产物,确认后可删除;测试报告本身不含业务代码改动。
+
+---
+
+---
+
+## 七、修复记录(2026-11-17)
+
+### BUG-01 已修复
+
+- 修复位置:`ai-electron/frontend/src/workbench/api/artifact.ts`
+- 浏览器 fallback 下载改为先取 blob,并检查响应头:
+  - 无 `Content-Disposition` 且 `Content-Type` 为 JSON → 解析 `message` 并抛错
+  - 合法 JSON 产物带 `Content-Disposition`,仍正常下载
+- 验证结果:
+  - 正常文件:download 事件正常触发
+  - 列表加载后从磁盘删除文件再点下载:**未触发 download 事件**,页面提示「产物文件不存在」
+- Electron 主进程原有 JSON 错误识别保持不变。
+
+### 预览弹框调整
+
+- 产物预览弹框移除全部下载按钮(含底部「下载」与错误态「下载查看」),只保留预览内容与系统的关闭/全屏按钮。
+- 产物下载入口仍保留在右侧产物列表行内。
+- 验证结果:
+  - 图片预览正常,弹框内按钮仅剩 `Close`,无下载按钮
+  - 损坏图片错误态只显示错误文案,无下载按钮
+  - HTML / CSV / 文本 / PDF / Office 预览行为不变
+
+---
+
+## 八、会话删除清理验证(2026-11-17)
+
+### 实现
+
+- 后端 `AiSessionServiceImpl.deleteWithValidByIds` 在会话删除成功后,清理 `workbench` 会话独立目录:
+  `cases/{caseId}/ai/workbench/{sessionId}`。
+- 仅清理 `source=workbench` 的会话;`source=chat` 会话共享
+  `agents/{entryAgentId}/{userId}` 用户工作区,**不删除**,避免误删其他会话文件。
+- 任务管理删除确认文案更新为:
+  「删除后消息记录不再展示,智能工作台会话的产物文件将一并清理。」
+- 聊天页「结束任务」只关闭会话,不触发产物清理;清理只发生在任务管理的「删除」动作。
+
+### 附带修正
+
+- 任务管理「来源」列原先对 `workbench` 会话也显示「手动对话」;已修正为
+  `workbench → 智能工作台`、`chat → 手动对话`,便于用户区分哪些会话删除会清理产物。
+
+### 验证结果
+
+| 用例 | 预期 | 实际 | 结果 |
+|---|---|---|---|
+| 任务管理删除带产物的 workbench 会话(session B) | 会话行删除、产物目录删除、列表刷新后消失 | `ai_session` / `ai_message` 行数 0;`workbench/2122612188289544193` 目录已删除;列表行消失 | PASS |
+| 删除 chat 会话(临时 `cleanup-guard-test`) | 共享工作区文件保留 | 共享工作区 marker 仍存在;会话行数 0 | PASS |
+| 删除确认文案 | 明示产物清理 | 显示「智能工作台会话的产物文件将一并清理」 | PASS |
+
+---
+
+**报告生成时间**:2026-11-17 16:55
+**测试执行**:ZCode(内置浏览器自动化)
+**代码改动**:2026-11-17 修复 BUG-01,并按要求移除预览弹框下载按钮