Compare commits

...

8 Commits

Author SHA1 Message Date
16d1496283 修复 Popover 宽度不稳定:移除比例组件硬编码宽度,改用 min-width + ResizeObserver 自适应内容
- Popover 新增 ResizeObserver 监听内容尺寸变化,自动重定位保持居中
- popover-content 补充 maxWidth/minWidth 约束,完善 width='auto' 模式
- 所有关闭路径(点击外部、关闭其他弹窗、modelValue watch)统一清理 observer
- 移除 painting/video 比例组件的 Popover 硬编码宽度,改用 min-width: 300px
- 修复 painting 分辨率选项非弹性布局导致的宽度抖动(white-space: nowrap)
- 修复 painting W/H 输入框盒模型和 flex 收缩问题(box-sizing + min-width: 0)
2026-06-05 16:03:18 +08:00
f0008aedde 修复响应解析:outputs 为扁平数组而非嵌套 images 对象,补充 CLAUDE.md 文档
轮询成功返回时 outputs 是 [{url, type}] 数组,代码误解析为 outputs.images 导致提取 URL 为空,触发"生成失败"通知且列表项无法更新为成功状态。同时在 CLAUDE.md 中补充了 API 响应格式说明、eslint 命令及 config/plugins.js 引用。
2026-06-04 18:48:54 +08:00
4f7357eefc 回退动态参数控件为独立组件,模型配置对齐 API 文档,修复多处缺陷
- 删除 params/ 动态控件,恢复 paintingProportion/Quantity 独立组件
- 模型参数 UI 双向绑定:proportion/resolution/quantity/customSize 同步到 paramValues
- 模型选择器适配 API tags 数组和 display_name,新增 displayNameMap 映射
- 模型配置对齐 RunningHub 文档,精简即梦/通义万相多余参数
- 模型列表缓存改为 30s TTL + pendingRequests 并发去重
- sessionId 改为从登录态获取,禁止随机生成
- Select 下拉菜单增加 max-height 防止溢出
- 更新 CLAUDE.md 架构文档
2026-06-04 18:30:50 +08:00
239b32fb95 重构 Painting 模型参数架构:每模型独立配置、动态参数表单、移除 workflow 适配
- 新增 src/config/models/ 每模型独立参数 schema(8 个模型)
- 新增 src/components/dialogBox/params/ 动态参数控件
- 模型选择器改为从 API 获取并按 tag 分组
- dialogBox 参数区改为根据模型 config 动态渲染控件
- createTask.js Painting 直接返回扁平 modelParams,Video 保留旧 workflow
- 删除旧的 proportion/painting.vue 和 quantity 组件
- 更新 CLAUDE.md 架构文档
2026-06-03 19:00:49 +08:00
791c56a46b 添加 .claude 配置目录,忽略 TEST 目录 2026-06-03 17:40:59 +08:00
2b1e7385e0 页面加载时预请求平台模型接口,避免首次点击"发送"时才触发请求 2026-06-03 17:39:47 +08:00
5da5496492 重构 API 层架构:统一 HTTP 请求、新增算力调度后端路由
- 请求拦截器统一 Auth 头不带 Bearer 前缀,新增 /suanli 前缀路由到算力调度后端
- 任务创建/轮询/历史接口迁移至 apis/display,改为 axios 调用替代原始 fetch
- 模型 API 分离为两层:apis 纯 HTTP 调用 + utils 缓存业务逻辑
- 新增历史任务列表接口 requestTaskHistory(支持 user_id/platform_code 筛选和分页)
- 响应拦截器兼容 status/code 双字段,用户信息兼容新旧 data 格式
- 移除免费次数(freeTimes)体系
- 更新 CLAUDE.md 文档
2026-06-02 18:05:55 +08:00
72267ab2c9 重构任务提交为 HTTP 接口,替换 WebSocket 方案
- POST /api/v1/tasks 创建任务,每 20 秒轮询 GET /api/v1/tasks/{id} 获取结果
- 新增 modelApi.js 通过 /suanli/v1/platforms/:code/models 获取模型 UUID
- dialogBox/canvas 集成 getModelId 查找,result 字段改为 request
- createTask 精简为仅返回 Playload,供 body 使用
- 更新 CLAUDE.md 反映新架构
2026-06-01 18:27:11 +08:00
31 changed files with 1200 additions and 431 deletions

View File

@ -0,0 +1,8 @@
{
"permissions": {
"allow": [
"Bash(git add *)",
"Bash(git commit *)"
]
}
}

View File

@ -3,8 +3,7 @@ VITE_BASE = '/'
# 主服务
VITE_API_PREFIX = '/api'
VITE_API_BASE_URL = 'http://test.xueai.art/api' # http://huanda.xueai.art http://106.54.11.219/api 43.248.131.153:8003
VITE_API_WS_URL = 'ws://test.xueai.art/api'
VITE_API_BASE_URL = 'http://test.xueai.art/newapi/api' # http://huanda.xueai.art http://106.54.11.219/api 43.248.131.153:8003
# 支付服务
VITE_API_PAY_PREFIX = '/pay'
@ -12,7 +11,8 @@ VITE_API_PAY_TARGET = 'http://test.xueai.art' # http://43.248.133.202 test.xue
# 任务处理模块
VITE_API_WORKFLOW_UPLOAD = 'http://43.248.97.19:4000/aigc/workflow/file/upload' # https://sxwz.xueai.art/workflow https://designtools.xueai.art/workflow
VITE_API_WORKFLOW_WS = 'ws://43.248.97.19:4000/testworkflow'
VITE_API_TASK_PREFIX = '/suanli'
VITE_API_TASK_TARGET = 'http://test.xueai.art'
# 是否开启开发者工具
VITE_OPEN_DEVTOOLS = false

View File

@ -7,7 +7,6 @@ VITE_BUILD_MOCK = false
# 主服务
VITE_API_PREFIX = '/api'
VITE_API_BASE_URL = 'https://sxwz.xueai.art/api'
VITE_API_WS_URL = 'wss://sxwz.xueai.art/api'
# 支付服务
VITE_API_PAY_PREFIX = '/pay'
@ -15,7 +14,8 @@ VITE_API_PAY_TARGET = 'https://sxwz.xueai.art' # http://43.248.133.202
# 任务处理模块
VITE_API_WORKFLOW_UPLOAD = 'https://designtools.xueai.art/workflow/file/upload' # https://sxwz.xueai.art/workflow https://designtools.xueai.art/workflow
VITE_API_WORKFLOW_WS = 'wss://talkingdraw.xueai.art/testworkflow'
VITE_API_TASK_PREFIX = '/suanli'
VITE_API_TASK_TARGET = 'http://test.xueai.art'
# 模型资源
VITE_API_MODEL_RESOURCE = 'https://resources.xueai.art/AIGC'

1
.gitignore vendored
View File

@ -22,3 +22,4 @@ dist-ssr
*.njsproj
*.sln
*.sw?
TEST/

168
CLAUDE.md
View File

@ -8,15 +8,21 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
pnpm dev # 启动 Vite 开发服务器
pnpm build # 生产构建
pnpm preview # 预览生产构建
npx eslint . # 代码检查(@antfu/eslint-configVue 支持,无 TypeScript
```
## 技术栈
Vue 3 (Composition API) + Vite 7 + Pinia + Vue Router + Element Plus + Less + pnpm
Vue 3 (Composition API) + Vite 7 + Pinia + Vue Router + Element Plus + `vue-element-plus-x`(多媒体编辑) + Less + pnpm
## 架构概览
这是一个 AI 绘画/视频生成的前端操作平台,通过 WebSocket 连接后端和第三方 AI 平台RunningHub提交生成任务并接收结果。
AI 绘画/视频生成前端操作平台,通过 HTTP 接口对接算力调度后端suanli和第三方 AI 平台RunningHub提交生成任务并轮询结果。
**Painting 和 Video 走两套不同的任务构造路径:**
- **Painting新架构**:本地模型参数 schema → 专用控件 + 动态表单 → `X-Session-Id` header + 扁平 API body
- **Video旧架构**:远程 workflow JSON → RunningHub Playload 适配器 → `{ workflowId, nodeInfoList }` body
### 关键目录
@ -25,54 +31,132 @@ src/
├── main.js # 入口:创建 Vue 应用,安装 Pinia/Router/VueVirtualScroller
├── router/index.js # 路由定义 + token 验证守卫
├── stores/ # Pinia 状态管理
│ ├── user.js # 用户认证、信息、免费次数
│ ├── user.js # 用户认证、信息(含 sessionId
│ ├── display.js # 生成历史列表、UI 状态(滚动、画布等)
│ └── param.js # 占位 store当前为空
├── apis/ # HTTP API 模块
│ ├── auth/ # 登录/登出/用户信息/验证码
│ └── display/ # 获取历史列表/收藏/删除
├── components/ # 通用组件
│ ├── dialogBox/ # 生成参数输入面板(核心交互入口),含模型选择、比例、上传等子组件
│ ├── virtual-scroller/# 虚拟滚动列表组件(自定义实现)
│ ├── canvas/ # 图片画布编辑(圆/矩形选区,局部重绘)
│ └── ...
├── views/ # 页面
│ ├── home/index.vue # 主页面容器dialogBox + display
│ ├── home/display/ # 历史记录展示区
│ └── login/ # 登录页(跳转外部登录)
│ └── param.js # 参数 store当前为空
├── apis/ # HTTP API 层:纯请求封装,不含业务逻辑
│ ├── auth/ # 认证相关登录、token 校验、用户信息)
│ └── display/ # 任务创建/轮询/历史、平台模型、收藏/删除
├── components/
│ ├── dialogBox/ # 生成参数输入面板(核心交互入口)
│ │ ├── model/ # 模型选择器(按 API 返回的 tags 分组value 编码为 tag::display_name
│ │ ├── proportion/ # 比例/分辨率选择器painting.vue 用于 Paintingvideo.vue 用于 Video
│ │ ├── imageUploader/ # 图片上传Painting
│ │ ├── videoImageUploader/ # 视频图片上传Video
│ │ ├── quantity/ # 生成数量选择器(支持 1-6
│ │ ├── Time/ # 视频时长选择器
│ │ └── pattern/ # 视频模式选择器
│ ├── virtual-scroller/# 虚拟滚动列表组件自定义实现reverse 模式)
│ └── canvas/ # 图片画布编辑(圆/矩形选区,局部重绘)
├── views/ # 页面home、login
├── utils/
│ ├── request.js # Axios 实例,拦截器处理 token 和不同服务的 baseURL 路由
│ ├── websocket.js # WebSocket 生成任务的核心流程(心跳、提交流程、结果处理)
│ ├── createTask.js # 根据配置构造任务 payload
│ ├── modelConfig.js # 从远程 JSON 加载模型配置localStorage 每日缓存
│ ├── auth.ts # token 存取工具localStorage
│ └── encrypt.ts # 加密工具Base64/MD5/RSA/AES
│ ├── request.js # Axios 实例 + 拦截器:统一 Auth不带 Bearer+ 按前缀路由 baseURL
│ ├── websocket.js # 任务生成入口:组装参数 → POST 创建任务 → 20s 轮询直至完成/失败
│ ├── modelApi.js # 模型业务层localStorage 30s 缓存 + pendingRequests 并发去重 + 平台编码映射
│ ├── createTask.js # 任务 body 构造Painting 返回 modelParamsVideo 走 Playload 适配器
│ ├── modelConfig.js # Video 旧架构:从远程 JSON 加载 workflow 配置
│ └── auth.ts # token 存取工具localStorage
├── config/
│ ├── index.js # 平台配置入口
└── runninghub/ # RunningHub 平台适配器Payload 构造和 Result 解析
└── config/ # 项目根目录下
└── plugins.js # Vite 插件配置(自动导入/组件注册/图标)
│ ├── plugins.js # Vite 插件配置unplugin-auto-import + unplugin-vue-components
├── index.js # 平台配置入口(目前仅导出 runninghub 供 Video 使用)
│ ├── runninghub/ # RunningHub 平台适配器Playload() 构造和 result() 解析Video 专用)
│ └── models/ # Painting 模型参数配置:每模型一个 JS 文件,定义 params schema
```
### 模型参数配置Painting 新架构)
`src/config/models/` 下每个模型一个 JS 文件,参数通过不同 UI 组件承载:
- **`ui: 'textarea'`** → Sender 组件主输入框prompt
- **`ui: 'proportion'`** + **`ui: 'resolution'`** → `paintingProportion` 组件(共用 Popover含自定义 W/H
- **`ui: 'quantity'`** → `Quantity` 组件(动态 1-6 张)
- **`ui: 'imageUpload'`** → `ImageUploader` 组件
- **`ui: 'hidden'`** → 无 UI仅写入默认值如 outputFormat: 'png'
模型选择器从 API`fetchPlatformModels`)获取模型列表,按 API 返回的 `tags` 数组字段分组(`text`→生成模型,`edit`→编辑模型,`vision`→视觉理解模型)。
### `displayNameMap` 机制
`src/config/models/index.js``displayNameMap` 负责将 API 返回的 `display_name` 映射到 config key。因为同一模型在不同 tag 下可能共用一个 `display_name`(如 `GPT-Image-2``GPT-image-2` 分别对应编辑/生成config key 采用内部中文名区分。
### API 层设计原则
- `src/apis/` 只做纯 HTTP 调用(`service.get/post/delete`不含缓存、localStorage、业务逻辑
- 缓存、数据转换等业务逻辑放在 `src/utils/`
### 核心数据流
1. 用户在 `dialogBox` 中设置参数(模型、提示词、比例、上传图片等)
2. 点击生成 → `websocket.js:generate()` 被调用
3. 先通过 `createTask.js` 调用 `config/runninghub``Playload()` 构造任务数据(从远程 JSON 加载 workflow 配置)
4. 建立 WebSocket 连接,经过握手协议(`please give me taskId` → `OK! Please continue.`)提交任务
5. 任务排队中 → `displayStore.addGeneratingItem()` 在前端列表中插入 "生成中" 条目
6. 完成后 WebSocket 关闭code=1000 reason=success`getTask()` 解析结果 URL → `updateItemToSuccess()` 更新列表
**Painting新架构**
1. 用户设置参数 → 模型选择器按 `tags` 分组,控件根据 model config 的 `ui` 字段渲染
2. `handleStart()` 收集 `paramValues`UI refs 通过 watcher 双向同步)→ 组装 `{ modelParams, request }`
3. `websocket.js:generate()``createTask(data)` → Painting 直接返回 `data.modelParams`
4. `getModelId(type, modelName)` 查找 UUID内部调用 `fetchPlatformModels` 走缓存)
5. `requestCreateTask(body, sessionId)` → POST `/suanli/v1/tasks`,携带 `X-Session-Id` header
6. 返回 task_id → 20s 间隔轮询直至完成/失败
**Video旧架构保留**
1. 用户设置 Pattern、videoModel、比例、时长
2. `createTask(data)``runninghub.Playload(data)``fetchModelConfig()` 获取 workflow JSON → 返回 `{ workflowId, nodeInfoList }`
3. 后续同 Painting 步骤 4-6
### 关键注意事项
- **`sessionId`** 来自登录接口返回的 `userInfo.sessionId`,存储在 `useUserStore().userInfo` 中。`websocket.js` 必须使用该值,禁止随机生成。
- **`X-Session-Id`** 自定义 header 需要 nginx 在 `/suanli/` location 的 `Access-Control-Allow-Headers` 中加入,否则 POST 请求会触发 CORS 预检失败。
- **模型列表缓存**`modelApi.js` 中 `fetchPlatformModels` 使用 localStorage 30 秒 TTL + `pendingRequests` Map 并发去重,避免重复请求。
### 接口速查
| 函数 | 端点 | 用途 |
|------|------|------|
| `requestCreateTask` | POST `/suanli/v1/tasks` | 创建任务(带 `X-Session-Id` header |
| `requestTaskStatus` | GET `/suanli/v1/tasks/:id` | 查询单个任务状态 |
| `requestTaskHistory` | GET `/suanli/v1/tasks/history` | 历史任务列表(支持 `user_id`/`platform_code`/`page`/`pageSize` |
| `fetchPlatformModels` | GET `/suanli/v1/platforms/:code/models` | 获取平台模型列表(返回 `{id, display_name, tags, disabled?}` |
| `cancelOrCollect` | POST `/collect/toggle` | 收藏/取消收藏 |
| `deleteGenerateHistory` | DELETE `/taskRecordHistory/delete` | 删除历史记录 |
### 任务响应格式
```json
// GET /suanli/v1/tasks/:id 返回结构
{
"code": 0,
"data": {
"task_id": "uuid",
"status": "completed", // queued | processing | completed | failed
"outputs": [ // ⚠️ 扁平数组,不是 { images: [...] }
{ "url": "https://...", "type": "png" }
],
"vendor_error": "..." // 仅 failed 时有值
}
}
```
### 请求拦截器路由
拦截器统一设置 `Authorization: <token>`(不带 Bearer 前缀),根据 URL 前缀切换后端:
| URL 前缀 | 环境变量 |
|----------|----------|
| `/suanli` | `VITE_API_TASK_TARGET` |
| `/pay` | `VITE_API_PAY_TARGET` |
| `/aigc` | `VITE_API_AIGC_TARGET` |
| 其他 | `VITE_API_BASE_URL`(默认) |
### 平台编码映射
| 类型 | 平台编码 |
|------|----------|
| Painting | `ai_painting_talk` |
| Video | `ai_video_talk` |
映射函数 `getPlatformCode()` 位于 `utils/modelApi.js`
### 自动导入
- `unplugin-auto-import` 自动导入 Vue/VRouter/Pinia API无需在 `.vue` 文件中手动 `import { ref, computed, watch } from 'vue'`
- `unplugin-vue-components` 自动注册 `src/components/` 下的组件和 Element Plus 组件
- `unplugin-auto-import`:自动导入 Vue/Router/Pinia API
- `unplugin-vue-components`自动注册 `src/components/` 下的组件和 Element Plus 组件
- Element Plus 图标通过 `unplugin-icons` 按需加载
### 环境变量
有两套环境文件。`VITE_API_BASE_URL` 定义主 API 地址,请求拦截器根据 URL 前缀自动切换不同的后端服务(主服务/支付服务/AIGC 工作流服务)。`VITE_API_WORKFLOW_WS` 定义 WebSocket 地址。
### 路由守卫
`src/router/index.js``beforeEach` 守卫检查 token 存在性和有效性(调用 `/auth/check/token`),无效则跳转 `/login`。支持通过 URL query `?token=xxx` 传入 token。

9
components.d.ts vendored
View File

@ -11,10 +11,18 @@ export {}
/* prettier-ignore */
declare module 'vue' {
export interface GlobalComponents {
2: typeof import('./src/components/virtual-scroller/VirtualScroller copy 2.vue')['default']
3: typeof import('./src/components/virtual-scroller/VirtualScroller copy 3.vue')['default']
Canvas: typeof import('./src/components/canvas/index.vue')['default']
copy: typeof import('./src/components/virtual-scroller/VirtualScroller copy.vue')['default']
DialogBox: typeof import('./src/components/dialogBox/index.vue')['default']
ElButton: typeof import('element-plus/es')['ElButton']
ElDatePicker: typeof import('element-plus/es')['ElDatePicker']
ElInput: typeof import('element-plus/es')['ElInput']
ElInputNumber: typeof import('element-plus/es')['ElInputNumber']
ElOption: typeof import('element-plus/es')['ElOption']
ElSelect: typeof import('element-plus/es')['ElSelect']
ElSwitch: typeof import('element-plus/es')['ElSwitch']
ElTooltip: typeof import('element-plus/es')['ElTooltip']
ElUpload: typeof import('element-plus/es')['ElUpload']
IEpCalendar: typeof import('~icons/ep/calendar')['default']
@ -26,6 +34,7 @@ declare module 'vue' {
ImageUploader: typeof import('./src/components/dialogBox/imageUploader/index.vue')['default']
Img: typeof import('./src/components/Img/index.vue')['default']
Painting: typeof import('./src/components/dialogBox/model/painting.vue')['default']
ParamControl: typeof import('./src/components/dialogBox/ParamControl.vue')['default']
Pattern: typeof import('./src/components/dialogBox/pattern/index.vue')['default']
Popover: typeof import('./src/components/Popover/index.vue')['default']
Quantity: typeof import('./src/components/dialogBox/quantity/index.vue')['default']

View File

@ -38,14 +38,10 @@ export function logout() {
/** @desc 获取用户信息 */
export const getUserInfo = () => {
return service.get(`${BASE_URL}/user/info`)
}
/** @desc 获取路由信息 */
export const getUserRoute = () => {
return service.get(`${BASE_URL}/route`)
return service.get(`/sysUser/currentUser
`)
}
export const checkUsertoken = () => {
return service.get(`${BASE_URL}/check/token`)
return service.post(`/login/validateToken`)
}

View File

@ -1,9 +1,6 @@
import service from '@/utils/request'
// 获取生成历史列表
export function getGenerateHistoryList(query) {
return service.get('/taskRecordHistory', { params: query })
}
// ==================== 历史记录 APIaxios ====================
// 取消或收藏
export function cancelOrCollect(query) {
@ -15,7 +12,28 @@ export function deleteGenerateHistory(query) {
return service.delete('/taskRecordHistory/delete', { params: query })
}
// 获取免费次数
export function getFreeTimes(id) {
return service.get('/plantformBalance/userBalances', { params: { id } })
}
// ==================== 任务 APIaxios经由 /suanli 前缀路由到算力调度后端) ====================
// 创建生成任务HTTP POST /suanli/v1/tasks
export function requestCreateTask(body, sessionId) {
return service.post('/suanli/v1/tasks', body, {
headers: { 'X-Session-Id': sessionId }
})
}
// 查询任务状态 / 获取历史任务结果HTTP GET /suanli/v1/tasks/:id
export function requestTaskStatus(taskId) {
return service.get(`/suanli/v1/tasks/${taskId}`)
}
// 获取历史任务列表HTTP GET /suanli/v1/tasks/history支持平台筛选和分页
export function requestTaskHistory(params) {
return service.get('/suanli/v1/tasks/history', { params })
}
// ==================== 平台模型 API ====================
// 获取平台模型列表(原始 HTTP 调用,不含缓存逻辑)
export function fetchPlatformModels(code) {
return service.get(`/suanli/v1/platforms/${code}/models`)
}

View File

@ -47,20 +47,27 @@ const contentRef = ref(null)
const visible = ref(props.modelValue)
const position = ref({ top: 0, left: 0 })
const popoverId = ref(Math.random().toString(36).substr(2, 9))
let resizeObserver = null
if (!window.__currentOpenPopoverId__) {
window.__currentOpenPopoverId__ = null
}
const contentStyle = computed(() => ({
width: typeof props.width === 'number' ? `${props.width}px` : props.width,
...position.value
}))
const contentStyle = computed(() => {
const w = typeof props.width === 'number' ? `${props.width}px` : props.width
return {
...position.value,
width: w,
maxWidth: w === 'auto' ? 'none' : w,
minWidth: w === 'auto' ? '0' : w
}
})
const togglePopover = async () => {
if (visible.value) {
visible.value = false
window.__currentOpenPopoverId__ = null
stopResizeObserver()
} else {
if (window.__currentOpenPopoverId__ && window.__currentOpenPopoverId__ !== popoverId.value) {
window.dispatchEvent(new CustomEvent('close-other-popovers', { detail: { excludeId: popoverId.value } }))
@ -72,20 +79,21 @@ const togglePopover = async () => {
window.__currentOpenPopoverId__ = popoverId.value
await nextTick()
updatePosition()
startResizeObserver()
}
emit('update:modelValue', visible.value)
}
const updatePosition = () => {
if (!triggerRef.value || !contentRef.value) return
const triggerRect = triggerRef.value.getBoundingClientRect()
const contentRect = contentRef.value.getBoundingClientRect()
const gap = 25
let top = 0
let left = 0
switch (props.placement) {
case 'top':
top = triggerRect.top - contentRect.height - gap
@ -104,19 +112,35 @@ const updatePosition = () => {
left = triggerRect.right + gap
break
}
position.value = {
top: `${top}px`,
left: `${left}px`
}
}
const startResizeObserver = () => {
if (!contentRef.value) return
stopResizeObserver()
resizeObserver = new ResizeObserver(() => {
updatePosition()
})
resizeObserver.observe(contentRef.value)
}
const stopResizeObserver = () => {
if (resizeObserver) {
resizeObserver.disconnect()
resizeObserver = null
}
}
const handleClickOutside = (e) => {
if (!visible.value) return
const triggerEl = popoverRef.value
const contentEl = contentRef.value
if (
triggerEl &&
!triggerEl.contains(e.target) &&
@ -125,6 +149,7 @@ const handleClickOutside = (e) => {
) {
visible.value = false
window.__currentOpenPopoverId__ = null
stopResizeObserver()
emit('update:modelValue', false)
}
}
@ -132,12 +157,14 @@ const handleClickOutside = (e) => {
const handleCloseOtherPopovers = (e) => {
if (e.detail.excludeId !== popoverId.value) {
visible.value = false
stopResizeObserver()
}
}
const handleCloseOtherSelects = () => {
visible.value = false
window.__currentOpenPopoverId__ = null
stopResizeObserver()
}
watch(() => props.modelValue, async (val) => {
@ -145,6 +172,9 @@ watch(() => props.modelValue, async (val) => {
if (val) {
await nextTick()
updatePosition()
startResizeObserver()
} else {
stopResizeObserver()
}
})
@ -162,6 +192,7 @@ onBeforeUnmount(() => {
window.removeEventListener('scroll', updatePosition, true)
window.removeEventListener('close-other-popovers', handleCloseOtherPopovers)
window.removeEventListener('close-other-selects', handleCloseOtherSelects)
stopResizeObserver()
})
</script>

View File

@ -261,6 +261,8 @@ onBeforeUnmount(() => {
border: 1px solid #e8e8e8;
animation: fadeIn 0.2s ease;
gap: 10px;
max-height: 360px;
overflow-y: auto;
}
@keyframes fadeIn {

View File

@ -161,8 +161,9 @@
<script setup>
import { generate } from '@/utils/websocket'
import { useDisplayStore, useUserStore } from '@/stores'
import { useDisplayStore } from '@/stores'
import request from '@/utils/request'
import { getModelId } from '@/utils/modelApi'
const props = defineProps({
visible: {
@ -725,6 +726,8 @@ const handleSend = async () => {
const proportion = getImageAspectRatio()
const modelId = await getModelId(props.type, 'GPT')
const generateData = {
model: 'GPT-image2.0',
modelType: 'edit',
@ -737,15 +740,15 @@ const handleSend = async () => {
AIGC: 'Painting',
platform: 'runninghub',
modelName: 'GPT',
modelId,
quantity: 1,
free: useUserStore().freeTimes,
params: [
{ name: 'prompt', data: inputText.value + '并且去除掉图1中的框' },
{ name: 'index', data: 1 },
{ name: 'proportion', data: proportion?.aspectRatio || '4:3' },
],
imgs: uploadedImgs,
result: JSON.stringify(generateData)
request: JSON.stringify(generateData)
}
emit('send', {

View File

@ -7,14 +7,14 @@
<div class="sender-top">
<div v-if="useDisplay.Sender_variant === 'default'" class="scroll-to-bottom-text" @click.stop="handleScrollToBottom">回到底部<img src="@/assets/dialog/ArrowDown.svg"></div>
<div v-show="modelType !== 'text'" class="upload-img-container">
<div v-show="showImageUploader" class="upload-img-container">
<div class="reference-diagram">
<ImageUploader
v-if="props.type === 'Painting'"
ref="referenceDiagramRef"
v-model="referenceImages"
:limit="4"
@open-canvas="handleOpenCanvas"
<ImageUploader
v-if="props.type === 'Painting'"
ref="referenceDiagramRef"
v-model="referenceImages"
:limit="imageUploadLimit"
@open-canvas="handleOpenCanvas"
/>
<VideoImageUploader
v-else-if="props.type === 'Video'"
@ -31,13 +31,17 @@
<template #prefix>
<div v-if="useDisplay.Sender_variant !== 'default' && props.type === 'Painting'" class="prefix-self-wrap">
<paintingModel v-model="model" v-model:typeValue="modelType" />
<paintingProportion
v-model="proportion"
v-model:resolution="resolution"
:proportion-options="proportionOptions"
:resolution-options="resolutionOptions"
<paintingProportion
v-if="showProportion"
v-model="proportion"
v-model:resolution="resolution"
v-model:width="customWidth"
v-model:height="customHight"
:proportion-options="paintingProportionOpts"
:resolution-options="paintingResolutionOpts"
:allow-custom="hasCustomSize"
/>
<Quantity v-model="quantity" />
<Quantity v-if="showQuantity" v-model="quantity" :max="quantityMax" />
</div>
<div v-if="useDisplay.Sender_variant !== 'default' && props.type === 'Video'" class="prefix-self-wrap">
@ -73,20 +77,22 @@
</template>
<script setup>
import paintingProportion from './proportion/painting.vue'
import videoProportion from './proportion/video.vue'
import paintingModel from './model/painting.vue'
import videoModel from './model/video.vue'
import Quantity from './quantity/index.vue'
import Pattern from './pattern/index.vue'
import ImageUploader from './imageUploader/index.vue'
import VideoImageUploader from './videoImageUploader/index.vue'
import Time from './Time/index.vue'
import paintingProportion from './proportion/painting.vue'
import Quantity from './quantity/index.vue'
import { Sender } from 'vue-element-plus-x'
import { useDisplayStore, useUserStore } from '@/stores'
import { useDisplayStore } from '@/stores'
import { generate } from '@/utils/websocket'
import { useRouter } from 'vue-router'
import { getModelId, fetchPlatformModels, getPlatformCode } from '@/utils/modelApi'
import { fetchModelConfig } from '@/utils/modelConfig'
import { getModelConfig } from '@/config/models/index.js'
const props = defineProps({
isGenerate: {
@ -105,30 +111,162 @@ const props = defineProps({
const router = useRouter()
const useDisplay = useDisplayStore()
const useUser = useUserStore()
const isgerenate = ref(false)
const model = ref() //
const modelType = ref('text')
const modelDisplayConfig = ref(null)
//
const modelConfig = computed(() => {
return props.type === 'Painting' ? getModelConfig(model.value) : null
})
//
const paramValues = reactive({})
const showImageUploader = computed(() => {
if (props.type === 'Video') return modelType.value !== 'text'
return modelType.value !== 'text' || modelConfig.value?.inputType === 'image' || modelConfig.value?.inputType === 'both'
})
// imageNum
const showQuantity = computed(() => {
if (props.type !== 'Painting') return false
const qtyParam = modelConfig.value?.params?.find(p => p.ui === 'quantity')
if (qtyParam) return true
return modelType.value === 'text' && !modelConfig.value?.params?.find(p => p.name === 'forceSingle')
})
// 使 proportion aspectRatio
const showProportion = computed(() => {
return !!modelConfig.value?.params?.find(p => p.ui === 'proportion')
})
// aspectRatio 'custom'
const hasCustomSize = computed(() => {
const ratioParam = modelConfig.value?.params?.find(p => p.ui === 'proportion')
return ratioParam?.options?.includes('custom') || false
})
// 退
const paintingProportionOpts = computed(() => {
const ratioParam = modelConfig.value?.params?.find(p => p.ui === 'proportion')
if (ratioParam?.options) {
return ratioParam.options
.filter(o => o !== 'custom')
.map(o => ({ value: o, label: o }))
}
return proportionOptions.value
})
// resolution
const paintingResolutionOpts = computed(() => {
const resParam = modelConfig.value?.params?.find(p => p.ui === 'resolution')
if (resParam?.options) {
return resParam.options.map(o => ({ value: o, label: o.toUpperCase() }))
}
return []
})
const imageUploadLimit = computed(() => {
if (!modelConfig.value) return 4
const imageParam = modelConfig.value.params.find(p => p.ui === 'imageUpload')
return imageParam?.maxCount || modelConfig.value.maxImages || 4
})
const promptPlaceholder = ref('描述你想生成的画面和动作。') //
const prompt = ref('') //
const proportion = ref('16:9') //
const resolution = ref('1k') //
const proportion = ref('16:9') // Video
const resolution = ref('1k') // Video
const referenceImages = ref([])
//
const quantity = ref(1) //
const customWidth = ref(1024) //
const customHight = ref(1024) //
const quantityMax = computed(() => {
const qtyParam = modelConfig.value?.params?.find(p => p.ui === 'quantity')
if (qtyParam?.options?.length) return Math.max(...qtyParam.options)
return 4
})
// paramValues UI refs
watch(modelConfig, (config) => {
if (!config) return
config.params.forEach(p => {
if (!(p.name in paramValues)) {
if (p.name === 'outputFormat') {
paramValues[p.name] = 'png'
} else {
paramValues[p.name] = p.default ?? ''
}
}
})
// UI
const ratioParam = config.params.find(p => p.ui === 'proportion')
if (ratioParam) proportion.value = ratioParam.default || '1:1'
const resParam = config.params.find(p => p.ui === 'resolution')
if (resParam) resolution.value = resParam.default || '2k'
const qtyParam = config.params.find(p => p.ui === 'quantity')
if (qtyParam) quantity.value = qtyParam.default || 1
const cwParam = config.params.find(p => p.name === 'customWidth')
if (cwParam) customWidth.value = cwParam.default || 1024
const chParam = config.params.find(p => p.name === 'customHight')
if (chParam) customHight.value = chParam.default || 1024
}, { immediate: true })
// UI refs paramValues
watch(proportion, (val) => {
const p = modelConfig.value?.params?.find(param => param.ui === 'proportion')
if (p) paramValues[p.name] = val
})
watch(resolution, (val) => {
const p = modelConfig.value?.params?.find(param => param.ui === 'resolution')
if (p) paramValues[p.name] = val
})
watch(quantity, (val) => {
const p = modelConfig.value?.params?.find(param => param.ui === 'quantity')
if (p) paramValues[p.name] = val
})
watch(customWidth, (val) => {
if (modelConfig.value?.params?.find(p => p.name === 'customWidth')) {
paramValues.customWidth = val
}
})
watch(customHight, (val) => {
if (modelConfig.value?.params?.find(p => p.name === 'customHight')) {
paramValues.customHight = val
}
})
// paramValues
watch(referenceImages, (imgs) => {
const imageParam = modelConfig.value?.params?.find(p => p.ui === 'imageUpload')
if (imageParam) {
paramValues[imageParam.name] = imgs.map(img => img.url)
}
}, { deep: true })
//
const duration = ref(5) //
const videoPattern = ref('文生视频') // ''
const resolutionOptions = ref([])
const proportionOptions = ref([])
const resolutionOptions = ref([
{ value: '1k', label: '标清 1K' },
{ value: '2k', label: '高清 2K' },
{ value: '4k', label: '超清 4K' },
])
const proportionOptions = ref([
{ value: '智能', label: '智能' },
{ value: '21:9', label: '21:9' },
{ value: '16:9', label: '16:9' },
{ value: '4:3', label: '4:3' },
{ value: '1:1', label: '1:1' },
{ value: '3:4', label: '3:4' },
{ value: '9:16', label: '9:16' },
])
const durationOptions = ref([])
const isInitialized = ref(false)
@ -141,44 +279,38 @@ const autoSizeConfig = computed(() => {
}
})
const loadModelConfig = async (modelName, currentModelType) => {
const modelDisplayConfig = ref(null)
// Video: workflow
const loadVideoModelConfig = async (modelName, currentModelType) => {
try {
const config = await fetchModelConfig(props.type, modelName, currentModelType)
modelDisplayConfig.value = config
if (config.display) {
const display = config.display
if (display.promptPlaceholder) {
promptPlaceholder.value = display.promptPlaceholder.default || '描述你想生成的画面和动作。'
}
if (display.prompt && !isInitialized.value) {
prompt.value = display.prompt.default || ''
}
if (display.resolution) {
resolution.value = display.resolution.default || '1k'
resolutionOptions.value = display.resolution.options || []
}
if (display.proportion) {
proportion.value = display.proportion.default || '16:9'
proportionOptions.value = display.proportion.options || []
}
if (display.duration) {
duration.value = display.duration.default || 5
durationOptions.value = display.duration.options || []
}
}
isInitialized.value = true
return config
} catch (error) {
console.error('加载模型配置失败:', error)
return null
console.error('加载视频模型配置失败:', error)
}
}
@ -190,7 +322,7 @@ const handleStart = async () => {
ElMessage.primary('敬请期待 Seedance 2.0')
return
}
if (!props.isGenerate) {
router.push({ name: 'home', query: { loading: false, Generate: true, type: currentType } })
}
@ -199,18 +331,22 @@ const handleStart = async () => {
ElMessage.error('请输入提示词')
return
}
if (modelType.value === 'image' && !referenceImages.value.length){
if (showImageUploader.value && !referenceImages.value.length){
ElMessage.warning('请上传图片')
return
}
isgerenate.value = true
console.log('生成开始', isgerenate.value)
const imgs = []
referenceImages.value.forEach((img, index) => {
imgs.push({ name: `image_${index + 1}`, url: img.url })
})
// Painting
const modelParams = { ...paramValues }
if (prompt.value) modelParams.prompt = prompt.value
const generateData = {
model: model.value,
modelType: currentModelType,
@ -219,27 +355,34 @@ const handleStart = async () => {
referenceImages: referenceImages.value,
quantity: quantity.value,
resolution: resolution.value,
customWidth: customWidth.value,
customHight: customHight.value,
duration: duration.value,
videoPattern: videoPattern.value
videoPattern: videoPattern.value,
modelParams,
}
const data = {
const modelId = await getModelId(currentType, model.value)
// Painting Video params
const isPainting = currentType === 'Painting'
const data = {
type: currentType,
modelType: currentModelType,
AIGC: currentType,
platform: 'runninghub',
modelName: model.value,
quantity: quantity.value,
free: useUser.freeTimes,
params: [
{ name: 'prompt', data: prompt.value},
{ name: 'quantity', data: quantity.value},
{ name: 'proportion', data: proportion.value},
{ name: 'resolution', data: resolution.value},
{ name: 'duration', data: duration.value}
modelId: modelId || '',
modelParams: isPainting ? modelParams : {},
params: isPainting ? [] : [
{ name: 'prompt', data: prompt.value },
{ name: 'quantity', data: quantity.value },
{ name: 'proportion', data: proportion.value },
{ name: 'resolution', data: resolution.value },
{ name: 'duration', data: duration.value },
],
imgs,
result: JSON.stringify(generateData)
request: JSON.stringify(generateData)
}
await generate(data, generateData)
console.log('生成中', isgerenate.value)
@ -255,8 +398,11 @@ const fillParamsFromResult = (resultData) => {
if (resultData.referenceImages !== undefined) referenceImages.value = resultData.referenceImages
if (resultData.quantity !== undefined) quantity.value = resultData.quantity
if (resultData.resolution !== undefined) resolution.value = resultData.resolution
if (resultData.customWidth !== undefined) customWidth.value = resultData.customWidth
if (resultData.customHight !== undefined) customHight.value = resultData.customHight
if (resultData.duration !== undefined) duration.value = resultData.duration
if (resultData.videoPattern !== undefined) videoPattern.value = resultData.videoPattern
if (resultData.modelParams !== undefined) Object.assign(paramValues, resultData.modelParams)
}
defineExpose({
@ -286,27 +432,27 @@ watch(() => useDisplay.isSubGerenate, (newValue) => {
watch([() => model.value, () => modelType.value], async ([newModel, newModelType]) => {
console.log('模型或类型改变:', newModel, newModelType)
if (newModel && newModelType) {
await loadModelConfig(newModel, newModelType)
if (!newModel) return
if (props.type !== 'Painting') {
await loadVideoModelConfig(newModel, newModelType)
}
})
// ""
const prefetchModels = () => {
const code = getPlatformCode(props.type)
fetchPlatformModels(code)
}
watch(() => props.type, (newType) => {
if (newType === 'Video') {
model.value = 'LTX2.0'
} else {
model.value = 'flux'
}
const chargeType = newType === 'Painting' ? 1 : 4
useUser.fetchFreeTimes(chargeType)
prefetchModels()
}, { immediate: true })
//
onMounted(async () => {
const chargeType = props.type === 'Painting' ? 1 : 4
await useUser.fetchFreeTimes(chargeType)
console.log('免费次数', useUser.freeTimes)
})
</script>
<style lang="less" scoped>

View File

@ -1,6 +1,6 @@
<template>
<Select
v-model="model"
v-model="selectValue"
:grouped-options="modelGroups"
class="model-select"
position="top"
@ -13,122 +13,123 @@
<script setup>
import Select from '@/components/Select/index.vue'
import { fetchPlatformModels, getPlatformCode } from '@/utils/modelApi'
import { getModelConfig } from '@/config/models/index.js'
const props = defineProps({
modelValue: {
type: String,
default: 'flux'
},
typeValue: {
type: String,
default: 'text'
}
modelValue: { type: String, default: 'Flux 2' },
typeValue: { type: String, default: 'text' },
})
const emit = defineEmits(['update:modelValue', 'update:typeValue'])
const paintingConfig = ref({
generate: [],
edit: [],
vision: []
})
const platformModels = ref([])
const fetchConfig = async () => {
try {
const url = `${import.meta.env.VITE_API_MODEL_RESOURCE}/static/public/Platform/AIGC_modelConfig/painting.json`
const response = await fetch(url)
const data = await response.json()
paintingConfig.value = data
} catch (error) {
console.error('Failed to fetch painting config:', error)
}
const categoryMap = [
{ tag: 'text', label: '生成模型', inputType: 'text' },
{ tag: 'edit', label: '编辑模型', inputType: 'image' },
{ tag: 'vision', label: '视觉理解模型', inputType: 'vision' },
]
function parseValue(encoded) {
if (!encoded) return null
const idx = encoded.indexOf('::')
if (idx === -1) return null
return { tag: encoded.substring(0, idx), modelName: encoded.substring(idx + 2) }
}
function encodeValue(tag, modelName) {
return `${tag}::${modelName}`
}
fetchConfig()
watch(() => paintingConfig.value, (newConfig) => {
const allModels = [
...(newConfig.generate || []),
...(newConfig.edit || []),
...(newConfig.vision || [])
]
if (allModels.length > 0) {
const enabledModels = allModels.filter(m => !m.disabled)
if (enabledModels.length > 0) {
const currentModelExists = enabledModels.find(m => m.value === props.modelValue)
if (!currentModelExists) {
const firstEnabled = enabledModels[0].value
emit('update:modelValue', firstEnabled)
const newType = getModelType(firstEnabled)
emit('update:typeValue', newType)
}
}
}
}, { deep: true })
const model = computed({
get: () => props.modelValue,
set: (value) => {
emit('update:modelValue', value)
const newType = getModelType(value)
emit('update:typeValue', newType)
}
})
const generateModels = computed(() => paintingConfig.value.generate || [])
const editModels = computed(() => paintingConfig.value.edit || [])
const visionModels = computed(() => paintingConfig.value.vision || [])
const modelGroups = computed(() => {
return [
{
label: '生成模型',
options: generateModels.value
},
{
label: '编辑模型',
options: editModels.value
},
{
label: '视觉理解模型',
options: visionModels.value
}
]
})
const getModelType = (value) => {
if (generateModels.value.find(m => m.value === value)) {
return 'text'
}
if (editModels.value.find(m => m.value === value)) {
return 'image'
}
if (visionModels.value.find(m => m.value === value)) {
return 'vision'
function findTagForModel(modelName) {
for (const cat of categoryMap) {
const model = platformModels.value.find(m => (m.display_name || m.name) === modelName && m.tags?.includes(cat.tag))
if (model) return cat.tag
}
return 'text'
}
const getFirstEnabledModel = () => {
const allModels = [...generateModels.value, ...editModels.value, ...visionModels.value]
const firstEnabled = allModels.find(m => !m.disabled)
return firstEnabled ? firstEnabled.value : ''
function tagToInputType(tag) {
const cat = categoryMap.find(c => c.tag === tag)
return cat?.inputType || 'text'
}
watch(() => props.modelValue, (newValue) => {
const allModels = [...generateModels.value, ...editModels.value, ...visionModels.value]
const currentModel = allModels.find(m => m.value === newValue)
if (currentModel && currentModel.disabled) {
const firstEnabled = getFirstEnabledModel()
// Select
const selectValue = computed({
get: () => {
if (!props.modelValue) return ''
const tag = findTagForModel(props.modelValue)
return encodeValue(tag, props.modelValue)
},
set: (encoded) => {
const parsed = parseValue(encoded)
if (!parsed) return
emit('update:modelValue', parsed.modelName)
emit('update:typeValue', tagToInputType(parsed.tag))
},
})
// API
const loadModels = async () => {
try {
const code = getPlatformCode('Painting')
const models = await fetchPlatformModels(code)
platformModels.value = models || []
} catch (error) {
console.error('加载平台模型列表失败:', error)
}
}
loadModels()
// value tag::displayName
const modelGroups = computed(() => {
const models = platformModels.value
if (models.length === 0) return []
return categoryMap
.filter(cat => models.some(m => m.tags?.includes(cat.tag)))
.map(cat => ({
label: cat.label,
options: models
.filter(m => m.tags?.includes(cat.tag))
.map(m => ({
value: `${cat.tag}::${m.display_name || m.name}`,
label: m.display_name || m.name,
disabled: m.disabled || false,
}))
.sort((a, b) => a.label.localeCompare(b.label, undefined, { sensitivity: 'base' })),
}))
})
//
watch(platformModels, (models) => {
if (models.length === 0) return
const currentModel = models.find(m => (m.display_name || m.name) === props.modelValue || m.id === props.modelValue)
if (!currentModel || currentModel.disabled) {
const firstEnabled = models.find(m => !m.disabled)
if (firstEnabled) {
emit('update:modelValue', firstEnabled)
const newType = getModelType(firstEnabled)
emit('update:typeValue', newType)
emit('update:modelValue', firstEnabled.display_name || firstEnabled.name)
emit('update:typeValue', tagToInputType(findTagForModel(firstEnabled.display_name || firstEnabled.name)))
}
}
}, { immediate: true })
// modelValue
watch(() => props.modelValue, (newValue) => {
if (!newValue) return
const models = platformModels.value
if (models.length === 0) return
const currentModel = models.find(m => (m.display_name || m.name) === newValue)
if (currentModel && currentModel.disabled) {
const firstEnabled = models.find(m => !m.disabled)
if (firstEnabled) {
emit('update:modelValue', firstEnabled.display_name || firstEnabled.name)
emit('update:typeValue', tagToInputType(findTagForModel(firstEnabled.display_name || firstEnabled.name)))
}
}
})
</script>
<style lang="less" scoped>
@ -139,24 +140,24 @@ watch(() => props.modelValue, (newValue) => {
border-radius: 10px;
border: 1px solid #E8E9EB;
background: #f5f6f7;
&:hover {
background: #e9eaeb;
}
}
:deep(.select-text) {
font-size: 14px;
}
:deep(.dropdown-menu) {
max-height: 510px;
overflow-y: auto;
}
:deep(.dropdown-item) {
min-width: 120px;
&.active {
background: rgba(0, 15, 51, 0.10);
color: #000F33;

View File

@ -1,5 +1,5 @@
<template>
<Popover placement="top" :width="400">
<Popover placement="top">
<div class="proportion-container">
<div class="section">
<h3>选择比例</h3>
@ -32,7 +32,7 @@
</div>
</div>
<div class="section">
<div v-if="allowCustom" class="section">
<h3>尺寸(px)</h3>
<div class="size-inputs">
<div class="input-group">
@ -85,6 +85,10 @@ const props = defineProps({
{ value: '9:16', label: '9:16' }
]
},
allowCustom: {
type: Boolean,
default: true,
},
resolutionOptions: {
type: Array,
default: () => [
@ -244,6 +248,7 @@ watch(() => [props.modelValue, props.resolution], () => {
.proportion-container{
padding: 20px;
min-width: 300px;
}
.section{
@ -265,7 +270,7 @@ watch(() => [props.modelValue, props.resolution], () => {
.proportion-options{
display: flex;
flex-wrap: nowrap;
justify-content: space-between;
gap: 8px;
margin-bottom: 16px;
background-color: #F8F9FA;
padding: 5px;
@ -321,14 +326,13 @@ watch(() => [props.modelValue, props.resolution], () => {
}
.resolution-item{
flex: 1;
padding: 10px;
padding: 10px 16px;
border-radius: 8px;
cursor: pointer;
font-size: 14px;
text-align: center;
transition: all 0.2s ease;
// background: #f5f5f5;
white-space: nowrap;
color: #666;
&:hover{
@ -350,6 +354,7 @@ watch(() => [props.modelValue, props.resolution], () => {
.input-group{
flex: 1;
min-width: 0;
position: relative;
label{
@ -363,6 +368,7 @@ watch(() => [props.modelValue, props.resolution], () => {
}
input{
box-sizing: border-box;
width: 100%;
height: 36px;
padding: 12px 12px 12px 30px;

View File

@ -1,5 +1,5 @@
<template>
<Popover placement="top" :width="400">
<Popover placement="top">
<div class="proportion-container">
<div class="section">
<h3>选择比例</h3>
@ -142,6 +142,7 @@ const getProportionStyle = (value) => {
.proportion-container{
padding: 20px;
min-width: 300px;
}
.section{

View File

@ -18,6 +18,10 @@ const props = defineProps({
modelValue: {
type: Number,
default: 1
},
max: {
type: Number,
default: 4
}
})
@ -28,12 +32,9 @@ const quantity = computed({
set: (value) => emit('update:modelValue', value)
})
const quantityOptions = [
{ value: 1, label: '1 张' },
{ value: 2, label: '2 张' },
{ value: 3, label: '3 张' },
{ value: 4, label: '4 张' }
]
const quantityOptions = computed(() =>
Array.from({ length: props.max }, (_, i) => ({ value: i + 1, label: `${i + 1}` }))
)
</script>
<style lang="less" scoped>

51
src/config/models/flux.js Normal file
View File

@ -0,0 +1,51 @@
// Flux 2 Dev — 文生图
export default {
name: 'Flux 2',
tag: '文生图',
inputType: 'text',
params: [
{
name: 'prompt',
label: '提示词',
type: 'string',
required: true,
ui: 'textarea',
},
{
name: 'aspectRatio',
label: '比例',
type: 'select',
default: '1:1',
options: ['1:1', '3:4', '4:3', '9:16', '16:9', '2:3', '3:2', 'custom'],
ui: 'proportion',
},
{
name: 'customWidth',
label: '宽度',
type: 'number',
default: 1024,
min: 256,
max: 1536,
ui: 'number',
showWhen: { aspectRatio: 'custom' },
},
{
name: 'customHight',
label: '高度',
type: 'number',
default: 1024,
min: 256,
max: 1536,
ui: 'number',
showWhen: { aspectRatio: 'custom' },
},
{
name: 'outputFormat',
label: '输出格式',
type: 'string',
default: 'png',
options: ['png', 'jpeg', 'webp(lossless)', 'webp(lossy)'],
ui: 'hidden',
},
],
}

View File

@ -0,0 +1,48 @@
// GPT-Image-2 I2I — 图片编辑
export default {
name: 'GPT-Image-2 I2I',
tag: '图片编辑',
inputType: 'image',
maxImages: 10,
params: [
{
name: 'imageUrls',
label: '参考图片',
type: 'image',
required: true,
ui: 'imageUpload',
maxCount: 10,
},
{
name: 'prompt',
label: '编辑指令',
type: 'string',
required: true,
ui: 'textarea',
},
{
name: 'aspectRatio',
label: '比例',
type: 'select',
default: '1:1',
options: ['1:1', '1:2', '2:1', '1:3', '3:1', '2:3', '3:2', '3:4', '4:3', '4:5', '5:4', '9:16', '21:9', '9:21', '16:9'],
ui: 'proportion',
},
{
name: 'resolution',
label: '分辨率',
type: 'select',
default: '2k',
options: ['1k', '2k', '4k'],
ui: 'resolution',
},
{
name: 'quality',
label: '画质',
type: 'select',
default: 'medium',
options: ['low', 'medium', 'high'],
ui: 'select',
},
],
}

View File

@ -0,0 +1,39 @@
// GPT-Image-2 — 文生图
export default {
name: 'GPT-Image-2',
tag: '文生图',
inputType: 'text',
params: [
{
name: 'prompt',
label: '提示词',
type: 'string',
required: true,
ui: 'textarea',
},
{
name: 'aspectRatio',
label: '比例',
type: 'select',
default: '1:1',
options: ['1:1', '1:2', '2:1', '1:3', '3:1', '2:3', '3:2', '3:4', '4:3', '4:5', '5:4', '9:16', '21:9', '9:21', '16:9'],
ui: 'proportion',
},
{
name: 'resolution',
label: '分辨率',
type: 'select',
default: '2k',
options: ['1k', '2k', '4k'],
ui: 'resolution',
},
{
name: 'quality',
label: '画质',
type: 'select',
default: 'medium',
options: ['low', 'medium', 'high'],
ui: 'select',
},
],
}

View File

@ -0,0 +1,45 @@
// 模型配置注册表 — 按模型名称查找参数 schema
import flux from './flux.js'
import zImage from './z-image.js'
import jimeng from './jimeng.js'
import qwen from './qwen.js'
import gptImage from './gpt-image.js'
import nanoPro from './nano-pro.js'
import qwenEdit from './qwen-edit.js'
import gptImageI2i from './gpt-image-i2i.js'
const configs = {
'Flux 2': flux,
'Z-Image Turbo': zImage,
'即梦4.6': jimeng,
'通义万相2.0': qwen,
'GPT-Image-2': gptImage,
'Nano Pro': nanoPro,
'通义万相2.0 Pro': qwenEdit,
'GPT-Image-2 I2i': gptImageI2i,
}
// API display_name → config key 映射API 返回的 display_name 可能与 config 的 name 不同)
const displayNameMap = {
'flux': 'Flux 2',
'Z-image': 'Z-Image Turbo',
'Jimeng4.6': '即梦4.6',
'QwenImage2.0': '通义万相2.0',
'GPT-image-2': 'GPT-Image-2',
'Banana-Pro': 'Nano Pro',
'QwenImage2.0-Pro': '通义万相2.0 Pro',
'GPT-Image-2': 'GPT-Image-2 I2I',
}
/** 根据模型名称获取参数配置,支持 API display_name 和 config key 两种方式查找 */
export function getModelConfig(modelName) {
if (configs[modelName]) return configs[modelName]
const mappedKey = displayNameMap[modelName]
if (mappedKey && configs[mappedKey]) return configs[mappedKey]
return null
}
/** 获取所有模型配置 */
export function getAllModelConfigs() {
return configs
}

View File

@ -0,0 +1,33 @@
// 即梦 4.6 — 文生图(直接指定宽高像素)
export default {
name: '即梦4.6',
tag: '文生图',
inputType: 'text',
params: [
{
name: 'prompt',
label: '提示词',
type: 'string',
required: true,
ui: 'textarea',
},
{
name: 'width',
label: '宽度',
type: 'number',
default: 1024,
min: 900,
max: 6197,
ui: 'number',
},
{
name: 'height',
label: '高度',
type: 'number',
default: 1024,
min: 768,
max: 4096,
ui: 'number',
},
],
}

View File

@ -0,0 +1,40 @@
// Nano Pro — 图片编辑
export default {
name: 'Nano Pro',
tag: '图片编辑',
inputType: 'image',
maxImages: 10,
params: [
{
name: 'imageUrls',
label: '参考图片',
type: 'image',
required: true,
ui: 'imageUpload',
maxCount: 10,
},
{
name: 'prompt',
label: '编辑指令',
type: 'string',
required: true,
ui: 'textarea',
},
{
name: 'aspectRatio',
label: '比例',
type: 'select',
default: '1:1',
options: ['1:1', '3:2', '2:3', '3:4', '4:3', '4:5', '5:4', '9:16', '16:9', '21:9'],
ui: 'proportion',
},
{
name: 'resolution',
label: '分辨率',
type: 'select',
default: '2k',
options: ['1k', '2k', '4k'],
ui: 'resolution',
},
],
}

View File

@ -0,0 +1,46 @@
// 通义万相 2.0 Pro — 图片编辑
export default {
name: '通义万相2.0 Pro',
tag: '图片编辑',
inputType: 'image',
maxImages: 3,
params: [
{
name: 'imageUrls',
label: '参考图片',
type: 'image',
required: true,
ui: 'imageUpload',
maxCount: 3,
},
{
name: 'prompt',
label: '提示词',
type: 'string',
default: '',
ui: 'textarea',
},
{
name: 'size',
label: '分辨率',
type: 'select',
default: '1024*1024',
options: [
'1024*1024', '1536*1536',
'768*1152', '1024*1536', '1152*768', '1536*1024',
'960*1280', '1080*1440', '1280*960', '1440*1080',
'720*1280', '1080*1920', '1280*720', '1920*1080',
'1344*576', '2048*872',
],
ui: 'select',
},
{
name: 'imageNum',
label: '生成张数',
type: 'select',
default: 1,
options: [1, 2, 3, 4, 5, 6],
ui: 'quantity',
},
],
}

38
src/config/models/qwen.js Normal file
View File

@ -0,0 +1,38 @@
// 通义万相 2.0 — 文生图
export default {
name: '通义万相2.0',
tag: '文生图',
inputType: 'text',
maxImages: 6,
params: [
{
name: 'prompt',
label: '提示词',
type: 'string',
required: true,
ui: 'textarea',
},
{
name: 'size',
label: '分辨率',
type: 'select',
default: '1024*1024',
options: [
'1024*1024', '1536*1536',
'768*1152', '1024*1536', '1152*768', '1536*1024',
'960*1280', '1080*1440', '1280*960', '1440*1080',
'720*1280', '1080*1920', '1280*720', '1920*1080',
'1344*576', '2048*872',
],
ui: 'select',
},
{
name: 'imageNum',
label: '生成张数',
type: 'select',
default: 1,
options: [1, 2, 3, 4, 5, 6],
ui: 'quantity',
},
],
}

View File

@ -0,0 +1,31 @@
// Z-Image Turbo — 文生图
export default {
name: 'Z-Image Turbo',
tag: '文生图',
inputType: 'text',
params: [
{
name: 'prompt',
label: '提示词',
type: 'string',
required: true,
ui: 'textarea',
},
{
name: 'aspectRatio',
label: '比例',
type: 'select',
default: '1:1',
options: ['1:1', '3:4', '4:3', '9:16', '16:9', '2:3', '3:2'],
ui: 'proportion',
},
{
name: 'outputFormat',
label: '输出格式',
type: 'string',
default: 'png',
options: ['png', 'jpeg', 'webp(lossless)', 'webp(lossy)'],
ui: 'hidden',
},
],
}

View File

@ -4,7 +4,6 @@ import {
getUserInfo as getUserInfoApi,
logout as logoutApi
} from '@/apis/auth'
import { getFreeTimes } from '@/apis/display'
import { clearToken, getToken, setToken } from '@/utils/auth'
const storeSetup = () => {
@ -34,7 +33,6 @@ const storeSetup = () => {
const dept = ref({}) // 当前用户所在部门集合
const isLogin = ref(false)
const freeTimes = ref(0) // 免费次数
// 重置token
const resetToken = () => {
@ -45,49 +43,40 @@ const storeSetup = () => {
// 检查token有效性
const checkTokenValid = async () => {
const res = await checkUsertokenApi()
console.log('checkTokenValid:', res) // 打印响应数据以进行调试
if (res.code === '401' || res.success === false) {
// 检查响应数据是否存在,以避免空响应导致的错误
console.error('Token is invalid:', res.message)// 打印错误信息以进行调试
console.log('checkTokenValid:', res)
if (res.code === '401' || res.status === '401' || res.success === false) {
console.error('Token is invalid:', res.message)
return false
}
console.log('Token is valid') // 打印成功信息以进行调试
console.log('Token is valid')
return true
}
// 获取用户信息
const getInfo = async () => {
const res = await getUserInfoApi()
Object.assign(userInfo, res.data)
// userInfo.avatar = getAvatar(res.data.avatar, res.data.gender)
userInfo.username = res.data.username
if (typeof res.data.routers === 'string' && res.data.routers.trim() !== '') {
userInfo.routers = res.data.routers.split(',').map((item) => item.trim()) // 补充trim处理更完善
// 兼容新旧格式:新格式 data.userInfo 嵌套,旧格式 data 扁平
const u = res.data.userInfo || res.data
Object.assign(userInfo, u)
userInfo.id = u.userId || u.id
userInfo.username = u.userName || u.username
if (typeof u.routers === 'string' && u.routers.trim() !== '') {
userInfo.routers = u.routers.split(',').map((item) => item.trim())
} else {
userInfo.routers = []
}
if (res.data.roles && res.data.roles.length) {
roles.value = res.data.roles
permissions.value = res.data.permissions
// 角色和权限在 data 层级(非 userInfo 内)
const roleList = res.data.roles || u.roles
if (roleList?.length) {
roles.value = roleList
permissions.value = res.data.permissions || u.permissions || []
}
}
// 获取免费次数
const fetchFreeTimes = async (chargeType = 1) => {
if (userInfo.id) {
const res = await getFreeTimes(userInfo.id)
const balanceList = res.data || []
const target = balanceList.find((item) => item.chargeType === chargeType)
freeTimes.value = target?.balance || 0
return freeTimes.value
}
return 0
}
// 登录
const accountLogin = async (req) => {
const res = await accountLoginApi(req)
if (res.data == null || res.code === '500' || res.success === false) {
if (res.data == null || res.code === '500' || res.status === 500 || res.success === false) {
// eslint-disable-next-line no-undef
ElMessage({
title: '提示',
@ -134,14 +123,12 @@ const storeSetup = () => {
dept,
username,
isLogin,
freeTimes,
accountLogin,
logout,
logoutCallBack,
getInfo,
resetToken,
checkTokenValid,
fetchFreeTimes
checkTokenValid
}
}

View File

@ -1,22 +1,15 @@
import outPlatform from '@/config/index'
// 处理音频生成任务的数据并返回
export async function createTask(data, taskId, token) {
console.log(data)
const payload = await outPlatform[data.platform].Playload(data)
return {
AIGC: data.AIGC,
platform: data.platform,
taskType: data.modelType === 'text' ? 1 : 2,
modelName: data.modelName,
payload,
taskId,
token,
quantity: data.quantity,
free: data.free,
result: data.result
// 构造任务 body
export async function createTask(data) {
// Painting 使用新架构:直接使用动态模型参数
if (data.type === 'Painting') {
return data.modelParams || {}
}
// Video 继续使用旧 workflow 适配器
const payload = await outPlatform[data.platform].Playload(data)
return payload
}
// 获取结果
@ -26,4 +19,4 @@ export async function getTask(result) {
return { type: true, urls: urls }
}
return { type: false, message: result.data.exception_message || '生成失败' }
}
}

110
src/utils/modelApi.js Normal file
View File

@ -0,0 +1,110 @@
import { fetchPlatformModels as fetchModelsRaw } from '@/apis/display'
const CACHE_PREFIX = 'platform_models_'
const CACHE_TTL = 30 * 1000 // 30秒有效期
function getCacheKey(code) {
return `${CACHE_PREFIX}${code}`
}
function getFromCache(code) {
try {
const key = getCacheKey(code)
const stored = localStorage.getItem(key)
if (!stored) return null
const data = JSON.parse(stored)
// 清理旧格式缓存(无 timestamp 字段)或过期缓存
if (!data.timestamp || Date.now() - data.timestamp > CACHE_TTL) {
localStorage.removeItem(key)
return null
}
return data.models
} catch {
return null
}
}
function saveToCache(code, models) {
try {
const key = getCacheKey(code)
localStorage.setItem(key, JSON.stringify({
models,
timestamp: Date.now()
}))
} catch (error) {
console.error('保存模型列表缓存失败:', error)
}
}
// 类型 → 平台编码映射
export function getPlatformCode(type) {
switch (type) {
case 'Painting':
return 'ai_painting_talk'
case 'Video':
return 'ai_video_talk'
default:
return 'ai_painting_talk'
}
}
const pendingRequests = new Map() // 并发请求去重
// 获取平台模型列表localStorage 缓存30秒有效
export async function fetchPlatformModels(code) {
const cached = getFromCache(code)
if (cached) {
return cached
}
// 已有进行中的请求则复用,避免并发重复请求
if (pendingRequests.has(code)) {
return pendingRequests.get(code)
}
const promise = (async () => {
try {
const result = await fetchModelsRaw(code)
if (result.code === 0 && result.data?.models) {
saveToCache(code, result.data.models)
return result.data.models
}
console.error('获取模型列表失败:', result.message)
return []
} catch (error) {
console.error('获取模型列表失败:', error)
return []
} finally {
pendingRequests.delete(code)
}
})()
pendingRequests.set(code, promise)
return promise
}
// 根据模型名称查找 model_id
export async function getModelId(type, modelName) {
if (!modelName) return ''
const code = getPlatformCode(type)
const models = await fetchPlatformModels(code)
const found = models.find(m => m.name === modelName || m.display_name === modelName)
return found?.id || ''
}
// 清除所有平台模型缓存
export function clearPlatformModelCache() {
const keysToRemove = []
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i)
if (key && key.startsWith(CACHE_PREFIX)) {
keysToRemove.push(key)
}
}
keysToRemove.forEach(key => localStorage.removeItem(key))
}

View File

@ -29,21 +29,19 @@ const StatusCodeMessage = {
service.interceptors.request.use(
(config) => {
const token = getToken()
if (token) {
if (!config.headers) {
config.headers = {}
}
config.headers.Authorization = `Bearer ${token}`
if (!config.headers) {
config.headers = {}
}
// console.log(config.baseURL)
if (config.url?.startsWith(import.meta.env.VITE_API_PAY_PREFIX)) { // 支付服务路由
// 统一 Auth 头不带 Bearer 前缀
if (token) config.headers.Authorization = token
if (config.url?.startsWith(import.meta.env.VITE_API_TASK_PREFIX)) { // 算力调度后端
config.baseURL = import.meta.env.VITE_API_TASK_TARGET
} else if (config.url?.startsWith(import.meta.env.VITE_API_PAY_PREFIX)) { // 支付服务路由
config.baseURL = import.meta.env.VITE_API_PAY_TARGET
} else if (config.url?.startsWith(import.meta.env.VITE_API_AIGC_PREFIX)) { // 资源服务路由
// config.url = config.url.replace(import.meta.env.VITE_API_AIGC_PREFIX, '')
config.baseURL = import.meta.env.VITE_API_AIGC_TARGET
} else if (config.url?.startsWith(import.meta.env.VITE_API_MUSIC_WORKFLOW_PREFIX)) { // 音频生成平台工作流服务路由
config.url = config.url.replace(import.meta.env.VITE_API_MUSIC_WORKFLOW_PREFIX, '')
config.baseURL = import.meta.env.VITE_API_MUSIC_WORKFLOW_TARGET
}
return config
},
@ -57,11 +55,11 @@ service.interceptors.request.use(
service.interceptors.response.use(
(response) => {
const { data } = response
const { success, code, msg } = data
if (success || code === 0) {
const { success, code, status, msg, message } = data
if (success || code === 0 || status === 0) {
console.log('msg: \n', msg)
return response.data
} else if (code === 401 && response.config.url !== '/auth/check/token`') { // 判断code=401时进行页面刷新但是不对检验token这个路由的请求判断防止出现死循环
} else if (code === 401 && response.config.url !== '/login/validateToken`') { // 判断code=401时进行页面刷新但是不对检验token这个路由的请求判断防止出现死循环
userError()
}
console.log('CodeMessage: \n', StatusCodeMessage[code])

View File

@ -1,9 +1,9 @@
import { ElNotification } from 'element-plus'
import { h, ref } from 'vue'
import { h } from 'vue'
import { useDisplayStore, useUserStore } from '@/stores'
import { getToken } from '@/utils/auth'
import { createTask, getTask } from '@/utils/createTask'
import { createTask } from '@/utils/createTask'
import { userError } from '@/utils/tokenError'
import { requestCreateTask, requestTaskStatus } from '@/apis/display'
export function getChargeType(chargeType) {
switch (chargeType) {
@ -23,13 +23,13 @@ export function websocketError(code, msg) {
message = '用户身份验证失败'
userError()
break
case 4401: // 后端返回常规错误
case 4401:
message = msg
break
case 4402: // 后端返回外部平台提交时的错误
case 4402:
message = JSON.parse(msg)
break
case 4403: // 外部平台的任务结果的错误
case 4403:
message = msg
break
default:
@ -38,15 +38,13 @@ export function websocketError(code, msg) {
ElNotification({
title: '生成失败',
message: h('i', { style: 'color: teal' }, message),
type: 'error',
duration: 6000 // 增加持续时间以适应更多信息
duration: 6000
})
}
export function websocketSuccess() {
// 合并两个通知为一个
ElNotification({
title: '生成成功',
message: h('div', [
@ -55,135 +53,140 @@ export function websocketSuccess() {
h('div', { style: 'color: orange; margin-top: 5px;' }, '内测状态请及时下载生成的文件云端储存与历史记录保留24小时')
]),
type: 'success',
duration: 6000 // 增加持续时间以适应更多信息
duration: 6000
})
}
// 当前活跃的轮询定时器集合,用于页面卸载时清理
const activePollIntervals = new Set()
export async function generate(data, generateData) {
const progress_text = ref('')
const message = ref('')
const useDisplay = useDisplayStore()
const token = getToken()
const taskId = crypto.randomUUID()
let currentTaskId = null
let taskId = null
let pollInterval = null
if (!data.modelId) {
ElNotification({
title: '生成失败',
message: h('i', { style: 'color: teal' }, '未找到模型ID请联系管理员配置'),
type: 'error'
})
return
}
useDisplay.isSubGerenate = true
const result = await createTask(data, taskId, token)
console.log(result)
// const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjY0NDEwODAyMjk1OTgzNzIzMCwicm5TdHIiOiJiWkVwS2JLWFJyZmRIaFFHWXZKTkdzOGdGM0JSRmxQOCJ9.5eQ2GtVdrDntQDe2tnF8vl_DhTfd2uW-KNqzvl1imc0'
const wsURL = `${import.meta.env.VITE_API_WORKFLOW_WS}/?token=Bearer ${token}`
const socket = new WebSocket(wsURL)
console.log('WebSocket连接已建立')
// 心跳机制相关变量
let heartbeatInterval = null
const heartbeatIntervalTime = 20000 // 30秒发送一次心跳
// 从登录态获取 sessionId
const sessionId = useUserStore().userInfo.sessionId
if (!sessionId) {
ElNotification({
title: '生成失败',
message: h('i', { style: 'color: teal' }, '用户身份已过期,请重新登录'),
type: 'error'
})
useDisplay.isSubGerenate = false
return
}
try {
// 接收服务器消息
socket.onmessage = async (event) => {
// 处理pong响应
if (event.data === 'pong') {
console.log('收到心跳响应')
return
} else if (event.data === 'please give me taskId') {
socket.send(`setTaskId:${taskId}`)
progress_text.value = '信息提交中...'
return
} else if (event.data === 'OK! Please continue. ') {
socket.send(JSON.stringify({
type: 'generate',
data: result
}))
return
} else if (event.data === '任务提交成功,正在排队中...') {
progress_text.value = '视频生成中...'
currentTaskId = taskId
useDisplay.addGeneratingItem({
taskId: taskId,
type: data.type,
generateData: generateData
})
setTimeout(() => {
useDisplay.scrollToBottom()
}, 100)
return
}
message.value = event.data
// 通过 createTask 获取 body 内容RunningHub workflow payload
const body = await createTask(data)
// 构造请求体
const requestBody = {
model_id: data.modelId,
body,
request: data.request
}
// 处理链接错误
socket.onerror = (error) => {
console.error('WebSocket链接出错:', error)
// POST 创建任务
const createResult = await requestCreateTask(requestBody, sessionId)
// 清理心跳定时器
if (heartbeatInterval) {
clearInterval(heartbeatInterval)
}
// eslint-disable-next-line no-undef
if (createResult.code !== 0) {
ElNotification({
title: '生成通知',
// eslint-disable-next-line no-undef
message: h('i', { style: 'color: teal' }, '生成视频失败'),
title: '生成失败',
message: h('i', { style: 'color: teal' }, createResult.message || '任务创建失败'),
type: 'error'
})
}
// 处理链接关闭
socket.onclose = async (event) => {
console.log('WebSocket已关闭:', event)
useDisplay.isSubGerenate = false
if (heartbeatInterval) {
clearInterval(heartbeatInterval)
}
const res = JSON.parse(message.value)
if (event.code === 1006) {
console.error('用户身份验证失败')
userError()
} else if (event.code === 1000 && event.reason === 'success') {
console.log('收到服务器消息:', res)
const result = await getTask(res)
if(useUserStore().freeTimes) await useUserStore().fetchFreeTimes()
if (result.type) {
if (currentTaskId) {
useDisplay.updateItemToSuccess(currentTaskId, result.urls)
return
}
taskId = createResult.data.task_id
// 在列表中插入"生成中"条目
useDisplay.addGeneratingItem({
taskId,
type: data.type,
generateData
})
setTimeout(() => {
useDisplay.scrollToBottom()
}, 100)
// 轮询任务状态
const pollTask = async () => {
try {
const pollResult = await requestTaskStatus(taskId)
if (pollResult.code !== 0) return
const taskData = pollResult.data
if (taskData.status === 'completed') {
clearInterval(pollInterval)
activePollIntervals.delete(pollInterval)
useDisplay.isSubGerenate = false
// 提取结果 URL
const urls = taskData.outputs?.map(img => img.url) || []
if (urls.length > 0) {
useDisplay.updateItemToSuccess(taskId, urls)
websocketSuccess()
} else {
websocketError(4403, '未获取到生成结果')
}
websocketSuccess()
} else {
websocketError(4403, result.message)
} else if (taskData.status === 'failed') {
clearInterval(pollInterval)
activePollIntervals.delete(pollInterval)
useDisplay.isSubGerenate = false
websocketError(4403, taskData.vendor_error || '生成失败')
}
} else {
websocketError(event.code, event.reason)
}
if (heartbeatInterval) {
clearInterval(heartbeatInterval)
// queued / processing 状态继续轮询
} catch (error) {
console.error('轮询任务状态失败:', error)
}
}
// 等待 WebSocket 连接打开
socket.onopen = () => {
console.log('WebSocket连接已建立')
// 每 20 秒轮询一次
pollInterval = setInterval(pollTask, 20000)
activePollIntervals.add(pollInterval)
// 5 秒后先做第一次轮询
setTimeout(pollTask, 5000)
// 启动心跳机制
heartbeatInterval = setInterval(() => {
if (socket.readyState === WebSocket.OPEN) {
socket.send('ping')
console.log('发送心跳包')
}
}, heartbeatIntervalTime)
}
} catch (error) {
console.log('Error creating AI3D_file:', error)
// eslint-disable-next-line no-undef
console.error('创建任务失败:', error)
useDisplay.isSubGerenate = false
ElNotification({
title: '生成通知',
// eslint-disable-next-line no-undef
message: h('i', { style: 'color: teal' }, '生成失败,请检查参数后重新提交任务'),
type: 'error'
})
if (pollInterval) {
clearInterval(pollInterval)
activePollIntervals.delete(pollInterval)
}
}
}
// 页面卸载时清理所有轮询
if (typeof window !== 'undefined') {
window.addEventListener('beforeunload', () => {
for (const interval of activePollIntervals) {
clearInterval(interval)
}
activePollIntervals.clear()
})
}

View File

@ -73,9 +73,10 @@ import RefreshOverlay from './components/RefreshOverlay.vue'
import Select from '@/components/Select/index.vue'
import { VirtualScroller } from '@/components/virtual-scroller'
import Canvas from '@/components/canvas/index.vue'
import { getGenerateHistoryList } from '@/apis/display'
import { requestTaskHistory } from '@/apis/display'
import { useRouter } from 'vue-router'
import { getChargeType } from '@/utils/websocket'
import { getPlatformCode } from '@/utils/modelApi'
const props = defineProps({
if: {
@ -163,12 +164,11 @@ const fetchHistory = async (isLoadMore = false) => {
try {
const pageToFetch = isLoadMore ? currentPage.value + 1 : 1
const result = await getGenerateHistoryList({
userId: userStore.userInfo.id,
chargeType: chargeType.value,
page: pageToFetch,
size: 10,
sort: 'createTime,desc'
const result = await requestTaskHistory({
user_id: userStore.userInfo.id,
platform_code: getPlatformCode(props.type),
page: pageToFetch,
pageSize: 10
})
const dataList = result.data?.list || result.data || []