artifact.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. import { defHttp } from '@/core/utils/http/axios';
  2. import { useGlobSetting } from '@/core/hooks/setting';
  3. import { useMessage } from '@/core/hooks/web/useMessage';
  4. import { getToken } from '@/core/utils/auth';
  5. import { isDesktopDownloadAvailable, onDownloadProgress, startDownload } from '@/core/utils/desktop/downloader';
  6. import { downloadByData } from '@/core/utils/file/download';
  7. import { aiGet, aiUrl } from './http';
  8. export type Id = string | number;
  9. /** 产物类别(由后端按扩展名推导) */
  10. export type ArtifactKind =
  11. | 'text'
  12. | 'markdown'
  13. | 'csv'
  14. | 'json'
  15. | 'image'
  16. | 'pdf'
  17. | 'html'
  18. | 'office'
  19. | 'archive'
  20. | 'other';
  21. export interface ArtifactItem {
  22. /** 相对会话工作区根目录的 POSIX 路径 */
  23. path: string;
  24. name: string;
  25. kind: ArtifactKind;
  26. mime?: string;
  27. size?: number;
  28. lastModified?: string;
  29. previewable?: boolean;
  30. downloadable?: boolean;
  31. }
  32. export interface ArtifactListVO {
  33. sessionId: Id;
  34. items: ArtifactItem[];
  35. total: number;
  36. truncated: boolean;
  37. }
  38. export interface ArtifactContentVO {
  39. path: string;
  40. name: string;
  41. kind: ArtifactKind;
  42. mime?: string;
  43. size?: number;
  44. lastModified?: string;
  45. text: string;
  46. truncated: boolean;
  47. }
  48. const artifactBase = (sessionId: Id) => `/ai/chat/session/${encodeURIComponent(String(sessionId))}/artifacts`;
  49. /** 产物列表(直接扫描会话工作区磁盘) */
  50. export function listArtifacts(sessionId: Id): Promise<ArtifactListVO> {
  51. return aiGet<ArtifactListVO>(artifactBase(sessionId));
  52. }
  53. /** 文本类产物内容(HTML 返回源码,由前端 iframe 同源渲染) */
  54. export function getArtifactContent(sessionId: Id, path: string): Promise<ArtifactContentVO> {
  55. return aiGet<ArtifactContentVO>(`${artifactBase(sessionId)}/content`, { path });
  56. }
  57. /** 下载接口绝对地址(主进程下载需要完整 URL) */
  58. export function buildArtifactDownloadUrl(sessionId: Id, path: string, inline = false): string {
  59. const { apiUrl, urlPrefix, adminPath } = useGlobSetting();
  60. const prefix = `${apiUrl || ''}${urlPrefix || ''}${adminPath || ''}`.replace(/\/+$/, '');
  61. const query = new URLSearchParams({ path });
  62. if (inline) {
  63. query.set('inline', 'true');
  64. }
  65. return `${prefix}${artifactBase(sessionId)}/download?${query.toString()}`;
  66. }
  67. /** 预览图片 / PDF:带 x-token 拉取 blob(走与 aiGet 相同的 URL 拼接,兼容 Electron/浏览器) */
  68. export async function fetchArtifactBlob(sessionId: Id, path: string): Promise<Blob> {
  69. const res: any = await defHttp.request(
  70. {
  71. url: aiUrl(`${artifactBase(sessionId)}/download`),
  72. method: 'GET',
  73. params: { path, inline: true },
  74. responseType: 'blob',
  75. },
  76. {
  77. isReturnNativeResponse: true,
  78. isTransformResponse: false,
  79. skipErrorMessage: true,
  80. },
  81. );
  82. const data = res?.data ?? res;
  83. return data instanceof Blob ? data : new Blob([data]);
  84. }
  85. /**
  86. * 下载产物:桌面端交给现有下载管理器(进度/记录在顶栏),浏览器端走 blob 另存。
  87. */
  88. export async function downloadArtifact(sessionId: Id, item: ArtifactItem): Promise<void> {
  89. const { createMessage } = useMessage();
  90. if (isDesktopDownloadAvailable()) {
  91. const token = getToken();
  92. const record = await startDownload({
  93. url: buildArtifactDownloadUrl(sessionId, item.path),
  94. fileName: item.name,
  95. mime: item.mime,
  96. headers: token ? { 'x-token': String(token) } : undefined,
  97. source: 'AI 产物',
  98. });
  99. createMessage.success(`已开始下载:${record.fileName}`);
  100. // 主进程异步下载:完成/失败通过进度通道回传;只关心本次记录
  101. const stop = onDownloadProgress((next) => {
  102. if (next.id !== record.id) {
  103. return;
  104. }
  105. if (next.status === 'done') {
  106. createMessage.success(`已下载:${next.fileName}`);
  107. stop();
  108. } else if (next.status === 'failed') {
  109. createMessage.error(next.message || '产物下载失败');
  110. stop();
  111. }
  112. });
  113. return;
  114. }
  115. await downloadArtifactInBrowser(sessionId, item);
  116. }
  117. /**
  118. * 浏览器 fallback 下载:先取 blob 并识别 JSON 错误,再触发另存。
  119. *
  120. * <p>后端业务异常会返回 HTTP 200 + JSON(无 Content-Disposition),不能直接当文件下载;
  121. * 合法 JSON 产物带有 Content-Disposition,仍按文件正常保存。</p>
  122. */
  123. async function downloadArtifactInBrowser(sessionId: Id, item: ArtifactItem): Promise<void> {
  124. const res: any = await defHttp.request(
  125. {
  126. url: aiUrl(`${artifactBase(sessionId)}/download`),
  127. method: 'GET',
  128. params: { path: item.path },
  129. responseType: 'blob',
  130. },
  131. {
  132. isReturnNativeResponse: true,
  133. isTransformResponse: false,
  134. skipErrorMessage: true,
  135. },
  136. );
  137. const headers = res?.headers;
  138. const disposition =
  139. typeof headers?.get === 'function' ? headers.get('content-disposition') : headers?.['content-disposition'];
  140. const data = res?.data ?? res;
  141. const blob = data instanceof Blob ? data : new Blob([data], { type: item.mime });
  142. if (!disposition && blob.type.includes('json')) {
  143. const message = await readArtifactErrorMessage(blob);
  144. throw new Error(message || '产物下载失败');
  145. }
  146. downloadByData(blob, item.name);
  147. }
  148. /** 读取后端 JSON 错误体中的可读消息 */
  149. async function readArtifactErrorMessage(blob: Blob): Promise<string> {
  150. try {
  151. const text = await blob.text();
  152. const parsed = JSON.parse(text);
  153. return String(parsed?.message || parsed?.msg || '').trim();
  154. } catch {
  155. return '';
  156. }
  157. }