| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170 |
- 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 '';
- }
- }
|