commit 9b6a6a4bd5bc7323882d442b0a1c52e719c405b3 Author: Codex Date: Tue Nov 10 21:36:09 2026 +0800 chore: checkpoint verified visual studio baseline diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..5727e31 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,11 @@ +.git +**/.env* +!**/.env.example +**/.venv +**/node_modules +**/data +**/__pycache__ +**/.pytest_cache +**/*.log +**/.inference-key +qa diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..999e5ba --- /dev/null +++ b/.env.example @@ -0,0 +1,15 @@ +# Copy to .env on the server. This file contains no working credentials. +CMVR_MODE=production +MYSQL_HOST=192.168.28.10 +MYSQL_PORT=3306 +MYSQL_DATABASE=cmvr-visual +MYSQL_USER= +MYSQL_PASSWORD= +ADMIN_USERNAME=admin +ADMIN_DISPLAY_NAME=管理员 +ADMIN_PASSWORD= +# Set true behind public HTTPS. False is only for loopback HTTP/SSH preview. +COOKIE_SECURE=false +TTS_API_KEY= +WORKSPACE_HOST=/data/llmusers/llmuser/workspace +WEB_PORT=18193 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a2b0005 --- /dev/null +++ b/.gitignore @@ -0,0 +1,20 @@ +**/.env +**/.env.* +!**/.env.example +!**/.env.test.example +**/.venv/ +**/__pycache__/ +**/.pytest_cache/ +**/node_modules/ +**/dist/ +**/data/ +**/.coverage +**/coverage/ +**/test-results/ +**/playwright-report/ +**/*.log +**/.inference-key +**/*credentials*.json +/.deploy/ +/.cache-models/ +/.local/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..fa4cd4e --- /dev/null +++ b/README.md @@ -0,0 +1,220 @@ +# CMVR Visual + +面向本地模型的创作工作台:Vue 3、Element Plus、Pinia 前端,FastAPI、SQLAlchemy async、MySQL 后端,通过 HTTP 和 SSE 提供登录、素材管理、异步任务与实时状态。 + +## 当前交付状态 + +- 工程目录:`E:\workspace\hybrid\cmvr-visual`;服务器源码目录:`/workspace/projects/cmvr-visual`。 +- 已连接用户指定的正式数据库 `192.168.28.10:3306/cmvr-visual`,按本次要求暂用 root;创建六张本应用 `visual_*` 表和默认网站管理员。`/api/system/status` 返回 `environment=production`、`database_backend=mysql`。 +- 默认管理员为 `admin`,初始密码按用户指定的本次私有配置设置;初始管理员支持六位密码,普通用户创建仍要求12位以上。重启不会重置已有密码。后续补账号维护、改密与专用数据库账号,详见复核方案。 +- 本机私有 `.env.server` 保存当前服务器配置,`.env.preview` 仅保留旧验收库配置。原独立 MySQL 与样例数据没有自动迁入正式库;秘密不提交Git、不打印到日志、不复制进文档。`.env.example` 不含可用密码。 +- 网站仅发布服务器 `127.0.0.1:18193`,当前通过受信 SSH 隧道本地访问;不直接向局域网或互联网公开。 + +执行结果以实际验收记录及接口状态为准。单元测试、模拟上游边界和构建成功分别验证各自范围,不等同于真实模型生成或正式数据库验收。 + +历史功能基线见 [验收报告](docs/验收报告.md):75项自动化测试、八类真实服务调用及桌面/手机验证。正式库接入后新增初始账号回归,后端52项通过;[实际接入记录](qa/mysql-integration-20261110.json)验证正式库登录、读写与SSE。 + +最新 [需求复核与落地方案](docs/需求复核与落地方案_20261110.md) 已纳入用户确认的“三分镜合成15秒”和“交互全天/批量夜间”。这两项与审计修复仍为待实施计划;当前视频生成单任务仍约5秒,调度仍只有单次预约。 + +二次可实施性复审见 [实施方案V2](docs/实施方案V2_20261110.md) 和 [12项执行计划](docs/superpowers/plans/2026-11-10-cmvr-visual-v2.md):补齐上游协议、执行代次、分镜依赖、夜间停止确认、批次/资源阶段、时间轴、迁移与恢复。V2尚未实施,Qwen批量须先验证单请求停止能力。 + +## 八项能力与实际限制 + +| 任务类型 | 后端 | 实际能力与边界 | +| --- | --- | --- | +| `image.generate` | 既有 Qwen-Image GPU 队列 | 文本生成图片;默认 1024²、50 步。不提供图像编辑或 LoRA 管理。 | +| `video.generate` | 既有 Wan2.2-TI2V-5B,可接 Real-ESRGAN | 文生视频或参考首帧;最多 121 帧、24 fps,约 **5 秒**,可选 1080p 增强。不是 15 秒生成,也不附带声音。 | +| `defect.generate` | SDXL + Canny ControlNet | 根据参考图片边缘约束生成条件样本,输出合成图和控制图;**控制图不是缺陷真值 mask**。 | +| `audio.transcribe` | 既有 Whisper large-v3-turbo | 音频或有声视频转写;视频先在 CPU 提取音轨,最长 1800 秒。时间戳是约 30 秒分块边界,不是逐词对齐。 | +| `math.solve` | 既有 Qwen 文本 HTTP 服务 | 数学解答文本;没有形式化证明或专业正确率验收承诺。 | +| `media.structure` | Qwen 视觉 HTTP + CPU 抽帧 | 图片理解、视频实际抽帧后的主体/场景/OCR/标签。均匀抽帧不等同于完整镜头切分。 | +| `video.compose` | CPU FFmpeg | 片段排序、裁切、直切拼接、上传音轨和人工字幕;最多 24 段、总长 30 分钟,帧率 24/25/30/60。没有热度预测。 | +| `audio.speech` | 独立 Kokoro-82M **CPU** 服务 | 中文配音 WAV,当前音色 `zf_xiaobei`、`zm_yunxi`;语速 0.5–2。仅在配置真实服务后启用,不提供音乐生成。 | + +参数约束以登录后的 `/api/capabilities` 为准。生成步数字段为 `num_inference_steps`。只有图片和条件样本支持 `count=1..4`,批次拆成独立任务,种子按序递增。没有真实生成进度来源时 `progress=null`,界面不编造百分比。 + +## 项目分层与通信 + +```text +浏览器 Vue / Pinia + │ 同源 HTTP:登录、上传、查询、取消、下载 + │ SSE:持久任务/素材事件与断线重放 +Nginx → FastAPI 业务 API → MySQL visual_* 表 + │ + ├─ 持久协调器 → 既有 GPU jobs API + ├─ Qwen 文本/视觉 HTTP + └─ CPU FFmpeg / 独立 CPU Kokoro +``` + +`frontend/` 为界面;`backend/app/` 为账号、素材、任务、事件和协调器;`providers.py`、`media.py` 为数据库无关的模型与媒体适配;`tts/` 为 CPU 配音服务;`deploy/`、`compose.yaml` 为部署文件;[API 示例](docs/API-examples.md) 和 [共享契约](docs/api-contract.md) 说明调用方式。 + +任务提交是短 HTTP 请求,长任务通过 SSE 单向通知浏览器,不需要双向 WebSocket。事件先和数据库状态一起提交;`Last-Event-ID` 用于重连重放,Cookie 使原生 EventSource 无需把令牌放进 URL。SSE 断开不会取消生成,重连后还会重新获取 HTTP 状态快照。[SSE 标准](https://html.spec.whatwg.org/multipage/server-sent-events.html) + +后端只使用 CPU,不持有 GPU。新模型始终由已部署的 `llmuser` 队列/守护执行:一次只选择一张空闲 GPU 执行一个任务,其他用户优先;运行中发现外部占卡,会清理自己的模型进程并用**同一上游 ID**重新排队。网站保留 `running → queued`、尝试次数和让卡记录,不创建替代生成。 + +上游提交前持久化完整请求和固定幂等键;响应丢失时只原样重试同一请求、同一键取回 ID。ID 已知后只查询或取消。最终输出下载失败只重试导入;多文件结果全部导入成功后才一起公开。取消先于归档事务提交时,取消优先;明确点击“再次生成”则创建新的业务任务。 + +## 路径与隔离 + +| 用途 | 路径 / 设置 | +| --- | --- | +| 宿主工作区 | `/data/llmusers/llmuser/workspace` | +| 容器共享工作区 | `/workspace` | +| 服务器网站源码 | `/workspace/projects/cmvr-visual` | +| 素材 | `/workspace/cmvr-visual/assets` | +| CPU 工作目录与导入暂存 | `/workspace/cmvr-visual/jobs` | +| 协调器锁 | `/workspace/cmvr-visual/state/coordinator.lock` | +| 容器 UID:GID | `1013:1014` | +| 专用 Docker 网络 | `cmvr-visual-net` | +| 模型 API | Docker 网络内 `http://llmuser-workspace:18190` | +| 模型认证文件 | `/workspace/projects/llm-services/config/api_key`,仅后端读取 | + +用户只提交素材 ID;服务器校验 owner 后解析共享工作区路径。素材内容、缩略图、Range 请求、任务和 SSE 都经过登录与归属校验,不将素材目录直接挂成公开静态目录。被任务引用的已删除输入仍保留物理文件。账号密码用加盐 scrypt,Cookie 为 HttpOnly;所有写操作除登录外均要求 CSRF 头。 + +API 和 TTS 容器不挂 GPU、宿主 `/proc`、Docker socket,不使用 privileged;根文件系统只读,工作数据只写入配置的工作区。现有 GPU 权重、模型队列、守护与其他用户服务**不由此工程重新部署**。 + +## 本地开发 + +需要 Python 3.11+、Node/pnpm;媒体探测和合成需 `ffmpeg`、`ffprobe` 在 PATH。本地 SQLite 仅是显式开发预览,不是 MySQL 故障后的自动回退。 + +PowerShell,在项目根目录执行: + +```powershell +python -m venv backend/.venv +& ./backend/.venv/Scripts/python.exe -m pip install -r backend/requirements.txt +New-Item -ItemType Directory -Force .local/workspace | Out-Null +$env:CMVR_MODE = 'preview' +$env:WORKSPACE_ROOT = (Resolve-Path .local/workspace).Path +$dbPath = Join-Path (Resolve-Path .local).Path 'preview.sqlite3' +$env:DATABASE_URL = 'sqlite+aiosqlite:///' + $dbPath.Replace('\', '/') +$env:COOKIE_SECURE = 'false' +$env:INFERENCE_BASE_URL = '' +$env:ADMIN_USERNAME = Read-Host '初始管理员账号' +$adminSecret = Read-Host '初始管理员密码(至少12字符)' -AsSecureString +$env:ADMIN_PASSWORD = [Net.NetworkCredential]::new('', $adminSecret).Password +& ./backend/.venv/Scripts/python.exe -m uvicorn app.main:app --app-dir backend --host 127.0.0.1 --port 8000 --workers 1 +``` + +另开终端: + +```powershell +cd frontend +pnpm install --frozen-lockfile +pnpm dev +``` + +访问 `http://127.0.0.1:5173`。Vite 将 `/api` 同源代理到 `127.0.0.1:8000`。开发进程不会自动加载 `.env`;须显式设置环境或使用受控的环境文件加载方式。首次启动仅在账号不存在时创建管理员,重复启动不会用环境变量重置已有密码。无默认密码、无公开注册。 + +上例主动禁用 GPU 入口:Windows 本地文件路径不能作为远端模型的 `/workspace` 路径。真实生成使用下述同机 Docker 部署。数学/视觉、FFmpeg、配音是否可用取决于实际服务和本地程序配置;不会在缺失时生成假结果。 + +测试与前端构建: + +```powershell +cd backend +& ./.venv/Scripts/python.exe -m pytest -q +cd ../frontend +pnpm test +pnpm build +``` + +缺少 FFmpeg 时相关媒体集成测试会跳过,Linux 的实际媒体测试应单独执行。不要据 SQLite 测试推断正式 MySQL 已连接。 + +## 正式 MySQL 配置 + +目标库 `192.168.28.10:3306/cmvr-visual` 已实际接入,当前按用户要求暂用 root,之后再创建独立数据库业务账号。DBA 可参考 [最小权限 SQL 示例](deploy/production.sql.example),仅授权本库并限制账号来源;不读取或复用其他项目的秘密。 + +私有 `.env` 至少配置 `CMVR_MODE=production`、`MYSQL_HOST`、`MYSQL_PORT`、`MYSQL_DATABASE`、`MYSQL_USER`、`MYSQL_PASSWORD` 及管理员初始化信息。推荐这些分离字段,后端用 `URL.create` 处理数据库名与密码特殊字符;不要手工拼接连接串。正式库不可达时启动失败,不会切换 SQLite。 + +应用仅创建以下表:`visual_users`、`visual_sessions`、`visual_assets`、`visual_jobs`、`visual_job_assets`、`visual_job_events`。当前启动使用 `create_all`,**没有自动迁移工具**:它不会删除现有数据,也不会替已有表添加新字段。升级前备份并审查 schema 差异,在独立库演练迁移;不能靠删表、删库或清队列解决字段不一致。 + +## Docker Compose 启动 + +运维在宿主源码目录 `/data/llmusers/llmuser/workspace/projects/cmvr-visual` 操作。先将前端构建为 `frontend/dist`,因为前端镜像直接复制该目录: + +也可在本机 `E:\workspace\hybrid\cmvr-visual\frontend` 执行 `pnpm install --frozen-lockfile`、`pnpm build`,再将生成的 `dist` 同步到服务器 `frontend/dist`。本次验收采用这一方式;服务器镜像构建不依赖宿主 Node/pnpm。 + +```bash +cd /data/llmusers/llmuser/workspace/projects/cmvr-visual +cp .env.example .env +chmod 600 .env +# 用本机安全编辑器填写专用数据库与管理员秘密;不把秘密写进命令历史。 +cd frontend +pnpm install --frozen-lockfile +pnpm build +cd .. +``` + +已有配置时不要重新覆盖 `.env`。预览环境的 `.env.preview` 是独立秘密记录,不能原样当成正式账号配置。本 Compose 的 API 使用 `env_file: .env`;仅加 `--env-file .env.preview` 不会替换这条容器环境文件设置。检查时使用 `docker compose config --quiet`,不要打印会展开秘密的完整配置。[Compose 环境插值说明](https://docs.docker.com/compose/how-tos/environment-variables/variable-interpolation/) + +首次确认专用网络存在,并确认既有模型容器已接入;只在尚未创建/连接时执行对应命令: + +```bash +docker network inspect cmvr-visual-net +# 网络不存在时: +docker network create cmvr-visual-net +# llmuser-workspace 尚未接入此网络时: +docker network connect cmvr-visual-net llmuser-workspace +``` + +确认共享目录可由 `1013:1014` 写入;不要递归修改其他模型或其他业务目录的所有权。Kokoro 所需的清单权重需预先放入 `/workspace/models/kokoro-82m`。首次缺失时,可在既有工作区容器内用清单下载并校验: + +```bash +docker exec --user 1013:1014 llmuser-workspace /workspace/.venv/bin/python \ + /workspace/projects/cmvr-visual/scripts/download_tts_models.py \ + --manifest /workspace/projects/cmvr-visual/deploy/kokoro-manifest.json +``` + +这只准备独立 CPU 配音模型,不安装或重启既有 GPU 服务。之后: + +```bash +docker compose config --quiet +docker compose up -d --build api tts frontend +docker compose ps +docker compose logs --tail=100 api +``` + +主 `compose.yaml` **不创建 preview-db 或任何生产数据库**。独立 MySQL 8 预览实例由运维单独管理。网站 API 固定单进程 `--workers 1`,协调器另持有工作区文件锁;当前不支持多 API 实例或分布式调度。 + +更新镜像使用 `docker compose up -d --build api tts frontend`。只改 `.env` 时使用 `docker compose up -d --force-recreate api tts` 让配置进入容器,单纯 `restart` 不会重新注入环境。停止本工程使用 `docker compose stop frontend api tts`;不要操作既有 GPU worker、全局 Docker/systemd,或使用全局清理命令。 + +## 访问方式与对外安全边界 + +当前宿主只监听 `127.0.0.1:18193`。从客户端建立隧道: + +```bash +ssh -N -L 127.0.0.1:18193:127.0.0.1:18193 root@192.168.28.10 +``` + +使用已有获准的运维 SSH 账号;`root` 仅是当前运维连接示例,命令没有内嵌密码。受限 `llmuser` 的 SSH 转发已禁用,不要为了网站访问放开其隔离规则。上述命令后访问 `http://127.0.0.1:18193`;当前已建立的隧道入口为 `http://127.0.0.1:8000`。默认管理员配置由本机私有 `.env.server` 安全取得,不在控制台回显。 + +当前回环 HTTP/SSH 验收使用 `COOKIE_SECURE=false`。互联网或不可信网络访问必须先配置 HTTPS 反代或受信加密隧道,并在 HTTPS 浏览器入口使用 `COOKIE_SECURE=true`。保持前后端同源;Cookie 为 HttpOnly/SameSite,CSRF 校验不得移除,推理密钥不得进入前端变量或 URL。 + +`deploy/nginx.conf` 已配置同源 CSP,限制脚本、媒体、网络连接来源。任何外层反代也要保持 SSE 不缓冲、不缓存,超时大于心跳间隔,并透传 `Range`、Cookie 和 CSRF 头,不要将素材端点改成绕过鉴权的静态文件服务。当前 API 支持单个字节 Range;多区间请求不支持。[Nginx proxy_buffering](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffering) + +## 备份与排查 + +备份必须包含正式库中的 `visual_*` 表、`/workspace/cmvr-visual/assets`、`jobs` 和 `state`;后两者含持久请求引用的预处理输入。秘密配置单独安全保管。网站备份不包含 GPU 模型权重或上游队列,相关结果保留策略由既有模型服务管理。 + +使用 DBA 的受保护客户端配置文件,不把密码作为命令参数。以下仅为备份步骤示例,需先准备兼容的 MySQL 客户端及安全目录: + +```bash +docker compose stop api +# /secure/cmvr-visual-backup.cnf 由运维安全创建,权限600,不属于源码。 +mysqldump --defaults-extra-file=/secure/cmvr-visual-backup.cnf \ + --single-transaction --no-tablespaces --set-gtid-purged=OFF \ + cmvr-visual visual_users visual_sessions visual_jobs visual_assets visual_job_assets visual_job_events \ + > /secure/backups/cmvr-visual.sql +tar -czf /secure/backups/cmvr-visual-files.tar.gz \ + -C /data/llmusers/llmuser/workspace/cmvr-visual assets jobs state +docker compose up -d api +``` + +先在独立数据库验证恢复,不将全库恢复脚本覆盖其他业务。API 停止不会自动取消已提交的上游 GPU 任务,重启后继续按同一 ID 查询。 + +- 页面显示验收环境:查看 `/api/system/status` 的 `environment` 与 `database_backend`,不要把它当成正式库故障。 +- 登录失败:检查是否设置管理员初始账号、密码和正确的 Cookie Secure/TLS 组合;已有账号不会被 bootstrap 重置。 +- 四卡繁忙或外部用户占卡:任务可能保持 queued 或从 running 回 queued,这是既有让卡策略;不要新建替代任务或手动删上游锁。 +- `sync_warning`:网络或产物导入正在恢复,不等于生成失败。 +- collecting:推理已完成,正在归档;当前不再接受新的取消。归档之前已提交的取消仍有事务优先保护。 +- SSE 不更新:检查外层代理缓冲/超时、会话是否有效,重新获取 HTTP 快照;不要为了重连再次生成。 +- `stale`/上游执行器异常:检查日志并交运维确认,不能删除数据库、锁或守护状态强制运行。 diff --git a/backend/.dockerignore b/backend/.dockerignore new file mode 100644 index 0000000..ee05c56 --- /dev/null +++ b/backend/.dockerignore @@ -0,0 +1,8 @@ +.venv +data +__pycache__ +**/__pycache__ +.pytest_cache +.env* +tests +*.log diff --git a/backend/.env.example b/backend/.env.example new file mode 100644 index 0000000..4e44ebb --- /dev/null +++ b/backend/.env.example @@ -0,0 +1,27 @@ +CMVR_MODE=production +MYSQL_HOST=192.168.28.10 +MYSQL_PORT=3306 +MYSQL_DATABASE=cmvr-visual +MYSQL_USER= +MYSQL_PASSWORD= +WORKSPACE_ROOT=/workspace +ASSET_ROOT=/workspace/cmvr-visual/assets +JOB_WORK_ROOT=/workspace/cmvr-visual/jobs +STATE_ROOT=/workspace/cmvr-visual/state +ADMIN_USERNAME= +ADMIN_PASSWORD= +ADMIN_DISPLAY_NAME=管理员 +COOKIE_SECURE=true +RUN_COORDINATOR=true +INFERENCE_BASE_URL=http://llmuser-workspace:18190 +INFERENCE_API_KEY_FILE=/workspace/projects/llm-services/config/api_key +GPU_STATUS_PATH=/run/llm-gpu-policy/status.json +GPU_SCHEDULER_PATH=/workspace/projects/llm-services/state/gpu-scheduler.json +QWEN_BASE_URL=http://192.168.28.10:14081/v1 +QWEN_MODEL=Qwen/Qwen3.8-27B-FP8 +QWEN_API_KEY= +TTS_BASE_URL= +TTS_MODEL= +TTS_API_KEY= +FFMPEG_BIN=ffmpeg +FFPROBE_BIN=ffprobe diff --git a/backend/Dockerfile b/backend/Dockerfile new file mode 100644 index 0000000..ecdb677 --- /dev/null +++ b/backend/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.12-slim +ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PIP_NO_CACHE_DIR=1 +RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg fonts-noto-cjk && rm -rf /var/lib/apt/lists/* +WORKDIR /opt/app +COPY requirements.txt ./requirements.txt +RUN pip install -r requirements.txt +COPY app ./app +USER 1013:1014 +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"] diff --git a/backend/app/__init__.py b/backend/app/__init__.py new file mode 100644 index 0000000..40c3cd1 --- /dev/null +++ b/backend/app/__init__.py @@ -0,0 +1 @@ +"""CMVR Visual CPU business backend.""" diff --git a/backend/app/assets.py b/backend/app/assets.py new file mode 100644 index 0000000..7a9d5b6 --- /dev/null +++ b/backend/app/assets.py @@ -0,0 +1,277 @@ +import asyncio +import hashlib +import os +from pathlib import Path +import re +import shutil +import stat +from urllib.parse import quote +from fastapi import APIRouter, Depends, File, Form, Request, Response, UploadFile +from fastapi.responses import StreamingResponse +from pydantic import BaseModel, Field +from sqlalchemy import func, select +from starlette.background import BackgroundTask +from .auth import Actor, csrf_actor, current_actor +from .dto import asset_dto +from .errors import fail +from .events import emit_asset, emit_job +from .models import Asset, Job, JobAsset, new_id, utcnow + +router = APIRouter(prefix="/assets", tags=["assets"]) + + +def confined(root, value, *, exists=False): + root = Path(root).resolve() + path = Path(value) + path = (path if path.is_absolute() else root / path).resolve(strict=exists) + if not path.is_relative_to(root): + raise ValueError("File is outside its permitted directory") + return path + + +def safe_file(root, value): + path = confined(root, value, exists=True) + fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + try: + if not stat.S_ISREG(os.fstat(fd).st_mode): + raise ValueError("Regular file required") + if os.name == "posix": + confined(root, os.readlink(f"/proc/self/fd/{fd}"), exists=True) + return os.fdopen(fd, "rb") + except BaseException: + os.close(fd) + raise + + +async def owned_asset(session, asset_id, owner_id, *, include_deleted=False): + query = select(Asset).where(Asset.id == asset_id, Asset.owner_id == owner_id, Asset.ready.is_(True)) + if not include_deleted: + query = query.where(Asset.deleted_at.is_(None)) + asset = await session.scalar(query) + if asset is None: + fail(404, "asset_not_found", "素材不存在") + return asset + + +async def touch_source_job(session, asset): + if asset.source_job_id: + source = await session.scalar(select(Job).where(Job.id == asset.source_job_id, Job.owner_id == asset.owner_id)) + if source is not None: + await emit_job(session, source) + + +async def build_asset(settings, owner_id, asset_id, path, name, **fields): + from .media import inspect_media, make_thumbnail + path = confined(settings.asset_root, path, exists=True) + metadata = await inspect_media(path, settings) + def hash_file(): + digest = hashlib.sha256() + with safe_file(settings.asset_root, path) as source: + while chunk := source.read(1024 * 1024): + digest.update(chunk) + return digest.hexdigest() + digest = await asyncio.to_thread(hash_file) + thumbnail = await make_thumbnail(path, path.with_name("thumbnail.jpg"), settings) + return Asset(id=asset_id, owner_id=owner_id, name=name[:255], + storage_key=path.relative_to(settings.asset_root).as_posix(), + thumbnail_key=Path(thumbnail).relative_to(settings.asset_root).as_posix() if thumbnail else None, + kind=metadata["kind"], mime_type=metadata["mime_type"], size_bytes=path.stat().st_size, + sha256=digest, width=metadata.get("width"), height=metadata.get("height"), + duration_seconds=metadata.get("duration_seconds"), tags=[], favorite=False, **fields) + + +async def import_output(db, settings, job, source, index): + async with db.session() as session: + existing = await session.scalar(select(Asset).where(Asset.source_job_id == job.id, + Asset.source_output_index == index)) + if existing: + return existing + asset_id = new_id() + source = confined(settings.job_work_root, source, exists=True) + directory = confined(settings.asset_root, Path(job.owner_id) / asset_id) + directory.mkdir(parents=True) + suffix = source.suffix.lower() if re.fullmatch(r"\.[a-z0-9]{1,10}", source.suffix.lower()) else ".bin" + destination = directory / ("original" + suffix) + def copy(): + with safe_file(settings.job_work_root, source) as src, destination.open("xb") as dst: + shutil.copyfileobj(src, dst, 1024 * 1024) + try: + await asyncio.to_thread(copy) + asset = await build_asset(settings, job.owner_id, asset_id, destination, source.name, + origin="generated", source_job_id=job.id, source_upstream_id=job.upstream_id, + source_output_index=index, ready=False) + async with db.session() as session: + session.add(asset) + await session.flush() + await session.commit() + return asset + except BaseException: + shutil.rmtree(directory, ignore_errors=True) + raise + + +@router.post("", status_code=201) +async def upload(request: Request, file: UploadFile = File(), name: str | None = Form(default=None), + actor: Actor = Depends(csrf_actor)): + settings = request.app.state.settings + asset_id = new_id() + directory = confined(settings.asset_root, Path(actor.id) / asset_id) + directory.mkdir(parents=True) + original_name = (file.filename or "素材").replace("\\", "/").rsplit("/", 1)[-1] + suffix = Path(original_name).suffix.lower() + if not re.fullmatch(r"\.[a-z0-9]{1,10}", suffix): + suffix = ".bin" + path, size = directory / ("original" + suffix), 0 + try: + with path.open("xb") as output: + while chunk := await file.read(1024 * 1024): + size += len(chunk) + if size > settings.max_upload_bytes: + fail(413, "upload_too_large", "文件超过上传大小限制") + output.write(chunk) + if not size: + fail(422, "empty_upload", "文件不能为空") + asset = await build_asset(settings, actor.id, asset_id, path, name or original_name or "素材", origin="upload") + if asset.kind not in {"image", "video", "audio"}: + fail(422, "unsupported_upload", "上传仅支持图片、视频或音频") + async with request.app.state.db.session() as session: + session.add(asset) + await session.flush() + emit_asset(session, actor.id, "asset.created", {"asset": asset_dto(asset)}) + await session.commit() + return asset_dto(asset) + except BaseException as exc: + shutil.rmtree(directory, ignore_errors=True) + if hasattr(exc, "code") and hasattr(exc, "message"): + fail(422, exc.code, exc.message) + raise + finally: + await file.close() + + +@router.get("") +async def list_assets(request: Request, page: int = 1, page_size: int = 24, kind: str = "", q: str = "", tag: str = "", + actor: Actor = Depends(current_actor)): + if page < 1 or not 1 <= page_size <= 100: + fail(422, "invalid_page", "分页参数无效") + async with request.app.state.db.session() as session: + query = select(Asset).where(Asset.owner_id == actor.id, Asset.deleted_at.is_(None), Asset.ready.is_(True)) + if kind: + query = query.where(Asset.kind == kind) + if q: + query = query.where(Asset.name.contains(q[:255], autoescape=True)) + # JSON tags are filtered in Python for equivalent MySQL/SQLite preview semantics. + rows = (await session.scalars(query.order_by(Asset.created_at.desc(), Asset.id.desc()))).all() + if tag: + rows = [asset for asset in rows if tag in (asset.tags or [])] + return {"items": [asset_dto(a) for a in rows[(page - 1) * page_size:page * page_size]], + "total": len(rows), "page": page, "page_size": page_size} + + +@router.get("/{asset_id}") +async def get_asset(asset_id: str, request: Request, actor: Actor = Depends(current_actor)): + async with request.app.state.db.session() as session: + return asset_dto(await owned_asset(session, asset_id, actor.id)) + + +class AssetPatch(BaseModel): + name: str | None = Field(default=None, min_length=1, max_length=255) + tags: list[str] | None = Field(default=None, max_length=30) + favorite: bool | None = None + + +@router.patch("/{asset_id}") +async def patch_asset(asset_id: str, body: AssetPatch, request: Request, actor: Actor = Depends(csrf_actor)): + async with request.app.state.db.session() as session: + asset = await owned_asset(session, asset_id, actor.id) + if body.name is not None: + asset.name = body.name.strip() or asset.name + if body.tags is not None: + if any(not tag.strip() or len(tag) > 64 for tag in body.tags): + fail(422, "invalid_tag", "标签须为 1–64 个字符") + asset.tags = list(dict.fromkeys(tag.strip() for tag in body.tags)) + if body.favorite is not None: + asset.favorite = body.favorite + emit_asset(session, actor.id, "asset.updated", {"asset": asset_dto(asset)}) + await touch_source_job(session, asset) + await session.commit() + return asset_dto(asset) + + +@router.delete("/{asset_id}", status_code=204) +async def delete_asset(asset_id: str, request: Request, actor: Actor = Depends(csrf_actor)): + async with request.app.state.db.session() as session: + asset = await owned_asset(session, asset_id, actor.id) + asset.deleted_at = utcnow() + referenced = await session.scalar(select(JobAsset.job_id).where(JobAsset.asset_id == asset_id).limit(1)) + storage = asset.storage_key + emit_asset(session, actor.id, "asset.deleted", {"id": asset.id}) + await touch_source_job(session, asset) + await session.commit() + if referenced is None: + try: + path = confined(request.app.state.settings.asset_root, storage) + shutil.rmtree(path.parent) + except (OSError, ValueError): + pass + return Response(status_code=204) + + +def file_response(settings, asset, key, range_header, download): + try: + handle = safe_file(settings.asset_root, key) + except (ValueError, OSError): + fail(404, "file_unavailable", "素材文件不可用") + size = os.fstat(handle.fileno()).st_size + start, end, code = 0, size - 1, 200 + if range_header: + match = re.fullmatch(r"bytes=(\d*)-(\d*)", range_header.strip()) + try: + if not match or not any(match.groups()): + raise ValueError + a, b = match.groups() + if a: + start, end = int(a), min(int(b), size - 1) if b else size - 1 + else: + start, end = max(0, size - int(b)), size - 1 + if start > end or start >= size or start < 0: + raise ValueError + code = 206 + except ValueError: + handle.close() + return Response(status_code=416, headers={"Content-Range": f"bytes */{size}"}) + handle.seek(start) + def chunks(): + remaining = end - start + 1 + try: + while remaining > 0: + data = handle.read(min(1024 * 1024, remaining)) + if not data: + break + remaining -= len(data) + yield data + finally: + handle.close() + headers = {"Accept-Ranges": "bytes", "Content-Length": str(max(0, end - start + 1)), + "X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store", + "Content-Disposition": ("attachment" if download else "inline") + "; filename*=UTF-8''" + quote(asset.name, safe="")} + if code == 206: + headers["Content-Range"] = f"bytes {start}-{end}/{size}" + return StreamingResponse(chunks(), status_code=code, media_type="image/jpeg" if key != asset.storage_key else asset.mime_type, + headers=headers, background=BackgroundTask(handle.close)) + + +@router.get("/{asset_id}/content") +async def content(asset_id: str, request: Request, download: bool = False, actor: Actor = Depends(current_actor)): + async with request.app.state.db.session() as session: + asset = await owned_asset(session, asset_id, actor.id) + return file_response(request.app.state.settings, asset, asset.storage_key, request.headers.get("range"), download) + + +@router.get("/{asset_id}/thumbnail") +async def thumbnail(asset_id: str, request: Request, actor: Actor = Depends(current_actor)): + async with request.app.state.db.session() as session: + asset = await owned_asset(session, asset_id, actor.id) + if not asset.thumbnail_key and asset.kind != "image": + fail(404, "thumbnail_unavailable", "预览图暂不可用") + return file_response(request.app.state.settings, asset, asset.thumbnail_key or asset.storage_key, None, False) diff --git a/backend/app/auth.py b/backend/app/auth.py new file mode 100644 index 0000000..54dbdc7 --- /dev/null +++ b/backend/app/auth.py @@ -0,0 +1,158 @@ +import asyncio +from dataclasses import dataclass +from datetime import timedelta +import hashlib +import hmac +import re +import secrets +from fastapi import APIRouter, Depends, Request, Response +from pydantic import BaseModel, Field +from sqlalchemy import delete, select +from sqlalchemy.exc import IntegrityError +from .errors import fail +from .models import Session, User, utcnow + +router = APIRouter(prefix="/auth", tags=["auth"]) +COOKIE = "cmvr_session" + + +def token_hash(token): + return hashlib.sha256(token.encode()).hexdigest() + + +def hash_password(password): + salt = secrets.token_bytes(16) + key = hashlib.scrypt(password.encode(), salt=salt, n=32768, r=8, p=1, dklen=64, maxmem=128 * 1024 * 1024) + return f"scrypt$32768$8$1${salt.hex()}${key.hex()}" + + +def verify_password(password, encoded): + try: + _, n, r, p, salt, expected = encoded.split("$") + key = hashlib.scrypt(password.encode(), salt=bytes.fromhex(salt), n=int(n), r=int(r), p=int(p), + dklen=64, maxmem=128 * 1024 * 1024) + return hmac.compare_digest(key.hex(), expected) + except (ValueError, TypeError): + hashlib.scrypt(password.encode(), salt=b"\0" * 16, n=32768, r=8, p=1, maxmem=128 * 1024 * 1024) + return False + + +def validate_password(password, *, minimum=12): + if not minimum <= len(password) <= 256: + fail(422, "weak_password", f"密码长度须为 {minimum}–256 个字符") + + +def user_dto(user): + return {"id": user.id, "username": user.username, "display_name": user.display_name, "role": user.role} + + +@dataclass +class Actor: + id: str + username: str + display_name: str + role: str + csrf_token: str + token_hash: str + + +async def current_actor(request: Request): + token = request.cookies.get(COOKIE) + if not token or len(token) > 512: + fail(401, "not_authenticated", "请先登录") + async with request.app.state.db.session() as session: + row = (await session.execute(select(Session, User).join(User, User.id == Session.user_id) + .where(Session.token_hash == token_hash(token), Session.expires_at > utcnow(), + User.disabled.is_(False)))).first() + if row is None: + fail(401, "session_expired", "登录已失效,请重新登录") + saved, user = row + return Actor(user.id, user.username, user.display_name, user.role, saved.csrf_token, saved.token_hash) + + +async def csrf_actor(request: Request, actor: Actor = Depends(current_actor)): + supplied = request.headers.get("X-CSRF-Token", "") + if not hmac.compare_digest(supplied.encode("utf-8"), actor.csrf_token.encode("utf-8")): + fail(403, "csrf_failed", "请求校验失败,请刷新登录状态") + # Same-origin proxy is the deployment default; reject explicitly cross-site writes. + if request.headers.get("sec-fetch-site") == "cross-site": + fail(403, "cross_site_request", "不允许跨站写入") + return actor + + +class Login(BaseModel): + username: str = Field(min_length=1, max_length=64) + password: str = Field(min_length=1, max_length=256) + + +class CreateUser(Login): + display_name: str = Field(default="", max_length=80) + + +async def bootstrap_admin(db, settings): + if not settings.admin_username and not settings.admin_password: + return + if not settings.admin_username or not settings.admin_password: + raise ValueError("Both ADMIN_USERNAME and ADMIN_PASSWORD are required for bootstrap") + # The initial account may use the operator's explicitly chosen six-character + # password. Ordinary user creation keeps the 12-character minimum. + validate_password(settings.admin_password, minimum=6) + async with db.session() as session: + exists = await session.scalar(select(User).where(User.username == settings.admin_username.strip().lower())) + if exists is not None: + return + session.add(User(username=settings.admin_username.strip().lower(), display_name=settings.admin_display_name, + role="admin", password_hash=await asyncio.to_thread(hash_password, settings.admin_password))) + await session.commit() + + +@router.post("/login") +async def login(body: Login, request: Request, response: Response): + async with request.app.state.db.session() as session: + user = await session.scalar(select(User).where(User.username == body.username.strip().lower())) + valid = await asyncio.to_thread(verify_password, body.password, user.password_hash if user else "") + if not valid or user is None or user.disabled: + fail(401, "invalid_credentials", "用户名或密码不正确") + token, csrf = secrets.token_urlsafe(32), secrets.token_urlsafe(32) + settings = request.app.state.settings + session.add(Session(token_hash=token_hash(token), user_id=user.id, csrf_token=csrf, + expires_at=utcnow() + timedelta(hours=settings.session_hours))) + await session.commit() + response.set_cookie(COOKIE, token, httponly=True, secure=settings.cookie_secure, samesite="lax", + max_age=settings.session_hours * 3600, path="/") + return {"user": user_dto(user), "csrf_token": csrf} + + +@router.get("/me") +async def me(actor: Actor = Depends(current_actor)): + return {"user": {"id": actor.id, "username": actor.username, "display_name": actor.display_name, "role": actor.role}, + "csrf_token": actor.csrf_token} + + +@router.post("/logout", status_code=204) +async def logout(request: Request, actor: Actor = Depends(csrf_actor)): + async with request.app.state.db.session() as session: + await session.execute(delete(Session).where(Session.token_hash == actor.token_hash)) + await session.commit() + response = Response(status_code=204) + response.delete_cookie(COOKIE, path="/") + return response + + +@router.post("/users", status_code=201) +async def create_user(body: CreateUser, request: Request, actor: Actor = Depends(csrf_actor)): + if actor.role != "admin": + fail(403, "admin_required", "此操作仅限管理员") + username = body.username.strip().lower() + if not re.fullmatch(r"[a-z0-9_.-]{3,64}", username): + fail(422, "invalid_username", "用户名须为 3–64 位字母、数字、点、横线或下划线") + validate_password(body.password) + async with request.app.state.db.session() as session: + user = User(username=username, display_name=body.display_name.strip() or username, + password_hash=await asyncio.to_thread(hash_password, body.password)) + session.add(user) + try: + await session.commit() + except IntegrityError: + fail(409, "username_exists", "用户名已存在") + return user_dto(user) diff --git a/backend/app/config.py b/backend/app/config.py new file mode 100644 index 0000000..291f685 --- /dev/null +++ b/backend/app/config.py @@ -0,0 +1,109 @@ +from dataclasses import dataclass +import os +from pathlib import Path +from sqlalchemy.engine import URL, make_url + + +def boolean(value): + return str(value).lower() in {"1", "true", "yes", "on"} + + +@dataclass +class Settings: + mode: str = "production" + database_url: str | None = None + mysql_host: str = "192.168.28.10" + mysql_port: int = 3306 + mysql_database: str = "cmvr-visual" + mysql_user: str = "" + mysql_password: str = "" + workspace_root: Path = Path("/workspace") + asset_root: Path | None = None + job_work_root: Path | None = None + state_root: Path | None = None + admin_username: str = "" + admin_password: str = "" + admin_display_name: str = "管理员" + cookie_secure: bool = True + session_hours: int = 12 + run_coordinator: bool = True + poll_seconds: float = 1.0 + event_heartbeat_seconds: float = 15.0 + max_upload_bytes: int = 512 * 1024 * 1024 + max_output_bytes: int = 2 * 1024 * 1024 * 1024 + request_timeout_seconds: float = 30.0 + inference_base_url: str = "http://llmuser-workspace:18190" + inference_api_key: str = "" + inference_api_key_file: Path | None = Path("/workspace/projects/llm-services/config/api_key") + gpu_status_path: Path | None = Path("/run/llm-gpu-policy/status.json") + gpu_scheduler_path: Path | None = Path("/workspace/projects/llm-services/state/gpu-scheduler.json") + qwen_base_url: str = "http://192.168.28.10:14081/v1" + qwen_model: str = "Qwen/Qwen3.8-27B-FP8" + qwen_api_key: str = "" + ffmpeg_bin: str = "ffmpeg" + ffprobe_bin: str = "ffprobe" + tts_base_url: str = "" + tts_model: str = "kokoro-82m" + tts_api_key: str = "" + tts_voices: tuple[str, ...] = ("zf_xiaobei", "zm_yunxi") + + def __post_init__(self): + if self.mode not in {"production", "preview", "test"}: + raise ValueError("CMVR_MODE must be production, preview or test") + self.workspace_root = Path(self.workspace_root).resolve() + for field, leaf in (("asset_root", "assets"), ("job_work_root", "jobs"), ("state_root", "state")): + value = Path(getattr(self, field) or self.workspace_root / "cmvr-visual" / leaf).resolve() + if not value.is_relative_to(self.workspace_root): + raise ValueError(field + " must stay inside WORKSPACE_ROOT") + setattr(self, field, value) + for field in ("inference_api_key_file", "gpu_status_path", "gpu_scheduler_path"): + if getattr(self, field): + setattr(self, field, Path(getattr(self, field))) + if self.database_url: + url = make_url(self.database_url) + if url.drivername.startswith("sqlite"): + if self.mode not in {"preview", "test"} or url.drivername != "sqlite+aiosqlite": + raise ValueError("SQLite requires explicit test/preview mode and the aiosqlite driver") + elif url.drivername != "mysql+aiomysql": + raise ValueError("Production database must use mysql+aiomysql") + elif self.mode != "production": + raise ValueError("Test/preview mode requires an explicit DATABASE_URL") + elif not self.mysql_user or not self.mysql_password: + raise ValueError("Production MySQL credentials must be configured") + + @property + def sqlalchemy_url(self): + if self.database_url: + return make_url(self.database_url) + return URL.create("mysql+aiomysql", username=self.mysql_user, password=self.mysql_password, + host=self.mysql_host, port=self.mysql_port, database=self.mysql_database, + query={"charset": "utf8mb4"}) + + @classmethod + def from_env(cls): + env = os.environ + values = {} + strings = ("database_url", "mysql_host", "mysql_database", "mysql_user", "mysql_password", + "admin_username", "admin_password", "admin_display_name", "inference_base_url", + "inference_api_key", "qwen_base_url", "qwen_model", "qwen_api_key", "ffmpeg_bin", "ffprobe_bin", + "tts_base_url", "tts_model", "tts_api_key") + for field in strings: + if field.upper() in env: + values[field] = env[field.upper()] + for field in ("workspace_root", "asset_root", "job_work_root", "state_root", "inference_api_key_file", + "gpu_status_path", "gpu_scheduler_path"): + if field.upper() in env: + values[field] = Path(env[field.upper()]) if env[field.upper()] else None + for field in ("mysql_port", "session_hours", "max_upload_bytes", "max_output_bytes"): + if field.upper() in env: + values[field] = int(env[field.upper()]) + for field in ("poll_seconds", "event_heartbeat_seconds", "request_timeout_seconds"): + if field.upper() in env: + values[field] = float(env[field.upper()]) + for field in ("cookie_secure", "run_coordinator"): + if field.upper() in env: + values[field] = boolean(env[field.upper()]) + values["mode"] = env.get("CMVR_MODE", "production") + if "TTS_VOICES" in env: + values["tts_voices"] = tuple(v.strip() for v in env["TTS_VOICES"].split(",") if v.strip()) + return cls(**values) diff --git a/backend/app/coordinator.py b/backend/app/coordinator.py new file mode 100644 index 0000000..9c1bb47 --- /dev/null +++ b/backend/app/coordinator.py @@ -0,0 +1,340 @@ +import asyncio +from datetime import timedelta +import json +import logging +from pathlib import Path +import re +from filelock import FileLock +from sqlalchemy import case, or_, select +from .assets import confined, import_output, safe_file +from .dto import asset_dto, public_value +from .events import emit_asset, emit_job +from .jobs import GPU_TYPES, TERMINAL +from .models import Asset, Job, JobAsset, utcnow + +LOG = logging.getLogger(__name__) + + +class Coordinator: + def __init__(self, settings, db, provider): + self.settings, self.db, self.provider = settings, db, provider + self._task = None + self._cpu = {} + self._run_lock = asyncio.Lock() + self._wake = asyncio.Event() + self._file_lock = FileLock(str(settings.state_root / "coordinator.lock")) + self._closing = False + + def wake(self): + self._wake.set() + + async def start(self): + self._file_lock.acquire(timeout=0) + try: + # CPU calls cannot be replayed after an unknown crash. GPU IDs and + # persisted submit payload/key are resumed by their normal branches. + async with self.db.session() as session: + rows = (await session.scalars(select(Job).where(Job.state.notin_(TERMINAL), + Job.task_type.notin_(GPU_TYPES), Job.phase == "cpu_running"))).all() + for job in rows: + job.state = "cancelled" if job.cancel_requested else "failed" + job.phase, job.finished_at = job.state, utcnow() + job.error_json = {"code": "worker_interrupted", "message": "服务重启中断了此任务,可手动重试", "retriable": True} + await emit_job(session, job) + await session.commit() + self._task = asyncio.create_task(self._loop(), name="cmvr-coordinator") + except BaseException: + self._file_lock.release() + raise + + async def close(self): + self._closing = True + if self._task: + self._task.cancel() + await asyncio.gather(self._task, return_exceptions=True) + for task in self._cpu.values(): + task.cancel() + await asyncio.gather(*list(self._cpu.values()), return_exceptions=True) + if self._file_lock.is_locked: + self._file_lock.release() + + async def _loop(self): + while True: + try: + await self.run_once() + except asyncio.CancelledError: + raise + except Exception: + LOG.exception("Coordinator tick failed; persisted work remains recoverable") + self._wake.clear() + try: + await asyncio.wait_for(self._wake.wait(), timeout=self.settings.poll_seconds) + except asyncio.TimeoutError: + pass + + async def _job(self, job_id): + async with self.db.session() as session: + return await session.get(Job, job_id) + + async def _update(self, job_id, *, fresh_dispatch=False, **changes): + async with self.db.session() as session: + job = await session.get(Job, job_id) + if job.state in TERMINAL: + return job + if job.cancel_requested: + if fresh_dispatch or changes.get("state") in {"collecting", "succeeded", "failed", "timed_out", "cancelled"}: + # Cancellation is arbitrated against the authoritative row + # in the same transaction as any outcome/publication phase. + changes = {"state": "cancelled", "phase": "cancelled", "finished_at": utcnow(), + "result_json": None, "error_json": None, "sync_warning": None} + elif changes.get("state") in {"queued", "running", "submitting"}: + changes["state"], changes["phase"] = "cancelling", "cancellation_pending" + changed = False + for key, value in changes.items(): + if getattr(job, key) != value: + setattr(job, key, value) + if key not in {"next_action_at", "sync_failures"}: + changed = True + if changed: + await emit_job(session, job) + await session.commit() + return job + + async def _assets(self, job): + async with self.db.session() as session: + assets = (await session.scalars(select(Asset).join(JobAsset, JobAsset.asset_id == Asset.id) + .where(JobAsset.job_id == job.id, Asset.owner_id == job.owner_id))).all() + return {asset.id: confined(self.settings.asset_root, asset.storage_key, exists=True) for asset in assets} + + async def _workdir(self, job): + job = await self._update(job.id, work_attempt=job.work_attempt + 1) + path = confined(self.settings.job_work_root, Path(job.id) / f"attempt-{job.work_attempt:04d}") + path.mkdir(parents=True, exist_ok=False) + return job, path + + async def _warning(self, job_id, error): + job = await self._job(job_id) + await self._update(job_id, sync_warning="上游连接或结果导入暂不可用,正在恢复同步", + sync_failures=job.sync_failures + 1, + next_action_at=utcnow() + timedelta(seconds=min(30, 2 ** min(job.sync_failures, 5)))) + LOG.warning("Job %s external boundary unavailable: %s", job_id, type(error).__name__) + + async def _failure(self, job_id, exc): + job = await self._job(job_id) + code = getattr(exc, "code", "processing_failed") + message = getattr(exc, "message", "任务处理失败,请联系管理员查看服务日志") + await self._update(job_id, state="cancelled" if job.cancel_requested else "failed", + phase="cancelled" if job.cancel_requested else "failed", finished_at=utcnow(), + error_json={"code": code, "message": message, "retriable": bool(getattr(exc, "retriable", False))}) + + async def _complete(self, job_id, result): + async with self.db.session() as session: + job = await session.get(Job, job_id) + if job.state in TERMINAL: + return + if job.cancel_requested: + job.state, job.phase = "cancelled", "cancelled" + job.result_json, job.error_json, job.sync_warning = None, None, None + job.finished_at = utcnow() + await emit_job(session, job) + await session.commit() + return + outputs = (await session.scalars(select(Asset).where(Asset.source_job_id == job_id) + .order_by(Asset.source_output_index))).all() + if not outputs: + raise ValueError("Completed job has no imported artifacts") + for asset in outputs: + if not asset.ready: + asset.ready = True + emit_asset(session, job.owner_id, "asset.created", {"asset": asset_dto(asset)}) + job.state, job.phase = "succeeded", "completed" + job.result_json, job.finished_at, job.sync_warning = result, utcnow(), None + await emit_job(session, job) + await session.commit() + + async def run_once(self, *, force=False): + async with self._run_lock: + for job_id, task in list(self._cpu.items()): + if task.done(): + self._cpu.pop(job_id) + await asyncio.gather(task, return_exceptions=True) + async with self.db.session() as session: + query = select(Job).where(Job.state.notin_(TERMINAL)) + if not force: + query = query.where(Job.next_action_at <= utcnow()) + ordering = (case((Job.cancel_requested.is_(True), 0), else_=1), + Job.next_action_at, Job.created_at, Job.batch_index, Job.id) + jobs = list((await session.scalars(query.order_by(*ordering).limit(50))).all()) + # Reserve one CPU candidate independently of a large GPU or + # cancellation backlog; network/GPU waiting cannot consume its slot. + cpu = await session.scalar(query.where(Job.task_type.notin_(GPU_TYPES), + or_(Job.scheduled_at.is_(None), Job.scheduled_at <= utcnow())).order_by(*ordering).limit(1)) + if cpu is not None: + # Start/cancel the independent CPU task before potentially + # slow GPU HTTP calls, rather than merely adding a tail slot. + jobs = [cpu] + [job for job in jobs if job.id != cpu.id] + for job in jobs: + if job.scheduled_at and job.scheduled_at > utcnow(): + continue + # Every inspected candidate moves forward, even when CPU is + # busy. This durable timestamp rotates bounded batches fairly. + job = await self._update(job.id, next_action_at=utcnow() + timedelta(seconds=self.settings.poll_seconds)) + if job.state in TERMINAL: + continue + if job.id in self._cpu: + if job.cancel_requested and job.state != "collecting": + self._cpu[job.id].cancel() + continue + if job.task_type in GPU_TYPES: + await self._gpu(job) + elif job.state == "collecting": + try: + await self._collect_cpu(job) + except Exception as exc: + await self._warning(job.id, exc) + elif not self._cpu: + self._cpu[job.id] = asyncio.create_task(self._run_cpu(job), name=f"cpu-job-{job.id}") + + async def _gpu(self, job): + try: + if job.state == "collecting": + await self._collect_gpu(job) + return + if not job.upstream_id: + if job.cancel_requested and job.upstream_payload is None: + await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow()) + return + if job.upstream_payload is None: + job = await self._update(job.id, phase="preparing", state="submitting") + job, work = await self._workdir(job) + payload = await self.provider.prepare_gpu_payload(job.task_type, job.input_json, job.parameters, + await self._assets(job), work) + # This commit precedes POST; retries must reuse both values. + job = await self._update(job.id, upstream_payload=payload, phase="dispatching", fresh_dispatch=True) + if job.state in TERMINAL: + return + # This invocation knows no POST has started yet. An existing + # persisted payload on restart is instead ambiguous and must + # still recover its upstream ID using the same key below. + job = await self._job(job.id) + if job.cancel_requested: + await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow()) + return + remote = await self.provider.submit(job.upstream_payload, job.upstream_key) + remote_id = remote.get("id") + if not isinstance(remote_id, str) or not remote_id: + raise ValueError("Upstream omitted its job ID") + job = await self._update(job.id, upstream_id=remote_id) + else: + remote = await self.provider.cancel(job.upstream_id) if job.cancel_requested else await self.provider.query(job.upstream_id) + # A cancellation arriving while POST was in flight is persisted and + # sent against the same recovered ID on the next tick. + await self._apply_remote(job.id, remote) + except asyncio.CancelledError: + raise + except Exception as exc: + if not job.upstream_id and getattr(exc, "code", None) == "upstream_rejected": + await self._failure(job.id, exc) + elif getattr(exc, "retriable", False) or job.upstream_payload is not None or job.upstream_id: + await self._warning(job.id, exc) + else: + LOG.exception("Job %s preparation failed", job.id) + await self._failure(job.id, exc) + + async def _apply_remote(self, job_id, remote): + state = remote.get("state") + if state not in {"queued", "running", "succeeded", "failed", "cancelled", "timed_out"}: + raise ValueError("Invalid upstream job state") + job = await self._job(job_id) + changes = {"state": state, "phase": remote.get("stage") or state, + "attempt_count": int(remote.get("attempt_count", job.attempt_count)), + "preemptions": int(remote.get("preemptions", job.preemptions)), + "last_preempted_reason": public_value(remote.get("last_preempted_reason")), + "sync_warning": None, "sync_failures": 0, + "next_action_at": utcnow() + timedelta(seconds=self.settings.poll_seconds)} + if state == "running" and not job.started_at: + changes["started_at"] = utcnow() + if state == "succeeded": + changes.update(state="collecting", phase="importing_outputs", upstream_result=remote.get("result") or {}) + elif state in TERMINAL: + changes["finished_at"] = utcnow() + if state in {"failed", "timed_out"}: + changes["error_json"] = {"code": "upstream_" + state, "message": "模型任务未完成,请检查参数或重试", "retriable": True} + job = await self._update(job_id, **changes) + if job.state == "collecting": + await self._collect_gpu(job) + + async def _collect_gpu(self, job): + outputs = (job.upstream_result or {}).get("outputs") + if not isinstance(outputs, list) or not outputs: + raise ValueError("Succeeded upstream job has no outputs") + directory = confined(self.settings.job_work_root, Path(job.id) / "imports") + directory.mkdir(parents=True, exist_ok=True) + assets = [] + for index, output in enumerate(outputs): + async with self.db.session() as session: + existing = await session.scalar(select(Asset).where(Asset.source_job_id == job.id, + Asset.source_output_index == index)) + if existing: + assets.append(existing) + continue + raw = output.get("path", "") if isinstance(output, dict) else str(output) + suffix = Path(raw).suffix.lower() + if not re.fullmatch(r"\.[a-z0-9]{1,10}", suffix): + suffix = ".bin" + destination = directory / f"output-{index:04d}{suffix}" + await self.provider.download(job.upstream_id, index, destination) + assets.append(await import_output(self.db, self.settings, job, destination, index)) + result = public_value((job.upstream_result or {}).get("metadata", {})) + if job.task_type == "audio.transcribe": + for asset in assets: + if asset.kind == "json" and asset.size_bytes <= 5 * 1024 * 1024: + with safe_file(self.settings.asset_root, asset.storage_key) as stream: + transcript = json.load(stream) + result = {"text": transcript.get("text", ""), "segments": transcript.get("segments", [])} + break + await self._complete(job.id, result) + + async def _run_cpu(self, job): + try: + if job.cancel_requested: + await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow()) + return + job = await self._update(job.id, state="running", phase="cpu_running", started_at=utcnow(), + attempt_count=job.attempt_count + 1) + if job.state in TERMINAL or job.cancel_requested: + if job.state not in TERMINAL: + await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow()) + return + job, work = await self._workdir(job) + result = await self.provider.run_cpu(job.task_type, job.input_json, job.parameters, await self._assets(job), work) + job = await self._job(job.id) + if job.cancel_requested: + await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow()) + return + if not isinstance(result.outputs, list) or not result.outputs: + raise ValueError("CPU provider returned no artifacts") + private = {"cpu_outputs": [str(confined(self.settings.job_work_root, p, exists=True)) for p in result.outputs], + "cpu_result": result.result, "metadata": result.metadata} + job = await self._update(job.id, state="collecting", phase="importing_outputs", upstream_result=private) + if job.state not in TERMINAL: + await self._collect_cpu(job) + except asyncio.CancelledError: + job = await self._job(job.id) + if job.state != "collecting": + await self._update(job.id, state="cancelled" if job.cancel_requested else "failed", + phase="cancelled" if job.cancel_requested else "interrupted", finished_at=utcnow(), + error_json=None if job.cancel_requested else {"code": "worker_interrupted", "message": "任务因服务停止而中断", "retriable": True}) + except Exception as exc: + job = await self._job(job.id) + if job.state == "collecting": + await self._warning(job.id, exc) + else: + LOG.exception("CPU job %s failed", job.id) + await self._failure(job.id, exc) + + async def _collect_cpu(self, job): + private = job.upstream_result or {} + for index, source in enumerate(private.get("cpu_outputs", [])): + await import_output(self.db, self.settings, job, Path(source), index) + await self._complete(job.id, public_value(private.get("cpu_result", {}))) diff --git a/backend/app/database.py b/backend/app/database.py new file mode 100644 index 0000000..c9b1424 --- /dev/null +++ b/backend/app/database.py @@ -0,0 +1,34 @@ +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine +from sqlalchemy import event +import asyncio +from contextlib import asynccontextmanager +from .models import Base + + +class Database: + def __init__(self, settings): + self.engine = create_async_engine(settings.sqlalchemy_url, pool_pre_ping=True) + if settings.sqlalchemy_url.drivername.startswith("sqlite"): + @event.listens_for(self.engine.sync_engine, "connect") + def sqlite_options(connection, _): + cursor = connection.cursor() + cursor.execute("PRAGMA foreign_keys=ON") + cursor.execute("PRAGMA busy_timeout=10000") + cursor.close() + self._sessions = async_sessionmaker(self.engine, expire_on_commit=False) + # One API process by deployment contract. Short DB units are serialized + # so durable SSE IDs are observed in commit order, including CPU imports. + self._unit_lock = asyncio.Lock() + + @asynccontextmanager + async def session(self): + async with self._unit_lock: + async with self._sessions() as session: + yield session + + async def initialize(self): + async with self.engine.begin() as connection: + await connection.run_sync(Base.metadata.create_all) + + async def close(self): + await self.engine.dispose() diff --git a/backend/app/dto.py b/backend/app/dto.py new file mode 100644 index 0000000..72bb777 --- /dev/null +++ b/backend/app/dto.py @@ -0,0 +1,44 @@ +import re +from sqlalchemy import select +from .models import Asset, JobAsset + + +def iso(value): + return value.isoformat(timespec="milliseconds") + "Z" if value is not None else None + + +def public_value(value): + if isinstance(value, dict): + return {k: public_value(v) for k, v in value.items() + if k not in {"path", "output_dir", "storage_key", "api_key", "token", "request_path"}} + if isinstance(value, list): + return [public_value(v) for v in value] + if isinstance(value, str): + value = re.sub(r"/(?:workspace|run|data|home|var|tmp|srv)/[^\s,;]+", "[server file]", value) + return re.sub(r"[A-Za-z]:[\\/][^\s,;]+", "[server file]", value) + return value + + +def asset_dto(asset): + return {"id": asset.id, "name": asset.name, "kind": asset.kind, "mime_type": asset.mime_type, + "size_bytes": asset.size_bytes, "width": asset.width, "height": asset.height, + "duration_seconds": asset.duration_seconds, + "preview_url": f"/api/assets/{asset.id}/content", + "thumbnail_url": f"/api/assets/{asset.id}/thumbnail" if asset.kind in {"image", "video"} else None, + "download_url": f"/api/assets/{asset.id}/content?download=1", "source_job_id": asset.source_job_id, + "origin": asset.origin, "tags": asset.tags or [], "favorite": asset.favorite, + "created_at": iso(asset.created_at)} + + +async def job_dto(session, job): + assets = (await session.scalars(select(Asset).where(Asset.source_job_id == job.id, Asset.deleted_at.is_(None), Asset.ready.is_(True)) + .order_by(Asset.source_output_index))).all() + inputs = (await session.scalars(select(JobAsset.asset_id).where(JobAsset.job_id == job.id))).all() + return {"id": job.id, "task_type": job.task_type, "state": job.state, "phase": job.phase, + "version": job.version, "prompt": job.input_json.get("prompt", ""), "parameters": job.parameters, + "input_asset_ids": list(inputs), "result_assets": [asset_dto(a) for a in assets], + "result": public_value(job.result_json), "progress": None, "queue_position": None, + "upstream_id": job.upstream_id, "attempt_count": job.attempt_count, "preemptions": job.preemptions, + "last_preempted_reason": job.last_preempted_reason, "cancel_requested": job.cancel_requested, + "error": job.error_json, "sync_warning": job.sync_warning, "created_at": iso(job.created_at), + "scheduled_at": iso(job.scheduled_at), "started_at": iso(job.started_at), "finished_at": iso(job.finished_at)} diff --git a/backend/app/errors.py b/backend/app/errors.py new file mode 100644 index 0000000..71ad874 --- /dev/null +++ b/backend/app/errors.py @@ -0,0 +1,5 @@ +from fastapi import HTTPException + + +def fail(status, code, message): + raise HTTPException(status, detail={"code": code, "message": message}) diff --git a/backend/app/events.py b/backend/app/events.py new file mode 100644 index 0000000..d3a6fc6 --- /dev/null +++ b/backend/app/events.py @@ -0,0 +1,77 @@ +import asyncio +import json +import time +from fastapi import APIRouter, Depends, Request +from fastapi.responses import StreamingResponse +from sqlalchemy import func, select +from .auth import Actor, COOKIE, current_actor, token_hash +from .dto import job_dto +from .errors import fail +from .models import Event, Session, User, utcnow + +router = APIRouter(tags=["events"]) + + +async def emit_job(session, job, *, increment=True): + if increment: + job.version += 1 + await session.flush() + session.add(Event(owner_id=job.owner_id, job_id=job.id, event_type="job.updated", + data={"job": await job_dto(session, job)})) + + +def emit_asset(session, owner_id, event_type, data): + session.add(Event(owner_id=owner_id, event_type=event_type, data=data)) + + +async def event_batch(db, owner_id, after, limit=100): + async with db.session() as session: + events = (await session.scalars(select(Event).where(Event.owner_id == owner_id, Event.id > after) + .order_by(Event.id).limit(limit))).all() + return [{"id": event.id, "event": event.event_type, "data": event.data} for event in events] + + +async def session_is_active(db, token): + if not token: + return False + async with db.session() as session: + return (await session.scalar(select(Session.token_hash).join(User, User.id == Session.user_id) + .where(Session.token_hash == token_hash(token), Session.expires_at > utcnow(), User.disabled.is_(False)))) is not None + + +async def event_stream(request, owner_id, token, after): + # Authentication was checked by the endpoint. Flush a body immediately so + # EventSource/proxies need not wait for the first durable event or heartbeat. + yield ": connected\n\n" + db = request.app.state.db + heartbeat = request.app.state.settings.event_heartbeat_seconds + last_heartbeat = time.monotonic() + async with db.session() as session: + maximum = await session.scalar(select(func.max(Event.id)).where(Event.owner_id == owner_id)) or 0 + if after > maximum: + yield f"id: {maximum}\nevent: reset\ndata: {{}}\n\n" + after = maximum + while not await request.is_disconnected(): + if not await session_is_active(db, token): + return + rows = await event_batch(db, owner_id, after) + for event in rows: + after = event["id"] + yield f"id: {after}\nevent: {event['event']}\ndata: {json.dumps(event['data'], ensure_ascii=False, separators=(',', ':'))}\n\n" + if time.monotonic() - last_heartbeat >= heartbeat: + yield ": heartbeat\n\n" + last_heartbeat = time.monotonic() + if not rows: + await asyncio.sleep(min(.5, heartbeat)) + + +@router.get("/events") +async def events(request: Request, after: int = 0, actor: Actor = Depends(current_actor)): + try: + cursor = int(request.headers.get("Last-Event-ID", after)) + if cursor < 0: + raise ValueError + except ValueError: + fail(422, "invalid_cursor", "事件游标必须为非负整数") + return StreamingResponse(event_stream(request, actor.id, request.cookies.get(COOKIE), cursor), + media_type="text/event-stream", headers={"Cache-Control": "no-cache, no-transform", "X-Accel-Buffering": "no"}) diff --git a/backend/app/jobs.py b/backend/app/jobs.py new file mode 100644 index 0000000..bd36fb0 --- /dev/null +++ b/backend/app/jobs.py @@ -0,0 +1,217 @@ +from datetime import datetime, timezone +import hashlib +import json +from fastapi import APIRouter, Depends, Header, Request +from pydantic import BaseModel, Field +from sqlalchemy import func, select +from sqlalchemy.exc import IntegrityError +from .assets import owned_asset +from .auth import Actor, csrf_actor, current_actor +from .dto import job_dto +from .errors import fail +from .events import emit_job +from .models import Event, Job, JobAsset, new_id, utcnow + +router = APIRouter(prefix="/jobs", tags=["jobs"]) +GPU_TYPES = {"image.generate", "video.generate", "defect.generate", "audio.transcribe"} +CPU_TYPES = {"math.solve", "media.structure", "video.compose", "audio.speech"} +TERMINAL = {"succeeded", "failed", "cancelled", "timed_out"} + + +class Submit(BaseModel): + task_type: str + input: dict = Field(default_factory=dict) + parameters: dict = Field(default_factory=dict) + count: int = Field(default=1, ge=1, le=4) + scheduled_at: datetime | None = None + + +async def owned_job(session, job_id, owner_id): + job = await session.scalar(select(Job).where(Job.id == job_id, Job.owner_id == owner_id)) + if job is None: + fail(404, "job_not_found", "任务不存在") + return job + + +def input_ids(inputs, parameters): + result = [] + for field in ("image_asset_id", "audio_asset_id", "asset_id"): + if inputs.get(field): + result.append(inputs[field]) + if inputs.get("asset_ids"): + if not isinstance(inputs["asset_ids"], list): + fail(422, "invalid_assets", "asset_ids 必须为素材编号列表") + result.extend(inputs["asset_ids"]) + for clip in parameters.get("clips", []): + if not isinstance(clip, dict) or not isinstance(clip.get("asset_id"), str): + fail(422, "invalid_clip", "每个片段需要素材编号") + result.append(clip["asset_id"]) + if parameters.get("audio_asset_id"): + result.append(parameters["audio_asset_id"]) + if any(not isinstance(value, str) or len(value) > 64 for value in result): + fail(422, "invalid_assets", "素材编号格式不正确") + return list(dict.fromkeys(result)) + + +async def validate_submission(session, body, owner_id, settings): + if body.task_type not in GPU_TYPES | CPU_TYPES: + fail(422, "unsupported_task", "不支持此任务类型") + allowed = {"prompt", "negative_prompt", "image_asset_id", "audio_asset_id", "asset_id", "asset_ids"} + if set(body.input) - allowed: + fail(422, "invalid_input", "只允许提示词与素材编号,不接受服务器路径或 URL") + if body.count > 1 and body.task_type not in {"image.generate", "defect.generate"}: + fail(422, "batch_not_supported", "此任务类型不支持批量生成") + if body.task_type == "audio.speech" and not settings.tts_base_url: + fail(422, "speech_unavailable", "尚未配置真实配音服务") + from .providers import ProviderError, validate_arguments + try: + validate_arguments(body.task_type, body.input, body.parameters, settings) + except ProviderError as exc: + fail(400, exc.code, exc.message) + prompt = body.input.get("prompt", "") + if not isinstance(prompt, str) or len(prompt) > 8000: + fail(422, "invalid_prompt", "提示词须为不超过 8000 字符的文本") + if body.task_type in {"image.generate", "video.generate", "defect.generate", "math.solve", "audio.speech"} and not prompt.strip(): + fail(422, "prompt_required", "请输入提示词或文本") + ids = input_ids(body.input, body.parameters) + assets = {asset_id: await owned_asset(session, asset_id, owner_id) for asset_id in ids} + required = {"defect.generate": "image_asset_id", "audio.transcribe": "audio_asset_id", "media.structure": "asset_id"} + if body.task_type in required: + key = required[body.task_type] + value = body.input.get(key) or (body.input.get("asset_id") if key == "audio_asset_id" else None) + if not value: + fail(422, "asset_required", "此任务需要输入素材") + for key, kinds in (("image_asset_id", {"image"}), ("audio_asset_id", {"audio", "video"})): + if body.input.get(key) and assets[body.input[key]].kind not in kinds: + fail(422, "wrong_asset_kind", "输入素材类型不正确") + if body.task_type == "media.structure" and assets[body.input["asset_id"]].kind not in {"image", "video"}: + fail(422, "wrong_asset_kind", "素材理解需要图片或视频") + if body.task_type == "audio.transcribe": + source_id = body.input.get("audio_asset_id") or body.input.get("asset_id") + if assets[source_id].kind not in {"audio", "video"}: + fail(422, "wrong_asset_kind", "转写需要音频或视频素材") + if body.task_type == "video.compose" and not ids: + fail(422, "clips_required", "请添加待合成片段") + if body.task_type == "video.compose": + if any(assets[clip["asset_id"]].kind != "video" for clip in body.parameters.get("clips", [])): + fail(422, "wrong_asset_kind", "编排片段必须为视频素材") + audio_id = body.input.get("audio_asset_id") or body.parameters.get("audio_asset_id") + if audio_id and assets[audio_id].kind != "audio": + fail(422, "wrong_asset_kind", "成片音轨必须为音频素材") + if body.scheduled_at is not None and body.scheduled_at.tzinfo is None: + fail(422, "timezone_required", "定时任务时间须包含时区") + return ids + + +async def create_jobs(session, body, actor, settings, key=None): + if key is not None and not 1 <= len(key) <= 128: + fail(422, "invalid_idempotency_key", "幂等键长度须为 1–128") + payload = body.model_dump(mode="json") + try: + fingerprint = hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=False, + allow_nan=False).encode()).hexdigest() + except (ValueError, TypeError): + fail(422, "invalid_json", "任务参数必须为有限数值和合法 JSON") + if key: + existing = (await session.scalars(select(Job).where(Job.owner_id == actor.id, Job.request_key == key) + .order_by(Job.batch_index))).all() + if existing: + if existing[0].request_hash != fingerprint: + fail(409, "idempotency_conflict", "此幂等键已用于不同的任务参数") + return existing + ids = await validate_submission(session, body, actor.id, settings) + scheduled = body.scheduled_at.astimezone(timezone.utc).replace(tzinfo=None) if body.scheduled_at else None + jobs = [] + for index in range(body.count): + job_id = new_id() + future = scheduled and scheduled > utcnow() + parameters = dict(body.parameters) + if body.count > 1: + parameters["seed"] = (parameters.get("seed", 42) + index) % (2 ** 32) + job = Job(id=job_id, owner_id=actor.id, task_type=body.task_type, + state="scheduled" if future else "submitting", phase="scheduled" if future else "waiting_dispatch", + version=1, input_json=body.input, parameters=parameters, request_key=key, + request_hash=fingerprint, batch_index=index, upstream_key="cmvr-visual:" + job_id, + scheduled_at=scheduled, next_action_at=scheduled if future else utcnow(), + attempt_count=0, work_attempt=0, preemptions=0, cancel_requested=False) + session.add(job) + await session.flush() + session.add_all(JobAsset(job_id=job.id, asset_id=asset_id) for asset_id in ids) + await emit_job(session, job, increment=False) + jobs.append(job) + return jobs + + +def wake(request): + request.app.state.coordinator.wake() + + +@router.post("", status_code=202) +async def submit(body: Submit, request: Request, idempotency_key: str | None = Header(default=None), + actor: Actor = Depends(csrf_actor)): + async with request.app.state.db.session() as session: + try: + jobs = await create_jobs(session, body, actor, request.app.state.settings, idempotency_key) + await session.commit() + except IntegrityError: + await session.rollback() + jobs = await create_jobs(session, body, actor, request.app.state.settings, idempotency_key) + result = {"jobs": [await job_dto(session, job) for job in jobs]} + wake(request) + return result + + +@router.get("") +async def list_jobs(request: Request, page: int = 1, page_size: int = 24, task_type: str = "", state: str = "", + actor: Actor = Depends(current_actor)): + if page < 1 or not 1 <= page_size <= 100: + fail(422, "invalid_page", "分页参数无效") + async with request.app.state.db.session() as session: + query = select(Job).where(Job.owner_id == actor.id) + if task_type: + query = query.where(Job.task_type == task_type) + if state: + query = query.where(Job.state == state) + total = await session.scalar(select(func.count()).select_from(query.subquery())) + jobs = (await session.scalars(query.order_by(Job.created_at.desc(), Job.id.desc()) + .offset((page - 1) * page_size).limit(page_size))).all() + cursor = await session.scalar(select(func.max(Event.id)).where(Event.owner_id == actor.id)) or 0 + return {"items": [await job_dto(session, job) for job in jobs], "total": total, + "page": page, "page_size": page_size, "cursor": cursor} + + +@router.get("/{job_id}") +async def get_job(job_id: str, request: Request, actor: Actor = Depends(current_actor)): + async with request.app.state.db.session() as session: + return await job_dto(session, await owned_job(session, job_id, actor.id)) + + +@router.post("/{job_id}/cancel") +async def cancel(job_id: str, request: Request, actor: Actor = Depends(csrf_actor)): + async with request.app.state.db.session() as session: + job = await owned_job(session, job_id, actor.id) + if job.state not in TERMINAL and job.state != "collecting": + job.cancel_requested = True + if job.upstream_id is None and job.upstream_payload is None and job.phase not in {"cpu_running", "preparing"}: + job.state, job.phase, job.finished_at = "cancelled", "cancelled", utcnow() + else: + job.state, job.phase = "cancelling", "cancellation_pending" + await emit_job(session, job) + await session.commit() + result = await job_dto(session, job) + wake(request) + return result + + +@router.post("/{job_id}/retry", status_code=202) +async def retry(job_id: str, request: Request, actor: Actor = Depends(csrf_actor)): + async with request.app.state.db.session() as session: + old = await owned_job(session, job_id, actor.id) + if old.state not in TERMINAL: + fail(409, "job_not_finished", "请先等待或取消当前任务") + body = Submit(task_type=old.task_type, input=old.input_json, parameters=old.parameters) + jobs = await create_jobs(session, body, actor, request.app.state.settings) + await session.commit() + result = {"jobs": [await job_dto(session, job) for job in jobs]} + wake(request) + return result diff --git a/backend/app/main.py b/backend/app/main.py new file mode 100644 index 0000000..f8ea3b3 --- /dev/null +++ b/backend/app/main.py @@ -0,0 +1,76 @@ +from contextlib import asynccontextmanager +import asyncio +import logging +from fastapi import Depends, FastAPI +from fastapi.responses import JSONResponse +from sqlalchemy import text +from sqlalchemy.exc import SQLAlchemyError +from . import assets, auth, events, jobs +from .config import Settings +from .coordinator import Coordinator +from .database import Database + + +def create_app(settings=None, *, provider=None): + @asynccontextmanager + async def lifespan(app): + configuration = settings or Settings.from_env() + for root in (configuration.asset_root, configuration.job_work_root, configuration.state_root): + root.mkdir(parents=True, exist_ok=True) + db = Database(configuration) + app.state.settings, app.state.db = configuration, db + live_provider = provider + if live_provider is None: + from .providers import Provider + live_provider = Provider(configuration) + app.state.provider = live_provider + coordinator = Coordinator(configuration, db, live_provider) + app.state.coordinator = coordinator + try: + await db.initialize() + await auth.bootstrap_admin(db, configuration) + if configuration.run_coordinator: + await coordinator.start() + yield + finally: + await coordinator.close() + await live_provider.aclose() + await db.close() + + app = FastAPI(title="CMVR Visual", lifespan=lifespan) + @app.exception_handler(SQLAlchemyError) + async def database_failure(request, exc): + logging.getLogger(__name__).error("Database request failed: %s", type(exc).__name__) + return JSONResponse(status_code=503, content={"detail": {"code": "database_unavailable", "message": "数据库暂不可用,请稍后重试"}}) + + @app.exception_handler(Exception) + async def internal_failure(request, exc): + logging.getLogger(__name__).exception("Unhandled application error") + return JSONResponse(status_code=500, content={"detail": {"code": "internal_error", "message": "服务处理失败,请联系管理员"}}) + for router in (auth.router, assets.router, jobs.router, events.router): + app.include_router(router, prefix="/api") + + @app.get("/api/health") + async def health(): + async with app.state.db.session() as session: + await session.execute(text("SELECT 1")) + return {"status": "ok", "database": app.state.settings.sqlalchemy_url.get_backend_name()} + + @app.get("/api/capabilities", dependencies=[Depends(auth.current_actor)]) + async def capabilities(): + from .providers import capabilities as provider_capabilities + return {"items": provider_capabilities(app.state.settings), + "scheduler": await app.state.provider.scheduler_status()} + + @app.get("/api/system/status", dependencies=[Depends(auth.current_actor)]) + async def status(): + from .providers import capabilities as provider_capabilities + online, scheduler = await asyncio.gather(app.state.provider.health(), app.state.provider.scheduler_status()) + return {"inference_online": online, "scheduler": scheduler, "models": provider_capabilities(app.state.settings), + "environment": app.state.settings.mode, + "database_backend": app.state.settings.sqlalchemy_url.get_backend_name()} + + return app + + +app = create_app() diff --git a/backend/app/media.py b/backend/app/media.py new file mode 100644 index 0000000..db4a7d5 --- /dev/null +++ b/backend/app/media.py @@ -0,0 +1,235 @@ +"""Bounded CPU media operations. No shell, CUDA, external URLs or user filters.""" +from __future__ import annotations + +import asyncio +import json +import math +import os +from pathlib import Path +import uuid + +from PIL import Image, ImageOps, UnidentifiedImageError + + +class MediaError(RuntimeError): + def __init__(self, code: str, message: str, retriable: bool = False): + super().__init__(message) + self.code, self.message, self.retriable = code, message, retriable + + +def confined(path: Path, settings, *, exists: bool = True, root: Path | None = None) -> Path: + try: + candidate = Path(path) + boundary = Path(root or settings.workspace_root).resolve() + if not candidate.is_absolute(): + raise ValueError + resolved = candidate.resolve() + if not resolved.is_relative_to(boundary) or (exists and not resolved.is_file()): + raise ValueError + return resolved + except (OSError, ValueError, TypeError): + raise MediaError('invalid_asset', '素材文件不存在或不可访问。') from None + + +async def _stop(process): + if process.returncode is None: + try: + process.terminate() + except ProcessLookupError: + pass + try: + await asyncio.wait_for(process.wait(), 2) + except asyncio.TimeoutError: + try: + process.kill() + except ProcessLookupError: + pass + await asyncio.wait_for(process.wait(), 5) + + +async def _cleanup(process, readers): + for task in readers: + if not task.done(): + task.cancel() + await asyncio.gather(*readers, return_exceptions=True) + + async def discard(stream): + while await stream.read(65536): + pass + + # Drain after a size rejection/cancel too. Otherwise a full paused pipe + # can keep asyncio's process transport alive even after the child exited. + drains = [asyncio.create_task(discard(process.stdout)), asyncio.create_task(discard(process.stderr))] + try: + await _stop(process) + await asyncio.wait_for(asyncio.gather(*drains), 5) + finally: + for task in drains: + if not task.done(): + task.cancel() + await asyncio.gather(*drains, return_exceptions=True) + + +async def run_process(argv: list[str], *, timeout: float = 120, max_output: int = 1024 * 1024, + cwd: Path | None = None, return_stderr: bool = False) -> bytes | tuple[bytes, bytes]: + """Own one executable; cancellation does TERM/KILL/wait only on that child. + + FFmpeg/ffprobe do not launch child programs. Pipe readers enforce their + bounds while the child runs, rather than buffering arbitrary diagnostics. + """ + process = None + readers = [] + + async def read_bounded(stream): + chunks, count = [], 0 + while chunk := await stream.read(65536): + count += len(chunk) + if count > max_output: + raise MediaError('media_output_limit', '媒体处理诊断超出限制。') + chunks.append(chunk) + return b''.join(chunks) + + try: + process = await asyncio.create_subprocess_exec(*[str(value) for value in argv], + stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, cwd=str(cwd) if cwd else None, + start_new_session=(os.name == 'posix')) + readers = [asyncio.create_task(read_bounded(process.stdout)), + asyncio.create_task(read_bounded(process.stderr))] + async with asyncio.timeout(timeout): + stdout, stderr = await asyncio.gather(*readers) + await process.wait() + if process.returncode != 0: + raise MediaError('media_processing_failed', '媒体解码或处理失败,请检查素材格式。') + return (stdout, stderr) if return_stderr else stdout + except asyncio.CancelledError: + raise + except asyncio.TimeoutError: + raise MediaError('media_timeout', '媒体处理超时,请缩短素材后重试。', True) from None + except (OSError, ValueError): + raise MediaError('media_unavailable', '媒体处理程序不可用。', True) from None + finally: + if process is not None: + cleanup = asyncio.create_task(_cleanup(process, readers)) + recancelled = False + while not cleanup.done(): + try: + await asyncio.shield(cleanup) + except asyncio.CancelledError: + recancelled = True + await cleanup + if recancelled: + raise asyncio.CancelledError + + +def input_options() -> list[str]: + # Exclude playlists, concat input, network protocols and nested file lists. + return ['-protocol_whitelist', 'file,pipe', '-format_whitelist', + 'mov,matroska,webm,avi,wav,mp3,flac,ogg,aac,mpeg,mpegts'] + + +def _image_info(path): + try: + with Image.open(path) as image: + mime = {'PNG': 'image/png', 'JPEG': 'image/jpeg', 'WEBP': 'image/webp'}.get(image.format) + if mime is None or image.width * image.height > 40_000_000: + raise MediaError('invalid_image', '仅支持像素数受限的 PNG、JPEG、WebP 图片。') + image.load() + return {'kind': 'image', 'mime_type': mime, 'width': image.width, + 'height': image.height, 'duration_seconds': None} + except UnidentifiedImageError: + return None + except (OSError, ValueError, Image.DecompressionBombError): + raise MediaError('invalid_image', '图片文件无法解码。') from None + + +def _text_info(path): + if path.suffix.lower() not in {'.json', '.txt', '.md', '.srt', '.vtt'}: + return None + try: + if path.stat().st_size > 4 * 1024 * 1024: + raise ValueError + text = path.read_text(encoding='utf-8-sig') + if '\x00' in text or not text.strip(): + raise ValueError + is_json = path.suffix.lower() == '.json' + if is_json: + json.loads(text, parse_constant=lambda _: (_ for _ in ()).throw(ValueError())) + return {'kind': 'json' if is_json else 'text', + 'mime_type': 'application/json' if is_json else 'text/plain', + 'width': None, 'height': None, 'duration_seconds': None} + except (OSError, UnicodeError, ValueError, RecursionError): + raise MediaError('invalid_text', '文本或 JSON 文件格式无效。') from None + + +async def inspect_media(path: Path, settings) -> dict: + source = confined(path, settings) + if source.stat().st_size <= 0: + raise MediaError('invalid_asset', '素材文件为空。') + text = await asyncio.to_thread(_text_info, source) + if text is not None: + return text + image = await asyncio.to_thread(_image_info, source) + if image is not None: + return image + if source.suffix.lower() in {'.png', '.jpg', '.jpeg', '.webp'}: + raise MediaError('invalid_image', '图片文件无法解码。') + raw = await run_process([settings.ffprobe_bin, '-v', 'error', *input_options(), + '-show_entries', 'format=format_name,duration,start_time:stream=codec_type,codec_name,width,height,duration:stream_disposition=attached_pic', + '-of', 'json', str(source)], timeout=30, max_output=256 * 1024) + try: + data = json.loads(raw) + streams = data['streams'] + videos = [item for item in streams if item.get('codec_type') == 'video' + and not item.get('disposition', {}).get('attached_pic')] + audios = [item for item in streams if item.get('codec_type') == 'audio'] + if not videos and not audios: + raise ValueError + stream = videos[0] if videos else audios[0] + duration = float(data.get('format', {}).get('duration', stream.get('duration', 0))) + start_time = float(data.get('format', {}).get('start_time', 0)) + if not math.isfinite(start_time): + raise ValueError + if not math.isfinite(duration) or not 0 < duration <= 86400: + raise ValueError + width, height = stream.get('width'), stream.get('height') + if videos and (type(width) is not int or type(height) is not int or width <= 0 or height <= 0 + or width * height > 40_000_000): + raise ValueError + formats = str(data.get('format', {}).get('format_name', '')).split(',') + if videos: + mime = 'video/webm' if 'webm' in formats and source.suffix.lower() == '.webm' else 'video/mp4' if 'mov' in formats else 'video/x-matroska' if 'matroska' in formats else 'video/mp2t' if 'mpegts' in formats else 'video/mpeg' if 'mpeg' in formats else 'video/x-msvideo' + else: + mime = 'audio/wav' if 'wav' in formats else 'audio/mpeg' if 'mp3' in formats else 'audio/flac' if 'flac' in formats else 'audio/ogg' if 'ogg' in formats else 'audio/aac' if 'aac' in formats else 'audio/mp4' + return {'kind': 'video' if videos else 'audio', 'mime_type': mime, 'has_audio': bool(audios), + 'width': width if videos else None, 'height': height if videos else None, + 'duration_seconds': duration, 'start_seconds': start_time} + except (ValueError, TypeError, KeyError, AttributeError): + raise MediaError('invalid_media', '媒体文件信息无效。') from None + + +async def make_thumbnail(path: Path, destination: Path, settings) -> Path | None: + source, target = confined(path, settings), confined(destination, settings, exists=False) + info = await inspect_media(source, settings) + if info['kind'] not in {'image', 'video'}: + return None + target.parent.mkdir(parents=True, exist_ok=True) + temporary = target.with_name(target.name + '.part-' + uuid.uuid4().hex + '.jpg') + try: + if info['kind'] == 'image': + def convert(): + with Image.open(source) as image: + image = ImageOps.exif_transpose(image).convert('RGB') + image.thumbnail((512, 512)) + image.save(temporary, format='JPEG', quality=85) + await asyncio.to_thread(convert) + else: + await run_process([settings.ffmpeg_bin, '-v', 'error', '-nostdin', *input_options(), + '-i', str(source), '-frames:v', '1', '-vf', 'scale=512:512:force_original_aspect_ratio=decrease', + '-threads', '2', '-f', 'image2', '-update', '1', str(temporary)], timeout=60) + if not temporary.is_file() or temporary.stat().st_size == 0: + raise MediaError('thumbnail_failed', '预览图生成失败。') + os.replace(temporary, target) + return target + finally: + temporary.unlink(missing_ok=True) diff --git a/backend/app/models.py b/backend/app/models.py new file mode 100644 index 0000000..b201f08 --- /dev/null +++ b/backend/app/models.py @@ -0,0 +1,120 @@ +from datetime import datetime, timezone +import uuid +from sqlalchemy import BigInteger, Boolean, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column +from sqlalchemy.dialects.mysql import DATETIME + +# MySQL's plain DATETIME truncates fractions, scrambling FIFO for jobs created +# within one second. Keep the same microsecond precision as SQLite/Python UTC. +Timestamp = DateTime().with_variant(DATETIME(fsp=6), "mysql") + + +def utcnow(): + return datetime.now(timezone.utc).replace(tzinfo=None) + + +def new_id(): + return uuid.uuid4().hex + + +class Base(DeclarativeBase): + pass + + +class User(Base): + __tablename__ = "visual_users" + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + username: Mapped[str] = mapped_column(String(64), unique=True) + display_name: Mapped[str] = mapped_column(String(80)) + password_hash: Mapped[str] = mapped_column(String(512)) + role: Mapped[str] = mapped_column(String(16), default="user") + disabled: Mapped[bool] = mapped_column(Boolean, default=False) + created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) + + +class Session(Base): + __tablename__ = "visual_sessions" + token_hash: Mapped[str] = mapped_column(String(64), primary_key=True) + user_id: Mapped[str] = mapped_column(ForeignKey("visual_users.id"), index=True) + csrf_token: Mapped[str] = mapped_column(String(128)) + expires_at: Mapped[datetime] = mapped_column(Timestamp, index=True) + created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) + + +class Asset(Base): + __tablename__ = "visual_assets" + __table_args__ = (UniqueConstraint("source_job_id", "source_output_index"), + UniqueConstraint("source_upstream_id", "source_output_index")) + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + owner_id: Mapped[str] = mapped_column(ForeignKey("visual_users.id"), index=True) + name: Mapped[str] = mapped_column(String(255)) + storage_key: Mapped[str] = mapped_column(String(512), unique=True) + thumbnail_key: Mapped[str | None] = mapped_column(String(512), nullable=True) + kind: Mapped[str] = mapped_column(String(16)) + mime_type: Mapped[str] = mapped_column(String(128)) + size_bytes: Mapped[int] = mapped_column(BigInteger) + sha256: Mapped[str] = mapped_column(String(64)) + width: Mapped[int | None] = mapped_column(Integer, nullable=True) + height: Mapped[int | None] = mapped_column(Integer, nullable=True) + duration_seconds: Mapped[float | None] = mapped_column(nullable=True) + tags: Mapped[list] = mapped_column(JSON, default=list) + favorite: Mapped[bool] = mapped_column(Boolean, default=False) + origin: Mapped[str] = mapped_column(String(16), default="upload") + ready: Mapped[bool] = mapped_column(Boolean, default=True) + source_job_id: Mapped[str | None] = mapped_column(ForeignKey("visual_jobs.id"), nullable=True, index=True) + source_upstream_id: Mapped[str | None] = mapped_column(String(128), nullable=True) + source_output_index: Mapped[int | None] = mapped_column(Integer, nullable=True) + created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow, index=True) + deleted_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) + + +class Job(Base): + __tablename__ = "visual_jobs" + __table_args__ = (UniqueConstraint("owner_id", "request_key", "batch_index"), + Index("visual_jobs_dispatch", "state", "next_action_at")) + id: Mapped[str] = mapped_column(String(32), primary_key=True, default=new_id) + owner_id: Mapped[str] = mapped_column(ForeignKey("visual_users.id"), index=True) + task_type: Mapped[str] = mapped_column(String(48)) + state: Mapped[str] = mapped_column(String(24)) + phase: Mapped[str] = mapped_column(String(48)) + version: Mapped[int] = mapped_column(Integer, default=1) + input_json: Mapped[dict] = mapped_column(JSON) + parameters: Mapped[dict] = mapped_column(JSON) + request_key: Mapped[str | None] = mapped_column(String(128), nullable=True) + request_hash: Mapped[str] = mapped_column(String(64)) + batch_index: Mapped[int] = mapped_column(Integer, default=0) + upstream_key: Mapped[str] = mapped_column(String(128), unique=True) + upstream_id: Mapped[str | None] = mapped_column(String(128), nullable=True, unique=True) + upstream_payload: Mapped[dict | None] = mapped_column(JSON, nullable=True) + upstream_result: Mapped[dict | None] = mapped_column(JSON, nullable=True) + result_json: Mapped[dict | None] = mapped_column(JSON, nullable=True) + error_json: Mapped[dict | None] = mapped_column(JSON, nullable=True) + cancel_requested: Mapped[bool] = mapped_column(Boolean, default=False) + attempt_count: Mapped[int] = mapped_column(Integer, default=0) + work_attempt: Mapped[int] = mapped_column(Integer, default=0) + preemptions: Mapped[int] = mapped_column(Integer, default=0) + last_preempted_reason: Mapped[str | None] = mapped_column(Text, nullable=True) + sync_warning: Mapped[str | None] = mapped_column(String(512), nullable=True) + sync_failures: Mapped[int] = mapped_column(Integer, default=0) + next_action_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) + created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow, index=True) + scheduled_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) + started_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) + finished_at: Mapped[datetime | None] = mapped_column(Timestamp, nullable=True) + + +class JobAsset(Base): + __tablename__ = "visual_job_assets" + job_id: Mapped[str] = mapped_column(ForeignKey("visual_jobs.id"), primary_key=True) + asset_id: Mapped[str] = mapped_column(ForeignKey("visual_assets.id"), primary_key=True) + + +class Event(Base): + __tablename__ = "visual_job_events" + __table_args__ = (Index("visual_events_owner_cursor", "owner_id", "id"),) + id: Mapped[int] = mapped_column(BigInteger().with_variant(Integer, "sqlite"), primary_key=True, autoincrement=True) + owner_id: Mapped[str] = mapped_column(ForeignKey("visual_users.id")) + job_id: Mapped[str | None] = mapped_column(String(32), nullable=True) + event_type: Mapped[str] = mapped_column(String(48)) + data: Mapped[dict] = mapped_column(JSON) + created_at: Mapped[datetime] = mapped_column(Timestamp, default=utcnow) diff --git a/backend/app/providers.py b/backend/app/providers.py new file mode 100644 index 0000000..1603cdb --- /dev/null +++ b/backend/app/providers.py @@ -0,0 +1,775 @@ +"""Database-independent adapters for deployed GPU jobs, text/vision and CPU media.""" +from __future__ import annotations + +import asyncio +import base64 +from dataclasses import dataclass +from datetime import datetime, timezone +import html +from io import BytesIO +import json +import math +import os +from pathlib import Path +import re +import stat +import time +from urllib.parse import urlsplit +import uuid + +import httpx +from PIL import Image, ImageOps + +from .media import MediaError as ProviderError, confined, input_options, inspect_media, run_process + + +GPU_TASKS = {'image.generate', 'video.generate', 'defect.generate', 'audio.transcribe'} +LANGUAGES = ['zh', 'en', 'ja', 'ko', 'de', 'fr', 'es', 'ru', 'ar', 'pt', 'it', 'auto'] +_UUID = re.compile(r'GPU-[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}\Z') + + +@dataclass +class CpuResult: + outputs: list[Path] + result: dict + metadata: dict + + +def _invalid(message='任务输入或参数无效。'): + return ProviderError('invalid_input', message) + + +def _keys(value, allowed): + if not isinstance(value, dict) or set(value) - set(allowed): + raise _invalid('包含不支持的输入或参数。') + + +def _int(value, low, high, step=1): + if type(value) is not int or not low <= value <= high or value % step: + raise _invalid('整数参数超出范围或步长不正确。') + return value + + +def _float(value, low, high): + if isinstance(value, bool) or not isinstance(value, (float, int)): + raise _invalid('数值参数无效。') + try: + normalized = float(value) + except (ValueError, OverflowError): + raise _invalid('数值参数无效。') from None + if not math.isfinite(normalized) or not low <= normalized <= high: + raise _invalid('数值参数超出范围。') + return normalized + + +def _string(value, maximum=8000, *, required=True): + if not isinstance(value, str) or len(value) > maximum or (required and not value.strip()): + raise _invalid('文字内容为空或超出长度限制。') + return value + + +def _voices(settings): + values = getattr(settings, 'tts_voices', ['zf_xiaobei', 'zm_yunxi']) + if isinstance(values, str): + values = [item.strip() for item in values.split(',') if item.strip()] + return [value for value in values if isinstance(value, str) and re.fullmatch(r'[A-Za-z0-9_-]{1,64}', value)] + + +def capabilities(settings) -> list[dict]: + image_defaults = {'width': 1024, 'height': 1024, 'num_inference_steps': 50, 'seed': 42, 'guidance_scale': 4.0} + image_limits = {'width': {'min': 256, 'max': 2048, 'step': 16}, + 'height': {'min': 256, 'max': 2048, 'step': 16}, + 'num_inference_steps': {'min': 1, 'max': 100}, + 'guidance_scale': {'min': 1, 'max': 20}, 'seed': {'min': 0, 'max': 2**32 - 1}, + 'count': {'min': 1, 'max': 4}, 'max_pixels': 2048 * 2048} + video_defaults = dict(image_defaults, width=1280, height=704, guidance_scale=5.0, + num_frames=121, fps=24, upscale=True, upscale_width=1920, upscale_height=1080, tile_size=128) + video_limits = {**image_limits, 'width': {'min': 256, 'max': 1280, 'step': 32}, + 'height': {'min': 256, 'max': 1280, 'step': 32}, 'max_pixels': 1280 * 704, + 'count': {'min': 1, 'max': 1}, 'num_frames': {'min': 5, 'max': 121, 'step': 4}, + 'fps': {'values': [24]}, 'upscale': {'values': [True, False]}, + 'upscale_width': {'min': 256, 'max': 3840, 'step': 2}, + 'upscale_height': {'min': 256, 'max': 2160, 'step': 2}, 'tile_size': {'min': 64, 'max': 256, 'step': 16}} + configured = bool(getattr(settings, 'inference_base_url', '')) + qwen = bool(getattr(settings, 'qwen_base_url', '') and getattr(settings, 'qwen_model', '')) + speech = bool(getattr(settings, 'tts_base_url', '') and getattr(settings, 'tts_model', '') and _voices(settings)) + def item(task_type, label, model, available, types, defaults, constraints, description): + return dict(task_type=task_type, label=label, model=model, available=available, + input_types=types, defaults=defaults, constraints=constraints, description=description) + return [ + item('image.generate', '图像生成', 'Qwen-Image', configured, ['text'], image_defaults, image_limits, + '文字生成图片;不包含图像编辑或风格 LoRA 管理。'), + item('video.generate', '视频生成', 'Wan2.2-TI2V-5B + Real-ESRGAN', configured, ['text', 'image'], + video_defaults, video_limits, '最多121帧、24fps,约5秒无声视频;可选1080p增强。'), + item('defect.generate', '条件样本生成', 'SDXL + Canny ControlNet', configured, ['text', 'image'], + dict(image_defaults, guidance_scale=7.5, controlnet_conditioning_scale=.8, canny_low=100, canny_high=200), + {**image_limits, 'controlnet_conditioning_scale': {'min': 0, 'max': 2}, + 'canny_low': {'min': 0, 'max': 255}, 'canny_high': {'min': 0, 'max': 255}}, + '参考图片提供边缘结构;输出控制图不是缺陷真值掩膜。'), + item('audio.transcribe', '语音转写', 'Whisper-large-v3-turbo', configured, ['audio', 'video'], + {'language': 'zh', 'max_audio_seconds': 1800}, + {'language': {'values': LANGUAGES}, 'max_audio_seconds': {'min': 1, 'max': 1800}}, + '支持音频和有声视频;时间戳为30秒块边界,不是字词对齐。'), + item('math.solve', '数学推演', getattr(settings, 'qwen_model', ''), qwen, ['text'], + {'max_tokens': 2048, 'enable_thinking': False}, {'max_tokens': {'min': 1, 'max': 4096}}, + '调用现有文本服务给出解答,未集成形式化证明或准确率评测。'), + item('media.structure', '素材理解', getattr(settings, 'qwen_model', ''), qwen, ['image', 'video'], + {'frame_count': 6}, {'frame_count': {'min': 1, 'max': 12}}, + '视频均匀抽帧后理解画面、文字和标签;不承诺镜头切分准确率。'), + item('video.compose', '成片编排', 'FFmpeg CPU', True, ['video', 'audio'], + {'width': 1280, 'height': 720, 'fps': 24}, + {'width': {'min': 256, 'max': 3840, 'step': 2}, 'height': {'min': 256, 'max': 2160, 'step': 2}, + 'fps': {'values': [24, 25, 30, 60]}, 'clips': {'min': 1, 'max': 24}, + 'duration_seconds': {'min': .05, 'max': 1800}}, + '按顺序裁剪拼接片段,支持上传音轨和人工字幕;无热度预测。'), + item('audio.speech', '中文配音', getattr(settings, 'tts_model', '') or '尚未配置', speech, ['text'], + {'voice': (_voices(settings) or [''])[0], 'speed': 1.0}, + {'voice': {'values': _voices(settings)}, 'speed': {'min': .5, 'max': 2}, 'text': {'max': 2000}}, + '仅在配置真实语音服务后可用;输出 WAV,不提供音乐生成。'), + ] + + +def validate_arguments(task_type: str, inputs: dict, parameters: dict, settings=None) -> None: + """Pure submission validation: no HTTP, file decoding, mkdir or model work.""" + p = parameters + if task_type in GPU_TASKS: + allowed = {'audio_asset_id', 'asset_id'} if task_type == 'audio.transcribe' else {'prompt', 'negative_prompt'} + if task_type in {'video.generate', 'defect.generate'}: + allowed.add('image_asset_id') + _keys(inputs, allowed) + defaults = next(item['defaults'] for item in capabilities(settings) if item['task_type'] == task_type) + _keys(p, set(defaults) | ({'negative_prompt'} if task_type != 'audio.transcribe' else set())) + p = {**defaults, **p} + if task_type == 'audio.transcribe': + if not (inputs.get('audio_asset_id') or inputs.get('asset_id')): + raise _invalid('请选择转写素材。') + if inputs.get('audio_asset_id') and inputs.get('asset_id') and inputs['audio_asset_id'] != inputs['asset_id']: + raise _invalid('请仅选择一个转写素材。') + if p['language'] not in LANGUAGES: + raise _invalid('不支持此转写语言。') + _int(p['max_audio_seconds'], 1, 1800) + return + _string(inputs.get('prompt')) + _string(inputs.get('negative_prompt', ''), required=False) + if 'negative_prompt' in p: + _string(p['negative_prompt'], required=False) + video = task_type == 'video.generate' + for key in ('width', 'height'): + _int(p[key], 256, 1280 if video else 2048, 32 if video else 16) + if p['width'] * p['height'] > (1280 * 704 if video else 2048 * 2048): + raise _invalid('画面像素总数超出服务限制。') + _int(p['num_inference_steps'], 1, 100) + _int(p['seed'], 0, 2**32 - 1) + _float(p['guidance_scale'], 1, 20) + if task_type == 'defect.generate': + if not inputs.get('image_asset_id'): + raise _invalid('条件样本任务需要参考图片。') + _float(p['controlnet_conditioning_scale'], 0, 2) + _int(p['canny_low'], 0, 255) + _int(p['canny_high'], 0, 255) + if p['canny_low'] >= p['canny_high']: + raise _invalid('Canny低阈值必须小于高阈值。') + if video: + _int(p['num_frames'], 5, 121) + if p['num_frames'] % 4 != 1 or type(p['fps']) is not int or p['fps'] != 24 or type(p['upscale']) is not bool: + raise _invalid('视频帧数、帧率或增强开关无效。') + _int(p['upscale_width'], 256, 3840, 2) + _int(p['upscale_height'], 256, 2160, 2) + _int(p['tile_size'], 64, 256, 16) + return + if task_type == 'math.solve': + _keys(inputs, {'prompt'}) + _keys(p, {'max_tokens', 'enable_thinking'}) + _string(inputs.get('prompt')) + _int(p.get('max_tokens', 2048), 1, 4096) + if type(p.get('enable_thinking', False)) is not bool: + raise _invalid('思考开关必须为布尔值。') + return + if task_type == 'media.structure': + _keys(inputs, {'asset_id', 'image_asset_id'}) + _keys(p, {'frame_count'}) + if not (inputs.get('asset_id') or inputs.get('image_asset_id')): + raise _invalid('请选择待理解素材。') + if inputs.get('asset_id') and inputs.get('image_asset_id') and inputs['asset_id'] != inputs['image_asset_id']: + raise _invalid('请选择一个待理解素材。') + _int(p.get('frame_count', 6), 1, 12) + return + if task_type == 'audio.speech': + _keys(inputs, {'prompt'}) + _keys(p, {'voice', 'speed'}) + _string(inputs.get('prompt'), 2000) + voices = _voices(settings) + if not voices or p.get('voice', voices[0]) not in voices: + raise _invalid('请选择已配置的中文音色。') + _float(p.get('speed', 1), .5, 2) + return + if task_type == 'video.compose': + _keys(inputs, {'asset_ids', 'audio_asset_id'}) + _keys(p, {'clips', 'audio_asset_id', 'subtitles', 'width', 'height', 'fps'}) + clips = p.get('clips') + if not isinstance(clips, list) or not 1 <= len(clips) <= 24: + raise _invalid('请选择1至24个视频片段。') + for clip in clips: + _keys(clip, {'asset_id', 'start_seconds', 'end_seconds'}) + _string(clip.get('asset_id'), 64) + start = _float(clip.get('start_seconds', 0), 0, 1800) + if clip.get('end_seconds') is not None and _float(clip['end_seconds'], 0, 1800) <= start: + raise _invalid('片段结束时间必须大于开始时间。') + if 'asset_ids' in inputs and inputs['asset_ids'] != [clip['asset_id'] for clip in clips]: + raise _invalid('素材顺序应与编排片段一致。') + if inputs.get('audio_asset_id') and p.get('audio_asset_id') and inputs['audio_asset_id'] != p['audio_asset_id']: + raise _invalid('请只选择一个成片音轨。') + _int(p.get('width', 1280), 256, 3840, 2) + _int(p.get('height', 720), 256, 2160, 2) + if type(p.get('fps', 24)) is not int or p.get('fps', 24) not in {24, 25, 30, 60}: + raise _invalid('不支持此成片帧率。') + cues = p.get('subtitles', []) + if not isinstance(cues, list) or len(cues) > 1000: + raise _invalid('人工字幕数量超出限制。') + for cue in cues: + _keys(cue, {'start', 'end', 'text'}) + start, end = _float(cue.get('start'), 0, 1800), _float(cue.get('end'), 0, 1800) + text = _string(cue.get('text'), 2000) + if end <= start or '\n\n' in text or re.search(r'[\\{}\x00-\x08\x0b-\x1f]', text): + raise _invalid('字幕时间或纯文本内容无效;不支持ASS控制语法。') + return + raise _invalid('不支持此任务类型。') + + +def _read_key(path): + descriptor = None + try: + path = Path(path) + if not path.is_absolute() or path.is_symlink(): + raise ValueError + descriptor = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0)) + info = os.fstat(descriptor) + if not stat.S_ISREG(info.st_mode) or (os.name == 'posix' and info.st_mode & 0o022): + raise ValueError + raw = os.read(descriptor, 4097) + value = raw.decode('utf-8').strip() + if not value or len(raw) > 4096 or '\n' in value or '\r' in value: + raise ValueError + return value + except (OSError, ValueError, UnicodeError): + raise ProviderError('provider_not_configured', '模型服务认证配置不可用。', True) from None + finally: + if descriptor is not None: + os.close(descriptor) + + +def _url(base, suffix): + if not isinstance(base, str) or not base: + raise ProviderError('capability_unavailable', '此能力尚未配置。') + parsed = urlsplit(base) + if parsed.scheme not in {'http', 'https'} or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment: + raise ProviderError('provider_not_configured', '模型服务地址配置无效。', True) + return base.rstrip('/') + suffix + + +class Provider: + def __init__(self, settings): + self.settings = settings + self.client = httpx.AsyncClient(trust_env=False, follow_redirects=False, + timeout=httpx.Timeout(float(settings.request_timeout_seconds)), + limits=httpx.Limits(max_connections=4, max_keepalive_connections=2)) + + async def aclose(self): + await self.client.aclose() + + def _headers(self, family='inference'): + key = getattr(self.settings, family + '_api_key', '') or '' + if family == 'inference' and getattr(self.settings, 'inference_api_key_file', None): + key = _read_key(self.settings.inference_api_key_file) + if not isinstance(key, str) or len(key) > 4096 or any(not 32 <= ord(char) <= 126 for char in key): + raise ProviderError('provider_not_configured', '模型服务认证配置不可用。', True) + return {'Authorization': 'Bearer ' + key} if key else {} + + @staticmethod + def _http_error(status): + if status in {400, 413, 415, 422}: + return ProviderError('upstream_rejected', '模型服务拒绝了任务输入或参数。') + if status == 404: + return ProviderError('upstream_not_found', '模型服务未找到请求的任务或结果。', True) + if status == 409: + return ProviderError('upstream_conflict', '模型任务或幂等请求发生冲突。') + return ProviderError('upstream_unavailable', '模型服务暂时不可用。', True) + + async def _json(self, method, url, *, payload=None, headers=None): + try: + async with asyncio.timeout(float(self.settings.request_timeout_seconds) + 1): + async with self.client.stream(method, url, json=payload, headers=headers) as response: + if not 200 <= response.status_code < 300: + raise self._http_error(response.status_code) + data, size = [], 0 + async for chunk in response.aiter_bytes(): + size += len(chunk) + if size > 2 * 1024 * 1024: + raise ProviderError('invalid_upstream_response', '模型服务响应超出限制。', True) + data.append(chunk) + value = json.loads(b''.join(data)) + if not isinstance(value, dict): + raise ValueError + return value + except (httpx.HTTPError, asyncio.TimeoutError): + raise ProviderError('upstream_unavailable', '模型服务连接失败或响应超时。', True) from None + except (ValueError, UnicodeError, RecursionError): + raise ProviderError('invalid_upstream_response', '模型服务返回了无效响应。', True) from None + + async def health(self): + try: + value = await self._json('GET', _url(self.settings.inference_base_url, '/health'), headers=self._headers()) + return value.get('status') == 'ok' + except ProviderError: + return False + + async def scheduler_status(self): + unavailable = {'available': False, 'state': 'unavailable', 'reason': 'GPU状态暂时不可用。', 'gpus': [], 'updated_at': None} + try: + path = Path(self.settings.gpu_status_path) + if path.stat().st_size > 1024 * 1024: + return unavailable + data = json.loads(path.read_bytes()) + now = time.time() + generated = _float(data['generated_at'], 0, now + 1) + if data['schema_version'] != 1 or data.get('error') is not None or now - generated > 5: + return unavailable + seen, gpus = set(), [] + for gpu in data['gpus']: + index = _int(gpu['index'], 0, 1024) + if index in seen or not isinstance(gpu['uuid'], str) or not _UUID.fullmatch(gpu['uuid']): + return unavailable + seen.add(index) + total = _float(gpu['total_gib'], .001, 100000) + free = _float(gpu['free_gib'], 0, total) + external, own = gpu['external_pids'], gpu['own_pids'] + if not all(isinstance(values, list) and all(type(pid) is int and pid > 0 for pid in values) + for values in (external, own)): + return unavailable + idle = gpu.get('idle_since') + if idle is not None: + idle = _float(idle, 0, now + 1) + busy = bool(external or own) + gpus.append({'index': index, 'name': f'GPU {index}', 'busy': busy, + 'eligible': not busy and free >= 76 and idle is not None and now - idle >= 15, 'free_gib': free}) + state = 'ready' if any(gpu['eligible'] for gpu in gpus) else 'waiting' + reason = None if state == 'ready' else '等待可用GPU,外部任务优先。' + try: + scheduler_path = Path(self.settings.gpu_scheduler_path) + if scheduler_path.stat().st_size <= 1024 * 1024: + scheduler = json.loads(scheduler_path.read_bytes()) + if scheduler.get('state') in {'blocked', 'preempting'}: + state = scheduler['state'] + reason = '正在释放GPU并等待重新排队。' if state == 'preempting' else '执行器需要管理员检查。' + elif scheduler.get('state') == 'leased' and any(gpu['busy'] for gpu in gpus): + state, reason = 'running', '模型任务正在执行。' + except (OSError, ValueError, TypeError, AttributeError): + pass + return {'available': True, 'state': state, 'reason': reason, 'gpus': gpus, + 'updated_at': datetime.fromtimestamp(generated, timezone.utc).isoformat()} + except (OSError, ValueError, TypeError, KeyError, AttributeError, ProviderError, OverflowError): + return unavailable + + def _work(self, path): + work = confined(path, self.settings, exists=False, root=self.settings.job_work_root) + if not work.is_dir(): + raise _invalid('任务工作目录不可用。') + return work + + def _asset(self, asset_id, assets): + if not isinstance(asset_id, str) or asset_id not in assets: + raise _invalid('请选择可访问的素材。') + return confined(assets[asset_id], self.settings) + + async def prepare_gpu_payload(self, task_type, inputs, parameters, assets, work_dir): + validate_arguments(task_type, inputs, parameters, self.settings) + work = self._work(work_dir) + if task_type not in GPU_TASKS: + raise _invalid('不支持此模型任务类型。') + p = dict(parameters) if isinstance(parameters, dict) else parameters + allowed_input = {'audio_asset_id', 'asset_id'} if task_type == 'audio.transcribe' else {'prompt', 'negative_prompt'} + if task_type in {'video.generate', 'defect.generate'}: + allowed_input.add('image_asset_id') + _keys(inputs, allowed_input) + defaults = next(item['defaults'] for item in capabilities(self.settings) if item['task_type'] == task_type) + _keys(p, set(defaults) | ({'negative_prompt'} if task_type != 'audio.transcribe' else set())) + normalized = {**defaults, **p} + out = {} + if task_type == 'audio.transcribe': + asset_id = inputs.get('audio_asset_id') or inputs.get('asset_id') + if inputs.get('audio_asset_id') and inputs.get('asset_id') and inputs['audio_asset_id'] != inputs['asset_id']: + raise _invalid('请仅选择一个转写素材。') + source = self._asset(asset_id, assets) + info = await inspect_media(source, self.settings) + if normalized['language'] not in LANGUAGES: + raise _invalid('不支持此转写语言。') + _int(normalized['max_audio_seconds'], 1, 1800) + if info['kind'] not in {'audio', 'video'} or info['duration_seconds'] > normalized['max_audio_seconds']: + raise _invalid('请选择时长受限的音频或有声视频。') + if info['kind'] == 'video': + target = work / 'asr-input.wav' + temporary = work / ('asr-' + uuid.uuid4().hex + '.wav') + try: + await run_process([self.settings.ffmpeg_bin, '-v', 'error', '-nostdin', *input_options(), + '-i', str(source), '-map', '0:a:0', '-vn', '-ac', '1', '-ar', '16000', + '-c:a', 'pcm_s16le', '-t', str(normalized['max_audio_seconds']), '-threads', '2', str(temporary)], timeout=300) + if not temporary.is_file() or not temporary.stat().st_size: + raise _invalid('视频没有可转写的音轨。') + os.replace(temporary, target) + finally: + temporary.unlink(missing_ok=True) + source = target + out['audio_path'] = str(source) + else: + out['prompt'] = _string(inputs.get('prompt')) + out['negative_prompt'] = _string(normalized.pop('negative_prompt', inputs.get('negative_prompt', '')), required=False) + video = task_type == 'video.generate' + for key in ('width', 'height'): + _int(normalized[key], 256, 1280 if video else 2048, 32 if video else 16) + if normalized['width'] * normalized['height'] > (1280 * 704 if video else 2048 * 2048): + raise _invalid('画面像素总数超出服务限制。') + _int(normalized['num_inference_steps'], 1, 100) + _int(normalized['seed'], 0, 2**32 - 1) + normalized['guidance_scale'] = _float(normalized['guidance_scale'], 1, 20) + if 'image_asset_id' in inputs: + source = self._asset(inputs['image_asset_id'], assets) + if (await inspect_media(source, self.settings))['kind'] != 'image': + raise _invalid('参考素材必须是图片。') + out['image_path'] = str(source) + if task_type == 'defect.generate': + if 'image_path' not in out: + raise _invalid('条件样本任务需要参考图片。') + normalized['controlnet_conditioning_scale'] = _float(normalized['controlnet_conditioning_scale'], 0, 2) + _int(normalized['canny_low'], 0, 255) + _int(normalized['canny_high'], 0, 255) + if normalized['canny_low'] >= normalized['canny_high']: + raise _invalid('Canny低阈值必须小于高阈值。') + if video: + _int(normalized['num_frames'], 5, 121) + if normalized['num_frames'] % 4 != 1 or type(normalized['fps']) is not int or normalized['fps'] != 24: + raise _invalid('视频仅支持4n+1帧、最多121帧和24fps。') + if type(normalized['upscale']) is not bool: + raise _invalid('增强开关必须为布尔值。') + _int(normalized['upscale_width'], 256, 3840, 2) + _int(normalized['upscale_height'], 256, 2160, 2) + _int(normalized['tile_size'], 64, 256, 16) + return {'task_type': task_type, 'input': out, 'parameters': normalized, 'timeout_seconds': 3600} + + async def submit(self, payload, idempotency_key): + _string(idempotency_key, 128) + if any(not 33 <= ord(char) <= 126 for char in idempotency_key): + raise _invalid('幂等请求标识无效。') + return self._sanitize_job(await self._json('POST', _url(self.settings.inference_base_url, '/jobs'), payload=payload, + headers={**self._headers(), 'Idempotency-Key': idempotency_key})) + + @staticmethod + def _job_id(value): + if not isinstance(value, str) or re.fullmatch(r'[0-9a-f]{32}', value) is None: + raise _invalid('模型任务标识无效。') + return value + + @staticmethod + def _sanitize_job(value): + if value.get('error'): + value['error'] = '模型任务执行失败,请检查任务输入或联系管理员。' + if value.get('last_preempted_reason'): + value['last_preempted_reason'] = 'GPU资源已让出,任务重新排队。' + return value + + async def query(self, upstream_id): + return self._sanitize_job(await self._json('GET', _url(self.settings.inference_base_url, + '/jobs/' + self._job_id(upstream_id)), headers=self._headers())) + + async def cancel(self, upstream_id): + return self._sanitize_job(await self._json('POST', _url(self.settings.inference_base_url, + '/jobs/' + self._job_id(upstream_id) + '/cancel'), headers=self._headers())) + + async def _download_url(self, url, destination, headers, *, payload=None): + target = confined(destination, self.settings, exists=False) + target.parent.mkdir(parents=True, exist_ok=True) + temporary = target.with_name(target.name + '.part-' + uuid.uuid4().hex) + try: + async with asyncio.timeout(max(30, min(600, float(self.settings.request_timeout_seconds) * 4))): + async with self.client.stream('POST' if payload is not None else 'GET', url, + headers=headers, json=payload) as response: + if not 200 <= response.status_code < 300: + raise self._http_error(response.status_code) + limit = int(self.settings.max_output_bytes) + declared = response.headers.get('Content-Length') + if declared is not None and (not declared.isdigit() or int(declared) > limit): + raise ProviderError('output_too_large', '输出文件超出大小限制。') + count = 0 + with temporary.open('xb') as stream: + async for chunk in response.aiter_bytes(): + count += len(chunk) + if count > limit: + raise ProviderError('output_too_large', '输出文件超出大小限制。') + stream.write(chunk) + if not count or (declared is not None and count != int(declared)): + raise ProviderError('invalid_upstream_response', '输出文件为空或未传输完整。', True) + os.replace(temporary, target) + except (httpx.HTTPError, asyncio.TimeoutError): + raise ProviderError('upstream_unavailable', '输出文件传输失败,请稍后重试。', True) from None + except OSError: + raise ProviderError('output_unavailable', '无法保存输出文件。', True) from None + finally: + temporary.unlink(missing_ok=True) + + async def download(self, upstream_id, index, destination): + _int(index, 0, 1000) + await self._download_url(_url(self.settings.inference_base_url, + '/jobs/' + self._job_id(upstream_id) + '/outputs/' + str(index)), destination, self._headers()) + + async def _chat(self, messages, *, max_tokens=2048, thinking=False): + if not self.settings.qwen_model: + raise ProviderError('capability_unavailable', '文本与视觉服务尚未配置。') + value = await self._json('POST', _url(self.settings.qwen_base_url, '/chat/completions'), + headers=self._headers('qwen'), payload={'model': self.settings.qwen_model, 'messages': messages, + 'stream': False, 'temperature': 0, 'max_tokens': max_tokens, + 'chat_template_kwargs': {'enable_thinking': thinking}}) + choices = value.get('choices') + if (isinstance(choices, list) and choices and isinstance(choices[0], dict) + and choices[0].get('finish_reason') == 'length'): + raise ProviderError('output_truncated', '模型输出达到长度上限,内容不完整;请提高输出长度或简化要求后重新提交。') + try: + content = value['choices'][0]['message']['content'] + if isinstance(content, list): + content = ''.join(part['text'] for part in content if part.get('type') == 'text') + content = _string(content, 200_000) + inline = re.fullmatch(r'\s*.*?\s*(.*)', content, flags=re.DOTALL) + if inline: + content = inline.group(1).strip() + if not content: + raise ValueError + return content + except (ValueError, TypeError, KeyError, IndexError, AttributeError, ProviderError): + raise ProviderError('invalid_upstream_response', '文本服务没有返回有效内容。', True) from None + + @staticmethod + def _json_file(work, name, value): + target = work / name + temporary = work / (name + '.part-' + uuid.uuid4().hex) + try: + temporary.write_text(json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2), encoding='utf-8') + os.replace(temporary, target) + finally: + temporary.unlink(missing_ok=True) + return target + + async def run_cpu(self, task_type, inputs, parameters, assets, work_dir): + work = self._work(work_dir) + validate_arguments(task_type, inputs, parameters, self.settings) + try: + if task_type == 'math.solve': + _keys(inputs, {'prompt'}) + _keys(parameters, {'max_tokens', 'enable_thinking'}) + tokens = _int(parameters.get('max_tokens', 2048), 1, 4096) + thinking = parameters.get('enable_thinking', False) + if type(thinking) is not bool: + raise _invalid('思考开关必须为布尔值。') + text = await self._chat([{'role': 'system', 'content': '请给出可复核的数学解题步骤和最终答案;不确定时明确说明。'}, + {'role': 'user', 'content': _string(inputs.get('prompt'))}], max_tokens=tokens, thinking=thinking) + answer = work / 'answer.txt' + answer.write_text(text + '\n', encoding='utf-8') + result = {'text': text} + return CpuResult([answer, self._json_file(work, 'answer.json', result)], result, + {'provider': 'qwen', 'model': self.settings.qwen_model, 'formal_verification': False}) + if task_type == 'media.structure': + return await self._structure(inputs, parameters, assets, work) + if task_type == 'video.compose': + return await self._compose(inputs, parameters, assets, work) + if task_type == 'audio.speech': + return await self._speech(inputs, parameters, work) + raise _invalid('不支持此CPU任务类型。') + except OSError: + raise ProviderError('output_unavailable', '任务文件处理失败。', True) from None + + async def _image_uri(self, source): + def encode(): + with Image.open(source) as image: + image = ImageOps.exif_transpose(image).convert('RGB') + image.thumbnail((1280, 1280)) + buffer = BytesIO() + image.save(buffer, format='JPEG', quality=85) + return 'data:image/jpeg;base64,' + base64.b64encode(buffer.getvalue()).decode('ascii') + return await asyncio.to_thread(encode) + + async def _structure(self, inputs, p, assets, work): + _keys(inputs, {'asset_id', 'image_asset_id'}) + _keys(p, {'frame_count'}) + asset_id = inputs.get('asset_id') or inputs.get('image_asset_id') + if inputs.get('asset_id') and inputs.get('image_asset_id') and inputs['asset_id'] != inputs['image_asset_id']: + raise _invalid('请选择一个待理解素材。') + count = _int(p.get('frame_count', 6), 1, 12) + source = self._asset(asset_id, assets) + info = await inspect_media(source, self.settings) + if info['kind'] not in {'image', 'video'}: + raise _invalid('素材理解支持图片或视频。') + samples, outputs = [(0.0, source)], [] + if info['kind'] == 'video': + samples = [] + for index in range(count): + timestamp = (index + .5) * info['duration_seconds'] / count + frame = work / f'frame-{index:03d}.jpg' + # Fixed filters and numeric seek only; never accept a filter from input. + _, diagnostics = await run_process([self.settings.ffmpeg_bin, '-v', 'info', '-nostdin', '-copyts', *input_options(), + '-ss', f'{timestamp:.6f}', '-i', str(source), '-frames:v', '1', '-vf', + 'scale=1280:1280:force_original_aspect_ratio=decrease,showinfo', '-threads', '2', str(frame)], + timeout=90, return_stderr=True) + if not frame.is_file() or not frame.stat().st_size: + raise ProviderError('frame_extraction_failed', '视频抽帧失败。') + actual_pts = re.search(rb'\bpts_time:([+-]?[0-9]+(?:\.[0-9]+)?)', diagnostics) + if actual_pts is None: + raise ProviderError('frame_extraction_failed', '无法确认抽帧的实际时间。') + actual_time = float(actual_pts.group(1)) - info.get('start_seconds', 0) + if not math.isfinite(actual_time) or not -.1 <= actual_time <= info['duration_seconds'] + .1: + raise ProviderError('frame_extraction_failed', '抽帧时间超出素材范围。') + samples.append((max(0, actual_time), frame)) + outputs.append(frame) + frames = [] + prompt = ('仅根据画面可见内容输出JSON对象,不要Markdown。字段 subjects 为字符串数组,scene 为字符串,' + 'ocr 为画面实际可见文字的字符串数组,tags 为字符串数组。看不清请写不确定,不要臆测人物身份。') + for timestamp, frame in samples: + text = await self._chat([{'role': 'user', 'content': [ + {'type': 'image_url', 'image_url': {'url': await self._image_uri(frame)}}, + {'type': 'text', 'text': prompt}]}]) + try: + fenced = re.fullmatch(r'\s*```(?:json)?\s*(.*?)\s*```\s*', text, flags=re.DOTALL | re.IGNORECASE) + value = json.loads(fenced.group(1) if fenced else text) + scene = _string(value['scene'], 2000, required=False) + normalized = {} + for key in ('subjects', 'ocr', 'tags'): + items = value.get(key, []) if key == 'tags' else value[key] + if not isinstance(items, list) or len(items) > 100: + raise ValueError + normalized[key] = list(dict.fromkeys(_string(item, 2000, required=False) for item in items)) + frames.append({'timestamp_seconds': round(timestamp, 6), 'scene': scene, **normalized}) + except (ValueError, KeyError, TypeError, AttributeError, ProviderError): + raise ProviderError('invalid_visual_response', '视觉服务未返回有效的结构化内容。', True) from None + result = {'subjects': list(dict.fromkeys(item for frame in frames for item in frame['subjects'])), + 'scene': ';'.join(dict.fromkeys(frame['scene'] for frame in frames)), + 'ocr': list(dict.fromkeys(item for frame in frames for item in frame['ocr'])), + 'tags': list(dict.fromkeys(item for frame in frames for item in frame['tags'])), 'frames': frames} + outputs.append(self._json_file(work, 'structure.json', result)) + return CpuResult(outputs, result, {'provider': 'qwen', 'model': self.settings.qwen_model, + 'sampling': 'uniform seek' if info['kind'] == 'video' else 'single image', + 'timestamp_precision': 'decoded frame PTS relative to source start', 'frame_count': len(frames)}) + + async def _speech(self, inputs, p, work): + if not self.settings.tts_base_url or not self.settings.tts_model or not _voices(self.settings): + raise ProviderError('capability_unavailable', '中文配音服务尚未配置。') + _keys(inputs, {'prompt'}) + _keys(p, {'voice', 'speed'}) + text = _string(inputs.get('prompt'), 2000) + voice = p.get('voice', _voices(self.settings)[0]) + if voice not in _voices(self.settings): + raise _invalid('请选择已配置的中文音色。') + speed = _float(p.get('speed', 1.0), .5, 2) + target = work / 'speech.wav' + await self._download_url(_url(self.settings.tts_base_url, '/audio/speech'), target, self._headers('tts'), + payload={'model': self.settings.tts_model, 'input': text, 'voice': voice, 'speed': speed, 'response_format': 'wav'}) + info = await inspect_media(target, self.settings) + if info['kind'] != 'audio' or info['mime_type'] != 'audio/wav': + target.unlink(missing_ok=True) + raise ProviderError('invalid_speech_response', '配音服务未返回有效的 WAV 音频。', True) + return CpuResult([target], {'text': text, 'voice': voice, 'duration_seconds': info['duration_seconds']}, + {'provider': 'openai-compatible-tts', 'model': self.settings.tts_model, 'speed': speed}) + + async def _compose(self, inputs, p, assets, work): + _keys(inputs, {'asset_ids', 'audio_asset_id'}) + _keys(p, {'clips', 'audio_asset_id', 'subtitles', 'width', 'height', 'fps'}) + clips = p.get('clips') + if not isinstance(clips, list) or not 1 <= len(clips) <= 24: + raise _invalid('请选择1至24个视频片段。') + width, height, fps = p.get('width', 1280), p.get('height', 720), p.get('fps', 24) + _int(width, 256, 3840, 2) + _int(height, 256, 2160, 2) + if type(fps) is not int or fps not in {24, 25, 30, 60}: + raise _invalid('不支持此成片帧率。') + normalized = [] + for clip in clips: + _keys(clip, {'asset_id', 'start_seconds', 'end_seconds'}) + start = _float(clip.get('start_seconds', 0), 0, 1800) + end = clip.get('end_seconds') + if end is not None and _float(end, 0, 1800) <= start: + raise _invalid('片段结束时间必须大于开始时间。') + normalized.append((self._asset(clip.get('asset_id'), assets), start, end)) + if 'asset_ids' in inputs and inputs['asset_ids'] != [clip['asset_id'] for clip in clips]: + raise _invalid('素材顺序应与编排片段一致。') + a, b = inputs.get('audio_asset_id'), p.get('audio_asset_id') + if a and b and a != b: + raise _invalid('请只选择一个成片音轨。') + audio = self._asset(a or b, assets) if a or b else None + subtitles = p.get('subtitles', []) + if not isinstance(subtitles, list) or len(subtitles) > 1000: + raise _invalid('人工字幕数量超出限制。') + cues = [] + for cue in subtitles: + _keys(cue, {'start', 'end', 'text'}) + start, end = _float(cue.get('start'), 0, 1800), _float(cue.get('end'), 0, 1800) + text = _string(cue.get('text'), 2000) + if end <= start or '\n\n' in text or re.search(r'[\\{}\x00-\x08\x0b-\x1f]', text): + raise _invalid('字幕时间或纯文本内容无效;不支持ASS控制语法。') + cues.append((start, end, html.escape(text, quote=False))) + parts, total = [], 0.0 + for source, start, end in normalized: + info = await inspect_media(source, self.settings) + if info['kind'] != 'video': + raise _invalid('编排片段必须是视频素材。') + end = info['duration_seconds'] if end is None else end + if start >= end or end > info['duration_seconds'] + .05 or end - start < .05: + raise _invalid('裁剪范围超出视频实际时长。') + total += end - start + if total > 1800: + raise _invalid('成片总时长不能超过30分钟。') + parts.append((source, start, end - start, info.get('has_audio', False))) + if any(end > total + .05 for _, end, _ in cues): + raise _invalid('字幕超出成片时长。') + if audio and (await inspect_media(audio, self.settings))['kind'] != 'audio': + raise _invalid('成片音轨必须为音频素材。') + files = [] + async with asyncio.timeout(900): + for index, (source, start, duration, has_audio) in enumerate(parts): + target = work / f'clip-{index:03d}.mp4' + command = [self.settings.ffmpeg_bin, '-v', 'error', '-nostdin', *input_options(), '-i', str(source)] + if not has_audio: + command += ['-f', 'lavfi', '-i', 'anullsrc=channel_layout=stereo:sample_rate=48000'] + command += ['-ss', f'{start:.6f}', '-t', f'{duration:.6f}', '-map', '0:v:0', '-map', + '0:a:0' if has_audio else '1:a:0', '-vf', + f'scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps={fps}', + '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20', '-pix_fmt', 'yuv420p', + '-c:a', 'aac', '-ar', '48000', '-ac', '2', '-threads', '2', '-fs', str(self.settings.max_output_bytes), str(target)] + await run_process(command, timeout=min(600, max(60, duration * 5))) + files.append(target) + if sum(path.stat().st_size for path in files) >= self.settings.max_output_bytes: + raise ProviderError('output_too_large', '成片中间文件超出大小限制。') + listing = work / 'concat.txt' + listing.write_text(''.join(f"file '{path.name}'\n" for path in files), encoding='utf-8') + if cues: + def stamp(value): + milliseconds = round(value * 1000) + hours, milliseconds = divmod(milliseconds, 3600000) + minutes, milliseconds = divmod(milliseconds, 60000) + seconds, milliseconds = divmod(milliseconds, 1000) + return f'{hours:02}:{minutes:02}:{seconds:02},{milliseconds:03}' + (work / 'subtitles.srt').write_text(''.join(f'{index}\n{stamp(start)} --> {stamp(end)}\n{text}\n\n' + for index, (start, end, text) in enumerate(cues, 1)), encoding='utf-8') + target = work / 'composition.mp4' + command = [self.settings.ffmpeg_bin, '-v', 'error', '-nostdin', '-f', 'concat', '-safe', '1', '-i', listing.name] + if audio: + command += [*input_options(), '-i', str(audio)] + command += ['-map', '0:v:0', '-map', '1:a:0' if audio else '0:a:0'] + if cues: + command += ['-vf', 'subtitles=filename=subtitles.srt', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20', '-pix_fmt', 'yuv420p'] + else: + command += ['-c:v', 'copy'] + command += ['-af', 'apad', '-t', f'{total:.6f}', '-c:a', 'aac', '-threads', '2', + '-movflags', '+faststart', '-fs', str(self.settings.max_output_bytes), str(target)] + await run_process(command, timeout=min(600, max(60, total * 5)), cwd=work) + info = await inspect_media(target, self.settings) + if abs(info['duration_seconds'] - total) > max(.2, 2 / fps) or target.stat().st_size >= self.settings.max_output_bytes: + raise ProviderError('composition_incomplete', '成片未完整输出或超出大小限制。') + result = {'duration_seconds': info['duration_seconds'], 'width': width, 'height': height, + 'fps': fps, 'clip_count': len(parts), 'subtitle_count': len(cues)} + manifest = self._json_file(work, 'composition.json', result) + return CpuResult([target, manifest], result, {'provider': 'ffmpeg-cpu', 'audio': 'uploaded' if audio else 'original-or-silence'}) diff --git a/backend/pyproject.toml b/backend/pyproject.toml new file mode 100644 index 0000000..5009c36 --- /dev/null +++ b/backend/pyproject.toml @@ -0,0 +1,10 @@ +[project] +name = "cmvr-visual-backend" +version = "0.1.0" +requires-python = ">=3.11" + +[tool.pytest.ini_options] +asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" +testpaths = ["tests"] +filterwarnings = ["error::ResourceWarning"] diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000..30438e2 --- /dev/null +++ b/backend/requirements.txt @@ -0,0 +1,12 @@ +fastapi>=0.115,<1 +uvicorn[standard]>=0.30,<1 +SQLAlchemy[asyncio]>=2.0,<3 +aiomysql>=0.2,<1 +aiosqlite>=0.20,<1 +cryptography>=43 +python-multipart>=0.0.18 +httpx>=0.27,<1 +filelock>=3.16,<5 +Pillow>=10.4 +pytest>=8,<10 +pytest-asyncio>=0.24,<2 diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py new file mode 100644 index 0000000..66b7ec2 --- /dev/null +++ b/backend/tests/conftest.py @@ -0,0 +1,125 @@ +import asyncio +import io +from pathlib import Path +from types import SimpleNamespace + +import httpx +from PIL import Image +import pytest +import pytest_asyncio + + +PASSWORD = "Sufficient-Password-194!" + + +class BoundaryError(Exception): + def __init__(self, message="network interrupted", retriable=True): + self.code, self.message, self.retriable = "upstream_unavailable", message, retriable + super().__init__(message) + + +class FakeProvider: + """External-service boundary only. DB, events, HTTP/auth and files are real.""" + def __init__(self): + self.remote = {} + self.accepted = {} + self.lost_response = False + self.fail_download_once = False + self.fail_download_at = None + self.submitted_payloads = [] + self.download_count = 0 + self.cpu_wait = False + self.cpu_runs = 0 + self.reject_submission = False + + async def health(self): + return True + + async def scheduler_status(self): + return {"available": True, "state": "ready", "reason": None, "gpus": [], "updated_at": None} + + async def prepare_gpu_payload(self, task_type, inputs, parameters, assets, work_dir): + resolved = dict(inputs) + for source, target in (("image_asset_id", "image_path"), ("audio_asset_id", "audio_path"), + ("asset_id", "audio_path")): + if source in resolved: + resolved[target] = str(assets[resolved.pop(source)]) + return {"task_type": task_type, "input": resolved, "parameters": parameters, "timeout_seconds": 3600} + + async def submit(self, payload, idempotency_key): + self.submitted_payloads.append((idempotency_key, payload)) + if self.reject_submission: + error = BoundaryError("unsupported upstream input", retriable=False) + error.code = "upstream_rejected" + raise error + if idempotency_key not in self.accepted: + remote_id = f"remote-{len(self.accepted) + 1}" + self.accepted[idempotency_key] = remote_id + self.remote[remote_id] = {"id": remote_id, "state": "queued", "attempt_count": 0, "preemptions": 0} + remote_id = self.accepted[idempotency_key] + if self.lost_response: + self.lost_response = False + raise BoundaryError() + return dict(self.remote[remote_id]) + + async def query(self, upstream_id): + return dict(self.remote[upstream_id]) + + async def cancel(self, upstream_id): + self.remote[upstream_id].update(state="cancelled") + return dict(self.remote[upstream_id]) + + async def download(self, upstream_id, index, destination): + self.download_count += 1 + if self.fail_download_once or self.fail_download_at == index: + self.fail_download_once = False + self.fail_download_at = None + raise BoundaryError("download interrupted") + destination.parent.mkdir(parents=True, exist_ok=True) + Image.new("RGB", (12, 10), "blue").save(destination, format="PNG") + + async def run_cpu(self, task_type, inputs, parameters, assets, work_dir): + self.cpu_runs += 1 + if self.cpu_wait: + await asyncio.sleep(60) + work_dir.mkdir(parents=True, exist_ok=True) + output = work_dir / "answer.txt" + output.write_text("The answer is 5", encoding="utf-8") + return SimpleNamespace(outputs=[output], result={"text": "The answer is 5"}, metadata={}) + + async def aclose(self): + pass + + +@pytest.fixture +def png_bytes(): + data = io.BytesIO() + Image.new("RGB", (16, 12), "red").save(data, format="PNG") + return data.getvalue() + + +@pytest_asyncio.fixture +async def system(tmp_path): + from app.config import Settings + from app.main import create_app + settings = Settings(mode="test", database_url=f"sqlite+aiosqlite:///{tmp_path / 'test.sqlite3'}", + workspace_root=tmp_path, admin_username="admin", admin_password=PASSWORD, + run_coordinator=False, cookie_secure=False, event_heartbeat_seconds=.03) + provider = FakeProvider() + app = create_app(settings, provider=provider) + async with app.router.lifespan_context(app): + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client: + response = await client.post("/api/auth/login", json={"username": "admin", "password": PASSWORD}) + assert response.status_code == 200, response.text + client.headers["X-CSRF-Token"] = response.json()["csrf_token"] + yield SimpleNamespace(app=app, client=client, settings=settings, provider=provider) + + +@pytest_asyncio.fixture +async def other_client(system): + response = await system.client.post("/api/auth/users", json={"username": "alice", "display_name": "Alice", "password": PASSWORD}) + assert response.status_code == 201, response.text + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=system.app), base_url="http://test") as client: + login = await client.post("/api/auth/login", json={"username": "alice", "password": PASSWORD}) + client.headers["X-CSRF-Token"] = login.json()["csrf_token"] + yield client diff --git a/backend/tests/test_assets.py b/backend/tests/test_assets.py new file mode 100644 index 0000000..f0c693b --- /dev/null +++ b/backend/tests/test_assets.py @@ -0,0 +1,60 @@ +from pathlib import Path + + +async def test_assets_are_owned_range_enabled_and_deleted_inputs_are_retained(system, other_client, png_bytes): + uploaded = await system.client.post("/api/assets", files={"file": ("../reference.png", png_bytes, "image/png")}) + assert uploaded.status_code == 201, uploaded.text + asset = uploaded.json() + assert asset["kind"] == "image" and asset["width"] == 16 + assert not any(key.endswith("path") for key in asset) + for suffix in ("", "/content", "/thumbnail"): + assert (await other_client.get(f"/api/assets/{asset['id']}{suffix}")).status_code == 404 + content = await system.client.get(asset["preview_url"], headers={"Range": "bytes=0-7"}) + assert content.status_code == 206 and content.content == png_bytes[:8] + assert content.headers["content-range"] == f"bytes 0-7/{len(png_bytes)}" + patched = await system.client.patch(f"/api/assets/{asset['id']}", json={"tags": ["product"], "favorite": True}) + assert patched.json()["favorite"] and patched.json()["tags"] == ["product"] + response = await system.client.post("/api/jobs", json={"task_type": "video.generate", + "input": {"prompt": "rotate", "image_asset_id": asset["id"]}, "parameters": {}}) + assert response.status_code == 202, response.text + files_before = list(system.settings.asset_root.rglob("original*")) + assert (await system.client.delete(f"/api/assets/{asset['id']}")).status_code == 204 + assert all(path.exists() for path in files_before) + assert (await system.client.get(f"/api/assets/{asset['id']}/content")).status_code == 404 + await system.app.state.coordinator.run_once(force=True) + assert len(system.provider.accepted) == 1 + + +async def test_foreign_asset_cannot_be_used_to_create_job(system, other_client, png_bytes): + asset = (await system.client.post("/api/assets", files={"file": ("image.png", png_bytes, "image/png")})).json() + response = await other_client.post("/api/jobs", json={"task_type": "defect.generate", + "input": {"prompt": "scratch", "image_asset_id": asset["id"]}, "parameters": {}}) + assert response.status_code == 404 + + +async def test_generated_asset_changes_update_source_job_version_and_sse_snapshot(system): + from app.events import event_batch + job = (await system.client.post("/api/jobs", json={"task_type": "image.generate", + "input": {"prompt": "cup"}, "parameters": {}})).json()["jobs"][0] + coordinator = system.app.state.coordinator + await coordinator.run_once(force=True) + system.provider.remote["remote-1"].update(state="succeeded", result={"outputs": [{"path": "image.png"}]}) + await coordinator.run_once(force=True) + old = (await system.client.get(f"/api/jobs/{job['id']}")).json() + asset_id = old["result_assets"][0]["id"] + cursor = (await system.client.get("/api/jobs")).json()["cursor"] + await system.client.patch(f"/api/assets/{asset_id}", json={"name": "renamed.png", "favorite": True}) + renamed = (await system.client.get(f"/api/jobs/{job['id']}")).json() + assert renamed["version"] > old["version"] + assert renamed["result_assets"][0]["name"] == "renamed.png" + owner_id = (await system.client.get("/api/auth/me")).json()["user"]["id"] + events = await event_batch(system.app.state.db, owner_id, cursor) + snapshots = [event["data"]["job"] for event in events if event["event"] == "job.updated"] + assert snapshots and snapshots[-1]["version"] == renamed["version"] + cursor = events[-1]["id"] + await system.client.delete(f"/api/assets/{asset_id}") + deleted = (await system.client.get(f"/api/jobs/{job['id']}")).json() + assert deleted["version"] > renamed["version"] and deleted["result_assets"] == [] + events = await event_batch(system.app.state.db, owner_id, cursor) + snapshots = [event["data"]["job"] for event in events if event["event"] == "job.updated"] + assert snapshots and snapshots[-1]["result_assets"] == [] diff --git a/backend/tests/test_auth.py b/backend/tests/test_auth.py new file mode 100644 index 0000000..baba064 --- /dev/null +++ b/backend/tests/test_auth.py @@ -0,0 +1,55 @@ +import httpx +from conftest import PASSWORD + + +async def test_login_cookie_csrf_and_revocation(system): + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=system.app), base_url="http://test") as client: + assert (await client.get("/api/auth/me")).status_code == 401 + denied = await client.post("/api/auth/login", json={"username": "admin", "password": "wrong"}) + assert denied.status_code == 401 + login = await client.post("/api/auth/login", json={"username": "admin", "password": PASSWORD}) + assert login.status_code == 200 and "HttpOnly" in login.headers["set-cookie"] + assert (await client.post("/api/auth/logout")).status_code == 403 + assert (await client.post("/api/auth/logout", headers={"X-CSRF-Token": b"\xc3\xa9"})).status_code == 403 + csrf = login.json()["csrf_token"] + assert (await client.get("/api/auth/me")).json()["csrf_token"] == csrf + cookie = client.cookies.get("cmvr_session") + assert (await client.post("/api/auth/logout", headers={"X-CSRF-Token": csrf})).status_code == 204 + client.cookies.set("cmvr_session", cookie) + assert (await client.get("/api/auth/me")).status_code == 401 + + +async def test_non_admin_cannot_create_users_and_public_registration_is_absent(other_client): + assert (await other_client.post("/api/auth/users", json={"username": "bob", "password": PASSWORD})).status_code == 403 + assert (await other_client.post("/api/auth/register", json={})).status_code == 404 + + +async def test_requested_initial_admin_password_is_hashed_and_not_reset_on_restart(tmp_path): + from sqlalchemy import select + from app.auth import verify_password + from app.config import Settings + from app.main import create_app + from app.models import User + from conftest import FakeProvider + + settings = Settings(mode="test", database_url=f"sqlite+aiosqlite:///{tmp_path / 'admin.sqlite3'}", + workspace_root=tmp_path, admin_username="admin", admin_password="123456", + run_coordinator=False, cookie_secure=False) + app = create_app(settings, provider=FakeProvider()) + async with app.router.lifespan_context(app): + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client: + login = await client.post("/api/auth/login", json={"username": "admin", "password": "123456"}) + assert login.status_code == 200 and login.json()["user"]["role"] == "admin" + async with app.state.db.session() as session: + user = await session.scalar(select(User).where(User.username == "admin")) + assert user.password_hash != "123456" and verify_password("123456", user.password_hash) + client.headers["X-CSRF-Token"] = login.json()["csrf_token"] + denied = await client.post("/api/auth/users", json={"username": "ordinary", "password": "123456"}) + assert denied.status_code == 422 # Ordinary accounts retain their stronger password policy. + + settings.admin_password = PASSWORD + restarted = create_app(settings, provider=FakeProvider()) + async with restarted.router.lifespan_context(restarted): + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=restarted), base_url="http://test") as client: + assert (await client.post("/api/auth/login", json={"username": "admin", "password": "123456"})).status_code == 200 + assert (await client.post("/api/auth/login", json={"username": "admin", "password": PASSWORD})).status_code == 401 diff --git a/backend/tests/test_core.py b/backend/tests/test_core.py new file mode 100644 index 0000000..250dee5 --- /dev/null +++ b/backend/tests/test_core.py @@ -0,0 +1,44 @@ +import pytest + + +def test_production_never_silently_uses_sqlite(tmp_path): + from app.config import Settings + with pytest.raises(ValueError): + Settings(mode="production", database_url="sqlite+aiosqlite:///:memory:", workspace_root=tmp_path) + + +def test_mysql_url_preserves_hyphen_database_and_password_special_characters(tmp_path): + from app.config import Settings + settings = Settings(mode="production", mysql_user="visual", mysql_password="p@ss:/?#&", + workspace_root=tmp_path) + assert settings.sqlalchemy_url.database == "cmvr-visual" + assert settings.sqlalchemy_url.password == "p@ss:/?#&" + assert settings.sqlalchemy_url.drivername == "mysql+aiomysql" + + +async def test_application_creates_only_prefixed_tables(system): + from sqlalchemy import inspect + async with system.app.state.db.engine.connect() as connection: + names = await connection.run_sync(lambda sync: inspect(sync).get_table_names()) + assert names and all(name.startswith("visual_") for name in names) + + +async def test_status_discloses_preview_mode_without_connection_details(system): + response = await system.client.get("/api/system/status") + assert response.status_code == 200 + status = response.json() + assert status["environment"] == "test" and status["database_backend"] == "sqlite" + assert "database_url" not in response.text and "password" not in response.text + + +async def test_only_one_coordinator_can_hold_the_workspace_lock(system): + from app.coordinator import Coordinator + from filelock import Timeout + first = Coordinator(system.settings, system.app.state.db, system.provider) + second = Coordinator(system.settings, system.app.state.db, system.provider) + try: + await first.start() + with pytest.raises(Timeout): + await second.start() + finally: + await first.close() diff --git a/backend/tests/test_events.py b/backend/tests/test_events.py new file mode 100644 index 0000000..7f32336 --- /dev/null +++ b/backend/tests/test_events.py @@ -0,0 +1,64 @@ +from sqlalchemy import select +from types import SimpleNamespace +import asyncio + + +async def test_empty_stream_immediately_sends_connection_comment(system): + from app.events import event_stream + system.settings.event_heartbeat_seconds = 15 + owner = (await system.client.get("/api/auth/me")).json()["user"]["id"] + async def connected(): + return False + request = SimpleNamespace(app=system.app, is_disconnected=connected) + stream = event_stream(request, owner, system.client.cookies.get("cmvr_session"), 0) + try: + assert await asyncio.wait_for(anext(stream), timeout=.1) == ": connected\n\n" + finally: + await stream.aclose() + + +async def test_durable_events_owner_replay_and_session_revocation(system, other_client): + from app.events import event_batch, session_is_active + job = (await system.client.post("/api/jobs", json={"task_type": "image.generate", + "input": {"prompt": "cup"}, "parameters": {}})).json()["jobs"][0] + actor = (await system.client.get("/api/auth/me")).json()["user"] + other = (await other_client.get("/api/auth/me")).json()["user"] + events = await event_batch(system.app.state.db, actor["id"], 0) + assert events and events[-1]["data"]["job"]["id"] == job["id"] + assert await event_batch(system.app.state.db, other["id"], 0) == [] + assert await event_batch(system.app.state.db, actor["id"], events[-1]["id"]) == [] + token = system.client.cookies.get("cmvr_session") + assert await session_is_active(system.app.state.db, token) + assert (await system.client.post("/api/auth/logout")).status_code == 204 + assert not await session_is_active(system.app.state.db, token) + + +async def test_real_stream_replays_ids_heartbeats_then_stops_after_logout(system): + from app.events import event_stream + await system.client.post("/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "cup"}, "parameters": {}}) + owner = (await system.client.get("/api/auth/me")).json()["user"]["id"] + async def connected(): + return False + request = SimpleNamespace(app=system.app, is_disconnected=connected) + stream = event_stream(request, owner, system.client.cookies.get("cmvr_session"), 0) + assert await anext(stream) == ": connected\n\n" + event = await anext(stream) + assert "event: job.updated" in event and "id: " in event + heartbeat = await asyncio.wait_for(anext(stream), timeout=1) + assert heartbeat == ": heartbeat\n\n" + await system.client.post("/api/auth/logout") + try: + await anext(stream) + assert False, "revoked sessions must stop SSE" + except StopAsyncIteration: + pass + + +async def test_http_eventsource_last_event_id_overrides_initial_query(system, monkeypatch): + import app.events as events + async def one_event(request, owner_id, token, after): + yield f"id: {after}\nevent: reset\ndata: {{}}\n\n" + monkeypatch.setattr(events, "event_stream", one_event) + response = await system.client.get("/api/events?after=2", headers={"Last-Event-ID": "19"}) + assert response.status_code == 200 and response.text.startswith("id: 19\n") + assert response.headers["x-accel-buffering"] == "no" diff --git a/backend/tests/test_jobs.py b/backend/tests/test_jobs.py new file mode 100644 index 0000000..15b20b3 --- /dev/null +++ b/backend/tests/test_jobs.py @@ -0,0 +1,254 @@ +import json +import asyncio +from datetime import datetime, timedelta, timezone +from sqlalchemy import select + + +async def submit(system, **changes): + body = {"task_type": "image.generate", "input": {"prompt": "a blue cup"}, "parameters": {}} + body.update(changes) + response = await system.client.post("/api/jobs", json=body) + assert response.status_code == 202, response.text + return response.json()["jobs"] + + +async def test_batch_idempotency_and_scheduled_jobs_do_not_dispatch_early(system): + future = (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat() + body = {"task_type": "image.generate", "input": {"prompt": "cup"}, "parameters": {}, "count": 3, "scheduled_at": future} + first = await system.client.post("/api/jobs", json=body, headers={"Idempotency-Key": "batch-one"}) + second = await system.client.post("/api/jobs", json=body, headers={"Idempotency-Key": "batch-one"}) + assert first.status_code == 202 and second.json() == first.json() + assert len(first.json()["jobs"]) == 3 + assert [job["parameters"]["seed"] for job in first.json()["jobs"]] == [42, 43, 44] + assert {job["state"] for job in first.json()["jobs"]} == {"scheduled"} + body["input"]["prompt"] = "changed" + assert (await system.client.post("/api/jobs", json=body, headers={"Idempotency-Key": "batch-one"})).status_code == 409 + await system.app.state.coordinator.run_once(force=True) + assert not system.provider.accepted + + +async def test_lost_submit_response_recovers_same_id_and_known_id_never_resubmits(system): + job = (await submit(system))[0] + system.provider.lost_response = True + await system.app.state.coordinator.run_once(force=True) + await system.app.state.coordinator.run_once(force=True) + current = (await system.client.get(f"/api/jobs/{job['id']}")).json() + assert current["upstream_id"] == "remote-1" and len(system.provider.accepted) == 1 + assert system.provider.submitted_payloads[0] == system.provider.submitted_payloads[1] + submitted = len(system.provider.submitted_payloads) + system.provider.remote["remote-1"].update(state="running", attempt_count=1) + await system.app.state.coordinator.run_once(force=True) + running = (await system.client.get(f"/api/jobs/{job['id']}")).json() + system.provider.remote["remote-1"].update(state="queued", attempt_count=1, preemptions=1, + last_preempted_reason="External user arrived") + await system.app.state.coordinator.run_once(force=True) + queued = (await system.client.get(f"/api/jobs/{job['id']}")).json() + assert queued["state"] == "queued" and queued["version"] > running["version"] + assert queued["preemptions"] == 1 and queued["upstream_id"] == "remote-1" + assert len(system.provider.submitted_payloads) == submitted + + +async def test_output_import_retry_does_not_generate_again_or_duplicate_assets(system): + job = (await submit(system))[0] + await system.app.state.coordinator.run_once(force=True) + system.provider.remote["remote-1"].update(state="succeeded", attempt_count=1, + result={"outputs": [{"path": "/workspace/private/should-not-leak.png"}], "metadata": {"engine": "real"}}) + system.provider.fail_download_once = True + await system.app.state.coordinator.run_once(force=True) + collecting = (await system.client.get(f"/api/jobs/{job['id']}")).json() + assert collecting["state"] == "collecting" + await system.app.state.coordinator.run_once(force=True) + completed = (await system.client.get(f"/api/jobs/{job['id']}")).json() + assert completed["state"] == "succeeded" and len(completed["result_assets"]) == 1 + assert "/workspace/" not in json.dumps(completed) + await system.app.state.coordinator.run_once(force=True) + assets = (await system.client.get("/api/assets")).json() + assert assets["total"] == 1 and len(system.provider.accepted) == 1 + + +async def test_partial_outputs_remain_private_until_every_output_is_imported(system): + job = (await submit(system))[0] + await system.app.state.coordinator.run_once(force=True) + system.provider.remote["remote-1"].update(state="succeeded", result={"outputs": [{"path": "one.png"}, {"path": "two.png"}]}) + system.provider.fail_download_at = 1 + await system.app.state.coordinator.run_once(force=True) + assert (await system.client.get(f"/api/jobs/{job['id']}")).json()["state"] == "collecting" + assert (await system.client.get("/api/assets")).json()["total"] == 0 + await system.app.state.coordinator.run_once(force=True) + completed = (await system.client.get(f"/api/jobs/{job['id']}")).json() + assert completed["state"] == "succeeded" and len(completed["result_assets"]) == 2 + assert (await system.client.get("/api/assets")).json()["total"] == 2 + + +async def test_owner_isolation_cancel_and_explicit_retry(system, other_client): + job = (await submit(system))[0] + for method, path in (("get", f"/api/jobs/{job['id']}"), ("post", f"/api/jobs/{job['id']}/cancel"), + ("post", f"/api/jobs/{job['id']}/retry")): + assert (await getattr(other_client, method)(path)).status_code == 404 + cancelled = await system.client.post(f"/api/jobs/{job['id']}/cancel") + assert cancelled.json()["state"] == "cancelled" + retried = await system.client.post(f"/api/jobs/{job['id']}/retry") + assert retried.status_code == 202 and retried.json()["jobs"][0]["id"] != job["id"] + + +async def test_unsupported_parameters_are_rejected_before_job_creation(system): + response = await system.client.post("/api/jobs", json={"task_type": "image.generate", + "input": {"prompt": "cup"}, "parameters": {"steps": 1}}) + assert response.status_code == 400 + assert (await system.client.get("/api/jobs")).json()["total"] == 0 + + +async def test_definitive_upstream_input_rejection_is_terminal_not_retried_forever(system): + job = (await submit(system))[0] + system.provider.reject_submission = True + await system.app.state.coordinator.run_once(force=True) + current = (await system.client.get(f"/api/jobs/{job['id']}")).json() + assert current["state"] == "failed" and current["error"]["code"] == "upstream_rejected" + count = len(system.provider.submitted_payloads) + await system.app.state.coordinator.run_once(force=True) + assert len(system.provider.submitted_payloads) == count + + +async def test_coordinator_restart_recovers_id_and_cancel_unknown_submit(system): + from app.coordinator import Coordinator + job = (await submit(system))[0] + system.provider.lost_response = True + await system.app.state.coordinator.run_once(force=True) + cancelled = await system.client.post(f"/api/jobs/{job['id']}/cancel") + assert cancelled.json()["state"] == "cancelling" + restarted = Coordinator(system.settings, system.app.state.db, system.provider) + await restarted.run_once(force=True) + await restarted.run_once(force=True) + current = (await system.client.get(f"/api/jobs/{job['id']}")).json() + assert current["state"] == "cancelled" and current["upstream_id"] == "remote-1" + assert len(system.provider.accepted) == 1 + + +async def test_cpu_provider_results_are_real_assets_and_cancelled_stale_job_never_runs(system): + job = (await submit(system, task_type="math.solve", input={"prompt": "2+3?"}))[0] + coordinator = system.app.state.coordinator + await coordinator.run_once(force=True) + await asyncio.gather(*list(coordinator._cpu.values())) + completed = (await system.client.get(f"/api/jobs/{job['id']}")).json() + assert completed["state"] == "succeeded" and completed["result"]["text"] == "The answer is 5" + content = await system.client.get(completed["result_assets"][0]["preview_url"]) + assert content.content == b"The answer is 5" + stale_job = (await submit(system, task_type="math.solve", input={"prompt": "next"}))[0] + stale = await coordinator._job(stale_job["id"]) + await system.client.post(f"/api/jobs/{stale_job['id']}/cancel") + before = system.provider.cpu_runs + await coordinator._run_cpu(stale) + assert system.provider.cpu_runs == before + + +async def test_running_cpu_cancellation_waits_provider_task(system): + job = (await submit(system, task_type="math.solve", input={"prompt": "2+3?"}))[0] + system.provider.cpu_wait = True + coordinator = system.app.state.coordinator + await coordinator.run_once(force=True) + for _ in range(100): + if system.provider.cpu_runs: + break + await asyncio.sleep(.01) + await system.client.post(f"/api/jobs/{job['id']}/cancel") + tasks = list(coordinator._cpu.values()) + await coordinator.run_once(force=True) + await asyncio.gather(*tasks, return_exceptions=True) + current = (await system.client.get(f"/api/jobs/{job['id']}")).json() + assert current["state"] == "cancelled" + + +async def test_cancel_during_gpu_preparation_never_starts_new_upstream_job(system): + job = (await submit(system))[0] + entered, release = asyncio.Event(), asyncio.Event() + original = system.provider.prepare_gpu_payload + async def blocked_prepare(*args, **kwargs): + entered.set() + await release.wait() + return await original(*args, **kwargs) + system.provider.prepare_gpu_payload = blocked_prepare + task = asyncio.create_task(system.app.state.coordinator.run_once(force=True)) + try: + await asyncio.wait_for(entered.wait(), 2) + response = await system.client.post(f"/api/jobs/{job['id']}/cancel") + assert response.json()["state"] == "cancelling" + release.set() + await asyncio.wait_for(task, 3) + finally: + release.set() + await asyncio.gather(task, return_exceptions=True) + final = (await system.client.get(f"/api/jobs/{job['id']}")).json() + assert final["state"] == "cancelled" + assert not system.provider.accepted and not system.provider.submitted_payloads + + +async def test_cpu_cancel_after_result_read_wins_collection_and_publication(system): + job = (await submit(system, task_type="math.solve", input={"prompt": "2+3?"}))[0] + coordinator = system.app.state.coordinator + entered, release = asyncio.Event(), asyncio.Event() + original = coordinator._update + async def blocked_collect(job_id, **changes): + if changes.get("state") == "collecting": + entered.set() + await release.wait() + return await original(job_id, **changes) + coordinator._update = blocked_collect + try: + await coordinator.run_once(force=True) + await asyncio.wait_for(entered.wait(), 2) + response = await system.client.post(f"/api/jobs/{job['id']}/cancel") + assert response.json()["state"] == "cancelling" + release.set() + await asyncio.gather(*list(coordinator._cpu.values())) + finally: + release.set() + current = (await system.client.get(f"/api/jobs/{job['id']}")).json() + assert current["state"] == "cancelled" and not current["result_assets"] + assert (await system.client.get("/api/assets")).json()["total"] == 0 + + +async def test_final_publication_reloads_committed_cancel_and_keeps_pending_private(system): + from app.models import Job + job = (await submit(system, task_type="math.solve", input={"prompt": "2+3?"}))[0] + coordinator = system.app.state.coordinator + entered, release = asyncio.Event(), asyncio.Event() + original = coordinator._complete + async def blocked_complete(*args, **kwargs): + entered.set() + await release.wait() + return await original(*args, **kwargs) + coordinator._complete = blocked_complete + await coordinator.run_once(force=True) + try: + await asyncio.wait_for(entered.wait(), 2) + # Simulates a previously committed cancellation surviving a stale + # collection transition; _complete must defend publication itself. + async with system.app.state.db.session() as session: + saved = await session.get(Job, job["id"]) + saved.cancel_requested, saved.state = True, "cancelling" + await session.commit() + release.set() + await asyncio.gather(*list(coordinator._cpu.values())) + finally: + release.set() + final = (await system.client.get(f"/api/jobs/{job['id']}")).json() + assert final["state"] == "cancelled" and not final["result_assets"] + assert (await system.client.get("/api/assets")).json()["total"] == 0 + + +async def test_large_waiting_gpu_queue_does_not_starve_later_cpu_or_cancel(system): + ids = [] + for _ in range(13): + ids.extend(job["id"] for job in await submit(system, count=4)) + cpu = (await submit(system, task_type="math.solve", input={"prompt": "2+3?"}))[0] + coordinator = system.app.state.coordinator + await coordinator.run_once(force=True) + await coordinator.run_once(force=True) + await asyncio.gather(*list(coordinator._cpu.values())) + assert system.provider.cpu_runs == 1 and len(system.provider.accepted) == 52 + assert (await system.client.get(f"/api/jobs/{cpu['id']}")).json()["state"] == "succeeded" + last = (await system.client.get(f"/api/jobs/{ids[-1]}")).json() + assert last["upstream_id"] + await system.client.post(f"/api/jobs/{ids[-1]}/cancel") + await coordinator.run_once(force=True) + assert (await system.client.get(f"/api/jobs/{ids[-1]}" )).json()["state"] == "cancelled" diff --git a/backend/tests/test_media.py b/backend/tests/test_media.py new file mode 100644 index 0000000..908ef66 --- /dev/null +++ b/backend/tests/test_media.py @@ -0,0 +1,121 @@ +from __future__ import annotations + +import asyncio +import gc +import importlib +import json +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +from types import SimpleNamespace +import unittest +import warnings +from unittest.mock import patch + +from PIL import Image + + +class MediaTests(unittest.IsolatedAsyncioTestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name).resolve() + self.settings = SimpleNamespace(workspace_root=self.root, asset_root=self.root / 'assets', + job_work_root=self.root / 'jobs', ffmpeg_bin=shutil.which('ffmpeg') or 'ffmpeg', + ffprobe_bin=shutil.which('ffprobe') or 'ffprobe', request_timeout_seconds=3, + max_output_bytes=1024 * 1024) + self.media = importlib.import_module('app.media') + + async def test_image_is_decoded_and_thumbnail_really_exists(self): + source = self.root / 'source.png' + Image.new('RGB', (800, 400), 'red').save(source) + info = await self.media.inspect_media(source, self.settings) + self.assertEqual((info['kind'], info['mime_type'], info['width'], info['height']), + ('image', 'image/png', 800, 400)) + target = await self.media.make_thumbnail(source, self.root / 'thumb.jpg', self.settings) + with Image.open(target) as thumbnail: + self.assertEqual(thumbnail.size, (512, 256)) + + async def test_generated_json_and_text_are_validated_as_assets(self): + source = self.root / 'answer.json' + source.write_text('{"text":"数学"}', encoding='utf-8') + self.assertEqual((await self.media.inspect_media(source, self.settings))['kind'], 'json') + source.write_text('{broken', encoding='utf-8') + with self.assertRaises(self.media.MediaError): + await self.media.inspect_media(source, self.settings) + source = self.root / 'answer.txt' + source.write_text('答案是 42', encoding='utf-8') + self.assertEqual((await self.media.inspect_media(source, self.settings))['mime_type'], 'text/plain') + self.assertIsNone(await self.media.make_thumbnail(source, self.root / 'unused.jpg', self.settings)) + + async def test_outside_path_and_fake_image_fail_without_path_disclosure(self): + with self.assertRaises(self.media.MediaError) as caught: + await self.media.inspect_media(self.root.parent / 'PRIVATE-SECRET.png', self.settings) + self.assertNotIn('PRIVATE-SECRET', str(caught.exception)) + broken = self.root / 'fake.png' + broken.write_bytes(b'not an image') + with self.assertRaises(self.media.MediaError): + await self.media.inspect_media(broken, self.settings) + + async def test_cancel_waits_for_owned_subprocess_and_preserves_unrelated_process(self): + observed = [] + create = asyncio.create_subprocess_exec + + async def record(*args, **kwargs): + process = await create(*args, **kwargs) + observed.append(process) + return process + + unrelated = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)']) + try: + with patch.object(self.media.asyncio, 'create_subprocess_exec', side_effect=record): + task = asyncio.create_task(self.media.run_process( + [sys.executable, '-c', 'import time; time.sleep(60)'], timeout=30)) + for _ in range(100): + if observed: + break + await asyncio.sleep(.01) + self.assertTrue(observed) + task.cancel() + with self.assertRaises(asyncio.CancelledError): + await asyncio.wait_for(task, 5) + self.assertIsNotNone(observed[0].returncode) + self.assertIsNone(unrelated.poll()) + finally: + unrelated.kill() + unrelated.wait(timeout=5) + + async def test_process_timeout_and_output_bound_are_enforced(self): + with self.assertRaises(self.media.MediaError) as caught: + await self.media.run_process([sys.executable, '-c', 'import time; time.sleep(60)'], timeout=.1) + self.assertEqual(caught.exception.code, 'media_timeout') + with self.assertRaises(self.media.MediaError): + await self.media.run_process([sys.executable, '-c', 'print("x"*100000)'], timeout=3, max_output=256) + with warnings.catch_warnings(record=True) as captured: + warnings.simplefilter('always', ResourceWarning) + with self.assertRaises(self.media.MediaError): + await asyncio.wait_for(self.media.run_process([sys.executable, '-c', + 'import sys; sys.stdout.write("x"*10000000); sys.stdout.flush()'], timeout=3, max_output=256), 5) + await asyncio.sleep(.05) + gc.collect() + self.assertFalse([warning for warning in captured if issubclass(warning.category, ResourceWarning)]) + + async def test_bounded_diagnostics_can_return_actual_frame_timestamps(self): + stdout, stderr = await self.media.run_process([sys.executable, '-c', + 'import sys; print("result"); print("pts_time:0.541667",file=sys.stderr)'], + timeout=3, return_stderr=True) + self.assertIn(b'result', stdout) + self.assertIn(b'pts_time:0.541667', stderr) + + @unittest.skipUnless(shutil.which('ffmpeg') and shutil.which('ffprobe'), 'FFmpeg not installed') + async def test_real_video_probe_and_thumbnail(self): + video = self.root / 'tiny.mp4' + await self.media.run_process([self.settings.ffmpeg_bin, '-v', 'error', '-f', 'lavfi', '-i', + 'color=c=blue:s=320x240:r=24:d=0.5', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', str(video)], timeout=30) + info = await self.media.inspect_media(video, self.settings) + self.assertEqual((info['kind'], info['width'], info['height']), ('video', 320, 240)) + self.assertGreater(info['duration_seconds'], .4) + thumb = await self.media.make_thumbnail(video, self.root / 'video.jpg', self.settings) + self.assertTrue(thumb.is_file()) diff --git a/backend/tests/test_providers.py b/backend/tests/test_providers.py new file mode 100644 index 0000000..5a18e94 --- /dev/null +++ b/backend/tests/test_providers.py @@ -0,0 +1,274 @@ +from __future__ import annotations + +import asyncio +from io import BytesIO +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import importlib +import json +import os +from pathlib import Path +import shutil +import tempfile +import threading +import time +from types import SimpleNamespace +import unittest +import wave + +from PIL import Image + + +UPSTREAM_ID = 'a' * 32 + + +class ProviderTests(unittest.IsolatedAsyncioTestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name).resolve() + (self.root / 'assets').mkdir() + (self.root / 'jobs').mkdir() + self.work = self.root / 'jobs' / 'attempt' + self.work.mkdir() + self.requests = [] + self.reply = {'id': UPSTREAM_ID, 'state': 'queued'} + self.status = 200 + self.binary = b'actual-file' + owner = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_): + pass + + def respond(self): + data = self.rfile.read(int(self.headers.get('Content-Length', '0'))) + owner.requests.append((self.command, self.path, dict(self.headers), json.loads(data) if data else None)) + blob = owner.binary if '/outputs/' in self.path or self.path.endswith('/audio/speech') else json.dumps(owner.reply).encode() + self.send_response(owner.status) + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(blob))) + self.end_headers() + self.wfile.write(blob) + + do_GET = do_POST = respond + + self.server = ThreadingHTTPServer(('127.0.0.1', 0), Handler) + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + self.addCleanup(self.server.server_close) + self.addCleanup(self.server.shutdown) + url = f'http://127.0.0.1:{self.server.server_port}' + self.settings = SimpleNamespace(inference_base_url=url, inference_api_key='PRIVATE-KEY', + inference_api_key_file=None, workspace_root=self.root, asset_root=self.root / 'assets', + job_work_root=self.root / 'jobs', gpu_status_path=self.root / 'status.json', + gpu_scheduler_path=self.root / 'scheduler.json', qwen_base_url=url + '/v1', + qwen_model='existing-model', qwen_api_key='QWEN-PRIVATE', ffmpeg_bin=shutil.which('ffmpeg') or 'ffmpeg', + ffprobe_bin=shutil.which('ffprobe') or 'ffprobe', tts_base_url='', tts_model='', tts_api_key='', + request_timeout_seconds=3, max_output_bytes=1024 * 1024) + self.module = importlib.import_module('app.providers') + self.provider = self.module.Provider(self.settings) + self.addAsyncCleanup(self.provider.aclose) + self.image = self.root / 'assets' / 'source.png' + Image.new('RGB', (320, 240), 'red').save(self.image) + + async def test_video_payload_has_real_frame_limit_and_owned_image_path(self): + payload = await self.provider.prepare_gpu_payload('video.generate', + {'prompt': '镜头缓慢移动', 'image_asset_id': 'owned'}, {}, {'owned': self.image}, self.work) + self.assertEqual(payload['input']['image_path'], str(self.image)) + self.assertEqual((payload['parameters']['num_frames'], payload['parameters']['fps']), (121, 24)) + self.assertEqual(payload['parameters']['num_inference_steps'], 50) + for parameters in ({'num_frames': 361}, {'num_frames': 120}, {'fps': 8}, + {'width': 1280, 'height': 736}, {'unknown': True}): + with self.subTest(parameters=parameters), self.assertRaises(self.module.ProviderError): + await self.provider.prepare_gpu_payload('video.generate', {'prompt': 'x'}, parameters, {}, self.work) + + async def test_submission_validation_rejects_unknown_fields_before_creating_job(self): + validate = self.module.validate_arguments + validate('video.generate', {'prompt': 'x'}, {'num_frames': 121}, self.settings) + for task, inputs, parameters in ( + ('image.generate', {'prompt': 'x'}, {'steps': 10}), + ('math.solve', {'prompt': 'x'}, {'shell': 'evil'}), + ('media.structure', {'asset_id': 'x'}, {'frame_count': 13}), + ('audio.speech', {'prompt': 'x'}, {'voice': '/tmp/foreign.npy'}), + ('video.compose', {}, {'clips': [{'asset_id': 'x'}], 'filter': 'unsafe'}), + ('video.generate', {'prompt': 'x'}, {'num_frames': 361}), + ): + with self.subTest(task=task), self.assertRaises(self.module.ProviderError): + validate(task, inputs, parameters, self.settings) + + async def test_unknown_inputs_and_foreign_paths_are_rejected(self): + for inputs, assets in (({'prompt': 'x', 'image_path': '/etc/passwd'}, {}), + ({'prompt': 'x', 'image_asset_id': 'x'}, {'x': self.root.parent / 'secret.png'})): + with self.assertRaises(self.module.ProviderError) as caught: + await self.provider.prepare_gpu_payload('video.generate', inputs, {}, assets, self.work) + self.assertNotIn('passwd', caught.exception.message) + self.assertNotIn('secret.png', caught.exception.message) + with self.assertRaises(self.module.ProviderError): + await self.provider.prepare_gpu_payload('defect.generate', {'prompt': 'scratch'}, {}, {}, self.work) + + async def test_image_and_defect_constraints_match_actual_runner(self): + payload = await self.provider.prepare_gpu_payload('defect.generate', + {'prompt': 'scratch', 'image_asset_id': 'x'}, {}, {'x': self.image}, self.work) + self.assertEqual(payload['parameters']['controlnet_conditioning_scale'], .8) + for parameters in ({'canny_low': 200, 'canny_high': 100}, {'guidance_scale': float('nan')}, + {'width': True}, {'num_inference_steps': 101}, {'mask_asset_id': 'x'}): + with self.subTest(parameters=parameters), self.assertRaises(self.module.ProviderError): + await self.provider.prepare_gpu_payload('defect.generate', + {'prompt': 'scratch', 'image_asset_id': 'x'}, parameters, {'x': self.image}, self.work) + + async def test_submit_preserves_immutable_key_and_error_never_leaks_secret(self): + payload = {'task_type': 'image.generate', 'input': {'prompt': 'x'}, 'parameters': {}, 'timeout_seconds': 3600} + for _ in range(2): + await self.provider.submit(payload, 'same-key') + self.assertEqual([request[2]['Idempotency-Key'] for request in self.requests], ['same-key', 'same-key']) + self.assertEqual(self.requests[0][3], self.requests[1][3]) + self.status, self.reply = 500, {'detail': 'PRIVATE-KEY /workspace/private'} + with self.assertRaises(self.module.ProviderError) as caught: + await self.provider.query(UPSTREAM_ID) + self.assertTrue(caught.exception.retriable) + self.assertNotIn('PRIVATE', caught.exception.message) + self.assertNotIn('/workspace', caught.exception.message) + + async def test_replayed_submit_and_cancel_errors_are_sanitized(self): + self.reply = {'id': UPSTREAM_ID, 'state': 'failed', 'error': 'PRIVATE-KEY /workspace/private', + 'last_preempted_reason': 'PRIVATE /run/private'} + payload = {'task_type': 'image.generate', 'input': {'prompt': 'x'}, 'parameters': {}, 'timeout_seconds': 3600} + for value in (await self.provider.submit(payload, 'fixed'), await self.provider.cancel(UPSTREAM_ID)): + self.assertNotIn('PRIVATE', json.dumps(value)) + self.assertNotIn('/workspace', json.dumps(value)) + + async def test_download_is_real_atomic_and_bounded(self): + target = self.work / 'result.png' + await self.provider.download(UPSTREAM_ID, 0, target) + self.assertEqual(target.read_bytes(), b'actual-file') + self.settings.max_output_bytes = 4 + with self.assertRaises(self.module.ProviderError): + await self.provider.download(UPSTREAM_ID, 1, self.work / 'too-large.png') + self.assertFalse((self.work / 'too-large.png').exists()) + self.assertFalse(list(self.work.glob('*.part-*'))) + + async def test_private_key_file_is_bounded_and_not_symlink_followed(self): + key = self.root / 'private-key' + key.write_text('FILE-SECRET', encoding='utf-8') + if os.name != 'nt': + key.chmod(0o600) + self.settings.inference_api_key_file, self.settings.inference_api_key = key, '' + await self.provider.query(UPSTREAM_ID) + self.assertEqual(self.requests[-1][2]['Authorization'], 'Bearer FILE-SECRET') + key.write_text('x' * 5000) + with self.assertRaises(self.module.ProviderError): + await self.provider.query(UPSTREAM_ID) + + async def test_math_and_visual_structure_return_real_text_json_files(self): + self.reply = {'choices': [{'message': {'content': '答案为 4。'}, 'finish_reason': 'stop'}]} + result = await self.provider.run_cpu('math.solve', {'prompt': '2+2'}, {}, {}, self.work) + self.assertEqual(result.result, {'text': '答案为 4。'}) + self.assertTrue(all(path.is_file() for path in result.outputs)) + self.assertNotIn('reasoning_content', result.result) + self.reply = {'choices': [{'message': {'content': '{"subjects":["红色画面"],"scene":"室内","ocr":[],"tags":["红色"]}'}}]} + result = await self.provider.run_cpu('media.structure', {'asset_id': 'x'}, {}, {'x': self.image}, self.work) + self.assertEqual(result.result['subjects'], ['红色画面']) + content = self.requests[-1][3]['messages'][-1]['content'] + self.assertTrue(content[0]['image_url']['url'].startswith('data:image/jpeg;base64,')) + self.assertEqual(result.result['frames'][0]['timestamp_seconds'], 0) + self.assertTrue(all(path.is_file() for path in result.outputs)) + + async def test_math_length_finish_is_failure_and_creates_no_answer_artifacts(self): + self.reply = {'choices': [{'message': {'content': '计算尚未完成:17*3='}, 'finish_reason': 'length'}]} + with self.assertRaises(self.module.ProviderError) as caught: + await self.provider.run_cpu('math.solve', {'prompt': '17*3?'}, {'max_tokens': 128}, {}, self.work) + self.assertEqual(caught.exception.code, 'output_truncated') + self.assertIn('提高输出长度', caught.exception.message) + self.assertFalse((self.work / 'answer.txt').exists()) + self.assertFalse((self.work / 'answer.json').exists()) + + async def test_visual_length_finish_is_failure_even_when_partial_output_parses_as_json(self): + self.reply = {'choices': [{'message': {'content': '{"subjects":[],"scene":"部分内容","ocr":[],"tags":[]}'}, + 'finish_reason': 'length'}]} + with self.assertRaises(self.module.ProviderError) as caught: + await self.provider.run_cpu('media.structure', {'asset_id': 'x'}, {}, {'x': self.image}, self.work) + self.assertEqual(caught.exception.code, 'output_truncated') + self.assertFalse((self.work / 'structure.json').exists()) + + async def test_visual_non_json_and_unconfigured_speech_are_explicit_failures(self): + self.reply = {'choices': [{'message': {'content': 'not json'}}]} + with self.assertRaises(self.module.ProviderError): + await self.provider.run_cpu('media.structure', {'asset_id': 'x'}, {}, {'x': self.image}, self.work) + with self.assertRaises(self.module.ProviderError) as caught: + await self.provider.run_cpu('audio.speech', {'prompt': 'hello'}, {'voice': 'zf_xiaobei'}, {}, self.work) + self.assertEqual(caught.exception.code, 'capability_unavailable') + + async def test_composition_rejects_url_filter_and_invalid_subtitles_before_ffmpeg(self): + for parameters in ({'clips': [{'asset_id': 'x', 'url': 'http://evil'}]}, + {'clips': [{'asset_id': 'x'}], 'filter': 'movie=/etc/passwd'}, + {'clips': [{'asset_id': 'x', 'start_seconds': 2, 'end_seconds': 1}]}, + {'clips': [{'asset_id': 'x'}], 'subtitles': [{'start': 0, 'end': 1, 'text': '{\\p1}'}]}): + with self.subTest(parameters=parameters), self.assertRaises(self.module.ProviderError): + await self.provider.run_cpu('video.compose', {}, parameters, {'x': self.image}, self.work) + + async def test_capabilities_and_scheduler_do_not_overstate_or_disclose_pids(self): + items = {item['task_type']: item for item in self.module.capabilities(self.settings)} + self.assertFalse(items['audio.speech']['available']) + self.assertEqual(items['video.generate']['constraints']['num_frames'], {'min': 5, 'max': 121, 'step': 4}) + status = {'schema_version': 1, 'generated_at': time.time(), 'error': None, 'container_id': 'b' * 64, + 'gpus': [{'index': 2, 'uuid': 'GPU-00000000-0000-0000-0000-000000000002', + 'total_gib': 79.6, 'free_gib': 79.5, 'idle_since': time.time() - 20, + 'own_pids': [], 'external_pids': [], 'baseline_pids': [2880]}]} + self.settings.gpu_status_path.write_text(json.dumps(status)) + scheduler = await self.provider.scheduler_status() + self.assertTrue(scheduler['available']) + self.assertTrue(scheduler['gpus'][0]['eligible']) + self.assertNotIn('2880', json.dumps(scheduler)) + status['generated_at'] -= 10 + self.settings.gpu_status_path.write_text(json.dumps(status)) + self.assertFalse((await self.provider.scheduler_status())['available']) + + @unittest.skipUnless(shutil.which('ffmpeg') and shutil.which('ffprobe'), 'FFmpeg not installed') + async def test_real_compose_preserves_order_trims_and_video_asr_prepares_wav(self): + from app.media import run_process, inspect_media + video = self.root / 'assets' / 'tiny.mp4' + await run_process([self.settings.ffmpeg_bin, '-v', 'error', '-f', 'lavfi', '-i', + 'color=c=blue:s=320x256:r=24:d=1', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=1', + '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-shortest', str(video)], timeout=30) + red = self.root / 'assets' / 'red.mp4' + await run_process([self.settings.ffmpeg_bin, '-v', 'error', '-f', 'lavfi', '-i', + 'color=c=red:s=320x256:r=24:d=1', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', str(red)], timeout=30) + result = await self.provider.run_cpu('video.compose', {}, {'clips': [ + {'asset_id': 'v', 'start_seconds': 0, 'end_seconds': .25}, + {'asset_id': 'r', 'start_seconds': .5, 'end_seconds': .75}], 'width': 320, 'height': 256, + 'subtitles': [{'start': 0, 'end': .4, 'text': 'Safe & credits'}]}, {'v': video, 'r': red}, self.work) + info = await inspect_media(result.outputs[0], self.settings) + self.assertEqual((info['width'], info['height']), (320, 256)) + self.assertAlmostEqual(info['duration_seconds'], .5, delta=.15) + for timestamp, dominant in ((.1, 2), (.4, 0)): + frame = await run_process([self.settings.ffmpeg_bin, '-v', 'error', '-ss', str(timestamp), + '-i', str(result.outputs[0]), '-frames:v', '1', '-f', 'image2pipe', '-c:v', 'png', 'pipe:1'], timeout=30) + with Image.open(BytesIO(frame)) as image: + color = image.convert('RGB').getpixel((10, 10)) + self.assertGreater(color[dominant], 150) + self.assertLess(color[2 if dominant == 0 else 0], 50) + payload = await self.provider.prepare_gpu_payload('audio.transcribe', {'audio_asset_id': 'v'}, {}, {'v': video}, self.work) + self.assertEqual(Path(payload['input']['audio_path']).suffix, '.wav') + self.assertEqual((await inspect_media(Path(payload['input']['audio_path']), self.settings))['kind'], 'audio') + self.reply = {'choices': [{'message': {'content': '{"subjects":[],"scene":"blue","ocr":[],"tags":[]}'}}]} + structure = await self.provider.run_cpu('media.structure', {'asset_id': 'v'}, {'frame_count': 2}, {'v': video}, self.work) + self.assertEqual(len(structure.result['frames']), 2) + self.assertAlmostEqual(structure.result['frames'][0]['timestamp_seconds'], .25, delta=.05) + self.assertAlmostEqual(structure.result['frames'][1]['timestamp_seconds'], .75, delta=.05) + self.assertTrue(all(path.is_file() for path in structure.outputs)) + + @unittest.skipUnless(shutil.which('ffprobe'), 'FFprobe not installed') + async def test_configured_speech_posts_only_allowed_voice_and_real_wav_output(self): + stream = BytesIO() + with wave.open(stream, 'wb') as audio: + audio.setnchannels(1) + audio.setsampwidth(2) + audio.setframerate(16000) + audio.writeframes(b'\x00\x00' * 1600) + self.binary = stream.getvalue() + self.settings.tts_base_url = self.settings.inference_base_url + '/v1' + self.settings.tts_model = 'kokoro-82m' + result = await self.provider.run_cpu('audio.speech', {'prompt': '你好'}, {'voice': 'zf_xiaobei', 'speed': 1.2}, {}, self.work) + self.assertEqual(result.outputs[0].read_bytes(), self.binary) + self.assertEqual(self.requests[-1][3], {'model': 'kokoro-82m', 'input': '你好', 'voice': 'zf_xiaobei', + 'speed': 1.2, 'response_format': 'wav'}) diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..58197c0 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,87 @@ +name: cmvr-visual +services: + api: + build: ./backend + image: cmvr-visual-api:20261110 + container_name: cmvr-visual-api + env_file: .env + environment: + WORKSPACE_ROOT: /workspace + ASSET_ROOT: /workspace/cmvr-visual/assets + JOB_WORK_ROOT: /workspace/cmvr-visual/jobs + STATE_ROOT: /workspace/cmvr-visual/state + INFERENCE_BASE_URL: http://llmuser-workspace:18190 + INFERENCE_API_KEY_FILE: /workspace/projects/llm-services/config/api_key + GPU_STATUS_PATH: /run/llm-gpu-policy/status.json + GPU_SCHEDULER_PATH: /workspace/projects/llm-services/state/gpu-scheduler.json + TTS_BASE_URL: http://cmvr-visual-tts:8001/v1 + TTS_MODEL: kokoro-82m + TTS_VOICES: zf_xiaobei,zm_yunxi + TMPDIR: /workspace/cmvr-visual/tmp + volumes: + - ${WORKSPACE_HOST:-/data/llmusers/llmuser/workspace}:/workspace + - /var/lib/llmuser-gpu-policy:/run/llm-gpu-policy:ro + networks: [visual] + user: '1013:1014' + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + init: true + pids_limit: 256 + cpus: 4 + mem_limit: 4g + memswap_limit: 4g + stop_grace_period: 45s + restart: unless-stopped + logging: {driver: json-file, options: {max-size: 10m, max-file: '3'}} + frontend: + build: {context: ., dockerfile: deploy/Dockerfile.frontend} + image: cmvr-visual-frontend:20261110 + container_name: cmvr-visual-frontend + ports: ['127.0.0.1:${WEB_PORT:-18193}:8080'] + depends_on: [api] + networks: [visual] + user: '1013:1014' + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + tmpfs: ['/tmp:rw,nosuid,nodev,size=32m,mode=1777'] + pids_limit: 64 + cpus: 1 + mem_limit: 128m + restart: unless-stopped + logging: {driver: json-file, options: {max-size: 5m, max-file: '2'}} + tts: + build: ./tts + image: cmvr-visual-tts:20261110 + container_name: cmvr-visual-tts + environment: + TTS_API_KEY: ${TTS_API_KEY:-} + TTS_MODEL_DIR: /workspace/models/kokoro-82m + TTS_WORK_DIR: /workspace/cmvr-visual/tts-work + HF_HOME: /workspace/cmvr-visual/tts-cache + XDG_CACHE_HOME: /workspace/cmvr-visual/tts-cache + TMPDIR: /workspace/cmvr-visual/tmp + CUDA_VISIBLE_DEVICES: '' + HF_HUB_OFFLINE: '1' + TRANSFORMERS_OFFLINE: '1' + volumes: + - ${WORKSPACE_HOST:-/data/llmusers/llmuser/workspace}/models/kokoro-82m:/workspace/models/kokoro-82m:ro + - ${WORKSPACE_HOST:-/data/llmusers/llmuser/workspace}/cmvr-visual/tts-work:/workspace/cmvr-visual/tts-work + - ${WORKSPACE_HOST:-/data/llmusers/llmuser/workspace}/cmvr-visual/tts-cache:/workspace/cmvr-visual/tts-cache + - ${WORKSPACE_HOST:-/data/llmusers/llmuser/workspace}/cmvr-visual/tmp:/workspace/cmvr-visual/tmp + networks: [visual] + user: '1013:1014' + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + init: true + pids_limit: 128 + cpus: 4 + mem_limit: 4g + memswap_limit: 4g + stop_grace_period: 15s + restart: unless-stopped + logging: {driver: json-file, options: {max-size: 5m, max-file: '2'}} +networks: + visual: {external: true, name: cmvr-visual-net} diff --git a/deploy/Dockerfile.frontend b/deploy/Dockerfile.frontend new file mode 100644 index 0000000..23a9c89 --- /dev/null +++ b/deploy/Dockerfile.frontend @@ -0,0 +1,6 @@ +FROM nginx:1.30.6-alpine +COPY deploy/nginx.conf /etc/nginx/nginx.conf +COPY frontend/dist /usr/share/nginx/html +USER 1013:1014 +EXPOSE 8080 +ENTRYPOINT ["nginx", "-g", "daemon off;"] diff --git a/deploy/kokoro-manifest.json b/deploy/kokoro-manifest.json new file mode 100644 index 0000000..8e38f46 --- /dev/null +++ b/deploy/kokoro-manifest.json @@ -0,0 +1,49 @@ +{ + "repo": "hexgrad/Kokoro-82M", + "revision": "f3ff3571791e39611d31c381e3a41a3af07b4987", + "files": [ + { + "rfilename": "config.json", + "blobId": "14a726edd3718279eac426630879ff743955b16a", + "size": 2351, + "sha256": "5abb01e2403b072bf03d04fde160443e209d7a0dad49a423be15196b9b43c17f", + "download_url": "https://www.modelscope.cn/api/v1/models/AI-ModelScope/Kokoro-82M/repo?Revision=7e4304e4a2b8b8fdeef357c7d4bcb987865677a0&FilePath=config.json" + }, + { + "rfilename": "kokoro-v1_0.pth", + "blobId": "15769c415594dcb424579ba3dfae3085578aac4e", + "size": 327212226, + "lfs": { + "sha256": "496dba118d1a58f5f3db2efc88dbdc216e0483fc89fe6e47ee1f2c53f18ad1e4", + "size": 327212226, + "pointerSize": 134 + }, + "sha256": "496dba118d1a58f5f3db2efc88dbdc216e0483fc89fe6e47ee1f2c53f18ad1e4", + "download_url": "https://www.modelscope.cn/api/v1/models/AI-ModelScope/Kokoro-82M/repo?Revision=7e4304e4a2b8b8fdeef357c7d4bcb987865677a0&FilePath=kokoro-v1_0.pth" + }, + { + "rfilename": "voices/zf_xiaobei.pt", + "blobId": "98d012c808d0c720f343605125b378c0390e7cfe", + "size": 523435, + "lfs": { + "sha256": "9b76be63dab4f4f96962030acc0126a9aee9728608fbbe115e2b58a2bd504df6", + "size": 523435, + "pointerSize": 131 + }, + "sha256": "9b76be63dab4f4f96962030acc0126a9aee9728608fbbe115e2b58a2bd504df6", + "download_url": "https://www.modelscope.cn/api/v1/models/AI-ModelScope/Kokoro-82M/repo?Revision=3cbf1fa40f92ebf18fcbf80866b4765561d16e70&FilePath=voices/zf_xiaobei.pt" + }, + { + "rfilename": "voices/zm_yunxi.pt", + "blobId": "ab5b4af8e051d3940b7f265e0ff6a113a7a68f2a", + "size": 523425, + "lfs": { + "sha256": "dbe6e1ce7c3dbaf2f5667432947b638b1c6831ccbe154c4610dbcc44f431e27b", + "size": 523425, + "pointerSize": 131 + }, + "sha256": "dbe6e1ce7c3dbaf2f5667432947b638b1c6831ccbe154c4610dbcc44f431e27b", + "download_url": "https://www.modelscope.cn/api/v1/models/AI-ModelScope/Kokoro-82M/repo?Revision=3cbf1fa40f92ebf18fcbf80866b4765561d16e70&FilePath=voices/zm_yunxi.pt" + } + ] +} \ No newline at end of file diff --git a/deploy/nginx.conf b/deploy/nginx.conf new file mode 100644 index 0000000..342301e --- /dev/null +++ b/deploy/nginx.conf @@ -0,0 +1,47 @@ +pid /tmp/nginx.pid; +worker_processes 2; +error_log /dev/stderr warn; +events { worker_connections 1024; } +http { + include /etc/nginx/mime.types; + default_type application/octet-stream; + access_log /dev/stdout; + sendfile on; + server_tokens off; + client_body_temp_path /tmp/client_temp; + proxy_temp_path /tmp/proxy_temp; + fastcgi_temp_path /tmp/fastcgi_temp; + uwsgi_temp_path /tmp/uwsgi_temp; + scgi_temp_path /tmp/scgi_temp; + server { + listen 8080; + server_name _; + root /usr/share/nginx/html; + index index.html; + client_max_body_size 512m; + add_header X-Content-Type-Options nosniff always; + add_header Referrer-Policy same-origin always; + add_header X-Frame-Options SAMEORIGIN always; + add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; font-src 'self' data:; frame-ancestors 'self'; object-src 'none'; base-uri 'self'" always; + location /api/ { + proxy_pass http://cmvr-visual-api:8000; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header Connection ""; + proxy_buffering off; + proxy_cache off; + proxy_request_buffering off; + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; + } + # The library SPA route shares the build directory's name. Serve the + # entry point explicitly so Nginx cannot redirect it to container :8080. + location = /assets { try_files /index.html =404; expires -1; } + location = /assets/ { try_files /index.html =404; expires -1; } + location /assets/ { try_files $uri =404; expires 7d; } + location = /index.html { try_files $uri =404; expires -1; } + location / { try_files $uri $uri/ /index.html; } + } +} diff --git a/deploy/production.sql.example b/deploy/production.sql.example new file mode 100644 index 0000000..cf37cbd --- /dev/null +++ b/deploy/production.sql.example @@ -0,0 +1,36 @@ +-- CMVR Visual / MySQL 专用账号最小权限示例 +-- 仅供有权限的 DBA 审核后逐项执行。全部语句默认注释,不含真实密码。 +-- 用户指定的正式目标库已存在:192.168.28.10:3306/cmvr-visual。 +-- 不创建/删除数据库,不读取其他项目凭据,不操作其他库。 +-- +-- 先替换两种占位: +-- <API_SOURCE_HOST>:MySQL 实际看到的 API 来源主机或受限网段;不要直接用 %。 +-- <INDEPENDENT_RANDOM_PASSWORD>:独立随机强密码,安全交付,不提交源码。 +-- Docker NAT/桥接可能使来源不同于浏览器或服务器公网 IP,需由 DBA 实测确定。 + +-- CREATE USER 'cmvr_visual_app'@'<API_SOURCE_HOST>' +-- IDENTIFIED BY '<INDEPENDENT_RANDOM_PASSWORD>'; + +-- 阶段1:首次由应用 create_all 建立 visual_* 表,需要库内 DDL 权限。 +-- GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, INDEX, REFERENCES +-- ON `cmvr-visual`.* +-- TO 'cmvr_visual_app'@'<API_SOURCE_HOST>'; + +-- 应用启动、表结构确认且已有正式备份后,撤销临时建表权限。 +-- 阶段2:日常运行仅保留该库的 DML;不是全局权限或管理账号。 +-- REVOKE CREATE, INDEX, REFERENCES +-- ON `cmvr-visual`.* +-- FROM 'cmvr_visual_app'@'<API_SOURCE_HOST>'; + +-- 验证权限: +-- SHOW GRANTS FOR 'cmvr_visual_app'@'<API_SOURCE_HOST>'; + +-- 应用使用以下六张表,均有 visual_ 前缀: +-- visual_users, visual_sessions, visual_jobs, +-- visual_assets, visual_job_assets, visual_job_events +-- 当前 create_all 不提供 ALTER/迁移能力;升级应先备份,由 DBA 审查迁移。 +-- 不授予 DROP、ALTER、FILE、PROCESS、SUPER、CREATE USER 或 GRANT OPTION。 +-- 不需要 FLUSH PRIVILEGES;使用 CREATE USER / GRANT / REVOKE 后权限即生效。 +-- 若数据库由其他应用共用,DBA 可在表创建后进一步按 visual_* 具体表授权, +-- 而不使用库级 DML。不要假定此示例授权可访问其他项目的数据。 +-- 官方说明:https://dev.mysql.com/doc/refman/8.0/en/grant.html diff --git a/docs/API-examples.md b/docs/API-examples.md new file mode 100644 index 0000000..bbe65b6 --- /dev/null +++ b/docs/API-examples.md @@ -0,0 +1,242 @@ +# HTTP + SSE 调用示例 + +以下针对网站业务 API,**不是**直接调用 GPU 上游。示例使用同一登录用户;素材 ID、任务 ID 均由服务器返回,不接受客户端提供的服务器路径。完整字段见 [共享契约](api-contract.md)。 + +## 登录与会话 + +Python/httpx 示例通过交互输入取得密码,不写在源码、命令行参数或日志里。使用 SSH 隧道的本地 HTTP 地址;正式 HTTPS 部署改成自己的同源地址。 + +```python +import getpass +import uuid +from pathlib import Path +import httpx + +client = httpx.Client(base_url="http://127.0.0.1:18193/api", timeout=30) +response = client.post("/auth/login", json={ + "username": input("账号:"), + "password": getpass.getpass("密码:"), +}) +response.raise_for_status() +client.headers["X-CSRF-Token"] = response.json()["csrf_token"] +# client 自动携带 HttpOnly 会话 Cookie;不要打印 response 或 Cookie。 +``` + +管理员创建普通用户使用 `POST /auth/users`,字段为 `username/display_name/password`,密码至少12字符;无公开注册。当前默认管理员配置在本机私有 `.env.server` 中获取,不复制进本示例。初始管理员支持本次指定的六位密码,不改变普通用户12位要求。 + +## 素材上传、编辑和读取 + +```python +def upload(path): + path = Path(path) + with path.open("rb") as stream: + response = client.post("/assets", files={"file": (path.name, stream)}) + response.raise_for_status() + return response.json() + +image = upload("reference.png") # 替换为自己的真实本地文件 +image_id = image["id"] + +response = client.patch(f"/assets/{image_id}", json={ + "name": "产品参考图", "tags": ["产品", "参考"], "favorite": True, +}) +response.raise_for_status() + +response = client.get("/assets", params={"kind": "image", "tag": "参考", "page": 1, "page_size": 24}) +response.raise_for_status() +``` + +`preview_url`、`thumbnail_url`、`download_url` 都指向受会话保护的 `/api/assets/...` 路由。浏览器同源 `<img>`、`<video>`、`<audio>` 可自动携带 Cookie。下面直接用相对路由测试单段 Range: + +```python +response = client.get(f"/assets/{image_id}/content", headers={"Range": "bytes=0-31"}) +response.raise_for_status() # 有效范围返回206,Content-Range包含实际长度 +response = client.get(f"/assets/{image_id}/content", params={"download": 1}) +response.raise_for_status() +Path("reference-copy.png").write_bytes(response.content) +``` + +不存在、已删除或非本人素材均不可读取。删除使用 `DELETE /assets/{id}`;如果输入仍被任务引用,只从素材库移除,不立即物理删除。生成素材改名、收藏、标签或删除时,来源任务会产生新 version 和 `job.updated` 事件。 + +## 提交约定 + +```python +def submit(payload, key=None): + # 网络结果未知时,应保留本次 key 和原 payload 重试,而非重新生成 key。 + request_key = key or str(uuid.uuid4()) + response = client.post("/jobs", json=payload, headers={"Idempotency-Key": request_key}) + response.raise_for_status() + return response.json()["jobs"], request_key +``` + +HTTP 202 只表示接受任务。相同用户、相同幂等键和相同参数返回同一批业务任务;参数改变返回 409。不要把重新连接当成“再次生成”。下面八个 payload 应按需单独执行,不需要一次运行所有模型。 + +### 1. 文生图片与批次 + +```python +payload = { + "task_type": "image.generate", "input": {"prompt": "白色背景上的蓝色陶瓷杯,柔和自然光"}, + "parameters": {"width": 1024, "height": 1024, "num_inference_steps": 50, "seed": 42}, + "count": 2, +} +jobs, request_key = submit(payload) +job_id = jobs[0]["id"] +``` + +批量仅适用于 `image.generate`、`defect.generate`,最多 4 项,各项独立排队。此例两个实际种子分别为 42、43。普通 Qwen-Image 不支持参考图编辑。 + +### 2. 文生或图生视频 + +```python +payload = { + "task_type": "video.generate", + "input": {"prompt": "镜头缓慢绕产品移动,保持主体结构稳定", "image_asset_id": image_id}, + "parameters": {"width": 1280, "height": 704, "num_frames": 121, "fps": 24, + "num_inference_steps": 50, "seed": 42, "upscale": True, + "upscale_width": 1920, "upscale_height": 1080, "tile_size": 128}, +} +# 删除 image_asset_id 即为文生视频;保留时必须是本人上传/生成的图片。 +``` + +最多约 5 秒,帧数须为 `4n+1` 且不超过 121,帧率固定 24。当前不是 15 秒任务,结果默认无声。 + +### 3. Canny 条件样本 + +```python +payload = { + "task_type": "defect.generate", + "input": {"prompt": "金属零件表面细小划痕,真实工业摄影", "image_asset_id": image_id}, + "parameters": {"width": 1024, "height": 1024, "num_inference_steps": 50, + "controlnet_conditioning_scale": 0.8, "canny_low": 100, "canny_high": 200}, +} +``` + +输出包含合成图和边缘控制图,不是带缺陷真值掩膜的训练标注对。 + +### 4. Whisper 转写 + +```python +audio = upload("speech.wav") +payload = { + "task_type": "audio.transcribe", "input": {"audio_asset_id": audio["id"]}, + "parameters": {"language": "zh", "max_audio_seconds": 1800}, +} +``` + +也可使用本人有声视频的 asset ID;服务先做 CPU 音轨提取。`language="auto"` 为自动识别。成功后 `job.result` 包含 `text`、`segments`,分段为 `start/end/text`,时间按实际分块记录,不是逐词时间轴。 + +### 5. 数学推演 + +```python +payload = {"task_type": "math.solve", "input": {"prompt": "解方程 x²-5x+6=0,并验证答案"}, + "parameters": {"max_tokens": 2048, "enable_thinking": False}} +``` + +结果为 `job.result.text` 及文本/JSON 素材;需要业务复核,不把输出当作形式化证明。 + +### 6. 图片/视频理解 + +```python +payload = {"task_type": "media.structure", "input": {"asset_id": image_id}, + "parameters": {"frame_count": 1}} +# 视频使用视频 asset ID,frame_count 可取1..12。 +``` + +结果含 `subjects/scene/ocr/tags/frames`;视频帧的 `timestamp_seconds` 来自实际解码帧时间。只描述可见画面,不宣称实现完整镜头切分指标。 + +### 7. CPU 成片合成 + +```python +video = upload("clip.mp4") +payload = { + "task_type": "video.compose", "input": {"asset_ids": [video["id"]]}, + "parameters": {"width": 1280, "height": 720, "fps": 24, + "clips": [{"asset_id": video["id"], "start_seconds": 0, "end_seconds": 3}], + "subtitles": [{"start": 0, "end": 2, "text": "我的产品介绍"}]}, +} +# 片段实际时长须至少3秒;可在input加入audio_asset_id引用自己的音频。 +``` + +`asset_ids` 顺序必须与 `clips` 一致;剪辑点、字幕不能越过实际素材/成片时长。帧率限 24、25、30、60,不接受任意 FFmpeg filter、外部 URL 或命令行。外部音轨由用户上传,不自动生成背景音乐。 + +### 8. Kokoro CPU 中文配音 + +```python +payload = {"task_type": "audio.speech", "input": {"prompt": "欢迎来到本地创作工作台。"}, + "parameters": {"voice": "zf_xiaobei", "speed": 1.0}} +``` + +另一当前音色为 `zm_yunxi`。须先配置真实 Kokoro 服务;没有可用服务时能力不启用,不返回模拟音频。配音属于 CPU provider,不进入新 GPU 模型队列。 + +## 定时、查询、取消与重新生成 + +```python +from datetime import datetime, timedelta, timezone +payload["scheduled_at"] = (datetime.now(timezone.utc) + timedelta(minutes=30)).isoformat() +# 如需提交:jobs, request_key = submit(payload) + +response = client.get(f"/jobs/{job_id}") +response.raise_for_status() +job = response.json() +print(job["id"], job["state"], job["attempt_count"], job["preemptions"]) + +response = client.post(f"/jobs/{job_id}/cancel") +response.raise_for_status() +# 可能仍为cancelling,须继续查询确认最终cancelled。 +``` + +归档 `collecting` 阶段不再接受新的取消;此前已提交的取消会在完成事务中优先处理,不公开 pending 输出。只有 `succeeded/failed/cancelled/timed_out` 终态可调用 `POST /jobs/{id}/retry`;这是用户明确要求的新生成,会取得新业务 ID,不是网络恢复机制。 + +任务状态包括 `scheduled/submitting/queued/running/collecting/cancelling/succeeded/failed/cancelled/timed_out`。外部用户占用 GPU 时可出现同 ID 的 `running → queued`,`preemptions` 递增;不要为此创建替代任务。`sync_warning` 不是终态失败,`progress=null` 表示没有真实百分比来源。 + +## SSE 与重连 + +在已登录网站的浏览器中,先获取任务快照和 cursor,再打开同源 EventSource: + +```javascript +const snapshot = await fetch('/api/jobs?page_size=24', {credentials:'include'}).then(r => r.json()); +const source = new EventSource(`/api/events?after=${snapshot.cursor}`, {withCredentials:true}); +source.addEventListener('job.updated', event => { + const {job} = JSON.parse(event.data); + console.log(event.lastEventId, job.id, job.state, job.version); + // 仅将更高version应用到本地同ID任务。 +}); +source.addEventListener('reset', () => { + // 重新获取HTTP快照;不要重新生成任务。 +}); +// 离开工作空间/注销时 source.close();关闭流不取消任务。 +``` + +服务端事件格式: + +```text +id: 123 +event: job.updated +data: {"job":{"id":"...","version":3,"state":"queued"}} + +: heartbeat + +``` + +`Last-Event-ID` header 在重连时优先于最初的 `?after=`;浏览器自动维护该 header。事件持久存于 MySQL,按 owner 过滤。另有 `asset.created/asset.updated/asset.deleted/reset`;心跳不改变游标。注销或会话过期会结束流,前端应恢复登录而不是一直重建任务。 + +Python 已登录 client 也可重放(会持续读取,按 Ctrl+C 结束): + +```python +cursor = client.get("/jobs").json()["cursor"] +with client.stream("GET", "/events", headers={"Last-Event-ID": str(cursor)}, + timeout=httpx.Timeout(10, read=None)) as response: + response.raise_for_status() + for line in response.iter_lines(): + if line.startswith(("id:", "event:", ":")): + print(line) # 不打印Cookie、密码或推理密钥。 +``` + +调试完注销并清理连接: + +```python +client.post("/auth/logout").raise_for_status() +client.close() +``` + +常见错误:401 登录无效;403 CSRF/权限拒绝;404 非本人或已删资源;409 幂等键冲突或任务状态不允许;400/422 参数不支持;413 上传过大。错误为 `detail.code/message`,验证错误可能附字段位置。不要向用户显示服务器绝对路径或上游认证内容。 diff --git a/docs/api-contract.md b/docs/api-contract.md new file mode 100644 index 0000000..e29dcf5 --- /dev/null +++ b/docs/api-contract.md @@ -0,0 +1,70 @@ +# Shared API contract + +All endpoints use `/api`. JSON errors: `{detail:{code,message}}`; normal FastAPI validation errors may additionally contain field locations. Session cookie `cmvr_session` is HttpOnly, same-origin. POST/PATCH/DELETE except login need `X-CSRF-Token` from auth response. Never expose inference keys or absolute server paths. + +## Authentication + +- POST `/auth/login` `{username,password}` → `{user:{id,username,display_name,role},csrf_token}` plus session cookie. +- GET `/auth/me` → same shape; 401 when signed out. +- POST `/auth/logout` → 204; close SSE on frontend. +- Admin POST `/auth/users` `{username,display_name,password}` → user. + +## Capabilities and resources + +- GET `/capabilities` → `{items:Capability[],scheduler:Scheduler}`. +- GET `/system/status` → `{inference_online:boolean,scheduler:Scheduler,models:Capability[]}`. +- Capability: `{task_type,label,model,available,input_types:string[],defaults:object,constraints:object,description:string}`. +- Scheduler: `{available:boolean,state:string,reason:string|null,gpus:[{index,name,busy:boolean,eligible:boolean,free_gib:number|null}],updated_at:string|null}`. No PID or user identity. +- Types: `image.generate`, `video.generate`, `defect.generate`, `audio.transcribe`, `math.solve`, `media.structure`, `video.compose`, optional `audio.speech` (only available when a real provider is configured). + +## Assets + +- POST `/assets` multipart field `file`, optional `name` → Asset. +- GET `/assets?page=1&page_size=24&kind=&q=&tag=` → `{items:Asset[],total,page,page_size}`. +- GET `/assets/{id}` → Asset. +- PATCH `/assets/{id}` `{name?,tags?:string[],favorite?:boolean}` → Asset. +- DELETE `/assets/{id}` → 204; retain referenced physical input. +- GET `/assets/{id}/content` inline, Range supported; `?download=1` attachment. +- GET `/assets/{id}/thumbnail` authenticated image preview (fallback image content when no separate thumbnail). +- Asset: `{id,name,kind:'image'|'video'|'audio'|'text'|'json',mime_type,size_bytes,width:null|number,height:null|number,duration_seconds:null|number,preview_url,thumbnail_url:null|string,download_url,source_job_id:null|string,origin:'upload'|'generated',tags:string[],favorite:boolean,created_at:string}`. + +## Jobs + +- POST `/jobs`, optional `Idempotency-Key`, body `{task_type,input:{prompt?,negative_prompt?,image_asset_id?,audio_asset_id?,asset_id?,asset_ids?:string[]},parameters:object,count?:1..4,scheduled_at?:ISO8601|null}` → `{jobs:Job[]}`. Batch only for image/defect; each gets its own serial upstream job. Composition clip order and trims live in `parameters.clips:[{asset_id,start_seconds?,end_seconds?}]`, optional `audio_asset_id`, `subtitles:[{start,end,text}]`, width/height/fps. Server resolves owned assets only. +- GET `/jobs?page=1&page_size=24&task_type=&state=` → `{items:Job[],total,page,page_size,cursor:number}`. +- GET `/jobs/{id}` → Job. +- POST `/jobs/{id}/cancel` → Job, cancellation may remain pending. +- POST `/jobs/{id}/retry` → `{jobs:Job[]}` (user requested new generation, new business ID). +- Job: `{id,task_type,state,phase,version,prompt:string,parameters:object,input_asset_ids:string[],result_assets:Asset[],result:object|null,progress:number|null,queue_position:number|null,upstream_id:string|null,attempt_count:number,preemptions:number,last_preempted_reason:string|null,cancel_requested:boolean,error:null|{code,message,retriable},sync_warning:string|null,created_at:string,scheduled_at:string|null,started_at:string|null,finished_at:string|null}`. +- States: `scheduled,submitting,queued,running,collecting,cancelling,succeeded,failed,cancelled,timed_out`. Remote sync failures do not invent terminal failures; set sync_warning. Requeue is the same job ID and may go running→queued. +- Image defaults1024²/50 steps; video defaults1280×704/121frames/24fps/50steps, 1080p enhancement optional. Advanced field is exactly `num_inference_steps`. No fake generation percentage. +- ASR input accepts audio asset or video asset (CPU extract to owned WAV before upstream dispatch). Structure accepts image/video; result `subjects,scene,ocr,tags,frames?`, timestamps reflect actual sampled frames. Math result `{text}`; ASR result `{text,segments}`; composition produces video asset. + +## Events + +- GET `/events?after=0` authenticated EventSource. `Last-Event-ID` header overrides query on reconnect. +- Durable event: `id: <integer>\nevent: job.updated\ndata: {"job":Job}\n\n`. +- Other events: `asset.created` data `{asset:Asset}`, `asset.updated` same; `asset.deleted` `{id}`, `reset` asks client to refetch snapshots. Heartbeat comments do not change cursor. Stream owner-filtered; logout/expiry ends stream. +- Fetch jobs snapshot and cursor before opening stream; after reconnection refresh HTTP state as well. Ignore Job versions older than or equal to the current version. + +## Backend provider interface + +Implemented in `app/providers.py` and `app/media.py`, independent of database models. + +`Provider(settings)` methods (async): + +- `health() -> bool` +- `scheduler_status() -> dict` sanitized Scheduler above. +- `prepare_gpu_payload(task_type:str, inputs:dict, parameters:dict, assets:dict[str,Path], work_dir:Path) -> dict` validated original upstream payload `{task_type,input,parameters,timeout_seconds}`. Input paths must be within shared workspace. Preprocess video ASR as needed. +- `submit(payload:dict,idempotency_key:str) -> dict` original upstream job response; retry only same immutable payload/key. +- `query(upstream_id:str) -> dict`, `cancel(upstream_id:str) -> dict`. +- `download(upstream_id:str,index:int,destination:Path) -> None` atomic streamed output, size bounded. +- `run_cpu(task_type:str, inputs:dict, parameters:dict, assets:dict[str,Path], work_dir:Path) -> CpuResult`. +- `aclose() -> None`. +- `CpuResult` dataclass: `outputs:list[Path]`, `result:dict`, `metadata:dict`. +- `ProviderError(code,message,retriable=False)` has those attributes; no secret/path leaks in public messages. +- Settings attributes consumed: `inference_base_url,inference_api_key,inference_api_key_file,workspace_root,asset_root,job_work_root,gpu_status_path,gpu_scheduler_path,qwen_base_url,qwen_model,qwen_api_key,ffmpeg_bin,ffprobe_bin,tts_base_url,tts_model,tts_api_key,request_timeout_seconds,max_output_bytes`. +- `app/media.py`: `inspect_media(path:Path,settings)->dict` (kind,mime_type,width,height,duration_seconds); `make_thumbnail(path:Path,destination:Path,settings)->Path|None`. These are async, subprocess is fixed argv, bounded time/resources; no shell. Image validation can use Pillow. JSON/text generated outputs supported. +- `capabilities(settings)->list[dict]` returns exact DTO above. Optional speech is false unless real service configured; provider speech through OpenAI-compatible `/audio/speech` if selected later. + +Production files live under `/workspace/cmvr-visual`. Tests/explicit local preview use isolated configured roots, never implicitly access host files. CPU provider cancellation must kill/wait only its own subprocess. The coordinator supplies one task-private work directory per attempt. diff --git a/docs/design.md b/docs/design.md new file mode 100644 index 0000000..ca820de --- /dev/null +++ b/docs/design.md @@ -0,0 +1,35 @@ +# CMVR Visual 实施设计 + +用户指定 Vue 3、Element Plus、Pinia 前端与 Python、FastAPI、MySQL 后端,工程位于 `E:\workspace\hybrid\cmvr-visual`。产品借鉴即梦的集中创作入口,使用自己的品牌、组件与真实本地模型结果。 + +本文描述已实现基线。最新复核与已确认的“三分镜15秒、交互全天/批量夜间”见 [落地方案](需求复核与落地方案_20261110.md),相关功能尚待实施。 + +## 产品与能力 + +提供创作工作台、素材库、任务中心、素材理解、数学推演、成片编排。图像使用 Qwen-Image;视频使用 Wan2.2-TI2V-5B 和可选 Real-ESRGAN,严格限定当前已部署的 121 帧/24fps,约 5 秒;缺陷功能为 SDXL+Canny ControlNet,控制图不是缺陷掩膜;语音转写使用 Whisper。数学和视觉理解复用已有 Qwen3.8-27B-FP8。FFmpeg 负责 CPU 媒体探测、抽帧、转码、片段拼接、上传音轨和人工字幕。 + +声音生成按中文旁白需求先实现 Kokoro-82M CPU 本地配音,提供小贝、云希两个普通话音色和 WAV 输出;Whisper 负责语音转写。音频类型已向用户询问,尚未收到进一步偏好,音乐和音效不在本轮实现范围。能力接口不伪造音乐、热度预测、训练掩膜、15秒视频或模型内部百分比。专业数学准确率、镜头切分准确率等原方案指标不作为已验收事实。 + +## 架构决策 + +浏览器只调用业务后端。HTTP 处理登录、上传、查询、任务提交/取消与文件下载,单个用户 SSE 流负责持久任务事件及断线重放。无需双向持续交互,故不引入 WebSocket。Nginx/开发代理统一同源,使用 HttpOnly 会话 Cookie 和 CSRF 头保护写操作。 + +生产后端为独立 CPU 容器,和既有 `llmuser-workspace` 接入专用 Docker 网络,通过内部名称访问私有模型 API,保留其原有认证和 host loopback 发布限制。后端与模型容器只共享 llmuser 的 `/workspace`,素材存放专用子目录。无需修改已验收 GPU 队列、驱动、系统或其他业务;生产部署脚本不会停止已有服务。 + +GPU 工作仍只有现有模型 worker 执行。业务后端持久化请求与固定上游幂等键,再提交原样请求;网络结果不明时只能重试相同幂等键和相同请求,绝不创建替代生成。已知上游 ID 后只恢复查询,取消等待确认清理完成。抢占反映为同一业务任务 running→queued、尝试次数增加。CPU FFmpeg/Qwen HTTP 作业由业务协调器处理,不占用新 GPU worker。 + +MySQL 已接入 `192.168.28.10:3306/cmvr-visual`,按用户本次要求暂用 root;接入前确认空库,初始化六张本应用 `visual_` 表和默认管理员。之后再创建独立数据库账号。旧独立 MySQL 验收实例及样例数据保留,没有自动迁移。当前运行环境为production,但HTTP仍仅回环发布;SQLite仅用于显式本地preview/test,MySQL失败绝不自动回退。 + +## 可靠性与权限 + +任务、事件和结果导入状态存入数据库;事件和任务版本在一个事务内提交。SSE 通过 owner+递增ID查询,不长期占用数据库事务,支持 Last-Event-ID、心跳和重连同步。模型不提供进度时 progress=null;前端允许 running→queued,按 version 去重。 + +所有素材、任务、SSE 和文件内容均校验 owner。浏览器只传 asset ID,不接受服务器绝对路径、任意 URL、FFmpeg filter 或 shell 命令。文件名由服务端生成,临时文件验证后原子发布,引用中的输入不物理删除。最终产物导入后才进入素材库,视频使用带 Range 支持的鉴权文件响应。会话令牌只存哈希,密码使用加盐强哈希,凭据通过部署环境/私有文件传入,禁止进入源码或前端。 + +## 交互 + +深色创作工作台、窄侧栏、宽结果区域、集中提示词和参数面板。Element Plus 用于真实表单/上传/抽屉交互,Pinia 管理会话、创作草稿、素材及任务流。示例只能明确标记为模型验收样例;用户任务和素材库初始为空。支持上传预览、筛选搜索、素材详情、取消、再次生成、下载和将图片用于视频、将视频用于编排。 + +## 验证 + +先测试权限、上游幂等提交、断线恢复、抢占重排、取消、结果导入与 SSE 事件重放。构建检查前端,测试事件版本去重和重排状态,最后使用实际浏览器验证布局、上传、生成、视频/音频播放和下载。MySQL 连通及真实模型调用均单独报告,不将测试替身称为线上验收。 diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md new file mode 100644 index 0000000..4b6c96f --- /dev/null +++ b/docs/implementation-plan.md @@ -0,0 +1,25 @@ +# CMVR Visual Implementation Plan + +**Goal:** Deliver the requested Vue3/Element Plus/Pinia and FastAPI/MySQL creative studio connected to the server's real inference queue. + +**Architecture:** Same-origin HTTP plus durable authenticated SSE; business data in MySQL; original upstream worker remains the only GPU executor. Production web CPU containers share the isolated workspace and a private Docker network with the inference container. Local test databases require explicit mode. + +**Spec:** `docs/design.md`, shared interfaces `docs/api-contract.md`. + +## Constraints and review focus + +- Preserve existing GPU priority, serial execution, services and confinement. No database-wide deletion, driver changes, global Docker/systemd restart or public publication. +- Credentials absent from source and browser; session/owner/CSRF checks protect every mutation/content stream. +- Persist immutable upstream request/key before dispatch. No duplicate inference after timeout/restart; no job replay after known upstream ID. +- Preserve running→queued preemption, cancellation races, idempotent output import and event ordering. +- Only genuine capabilities and samples; five-second video limit, no defect mask claim, no synthetic GPU percentages. +- Detached SSE must not hold transactions or cancel inference. Reconnection uses event cursor and HTTP reconciliation. + +## Implementation + +- [ ] Backend core: write failing auth/ownership/jobs/event recovery tests; implement MySQL/explicit SQLite config, schema, auth, asset storage, job coordinator and SSE. Prove negative access and upstream lifecycle transitions. +- [ ] Providers: test actual parameter/path validation, HTTP boundary, safe subprocess and output handling; implement existing GPU API adapter, Qwen math/vision, CPU FFmpeg analysis/composition, bounded file probing and optional speech provider. +- [ ] Frontend: implement shared DTOs and HTTP client, cookie/CSRF flow, Pinia versioned job/SSE store, creation forms, real asset previews/library, task center and composition. Test requeue/version handling; build/typecheck. +- [ ] Integration: install isolated dependencies, verify OpenAPI/schema contract, run tests and MySQL connectivity if credentials arrive, package private-network deployment and environment examples. Do not auto-switch DB on failure. +- [ ] Visual and live verification: run browser, inspect desktop/mobile layouts and actual actions; perform real image/ASR or CPU generation against the model host without interrupting existing users. Record any capability or credential blocker honestly. +- [ ] Deliver source, setup guide, communication recommendation, verified URLs and acceptance report. diff --git a/docs/superpowers/plans/2026-11-10-cmvr-visual-v2.md b/docs/superpowers/plans/2026-11-10-cmvr-visual-v2.md new file mode 100644 index 0000000..618b3a4 --- /dev/null +++ b/docs/superpowers/plans/2026-11-10-cmvr-visual-v2.md @@ -0,0 +1,183 @@ +# CMVR Visual V2 Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development or superpowers:executing-plans to implement this plan task-by-task. Checkboxes track implementation, not this planning review. + +**Goal:** 在现有正式库与模型服务上交付可靠提交、三分镜15秒工作流及交互/夜间批量调度。 + +**Architecture:** 保留单FastAPI业务协调器、MySQL任务/事件与既有独立GPUworker。先升级受版本约束的上游调度/停止协议,再开放工作流;资源池new_gpu/cpu_media/qwen_http分别最多1个执行。MySQL只由业务进程产生有序领域事件,不直接扩成多API实例。 + +**Tech Stack:** Vue3、Element Plus、Pinia、TypeScript;Python/FastAPI、SQLAlchemy async、MySQL8、Alembic;既有vLLM-Omni/Diffusers/Whisper、共享Qwen HTTP、CPU FFmpeg/Kokoro。 + +**Spec:** [实施方案V2](../../实施方案V2_20261110.md)。接口、状态与配额冲突时以Spec为准;旧R1–R12继续纳入下述任务。 + +## Global Constraints + +- 主工程根目录 `E:\workspace\hybrid\cmvr-visual`,下文无前缀的路径均相对此根。 +- `GPU/`前缀指另一个现有源码根 `C:\Users\Administrator\Documents\ChatGPT\大模型部署到服务器\llm-services`,部署到既有 `/workspace/projects/llm-services`;不创建另一套GPU worker。 +- 正式MySQL及admin已存在,不重复初始化、不覆盖密码、不迁移旧验收样例。 +- 三段各120个成片帧,最终360帧、24fps;保持多镜头定义。 +- Asia/Shanghai `[21:00,次日08:00)`;外部用户优先、新GPU任务全局1个。 +- 现有Qwen批量必须先通过单请求停止确认;未通过就关闭该项,不能杀共享服务PID。 +- 不读写其他项目数据库,不全局重启Docker/驱动,不修改宿主时钟;秘密不进入源码、命令行参数或测试输出。 +- 每任务先写有意义的失败测试,再最小实现、回归、独立审查并提交;只有对应验收通过才勾选。生产操作只在任务12执行。 + +## Review Focus + +1. 响应丢失与进程/DB故障不产生未经明确意图的新计算——任务3/4。 +2. 08点与claim、崩溃、时钟回拨竞争,不越界派发且不假称释放——任务5/6。 +3. 旧Run/旧Execution晚到,不能覆盖新成片或停止新进程——任务4/8。 +4. 部分镜头失败、短源、跨镜头字幕和超长旁白仍能得到确定结果——任务7/8。 +5. 已有正式数据升级、恢复及跨账号访问保持一致——任务1/9/10/12。 + +--- + +## Task 1:基线核验、迁移机制与恢复点 + +**Files:** 新建 `backend/alembic.ini`、`backend/alembic/env.py`、`backend/alembic/versions/001_legacy_baseline.py`、`scripts/schema_preflight.py`、`scripts/backup_checkpoint.py`、`backend/tests/test_schema_migrations.py`;修改 `backend/app/database.py`、`backend/requirements.txt`。 + +**Interfaces:** `schema_preflight(connection) -> SchemaDiff`;`check_schema_revision(connection, supported: set[str]) -> None`;备份清单包含checkpoint_id、应用/上游/schema版本、文件哈希、上游job IDs、执行状态和时间。 + +- [ ] 在隔离MySQL8.0.36复制当前六表基线,测试 `test_baseline_matches_existing_schema` 与 `test_drift_refuses_stamp`:准确基线可stamp001,少唯一约束或DATETIME精度不对必须拒绝,用户和任务行不变。 +- [ ] 实现显式迁移入口和只检查的生产启动;空库upgrade,已有库先核验再stamp;include_object只管理本应用表。 +- [ ] 写 `test_checkpoint_rejects_live_execution`、`test_restore_preserves_upstream_identity`:无停止ACK不能宣称静态恢复点;恢复不得把旧ID误接到独立前进的队列。 +- [ ] 隔离库实跑upgrade、失败中断修复、镜像兼容回退与备份恢复;输出schema diff、行数与校验结果。未演练前不做正式DDL。 + +## Task 2:冻结V2 DTO、表和媒体规范 + +**Files:** 新建 `backend/app/contracts_v2.py`、`backend/alembic/versions/002_workflow_execution.py`、`backend/tests/test_contracts_v2.py`;修改 `backend/app/models.py`、`frontend/src/types.ts`。以现有六表为起点新增Spec第3节表;素材标签使用 `visual_asset_tags` 关联表。 + +**Interfaces:** `WorkflowSpec`、`DraftDTO`、`RunDTO`、`StepDTO`、`ExecutionDTO`、`BatchDTO`、`BatchItemDTO`、`SchedulingEnvelope`;新输入 `extra=forbid`,输出完整标识/模式/版本/等待原因。关键spec固定为: + +```json +{ + "schema_version": 1, + "shots": [ + {"key":"shot_1","prompt":"...","image_asset_id":null,"parameters":{"seed":42}}, + {"key":"shot_2","prompt":"...","image_asset_id":null,"parameters":{"seed":43}}, + {"key":"shot_3","prompt":"...","image_asset_id":null,"parameters":{"seed":44}} + ], + "profile":"landscape_1080_v1", + "render":{"fps":24,"total_frames":360,"fit":"contain","audio":null,"subtitles":[],"template_version":"plain-v1"} +} +``` + +profile由服务器编译成冻结的模型默认参数/版本,横版1280×704→1920×1056内容→1920×1080画布;竖版对应704×1280→1056×1920→1080×1920。字幕字段start_frame/end_frame/text;audio字段以Spec为准。客户端不提交路径、父Job关系或宿主信息。 + +- [ ] `test_rejects_unknown_scheduling_and_timeline_fields`、`test_requires_exact_three_shot_keys`、`test_preset_compilation_is_frozen`:多/少镜头、重复key、非法帧区间和未知参数失败;已接受快照不随后续默认值变化。 +- [ ] 实现002的新增/回填,保留旧hash算法及旧attempt计数;所有旧Job回填interactive,历史Execution明细保持“未知/未提供”。 +- [ ] 在MySQL与SQLite测试执行同一DTO/唯一约束规则;生产schema指纹与新版本检查通过。 + +## Task 3:端到端提交幂等和额度原子性 + +**Files:** 新建 `backend/app/submissions.py`、`backend/tests/test_submissions.py`、`frontend/src/stores/submissions.ts`、`frontend/src/stores/submissions.test.ts`;修改 `backend/app/jobs.py`、`frontend/src/api.ts`、提交入口。 + +**Interfaces:** `accept_submission(session, owner_id, operation, key, payload_schema, body) -> Submission`;`GET /api/submissions/{key}?operation=...`;前端 `submitOrRecover(operation, immutableBody) -> resource`,使用按用户隔离的本地持久存储。 + +- [ ] 测试服务器commit后丢响应,客户端刷新/重试仍返回同批Job、同资源引用;同key改body返回409,复用不重复扣配额;GET404后原POST迟到也不重复。 +- [ ] 实现版本化canonical body哈希及旧v1幂等记录回填;原Job键继续能恢复。显式retry/Run创建也要求幂等键,不能仅保护第一层POST/jobs。 +- [ ] 前端持久化发送前意图,提供“确认提交状态”与“明确新建”两种行为;离线编辑不触发自动生成,退出用户清除敏感缓存。 +- [ ] 后端对应pytest、前端submissions.test通过;注入延迟/重复HTTP的集成断言只有一组实际子任务。 + +## Task 4:Execution、结果manifest与安全取消 + +**Files:** 新建 `backend/app/executions.py`、`backend/app/artifacts.py`、`backend/tests/test_execution_recovery.py`、`backend/tests/test_artifact_reconcile.py`;修改 `coordinator.py`、`assets.py`、`media.py`、`providers.py`、`events.py`。 + +**Interfaces:** `begin_execution(session, job_id) -> Execution`;`accept_manifest(session, execution_id, fence_token, manifest) -> bool`;`request_control(session, job_id, desired_state, expected_execution_id) -> ControlResult`;`reconcile_artifacts(...) -> ReconcileReport`。 + +- [ ] 先固定R2/R3故障:provider执行后写DB失败、manifest写前后崩溃、commit已成功但客户端收到异常,断言不自动重新provider调用、不误删已提交文件。 +- [ ] 明确Job可领取状态集合,paused/needs_attention不执行、collecting只导入;当前Execution与fence不匹配的回调拒绝;CPU可信manifest仅恢复归档。 +- [ ] 固定R5:重复cancel只发一次停止并等待清理;当前media/TTS shield规则保留。控制先提交但已经领取的任务允许在途停止,不再领取后续步骤。 +- [ ] 所有状态变化与领域事件同事务;SSE drain/20秒Uvicorn graceful与45秒Docker宽限配套测试。保持长连接重启时必须在强杀前完成清理。 + +## Task 5:GPU上游V2协议与队列资格 + +**Files:** 新建 `GPU/llm_services/scheduling.py`、`GPU/tests/test_scheduling_v2.py`;修改 `GPU/llm_services/api.py`、`store.py`、`worker.py`、网站`providers.py`与协议契约。 + +**Interfaces:** `GET /capabilities`;v2 `Submission.scheduling: SchedulingEnvelope`;`PUT /jobs/{id}/control`请求/ACK含command_id、control_version、expected_execution_id;`claim_eligible(now_utc, policy) -> Lease|None`;`evaluate_window(now_utc, mode, closed_windows) -> Eligibility`。 + +- [ ] 旧上游不支持v2时batch明确不可用;同key更改mode409;旧key仍返回原ID;所有未知新字段不能静默忽略。 +- [ ] 测试窗口 `[21:00,08:00)`、最后30秒禁新batch、07:59领取08点spawn被挡、关闭窗口回拨不重新开放;不改宿主时钟,注入Clock。 +- [ ] 原子claim跳过不合格队首,交互/批次/用户按Spec公平规则;子任务与重试mode继承,HTTP伪造父ID或通过retry降级拒绝。 +- [ ] 以desired_state+hold而非外部直接改running实现控制;cancel高于pause、终态不可逆,旧command不影响新Execution。原124项基线范围及新增协议测试回归。 + +## Task 6:独立监管、CPU窗口与Qwen前置验证 + +**Files:** 修改 `GPU/admin/gpu_guard.py`、`GPU/llm_services/gpu_policy.py`、`GPU/tests/test_gpu_guard.py`;新建 `GPU/tests/test_deadline_guardian.py`、`backend/app/resource_policy.py`、`backend/tests/test_resource_policy.py`、`scripts/probe_qwen_control.py`;修改 `tts/app.py`及生命周期测试。 + +**Interfaces:** `register_execution(identity, policy) -> LeaseAck`;`stop_execution(execution_id, fence_token) -> StopAck`;`resource_plan(task_type, input_kind) -> list[PhaseRequirement]`;`acquire_phase(execution_id, phase_key) -> SlotLease`。PhaseRequirement含phase_key与pool,分阶段checkpoint后释放再取得下一槽。探测报告必须区分“连接关闭”与“服务端计算结束ACK”。 + +- [ ] 用自有隔离进程夹具测试cgroup/UID、PID重用、starttime/boot_id、旧fence和任意宿主PID均不能误杀;worker07:59:59退出后监管仍对已登记batch截止。 +- [ ] 清理ACK加清理后的新GPU快照才释放槽;旧快照、尾进程、监控丢失、超15秒未ACK保持blocked。外部占用时不要求总显存回旧基线。 +- [ ] 将CPU编码/Kokoro pause和cancel分开,作业/子进程带Execution身份;按Spec实现TTS私有异步execution v2、control ACK和音频获取,原同步交互接口兼容。同ID重试不再次启动,登记/监管许可前不运行模型。batch停止依然保留已完成步骤,三个资源池各1,未知Qwen请求只挡新的Qwen请求。 +- [ ] 对现有Qwen的request_id/abort/结束确认及低优先能力只做获准的可控验证;没有证据输出false并禁用Qwen batch。不得通过停止共享进程让测试“通过”。 +- [ ] 视频ASR抽音与GPU转写、视频理解抽帧与Qwen请求分别计入对应槽;两任务交错不出现cpu_media并发2或槽互等死锁。暂停发生在阶段间时不运行下一阶段。 + +## Task 7:15秒媒体规范化 + +**Files:** 新建 `backend/app/timeline.py`、`backend/tests/test_timeline_v2.py`;修改 `media.py`、`providers.py`、`GPU/llm_services/adapters.py`的工作流增强配置与相应测试。 + +**Interfaces:** `compile_timeline(spec, owned_assets) -> TimelinePlan`;`compose_workflow(plan, work_dir, control) -> CpuResult`;`inspect_video_track(path) -> {frames,fps,width,height,duration}`。保留现有普通video.compose兼容接口,V2走独立白名单。 + +- [ ] 真实FFmpeg夹具:三个121帧24fps源各取120帧;结果视频流精确360帧、24fps、15秒,容器尾差≤0.10秒,横/竖版分别验证。 +- [ ] 119帧短源拒绝,不能借音轨时长或冻结补帧通过;超长音轨默认拒绝,显式3–18秒裁切通过;10秒音轨offset120通过/121拒绝,15秒音轨任何正偏移拒绝;短音轨补静音。 +- [ ] 字幕跨120/240帧边界、end=360通过,负数/越界/非法控制语法拒绝;片头在360帧内叠加。文件解码/规格为硬门槛,疑似黑帧或静帧作为可人工复核的质量提示。 +- [ ] 明确增强不先烧黑边,contain/cover各测试真实内容与输出画幅。全过程固定FFmpeg argv,不接收滤镜脚本、外部URL或字体路径。 + +## Task 8:Draft/Run/Step服务和父子SSE + +**Files:** 新建 `backend/app/workflows.py`、`backend/app/workflow_engine.py`、`backend/app/batches.py`、`backend/tests/test_workflows_v2.py`、`backend/tests/test_workflow_races.py`;修改 `main.py`、`events.py`、`dto.py`和`jobs.py`。 + +**Interfaces:** Spec第5.3节接口;`create_run(session, owner_id, draft_id, expected_version, revision, mode) -> RunSnapshot`;`advance_run(session, run_id) -> None`;`snapshot_run(session, owner_id, run_id) -> {run,steps,jobs,cursor}`;所有service沿用调用方事务,不嵌套申请当前进程的DB单元锁。 + +- [ ] 两标签页Draft冲突409,旧revision不能提交;运行期间草稿变更不变更Run快照。 +- [ ] 第二镜头失败仅它新增Job,抢占两次仍为同Job新Execution;compose失败不再生成三镜头;模式和政策继承。needs_attention未确认无残留执行不能重试,safe_to_retry后才允许显式新尝试。 +- [ ] 修改成功镜头产生新Run并复用其它已验证素材;旧合成晚到不改current_run_id/output;输入hash和引用检查覆盖裁切、音轨、字幕、模板变更。 +- [ ] 父取消与claim/完成/导入竞争;已领取者停止ACK后终态,未领取者不启动;pause/resume只处理手工hold,不解除夜间或维护限制。新增workflow.updated/draft.updated完整version快照,乱序与重连不倒退。 +- [ ] Batch有独立DTO、成员表、查询/control及batch.updated;Run和独立Job均能归属,刷新恢复混合成员且每批最多1个活动成员;安全清理完成后的失败项不堵其它项,全部终态混合结果为completed_with_errors,批次取消不删除成功产物。 + +## Task 9:账号、机器调用与额度/回收 + +**Files:** 新建 `backend/app/tokens.py`、`quotas.py`、`retention.py`、`maintenance.py`、`backend/tests/test_tokens_quotas.py`、`backend/tests/test_retention.py`;修改 `auth.py`、`assets.py`、`models.py`和对应增量迁移。 + +**Interfaces:** 本人改密、admin用户列表/停用/撤销会话、owner机器Token创建/撤销;`reserve_budget(session, owner_id, operation) -> Reservation`;`collect_garbage(dry_run=True) -> GCReport`;维护状态阻止新写入与claim而保留查询。 + +- [ ] 默认admin在私有验收仍能用初始密码登录且不被重启重置;公网preflight要求先在私有入口改密,未完成不能先暴露登录入口。停用/改密撤销会话,停用给任务加admin_suspend并停止,重新启用不自动重跑;不能停用最后一个有效管理员。Token仅哈希、到期/撤销生效并关闭其事件流,scope不授管理权限。 +- [ ] 配额事务内预留、复用幂等键不重复扣;batch mode权限、跨owner资产、每池并发及入口限流覆盖直接HTTP绕过测试。 +- [ ] 上传在multipart解析前限制流量并预留空间;输出/临时空间纳入预算,达到水位停止接新任务。实际超预留需原子追加预算,失败仅保留可恢复结果,不重生成。 +- [ ] SQL分页和标签关联索引;删除与引用互斥,非终态/commit不明文件不GC;事件过期cursor返回reset。先dry-run和隔离数据测试,禁止首次上线直接删除历史文件。 + +## Task 10:Vue工作流与持久草稿 + +**Files:** 新建 `frontend/src/stores/workflows.ts`、`draftPersistence.ts`及对应测试、`frontend/src/views/WorkflowView.vue`、`BatchView.vue`、`AccountView.vue`;修改router、api、types、Workbench/Compose/Tools/Tasks/Assets与capabilities。 + +**Interfaces:** 消费任务2/8/9 DTO;Pinia提供 `saveDraft(expectedVersion)`、`startRun(revision,mode)`、`recoverSubmission(key)`、`applyRunSnapshot(version)`,步骤Job事件必须匹配当前selected_job。 + +- [ ] 测试保存中/已保存/提交待确认/已接受区别,跨页配音回填和刷新不丢草稿;版本冲突保留本地内容,离线不自动提交。 +- [ ] 父任务按镜头完成数和合成阶段显示,展开Job/Execution记录;旧Run迟到不盖新版,window/manual/resource/cleanup理由可读。 +- [ ] batch在协议/Qwen能力不足时禁用对应项;前端受限参数与后端错误field一致,标签确认合并,历史分页和收藏/来源筛选。 +- [ ] 账号/改密/Token入口使用既有Element Plus规范;桌面1440×1000和手机390×844测试表单、抽屉、播放与seek;不新增外部CDN依赖。 + +## Task 11:完整故障和兼容性回归 + +**Files:** 新建 `backend/tests/test_acceptance_v2.py`、`GPU/tests/test_upgrade_compatibility.py`、`qa/browser-v2.cjs`;更新原服务/网站契约、README和验收矩阵。 + +- [ ] 在隔离MySQL8.0.36而非仅SQLite跑任务1–10;对比现有52后端基线、TTS/前端测试及原GPU服务测试,无跳过地报告媒体和迁移覆盖。 +- [ ] 使用可控Clock、假上游和自有Linux子进程遍历Spec控制竞争表;不得改宿主时间、伪造生产guard状态或让他人作业承担压力测试。 +- [ ] 兼容矩阵覆盖新网站/旧上游拒绝batch、旧幂等恢复、老前端字段/未知字段处理、旧镜像schema支持范围;覆盖保留期reset。 +- [ ] 浏览器断网/刷新、多标签、两用户、父子SSE乱序和媒体边界;保留无密码、Cookie、Token的报告。 + +## Task 12:受控发布与真实验收 + +**Files:** 修改 `compose.yaml`、`backend/Dockerfile`、`deploy/nginx.conf`;新建 `deploy/release-checklist.md`,输出版本、迁移、恢复和真实模型记录。 + +- [ ] 先确认维护开关、恢复点、独立监管健康;冻结镜像/依赖/模型revision。按Spec顺序做兼容上游、迁移、API、前端,未通过gate保持维护。 +- [ ] 缩窄API挂载并验证原子替换状态文件仍更新;Uvicorn20秒退出/容器45秒;重建执行容器后监管allowlist匹配真实ID/UID/镜像再开admission,新API IP的Nginx解析可恢复;不全局重启其它服务。 +- [ ] 先真实小规格三镜头验证控制链,再选空闲资源执行一次冻结默认规格360帧交付;记录排队/冷加载/推理/增强/归档而非承诺原GPU·秒。夜间与抢占测试使用自己的受控作业,单独记录观察到的停止ACK延迟。 +- [ ] 配置用户提供的HTTPS域名或受信隧道后验证Secure Cookie、SSE、Range、机器Token和限流;用户决定的独立DB账号按后续授权创建,不能擅改共享root密码。 +- [ ] 完成至少一次库+文件+上游checkpoint恢复演练。发布只在各门槛实际通过后记为完成,代码合并/测试数量不能替代上线验收。 + +## Commands and completion records + +开发环境:在`backend/`执行 `.venv/Scripts/python.exe -m pytest tests -q`;在`frontend/`执行 `pnpm test`、`pnpm build`。Linux媒体/迁移/监管与GPU仓库测试在各自隔离环境执行。只运行本任务对应检查,新的失败或依赖变更才扩大回归。 + +每任务记录:变更文件、失败→通过的测试、MySQL/媒体/真实GPU分别覆盖什么、剩余阻塞、回退版本。审查批准后再提交相应变更;当前清单保持未勾选,表示**尚未实施V2**。 diff --git a/docs/实施方案V2_20261110.md b/docs/实施方案V2_20261110.md new file mode 100644 index 0000000..d39ea0c --- /dev/null +++ b/docs/实施方案V2_20261110.md @@ -0,0 +1,222 @@ +# CMVR Visual 实施方案 V2 + +日期:2026-11-10,Asia/Shanghai。状态:**方案复审完成,待实施;本轮未修改运行中的应用或服务器**。 + +本方案承接[上一版复核](需求复核与落地方案_20261110.md),保留其中R1–R12和业务质量专项;以下规则解决上一版尚未明确的实施边界。发生冲突时以本方案为准。已完成的正式MySQL接入和默认管理员不重复执行。 + +## 1. 结论与一期范围 + +技术上可落地,现有Vue3/Element Plus/Pinia、FastAPI/MySQL、HTTP+SSE与独立GPU队列继续复用。上一版仍缺少上游调度协议、状态竞争、依赖失效、迁移回退和资源边界,不能直接按其概述并行开发。 + +用户已经确认:三段约5秒分镜合成15秒多镜头成片;交互创作全天使用空闲卡,批量任务仅21:00–08:00;新GPU任务全局最多一个,外部用户优先。保持这些决定。 + +一期验收范围:现有八种单任务能力、可靠提交与恢复、账号维护、持久草稿、三分镜工作流、夜间批量、标签/历史检索和受控对外API。基础质量检查使用固定文件规则;LoRA、数学专业指标、真实缺陷mask、镜头切分、热度预测和音乐生成仍按独立数据专项评测,不作为一期已具备能力。 + +**一个必须先验证的条件:**现有Qwen HTTP服务没有已实现的单请求取消及停止确认。关闭HTTP连接不能证明服务端GPU已停止。本期先验证该能力;未通过时,数学/视觉理解保持交互可用,Qwen批量明确标记不可用,不承诺其08:00硬截止,也不杀共享服务进程或重部署其模型。其它自管GPU与CPU批量可独立交付。如果必须一期同时包含Qwen夜间批量,则此验证是该项的放行阻塞。 + +## 2. 再次审查发现的九类遗漏 + +| 遗漏 | 为什么阻碍实施 | 本版决定 | +| --- | --- | --- | +| 上游不识别调度字段 | 当前Submission无scheduling,额外字段默认忽略,队列仍FIFO | 升级v2协议和能力协商;batch不允许降级为旧行为 | +| 数据身份与attempt含义混用 | 抢占重启、用户重新生成、修改草稿会混成同一次尝试 | 分离Draft、Run、Step、Job显式尝试、Execution运行尝试 | +| 暂停/取消/完成竞争 | HTTP直接改running可能与worker冲突;旧结果可能覆盖新版本 | 控制意图与执行状态分离,用执行代次和事务提交裁决 | +| 重做后依赖失效未定义 | 镜头变了,旧合成晚到仍可能显示为最新成片 | 成功镜头修改产生新Run,合成绑定有序输入哈希 | +| 夜间范围与进程故障缺约束 | 只在网页检查挡不住08点越界或worker崩溃后的runner | 所有batch计算步骤受窗口约束,独立监管确认停止 | +| 草稿和父子事件缺契约 | 多标签覆盖、重连失真、父任务显示过早完成 | 乐观版本锁、一致快照、workflow.updated及阶段计数 | +| 15秒只有时长描述 | 音频可撑长容器,横竖画幅、字幕和片头也会改变时长 | 固定视频轨360帧24fps,明确时间轴、音轨与画幅 | +| 正式库迁移/恢复只有口号 | 已有6表且无Alembic版本;DDL失败不能当普通事务回滚 | 校验基线后stamp、只增不删迁移、两类回退与联合备份 | +| 对外API、配额、回收边界缺数字与权限 | 自动客户端可冒充交互,积压与临时文件可无限增长 | 服务端分类、有限队列和空间预留、机器令牌及引用回收 | + +代码证据:前四项分别涉及现有 `llm_services/api.py:21`、`store.py:260/308`、`worker.py:294`,以及网站 `models.py`、`coordinator.py`、`jobs.py:212`;当前[API契约](api-contract.md)尚未定义工作流对象。该结论来自只读源码复审,不代表这些新功能已经实现。 + +## 3. 一致的数据模型和幂等规则 + +### 3.1 对象关系 + +`Draft → Run → Step → Job(一次显式尝试)→ Execution(一次真实运行)`。 + +| 对象 | 主要字段和职责 | +| --- | --- | +| `visual_drafts` | owner_id、name、kind、spec、revision、version、current_run_id、updated_at。revision只在内容变化时增加,version对记录变化增加;草稿可编辑 | +| `visual_workflow_runs` | draft_id/revision、owner_id、不可变spec_snapshot/spec_hash、execution_mode、batch_id、state、desired_state、version。运行不随草稿编辑变化 | +| `visual_batches` / `visual_batch_items` | owner、不可变项规范、desired_state、state、version;成员唯一(batch_id,item_index),target_kind=job/run、target_id。Run和独立Job关联成员,workflow子Job从Run继承,不能自行换批次 | +| `visual_workflow_steps` | run_id、step_key、kind、dependencies、semantic_input_hash、selected_job_id、state。首期固定shot_1/shot_2/shot_3/compose;配音/转写先在声音页生成素材后放入草稿,不隐式扩展新节点 | +| 现有 `visual_jobs` 扩展 | run_id/step_key、batch_id/batch_item_index、显式尝试序号、execution_mode、policy_version。Run也有batch_id/batch_item_index;子Job由Run继承这些只读关系。一次用户重试产生新Job;自动让卡保持原Job和原上游ID | +| `visual_job_executions` | job_id、execution_id、ordinal、phase_key、resource_pool、fence_token、upstream_attempt、lease_id、state、start/end、结果manifest引用。每次真实启动另记一次;不把旧attempt_count兼作镜头版本 | +| `visual_submissions` | owner_id、operation、幂等key、payload_schema、body_hash、resource_refs、accepted_at。与创建资源在一个事务提交,唯一约束(owner,operation,key) | +| `visual_asset_refs` | 对Run快照、输入、复用产物和导出文件的引用;与现有JobAsset共同决定是否可物理回收 | + +保留旧字段和历史数据;对已完成旧任务不伪造不存在的execution明细。旧request_key/hash按v1算法恢复,新请求存payload_schema=2;升级不能让原幂等键取不到旧任务。 + +### 3.2 三种重试必须分清 + +- **响应丢失/网络重试:**同owner、同operation、同key和同一版本化请求,返回原资源;参数变化返回409。客户端发送前持久保存key与不可变body;离线恢复不自动启动新生成。 +- **外部抢占/夜间暂停:**同Job、同上游ID,新Execution;只重算被打断的当前步骤。 +- **用户明确重试失败步骤:**在同Run/Step创建新Job及新上游key,旧成功步骤继续复用。 + +不承诺计算exactly-once:抢占会丢弃当前推理进度,进程崩溃和HTTP超时也可能产生不明确结果。承诺的是逻辑提交幂等、产物按当前执行代次发布一次,不能确定的CPU/HTTP执行进入needs_attention,不偷偷再执行。 + +CPU计算完成先写原子结果manifest,含execution_id、输入哈希、输出相对路径/大小/哈希,再登记数据库。若结果可验证就仅恢复导入;没有可靠manifest且执行已发生,则等待明确重试。资产commit结果不明时保留文件并对账,不在异常处理里无条件删除。 + +### 3.3 修改与旧结果 + +修改已成功镜头、配音、字幕或画幅后创建新Run,可复用输入哈希和模型配置完全一致、归属正确且文件校验通过的素材;不修改旧Run快照。 + +合成input_hash覆盖:有序视频内容哈希、裁切范围、画幅/适配方式、音轨范围、字幕帧区间、模板版本。旧Run晚到结果只进入历史;只有 `Draft.current_run_id == completed_run_id` 时才更新当前成片。每个步骤也只接受selected_job及匹配fence_token的结果。 + +删除素材先软删除;已被运行引用的文件保留。新Run不能选择已删除素材,旧Run可用已固定引用完成。管理员也不在普通接口中绕过owner读取他人素材;管理角色和内容归属是两套权限。 + +### 3.4 状态的唯一含义 + +Run使用第5节的八种状态;Step使用waiting/ready/running/paused/blocked/succeeded/cancelled,当前Job失败使Step进入blocked。Job保留现有十种状态并增加pausing/paused/needs_attention;cleanup_pending是phase与资源状态,不另作“已停止”的终态。Execution使用allocated/running/stopping/exited/results_ready/unknown,另记结束原因。 + +调度查询改为明确的可领取状态集合,不能用“不是终态”来决定重执行。collecting只做导入;paused和needs_attention不会调用provider。window/resource hold不会改用户desired_state,只有手工暂停改变用户意图;恢复条件为desired_state=run且所有hold均已解除。 + +## 4. 调度、暂停和资源回收协议 + +### 4.1 网站、上游、监管各自负责什么 + +网站MySQL持久保存用户意图、工作流、输入快照和事件;既有上游Store/worker负责唯一GPU领取与进程执行;独立监管负责自己的进程身份核验、执行截止和释放确认。保留一个FastAPI业务协调器,显式定义三个资源池:new_gpu=1、cpu_media=1(FFmpeg/Kokoro)、qwen_http=1;后两者不创建自管GPU租约。Qwen未知请求阻塞新Qwen请求,不把无关联CPU合成一起堵住;不能将它笼统称为CPU推理。 + +资源按阶段取得,不只按task_type分类。视频转写为 `extract_audio(cpu_media) → transcribe(new_gpu)`,视频理解为 `sample_frames(cpu_media) → describe_frames(qwen_http)`;数学为qwen_http,独立配音/合成为cpu_media。各阶段完成持久checkpoint后释放自己的槽,再取得下一槽,不持有一个槽等另一个槽。GPU runner内部必要的编解码由GPU容器的CPU配额约束并随该Execution整体停止,不再嵌套领取cpu_media。 + +上游新增 `GET /capabilities` 返回 `protocol_version=2`、支持的scheduling/pause/execution_ack/result_manifest能力;网站不满足最低版本时禁止batch并给出可读错误。新Submission明确 `extra=forbid`,增加独立的: + +`scheduling={execution_mode, principal_id, batch_id?, run_id?, step_key?, policy_version}`。 + +这些字段由网站验证/继承,并纳入v2幂等请求,不混入模型parameters。旧v1请求保留恢复路径。不得接受浏览器传入宿主PID、容器ID或任意截止时间。 + +### 4.2 窗口和队列 + +窗口为Asia/Shanghai的 `[21:00,次日08:00)`,以UTC存储绝对时间及window_id;执行计时使用monotonic。claim、spawn前和运行循环重新校验资格。已关闭window_id持久记录,时间回拨不得重新打开;检测到明显时钟偏移先暂停batch admission并告警。 + +interactive定义为一次受限单任务(图片1–4张或单个其它任务),或一次三分镜Run;多Run/清单批次只能由batch入口创建。服务端给子任务、重试和重做继承mode,客户端不能覆盖父关系或借普通retry降为interactive。 + +GPU原子领取时跳过不具执行资格的任务,白天batch队首不能堵住interactive。夜间建议每完成4个interactive GPU作业后,若有合格batch则给1个batch作业;用户之间轮转,批次内部FIFO。该策略只在领取时生效,不因新交互任务打断自己的当前作业;外部占卡规则始终优先。 + +无GPU时保持queued,不生成真实运行attempt、不消耗执行超时。返回blocked_reason/blocked_since/next_eligible_at,不虚构预计完成时间。 + +### 4.3 控制意图与状态 + +持久 `desired_state=run|pause|cancel` 与 `hold_reasons`(window/manual/resource/maintenance)分开保存。HTTP只提交控制意图,不能提前把正在运行的进程改成paused。恢复窗口只解除window hold,不解除manual或maintenance hold。 + +| 竞争或控制 | 固定规则 | +| --- | --- | +| 已有持久终态 | 不逆转;完成后取消返回原终态并提示未取消 | +| 取消与暂停同时发生 | cancel优先;清理结束后才能cancelled | +| 取消先提交、尚未领取 | 不派发新的步骤 | +| 已领取后取消 | 可有已在途执行,必须发停止并等待ACK,不再领取下一步 | +| 暂停先提交、完成尚未登记 | 当前Execution结果按暂停裁决,不发布过期结果;清理后排队 | +| 完成先提交、随后暂停 | 保留成功素材,暂停后续步骤 | +| 旧回调迟到 | execution_id、fence_token或控制版本不匹配即拒绝,不能停止/覆盖新执行 | + +API新增内部控制命令 `PUT /jobs/{id}/control`,含唯一command_id、expected_execution_id、control_version及desired_state。命令幂等;不存在当前执行时只登记意图。worker清理后返回带相同执行代次的ACK。已有 `/cancel` 保持用户取消终态语义,不能拿它冒充夜间暂停。 + +### 4.4 08:00与故障 + +所有标为batch的计算步骤受窗口限制:自管GPU、Whisper、CPU编码、Kokoro,以及经验证可停止的远端HTTP推理。08:00后禁止新计算;运行中的步骤请求停止并释放,下一窗口恢复未完成步骤。状态同步、清理、文件归档可以白天继续,它们不得启动新的模型或编码。 + +初始配置:窗口检查0.5秒,独立监管检查1秒,最后30秒不启动新的batch执行,清理ACK等待15秒;这些是待实测的工程默认值。截止触发不等于显存已经释放;超15秒未确认则cleanup_pending/blocked并告警,不能宣称零延迟或继续领取新任务。 + +worker在启动计算前登记带执行代次的本地lease/deadline,并取得监管确认。API或worker卡死后,监管仍能终止已登记的自有执行。监管只接受固定允许容器/cgroup/UID,并核验PID、starttime、boot_id、execution/fence;不从可写metadata接受任意宿主PID。CPU/TTS的batch子进程同样需要单执行标识与停止确认。 + +停止确认需进程清理ACK和清理动作之后的新监控快照证明自己的GPU PID已消失;进程组为空、TTL过期或显存数值下降都不能单独当释放证明。若外部用户正在用卡,不要求显存回到原基线,只确认自有资源消失。异常时保留全局槽并blocked,不进行双运行。 + +Kokoro私有服务增加execution v2能力:`POST /internal/executions/{id}/speech`登记后返回202,`GET /internal/executions/{id}`查询,`PUT .../control`停止并返回执行代次ACK,`GET .../audio`仅在完成后取WAV;全部沿用私有Bearer认证。登记、deadline、结果manifest在本地持久化,确认监管接管前不启动模型子进程;同ID不同请求409。现有同步 `/v1/audio/speech` 保持交互兼容,网站未检测到v2能力时不把同步断连当成batch停止。FFmpeg启动前也使用同样的登记/许可门槛。 + +上述承诺覆盖网站/API登记的任务;它不能替代整个服务器所有用户的统一准入系统。现有Qwen请求若没有request_id、abort与结束ACK,则batch能力保持关闭;交互调用继续复用且单独限额。 + +## 5. 工作流、时间轴与前后端契约 + +### 5.1 一期固定工作流 + +三镜头提示词和参考图在提交前确认。若需要Qwen辅助写脚本,先作为交互步骤完成并写入草稿;不在未验证可取消的batch中隐式调用Qwen。 + +Run状态:queued/running/paused/blocked/cancelling/succeeded/cancelled/failed。blocked/step_failed表示需要重试某一步,不能自动合成;failed用于不可恢复错误,用户结束使用cancel。succeeded/cancelled/failed均为终态。 + +三个shot步骤依次完成,每个输出经验证达到目标画幅、至少120帧。compose只能读取三个当前selected_job的已发布视频。失败镜头只重做该Step;合成失败只重做compose。needs_attention只有在确认无残留执行、safe_to_retry=true后才允许用户显式重试;仍未知时返回cleanup_pending,不以点击按钮代替停止证明。草稿变更不影响运行中的Run。 + +### 5.2 画幅和音视频边界 + +- 横版生成1280×704,超分内容保持1920×1056,最终画布1920×1080;竖版生成704×1280,超分内容1056×1920,最终画布1080×1920,24fps。工作流增强步骤保留原内容比例,避免先烧入黑边再无法实现cover;明确generation_size、enhancement_target、canvas和fit=contain|cover,界面展示补边或裁切,不默默拉伸。 +- 每镜头规范化为120帧,总360帧。使用视频流实际解码帧数、avg_frame_rate、时间基准验证,不能只看容器duration。短源失败,不用黑帧、重复末帧或长音轨凑足时间。 +- 最终视频轨15.000秒,音频AAC编码尾差使容器时长允许±0.10秒;帧率、分辨率和解码检查同时通过。15秒模板在360帧内叠加或占用原镜头,延长版单独计时。 +- 音轨字段为asset_id、source_start_ms、source_end_ms、offset_frame、short_policy=silence。毫秒/偏移均为非负整数,源区间有序且不越过源音频;还须满足 `(source_end_ms-source_start_ms)*24 ≤ (360-offset_frame)*1000`,否则invalid_timeline。18秒旁白默认拒绝无提示截断,显式选3–18秒且offset=0后通过;10秒音轨offset=120通过、121拒绝,短音轨剩余部分补静音。 +- 字幕采用全片帧区间 `[start_frame,end_frame)`,满足 `0≤start<end≤360`;统一模板字体与样式,禁止任意FFmpeg/ASS指令。首期允许人工编辑,不把Whisper块边界当逐词对齐。 + +### 5.3 API与错误 + +浏览器仍使用Cookie+CSRF和同源SSE,不引入WebSocket。所有变更语义明确的POST(包括运行、重试和重做)要求Idempotency-Key。 + +| 接口 | 关键约定 | +| --- | --- | +| `POST/GET/PATCH /api/workflows` | 管理Draft;PATCH带If-Match版本,冲突409,返回当前version且保留本地未保存内容 | +| `POST /api/workflows/{id}/runs` | 指定draft_revision、预期Draft版本和mode;原子创建快照、步骤及提交记录,返回更新后的draft以及run/steps/jobs/cursor | +| `GET /api/workflow-runs/{id}` | 同一事务的一致父子快照和cursor | +| `POST /api/workflow-runs/{id}/cancel` | 持久取消意图;保持cancelling直到子执行停止 | +| `POST /api/workflow-runs/{id}/pause`、`/resume` | owner控制手工hold;resume不解除window/resource/maintenance hold,均需要幂等键 | +| `POST /api/workflow-runs/{id}/steps/{key}/retry` | expected_run_version和target_job_id;仅当前失败或已确认safe_to_retry的尝试可重试,已取消父Run不可恢复,模式继承 | +| `POST /api/batches` | 最多100个Run/单任务规范,服务端固定batch;整批先校验再创建,子项用batch_id+item_index派生key | +| `GET /api/batches`、`GET /api/batches/{id}` | owner分页列表、成员/计数/当前执行项及一致snapshot+cursor | +| `POST /api/batches/{id}/control` | desired_state=run/pause/cancel,幂等键+expected_version;继承到成员,不清除成员独立的manual hold | +| `GET /api/submissions/{key}?operation=...` | 仅owner可查询;404不证明在途POST没被接受,恢复仍复用原key | + +成功镜头重做或参数变化通过修改Draft并新建Run处理,避免同时存在“修改旧Run”和“创建新Run”两套语义。普通Job retry拒绝直接操作workflow子Job,要求使用Step接口。 + +错误码补齐:draft_version_conflict、idempotency_conflict、step_not_retryable、dependency_changed、invalid_timeline、upstream_protocol_incompatible、batch_capability_unavailable、quota_exceeded、storage_insufficient、maintenance、cleanup_pending。字段错误返回field定位;409为版本/语义冲突,422为输入,429为额度,503为暂不可服务;返回可恢复条件,不默认提示重新生成。 + +Batch默认遇独立项失败继续其它项;失败Run保持blocked以便只重试其失败Step。其它可运行项全部结束后若仍有需要处理的成员,Batch为blocked;用户重试后继续。用户放弃某项使用该项cancel,全部成员已终态且有失败/取消时Batch为completed_with_errors;全成功才succeeded。批次取消不撤销已成功产物。Batch状态另有queued/running/paused/cancelling/cancelled。 + +SSE新增 `workflow.updated`、`draft.updated`、`batch.updated`,完整DTO有各自version;与其状态在同一DB事务写入现有owner流。忽略旧版本/旧selected_job事件,重连后HTTP刷新当前Run/Batch;cursor过旧时reset。显示镜头完成数和当前阶段,全部镜头完成仍需合成,不能提前显示整流程100%。 + +草稿先保存后提交;离线允许编辑,不悄悄排队自动生成。两标签页冲突不静默覆盖,退出用户清除本地敏感缓存,服务器草稿按owner读取。 + +## 6. 正式库升级、恢复和容量 + +### 6.1 已有六表如何纳入Alembic + +建立001基线,精确对应当前六表及索引/唯一约束/字符集和DATETIME(6)。已有库先生成schema指纹并核对,完全匹配才stamp 001;不匹配停止并输出差异,不盲目stamp head。空库直接upgrade。之后002起只增表/可空字段/索引,分批回填并校验,再收紧约束;只管理本应用表,不能自动删除其它表。 + +生产启动只校验schema支持范围,不自动create_all/upgrade;不满足则不启动协调器。Alembic stamp只记录版本,不替代迁移。[Alembic命令说明](https://alembic.sqlalchemy.org/en/latest/api/commands.html#alembic.command.stamp) + +MySQL DDL可能隐式提交,升级失败不能当成普通事务rollback即可恢复。优先使用兼容性增量变更和修复迁移;只回滚镜像须确认旧版能读当前schema且新任务功能关闭。不能安全读时保持维护状态,使用同一恢复点的库+文件备份在隔离环境恢复验证后切换,不自动downgrade删新数据。[MySQL DDL提交说明](https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html) + +### 6.2 联合备份和上游队列 + +维护模式先禁止新写入与派发,结束/暂停自己的活动计算并确认ACK,关闭SSE、停止业务协调器、上游worker及回收器后取快照;只操作本项目服务。备份MySQL应用表、assets/jobs/state、上游SQLite(使用其backup/checkpoint方式)与完成manifest/必要输出,另加受保护配置和版本/校验清单。 + +恢复时不能让恢复出的旧上游ID指向仍独立前进的当前队列:先校验同一checkpoint、对账IDs、execution代次和文件,启动监管后再开放调度。历史不明确的CPU执行转needs_attention,不自动重算。每日库备份可先做逻辑备份,但上线前至少完成一次联合恢复演练;保留7个每日点和4个每周点,容量预留计入专用目录。 + +### 6.3 建议初始配额(配置项,实施时校准) + +交互每用户最多8个未结束GPU子Job、每分钟6次创建命令,最多1个活动交互Run。单batch最多100项,每批最多1个成员(Run或独立Job)进入执行,其余可排队;每用户未结束叶任务最多500、全局最多2000。三个资源池各自全局1槽,各池每用户不超过1个活跃执行。创建前事务内检查配额,复用同幂等提交不二次扣额。 + +单文件仍512MiB;每用户保留素材100GiB,业务数据总预算2TiB。专用卷剩余低于max(50GiB,5%卷容量)或工作区预算不足时拒绝新计算/上传;为已接受任务预留预估输出与临时空间,实际超限终止自己的作业并明确失败。数字为起始配置,不是已验证产能,不允许耗尽整个服务器共享盘。 + +待定提交记录/非终态任务不自动过期删除;排队不计执行超时。已确认的临时同步采用1/2/4…30秒退避。执行状态不明的网络错误不据此新建任务;明确可重试的本地失败最多自动重试2次,OOM/参数错误不盲目重跑。抢占与窗口暂停单独计数。 + +SSE事件保留30天,最小可重放cursor单独记录;早于它的客户端收到reset,而不是悄悄漏事件。成功作业的可再生成中间文件保留7天,失败/中断尝试保留14天;资产原件、活动执行、当前Run引用和提交结果不明的文件不按年龄直接删除。回收器先对账、引用检查、标记与宽限,再物理删除;删除与新引用必须互斥,回收过程中不会重新引用待删文件。已清理结果的幂等提交保留tombstone,旧key返回410资源已清理,不能重新当新任务执行。 + +## 7. 管理、外部调用与发布 + +默认admin初始密码保持用户指定;补 `must_change_password`、本人改密、用户列表/停用、撤销会话。公开部署要求改密后才开放计算和Token创建;私有验收模式可保留初始化用法,不能靠客户端参数关闭公网限制。停用用户撤销认证并给未完成任务加admin_suspend hold,停止其计算;重新启用不自动重跑,需明确恢复。保留成功素材,不允许停用最后一个有效管理员。初始化不得覆盖已有账号;MySQL暂用root按用户原决定,后续另建专用账号时限制本库与实际来源,不改其它业务账号。 + +互联网发布前,先在私有入口完成默认管理员改密,再开放公网,不能把已知初始密码暴露后等待首次改密。公网preflight检查该状态、专用数据库权限、HTTPS/Secure Cookie、登录节流、额度、备份与恢复;未满足保持私有验收。IP限流只采信配置过的反代链,不能信任任意X-Forwarded-For。网站状态区分配置存在、模型在线、调度可用和等待资源。活性检查与readiness分离,后者包含schema、协调器心跳和协议兼容;无空闲GPU不是应用不健康。 + +外部机器调用增加按owner的可撤销API令牌,仅保存哈希、一次展示明文,配置到期时间和jobs/asset最小scope;默认只能batch,interactive另行授权并共用额度。令牌明文不进入URL、事件payload或前端构建产物;机器订阅SSE须有events:read并走Authorization头,撤销/到期结束流。浏览器继续Cookie+CSRF和原生EventSource。令牌不能调用管理员建用户/改权限接口。原登录会话方式保留为兼容调用路径。 + +容器镜像和模型revision/配置固定入部署清单;前后端与上游协议兼容范围明确。维护窗口采用“备份→上游兼容升级→迁移→业务API→前端→受控验收→开放写入”,失败关闭新功能而非静默降级。若重建执行容器,先在关闭admission时核对并更新监管allowlist中的真实容器ID/UID/镜像,再恢复计算。Nginx测试API容器换IP后的解析恢复,保留同源SSE、Range、鉴权与静态路由修复。 + +## 8. 实施顺序与验收 + +| 里程碑 | 依赖和交付 | 必须通过 | +| --- | --- | --- | +| M0 | 协议/取消能力验证、数据基线与可恢复备份 | 旧请求恢复不重复;Qwen batch明确支持或禁用;恢复点可对账 | +| M1 | R1–R5、幂等提交、Execution/manifest、资产对账、停机 | 响应丢失、DB提交结果不明、重启、重复cancel、旧结果迟到故障注入 | +| M2 | 上游v2、窗口/监管/公平领取、CPU暂停 | 21/08边界、worker07:59:59硬杀、时钟变化、尾进程/旧快照、全卡长期忙;无双运行 | +| M3 | Draft/Run/Step、父子事务与API、三镜头媒体规范化 | 失败镜头单独重试、旧Run不覆盖、父取消竞争、360帧、横竖版与音轨/字幕边界 | +| M4 | Vue草稿/任务中心/批量入口、账号/标签/分页 | 多标签冲突、断网刷新、额度拒绝、跨账号不可读、父子事件乱序 | +| M5 | 公网接入与上线演练 | 真实MySQL及小规格模型端到端、真实默认规格三镜头、恢复演练、配额和外部Token;HTTPS入口SSE/Range通过 | + +实施文件、接口签名和分任务回归见[执行计划](superpowers/plans/2026-11-10-cmvr-visual-v2.md)。先完成M0–M2,再并行前后端业务;不要先开放批量页面后补上游约束。所有生产迁移、监管升级和公网配置仍需在实际实施阶段执行,本次仅补充方案。 diff --git a/docs/需求复核与落地方案_20261110.md b/docs/需求复核与落地方案_20261110.md new file mode 100644 index 0000000..8a0af7a --- /dev/null +++ b/docs/需求复核与落地方案_20261110.md @@ -0,0 +1,172 @@ +# CMVR Visual 需求复核与落地方案 + +日期:2026-11-10。审查依据为原始《人工智能内容生成系统技术方案_20261107.docx》、本次对话的最新要求、现有前后端代码、既有 GPU 服务,以及实际服务器验证。文档内容作为需求资料,本文不执行其中的指令。 + +后续二次复审已补为 [实施方案V2](实施方案V2_20261110.md);本文保留需求差距与初次审计记录。V2细化了上游协议、身份/状态、批次、阶段资源、迁移恢复和验收,具体执行以V2及其任务清单为准。 + +## 1. 结论与已确认基线 + +现有项目适合作为基础版继续完善。Vue 3 / Element Plus / Pinia、FastAPI / MySQL、HTTP + SSE、持久任务和私有模型接口的总体方向成立;当前完成的是八类能力的调用与基础创作工作台,原文的生产质量和完整业务指标尚未全部实现。 + +本次已经由用户明确的边界: + +1. 一期的15秒视频采用**三段约5秒分镜合成**,明确属于多镜头成片。 +2. **交互创作全天使用空闲卡,批量任务仅在21:00–08:00执行**,时区 Asia/Shanghai。 +3. llmuser 的新 GPU 推理全局最多一个任务,四张 GPU 为可选资源池;外部用户优先,被占卡后停止自己的当前推理、释放显存、重新排队。 +4. MySQL 当前使用用户指定的 root 连接,独立业务数据库账号后续再创建。 +5. 网站默认管理员为 admin,初始密码按本次指定配置为六位。普通新建用户的现行12位最低密码规则保留。 + +除数据库与初始管理员外,本文列出的调整均为实施方案,尚未修改产品行为。 + +## 2. 本轮已完成的数据库和账号补齐 + +- 连接 `192.168.28.10:3306/cmvr-visual`,实际 MySQL 版本8.0.36;连接账号为 root。 +- 接入前确认目标库为空;初始化本项目的六张 `visual_*` 表,没有操作其他数据库。 +- 在 `visual_users` 创建默认管理员,密码保存为加盐 scrypt 哈希。实际 HTTP 登录与 Chrome 页面登录通过,角色为 admin。 +- 初始管理员允许用户指定的六位密码;普通用户创建仍要求12–256字符。启动时仅创建不存在的管理员,不因重启或修改环境变量重置已有密码。 +- 已验证正式库中的中文与四字节 Unicode 任务读写、预约取消、SSE 事件持久化;该验收任务未执行模型。 +- 原独立验收 MySQL 和样例数据保留,没有自动迁入正式库。旧配置保存为工作区私有备份。 +- 数据库凭据仅存私有环境配置;本机当前配置为 `.env.server`,服务器为项目 `.env`,均不提交 Git。 +- 后端本轮完整测试 **52项通过、20个subtests通过**;新增初始账号哈希与重启不重置回归先失败后通过。 + +证据:[正式库验证](../qa/mysql-integration-20261110.json)、[实际页面](../qa/mysql-admin-login.png)。网站仍只发布服务器回环18193,通过本机 SSH 隧道8000访问;连接正式数据库不等于已经开放互联网。 + +初始弱密码按用户要求保留。本期上线准备应补本人改密入口,公网发布前将它作为初始化密码完成更换,并将常驻 root 数据库连接换为专用账号;本轮没有修改 MySQL root 密码或创建额外数据库账号。 + +## 3. 原文要求与当前差距 + +| 能力 | 当前实际实现 | 尚未满足的原文要求 | 落地处理 | +| --- | --- | --- | --- | +| 图像 | Qwen-Image、尺寸、批量1–4张、提示词和种子 | 风格LoRA、系列一致性校验、13 GPU·秒与70%可用率验收 | 一期保留基础生图;建立业务提示词评分集,风格方案在样例评测后定 | +| 视频 | 文生/首帧图生约5秒,Real-ESRGAN可选增强 | 单段15秒、自动质量筛选、TensorRT+FP8、8路并发 | 已确认一期做三分镜15秒;其余作为独立性能/质量专项,移除8路承诺 | +| 数学 | 现有Qwen返回可读解答 | 符号计算、单位校验、作图、题型集和步骤/答案正确率 | 继续复用Qwen;二期加入受限计算工具和教学评测集 | +| 缺陷样本 | SDXL+Canny结构约束,生成图和边缘控制图 | 缺陷位置/形态控制、真实缺陷掩膜、下游召回提升8个百分点 | 先标明条件样本;真实工业训练数据另建标注与检测A/B流程 | +| 素材结构化 | 均匀抽帧最多12帧、画面理解、OCR、Whisper转写 | 每5秒抽帧、镜头切分、人物/场景/情绪/景别标签、标签检索闭环及质量评测 | 补时间/场景抽帧、标签应用与编辑、检索索引,单独评测镜头和标签 | +| 成片合成 | FFmpeg裁剪、直切、音轨、人工字幕 | 脚本关联、片头片尾、转场、热度模型与65%准确率 | 一期围绕三分镜成片补工作流和模板;热度模型等待历史业务数据 | +| 声音 | Whisper转写、Kokoro中文配音 | 精确字幕对齐、音乐/音效等扩展未实现 | 一期明确中文旁白与ASR,补字幕编辑;音乐不纳入本期承诺 | +| 生产作业 | 单任务预约、GPU空闲选择、外部抢占重排 | 每日夜间窗口、批次/分镜持久编排、暂停恢复、容量与质量报表 | 按已确认的交互/批量两种模式补调度 | + +精确视频型号应统一为 `Wan2.2-TI2V-5B`。当前约5秒限制是已部署服务的边界,需要通过新增编排完成15秒交付,不将其描述为模型的理论时长上限。[Wan官方仓库](https://github.com/Wan-Video/Wan2.2) + +现有 `Qwen/Qwen3.8-27B-FP8` 是原生视觉语言模型,可继续承担文本推演和图像/视频帧理解。应记录实际运行权重版本与配置,并使用业务题目、OCR和标签集验证替代效果;单次数学和图片调用不能证明92%/95%等指标。[官方模型卡](https://huggingface.co/Qwen/Qwen3.8-27B-FP8) + +模型服务内部继续按能力使用 vLLM-Omni、vLLM core、Diffusers 和现有 Qwen 服务,网站统一业务 API。当前 SDXL+Canny 使用 Diffusers;不能将“统一接口”写成所有模型都由 vLLM core 执行。[Omni支持表](https://docs.vllm.ai/projects/vllm-omni/en/v0.32.0/models/supported_models/)、[Diffusers SDXL ControlNet](https://huggingface.co/docs/diffusers/v0.40.0/api/pipelines/controlnet_sdxl) + +Real-ESRGAN 当前确实执行神经网络超分,再缩放/补边到目标画幅;默认1280×704内容适配到1920×1056并上下补边为1920×1080。需要把成品分辨率、原片分辨率和超分方式分别记录,不能宣称为原生1080p生成。 + +## 4. 代码审查发现与优先级 + +P1为正式业务或公网前优先解决,P2为本期工作流/运维完善,P3为体验优化。故障注入均使用隔离内存数据库,没有对线上任务注入故障。 + +| 编号 | 等级 | 问题、触发与证据 | 最小改动与验收 | +| --- | --- | --- | --- | +| R1 | P1 | 前端每次调用submit换幂等键。POST落库但响应丢失后再次点击会新建昂贵任务。[api.ts:44](../frontend/src/api.ts#L44);后端已支持复用同键 | 持久保存一次提交的key和不可变payload;结果不明时复用。断网、刷新、恢复后仍是同批任务;明确再次生成才换key | +| R2 | P1 | CPU执行失败且失败状态写库也失败时,done task异常被忽略,仍running的记录下一轮可再次执行。隔离故障注入得到执行次数2。[coordinator.py:157](../backend/app/coordinator.py#L157)、[195](../backend/app/coordinator.py#L195) | 增加持久attempt与运行时丢失任务守卫;不明确的执行转待确认/中断,不能自动当新执行。故障注入确认未经显式重试不重复执行 | +| R3 | P1 | 资产commit结果不明时外层异常无条件删目录,存在“库中有行、文件已删”的窗口;这是源码确认的故障窗口,尚未完整注入复现。[assets.py:106](../backend/app/assets.py#L106)、[141](../backend/app/assets.py#L141) | commit开始后结果不明保留暂存文件;数据库与文件对账后清理。复用pending记录前检查文件;恢复只重导入,不重生成 | +| R4 | P1 | SSE长连接使Uvicorn更新时等待,Docker45秒后强停;本轮切库实际观察到了这段等待。[Dockerfile](../backend/Dockerfile)、[events.py](../backend/app/events.py)、[compose](../compose.yaml) | Uvicorn graceful timeout约20秒,小于Docker45秒;配合drain与协调器清理。保持SSE连接更新,验证未进入强杀且恢复任务不重复 | +| R5 | P2 | 协调器每轮再次cancel正在清理的CPU task,可打断一般provider异步清理。[coordinator.py:184](../backend/app/coordinator.py#L184) | 取消信号只发一次,等待清理确认再终态。现有media与TTS已有shield,不能据此宣称当前FFmpeg必然遗留进程 | +| R6 | P2 | 成片草稿存组件ref,去声音页配音再返回就丢片段、字幕、裁切。[ComposeView.vue:18](../frontend/src/views/ComposeView.vue#L18) | Pinia管理并按用户持久保存草稿;跨页和刷新不丢,显式新建才清空 | +| R7 | P2 | 素材列表先读取全库后内存分页;标签也在Python过滤,数据库全局单元锁会放大阻塞。[assets.py:164](../backend/app/assets.py#L164)、[database.py:25](../backend/app/database.py#L25) | SQL计数/分页;标签关联表或MySQL索引;owner/状态/时间复合索引。较大素材库下查询不拖住SSE与提交 | +| R8 | P2 | 当前只有创建用户API,没有本人改密、用户停用/会话撤销及管理页;登录无节流且密码计算位于数据库全局锁内。[auth.py](../backend/app/auth.py)、[router.ts](../frontend/src/router.ts) | 补改密、建用户/列表/停用、会话撤销;密码计算移出DB锁,账号/IP登录限流;沿用admin/user与owner权限 | +| R9 | P2 | UI可输入不满足步长/Canny关系的值、超2000字配音、超24片段,依赖提交后报错。[WorkbenchView.vue](../frontend/src/views/WorkbenchView.vue)、[ToolsView.vue](../frontend/src/views/ToolsView.vue) | 共用参数schema/校验函数、字数与时长提示;错误定位到字段,后端继续保留最终校验 | +| R10 | P2 | 理解标签未应用到原素材;工具历史从混合最近48条筛选,旧记录易被挤出;“已配置”可能显示为“就绪” | 增加标签确认合并、按任务类型分页、区分配置/在线/可执行;加入故障断连与旧数据测试 | +| R11 | P2 | API整个workspace可写;没有schema升级、文件回收和容量控制闭环。[compose.yaml:22](../compose.yaml#L22)、[database.py:31](../backend/app/database.py#L31) | 缩窄挂载、模型密钥/状态目录只读;Alembic迁移;用户容量/任务上限、对账回收、联合备份恢复演练 | +| R12 | P3 | 收藏无筛选入口,上传与生成作品混合查找 | 复用素材库增加favorite/origin服务端筛选,无须另建复杂项目管理系统 | + +## 5. 架构取舍 + +### 方案A:保留现有单实例协调器,推荐本期采用 + +继续使用一个FastAPI进程、一套MySQL持久任务/事件表和既有独立GPU队列。先补上述可靠性与业务工作流。改动范围较小,适合当前全局仅一个新GPU推理任务的吞吐,不新增Redis/Celery依赖。 + +```mermaid +flowchart LR + U[Vue3 创作与管理页面] -->|HTTP 操作/文件| A[FastAPI 单实例业务层] + A -->|SSE 事件| U + A --> D[(MySQL 业务/任务/事件)] + A --> W[持久分镜与批量协调器] + W --> G[既有GPU串行队列] + G --> P[四卡空闲资源池 / 单任务租约] + W --> Q[现有Qwen文本视觉服务] + W --> C[CPU FFmpeg / Kokoro] +``` + +HTTP适合上传、任务命令和结果下载,SSE负责状态、让卡与结果事件,保留Last-Event-ID重放和HTTP快照恢复。本期没有持续双向音视频交互需求,WebSocket不增加必要能力。 + +### 方案B:API与业务Worker分离,作为后续扩展 + +当需要频繁无影响发布、多个API实例或多节点执行时再拆分。当前数据库单元锁仅在进程内;直接增加API workers或拆出协调器,会破坏现有事件提交顺序保证。MySQL自增ID分配顺序不等于事务提交顺序,SSE游标可能越过晚提交事件。拆分前必须落地事务outbox与单发布器,或数据库级序列锁,并明确全局唯一调度租约。本期不直接启用多worker。 + +## 6. 一期的具体实现 + +### 6.1 可靠性与账户 + +先完成R1–R5的故障恢复和取消修复;新增的attempt/checkpoint字段使用Alembic迁移,不用create_all代替升级。保留正式库现有用户、素材和任务;上线前做库与文件联合备份,并验证回退。 + +补本人改密、管理员创建/查看/停用普通用户、撤销会话,普通用户继续只访问自己的素材和任务。默认管理员用于初始化。后续创建仅授权本库的数据库业务账号,来源限制按实际Docker网络连接地址配置,不改其他业务root账号。 + +### 6.2 三分镜15秒工作流 + +新增持久workflow与step记录,现有Job通过workflow_id/step_key/attempt关联。工作流保存三段提示词、参考图、顺序、种子、画幅和模型配置快照,子任务保持各自幂等键。 + +1. 用户填写或审阅三个分镜,每段目标5秒,可以共用参考图。 +2. 顺序提交三个Wan子任务,由同一GPU队列串行执行。 +3. 三段完成后,CPU FFmpeg各裁取5秒;视频轨按24fps、总360帧输出15秒成片。 +4. 可选中文配音、人工/校正字幕与模板,输出成片及参数清单。15秒版片头片尾在已有360帧内叠加或占用已有镜头时长;额外插入的延长版另计时长和验收。配音时长超出画面时应提示调整文稿、语速或音轨裁切范围。 +5. 失败镜头可单独重新生成;成功镜头保留。网络重试仍复用原attempt键,明确重做才创建新attempt。 +6. 取消父工作流后不再启动新步骤;运行中的子任务清理后才确认取消,已有成功素材保留。 + +验收应检查视频轨360帧、24fps、15秒;封装音频允许合理编码尾部误差,并检验无黑帧、花屏、字幕缺字和音轨错位。三个镜头之间的身份/风格一致性需人工评分,不用拼接成功替代质量验收。 + +### 6.3 交互与夜间批量 + +在业务任务和上游GPU任务元数据中新增 `execution_mode=interactive|batch`,与模型推理parameters分开;当前模型参数白名单保持有效。 + +| 情形 | 规则 | +| --- | --- | +| 交互任务 | 全天可进入空闲卡队列 | +| 批量任务 | 仅Asia/Shanghai 21:00–次日08:00具备执行资格,白天明确显示等待窗口 | +| 同用户有多个等待任务 | 交互优先选取,批量之间按批次公平和创建顺序;不因新交互请求无条件打断已经执行的自身任务 | +| 其他用户开始占卡 | 停止自己的当前GPU推理、等待显存回收后重排,同一上游任务ID继续跟踪 | +| 到08:00仍有批量执行 | 暂停当前批量步骤并清理/释放资源,保留已完成步骤,下一窗口重新执行未完成步骤;白天不能以“恢复中”为由继续批量生成 | +| 夜间中断/抢占 | 当前模型推理进度可能丢失;已完成镜头不重跑。这里的恢复是工作流步骤级,不承诺保存扩散latent或模型计算断点 | + +不能简单用现有 `/cancel` 模拟夜间暂停:cancel是终态,同幂等键会返回已取消任务。应在既有GPU worker补可重排的窗口资格与暂停原因,并让被时间窗口挡住的批量任务不阻塞交互任务;网页显示等待时间与原因。 + +“立即让卡”实际包含检测、停止、CUDA回收延迟。现有方案为软件机会调度;要达到所有用户绝对无争用,需要全体任务统一准入,超出本应用单方面可保证的范围。本期记录并测量让卡延迟,不承诺零毫秒抢占。 + +Qwen文本/视觉通过已存在的HTTP服务共享,不是将其常驻GPU分配给llmuser;该服务的每请求优先级由自己的入口调度决定。若要求Qwen请求同样严格低优先级,应追加网关限额/队列设计,不能仅靠检测Linux GPU进程区分HTTP用户。 + +### 6.4 创作与素材闭环 + +将编排草稿、提示词、参考素材与字幕按用户持久保存,跨声音页、素材页和刷新后可恢复。素材理解结果提供“应用标签”操作,合并而非覆盖人工标签;人物、场景、情绪、景别采用可编辑词表。 + +历史记录按任务类型分页;素材支持名称、标签、来源、收藏筛选。第一阶段先做好这些确定性检索,再评估向量检索,避免引入尚无验收需求的额外数据库。 + +### 6.5 公网前的部署准备 + +配置HTTPS域名或受信穿透入口,Secure Cookie、同源代理、登录限流和用户资源配额。保留SSE不缓冲、文件鉴权与Range。API仅挂业务数据可写,模型密钥和原服务状态目录只读;原状态采用原子替换时须挂目录,避免单文件绑定读到旧inode。 + +增加任务积压/最老等待时间、协调器心跳、显存/让卡事件、磁盘余量与服务在线状态。建立任务/中间文件保留期和“先对账、后回收”策略;引用中的素材不随意删除,CPU工作目录与上游输出副本不能无限保留。 + +## 7. 原方案应重写的性能和验收口径 + +- 四张可选卡不等于同时四卡工作。本期全局一个新GPU任务时,11小时窗口的理论上限是11 GPU·小时;仍按80%有效时间假设,仅为8.8 GPU·小时,外部占用和抢占还会降低。不能沿用35.2 GPU·小时/夜、8路并发和月产12部承诺。 +- 并发数不能直接把单任务耗时除以8作为该任务延迟。分别报告单段延迟、完成吞吐与GPU占用,明确计量分母。 +- 旧记录为包含加载的墙钟:Qwen-Image1024²/50步约96.6秒;Wan121帧/50步含超分约291.9秒;SDXL768²/30步约22.6秒。它们规格不同、包含加载,不能直接与原文GPU·秒目标判定达标/不达标或推导15秒产能。 +- 以固定权重revision、GPU、分辨率、步数、帧数和增强配置测试,分别记录排队、冷启动加载、推理、超分、归档、让卡浪费、P50/P95和显存峰值。 +- 原文操作系统和依赖版本属于需要修订的部署基线;应记录现有稳定宿主/容器实际版本,不为了匹配旧文字直接重装或降级正在承载其他业务的服务器。若Ubuntu为强制合同项,则另做迁移与回退计划。 + +业务指标需要独立数据:图像可用率/风格评分、视频可用率/闪烁/失败率、数学按题型的步骤和答案评审、镜头边界与标签标注集、缺陷真实留出集上的检测A/B、历史业务数据上的热度分类。准确率、失败率和样本量应在测试前约定,不以官方通用榜单或小样例代替。 + +## 8. 分阶段交付和验收门槛 + +| 阶段 | 交付 | 放行条件 | +| --- | --- | --- | +| 0,已完成 | 正式MySQL、默认管理员、私有配置与回归 | 实际登录、哈希、正式库读写与SSE验证通过 | +| 1,先做 | 幂等/attempt/资产提交/取消/停机修复,账号维护、数据库迁移与基础限额 | 网络结果不明不重复生成;失败状态写库异常不重复执行;不出现数据库有记录而文件被误删;更新能清理退出;权限/改密/限流通过 | +| 2,一期核心 | 三分镜15秒、持久草稿、夜间批量窗口、标签和历史检索 | 360帧15秒视频;只重做失败分镜;21/08边界正确;批量暂停不堵交互;外部占卡后让行重排;跨页刷新不丢草稿 | +| 3,质量专项 | 字幕对齐、风格LoRA、数学工具、缺陷标注、镜头切分、自动质检 | 各自业务数据集、指标口径和人工评审通过,才写入已交付能力 | +| 后续数据项目 | 热度预测、音乐/音效、连续长镜头、业务Worker拆分 | 需求、训练数据、资源成本和迁移方案另行确认 | + +建议从阶段1开始实施,在阶段2完成后形成可试用的一期交付。原文研究型指标逐项评估进入阶段3;现有可运行代码和已有模型继续复用,不重建整个项目。 diff --git a/docs/验收报告.md b/docs/验收报告.md new file mode 100644 index 0000000..941cd19 --- /dev/null +++ b/docs/验收报告.md @@ -0,0 +1,51 @@ +# CMVR Visual 验收记录 + +后续更新(2026-11-10):现已接入用户指定的正式MySQL并创建默认管理员,见 [实际接入记录](../qa/mysql-integration-20261110.json)。后端新增初始账号回归后52项通过。下面保留的是**数据库切换之前的功能验收基线**,其中“账号待提供”“独立验收库”等均为当时状态;样例数据未迁入正式库。最新差距与后续计划见 [需求复核方案](需求复核与落地方案_20261110.md)。 + +验收日期:2026-11-10。代码位于 `E:\workspace\hybrid\cmvr-visual`;服务器源码位于受限工作区 `/workspace/projects/cmvr-visual`。 + +## 交付与访问 + +- Vue 3 + Element Plus + Pinia;Python FastAPI + SQLAlchemy async + MySQL;HTTP 提交与文件传输,SSE 实时事件。 +- 已启动 API、中文配音、Nginx 前端三个独立容器。仅 Nginx 发布宿主 `127.0.0.1:18193`,当前本机 SSH 隧道访问入口为 `http://127.0.0.1:8000`。隧道断开后按 [README](../README.md) 重建;网站容器继续运行。 +- 本机私有 `.env.preview` 中的 `ADMIN_USERNAME`、`ADMIN_PASSWORD` 为临时验收登录信息,不进入源码、镜像或报告。 +- **当前使用独立 MySQL 8.0.36 验收实例。正式 `192.168.28.10:3306/cmvr-visual` 的专用账号仍未提供,未连接、未修改正式库。**页面持续显示“验收环境 · MySQL”。互联网域名、HTTPS 或穿透入口尚未配置。 + +## 真实调用 + +以下八类任务均通过网站业务 API 创建,使用真实服务执行并归档到 MySQL 与素材库,无模拟生成。 + +| 能力 | 实际验证 | +| --- | --- | +| 图像生成 | Qwen-Image,512×512、10步;成品可下载、上传和预览 | +| 首帧视频 | Wan2.2-TI2V-5B,512×288、25帧、4步,使用真实图片首帧 | +| 条件样本 | SDXL+Canny ControlNet,512×512、6步,输出生成图与控制图 | +| 中文配音 | 本地 CPU Kokoro-82M,两个普通话音色均通过 HTTP 生成有效 WAV;小贝样例8.45秒,云希样例3.4秒 | +| 语音转写 | Whisper 将上述配音转为中文,与测试文本内容相符 | +| 数学推演 | 现有 Qwen 文本服务得到 `17×23=391`;浏览器实际提交 `2+3` 得到 `5` | +| 素材理解 | 现有 Qwen 视觉服务返回图片主体、场景、标签与 OCR 结构 | +| 成片编排 | CPU FFmpeg 拼接两个真实视频片段,加入配音和中文字幕,输出640×360、24fps、约2.12秒成片 | + +以上低分辨率、低步数任务验证功能连接,不代表默认生成质量、生产吞吐或耗时承诺。当前生成视频上限为121帧/24fps,约5秒;配音不是音乐生成;Canny 控制图不是缺陷真值掩膜;数学结果没有专业正确率或形式化证明保证。 + +## 自动化与浏览器 + +- Linux 后端:**51项通过,20个 subtests 通过,无跳过**;包含实际 FFmpeg 媒体处理、幂等恢复、取消与归档竞争、队列公平、归属权限和 SSE 重放。 +- TTS:**12项通过**;包含等待取消、重复取消、进程组清理、响应发送失败清理以及子进程不继承服务密钥。测试框架有1条 Starlette TestClient 依赖弃用提示,不影响本次断言。 +- 前端:**12项通过**;TypeScript 类型检查与生产构建通过。合计75项测试,subtests 另计。 +- 真实业务脚本:21项断言通过,八类任务成功;收到81条真实事件;验证上传、修改、收藏、标签、删除、预约取消、显式重试、CSRF、跨账号不可读与视频 Range。 +- 正式 Nginx 构建浏览器验收:1440×1000、390×844,共35条页面记录与34张截图;无页面脚本错误、HTTP错误、重试或横向溢出。 +- 桌面与手机图片可解码;视频/音频四次播放和定位均成功;捕获10次 Range 206。冷缓存任务直达链接会实际读取任务详情。 +- 实际 UI 数学任务的 SSE 连续经过 submitting → running → collecting → succeeded,版本1至5;流连接1次、断连0次。 +- Nginx 配置检查通过;首次 SSE 注释约0.094秒到达本机;首页与素材库路由不缓存,静态哈希文件保留长缓存;同源 CSP 生效。 +- 实际设置 `max_tokens=1` 时返回明确 `output_truncated`,不发布不完整答案为成功产物。 + +最终页面截图见 [桌面](../qa/browser-desktop-create-image.png)、[手机](../qa/browser-mobile-create-image.png)、[手机任务详情](../qa/browser-mobile-task-detail.png);真实成片字幕帧见 [字幕帧](../qa/composition-frame.png)。 + +原始记录:[服务器测试](../qa/server-tests.json)、[业务调用](../qa/e2e.json)、[浏览器](../qa/browser.json)、[代理](../qa/proxy-check.json)、[截断处理](../qa/truncation-check.json)、[部署与文件校验](../qa/deployment.json)。 + +## 资源与后续接入 + +新 API 与配音容器均无 GPU grant。GPU 推理继续使用原 `llmuser` worker、四卡空闲选择与外部用户优先守护;网站不重部署驱动、既有模型或其他用户服务。原 `llmuser-workspace` 容器 ID 保持不变,GPU 守护仍运行。CPU 配音仅挂载自己的模型只读目录、work、cache、tmp,不挂载推理服务密钥所在项目。 + +正式接入尚需数据库专用用户名和密码。收到后按 [正式配置说明](../README.md#正式-mysql-配置) 修改私有配置、初始化本应用 `visual_*` 表并重新连接验证;不会自动搬迁或覆盖数据。公网使用须提供 HTTPS 域名/反代或用户选择的受信穿透入口,设置 Secure Cookie 并保留 SSE 与鉴权文件代理行为。 diff --git a/frontend/.env.example b/frontend/.env.example new file mode 100644 index 0000000..a173b71 --- /dev/null +++ b/frontend/.env.example @@ -0,0 +1 @@ +VITE_API_PROXY=http://127.0.0.1:8000 diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..14e05e1 --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,2 @@ +<!doctype html> +<html lang="zh-CN"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><meta name="theme-color" content="#0e1116"/><meta name="description" content="CMVR Visual,本地多模态视觉创作工作台。"/><title>CMVR Visual · 视觉创作台
diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..715d82d --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,32 @@ +{ + "name": "cmvr-visual-frontend", + "private": true, + "version": "1.0.0", + "type": "module", + "scripts": { + "dev": "vite --host 127.0.0.1", + "typecheck": "vue-tsc --noEmit", + "build": "vue-tsc --noEmit && vite build", + "test": "vitest run", + "preview": "vite preview --host 127.0.0.1" + }, + "dependencies": { + "@element-plus/icons-vue": "2.3.2", + "@fontsource-variable/noto-sans-sc": "5.3.1", + "element-plus": "2.14.8", + "katex": "0.19.1", + "pinia": "4.1.0", + "vue": "3.5.45", + "vue-router": "4.6.4" + }, + "devDependencies": { + "@types/katex": "0.16.8", + "@types/node": "24.10.1", + "@vitejs/plugin-vue": "6.0.10", + "typescript": "5.9.3", + "vite": "8.3.7", + "vitest": "5.1.0", + "vue-tsc": "3.3.14" + }, + "packageManager": "pnpm@11.25.0" +} diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml new file mode 100644 index 0000000..60c4daf --- /dev/null +++ b/frontend/pnpm-lock.yaml @@ -0,0 +1,1228 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + '@element-plus/icons-vue': + specifier: 2.3.2 + version: 2.3.2(vue@3.5.45(typescript@5.9.3)) + '@fontsource-variable/noto-sans-sc': + specifier: 5.3.1 + version: 5.3.1 + element-plus: + specifier: 2.14.8 + version: 2.14.8(vue@3.5.45(typescript@5.9.3)) + katex: + specifier: 0.19.1 + version: 0.19.1 + pinia: + specifier: 4.1.0 + version: 4.1.0(@vue/devtools-api@8.2.1)(typescript@5.9.3)(vue@3.5.45(typescript@5.9.3)) + vue: + specifier: 3.5.45 + version: 3.5.45(typescript@5.9.3) + vue-router: + specifier: 4.6.4 + version: 4.6.4(vue@3.5.45(typescript@5.9.3)) + devDependencies: + '@types/katex': + specifier: 0.16.8 + version: 0.16.8 + '@types/node': + specifier: 24.10.1 + version: 24.10.1 + '@vitejs/plugin-vue': + specifier: 6.0.10 + version: 6.0.10(vite@8.3.7(@types/node@24.10.1))(vue@3.5.45(typescript@5.9.3)) + typescript: + specifier: 5.9.3 + version: 5.9.3 + vite: + specifier: 8.3.7 + version: 8.3.7(@types/node@24.10.1) + vitest: + specifier: 5.1.0 + version: 5.1.0(@types/node@24.10.1)(vite@8.3.7(@types/node@24.10.1)) + vue-tsc: + specifier: 3.3.14 + version: 3.3.14(typescript@5.9.3) + +packages: + + '@babel/helper-string-parser@7.29.13': + resolution: {integrity: sha512-fWegr+WsEsiMVW4KUNdIIzzMTZSzNiqhy0//6+2MRi2d5NFNsL/AYwBQW8eBnRbTBVRnDVzjaJEUqKaCWjMMdQ==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-identifier@7.29.7': + resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} + engines: {node: '>=6.9.0'} + + '@babel/parser@7.29.13': + resolution: {integrity: sha512-fJM50YYjlTiBhgdkGmC1tBpv+FMAyo4annf2X6Aks+0yRlaiVkYW/3f07xAfVVkYIoZ9fFZp+mEThUFnuybhkQ==} + engines: {node: '>=6.0.0'} + hasBin: true + + '@babel/types@7.29.11': + resolution: {integrity: sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ==} + engines: {node: '>=6.9.0'} + + '@ctrl/tinycolor@4.3.0': + resolution: {integrity: sha512-6V0+8vw/GmH92URQ/Ki12FPhoB3nqaQUJE+5xgbFbB5ok0OXYK5jCQsQQoyR3BzCddHsCpyCFRnIcI1PSOVYkQ==} + engines: {node: '>=14'} + + '@element-plus/icons-vue@2.3.2': + resolution: {integrity: sha512-OzIuTaIfC8QXEPmJvB4Y4kw34rSXdCJzxcD1kFStBvr8bK6X1zQAYDo0CNMjojnfTqRQCJ0I7prlErcoRiET2A==} + peerDependencies: + vue: ^3.2.0 + + '@floating-ui/core@1.8.0': + resolution: {integrity: sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==} + + '@floating-ui/dom@1.8.0': + resolution: {integrity: sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==} + + '@floating-ui/utils@0.2.12': + resolution: {integrity: sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==} + + '@fontsource-variable/noto-sans-sc@5.3.1': + resolution: {integrity: sha512-UB96JJ17HyD5ehEU7Em0hDdh7fvTMB4B4Hzmq5c4QaNwwSLqTrdM2S+coySeBqCkXwh0DxqXT0b0wMrmzorFpQ==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@oxc-project/types@0.156.0': + resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} + + '@rolldown/binding-android-arm-eabi@1.2.18': + resolution: {integrity: sha512-ubTG+4KlidvioxjOFdsdEa2F6JVGZb8m2ByJUqQ7fYzUeT1cEn194POcsQ10PKH4p//q0YQn4SB3YpSuzcA1Yg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.2.18': + resolution: {integrity: sha512-2Xa1t/JeFGTZn5TbzgPppcCftF8sCVnTNvrIvoSdcZhoFzAuVy1L3xxQUQ4sfWDtwVzg1u6Yi1R3SlJugRNV2Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.2.18': + resolution: {integrity: sha512-iUzw9HshVvrWci9gVXjxWS7/M/IcLvNo67vu2c/w9zKBz4hIvPRixdUpIW/iCfhldLaq9ER2hecsI9UY5z0/yA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.18': + resolution: {integrity: sha512-XuDHFzbFEtZl0QGJi92+fmG67tfnp1iZ9VOeDkwasGyTq2VG3/5PnJnvAr+MTzFh/rNScJ3VhN+XpZyyGsN7Jw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.2.18': + resolution: {integrity: sha512-MM8opLfsLK15oEXDz6iBc0t3ahu+ew9jsAmha+ovZ33hSwYgqo7YmpRITqFTfW7xA71BLEQ3jJdTsaCmhB1c9w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.18': + resolution: {integrity: sha512-J6EoCWiy5RnFQzHrKyHXXevZ9lukQfGpnchX/zG/k/WC2nc9O9XyS1JgA8kI9VxMFggMbCPjpv7LcikriXfehw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.2.18': + resolution: {integrity: sha512-HIkFuLF7CdDeki+1aCZLLbLq0hk/PHntb+z4/YCTo47JbksTD6jJEELIz92tYROmDmvMrNqUMqBi71BkJLDR+A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.2.18': + resolution: {integrity: sha512-4oqWItLLYt7IceOnElCct8T2ek5p7PmD7LN04TRJRXGo5f3HtKTgGH6PhYRFK4C2ICkq/LMUU0BVPvvlAKhm8g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.2.18': + resolution: {integrity: sha512-+AkRly5SrCEgnPhGRfub7pucASYEC2fTsxZg7VCcnozpA2+Wn/gCYy1t7LuJS67/xyJu/7noYBJncDUkbwgw2A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.18': + resolution: {integrity: sha512-Ttg1r9vVykMnQrE/GwYO9icKtXiuiMfRe/w74xJkeoVuvhRG+WtT6LEMOf58Yl63yd77lhHzO8Y55R8CC3XALA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.18': + resolution: {integrity: sha512-xX1Tt4o5jUMma0vJsXp5eRZA9nOuyigb2dKJMMzZRmzMxLYGE9PaKKSqHPzPvSQgM8ZOEacSTQwDQcwWfh0xmQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.2.18': + resolution: {integrity: sha512-4VVlGI5K2kociZlW3lSN8VjG3TW5yQIlAcfCdBXMgGjJxZll15Fa4ocRHXHvIVVnwlibCw/NQajJrNDiqqpiiw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.2.18': + resolution: {integrity: sha512-PApTsgH1jLYuyy3tSCz9De82Gq5qXwi7vImVZhEzTgX1C4150Cp5M2ZfL3pLvbCvbEHL0oJeC6pd6podtv8Y5w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-win32-arm64-msvc@1.2.18': + resolution: {integrity: sha512-J2XjWjx/SP+4x0H4r6dz3Vzb5WVkg7re40Do9K7HJ3sK2/xcmZrWwakXlSwaMvOkvruLJCD4CL/3wqsIR/thgg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.18': + resolution: {integrity: sha512-XwRJxRQvkuEtS0hIIt29QrqPJ+JzMJSNYHJw4ae/mc6uEarfRG1ceyg4HmmWiBdL/YCb6g7N5BLbSvmRJRYZHw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.1.0': + resolution: {integrity: sha512-K+NU2HDCEem4sClgHH4ZZXwdJeNFkJo+hRk479DIwdIviAPN2hFJH1KHHwg8CxHQXvi0M5XY4deTXINfIiSG6w==} + + '@sxzz/popperjs-es@2.11.8': + resolution: {integrity: sha512-wOwESXvvED3S8xBmcPWHs2dUuzrE4XiZeFu7e1hROIJkm02a49N120pmOXxY33sBb6hArItm5W5tcg1cBtV+HQ==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/estree@1.0.10': + resolution: {integrity: sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==} + + '@types/katex@0.16.8': + resolution: {integrity: sha512-trgaNyfU+Xh2Tc+ABIb44a5AYUpicB3uwirOioeOkNPPbmgRNtcWyDeeFRzjPZENO9Vq8gvVqfhaaXWLlevVwg==} + + '@types/lodash-es@4.17.12': + resolution: {integrity: sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==} + + '@types/lodash@4.17.27': + resolution: {integrity: sha512-VenMRv/eKNrspX9v3H4dbmjsrnCOYdYBG3kxXKk3dG6X+urBGcj2Prww3xw1U5K4FV/mE4h5GbWd0szEKf+9ew==} + + '@types/node@24.10.1': + resolution: {integrity: sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==} + + '@types/web-bluetooth@0.0.21': + resolution: {integrity: sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA==} + + '@vitejs/plugin-vue@6.0.10': + resolution: {integrity: sha512-b80aUQh3n+qEzzZm5oQp3rT2QImeCx58K6eFl/RkJ3d65KW0kTuv5lNsLRVAjbW9YRUpo/wzmvzMgV34bTAItA==} + engines: {node: ^20.19.0 || >=22.12.0} + peerDependencies: + vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0 + vue: ^3.2.25 || ^3.6.0-rc.10 + + '@vitest/mocker@5.1.0': + resolution: {integrity: sha512-5umB9/jlWcqVS6fsrFmv5Gdnpu6wAUio/lEOwAmvB7v+lFo/IW2B9FhAD0p19GCULTgMzLCdUmuCDCnAzWgppQ==} + peerDependencies: + msw: ^2.4.9 || ^3.0.0 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/spy@5.1.0': + resolution: {integrity: sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A==} + + '@volar/language-core@2.4.30': + resolution: {integrity: sha512-73fjwEV8wat6aOZ6U/y/hqtE30ocrIWECg67b0txGczOMNw+MffLmvJ5fnFfN9drVUEYZzLdaNo6VAy6G6avMw==} + + '@volar/language-service@2.4.30': + resolution: {integrity: sha512-w/xDsASiqC71ggCOm7sTDXDNk/l72XEptodeRC68tgZ0e5QM4hM3zAqBGC7mBctvhrpYwKfMG+t9xcUo2hEFtA==} + peerDependencies: + typescript: <7 + peerDependenciesMeta: + typescript: + optional: true + + '@volar/source-map@2.4.30': + resolution: {integrity: sha512-zym1ob/KwDDyN+0jGVtxwbxJSRRnUvv5HspCtz3yEfVVdCG4/dzxJktMGPAgemqRuVs81O0o/y0q3qOUErR8kg==} + + '@volar/typescript@2.4.30': + resolution: {integrity: sha512-/DgA5tgYFPfrLFuSjIMXMGHk1LQv2+P8eny6+BhGNzFJELWIW7UZlc56ZLIRFhLsPpMfIFxM8/HvOPBggrjTZg==} + peerDependencies: + typescript: <7 + peerDependenciesMeta: + typescript: + optional: true + + '@vue/compiler-core@3.5.45': + resolution: {integrity: sha512-XGHJrM6ufZARAc/w+tyOswStw9tdKiqCKBScI4gGaNxD+aaGu/HQWgKJ+JItjRLPqenQ7iE7G8AJC7T5ew1p+g==} + + '@vue/compiler-dom@3.5.45': + resolution: {integrity: sha512-LbP2d19GSOYGPmvMBBCVJVlv7TKtjM1Cfeyu3cYia720pknZP+1cLX7H5MVatvruT6MuJhiPuNbQBW/MDn/EwA==} + + '@vue/compiler-sfc@3.5.45': + resolution: {integrity: sha512-MKFjb2UX0M/l/jhfzqMLrI8VM4pfvFKG3pqFZkSZFHRLtNld/O4RtUPZFWSwhro/14qP88UQEkWzHxAZAQ0tsw==} + + '@vue/compiler-ssr@3.5.45': + resolution: {integrity: sha512-RF5sbZOfYz5AK00tOJUn2PwFXR2fS1u2HVzI8D9VF9rGAFxuGBqg2bB1kJ3ZHMprqSltXnT9MZE1IsqjSM8oew==} + + '@vue/devtools-api@6.6.4': + resolution: {integrity: sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==} + + '@vue/devtools-api@8.2.1': + resolution: {integrity: sha512-6u4vXBlIBAC1wMplIZgpyPn7uh/s4Bf6F5bMzvLv+EdJ0aHs/+4B7Ygv864EStQSjRbsRzTko/kUG1A1IejQ3A==} + + '@vue/devtools-kit@8.2.1': + resolution: {integrity: sha512-FIGIuq3AWReEpbAHY/cRGeHDfI0qOb8OCQ3YjbEAX04uaxIDbGc9rhkbVcG7rnfHPXE3RsU5KrWOu9V/okd8AQ==} + + '@vue/devtools-shared@8.2.1': + resolution: {integrity: sha512-Fkac7lUdGReh6pVOi3AYPRGe82LQqRmAfThW7RRligOAP0ZA/Z1z9XLHDM9dv34pV2HRc79DK8uKPeG2fLnA/g==} + + '@vue/language-core@3.3.14': + resolution: {integrity: sha512-kRB+3hHg0c+BdD1XLAvwjVMQd5pC05zijSlPDRI3ERvC/s04JlRs5upy2KjeMg/9m9oD5zuMVh9yVvkKfZqoJg==} + + '@vue/reactivity@3.5.45': + resolution: {integrity: sha512-WqkyubNWpI4OYBOipSrjIssMdJO8K1i9Zts/Wm8Er10/0msOEwCyWWWvZnAI7WW3kQsTong6DJp8Cbb+vd4cPA==} + + '@vue/runtime-core@3.5.45': + resolution: {integrity: sha512-bzIO3+FABjpj85uIKSc+Qnj36/sxDNI3tcH9i6w6xKA1k6e0ejv0G0jMCfeJBvK3yGL5XbJ3DMZj+ClqyCHFYw==} + + '@vue/runtime-dom@3.5.45': + resolution: {integrity: sha512-ZvRTFMDgfqTDYWvJfoVpQTJx1RN5M6l7Pyd6wfdY2NaXzbPQVh9ezeQYFbNPP6bIcRVn2SqSSR25N/jSW69BFw==} + + '@vue/server-renderer@3.5.45': + resolution: {integrity: sha512-1fNXUHhhsWf4EVL4XixbGBU5mKdiIXJAB82feHRTyPPo6ZUEYWIJuEeUl3mVV6QDBp50HJOX4obLhxYXlrjrzA==} + + '@vue/shared@3.5.45': + resolution: {integrity: sha512-ue9fgHmVNPlP7iW3+cxoBX/Cnlw53dHlVSw0JKGY6z1lObg8pHoj928M2nzG4/yVsMZ3NaRZ2s2z61uC16NDwQ==} + + '@vueuse/core@15.0.0': + resolution: {integrity: sha512-Zv67h5mrk7YHDJsRObx+DXaCBz6RKBUpxqLesJ+3xZNPG6yuQs7ja7kg3veFrrouYLWAqydQ7CwGEbLVxB43Ng==} + engines: {node: '>=22'} + peerDependencies: + vue: ^3.5.0 + + '@vueuse/metadata@15.0.0': + resolution: {integrity: sha512-sfWE5LADAKJ0KnjtGliMdSN8Ij/L7uP6rXIZlgPloAI4zvvefbw6H5Lt7KJA6RqQOYgVqWF5Guj50HHMIzygBg==} + engines: {node: '>=22'} + + '@vueuse/shared@15.0.0': + resolution: {integrity: sha512-vbNXhGrbV53xPOMSyOzMHQRvhMgZf7oNDw2RChUetVxwTIEkInQ1joZ9JbT0G3z2n2AJNjvmCWeM9ySYrnvogA==} + engines: {node: '>=22'} + peerDependencies: + vue: ^3.5.0 + + alien-signals@3.2.1: + resolution: {integrity: sha512-I8FjmltrfnDFoZedi5CG8DghVYNhzb/Ijluz7tCSJH0xpd0484Kowhbb1XDYOxfJpU1p5wnM2X54dA+IfGyD1g==} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + async-validator@4.2.5: + resolution: {integrity: sha512-7HhHjtERjqlNbZtqNqy2rckN/SpOOlmDliet+lP7k+eKZEjPk3DgyeU9lIXLdeLz0uBbbVp+9Qdow9wJWgwwfg==} + + birpc@2.9.0: + resolution: {integrity: sha512-KrayHS5pBi69Xi9JmvoqrIgYGDkD6mcSe/i6YKi3w5kekCLzrX4+nawcXqrj2tIp50Kw/mT/s3p+GVK0A0sKxw==} + + chai@6.3.0: + resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} + engines: {node: '>=18'} + + commander@15.1.0: + resolution: {integrity: sha512-cgnQ88TRrWcC7pVq46RzJVRMktu3W2RcbnoidnfBsl1bmDCBwJS/udcIZpKoCrbAYYaCqsz1yZCVIgbIaU3ddQ==} + engines: {node: '>=22.12.0'} + + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + + dayjs@1.11.23: + resolution: {integrity: sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + element-plus@2.14.8: + resolution: {integrity: sha512-Z4Br45W9b8vWKvVHSTvbS6rRKmsLjmHCPXICJR6osl35+i+S2LCBs4NN8apLBkQiUh0pzS9labK5eCS7yzDhWw==} + peerDependencies: + vue: ^3.3.7 + + entities@7.0.1: + resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==} + engines: {node: '>=0.12'} + + es-module-lexer@2.3.2: + resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} + + estree-walker@2.0.2: + resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + hookable@5.5.3: + resolution: {integrity: sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==} + + katex@0.19.1: + resolution: {integrity: sha512-jG8uKntjSEcm2EpQOh0XturpPuuC9r3Sq5HLHdsFdWZT27E672SF19QEi+of0/YeOy15lDgRhKvr5614uRrEfA==} + hasBin: true + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + lodash-es@4.18.1: + resolution: {integrity: sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==} + + lodash-unified@1.0.3: + resolution: {integrity: sha512-WK9qSozxXOD7ZJQlpSqOT+om2ZfcT4yO+03FuzAHD0wF6S0l0090LRPDx3vhTTLZ8cFKpBn+IOcVXK6qOcIlfQ==} + peerDependencies: + '@types/lodash-es': '*' + lodash: '*' + lodash-es: '*' + + lodash@4.18.1: + resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + magic-string@1.4.5: + resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==} + + memoize-one@6.0.0: + resolution: {integrity: sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw==} + + muggle-string@0.4.1: + resolution: {integrity: sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==} + + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + normalize-wheel-es@1.2.0: + resolution: {integrity: sha512-Wj7+EJQ8mSuXr2iWfnujrimU35R2W4FAErEyTmJoJ7ucwTn2hOUSsRehMb5RSYkxXGTM7Y9QpvPmp++w5ftoJw==} + + nostics@1.3.0: + resolution: {integrity: sha512-wzRsrJwNlFbqIRQt8aCeL2WE8USip/uuvGSOZV1D02CxX8ABTMbw8IywKjH7yWHETMXbWJI4OBpihg9rmz2Vyg==} + + obug@3.0.0: + resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==} + engines: {node: '>=12.20.0'} + + path-browserify@1.0.1: + resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==} + + perfect-debounce@2.1.0: + resolution: {integrity: sha512-LjgdTytVFXeUgtHZr9WYViYSM/g8MkcTPYDlPa3cDqMirHjKiSZPYd6DoL7pK8AJQr+uWkQvCjHNdiMqsrJs+g==} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + pinia@4.1.0: + resolution: {integrity: sha512-+5/HMuVjYQfKlCD5xQ7zfXn1xUzYFEa7pd0DQK5SaMfZCaFRTHlaH/c02N1FoGOdlzSiwf5EOPgJx//1QDw6gw==} + peerDependencies: + '@vue/devtools-api': ^8.2.1 + typescript: '>=5.6.0' + vue: ^3.5.11 + peerDependenciesMeta: + typescript: + optional: true + + postcss@8.5.32: + resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} + engines: {node: ^10 || ^12 || >=14} + + rolldown@1.2.18: + resolution: {integrity: sha512-C1uuT3UR60SShuCaPQFAAZyefJCWZlAKB02BV3BuPE2Rs4fevRQltEKoFO2tV5W9/eJhU5RieV6vJj3euulfNQ==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} + engines: {node: '>=0.10.0'} + + std-env@4.3.0: + resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} + + tinybench@6.2.3: + resolution: {integrity: sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==} + engines: {node: '>=20.0.0'} + + tinyexec@1.3.1: + resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@7.16.0: + resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==} + + vite@8.3.7: + resolution: {integrity: sha512-oxh0dMxrayBr33ScJvvBJ2HBQ2jc1TBrXKR2NyL/MJ9WPuX19mN2DXWUmywKdyw5RFVQBo8hmtb2FMC0LHrnng==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.7.1 || ^0.8.0 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@5.1.0: + resolution: {integrity: sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==} + engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 5.1.0 + '@vitest/browser-preview': 5.1.0 + '@vitest/browser-webdriverio': ^5.0.0-beta.5 || >=5.0.0 + '@vitest/coverage-istanbul': 5.1.0 + '@vitest/coverage-v8': 5.1.0 + '@vitest/ui': 5.1.0 + happy-dom: '*' + jsdom: '*' + vite: ^6.4.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + vscode-jsonrpc@10.0.0: + resolution: {integrity: sha512-USSfxg0vDIpTQqlQBGxF3mBARyoS8cU7LHLpbYNh6dOJt32dlskxPWB0Irrh5TllTmyf7oNLAvqDqzklbwwnpA==} + engines: {node: '>=14.17.0'} + + vscode-languageserver-protocol@3.18.5: + resolution: {integrity: sha512-FW4fBMzZ99N8xeob4py0l050wgCoRgTpEq5Xcsb9lM1bc29UKGR/wSV+4knaqFxssFHajy7OzNiKP/m3U1ZEuA==} + + vscode-languageserver-textdocument@1.0.16: + resolution: {integrity: sha512-qeNEuOi9a3qkqRf7Gfez2WL2VwlBTLCNekHBGO9kxPVUp9XuY15yfTJ9jwvOwKI0I2MhUUfZq95NSp+LK1CLQg==} + + vscode-languageserver-types@3.18.5: + resolution: {integrity: sha512-kPd6+JQNz3HMJvjKlqUxERSlZHAntl/aGpsk7ImwIh0ewDKDcjgAEyVSYciPiOJD3ftbK9IrfiqUeTZLSbCizw==} + + vscode-uri@3.2.0: + resolution: {integrity: sha512-m2gXo3bn0G1kT9InzMf07fTbqMbGtyckj3bH5ktLO+1Ssv+yiATZ4dhwaQv9UZWxJh6E9IFGnQyjgWVDWVBDrg==} + + vue-component-type-helpers@3.3.14: + resolution: {integrity: sha512-Pq3+OnbCiPCHk0R7KSZrx+j/XXaUn2kSQ1epxq60w8CPbByLjC1EJgV51n4WY851sTXUVzsNMuitywdkdVyKjA==} + + vue-router@4.6.4: + resolution: {integrity: sha512-Hz9q5sa33Yhduglwz6g9skT8OBPii+4bFn88w6J+J4MfEo4KRRpmiNG/hHHkdbRFlLBOqxN8y8gf2Fb0MTUgVg==} + peerDependencies: + vue: ^3.5.0 + + vue-tsc@3.3.14: + resolution: {integrity: sha512-URAu2H9AuMZMg9GCgnqbaHHHd8pBZRAwNV2e2yYS8VDsoTVXHiOSo663OS6DkEvauQ2yixn5TPFJ9WV9QIspkA==} + hasBin: true + peerDependencies: + typescript: '>=5.0.0' + + vue@3.5.45: + resolution: {integrity: sha512-3cvsib8m9c0vB24+MDKsgcW4+Da4xaBl9Z/5Tbm2pmSIsRPxcil4cdXjXlVsmJ2g64XJo5h+IRd7rsdGT9pZaw==} + peerDependencies: + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + why-is-node-running@3.2.1: + resolution: {integrity: sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==} + engines: {node: '>=20.11'} + hasBin: true + +snapshots: + + '@babel/helper-string-parser@7.29.13': {} + + '@babel/helper-validator-identifier@7.29.7': {} + + '@babel/parser@7.29.13': + dependencies: + '@babel/types': 7.29.11 + + '@babel/types@7.29.11': + dependencies: + '@babel/helper-string-parser': 7.29.13 + '@babel/helper-validator-identifier': 7.29.7 + + '@ctrl/tinycolor@4.3.0': {} + + '@element-plus/icons-vue@2.3.2(vue@3.5.45(typescript@5.9.3))': + dependencies: + vue: 3.5.45(typescript@5.9.3) + + '@floating-ui/core@1.8.0': + dependencies: + '@floating-ui/utils': 0.2.12 + + '@floating-ui/dom@1.8.0': + dependencies: + '@floating-ui/core': 1.8.0 + '@floating-ui/utils': 0.2.12 + + '@floating-ui/utils@0.2.12': {} + + '@fontsource-variable/noto-sans-sc@5.3.1': {} + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 + + '@oxc-project/types@0.156.0': {} + + '@rolldown/binding-android-arm-eabi@1.2.18': + optional: true + + '@rolldown/binding-android-arm64@1.2.18': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.18': + optional: true + + '@rolldown/binding-darwin-x64@1.2.18': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.18': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.18': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.18': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.18': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.18': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.18': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.18': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.18': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.18': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.18': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.18': + optional: true + + '@rolldown/pluginutils@1.1.0': {} + + '@sxzz/popperjs-es@2.11.8': {} + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/deep-eql@4.0.2': {} + + '@types/estree@1.0.10': {} + + '@types/katex@0.16.8': {} + + '@types/lodash-es@4.17.12': + dependencies: + '@types/lodash': 4.17.27 + + '@types/lodash@4.17.27': {} + + '@types/node@24.10.1': + dependencies: + undici-types: 7.16.0 + + '@types/web-bluetooth@0.0.21': {} + + '@vitejs/plugin-vue@6.0.10(vite@8.3.7(@types/node@24.10.1))(vue@3.5.45(typescript@5.9.3))': + dependencies: + '@rolldown/pluginutils': 1.1.0 + vite: 8.3.7(@types/node@24.10.1) + vue: 3.5.45(typescript@5.9.3) + + '@vitest/mocker@5.1.0(vite@8.3.7(@types/node@24.10.1))': + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + '@vitest/spy': 5.1.0 + estree-walker: 3.0.3 + magic-string: 1.4.5 + optionalDependencies: + vite: 8.3.7(@types/node@24.10.1) + + '@vitest/spy@5.1.0': {} + + '@volar/language-core@2.4.30': + dependencies: + '@volar/source-map': 2.4.30 + + '@volar/language-service@2.4.30(typescript@5.9.3)': + dependencies: + '@volar/language-core': 2.4.30 + vscode-languageserver-protocol: 3.18.5 + vscode-languageserver-textdocument: 1.0.16 + vscode-uri: 3.2.0 + optionalDependencies: + typescript: 5.9.3 + + '@volar/source-map@2.4.30': {} + + '@volar/typescript@2.4.30(typescript@5.9.3)': + dependencies: + '@volar/language-core': 2.4.30 + '@volar/language-service': 2.4.30(typescript@5.9.3) + path-browserify: 1.0.1 + vscode-uri: 3.2.0 + optionalDependencies: + typescript: 5.9.3 + + '@vue/compiler-core@3.5.45': + dependencies: + '@babel/parser': 7.29.13 + '@vue/shared': 3.5.45 + entities: 7.0.1 + estree-walker: 2.0.2 + source-map-js: 1.2.2 + + '@vue/compiler-dom@3.5.45': + dependencies: + '@vue/compiler-core': 3.5.45 + '@vue/shared': 3.5.45 + + '@vue/compiler-sfc@3.5.45': + dependencies: + '@babel/parser': 7.29.13 + '@vue/compiler-core': 3.5.45 + '@vue/compiler-dom': 3.5.45 + '@vue/compiler-ssr': 3.5.45 + '@vue/shared': 3.5.45 + estree-walker: 2.0.2 + magic-string: 0.30.21 + postcss: 8.5.32 + source-map-js: 1.2.2 + + '@vue/compiler-ssr@3.5.45': + dependencies: + '@vue/compiler-dom': 3.5.45 + '@vue/shared': 3.5.45 + + '@vue/devtools-api@6.6.4': {} + + '@vue/devtools-api@8.2.1': + dependencies: + '@vue/devtools-kit': 8.2.1 + + '@vue/devtools-kit@8.2.1': + dependencies: + '@vue/devtools-shared': 8.2.1 + birpc: 2.9.0 + hookable: 5.5.3 + perfect-debounce: 2.1.0 + + '@vue/devtools-shared@8.2.1': {} + + '@vue/language-core@3.3.14': + dependencies: + '@volar/language-core': 2.4.30 + '@vue/compiler-dom': 3.5.45 + '@vue/shared': 3.5.45 + alien-signals: 3.2.1 + muggle-string: 0.4.1 + path-browserify: 1.0.1 + picomatch: 4.0.7 + + '@vue/reactivity@3.5.45': + dependencies: + '@vue/shared': 3.5.45 + + '@vue/runtime-core@3.5.45': + dependencies: + '@vue/reactivity': 3.5.45 + '@vue/shared': 3.5.45 + + '@vue/runtime-dom@3.5.45': + dependencies: + '@vue/reactivity': 3.5.45 + '@vue/runtime-core': 3.5.45 + '@vue/shared': 3.5.45 + csstype: 3.2.3 + + '@vue/server-renderer@3.5.45': + dependencies: + '@vue/compiler-ssr': 3.5.45 + '@vue/runtime-dom': 3.5.45 + '@vue/shared': 3.5.45 + + '@vue/shared@3.5.45': {} + + '@vueuse/core@15.0.0(vue@3.5.45(typescript@5.9.3))': + dependencies: + '@types/web-bluetooth': 0.0.21 + '@vueuse/metadata': 15.0.0 + '@vueuse/shared': 15.0.0(vue@3.5.45(typescript@5.9.3)) + vue: 3.5.45(typescript@5.9.3) + + '@vueuse/metadata@15.0.0': {} + + '@vueuse/shared@15.0.0(vue@3.5.45(typescript@5.9.3))': + dependencies: + vue: 3.5.45(typescript@5.9.3) + + alien-signals@3.2.1: {} + + assertion-error@2.0.1: {} + + async-validator@4.2.5: {} + + birpc@2.9.0: {} + + chai@6.3.0: {} + + commander@15.1.0: {} + + csstype@3.2.3: {} + + dayjs@1.11.23: {} + + detect-libc@2.1.2: {} + + element-plus@2.14.8(vue@3.5.45(typescript@5.9.3)): + dependencies: + '@ctrl/tinycolor': 4.3.0 + '@element-plus/icons-vue': 2.3.2(vue@3.5.45(typescript@5.9.3)) + '@floating-ui/dom': 1.8.0 + '@popperjs/core': '@sxzz/popperjs-es@2.11.8' + '@types/lodash': 4.17.27 + '@types/lodash-es': 4.17.12 + '@vueuse/core': 15.0.0(vue@3.5.45(typescript@5.9.3)) + async-validator: 4.2.5 + dayjs: 1.11.23 + lodash: 4.18.1 + lodash-es: 4.18.1 + lodash-unified: 1.0.3(@types/lodash-es@4.17.12)(lodash-es@4.18.1)(lodash@4.18.1) + memoize-one: 6.0.0 + normalize-wheel-es: 1.2.0 + vue: 3.5.45(typescript@5.9.3) + vue-component-type-helpers: 3.3.14 + + entities@7.0.1: {} + + es-module-lexer@2.3.2: {} + + estree-walker@2.0.2: {} + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.10 + + expect-type@1.4.0: {} + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + fsevents@2.3.3: + optional: true + + hookable@5.5.3: {} + + katex@0.19.1: + dependencies: + commander: 15.1.0 + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + lodash-es@4.18.1: {} + + lodash-unified@1.0.3(@types/lodash-es@4.17.12)(lodash-es@4.18.1)(lodash@4.18.1): + dependencies: + '@types/lodash-es': 4.17.12 + lodash: 4.18.1 + lodash-es: 4.18.1 + + lodash@4.18.1: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + magic-string@1.4.5: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + memoize-one@6.0.0: {} + + muggle-string@0.4.1: {} + + nanoid@3.3.20: {} + + normalize-wheel-es@1.2.0: {} + + nostics@1.3.0: {} + + obug@3.0.0: {} + + path-browserify@1.0.1: {} + + perfect-debounce@2.1.0: {} + + picocolors@1.1.1: {} + + picomatch@4.0.7: {} + + pinia@4.1.0(@vue/devtools-api@8.2.1)(typescript@5.9.3)(vue@3.5.45(typescript@5.9.3)): + dependencies: + '@vue/devtools-api': 8.2.1 + nostics: 1.3.0 + vue: 3.5.45(typescript@5.9.3) + optionalDependencies: + typescript: 5.9.3 + + postcss@8.5.32: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.2.2 + + rolldown@1.2.18: + dependencies: + '@oxc-project/types': 0.156.0 + '@rolldown/pluginutils': 1.1.0 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.18 + '@rolldown/binding-android-arm64': 1.2.18 + '@rolldown/binding-darwin-arm64': 1.2.18 + '@rolldown/binding-darwin-x64': 1.2.18 + '@rolldown/binding-freebsd-x64': 1.2.18 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.18 + '@rolldown/binding-linux-arm64-gnu': 1.2.18 + '@rolldown/binding-linux-arm64-musl': 1.2.18 + '@rolldown/binding-linux-ppc64-gnu': 1.2.18 + '@rolldown/binding-linux-s390x-gnu': 1.2.18 + '@rolldown/binding-linux-x64-gnu': 1.2.18 + '@rolldown/binding-linux-x64-musl': 1.2.18 + '@rolldown/binding-openharmony-arm64': 1.2.18 + '@rolldown/binding-win32-arm64-msvc': 1.2.18 + '@rolldown/binding-win32-x64-msvc': 1.2.18 + + source-map-js@1.2.2: {} + + std-env@4.3.0: {} + + tinybench@6.2.3: {} + + tinyexec@1.3.1: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + typescript@5.9.3: {} + + undici-types@7.16.0: {} + + vite@8.3.7(@types/node@24.10.1): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.32 + rolldown: 1.2.18 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 24.10.1 + fsevents: 2.3.3 + + vitest@5.1.0(@types/node@24.10.1)(vite@8.3.7(@types/node@24.10.1)): + dependencies: + '@types/chai': 5.2.3 + '@vitest/mocker': 5.1.0(vite@8.3.7(@types/node@24.10.1)) + chai: 6.3.0 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 1.4.5 + obug: 3.0.0 + picomatch: 4.0.7 + std-env: 4.3.0 + tinybench: 6.2.3 + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + vite: 8.3.7(@types/node@24.10.1) + why-is-node-running: 3.2.1 + optionalDependencies: + '@types/node': 24.10.1 + transitivePeerDependencies: + - msw + + vscode-jsonrpc@10.0.0: {} + + vscode-languageserver-protocol@3.18.5: + dependencies: + vscode-jsonrpc: 10.0.0 + vscode-languageserver-types: 3.18.5 + + vscode-languageserver-textdocument@1.0.16: {} + + vscode-languageserver-types@3.18.5: {} + + vscode-uri@3.2.0: {} + + vue-component-type-helpers@3.3.14: {} + + vue-router@4.6.4(vue@3.5.45(typescript@5.9.3)): + dependencies: + '@vue/devtools-api': 6.6.4 + vue: 3.5.45(typescript@5.9.3) + + vue-tsc@3.3.14(typescript@5.9.3): + dependencies: + '@volar/typescript': 2.4.30(typescript@5.9.3) + '@vue/language-core': 3.3.14 + typescript: 5.9.3 + + vue@3.5.45(typescript@5.9.3): + dependencies: + '@vue/compiler-dom': 3.5.45 + '@vue/compiler-sfc': 3.5.45 + '@vue/runtime-dom': 3.5.45 + '@vue/server-renderer': 3.5.45 + '@vue/shared': 3.5.45 + optionalDependencies: + typescript: 5.9.3 + + why-is-node-running@3.2.1: {} diff --git a/frontend/pnpm-workspace.yaml b/frontend/pnpm-workspace.yaml new file mode 100644 index 0000000..b62826b --- /dev/null +++ b/frontend/pnpm-workspace.yaml @@ -0,0 +1,18 @@ +minimumReleaseAgeExclude: + - '@rolldown/binding-android-arm-eabi@1.2.18' + - '@rolldown/binding-android-arm64@1.2.18' + - '@rolldown/binding-darwin-arm64@1.2.18' + - '@rolldown/binding-darwin-x64@1.2.18' + - '@rolldown/binding-freebsd-x64@1.2.18' + - '@rolldown/binding-linux-arm-gnueabihf@1.2.18' + - '@rolldown/binding-linux-arm64-gnu@1.2.18' + - '@rolldown/binding-linux-arm64-musl@1.2.18' + - '@rolldown/binding-linux-ppc64-gnu@1.2.18' + - '@rolldown/binding-linux-s390x-gnu@1.2.18' + - '@rolldown/binding-linux-x64-gnu@1.2.18' + - '@rolldown/binding-linux-x64-musl@1.2.18' + - '@rolldown/binding-openharmony-arm64@1.2.18' + - '@rolldown/binding-win32-arm64-msvc@1.2.18' + - '@rolldown/binding-win32-x64-msvc@1.2.18' + - rolldown@1.2.18 + - vite@8.3.7 diff --git a/frontend/public/inspiration/priority-retry-image.png b/frontend/public/inspiration/priority-retry-image.png new file mode 100644 index 0000000..a93b076 Binary files /dev/null and b/frontend/public/inspiration/priority-retry-image.png differ diff --git a/frontend/public/inspiration/qwen-image.png b/frontend/public/inspiration/qwen-image.png new file mode 100644 index 0000000..e1e8f09 Binary files /dev/null and b/frontend/public/inspiration/qwen-image.png differ diff --git a/frontend/public/inspiration/sdxl-controlnet.png b/frontend/public/inspiration/sdxl-controlnet.png new file mode 100644 index 0000000..81cbdd8 Binary files /dev/null and b/frontend/public/inspiration/sdxl-controlnet.png differ diff --git a/frontend/public/inspiration/wan-middle.png b/frontend/public/inspiration/wan-middle.png new file mode 100644 index 0000000..127a673 Binary files /dev/null and b/frontend/public/inspiration/wan-middle.png differ diff --git a/frontend/src/App.vue b/frontend/src/App.vue new file mode 100644 index 0000000..2ee7a45 --- /dev/null +++ b/frontend/src/App.vue @@ -0,0 +1,30 @@ + + diff --git a/frontend/src/api.ts b/frontend/src/api.ts new file mode 100644 index 0000000..32e9b5f --- /dev/null +++ b/frontend/src/api.ts @@ -0,0 +1,53 @@ +import type { Asset, AuthResponse, CapabilitiesResponse, Job, JobRequest, JobsPage, Page, Scheduler, Capability } from './types' + +let csrfToken = '' +export function setCsrfToken(token: string) { csrfToken = token } +export class ApiError extends Error { + constructor(public code: string, message: string, public status = 0) { super(message) } +} +export function queryString(values: Record = {}) { + const search = new URLSearchParams() + for (const [key, value] of Object.entries(values)) if (value !== undefined && value !== null && value !== '') search.set(key, String(value)) + return search.size ? `?${search}` : '' +} +export function newRequestId() { return globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random().toString(36).slice(2)}` } +async function request(path: string, options: RequestInit = {}): Promise { + const method = (options.method || 'GET').toUpperCase() + const headers = new Headers(options.headers) + if (options.body && !(options.body instanceof FormData)) headers.set('Content-Type', 'application/json') + if (!['GET', 'HEAD'].includes(method) && path !== '/auth/login') { + if (!csrfToken) throw new ApiError('session_required', '登录状态已失效,请重新登录', 401) + headers.set('X-CSRF-Token', csrfToken) + } + let response: Response + try { response = await fetch(`/api${path}`, { ...options, headers, credentials: 'include' }) } + catch { throw new ApiError('network_error', '暂时无法连接服务,请检查网络后重试') } + if (!response.ok) { + const data = await response.json().catch(() => null) + const detail = data?.detail + const message = typeof detail === 'string' ? detail : Array.isArray(detail) + ? detail.map((item: { msg: string }) => item.msg).join(';') : detail?.message || `请求失败(${response.status})` + if (response.status === 401 && path !== '/auth/login' && typeof window !== 'undefined') window.dispatchEvent(new Event('cmvr:unauthorized')) + throw new ApiError(detail?.code || 'request_failed', message, response.status) + } + if (response.status === 204) return undefined as T + return response.json() as Promise +} +export const api = { + me: () => request('/auth/me'), + login: (username: string, password: string) => request('/auth/login', { method: 'POST', body: JSON.stringify({ username, password }) }), + logout: () => request('/auth/logout', { method: 'POST' }), + capabilities: () => request('/capabilities'), + systemStatus: () => request<{ inference_online: boolean; scheduler: Scheduler; models: Capability[]; environment: 'production' | 'preview' | 'test'; database_backend: 'mysql' | 'sqlite' }>('/system/status'), + jobs: (filters: Record = {}) => request(`/jobs${queryString(filters)}`), + job: (id: string) => request(`/jobs/${encodeURIComponent(id)}`), + submit: (body: JobRequest) => request<{ jobs: Job[] }>('/jobs', { method: 'POST', headers: { 'Idempotency-Key': newRequestId() }, body: JSON.stringify(body) }), + cancel: (id: string) => request(`/jobs/${encodeURIComponent(id)}/cancel`, { method: 'POST' }), + retry: (id: string) => request<{ jobs: Job[] }>(`/jobs/${encodeURIComponent(id)}/retry`, { method: 'POST' }), + assets: (filters: Record = {}) => request>(`/assets${queryString(filters)}`), + asset: (id: string) => request(`/assets/${encodeURIComponent(id)}`), + upload: (file: File) => { const form = new FormData(); form.set('file', file); return request('/assets', { method: 'POST', body: form }) }, + updateAsset: (id: string, patch: { name?: string; tags?: string[]; favorite?: boolean }) => request(`/assets/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify(patch) }), + deleteAsset: (id: string) => request(`/assets/${encodeURIComponent(id)}`, { method: 'DELETE' }), +} +export function errorMessage(error: unknown) { return error instanceof Error ? error.message : '操作未完成,请稍后重试' } diff --git a/frontend/src/components/AssetInput.vue b/frontend/src/components/AssetInput.vue new file mode 100644 index 0000000..cf38ad2 --- /dev/null +++ b/frontend/src/components/AssetInput.vue @@ -0,0 +1,37 @@ + + diff --git a/frontend/src/components/AssetPicker.vue b/frontend/src/components/AssetPicker.vue new file mode 100644 index 0000000..e8f5c93 --- /dev/null +++ b/frontend/src/components/AssetPicker.vue @@ -0,0 +1,51 @@ + + + diff --git a/frontend/src/components/AssetPreview.vue b/frontend/src/components/AssetPreview.vue new file mode 100644 index 0000000..fa973b0 --- /dev/null +++ b/frontend/src/components/AssetPreview.vue @@ -0,0 +1,60 @@ + + diff --git a/frontend/src/components/JobCard.vue b/frontend/src/components/JobCard.vue new file mode 100644 index 0000000..9ce393a --- /dev/null +++ b/frontend/src/components/JobCard.vue @@ -0,0 +1,22 @@ + + diff --git a/frontend/src/components/JobDetail.test.ts b/frontend/src/components/JobDetail.test.ts new file mode 100644 index 0000000..2cd5071 --- /dev/null +++ b/frontend/src/components/JobDetail.test.ts @@ -0,0 +1,22 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { createSSRApp, defineComponent, h } from 'vue' +import { renderToString } from 'vue/server-renderer' +import { createPinia } from 'pinia' +import JobDetail from './JobDetail.vue' +import { api } from '../api' + +vi.mock('./AssetPreview.vue', () => ({ default: { render: () => null } })) + +afterEach(() => vi.restoreAllMocks()) + +it('fetches an initially selected deep-linked task without depending on recent-list cache', async () => { + const request = vi.spyOn(api, 'job').mockReturnValue(new Promise(() => {})) + const application = createSSRApp(JobDetail, { jobId: 'archived-owned-job' }) + application.use(createPinia()) + application.component('ElDrawer', defineComponent({ setup: (_, { slots }) => () => h('aside', slots.default?.()) })) + application.component('ElProgress', { render: () => null }) + application.component('ElButton', { render: () => null }) + application.directive('loading', {}) + await renderToString(application) + expect(request).toHaveBeenCalledExactlyOnceWith('archived-owned-job') +}) diff --git a/frontend/src/components/JobDetail.vue b/frontend/src/components/JobDetail.vue new file mode 100644 index 0000000..f0f7e6b --- /dev/null +++ b/frontend/src/components/JobDetail.vue @@ -0,0 +1,38 @@ + + diff --git a/frontend/src/components/MathText.vue b/frontend/src/components/MathText.vue new file mode 100644 index 0000000..def7891 --- /dev/null +++ b/frontend/src/components/MathText.vue @@ -0,0 +1,17 @@ + + diff --git a/frontend/src/format.ts b/frontend/src/format.ts new file mode 100644 index 0000000..8805571 --- /dev/null +++ b/frontend/src/format.ts @@ -0,0 +1,34 @@ +import type { Job, TaskType } from './types' +export const taskLabels: Record = { + 'image.generate': '图像生成', 'video.generate': '视频生成', 'defect.generate': '缺陷样本', + 'audio.transcribe': '语音转写', 'audio.speech': '语音生成', 'math.solve': '数学推演', + 'media.structure': '素材理解', 'video.compose': '成片合成', +} +export const activeStates = new Set(['scheduled', 'submitting', 'queued', 'running', 'collecting', 'cancelling']) +export function isActive(job: Job) { return activeStates.has(job.state) } +export function stateLabel(job: Job) { + if (job.cancel_requested && isActive(job)) return '正在取消' + if (job.state === 'queued' && job.preemptions > 0) return '等待自动重试' + return { scheduled: '预约中', submitting: '正在提交', queued: '等待算力', running: '正在创作', collecting: '正在归档', cancelling: '正在取消', succeeded: '已完成', failed: '未完成', cancelled: '已取消', timed_out: '已超时' }[job.state] +} +export function reasonText(reason: string | null) { + if (!reason) return '' + if (/monitor|nvidia_query|stale|snapshot|监控/i.test(reason)) return '正在确认算力状态,任务将自动重试' + if (/external|foreign|other|busy|占用/i.test(reason)) return '已让出算力,等待空闲后自动重试' + return reason +} +export function phaseLabel(job: Job) { + if (job.error) return job.error.message + if (job.sync_warning) return job.sync_warning + if (job.cancel_requested && isActive(job)) return '等待当前进程释放资源' + if (job.state === 'queued' && job.preemptions) return reasonText(job.last_preempted_reason) + if (job.state === 'queued') return job.queue_position === null ? '等待空闲算力,任务会自动开始' : `队列位置 ${job.queue_position}` + if (job.state === 'scheduled') return job.scheduled_at ? `预约 ${formatDate(job.scheduled_at)}` : '等待预约时间' + if (job.state === 'collecting') return '正在安全保存最终产物' + if (job.state === 'running') return job.attempt_count > 1 ? `第 ${job.attempt_count} 次尝试 · ${job.phase || '执行中'}` : ({ loading: '正在加载模型', upscale: '正在增强画质', executing: '模型正在生成', launching: '正在准备模型' }[job.phase] || '模型正在执行') + return job.state === 'succeeded' ? '产物已归档到素材库' : '' +} +export function formatDate(value: string | null) { return value ? new Intl.DateTimeFormat('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false }).format(new Date(value)) : '—' } +export function formatBytes(bytes: number) { if (bytes < 1024) return `${bytes} B`; if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`; return `${(bytes / 1048576).toFixed(1)} MB` } +export function formatDuration(value: number | null) { if (value === null) return '—'; return value >= 60 ? `${Math.floor(value / 60)}:${Math.round(value % 60).toString().padStart(2, '0')}` : `${value.toFixed(1)} 秒` } +export async function copyText(value: string) { await navigator.clipboard.writeText(value) } diff --git a/frontend/src/inspirations.ts b/frontend/src/inspirations.ts new file mode 100644 index 0000000..727b075 --- /dev/null +++ b/frontend/src/inspirations.ts @@ -0,0 +1,6 @@ +export const inspirations = [ + { id: 'teapot', image: '/inspiration/qwen-image.png', title: '把日常,放进一束光', category: '产品摄影', model: 'Qwen-Image', size: '1024 × 1024', prompt: '一把红釉陶瓷茶壶放在浅色木桌上,午后自然侧光,柔和阴影,真实产品摄影,干净背景。' }, + { id: 'robot', image: '/inspiration/wan-middle.png', title: '让小小角色,拥有下一秒', category: '动态分镜', model: 'Wan2.2 · 视频帧', size: '1920 × 1080', prompt: '一只橙色玩具机器人站在桌面上,轻轻挥手,镜头缓慢靠近,温暖自然光,保持角色造型一致。' }, + { id: 'metal', image: '/inspiration/sdxl-controlnet.png', title: '看见材质的细微变化', category: '工业材质', model: 'SDXL + ControlNet', size: '768 × 768', prompt: '拉丝金属零件表面的细长划痕,真实工业摄影,保留零件边缘和原始结构,清晰的金属质感。' }, + { id: 'light', image: '/inspiration/priority-retry-image.png', title: '在留白中,寻找新的构图', category: '光影练习', model: 'Qwen-Image', size: '512 × 512', prompt: '红色陶瓷茶壶置于木桌上,暖色窗光与大面积留白,安静简洁的生活摄影。' }, +] diff --git a/frontend/src/main.ts b/frontend/src/main.ts new file mode 100644 index 0000000..9d68e55 --- /dev/null +++ b/frontend/src/main.ts @@ -0,0 +1,15 @@ +import { createApp } from 'vue' +import { createPinia } from 'pinia' +import ElementPlus from 'element-plus' +import zhCn from 'element-plus/es/locale/lang/zh-cn' +import 'element-plus/dist/index.css' +import 'element-plus/theme-chalk/dark/css-vars.css' +import 'katex/dist/katex.min.css' +import '@fontsource-variable/noto-sans-sc' +import './style.css' +import App from './App.vue' +import { router } from './router' +document.documentElement.classList.add('dark') +const app=createApp(App) +app.use(createPinia()).use(ElementPlus,{locale:zhCn}).use(router) +void router.isReady().then(()=>app.mount('#app')) diff --git a/frontend/src/router.ts b/frontend/src/router.ts new file mode 100644 index 0000000..fc62b75 --- /dev/null +++ b/frontend/src/router.ts @@ -0,0 +1,15 @@ +import { createRouter, createWebHistory } from 'vue-router' +import { useAuthStore } from './stores/auth' +export const router=createRouter({history:createWebHistory(),routes:[ + {path:'/login',component:()=>import('./views/LoginView.vue'),meta:{public:true,title:'登录'}}, + {path:'/',redirect:'/create/image'}, + {path:'/create/:mode',component:()=>import('./views/WorkbenchView.vue'),meta:{title:'创作工作台'}}, + {path:'/audio',component:()=>import('./views/ToolsView.vue'),meta:{title:'声音工作台'}}, + {path:'/math',component:()=>import('./views/ToolsView.vue'),meta:{title:'数学推演'}}, + {path:'/analyze',component:()=>import('./views/ToolsView.vue'),meta:{title:'素材理解'}}, + {path:'/compose',component:()=>import('./views/ComposeView.vue'),meta:{title:'成片编排'}}, + {path:'/assets',component:()=>import('./views/AssetsView.vue'),meta:{title:'素材库'}}, + {path:'/tasks',component:()=>import('./views/TasksView.vue'),meta:{title:'任务中心'}}, + {path:'/:pathMatch(.*)*',redirect:'/create/image'}, +]}) +router.beforeEach(async to=>{const auth=useAuthStore();if(!auth.checked)await auth.load();if(!to.meta.public&&!auth.user)return{path:'/login',query:{redirect:to.fullPath}};if(to.path==='/login'&&auth.user)return'/create/image';document.title=`${String(to.meta.title||'创作工作台')} · CMVR Visual`}) diff --git a/frontend/src/stores/assets.ts b/frontend/src/stores/assets.ts new file mode 100644 index 0000000..e4ea8d3 --- /dev/null +++ b/frontend/src/stores/assets.ts @@ -0,0 +1,20 @@ +import { defineStore } from 'pinia' +import { ref } from 'vue' +import { api } from '../api' +import type { Asset } from '../types' + +export const useAssetsStore = defineStore('assets', () => { + const byId = ref>({}) + const revision = ref(0) + const remoteRevision = ref(0) + let epoch = 0 + function upsert(asset: Asset) { byId.value[asset.id] = asset; revision.value++ } + function forget(id: string) { delete byId.value[id]; revision.value++ } + async function get(id: string) { const session = epoch; const asset = await api.asset(id); if (session === epoch) upsert(asset); return asset } + async function upload(file: File) { const session = epoch; const asset = await api.upload(file); if (session === epoch) upsert(asset); return asset } + async function update(id: string, patch: { name?: string; tags?: string[]; favorite?: boolean }) { const session = epoch; const asset = await api.updateAsset(id, patch); if (session === epoch) upsert(asset); return asset } + async function remove(id: string) { await api.deleteAsset(id); forget(id) } + function notifyRemote() { remoteRevision.value++ } + function clear() { epoch++; byId.value = {}; revision.value++; remoteRevision.value++ } + return { byId, revision, remoteRevision, notifyRemote, clear, upsert, forget, get, upload, update, remove } +}) diff --git a/frontend/src/stores/auth.ts b/frontend/src/stores/auth.ts new file mode 100644 index 0000000..575f940 --- /dev/null +++ b/frontend/src/stores/auth.ts @@ -0,0 +1,21 @@ +import { defineStore } from 'pinia' +import { ref } from 'vue' +import { api, setCsrfToken } from '../api' +import type { User } from '../types' + +export const useAuthStore = defineStore('auth', () => { + const user = ref(null) + const checked = ref(false) + function clear() { user.value = null; checked.value = true; setCsrfToken('') } + async function load() { + try { const response = await api.me(); user.value = response.user; setCsrfToken(response.csrf_token) } + catch { clear() } + finally { checked.value = true } + } + async function login(username: string, password: string) { + const response = await api.login(username, password) + user.value = response.user; checked.value = true; setCsrfToken(response.csrf_token) + } + async function logout() { await api.logout(); clear() } + return { user, checked, clear, load, login, logout } +}) diff --git a/frontend/src/stores/capabilities.ts b/frontend/src/stores/capabilities.ts new file mode 100644 index 0000000..d819477 --- /dev/null +++ b/frontend/src/stores/capabilities.ts @@ -0,0 +1,21 @@ +import { defineStore } from 'pinia' +import { ref } from 'vue' +import { api } from '../api' +import type { Capability, Scheduler, TaskType } from '../types' + +export const useCapabilitiesStore = defineStore('capabilities', () => { + const items = ref([]) + const scheduler = ref(null) + const loading = ref(false) + const error = ref('') + const environment = ref<'production' | 'preview' | 'test' | null>(null) + const databaseBackend = ref<'mysql' | 'sqlite' | null>(null) + async function load() { + loading.value = true + try { const [response, status] = await Promise.all([api.capabilities(), api.systemStatus()]); items.value = response.items; scheduler.value = status.scheduler || response.scheduler; environment.value = status.environment; databaseBackend.value = status.database_backend; error.value = '' } + catch (caught) { error.value = caught instanceof Error ? caught.message : '无法读取模型能力' } + finally { loading.value = false } + } + function forTask(type: TaskType) { return items.value.find(item => item.task_type === type) } + return { items, scheduler, loading, error, environment, databaseBackend, load, forTask } +}) diff --git a/frontend/src/stores/drafts.ts b/frontend/src/stores/drafts.ts new file mode 100644 index 0000000..d9dd580 --- /dev/null +++ b/frontend/src/stores/drafts.ts @@ -0,0 +1,14 @@ +import { defineStore } from 'pinia' +import { reactive } from 'vue' +import type { TaskType } from '../types' +export interface Draft { prompt: string; negative_prompt: string; parameters: Record; imageAssetId: string | null; count: number; scheduledAt: string | null } +export const useDraftsStore = defineStore('drafts', () => { + const drafts = reactive>({}) + function forTask(type: TaskType, defaults: Record = {}) { + if (!drafts[type]) drafts[type] = { prompt: '', negative_prompt: '', parameters: { ...defaults }, imageAssetId: null, count: 1, scheduledAt: null } + for (const [key, value] of Object.entries(defaults)) if (drafts[type]!.parameters[key] === undefined) drafts[type]!.parameters[key] = value + return drafts[type]! + } + function clear() { for (const key of Object.keys(drafts)) delete drafts[key] } + return { drafts, forTask, clear } +}) diff --git a/frontend/src/stores/jobs.test.ts b/frontend/src/stores/jobs.test.ts new file mode 100644 index 0000000..a6bce03 --- /dev/null +++ b/frontend/src/stores/jobs.test.ts @@ -0,0 +1,107 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createPinia, setActivePinia } from 'pinia' +import { useJobsStore } from './jobs' +import type { Job } from '../types' +import { api } from '../api' + +class FakeEventSource { + static instances: FakeEventSource[] = [] + onopen: (() => void) | null = null + onerror: (() => void) | null = null + listeners: Record void> = {} + close = vi.fn() + constructor(public url: string) { FakeEventSource.instances.push(this) } + addEventListener(name: string, listener: (event: any) => void) { this.listeners[name] = listener } + update(value: Job, id: number) { this.listeners['job.updated']?.({ data: JSON.stringify({ job: value }), lastEventId: String(id) }) } +} + +function job(overrides: Partial = {}): Job { + return { + id: 'job-a', task_type: 'image.generate', state: 'running', phase: 'executing', version: 4, + prompt: '红釉茶壶', parameters: { seed: 42 }, input_asset_ids: [], result_assets: [], result: null, + progress: null, queue_position: null, upstream_id: 'upstream-a', attempt_count: 1, + preemptions: 0, last_preempted_reason: null, cancel_requested: false, error: null, + sync_warning: null, created_at: '2026-11-10T10:00:00Z', scheduled_at: null, + started_at: '2026-11-10T10:00:02Z', finished_at: null, ...overrides, + } +} + +describe('durable task updates', () => { + beforeEach(() => setActivePinia(createPinia())) + afterEach(() => { useJobsStore().reset(); vi.restoreAllMocks(); vi.unstubAllGlobals(); FakeEventSource.instances = [] }) + + it('accepts a higher-version running-to-queued preemption without inventing failure', () => { + const store = useJobsStore() + store.applyJob(job()) + store.applyJob(job({ version: 5, state: 'queued', phase: 'preempted', preemptions: 1, + last_preempted_reason: 'external_gpu_usage', started_at: null })) + expect(store.byId['job-a']?.state).toBe('queued') + expect(store.byId['job-a']?.preemptions).toBe(1) + expect(store.byId['job-a']?.error).toBeNull() + }) + + it('discards older and equal versions so stale HTTP snapshots cannot undo SSE', () => { + const store = useJobsStore() + store.applyJob(job({ version: 8, state: 'succeeded', phase: 'completed', finished_at: '2026-11-10T10:03:00Z' })) + store.ingestSnapshot([job({ version: 7 }), job({ version: 8, state: 'queued' })], 40) + expect(store.byId['job-a']?.state).toBe('succeeded') + expect(store.byId['job-a']?.version).toBe(8) + }) + + it('keeps attempt progression and the same business ID through requeue', () => { + const store = useJobsStore() + store.applyJob(job({ version: 5, state: 'queued', preemptions: 1 })) + store.applyJob(job({ version: 6, state: 'running', attempt_count: 2, preemptions: 1 })) + expect(Object.keys(store.byId)).toEqual(['job-a']) + expect(store.byId['job-a']?.attempt_count).toBe(2) + expect(store.byId['job-a']?.progress).toBeNull() + }) + + it('does not move the durable event cursor backwards on stale reconciliation', () => { + const store = useJobsStore() + store.ingestSnapshot([job()], 120) + store.applyEvent(job({ version: 6, state: 'queued', preemptions: 1 }), 125) + store.ingestSnapshot([job({ version: 5 })], 121) + expect(store.cursor).toBe(125) + expect(store.byId['job-a']?.version).toBe(6) + expect(store.byId['job-a']?.state).toBe('queued') + }) + + it('waits for a successful HTTP snapshot before opening the SSE stream', async () => { + vi.stubGlobal('EventSource', FakeEventSource) + vi.spyOn(api, 'jobs').mockRejectedValue(new Error('offline')) + const store = useJobsStore() + await store.connect() + expect(FakeEventSource.instances).toHaveLength(0) + expect(store.connection).toBe('reconnecting') + }) + + it('starts from the snapshot cursor and reconciles HTTP after stream reconnection', async () => { + vi.stubGlobal('EventSource', FakeEventSource) + const fetchJobs = vi.spyOn(api, 'jobs').mockResolvedValue({ items: [job()], cursor: 40, total: 1, page: 1, page_size: 48 }) + const store = useJobsStore() + await store.connect() + const source = FakeEventSource.instances[0]! + expect(source.url).toBe('/api/events?after=40') + source.onopen?.() + source.update(job({ version: 5, state: 'queued', preemptions: 1 }), 41) + source.onopen?.() + await vi.waitFor(() => expect(fetchJobs).toHaveBeenCalledTimes(2)) + expect(store.byId['job-a']?.state).toBe('queued') + expect(store.byId['job-a']?.version).toBe(5) + expect(store.cursor).toBe(41) + }) + + it('closes the stream and rejects late events after signing out', async () => { + vi.stubGlobal('EventSource', FakeEventSource) + vi.spyOn(api, 'jobs').mockResolvedValue({ items: [job()], cursor: 40, total: 1, page: 1, page_size: 48 }) + const store = useJobsStore() + await store.connect() + const source = FakeEventSource.instances[0]! + store.reset() + source.update(job({ version: 9, state: 'succeeded' }), 50) + expect(source.close).toHaveBeenCalledOnce() + expect(store.byId).toEqual({}) + expect(store.cursor).toBe(0) + }) +}) diff --git a/frontend/src/stores/jobs.ts b/frontend/src/stores/jobs.ts new file mode 100644 index 0000000..f8df1b6 --- /dev/null +++ b/frontend/src/stores/jobs.ts @@ -0,0 +1,94 @@ +import { defineStore } from 'pinia' +import { computed, ref } from 'vue' +import { api } from '../api' +import { isActive } from '../format' +import type { Job, JobRequest } from '../types' +import { useAssetsStore } from './assets' + +export const useJobsStore = defineStore('jobs', () => { + const byId = ref>({}) + const cursor = ref(0) + const connection = ref<'idle' | 'connecting' | 'live' | 'reconnecting'>('idle') + const loaded = ref(false) + const recent = computed(() => Object.values(byId.value).sort((a, b) => b.created_at.localeCompare(a.created_at))) + const active = computed(() => recent.value.filter(isActive)) + let stream: EventSource | null = null + let refreshPending: Promise | null = null + let epoch = 0 + let recoveryTimer: ReturnType | undefined + + function applyJob(job: Job) { + const old = byId.value[job.id] + if (old && old.version >= job.version) return false + byId.value[job.id] = job + const assets = useAssetsStore() + for (const asset of job.result_assets || []) assets.upsert(asset) + return true + } + function ingestSnapshot(jobs: Job[], after: number) { + for (const job of jobs) applyJob(job) + cursor.value = Math.max(cursor.value, after || 0) + loaded.value = true + } + function applyEvent(job: Job, id: number) { applyJob(job); cursor.value = Math.max(cursor.value, id || 0) } + function refresh() { + if (refreshPending) return refreshPending + const session = epoch + const pending = api.jobs({ page_size: 48 }).then(response => { + if (session === epoch) ingestSnapshot(response.items, response.cursor) + }).finally(() => { if (refreshPending === pending) refreshPending = null }) + refreshPending = pending + return refreshPending + } + async function fetchOne(id: string) { const session = epoch; const job = await api.job(id); if (session === epoch) applyJob(job); return job } + async function submit(body: JobRequest) { const session = epoch; const response = await api.submit(body); if (session === epoch) response.jobs.forEach(applyJob); return response.jobs } + async function cancel(id: string) { const session = epoch; const job = await api.cancel(id); if (session === epoch) applyJob(job); return job } + async function retry(id: string) { const session = epoch; const response = await api.retry(id); if (session === epoch) response.jobs.forEach(applyJob); return response.jobs } + function disconnect() { + epoch++; stream?.close(); stream = null + clearTimeout(recoveryTimer); connection.value = 'idle' + refreshPending = null + } + function reset() { disconnect(); byId.value = {}; cursor.value = 0; loaded.value = false } + async function connect() { + if (stream || connection.value === 'connecting') return + connection.value = 'connecting' + const session = epoch + try { await refresh() } catch { + if (session === epoch) { + connection.value = 'reconnecting' + recoveryTimer = setTimeout(() => { void connect() }, 2000) + } + return + } + if (session !== epoch) return + const source = new EventSource(`/api/events?after=${cursor.value}`, { withCredentials: true }) + stream = source + let opened = false + source.onopen = () => { + if (session !== epoch) return + connection.value = 'live' + if (opened) { void refresh().catch(() => undefined); useAssetsStore().notifyRemote() } + opened = true + } + const listen = (event: string, operation: (value: any, id: number) => void) => { + source.addEventListener(event, ((message: MessageEvent) => { + if (session !== epoch) return + try { operation(JSON.parse(message.data), Number(message.lastEventId) || 0) } + catch { void refresh().catch(() => undefined) } + }) as EventListener) + } + listen('job.updated', (value, id) => { if (value.job) applyEvent(value.job, id) }) + listen('asset.created', (value, id) => { useAssetsStore().upsert(value.asset); useAssetsStore().notifyRemote(); cursor.value = Math.max(cursor.value, id) }) + listen('asset.updated', (value, id) => { useAssetsStore().upsert(value.asset); useAssetsStore().notifyRemote(); cursor.value = Math.max(cursor.value, id) }) + listen('asset.deleted', (value, id) => { useAssetsStore().forget(value.id); useAssetsStore().notifyRemote(); cursor.value = Math.max(cursor.value, id) }) + listen('reset', () => { void refresh().catch(() => undefined); useAssetsStore().notifyRemote() }) + source.onerror = () => { + if (session !== epoch) return + connection.value = 'reconnecting' + clearTimeout(recoveryTimer) + recoveryTimer = setTimeout(() => { void refresh().catch(() => undefined) }, 2000) + } + } + return { byId, cursor, connection, loaded, recent, active, applyJob, ingestSnapshot, applyEvent, refresh, fetchOne, submit, cancel, retry, connect, disconnect, reset } +}) diff --git a/frontend/src/style.css b/frontend/src/style.css new file mode 100644 index 0000000..fdabb61 --- /dev/null +++ b/frontend/src/style.css @@ -0,0 +1,18 @@ +:root,html.dark{--el-font-family:'Noto Sans SC Variable',Inter,'PingFang SC','Microsoft YaHei',sans-serif;font-family:var(--el-font-family);color:#e9edf2;background:#0e1116;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;--accent:#75e4ce;--muted:#89939f;--subtle:#5a6572;--panel:#171c23;--line:rgba(255,255,255,.075);--el-color-primary:#75e4ce;--el-color-primary-light-3:#95ecdb;--el-color-primary-light-5:#afeedf;--el-color-primary-dark-2:#52cbb3;--el-bg-color:#171c23;--el-bg-color-overlay:#20262f;--el-fill-color-blank:#171c23;--el-fill-color-light:#222932;--el-fill-color:#242c35;--el-fill-color-darker:#2c3541;--el-border-color:#343d48;--el-border-color-light:#2c3540;--el-text-color-primary:#e9edf2;--el-text-color-regular:#b5bfca;--el-text-color-secondary:#8d98a6;--el-text-color-placeholder:#606d7b;--el-mask-color:rgba(0,0,0,.72);--el-border-radius-base:8px;--el-font-size-base:13px} +*{box-sizing:border-box}html,body,#app{margin:0;min-width:360px;width:100%;height:100%;overflow:hidden}body{font-size:14px}button,input,textarea{font:inherit}button{cursor:pointer}button:disabled{cursor:not-allowed}a{color:inherit;text-decoration:none}button{color:inherit}button:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:4px}::selection{background:#75e4ce33;color:#fff}img,video{display:block;max-width:100%}button{border:0;background:none}button,a{-webkit-tap-highlight-color:transparent}h1,h2,h3,p{margin-top:0}h1,h2,h3{color:#f4f6f9}h1{font-weight:600;letter-spacing:-1.3px}h2{font-size:17px;font-weight:600}h3{font-size:14px;font-weight:600}.muted{color:var(--muted);line-height:1.8}.small,small{font-size:12px}.eyebrow{display:block;color:#8faba7;font-size:10px;letter-spacing:2.5px;font-weight:600;line-height:1.6}.text-link{color:var(--accent);font-size:12px;background:none;border:0}.surface{background:var(--panel);border:1px solid var(--line);border-radius:16px}.el-button{font-weight:500;gap:4px}.el-button--primary{--el-button-text-color:#132620;--el-button-hover-text-color:#10251f;--el-button-active-text-color:#10251f;font-weight:600}.el-input__wrapper,.el-textarea__inner{background:#12171e;box-shadow:0 0 0 1px var(--line) inset}.el-input__wrapper.is-focus,.el-textarea__inner:focus{box-shadow:0 0 0 1px #75e4ce77 inset}.el-select__wrapper{background:#151b23}.el-input-number{max-width:155px}.el-form-item__label{color:#b3becb!important}.el-dialog{max-width:calc(100vw - 32px);border:1px solid #ffffff14;border-radius:16px;padding:22px;background:#171c24}.el-dialog__header,.el-drawer__header{color:#e7ecf2;font-weight:600}.el-drawer{max-width:100vw;background:#141a22!important;border-left:1px solid var(--line)}.el-drawer__header{margin-bottom:10px}.el-drawer__body{padding:20px 24px}.el-popover.el-popper{padding:18px;border:1px solid #ffffff12;border-radius:12px;background:#1b222c}.el-overlay{backdrop-filter:blur(6px)}.el-message{border-radius:12px;background:#202a31;border:1px solid var(--line)}.el-pagination{justify-content:center;padding:30px 0}.el-loading-mask{background:rgba(14,17,22,.72)}.el-button+.el-button{margin-left:0}textarea{resize:vertical}.el-select{min-width:120px}audio{max-width:100%}pre{white-space:pre-wrap;overflow-wrap:anywhere}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:#35404b;border-radius:6px} +.app-shell{display:flex;height:100dvh;width:100%;background:radial-gradient(ellipse at 70% -20%,#1d2e3022,transparent 65%),#0e1116}.sidebar{width:80px;flex-shrink:0;border-right:1px solid var(--line);display:flex;flex-direction:column;align-items:center;background:#11151b;z-index:20}.brand{height:100px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:7px}.brand-glyph{width:33px;height:33px;display:grid;place-items:center;background:linear-gradient(145deg,#b5f6dd,#55c8b6);color:#173a32;border-radius:10px;font-weight:800;font-family:Arial,sans-serif;font-size:24px;box-shadow:0 3px 20px #70d8c414}.brand-caption{font-size:9px;letter-spacing:2px;color:#e3eae8;font-weight:700}.side-nav{width:100%;display:flex;flex-direction:column;gap:8px;padding:5px 11px}.side-nav a{height:59px;border-radius:10px;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:7px;position:relative;color:#83909c;font-size:11px;transition:background .2s,color .2s}.side-nav .el-icon{font-size:21px}.side-nav a:hover{color:#d9e4e7;background:#ffffff05}.side-nav a.selected{background:#74e4ce12;color:#8ee9d5}.side-nav a.selected:before{content:'';position:absolute;left:-11px;height:22px;width:2px;background:var(--accent);border-radius:3px}.nav-notification{width:5px;height:5px;border-radius:50%;background:var(--accent);position:absolute;top:10px;right:12px}.sidebar-bottom{margin-top:auto;display:flex;flex-direction:column;align-items:center;gap:20px;padding:24px 0}.sidebar-bottom>button{font-size:20px;color:#7b8895}.avatar-button{width:32px;height:32px;background:#314944;color:#a6e6d6;border:1px solid #77dab733;border-radius:50%;font-size:12px;font-weight:600}.app-main{display:flex;flex-direction:column;flex:1;min-width:0;position:relative;height:100dvh}.app-header{height:64px;flex-shrink:0;display:flex;align-items:center;justify-content:space-between;padding:0 34px;border-bottom:1px solid #ffffff04}.header-breadcrumb{display:flex;align-items:center;gap:13px;font-size:12px;color:#7e8996}.header-breadcrumb>span:first-child{font-size:13px;letter-spacing:.3px;color:#d3dbe3}.header-breadcrumb strong{font-weight:400;color:#a2adba}.breadcrumb-separator{color:#48515b}.header-actions{display:flex;align-items:center;gap:15px;font-size:11px;color:#71808c}.header-divider{height:13px;width:1px;background:#303842}.connection-status{display:flex;align-items:center;gap:7px;color:#8d9ca8;font-size:11px}.connection-status.live{color:#a4bdb7}.connection-status.reconnecting .live-dot{background:#d5af68}.live-dot{display:inline-block;height:5px;width:5px;border-radius:50%;background:#77d8bc;box-shadow:0 0 8px #5fceb333}.page-content{min-height:0;flex:1;position:relative;overflow:hidden}.connection-banner{display:flex;gap:10px;align-items:center;background:#bd955c10;border-bottom:1px solid #bd955c22;color:#ccb28a;font-size:12px;padding:8px 34px}.connection-banner button{color:#e3c38d;text-decoration:underline}.global-queue-bar{position:absolute;z-index:12;bottom:14px;left:50%;transform:translateX(-50%);max-width:calc(100% - 40px);display:flex;align-items:center;gap:12px;padding:11px 18px;border:1px solid #6abca83a;background:#172a25ee;backdrop-filter:blur(16px);border-radius:40px;box-shadow:0 6px 24px #0005;font-size:11px;white-space:nowrap}.global-queue-bar strong{color:#b7eddd;font-size:12px}.global-queue-bar>span:not(.queue-spinner){max-width:320px;overflow:hidden;text-overflow:ellipsis;color:#98aaa5}.global-queue-bar small{color:#798d87}.queue-spinner{width:11px;height:11px;border:1.5px solid #6d9b8c;border-top-color:#b7efd8;border-radius:50%;animation:spin 1.1s linear infinite} +.workbench{display:flex;flex-direction:column;height:100%}.workspace-scroll{flex:1;overflow:auto;padding:0 40px 28px}.workspace-topline{display:flex;justify-content:space-between;align-items:center;padding:14px 0 0}.mode-switch{display:flex;gap:4px;background:#151a21;border:1px solid #ffffff05;border-radius:9px;padding:4px}.mode-switch a,.mode-switch button{font-size:12px;color:#7e8a98;padding:9px 17px;border-radius:6px;white-space:nowrap}.mode-switch a.router-link-active,.mode-switch button.active{background:#2a333d;color:#e8edf2;box-shadow:0 2px 6px #0002}.quiet-note{font-size:10px;letter-spacing:.2px;color:#56636f}.creative-heading{padding:37px 0 29px}.creative-heading .eyebrow{color:#728f87;font-size:9px;letter-spacing:2.4px;margin-bottom:13px}.creative-heading h1{font-size:32px;line-height:1.45;margin-bottom:10px;font-weight:500;letter-spacing:-.9px}.creative-heading p{font-size:12px;color:#7d8b99;letter-spacing:.1px;margin-bottom:0;line-height:1.8}.section-heading{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-bottom:16px}.section-heading h2{font-size:14px;margin-bottom:0;color:#d4dde6;font-weight:500}.section-heading h2 span{font-size:11px;color:#687786;margin-left:6px}.section-heading p{font-size:11px;color:#62717e;margin:7px 0 0}.section-heading a{font-size:11px;color:#8e9eac;display:flex;align-items:center;gap:7px}.outline-label{border:1px solid #ffffff0e;padding:5px 8px;font-size:8px;letter-spacing:1.5px;color:#6c7f85;border-radius:4px}.inspiration-section{margin-top:5px}.inspiration-grid{display:grid;grid-template-columns:1.2fr 1fr 1fr;gap:16px}.inspiration-card{height:294px;position:relative;overflow:hidden;background:#1a2027;border-radius:13px;border:1px solid #ffffff08}.inspiration-card:nth-child(4){height:225px}.inspiration-card img{width:100%;height:100%;object-fit:cover;transition:transform .6s cubic-bezier(.2,.65,.3,1)}.inspiration-card:nth-child(2) img{object-position:73% center}.inspiration-card:hover img{transform:scale(1.035)}.sample-label{position:absolute;top:12px;left:12px;font-size:9px;padding:5px 8px;background:#141b1cc4;backdrop-filter:blur(8px);border:1px solid #ffffff16;border-radius:4px;color:#d2dbd8;letter-spacing:.5px}.inspiration-gradient{position:absolute;inset:0;padding:18px;display:flex;flex-direction:column;justify-content:flex-end;background:linear-gradient(transparent 28%,#080e1233 49%,#0a1013e6 100%)}.inspiration-gradient>span{font-size:9px;color:#ccd0caa6;letter-spacing:.5px}.inspiration-gradient h3{font-size:16px;line-height:1.7;font-weight:500;margin:7px 0 12px;color:#eef3ed}.inspiration-actions{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.inspiration-actions button{font-size:10px;display:flex;align-items:center;gap:8px;color:#deeee4;padding:5px 0}.inspiration-actions button+button{font-size:9px;margin-left:auto;color:#9bc0b3}.inspiration-actions button:hover{color:var(--accent)}.inspiration-actions .el-icon{font-size:12px}.results-section{margin-bottom:30px}.results-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px}.result-card{background:#151b23;border:1px solid #ffffff07;border-radius:12px;overflow:hidden;transition:border .2s}.result-card:hover{border-color:#90ad9e38}.result-media{display:block;position:relative;width:100%;aspect-ratio:1.15;background:#121922;padding:0;overflow:hidden}.result-media>img,.result-media>video{width:100%;height:100%;object-fit:cover}.media-badge{position:absolute;left:11px;top:11px;display:flex;align-items:center;gap:5px;border-radius:5px;background:#15201ed9;color:#c2d4cd;font-size:9px;padding:5px 7px;backdrop-filter:blur(8px)}.media-badge i{width:4px;height:4px;border-radius:50%;background:#85c9ae}.media-badge.failed{background:#341b1be6;color:#db9c97}.media-badge.failed i{background:#e08c86}.pulse{animation:pulse 1.8s ease-in-out infinite}.play-circle{position:absolute;inset:0;margin:auto;width:38px;height:38px;border:1px solid #ffffff70;border-radius:50%;display:grid;place-items:center;background:#09130f55;color:white;font-size:22px}.result-caption{padding:12px 13px}.result-kicker{display:flex;justify-content:space-between;align-items:center;color:#87a095;font-size:9px}.icon-button{font-size:17px;color:#8895a2;padding:1px 3px;display:flex}.result-prompt{padding:3px 0 9px;text-align:left;font-size:12px;line-height:1.6;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;overflow:hidden;color:#cbd5df;min-height:45px}.result-footnote{display:flex;justify-content:space-between;font-size:9px;color:#606f7c}.pending-art{height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:24px;gap:14px;background:radial-gradient(ellipse,#29433d22,transparent 65%)}.pending-art strong{font-size:12px;color:#a6bdb5;font-weight:500}.pending-art>span{color:#657d74;font-size:10px;line-height:1.8;max-width:180px}.generation-orbit{position:relative;width:48px;height:48px;border:1px solid #75e4ce21;border-radius:50%;display:block;margin:7px auto 18px}.generation-orbit:before{content:'';position:absolute;inset:7px;border:1px solid transparent;border-top-color:#75e4ce8a;border-bottom-color:#75e4ce30;border-radius:50%;animation:spin 2.5s linear infinite}.generation-orbit:after{content:'';position:absolute;inset:17px;background:#79dac7;border-radius:50%;box-shadow:0 0 22px #75e4ce48} +.composer-wrap{padding:14px 40px 16px;flex-shrink:0;background:linear-gradient(#0e1116dd,#0e1116);z-index:9}.app-main:has(.global-queue-bar) .composer-wrap{padding-bottom:53px}.prompt-composer{max-width:1120px;margin:0 auto;border:1px solid #ffffff1a;border-radius:15px;background:linear-gradient(135deg,#1b232a,#171d25);box-shadow:0 10px 40px #0003,inset 0 1px 0 #ffffff05;padding:15px 18px 13px}.prompt-composer>textarea{display:block;width:100%;height:66px;min-height:48px;max-height:150px;padding:6px 1px 12px;background:none;border:0;color:#dde8e9;font-size:13px;line-height:1.9;outline:none;resize:vertical}.prompt-composer>textarea::placeholder{color:#60717d}.composer-controls{display:flex;justify-content:space-between;align-items:center;gap:10px}.composer-parameters{display:flex;align-items:center;gap:7px;flex-wrap:wrap}.model-chip{font-size:10px;color:#bdccc9;display:flex;align-items:center;gap:7px;max-width:240px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:6px 8px;background:#222f30;border-radius:6px}.model-mark{width:15px;height:15px;background:#88d9cba1;color:#132e27;font-size:10px;display:grid;place-items:center;border-radius:4px;font-weight:800}.parameter-chip{display:flex;align-items:center;gap:5px;font-size:10px;color:#99a8b4;padding:7px 9px;border:1px solid #ffffff0b;border-radius:6px;white-space:nowrap;background:#1d252e}.parameter-chip:hover,.parameter-chip.highlighted{color:#baeadd;border-color:#75e4ce44}.count-select{width:70px;min-width:70px}.count-select .el-select__wrapper{min-height:29px;font-size:10px;border:1px solid #ffffff0b;background:#1d252e;box-shadow:none;padding:3px 7px}.generate-button.el-button{height:36px;border-radius:8px;padding:0 17px;font-size:12px}.composer-footnote{max-width:1120px;display:flex;justify-content:space-between;gap:12px;margin:9px auto 0;color:#566570;font-size:9px;line-height:1.5}.parameter-form{display:flex;flex-direction:column;gap:14px}.parameter-form h3{margin:0 0 2px;font-size:13px}.parameter-form label{display:flex;align-items:center;justify-content:space-between;gap:12px;font-size:11px;color:#a6b3c2}.parameter-form .el-input-number{width:145px}.parameter-form .el-input-number .el-input__inner{font-size:11px}.parameter-form .vertical-label{flex-direction:column;align-items:stretch;gap:8px}.parameter-form small{color:#6d7e8b;line-height:1.8;font-size:10px}.parameter-form .el-select{max-width:160px}.ratio-options{display:flex;gap:8px}.ratio-options button{flex:1;padding:9px;border:1px solid var(--line);border-radius:6px;font-size:11px;color:#abc1b8}.asset-input{position:relative;background:#10171e;border:1px dashed #667e8840;border-radius:10px;display:flex;align-items:center;min-height:120px;overflow:hidden}.asset-input.populated{min-height:68px;padding:8px 10px;gap:12px;border-style:solid}.asset-input>img{width:52px;height:52px;border-radius:6px;object-fit:cover}.asset-input-description{min-width:0;flex:1}.asset-input-description strong{display:block;font-size:11px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;color:#b8cbd0;font-weight:500}.asset-input-description small{display:block;color:#627b80;font-size:9px;margin-top:6px}.upload-trigger{width:100%;min-height:120px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:7px;padding:18px 10px 26px;color:#94aaa8}.upload-trigger>.el-icon{font-size:22px;margin-bottom:2px}.upload-trigger>span{font-size:12px}.upload-trigger small{font-size:10px;color:#57707a}.from-library{position:absolute;bottom:3px;right:8px;font-size:10px!important}.prompt-composer>.asset-input{min-height:62px;margin:0 0 8px}.prompt-composer>.asset-input:not(.populated){max-width:260px;min-height:61px}.prompt-composer .upload-trigger{min-height:61px;align-items:flex-start;gap:3px;padding:12px 13px}.prompt-composer .upload-trigger>.el-icon{display:none}.prompt-composer .upload-trigger>small{max-width:170px}.prompt-composer .from-library{top:16px;bottom:auto}.prompt-composer .asset-input-description small{display:none}.prompt-composer .asset-input>img{width:42px;height:42px} +.page-heading{padding:29px 0 24px}.page-heading .eyebrow{margin-bottom:12px;font-size:9px;color:#7f9e94}.page-heading h1{font-size:29px;font-weight:500;margin:0 0 13px;line-height:1.4}.page-heading p{color:#778896;font-size:12px;line-height:1.8;margin:0}.split-heading{display:flex;justify-content:space-between;align-items:center;gap:25px}.tool-page,.library-page,.tasks-page,.compose-page{height:100%;overflow:auto;padding:0 38px 80px}.panel-heading{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:22px}.panel-heading h2{margin:0;font-size:14px;font-weight:500}.tiny-model{font-size:9px;color:#819c92;max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;background:#77c9ad0b;border:1px solid #77c9ad11;border-radius:4px;padding:4px 6px}.audio-tabs{display:inline-flex;margin:0 0 22px}.audio-tabs small{font-size:8px;margin-left:4px;opacity:.55}.tool-columns{display:grid;grid-template-columns:1fr 1.1fr;gap:22px;align-items:start}.tool-input-panel,.tool-result-panel{padding:25px}.tool-textarea{width:100%;height:210px;border:0;background:#10171e;border-radius:10px;outline:none;padding:18px;color:#d3e1e4;line-height:1.9;font-size:13px}.tool-textarea::placeholder{color:#5c707d}.prompt-suggestions{display:flex;gap:8px;margin:10px 0 0}.prompt-suggestions button{font-size:10px;border:1px solid var(--line);border-radius:5px;color:#7c9a91;padding:6px 8px}.tool-parameters{margin-top:24px}.tool-submit{margin-top:24px;width:100%;height:38px}.tool-submit .el-icon:last-child{margin-left:auto}.source-audio{width:100%;height:38px;margin-top:18px}.tool-result-panel{min-height:430px}.tool-empty{min-height:320px}.inline-job-state{display:flex;align-items:center;gap:12px;margin-bottom:20px;color:#829b9d;font-size:10px;line-height:1.7}.math-text{font-family:inherit;white-space:pre-wrap;line-height:1.95;font-size:13px;color:#cbd6df;overflow-wrap:anywhere}.math-text .katex-display{overflow:auto;padding:8px 0}.tool-history{margin-top:28px}.tool-history>button{display:flex;align-items:center;width:100%;gap:15px;text-align:left;padding:14px 16px;border-bottom:1px solid #ffffff05;font-size:11px;color:#7c9298}.tool-history>button:hover,.tool-history>button.selected{background:#72c9ae06}.tool-history>button>strong{color:#a8bbc3;font-size:12px;font-weight:400;flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.tool-history>button>small{font-size:10px;color:#5b707b}.tag-cloud{display:flex;flex-wrap:wrap;gap:7px;margin:8px 0 24px}.tag-cloud>span{font-size:11px;padding:5px 9px;border:1px solid #80c7b729;background:#64bca810;border-radius:5px;color:#a4cabe}.analysis-result h3{font-size:12px;color:#9eafa9;margin-top:24px}.analysis-result p{font-size:12px;color:#c3cfd5;line-height:1.9}.analysis-result details{margin-top:22px;color:#819d97;font-size:12px}.tool-output-assets>div{display:flex;align-items:center;gap:12px;padding:12px 0;border-bottom:1px solid var(--line)}.tool-output-assets audio{width:100%;height:38px}.tool-output-assets button{font-size:12px;text-align:left;color:#a2c4bb}.segments{margin-top:24px;color:#91aaa6;font-size:12px}.segments>div{padding:12px 0;border-bottom:1px solid var(--line)}.segments code{font-size:10px;color:#687f81}.segments p{font-size:12px;color:#acbdc5;line-height:1.8;margin:8px 0}.segments small{font-size:10px} +.empty-state{display:flex;align-items:center;justify-content:center;flex-direction:column;text-align:center;padding:35px 24px;color:#70848e}.empty-state>.el-icon{color:#607e78;margin-bottom:18px}.empty-state h3{font-size:14px;color:#a5b6bc;font-weight:500;margin:0 0 10px}.empty-state p{font-size:11px;color:#637a85;line-height:1.9;max-width:310px;margin:0 0 20px}.empty-state.compact{min-height:160px;padding:25px 15px;grid-column:1/-1}.full-empty{grid-column:1/-1;min-height:380px;width:100%}.notice{padding:12px 14px;border:1px solid var(--line);border-radius:8px;font-size:11px;line-height:1.8;margin:15px 0;color:#aab9c2}.notice.warning{background:#a98b480b;border-color:#b6995730;color:#bea574}.notice.danger{background:#ad555511;border-color:#bf666633;color:#d19a95}.notice p{margin:5px 0 0}.warning-text{color:#b89e70!important}.status-pill{display:inline-flex;font-size:10px;border-radius:5px;padding:4px 7px;background:#2b343d;color:#a3b1bf;white-space:nowrap}.status-pill.running,.status-pill.collecting{color:#9ce4c9;background:#5fbd9915}.status-pill.queued,.status-pill.scheduled{color:#cdb77f;background:#c1a25713}.status-pill.succeeded{color:#9ed1bb;background:#649c8417}.status-pill.failed,.status-pill.timed_out{color:#d39990;background:#af605e18}.status-dot{width:5px;height:5px;border-radius:50%;background:#8dabb7;display:inline-block;flex-shrink:0}.status-dot.succeeded{background:#74c8a7}.status-dot.failed{background:#bd7971}.status-dot.running{background:#78dac0;box-shadow:0 0 10px #8ae8c533;animation:pulse 2s infinite}.status-dot.queued{background:#cfb77a}.status-dot.cancelled{background:#65717c}.status-dot.collecting{background:#88b7a9} +.library-toolbar{display:flex;align-items:center;justify-content:space-between;gap:20px;border-bottom:1px solid var(--line);padding-bottom:15px;margin-bottom:24px}.filter-tabs{display:flex;align-items:center;gap:19px}.filter-tabs button{font-size:11px;padding:5px 0;color:#738694;white-space:nowrap;position:relative}.filter-tabs button.active{color:#badfce}.filter-tabs button.active:after{content:'';position:absolute;height:2px;width:18px;left:0;bottom:-16px;background:#83d8b8;border-radius:1px}.library-search{display:flex;gap:8px}.library-search>.el-input{max-width:200px}.library-search>.el-input:first-child{width:105px}.asset-library-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:20px;min-height:180px}.library-card{border-radius:11px;background:#151c24;border:1px solid var(--line);position:relative;overflow:hidden}.library-media{width:100%;aspect-ratio:1.18;position:relative;padding:0;display:block;overflow:hidden;background:#0d151c}.library-media>img,.library-media>video{width:100%;height:100%;object-fit:cover;transition:transform .4s}.library-media:hover>img{transform:scale(1.035)}.favorite-button{position:absolute;right:9px;top:9px;height:27px;width:27px;display:grid;place-items:center;background:#0e171dc4;color:#adbeb8;border-radius:50%;backdrop-filter:blur(8px)}.favorite-button.selected{color:#95e5c7}.library-caption{padding:13px}.library-caption>button{padding:0;max-width:100%;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;font-size:12px;color:#b8c9d1;text-align:left}.library-caption>div{display:flex;justify-content:space-between;margin-top:10px;color:#5f7480;font-size:9px}.asset-tag-row{justify-content:flex-start!important;gap:5px;flex-wrap:wrap}.asset-tag-row>span{cursor:pointer;color:#849e95;font-size:9px;padding:3px 5px;background:#7ab09909;border-radius:3px}.media-duration{position:absolute;right:8px;bottom:8px;display:flex;align-items:center;gap:4px;font-size:9px;color:#d0dfda;background:#0d1b17bd;border-radius:3px;padding:4px 6px}.file-cover{width:100%;height:100%;min-height:100px;display:grid;place-items:center;background:radial-gradient(ellipse,#33464b45,transparent);color:#6e9d99}.picker-toolbar{display:flex;gap:8px;margin-bottom:20px}.picker-toolbar .el-input{flex:1}.picker-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:13px;min-height:220px;max-height:60vh;overflow:auto}.picker-item{border:1px solid var(--line);border-radius:8px;padding:0 0 12px;overflow:hidden;background:#121b22;text-align:left;min-width:0}.picker-item:hover{border-color:#71c6ae77}.picker-item:disabled{opacity:.3;filter:grayscale(1)}.picker-item>img,.picker-item>video{width:100%;aspect-ratio:1.15;object-fit:cover}.picker-item>.file-cover{height:110px}.picker-name{display:block;font-size:11px;padding:11px 10px 6px;color:#bdced2;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.picker-item small{display:block;font-size:9px;padding:0 10px;color:#617d87}.preview-layout{display:grid;grid-template-columns:minmax(0,1fr) 265px;gap:25px;min-height:420px}.preview-stage{border-radius:10px;overflow:hidden;background:#0c1118;display:flex;align-items:center;justify-content:center;min-height:370px;max-height:72vh}.preview-stage>img,.preview-stage>video{width:100%;height:100%;max-height:72vh;object-fit:contain}.preview-stage>pre{align-self:stretch;padding:24px;width:100%;overflow:auto;color:#b9c9d0;font-size:12px;line-height:1.9}.preview-meta .eyebrow{margin-bottom:22px}.preview-meta .el-form-item{margin-bottom:14px}.preview-meta .el-form-item__label{font-size:11px}.preview-meta>.el-button{margin:7px 0 0}.metadata-list{display:grid;grid-template-columns:50px 1fr;gap:12px;margin:24px 0;font-size:10px;line-height:1.5}.metadata-list dt{color:#5e7785}.metadata-list dd{margin:0;color:#a4b7c1;overflow-wrap:anywhere}.asset-actions{display:flex;gap:7px;margin-bottom:10px;flex-wrap:wrap}.asset-actions .el-button{font-size:11px}.audio-preview{padding:30px;max-width:100%;text-align:center}.audio-wave{font-size:24px;letter-spacing:6px;color:#6cbaa7;margin-bottom:30px;white-space:nowrap}.audio-preview audio{width:100%}.job-detail h2{font-size:20px;font-weight:500;line-height:1.7;margin:18px 0 12px}.detail-heading{display:flex;align-items:center;gap:11px}.detail-heading small{font-size:11px;color:#7a938f}.detail-actions{display:flex;gap:8px;margin:20px 0;flex-wrap:wrap}.detail-section{margin-top:28px;border-top:1px solid var(--line);padding-top:21px}.detail-section h3{font-size:12px;color:#9eb6b2;margin-bottom:17px}.detail-section h3 span{color:#5b7d77;font-size:10px;margin-left:5px}.detail-assets{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.detail-assets button{padding:0;background:#101820;border:1px solid var(--line);border-radius:7px;overflow:hidden;text-align:left}.detail-assets img{width:100%;aspect-ratio:1.2;object-fit:cover}.detail-assets strong{display:block;font-size:10px;font-weight:400;padding:11px;color:#b2c6cc;overflow-wrap:anywhere}.json-output{font-family:'SFMono-Regular',Consolas,monospace;font-size:10px;line-height:1.9;color:#85a09e;background:#0e161d;padding:14px;border-radius:7px;max-height:370px;overflow:auto}.execution-timeline{padding-left:8px}.execution-timeline>div{position:relative;border-left:1px solid #5d927d40;padding:0 0 22px 21px;display:flex;flex-direction:column;gap:8px}.execution-timeline>div:last-child{padding-bottom:3px}.execution-timeline i{position:absolute;left:-3px;top:4px;width:5px;height:5px;background:#79c0a8;border-radius:50%}.execution-timeline strong{font-size:11px;font-weight:500;color:#abc5bd}.execution-timeline span{font-size:10px;color:#6b858a;line-height:1.8}.execution-timeline code{font-size:9px;color:#576d76;overflow-wrap:anywhere}.task-identity{font-size:9px;color:#4f6974;overflow-wrap:anywhere} +.task-policy-note{font-size:11px;color:#859c93;border:1px solid #6daf9120;background:#6a9f8008;border-radius:8px;padding:12px 16px;display:flex;align-items:center;gap:10px;margin:0 0 26px}.task-filter-selects{display:flex;gap:10px}.task-filter-selects .el-select{width:130px}.task-row{display:flex;align-items:center;gap:20px;border-bottom:1px solid var(--line);padding:21px 6px}.task-thumb{height:76px;width:76px;flex-shrink:0;background:#18232b;color:#70948b;border-radius:9px;overflow:hidden;padding:0;display:grid;place-items:center;border:1px solid var(--line)}.task-thumb img{width:100%;height:100%;object-fit:cover}.task-main{flex:1;min-width:0}.task-title-line{display:flex;align-items:center;gap:10px;margin-bottom:9px}.task-title-line>small{font-size:9px;color:#798a87}.task-type{font-size:9px;color:#758a92}.task-title{display:block;font-size:13px;color:#c1d2d7;max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-align:left;padding:0;line-height:1.7}.task-main>p{color:#617d87;font-size:10px;margin:7px 0 6px}.task-main>small{font-size:9px;color:#526d79}.task-row-actions{display:flex;gap:12px;flex-shrink:0}.task-row-actions .el-button{font-size:11px} +.compose-layout{display:grid;grid-template-columns:minmax(0,1fr) 320px;gap:24px}.compose-preview{display:flex;align-items:center;justify-content:center;background:#090e14;border:1px solid var(--line);border-radius:12px;aspect-ratio:16/9;overflow:hidden}.compose-preview>video{width:100%;height:100%;object-fit:contain}.timeline-heading{display:flex;justify-content:space-between;align-items:center;margin:26px 0 15px}.timeline-heading h2{font-size:13px;margin:0}.timeline-heading h2>span{font-size:10px;color:#67858a;font-weight:400;margin-left:12px}.timeline-strip{display:flex;gap:12px;overflow:auto;padding-bottom:12px}.clip-card{border:1px solid var(--line);border-radius:8px;background:#151e26;min-width:148px;max-width:170px;flex-shrink:0;overflow:hidden;cursor:grab}.clip-card.selected{border-color:#77d5b981}.clip-thumbnail{height:87px;position:relative;background:#11171d}.clip-thumbnail img,.clip-thumbnail video{width:100%;height:100%;object-fit:cover}.clip-thumbnail>span{position:absolute;left:7px;top:7px;background:#10211bba;border-radius:3px;font-size:9px;padding:3px 5px;color:#c1d9ce}.clip-card>strong{display:block;font-size:10px;font-weight:400;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin:11px 10px 7px;color:#adc7ce}.clip-card>small{display:block;font-size:9px;color:#66858a;margin:0 10px}.clip-actions{display:flex;justify-content:space-between;padding:4px 5px}.clip-actions .el-button{padding:5px!important}.add-clip-card{min-width:135px;min-height:170px;border:1px dashed #718c8340;border-radius:8px;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:13px;color:#72958a;font-size:11px;flex-shrink:0}.add-clip-card>.el-icon{font-size:22px}.compose-settings{padding:23px 20px;height:fit-content}.settings-subheading{font-size:11px;color:#9fb8b2;margin:27px 0 15px}.compose-settings .asset-input{min-height:90px}.compose-settings .upload-trigger{min-height:90px}.compose-settings .asset-input.populated{padding:8px;gap:7px}.compose-settings .asset-input-description strong{font-size:10px}.compose-settings .asset-input-description small{display:none}.compose-settings .asset-input img{width:35px;height:35px}.subtitle-heading{display:flex;justify-content:space-between;align-items:center;margin-bottom:9px}.subtitle-heading .el-button{font-size:10px}.subtitle-row{border:1px solid var(--line);padding:10px;border-radius:7px;margin-bottom:9px;background:#121b22}.subtitle-row>div{display:flex;align-items:center;gap:6px;margin-bottom:7px}.subtitle-row>div>span{font-size:9px;color:#627c83}.subtitle-row .el-input-number{width:75px}.subtitle-row .el-textarea__inner{font-size:11px}.compose-job{margin-top:25px;padding:15px;display:flex;align-items:center;gap:12px;flex-wrap:wrap}.compose-job>span:nth-child(2){font-size:11px;color:#8aada0;flex:1} +.system-status>.eyebrow{font-size:9px;margin:4px 0 15px}.system-status>h2{font-size:20px;font-weight:500;line-height:1.7}.system-status>p{color:#738d95;font-size:11px;line-height:1.9}.system-status>h3{font-size:12px;color:#98b6ab;margin:30px 0 16px}.system-model{display:flex;gap:10px;padding:15px 0;border-bottom:1px solid var(--line);align-items:flex-start}.system-model>.status-dot{margin-top:5px}.system-model>div{flex:1}.system-model strong{font-size:11px;font-weight:500;color:#adcbc0;display:block;margin-bottom:6px}.system-model small{font-size:9px;color:#567783}.system-model p{font-size:10px;color:#708e95;line-height:1.8;margin:7px 0 0}.system-model>span:last-child{font-size:9px;color:#689182;white-space:nowrap}.gpu-status{display:flex;align-items:center;gap:12px;padding:12px 0;border-bottom:1px solid var(--line);font-size:10px;color:#709289}.gpu-status strong{font-size:11px;color:#abcbc0;flex:1}.gpu-status small{font-size:9px;color:#587780} +.login-page{display:flex;min-height:100dvh;height:100%;background:#10151b}.login-art{width:55%;height:100%;position:relative;overflow:hidden;flex-shrink:0}.login-art>img{width:100%;height:100%;object-fit:cover;object-position:46% center}.login-art-overlay{position:absolute;inset:0;background:linear-gradient(180deg,#0c171c3b 0%,transparent 25%,#0913141a 45%,#061412cf 100%)}.login-brand{display:flex;gap:12px;align-items:center;position:absolute;top:38px;left:44px}.login-brand>strong{font-size:16px;letter-spacing:1px;font-weight:500;color:#f2f5ed}.login-brand strong>span{display:block;font-size:7px;font-weight:500;letter-spacing:2.3px;color:#daebe4a3;margin-top:4px}.login-art-copy{position:absolute;left:50px;bottom:70px;right:30px}.login-art-copy>.eyebrow{font-size:9px;color:#d2e4d4b3;margin-bottom:18px}.login-art-copy h1{font-size:46px;font-weight:500;letter-spacing:1px;line-height:1.5;margin-bottom:20px;color:#f3f3df}.login-art-copy p{font-size:13px;color:#ced5c3b0;line-height:1.9;margin:0}.login-art-copy .sample-label{position:static;display:inline-block;margin-top:30px;font-size:8px;background:#14372d55;border-color:#ffffff16;color:#c7ddc8b0}.login-form-section{flex:1;min-width:0;display:flex;align-items:center;justify-content:center;position:relative;padding:50px}.login-form-box{width:100%;max-width:340px}.login-form-box>.eyebrow{font-size:9px;color:#6d9485;margin-bottom:18px;letter-spacing:2px}.login-form-box h2{font-size:28px;line-height:1.5;font-weight:500;margin-bottom:13px;letter-spacing:-.3px}.login-form-box>p{font-size:11px;color:#6d8791;margin-bottom:38px}.login-form-box .el-form-item{margin-bottom:24px}.login-form-box .el-form-item__label{font-size:11px!important;margin-bottom:11px;color:#8ca5aa!important}.login-form-box .el-input__wrapper{height:44px;border-radius:8px;background:#141d24}.login-form-box .el-input__inner{font-size:12px}.login-submit{width:100%;height:44px;margin-top:10px;border-radius:8px}.login-submit .el-icon{margin-left:auto}.login-help{font-size:10px!important;line-height:1.9;color:#4d6c77!important;margin:22px 0 0!important}.login-error{font-size:11px;line-height:1.8;background:#9e585810;border:1px solid #b76b6b30;border-radius:6px;color:#cf9790;padding:9px 12px;margin-bottom:10px}.login-form-section>footer{position:absolute;bottom:28px;font-size:7px;letter-spacing:1.8px;color:#425c65} +@keyframes spin{to{transform:rotate(360deg)}}@keyframes pulse{50%{opacity:.35}} +@media(min-width:1600px){.workspace-scroll{padding-left:64px;padding-right:64px}.composer-wrap{padding-left:64px;padding-right:64px}.inspiration-card{height:360px}.creative-heading{padding-top:45px;padding-bottom:36px}.creative-heading h1{font-size:36px}.prompt-composer{max-width:1220px}.composer-footnote{max-width:1220px}.results-grid{grid-template-columns:repeat(4,minmax(0,1fr))}.asset-library-grid{grid-template-columns:repeat(5,minmax(0,1fr))}} +@media(max-width:1200px){.quiet-note{display:none}.workspace-scroll{padding:0 26px 24px}.composer-wrap{padding-left:26px;padding-right:26px}.composer-controls{align-items:flex-end}.model-chip{max-width:170px}.inspiration-card{height:255px}.inspiration-gradient{padding:14px}.inspiration-gradient h3{font-size:14px}.inspiration-actions button+button{margin-left:0}.tool-page,.library-page,.tasks-page,.compose-page{padding-left:26px;padding-right:26px}.tool-columns{grid-template-columns:1fr 1fr;gap:16px}.tool-input-panel,.tool-result-panel{padding:20px}.asset-library-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.library-toolbar{align-items:flex-start;flex-direction:column;gap:23px}.library-search{width:100%;justify-content:flex-end}.filter-tabs{gap:21px}.library-toolbar .filter-tabs button.active:after{bottom:-9px}.task-filter-selects{align-self:flex-end}.compose-layout{grid-template-columns:minmax(0,1fr) 285px;gap:18px}.compose-settings{padding:20px 16px}.preview-layout{grid-template-columns:minmax(0,1fr) 240px}.task-row{gap:15px}.task-row-actions{gap:3px}.login-art{width:51%}.login-art-copy{left:35px}.login-art-copy h1{font-size:36px}.login-form-section{padding:35px}} +@media(max-width:900px){.sidebar{width:66px}.side-nav{padding-left:8px;padding-right:8px}.side-nav a{height:54px;font-size:10px}.side-nav a.selected:before{left:-8px}.app-header{padding:0 22px;height:58px}.local-label,.header-divider{display:none}.creative-heading h1{font-size:26px}.creative-heading{padding-top:28px;padding-bottom:24px}.inspiration-grid{grid-template-columns:1fr 1fr}.inspiration-card{height:250px}.inspiration-card:nth-child(4){height:250px}.results-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.composer-parameters{gap:5px}.model-chip{max-width:150px}.composer-controls{align-items:center;flex-wrap:wrap}.generate-button{margin-left:auto}.composer-footnote>span:last-child{display:none}.tool-columns{grid-template-columns:1fr}.tool-result-panel{min-height:250px}.tool-empty{min-height:200px}.page-heading h1{font-size:25px}.compose-layout{grid-template-columns:1fr}.compose-settings{display:block}.compose-preview{max-height:380px}.split-heading{align-items:flex-start}.task-row-actions{flex-direction:column}.preview-layout{grid-template-columns:1fr}.preview-meta{display:grid;grid-template-columns:1fr 1fr;gap:10px 20px}.preview-meta>.eyebrow,.preview-meta>.el-form,.metadata-list{grid-column:1/-1}.metadata-list{grid-template-columns:60px 1fr 50px 1fr;gap:9px}.preview-stage{max-height:50vh;min-height:200px}.preview-stage>img,.preview-stage>video{max-height:50vh}.login-art{width:45%}.login-brand{left:25px}.login-art-copy h1{font-size:29px}.login-art-copy{left:25px;bottom:55px}.login-art-copy p{font-size:11px}.login-form-section{padding:30px}} +@media(max-width:640px){.sidebar{width:58px}.brand{height:80px}.brand-glyph{width:29px;height:29px;font-size:20px}.brand-caption{font-size:7px}.side-nav{padding:3px 6px;gap:5px}.side-nav a{height:51px;font-size:9px;gap:5px}.side-nav .el-icon{font-size:19px}.side-nav a.selected:before{left:-6px}.sidebar-bottom{gap:18px;padding:20px 0}.app-header{padding:0 15px}.header-breadcrumb{gap:8px;font-size:10px}.header-breadcrumb>span:first-child{font-size:11px}.connection-status{font-size:9px}.header-actions{gap:5px}.workspace-scroll{padding-left:16px;padding-right:16px}.workspace-topline{padding-top:12px}.mode-switch a,.mode-switch button{padding:8px 11px;font-size:10px}.creative-heading{padding-top:25px}.creative-heading h1{font-size:23px;letter-spacing:-1px}.creative-heading p{font-size:10px}.creative-heading .eyebrow{font-size:7px}.section-heading{gap:10px}.section-heading h2{font-size:12px}.section-heading p{font-size:9px}.outline-label{font-size:6px;letter-spacing:1px}.inspiration-grid{grid-template-columns:1fr;gap:14px}.inspiration-card,.inspiration-card:nth-child(4){height:260px}.inspiration-card:nth-child(2){height:210px}.inspiration-gradient h3{font-size:17px}.sample-label{font-size:8px}.inspiration-actions button{font-size:11px}.composer-wrap{padding:8px 12px 12px}.prompt-composer{padding:11px;border-radius:11px}.prompt-composer>textarea{height:64px;font-size:11px}.composer-parameters{gap:5px}.model-chip{max-width:150px;font-size:9px}.parameter-chip{padding:6px;font-size:9px}.composer-controls{row-gap:10px}.generate-button.el-button{height:32px;font-size:10px;padding:0 12px}.composer-footnote{font-size:8px;margin-top:7px}.count-select{width:60px;min-width:60px}.results-grid{grid-template-columns:1fr}.page-heading h1{font-size:23px}.page-heading p{font-size:10px}.page-heading .eyebrow{font-size:7px}.tool-page,.library-page,.tasks-page,.compose-page{padding:0 16px 75px}.split-heading{flex-direction:column;gap:14px}.tool-input-panel,.tool-result-panel{padding:18px}.panel-heading{gap:6px}.panel-heading h2{font-size:12px}.tiny-model{max-width:160px;font-size:8px}.tool-history>button{gap:9px;padding:13px 3px}.tool-history>button>small{display:none}.asset-library-grid{grid-template-columns:repeat(2,minmax(0,1fr));gap:11px}.library-caption{padding:10px}.library-caption>button{font-size:10px}.library-caption>div{font-size:8px}.filter-tabs{gap:14px;flex-wrap:wrap}.filter-tabs button{font-size:10px}.library-search{gap:5px}.library-search>.el-input{min-width:0}.library-search>.el-input:first-child{width:75px}.picker-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.picker-toolbar{flex-wrap:wrap}.picker-toolbar>.el-input{flex-basis:100%}.preview-meta{display:block}.preview-meta>.el-button{margin:6px 0}.metadata-list{grid-template-columns:50px 1fr}.task-policy-note{font-size:9px;padding:10px;line-height:1.8;align-items:flex-start}.task-policy-note .live-dot{margin-top:5px;flex-shrink:0}.task-thumb{width:46px;height:57px;border-radius:6px}.task-row{gap:9px;padding:17px 0}.task-title{font-size:11px}.task-title-line{gap:6px;flex-wrap:wrap}.task-main>p{font-size:9px;line-height:1.6}.task-row-actions .el-button{font-size:10px;padding:6px}.task-title-line small{display:none}.task-filter-selects{width:100%}.task-filter-selects .el-select{width:50%;min-width:0}.task-type{font-size:8px}.status-pill{font-size:8px;padding:3px 5px}.task-main>small{font-size:8px}.global-queue-bar{padding:9px 13px;font-size:9px;gap:8px;max-width:calc(100% - 24px)}.global-queue-bar strong{font-size:10px}.global-queue-bar>span:not(.queue-spinner){max-width:125px}.global-queue-bar small{display:none}.compose-preview{min-height:200px;aspect-ratio:auto}.timeline-heading h2>span{display:block;margin:6px 0 0}.compose-job{gap:8px;font-size:10px}.connection-banner{padding:8px 14px;font-size:9px;line-height:1.7}.login-art{display:none}.login-form-section{padding:28px}.login-form-box{max-width:360px}.login-form-box h2{font-size:29px}.login-form-box>.eyebrow{font-size:8px}.login-form-section:before{content:'CMVR VISUAL';position:absolute;top:35px;left:28px;font-size:12px;letter-spacing:2px;color:#95c8b7}} +@media(prefers-reduced-motion:reduce){*,*:before,*:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}} diff --git a/frontend/src/taskForms.test.ts b/frontend/src/taskForms.test.ts new file mode 100644 index 0000000..e2d984e --- /dev/null +++ b/frontend/src/taskForms.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest' +import { buildToolRequest, composeFrameRates, isComposeFrameRateAllowed } from './taskForms' +import type { Capability } from './types' + +const composition: Capability = { + task_type: 'video.compose', label: '成片合成', model: 'FFmpeg', available: true, + input_types: ['video'], defaults: { width: 1280, height: 720, fps: 24 }, + constraints: { fps: { values: [24, 25, 30, 60] } }, description: '', +} + +describe('task-specific request contracts', () => { + it('drops speech controls when the user switches from speech to image understanding', () => { + const request = buildToolRequest('media.structure', '', { + frame_count: 6, voice: 'zf_xiaobei', speed: 1.2, + }, { id: 'owned-image', kind: 'image' }) + expect(request).toEqual({ task_type: 'media.structure', input: { asset_id: 'owned-image' }, parameters: { frame_count: 1 } }) + }) + + it('retains only the video-understanding sampling parameter from an old speech draft', () => { + const request = buildToolRequest('media.structure', '', { + frame_count: 8, voice: 'zm_yunxi', speed: 0.9, + }, { id: 'owned-video', kind: 'video' }) + expect(request.parameters).toEqual({ frame_count: 8 }) + expect(request.input).toEqual({ asset_id: 'owned-video' }) + }) + + it('keeps voice and speed only on a speech request and drops other tool fields', () => { + const request = buildToolRequest('audio.speech', ' 你好,创作。 ', { + voice: 'zf_xiaobei', speed: 1, frame_count: 6, language: 'zh', max_tokens: 2048, + }) + expect(request).toEqual({ task_type: 'audio.speech', input: { prompt: '你好,创作。' }, parameters: { voice: 'zf_xiaobei', speed: 1 } }) + }) + + it('uses the live discrete frame-rate contract instead of treating it as a numeric range', () => { + expect(composeFrameRates(composition)).toEqual([24, 25, 30, 60]) + expect(isComposeFrameRateAllowed(26, composition)).toBe(false) + expect(isComposeFrameRateAllowed(25, composition)).toBe(true) + const limited = { ...composition, constraints: { fps: { values: [30] } } } + expect(composeFrameRates(limited)).toEqual([30]) + expect(isComposeFrameRateAllowed(24, limited)).toBe(false) + }) +}) diff --git a/frontend/src/taskForms.ts b/frontend/src/taskForms.ts new file mode 100644 index 0000000..185ac8c --- /dev/null +++ b/frontend/src/taskForms.ts @@ -0,0 +1,34 @@ +import type { Asset, Capability, JobRequest, TaskType } from './types' + +const toolFields: Partial> = { + 'math.solve': ['max_tokens'], + 'media.structure': ['frame_count'], + 'audio.transcribe': ['language', 'max_audio_seconds'], + 'audio.speech': ['voice', 'speed'], +} + +/** Build the actual request boundary, independent of which tool was visible before. */ +export function buildToolRequest(taskType: TaskType, prompt: string, values: Record, asset: Pick | null = null): JobRequest { + const fields = toolFields[taskType] + if (!fields) throw new Error('当前任务不属于素材与文本工具') + const parameters = Object.fromEntries(fields.filter(field => values[field] !== undefined).map(field => [field, values[field]])) + const input: Record = {} + if (taskType === 'math.solve' || taskType === 'audio.speech') input.prompt = prompt.trim() + else { + if (!asset) throw new Error('请先选择或上传素材') + input[taskType === 'audio.transcribe' ? 'audio_asset_id' : 'asset_id'] = asset.id + if (taskType === 'media.structure' && asset.kind === 'image') parameters.frame_count = 1 + } + return { task_type: taskType, input, parameters } +} + +export function composeFrameRates(capability?: Capability): number[] { + const values = capability?.constraints.fps?.values + if (Array.isArray(values)) return [...new Set(values.filter((value): value is number => typeof value === 'number' && Number.isInteger(value) && value > 0))] + const fallback = capability?.defaults.fps + return typeof fallback === 'number' && Number.isInteger(fallback) && fallback > 0 ? [fallback] : [] +} + +export function isComposeFrameRateAllowed(value: unknown, capability?: Capability) { + return typeof value === 'number' && composeFrameRates(capability).includes(value) +} diff --git a/frontend/src/types.ts b/frontend/src/types.ts new file mode 100644 index 0000000..9462794 --- /dev/null +++ b/frontend/src/types.ts @@ -0,0 +1,35 @@ +export type TaskType = 'image.generate' | 'video.generate' | 'defect.generate' | 'audio.transcribe' | 'audio.speech' | 'math.solve' | 'media.structure' | 'video.compose' +export type AssetKind = 'image' | 'video' | 'audio' | 'text' | 'json' +export type JobState = 'scheduled' | 'submitting' | 'queued' | 'running' | 'collecting' | 'cancelling' | 'succeeded' | 'failed' | 'cancelled' | 'timed_out' +export interface User { id: string; username: string; display_name: string; role: string } +export interface AuthResponse { user: User; csrf_token: string } +export interface Asset { + id: string; name: string; kind: AssetKind; mime_type: string; size_bytes: number + width: number | null; height: number | null; duration_seconds: number | null + preview_url: string; thumbnail_url: string | null; download_url: string + source_job_id: string | null; origin: 'upload' | 'generated'; tags: string[]; favorite: boolean; created_at: string +} +export interface NumericConstraint { min?: number; max?: number; step?: number; values?: (string | number)[] } +export interface Capability { + task_type: TaskType; label: string; model: string; available: boolean; input_types: string[] + defaults: Record; constraints: Record; description: string +} +export interface Scheduler { + available: boolean; state: string; reason: string | null + gpus: { index: number; name: string; busy: boolean; eligible: boolean; free_gib: number | null }[] + updated_at: string | null +} +export interface Job { + id: string; task_type: TaskType; state: JobState; phase: string; version: number; prompt: string + parameters: Record; input_asset_ids: string[]; result_assets: Asset[]; result: Record | null + progress: number | null; queue_position: number | null; upstream_id: string | null + attempt_count: number; preemptions: number; last_preempted_reason: string | null; cancel_requested: boolean + error: { code: string; message: string; retriable: boolean } | null; sync_warning: string | null + created_at: string; scheduled_at: string | null; started_at: string | null; finished_at: string | null +} +export interface JobRequest { + task_type: TaskType; input: Record; parameters: Record; count?: number; scheduled_at?: string | null +} +export interface Page { items: T[]; total: number; page: number; page_size: number } +export interface JobsPage extends Page { cursor: number } +export interface CapabilitiesResponse { items: Capability[]; scheduler: Scheduler } diff --git a/frontend/src/views/AssetsView.vue b/frontend/src/views/AssetsView.vue new file mode 100644 index 0000000..67a5438 --- /dev/null +++ b/frontend/src/views/AssetsView.vue @@ -0,0 +1,29 @@ + + diff --git a/frontend/src/views/ComposeView.vue b/frontend/src/views/ComposeView.vue new file mode 100644 index 0000000..08765d5 --- /dev/null +++ b/frontend/src/views/ComposeView.vue @@ -0,0 +1,50 @@ + + diff --git a/frontend/src/views/LoginView.vue b/frontend/src/views/LoginView.vue new file mode 100644 index 0000000..1ae0b98 --- /dev/null +++ b/frontend/src/views/LoginView.vue @@ -0,0 +1,13 @@ + + diff --git a/frontend/src/views/TasksView.vue b/frontend/src/views/TasksView.vue new file mode 100644 index 0000000..e2a8cf7 --- /dev/null +++ b/frontend/src/views/TasksView.vue @@ -0,0 +1,29 @@ + + diff --git a/frontend/src/views/ToolsView.vue b/frontend/src/views/ToolsView.vue new file mode 100644 index 0000000..5d94bc9 --- /dev/null +++ b/frontend/src/views/ToolsView.vue @@ -0,0 +1,71 @@ + + +